texts: Graph Implementation in Java using Set and Map

texts:
There is a Graph implementation. I'm using Set to store unique Edges and Map to store Vertices and their associated edges. Assume Vertex and Edge class has been defined somewhere else implementing hashcode() and equals() working fine.

public class Graph
{
    static class Vertex {}

    static class Edge {}

    private Map<Vertex, Set<Edge>> vertexSetMap;
    private Set<Edge> edgeSet;

    public Graph()
    {
        edgeSet = new LinkedHashSet<>();
        vertexSetMap = new LinkedHashMap<>();
    }

    public boolean addVertex(Vertex vertex)
    {
        if(!vertexSetMap.containsKey(vertex))
        {
            vertexSetMap.put(vertex, new LinkedHashSet <>());
            return true;
        }
        return false;
    }

    public boolean addEdge(Vertex v1, Vertex v2, Edge edge)
    {
        if(edgeSet.add(edge))
        {
            vertexSetMap.get(v1).add(edge);
            vertexSetMap.get(v2).add(edge);
            return true;
        }
        return false;
    }

    public Set<Edge> getEdges(Vertex vertex)
    {
        return vertexSetMap.get(vertex);
    }

    public Set<Vertex> getNeighborsOf(Vertex vertex)
    {
        Set<Vertex> neighbors = new LinkedHashSet <>();
        for(Edge edge : vertexSetMap.get(vertex))
        {
            Vertex v1 = edge.getVertex1();
            Vertex v2 = edge.getVertex2();
            if(v1.equals(vertex)) neighbors.add(v2);
            else neighbors.add(v1);
        }
        return neighbors;
    }

    public void removeVertex(Vertex vertex)
    {
        Set<Edge> deleteEdges = getEdges(vertex);
        vertexSetMap.remove(vertex);
        edgeSet.removeAll(deleteEdges);
        vertexSetMap.keySet().forEach(vertex1 ->
        vertexSetMap.get(vertex1).removeAll(deleteEdges));
    }

    public void removeEdge(Edge edge)
    {
        edgeSet.remove(edge);
        Vertex v1 = edge.getVertex1();
        Vertex v2 = edge.getVertex2();
        vertexSetMap.get(v1).remove(edge);
        vertexSetMap.get(v2).remove(edge);
    }

    public boolean containsVertex(Vertex vertex)
    {
        return vertexSetMap.containsKey(vertex);
    }

    public boolean containsEdge(Vertex v1, Vertex v2, Edge edge)
    {
        return (edgeSet.contains(edge) && vertexSetMap.get(v1).contains(edge)
            && vertexSetMap.get(v2).contains(edge));
    }

    public boolean containsEdge(Vertex v1, Vertex v2)
    {
        for(Edge e : vertexSetMap.get(v1))
            if(vertexSetMap.get(v2).contains(e)) return true;
        return false;
    }

    public int totalVertices()
    {
        return vertexSetMap.keySet().size();
    }

    public int totalEdges()
    {
        return edgeSet.size();
    }

    public Set<Vertex> getAllVertices()
    {
        return new LinkedHashSet <>(vertexSetMap.keySet());
    }

    public Set<Edge> getAllEdges()
    {
        return edgeSet;
    }

    public void clear()
    {
        edgeSet = null;
        edgeSet = new LinkedHashSet <>();
        vertexSetMap = null;
        vertexSetMap = new LinkedHashMap <>();
    }
}


texts: Calculate the frequency of characters in a string

texts:
I wrote this program to check the number of times that each letter appears in a string input by the user. It works fine, but is there a more efficient or alternative solution of going about this task than reiterating through a twenty-six-element-long array for every single character?

import java.util.Scanner;
public class Letters {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        Scanner sc = new Scanner(System.in);
        char[] c = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        int[] f = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        System.out.println("Enter a string.");
        String k = sc.nextLine();
        String s = k.toUpperCase();
        s = s.trim();
        int l = s.length();
        System.out.println("Checking string = " + s);
        char ch;
        for (int i = 0; i < l; i++) {
            ch = s.charAt(i);
            for (int j = 0; j < c.length; j++) {
                if (ch == c[j]) {
                    f[j]++;
                }
            }
        }
        System.out.println("Char\tFreq");
        for (int i = 0; i < c.length; i++) {
            if (f[i] != 0) {
               System.out.println(c[i] + "\t" + f[i]);
            }
        }
    }
}


texts:
I was using setTimeouts for a project where a callback will be called after a duration, but the user has the options of extending, pausing or stopping the timeout. I felt using the default setTimeout was a bit clunky, especially since I needed to remember the timeout ids, and I decided to create a timeout utility object. I was wondering if I'm doing this properly, and whether you could give me some tips on how to refactor my code?

Object definition

//Utility object that makes it easier to control timeouts
function Timer(duration, callback) {
    this._duration = duration;
    this._callback = callback;
    this._id = -1;

    this._paused = true;
    this._lastRunTime = -1;
    this._remainingTime = this._duration;
}

//calls the current timeout; if a function is passed, run that function
//instead of default callback (but do not change the default callback)
Timer.prototype.callTimer = function(aCallback, aDuration) {
    var that = this,
        //sets callback and duration to default values if not passed in
        callback = aCallback || this._callback,
        duration = aDuration || this._duration;

    //if a previous timeout has been set, clear it
    if (this._id > -1 ) {
        clearTimeout(this._id);
    }
    //executes the callback and resets the timer
    this._id = setTimeout(function() {
        callback();
        that.resetTimer();
    }, duration);

    this._paused = false;
    //rememebers the time when the timer was run (for pauseTimer)
    this._lastRunTime = new Date();
}

Timer.prototype.resetTimer = function() {
    this._remainingTime = this._duration;
    this._paused = true;
    this._lastRunTime = -1;
    clearTimeout(this._id);
}

//changes the default callback
//if second argument is true, execute callTimer
Timer.prototype.changeCallback = function(callback, callTimer) {
    this._callback = callback;
    if (callTimer) this.callTimer();
}

Timer.prototype.pauseTimer = function() {
    if (this._lastRunTime === -1) {
        throw new Error('Timer has not been run yet');
    }

    //if currently paused, call timer with remaining time left
    if (this._paused) {
        this._lastRunTime = new Date();
        this.callTimer(this._callback, this._remainingTime);
    }
    //else pause
    else {
        clearTimeout(this._id);
        //subtract the amount of time that has elapsed
        this._remainingTime -= (new Date() - this._lastRunTime);
    }

    //toggles the _paused variable
    this._paused = !this._paused;
}

http://fiddle.jshell.net/6nhGW/

Test Code

var button = document.getElementById('extendTimeout'),
    button2 = document.getElementById('tempChangeCallback'),
    button3 = document.getElementById('changeCallback'),
    button4 = document.getElementById('resetTimer'),
    button5 = document.getElementById('pauseTimer'),
    startTime,
    timeout = -1;

var timer = new Timer(3000, function() {
    console.log('Total time elapsed: ' + (new Date() - startTime));
    startTime = null;
})

button.addEventListener('click', function() {
    if (!startTime) startTime = new Date();
    timer.callTimer();
})

button2.addEventListener('click', function() {
    if (!startTime) startTime = new Date();
    timer.callTimer(function() {
        console.log('Temporarily change callback');
        console.log('Total time elapsed: ' + (new Date() - startTime));
        startTime = null;
    });
})

button3.addEventListener('click', function() {
    timer.changeCallback(function() {
        console.log('Callback has been changed!');
        startTime = null;
    }, true);
});

button4.addEventListener('click', function() {
    timer.resetTimer();
    startTime = null;
});

button5.addEventListener('click', function() {
    if (!startTime) startTime = new Date();
    timer.pauseTimer();
});


texts: Changing line colors and move text for menu navigation

texts:
This code basically changes the color of the lines and move text for menu navigation.  Is there a simpler way of writing it?

$('.nav1 a').click(function () {
    $('.nav1').addClass("current_nav1");
    $('.sf_menu li').removeClass('current_nav2 current_nav3 current_nav4 current_nav5 current_nav6');
    $('#content, #home').slideDown(2000);
    $('#design, #seo, #galery, #about, #contact').slideUp(2000);
});

$('.nav2 a').click(function () {
    $('.nav2').addClass("current_nav2");
    $('.sf_menu li').removeClass('current_nav1  current_nav3 current_nav4 current_nav5 current_nav6 ');
    $('#content, #design').slideDown(2000);
    $('#home, #seo, #galery, #about, #contact').slideUp(2000);
});

$('.nav3 a').click(function () {
    $('.nav3').addClass("current_nav3");
    $('.sf_menu li').removeClass('current_nav1 current_nav2  current_nav4 current_nav5 current_nav6');
    $('#content, #seo').slideDown(2000);
    $('#home, #design, #galery, #about, #contact').slideUp(2000);
});

$('.nav4 a').click(function () {
    $('.nav4').addClass("current_nav4");
    $('.sf_menu li').removeClass('current_nav1 current_nav2 current_nav3  current_nav5 current_nav6');
    $('#content, #galery').slideDown(2000);
    $('#home, #design, #seo, #about, #contact').slideUp(2000);
});

$('.nav5 a').click(function () {
    $('.nav5').addClass("current_nav5");
    $('.sf_menu li').removeClass('current_nav1 current_nav2 current_nav3 current_nav4  current_nav6');
    $('#content, #about').slideDown(2000);
    $('#home, #design, #seo, #galery, #contact').slideUp(2000);
});

$('.nav6 a').click(function () {
    $('.nav6').addClass("current_nav6");
    $('.sf_menu li').removeClass('current_nav1 current_nav2 current_nav3 current_nav4 current_nav5 ');
    $('#content, #contact').slideDown(2000);
    $('#home, #design, #seo, #galery, #about').slideUp(2000);
});


texts: Reducing boilerplate of binary layout handling in Haskell

texts:
Here is the code: https://github.com/EarlGray/haskell-snippets/blob/master/ext2hs/Ext2.hs

My problem is that it is quite painful to make large Haskell "records" and deserialize a binary layout with Data.Binary.Get manually like this:

instance Binary Superblock where
  get = binGetSuperblock

binGetSuperblock = do
  uint13  <- replicateM 13   getWord32le
  ushort6 <- replicateM 6    getWord16le
  uint4   <- replicateM 4    getWord32le
  ushort2 <- replicateM 2    getWord16le
  return Superblock {
    sInodesCount = uint13 !! 0,           sBlocksCount = uint13 !! 1,
    sReservedBlocksCount = uint13 !! 2,   sFreeBlocksCount = uint13 !! 3,
    sFreeInodesCount = uint13 !! 4,       sFirstDataBlock = uint13 !! 5,
    sLogBlockSize = uint13 !! 6,          sLogClusterSize = uint13 !! 7,
    sBlocksPerGroup = uint13 !! 8,        sClustersPerGroup = uint13 !! 9,
    sInodesPerGroup = uint13 !! 10,       sMountTime = uint13 !! 11,
    sWriteTime = uint13 !! 12,

    sMountsCount = ushort6 !! 0,    sMaxMountsCount = int (ushort6 !! 1),
    sMagic = ushort6 !! 2,          sState = ushort6 !! 3,
    sErrors = ushort6 !! 4,
    sLastCheckTime = uint4 !! 0,    sCheckInterval = uint4 !! 1,
    sCreatorOS = uint4 !! 2,        sRevLevel = (uint4 !! 3, ushort6 !! 5),

    sDefaultResUID = ushort2 !! 0,  sDefaultResGID = ushort2 !! 1,

    sDynRev = Nothing,
    sPrealloc = Nothing,
    sJournaling = Nothing
  }

