texts: Check if array has the same number of even and odd values in Python

texts:
Task:
Complete the following function that determines if the number of even and odd values in an list of Integers is the same.

| In               | Out   |         Why            |
|------------------|-------|------------------------|
| [5, 1, 0, 2]     | true  | two evens and two odds |
| [5, 1, 0, 2, 11] | false | too many odds          |
| []               | true  | both have 0            |

The function should not affect the contents of the list.

My code:

def balanced(lst):
    n = len(lst)
    if n % 2 != 0:
        return False
    if n % 2 == 0:
        count_1 = 0
        count_2 = 0
        for item in lst:
            if item % 2 == 0:      #even
                count_1 += 1
            if item % 2 != 0:       #odd
                count_2 += 1
    if count_1 == count_2:
        return True
    else:
        return False
def result(lst):
     if balanced(lst):
         print("Your list is successfully balanced! It has same number of evens and odds!!")
     else:
         print("Oh no! Sorry! Your list seems to be not balanced! Try another list please!")
def main():
     lst_1 = [1,2,3,5,6,8,5,9]
     lst_2 = []
     lst_3 = [2,4,5,7]
     lst_4 = [1,2,4,4]
     lst_5 = [1,2,3]
     result(lst_1)
     result(lst_2)
     result(lst_3)
     result(lst_4)
     result(lst_5)
main()


texts:
I have the following problem statement:

  Modify a given list such that one specific element is "weaved" into that list.

  Examples if the element is 'module':

  [] remains []
  ['a'] remains ['a']
  ['a', 'b'] becomes ['a', 'module', 'b']
  ['a', 'b', 'c'] becomes ['a', 'module', 'b', 'module', 'c']

I solved it using the following code in Python 3.4:

@staticmethod
def __weave_element_into_list(element, values: list) -> list:
    """
    Weaves an element into a given list.

    Examples if the element is 'module':
     - Input [] remains [].
     - Input ['a'] remains ['a'].
     - Input ['a', 'b'] becomes ['a', 'module', 'b'].
     - Input ['a', 'b', 'c'] becomes ['a', 'module', 'b', 'module', 'c'].
     - etc.

    :param element: The element to weave into the list
    :param values:  The original list
    :return:    The list with element weaved into it.
    """
    copy_list = list(values)
    if len(copy_list) <= 1:
        return copy_list
    i = 1
    while i < len(copy_list):
        copy_list.insert(i, element)
        i += 2
    return copy_list

Is there a better (more Pythonic?) solution to it and is "weaving" the correct operation here?


texts:
For string similarity, it is defined as longest common prefix length. For example, "abc" and "abd" is 2, and "aaa" and "aaab" is 3.

The problem is calculate the similarity of string S and all its suffixes, including itself as the first suffix.

For example, for S="ababaa", suffixes are "ababaa", "babaa", "abaa","baa","aa"
and "a", the similarity are 6+0+3+0+1+1=11.

My code works and I am looking for smarter ideas to be more efficient.

# Complete the function below.
from collections import defaultdict

class TrieNode:
    def __init__(self):
        self.children=defaultdict(TrieNode)
        self.isEnd=False
class TrieTree:
    def __init__(self):
        self.root=TrieNode()
    def insert(self, word):
        node = self.root
        for w in word:
            node = node.children[w]
        node.isEnd = True
    def search(self, word):
        node = self.root
        count = 0
        for w in word:
            node = node.children.get(w)
            if not node:
                break
            else:
                count += 1
        return count

def  StringSimilarity(inputs):
    resultFormat=[]
    for word in inputs:
        # build Trie tree
        index = TrieTree()
        index.insert(word)
        result = 0
        # search for suffix
        for i in range(len(word)):
            result += index.search(word[i:])
        print result
        resultFormat.append(result)

    return resultFormat


texts:
So this is probably a popular problem, and I decided to take a crack at it today using C#.

I came up with the following solution:

private  BinaryTree<int>.BinaryTreeNode FindLowestNodes(BinaryTree<int>.BinaryTreeNode node, int depth, ref int biggestDepth) {
    this.WriteResult("Entering recursiorn for node.....{0}", node.Value.ToString());
    BinaryTree<int>.BinaryTreeNode lowestNode = null;
    if (node.Left != null) {
        var n = FindLowestNodes(node.  Left, depth + 1, ref biggestDepth);
        if (n != null) lowestNode = n;
    }
    if (node.Right != null) {
        var n = FindLowestNodes(node.Right, depth + 1, ref biggestDepth);
        if (n != null)
            lowestNode = n;
    }
    if (node.Left == null && node.Right == null) {
        if (depth > biggestDepth) {
            lowestNode = node;
            biggestDepth = depth;
        }
    }
    return lowestNode;
}

This is a recursive function using a depth parameter, and biggestDepth parameter that helps me determine if the node is indeed the lowest since the tree can have multiple depths. What I don't like about passing an int by reference is boxing...

Could this solution be written more efficiently?

Also, would it be easier to parallelize using a functional language like Clojure, or is that not really a factor as long as variables are not passed by reference?


texts: Modified Sieve of Eratosthenes has very long runtime

texts:
I am slowly moving through Project Euler, and have reached problem #10:

  The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

  Find the sum of all the primes below two million.

I did a naive implementation first, which was very slow (15+ minutes runtime).  But since I know the last number in the series, the Sieve of Eratosthenes should be far swifter, yet I still find it very slow.  I'm wondering whether I've mis-implemented a list somewhere so I go through it far more than I should.

Assuming I haven't messed up with the list, is there some other thing that might be the slow-down, or is this just a very intensive task that should take a long time?

#include <list>
#include <iterator>
#include <iostream>

int main(){

    std::list<long long> candidates;

    candidates.begin();

    for(long long i = 2; i<2000000; i++){

        candidates.push_back(i);
    }

    long long sieve      = 0;
    long long runningSum = 0;
    long long lastSieve  = 1415;

    std::list<long long>::iterator outer = candidates.begin();
    std::list<long long>::iterator inner = candidates.begin();

    while(outer != candidates.end()){

    sieve = *outer;
    outer++;
    inner = outer;

        while(sieve < lastSieve){

            if( *inner % sieve == 0){
                inner = candidates.erase(inner);
            }
            else{
                inner++;
            }
        }
    }

    for(std::list<long long>::iterator output = candidates.begin(); output != candidates.end(); output++){

    runningSum += *output;
    }

    std::cout << "\nTotal: " << runningSum << std::endl;
    return 0;
}


texts: Split a number into equal parts given the number of parts

texts:
I want to split a song into multiple parts, given the song duration and number of parts.

My code achieves that, but it feels a little "stupid" and I would like to learn a more sophisticated - and shorter - way. Particularly, I feel that the marker variable is a little overkill. I would welcome any suggestions.

song_duration = 20 # these two
num_of_parts = 4   # are given

part_duration = song_duration / num_of_parts
parts = []
marker = 0

for _ in range(num_of_parts):
    part = [marker, marker + part_duration]
    marker += part_duration
    parts.append(part)

print(parts)

# parts is : [[0, 5.0], [5.0, 10.0], [10.0, 15.0], [15.0, 20.0]]


texts: Is code optimization for branch predictor necessary now?

texts:
I would like to share a part of some code written several years ago (I have changed from mysql to mysqli); this code works perfectly. I am new to my company, and our senior programmers wrote some extra lines to optimize branch predictions. My question is: is it necessary to follow this code? Does it improve performance?

We are hosting our files on Linux VPS CentOS 64Bit, 4GM RAM

 $gq = array();   //to hold global ques
 $gq = array_merge($m1_array,$m2_array,$m3_array,$m4_array,$m5_array,$mp5_array) ;
        unset ($m1_array,$m2_array,$m3_array,$m4_array,$m5_array,$mp5_array);
        shuffle($gq);
    // collect answers
    //preparing list of question ids to get the answer
    $qnolist ='';
    foreach ($gq as $qm)
            {$qnolist = $qnolist.','.$qm['qid'];}
    $qnolist=substr_replace($qnolist ,'',0,1);
    //sorted list qry always good performance (branch predictor)
    $qnoarray =explode(",",$qnolist);
    sort($qnoarray);
    $qnolist=implode(",",$qnoarray);
    $sql = "SELECT some fields where `qid` in ({$qnolist}) order by `qid`,`aid`;";
    $result = mysqli_query ($dbcon, $sql) or die("Server connection error...");
      $ga = array();
        while ($row = mysqli_fetch_assoc($result)) {
              array_push($ga, $row);
              }
        mysqli_free_result($result);


texts:
I'm trying to make an XML editor. So far, I got the results I wanted, but a lot of code is repeated. How can I reuse more effectively?

import java.io.File;
import java.io.IOException;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlUtil {
    private static File fXmlFile;
    private static DocumentBuilderFactory dbFactory = DocumentBuilderFactory
            .newInstance();
    private static DocumentBuilder dBuilder;
    private static Document doc;

    public static ObservableList<String> getAllTagText(String fileName)
            throws ParserConfigurationException, SAXException, IOException {
        ObservableList<String> tagList = FXCollections.observableArrayList();

        dBuilder = dbFactory.newDocumentBuilder();
        fXmlFile = new File(fileName);
        doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("Tag");

        for (int i = 0; i < nodeList.getLength(); i++) {
            String tag = nodeList.item(i).getTextContent();
            tagList.add(tag);
        }

        return tagList;
    }

    public static String getLanguageText(String fileName, String tag,
            String language) throws ParserConfigurationException, SAXException,
            IOException {
        dBuilder = dbFactory.newDocumentBuilder();
        fXmlFile = new File(fileName);
        doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("TEXT");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                if (element.getElementsByTagName("Tag").item(0)
                        .getTextContent().equals(tag)) {
                    return element.getElementsByTagName(language).item(0)
                            .getTextContent();

                }
            }

        }
        return null;
    }

    public static void setText(String fileName, String tag, String textContent)
            throws SAXException, IOException, ParserConfigurationException,
            TransformerException {
        dBuilder = dbFactory.newDocumentBuilder();
        fXmlFile = new File(fileName);
        doc = dBuilder.parse(fXmlFile);

        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("TEXT");

        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                Element element = (Element) node;
                if (element.getElementsByTagName("Tag").item(0)
                        .getTextContent().equals(tag)) {
                    element.getElementsByTagName("Hungarian").item(0)
                            .setTextContent(textContent);
                }

            }
            TransformerFactory transformerFactory = TransformerFactory
                    .newInstance();

            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
            DOMSource domSource = new DOMSource(doc);

            StreamResult streamResult = new StreamResult(fXmlFile);
            transformer.transform(domSource, streamResult);
        }

    }
}


texts:
I have a couple of functions in WordPress that I'm rewriting to OOP. All these functions are interlinked in some way and also reuse code from other functions.

This is an example of the first class I'm trying. I'm very new to OOP, but I have learned about separation of concern, so basically each concern get its own class.

interface Single_Post_Referrer_Interface {

    function init();

    function get_is_author_referrer();

    function get_is_date_referrer();

    function set_is_author_referrer( $is_author_referrer );

    function set_is_date_referrer( $is_date_referrer );

}

class Single_Post_Referrer_Class implements Single_Post_Referrer_Interface {

    private $is_author_referrer;
    private $is_date_referrer;

    function __construct() {

        $this->init();

    }

