texts:
I am currently trying to learn bash scripting and I've made a script that backs up or restores my home folder. My main question is whether my code is readable or very messy. I would love to learn to write my scripts understandable to others and also optimally. This script isn't made for sharing right now. Any tips on how I can make it better in any way? (Of course, the answer is yes, but I'm looking for specifics.) This is my first real script, so please don't be harsh.

#!/bin/bash

# Find where device is mounted and print so the user can check if correct.
BACKUP_DEV_UUID=#ENTER UUID HERE#
BACKUP_DEV_NODE=$(sudo blkid | grep $BACKUP_DEV_UUID | cut -f1 -d':')
if [[ ! $BACKUP_DEV_NODE =~ /dev/* ]]; then
    echo "Error, device not connected"
    exit 0
fi
MOUNT_POINT=$(mount | grep $BACKUP_DEV_NODE | cut -f3 -d' ')
echo "Mount point is: $MOUNT_POINT"

# Determine if you want to backup, restore of quit. Then fix full path.
echo -e "Input 1 to backup, 2 to restore, anything else to quit"
read -p "Enter choice: " -n1 fc
echo -e ""
case $fc in
    1) echo "Backup chosen"
    FULL_PATH=$MOUNT_POINT/$(hostname)_backup/home/$USER
    if [[ ! -d $FULL_PATH ]]; then
        echo "Backup path doesn't exist, creating"
        mkdir -p $FULL_PATH
    fi
    ;;

    2) echo "Restore chosen"
    # Choose hostname and username folders
    echo "Select appropriate hostname folder"
    select hn in $MOUNT_POINT/*_backup;
    do
        echo "Picked hostname folder: $HOSTNAME_VAR"
        echo "Select appropriate username folder"
        select un in $HOSTNAME_VAR/home/*;
            do
                echo "Picked username folder: $USERNAME_VAR"
                FULL_PATH=$USERNAME_VAR
                break
            done
        break
    done
    ;;

    *) echo "Exiting";
    exit 0
    ;;
esac

# Print dest/source and ask user if accepted.
case $fc in
    1) echo "Doing home folder backup"
    echo "Backup to path: $FULL_PATH"
    ;;

    2) echo "Doing home folder restore"
    echo "Restore from path $FULL_PATH"
    ;;
esac
read -r -n1 -p "Continue? Press y/Y to start backup/restore"
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborting"
    exit 0
else
    echo "Continuing"
fi

# Actual backup/restore.
case $fc in
    1) rsync -aAXv ~/* $FULL_PATH --delete
    echo $(date) >> $FULL_PATH/homefolder_backup.log
    ;;

    2) rsync -aAXv $FULL_PATH ~/*
    ;;
esac
echo "Syncing"
sync
echo "Done"


texts: Java methods to add and authenticate users in MySQL

texts:
I'm going through some code and trying to figure out how to get rid of duplicates from the following two methods. Both methods execute a simple login/register query to a local MySQL DB. I couldnt figure out a good design pattern to solve my problem, especially to get rid of the duplicate try-catch.

Any advice?

public class DatabaseHandler {

    [...]

    public static boolean checkLogin(String username, String password) {
        Connection connection = createConenction();
        PreparedStatement statement = null;

        String query = "select * from users where username = ? and password = ? ";

        try {
            statement = connection.prepareStatement(query);
            statement.setString(1, username);
            statement.setString(2, password);
            ResultSet result = statement.executeQuery();
            return result.next(); //True if User exists
        } catch(SQLException e) {
            return false;
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static boolean registerUser(String username, String password) {
        Connection connection = createConenction();
        PreparedStatement statement = null;

        String query = "insert into users (username, password) values (?, ?)";

        try {
            statement = connection.prepareStatement(query);
            statement.setString(1, username);
            statement.setString(2, password);
            statement.executeUpdate();
            return true;
        } catch(SQLException e) {
            return false;
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
```


texts: Implementation of a generic thread-safe object wrapper

texts:
I'm currently trying to write useful helper classes for easier concurrent programming in C++ while at the same time also teaching myself 'modern C++'.

This is supposed to be a synchronized object class template, which essentially means that it wraps an object and it's supposed to guarantee that if the owner of the object hasn't gone out of his/her way to screw things up then the object should be thread safe.

It supports two kinds of operations. The first is the overloaded arrow operator which locks the object, performs an action and then unlocks it. The second one is the dereference operator that returns a handle that is a 'safe' reference to the object.

It's essentially supposed to be an easy way of making almost any object thread safe.

#pragma once

#ifndef SDK_SYNCHRONIZED_HPP
#define SDK_SYNCHRONIZED_HPP

#include <type_traits>
#include <mutex>

namespace sdk {

    template<typename T, typename Mutex = std::recursive_mutex>
    class synchronized {
        class object {
        public:

            object(T* obj, Mutex& lock) noexcept
                : m_obj(obj), m_lock(lock) {
            }

            inline object(object&& that) noexcept
                : m_obj(std::move(that.m_obj)), m_lock(std::move(that.m_lock)) {
            }

            inline auto operator->() noexcept {
                return m_obj;
            }

            inline auto operator->() const noexcept {
                return m_obj;
            }

        private:
            T* m_obj;
            std::unique_lock<Mutex> m_lock;
        };

    public:

        template<typename ... A,
         typename = std::enable_if_t<std::is_constructible_v<T, A ...>>>
        synchronized(A&& ... args)
            : m_mutex(), m_obj { std::forward<A>(args) ... } {
        }

        template<typename ... A,
         typename = std::enable_if_t<std::is_constructible_v<T, A ...>>>
        synchronized(Mutex&& m, A&& ... args)
            : m_mutex(m), m_obj { std::forward<A>(args) ... } {
        }

        synchronized(synchronized&& that)
            : m_mutex(std::move(that.m_mutex)), m_obj(std::move(m_obj)) {
        }

        // used for several actions

        [[nodiscard]] inline object operator*() {
            return object(&m_obj, m_mutex);
        }

        [[nodiscard]] inline const object operator*() const {
            return object(&m_obj, m_mutex);
        }

        // synchronized operations

        inline auto operator->() {
            object obj(&m_obj, m_mutex);
            return obj;
        }

        inline auto operator->() const {
            object obj(&m_obj, m_mutex);
            return obj;
        }

    private:

        Mutex m_mutex;
        T m_obj;

    };
}

#endif

And the usage is (normally) supposed to be something like:

// this is supposed to be safe

synchronized<Foo> foo(1, 2.f, true);
// alot of other stuff
auto dostuff = std::thread([&foo](){
    // more stuff here
    foo->bar(false);
    // you get the idea
});
//...
foo->bar(true);


texts: Hackerrank "Strings: Making Anagrams" Javascript Solution

texts:
This is the original problem :

  Input Format

  The first line contains a single string, a.  The second line contains a
  single string, b.

  Constraints

  1<= |a|,|b| <= 10^4

  It is guaranteed that  and  consist of lowercase English alphabetic
  letters (i.e.,  through ). Output Format

  Print a single integer denoting the number of characters you must
  delete to make the two strings anagrams of each other.

  Sample Input

  cde

  abc

  Sample Output

  4

  Explanation

  We delete the following characters from our two strings to turn them
  into anagrams of each other:

  Remove d and e from cde to get c. Remove a and b from abc to get c. We
  must delete  characters to make both strings anagrams, so we print  on
  a new line.

And this is the solution I've came up with using javascript. I've decided to use objects in order to avoid nested for loops which leads to O(M*N). I think my solution is O(M+N+O+P), however, I do believe there's a much better solution out there, and some more refactoring can be done to my code. Anyone?

There are some default I/O codes you may find in the original website

function main() {
  var a = readLine();
  var b = readLine();

  // Creating object with {"k": 5, "a": 2, "b": 1} for example
  var objA = countAlphabetFrequency(a);
  var objB = countAlphabetFrequency(b);

  var numOfDeletionsA = countNumberOfDeletions(objA,objB);
  var numOfDeletionsB = countNumberOfDeletions(objB,objA);

  console.log(numOfDeletionsA + numOfDeletionsB);
}

function countAlphabetFrequency (arrOfAlphabets){
    var resultObj = {}

    for (i = 0; i < arrOfAlphabets.length; i++) {
        if (resultObj[arrOfAlphabets[i]]) {
          resultObj[arrOfAlphabets[i]] += 1;
        } else {
          resultObj[arrOfAlphabets[i]] = 1;
        }
    }
    return resultObj;
}

function countNumberOfDeletions (mainObj, referenceObj){
    var numOfDeletions = 0;

    for (var k in mainObj) {
        if (mainObj.hasOwnProperty(k)) {
          if (mainObj[k] && referenceObj[k]) {
            // Alphabet k exists in both strings
            if (mainObj[k] > referenceObj[k]) {
              // Main string has more k than in reference string
              numOfDeletions += mainObj[k] - referenceObj[k];
              mainObj[k] = referenceObj[k];
            }
          } else {
            // Alphabet k only exists in Main string
            numOfDeletions += mainObj[k];
          }
        }
    }

    return numOfDeletions
}


texts:
I am doing this problem on HackerRank and I'm failing test cases because it's taking too long to run when n and k get over 8000. I believe the dictionary lookup should be \$O(1)\$ while lists are \$O(n)\$. Would it be faster to store the DNA string in another dictionary where the array position is the key? I'm not sure of any other optimizations I can make.

Essentially, given a string of n characters, iterate through that string k times while swapping values according to dictionary key/value pairs. So a string 'AAC' would look at 'AA'->'A', 'AC'->'C', and because of wrap-around, 'CA'->'C'. So after one iteration, 'AAC' becomes 'ACC'. Now repeat k times.

inp = input().split(' ')
n, k = inp[0], inp[1]
proteins = input()
#generated the dictionary with other python scripts since it's unchanging
#see challenge on Hackerrank for original table
#matrix['fromLetter+toLetter']='mutatedLetter'
matrix = {'AA': 'A', 'BD': 'C', 'AC': 'C', 'AB': 'B', 'AD': 'D', 'BB': 'A', 'BC': 'D', 'CC': 'A', 'CB': 'D', 'CA': 'C', 'DB': 'C', 'DC': 'B', 'CD': 'B', 'DA': 'D', 'DD': 'A', 'BA': 'B'}

for i in range(k):
    pos = 0
    mutated = ''
    while pos<n:
        #handle the protein wrap-around
        if pos == n-1:
            mutated += matrix[proteins[-1]+proteins[0]]
        else:
            mutated+= matrix[proteins[pos:pos+2]]

        pos+=1
    proteins = mutated
print(proteins)


texts:
This is my program currently to calculate sum of following series:

$$\frac{x^2}{2!} + \frac{x^4}{4!} + \frac{x^6}{6!} \dots$$

#include <iostream>

using namespace std;
int main() {
    int fac = 1;
    float x, sum = 0, p = 1;

    cout << "\nENTER x: ";
    cin >> x;
    p =  x;
    for(int i = 2; i <= 10; i++) {
        fac *= i;
        p *= x;
        cout << p << " ";
        if(i%2 == 0) {
            sum += p/fac;
        }
    }
    cout << " >> " << sum;
    return 0;
}

Is it well written? Can it be used without any optimisation for larger n values (currently only tried with small values)? How can I optimize these calculations?


texts: Generic tree data structure for flat data from a database

texts:
Could someone please review my code for performance(any other suggestions are welcome) which converts flat data list coming from database to a tree?

Interface for db entity class

public interface IDbEntityNode
{
     int Id { get; set; }
     int ParentId { get; set; }
     string Data { get; set; }
}

Example of db Entity class

public class ExceptionCategory :IDbEntityNode
{
    public  int Id { get; set; }
    public  int ParentId { get; set; }
    public string Data { get; set; }
    public ExceptionCategory(string data, int id, int parentId)
    {
        Id = id;
        ParentId = parentId;
        Data = data;
    }
}

Generic class which holds the structure of tree node

public class GenericNode<T>
{
    public T NodeInformation { get; set; }
    public GenericNode<T> Parent { get; set; }
    public List<GenericNode<T>> Children { get; set; } = new List<GenericNode<T>>();
}

Method which coverts flat list to tree

public static List<GenericNode<T>> CreateGenericTree<T>(List<T> flatDataObject,Func<T,bool> IsRootNode) where T : IDbEntityNode
{
    var lookup = new Dictionary<int, GenericNode<T>>();
    var rootNodes = new List<GenericNode<T>>();
    var noOfElements = flatDataObject.Count;
    for (int element = 0; element < noOfElements; element++)
    {
        GenericNode<T> currentNode;
        if (lookup.TryGetValue(flatDataObject[element].Id, out currentNode))
        {
            currentNode.NodeInformation = flatDataObject[element];
        }
        else
        {
            currentNode = new GenericNode<T>() { NodeInformation = flatDataObject[element] };
            lookup.Add(flatDataObject[element].Id, currentNode);
        }

        if (IsRootNode(flatDataObject[element]))
        {
            rootNodes.Add(currentNode);
        }
        else
        {
            GenericNode<T> parentNode;
            if (!lookup.TryGetValue(flatDataObject[element].ParentId, out parentNode))
            {
                parentNode = new GenericNode<T>();
                lookup.Add(flatDataObject[element].ParentId, parentNode);
            }
            parentNode.Children.Add(currentNode);
            currentNode.Parent = parentNode;
        }
    }

    return rootNodes;
}

Execution:

private static void Main(string[] args)
{
    List<IDbEntityNode> flatDataStructure = new List<IDbEntityNode>
    {
        new ExceptionCategory("System Exception",1,0),
        new ExceptionCategory("Index out of range",2,1),
        new ExceptionCategory("Null Reference",3,1),
        new ExceptionCategory("Invalid Cast",4,1),
        new ExceptionCategory("OOM",5,1),
        new ExceptionCategory("Argument Exception",6,1),
        new ExceptionCategory("Argument Out Of Range",7,6),
        new ExceptionCategory("Argument Null",8,6),
        new ExceptionCategory("External Exception",9,1),
        new ExceptionCategory("Com",10,9),
        new ExceptionCategory("SEH",11,9),
        new ExceptionCategory("Arithmatic Exception",12,1),
        new ExceptionCategory("DivideBy0",13,12),
        new ExceptionCategory("Overflow",14,12),
    };

    var tree = CreateGenericTree(flatDataStructure, IsRootNode);
}

Root node has ParentId set to 0

private static bool IsRootNode(IDbEntityNode dbEntity)
{
    bool isRootNode = false;
    if (dbEntity.ParentId == 0 )
        isRootNode = true;
    return isRootNode;
}


texts:
I want to start making some command line programs in C, this is a fork of something else I made but is more suitable to this site. My big question is there a better way to pipe commands? I think the way I did it feels improper. I especially feel the string method is a bit hacky.
#include <stdio.h>
#include <unistd.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char *argv[])
{
    char t[32767];
    unsigned int val = 0;
    if (argc == 2)
    {
        memset(t, '\0', sizeof(t));
        strcpy(t, argv[1]);
    }
    else
    {
        read(STDIN_FILENO, t, 32767);
    }
    for (int i = 0; t[i]; i++)
    {
        t[i] = tolower(t[i]);
    }
    int i;
    for (i = 0; t[i] != '\0'; i++)
    {
        switch (t[i])
        {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
        case 'l':
        case 'n':
        case 's':
        case 't':
        case 'r':
            val += 1;
            break;
        case 'd':
        case 'g':
            val += 2;
            break;
        case 'b':
        case 'c':
        case 'm':
        case 'p':
            val += 3;
            break;
        case 'f':
        case 'h':
        case 'v':
        case 'w':
        case 'y':
            val += 4;
            break;
        case 'k':
            val += 5;
            break;
        case 'j':
        case 'x':
            val += 8;
            break;
        case 'q':
        case 'z':
            val += 10;
        }
    }
    printf("%i\n", val);
    return 0;
}

I know this is similar to Scrabble word scoring, but I am less interested in the switch but the stdin and the piping.


texts:
I want to wrap NSCache in a Singleton in order to use dependency injection in my code. This has resulted, rather unfortunately, in passing the type through a function parameter, and I even need two mocks for success and failure since it is a singleton instance.
I think there might be a better way, but any comments appreciated!
ImageCache and protocol
protocol ImageCacheProtocol {
    static var shared: Self { get }
    func getCache() -> NSCache<AnyObject, UIImage>
}

final class ImageCache: ImageCacheProtocol {
    var cache: NSCache<AnyObject, UIImage> = NSCache<AnyObject, UIImage>()

    public static let shared = ImageCache()
    private init() {}

    func getCache() -> NSCache<AnyObject, UIImage> {
        return cache
    }
}

MockImageCache & MockImageCacheFailure
final class MockImageCache: ImageCacheProtocol {
    var cache: NSCache<AnyObject, UIImage> = MockNSCache(shouldReturnImage: true)

    public static let shared = MockImageCache()
    private init() {}

    func getCache() -> NSCache<AnyObject, UIImage> {
        return cache
    }
}

final class MockImageCacheFailure: ImageCacheProtocol {
    var cache: NSCache<AnyObject, UIImage> = MockNSCache(shouldReturnImage: false)

    public static let shared = MockImageCacheFailure()
    private init() {}

    func getCache() -> NSCache<AnyObject, UIImage> {
        return cache
    }
}

Instantiating my view model (snippet)
class ViewModel<U: ImageCacheProtocol> {

    private var cache: U.Type
    init<T: NetworkManagerProtocol>(networkManager: T, data: DisplayContent, imageCache: U.Type) {
        self.networkManager = AnyNetworkManager(manager: networkManager)

        cache = imageCache


texts: Functionally find the index of the minimum value in an array

texts:
I come from a C#/JavaScript/TypeScript background and am learning F# by implementing fundamental algorithms. This is finding the minimum value in an array:

let findMinimumValueIndex (array: int[]): int =
    let rec find (index: int) (minimumValueIndex: int) =
        let findNext = find (index + 1)
        match index with
        | i when i >= array.Length -> minimumValueIndex // base case
        | i when array.[i] < array.[minimumValueIndex] -> findNext i
        | _ -> findNext minimumValueIndex
    find 0 0

It works. I like the partial application of arguments in the findNext function. I like the nested rec function.

Questions

How can we make this code more readable?
How can we make this code a better match of canonical F# style?
Should we be using if... then... else instead of match when?
Should we be using more explanatory variables?

Test

[<Fact>]
let ``findMinimum returns the index of the minimum value in an array`` () =
    let array = [|4; 5; 6; 7; 3; 2; 7; 4; 6; 8; 3|]
    let result = findMinimumValueIndex array
    Assert.StrictEqual(result, 5);


texts: Creating an array with quarter hour times


texts: Creating HTML table with JSON data using pure JS

texts:
In the below function I'm fetching data from a JSON object, then creating and populating a HTML table with the contents. Yes the code is readable but I feel that it just looks too long winded for what it is. Any suggestions to how this could be simplified or made more concise?

function makeTable(data) {

    let table = document.createElement('table');
    table.id = 'itemData';

    let thead = document.createElement('thead');
    table.appendChild(thead);

    let tbody = document.createElement('tbody');
    table.appendChild(tbody);

    let header = document.createElement('tr');
    let dateHeader = document.createElement('th');
    let item1Header = document.createElement('th');
    let item2Header = document.createElement('th');
    let item3Header = document.createElement('th');
    let item4Header = document.createElement('th');
    let item5Header = document.createElement('th');
    let item6Header = document.createElement('th');
    let item7Header = document.createElement('th');

    dateHeader.appendChild(document.createTextNode('Date'));
    item1Header.appendChild(document.createTextNode('Item 1'));
    item2Header.appendChild(document.createTextNode('Item 2'));
    item3Header.appendChild(document.createTextNode('Item 3'));
    item4Header.appendChild(document.createTextNode('Item 4'));
    item5Header.appendChild(document.createTextNode('Item 5'));
    item6Header.appendChild(document.createTextNode('Item 6'));
    item7Header.appendChild(document.createTextNode('Item 7'));

    header.appendChild(dateHeader);
    header.appendChild(item1Header);
    header.appendChild(item2Header);
    header.appendChild(item3Header);
    header.appendChild(item4Header);
    header.appendChild(item5Header);
    header.appendChild(item6Header);
    header.appendChild(item7Header);

    thead.appendChild(header);

    for (let i = 0; i < Object.keys(data).length; i++) {

        let tr = document.createElement('tr');
        let dateCell = document.createElement('td');
        let item1Cell = document.createElement('td');
        let item2Cell = document.createElement('td');
        let item3Cell = document.createElement('td');
        let item4Cell = document.createElement('td');
        let item5Cell = document.createElement('td');
        let item6Cell = document.createElement('td');
        let item7Cell = document.createElement('td');

        dateCell.appendChild(document.createTextNode(Object.keys(data)[i]));
        item1Cell.appendChild(document.createTextNode(data[Object.keys(data)[i]]['item1']));
        item2Cell.appendChild(document.createTextNode(data[Object.keys(data)[i]]['item2']));
        item3Cell.appendChild(document.createTextNode(data[Object.keys(data)[i]]['item3']));
        item4Cell.appendChild(document.createTextNode(data[Object.keys(data)[i]]['item4']));
        item5Cell.appendChild(document.createTextNode(data[Object.keys(data)[i]]['item5']));
        item6Cell.appendChild(document.createTextNode(data[Object.keys(data)[i]]['item6']));
        item7Cell.appendChild(document.createTextNode(data[Object.keys(data)[i]]['item7']));

        tr.appendChild(dateCell);
        tr.appendChild(item1Cell);
        tr.appendChild(item2Cell);
        tr.appendChild(item3Cell);
        tr.appendChild(item4Cell);
        tr.appendChild(item5Cell);
        tr.appendChild(item6Cell);
        tr.appendChild(item7Cell);
        tbody.appendChild(tr);

    }

    document.body.appendChild(table);
}


texts: How to efficiently find if numbers in a given range contains either 1 or 3, but not both?

texts:
I am having a trouble speeding up my implementation. The question is, given a range of numbers from long a to long b, find how many lucky numbers are between a and b inclusive. A number is a lucky number if it contains either 1 or 3. If it contains both 1 and 3, it is not a lucky number.

Currently, I am iterating over from a to b, inclusive, using for loop, and have a while loop in each iteration where a while loop continues until current number is > 0. In the while loop, I use modulo 10 to get the last digit, check if it's 1 or 3, then set the current number to the number/10.

Is there a way to make this more efficient for range from 10000000000 to 20000000000? With my implementation, it takes around 160 seconds.

Here is my code:

public class Main {

    public static void main(String[] args) {

        long start = 10000000000L;
        long end = 20000000000L;

        int total = 0;

        double startTime = System.nanoTime();

        for (long i = start;i <= end; i++) {
            int numOf1 = 0;
            int numOf3 = 0;
            long number = i;
            while (number > 0) {
                long lastDigit = number % 10;
                if (lastDigit == 1) {
                    numOf1++;
                } else if (lastDigit == 3) {
                    numOf3++;
                }

                if (numOf1 > 0 && numOf3 > 0) {
                    break;
                }
                number /= 10;
            }

            if (numOf1 > 0 || numOf3 > 0) {
                total++;
            }
        }

        System.out.println(total);
        double endTime = System.nanoTime();

        System.out.println((endTime - startTime) / 1000000000);

    }

}


texts: Show time in format yyyy-MM-ddThh:mm:ss.SSS

texts:
My requirement is to convert a time (long) to a String with this date format:

  yyyy-MM-ddThh:mm:ss.SSS

For instance: 2017-03-07T03:52:31.298

My implementation:

private final static String DATE_FORMAT = "yyyy-MM-dd_hh:mm:ss.SSS";

private final static DateFormat DF =
        new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);

public static String formatTime(long time) {
    return DF.format(time).replace('_', 'T');
}

The underscore trick is to avoid  the Illegal pattern character T error I was getting if I had a T character in DATE_FORMAT. I am sure there is a better way to do this?
Also, I am sure more explicit names can be found for DATE_FORMAT/DF?


texts:
I'm just starting to learn programming again after a long break and decided on Python. Here's my code:

#"Code Wars: Where my anagrams at?" A program that finds all anagrams of "word" in "wordList".

import copy

def anagrams(word, wordList):
    result = [] #List to store all the anagrams.
    for i in wordList:  #Outer loop finds all anagrams of "word".
        source = copy.deepcopy(list(i))   #Creates a copy of the current word in the word list as a list.
        var = True #Boolean value that indicates whether "i" is an anagram of "word" or not.
        for j in word:  #Inner loop. It checks if "i" is an anagram of "word".
            if(j in source):    #Incrementally deletes the matching characters.
                source.remove(j)
            else:   #Early exit if a single character in "word" is missing from "i".
                var = False
                break
        if(source != []):    #If "i" is an anagram of "word", then "source" should be empty.
            var = False
        if(var):   #Add the word to the result list iff "i" is an anagram of "word".
            result.append(i)
    return(result)

What am I doing wrong (re best practices/design/efficiency)?
What could I do better?


texts:
Maybe this is fine the way it is, but it seems messy. Basically I have dynamically generated HTML that will display a list of songs in a given folder. Each song has an ID, and I want to add a button that allows you to add every song in the folder.

Right now it's creating the add all button with the array of song IDs as an argument. It just feels messy since the list can be incredibly long and is now exposed to the HTML, but maybe it's fine?

It's currently working like this:

if (songidarray.length > 0)
    backbuttonhtml += "Add Entire Folder";
window.$("#folderpagebackbutton").html(backbuttonhtml).trigger('create');

I could make the songidarray a global variable and make the button static. But that seems like a cop out for some reason, maybe I'm just asking a stupid question and that's the answer right there. Wondering if there is a way to do it without using a global variable, or if there's nothing wrong with using one.


texts:
I wrote a script that one way encrypts a user's password by generating a key, and multiplies by the ASCII value of the character and the ASCII value of the key character at (the position that the character has in the password string) and repeats this for the previous positions in the string meaning a key string with ASCII values of:

  49, 50, 51, 52, 53, 54, 55, 56, 57, 48

and a password string of

  112, 97, 115, 115, 119, 111, 114, 100, 46, 49

Would be multiplied like:

  [(112 * 49)] + [(97 * 50) + (97 * 49)] + ...

and so on.

As an example, the string password.1 encrypted with the key 1234567890 (auto generated) would return 203456.

$pass = $_GET["pass"];
$key = $_GET['key'];
$newPass = go($pass, $key);
echo $newPass;
function go($pass, $key){
    $passArray = str_split($pass);
    $keyArray = str_split($key);

    $total = 0;
    $pos = 0;
    foreach ($passArray as $char){
        $posInitial = $pos;
        while($pos !== 0){
            $total = $total + (ord($keyArray[$pos]) * ord($char));
            $pos--;
        }
        $pos = $posInitial + 1;
     }
     return $total;
}
function authorise($pass, $passEncode, $key){
    $passEncodeTest = go($pass, $key);
    if ($passEncode == $passEncodeTest){
        return true;
    } else {
        return false;
    }
}
authorise('password.2', $newPass, $key); ==> returns false
authorise('password.1', $newPass, $key); ==> returns true

(I will add a password sanitiser in later, but for now, plaintext)

My question is, what can I do to improve this code?


texts:
I've been writing a basic script to enumerate SMTP users (via a user dictionary) on poorly configured SMTP servers. In scripts like this, I usually see arguments handled as follows:

if (len(sys.argv) != 3:
    print "Usage: ..."
    sys.exit(0)

I found the if and print statement approach irritating, but without a concrete reason why in my mind. I decided to use assertions and combine argument handling with general setup. The following is the complete script.

#!/usr/bin/python

import socket
import sys
import os

SMTP_PORT = 25

#
# Helper Functions
#

def create_connection(host, port):
    smtp_server = sys.argv[1]
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((host, port))

    return(sock)

def smtp_verify(username, smtp_conn):
    smtp_conn.send('VRFY ' + username + '\r\n')
    smtp_reply = smtp_conn.recv(1024)

    return(smtp_reply)

#
# Arg checking, connection setup
#

try:
    assert len(sys.argv) == 3, \
    "Usage: smtp_enum.py <smtp_server_ip> <username_list_file>"

    users_file = sys.argv[2]
    assert os.path.isfile(users_file), "Cannot open file %s" % users_file

    smtp_server = sys.argv[1]
    smtp_conn = create_connection(smtp_server, SMTP_PORT)

    banner = smtp_conn.recv(1024)
    print banner
except Exception as e:
    print "Error: %s" % e
    exit(1)

#
# Perform SMTP enumeration
#

with open(users_file, 'r') as users:
    for user in users:
        print smtp_verify(user.strip(), smtp_conn)

smtp_conn.close()

I'm wondering if I may later regret the assertion approach if the script grows. Is this an abuse of assertions, or somehow problematic?


texts: Optimising multiple string splits and concatenations

texts:
I'm writing a program in Unity and am using a TextMeshProUGUI object (named history) to hold a list of messages to act as a terminal/console.

The problem I am having is that I am printing up to hundreds of lines a second, which can be detrimental to performance when I'm doing many string splits and then updating the text variable of the TextMeshProUGUI object, (which in turn gets rendered) every single frame.

My initial implementation looked like this:

private const int MAX_HISTORY = 64;  // the maximum number of lines to store
public TextMeshProUGUI history;      // value is set in Unity editor
private int inputs = 0;              // the size of the history object

public void Print(params string[] msgs)
{
    // add all messages to the history
    foreach (string msg in msgs)
    {
        if (msg == null)
            continue;
        inputs++;
        history.text += msg + '\n';
    }
    // and now reduce the size
    if (inputs > MAX_HISTORY)
    {
        string[] lines = history.text.Split('\n');
        history.text = "";
        for (int i = inputs - MAX_HISTORY; i < lines.Length; i++)
        {
            history.text += lines[i] + '\n';
        }
        inputs = MAX_HISTORY;
    }
}

and I have managed to reduce it to this:

public void Print(params string[] msgs)
{
    foreach (string msg in msgs)
    {
        if (msg == null)
            continue;
        inputs++;
        history.text += msg + '\n';
    }
    if (inputs > MAX_HISTORY)
    {
        history.text =
            history.text.Split(new char[] { '\n' }, inputs - MAX_HISTORY)[inputs - MAX_HISTORY - 1];
        inputs = MAX_HISTORY;
    }
}

But I am still concerned with the line in the if-statement with the large split function. I would appreciate it if somebody who has experience with C# and string manipulation could review this and tell me if my optimisation is (a) correct and (b) good.

Edit:

Changing the value of TextMeshProUGUI.text causes a layout and vertex recalculation which has poor performance so I've also added a StringBuilder to handle the concatenation and splits before setting the text value.

public void Print(params string[] msgs)
{
    StringBuilder text = new StringBuilder(history.text);
    foreach (string msg in msgs)
    {
        if (msg == null)
            continue;
        inputs++;
        text.AppendLine(msg);
    }
    while (inputs > MAX_HISTORY)
    {
        text.Remove(0, Convert.ToString(text).Split('\n').FirstOrDefault().Length + 1);
        inputs = MAX_HISTORY;
    }
    history.text = text.ToString();
}


texts:
I had an assignment some weeks ago that consisted of making a simple McCulloch-Pitts neural network. I ended up coding it in a pretty OO style (or the OO style I've been taught), and I felt that my implementation might have been a bit excessive for being a one-off assignment: could this perhaps been implemented in a simpler, less verbose way? Possibly forsaking modularity and such since it's not really a concern. I had never seen any Neural Network implementations in Java beforehand, so I didn't really know what was a reasonable approach for this kind of thing.

This was implemented in Java - you were supposed to use C or C++, but I didn't know either of them so the teacher indulged me. It models a neural network with three input neurons, one output neuron and two layers of hidden neurons. The actual input-output specification is probably not important here, so I'll just explain the main class (NeuralNetwork.java); This class holds information about all neurons in the network and mediates all message passing between neurons: the neurons will in each fire one or more of their outgoing neurons in each timestep, based on the sum of the input of the ingoing neurons in the previous timestep. All of this message passing goes through the network: all the neurons don't know about each other or the network.

So the crux of the problem is simply to coordinate neurons and whether or not they fire their synapses in each timestep, and to calculate the responses of the neurons that they fire "towards" (through the synapses).

package main;

import java.util.HashMap;
import java.util.LinkedList;

public class NeuralNetwork {

//for debugging
int timestep = 0;

HashMap<String,InputNeuron> inputNeurons;
LinkedList<Neuron> internalNeurons;
LinkedList<OutputNeuron> outputNeurons;

public NeuralNetwork
    (HashMap<String,InputNeuron> inputNeurons, LinkedList<Neuron> internalNeurons, LinkedList<OutputNeuron> outputNeurons)
{
    this.inputNeurons = inputNeurons;
    this.internalNeurons = internalNeurons;
    this.outputNeurons = outputNeurons;
    this.outputNeurons.get(0).getOutput();
}

public int getNrTimestep() {
    return timestep;
}

public int[] timestep(LinkedList<String> inputs) {
    System.out.println("Network: timestep: " + timestep);
    for (String inp : inputs) {
        assert inputNeurons.get(inp) != null : "timestep was given a String as key for an InputNeuron that didn't exist";
        inputNeurons.get(inp).fire();
    }
    for (Neuron internal : internalNeurons) {
        internal.nextTimestep();
    }
    for (Neuron outputNeuron : outputNeurons) {
        outputNeuron.nextTimestep();
    }
    int[] output = new int[outputNeurons.size()];
    int count = 0;
    for (OutputNeuron outputNeuron : outputNeurons) {
        output[count++] = outputNeuron.getOutput();
    }
    timestep++;
    resetAll();
    return output;
}

private void resetAll() {
    for (Neuron internal : internalNeurons) {
        internal.reset();
    }
    for (Neuron outputNeuron : outputNeurons) {
        outputNeuron.reset();
    }
}

}


texts:
I am making a project just for fun that employs the 3DES algorithm in Java. I was wondering if my algorithm looks secure. Is there any advice or feedback you could give me? Do I need to include an IV? Am I transferring the salt successfully?

My code can encrypt a file using the Triple DES algorithm.

// author @Alex Matheakis
public static void main(String[] args) throws Exception {

    // file to be encrypted
    Scanner inputScanner = new Scanner(System.in);
    System.out.println("Enter filename");
    String filename = inputScanner.nextLine();

    FileInputStream inputFile = new FileInputStream("C:\\Documents\\Encryptor\\" + filename + ".txt");

    // encrypted file
    FileOutputStream outputFile = new FileOutputStream("C:\\Documents\\Encryptor\\encryptedfile.des");

    // password to encrypt the file
    String passKey = "password";
    byte[] salt = new byte[8];
    Random r = new Random();
    r.nextBytes(salt);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(passKey.toCharArray());
    SecretKeyFactory secretKeyFactory = SecretKeyFactory
            .getInstance("PBEWithSHA1AndDESede");
    SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);

    PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 99999);
    Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
    outputFile.write(salt);

    byte[] input = new byte[64];
    int bytesRead;
    while ((bytesRead = inputFile.read(input)) != -1) {
        byte[] output = cipher.update(input, 0, bytesRead);
        if (output != null)
            outputFile.write(output);
    }

    byte[] output = cipher.doFinal();
    if (output != null)
        outputFile.write(output);

    inputFile.close();
    outputFile.flush();
    outputFile.close();
    inputScanner.close();
    System.out.println("File has been Encrypted.");
}


texts: Is indentation of #if & #endif directives an important readability convention?

texts:
I'm sharing C# code with a fellow programmer who is more use to writing C++. He uses #if and #endif directives (which I do not tend to use) and when they occur they have no indentation, for example

        private void dumpToDisplay()
        {
#if false
            ushort[] ScanStatus = new ushort[6];
            for (int ch = 0; ch < 6; ch++)
                ScanStatus[ch] = mySteppers.GetStatus(ch);

            return;
#endif
            string dumpString = stepDump();

            Debug.Print(dumpString);
        }

It is interesting that the code sample in the #if C# documentation adopts the same convention and has no indentation for the #if and #endif directives. Is this important? It certainly makes them stand out, but is that good?


texts:
I have a CSV like the following.
Category,Position,Name,Time,Team,avg_power,20minWKG,Male?,20minpower
A,1,Tom Smith ,00:41:58.95,7605,295,4.4,1,299.2
A,2,James Johnson,00:41:58.99,2740,281,4.5,1,283.95
A,3,Tom Lamb,00:41:59.25,1634,311,4.2,1,315
B,1,Elliot Farmer,00:45:06.23,7562,306,3.9,1,312
B,2,Matt Jones,00:45:10.10,4400,292,4.0,1,300
B,3,Patrick James,00:45:39.83,6508,299,4.1,1,311.6

I get the time of the rider in first place of category 'A'.
I then give any rider that is 15% slower than this 0 points in a new CSV.
For example if the first rider take 1 minute 40 seconds, then anyone slower than 1 minute 55 seconds will get 0 points.
def convert(seconds):  # function to convert amount of seconds to a time format
    seconds = seconds % (24 * 3600)
    hour = seconds // 3600
    seconds %= 3600
    minutes = seconds // 60
    seconds %= 60
    return "%d:%02d:%02d" % (hour, minutes, seconds)

with open("results.csv", 'rt', encoding='UTF-8', errors='ignore') as file:  # opening the full results file
    reader = csv.reader(file, skipinitialspace=True, escapechar='\\')  # skipping headers
    MaleCategoryList = []  # setting category as blank so a change is recognised
    for row in reader:
             if row[0] not in MaleCategoryList:
                    if row[0] == "A":
                        firstPlaceTime = datetime.strptime(row[3], "%H:%M:%S.%f")
                        timeInSecs = firstPlaceTime.second + firstPlaceTime.minute * 60 + firstPlaceTime.hour * 3600
                        timeDifference = timeInSecs * 1.15
                        MaxTime = datetime.strptime(convert(timeDifference), "%H:%M:%S")
# some code here which is not relevant i.e calculate points
             if cat == "A" and datetime.strptime(row[3], "%H:%M:%S.%f") > MaxTime:
                    points = int(0)
                    position_for_file = "DQ Time-Cut"
                    cat = "Time Cut"
             data = {'Position': position_for_file, 'Category': cat, 'Name': name, 'Club': club,
                        'Points': points, 'Time': time}  # dictionary of data to write to CSV

I feel that my code is very messy and inefficient. This is as there are lots of if in my loop and I believe a lot of the calculations seem unnecessary. Do you have any ideas of how I could improve my code?
I would prefer to not use Pandas if possible. This is as I have never used. However if there is a fast and easily maintainable solution to this with Pandas then I would be interested.


texts:
There is a matrix of \$m\$ rows and \$n\$ columns where each row is filled gradually. Given the first row of the matrix we can generate the elements in the subsequent rows using the formula:

$$\begin{align}
a_{i,j} =&\ a_{i-1,j} \oplus a_{i-1,j+1}\quad\forall j:0\le j\le n-2 \\
a_{i,n-1} =&\ a_{i-1,n-1} \oplus a_{i-1,0}
\end{align}$$

Each row is generated one by one, from the second row through the last row. Given the first row of the matrix, find and print the elements of the last row as a single line of space-separated integers.

For example, input as \$4 \space 2\$ (4 is the number of columns and 2 is the row which we are supposed to find):

\$6 \space 7 \space 1 \space 3\$ (1st row input)
6^7 = 1
7^1 = 6
1^3 = 2
3^6 = 5

\$1 \space 6 \space 2 \space 5\$ are the final row output. Now, how could I optimise my program if the value of \$n\$ is like pow(10,5) and \$m\$ is like pow(10,18)?

import java.util.Scanner;
class XorMatrixMain{
    public static void Xor_Array(int[] xor, int n){
        int num = xor[0];
        boolean bool = false;
        int last = 0;
        for(int j=0;j<n-1;j++){
            for(int i=0 ; i<xor.length ; i++){
                if(i<xor.length-1){
                    xor[i] = xor[i]^xor[i+1];
                }
                if(i==xor.length-1){
                    if(bool){
                        xor[i] = xor[i]^last;
                    }
                    else{
                        xor[i] = xor[i]^num;
                        bool = true;
                    }
                }
            }
            last = xor[0];
        }
        for(int i=0;i<xor.length;i++){
            System.out.print(xor[i]+" ");
        }
    }
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        int m = scan.nextInt();
        int n = scan.nextInt();
        int[] xor = new int[m];
        for(int i=0;i<m;i++){
            xor[i] = scan.nextInt();
        }
        Xor_Array(xor,n);
    }
}


texts:
How can I improve this code?

public virtual HttpResponseMessage Get(int pageNo, int pageSize)
{
    pageNo = pageNo > 0 ? pageNo - 1 : 0;
    pageSize = pageSize > 0 ? pageSize : 0;

    int total = repository.Table.Count();
    int pageCount = total > 0 ? (int)Math.Ceiling(total / (double)pageSize) : 0;

    var entity = repository.Table.OrderBy(c => c.ID).Skip(pageNo * pageSize).Take(pageSize);

    if (entity.Count() == 0 || entity == null)
    {
        var message = string.Format("{0}: No content", GenericTypeName);
        return ErrorMsg(HttpStatusCode.NotFound, message);
    }

    var response = Request.CreateResponse(HttpStatusCode.OK, entity);
    response.Headers.Add("X-Paging-PageNo", (pageNo + 1).ToString());
    response.Headers.Add("X-Paging-PageSize", pageSize.ToString());
    response.Headers.Add("X-Paging-PageCount", pageCount.ToString());
    response.Headers.Add("X-Paging-TotalRecordCount", total.ToString());

    return response;
}


texts:
Here's a rather hastily made time scheduler to suit my requirements and even for my future projects. It is working as intended but I want to improve more . I am a self taught enthusiast, and rather weak as a language lawyer.

This scheduler should be able to schedule tasks which will be executed the task at the right instance. It should arrange the time-points in chronological(//TODO boundary condition) order.

typedef std::function<void(void)> func;
typedef std::chrono::system_clock::time_point time_point;
std::map<time_point, func> schedule;

int main()
{
    schedule.insert(make_pair(std::chrono::system_clock::now() + std::chrono::seconds(4s), []() { std::cout << " Slow first \n"; }));
    schedule.insert(make_pair(std::chrono::system_clock::now() + std::chrono::seconds(3s), []() { std::cout << " Medium second \n"; }));
    thread t([]()
    {
        while (!schedule.empty())
        {
            if (chrono::system_clock::now() >= (schedule.begin())->first)
            {
                (schedule.begin())->second();
                schedule.erase(schedule.begin());
            }
            this_thread::sleep_for(chrono::milliseconds(1ms));
        }
    });
    schedule.insert(make_pair(std::chrono::system_clock::now() + std::chrono::milliseconds(500ms), []() { std::cout << " Impatience third \n"; }));
    std::cout << " main is waiting for the thread to end already \n";
    t.join();
    return 0;
}


texts:
I am new to perl and want some help in tuning this script if possible cause it takes time if I increased my array. also if I use warnings I get a lot of warnings which I'm unable to handle. I'm using perl (v5.24.0) built for darwin-thread-multi-2level.

Here is an example of what I want to achieve:
The number 886 is like 8*86 = 688, if we reverse it 886 which is the original number.
Also the same for 920781, 9*20781 = 187029, reverse 920781,
etc...

my $start_run = time();
use strict;
foreach (1..1000000000) {
   if ($_==reverse(substr($_, 0, 1) * substr($_, 1)))
      { print $_."\n" ;}
    if ($_==reverse(substr($_, 0, 2) * substr($_, 2)))
    { print $_."\n" ;}
    if ($_==reverse(substr($_, 0, 3) * substr($_, 3)))
    { print $_."\n" ;}
    if ($_==reverse(substr($_, 0, 4) * substr($_, 4)))
    { print $_."\n" ;}
    if ($_==reverse(substr($_, 0, 5) * substr($_, 5)))
    { print $_."\n" ;}
    if ($_==reverse(substr($_, 0, 6) * substr($_, 6)))
    { print $_."\n" ;}
    if ($_==reverse(substr($_, 0, 7) * substr($_, 7)))
    { print $_."\n" ;}
}
my $end_run = time();
my $run_time = $end_run - $start_run;
print "Time taken: ".$run_time." sec\n";


texts: Best way to preload images with callback on completion with pure JavaScript (ES6)

texts:
There are many related questions and answers but mostly with JQuery and/or from many years ago.

I prepared a version myself, and my question is whether this is currently (2020, hence ECMAScript 6 or similar) an optimal way to preload images in pure JavaScript. It appears to work (note the tests), although not all edge-cases are tested.

let preload_imgs = function(src_list, callback) {
    let loaded = 0;
    src_list.forEach((src) => {
        img = new Image();
        img.onload = () => {
            if (++loaded == src_list.length && callback) {
                callback();
            }
        };
        img.onerror = (err) => {
            console.log(err);
        };
        img.src = src;
    });
};

Here is an example usage:

let preload_imgs = function(src_list, callback) {
  let loaded = 0;
  src_list.forEach((src) => {
    img = new Image();
    img.onload = () => {
      if (++loaded == src_list.length && callback) {
        callback();
      }
    };
    img.onerror = (err) => {
      console.log(err);
    };
    img.src = src;
  });
};

let urls = ['https://i.picsum.photos/id/1000/5626/3635.jpg',
  'https://i.picsum.photos/id/10/2500/1667.jpg',
  'https://homepages.cae.wisc.edu/~ece533/images/cat.png',
  'https://homepages.cae.wisc.edu/~ece533/images/airplane.png'
];

let starttime = Date.now();
preload_imgs(urls, () => {
  console.log("All images preloaded in", Date.now() - starttime, 'ms.');
});


texts: Rational Approximation for e with Matlab

texts:
I've written a program that calculates the best rational approximation for e with a 1, 2, 3, 4, 5, and 6 digit denominator respectively (on Matlab). For a 5-digit denominator it takes about a minute. For a 6-digit denominator it takes 2 hours. I've tried to improve the code, but I am a beginner. Suggestions are kindly appreciated.

tic
clear
p=1;
q=1;
e=exp(1);
digits=1;
trial=1;
while numel(num2str(q))<=6
    while numel(num2str(q))==digits
        p=p+1;
        if p/q>e
            q=q+1;
        end
        A(trial)=p/q;
        B(trial,1:2)=[p,q];
        trial=trial+1;
    end
    for i=1:trial-1
        error(i)=abs(A(i)-e);
    end
    [b,r]=min(error);
    p_q(digits,1:2)=B(r,1:2);
    digits=digits+1;
end
p_q
toc

This is the output:

p_q =
          19           7
         106          39
        1264         465
       25946        9545
      271801       99990
     1084483      398959

Elapsed time is 7232.153581 seconds.

Edit: Thanks to all who answered. Dennis and Jonas were right. It was the strings and growing matrices that slowed everything down. Besides I got two wrong values for p and q. The new code is this:

tic
p_best=1;
q_best=1;
e=exp(1);
for i=1:6
    for q=10^(i-1):10^i-1
        p=round(q*e);
        if abs(p/q-e)<abs(p_best/q_best-e)
            p_best=p;
            q_best=q;
        end
    end
    disp([p_best,q_best])
end
toc

The output is:

      19           7
     193          71
    1457         536
   25946        9545
  271801       99990
 1084483      398959

Elapsed time is 0.054986 seconds.

It's faster and actually correct. I assumed I knew e like Dennis said. To Joni and hardmath: I can't use continued fractions because the teacher wanted us to use brute force, but thanks.


texts: Speeding up storage of about 220000 values in Core Data

texts:
I use this code on the app's first run to save about 220000 values into core data. The file Navaids.txt has about 200000 and Waypoints.txt has about 20000 lines, where I get data from each line and put it in an entity in core data.

I am still kind of new to CD but would like to see how I can improve this code on app's first launch to make it as fast as possible. Right now it takes about 10 seconds to run on an iPad but would like to see how I can improve.

Let me know if I should provide samples of my .txt files or if you need to see any of my delegate class.

if (self.firstRun == TRUE) {
        NSString* navaidPath = [[NSBundle mainBundle] pathForResource:@"Navaids" ofType:@"txt"];
        NSString* navContent = [NSString stringWithContentsOfFile:navaidPath encoding:NSUTF8StringEncoding error:NULL];
        NSArray *navContentLines = [navContent componentsSeparatedByString:@"\r\n"];

        NSString* wayptPath = [[NSBundle mainBundle] pathForResource:@"Waypoints" ofType:@"txt"];
        NSString* wayptContent = [NSString stringWithContentsOfFile:wayptPath encoding:NSUTF8StringEncoding     error:NULL];
        NSArray *wayptContentLines = [wayptContent componentsSeparatedByString:@"\r\n"];

        @autoreleasepool {
        for (int i = 0; i < [wayptContentLines count]; i++) {
            @autoreleasepool {

            NSArray *brokenFix = [[wayptContentLines objectAtIndex:i] componentsSeparatedByString:@"|"];

                newContact = [NSEntityDescription
                              insertNewObjectForEntityForName:@"Waypoints"
                              inManagedObjectContext:context];

                [newContact setValue: [brokenFix objectAtIndex:0] forKey:@"name"];
                [newContact setValue: [brokenFix objectAtIndex:1] forKey:@"latitude"];
                [newContact setValue: [brokenFix objectAtIndex:2] forKey:@"longitude"];

            }
        }
        }

        @autoreleasepool {
            for (int i = 0; i < [navContentLines count]; i++) {
                @autoreleasepool {

                    NSArray *brokenNav = [[navContentLines objectAtIndex:i] componentsSeparatedByString:@"|"];

                    newContact = [NSEntityDescription
                                  insertNewObjectForEntityForName:@"Navaids"
                                  inManagedObjectContext:context];

                    [newContact setValue: [brokenNav objectAtIndex:0] forKey:@"icao"];
                    [newContact setValue: [brokenNav objectAtIndex:1] forKey:@"name"];
                    [newContact setValue: [brokenNav objectAtIndex:6] forKey:@"latitude"];
                    [newContact setValue: [brokenNav objectAtIndex:7] forKey:@"longitude"];
                 }
            }
        }

         NSError *error;
        [context save:&error];


texts:
Today I tried to learn how to make a simple garbage collector for a future project, it didn't need to be fast nor complex nor optimal, it just needed to work. After lots of searching and reading, I was able to make something work.

So, how can I improve it from here? At some point I guess I'll have to ditch the std::array (the small size is just for testing purposes). Do I actually need to use new and delete, or can I just keep using STL containers?

For what I've read, I have a couple options: mark and compact, copying garbage collection, generational garbage collector. Which of them would be the more natural evolution from what I've done?

#include <array>
#include <iostream>
#include <string>

using std::cout;
using std::endl;

template <typename T>
struct Handle {
    bool marked {};
    T value {};
    Handle * next {};
};

template <typename T>
class Heap {
    std::array<Handle<T>, 10> heap;

    Handle<T> * root {};
    Handle<T> * free_list {};

    void push(Handle<T> * handle) {
        handle->next = free_list;
        free_list = handle;
    }

    void reset() {
        for (size_t i = 0; i < heap.size(); ++i) {
            heap[i].marked = false;
        }
    }

    void mark(Handle<T> * handle) {
        if (handle && !handle->marked) {
            handle->marked = true;
            mark(handle->next);
        }
    }

    void sweep() {
        free_list = nullptr;
        for (size_t i = 0; i < heap.size(); ++i) {
            if (!heap[i].marked) {
                heap[i].value = {};
                push(&heap[i]);
            }
        }
    }

public:
    Heap() {
        for (size_t i = 0; i < heap.size(); ++i) {
            push(&heap[i]);
        }
    }

    template <typename U>
    Handle<T> * allocate(U && u) {
        if (!free_list) {
            reset();
            mark(root);
            sweep();
            if (!free_list) {
                throw std::bad_alloc();
            }
        }
        Handle<T> * handle = free_list;
        free_list = free_list->next;
        handle->value = std::forward<T>(u);
        handle->next = nullptr;
        return handle;
    }

    Handle<T> * keep_alive(Handle<T> * handle) {
        handle->next = root;
        root = handle;
        return handle;
    }

    void signal() {
        root = nullptr;
    }
};

int main() {

    Heap<std::string> heap;

    auto a = heap.allocate("A");
    auto b = heap.keep_alive(a);

    a = heap.allocate("B");
    auto c = heap.keep_alive(a);

    a = heap.allocate("C");
    a = heap.allocate("D");
    a = heap.allocate("E");

    cout << a->value << endl;
    cout << b->value << endl;
    cout << c->value << endl;

    return 0;
}


texts: Like system with MySQL on multiple types of pages

texts:
I want to have a like system on my website on multiple pages like "news", "comments", "forum posts" etc. So I was wondering what was the best way to do it between:

having like tables for each of my "modules" (news, comments...)
having one table like :

table: likes
id (int) | page_id (varchar) | user_id (int)

which would have those datas:

5 | news_5576    | 676
6 | comment_6564 | 676
7 | forum_656    | 787

And I would get the number of likes of a module with his id and type:

$type = 'comment';
$id = 6564;
$query = "SELECT COUNT(*) FROM likes WHERE page_id = '$type_$id'";

What do you think is the best idea?


texts:
I'm doing a Ruby exercise to create new arrays with a given filter.

  Copy the values less than 4 in the array stored in the source variable
  into the array in the destination variable.

The editorial solution code is:

def array_copy(source)
  destination = []
  for number in source
    # Add number to destination if number
    # is less than 4
    destination << number if number < 4
  end
  return destination
end

But, as a beginner, I came up with this solution:

def array_copy(source)
  return source.select {|i| i < 4}
end

Is there any problems with my solution?


texts: Removing characters from end of string from character to character

texts:
I have a program that returns the following:

PS4      Modern Warfare (2019)
Xbox One Modern Warfare (2019)
PS4      Grand Theft Auto V (5)
Xbox One Grand Theft Auto V (5)

I want to remove the parentheses from the end of he strings so they would look like the following:

PS4      Modern Warfare
Xbox One Modern Warfare
PS4      Grand Theft Auto V
Xbox One Grand Theft Auto V

Currently, the code I have does it however I don't believe it is the best way to go about it as it seems to0 big for what it does.

foreach(var i in methodResponse.Response.Data.Results.Where(x => x.CategoryFriendlyName == platform))
{
    if (i.BoxName.EndsWith(")"))
    {
        var arr = i.BoxName.ToArray();
        bool exit = false;

        while(exit != true)
        {
            for (int j = arr.Length - 1; j != 0; j--)
            {
                if (!exit)
                {
                    if (arr[j] != '(')
                    {
                        i.BoxName = i.BoxName.Remove(j, 1);
                    }
                    else if (arr[j] == '(')
                    {
                        i.BoxName = i.BoxName.Remove(j, 1);
                        exit = true;
                    }
                }
            }
        }

        i.BoxName = i.BoxName.TrimEnd();
    }

I want to be able to understand an easier way to solve this issue. I know I could use substring however as you can see, the length of the item i want to remove is not always the same.

NOTE: If there are two sets of brackets in the name, I simply want to remove the last set, no other.


texts: Apache spark compaction script to handle small files in hdfs

texts:
I have some use cases where I have small parquet files in Hadoop, say, 10-100 MB. I would to compact them so as to have files at least say 100 MB or 200 MB.

The logic of my code is to:
* find a partition to compact then get the data from that partition and load it into a dataframe
* save that dataframe into a temporary location with a small coalesce number
* load the data into the location of the hive table

val tblName = args(0)
val explHdfs = args(1)
val tmpHdfs = args(2)
val numCoalesce = args(3).toInt
val partitionCompact = args(4).toInt
val removeDuplicates = args(5).toBoolean
println(s"tbl $tblName")
println(s"expl hdfs $explHdfs")
println(s"temp hdfs $tmpHdfs")
println(s"num coalesce $numCoalesce")
var sparkConf = new SparkConf().setAppName("Spark Compaction Load in Path") //.setMaster("local[2]")
sparkConf.set("spark.hadoop.parquet.enable.summary-metadata", "false")
var sc = new SparkContext(sparkConf)
sc.setLogLevel("ERROR")
var hiveContext = new HiveContext(sc)
hiveContext.setConf("hive.exec.dynamic.partition", "true")

hiveContext.setConf("hive.exec.dynamic.partition.mode", "nonstrict")

//set compression to gzip

hiveContext.setConf("parquet.compression", "GZIP")
val partitionsDf = hiveContext.sql(s"show partitions $tblName").toDF()
//think how to handle if more than one partitioned column
partitionsDf.show(false)
//collect the df I dont we need the year by itself
val countPartitions = partitionsDf.count().toInt
println(s"count the number of partitions $countPartitions")
val partitionsArray = partitionsDf.collect()
for (i <- 0 until countPartitions) {

  println(s"printing min partition next line  partition away $i")
  //2d array
  println(partitionsArray(i)(0))

  //minPartition(i).foreach(println)
}
//get the partition
val partitiitionCompact = partitionsArray(partitionCompact)(0).toString
val colPartitioned = partitiitionCompact.split("=")(1)

val explPartition = explHdfs + partitiitionCompact
println(s"expl partittion $explPartition")
val dfFiltered = if (removeDuplicates) hiveContext.sql(s"select * from $tblName where $partitiitionCompact").toDF().distinct()
else hiveContext.sql(s"select * from $tblName where $partitiitionCompact").toDF()
// now we need the column and not the partition
//partitionsDf.coalesce(numCoalesce).write.mode("overwrite").partitionBy(colPartitioned).parquet(tmpHdfs)
println("saved to temp location now loading data in path")
hiveContext.sql(s"load data inpath '$tmpHdfs/$partitionCompact' overwrite into table $tblName partition ($colPartitioned)")
println("finished loading data doing an msck repair table")
hiveContext.sql(s"msck repair table $tblName")

I would like some feedback and am specifically looking for ways to improve the technique or performance of a compactor.


texts:
Below is a Ruby implementation of a random statistical event, based on a hash with the actual observed counts of outcomes.

I'd be interested in feedback in particular on what techniques I might use to avoid a loop-based accumulator in the RandomEvent#predict! method. I'm also very curious as well about any other suggestions on refactoring, patterns and performance that might be applicable here.

The statistics material itself might be somewhat beyond the scope of a review but I'd appreciate any thoughts on appropriate naming and more effective (deterministic) ways to test this.

Spec

include Statistics
describe RandomEvent do
  context 'when an event has only one outcome' do
    it 'always happens' do
      expect(RandomEvent.from_hash(always: 1).predict!).to eq(:always)
    end
  end

  context 'when the event has multiple outcomes' do
    let(:trials) { 10_000 }

    subject(:event) do
      RandomEvent.from_hash(heads: 51, tails: 49)
    end

    it 'should distribute them' do
      coinflips = trials.times.map { event.predict! }

      heads_variance = (coinflips.count(:heads) - trials/2).abs
      tails_variance = (coinflips.count(:tails) - trials/2).abs

      expected_variance = trials/10

      expect(heads_variance).to be < expected_variance
      expect(tails_variance).to be < expected_variance
    end
  end
end

Implementation

class RandomEvent
  def initialize
    @outcome_counts = {}
  end

  def add_outcome(outcome, count:)
    @outcome_counts[outcome] = count
  end

  def normalized_outcome_probabilities
    total_outcome_counts = @outcome_counts.values.reduce(&:+)
    @outcome_counts.inject({}) do |hash,(outcome,count)|
      hash[outcome] = count / total_outcome_counts.to_f
      hash
    end
  end

  def predict!
    acc = 0.0
    roll = rand
    selected_outcome = nil

    normalized_outcome_probabilities.each do |outcome, probability|
      acc += probability
      if acc > roll
        selected_outcome = outcome
        break
      end
    end

    selected_outcome
  end

  def self.from_hash(outcome_counts_hash)
    event = new
    outcome_counts_hash.each do |outcome, count|
      event.add_outcome(outcome, count: count)
    end
    event
  end
end


texts:
I decided to improve my OOP design knowledge and learn python at the same time so I started to write a simple program which will be a fight "simulator".

For now, there are only 2 character types : Orc and Human.
The CharacterFactory class is created so that I'll be able to handle Orc and Human classes in a more abstract way or so.

GameState is meant to track the state of the game. Instances will be immediately registered to the GameState as soon as they created. And for example, if a character dies, I want to remove it from the list as well. (self.characters).

    #abtract factory or something
class CharacterFactory:
    def __init__(self, character=None, game_state=None):
        self.character = character
        game_state.register_character(self)

    def inspect(self):
        print(self.character.name)
        print(self.character.attack_dmg)
        print(self.character.health)
        print("\n")

    def attack(self, target):
        target.character.health = target.character.health - self.character.attack_dmg

#Observable or so
class GameState:
    def __init__(self):
        self.characters = []

    def register_character(self, character):
        self.characters.append(character)

    def show_characters(self):
        list(map(lambda x: x.inspect(), self.characters))

class Orc:
    def __init__(self,name):
        self.name = name
        self.attack_dmg = 50
        self.health = 100

class Human:
    def __init__(self,name):
        self.name = name
        self.attack_dmg = 45
        self.health = 105

def Main():
    game_state = GameState()

    orc = CharacterFactory(Orc("Karcsi"),game_state)
    #orc.inspect()
    #orc.attack()

    human = CharacterFactory(Human("Nojbejtoo"),game_state)
    #human.inspect()
    #human.attack()

    print("Game state:\n")

    game_state.show_characters()

    orc.attack(human)

    game_state.show_characters()

Main()

My question is:

Is this a good design? Or maybe a complete pain in the ... to work with? Is there something that I could improve?

Of course this code is really far from being finished, but I try to find the best approach possible to design things like this so that i can deepen my knowledge in design patterns and stuff like that.


texts:
The script should be a single python file that takes an excel file (or csv).  Each row represents one switch.  For each switch, there will be one or more interfaces.  The objective is to output a script of commands to execute to configure each switch, as specified.

For example, Row 1 is below:

switch1    Eth1    trunk    10,20,30    Eth2    Access    10    Y

The script should see that there are two interfaces.  For each trunk interface, the script should output the command “swithport mode trunk”, then “switchport trunk allow vlan …” with the list of allowed VLANs.  For each access interface, it’s the same, but with the word “access” instead of “trunk”.

The sample output for the above row is as below;

switch1

hostname switch1
!
interface Eth1
 switchport mode trunk
 switchport trunk allow vlan 10,20,30
!
interface Eth2
 switchport mode access
 switchport access vlan 10

Each switch’s output should be written as a separate column in a new csv or excel file.

My submitted code as below, please review and guide me for improvements;

#!/usr/bin/python
import csv
import sys
import re
import argparse

def parseCSV(path):
    '''
    Parses a CSV file and return the rows as a list
    '''
    rows = []
    try:
        f = path
    except IOError:
        print "Cannot open specified file: %s" % path
    else:
        reader = csv.reader(f)
        for row in reader:
            rows.append(row)
        f.close()
    return rows

def outputCSV(destpath, rows):
    '''
    Process the input rows and provide switch command output.
    Output then processed to destination CSV file.
    '''
    try:
        f = destpath
    except IOError:
        print "Cannot open specified file: %s" % destpath
    else:
        writer = csv.writer(f)
    for i in range(len(rows)):
        new_list = []
        final_string = ''
        if re.match(r'^switch\d$', rows[i][0]):
            new_list.append(rows[i][0])
            new_list.append('')
            new_list.append('hostname '+rows[i][0])
            new_list.append('!')
            if rows[i][1] is not None:
                new_list.append('interface '+rows[i][1].lower())
                new_list.append(' switchport mode '+rows[i][2])
                new_list.append(' switchport '+rows[i][2]+' allow vlan '+rows[i][3])
            new_list.append('!')
            if rows[i][4] is not None:
                new_list.append('interface '+rows[i][4].lower())
                new_list.append(' switchport mode '+rows[i][5].lower())
                new_list.append(' switchport '+rows[i][5].lower()+' vlan '+rows[i][6])
            final_string = '\n'.join(new_list)
            writer.writerow([final_string])
    f.close()

def main(args):
    '''
    Parses the command line arguments
    Arguments are:
        arg1: Input CSV file to process
        arg2: Output CSV file

    Sample program execution: python myfile.py arg1 arg2
    '''
    parser = argparse.ArgumentParser(description="Reads CSV input and provide switch commands in CSV output file")
    parser.add_argument('path', help="CSV file to process", type=argparse.FileType('rt'))
    parser.add_argument('destpath', help="Output CSV file", type=argparse.FileType('at'))
    try:
        args = parser.parse_args()
    except IOError, msg:
        parser.error(str(msg))
        return
    rows = parseCSV(args.path)
    outputCSV(args.destpath, rows)

if __name__ == '__main__':
    args = sys.argv[1:]
    main(args)


texts: Handling Many Unexpected States with except

texts:
I am creating a server with Flask and it has quite a few routes. Most routes require a specific state, such as "logged in" or "process started". All of my functions and methods in packages will throw certain type of exceptions when the specific state is not matched. At the end my code ends up like this:

@app.route("/sayHello")
def sayHello():
    try:
        name = get_session_data("user", "name")

        # Some other stuff that throw meaningful exceptions

        return someTemplate

    except NotLoggedIn:
        return flask.redirect(flask.url_for("login"))

    except UserNotReadyToSayHello:
        return "You are not ready to say hello!", status.HTTP_400_BAD_REQUEST

    except UserHelloMessageNotDefined:
        return "You did not set up a greeting message!", status.HTTP_400_BAD_REQUEST

    except ConnectionToDatabaseFailed:
        return "Cannot access database", status.HTTP_500_INTERNAL_SERVER_ERROR

    except UnexpectedError:
        return "Something happened", status.HTTP_500_INTERNAL_SERVER_ERROR

Of course this is just an example I made up to demonstrate the problem, however it is more or less equivalent to the actual code.

This made programming the routes much easier than checking everything with if statements everywhere, however I ended up with a lot of except cases to the point where PyLint is telling me

  Too many return statements (9/6)

How should I handle this situation? A lot of routes actually share a very similar sets of except cases.


texts:
I will build a system in C# and I want to use the three layers architecture is next:

Entity Layer

namespace EntitiesLayer
{
    public class ECategoria
    {
        private int _idcategoria;
        private string categoria;
        private string descripcion;
    public int Idcategoria
    {
        get { return _idcategoria; }
        set { _idcategoria = value; }
    }

    public string Categoria
    {
        get { return categoria; }
        set { categoria = value; }
    }

    public string Descripcion
    {
        get { return descripcion; }
        set { descripcion = value; }
    }

Data Access Layer

public class DCategoria
{
    public string Act_Categoria(ECategoria categoria)
    {
        string rpta = "";
        DataSet ds = new DataSet();

        try
        {
        string query = "SP_ACTCATEGORIA";
        Dictionary<string, object> parameters = new Dictionary<string, object>();
        parameters.Add("@idcategoria", categoria.Idcategoria);
        parameters.Add("@categoria", categoria.Categoria);
        parameters.Add("@descripcion", categoria.Descripcion);
        ds = dbconnection.execute_query(query, parameters);
        if (ds == null)
        {
            rpta = "Error Insertando";
        }
        else
        {
            rpta = "REGISTRO REGISTRADO/ACTUALIZADO EXITOSAMENTE";
        }
    }
    catch (Exception ex)
    {
        rpta = ex.Message;
    }

    return rpta;
}

Business Logic Layer

public class BCategoria
{
    private DCategoria data_categoria = new DCategoria();

public string Act_categoria(ECategoria categoria)
{
    return data_categoria.Act_Categoria(categoria);
}

public DataSet Select_categoria()
{
    return data_categoria.Select_Categoria();
}

public string Delete_categoria(ECategoria categoria)
{
    return data_categoria.Delete_Categoria(categoria);
}

public DataSet FilterbyID(ECategoria categoria)
{
    return data_categoria.FilterbyID(categoria);
}

public DataSet FilterByName(ECategoria categoria)
{
    return data_categoria.FilterByName(categoria);
}

Presentation Layer

public ECategoria get_data()
{
    ECategoria categoria = new ECategoria();
    categoria.Idcategoria = Convert.ToInt32(this.txtcodigo.Text.Trim());
    categoria.Categoria = this.txtcategoria.Text.Trim();
    categoria.Descripcion = this.txtcategoria.Text.Trim();
    return categoria;
}

private void btnNuevo_Click(object sender, EventArgs e)
{
    categoria = get_data();
    rpta = bus_categoria.Act_categoria(categoria);
}

Is this a good implementation of the three layers architecture?


texts: Search for a symmetrical inner portion of a list

texts:
What the code does: Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list. Example:

symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)

Note: Symmetry occurs if the value of the ith element from the start of the list is equal to the value of the ith element from the end of the list.

def symmetrical_sum(a):
'''Takes a Python list of integers as input and searches for a 'symmetrical' inner-portion of the list

Example: symmetrical_sum([10,8,7,5,9,8,15]) == ([8, 7, 5, 9, 8], 37)

Symmetry occurs if the value of the ith element at the start of the list is equal to the value of the
ith element at the end of the list'''

#extract duplicate value
dupe = [x for n, x in enumerate(a) if x in a[:n]]

#if no duplicate values found, do the following:
if dupe == []:
    middle = float(len(a))/2
    if middle % 2 != 0:
        sym = a[int(middle - .5):int(middle + .5)]
        ans = a[int(middle - .5)]
        tuple1 = (sym,ans)
    elif middle % 2 == 0:
        sym = a[int(middle - 1):int(middle + 1)]
        ans = sum(a[int(middle - 1):int(middle + 1)])//2
        tuple1 = (sym,ans)
    return tuple1
else:
    d_to_i = int("".join(map(str, dupe))) #convert duplicate value to integer
    p1 = a.index(d_to_i) #get index of first duplicate
    p2 = a.index(d_to_i, p1+1) #get index of second duplicate
    sym = a[p1:p2+1] #[symmetrical-portion]
    ans = sum(sym) #sum-of-symmetrical-portion
    tuple2 = (sym, ans)

return tuple2

Looking at my code I realize that it could probably be more efficient than this. It works, but I'm sure it could be better. I just don't possess the skills to 'compress it'. I've submitted my code already so this is just for my own personal development.


texts: A heart.lisp I wrote with my 6 year old daughter

texts:
Is it possible to improve this program somehow? It will probably be more convenient to suggest edits as forks of this Gist.

(defpackage heart
  (:use :cl))
(in-package :heart)

;; Usage:
;; sbcl -l heart.lisp -e '(uiop:quit 0)'
;;

(defun print-line (&rest args)
  (loop
     :for type :in args :by #'cddr
     :for num :in (cdr args) :by #'cddr
     :do (loop :repeat num
            :do (princ (ecase type
                         (:s " ")
                         (:h "❤")))))
  (format t "~%"))

(defun print-lines (data)
  ;; ensure there is a new line
  (format t "~&")

  (dolist (line data)
    (apply #'print-line line)))

(defvar *data*
  '((:s 8 :h 8 :s 8 :h 8)
    (:s 3 :h 15 :s 4 :h 15)
    (:s 1 :h 18 :s 2 :h 18)
    (:s 0 :h 40)
    (:s 0 :h 40)
    (:s 0 :h 40)
    (:s 1 :h 38)
    (:s 2 :h 36)
    (:s 4 :h 32)
    (:s 6 :h 28)
    (:s 8 :h 24)
    (:s 11 :h 18)
    (:s 13 :h 14)
    (:s 15 :h 10)
    (:s 17 :h 6)
    (:s 19 :h 2)))

(print-lines *data*)


texts: Knuth Morris Pratt substring search algorithm

texts:
Below you can find a Kotlin based implementation of the Knuth-Morris-Pratt substring search algorithm.
class KnutMorrisPrat(R: Int, private val pat: String) {

    private val m = pat.length

    private val dfa: Array<Array<Int>> = Array(R) { Array(m) { 0 } }

    constructor(pat: CharArray) : this(256, String(pat))

    constructor(pat: String) : this(256, pat)

    init {
        dfa[pat[0].toInt()][0] = 1
        var x = 0
        var j = 1
        while(j < m) {
            (0 until R).forEach { c -> dfa[c][j] = dfa[c][x] } // Copy mismatch cases.
            dfa[pat[j].toInt()][j] = j + 1                     // Set match case.
            x = dfa[pat[j].toInt()][x]                         // Update restart state.
            j++                                                // Move to next character in pattern
        }
    }

    fun search(txt: String): Int {
        return doSearch(txt, 0)
    }

    fun search(txt: String, start: Int): Int {
        return doSearch(txt, start)
    }

    private fun doSearch(txt: String, start: Int): Int {
        val m = pat.length
        val n = txt.length
        var i = start
        var j = 0
        while(i < n && j < m) {
            j = dfa[txt[i++].toInt()][j]
        }
        return if (j == m) i - m else -1
    }
}

Here is a unit test, using JUnit 4:
import org.hamcrest.core.Is
import org.junit.Assert.assertThat
import org.junit.Test

class KnutMorrisPratTest {

    @Test
    fun search() {
        val text = "All we're supposed to know about is our patter pattern. And we're supposed to light the light if we find our pattern and that's it"
        assertThat(KnutMorrisPrat("we").search(text), Is.`is`(text.indexOf("we")))
        assertThat(KnutMorrisPrat("All").search(text), Is.`is`(text.indexOf("All")))
        assertThat(KnutMorrisPrat("know").search(text), Is.`is`(text.indexOf("know")))
        assertThat(KnutMorrisPrat("pattern").search(text), Is.`is`(text.indexOf("pattern")))
        assertThat(KnutMorrisPrat("supposed").search(text), Is.`is`(text.indexOf("supposed")))
        assertThat(KnutMorrisPrat("patter").search(text), Is.`is`(text.indexOf("patter")))
        assertThat(KnutMorrisPrat("that's").search(text), Is.`is`(text.indexOf("that's")))
        assertThat(KnutMorrisPrat("pattern").search(text, 57), Is.`is`(text.indexOf("pattern", 57)))
        assertThat(KnutMorrisPrat(127,"pattern").search(text, 57), Is.`is`(text.indexOf("pattern", 57)))
        assertThat(KnutMorrisPrat("pattern".toCharArray()).search(text, 57), Is.`is`(text.indexOf("pattern", 57)))
        assertThat(KnutMorrisPrat("asddada".toCharArray()).search(text), Is.`is`(text.indexOf("asddada")))
    }

}

The search should give the same results as java.lang.String.indexOf.


texts:
I created a class of a directed graph and a method for finding if graph has an Euler cycle and updating a vector accordingly.Is there any optimization or a nicer way to do this.

class Graph {
private:
    int V;          // No. of vertices
    list<int> *adj; // Pointer to array of lists
    bool cycleHelper(int v, bool visited[], bool *reStack, vector<int> &path) const; // Helper for cycle()

public:
    Graph(int V);                   // Constructor
    ~Graph();                       // De-constructor Who wants to live forever when love must Die
    void addEdge(int u, int w);     // function to add an edge to graph

    bool cycle(vector<int> &path) const; // Returns True if Graph has a circle, and sets path to its route
};

Graph::Graph(int V) {
    this->V = V;         // Set Graph nodes
    adj = new list<int>[V]; // V-dimention array of lists
}
Graph::~Graph() {
    delete[] adj;
}

void Graph::addEdge(int u, int w) {
    adj[u].push_back(w); // Add u to v's list.
}

bool Graph::cycleHelper(int v, bool visited[], bool *recStack, vector<int> &path) const {
    if (visited[v] == false) {
        // Mark the current node as visited and not in recursion stack
        visited[v] = true;
        recStack[v] = true;

        for (auto i : adj[v]) {
          if ( i == path[0]) return true;
          else if (!visited[i] && cycleHelper(i, visited, recStack, path)){
              path.push_back(i);
              return true;
            }
          else if (recStack[i]){
              path.push_back(i);
              return true;
            }
        }
    }
    recStack[v] = false; // remove from recursion stack, I don't need u any more
    return false;
}

bool Graph::cycle(vector<int> &path) const {
    // Mark all the vertices as not visited and not part of recursion stack
    bool *visited = new bool[V];
    bool *recStack = new bool[V];
    for (int i = 0; i < V; i++) {
        visited[i] = false;
        recStack[i] = false;
    }
    // Call the  helper function

    for (int i = 0; i < V; i++){
        path.push_back(i);
        if (cycleHelper(i, visited, recStack, path)) {
            //path.push_back(i);
            reverse(path.begin(),path.end());
            //if (path.begin()[0] == path.end()[-1]) path.pop_back();
            return true;
        }
        path.clear();
    }
    path.clear();
    return false;
}


texts: Remove extra spaces from a string without using Regex or any internal library methods

texts:
The objective is to remove extra spaces from the below string:

  "   Today   it  is     going    to  rain.     "

so it looks like below

  "Today it is going to rain."

Please determine if the code will perform well and if there is a better solution (NO REGEX or LAMBDA).

static string CompactStringPerfect()
{
    string longString = "   Today   it  is     going    to  rain.     ";

    StringBuilder sb = new StringBuilder();
    char[] longChars = longString.ToCharArray();

    int spaceCount = 0;

    //Using standard method with no library help
    for (int i = 0; i < longChars.Length; i++)
    {
        //If space then keep a count and move on until nonspace char is found
        if (longChars[i] == 32)
        {
            spaceCount++;
            continue;
        }

        //If more than one space then append a single space
        if (spaceCount > 1 && sb.Length > 0)
            sb.Append(" ");

        //Append the non space character
        sb.Append(longChars[i]);

        //Reset the space count
        spaceCount = 1;
    }
    return sb.ToString();
}


texts:
Given below is my task

  Write a selenium test that makes a booking from Bangalore to New Delhi
  for today's date with a return of tomorrow using makemytrip.com.
  Select the cheapest flight and make sure that you come to the booking page.

I'm pretty new to Selenium and I would like to know if my attempt at achieving the aforementioned task is as good as it can get or if there are certain aspects of my code that could be improved.

I've relied on some simple element selectors to achieve the task and one concern I have with automating a test case (such as the one mentioned above) for a web site is to do it in such a way that it remains change proof i.e. a test case written in such a way that it validates certain functions of the site without relying on the structure of the web page itself especially when the "id" attribute isn't available. Are there any general recommendations/practices as far as automation of web sites is concerned ?

from selenium import webdriver,common
from selenium.webdriver.common.keys import Keys
from datetime import datetime
import time,re

def type_and_enter(element,text):
    element.clear()
    element.send_keys(text)
    time.sleep(1)
    element.send_keys(Keys.ENTER)

source = "Bangalore"
destination = "New Delhi"

# CREATE A NEW GOOGLE CHROME OBJECT & LOGIN TO makemytrip.com
chrome_browser = webdriver.Chrome()
chrome_browser.get("https://www.makemytrip.com/")

# ASSERT WE ARE ON THE CORRECT PAGE
assert "makemytrip" in chrome_browser.title.lower()

# ENTER VALUE FOR "FROM"
from_field = chrome_browser.find_element_by_id("hp-widget__sfrom")
type_and_enter(from_field,source)

# ENTER VALUE FOR "TO"
to_field = chrome_browser.find_element_by_id("hp-widget__sTo")
type_and_enter(to_field,destination)

# SET DEPART DATE TO PRESENT DAY
depart_field = chrome_browser.find_element_by_id("hp-widget__depart")
depart_field.click()


texts:
I made a state machine.

You can press 0 and 1 to switch between the hypothetical menu and playing state.

I hope you can help me improve it further.

StateManager.h

#pragma once

#ifndef StateManager_H
#define StateManager_H

#include <iostream>
#include "State.h"

/*
State classes
*/

class StateManager {
public:
    // Define m_current_state upon the creation of this class (since that prevents there being a nullptr error in change_state
    StateManager(State* state)
        : m_current_state(state)
    {}

    void change_state(State* state) {
        m_current_state->on_exit();
        m_current_state = state;
        m_current_state->on_enter();
    }

    void update_state(StateManager* manager) {
        m_current_state->on_update(manager);
    }

    State* get_state() {
        return m_current_state;
    }

private:
    State* m_current_state;
};

#endif

State.h

#pragma once

#ifndef State_H
#define State_H

#include "StateManager.h"

// I'm using forward declaration here since I've had a problem with circular dependency
class StateManager;

class State {
public:
    // All states have to have these three functions
    virtual void on_enter() = 0;
    virtual void on_update(StateManager* state_manager) = 0;
    virtual void on_exit() = 0;
};

#endif

IntroState.h

#pragma once

#ifndef IntroState_H
#define IntroState_H

#include "StateManager.h"
#include "State.h"
#include "GameState.h"

/*
Basic test state for demonstration
*/

class MenuState : public State {
public:
    MenuState();

    virtual void on_enter() override;

    virtual void on_update(StateManager* state_manager) override;

    virtual void on_exit() override;

private:
    bool should_change_state;
};

#endif

Introstate.cpp

#include "IntroState.h"

MenuState::MenuState()
    : should_change_state(false)
{}

void MenuState::on_enter(){
    std::cout << "Entering the menu state" << std::endl;
}

void MenuState::on_update(StateManager* state_manager){
    // update the menu
    std::cout << "Should the state be changed to the playing state" << std::endl;
    std::cin >> should_change_state;
    if (should_change_state == true) {
        state_manager->change_state(new PlayingState());
    }
}

void MenuState::on_exit(){
    std::cout << "Exiting the menu state" << std::endl;
}

GameState.h

#pragma once

#ifndef GameState_H
#define GameState_H

#include "IntroState.h"
#include "State.h"

/*
Basic test state for demonstration
*/

class PlayingState : public State {
public:
    PlayingState();

    virtual void on_enter() override;

    virtual void on_update(StateManager* state_manager) override;

    virtual void on_exit() override;

private:
    bool should_change_state;
};

#endif

GameState.cpp

#include "GameState.h"

PlayingState::PlayingState()
    : should_change_state(false)
{}

void PlayingState::on_enter() {
    std::cout << "Entering the playing state" << std::endl;
}

void PlayingState::on_update(StateManager* state_manager) {
    // update the menu
    std::cout << "Should the state be changed to the menu state" << std::endl;
    std::cin >> should_change_state;
    if (should_change_state == true) {
        state_manager->change_state(new MenuState());
    }
}

void PlayingState::on_exit() {
    std::cout << "Exiting the playing state" << std::endl;
}

Source.cpp

#include "StateManager.h"
#include "State.h"
#include "IntroState.h"

int main() {
    StateManager* manager = new StateManager(new MenuState());

    int exit = 0;
    while (exit != 1) {
        manager->update_state(manager);
    }

    return 0;
}

Thanks!


texts: The multithreading model to clean ConcurrentQueue in C#

texts:
I have some code that populate EventfulConcurrentQueue which is ConcurrentQueue. So I need to save all data from  EventfulConcurrentQueue to a database.
I think to use sort of multithreading model in order to dequeue items.
So EventfulConcurrentQueue  should be depopulated from different threads that grab the part of items of EventfulConcurrentQueue and that items will insert to a database.
So far I have following code.
Usage of EventfulConcurrentQueue
public partial class FormMain: Form {

  private EventfulConcurrentQueue < PacketItem > PacketQueue {
    get;
    set;
  } = new EventfulConcurrentQueue < PacketItem > ();

  private void FormMain_Load(object sender, EventArgs e) {
    StartPersistingTask();
  }

  private async Task StartPersistingTask() {
    var chunkOfPacketsToInsert = 100;

    try {
      while (true) {
        if (PacketQueue.Count > chunkOfPacketsToInsert) {
          int counter = 0;
          var chunkToBulkInsert = DataHelper.CreateBulkCopyDataTable();

          while (counter <= chunkOfPacketsToInsert) {
            PacketItem packetItem = null;
            PacketQueue.TryDequeue(out packetItem);
            if (packetItem != null) {
              chunkToBulkInsert.Rows.Add(Guid.NewGuid(), packetItem.AtTime, packetItem.GPSTrackerID, packetItem.PacketBytes);
              counter++;
            } else {
              break;
            }
          };

          //create object of SqlBulkCopy which help to insert
          using
          var bulkCopy = new SqlBulkCopy(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString, SqlBulkCopyOptions.Default);
          bulkCopy.DestinationTableName = "MyTable";
          try {
            bulkCopy.WriteToServer(chunkToBulkInsert);
          } catch (Exception ex) {
            Log(ex, LogErrorEnums.Fatal);
          } finally {
            Log(LogErrorEnums.Info, $ "Items: {counter}");
          }
        } else {
          await Task.Delay(100);
        }
      }
    } catch (Exception ex) {
      Log(ex, LogErrorEnums.Error);
    }
  }

}

Definition of EventfulConcurrentQueue
public sealed class EventfulConcurrentQueue < T > {
  private readonly ConcurrentQueue < T > _queue;

  public EventfulConcurrentQueue() {
    _queue = new ConcurrentQueue < T > ();
  }

  public int Count {
    get {
      return _queue.Count;
    }
  }

  public bool IsEmpty {
    get {
      return _queue.IsEmpty;
    }
  }

  public void Enqueue(T item) {
    _queue.Enqueue(item);
    OnItemEnqueued();
  }

  public bool TryDequeue(out T result) {
    var success = _queue.TryDequeue(out result);

    if (success) {
      OnItemDequeued(result);
    }
    return success;
  }

  public event EventHandler ItemEnqueued;
  public event EventHandler < ItemDequeuedEventArgs < T >> ItemDequeued;

  void OnItemEnqueued() {
    ItemEnqueued?.Invoke(this, EventArgs.Empty);
  }

  void OnItemDequeued(T item) {
    ItemDequeued?.Invoke(this, new ItemDequeuedEventArgs < T > {
      Item = item
    });
  }
}

public sealed class ItemDequeuedEventArgs < T >: EventArgs {
  public T Item {
    get;
    set;
  }
}

public sealed class PacketItem {
  public int GPSTrackerID {
    get;
    set;
  }
  public DateTime AtTime {
    get;
    set;
  }

  public byte[] PacketBytes {
    get;
    set;
  }

  public int GPSTrackerTypeID {
    get;
    set;
  }

  /// <summary>
  /// Parsed by device's protocol packet
  /// </summary>
  public object ParsedPacket {
    get;
    set;
  }
}


texts: Simple file locking wrapper command in C

texts:
A simple command that wraps another command, locking a file first. It is similar to flock, just simpler.

#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/file.h>
#include <err.h>
#include <stdlib.h>

void attemptLock(const char *lockFileName)
{
    int fd = open(lockFileName, O_CREAT | O_WRONLY, 0666);
    if (!fd || flock(fd, LOCK_EX))
        warn("Cannot lock %s", lockFileName);
}

int main(int argc, char *argv[])
{
    if (argc < 3)
        errx(EXIT_FAILURE, "Not enough arguments.\nUsage: %s LOCKFILENAME COMMAND...\n", argv[0]);
    attemptLock(argv[1]);
    argv += 2;  // Skip our own command name and LOCKFILENAME.
    execvp(argv[0], argv);
    err(EXIT_FAILURE, "Cannot execute %s", argv[0]);
}

Anything fishy? Bogus? Wrong? Anything that can be improved (besides adding options like -h)?


texts: Flatten iterator for nested list in python3

texts:
flatten.py

from collections import Iterable, Mapping
from operator import methodcaller

from stack import Stack

class flatten(object):
    """
    Iterator that walk through nested iterable.
    If the initial item is not iterable, only itself will be yielded.
    Args:
        item         (Object): Any object.
        depth (Optional[int]): Maximum nesting layer.
        mapping_iter    (str): the method to be called when handling mapping

    >>> from collections import OrderedDict
    >>> kwargs = OrderedDict()
    >>> kwargs['file'] = 'test.txt'
    >>> kwargs['data'] = [[0, 1], [-1, 0]]
    >>> tuple(flatten(kwargs))
    ('test.txt', 0, 1, -1, 0)
    >>> tuple(flatten('apple'))
    ('apple',)
    """

    def __init__(self, item, depth=128, map_iter='values'):
        self.map_iter = methodcaller(map_iter)

        done, item = self.expand(item)
        if done:
            item = iter((item,))
        self.stack = Stack([item], depth)

    def __iter__(self):
        return self

    def __next__(self):
        while self.stack:
            for item in self.stack[-1]:
                done, item = self.expand(item)
                if done:
                    return item
                else:
                    self.stack.append(item)
                    break
            else:
                self.stack.pop()
        raise StopIteration

    def expand(self, item):
        if isinstance(item, str):
            return True, item
        elif isinstance(item, Mapping):
            return False, iter(self.map_iter(item))
        elif isinstance(item, Iterable):
            return False, iter(item)
        else:
            return True, item

class named_flatten(flatten):
    """
    Iterator that walk through nested iterable and create tuple key.
    For non Mapping iterable, the key are generated by enumerate.
    If the initial item is not iterable, only itself will be yielded.
    Args:
        item         (Object): Any object.
        depth (Optional[int]): Maximum nesting layer.

    >>> from collections import OrderedDict
    >>> kwargs = OrderedDict()
    >>> kwargs['file'] = 'test.txt'
    >>> kwargs['data'] = [[0, 1], [-1, 0]]
    >>> result = tuple(named_flatten(kwargs))
    >>> result[0]
    (('file',), 'test.txt')
    >>> result[1]
    (('data', 0, 0), 0)
    >>> tuple(named_flatten('apple'))
    (((), 'apple'),)
    """

    def __init__(self, item, depth=128):
        super().__init__(((), item), depth, map_iter)

    def expand(self, item):
        key, value = item
        if isinstance(value, str):
            return True, item
        elif isinstance(value, Mapping):
            it = value.items()
        elif isinstance(value, Iterable):
            it = enumerate(value)
        else:
            return True, item
        return False, ((key+(k,), v) for k, v in it)

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

stack.py

from collections import deque

class FullStackError(MemoryError):
    pass

class Stack(deque):

    @property
    def full(self):
        return 0 == (self.maxlen - len(self) if self.maxlen else self.maxlen)

    def append(self, x):
        if self.full:
            raise FullStackError
        super().append(x)

    def appendleft(self, x):
        if self.full:
            raise FullStackError
        super().appendleft(x)

    def insert(self, i, x):
        if self.full:
            raise FullStackError
        super().insert(i, x)

    def extend(self, iterable):
        for x in iterable:
            self.append(x)

    def extendleft(self, iterable):
        for x in iterable:
            self.appendleft(x)

    def __str__(self):
        return 'Stack' + super().__str__()[5:]

    def __repr__(self):
        return 'Stack' + super().__repr__()[5:]


texts:
Please help me in reducing the time complexity of this code as it is taking a long time to read its Excel input.

# -*- coding: utf-8 -*-
"""
Created on Wed Mar  9 14:26:22 2016

@author: DalalNS
"""
from openpyxl import load_workbook
import os
import shutil
filename = 'test.xlsx'
wb = load_workbook(filename, use_iterators=True)
sheetlist=(wb.get_sheet_names())
searclist=[]
for i in range(len(sheetlist)):
    ws=wb[sheetlist[i]]
    for row in ws.iter_rows():
        for cell in row:
            if(cell[1]=='B'):
                searclist.append((cell.internal_value))
searclist = [os.path.splitext(each)[0] for each in searclist]

def search(searclist):
    for root, dirs, files in os.walk('C://Users/DalalNS/Desktop/Mapping/a/b'):
        for _file in files:
            try:
                print(_file[:-4])

                if _file[:-4] in searclist:
            # If we find it, notify us about it and copy it it to C:\NewPath\
                    print('Found file in: ' + str(root))
                    shutil.copy(os.path.abspath(root + '/' + _file), 'C://Users/DalalNS/Desktop/Mapping/output')
                elif _file[:-5] in searclist:
            # If we find it, notify us about it and copy it it to C:\NewPath\
                    print('Found file in: ' + str(root))
                    shutil.copy(os.path.abspath(root + '/' + _file), 'C://Users/DalalNS/Desktop/Mapping/output')

                else:
                    print("not found")
            except:
                print("runtime exception")
print(search(searclist))