(this is ext2fs superblock structure).

First of all, I would like to make binary layout as much declarative as possible, abstracting away those ugly sequences of getWord32le in Get monad with temporary fields. I want something like my python code, where binary fields are unpacked to a map according to a struct format string

The second thing I need is a more concise and more clear way for initializing a large Haskell record (creating a lot of temporary named values in the monad is pain).

One way I think of is to read binary fields into a heterogeneous map forall a. BinaryField a => Map String a, accessing each value by its name and pre-extracting most used ones to Haskell.
Perhaps Template Haskell and code generation from a declarative format may help, but I have no experience with TH yet.

I would be glad to hear any suggestions or hints about a more idiomatic way (are there any relevant tools?) or about the code in general (though it's just my learning code and it's very incomplete at the moment).


texts: Return the first number found greater than the provided input number (13 digits)

texts:
This script converts the numbers to be at least 13 characters long (for UNIX_MS strings). For use with timestamps, I'm having issues with it being very slow. I wanted an alternative to grepping for one specific UNIX_MS timestamp and not finding it and then having to grep multiple more times.

For the output I wanted the line number in the file (for slicing) as well as the original line (to confirm/inspect).

I'm very specifically looking for optimizations as I'd like this to be as-close-to-as-fast as grepping a single timestamp.

Usage: ./script.sh file UNIX_MS