    function init() {

        $is_author_referrer = isset( $_GET['aq'] );
        $is_date_referrer   = isset( $_GET['dq'] );

        $this->set_is_author_referrer( $is_author_referrer );
        $this->set_is_date_referrer( $is_date_referrer );

    }

    function get_is_author_referrer() {

        return $this->is_author_referrer;

    }

    function get_is_date_referrer() {

        return $this->is_date_referrer;

    }

    function set_is_author_referrer( $is_author_referrer ) {

        $this->is_author_referrer = $is_author_referrer ;

        return $this;

    }

    function set_is_date_referrer( $is_date_referrer ) {

        $this->is_date_referrer = $is_date_referrer ;

        return $this;

    }

}

$a = new Single_Post_Referrer_Class();

This class basically is a lot of conditional checks (checks if a certain query variable is in the URL and sets the appropriate condition) and return the conditional checks with a boolean value which will be used by other classes.

As this is my first attempt, I would like to know if this is correctly done and if not, where I can improve. Just a note: I correctly get the correct values if I do a var_dump( $a );.


texts: Incrementing and displaying a field if not empty

texts:
I've got this code to work, but being really new to PHP, I don't know if this is proper. This is my first time using PHP to increment.

I have 10 fields for YouTube videos (using Advanced Custom Fields in WordPress - I don't have the repeater fields and won't be getting them)
The video/html elements only show if the corresponding video field is not empty

Are the variables correctly placed?

Are there better ways to do this?

    <?php
         $vidnum = 'video_';
         for($n=0; $n<=9; $n++) {
         $next = $vidnum.($n +1 );
         $video = get_field('' . $next . '');
             if (!empty($video))
                    echo '
' . $video . '
';
                }

        ?>


texts:
I have just started learning Java, and don't want to start any bad habits, so please review my latest game code:

import java.util.Random;
import java.util.Scanner;
class GuessMyNumber {
    public static void main(String args[]) {
        Random random = new Random();
        Scanner input = new Scanner(System.in);
        int MIN = 1;
        int MAX = 100;
        int comp = random.nextInt(MAX - MIN + 1) + MIN;
        int user;
        int guesses = 0;
        do {
            System.out.print("Guess a number between 1 and 100: ");
            user = input.nextInt();
            guesses++;
            if (user > comp)
                System.out.println("My number is less than " + user + ".");
            else if (user < comp)
                System.out.println("My number is greater than " + user + ".");
            else
                System.out.println("Well done! " + comp + " was my number! You guessed it in " + guesses + " guesses.");
        } while (user != comp);
    }
}


texts:
Given a 2D array of unsigned integers and a maximum length n, find a path in that matrix that is not longer than n and which maximizes the product of the elements in the path. The output should consist of both the path and the product.

A path consists of neighbouring integers that are either all in the same row, or in the same column, or down a diagonal in the down-right direction. The code for this problem is below:

def maxPathProduct(self, matrix, maxLen):
    """
    Take a 2D Array of ints
    and return the largest Product of list of ints of length maxLen
    and the product of the list integers
    """
    maxProduct = -1
    maxList = []
    if len(matrix) == 0:
        return maxProduct, maxList
    numRows = len(matrix)
    numCols = len(matrix[0])

    for direction in range(1, 4):
        if direction == 1:
            numLines = numCols
        elif direction == 2:
            numLines = numRows
        elif direction == 3:
            numLines = numRows + numCols -1
        for line in range (0,numLines):
            pathProduct = 1
            pathLen = 0
            if direction == 1:
                headRow = 0
                headCol = line
            elif direction ==2:
                headCol = 0
                headRow = line
            elif direction == 3:
                headRow =  0 if line  >= numRows else line
                headCol =  line-numRows if line  >= numRows else 0
            tailRow = headRow
            tailCol = headCol
            pathList = []
            while headRow < numRows  and headCol < numCols:
                pathList.append(matrix[headRow][headCol])
                pathProduct *= matrix[headRow][headCol]
                pathLen+=1
                if pathLen > maxLen:
                    pathProduct /= matrix[tailRow][tailCol]
                    pathList = pathList[1:]
                    if direction== 1:
                        tailRow += 1
                    elif direction == 2:
                        tailCol += 1
                    elif direction == 3:
                        tailCol += 1
                        tailRow += 1
                if pathProduct > maxProduct:
                    maxProduct = pathProduct
                    maxList = pathList
                if direction== 1:
                        headRow += 1
                elif direction == 2:
                    headCol += 1
                elif direction == 3:
                    headCol += 1
                    headRow += 1
        return maxProduct, maxList
matrix = [
    [1,  2,  3,  4,  5],
    [1,  1,  2,  3,  5],
    [3,  4,  5,  5,  5],
    [3,  4,  5, 9,  5],
    [1,  1,  5,  5, 25],
]

The issue here is that the solution constitutes changing the values of the "head" and "tail" variables based on the current direction being considered in the 2D requiring the use of multiple if/else statements. This makes the code a look longer and possibly harder to follow. I'm basing this off of these errors listed by pylint:

[pylint] C0103:Invalid function name "maxPathProduct"
[pylint] R0914:Too many local variables (17/15)
[pylint] C0103:Invalid argument name "maxLen"
[pylint] C0103:Invalid argument name "maxLen"

I'm not sure if these errors actually warrant any changes but if they do, is there anyway to possibly refactor the if/else statements or any unwieldy part of the code while maintaining the functionality of the solution?


texts: VLookup simulation: copying data from one sheet to another

texts:
I tried to write a VLOOKUP in my macro but for some unknown reasons it didn't work (see my post on StackOverFlow for more info.

So I decided to do a macro which achieves the same result, but it takes about 20 sec to run. Any ideas on how I can improve its performance ?

What this macro is doing :

I have 2 worksheets in my workbook. Both have a column listing VINs + other info. What this macro is doing is a Vlookup from one sheet to the other one to retrieve some information when the same VIN is found.

Sub ReplacementVlookups()

'Delete Rows with no content
    Dim i As Integer
    i = 0
    Do
    i = i + 1
    Loop While Range("A" & i) <> ""
    Rows(i & ":" & Worksheets("All Time SMS Dump").Range("A" & Rows.Count).End(xlUp).Row).Delete (xlShiftUp)
Worksheets("All Time SMS Dump").Columns("G:G").NumberFormat = "General"
Worksheets("All Time SMS Dump").Columns("H:H").NumberFormat = "General"
'Store all Lookup values in a 1D array
Dim VLookupType As Integer
Dim j As Integer
Dim LastRow As Integer
Dim LastRowSF As Integer
Dim VINArrayAllTime As Variant
Dim VINArraySF As Variant
Dim ValuesCopied As Variant
Dim ValuesPasted As Variant
LastRow = Worksheets("All Time SMS Dump").Range("A" & Rows.Count).End(xlUp).Row
LastRowSF = Worksheets("Salesforce Dump").Range("A" & Rows.Count).End(xlUp).Row
VINArrayAllTime = Worksheets("All Time SMS Dump").Range("A2:A" & LastRow)
VINArraySF = Worksheets("Salesforce Dump").Range("C2:C" & LastRowSF)
For VLookupType = 1 To 3 ' I have 3 columns on which I want to apply the VLookup
    If VLookupType = 1 Then
        ValuesCopied = Worksheets("Salesforce Dump").Range("D2:D" & LastRowSF)
        ValuesPasted = Worksheets("All Time SMS Dump").Range("G2:G" & LastRow)
        'Do a VLOOKUP
        For i = 2 To LastRow
            For j = 2 To LastRowSF - 1
                If VINArrayAllTime(i - 1, 1) = VINArraySF(j - 1, 1) Then
                    ValuesPasted(i - 1, 1) = ValuesCopied(j - 1, 1)
                    Exit For
                End If
            Next j
        Next i

        Worksheets("All Time SMS Dump").Range("G2:G" & LastRow) = ValuesPasted
    ElseIf VLookupType = 2 Then
        ValuesCopied = Worksheets("Salesforce Dump").Range("E2:E" & LastRowSF)
        ValuesPasted = Worksheets("All Time SMS Dump").Range("H2:H" & LastRow)
        'Do a VLOOKUP
        For i = 2 To LastRow
            For j = 2 To LastRowSF - 1
                If VINArrayAllTime(i - 1, 1) = VINArraySF(j - 1, 1) Then
                    ValuesPasted(i - 1, 1) = ValuesCopied(j - 1, 1)
                    Exit For
                End If
            Next j
        Next i

        Worksheets("All Time SMS Dump").Range("H2:H" & LastRow) = ValuesPasted

    Else:
        ValuesCopied = Worksheets("Salesforce Dump").Range("F2:F" & LastRowSF)
        ValuesPasted = Worksheets("All Time SMS Dump").Range("I2:I" & LastRow)
        'Do a VLOOKUP
        For i = 2 To LastRow
            For j = 2 To LastRowSF - 1
                If VINArrayAllTime(i - 1, 1) = VINArraySF(j - 1, 1) Then
                    ValuesPasted(i - 1, 1) = ValuesCopied(j - 1, 1)
                    Exit For
                End If
            Next j
        Next i

        Worksheets("All Time SMS Dump").Range("I2:I" & LastRow) = ValuesPasted
    End If
Next VLookupType

End Sub


texts: Instantiating a property when the required attributes have been set

texts:
I have a simple class which holds my product. Someone can add a serial to this product and also a purchase id. On change of the properties, I want to check whether both properties are set, and get the license class and add it to the product.

public class License
{
    public bool IsTrial { get; set; }

    public bool IsValid { get; set; }

    public string Type { get; set; }

    public License()
    {

    }

    public License(string purchaseId, string serial)
    {
        this.IsTrial = true;
        this.IsValid = true;
        this.Type = "Enterprise";
    }

Example License class

public class Product
{
    private License _license;
    public License license
    {
        get
        {
            return _license;
        }
        set
        {
            _license = value;
        }
    }

    public string Name { get; set; }

    private string _purchaseId;
    public string PurchaseId {
        get
        {
            return _purchaseId;
        }
        set
        {
            _purchaseId = value;
            GetLicense();
        }
    }

    private string _serial;
    public string Serial
    {
        get
        {
            return _serial;
        }
        set
        {
            _serial = value;
            GetLicense();
        }
    }