#! /bin/bash
# return the first number found that's greater than the provided input number
res=
linenum=
count=0
returnline=             # hold onto the line for return
tocheck=$2
tocheck=$(($tocheck*(10**(( ${#tocheck} - 13) * -1))))
inseconds=$(($tocheck/1000))
date=$(date -r $inseconds)
echo "Looking for first timestamp -ge to $date.."
while read line;
  do
    count=$(($count + 1))
    timearray=$(grep -o -E "^(.*?)([0-9]{10,13})?" <<< $line)
    if [ -z "$timearray" ]; then
    echo "PROBLEM"
        echo "grep -o -E '^(.*?)([0-9]{10,13})?' <<< $line"
        exit 1
    fi
    timestamp=$(sed -Ee "s/[0-9]+\://" <<< $timearray)
# normalize timestamp to be 13 digits
    if [ "${#timestamp}" -lt "13" ]; then
        mult=$((10**(( ${#timestamp} - 13) * -1)))
        timestamp=$(($timestamp * $mult))
    fi
    echo "$timestamp >= $tocheck?"
    linenum=$([ "$timestamp" -ge "$tocheck" ] && echo $count)
    if [ -z "$linenum" ]; then
        :;
    else
        returnline=$line
    break;
    fi
done < $1
echo "$linenum:$returnline"
echo ""


texts:
In the codebase I support, I found the following code. I am interested in your opinion about its expediency and especially the expediency of redefining the operator().

  template <typename KEY, typename VALUE>
  class MyUnorderedMap {
    std::unordered_map<KEY, VALUE> map;

  public:
    template <typename T>
    auto insert(const T value) {
      return map.insert(value);
    }
    inline auto& operator()(const KEY& r) { return (*this)[r]; }
    inline auto& operator[](const KEY r) { return map[r]; }
    inline auto find(const KEY& key) const { return map.find(key); }
    inline auto size() const { return map.size(); }
    inline auto begin() { return map.begin(); }
    inline auto end() { return map.end(); }

    inline bool exists(const KEY& userId) const {
      return map.find(userId) != map.end();
    }
    bool remove(const KEY& userId) {
      auto it = map.find(userId);
      bool retval = (it != map.end());
      if (retval)
        map.erase(it);
      return retval;
    }
  };


texts:
The aim of it is to be the quickest way to add to existing notes via SSHh.

Is this code in Python style? Am I missing any methods that would make the code simpler or legible?

#! /usr/bin/python3

#Maintain: myemail@mail.com
#Purpose: A simple way to add entries to existing files
#Usage: Write the name of the file you intend to add to.
#Future: A list of editable files when the program opens

from sys import argv
import datetime
import os,errno
import os.path
import contextlib

script, typed = argv
filename = typed+".txt"
savelocation = os.path.join('/home/user/',filename)
print(savelocation)
print("Aditor: a digital typewriter, Type: d when done")

date = str(datetime.datetime.now().date())
with open("/tmp/tempfile.txt","a+") as target:
        target.write("\n")
        target.write(date)
        while True:
                entry=input()
                target.write("\n")
                if entry in ['done','d']:
                        break
                else:
                        target.write(entry)

target = open("/tmp/tempfile.txt","r")
f = open(filename, "a")
f.write(target.read())

f.close()
target.close()
print("Entry saved.")

with contextlib.suppress(FileNotFoundError):
    os.remove("/tmp/tempfile.txt")


texts: Random string of variable length generator

texts:
Below is my code for generating a random string of random length. I am using it in integration tests. Currently I have almost 2000 tests running each time a commit is made to master and a few of those tests are using this class.

I would like to make sure the code is optimized so that the tests complete as quickly as possible.

public class Strings
{
    private static readonly Random Random = new Random();

    private static int RandomChar => Random.Next(char.MinValue, char.MaxValue);

    public static string GenerateRandomStringOfSetLength(int length)
    {
        return GenerateRandomString(length);
    }

    private static string GenerateRandomString(int length)
    {
        var stringBuilder = new StringBuilder();

        while (stringBuilder.Length - 1 <= length)
        {
            var character = Convert.ToChar(RandomChar);
            if (!char.IsControl(character))
            {
                stringBuilder.Append(character);
            }
        }

        return stringBuilder.ToString();
    }
}


texts: 2 methods to parse the same pattern of line in a file

texts:
I use 2 methods in order to parse those 2 lines:

flux=rp_evtmedprev_out
partitions=a054010a,a054020a,a054030a,a034040a,a054050a,a054060a,a054070a,a054080a,a054090a

This is the call:

BufferedReader reader = new BufferedReader(new InputStreamReader(
        httpConn.getInputStream()));
StringBuilder buf = new StringBuilder();
String line = null;

String flux = reader.readLine();
String partitionsString = reader.readLine();
insertToplogieNatures(flux, topologie);
insertToplogiePartitions(partitionsString, topologie);

Is there a way to merge those 2 methods:

public void insertToplogiePartitions(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = line.split("=");
    splitLigneDeuxiemePartie = splitLigneDeuxiemePartie[1].split(",");
    Partition partTemp;
    List<Partition> partitionsBuild = new ArrayList<Partition>();

    for (String partStringTemp : splitLigneDeuxiemePartie) {
        partTemp = new Partition();
        partTemp.setHostname(partStringTemp);
        partitionsBuild.add(partTemp);
    }
    topologie.setPartitions(partitionsBuild);
}

public void insertToplogieNatures(String line, Topologie topologie) {
    String[] splitLigneDeuxiemePartie = line.split("=");
    splitLigneDeuxiemePartie = splitLigneDeuxiemePartie[1].split(",");

    List<String> naturesBuild = new ArrayList<String>();

    for (String natureTemp : splitLigneDeuxiemePartie) {
        naturesBuild.add(natureTemp);
    }
    topologie.setNatures(naturesBuild);
}

If it's possible, I'm not even sure that it would be a good idea due to readability.


texts: my implementation of conway's game of life in C++

texts:
I found Conway's game of life. I had heard of it, of course, but didn't think it would be so easy and fun to implement. Anyway, here's my code which I know needs a lot of polish:
#include <iostream>
#include <vector>
#include <windows.h>

#define SIZE 10

using std::vector;

struct Pos {
    int x;
    int y;

    Pos(int ix, int iy) : x(ix), y(iy) {}
};

void printGrid();

int getNeighborCount(Pos cellPos);

void next(int (&universe)[SIZE][SIZE]);

void killOrBirthCells(int (&universe)[SIZE][SIZE], vector<Pos> &toKill, vector<Pos> &toBirth);

void cellFate(int &cell, Pos cellPos, int neighborCount, vector<Pos> &toKill, vector<Pos> &toBirth);

void printUniverse(int (&universe)[SIZE][SIZE]);

int main() {
    int universe[SIZE][SIZE] = {0};

    // glider
    universe[0][2] = 1;
    universe[1][2] = 1;
    universe[2][2] = 1;
    universe[2][1] = 1;
    universe[1][0] = 1;

    while (1) {
        system("cls");
        next(universe);
        printUniverse(universe);
        Sleep(500);
    }

    return 0;
}

int getNeighborCount(int (&universe)[SIZE][SIZE], Pos cellPos) {
    int count = 0;
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            int x = cellPos.x - 1 + j;
            int y = cellPos.y - 1 + i;
            // handle cells on the edge
            if (x >= 0 && y >= 0 && x < SIZE && y < SIZE
                && universe[cellPos.y - 1 + i][cellPos.x - 1 + j] == 1) {
                count++;
            }
        }
    }
    // exclude itself
    if (universe[cellPos.y][cellPos.x]) {
        return count - 1;
    }
    return count;
}

void next(int (&universe)[SIZE][SIZE]) {
    std::vector<Pos> toKill;
    std::vector<Pos> toBirth;

    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            Pos cellPos{j, i};
            int neighborCount = getNeighborCount(universe, cellPos);
            cellFate(universe[i][j], cellPos, neighborCount, toKill, toBirth);
        }
    }

    killOrBirthCells(universe, toKill, toBirth);
}

// populate toKill and toBirth vectors
void cellFate(int &cell, Pos cellPos, int neighborCount, vector<Pos> &toKill, vector<Pos> &toBirth) {
    if (cell == 1) {
        // lonely
        if (neighborCount == 0 || neighborCount == 1) {
            toKill.push_back(cellPos);
        // overcrowded
        } else if (neighborCount >= 4 && neighborCount <= 8) {
            toKill.push_back(cellPos);
        }
    } else {
        if (neighborCount == 3) {
            toBirth.push_back(cellPos);
        }
    }
}

void killOrBirthCells(int (&universe)[SIZE][SIZE], vector<Pos> &toKill, vector<Pos> &toBirth) {
    for (Pos cellPos : toKill) {
        universe[cellPos.y][cellPos.x] = 0;
    }
    for (Pos cellPos : toBirth) {
        universe[cellPos.y][cellPos.x] = 1;
    }
    toKill.clear();
    toBirth.clear();
}

void printUniverse(int (&universe)[SIZE][SIZE]) {
    for (int i = 0; i < SIZE; i++) {
        for (int j = 0; j < SIZE; j++) {
            if (universe[i][j] == 1) {
                std::cout << 'x';
            } else {
                std::cout << '.';
            }
        }
        std::cout << '\n';
    }
}


texts:
I'm trying to write the most efficient query I can to pull the relevant data I need for retrieving the latest conversations for a user, ordering groupings of conversations by most recent message in that conversation.

I don't like the idea of using a subselect to match the max timestamp. Is there a better or more efficient way to do this?

SELECT c.id, c.fromUserId, c.toUserId, m.userId, m.message, m.timestamp, pm.filename AS thumbnail, u.username
FROM conversations c, messages m, productmedia pm, users u
WHERE (c.fromUserId = '9' OR c.toUserId = '9')
AND c.id = m.conversationId
AND m.timestamp = (SELECT MAX(m.timestamp) FROM messages m WHERE m.conversationId = c.id)
AND c.productId = pm.productId
AND pm.sortOrder = '0'
AND m.userId = u.id
GROUP BY c.id
ORDER BY m.timestamp DESC


texts: Alternative way for checking an anagram pair

texts:
I'm writing a program to check whether a pair of Strings (entered by the user) are anagrams. I've already did with the standard way to sort both of the strings using Arrays.sort() but I also thought of an alternative version not requiring any sorting and ended up with this:

import java.util.Scanner;

public class Anagrams {
    public static void main(String[] args) {
        String s1, s2;
        try (Scanner sc = new Scanner(System.in)) {
            System.out.println("Enter the two words: ");
            s1 = sc.nextLine().toLowerCase().replace(" ", "");
            s2 = sc.nextLine().toLowerCase().replace(" ", "");
        }
        if (s1.length() == s2.length() && isAnagram(s1, s2)) {
            System.out.format("%s is an anagram of %s.", s1, s2);
        } else {
            System.out.format("'%s' and '%s' are not anagrams.", s1, s2);
        }
    }

    public static boolean isAnagram(String s1, String s2) {
        return (sumOfChars(s1) == sumOfChars(s2));
    }

    public static int sumOfChars(String s) {
        int sum = 0;
        for (char c : s.toCharArray()) {
            sum += c;
        }
        return sum;
    }
}

I know this isn't perfect but it does work with most of the anagram pairs that exist in the dictionary (that I've tested). Can I improve anything here or should I forgo this?


texts: Executing multiple async methods synchronously without throwing

texts:
I have a following task: execute multiple asynchronous methods synchronously and always execute them all, even when one of them throws. Rethrow thrown exceptions if any occured only after all tasks have finished. Here is my code:

public static async Task ContinueWithoutThrowing(this IEnumerable<Func<Task>> tasks)
    {
        var thrownExceptions = new List<Exception>();

        foreach (var task in tasks)
        {
            try
            {
                await task().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                thrownExceptions.Add(ex);
            }
        }

        if (thrownExceptions.Any())
        {
            throw new AggregateException(thrownExceptions);
        }
    }

Usage of this code is following:

Func<Task>[] tasks = { First, Second };
await tasks.ContinueWithoutThrowing().ConfigureAwait(false);

I am not sure whether what I am doing is accomplishable using already implemented methods on Task class like WhenAll. But using WhenAll with await throws on first exception. Also couldn't figure out some better name than ContinueWithoutThrowing when it actually throws if used with await (but its wanted behavior). I know this code doesn't handle cancellation but its not my main concern right now.


texts: PyQt5 - Open new image window for each button click in menu

texts:
I wanted to write a code that each time I will press some button in my menu, a numpy image array will somehow be created, and this image will show up in a new window.

So the following code is the same purpose, but with the same numpy image array for all new windows (for simplifying).

Which means, for a given numpy image array, each time I will press the 'New' button in my menu, The image will show up as a new window.

I just started playing with PyQt5, so I'd love to get any feedback, because I never did these stuff before (GUI, images), so I might get stuff heavily wrong.

NewNumpyImageWindowMenu.py class (main) pressing 'New' will create a new instance of NewImage (in the other class), and will hold the object in a list, in order for all the windows to still be visible.

import cv2
import sys
from PyQt5 import QtWidgets
from NewNumpyImageWindow import NewImage

class Menu(QtWidgets.QMainWindow):

    def __init__(self, numpy_img):
        super().__init__()
        newAct = QtWidgets.QAction('New', self)
        self.numpyPicture = numpy_img
        newAct.triggered.connect(self.new_image_window)
        toolbar = self.addToolBar('Exit')
        toolbar.addAction(newAct)
        self.images_list = []
        self.setGeometry(300, 300, 350, 250)
        self.show()

    def new_image_window(self):
        self.images_list.append(NewImage(self.numpyPicture))

if __name__ == '__main__':
    currentNumpyImage = cv2.imread("capture.png") # some picture
    app = QtWidgets.QApplication(sys.argv) # converts picture to numpy array
    menu = Menu(currentNumpyImage)
    sys.exit(app.exec_())

NewNumpyImageWindow.py class

import cv2
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel
from PyQt5.QtGui import QPixmap, QImage

class NewImage(QWidget):

    def __init__(self, numpy_image):
        super().__init__()
        label = QLabel(self)
        pixmap = self.convert_numpy_img_to_qpixmap(numpy_image)
        label.setPixmap(pixmap)
        self.resize(pixmap.width(), pixmap.height())
        self.show()

    @staticmethod
    def convert_numpy_img_to_qpixmap(np_img):
        height, width, channel = np_img.shape
        bytesPerLine = 3 * width
        return QPixmap(QImage(np_img.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped())

# if __name__ == '__main__':
#     app = QApplication(sys.argv)
#     current_numpy_Image = cv2.imread("capture.png")
#     window = NewImage(current_numpy_Image)
#     sys.exit(app.exec_())

Any help would be appreciated :)


texts: Taking a node in rootA and finding a clone node in other tree

texts:
I was asked this as an interview question. I was also asked to assume that there is a function which can compare and say two nodes are identical. I would like to implement that function as well. I'm not sure what's a sure shot way of saying that in pure JavaScript.

    O         O
   / \       / \
  O   O     O   O
     /|\       /|\
    O O O     O O O

  Assume two DOM trees with roots: rootA and rootB, the rootB tree
  being a clone of the rootA tree.  Write a function which takes a node
  in rootA and finds a clone node in the other tree.

I believe there is a better solution than recursion.

jsFiddle

function walkTheDom(root, cb) {
    if (!root) {
        return;
    }
    var r = root;
    if (cb (r)) {
        foundNode = r;
        return;
    }
    r = r.firstChild;

    while (r) {
        walkTheDom(r, cb);
        r = r.nextSibling;
    }

}

var compare = function (el) {
    //return true if nodes are equal
    //false if they're not
}

function findNode(node, rootB) {
    var foundNode = '';
    walkTheDom(rootB, compare);
    if (foundNode) {
        return foundNode
    }
}


texts: Four-function and exponentiation console calculator

texts:
This code works as it is supposed to:

#include<iostream>
#include<cmath>
#include<cstdlib>

using namespace std;

int main()
{
    char cAgain, type;
    int x, y=0;
    double addition(double num1, double num2), subtraction(double num1, double num2), division(double num1, double num2),
        multiplication(double num1, double num2), exponential(double num1, double num2), num1, num2, total;
    do
    {
        cout << "How many operations would you like to do?" << endl;
        cin >> x;
        if (x <= 0)
        {
            cout << "Error: You must have 1 or more operations." << endl;
        }
        else
        {
            while (x != 0, x--)
            {
                y++;
                cout << "Enter in your "<<y<< " operation. (First Number (+,-,*,/,^) Second Number)" << endl;
                cin >> num1 >> type >> num2;
                switch (type)
                {
                case '+':
                    total = addition(num1, num2);
                    cout << num1 << " + " << num2 << "= " << total<< endl;
                    break;
                case'-':
                    total = subtraction(num1, num2);
                    cout << num1 << " - " << num2 << "= " << total<< endl;
                    break;
                case'/':
                    total = division(num1, num2);
                    cout << num1 << " / " << num2 << "= " << total<< endl;
                    break;
                case'*':
                    total = multiplication(num1, num2);
                    cout << num1 << " * " << num2 << "= " << total << endl;
                    break;
                case'^':
                    total = exponential(num1, num2);
                    cout << num1 << " ^ " << num2 << "= " << total << endl;
                    break;
                }
            }
        }
        cout << "Would you like to run the program again.(Y/N)" << endl;
            cin >> cAgain;
    } while (cAgain == 'Y' || cAgain == 'y');
return 0;
}

double addition(double num1, double num2)
{
    double total;
    total = num1 + num2;
    return (total);
}
double subtraction(double num1, double num2)
{
    double total;
    total = num1 - num2;
    return (total);
}
double division(double num1, double num2)
{
    double total;
    total = num1 / num2;
    return (total);
}
double multiplication(double num1, double num2)
{
    double total;
    total = num1 * num2;
    return (total);
}
double exponential(double num1, double num2)
{
    double total;
    total = pow(num1,num2);
    return (total);
}

It starts by asking for the number of operations to perform. You enter a number, such as 3. Then it asks you to enter in your operation, such as 5+5, which is 10. Then it asks for a second, such as 10^2, which is 100. Then it asks for a third, such as 100-10, which is 90. Then it asks if you'd like to start over.


texts:
I'm working on a JSON to CSS converter in NodeJS, which takes a .json file and generates a .css file with its utility classes from it.

.json example

    }
        "breakpoints-map": {
            "default": "0",
            "sm": "only screen and (min-width: 508px)",
            "md": "only screen and (min-width: 768px)"
        },
        "bg-repeat-map": {
            "bg-repeat": "repeat",
            "bg-repeat-y": "repeat-y",
            "bg-no-repeat": "no-repeat",
            "bg-repeat-x": "repeat-x"
        },
        "bg-position-map": {
            "bg-pos-top": "top",
            "bg-pos-right-top": "top right",
            "bg-pos-right-center": "right",
            "bg-pos-right-bottom": "right bottom",
            "bg-pos-bottom": "bottom",
            "bg-pos-left-bottom": "left bottom",
            "bg-pos-left": "left",
            "bg-pos-left-top": "left top",
            "bg-pos-center": "center center"
        },
        "bg-attachment-map": {
            "bg-att-scroll": "scroll",
            "bg-att-fixed": "fixed"
        },
        "border-style-map": {
            "border-dotted": "dotted",
            "border-dashed": "dashed",
            "border-solid": "solid",
            "border-double": "double"
        }
    }

.js code

    module.exports = (fileName) => {
        let cssWriter = fs.createWriteStream('style.css', {
            flags: 'a'
        });

        fs.readFile(fileName, (error, data) => {
            if (error) {
                functions.logIt("The file cannot be found or is unreadable.", error);
            } else {
                try {
                    const dataJson = JSON.parse(data);
                    const breakpointMap = dataJson["breakpoints-map"]
                    delete dataJson["breakpoints-map"];
                    Object.entries(breakpointMap).forEach(([breakpointKey, breakpointValue]) => {
                        if (functions.isDefault(breakpointKey) == false) {
                            cssWriter.write("@media " + breakpointValue + " {\n");
                        }
                        Object.entries(dataJson).forEach(([mapKey, mapValues]) => {
                            let breakpoint = (functions.isDefault(breakpointKey) == true ? "" : breakpointKey + "\\:");
                            let property = functions.getProperty(mapKey);
                            Object.entries(mapValues).forEach(([classKey, classValue]) => {
                                cssWriter.write("." + breakpoint + classKey + "{ " + property + ": " + classValue + "}\n");
                            })
                        })
                        if (functions.isDefault(breakpointKey) == false) {
                            cssWriter.write("}\n");
                        }
                    })
                } catch (error) {
                    functions.logIt("The file could not be parsed to JSON.", error);
                }
            }
            cssWriter.end();
        });
    };

The isDefault function just checks whether the given parameter is equal to "default", in order to not put a media query around it.

The getProperty function just links the right CSS property depending on the map name (width-map => width, bg-repeat-map => background-position).


texts:
I was bored, and looking to do something that involved anonymous functions, and it was suggested by @Quill, that I create a summation function. I decided to also include a product function as well to top the whole thing off.

For those who don't know, a summation is usually defined like this:

  $$\sum_{n=a}^{b}f(n)$$

And a product is usually defined like this:

  $$\prod_{n=a}^{b}f(n)$$

I'd like to know the following things:

Am I doing this in a proper functional way?
Is there a way to reduce the repetitiveness of the code?
Is it okay to use List.fold to multiply all the elements of a list together? Is there a better way?
Am I violation any style guidelines?
Anything else?

Here's the code:

/// <summary>
/// Find the summation in a specific range, given
/// a specific function.
/// </summary>
let summation func low high =
    let function_result_set: int list = [for x in low..high do yield x |> func]
    let result = function_result_set |> List.sum
    result

/// <summary>
/// Find the product in a specific range, given
/// a specific function.
/// </summary>
let product func low high =
    let function_result_set: int list = [for x in low..high do yield x |> func]
    let result = function_result_set |> List.fold (*) 1
    result

And finally, here's a few tests:

[<EntryPoint>]
let main argv =
    System.Console.WriteLine(summation (fun n -> n) 1 10)
    System.Console.WriteLine(product (fun n -> n) 1 10)
    System.Console.ReadKey() |> ignore
    0

And here's the desired output from the above tests:

55
3628800


texts: Accessing list elements when counting the number of rectilinear paths

texts:
I am trying to solve the RIVALS problem on SPOJ: Starting from (0, 0), how many paths are there to reach point (X, Y), only taking one-unit steps moving to the right or up?  Constraints: 0 ≤ X ≤ 106, 0 ≤ Y ≤ 106, answer is to be given modulo (109 + 7).

I am facing a performance issue with accessing elements of a list. I am also facing a runtime error if I am trying to access the list element.

In order to get the nth element I am using [1,1,1,2]!!n, but I have been told that this runs in O(n) which is very slow.  Is there any other data structure in Haskell which gives O(1) access time for nth element?

About my algorithm: the number of way to move form (0,0) to (x,y) in 2D plain and answer is:

$$\frac{(x+y)!}{x!\ y!}$$

{-# LANGUAGE BangPatterns #-}
{-# OPTIONS_GHC -O2 #-}
import Data.List
import Data.Bits
import Data.Maybe
import Control.Monad
import qualified Data.ByteString.Char8 as C

seqI :: Integer -> Integer
seqI x = seq x x

seqB :: Bool -> Bool
seqB x = seq x x

modExp' :: Integer -> Integer -> Integer -> Integer -> Integer
modExp' r b p m = let nextR = seqI $ (seqI $ r*b)`rem` m
                      nextB = seqI $ (seqI $ b*b)`rem` m
                      nextP = seqI $ shiftR  p 1
                      incl  = seqB $ testBit p 0
                      cont  = seqB $ nextP  /= 0
                  in  if incl
                         then if cont
                                 then modExp' nextR nextB nextP m
                                 else nextR
                         else if cont
                                 then modExp' r     nextB nextP m
                                 else r

modExp :: Integer -> Integer -> Integer -> Integer
modExp b p m = modExp' 1 b p m

readInts :: IO [Int]
readInts = fmap (map read.words) getLine

read2Ints :: IO [Int]
read2Ints = do
     ints <- readInts
     if length ints == 2 then return ints else do
         putStrLn ("sorry, could you give me exactly two integers, "
                  ++ "separated by spaces?")
         read2Ints

p = 1000000007::Integer
ip = 1000000005::Integer
mtimes a b =  (a * b)`rem`p
facts = scanl mtimes 1 [1..2000001]

anstable ::[Integer]
anstable  =  facts

solve ::Int->Int-> Integer
solve x y = anstable!!(x+y)*(modExp (anstable!!x) ip p)*(modExp (anstable!!y) ip p)`rem`1000000007

main :: IO ()
main = do
    n <- readLn
    forM_ [1..n::Int] (\i -> do
       xs <- read2Ints
       print $(solve (head xs) (last xs)))


texts: Caesar Cipher that takes an arbitrary offset

texts:
This Caesar cipher can take any integer and it will wrap around the correct number of times and still perform the encryption/decryption.

Let's say we have a text file named dog.

  ~$ cat dog
  The quick brown fox jumps over the lazy dog...

If the user enters a normal offset (1-26), it will perform like any other Caesar cipher.

  ~$ ./caesar dog 1
  ~$ cat dog
  Uif rvjdl cspxo gpy kvnqt pwfs uif mbaz eph...

Negative numbers can be used to shift backwards.

  ~$ ./caesar dog -1
  ~$ cat dog
  The quick brown fox jumps over the lazy dog...

Now, here's the beauty of it. Choosing an offset of 1 is no different then choosing an offset of, say, 53 or -51. This algorithm will correctly wrap around.

  ~$ ./caesar dog -51
  ~$ cat dog
  Uif rvjdl cspxo gpy kvnqt pwfs uif mbaz eph...
  ~$ ./caesar dog 51
  ~$ cat dog
  The quick brown fox jumps over the lazy dog...

I wrote this a long time ago and I posted it on some other programming site back in the day. I haven't really written much pure c code since. I'm guessing there's plenty of room for improvement.

Compiles with:
gcc -ansi -pedantic -Wall -Werror -O3 -o caesar caesar.c

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

/* #define offset (-1) */ /* My chosen default offset */
#define lstart (0x61) /* Start of lowercase ASCII alphabet */
#define ustart (0x41) /* Start of uppercase ASCII alphabet */
#define nalpha 26 /* Number of letters in my alphabet */

int main(int argc, char **argv) {
    int ec, wrap, offset;
    FILE *fp;

    if (argc != 3) {
        fprintf(stderr, "Usage: %s <filename> <offset>\n", argv[0]);
        return 1;
    }

    fp = fopen(argv [1], "r+b");

    offset = atoi (argv[2]);

    if(!fp) {
        fprintf(stderr, "Error: could not open file!\n");
        return 1;
    }

    while((ec = fgetc(fp)) != EOF) {
        if(isalpha(ec)) {
            if(islower(ec)) {
                wrap = (ec + offset - lstart) % nalpha;
                wrap = (wrap < 0) ? nalpha + wrap : wrap;

            } else {
                wrap = (ec + offset - ustart) % nalpha;
                wrap = (wrap < 0) ? nalpha + wrap : wrap;
            }

            ec = islower(ec) ? wrap + lstart : wrap + ustart;

            fseek(fp, -1L, SEEK_CUR);
            fputc(ec, fp);
        }
    }

    fclose(fp);
    return 0;
}

Update: I will leave the code I originally posted above. Any modifications that I make will be posted below.

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define NALPHA (26)

int main (int argc, char **argv) {
    int ec, offset ;
    FILE *fp ;

    if (argc != 3) {
        fprintf(stderr, "Usage: %s <filename> <offset>\n", argv[0]);
        return 1;
    }

    fp = fopen(argv[1], "r+b");
    offset = atoi(argv[2]);

    if (!fp) {
        fprintf(stderr, "Error: Could not open file: %s\n", argv[1]);
        return 1;
    }

    while ((ec = fgetc(fp)) != EOF) {
        if (isalpha(ec)) {
            const int ascii_offset = islower (ec) ? 'a' : 'A';
            int wrap = (ec + offset - ascii_offset) % NALPHA;
            if (wrap < 0) {
                wrap += NALPHA ;
            }
            ec = wrap + ascii_offset;
        }

        fputc(ec, stdout);
    }

    fclose(fp);
    return 0;
}


texts: A program that performs logistic regression based on Iris dataset

texts:
I am a newcomer in Machine Learning and I have wrote a simple
program for logistic regression based on Iris dataset.
I would like for experts to tell me about its drawbacks and bugs, and if it can be implemented in easier ways.
#Loading data
import pandas as pd
df=pd.read_csv('file:///C:/Users/Desktop/iris.csv')
dftr=pd.read_csv('file:///C:/Users/Desktop/AI/iristr.csv')
dfts=pd.read_csv('file:///C:/Users/Desktop/AI/irists.csv')

#Normalizing data
from sklearn import preprocessing
from sklearn.preprocessing import StandardScaler
dfr=df.drop(df.columns[len(df.columns)-1], axis=1)
dfr=preprocessing.StandardScaler().fit(dfr).transform(dfr)
dfr=pd.DataFrame(dfr)

#Splitting data
Xtr=dftr.iloc[:,0:4].dropna()
Xts=dfts.iloc[:,0:4].dropna()
Ytr=dftr.iloc[:,4].dropna()
Yts=dfts.iloc[:,4].dropna()

#Defining classifier
from sklearn.linear_model import LogisticRegression
clf = LogisticRegression(penalty='l2', tol=0.0001, C=1.0, intercept_scaling=1, solver='newton-cg', max_iter=100, warm_start=False)

#Training
M=clf.fit(Xtr, Ytr)

#Predicting
Ytrpr=M.predict(Xtr)
Ytspr=M.predict(Xts)

#evaluation
from sklearn.metrics import accuracy_score
ACtr=accuracy_score(Ytr, Ytrpr)
ACts=accuracy_score(Yts, Ytspr)
print('ACtr=', ACtr)
print('ACts=', ACts)


texts:
Please suggest a way to optimize the below code. I want to reduce the execution time. This is a program to multiply using the shift operator.

import java.util.Scanner;

public class Test2 {

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

        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        long[] [] list=new long[N][2];
        for(int i=0;i<N;i++){
            list[i][0]=in.nextLong();
            list[i][1]=in.nextLong();
        }
        for(long[] s:list){
            System.out.println(calc(s[0], s[1]));
        }
    }

    public static String calc(long n1, long n2) {
        long temp, i = 0, result = 0;
        String s=null;
        while (n2 != 0) {
            if ((n2 & 1) == 1) {
                temp = n1;
                if(s==null){
                    s="("+i+"-"+i+") ";
                }else{
                    s=s+"("+i+"-"+i+") + ";
                }
                result += (temp<<=i);
            }
            n2 >>= 1;
            i++;
        }
        return s;
    }
}


texts: Adding push to array inside the class that is being pushed

texts:
I used to mostly do this:

class Person
  constructor : (@parent, @data)->
    @index = @parent.length

class People
  constructor : ->
    people = []

    for data in database.people
      people.push new Person(people, data)

Lately I have been trying the following:

class Person
  constructor : (@data)->

  pushTo : (list)->
    this.index = list.length
    list.push this

class People
  constructor : ->
    people = []

    for data in database.people
      person = new Person(data)
      person.pushTo people

So was wondering if there is any cons about doing it the second way. The reason I am asking is that it might not be the responsibility of Person to add himself to the list.


texts: Codility Frog Jump - Count minimal number of jumps from position X to Y

texts:
Here is a question I tried from the Codility train website:

  A small frog wants to get to the other side of the road. The frog is
  currently located at position X and wants to get to a position greater
  than or equal to Y. The small frog always jumps a fixed distance, D.
  Count the minimal number of jumps that the small frog must perform to
  reach its target.

  Write a function:

class Solution { public int solution(int X, int Y, int D); }

  that, given three integers X, Y and D, returns the minimal number of
  jumps from position X to a position equal to or greater than Y.

  For example, given:

  X = 10   Y = 85   D = 30

  the function should return 3, because the frog will be positioned as
  follows: after the first jump, at position 10 + 30 = 40 after the
  second jump, at position 10 + 30 + 30 = 70 after the third jump, at
  position 10 + 30 + 30 + 30 = 100

Assume that:
X, Y and D are integers within the range [1..1,000,000,000];
X ≤ Y.
Complexity:
expected worst-case time complexity is O(1);
expected worst-case space complexity is O(1).

This is the solution I gave which fetched me 50% and time complexity of O(Y-X). Can anyone please suggest a better solution?

class Solution {
//X=start, Y=end, D=distance for code clarity
public int solution(int start, int end, int distance) {

// write your code in Java SE 7
int progress = start;
int count=0;
while(progress<end) {
progress=progress+distance;
count++;
}
return count;
}
}


texts: Logging and getting the response in a controller

texts:
I have an action that does two things:

It sends a chain of commands, and gets the response from an external API that we call wrapper.
It logs the chain of commands and the tunnel (look at tunnels as different machines) the command was sent to.

My problem is the contents of the if statement. The two things (sending the command/getting the response, and logging the exchange) are happening in that if block, and they both need the chain and tunnel variables. I'd ideally want to have two functions, getResponseFromWrapper() and logCommandAndResponse(), effectively reducing the number of statements inside my if block to just two.

public function indexAction(Request $request)
{
    $response = '';
    $form = $this->createForm(new TerminalType());
    $form->handleRequest($request);

    if ($form->isValid()) {
        $data = $form->getData();
        $tunnel = $data['tunnel'];
        $chain = $data['chain'];

        $response = $this->retrieveResponseFromWrapper($chain, $tunnel);
        $this->get('command_logger')->log($chain, $tunnel, $response);
    }

    return $this->render('terminal/index.html.twig', [
        'title' => 'Terminal',
        'form' => $form->createView(),
        'response' => $response
    ]);
}

In other words, I feel like the three first lines in the if block are making it a bit more difficult for the reader to know what's happening.

Better code might be:

public function indexAction(Request $request)
{
    $response = '';
    $form = $this->createForm(new TerminalType());
    $form->handleRequest($request);

    if ($form->isValid()) {
        list($chain, $tunnel) = $this->extractChainAndTunnelFromForm($form);
        $response = $this->retrieveResponseFromWrapper($chain, $tunnel);
        $this->get('command_logger')->log($chain, $tunnel, $response);
    }

    return $this->render('terminal/index.html.twig', [
        'title' => 'Terminal',
        'form' => $form->createView(),
        'response' => $response
    ]);
}

This is much shorter. However, returning two values from a function leaves a bad taste in my mouth.

How can I improve the first code block and reduce the number of statements in the if block? Do I need to create something like a DTO (i.e. have my extractCommandAndTunnelFromForm() create a plain old PHP object and set the tunnel and chain as its properties)? Do I need to inject the commandLogger service into the service that sends commands to the wrapper, and remove logging from the controller entirely?


texts:
NOTE: See follow up to this question here

I created a simple python script to plot quadratic, cubic and quartic polynomials with integer coefficients between -4 and 4. It uses numpy to find the roots for the polynomials and matplotlib for the actual plotting of the points. Because I want to plot all possible polynomial with integer coefficients between -4 and 4 I figured I needed to do a recursive function with a loop. However if I'm not mistaken this will give a time complexity of \$O(n!)\$.

import matplotlib

# Use Qt4Agg because otherwise matplotlib crashes on my computer running Arch Linux
matplotlib.use('Qt4Agg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np

min_degree = 2
max_degree = 3
colours = []

def polynomial_scatter(ax, min_x, max_x, min_degree, max_degree, cur_degree, coeff):
    global colours

    if cur_degree <= max_degree:
        for c in range(min_x, max_x):
            new_coeff = coeff + [c]
            polynomial_scatter(ax, min_x, max_x, min_degree, max_degree, cur_degree + 1, new_coeff)
            if cur_degree >= min_degree:
                roots = np.roots(new_coeff)

                # check if no possible solution exists
                if len(roots) == 0:
                    continue

                # the real part of the roots will be our x values, the imaginary parts will be our y values
                x, y = zip(*[(t.real, t.imag) for t in roots])

                # scatter the roots for this polynomial with a colour corresponding to the degree of the polynomial
                ax.scatter(x, y, c=colours[cur_degree - max_degree], alpha=.5, s=1)

if __name__ == "__main__":
    f, ax = plt.subplots()
    colours = cm.rainbow(np.linspace(0, 1, max_degree - min_degree + 1))
    polynomial_scatter(ax, -4, 4, min_degree, max_degree, 0, [])
    plt.savefig("plot.svg", format="svg")
    plt.show()

Here are some pictures showing the result:

if I set max_degree to 5 it takes between 7-15 hours on my computer which is very long. Perhaps there is a way to implement multithreading.

How can I improve the performance of the polynomial_scatter algorithm?


texts: Find length of largest substring with unique characters

texts:
The below code scans a string and returns the length of the largest substring containing all unique characters.

I am iterating over the input string's characters and analyzing the longest unique charactered substring ending at the current character. By caching some info about the longest substring ending at the PREVIOUS characters, we can quickly make statements about this one.

I am not too concerned about the logic or runtime of this code, as I am only starting to get back into my interview prep. I am more concerned this code does not look "javascript" enough for more seasoned javascript developers. Coming from an OOP (Java, C#, typescript) background, I might be trying to force certain structures onto the code that might not be suitable.

let LongestSubstringNoRepeats = function (s) {
    let currSubstring = {
        length: 1,
        substring: s[0],
    }

    currSubstring.chars = {};
    currSubstring.chars[s[0]] = true;

    let currMax = 1;
    for (let i = 1; i < s.length; ++i) {

        if (currSubstring.chars[s[i]]) {
            //repeat character
            let substring = currSubstring.substring;
            let index = substring.indexOf(s[i]);
            substring = substring.slice(index + 1);
            newChars = {} ;
            substring.split("").map((char) => {
                newChars[char] = true;
            });
            currSubstring.substring = substring;
            currSubstring.chars = newChars;
            currSubstring.length = substring.length;

        } else {
            currSubstring.length++;
            currSubstring.substring = currSubstring.substring.concat(s[i]);
            currSubstring.chars[s[i]] = true;
        }

        if (currSubstring.length > currMax){
            currMax = currSubstring.length;
        }
    }
    return currMax;
}


texts: Check status of all child generations of medical claim

texts:
When a medical claim is replaced, it gets a new number. The older version is supposed to get cancelled out, but this doesn't always happen successfully yet at my workplace. I wrote this to try to aid in my research by automatically getting the entire tree of claims and their statuses.

However, it runs too slowly to be of much use in its current form. Is there an alternative approach I could take?

Current input:

  Claim1

  Claim2

  Claim3

Current Output:

TopLevel    Child       ChildStatus    Level
============================================================
Claim1      Claim11     Claim11Status   1
Claim1      Claim12     Claim13Status   2
Claim1      Claim13     Claim13Status   3
Claim2      Claim21     Claim21Status   1
Claim2      Claim22     Claim22Status   2
Claim3      Claim31     Claim31Status   1
Claim3      Claim32     Claim32Status   2
Claim3      Claim33     Claim33Status   3
Claim3      Claim34     Claim34Status   4

Current query:

if object_id('tempdb..#ClaimsToCheckForOriginals') is not null drop table #ClaimsToCheckForOriginals;

select ParentNum as TopLevel

into #ClaimsToCheckForOriginals

from Table2

where ParentNum in ();

with RekeysAllLevelsDeep as (

select
 a.TopLevel
,b.ParentNum as Rekey
,b.ChildNum as Original
,c.TsnSts as OrigTsnSts
,1 as RekeyLevel

from #ClaimsToCheckForOriginals a

join Table1 (nolock) b
    on a.TopLevel = b.ParentNum
    and b.ChildNum is not null
    and b.ChildNum <> b.ParentNum
    and b.ParentNum in (select * from #ClaimsToCheckForOriginals)
join Table2 (nolock) c
    on b.ChildNum = c.ParentNum

union all

select
 a.TopLevel
,b.ParentNum as Rekey
,b.ChildNum as Original
,c.TsnSts as OrigTsnSts
,RekeyLevel + 1

from RekeysAllLevelsDeep a

join Table1 (nolock) b
    on a.Original = b.ParentNum
    and b.ChildNum is not null
    and b.ChildNum <> b.ParentNum
join Table2 (nolock) c
    on b.ChildNum = c.ParentNum
)

select distinct
 TopLevel
,Original
,OrigTsnSts
,RekeyLevel

from RekeysAllLevelsDeep

order by TopLevel, RekeyLevel


texts: Script to unpack archives of various kinds

texts:
Just looking for some feedback and constructive criticism. This is the second script I ever made. Just recently started learning the basics. Anyway just wanted to post the script and see if maybe I can get some input on where I can maybe do things better.
The script is for extracting the compressed file types you run into the most on Linux. I added the option to extract to a directory of the user's choosing and not just keep it limited to only the working directory.
I feel like I have too many if/then statements and they can somehow be better but I'm not sure. And not sure if I Implemented the exits the right way. Some of you are probably gonna cringe when you see this lol! Anyway if you can help thanks.
#!/bin/bash

error() {
    echo "For help, type: nzip -h"
}

usage() {
    echo "Usage: nzip [FILE]..."
    echo "By default file(s) will be extracted to the working directory."
    echo
    echo "OPTIONS.."
    echo
    echo "-d, --directory, eg. nzip [file] [-d] [directory]"
    echo
    echo
}

if [ $# -eq 0 ]
then
    error >&2
    exit 1
fi

if [ $# -eq 1 ]
then
    case $1 in
        -h) usage
            exit 0
            ;;
        *.7z) 7z e "$1"
            ;;
        *.tar.bz2) tar xjvf "$1"
            ;;
        *.tar.gz) tar xzvf "$1"
            ;;
        *.rar) unrar e "$1"
            ;;
        *.tar) tar xvf "$1"
            ;;
        *.bz2) bunzip2 "$1"
            ;;
        *.tbz) tar xjvf "$1"
            ;;
        *.gz) gunzip "$1"
            ;;
        *.tgz) tar xzvf "$1"
            ;;
        *.jar) unzip "$1"
            ;;
        *.xz) tar xvf "$1"
            ;;
        *.zip) unzip "$1"
            ;;
        *.Z) uncompress "$1"
            ;;
        *) echo "No extraction option for $1" >&2
            exit 1
    esac
    exit 0