    private void GetLicense()
    {
        if (!string.IsNullOrEmpty(this.Serial) && !string.IsNullOrEmpty(this.PurchaseId))
        {
            License lice = new License(serial, PurchaseId);
            this.License = lice;
        }
    }

That's the approach I used. Is this a correct way to do it? How is this called and what is the best practice? I need to use .NET Framework 3.5.


texts: Binary file Handling - Add,modify and display records

texts:
I have written a basic binary file handling program and have used goto, so I want to know how to improve this program by replacing goto with another function

#include<fstream>
#include<process>
#include<string>
#include<stdio>
#include<conio>

using namespace std;

int opt;
class housing
{
  int hno,income;
  char name[20],type[20];
  public:
  void assign()
  {
   if(income<15000)
   strcpy(type,"LIG");
   else if(income>=15000)
   strcpy(type,"MIG");
   else if(income>=25000)
   strcpy(type,"HIG");
  }
  void input()
  {
   cout<<"\n Enter House Number: ";
   cin>>hno;
   cout<<"\n House Name: ";
   gets(name);
   cout<<"\n Annual Income: ";
   cin>>income;
   assign();
  }
   void output()
  {
   cout<<"House Number: "<<hno<<"\n"<<"House Name: "<<name<<"\n"<<"Annual                                           Income: "<<income<<"\n"<<"Type: "<<type;
  }
  int retno()
  {
  return hno;
  }
};

void main()
{
 housing h,h1;
 fstream f;
 int hono;
 menu:
 cout<<"\n 1:Add a Record"<<'\t'<<"\n 2:Modify"<<'\t'<<"\n 3:Display All  Records"<<'\t'<<"\n 4:Exit"<<endl;
 cin>>opt;
 if(opt==1)
 {
  char ch='y';
  f.open("hous.dat",ios::out|ios::binary|ios::app);
  while(ch=='y')
  {
   cout<<"\n Enter Details: ";
   h.input();
   f.write((char*)&h,sizeof(h));
   cout<<"\n Want to Enter More? y/n: "<<endl;
   cin>>ch;
  }
 f.close();
 }
 if(opt==2)
 {
  cout<<"\n Enter House No of Record to be modified: ";
  cin>>hono;
  f.open("hous.dat",ios::in|ios::out|ios::binary|ios::ate);
  f.seekg(0);
  while(f.read((char*)&h,sizeof(h)))
  {
   if(h.retno()==hono)
   {
    cout<<"\n New Value: ";
    h1.input();
    f.seekp(-sizeof(h),ios::cur);
    f.write((char*)&h1,sizeof(h1));
   }
  }
 f.close();
 }
 if(opt==3)
 {
  f.open("hous.dat",ios::in|ios::binary);
  f.seekg(0);
  while(f.read((char*)&h,sizeof(h)))
  h.output();
  f.close();
 }
 if(opt==4)
 exit(0);
 cout<<"\nPress ... ";
 getch();
 goto menu;

}


texts: Increase efficiency of basic string compressor

texts:
I was wondering what I can do to increase the performance of this program. The algorithm is pretty slow right now but I was wondering what I can do to increase the efficiency of this program.  I used lists instead of strings to avoid immutable string concatenation.

This program should compress strings by the number of characters within the string

Example:

aaabbbcc --> a3b3c2

Code:

def compressBad(string):
    string = list(string)
    mystr = []
    last = string[0]
    count = 1
    for x in xrange(1,len(string)):
        if string[x] == last:
            count += 1
        else:
            mystr.append(last)
            mystr.append(str(count))
            last = string[x]
            count = 1
    # add the last character
    mystr.append(last)
    mystr.append(str(count))
    return ''.join(mystr)

print compressBad("abaabccc")

output:

a1b1a2b1c3


texts: Maintainable and Adaptable FizzBuzz implementation

texts:
Something I haven't often seen in FizzBuzz implementation is a focus on making it flexible and maintainable. I have attempted to create a version that prioritizes these, such as by making it easier to change the conditions and add more conditions. What else could I do to work towards these criteria?

public class V3_ifFunc
{
   public static void main(String[] args)
   {
       String out;
       int i;
       for(i=0; i<=100; i++)
       {
           out = "";
           if(divisible(i, 3)){
               out += "Fizz";
           }
           if(divisible(i, 5)){
               out += "Buzz";
           }
           if(out.equals("")){
               out += Integer.toString(i);
           }
           System.out.println(out);
       }
   }
   public static boolean divisible(int i, int by)
   {
       if(i%by==0){
           return true;
       }else{
           return false;
       }
   }
}


texts: Extract a list of users from a text file

texts:
fo=open("haproxyfile.txt","r")
users=[]
for lines in fo.readlines():
    if 'user' and 'password' in lines:
        items=lines.split() #converts to list"""
        users.append(items[1]) #append the second item that is the username"""

print users

The content of haproxyfile.txt is below

ssl-default-bind-ciphers EECDH+EDSA+ACM:CDH+aRSA+AEdfGCM:EECDH+ECDSA+SHA384:EEC+
ESA+SHA:EDH+aRSA+SHA384:EECDH+aRSA+SHA256:EDH:AES128-GCM-SHA256:AES128-SHA256:AES128-S
HA:EDH+SA:AES256-GCM-SHA384:AES-SHA256:AES256-SHA:!RC4:!aNULL:!eNULL:!LOW:!3D:!MD5:!EXP:
!PSK:!SRP:!DSS

        # Users
        userlist IntacctAdmins
          group admins users aasghar,achouchoulas,bwright,calla,gspiliotis,haris,pdam
          user aasghar password $1$CFdTKLSRSbQME/
          user achouchoulas password $1$uLy//uPCaVSNhfFG/
          user bwright password $1$q3Fk$kmqM.J531
          user calla password $1$f%g23a44$Bl.1fPj/
          user gspiliotis password $1$d/2OI.TQOiV1
          user haris password $1$mwQ$uG/1mUjE0
          user pdam password $1t24Z$K4FUH/

What I need to parse from the content

The line after having the words groups are the lines where my user names are located. They are the single words after user keyword.I have fetched it using the method above.Is there any better way to fetch it?


texts: Merging and summing multi-dimensional arrays

texts:
I've found myself today really struggling with this subject and I'm pretty sure that there must be a better way to do this.

First of all my arrays have the same layout, I need to merge them and sum every value by domain.

Let me give you an example:

$array[0]['X1']['Y1'] = 1;
$array[0]['X1']['Y2'] = 2;
$array[0]['INFO']['DOMAIN'] = 'example1.com';

$array[1]['X1']['Y1'] = 1;
$array[1]['X1']['Y2'] = 2;
$array[1]['INFO']['DOMAIN'] = 'example1.com';

$array[2]['X1']['Y1'] = 2;
$array[2]['X1']['Y2'] = 5;
$array[2]['INFO']['DOMAIN'] = 'example2.com';

$array[3]['X1']['Y1'] = 2;
$array[3]['X1']['Y2'] = 5;
$array[3]['INFO']['DOMAIN'] = 'example2.com';

I need to produce the following new array:

$mergedArray[0]['X1']['Y1'] = 2;
$mergedArray[0]['X1']['Y2'] = 4;
$mergedArray[0]['INFO']['DOMAIN'] = 'example1.com';

$mergedArray[1]['X1']['Y1'] = 4;
$mergedArray[1]['X1']['Y2'] = 10;
$mergedArray[1]['INFO']['DOMAIN'] = 'example2.com';

I'm using the following code to achieve this (forgive me for the bad namings).

foreach($array as $subKey => $subValue) {
    foreach($subValue as $key => $value) {
        foreach($value as $key2 => $value2) {
            if($key2=='DOMAIN' && !isset($merged[$value2])) {
                $merged[$value2] = $subValue;
            } else if ($key2=='DOMAIN' && isset($merged[$value2])) {
                foreach($subValue as $key3=>$value3) {
                    foreach($value3 as $key4=>$value4) {
                        if($key4!='DOMAIN')
                            $merged[$value2][$key3][$key4] += $value4;
                    }
                }
            }
        }
    }
}

How could I improve this piece of code?


texts:
Given the following definition:

data Cons a = Cons a (Cons a)
             | Empty
             deriving Show

I implemented the following attempt at its Applicative instance:

instance Applicative Cons where
    pure x               = Cons x Empty
    Empty <*> _          = Empty
    (Cons g gs) <*> x    = append (fmap g x) (gs <*> x)

append :: Cons a -> Cons a -> Cons a
append Empty x           = x
append x Empty           = x
append (Cons x Empty) ys = Cons x ys
append (Cons x xs) ys    = Cons x (append xs ys)

Please review this implementation - for correctness and whether it's idiomatic/verbose, etc.


texts:
Is there a way to improve the Javascript that I wrote in this code? I made a dropdown box that toggles between showing and hiding the textbox. I then realize that the Jquery/Javscript code I was writing began to repeat itself.

Just want to know if there is a way to simplify the Javascript/JQuery that I wrote.

Is there a way to improve the Javascript that I wrote in this code? I made a dropdown box that toggles between showing and hiding the textbox. I then realize that the Jquery/Javscript code I was writing began to repeat itself.

Just want to know if there is a way to simplify the Javascript/JQuery that I wrote.

$(document).ready(function() {
  $("body").css("background-color", "yellow");

  $("#dropdown1").on('click', function() {
    $('#menu1').slideToggle();
    var arrow = $("div.arrow");
    arrow.toggleClass("right");
    arrow.toggleClass("down");
  });
  $("#dropdown2").on('click', function() {
    $('#menu2').slideToggle();
    var arrow = $("div.arrow2");
    arrow.toggleClass("right2");
    arrow.toggleClass("down2");
  });
});
body {
  background-color: #333;
}

.wrapper {
  max-width: 1024px;
  display: block;
  margin: 0 auto;
  background-color: #ffffff;
  padding: 5px 20px;
}

div.container {
  max-width: 90%;
}

.arrow,
.arrow2,
.arrow3 {
  /*    float: left;*/
  display: inline-block;
  border: solid black;
  border-width: 0 3px 3px 0;
  padding: 4px 4px 4px 4px;
  margin: 0 0 0 10px;
}

.down,
.down2 {
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
  margin: 0 0 2px 10px;
}

.up {
  transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
  margin: 0 0 -4px 10px;
}

.right,
.right2,
.right3 {
  transform: rotate(-45deg);
  -webkit-transform: rotate(-45deg);
  margin: 0 0 0px 10px;
}

#menu1,
#menu2,
#menu3 {
  display: none;
}

.title {
  padding: 5px 0 5px 10px;
  display: inline-block;
}
<!DOCTYPE html>

  <link href="style.css" rel="stylesheet" type="text/css">
  <title></title>

Dropdown 1

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
            irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Dropdown 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute
            irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


texts:
I wrote a variation of the Caeser Cipher and would like some feedback.
Is it idiomatic? Can you generally see anything that can be improved?

Use example:

let e = enc "Hello World" "This is the key"
 in dec e "This is the key"

Instead of taking a single value as the offset, it takes a String as the key and uses each respective character from the key as the offset; wrapping when it reaches the upper/lower bound.

module Encryption where

import Data.Char

type Key = String
type Message = String
type Direction = (Int -> Int -> Int)

--Upper and lower ascii code bounds
upperBound = 127 ; lowerBound = 32

shift :: Char -> Char -> (Int -> Int -> Int) -> Char
shift char charoff dir = fix $ dir (ord char) (ord charoff)

fix :: Int -> Char
fix charcode
        | charcode > upperBound = chr $ (lowerBound - 1) + excessOf (upperBound + lowerBound)
        | charcode < lowerBound = chr $ (upperBound + 1) - excessOf (lowerBound - lowerBound)
        | otherwise = chr charcode
        where   excessOf boundry = abs(boundry - charcode)

alter :: Message -> Key -> (Int -> Int -> Int) -> Message
alter msg key dir = [(shift c k dir) | (c,k) <- zip msg (cycle key)]

enc msg key = alter msg key (+)
dec msg key = alter msg key (-)

--Basic Caeser Cipher
{-
alter :: Message -> Key -> Direction -> Message
alter m k dir = [chr $ dir (ord out) k | out <- m]

enc m k = alter m k (+)
dec m k = alter m k (-)
-}


texts: Rails view to list users in a zebra-striped table

texts:
<% i = 0 %>
<% @patients.each do |patient| %>
 <tr class="<%= i % 2 == 0 ? 'Even' : 'Odd' %>">
    <%= link_to patient.id, patient %>
    <%= patient.user.username %>
    <%= patient.user.first_name %>
    <%= patient.user.last_name %>
    <%= patient.user.email %>
    <%= patient.user.active %>
    <%= patient.user.disabled %>

<%= link_to 'Detail', patient %>

<% i += 1 %>

I don't like that I have to define an i variable, is there a better way?


texts:
As per a similar question, following a lockfree list implementation. Note that this list has a pre-defined maximum set of elements which can be inserted (N argument in the template declaration). Please let me know if I've missed anything.

// Lockfree FIFO list, with N pre-allocated slots
template<typename T, size_t N = 128>
class list {
    typedef union {
        struct {
            T   *ptr;
            size_t  cnt;
        } s;
        __int128    intv;
    } ptrcnt;