fi

if [ $# -eq 3 ] && [ "$2" = "-d" ]
then
    case $1 in
        *.7z) 7z e "$1" -o"$3"
            ;;
        *.tar.bz2) tar xjvf "$1" -C "$3"
            ;;
        *.tar.gz) tar xzvf "$1" -C "$3"
            ;;
        *.rar) unrar e "$1" "$3"
            ;;
        *.tar) tar xvf "$1" -C "$3"
            ;;
        *.bz2) bunzip2 "$1" -c > "$3"
            ;;
        *.tbz) tar xjvf "$1" -C "$3"
            ;;
        *.gz) gunzip "$1" -c > "$3"
            ;;
        *.tgz) tar xzvf "$1" -C "$3"
            ;;
        *.jar) unzip "$1" -d "$3"
            ;;
        *.xz) tar xvf "$1" -C "$3"
            ;;
        *.zip) unzip "$1" -d "$3"
            ;;
        *.Z) uncompress "$1" -c > "$3"
            ;;
        *) echo "No extraction option for $1" >&2
            exit 1
    esac
else
    error >&2
    exit 1
fi
```


texts:
I wrote a small function to return a random in a given range:

int random_in_range(int min, int max) {
    std::random_device rd;
    std::mt19937 rng(rd());
    std::uniform_int_distribution<int> uni(min, max);
    return uni(rng);
}

But I read somewhere that you should only seed a random number generator once leading me to believe that the function should really be:

std::random_device rd;
std::mt19937 rng(rd());
int random_in_range(int min, int max) {
    std::uniform_int_distribution<int> uni(min, max);
    return uni(rng);
}

I later tested both to see if one was clearly better than the other (in terms of randomness) and got results which do not make things any clearer.

First example result with 10 runs, making a decision of 1 or 0:

for (int i = 0; i < 10; i++) {
    cout << first_example(0, 1);
}
>0100100001

The second example result with 10 runs, making a decision of 1 or 0:

 for (int i = 0; i < 10; i++) {
    cout << second_example(0, 1);
}
>1011000110

The two results don't seem too strange leading me to be confused about how I should initialize random number generators.
Basically, what I am asking is: which of these two example (or something else if both are wrong) would be used in order to guarantee the lowest amount of bias?


texts:
We have a fair amount of code which looks like this:

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    if (part == null && newName == null) {
        return false;
    }
    if (part == null || newName == null) {
        return true;
    }
    return !part.getName().equals(newName);
}

That is, if the thing's current part is null and we're trying to set its name to null, that's not a change.  If the part is null or the name is null, but not both, that is a change.  And if neither is null, we have to look at it a little closer.

Thing and Part represent different entities for different such methods, so the first and final lines have the same general form but different specifics.

As written, this generates a SimplifiableIfStatement warning in Intellij, which would prefer to see it as:

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    return !(part == null && newName == null) && (part == null || newName == null || !part.getName().equals(newName));
}

Which is arguably simpler, but certainly not easier for me to read.  I can of course suppress the warning with @SuppressWarnings("SimplifiableIfStatement") but prefer to avoid that if possible.

I would like to find a way to extract this bit:

if (part == null && newName == null) {
    return false;
}
if (part == null || newName == null) {
    return true;
}

which is duplicated in all the instances of this code, because (a) it triggers the SimplifiableIfStatement warning and (b) it just seems too wordy to have it everywhere.  So far I've come up with this:

private Boolean changedFromNull(Object a, Object b) {
    // if both are null, nothing has changed.
    if (a == null && b == null) {
        return false;
    }
    // if only one is null, something has changed
    if (a == null || b == null) {
        return true;
    }
    // if neither is null, further analysis is required
    return null;
}

but that's arguably even worse, because now the calling code has to null-check the result of this method in addition to all the other null checking already going on.

private boolean isThingChanged(String newName, Thing thing) {
    final Part part = thing.getPart();
    final Boolean changedFromNull = changedFromNull(part, newName);
    return changedFromNull != null ? changedFromNull : !part.getName().equals(newName);
}

What's a good approach to this?


texts: Finding the number of perfect squares in an array

texts:
I am posting here for feedback about the code that I wrote to count the number of perfect squares in an array.

var arr = Array(4...17)
var count = 0
for i in arr{
  if Double(i).squareRoot().rounded() == Double(i).squareRoot(){
    count += 1
    }
}
print(count)

The result from the code is as expected. However, is this the "correct" way of doing? Or is there a "better" way of doing it? I did a coding test from a tech recruiting website (platform) and although the result is as expected, but the website gave me 0% on the "correctness" criteria and 0% overall mark.


texts:
I need to add logging functionality for an existing code, based on a result of an operation. I was thinking of creating a class that, when constructed, receives a condition function and a function for execution.  Based on the result of the condition, the code will be executed.

Example:

class auto_logger{

public:
auto_logger(const std::function<bool()>& cond,
            const std::function<void()>& func): _cond(cond), _func(func) {}

virtual ~auto_logger()
{
    try {
        if (_cond()) {
            _func();
        }
    } catch (...) {

    }
}

private:
    std::function<bool()> _cond;
    std::function<void()>  _func;
};

I will use this class like this:

int existing_func()
{
    int res = FAILURE;

    // this is the only additional code
    auto_logger logger([&](){
        return res == SUCCESS;
    },
    [](){
        print_to_log();
    });

    do_some_stuff_that_may_throw();

    res = perform_operation();

    return res;

}

I would be happy to get some comments on this code.  Are there any problem I am not seeing in this solution?  Are there any better solutions?


texts: Reducing the sorting time of a large number of numbers

texts:
I have to sort many large numbers in a given time limit. The program below works, but not when the test cases reaches \$10^6\$, in which case it exceeds the time limit.

def tsort(tests)
        sorted_array = []
        1.upto(tests) do
            input_num = gets.chomp.to_i
            sorted_array[input_num] = 1
        end
        #puts sorted_array.sort!
        sorted_array.each_index {|index| puts index if sorted_array[index] == 1}
    end

    test_cases = gets.chomp.to_i
    tsort(test_cases)

I wanted to ask if there was a better way to do this. Perhaps an algorithm will help me accomplish this.


texts:
I wonder if there are some possible ways to simplify my code.

startDate = '04/02/2014'
endDate = '04/06/2014'

mondayTag = 0
tuesdayTag = 0
wednesdayTag = 1
thursdayTag = 0
fridayTag = 1
saturdayTag = 0
sundayTag = 0

public int GetRemainingDays(DateTime startDate, DateTime endDate, bool mondayTag, bool tuesdayTag, bool wednesdayTag, bool thursdayTag, bool fridayTag, bool saturdayTag, bool sundayTag)
{
    int i = 0;
    for (DateTime day = startDate.AddDays(1); day.Date <= endDate.Date; day = day.AddDays(1))
    {
        if (day.DayOfWeek == DayOfWeek.Monday && mondayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Tuesday && tuesdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Wednesday && wednesdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Thursday && thursdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Friday && fridayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Saturday && saturdayTag == true)
        {
            i = i + 1;
        }
        else if (day.DayOfWeek == DayOfWeek.Sunday && sundayTag == true)
        {
            i = i + 1;
        }
    }
    return i > 0 ? i : 0;
}


texts: React components to render two kinds of form elements

texts:
I have two React components. The only difference is the input tag vs select tag. I'm trying to move the bulk of the duplicate code to a higher order component but I can't wrap my head around it. Any suggestions?

import React from "react";
import Style from "./style.scss";

export class FloatingLabelInput extends React.Component {
    render() {
        const { label, ...props } = this.props;
        const clsOK = props.value ? Style.ok : "";
        return (
            <div className={`${Style.wrapper}`}>
                <input className={`${Style.input} ${clsOK}`} ref={el => this.input = el} {...props} />
                <label className={`${Style.label}`} htmlFor={props.id}>{label}

        );
    }
}

export class FloatingLabelDropDown extends React.Component {
    render() {
        const { label, ...props } = this.props;
        const clsOK = props.value ? Style.ok : "";
        return (
            <div className={`${Style.wrapper}`}>
                <select
                    className={`${Style.input} ${clsOK}`}
                    ref={el => this.input = el} {...props} >
                    {this.props.children}
                </select>
                <label className={`${Style.label}`} htmlFor={props.id}>{label}

        );
    }
}


texts:
I tried this problem below and solved it in O(test_cases * string_length * pattern_length) complexity involving three nested loops.I want to know how can i further decrease time. I figured as much:

1:I'm comparing few patterns more than once.

2:Should find a way to not repeat the comparisons which i am unable to do.

The problem is as below:-

We are given a string S and a Pattern P. You need to find all matches of hash of P in string S. Also, print the index (0 based) at which the pattern's hash is found. If no match is found, print -1.

Note: All the matches should have same length as pattern P.

The hash of pattern P is calculated by summing the values of characters as they appear in the alphabets table. For reference, a is 1, b is 2, ...z is 26. Now, using the mentioned values, hash of ab is 1+2=3.

Input:

The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two lines of input. The first line contains the string S. The second line contains the pattern P.

Output:

For each testcase, in a new line, print the matches and index separated by a space. All the matches should be printed in their own separate lines.

Constraints:

1 <= T <= 100

1 <= |S|, |P| <= 105

Examples:

Input:

1
bacdaabaa
aab

Output:

aab 4
aba 5
baa 6

Explanation:

Testcase1:
 P is aab, and S is bacdaabaa
Now, the hash of P: aab is 1+1+2=4
In the string S, the hash value of 4 is obtained by the following:

aab=1+1+2=4, at index 4
aba=1+2+1=4, at index 5
baa=2+1+1=4, at index 6

My code in c++ :-

#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
long ind,j,test,kal;
cin>>test; //testcases' input//
for(ind=0;ind<test;ind++)
{
   long len1,len2,sum1=0,sum2=0;
   string s1,s2,s3;  //s1 for the input string,s2 for pattern,s3 to print the patterns that we find//
   cin>>s1>>s2;
   len1=s1.size();       //length of input string//
   len2=s2.size();       //length of pattern //
   for(j=0;j<len2;j++)
   {
       sum2=sum2+(int)s2[j]-96;   //doing the hash sum of pattern first so that i need not do pattern matching//
   }
   for(j=0;j<=len1-len2;j++)    //iterate len1-len2 times since we get those many distinct or duplicate patterns//
   {
       for(kal=j;kal<j+len2;kal++)  //iterate j+len2 times which is size of the pattern each time//
       {
           sum1=sum1+(int)s1[kal]-96; //updating the sum obtained//
           s3.push_back(s1[kal]);  //since we also need to print the pattern which has the hash sum//
       }
       if(sum1==sum2)        //if the sum matches print the string and starting index//
       cout<<s3<<" "<<j<<endl;
       s3.erase();           //clear the string for next testcase//
       sum1=0;               //clear the sum for next testcase//
   }
}
return 0;}

Please suggest changes that reduces the time.
Thanks for reading and any help will be a great favor .


texts:
Many times I have copy and pasted from a guide that had the following instruction:

$ echo "Execute xyz"

and would get the error

$: command not found

So I created a bash script to ignore the '$' at the beginning; The solution is as follows:

Put the below script in a file called '$'

vim $

Make it executable

chmod +x $

Add it to your bin

sudo cp $ /usr/bin/$

The script:
#!/bin/bash
eval $@


texts: Python traverse a directory recursively and print contact numbers

texts:
I am writing a python code to recursively traverse a directory containing only text files and then print the 10 digit Indian phone number and all its variants. I am very new to python and I have written the following code to print the numbers and this code is working fine. I want to know if there is any other better way to do this program so that the code looks better. Right now, I have used 3 nested for loops, I was wondering if I could reduce time complexity a bit. I am a beginner in python.

Contact_finder.py

import os, re

class ContactFinder:

    pattern = re.compile('^(?:(?:\+|0{0,2})91(\s*[\ -]\s*)?|[0]?)?[789]\d{9}|(\d[ -]?){10}\d$')

    def traverse(self,dir_path):
        for root, dirs, files in os.walk(dir_path):
            for file in files:
                filename = os.path.join(root, file)
                with open(filename) as fn:
                    for contact in fn:
                        if self.pattern.match(contact):
                            print contact

contact = ContactFinder()
contact.traverse('/home/sinscary/Documents/niki')

Please suggest me a better solution than this.


texts: TypeScript definitions for Server-Sent Events

texts:
I could not find any definitions of the EventSource object that belongs to Server-Sent Events, so I create the definitions. That's how they look like:

declare var EventSource : sse.IEventSourceStatic;

declare module sse {

    enum ReadyState {CONNECTING = 0, OPEN = 1, CLOSED = 2}

    interface IEventSourceStatic extends EventTarget {
        new (url: string, eventSourceInitDict?: IEventSourceInit);
        url: string;
        withCredentials: boolean;
        CONNECTING: ReadyState; // constant, always 0
        OPEN: ReadyState; // constant, always 1
        CLOSED: ReadyState; // constant, always 2
        readyState: ReadyState;
        onopen: Function;
        onmessage: (event: IOnMessageEvent) => void;
        onerror: Function;
        close: () => void;
    }

    interface IEventSourceInit {
        withCredentials?: boolean;
    }

    interface IOnMessageEvent {
        data: string;
    }
}

Also available on GitHub.

I am new to TypeScript so I wonder if this definition is OK with common best practices and whether it could be improved.


texts:
I am working through Programming Fundamentals with Python on Udacity. The assignment was to create a recursive triangle. I am happy with the output, but I am hoping for feedback on the actual construction of the program. Could I have done this in a more simple and concise way?

import turtle

def draw_polygon(a_turtle, length, sides):
    counter = 0
    while (counter < sides):
        a_turtle.forward(length)
        a_turtle.right(360 / sides)
        counter = counter + 1

def draw_triangle(a_turtle, length):
    draw_polygon(a_turtle, length, 3)

def draw_fractal_triangle(a_turtle, length, depth):
    if (depth == 1):
        draw_triangle(a_turtle, length)
    else:
        for i in range(1,4):
            draw_fractal_triangle(a_turtle, length/2, depth-1)
            a_turtle.forward(length)
            a_turtle.right(120)

def draw():
    window = turtle.Screen()
    window.bgcolor("black")

    brent = turtle.Turtle()
    brent.shape("turtle")
    brent.color("yellow")

    length = 200
    brent.backward(length/2)
    draw_fractal_triangle(brent, length, 5)
    window.exitonclick()

draw()

```


texts: Python pattern searching using re standard lib, str.find()

texts:
I'm trying to improve some code in order to get a better perfomance, I have to do a lot of pattern matching for little tags on medium large strings, for example:

import re
STR = "0001x10x11716506872xdc23654&xd01371600031832xx10xID=000110011001010\n"

def getID(string):
    result = re.search('.*ID=(\d+)', string)
    if result:
        print result.group(1)
    else:
        print "No Results"

Taking in mind the perfomance I rewrite it:

def getID2(string):
    result = string.find('ID=')
    if result:
        result += 3
        print string[result:result+15]
    else:
        print 'No Results'

Are there a better way to improve these approaches?
Any comments are welcome...


texts:
Newton's method for finding cube roots states that for any given \$x\$ and a guess \$y\$, a better approximation is \$\dfrac{(\dfrac{x}{y^2} + 2y)}{3}\$.

What do you think of this code for finding a cube root in Scheme?

(define (improveguess y x)
  ; y is a guess for cuberoot(x)
  (/ (+ (/ x (expt y 2)) (* 2 y)) 3))

(define (cube x) (* x x x))

(define (goodenough? guess x)
  (< (/ (abs (- (cube guess) x)) guess) 0.0001))

(define (cuberoot x) (cuberoot-iter 1.0 x))