    volatile size_t _head,
            _tail;
    ptrcnt      _ptrbuf[N];
public:
    // Initialise elements' cnt with a non-equal seed
    list() {
        _head = _tail = 0;
        for(size_t i = 0; i < N; ++i) {
            _ptrbuf[i].s.ptr = 0;
            _ptrbuf[i].s.cnt = i*100 + i*3 + i;
        }
    }

    bool push(const T& in) {
        std::auto_ptr<T>    v(new T(in));
        while(true) {
            // first, prepare pointer to use next
            ptrcnt      cur_ptr = _ptrbuf[_tail%N],
                    next_ptr = cur_ptr;
            cur_ptr.s.ptr = 0;
            next_ptr.s.ptr = v.get();
            ++next_ptr.s.cnt;
            if(_tail - _head  >= N) {
                break;
            }
            // add new element
            if(!__sync_bool_compare_and_swap(&_ptrbuf[_tail%N].intv, cur_ptr.intv, next_ptr.intv)) {
                continue;
            }
            // if we're after this point, no other thread should have
            // accessd the slot, set the tail
            __sync_fetch_and_add(&_tail, 1);
            // all done, return true
            v.release();
            return true;
        }
        return false;
    }

    bool pop(T& out) {
        while(true) {
            // get current pointer, then swap
            ptrcnt      lcl_ptr = _ptrbuf[_head%N],
                    next_ptr = lcl_ptr;
            next_ptr.s.ptr = 0;
            ++next_ptr.s.cnt;
            if(!lcl_ptr.s.ptr || _head == _tail) {
                return false;
            }
            // first, swap pointer to use next
            if(!__sync_bool_compare_and_swap(&_ptrbuf[_head%N].intv, lcl_ptr.intv, next_ptr.intv)) {
                continue;
            }
            // then increment the head; no other thread should access 'head'
            // while performing this increment
            __sync_fetch_and_add(&_head, 1);
            // return the value
            out = *lcl_ptr.s.ptr;
            delete lcl_ptr.s.ptr;
            return true;
        }
        return false;
    }
};


texts: Implement two level caching using spring's cache abstraction Cache and CacheManager

texts:
Details about spring's caching framework are here. When I was reading this link, I thought the composite cache mentioned there was one that used levels of caching based on the order given to the constructor. On reading the documentation here, I realized that it was not so; this was so that different caching solutions could be used in different methods.

With the following code, one can have a GuavaCache as L1 as that uses plain Java objects and wouldn't incur network latency or serialization and deserialization overhead. In case of a miss in L1 one would perform a get from L2 (and put it in L1 if found there). For L2 one might use a distributed caching solution - probably a cache running on another fleet of hosts.

TwoLevelCacheManager

package hello;

import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.support.NoOpCacheManager;

import java.util.Collection;

public class TwoLevelCacheManager implements CacheManager {
    CacheManager currentLevel;
    CacheManager nextLevel;

    TwoLevelCacheManager(CacheManager singleLevel) {
        this(singleLevel, new NoOpCacheManager());
    }

    TwoLevelCacheManager(CacheManager currentLevel, CacheManager nextLevel) {
        //assert both contain same cache names or dynamic creation true?
        this.currentLevel = currentLevel;
        this.nextLevel = nextLevel;
    }

    @Override
    public Cache getCache(String name) {
        return new TwoLevelCacheCache(name, currentLevel.getCache(name), nextLevel.getCache(name));
    }

    @Override
    public Collection<String> getCacheNames() {
        return currentLevel.getCacheNames();
    }
}

TwoLevelCacheCache

package hello;

import org.springframework.cache.Cache;

public class TwoLevelCacheCache implements Cache {
    private String name;
    private Cache levelOneCache;
    private Cache nextLevelCache;

    TwoLevelCacheCache(String name, Cache cache) {
        this(name, cache, new NoOpCache(name));
    }

    TwoLevelCacheCache(String name, Cache levelOneCache, Cache nextLevelCache) {
        this.name = name;
        this.levelOneCache = levelOneCache;
        this.nextLevelCache = nextLevelCache;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Object getNativeCache() {
        return this;
    }

    @Override
    public ValueWrapper get(Object o) {
        ValueWrapper value = levelOneCache.get(o);
        if (value == null) {
            value = nextLevelCache.get(o);
            if (value != null) {
                levelOneCache.put(o, value.get());
            }
        }
        return value;
    }

    @Override
    public <T> T get(Object o, Class<T> aClass) {
        T value = levelOneCache.get(o, aClass);
        if (value == null) {
            value = nextLevelCache.get(o, aClass);
            if (value != null) {
                levelOneCache.put(o, value);
            }
        }
        return value;
    }

    @Override
    public void put(Object o, Object o1) {
        levelOneCache.put(o, o1);
        nextLevelCache.put(o, o1);
    }

    @Override
    public ValueWrapper putIfAbsent(Object o, Object o1) {
        //synchronize?
        ValueWrapper value = get(o);
        if (value == null) {
            put(o, o1);
        }
        return value;
    }

    @Override
    public void evict(Object o) {
        levelOneCache.evict(o);
        nextLevelCache.evict(o);
    }

    @Override
    public void clear() {
        levelOneCache.clear();
        nextLevelCache.clear();
    }
}


texts: A Discord bot that connects to a local database (OOP)

texts:
I am currently working on a Discord bot as a way to learn and practice Python. I have been trying to learn object-oriented programming, and apply the "don't repeat yourself" principle.

The code below connects/disconnects from a local database (using XAMPP) with the "mysql.connector" package, and registers a user in the database using their Discord ID. In my example below, I define a class called MySQL, and define three methods (connect(), disconnect() and query_users()) that I found myself using in almost every command/method.

In my register command/method, I call all three methods (connect(), disconnect() and query_users()). Is this the correct way to access those methods and their variables in my register command? My code works great, but the more I read on OOP, the less confident I become, and the more I question myself. Any tips or confirmation would be greatly appreciated.

Thank you all for your help.

"""The following packages/modules are required:"""
import json
import mysql.connector
from discord.ext import commands as viking

with open('config/database.json') as config:
    database = json.load(config)

class MySQL:
    def __init__(self, viking):
        self.viking = viking

    def connect(self):
        self.connection = mysql.connector.connect(**database)
        self.cursor = self.connection.cursor(buffered=True)

    def disconnect(self):
        self.cursor.close()
        self.connection.close()

    def query_users(self):
        self.cursor.execute("SELECT discord_id FROM users")
        self.existing_users = ', '.join([str(users[0]) for users in self.cursor])

    @viking.command(pass_context=True)
    async def register(self, ctx):
        """*register
        Viking will register your Discord ID in the Viking database."""

        self.connect()
        self.query_users()
        discord_id = str(ctx.message.author.id)

        if discord_id in self.existing_users:
            await self.viking.say('You are already a registered member in the Viking database.')
        else:
            self.cursor.execute("INSERT INTO users (discord_id) VALUES (%s)", (discord_id,))
            self.connection.commit()
            await self.viking.say('You are now registered in the Viking database.')

        self.disconnect()


texts: Count frequency of words in a string returning list of unique words sorted by frequency in descending order

texts:
I have the following solution but I am trying to optimize it to run in O(n) time, any thoughts?

I first split the string removing any non-alphanumeric characters, then split the words using spaces and then sort the new string. The rest is just looping to get the duplicate words and its count which I sort one last time to have the most frequently used word on top of the list.

This function also takes care of empty spaces, and limits the numofwords parameter to the total number of words, to avoid any unexpected results.

function getFrequency(mystring, numofwords) {
    mystring = mystring.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()]/g,"");
    var words = mystring.split(' '),
    sortedWords = words.sort(),
    uniqueWords = [],
    d = {},
    wordcount = 1,
    result = [];

    for (var i=0; i<sortedWords.length; i++) {

        var currentword = sortedWords[i];

        if(sortedWords[i+1] === currentword) {
            wordcount++;
        }

        if(!d[currentword]) {
            d[currentword] = true;
            uniqueWords.push({word:currentword, count:wordcount});
        }
    }

uniqueWords = uniqueWords.slice(0,numofwords).sort(function (a,b) { return b.count-a.count;});

for(i=0; i<uniqueWords.length; i++) {

    result.push(uniqueWords[i].word);
}

return result.toString();
}


texts:
I'm saving string values in an array one at a time so I cannot initialize the array with the values all at once. After I'm done with the array I need to pass it to another class that is expected a String array.

Normally I would use a List but the end result is expecting an Array so I stuck with the Array. I'm having second thoughts though because maybe it would have better performance if I used a List then when I'm finished filling up the List I could use List.toArray and get the Array that way? Here is majority of the Array code I wrote that takes one argument at a time and adds it to the Array,

public String[] addArgument(String[] arguments, String arg) {

    String[] temp = new String[arguments.length + 1];

    for(int i=0; i<arguments.length; i++)
        temp[i] = arguments[i];

    temp[arguments.length] = arg;

    arguments = temp;

    temp = null;

    return arguments;
}


texts: Confirming the presence/create directories

texts:
While preparing an automated process to manipulate files, I've made the following function to check for the base directory and sub-directories presence, as to allow or deny the remaining code to be executed:

/* Check Directories
 *
 * Confirm that the necessary directories exist, and if not,
 * tries to create them.
 *
 * @_param string $whereAmI    -> Script location
 * @_param string $backup_path -> target directory relative path
 * @_param array  $subDirArr   -> sub-directories array
 *
 * @return
 *  success -> Boolean
 *  failure -> string with failure path
 */
function check_directories($whereAmI, $backup_path, $subDirArr) {

  // initialize return variable
  $status = FALSE;

  // check for the merchant base directory
  if (!is_dir($whereAmI."/".$backup_path)) {

      // trying to create the directory with permissions
      exec("mkdir ".$backup_path." -m 777 2>&1", $output, $return_value);

      // error returned, stop and return status
      $status = (is_array($output) && count($output)>=1) ? $backup_path : TRUE;
  } else {
    $status = TRUE;
  }

  // base directory exists, continue
  if ($status===TRUE) {

      // run by each sub-directory
      foreach ($subDirArr as $subDir) {

          /* keep checking for status value, if changed,
           * one directory has failed and we can't proceed
           */
          if ($status===TRUE) {

              // check for the sub-directory presence
              if (!is_dir($whereAmI."/".$subDir)) {

                  // trying to create the directory with permissions
                  exec("mkdir ".$subDir." -m 777 2>&1", $output, $return_value);

                  // error returned, stop and update status
                  $status = (is_array($output) && count($output)>=1) ? $subDir : TRUE;
              }

          } else {
              return $status;
          }
      }
  }

  return $status;
}