(define (cuberoot-iter guess x)
  (if (goodenough? guess x) guess
      (cuberoot-iter (improveguess guess x) x)))


texts: Calculate the total items used, if for every x items used, you get one additional item to use

texts:
I am looking for a way to optimize this code so that it runs faster. I am trying to calculate the total items used, if for every x items used, you get one  additional item to use.

This is the code I currently have. I get the correct result, but with a large amount of items, it is taking too long to calculate.

public static int TotalItems(int startingTotalItems, int newItemInterval)
{
    int itemsUsed = 0;
    int itemsUsedThisInterval = 0;
    int totalItems = startingTotalItems;

    while (totalItems > 0)
    {
        totalItems--;
        itemsUsed++;
        itemsUsedThisInterval++;
        if (itemsUsedThisInterval == newItemInterval)
        {
            totalItems++;
            itemsUsedThisInterval = 0;
        }
    }
    return itemsUsed;
}

public static void Main(string[] args)
{
    Console.WriteLine(TotalItems(3, 2));
}

Console output: 5

//-- psudo
// Start with 3 items
// Use 2 items
// Now I have 1 item plus I get 1 new additional item, giving a total of 2 items
// Use 2 items
// Now I have 0 items but since I used another 2 items, I get 1 more new additional item
// Use 1
// I have used a total of 5 items - Thisis the result
//--