Considerations:

Directory permissions when in production aren't 777.
Server is running PHP Version 5.3.10.

Can this be simplified, thus reducing the amount of code, and perhaps in such reduction, have it improved?


texts: Sending test emails to a list of email addresses

texts:
I've made the following program that takes a list of email addresses from a table in MS Access and sends each a test email.

'Send email to mailing list
Function SendNotificationEmail()

 'Handle any errrors
 On Error GoTo ErrHandler:

    'Create Outlook object
    Dim olApp As Outlook.Application

    'Namespace
    Dim olNS As Outlook.NameSpace
    Dim olFolder As Outlook.MAPIFolder

    'Create a reference to the email item you will use to send the email
    Dim olMailItem As Outlook.MailItem

    Set olApp = CreateObject("Outlook.Application")
    Set olNS = olApp.GetNamespace("MAPI")

    Set olFolder = olNS.GetDefaultFolder(olFolderInbox)
    Set olMailItem = olFolder.Items.Add("IPM.Note")

    'Create the body of the message
    Dim strBodyText As String
    strBodyText = "Test Email - DELETE ME :D"

    'Open record set on
        Dim dbC As DAO.Database
        Dim rcdSet As DAO.Recordset
        Dim fld As DAO.field

        'Used to update the table
        Dim strSQL As String
        strSQL = "SELECT DISTINCT [Email Address] FROM tblMailingList"

        'Connect to current database
        Set dbC = CurrentDb
        Set rcdSet = dbC.OpenRecordset(strSQL)

        'Count the number of records
        Dim intNumRecords As Integer
        'Move to the last record in order to count all the records
        rcdSet.MoveLast

        intNumRecords = rcdSet.RecordCount - 1
        'Move back
        rcdSet.MoveFirst

        'Get data back from field birth date
        Set fld = rcdSet.Fields("Email Address")

        'Subject
        olMailItem.Subject = "Mailing List Test"

        'Loop through the records
        For i = 0 To intNumRecords
            'Recipient/s
            olMailItem.To = fld.Value

            'Body of email
            olMailItem.Body = strBodyText

            'Automatically send the email
            olMailItem.Send

           'Reset email item otherwise it won't work
            Set olMailItem = olFolder.Items.Add("IPM.Note")

            'Move to the next record
            rcdSet.MoveNext
        Next

    'Close record set and connection
    rcdSet.Close

    'Empty variables
    Set fld = Nothing
    Set rcdSet = Nothing
    Set dbC = Nothing

    'Relase all the object variables
    Set olMailItem = Nothing
    Set olFolder = Nothing
    Set olNS = Nothing
    Set olApp = Nothing

ErrHandler:

'If error occurs
If Err.Number <> 0 Then
  MsgBox "Error Number: " + Err.Number + ": Description: " + Err.Description
End If

End Function

Is my approach above correct? I had to reset the olMailItem in the loop otherwise it would return a Type Error. Is there a better approach to sending multiple emails?


texts: Simple calculator in Object-oriented JavaScript

texts:
There is a simple form which takes two numbers num1, num2 and an operation op. After submission, a new object is created. I'm new to OOJS and any correction and improvements are appreciated. Is this the best way to code this small calculator in Javascript using Object Oriented approach?

window.onload = function() {

  let form = document.forms['cal-form'];
  form.addEventListener('submit', calculate);

  function calculate(e) {
    //prevent default form submission
    e.preventDefault();
    //get form values
    let num1 = parseInt(document.getElementsByTagName('input')[0].value);
    let num2 = parseInt(document.getElementsByTagName('input')[1].value);
    let op = document.getElementsByTagName('select')[0].value;

    //create object constructor function
    function Calculate(num1, num2, op){
      this.num1 = num1;
      this.num2 = num2;
      this.op = op;
    }

    Calculate.prototype.result = function() {
      let res;
      switch (op) {
        case 'add':
          res = this.num1 + this.num2;
          break;
        case 'sub':
          res = this.num1 - this.num2;
          break;
        case 'mul':
          res = this.num1 * this.num2;
          break;
        case 'div':
          res = this.num1 / this.num2;
          break;
        default:
          res= 'Error! No operation selected.';
      }
      return res;
    };

    //create an object
    let cal = new Calculate(num1, num2, op);
    //display result
    document.getElementById('result').innerHTML = cal.result();

  }
};


texts: Looking for improvements on basic dice roll code (Python 3)

texts:
I've created a code based upon a dice roll where the number of rolls is decided by user input. I am new to this, so any and all feedback will be appreciated as I feel the code is quite clunky at best.

number_of_times = int(input("How many times do you want to roll the dice?: "))
print(number_of_times)

def dice_roll(x):
    import random
    for r in range(x):
        roll = random.randint(1,20)
        print(roll)

dice_roll(number_of_times)


texts: Angular controller for Project Euler problems

texts:
I have a controller which contains a $scope object like so:

$scope.ProjectEuler.Ctrl: {
    problems: [//List of problems]
}

In the array above I have listed everything related to that particular Project Euler problem. A typical object in that array looks like this:

{
    id: '1',
    title: 'Mutiples of 3 and 5',
    description: 'description of problem',
    isCollapsed: true,
    logic: function() {
        // List of functions not on $scope that solve the problem
    },
    solution: {
        answer: '',
        msg: {
            text: '',
            type: INFO
        },
        time: ''
    }
}

Finally I have functions that can be used by all the objects above for displaying the answer, each of which requires access to the $scope to determine where the answer is placed - like so:

$scope.ProjectEulerCtrl.functions = {
        setMessage: function (index, msg, severity) {
            this.resetSolution(index);
            // Replace with this?
            $scope.ProjectEulerCtrl.problems[index].solution.msg.text = msg;
            $scope.ProjectEulerCtrl.problems[index].solution.msg.type = severity;
        },
        resetSolution: function (index) {
            $scope.ProjectEulerCtrl.problems[index].solution.answer = '';
            $scope.ProjectEulerCtrl.problems[index].solution.msg.text = '';
            $scope.ProjectEulerCtrl.problems[index].solution.time = '';
        },
        setSolution: function (index, answer, msg, time) {
            $scope.ProjectEulerCtrl.problems[index].solution.answer = answer;
            $scope.ProjectEulerCtrl.problems[index].solution.msg.text = msg;
            $scope.ProjectEulerCtrl.problems[index].solution.time = time;
        }
    };

So above I have another object that contains all the functions that can be used in the array - this attaches at the same level as the 'problems' array.

Question

Is this considered bad practice to have everything attached to the one object in this way?

I know that if I split everything out and just had (for example) $scope.setMessage() it would be on the controller scope anyway and that I have introduced another object to the mix.


texts: grouping values in a list of tuples to a dictionary

texts:
I've a list of tuples (comes in pairs only)

a = [(1,2),(1,4),(3,5),(5,7)]

which I'm trying to convert to a dictionary as below

d = {1: [2, 4], 3: 5, 5: 7}

Here's what I've come up with -

a= [(1,2),(1,4),(3,5),(5,7)]
d= {}

for k, v in a:
    if k not in d:
        d[k] = v
    else:
        d[k] = [d[k]]
        d[k].append(v)

Is there a better way to do this? Can this be achieved using something like defaultdict(list) without having to compromise on the desired output?


texts: Longest increasing subsequence algorithm

texts:
I'm just getting into Rust, and I've decided to implement the longest increasing subsequence algorithm suggested in the related Wikipedia page. Though this program compiles and returns the expected sequence for what's passed to lis, I am wondering if more experienced Rust programmers would have written this same algorithm in a different way?

 fn lis(x: Vec<i32>)-> Vec<i32> {
    let n = x.len();
    let mut m = vec![0; n];
    let mut p = vec![0; n];
    let mut l = 0;

    for i in 0..n {
        let mut lo = 1;
        let mut hi = l;

        while lo <= hi {
            let mut mid = (lo + hi) / 2;

            if x[m[mid]] <= x[i] {
                lo = mid + 1;
            } else {
                hi = mid - 1;
            }
        }

        let mut new_l = lo;
        p[i] = m[new_l - 1];
        m[new_l] = i;

        if new_l > l {
            l = new_l;
        }
    }

    let mut o = vec![0; l];
    let mut k = m[l];
    for i in (0..l).rev() {
        o[i] = x[k];
        k    = p[k];
    }

    o
}

fn main() {
    let v = vec![0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15];
    let o = lis(v);
    println!("{:?}", o);
}


texts: Asynchronously fetching Bitcoin orders and quotes

texts:
I have the following code to get data using async/await

import fetch from 'node-fetch';

let bid = 0;
let ask = 0;
let lastBuy = 0;
let buyOrders = [];
let sellOrders = [];
const currency = process.argv[3].toUpperCase();

const getOrderBook = async () => {
  const orderBook = await fetch(`https://bittrex.com/api/v1.1/public/getorderbook?market=BTC-${currency}&type=both`)
    .then(response => response.json())
    .then(response => response.result)
    .then(result => ({ buys: result.buy.slice(0, 10), sells: result.sell.slice(0, 10) }));

  return orderBook;
};

const getTicker = async () => {
  const ticker = await fetch(`https://bittrex.com/api/v1.1/public/getticker?market=BTC-${currency}`)
    .then(response => response.json())
    .then(response => response.result);

  return ticker;
};

const getCurrencyData = () => {
  getOrderBook().then(orderBook => ([buyOrders, sellOrders] =  [orderBook.buys, orderBook.sells] )); //eslint-disable-line
  getTicker().then(ticker => ([bid, ask, lastBuy] = [ticker.Bid, ticker.Ask, ticker.Last])); //eslint-disable-line
};

setInterval(() => {
  getCurrencyData();
}, 5000);

This is the first time I use async/await, so I have the following doubts:

First, on my getOrderBook and getTicker function I can't find a way to return the values without first assigning to a variable.

Also, it looks very ugly in the getCurrencyData function, because after I called the functions I have to make a ".then" to assign the data to my variables.


texts: Do these unit tests cover my method under test?

texts:
I've written an extension method to truncate strings:

/// <summary>
/// Returns the string, or a substring of the string with a length of <paramref name="maxLength"/> if the string is longer than maxLength.
/// </summary>
/// <param name="maxLength">The maximum length of the string to return.</param>
/// <exception cref="ArgumentException">If <paramref name="maxLength"/> is smaller than zero, an ArgumentException is raised.</exception>
/// <![CDATA[ Documentation:
/// If the string is null or an empty string, the input is returned.
/// If the string is shorter than or equal to maxLength, the input is returned.
/// If the string is longer than maxLength, the first N (where N=maxLength) characters of the string are returned.
/// ]]>
public static String Truncate(this String input, int maxLength)
{
    if (maxLength < 0)
    {
        throw new ArgumentException("Must be >= 0", "maxLength");
    }

    if (String.IsNullOrEmpty(input) || input.Length <= maxLength)
    {
        return input;
    }

    return input.Substring(0, maxLength);
}

I have written these test cases:

[TestFixture]
public class TruncateTests
{
    String longString = "ABC";
    String shortString = "A";
    String nullOrEmptyString = null;
    String output = "";

    [Test]
    public void LessThanOrEqual()
    {
        // If input is shorter than or equal to maxLength, the input is returned.
        output = longString.Truncate(longString.Length + 5);
        Assert.AreEqual(longString, output);

        output = longString.Truncate(longString.Length);
        Assert.AreEqual(longString, output);
    }

    [Test]
    public void GreaterThan()
    {
        // If input is longer than maxLength, the first N (where N=maxLength) characters of input are returned.
        output = longString.Truncate(1);
        Assert.AreEqual(shortString, output);
    }

    [Test]
    public void NullOrEmpty()
    {
        // If input is null or an empty string, input is returned.
        output = nullOrEmptyString.Truncate(42);
        Assert.AreEqual(output, nullOrEmptyString);

        nullOrEmptyString = "";
        output = nullOrEmptyString.Truncate(42);
        Assert.AreEqual(output, nullOrEmptyString);
    }

    [ExpectedException(typeof(ArgumentException))]
    [Test]
    public void MaxLengthException()
    {
        // If maxLength is smaller than zero, an ArgumentException is raised.
        "".Truncate(-1);
    }

    //http://www.fileformat.info/info/unicode/char/1f3bc/index.htm
    string multiByteString = "\x1F3BC";

    [Test]
    public void MultiByte()
    {
        Assert.IsTrue(multiByteString.Length == 2);

        output = multiByteString.Truncate(1);

        Assert.IsTrue(output.Length == 1);
    }
}

Now how can I confirm that:

The method Truncate() does what it is supposed to do?
I have written test code to test al promises made?
This test code follows practices and guidelines valid for unit testing?

I'm especially curious about the last one. I've written a few tests in my time, but I'm never sure whether I'm testing enough and not too much at the same time. Can anyone shed a general light on this and maybe point me towards invaluable resources about unit testing?


texts: A .py utility file for neural network learing rate policies

texts:
I've created a .py utility file, which specifies the learning rate policy for the neural network in PyTorch. The program in prior reads a json and creates a dict, called here is cfg.
So far, I have implemented 3 kinds of learning policies - steps, exp, cos, and for each of them I've created a separate class with the __call__ method. I've done this to have this parameters set in the LambdaLR without further refering to cfg during the training.
In order to avoid branch of if's I've created a dict, which chooses one of the options, and in the function create_scheduler the instance of one of these classes is created, passed to the initializer of LambdaLR scheduler, and this scheduler is then returned.
class LR_Steps:
    def __init__(self, cfg):
        self.lr_base = cfg["OPTIM"]["BASE_LR"]
        self.lr_mult = cfg["OPTIM"]["LR_MULT"]
        self.steps   =  cfg["OPTIM"]["STEPS"]
        # the current index in the steps
        self.ind = 0

    def __call__(self, epoch):
        if epoch > self.steps[self.ind]:
            self.ind += 1

        return self.lr_base * (self.lr_mult ** self.ind)

class LR_Exp:
    def __init__(self, cfg):
        self.lr_base = cfg["OPTIM"]["BASE_LR"]
        self.lr_mult = cfg["OPTIM"]["LR_MULT"]

    def __call__(self, epoch):
        return self.lr_base * (self.lr_mult ** epoch)

class LR_Cos:
    def __init__(self, cfg):
        self.lr_base = cfg["OPTIM"]["BASE_LR"]
        self.max_epoch = cfg["OPTIM"]["MAX_EPOCH"]

    def __call__(self, epoch):
        return 0.5 * self.lr_base * (1.0 + np.cos(np.pi * epoch / self.max_epoch))

lr_policy_dict = {
    "cos" : LR_Cos,
    "exp" : LR_Exp,
    "steps" : LR_Steps
}

def create_scheduler(optimizer, cfg):
    return optim.lr_scheduler.LambdaLR(optimizer, lr_policy_dict[cfg["OPTIM"]["LR_POLICY"]](cfg))

My question is - if there a shorter or safer way to do this? I would also appreciate criticism, concerning the structure of code and functionality.


texts: Correct and safe way of performing token exchange?

texts:
I am dipping my fingers in external apis that a user would login and retrieve a code to exchange for a token.
In my case, it is for the SpotifyAPI.

All the web app does it return the users top tracks of x amount of time.

Please note I havent done much cleaning up as im not entire sure whether my flow is secure and the correct way to do it

I have a basic flow of:

User explicitly presses an Authorize Button
When authorized via the spotify api, they are redirected to a callback function where an authorization code is retrieved from the URL and passed to the server
The code is then used to exchange for a token and then I am able to perform api requests

HomeComponent which contains the button press to authorize the user - Step 1

export class HomeComponent {

    baseUrl: string;
    http: HttpClient;
    constructor(@Inject('BASE_URL') baseUrl: string, http: HttpClient){

      this.baseUrl = baseUrl;
      this.http = http;
  }
//Called on button press
  authenticate() {
    this.http.get<string>(this.baseUrl + 'spotify/authenticate').subscribe(result => {
    }, error => console.error(error));
  }
}

authenticate calls through to an angular component which passed the code to this Web API method (will remove singleton in future) - Step 2

[HttpGet]
[Route("authenticate")]
public void Authenticate()
{
    AuthSingleton.auth = new AuthorizationCodeAuth(
        "clientID",
        "secretID",
        "https://localhost:44345/top",
        "http://localhost:4002",
        Scope.UserTopRead
    );
    AuthSingleton.auth.Start(); // Starts an internal HTTP Server
    AuthSingleton.auth.OpenBrowser();
}

This starts the authentication where the Spotify "login page" appears.

Once logged in, the callback then calls this Web API method - Step 3

[HttpGet]
[Route("top")]
public async Task<OkObjectResult> Top(string code)
{
    AuthSingleton.auth.Stop();

    if (code != null)
    {
        //Code used to get token
        Token token = await AuthSingleton.auth.ExchangeCode(code);

        SpotifyWebAPI api = new SpotifyWebAPI();

        if (token.IsExpired())
        {
            Token refreshToken = await AuthSingleton.auth.RefreshToken(token.RefreshToken);
            api.AccessToken = refreshToken.AccessToken;
            api.TokenType = refreshToken.TokenType;
        }
        else
        {
            api.TokenType = token.TokenType;
            api.AccessToken = token.AccessToken;
        }
        //Api Requests
        Paging<FullTrack> shortTermTracks = api.GetUsersTopTracks(TimeRangeType.ShortTerm);
        MappedTracks mappedTracks = TrackMapper.MapTracks(shortTermTracks);

        //Return the top tracks
        return Ok(mappedTracks);
    }
    return null;
}

Is this an okay way of doing what I am trying to achieve?


texts: entab program which replaces 4 spaces with a tab

texts:
I wrote an entab program which needs to replace every \$n\$ spaces with 1 tab. I picked \$n\$ to be 4, so every 4 spaces should be 1 tab. I have a feeling that my code is far too complicated than it should be, and the logic I made it with could be much simpler.

The logic of the code:

Note: \$n\$ = 4

Get line from input and put it in line array.
Whenever n spaces is found in that line kick n-1 of them from the array and the remaining space is replaced with tab.
Print the line.

#include <stdio.h>
#define MAXLINESIZE 100
#define TABSPACES 4

int mgetline(char *s, int lim);
void kick(char *x, char val);
int countx(char *x);
void swap(char* x, int i, int j);

int main(void) {
    char line[MAXLINESIZE];
    char *linep = line;
    char *tmp = 0;
    int tab = 0;
    int i = TABSPACES - 1;
    while (mgetline(line, MAXLINESIZE) > 0) {
        while (*linep) {
            if (*linep == ' ') {
                if (tab == TABSPACES - 1) {
                    while (i > 0) {
                        tmp = linep - i;
                        kick(tmp, ' ');
                        linep--;
                        i--;
                    }
                    *linep = '\t';
                    tab = 0;
                }
                else
                    tab++;
            }
            else
                tab = 0;
            linep++;
        }
        printf("%s", line);
        linep = line;
    }
    return 0;
}

int mgetline(char *s, int lim)
{
    int c;
    char *t = s;

    while (--lim > 0 && (c = getchar()) != EOF && c != '\n')
        *s++ = c;
    if (c == '\n')
        *s++ = c;

    *s = '\0';

    return s - t;
}

void kick(char *x, char val) {
    char *sp = x;
    int i = 1;
    while (*x) {
        if (*x == val) {
            while (countx(sp) - i != x - sp) {
                swap(sp, x - sp, countx(sp) - i);
                i++;
            }
            *(sp + countx(sp) - 1) = 0;
            return;
        }
        x++;
    }
}

int countx(char* x) {
    int i;
    for (i = 0; x[i]; i++);
    return i;
}

void swap(char* x, int i, int j) {
    char tmp = x[i];
    x[i] = x[j];
    x[j] = tmp;
}


texts: An attempt at a simple type safe python enum

texts:
There have been many posts here about enums in python, but none seem to be both type safe and simple. Here is my attempt at it. Please let me know if you see anything obviously wrong with it.

def typeSafeEnum(enumName, *sequential):
    topLevel = type(enumName, (object,), dict(zip(sequential, [None] * len(sequential))))
    vals = map(lambda x: type(x,(topLevel,),{}), sequential)
    for k, v in zip(sequential, vals):
        setattr(topLevel, k, v())
    return topLevel

Then to test it:

Colors = typeSafeEnum('Colors', 'RED', 'GREEN', 'BLUE')

if __name__ == '__main__':
    x = Colors.RED
    assert isinstance(x, Colors)


texts: Elixir/Ecto find_or_create with custom error

texts:
I need to find_or_create user, but first, check if his email ends with a required domain.

Can I somehow write following code using pattern matching with/case block?

  def create_user(attrs \\ %{}) do
    %User{}
    |> User.changeset(attrs)
    |> Repo.insert()
  end

  def find_or_create_user(attrs \\ %{}) do
    if String.ends_with?(attrs.email, "@test.com") do
      user = Repo.get_by(User, %{email: attrs.email}) # returns nil or user
      if user do
        {:ok, user}
      else
        create_user(attrs) # returns {:ok, user} or {:error, :reason}
      end
    else
      {:error, :invalid_email_domain}
    end
  end


texts: Validating a model that requires database access

texts:
Let's say I have this User model:

class User
{
    public $id;
    public $email;
    public $password;
    public $errors;

    public function isValid()
    {
        if (strpos($this->email, '@') === false) {
            $this->errors['email'] = 'Please enter an email address';
        }
        if (!$this->password) {
            $this->errors['password'] = 'Please enter a password';
        } elseif (strlen($this->password) < 4) {
            $this->errors['password'] = 'Please enter a longer password';
        }

        return !$this->errors;
    }
}

And let's say I have this UserDAO for retrieving, adding, updating, and deleting users:

class UserDAO
{
    protected $conn;
    protected $logger;

    public function __construct(PDO $dbh, Logger $logger)
    {
        $this->dbh = $dbh;
        $this->logger = $logger;
    }

    public function getUsers()
    {
        $rows = null;
        try {
            $rows = $this->dbh->query("SELECT * FROM users")->fetchAll();
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return $rows;
    }

    public function getUserById($id)
    {
        $row = null;
        try {
            $sth = $this->dbh->prepare("SELECT * FROM users WHERE id = ?");
            $sth->execute(array($id));
            $row = $sth->fetchObject('User');
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return $row;
    }

    public function addUser(User &$user)
    {
        $success = false;
        try {
            $sth = $this->dbh->prepare("
                INSERT INTO users (email, password) VALUES (?, ?)
            ");
            $sth->execute(array($user->email, $user->password));
            if ($success = (bool) $sth->rowCount()) {
                $user->id = $this->dbh->lastInsertId();
            }
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return $success;
    }

    public function updateUser(User $user)
    {
        // ...
    }

    public function deleteUser($id)
    {
        // ...
    }

    public function isEmailUnique($email)
    {
        $count = 0;
        try {
            $sth = $this->dbh->prepare("SELECT COUNT(id) FROM users WHERE email = LOWER(?)");
            $sth->execute(array($email));
            $count = $sth->fetchColumn();
        } catch (PDOException $e) {
            $this->logger->log($e->getMessage(), __METHOD__);
        }
        return !$count;
    }
}

When I process a form, I typically do something like this:

// ...

$userDAO = new UserDAO($dbh, $logger);
$user = new User();
$user->email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
$user->password = filter_input(INPUT_POST, 'password');
// validate user
if ($user->isValid()) {
    // check if email address is unique (SO UGLY!)
    if ($userDAO->isEmailUnique($user->email)) {
        $user->errors['email'] = 'Please use a different email address';
    }
    // save user
    if ($user->addUser($user)) {
        // ...
    } else {
        // ...
    }
} else {
    // do something with $user->errors
}

This works great for simple cases, but how can I improve this? In particular, how can I do validations that require database access? For example, if I wanted to check that the email is unique and make it part of my validation, what would be a better way of doing this?


texts:
I have implemented several lock-free algorithms to maximise throughput but have always baulked when performing a spin-lock. I can usually convince myself that this is the only way but it still nags at me that a spin-lock is a terribly bad idea.

I recently came across a FIFOMutex code fragment and thought perhaps that would be a solution. I have hacked it around a bit because I don't want mine to consume interrupt exceptions but essentially it looks like this:

/**
 * Queue of blocked writers.
 */
private static class BlockedQueue {
  // Everyone who is waiting.
  private final Queue<Thread> waiting = new ConcurrentLinkedQueue<>();
  // Ensure only one thread unlocks at a time.
  private final AtomicBoolean lock = new AtomicBoolean(false);

  public void sleep() {
    Thread me = Thread.currentThread();
    // Put me in the queue.
    waiting.add(me);
    try {
      do {
        // Park until I am head of the queue and I hold the lock
        LockSupport.park(this);
        /*
         * If I am not at the head of the queue - go back to sleep.
         *
         * If I am at the head of the queue - grab the lock and get out of the loop.
         *
         * If I was at the head and I couldn't get the lock - go back to sleep -
         * someone else is still in the process of exiting.
         */
      } while (!(waiting.peek() == me && lock.compareAndSet(false, true)));
    } finally {
      // Take me from the queue - it must be me because I locked everyone else out.
      waiting.remove();
      // Done with the lock.
      lock.set(false);
    }
  }

  public void wakeup() {
    // Wake the first in the queue ... unpark does nothing with a null parameter.
    LockSupport.unpark(waiting.peek());
  }
}
// Use this to block for a while.
private final BlockedQueue block = new BlockedQueue();

/**
 * Wait for a time when it is likely that a free slot is available.
 */
private void waitForFree() {
  // Still full?
  while (isFull()) {
    // Park me 'till something is removed.
    block.sleep();
  }
}

/**
 * A slot has been freed up. If anyone is waiting, let the next one know.
 */
private void signalFree() {
  block.wakeup();
}

See how I can now call block.sleep() in what used to be a spin-lock around while(isFull()).

What I like most about this is that the wakeup method is truly simple and that it will only wake up the thread that has been waiting longest.

I have some questions though:

Will this do what I want it to do - i.e. handle multiple threads waiting for a resource without consuming unnecessary CPU.
Is the while ((removed = waiting.remove()) != me) necessary? Logic suggests that the head of the queue at that point must be me but is there a scenario where it may not be?


texts: Is the following repository pattern properly applied?

texts:
Is this repository code written according to best practices? The Last Section I included it in the repository as well.

class HR_Repository<T> : IRepository<T> where T : class
{
    private readonly  LoginDataContext dataContext;
    public HR_Repository(LoginDataContext dataContext)
    {
    this.dataContext = dataContext;
    }

    public void Commit()
    {
        dataContext.SubmitChanges();
    }

    public IList<T> FindAll()
    {
        var table = this.LookupTableFor(typeof(T));
        return table.Cast<T>().ToList();
    }

    public IQueryable<T> Find()
    {
        var table = this.LookupTableFor(typeof(T));
        return table.Cast<T>();
    }

    public void Add(T item)
    {
        var table = this.LookupTableFor(typeof(T));
        table.InsertOnSubmit(item);
    }

    public void Delete(T item)
    {
        var table = this.LookupTableFor(typeof(T));
        table.DeleteOnSubmit(item);
    }

    private ITable LookupTableFor(Type entityType)
    {
        return dataContext.GetTable(entityType);
    }
}

public static class UserQueries
{
    public static Employee ByUserName(this IQueryable<Employee> employees, string username)
    {
        return employees.Where(u => u.User_Name == username).FirstOrDefault();
    }
}


texts: Async scheduler that executes commands multitthreaded

texts:
I have made a multithreaded command runner that works, just wanted to share the code and see if you guys can see any pitfalls. Comments are not part of actual code

protected async Task<bool> PollQueue(CancellationToken cancellationToken)
{
    async Task<Batch> SyncQueueTask(CancellationToken token)
    {
        await WaitForQueue(token);
        return null;
    }

    var queue = new Queue<Batch>();
    var runners = new Dictionary<Guid, Task<Batch>>();

    Task<Batch> syncTask = null;
    var cancelSyncTask = new CancellationTokenSource();
    bool QueueWasReleased() => syncTask == null;

    do
    {
        //Do not spawn new work if application is closing down, but let ongoing work have a chance to complete
        if (!cancellationToken.IsCancellationRequested)
        {
            var slots = Environment.ProcessorCount - runners.Count;
            //Poll SQL queue if slots are available and we have gotten a signal that work is is available
            if (QueueWasReleased())
            {
                using (var scope = _serviceProvider.CreateScope())
                {
                    var batch = (await scope.ServiceProvider.GetService<ICommandRepository>()
                            .ListByAsync(CommandState.Pending))
                            .Where(c => !runners.ContainsKey(c.BatchId))
                            .GroupBy(c => c.BatchId)
                            .Select(grp => new Batch {Id = grp.Key, Commands = grp.ToList()});

                    queue = new Queue<Batch>(batch);
                }
            }
            //Start new work
            var tempQueue = queue;
            Enumerable
                .Range(0, Math.Min(slots, queue.Count))
                .ForEach(i =>
                {
                    var batch = tempQueue.Dequeue();
                    var runner = Task.Run(async () =>
                    {
                        await batch
                            .Commands
                            .Select(ExecuteCommand)
                            .WaitAll(cancellationToken);

                        return batch;
                    }, CancellationToken.None);
                    runners[batch.Id] = runner;
                });
        }

        if (runners.Count == 0) break;
        //Create a sync task thats only purpose is to release await if new work is available. This is to that long running work does not starve queue
        if (syncTask == null)
            syncTask = SyncQueueTask(cancelSyncTask.Token);

        //Wait for next completed work or that new work are avialable on queue
        var completed = await Task.WhenAny(runners.Values.Concat(syncTask));
        if (completed == syncTask)
            syncTask = null;
        else
            runners.Remove(completed.Result.Id);

    } while (true);

    //Cleanup if we are waiting
    if (syncTask != null)
        cancelSyncTask.Cancel();

    return false;
}

WaitForQueue is just a semaphoreslim. (With an extensionmethod that swallows cancelation exceptions)

private Task WaitForQueue(CancellationToken token)
{
    return _queueSync.SilentWaitAsync(Delay, token);
}


texts: Reducing lock contention for a caching utility, or make it totally lockless but threadsafe

texts:
My Java program is a module called configProxy which fetches configuration entries from a remote node (say from a Redis instance). When the caller calls the get(configKey) method, this module checks in a local cache (a concurrent hashmap) to see if the setting is already cached.  If not, it fetches the setting from a Redis instance, caches it and then returns.

The implementation of this singleton class:

public class ConfigProxy {

/** This is our one-n-only instance **/
private static ConfigProxy _instance = null;

/** default values for some keys which may not be declared **/
private HashMap<String, String> _defaults = null;

private Jedis jedisConfigConnection;

// hash map for storing the data of config proxy as a cache for each
// String,List and Hash
// to prevent constant hitting to Redis
private ConcurrentHashMap<String, String> _cacheStrings = new ConcurrentHashMap<String, String>();
private ConcurrentHashMap<String, List<String>> _cacheLists = new ConcurrentHashMap<String, List<String>>();
private ConcurrentHashMap<String, HashMap<String, Object>> _cacheHashes = new ConcurrentHashMap<String, HashMap<String, Object>>();

/*
 * Takes host and port as parameters to connect with redis instance
 */
private ConfigProxy(String host, int port) throws ConnectionException {

    try {

        jedisConfigConnection = new Jedis(host, port);
        jedisConfigConnection.ping();
    } catch (Exception e) {
        throw new ConnectionException("Unable to connect to Config Server");
    }

}

public static ConfigProxy getInstance(String host, int port)
        throws ConnectionException {

    if (_instance == null) _instance = new ConfigProxy(host, port);
    return _instance;
}

/**
 * Overloaded version which doesn't take any parameters. Inorder for this
 * call to succeed, the caller, somewhere should have called
 * getInstance(host, port), once. else this throws InitializationException.
 *
 * @return
 * @throws NotInitializedException
 */
public static ConfigProxy getInstance() throws NotInitializedException {
    if (_instance == null) throw new NotInitializedException();
    return _instance;
}

...

/**
 * Returns a configuration setting value either from cache or from a
 * configured Redis instance.
 *
 *  If the given setting was not cached, and it needs to be fetched
 *  from Redis, then the code locks this object
 * @param key
 * @return The value configured for the specified key, if one exists.
 */
public String get(String key) {
    if (_cacheStrings.containsKey(key))
        return _cacheStrings.get(key);
    else {
        synchronized (jedisConfigConnection) {
            String res = (String) jedisConfigConnection.get(key);
            if (res == null) return res;
            _cacheStrings.put(key, res);
            return res;
        }
    }
}

...
...
}

Currently, if the key already exists in the cache, the get(configkey) doesn't lock, and simply returns the value from cache.  However the get function (shown at the bottom in the above code), obtains a lock on jedis connection object, before attempting to fetch data from Redis.

I want to know:

If this is correct, or if I obtain a lock on the entire "this" (configProxy) object.
If it is possible to improve it in any way to further reduce locking contentions, as this will be used in a multi-threaded high txn oriented environment.

EDIT

After review, this is my next version of the get method.

public String get(String key) {

    if (_cacheStrings.containsKey(key)) return _cacheStrings.get(key);
    else {
        String res = null;
        synchronized (jedisConfigConnection) { res = (String) jedisConfigConnection.get(key); }
        if (res != null) _cacheStrings.putIfAbsent(key, res);
        return res;
    }
}


texts: Java 8 Stream to produce all permutations of an array using recursion

texts:
I want to write a class that returns a Stream of permutations of an int[].

public class Permutations {
    public static Stream<int[]> of(int[] array) {
        return permute(array, array.length);
    }
    public static Stream<int[]> permute(int[] array, int n) {
        if (n == 1) {
            return Stream.of(Arrays.copyOf(array, array.length));
        } else {
            Stream tmp = Stream.empty();
            for (int i = 0; i < n; i++) {
                swap(array, i, n - 1);
                tmp = Stream.concat(permute(array, n - 1), tmp);
                swap(array, i, n - 1);
            }
            return tmp;
        }
    }
    private static void swap(int[] a, int i, int j) {
        if (i != j) {
            int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
        }
    }
}

Problem with my solution is that it is nesting a lot of Streams with concat, many of them being just empty ones. Another issue is that it creates all permutations before returning the Stream, so it not really streaming...  :- )

I saw Minborg's solution, but I wanted to make something simpler, here based on  Sedgewick and Wayne's algorithm.

Can above code be improved?


texts: Excel Duplicate File name with different Revisions

texts:
I have an Excel where i have file names in one column with the revision numbers in another column. I need to remove the duplicates(file with higher version should be retained and lowerversion deleted).Can you guys help me with excel VBA for this.

Eg Raw Data

Desired output from macro

What i have tried( i am new to VBA , tried the following with help of google)

with Sheets("Sheet1")
    LRow1 = .Cells(Rows.Count, 1).End(xlUp).row
    LRow3 = "A1:" & getColumnAlpha & LRow1

     For d = 2 To LRow1
    Cells(d, 4) = Cells(d, 1) & "_" & Cells(d, 3)
    Next d
    Range("A2:F" & LRow1).Sort Key1:=Range("D2:D" & LRow1), order1:=xlAscending, Header:=xlNo
    'Sheets("Sheet1").Columns(4).Copy Destination:=Sheets("Test").Columns(2)
    Dim test As String
    test = LRow1
    finishedRow = LRow1
    'finishedRow() = test.ToStringArray
    'ReDim finishedRow(LRow1) As String
    row = 1
    resultRow = 1
    index = 1

    Do While .Range("D" & row) <> ""

      If UBound(Filter(finishedRow, row)) < 0 Then
    finishedRow = row
    index = index + 1
    innerRow = 1

    Do While .Range("D" & innerRow) <> ""

        If UBound(Filter(finishedRow, innerRow)) < 0 Then

            If .Range("D" & row) = .Range("D" & innerRow) Then

                If .Range("B" & row) < .Range("B" & innerRow) Then
                'Update time in result record
                'Sheets("Sheet1").Range("B" & resultRow) = "Delete"
                 Rows(resultRow).EntireRow.Delete

                End If

                            'Add row to record array
                            finishedRow = innerRow
                            index = index + 1

                        End If

                    End If

                    'Increase inner row
                    innerRow = innerRow + 1

                Loop

                'Increase result row
                resultRow = resultRow + 1

            End If

            'Increase row
            row = row + 1
    Loop

End With

This code removes duplicates but requires the macro to be run multiple times


texts: N-queens problem in Haskell by bruteforce

texts:
I wrote a Haskell program to solve the N-queens problem by bruteforce. It works and I find it reasonably readable

But it is pretty slow:

5 seconds for one solution of 8 queens.
1 minute for one solution for 9 queens.
Crash for 10 queens. I fear that allFalseOneTrue gives memory problems as it uses permutations.

I would like to hear both improvements on readability and performance:

import Control.Monad
import Data.List

-- True indicates that there is a queen, False that there is not.
type QueenBoard = [[Bool]]

count   :: Eq a => a -> [a] -> Int
count x =  length . filter (==x)

fAnd :: (a -> Bool) -> (a -> Bool) -> (a -> Bool)
fAnd = liftM2 (&&)

rotate90 :: [[a]] -> [[a]]
rotate90 = map reverse . transpose

noQueensinSameRow :: QueenBoard -> Bool
noQueensinSameRow board = not (any (\row -> count True row > 1) board)

noQueensinSameColumn :: QueenBoard -> Bool
noQueensinSameColumn = noQueensinSameRow . rotate90

-- Attribution to http://stackoverflow.com/questions/32465776/getting-all-the-diagonals-of-a-matrix-in-haskell
diagonals :: [[a]] -> [[a]]
diagonals []       = []
diagonals ([]:xss) = xss
diagonals xss      = zipWith (++) (map ((:[]) . head) xss ++ repeat [])
                                  ([]:(diagonals (map tail xss)))

allDiagonals :: [[a]] -> [[a]]
allDiagonals xss = (diagonals xss) ++ (diagonals (rotate90 xss))

noQueensinSameDiagonal :: QueenBoard -> Bool
noQueensinSameDiagonal = noQueensinSameRow . allDiagonals

isQueenSolution :: QueenBoard -> Bool
isQueenSolution = (noQueensinSameRow `fAnd` noQueensinSameColumn `fAnd` noQueensinSameDiagonal)

allFalseOneTrue :: Int -> [[Bool]]
allFalseOneTrue length = nub $ permutations ( [True] ++ (replicate (length - 1) False) )

allProduct = sequence :: [[a]] -> [[a]]

allPossibleBoards :: Int -> [QueenBoard]
allPossibleBoards size = allProduct (replicate size (allFalseOneTrue size))

solveQueens :: Int -> [QueenBoard]
solveQueens = (filter isQueenSolution) . allPossibleBoards

main :: IO()
main = mapM_ putStrLn $ map show $ head $ solveQueens 8


texts:
I have the following code that simulates the monty hall problem (see google for more details). I used sets to do it but is there a more intuitive or efficient way to do it?

import random as r
from sets import Set
def montysim(N):
  K = 0
  for i in range(N):
    s = Set([1,2,3])
    doorstoswitch = Set([1,2,3])
    cardoor = r.randint(1,3)
    chosendoor = r.randint(1,3)
    doorstoswitch.remove(chosendoor)
    if chosendoor != cardoor:
        s.remove(chosendoor)
    s.remove(cardoor)

    montydoor = r.sample(s, 1)[0]
    doorstoswitch.remove(montydoor)
    newdoor = r.sample(doorstoswitch, 1)[0]
    if newdoor == cardoor:
        K+=1
  return float(K) / float(N)

print montysim(10000)


texts:
I have more than 20 sheets in Excel and one main sheet (all programs with 200 names). Each sheet has a column with names and 24 months (Jan 18 to Dec 18, Jan 19 to Dec 20). Each sheet names is a subset of the main sheet.

Main sheet (all programs) has 200 names and 24 months (values to be calculated based on other sheets). The other sheet has names and values for each month respective to the main sheet. I need to take each name in main sheet and search the name in all other sheets, and if present sum all same column values and insert in the main sheet.

For 1 name I need to do calculation on 34 cells (for 200 names * 34 cells = 6800 cells). It's taking almost 20 minutes with my code. Is there any other way I can do it or any modification which improves the performance?

Main Sheet has name "employee1"

Sheet1

Sheet2

Value on the main sheet should be calculated respect to months

Dim sheetCount As Integer
Dim datatoFind
Private Sub CommandButton1_Click()
    Dim mainSheet As String: mainSheet = "All Programs"
    Dim nameColumnStart As String: nameColumnStart = "A"

    Dim namesStart As Integer: namesStart = 1
    Dim namesEnd As Integer: namesEnd = 200

    Dim startColumn As Integer: startColumn = 10 'J Column'
    Dim EndColumn As Integer: EndColumn = 33 'AG Column'

    namesStart = InputBox("Please enter start value")
    namesEnd = InputBox("Please enter end value")

    Dim temp_str As String
    Dim total As Single
    On Error Resume Next
    Sheets(mainSheet).Activate
    lastRow_main = ActiveCell.SpecialCells(xlLastCell).Row
    lastCol_main = 34
    For vRow = namesStart To namesEnd
        temp_str = Sheets(mainSheet).Cells(vRow, "A").Text
        datatoFind = StrConv(temp_str, vbLowerCase)
            For vCol = startColumn To EndColumn
                total = Find_Data(vCol)
                Worksheets(mainSheet).Cells(vRow, vCol).Value = total
            Next vCol
    Next vRow
    Sheets(mainSheet).Activate
    'MsgBox ("Calculated all values")'
End Sub

Private Function Find_Data(ByVal ColumnName As Integer) As Single
    Dim counter As Integer
    Dim currentSheet As Integer
    Dim sheetCount As Integer
    Dim str As String
    Dim lastRow As Long
    Dim lastCol As Long
    Dim val As Single

    Find_Data = 0

    currentSheet = ActiveSheet.Index

    If datatoFind = "" Then Exit Function

    sheetCount = ActiveWorkbook.Sheets.Count

    For counter = 2 To sheetCount

        Sheets(counter).Activate

        lastRow = ActiveCell.SpecialCells(xlLastCell).Row
        lastCol = ActiveCell.SpecialCells(xlLastCell).Column

        For vRow = 1 To lastRow
                str = Sheets(counter).Cells(vRow, "A").Text
                If InStr(1, StrConv(str, vbLowerCase), datatoFind) Then
                        val = Sheets(counter).Cells(vRow, ColumnName).Value
                        Find_Data = Find_Data + val
                End If
        Next vRow

    Next counter

End Function


texts: Python: Use of class methods to change data

texts:
Could you please give me some feedback on the use of class methods in this Python script?
The code retrieves time entries from the Toggl API and works as expected. My question is, do the methods make sense? The methods first_api_call and make_subsequent_calls change self.data. Is this okay or should all the changes to self.data be made in retrieve_data?
from datetime import datetime

import requests

today = datetime.today().date()
since = datetime(today.year, 1, 1)

class Toggl:
    def __init__(self):
        self.data = []
        self.total_calls = None
        self.params = {
            'workspace_id': '5604761',
            'since': since,
            'until': today,
            'user_agent': 'john@doe.com',
            'page': 1,
        }

    def retrieve_data(self):
        r = self.first_api_call()
        self.total_calls = self.calculate_number_of_extra_calls_needed(r)
        self.make_subsequent_calls()

    def first_api_call(self):
        r = requests.get('https://toggl.com/reports/api/v2/details',
                         params=self.params,
                         auth=('APIKEY', 'api_token'))
        r.raise_for_status()
        r = r.json()
        self.data = r['data']
        return r

    def calculate_number_of_extra_calls_needed(self, r):
        """
        Calculate the number of pages that need to be retrieved.
        The second part is True/False to round up.
        Finally minus 1 because we got the first page already.
        """
        total_calls = r['total_count'] // 50 + (r['total_count'] % 50 > 0) - 1
        return total_calls

    def make_subsequent_calls(self):
        """Make the new API calls and store the data"""
        for i in range(self.total_calls):
            self.params['page'] = self.params['page'] + 1
            r = requests.get('https://toggl.com/reports/api/v2/details',
                             params=self.params,
                             auth=('APIKEY', 'api_token'))
            r.raise_for_status()
            r = r.json()
            for d in r['data']:
                self.data.append(d)

if __name__ == "__main__":
    toggl = Toggl()
    toggl.retrieve_data()
    print(toggl.data)