I think the issue is the use of the while loop. I would think that there would be an efficient algorithm I could apply for this but but, so far, I have not had any luck finding one.

What my boss is saying is "Your code took too long to calculate an answer. Analyze how your code behaves when the input increases in size and see if you can make it work faster."


texts:
I have millions of files in a folder. File types will be with the name PES_timestamp and DOM_timestamp. I have to aggregate all PES and DOM filenames into one file which has the same filename.

The Aggregator program picks up only matching PES and DOM file pairs based on the timestamp of the file name from the incoming folder.

Example:

pes234343440
dom234343440

I thought of this idea to create 3 lists:

Holds all files in the folder
Holds only PES files
Holds all DOM files

Finally, I will read all the file name from list and aggregate them from this program:

public void mergeFiles(File output,List<String> list) throws IOException {
        BufferedWriter writer=null;
        BufferedReader br = null;
        BufferedReader r = null;
        try {
        writer = new BufferedWriter(new FileWriter(output));
        for(int i=0;i<list.size();i++){
              br = new BufferedReader(new FileReader("INCOMINGFOLDER/"+list.get(0)));
              AggregateNj obj=new AggregateNj();
              String s1 =null;
                while ((s1 = br.readLine()) != null) {
                    writer.write(s1);
                    writer.write("\n");
                }
            }
        } catch (IOException e){
            e.printStackTrace();
        }finally{
            if(br != null)br.close();
            if(r != null)r.close();
            if(writer != null)writer.close();
        }
    }

Is this approach correct, or can you suggest a better approach?


texts: Scan a spatio-temporal cube and run a cross-correlation on it

texts:
I have a nested for-loop that looks like the following. The for-loop is used to scan a spatio-temporal (3D) cube and run a specific kind of cross-correlation used in seismology.
# some initialization
i,j,k = np.where(Pg1t > 0.1)
qp = np.sum(Pg1t[:-1,20:40,20:40],axis = 1)/20

corr_arr_x = np.zeros((1750,384,384))
corr_arr_y = np.zeros((1750,384,384))

# for-loop starts
for ii in range (0,1): # this range will actually go (0,1750)
    for jj in range (31,351):
        for kk in range (31,351):
            pulse_2d = np.zeros((39,63,63))
            pulse_2d[i,j,k] = Pressure[ii + i, jj - 31 + j, kk -31 + k]
            corr_arr_x[ii,jj,kk] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 2),qp))
            corr_arr_y[ii,jj,kk] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 1),qp))

Ofcourse this is not very smart way to do it and it takes 1 minute and 36 seconds to be executed. This means, if I select the first loop to run for (0 to 1750), then it will take around 40 hours or more. So I tried the itertools.
for x in itertools.product(np.linspace(0,1,1,dtype = 'int'), np.linspace(31,351-1,351-31,dtype = 'int'), np.linspace(31,351-1,351-31,dtype = 'int')):
    pulse_2d = np.zeros((39,63,63))
    pulse_2d[i,j,k] = Pressure[x[0] + i, x[1] - 31 + j, x[2] -31 + k]
    corr_arr_x[x[0],x[1],x[2]] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 2),qp))
    corr_arr_y[x[0],x[1],x[2]] = np.max(signal.correlate(np.sum(pulse_2d[:,20:40,20:40],axis = 1),qp))

However, this takes about 1 minute 27 seconds to be executed. Not a great improvement, may save an hour at best!
Is there any way to parallelize this code or optimize in any other way so that the execution time can be significantly decreased?


texts:
I need to write some JavaScript code that will take a JSON string, parse it, and return the names of the most-deeply nested properties. For example, for this input:

var json =
"{\
foo: {\
  bar: 'something',\
  baz: {\
    jack: 'other',\
  },\
  bob: {\
    bill: 'hello',\
    bilbo: 11,\
      baggins: {\
        fizz: 'buzz'\
        finger: 'bang'\
      }\
    }\
  }\
}";

it should return ['fizz', 'finger']. There are a couple of caveats:

the parsing must be done "manually"- i.e. I can't use eval or a JS library to parse the JSON
the JSON property values are guaranteed to be strings, numbers, or objects, i.e. no arrays

Here's what I've come up with so far. The main function is findDeepestLeaveNodes. At the moment the code is a bit inefficient as it has to iterate twice over the whole input String. I'd like to improve this if possible, and am also looking for suggestions for improving the code quality.

var constants = {
    BLOCK_START: '{',
    BLOCK_END: '}'
};

function findDeepestLeaveNodes(json) {

    var maxNesting = getMaxNesting(json);
    var currentNestLevel = 0;
    var results = [];
    var jsonLength = json.length;

    for (var currentCharIndex = 0; currentCharIndex < jsonLength; currentCharIndex++) {
        var currentChar = json.charAt(currentCharIndex);
        //console.log("Nesting level " + currentNestLevel + " at character '" + currentChar + "'");

        if (currentChar == constants.BLOCK_START) {

            // FIXME The following parsing is fairly fragile. It doesn't handle the possibility
            // that a '}' or ',' way occur inside a String and therefore do always close a block or
            // separate sibling JSON properties. To handle this we'd need to write a proper JSON parser.
            if (++currentNestLevel == maxNesting) {
                // read the content of the current block
                var blockEndIndex = json.indexOf(constants.BLOCK_END, currentCharIndex);
                var currentBlock = json.substring(currentCharIndex + 1, blockEndIndex);

                // Each position in the properties array will contain a property name and it's value
                var properties = currentBlock.split(',');

                for (var i = 0; i < properties.length; i++) {
                    // parse out the property name
                    var property = properties[i];
                    var separatorPosition = properties[i].indexOf(':');
                    var propertyName = property.substring(0, separatorPosition);

                    results.push(propertyName.trim());
                }
            }
        } else if (currentChar == constants.BLOCK_END) {
            --currentNestLevel;
        }
    }
    return results;
}

function getMaxNesting(json) {
    var jsonlength = json.length;
    var currentNestLevel = 0;
    var maxNestLevel = 0;

    for (var i = 0; i < jsonlength; i++) {
        var currentChar = json.charAt(i);

        if (currentChar == constants.BLOCK_START) {
            ++currentNestLevel;

        } else if (currentChar == constants.BLOCK_END) {
            // update maxNestLevel if necessary
            maxNestLevel = Math.max(currentNestLevel, maxNestLevel);
            --currentNestLevel;
        }
    }
    return maxNestLevel;
}


texts: LeetCode 76: Minimum Window Substring - Python

texts:
I'm posting a two-pointer, sliding-window problem of LeetCode (Minimum Window Substring) solved with Python. If you have time and would like to review the code, please do so, I appreciate that.
On LeetCode, we are only allowed to change the variable names and brute force algorithms are discouraged, usually fail with TLE (Time Limit Error) or MLE (Memory Limit Error).
Problem

Given a string base_string and a string target, find the minimum window
in base_string which will contain all the characters in target in
complexity O(n).
Example:
Input: base_string = "ADOBECODEBANC", target = "ABC" Output: "BANC"
Note:
If there is no such window in base_string that covers all characters in
target, return the empty string "". If there is such window, you are
guaranteed that there will always be only one unique minimum window in
base_string.

Solution 1
import collections

class Solution:
    def minWindow(self, base_string: str, target: str) -> str:
        count_map = collections.Counter(target)
        left = 0
        min_left, min_right = 0, 0
        target_length = len(target)

        for right, char in enumerate(base_string, 1):
            target_length -= count_map[char] > 0
            count_map[char] -= 1
            if not target_length:
                while left < right and count_map[base_string[left]] < 0:
                    count_map[base_string[left]], left = -~count_map[base_string[left]], -~left
                if not min_right or right - left <= min_right - min_left:
                    min_left, min_right = left, right

        return base_string[min_left:min_right]

Solution 2
import collections

class Solution:
    def minWindow(self, base_string: str, target: str) -> str:
        count_map = collections.Counter(target)
        left, right = 0, 0
        min_left, min_right, min_window = 0, float('inf'), ''
        target_length = len(target)

        while right < len(base_string):
            if count_map[base_string[right]] > 0:
                target_length -= 1

            count_map[base_string[right]] -= 1

            while target_length == 0:
                sliding_window = -~right - left

                if not min_window or sliding_window < len(min_window):
                    min_window = base_string[left:-~right]

                count_map[base_string[left]] += 1

                if count_map[base_string[left]] > 0:
                    target_length += 1
                left += 1
            right += 1

        return min_window

Reference

Question

Solution

Discussion


texts: Segment Intersection — Failing on Unknown Edge Cases

texts:
I was recently at a programming competition. One of the problems was to determine whether two line segments are parallel, intersect, or do not intersect.

For all of the test cases I ran, my solution worked. However, when I submitted it, it was rejected (but no other information was given). I suspect there is either some edge case I am completely missing... or perhaps the judges messed up.

Input is entered as follows:

ax ay bx by cx cy dx dy

where the first segment is given by $$(a_x, a_y), (b_x, b_y)$$ and the second by $$(c_x, c_y), (d_x, d_y)$$

Some other rules/assumptions:

We may assume that no segment has length zero; that is, each segment has distinct endpoints.
Segments may share endpoint(s) with the other segment. Endpoints are included in the segment and thus are able to intersect (this also means that a segment whose endpoint lies within the other segment will intersect)
Lines which both intersect and are parallel (either partial or complete overlap) should be considered parallel.
All coordinates are integers on the open interval (-1000, 1000).

Here's a screenshot of the problem. Note that I'm ignoring the multiple tests option because I highly doubt that was the issue.

import java.util.Scanner;

public class QP1505
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);

        int ax = in.nextInt();
        int ay = in.nextInt();
        int bx = in.nextInt();
        int by = in.nextInt();
        int cx = in.nextInt();
        int cy = in.nextInt();
        int dx = in.nextInt();
        int dy = in.nextInt();

        in.close();

        /*
         * Cross multiply to check equal slopes This takes care of
         * +/- infinity as well as zero
         */
        if ((by - ay) * (dx - cx) == (dy - cy) * (bx - ax))
        {
            System.out.println("PARALLEL");
        }
        else
        {
            double m1 = (double) (by - ay) / (bx - ax);
            double m2 = (double) (dy - cy) / (dx - cx);

            // Find point of intersection
            double x, y;
            if (Double.isInfinite(m1))
            {
                x = ax;
                y = m2 * (x - cx) + cy;
            }
            else if (Double.isInfinite(m2))
            {
                x = cx;
                y = m1 * (x - ax) + ay;
            }
            else
            {
                x = (m1 * ax - ay - m2 * cx + cy) / (m1 - m2);
                y = m1 * (x - ax) + ay;
            }

            // Check bounds
            if (((x >= ax && x <= bx) || (x <= ax && x >= bx))
                    && ((y >= ay && y <= by) || (y <= ay && y >= by))
                    && ((x >= cx && x <= dx) || (x <= cx && x >= dx))
                    && ((y >= cy && y <= dy) || (y <= cy && y >= dy)))
            {
                System.out.println("INTERSECT");
            }
            else
            {
                System.out.println("DO NOT INTERSECT");
            }
        }

    }
}

And some test cases:

Vertical Horizontal, Intersect

0 0 0 5 -1 2 1 2
INTERSECT

Vertical Horizontal, No Intersect

0 0 0 5 1 2 4 2
DO NOT INTERSECT

Horizontal Horizontal, Parallel

0 0 5 0 1 1 5 1
PARALLEL

Vertical Regular, Intersect

0 0 0 5 1 0 -1 4
INTERSECT

Vertical Regular, No Intersect

0 0 0 5 1 0 4 6
DO NOT INTERSECT

Horizontal Regular, Intersect

4 4 7 4 4 3 6 5
INTERSECT

Horizontal Regular, No Intersect

2 2 8 2 3 3 9 6
do not intersect

Regular Regular, Intersect

2 1 4 3 1 2 5 1
INTERSECT

Regular Regular, Parallel

1 2 5 6 3 2 5 4
PARALLEL

Regular Regular, No Intersect

1 2 5 6 3 2 8 5
DO NOT INTERSECT

Let me know if anything else needs to be clarified (or any other test cases).


texts:
I am learning to write test cases in iOS using Swift. I was stuck at testing static functions from my Utilities class, so I tried to mock that class and then test the cases. Please let me know if its the correct approach or else tell me how to do that. Here is my code:

import XCTest
@testable import ConnectAndSell

class UtilitiesMock{
    func getBuildNumber() -> String{
        return Utilities.getAppBuildNumber()
    }
    func getVersionNumber() -> String{
        return Utilities.getAppVersion()
    }
}

class UtilitiesTests: XCTestCase {
    //system under test
    var sut:UtilitiesMock!

    override func setUp() {
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
        sut = UtilitiesMock()
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
        sut = nil
    }

    func testBuildNumber() {
        let buildNumber = Bundle.main.infoDictionary?["CFBundleVersion"] as! String
        XCTAssertEqual(buildNumber, sut.getBuildNumber())

    }

    func testVersionNumber() {
        let versionNumber = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as! String
        XCTAssertEqual(versionNumber, sut.getVersionNumber())
    }

}

EDIT: Adding Utilities class so that you guys can see what am I trying to test. It's just simple functions to verify the current build number and version number. I have taken these function just for example. My main aim is to know is it the correct approach to test static methods.

import Foundation

class Utilities {

    static func getAppVersion() -> String {
        if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            log.debug("App verison: \(version)")
            return version
        }
        return ""
    }
    static func getAppBuildNumber() -> String {
        if let number = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
            log.debug("Build number: \(number)")
            return number
        }
        return ""
    }

}


texts:
I have recently adjusted the way I create my mysqli connections. Initially I would include the connection file and use if($mysqli->connect_error)... in my main script. Now I check if there is an issue with the connection within the connection file. If there isn't an issue then I just check that the variable name for the connection is set. Before I continue I'm curious if there are any issues with the way I am doing this and if it goes against any 'best-practices'.
The contents of my connection file: (connect_db_login.php)
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try{
    $test = new mysqli('localhost:3306','login','password','testdb');
    $test->set_charset('utf8');
}catch(Exception $e){ //$e not used; dead code?
    echo('<script> alert("Connection to database failed!");</script>');
    header("refresh:0; url=../login.php"); //using refresh because location doesnt wait for script
}

Checking that the connection has been made in main script:
<?php
    include('../connect_db_login.php'); // using include not require
    if(isset($test)){
    ...


texts: Find largest two numbers from list using clojure

texts:
I'm trying to write a function that finds the largest two numbers from a list of positive integers in Clojure.

I've toyed around with Scheme in the past, but I'm very new to Clojure. This is what I came up with:

; Accumulator function for reduce later
(defn top-two [acc x]
  (let [big1 (first acc) big2 (second acc)]
    (cond
      (> x big1) [x big1]
      (> x big2) [big1 x]
      :else acc)))

(defn top-two-list [coll]
  (reduce top-two [0 0] coll))

This works, but I'm wondering if there is a way to simplify the top-two function, or to make this more readable or idiomatic.

This could be done much simpler if I was willing to sort the entire list, but I'm looking for an O(n) solution.

Any thoughts?


texts: Using atom to reference state in Clojure

texts:
I am trying to implement a 2D fighting game in Clojure both for fun and learning.

Since the characters in a fighter game are essentially state machines, I constructed the following code:

(defrecord Frames [frames id])

where "frames" refer to the actual datas (hitboxes texture-names and etc) and "id" will be an atom referencing the "frames" data representing the current frame the character is in.

so I will initialize a frame like this (used :a :b :c just for testing):

(def f (Frames. [:a :b :c :d :e :f :g] (atom 0)))

and will retrieve the current frame by this:

(defn get-current-frame [frames] (nth (:frames frames) @(:id frames)))

and update by:

(defn update-current-frame [frames active] (reset! (:id frames) active))

and it works fine:

(def f (Frames. [:a :b :c :d :e :f :g] (atom 0)))
(update-current-frame f 3)
(get-current-frame f) ;; => :d

Obviously it works, but I am extremely in doubt that this is a good practice.

Due to my poor knowledge with Clojure, I am here asking

Is using atom referencing a vector the best way for representing simple states?
Should I use this kind of data structure for implementing fighting game frames?
If ignoring data structures, am I defining the functions (get-current-frame) and (get-current-frame) in an idiomatic way?


texts: My code for a LocalBinaryPatern in python is running very slow. Any tips?

texts:
My code for a LocalBinaryPatern in python is running very slow. I tried optimizing it with tips from online. I'am still getting used to python, and programming in General so any tips are very welcome! Here is the code:
def localbinarypattern(image, radius=2):
    h, w = image.shape
    if radius == 1:
        return 0
    else:
        abase = math.pi/4
        xshift, yshift = [0 for _ in range(8)], [0 for _ in range(8)]

        for i in range(8):
            xshift[i] = - radius * sin(i*abase)
            yshift[i] = radius * cos(i*abase)

        feat = [0 for _ in range(255)]
        lbp = [0 for _ in range(8)]
        base = [1, 2, 4,8, 16, 32, 64, 128]
        for y in (range(radius, (h-radius))):
            for x in (range(radius, (w-radius))):
                lbp = [0 for _ in range(8)]
                for i in range(8):
                    cx = xshift[i]+x
                    cy = yshift[i]+y
                    ry = int(cy+0.5)
                    rx = int(cx + 0.5)

                    if image[ry][rx] > 0:
                        lbp[i] = 1

                bits = 0
                for i in range(8):
                    bits += int(lbp[i]*base[i])

                if bits < 255:
                    feat[bits] += 1

        sum_lbp = 0
        for i in range(len(feat)):
            sum_lbp += feat[i]
        if sum_lbp ==0:
            print ("warning: the sum of LBP feature is zero!\n")
        else:
            for i in range(len(feat)):
                feat[i] /= sum_lbp
        return feat


texts: Function that Loads a Random Image from an Array

texts:
I'm new to PHP and had to put together a function that loads a random image from an array (it works fine). Here's what I came up with. Could it be improved? Any feedback would be appreciated.

<?php
function displayRandomPhotoArea() {
    $photoAreas = array("imageURL1", "imageURL2", "imageURL3", "imageURL4", "imageURL5");

    $randomNumber = rand(0, (count($photoAreas) - 1));

    echo '<img src="' . $photoAreas[$randomNumber] . '" width="725" height="194">';
}

// Display a random image here
displayRandomPhotoArea();
?>