texts: Tower of Hanoi Recursive Implementation using Python with OOP

texts:
I have just finished a small program for Tower of Hanoi using recursion. I did it to practice OOP which I recently learnt. It took me about 2 hours to research about the recursive algorithm and write out the code. It works, after much debugging... However, after comparing to other implementations, I realised my code is rather long, plus unconventional when it comes to how I approach and execute as well as the naming conventions.

Could I have some feedback about the program? Thank you!

class rod:
    move_count = 0

    def __init__(self,disks=[],position=""):
        self.diskslist=disks
        self.rod_position=position
    # Remove the top disk of a rod
    def remove_top(self):
        print(f"Move the disk of size {self.diskslist[0].size} from {self.rod_position} Rod ", end="")
        rod.move_count += 1
        return self.diskslist.pop(0)
    # Add a disk to the top of a rod. Only allows in two conditions a. No disks currently on that rod b. Disk smaller than the disk below it
    def add_to_top(self,current_disk,announce=True):
        if len(self.diskslist) == 0:
            if announce==True:
                print(f"on to the top of the {self.rod_position} Rod", end="\n")
            self.diskslist.insert(0,current_disk)
            return True
        else:
            if current_disk.size < self.diskslist[-1].size:
                if announce == True:
                    print(f"on to the top of the {self.rod_position} Rod", end="\n")
                self.diskslist.insert(0,current_disk)
                return True
            else:
                return False

class disk:
    num=0
    def __init__(self,size):
        self.size=size
        disk.num += 1

#Generating 8 disks of increasing size
disk_num=8
disks = []
for i in range(disk_num):
    disks.append(disk(i))

#Generating 3 rods
rods = []
rods.append(rod([],"Left"))
rods.append(rod([],"Middle"))
rods.append(rod([],"Right"))

# Attaching all disks to the left rod
for i in range(len(disks)):
    rods[0].add_to_top(disks[len(disks)-i-1],False)

def recursive_solve(current_rod, lower_range, target_rod):
    # If only moving the top disk, execute it
    if lower_range == 0:
        rods[target_rod].add_to_top(rods[current_rod].remove_top())
    # If not, keeping simplifying the recursion.
    else:
        alt_rod = 3 - current_rod - target_rod
        recursive_solve(current_rod, lower_range - 1, alt_rod)
        recursive_solve(current_rod, 0, target_rod)
        recursive_solve(alt_rod, lower_range - 1, target_rod)

print(f"The steps needed to move {disk_num} pieces of disks are:")
recursive_solve(0,len(disks)-1,2)

for i in range(len(rods)):
    print(f'\n For rod number {i+1}:',end=" ")
    for j in range(len(rods[i].diskslist)):
        print(rods[i].diskslist[j].size,end=" ")

print(f'\n The number of moves taken in total is {rod.move_count}')


texts: Solving "Quadruple sum" problem using dynamic programming

texts:
I am trying to learn dynamic programming using hash table. I was given this the "Quadruple sum" problem from firecode.io as a challenge:

  Given a sorted array of integers and an integer target, find all the unique quadruplets which sum up to the given target.

  Note: Each quadruplet must have elements (input[i], input[j], input[k], input[l]), such that \$i < j < k < l\$. The ordering of unique quadruplets within the output list does not matter.

  Examples:

Input : [1,2,3,4,5,6,7,8]
Target: 10
Output: [(1, 2, 3, 4])]

Input : [1,2,3,4,5,6,7]
Target: 20
Output: [(2, 5, 6, 7), (3, 4, 6, 7)]

solution #1

def all_sums(xs):
    dict = {}
    l = [[(i,j) for i in range(len(xs)) if i < j] for j in range(len(xs))]
    pairs = [item for sublist in l for item in sublist]
    for i,j in pairs:
        if xs[i]+xs[j] not in dict:
            dict[xs[i]+xs[j]] = set()
        dict[xs[i]+xs[j]].add((i,j))
    return dict

def iquadruple_sum(xs, target):
    sums = all_sums(xs)
    for s, positions in sums.items():
        for (k,l) in positions:
            if target - s in sums:
                for (i,j) in sums[target - s]:
                    if len({i,j,k,l}) == 4: yield sorted((xs[i],xs[j],xs[k],xs[l]))

def quadruple_sum(xs, target):
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))

\$O(n^4)\$ in the worst case (if the array is mostly complementary). It also takes \$O(n^2)\$ space, vs \$O(n)\$. The worst case is unlikely though.

Alternative solution #2

#
def all_sums(xs):
    "Returns dictionary of all possible ordered sums in O(n^2) time and space."
    from collections import defaultdict
    from itertools import product
    d = defaultdict(set)
    pairs = ((i,j) for (i,x),(j,y) in product(enumerate(xs), enumerate(xs)) if i<j)
    for i,j in pairs: d[xs[i]+xs[j]].add((i,j))
    return d

def iquadruple_sum(xs, target):
    sums = all_sums(xs)
    for s, positions in sums.items():
        for (k,l) in positions:
            for (i,j) in sums[target - s]:
                if len({i,j,k,l}) == 4: yield sorted((xs[i],xs[j],xs[k],xs[l]))

def quadruple_sum(xs, target):
    return list(set(tuple(x) for x in iquadruple_sum(xs, target)))


texts: Modifying the response object for creating and downloading a document

texts:
I've been looking at some code done in C# ASP .NET WebForms and for some reason I really don't like the below code. What is the best alternative for creating a document and downloading it in Webforms, on the click of a button? Should the developer be messing with the Response at all, in this way?

Response.ClearContent();
Response.BufferOutput = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", string.Format("attachment; filename={0:yyyyMMdd}.xlsx", DateTime.Now));
Response.BinaryWrite(pck.GetAsByteArray());
Response.Flush();
Response.End();


texts:
I'm very new to Neo4J, and to Jaccard similarity (weighted or non!), so I'd really appreciate someone casting an eye over my code here before I try to use the results.

Jaccard similarity for 2 sets is:

$$
J(A,B) = \frac{\vert A \cap B \vert}{\vert A \cup B \vert}
= \frac{\vert A \cap B \vert}{\vert A \vert + \vert B \vert - \vert A \cap B \vert}
$$

I calculate that in Neo4j like this:

MATCH (w:Word{toProcess: True})

MATCH (w)-[:NEXT_WORD]->(right:Word), (o:Word)-[:NEXT_WORD]->(right) WHERE w <> o
WITH w, o, count(distinct right.name) as intersection
MATCH (all:Word) WHERE (w)-[:NEXT_WORD]->(all) OR (o)-[:NEXT_WORD]->(all)
WITH w, o, toFloat(intersection)/toFloat(count(distinct all.name)) as rightJaccard

MATCH (w)<-[:NEXT_WORD]-(left:Word), (o)<-[:NEXT_WORD]-(left) WHERE w <> o
WITH w, o, rightJaccard, count(distinct left.name) as intersection
MATCH (all:Word) WHERE (w)<-[:NEXT_WORD]-(all) OR (o)<-[:NEXT_WORD]-(all)
WITH w, o, rightJaccard, toFloat(intersection)/toFloat(count(distinct all.name)) as leftJaccard

RETURN w, o, (rightJaccard + leftJaccard)/2.0 as paradig

(Weighted Jaccard is described here.)

$$
J(x, y) =
\frac{\sum_i{\min(x_i,y_i)}}{\sum_i{\max(x_i,y_i)}}
$$

I think this code (adapted from the basic Jaccard above) calculates the weighted Jaccard:

MATCH (w:Word{toProcess: True})
MATCH (w)-[rw:NEXT_WORD]->(right:Word), (o:Word)-[ro:NEXT_WORD]->(right)
WHERE w <> o
WITH w, o, sum(min(rw.weight, ro.weight)) as intersection
MATCH (all:Word) WHERE (w)-[rw1:NEXT_WORD]->(all) AND NOT (o)-[:NEXT_WORD]->(all)
WITH w, o, intersection, sum(rw1.weight) as wSum
MATCH (all:Word) WHERE (w)-[:NEXT_WORD]->(all) AND NOT (o)-[ro1:NEXT_WORD]->(all)
WITH w, o, toFloat(intersection)/toFloat(wSum + sum(ro1.weight) - intersection) as rightJaccard

MATCH (w)<-[rw:NEXT_WORD]-(left:Word), (o)<-[ro:NEXT_WORD]-(left)
WHERE w <> o
WITH w, o, sum(min(rw.weight, ro.weight)) as intersection
MATCH (all:Word) WHERE (w)<-[rw1:NEXT_WORD]-(all) AND NOT (o)<-[:NEXT_WORD]-(all)
WITH w, o, intersection, sum(rw1.weight) as wSum
MATCH (all:Word) WHERE (w)<-[:NEXT_WORD]-(all) AND NOT (o)<-[ro1:NEXT_WORD]-(all)
WITH w, o, intersection, wSum,
toFloat(intersection)/toFloat(wSum + sum(ro1.weight) - intersection) as leftJaccard

WITH w, o, (rightJaccard + leftJaccard)/2.0 as sim
MERGE (w)<-[r:RELATED_TO]->(o) SET r.paradig = sim
set w.toProcess = false

I sum all the min weights of the AB intersection set (min weight will be zero outside this set).

Then divide this by the sum of the weights of the individual A and B sets
minus the min weights of the intersection set.

Subtracting the min weights of the intersection set, leaves the max weight for the intersection values, and the (by definition) max weight for the difference in the denominator.

I think I'm on firm ground here because expressing it in this way makes clear the link between the weighted version and the 2nd version of the basic Jaccard calculation (as expressed in terms of just the sets and their intersection). But I'd like to be sure my code is right, and that there isn't a better way of doing it in cypher.


texts:
I am trying to solve this coding exercise:

You are given an array (which will have a length of at least 3, but could be very large) containing integers. The array is either entirely comprised of odd integers or entirely comprised of even integers except for a single integer N. Write a method that takes the array as an argument and returns N.
For example:
[2, 4, 0, 100, 4, 11, 2602, 36]
Should return: 11
[160, 3, 1719, 19, 11, 13, -21]
Should return: 160

Here is my code:
import java.util.ArrayList;
public class FindOutLier {
    public static int search(ArrayList<Integer> lists, int num) {
        int count = 0;
        int index;
        Integer a[] = new Integer[lists.size()];
        a = lists.toArray(a);
        for (index = 0; index < a.length; index++) {
            if (num == a[index]) {
                count++;
            }
        }
        return count;
    }

    public static boolean checkEvenOrOdd(int[] integers) {
        int t = 0;
        double result = 0.0;
        ArrayList<Integer> l = new ArrayList<Integer>(integers.length);
        while (t < integers.length) {
            result = integers[t] % 2;
            if (result == 0.0) {
                l.add(1);
                t++;
            } else {
                l.add(0);
                t++;
            }
        }
        int counter = search(l, 1);
        if (counter == 1)
            return true;
        else
            return false;
    }

    public static int find(int[] integers) {
        int t = 0;
        double newresult = 0.0;
        boolean result = checkEvenOrOdd(integers);
        if (result == false) //
        {
            while (t < integers.length) {
                newresult = integers[t] % 2;
                if (newresult != 0.0) {
                    break;
                } else {
                    t++;
                }
            }
        } else {
            while (t < integers.length) {
                newresult = integers[t] % 2;
                if (newresult == 0.0) {
                    break;
                } else {
                    t++;
                }
            }
        }
        return integers[t--];
    }
}

It passed Junit Test in Eclipse. Please review it/ suggest any improvements.
Thanks.


texts: C function to move and collapse cells in 2048 game

texts:
I'm implementing a clone of 2048 in C with SDL, and I have the following function for performing a movement on a column vector/array

/**
 * collapseVector: Collapse a vector "2048" style, flush the cells in one direction, joining them if legal.
 * @param _vector 1-D array to be collapsed
 * @param _score Score counter
 * @param invert Whether or not to inverse-flush vector. Useful for Up(false) vs. Down(true), and so on
 */
void collapseVector(int _vector[MAX_BOARD_POS], int **_score, bool invert) {
    int idx;
    int buf[MAX_BOARD_POS] ={0};
    if (invert) {
        idx = MAX_BOARD_POS - 1;
        for (int i = MAX_BOARD_POS - 1; (MAX_BOARD_POS - i) < MAX_BOARD_POS + 1; --i){
            if(!_vector[i]){
                continue;
            }
            if(!buf[idx]){
                buf[idx] = _vector[i];
            }else if(_vector[i] == buf[idx]){
                ++buf[idx];
                **_score += 1 << buf[idx];
            }else{
                buf[--idx] = _vector[i];
            }
        }

    } else {
        idx = 0;
        for (int i = 0; i < MAX_BOARD_POS; ++i) {
            // If it's an empty cell (0) ignore it. The buf vector is zero-filled anyway
            if (!_vector[i]) {
                continue;
            }
            // Special case for filling in the first cell of buffer
            if (!buf[idx]) {
                buf[idx] = _vector[i];
            } else if (_vector[i] == buf[idx]) {
                // If we have identical neighbouring cells join them
                ++buf[idx];
                // Add 2^buf[idx] to our score counter.
                **_score += 1 << buf[idx];
            } else {
                // Flush cells to the end of vector
                buf[++idx] = _vector[i];
            }
        }
    }
    memcpy(_vector, buf, MAX_BOARD_POS * sizeof(*_vector));
}

This code works perfectly, but it's long and repetitive. How can I improve this? The two for loops in here are very similar and I wonder whether I could join them perhaps.


texts:
I'm writing a program to calculate the longest collatz sequence for positive integers below some N. I have optimized it as far as I can - is there anything more I could do to optimize it? Any constructive criticism is welcome :)

A few interesting notes: It is easy to prove (by contradiction or otherwise) that the number that produces the longest chain exists in the second half of the numbers from 1-N (that is, it must be greater than N/2). If we try to run the loop from N/2 to N, the running time becomes substantially slower. Interesting... Also, the lower while loop is an interesting idea, but provides no tangible performance benefits (or losses, for that matter - which is why I kept it. It's an interesting idea).

Thank you!

#include <iostream>
#include <chrono>

using namespace std::chrono;

const int N = 1000000;
long long iCpy;
short ct;
short maxLength = 0;
short vals[N] = {0};

int main() {
  // Time the program:
  auto startTime = steady_clock::now();

  int i, maxIndex = 0;

  // calculate collatz lengths for all indices.
  // keep track of max value:
  for (i = 2; i < N; i++) {
    iCpy = i;
    ct = 0;

    while (iCpy != 1) {
      if (iCpy < N && vals[iCpy]) {
        ct += vals[iCpy];
        break;
      }

      if (iCpy & 1) {
        iCpy *= 3;
        iCpy++;
      } else {
        iCpy >>= 1; // Equivalent to iCpy /= 2
      }

      ct++;
    }

    iCpy = i;
    vals[iCpy] = ct;
    while (iCpy < N/2) {
      iCpy <<= 1; // Equivalent to iCpy *= 2
      vals[iCpy] = ++ct;
    }
    if (ct > maxLength) {
      maxLength = ct;
      maxIndex = iCpy;
    }
  }

  // output the max index and length:
  std::cout << "Max number: " << maxIndex << ", with length " << maxLength << std::endl;

  auto elapsed = duration_cast<milliseconds>(steady_clock::now() - startTime);
  std::cout << "Program execution took " << elapsed.count() << "ms\n";
  return 0;
}


texts: Extract integers from a string that is split at given positions

texts:
I am writing a program which runs quite slow and on profiling I found that the bottleneck is to split a given string at given positions.

The first and short version I wrote was (80% of 67 sec, i.e. 53 sec spent):

split list pos = uncurry (:) $ mapAccumR (flip splitAt) list pos

A faster version I wrote is (76% of 21 sec, i.e. 15 sec spent):

split :: String -> [Int] -> [Int]
split = go [] 0 0
    where
        -- no more string to split
        go nums num _ [] _ = num : nums
        -- no more position to split
        go nums num _ list [] = read (intToDigit num : list) : nums
        go nums num i (l:ls) pos@(p:ps)
            | i == p = go (num:nums) (digitToInt l) (i+1) ls ps
            | otherwise = go nums (10 * num + digitToInt l) (i+1) ls pos

How can I improve this?


texts: SkipLast of an IEnumerable - Linq Extension

texts:
As my answer to this question, I came up with this solution:

static public IEnumerable<T> SkipLast<T>(this IEnumerable<T> data, int count)
{
  if (data == null || count < 0) yield break;

  Queue<T> queue = new Queue<T>(data.Take(count));

  foreach (T item in data.Skip(count))
  {
    queue.Enqueue(item);
    yield return queue.Dequeue();
  }
}

It returns all items in the set but the count last, but without knowing anything about the size of the data set. I think it's funny and that it's working, but a comment claims that is doesn't. Am I overlooking something?

A version with a circular queue could be:

static public IEnumerable<T> SkipLast<T>(this IEnumerable<T> data, int count)
{
  if (data == null || count < 0) yield break;
  if (count == 0)
  {
    foreach (T item in data)
      yield return item;
  }
  else
  {
    T[] queue = data.Take(count).ToArray();
    int index = 0;

    foreach (T item in data.Skip(count))
    {
      index %= count;
      yield return queue[index];
      queue[index] = item;
      index++;
    }
  }
}

Performance wise they seems to be even.

Compared to other solutions like the most obvious:

data.Reverse().Skip(count).Reverse()

It seems to be at least as fast and for very large set about twice as fast.

Test case:

  int count = 20;
  var data = Enumerable.Range(1, count);

  for (int i = 0; i < count + 5; i++)
  {
    Console.WriteLine($"Skip: {i} => {(string.Join(", ", data.SkipLast1(i)))}");
  }

Any comments are useful.


texts: Creating a RegExp in JavaScript from user input

texts:
My goal is to accept user input regex in the following forms

/regex|here/i
/regex|here/
regex|here

From there I want to be able to pass that to a function and return a RexExp object for use later with string.match()

I came up with the below to achieve that, and not break the caller which is expecting the RegExp object returned.  Is there any part of this that I'm doing wrong or exceedingly sub-optimally?  (I'm not very familiar with Javascript).

function regGen(uInput)
{
    var inReg = "";
    var inMod = "";
    var outReg = /(?!)/

    if(uInput[0] == "/" && uInput[uInput.length-1] == "/")
    {
        inReg = uInput.slice(1,uInput.length-1);
    }
    else if(uInput[0] == "/")
    {
        var temp = uInput.split("/");
        inMod = temp[temp.length-1];
        inReg = temp;
            inReg.pop();
            inReg.shift();
        inReg = inReg.join("/");
    }
    else
    {
        inReg = uInput;
    }
    try {
        outReg = new RegExp(inReg,inMod);
    }
    catch(err)
    {
        alert("Malformed Regex");
    }
    return outReg;
}


texts:
I would like to know how I might improve my code?
I just started coding and liking it a few days ago so I am quite new to this whole world...

The objective is to calculate the amount of water one has drunk in a day. Depending on the user's input, the app tells him or her if the amount of water drunk is great or not.

Now I would like know how I might improve this whole code?
And I'd be grateful for some advice (what I could improve etc)...

package com.ahmed.everything;
import java.util.*;
import java.util.concurrent.TimeUnit;

public class DrinkingWater {
    public static void main(String [] args) throws Exception {
    Scanner sc = new Scanner(System.in);

    System.out.print("Amount of water your bottle can hold: ");
    // entering amount of water bottle can hold
    double litre = sc.nextDouble();
    System.out.print("How many bottles have you drunk today? : ");
    // amount of bottles for today
    double bottles = sc.nextDouble();
    // calculating water drunk
    double total = (bottles * litre);

    // result
    if (bottles == 1) {
    System.out.print("You've only drunk one bottle today! :(" + "\n");
    }
    else {
        System.out.println("Today, you have drunk " + bottles + " bottles. Which equals to " + total + " liters of water.");
    }

    // advice
    if (total < 4) {
        System.out.println("You did not drink enough water, drink at least 4 liters to stay healthy!");
    }

    else if (total >= 4) {
        System.out.println("Good job! You've drunk enough water today! :)");
    }
    else;

    //short time span
    TimeUnit.SECONDS.sleep(1);
    System.out.print(".");
    TimeUnit.SECONDS.sleep(1);
    System.out.print(".");
    TimeUnit.SECONDS.sleep(1);
    System.out.println(".");
    TimeUnit.SECONDS.sleep(1);

    System.out.println("Did you like our little app? Please review it from 1-5. 1 being considerer as very good and 5 as very bad.");
    int note = sc.nextInt();
    if (note <= 4 || note >= 1) {
        System.out.println("Thanks for your review.");
    }else {
        System.out.println("That's better, we'll do our best the next time");
    }

    }
}


texts: Alternative code to classes in Javascript?

texts:
I'm new to JavaScript and came across classes in ES6. Though they are great, I don't want to learn something that can be done in other ways. So, I created this code that does somehow similar job to what classes in JS do. Please give me feedback on whether classes does more than what I think they can do and whether my code is missing something that classes can do.
This is the JS code:

<script>
const person = function(first, second, age, sex){
    return {
        firstName:first,
        lastName:second,
        age:age,
        gender:sex,
        fullName:function(){
            return this.firstName + " " + this.lastName;
        }
    }
}
var John = person("John", "Anderson", 21, "Male");
var Mary = person("Mary", "Smith", 32, "Female");

document.getElementById("demo1").innerHTML = John.firstName;
document.getElementById("demo2").innerHTML = Mary.fullName();
</script>

And the output of the code is:

John

Mary Smith


texts:
I am studying the merge sort algorithm and implemented it. In the mergeSort function, I am allocating two new vectors. Can I do it without allocating extra memory? Are there any other suggestions?

#ifndef MERGE_SORT
#define MERGE_SORT
#include <vector>

template<typename T>
void merge(std::vector<T>& array, std::vector<T> left, std::vector<T> right) {
    array.clear();
    auto lsize = left.size();
    auto rsize = right.size();
    unsigned int i=0, j=0;
    while (i < lsize && j < rsize) {
        if (left[i] < right[j]) {
            array.push_back(left[i]);
            ++i;
        }else {
            array.push_back(right[j]);
            ++j;
        }
    }
    for(; i<lsize; ++i)
        array.push_back(left[i]);
    for(; j<rsize; ++j)
        array.push_back(right[j]);
}

template<typename T>
void mergeSort(std::vector<T>& seq) {
    auto n = seq.size();
    if (n > 1) {
        auto start = seq.begin();
        auto end = seq.end();
        auto middle = start + n / 2;
        std::vector<T> left(start, middle);
        std::vector<T> right(middle, end);
        mergeSort(left);
        mergeSort(right);
        merge(seq, left, right);
    }
}

#endif // MERGE_SORT


texts: DisjointSet with O(1) find and O(1) amortised union

texts:
Does this code outperform the common implementation with path-compression and union-by-rank?  I'm still okay with a review.

GitHub

import java.util.*;

public class DisjointSet<E> {
    public static void main(String... args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt();

        DisjointSet<String> set = new DisjointSet<>();

        for (int i = 0; i < n; i++) {
            String a = s.next();
            String b = s.next();
            set.union(a, b);
        }

        System.out.println(set);
    }

    /**
    * a map from each element to a reference to the set
    * that contains them. The reference is used so that many
    * map entries can be updated at once in O(1) without
    * the cost of iterating through each entry.
    * This occurs when performing the union. If we are merging
    * a set A and a set B then we would otherwise be required
    * to iterate through all of B's entries and point them to
    * A and then call A.addAll(B). By having a mutable reference
    * we skip the iteration and update all entries of B in O(1).
    */
    private HashMap<E, Ref<Set<E>>> map = new HashMap<>();

    /**
    * a set of references to subsets.
    * Just used for #toString().
    */
    private Set<Ref<Set<E>>> refs = new HashSet<>();

    /**
     * @time worst case O(n), amortised O(1)
     */
    public void union(E a, E b) {
        Ref<Set<E>> ra = map.get(a);
        Ref<Set<E>> rb = map.get(b);

        Set<E> sa = ra != null ? ra.value : null;
        Set<E> sb = rb != null ? rb.value : null;

        Set<E> t;

        if (sa == null && sb == null) {
            t = new HashSet<>();
            t.add(a);
            t.add(b);
        } else if (sa != null && sb != null) {
            t = sa.size() > sb.size() ? sa : sb;

            // addAll is worst-case O(n) but you have to add n items to be able to
            // experience that worst case, and all intermediate adds will be O(1),
            // so #union is amortised O(1)
            t.addAll(sa.size() > sb.size() ? sb : sa);
        } else {
            t = sa != null ? sa : sb;
            t.add(a);
            t.add(b);
        }

        Ref<Set<E>> ref = ra != null ? ra : rb != null ? rb : new Ref<>();

        ref.value = t;

        map.put(a, ref);
        map.put(b, ref);

        refs.remove(ra);
        refs.remove(rb);
        refs.add(ref);
    }

    /**
     * @param e the element whose (sub)set you would like to find.
     * @return the set that e belongs to or null if it is not present
     * @time O(1)
     */
    public Set<E> find(E e) {
        Ref<Set<E>> ref = map.get(e);
        return ref != null ? ref.value : null;
    }

    /**
     * @time O(n)
     */
    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();

        for (Ref<Set<E>> ref : refs) {
            builder.append(ref.value);
            builder.append('\n');
        }

        return builder.toString();
    }

    private class Ref<R> {
        private R value;

        Ref(R r) {
            value = r;
        }

        public Ref() {

        }
    }
}


texts: Code reuse while keeping meaning clear and avoiding unforseen consequences

texts:
I like to reuse code as much as possible and keeps things DRY. But I'm afraid that sometimes it creates too many layers of indirection. It then becomes a chore to find where code exists that is relevant to the problem at hand. I'll give a couple of examples.

In the first example, I'm using inheritance on classes that are not directly related, but one class happens to need a lot of functions from the other class.

Here's a portion of the base class:

class GetTimecard < Interactor
  def date_range_start
    if @request.params[:date_range_start]
      Date.parse(@request.params[:date_range_start])
    else
      pay_period.last_starts_on
    end
  end

  def date_range_end
    if @request.params[:date_range_end]
      Date.parse(@request.params[:date_range_end]) + 1.day
    else
      pay_period.last_ends_on
    end
  end
end

The inherited class is largely the same as base class but does not need a date range. It is only interested in a single day.

class GetTimecardForShift < GetTimecard
  def call
    @request.params[:date_range_start] = @request.params[:date]
    @request.params[:date_range_end] = @request.params[:date]
  end
end

So in the call method you have a strange assignment of variables that only makes sense if you have a look at the base class.

In the second example, I use modules to share common functionality between many classes.

There is a module like this:

module Timeable
  def timesheet_entries_for(shift)
    TimesheetEntryRepository.where(account_and_user_ids.merge(assigned_shift_id: shift.id))
  end
end

This function calls a method, account_and_user_ids which is not defined in the module itself. Instead, it's defined in each class that includes the module. But each class may define it differently. For example:

class RecordTime < Interactor
  include Timeable

  def account_and_user_ids
    { account_id: @request.account_id, user_id: @request.current_user.id }
  end
end

class GetTimecard < Interactor
  include Timeable

  def account_and_user_ids
    @account_and_user_ids ||= { account_id: @request.account_id, user_id: get_user_ids }
  end

  def get_user_ids
    if @request.params[:id]
      @request.params[:id]
    else
      if @request.params[:departments]
        UserRepository.by_account(@request.account_id).where(department_id: @request.params[:departments]).map(&:id) & managed_users.map(&:id)
      else
        managed_users.map(&:id)
      end
    end
  end
end

So it quickly becomes confusing trying to figure out which method is defined where and how changing one method will affect other code.

Are there standard ways of making these dependencies explicit? Hopefully there's a naming convention or a better way to names things. I'm not a fan of too many comments in code because they have a tendency to tell less than the code itself and even to be flat out wrong.


texts:
I'm trying to solve the problem given here.

Arrange given numbers to form the biggest number | Set 1
Given an array of numbers, arrange them in a way that yields the largest value. For example, if the given numbers are > {54, 546, 548, 60}, the arrangement 6054854654 gives the largest value. And if the given numbers are {1, 34, 3, 98, 9, > 76, 45, 4}, then the arrangement 998764543431 gives the largest value.
A simple solution that comes to our mind is to sort all numbers in descending order, but simply sorting doesn’t work. > For example, 548 is greater than 60, but in output 60 comes before 548. As a second example, 98 is greater than 9, but > 9 comes before 98 in output.
So how do we go about it? The idea is to use any comparison based sorting algorithm.
In the used sorting algorithm, instead of using the default comparison, write a comparison function myCompare() and use > it to sort numbers.
Given two numbers X and Y, how should myCompare() decide which number to put first – we compare two numbers XY (Y > appended at the end of X) and YX (X appended at the end of Y). If XY is larger, then X should come before Y in output, > else Y should come before. For example, let X and Y be 542 and 60. To compare X and Y, we compare 54260 and 60542. Since 60542 is greater than 54260, we put Y first.
Following is the implementation of the above approach.
To keep the code simple, numbers are considered as strings, the vector is used instead of a normal array.

I'm getting the required output but the written code looks like code bloat(I mean could've have written better simpler and easy code). Can somebody suggest a better way of doing it. This is my code
#include <iostream>
#include <string>
#include <algorithm>

bool comp(const int32_t ia, const int32_t ib) {
    const std::string a = std::to_string(ia);
    const std::string b = std::to_string(ib);

    int32_t i = 0;
    if (a.size() == b.size()) {
        while (i < a.size()) {
            if (a.at(i) == b.at(i)) {
                ++i;

                continue;
            }
            else if (a.at(i) > b.at(i))
                return true;
            else
                return false;
        }
    } else {
        int32_t min_size = static_cast<int32_t>(std::min(a.size(), b.size()));
        int32_t max_size = static_cast<int32_t>(std::max(a.size(), b.size()));

        while (i < min_size) {
            if (a.at(i) == b.at(i)) {
                ++i;

                continue;
            }
            else if (a.at(i) > b.at(i))
                return true;
            else
                return false;
        }

        const char temp = a.at(0);
        const std::string& max_str = (a.size() > b.size()) ? a : b;
        if (max_str == b) {
            while (i < max_size) {
                if (temp >= max_str.at(i++))
                    return true;
                else
                    return false;
            }
        } else {
            while (i < max_size) {
                if (temp >= max_str.at(i++))
                    return false;
                else
                    return true;
            }
        }
    }
}

int32_t main() {
    int32_t arr[] = { 546, 548, 54, 60 };
    int32_t arr_size = sizeof(arr) / sizeof(*arr);

    std::sort(arr, arr + arr_size, comp);
    for (const int val : arr)
        std::cout << val;
    std::cout << std::endl;

    return 0;
}


texts: Circumference and Area of a Circle in COBOL

texts:
I recently started Learning COBOL from Lynda and this is my code for the first challenge .

The Objective is that the user will provide the radius and we have to calculate the Circumference and the area of the circle and then display it.

Here is the Code.

       IDENTIFICATION DIVISION.
   PROGRAM-ID. CIRCUMFERENCE AS "CIRCUMFERENCE".
   AUTHOR. ASWIN MOHAN.

  ***************************************************************
  *    Create a Program to read the Radius of a circle and THEN
  *    print out the Circumference and the radius of the circle.
  ***************************************************************

   ENVIRONMENT DIVISION.

   CONFIGURATION SECTION.
   SOURCE-COMPUTER.
   OBJECT-COMPUTER.

   INPUT-OUTPUT SECTION.

   DATA DIVISION.

   FILE SECTION.

   WORKING-STORAGE SECTION.
    01   WS-CONSTANTS.
       05    WS-PI                 PIC 9V9999  VALUE 3.1415.
    01   WS-CIRCLE.
       05    WS-RADIUS             PIC 999V99 VALUE ZEROES.
       05    WS-CIRCUMFERENCE      PIC 9999V99 VALUE ZEROES.
       05    WS-AREA               PIC 99999V99 VALUE ZEROES.
    01   WS-DISPLAY.
       05    WS-DISPLAY-CIRCUMFERECE   PIC ZZ99.99.
       05    WS-DISPLAY-AREA           PIC ZZ999.99.

   PROCEDURE DIVISION.
    0100-PROCESS-RECORDS.

        DISPLAY "Enter the Radius".
        ACCEPT WS-RADIUS.

        COMPUTE WS-CIRCUMFERENCE = 2 * WS-PI * WS-RADIUS.
        MOVE WS-CIRCUMFERENCE TO WS-DISPLAY-CIRCUMFERECE.

        COMPUTE WS-AREA = WS-PI * WS-RADIUS * WS-RADIUS.
        MOVE WS-AREA TO WS-DISPLAY-AREA.

        DISPLAY "The Circumferece is " , WS-DISPLAY-CIRCUMFERECE.
        DISPLAY "The Area is " , WS-DISPLAY-AREA.

        STOP RUN.

        END PROGRAM CIRCUMFERENCE.

I'm using GNU-COBOL and I'm worried that my COBOL coding style is not so great. I'm just starting out so all feedback is appreciated.


texts:
This is my first ever program in C and I was just tinkering around with this idea, as I'm on a music based course and the synth plugins all use milliseconds as its time.

Any improvements to make it more efficient or less dependant with a little explanation would be really appreciated.

/* declarations */
int crotchet(int);
int semibreve(int);
int minim(int);
int quaver(int);
int semiquaver(int);
int demisemiquaver(int);

int main() {

int bpm;

/* Ask for note bpm */
printf("Enter bpm value:\n");
scanf("%d", &bpm);

/* returns note lengths from functions */
printf("Semibreve would last for... ");
printf("%d", semibreve(bpm));
printf(" miliseconds! \n");

return 0;
}

int crotchet(int bpm)
{
/*  1 second = 1000
 1 min = 60 seconds = 6000 miliseconds
 */

int crotchet;
crotchet = 6000 / bpm;

return crotchet;
}

int semibreve(int bpm)
{
int crot;
crot = crotchet(bpm);
int semibreve;
semibreve = crot * 4;

return semibreve;
}

int minim(int bpm)
{
int crot;
crot = crotchet(bpm);
int minim;
minim = crot * 2;

return minim;
}

Same for quaver (dividing crot by 2), semiquaver (dividing crot by 4) and demi semiquaver (dividing crot by 8).

Any additional explanation towards the music theory I will also add if requested.


texts: OpenMP parallel for critical section and use of flush

texts:
I am not sure about the place where flush should be used (if it is used at all here).

int Window_Shift :: get_window_shift()
{
    int window_shift = INFINITE;

    #pragma omp parallel for
    for(unsigned int node_id = 0;node_id< no_of_valid_nodes ;node_id++)
    {
        //for all the nodes that can be extended
        //finds the minimum possible window shift
        if(can_node_determine_window_shift(node_id) == true)
        {
            int node_window_shift = get_window_shift_for_node(node_id);
            #pragma omp flush(window_shift)
            #pragma omp critical(get_window_shift_for_node)
            {
            window_shift = min(window_shift,node_window_shift);
            #pragma omp flush(window_shift)
            }
        }
    }

Please review the code, especially the flush() commands.  Should atomic be used instead of a critical section?


texts: A class for solving a system of linear equations using Gaussian Elimination

texts:
class LinearEquationSolver
{
    List<LinearEquation> rows = new List<LinearEquation>();
    decimal[] solution;

    public void AddLinearEquation(decimal result, params decimal[] coefficients)
    {
        rows.Add(new LinearEquation(result, coefficients));
    }

    public IList<decimal> Solve()       //Returns a list of coefficients for the variables in the same order they were entered
    {
        solution = new decimal[rows[0].Coefficients.Count()];

        for (int pivotM = 0; pivotM < rows.Count() - 1; pivotM++)
        {
            int pivotN = rows[pivotM].IndexOfFirstNonZero;

            for (int i = pivotN + 1; i < rows.Count(); i++)
            {
                LinearEquation rowToReduce = rows[i];
                decimal pivotFactor = rowToReduce[pivotN] / -rows[pivotM][pivotN];
                rowToReduce.AddCoefficients(rows[pivotM], pivotFactor);
            }
        }

        while (rows.Any(r => r.Result != 0))
        {
            LinearEquation row = rows.FirstOrDefault(r => r.NonZeroCount == 1);
            if (row == null)
            {
                break;
            }

            int solvedIndex = row.IndexOfFirstNonZero;
            decimal newSolution = row.Result / row[solvedIndex];

            AddToSolution(solvedIndex, newSolution);
        }

        return solution;
    }

    private void AddToSolution(int index, decimal value)
    {
        foreach (LinearEquation row in rows)
        {
            decimal coefficient = row[index];
            row[index] -= coefficient;
            row.Result -= coefficient * value;
        }

        solution[index] = value;
    }

    private class LinearEquation
    {
        public decimal[] Coefficients;
        public decimal Result;

        public LinearEquation(decimal result, params decimal[] coefficients)
        {
            this.Coefficients = coefficients;
            this.Result = result;
        }

        public decimal this[int i]
        {
            get { return Coefficients[i]; }
            set { Coefficients[i] = value; }
        }

        public void AddCoefficients(LinearEquation pivotEquation, decimal factor)
        {
            for (int i = 0; i < this.Coefficients.Count(); i++)
            {
                this[i] += pivotEquation[i] * factor;
                if (Math.Abs(this[i]) < 0.000000001M)    //Because sometimes rounding errors mean it's not quite zero, and it needs to be
                {
                    this[i] = 0;
                }
            }

            this.Result += pivotEquation.Result * factor;
        }

        public int IndexOfFirstNonZero
        {
            get
            {
                for (int i = 0; i < Coefficients.Count(); i++)
                {
                    if (this[i] != 0) return i;
                }
                return -1;
            }
        }

        public int NonZeroCount
        {
            get
            {
                int count = 0;
                for (int i = 0; i < Coefficients.Count(); i++)
                {
                    if (this[i] != 0) count++;
                }
                return count;
            }
        }
    }
}

Are there any edge-cases I've missed? Is there a better way to handle potential rounding errors than just checking if a value is close to zero and zeroing it if it is? Is it overkill to use Decimals like this?

Here's a test program:

class Program
{
    static void Main(string[] args)
    {
        LinearEquationSolver test = new LinearEquationSolver();

        test.AddLinearEquation(5, 1, 2, 1, -1);
        test.AddLinearEquation(16, 3, 2, 4, 4);
        test.AddLinearEquation(22, 4, 4, 3, 4);
        test.AddLinearEquation(15, 2, 0, 1, 5);
        var result = test.Solve();

        foreach (var asdf in result)
        {
            Console.Write(asdf);
        }

        Console.ReadKey();
    }
}


texts: Look up value from one dataframe and find percent of values in another dataframe that are less than that

texts:
Is there a one-liner that can accomplish this same thing? Essentially I have two dataframes: one that has my raw data (data), and one that has values that I want to lookup (lookup). I want to find the percent of values in data (by 2 factors, Site and variable) that are less than the lookup value for those same 2 factors.

I'd love to just be able add the result to the lookup dataframe as a column, instead of creating two new objects.

combine <- merge(data, lookup, by = c("Site", "variable"), allow.cartesian = TRUE)
test <- ddply(combine, .(Site, variable), summarize, percent = sum(data.values < lookup.value) / length(data.values))

Any advice is appreciated!


texts:
Team 7 faces a horrible foe. He can only be defeated with a special
  quadruple combination attack of strength (\$1 <=S <= 10^9\$). Naruto,
  Sasuke, Sakura and Kakashi must attack simultaneously to perform the
  combo. Each of them can choose from \$N\$ (\$1 <= N <=1000\$) attacks,
  having strengths \$si\$ each (\$0 <= i < N\$, \$1 <= si <=10^9\$). The strengths
  of individual attacks add up to form the strength of the combo.

  Is there a valid combination that they can use? Note that the same attacks are available to all of them.

  You are required to write a function which takes input as follows:

  An integer \$N\$ as number of attacks, an integer vector s[] as the
  strengths of \$N\$ attacks and an integer S as the required strength of
  the combo. Set the output variable to the number of distinct valid
  combos.

  Two combinations are different if they differ in strength of at least one attack used.

  Input: 1 {1} 4
  Output: 1  ===> {1,1,1,1}

  Input: 2 {1,2} 5
  Output: 1 ===> {1,1,1,2}

#include "stdafx.h"
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<algorithm>

const int noOfPalyers = 4;

int validCombo(int input1,int input2[],int input3)
{
    std::cout<< "-----------------------------------------------------------------------------"<<"\n";
    int count = 0;
    std::vector<int> vec;
    int size =input1*noOfPalyers;
    for(int i = 0; i < input1; i++)
    {
        for(int j = 0; j < noOfPalyers;j++)
        {
            vec.push_back(input2[i]);
        }
    }

    std::vector< std::vector< std::pair<int, int> > > vecHash;

    for(int i =0; i < (size*size); i++)
    {
        vecHash.push_back(std::vector< std::pair<int, int> > ());
    }

    for(int i =0; i < size; i++)
    {
        for(int j =1; j < size; j++)

        {
            int key = vec[i] + vec[j];
            if(vec[i]<= vec[j])
                vecHash[key].push_back(std::make_pair(vec[i], vec[j]));
            else
                vecHash[key].push_back(std::make_pair(vec[j], vec[i]));

        }
    }

    std::set< std::vector<int> > solution;
    for(int i = 0; i < input3; i++)
    {

        if(vecHash[input3 - i].size() > 0)
        {
            for(int k = 0; k < vecHash[i].size() ; k++)
            {
                std::pair<int, int> fPair = vecHash[i][k];

                for(int m =0; m < vecHash[input3 - i].size(); m++)
                {
                    std::pair<int, int> sPair = vecHash[input3 - i][m];
                    std::vector<int> vec;
                    vec.push_back(fPair.first);
                    vec.push_back(fPair.second);
                    vec.push_back(sPair.first);
                    vec.push_back(sPair.second);
                    std::sort(vec.begin(), vec.end());
                    solution.insert(vec);
                }

            }
        }
    }

    std::set< std::vector< int> >::iterator it;
    for (it = solution.begin(); it != solution.end(); it++)
    {
        std::cout<< "\n";
        for(int i = 0; i < (*it).size(); i++)
            std::cout << (*it)[i] << " , ";
        std::cout<< "\n";
    }
    count = solution.size();

    std::cout << "solution size = "  << solutionSet.size();
    std::cout<< "\n";
    std::cout<< "\n";

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

    return count;

}

int  main()
{
    int i = 3;
    int arr[] = {1,2,3};
    int j = 7;
    int arr1[] ={1};
    std::cout <<"o/p == "  << validCombo(i, arr, j)<< "\n";
    std::cout <<"o/p == "  << validCombo(1, arr1, 4);

    getchar();
    return 0;
}


texts: React-Native: Using expo-font hook to retrieve assets

texts:
I am using expo and wanted to use the hook 'useFonts' from expo-fonts to retrieve fonts.
While the assets are being retrieved a splashscreen is displaying.
This is my solution.
// Import the hook.
import { useFonts } from 'expo-font';

export default function App() {

  const [appReady, setReady] = useState(false);

  const [loaded] = useFonts({
    Roboto: require('native-base/Fonts/Roboto.ttf'),
    Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'),
  })

  useEffect(() => {
    if (loaded) {
      setReady(true);
    }
  }, [loaded])

  //if assets are not loaded, load them first, then display app.
  if (!appReady) {
    return (
      // Show splashscreen while waiting.
    );
  }

I'm new to react hooks and just wanted to know if this approach is acceptable.


texts:
I wrote a simple sound player to use as part of my MorseString class. I am new to using sounds (in fact, I was helped a lot by Google) and I don't know if this is the correct way to play a sound.

The method takes a specific frequency and a duration as parameters, and plays the frequency for the specified duration.

private static final int SAMPLING_FREQUENCY_IN_HZ = 8000;
private static final int NUMBER_OF_FADE_SAMPLES = 80;

private static void sound(int hz, int msecs) throws LineUnavailableException {
    byte[] buf = new byte[msecs * Byte.SIZE];
    for (int i = 0; i < buf.length; i++) {
        double angle = i / (SAMPLING_FREQUENCY_IN_HZ / hz) * 2 * Math.PI;
        buf[i] = (byte) (Math.sin(angle) * Byte.MAX_VALUE);
    }
    for (int i = 0; i < NUMBER_OF_FADE_SAMPLES && i < buf.length / 2; i++) {
        buf[i] = (byte) (buf[i] * i / NUMBER_OF_FADE_SAMPLES);
        buf[buf.length - 1 - i] = (byte) (buf[buf.length - 1 - i] * i / NUMBER_OF_FADE_SAMPLES);
    }
    AudioFormat af = new AudioFormat(SAMPLING_FREQUENCY_IN_HZ, Byte.SIZE, 1, true, false);
    SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
    sdl.open(af);
    sdl.start();
    sdl.write(buf, 0, buf.length);
    sdl.drain();
    sdl.close();
}

The sound sounds like it is low-quality. Is there a way to improve that?
Did I do my math wrong?

Please explain in as much detail as possible, as I'm new and might not understand.


texts: Using reduce twice in a row for Run Length Encoding

texts:
First of all, I'm new to Lisp (I currently use CLISP and SBCL). There probably are huge mistakes in this code so any guidelines are welcome :)

I'm very confused about how to do this. It's just about a habit and I don't want my actual help to implement an algorithm, as the one I came up with is not the best one.

Is it okay to use reduce twice in a row on the same list? (it is not exactly the same list as it has been reduced, but I hope you get my point)

Here the algorithm is pretty much the same as the run-length encoding the only differences I see are:

when a letter occurs only once, it has no number indication
the number of occurrences of a letters is put on the right instead of the left

For example:

input: aabcbaaabbbcc

output: a2bcba3b3c2

The steps I have chosen to do are these:

Convert the string input to a char list (\#a \#a \#b etc.)
Use reduce to transform the char list to ((\#a \#a) (\#b) etc.)
Transform the new list to a string using reduce again (this is where I'm wondering if the previous step should not be a reduce but a map)

I have implemented the 2 first steps of this algorithm here:

(defun compress-reduce (prev curr)
  ;prev is always a 2d list -> ex: ((a) (b))
  ;curr is always a char
  (format t "prev: ~A | curr: ~A | " prev curr)
  (let ((last-seq (nth 0 (last prev)))
        (last-char (nth 0 (nth 0 (last prev)))))

    (format t "last-seq: ~A | last-char: ~A~%" last-seq last-char)

    (if
      (= (char-int last-char) (char-int curr))
      (and (push curr last-seq)
           (setf (nth (- (length prev) 1) prev) last-seq) prev)
      (append prev (list (list curr))))))

(defun compress ()
  (let ((l (coerce "abcccbbabaaa" 'list) ))

    ; reduce
    (format t "~A" (reduce #'compress-reduce l :initial-value (list (list (nth 0 l)))))))

(format t "~A" (compress))

This always outputs:

prev: ((a)) | curr: a | last-seq: (a) | last-char: a
prev: ((a a)) | curr: b | last-seq: (a a) | last-char: a
prev: ((a a) (b)) | curr: c | last-seq: (b) | last-char: b
prev: ((a a) (b) (c)) | curr: c | last-seq: (c) | last-char: c
prev: ((a a) (b) (c c)) | curr: c | last-seq: (c c) | last-char: c
prev: ((a a) (b) (c c c)) | curr: b | last-seq: (c c c) | last-char: c
prev: ((a a) (b) (c c c) (b)) | curr: b | last-seq: (b) | last-char: b
prev: ((a a) (b) (c c c) (b b)) | curr: a | last-seq: (b b) | last-char: b
prev: ((a a) (b) (c c c) (b b) (a)) | curr: b | last-seq: (a) | last-char: a
prev: ((a a) (b) (c c c) (b b) (a) (b)) | curr: a | last-seq: (b) | last-char: b
prev: ((a a) (b) (c c c) (b b) (a) (b) (a)) | curr: a | last-seq: (a) | last-char: a
prev: ((a a) (b) (c c c) (b b) (a) (b) (a a)) | curr: a | last-seq: (a a) | last-char: a
((a a) (b) (c c c) (b b) (a) (b) (a a a))NIL


texts:
I am basically looking for Critique on the following code as i know its not the best and i am trying to find a set way of building javascript objects.

Be brutal as you way its a learning tool for me, basically i am pulling in a twitter feed via json and adding it to the dom.

var TwitterTimeline = {
  twitterFeed: function (data) {
    $.ajax({
      url: 'http://example.com/api/twitter/timeline/name/' + data.name,
      dataType: 'json',
      crossDomain: true,
      cache: false,
      success: function (items) {
        var tweets = "
";
        $.each(items, function (i, tweet) {
          var parser = new TwitterTimeline.Parser(tweet.text);
          parser.linkifyURLs();
          parser.linkifyHashTags();
          tweets += "

" + tweet.user.name + "
" + parser.getHTML() + "
";
          if(i === (data.limit - 1)) {
            return false;
          }
        });
        tweets += "
";
        $(data.id).html(tweets);
      }
    });
  },
  Parser: function (text) {

    var html = text;

    var urlRegex = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
    var hashTagRegex = /#([^ ]+)/gi;

    this.linkifyURLs = function () {
      html = html.replace(urlRegex, '$1');
    };
    this.linkifyHashTags = function () {
      html = html.replace(hashTagRegex, '#$1');
    };

    this.getHTML = function () {
      return html;
    };

  }
}

TwitterTimeline.twitterFeed({
  id: "#twitter-feed",
  name: 'testaccount',
  limit: 2
});

And my html

Any issues or bad practise which i bet there is a lot please let me know. So many different way to do things with javascript i always feel like i am hacking things together without any structure.

Thanks


texts: Ruby on Rails: refactor big search method

texts:
I have big search method in my model that corresponds to search a proper Car.

It looks like this:

  def self.search(params)
    cars = joins(:reservations).where.not("reservations.reception_time <= ? AND reservations.return_time >= ?",
      params[:return_date], params[:handover_date])
    cars = joins(:car_class).where("car_classes.id= ?", params[:car_class])
    cars = cars_at_both_locations(params[:handover_location], params[:return_location])
    cars = params[:car_body_style] == [""] ? cars : joins(:car_configuration).
       where("car_configurations.body_style_id = ?", params[:car_body_style])
    cars = params[:car_fuel] == [""] ? cars : where(fuel: params[:car_fuel])
    cars = params[:car_transmission] == [""] ? cars : where(transmission: params[:car_transmission])
    cars = params [:car_seats] == [""] ? cars : car_seats(params[:car_seats])
    cars = Car.joins(:prices).where('prices.to_days >= ?',
      (Date.parse(params[:return_date]) - Date.parse(params[:handover_date])).to_i)
end

It is very unreadable now.

Does anyone have an idea how to refactor this method to be more readable?


texts:
I know that is generally expected that you should not swallow exceptions. In this code, an Infragistic's UltraWinGrid is being configured. Is there a better way to handle the failed catches?  Is this an exception to the rule?

private void HideExcludedColumns(UltraGridBase grid)
{
    if (_scExclusions == null) return;
    foreach (var strKey in _scExclusions)
    {
        //Set the appropriate column of the grid to hidden.
        foreach (var band in grid.DisplayLayout.Bands)
        {
            try
            {
                band.Columns[strKey].Hidden = true;
                break;
            }
            catch { }   //go to the next band.
        }
    }
}


texts: Implementation of reactive file write from InputStream

texts:
I want to implement reactive write to file.
In low level, it uses NIO and Futures.
After reading this section
I created this code but maybe there's more clean or less code solution.

Thanks.

public class LocalImageService implements IImageService {
    private String imageDir = "/tmp";

@Override
public Mono<String> storeImage(@NonNull InputStream imageStream, @NonNull String ext) {
    val processor = new ImageProcessor();
    processor.fileName = UUID.randomUUID() + "." + ext;
    val targetFile = new File(imageDir, processor.fileName);

    final Flux<CompletableFuture<Integer>> bridge = Flux.push(sink -> {
        try {
            processor.sink = sink;
            processor.inputChannel = Channels.newChannel(imageStream);
            processor.fileChannel = AsynchronousFileChannel.open(targetFile.toPath(),
                StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            processor.processNextChunk();
        } catch (IOException e) {
            processor.onError(new RuntimeException("Can not write image file: " + processor.fileName, e));
        }
    });
    return bridge.flatMap(Mono::fromFuture)
        .reduce(0, (acc, num) -> {
            processor.buffer.compact();
            processor.processNextChunk();
            return acc + num;
        })
        .then(Mono.just(targetFile.getPath()));
}

private static final class ImageProcessor {
    int position = 0;
    ReadableByteChannel inputChannel;
    AsynchronousFileChannel fileChannel;
    FluxSink<CompletableFuture<Integer>> sink;
    final ByteBuffer buffer = ByteBuffer.allocate(4096);
    String fileName;

    void onComplete() {
        closeStreams();
        if (null != sink) {
            sink.complete();
        }
    }

    private void closeStreams() {
        IOUtils.closeQuietly(inputChannel);
        IOUtils.closeQuietly(fileChannel);
    }

    void onError(Throwable e) {
        closeStreams();
        if (null != sink) {
            sink.error(e);
        }
    }

    void processNextChunk() {
        try {
            int receivedBytes;
            if ((receivedBytes = inputChannel.read(buffer)) >= 0 || buffer.position() > 0) {
                buffer.flip();
                val lastWrite = fileChannel.write(buffer, position);
                position += receivedBytes;
                if (lastWrite != null) {
                    sink.next(CompletableFuture.supplyAsync(() -> {
                        try {
                            return lastWrite.get();
                        } catch (InterruptedException | ExecutionException e) {
                            onError(new RuntimeException("Can not write image file: " + fileName, e));
                            return -1;
                        }
                    }));
                }
            } else {
                onComplete();
            }
        } catch (IOException e) {
            onError(new RuntimeException("Can not write image file: " + fileName, e));
        }
    }
}

}


texts: Fetching data through HTTP and caching JSON result in a file

texts:
The task is to fetch some JSON data from an API with a GET request. If the location is not available for any reason, read a cache file. Otherwise write the cache file for future use.

The following function works but it is clumsy due to:

The nested try/except, which is difficult to read
It's difficult to figure out what the error is (I am catching both HTTPError and the JSONDecodeError to avoid further nesting
I don't dare to use a context manager for opening the file (with) due to a further nesting level within a try/except clause

Have you got any ideas for improvement?

def fetch_list(location=MY_LOCATION, cache_file=CACHE_FILE):
    """Goes to the default location and returns
    a python list
    """
    http = urllib3.PoolManager()
    try:
        r = http.request("GET",
                         location)
        raw_data = r.data.decode("utf-8")
        data = json.loads(raw_data)
    except (urllib3.exceptions.HTTPError, JSONDecodeError):
        logger.error("Cannot access Intranet List Location - fetching cache")
        try:
            data = json.loads(open(cache_file).readlines())
        except (IOError, JSONDecodeError):
            logger.error("Cache File not found or broken")
            raise
    else:
        with open(cache_file, "w") as f:
            f.write(raw_data)

    return data


texts:
I have written this program to compute the leading set of the following productions

E->E+T
E->T
T->T*F
T->F
F->(E)
F->#

Here identifier is taken as '#'

#include<stdio.h>
#include<conio.h>
#include<ctype.h>
struct leadT
{
    int n;
    char lead[5];
};
struct leadT leading[7];
char ip[7][7];
int col,cnt=0;
char Sym[5]={ '+','(',')','*','#','i' };
int isSym(char);
void findLeading(char,int);
void leadTabOp(char,int);
void main()
{
    int i,j,c;
    char b[4];
    for(i=0;i<=5;i++)
    {
        scanf("%s",&ip[i]);
    }
    printf("\n");
     for(i=0;i<6;i++)
       {    c=0;
        for(j=0;j<i+1;j++)
        {
            if(ip[i][0] == b[j])
            {
                c=1;
                break;
            }
        }
        if(c !=1)
        {
          b[cnt] = ip[i][0];
          cnt++;
        }

        }
    for(i=cnt-1;i>=0;i--)
    {   leading[i].n=0;
        col=1;
        leading[i].lead[0]=b[i];
        findLeading(b[i],i);
    }

    printf("\n");

    for(i=0;i<cnt;i++)
    {
        for(j=0;j<=leading[i].n;j++)
        {
            if(j==0)
            {
                    printf("leading(%c) = { ",leading[i].lead[j]);
             }
           else if(j == leading[i].n)
           {
               printf("%c ",leading[i].lead[j]);
           }
           else
           {
               printf("%c,",leading[i].lead[j]);
           }

        }
        printf("}");
        printf("\n");
    }

}
int isSym(char ip)
{
    int i;
    for(i=0;i<5;i++)
    {
        if(ip==Sym[i])
        {
            return 1;
        }
    }

    return 0;
}
void findLeading(char p,int row)
{
    int i;
    for(i=5;i>=0;i--)
    {
        if(p == ip[i][0])
        {
            if((ip[i][2] == '>') && (ip[i][4]=='\0'))
            {
                if(isupper(ip[i][3]))
                {
                                leadTabOp(ip[i][3],row);
                }
                else
                {
                                leading[row].lead[col]=ip[i][3];
                                leading[row].n++;
                                col++;
                }
            }
            if( (ip[i][2] == '>') && ( isupper(ip[i][3]) ) && ( isSym( ip[i][4] ) ) )
            {
                            leading[row].lead[col]=ip[i][4];
                            col++;
                            leading[row].n++;
            }
            if( ( ip[i][2] == '>') && ( isSym( ip[i][3] ) ) && ( isupper( ip[i][4] ) ) )
            {
                            leading[row].lead[col]=ip[i][3];
                            col++;
                                leading[row].n++;
            }
        }
    }
}
void leadTabOp(char p,int row)
{   int i,j;
    for(i=0;i<cnt;i++)
    {
        if(p == leading[i].lead[0])
        {
            for(j=1;j<=leading[i].n;j++)
            {
                leading[row].lead[col]=leading[i].lead[j];
                col++;
                leading[row].n++;
            }
        }
    }
}

Please review this.


texts:
I wrote this class for the project I'm currently working on. It's basically used to change a user's password. I'd like to know your thoughts on the basic structure/design of this class and how it can be improved, or if you'd have written it differently.

class Recover_password{
    //class by sami
    private $conn;
    private $password_one;
    private $password_two;

    function initialize_connection($conn){
        if($conn instanceof PDO){
            $this->conn = $conn;
        }else{
            echo "Connection problem accured";
        }
    }

    function is_posted(){
        if(isset($_POST["change_password"])){
            $this->is_empty();
        }else{
            echo "nothing's being posted!";
        }
    }

    private function is_empty(){
        foreach($_POST as $post_value){
            if(!empty($post_value)){
                $is_empty = false;
            }else{
                echo "Field/s are empty";
                break;
            }
        }

        if(isset($is_empty)){
            $this->set_values();
        }
    }

    private function set_values(){
        $this->password_one = strip_tags(stripslashes(trim($_POST["password_two"], '"')));
        $this->password_two = strip_tags(stripslashes(trim($_POST["password_one"], '"')));

        if($this->password_one == $this->password_two){
            if( (strlen($this->password_one) > 10) or (strlen($this->password_two) > 10) ){
                $this->password_one = md5($this->password_one);
                $this->change_password_to_new();
            }else{
                $this->show_message("The password you provided is too weak");
            }
        }else{
            $this->show_message("Please make sure the passwords match");
        }
    }

    private function change_password_to_new(){
        $insert_pass_query = $this->conn->prepare("update registered_users set user_password = :user_password where username = :username");
        if( $insert_pass_query->execute(array('user_password'=>$this->password_one, 'username'=>$_SESSION["logged_in"])) ){
            $this->show_message("Password has been sucessfully changed!");
        }else{
            $this->show_message("Unknown error occured, please contact admin.");
        }
    }

    private function show_message($message){
        $_SESSION["message"] = $message;
        header("location: show_message.php");
    }
}


texts: Get the value of the precedent day in a pivot table

texts:
I have a pivot table of approximately 2 millions lines coming from a dataframe with the same structure as below:
raw = pd.DataFrame([[123456,datetime(2020,7,1),'A',10 ],
                   [123456,datetime(2020,7,1),'B',25 ],
                   [123456,datetime(2020,7,1),'C',0 ],
                   [123456,datetime(2020,7,2),'A',17 ],
                   [123456,datetime(2020,7,2),'B',23 ],
                   [123456,datetime(2020,7,2),'C',float('NaN') ],
                   [789012,datetime(2020,7,2),'A',11 ],
                   [789012,datetime(2020,7,2),'B',19 ],
                   [789012,datetime(2020,7,3),'A',8 ],
                   [789012,datetime(2020,7,3),'B',21 ]],
                   columns=['GROUP_ID','DATE', 'NAME', 'VALUE'])

    GROUP_ID    DATE    NAME VALUE
0   123456  2020-07-01   A   10.0
1   123456  2020-07-01   B   25.0
2   123456  2020-07-01   C    0.0
3   123456  2020-07-02   A   17.0
4   123456  2020-07-02   B   23.0
5   123456  2020-07-02   C    NaN
6   789012  2020-07-02   A   11.0
7   789012  2020-07-02   B   19.0
8   789012  2020-07-03   A    8.0
9   789012  2020-07-03   B   21.0

As you can see, the VALUE column can be Nan.
The pivot table is created like this:
pt = raw.pivot_table(index=['GROUP_ID', 'DATE'], columns=['NAME'], values=['VALUE'])

                      VALUE
            NAME      A      B       C
GROUP_ID    DATE
123456  2020-07-01  10.0    25.0    0.0
        2020-07-02  17.0    23.0    NaN
789012  2020-07-02  11.0    19.0    NaN
        2020-07-03   8.0    21.0    NaN

The idea is to create a level 0 column VALUE_PREV where I can have the value of C for the day before.
I first did this, and it took 10 seconds:
dfA = pt.stack().unstack(level='DATE').shift(1, axis=1).stack(level='DATE')
dfA = dfA[dfA.index.get_level_values('NAME') == 'C']
dfA = dfA.unstack(level='NAME').rename(columns={'VALUE':'VALUE_PREV'})
ptA = pt.merge(dfA, how='outer', on=['GROUP_ID', 'DATE'])

                     VALUE                 VALUE_PREV
            NAME     A         B     C     C
GROUP_ID    DATE
123456  2020-07-01  10.0    25.0    0.0   NaN
        2020-07-02  17.0    23.0    NaN   0.0
789012  2020-07-02  11.0    19.0    NaN   NaN
        2020-07-03   8.0    21.0    NaN   NaN

So I was wondering if there is a quicker way to do this or at least something less heavy to write / understand?
Edit : if the VALUE C is NaN at t, VALUE_PREV C at t+1 MUST be NaN and not 0


texts: Lights on: playing with buttons in Javascript

texts:
First play with the game a little bit, and it is quite fun (a little hard but very satisfying when you win, be sure to put it full page):

<!DOCTYPE html5>

  <title>Lights on</title>

Clicking a button inverts it and its neightbours.
You win when you switch on all the lights.

  <button style="height:150px;width:150px" id=1 onclick="switch_with_neightbors(1)">0</button>
  <button style="height:150px;width:150px" id=2 onclick="switch_with_neightbors(2)">1</button>
  <button style="height:150px;width:150px" id=3 onclick="switch_with_neightbors(3)">0</button>

  <button style="height:150px;width:150px" id=4 onclick="switch_with_neightbors(4)">1</button>
  <button style="height:150px;width:150px" id=5 onclick="switch_with_neightbors(5)">1</button>
  <button style="height:150px;width:150px" id=6 onclick="switch_with_neightbors(6)">1</button>

  <button style="height:150px;width:150px" id=7 onclick="switch_with_neightbors(7)">1</button>
  <button style="height:150px;width:150px" id=8 onclick="switch_with_neightbors(8)">1</button>
  <button style="height:150px;width:150px" id=9 onclick="switch_with_neightbors(9)">0</button>

Ok, now the bad news:

I put HTML and JavaScript together. Would separating them improve readability?
I generate 9 buttons by hand, and I copy-paste the size for each one. Can I avoid so much repetition?
I am confused by the looping constructs of JavaScript. Is my use of the for .. in sensible?
I put the neighbours hash inside a function. Is this standard practice? Is this weird?
I cast variables to different types all the time. Can you help me spot unnecessary conversions?
Is my code modular enough?


texts:
Given a typelist, return a typelist of all the permutations of it. For example:

using Types = typelist<char, int, double>;
using Permutations = typelist<
    typelist<char, int, double>,
    typelist<char, double, int>,
    typelist<int, char, double>,
    typelist<int, double, char>,
    typelist<double, char, int>,
    typelist<double, int, char>
    >;

static_assert(std::is_same<permute_t<Types>, Permutations>{}, "!");

There are two different ways of writing metafunction "overloads": partial specialization or function overloading. I'm still unsure of which is "better", and in this solution I ended up using both, which strikes me as questionable.

The algorithm here is: the permutations of a list is the concatenation of (each element in the list prepended to all the permutations of the list with that element removed).

template <class...> struct typelist { };
template <class T> struct tag { using type=T; };

// remove first instance of type from a typelist
template <class T, class... Ts, class... Rs>
auto remove_first(tag<T>, typelist<T, Ts...>, typelist<Rs...>)
    -> tag<typelist<Rs..., Ts...>>;

template <class T, class F, class... Ts, class... Rs>
auto remove_first(tag<T>, typelist<F, Ts...>, typelist<Rs...>)
    -> decltype(remove_first(tag<T>{}, typelist<Ts...>{}, typelist<Rs..., F>{}));

template <class T, class TL>
using remove_first_t = typename decltype(remove_first(tag<T>{}, TL{}, typelist<>{}))::type;

// concatenate lots of typelists into one typelist
template <class TL>
auto concat(TL ) -> tag<TL>;

template <class... A, class... B, class... Cs>
auto concat(typelist<A...>, typelist<B...>, Cs... cs)
    -> decltype(concat(typelist<A..., B...>{}, cs...));

template <class... Ts>
using concat_t = typename decltype(concat(Ts{}...))::type;

// prepend a type onto a typelist of typelists
template <class T, class... TLs>
auto prepend(tag<T>, typelist<TLs...>)
    -> tag<typelist<concat_t<typelist<T>, TLs>...>>;

template <class T, class TL>
using prepend_t = typename decltype(prepend(tag<T>{}, TL{}))::type;

// get all the permutations of a typelist
template <class T, class=void>
struct permute : tag<typelist<T>> { };

template <class T>
using permute_t = typename permute<T>::type;

template <class... Ts>
struct permute<typelist<Ts...>, std::enable_if_t<(sizeof...(Ts)>1)>>
    : tag<
        concat_t<
            prepend_t<
                Ts,
                permute_t<remove_first_t<Ts, typelist<Ts...>>>
            >...
        >
    >
{ };


texts: Create a probability list which sums up to one

texts:
I use the numpy.random.choice method to draw a sample from a list.

The entries in the list are short dicts and look like

{'name': 'SomeName', 'strength': 0.75},
{'name': 'SomeName', 'strength': 0.25},
...

I want to use the 'strength' value (between 0 and 1) as a probability indicator.

To use
drawResults = choice(data, drawCount, p=resultProb)

I have to create the resultProb list which has to sum up to 1

So I came up with a function:

def makeProbabilities(data) -> list:
    probResult = []

    totalScore = sum(item['strength'] for item in data) # calculate in sum of all 'strength' values

    for item in data:
        if item['strength'] > 0:
            value = (100.0/totalScore)*item['strength'] #how much is this strength in relation to the total
            value2 = (1.0/100)*value                    #how much is the result above in relation to 1

            probResult.append(value2)
        else:
            probResult.append(0.0)

    return probResult

That seems to work, it just have a very small rounding error on the result (the sum is like 1.0000000001) but the numby.choice method does accept it.

But I have the strong impression that this solution is a bit awkward, un-pythonique and perhaps not very efficient on large data sets.

I am just discovering python so I am a bit lost with all the information concerning this language.

Any feedback on that is very welcome.


texts:
I am just starting out with golang. I implemented the merge sort algorithm just to practice.

Any suggestions or criticisms regarding the coding style?

package main

import (
    "fmt"
)

func main() {
    A := []int{3, 5, 1, 6, 1, 7, 2, 4, 5}
    fmt.Println(sort(A))
}

// top-down approach
func sort(A []int) []int {
    if len(A) <= 1 {
        return A
    }

    left, right := split(A)
    left = sort(left)
    right = sort(right)
    return merge(left, right)
}

// split array into two
func split(A []int) ([]int, []int) {
    return A[0:len(A) / 2], A[len(A) / 2:]
}

// assumes that A and B are sorted
func merge(A, B []int) []int {
    arr := make([]int, len(A) + len(B))

    // index j for A, k for B
    j, k := 0, 0

    for i := 0; i < len(arr); i++ {
        // fix for index out of range without using sentinel
        if j >= len(A) {
            arr[i] = B[k]
            k++
            continue
        } else if k >= len(B) {
            arr[i] = A[j]
            j++
            continue
        }
        // default loop condition
        if A[j] > B[k] {
            arr[i] = B[k]
            k++
        } else {
            arr[i] = A[j]
            j++
        }
    }

    return arr
}


texts: SQL transaction management in Node.js with MySQL: use the existing transaction or create a new one if none exists

texts:
I'm trying to implement a SQL transaction management in Node.js, that would append queries to an existing transaction if available, or create a new one if none exists yet, thanks to an optional
connection parameters. I'm using the mysql NPM package, and after having had a look to their (rather small) section about transactions, I came up with the following:

import mysql from "mysql";

const pool = mysql.createPool({
  ...
});

const _getConnection = () => new Promise((resolve, reject) => {
  pool.getConnection((error, connection) => {
    if (error) {
      reject(error);
    } else {
      resolve(connection);
    }
  });
});

const _beginTransaction = (connection) => new Promise((resolve, reject) => {
  connection.beginTransaction((error) => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  });
});

const _commitTransaction = (connection) => new Promise((resolve, reject) => {
  connection.commit((error) => {
    if (error) {
      reject(error);
    } else {
      resolve();
    }
  });
});

const _rollbackTransaction = (connection) => new Promise((resolve) => {
  connection.rollback(resolve);
});

const _transactional = async (run, retry = true) => {
  const connection = await _getConnection();
  await _beginTransaction(connection);
  try {
    const result = await run(connection);
    await _commitTransaction(connection);
    return result;
  } catch (error) {
    await _rollbackTransaction(connection);
    const errorCode = error && error.code;
    if ("ER_LOCK_DEADLOCK" === errorCode && retry) {
      return _transactional(run, false);
    } else {
      throw error;
    }
  } finally {
    connection.release();
  }
};

export const transactional = (run) => async (...args) => {
  if (args.length) {
    const lastArg = args[args.length - 1];
    if (lastArg && "PoolConnection" === lastArg.constructor.name) {
      return run(...args);
    }
  }
  return _transactional(async (connection) => run(...[...args].concat(connection)));
};

export const query = (sql, values, connection) => new Promise((resolve, reject) => {
  connection.query(sql, values, (error, results) => {
    if (error) {
      reject(error);
    } else {
      resolve(results);
    }
  });
});

Now, in some other file:

import { transactional, query } from "./..."

export const fn1 = transactional(async (x, y, z, connection) => {
  const result = await query("...", [x, y], connection);
  return query("...", [result.id, z], connection);
});

export const fn2 = transactional(async (x, y, z, connection) => {
  // passing the connection instance to fn1,
  // so that it does not create a new transaction,
  // but rather use the one created by fn2
  // (where this connection instance comes from):
  await fn1(x, y, z, connection);
  return query("...", [], connection);
});

Finally, in some other file again:

// fn1 will create its own transaction since none is passed:
await fn1(x, y, z);

// fn2 will create its own transaction since none is passed,
// but when it calls fn1, that same transaction will be used:
await fn2(x, y, z);

This seems to do the job quite nicely so far, but we aren't really under heavy load yet, more in a kind of "beta-live" state at the moment.

So the question is, will it scale? Do you see any issue with this implementation? I don't like reinventing square wheels, but I couldn't find such implementation already.


texts: VBA Automatic insert in a Excel Spreadsheet

texts:
Since I'm new at this site I will try to start with something very simple.

I'm making an "Automatic insert" in a Excel Spreadsheet and my code is working correctly, but I'm not so sure about my way of coding. Does the code follow good VBA programming practices?

Here is my code:

Option Explicit

Sub inserisciAutomatico()
Application.ScreenUpdating = False
Application.EnableEvents = False

Dim KitNr As String
Dim KitNrAppoggio As String
Dim kitNrSecondoAppoggio As String
Dim provaFormula As Range
Dim primoValore As String
Dim numeroID As String
Dim descrizione As String
Dim gruppo As String

Dim concatena As String
Dim disegno As String
Dim treD As String
Dim distinta As String
Dim immagine As String
Dim formulaCopy As String

Dim cell As Range
Dim risultato As Range
Dim risultatoAppoggio As Range

Dim valore As String
Dim appoggio As String

Dim provissima As Integer

valore = Worksheets("CODICI").ComboBox1.Value
appoggio = "fine"

Set cell = Worksheets("CODICI").Range("D4:D250").Find(valore)

'Debug.Print cell.Address

Set risultato = Worksheets("CODICI").Range("D4:D250").Find(appoggio, LookIn:=xlValues, After:=cell)
Set risultatoAppoggio = Worksheets("CODICI").Range("D4:D250").Find(Worksheets("CODICI").ComboBox1.Value, LookIn:=xlValues)

'Debug.Print risultato.Address
'Debug.Print risultatoAppoggio.Address

'kitNr = risultato.Offset(0, -2)
kitNrSecondoAppoggio = risultatoAppoggio.Offset(-1, -3)

Set provaFormula = Worksheets("CODICI").Range("Z1")

provaFormula.FormulaArray = "=MAX(IF(LEFT(B7:B250,1)=""" & kitNrSecondoAppoggio & """, B7:B250))"

KitNr = Worksheets("CODICI").Range("Z1").Value

Debug.Print provaFormula.FormulaArray

KitNrAppoggio = KitNr + 1

'Application.WorksheetFunction.Max (Range("a:a"))

Range(risultato.Address).EntireRow.Insert

primoValore = risultato.Offset(-1, -3).Address
numeroID = risultato.Offset(-1, -2).Address
descrizione = risultato.Offset(-1, 0).Address
gruppo = risultato.Offset(-1, 1).Address
concatena = risultato.Offset(-1, 2).Address
disegno = risultato.Offset(-1, 3).Address
treD = risultato.Offset(-1, 4).Address
distinta = risultato.Offset(-1, 5).Address
immagine = risultato.Offset(-1, 6).Address
formulaCopy = risultato.Offset(-2, 2).Address

Range(primoValore).Value = "T0"

Range(numeroID).Value = KitNrAppoggio
Range(numeroID).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
'Range(numeroID).Borders(xlEdgeBottom).Weight = xlHairline
Range(numeroID).Font.Bold = False
Range(numeroID).Font.Name = "Calibri"
Range(numeroID).Font.Size = 10

Range(descrizione).Font.Bold = False
Range(descrizione).Font.Name = "Calibri"
Range(descrizione).Font.Size = 10
Range(descrizione).Value = Worksheets("CODICI").TextBox1.Value
Range(descrizione).Borders(xlEdgeBottom).LineStyle = XlLineStyle.xlContinuous
'Range(descrizione).Borders(xlEdgeBottom).Weight = xlHairline

Range(gruppo).NumberFormat = "@"
Range(gruppo).Value = Worksheets("CODICI").ComboBox2.Value
Range(formulaCopy).Select
Selection.Copy
Range(concatena).PasteSpecial xlPasteFormulas
'Range(concatena).Value = "T0" + KitNrAppoggio + Worksheets("CODICI").ComboBox2.Value

Range(disegno).Value = ".dwg"
Range(treD).Value = ".asm"
Range(distinta).Value = ".xls"
Range(immagine).Value = ".jpg"


texts: Check string is permutation of palindrome

texts:
I assume there can be space in between and I have ignored that. Also, there will be only lower case characters in the string.

My logic: There can be only one occurrence of odd number of character in palindrome string.

#include <iostream>
#include <algorithm>
#include <unordered_map>

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

int main(int argc, const char * argv[]) {

    char arr[] = "tact coa";

    std::unordered_map<char, int> m;

    size_t len = strlen(arr);

    for (int i = 0; i<len; i++) {

        if(arr[i] == ' ') continue; //ignoring space

        if(m.find(arr[i]) == m.end())
        {
             m[arr[i]] = 1;

        }
        else{
            m[arr[i]]++;
        }
    }

    int count = 0;

    for (int i = 0; i<len; i++) {

        if((m[arr[i]] % 2) == 1)count++;

    }
    if(count > 1) {cout<<"Not Palindrom"<<endl;}
    else {cout<<"Palindrom"<<endl;}

    return 0;
}


texts: Formatting seconds as days hours minutes seconds

texts:
I have the below and it gives me the desired output (ie; 1 day 12:05:33) but it looks overly complicated, is there a more straight forward way of doing this with the least amount of string concatenations?

     std::string eta_string ( int64_t s ) {

     time_t seconds ( s );
     tm p;
     gmtime_s ( &p , &seconds );
     std::string str;

     if ( p.tm_yday > 0 ) {
      if ( p.tm_yday == 1 ) {
        str = std::to_string ( p.tm_yday ) += " day ";
      } else {
        str = std::to_string ( p.tm_yday ) += " days ";
      }
      if ( p.tm_hour < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_hour ) += ":";
      } else {
        str = str += std::to_string ( p.tm_hour ) += ":";
      }
      if ( p.tm_min < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_min ) += ":";
      } else {
        str = str += std::to_string ( p.tm_min ) += ":";
      }
      if ( p.tm_sec < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_sec );
      } else {
        str = str += std::to_string ( p.tm_sec );
      }
     }
     else if ( p.tm_hour > 0 ) {
      if ( p.tm_hour < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_hour ) += ":";
       } else {
        str = str += std::to_string ( p.tm_hour ) += ":";
       }
       if ( p.tm_min < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_min ) += ":";
       } else {
        str = str += std::to_string ( p.tm_min ) += ":";
       }
       if ( p.tm_sec < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_sec );
       } else {
        str = str += std::to_string ( p.tm_sec );
       }
     } else if ( p.tm_min > 0 ) {
      str = "00:";
      if ( p.tm_min < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_min ) += ":";
      } else {
        str = str += std::to_string ( p.tm_min ) += ":";
      }
      if ( p.tm_sec < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_sec );
      } else {
        str = str += std::to_string ( p.tm_sec );
      }
     } else {
      str = "00:00:";
      if ( p.tm_sec < 10 ) {
        str = str.append ( "0" ) += std::to_string ( p.tm_sec );
      } else {
        str = str += std::to_string ( p.tm_sec );
      }
    }
    return str;
 }


texts:
Here is a simple Python script that I wrote with lots of help from the Python mailing list. I moves all the files of subdirectories to the top level directory. It works well for my use, but if there are things that can be improved then I would like to know. I ask in the interest of being a better Python programmer and learning the language better. Thanks.

#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import os
import shutil

currentDir = os.getcwd()
forReal = False

if ( currentDir in ['/home/dotancohen', '/home/dotancohen/.bin'] ):
        print "Error: Will not run in "+currentDir
        exit()

if ( len(sys.argv)>1 and sys.argv[1] in ['m', 'M', 'c', 'C'] ):
        forReal = True
else:
        print "\nThis is a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name.\n"

filesList = os.walk(currentDir)

for rootDir, folders, files in filesList:
        for f in files:
                if (rootDir!=currentDir):
                        toMove = os.path.join(rootDir, f)
                        print toMove
                        newFilename = os.path.join(currentDir,f)
                        renameNumber = 1
                        while(os.path.exists(newFilename)):
                                newFilename = os.path.join(currentDir,f)+"_"+str(renameNumber)
                                renameNumber = renameNumber+1
                        if ( forReal and sys.argv[1] in ['m', 'M'] ):
                                os.rename(toMove, newFilename)
                        elif ( forReal and sys.argv[1] in ['c', 'C'] ):
                                shutil.copy(toMove, newFilename)

if ( not forReal ):
        print "\nThis was a test run. To actually perform changes, add 'm' (move) or 'c' (copy) after the program name."


texts: add_const or remove_const based on another type

texts:
Here is a type trait which - I feel - could fit in std next to std::add_const and std::remove_const:

#include <type_traits>

template <typename T>
struct set_constness_of {
    template <typename U>
    struct by {
        using type = typename std::conditional<
            std::is_const<U>::value,
            typename std::add_const<T>::type,
            typename std::remove_const<T>::type
            >::type;
    };
};

Note this is intentionally C++11 to minimize requirements for using it. One can obviously define set_constness_of_t in which by is a type rather than a struct with a type.

I've also written a tiny sample program (coliru.com) to ensure it runs, at least for some cases.

/* the above definition of set_constness_of goes here (paste it) */
#inlcude <iostream>

struct foo {
    void m() { std::cout << "Non-const\n"; }
    void m() const { std::cout << "Const\n"; }
};

template <class T> void call_m() { T().m(); }

int main() {
    call_m<foo>();
    using bar = const int;
    call_m< set_constness_of<foo>::by<bar>::type >();
}

Questions:

Is this correctly defined for all cases?
What do you think about placing the second template parameter as an inner struct's template param, rather than having two template parameters on the outer struct?
What do you think about the choice of naming?

Other comments are welcome.


texts:
Here is my word break problem in c#

static void breakSentenceIntoWords(string input,List<string> validWords)
    {
        if (String.IsNullOrEmpty(input))
            throw new Exception("String cannot be empty");

        int indicator = 0;
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < input.Length; i++)
        {
            builder.Append(input[i]);
            if (validWords.Contains(builder.ToString()))
            {
                indicator += builder.ToString().Length;
                Console.Write("{0} ", builder.ToString());
                builder.Clear();
            }
        }

        if (indicator != input.Length)
        {
            Console.WriteLine("Not all words could be found");
        }
    }

    List<string> validwords = new List<string>() { "I", "like", "had", "play","to" };
        breakSentenceIntoWords("Ihadplayliketo", validwords);

I think the complexity here is O(n2) because of the for-loop and the contains method. How can I improve its efficiency ?


texts:
Is this code okay?

import java.util.Stack;

public class DelimiterMatching {

    public static void main(String[] args) {

        final String input = "[(A+B)]";

        delimiterCheck(input);
    }

    public static void delimiterCheck(String input) {
        if (input.length() == 0) {
            System.out.println("String is empty");
        }
        Stack<Character> theStack = new Stack<>();
        for (int i = 0; i < input.length(); i++) {
            char individualChar = input.charAt(i);
            if (individualChar == '{' || individualChar == '['
                    || individualChar == '(') {
                theStack.push(individualChar);

            } else if (individualChar == '}' || individualChar == ']'
                    || individualChar == ')') {
                if (!theStack.isEmpty()) {
                    char individualCharRight = theStack.pop();
                    if ((individualChar == '}' && individualCharRight != '{')
                            || (individualChar == ')' && individualCharRight != '(')
                            || (individualChar == ']' && individualCharRight != '[')) {
                        System.out.println("Error at index " + i);
                    }
                }
            }
        }
        if (!theStack.isEmpty()) {
            System.out.println("Error in delimiter");
        }
    }
}


texts: Frequency analysis for simultaneous dice rolls - follow-up

texts:
I had another question for my Perl class assignment.

Related question:

Frequency analysis for simultaneous dice rolls

use warnings;
use diagnostics;
use GD::Graph::hbars;
use List::Util qw(max);
my $number_of_dice=0;
my $number_of_rolls=0;
my @total_sum_of_eyes;
my %count;
my $counter=0;

print "\n Please insert the number_of_dice: ";
chomp($number_of_dice=<STDIN>);
print "\n Please instert the number_of_rolls: ";
chomp($number_of_rolls=<STDIN>);

while ($counter< $number_of_rolls){
    push(@total_sum_of_eyes,roll($number_of_dice));
    $counter++;
}
frequency(@total_sum_of_eyes);
representation(%count);

sub roll{
    my $number=0;
    my $sum_of_throw=0;
    $sum_of_throw = 0;
    for($i=0;$i<$number_of_dice;$i++){
        $number = int(rand(6) +1);
        $sum_of_throw+=$number;
    }
    return $sum_of_throw;
}
sub frequency{

    for($i=0;$i<$number_of_rolls;$i++){
        $count{$total_sum_of_eyes[$i]}++;
    }
    return;
}
sub representation{
    my @single_sum_of_eyes;
    my @frequency;
    print "\n the frequencys-distribution is: \n";
    print "\n total_sum_of_eyes\t frequency\t frequencys-distribution in %\n";
    foreach my $eyes (sort{$a <=> $b} keys %count){
        push(@frequency, $count{$eyes});
        push(@single_sum_of_eyes, $eyes);
        printf "\n\t $eyes\t\t\t  $count{$eyes}\t\t%g",($count{$eyes}/$number_of_rolls)*100;
    }
    print "\n";
    my $graph = GD::Graph::hbars->new(1600, 600);
$graph->set(
    x_label             => 'total_sum_of_eyes',
    y_label             => 'frequency',
    title               => 'frequencys-distribution',
    y_max_value         =>  max(@frequency)+1,
    y_tick_number       => 8,
    transparent         => 0,
    long_ticks          => 1,
) or die $graph->error;
my @data = (\@single_sum_of_eyes,\@frequency);
$graph->set( dclrs => [ qw(green) ] );
my $gd = $graph->plot(\@data) or die $graph->error;
open(IMG, '>gd_bars.gif') or die $!;
binmode IMG;
print IMG $gd->gif;
return;
}

frequency(@total_sum_of_eyes);
representation(%count);

Is this necessary?

foreach my $eyes (sort{$a <=> $b} keys %count){
        push(@frequency, $count{$eyes});
        push(@single_sum_of_eyes, $eyes);
        printf "\n\t $eyes\t\t\t  $count{$eyes}\t\t%g",($count{$eyes}/$number_of_rolls)*100;
    }

I can't seem to find a simple for-loop for this one.


texts: Using a template to cycle through a sequence of containers

texts:
I'm trying to implement a template that takes a container as parameter. The template has a getnext method that cycles through the elements in the parameter. Take note that I'm not using C++11.

Header:

#pragma once

template<template<class, class> class TContainer, class TObject>
class cycle
{
public:

    explicit cycle( TContainer<TObject, std::allocator<TObject>> & container )
        : mContainer( container ), index(0) {}

    TObject getNext(int numObjectsToCycle)
    { return mContainer[index++ % numObjectsToCycle]; }
private:
    TContainer<TObject, std::allocator<TObject>> & mContainer;
    int index;
};

Implementation:

#include <iostream>
#include <vector>

#include "cycle.h"

using namespace std;

class Processor
{
   int mIndex;
   vector<int> numbers;

public:
   cycle<vector, int> cycler;
   // Is it safe to pass numbers since it is declared first??
   Processor() : mIndex(0), cycler(numbers) {}
   void update() { cout << numbers[mIndex++ % numbers.size()] << std::endl;}
   void addNumber(int x) { numbers.push_back(x); }
};

int main()
{
   Processor S;

   for (int i = 0; i < 5; ++i)
   {
      S.addNumber(i+1);
   }
   cout << "using update" << endl;
   for (int c = 0; c < 10; ++c)
   {
      S.update();
   }

   cout << "using cycle" << endl;
   for (int c = 0; c < 10; ++c)
   {
      cout << S.cycler.getNext(5) << endl;
   }

   std::cin.get();

}

Any improvement or potential issues to the code?


texts:
Wondering if I could do this a little bit better. Currently, my DAL has a blank constructor that sets the connection string from the web.config.

private string cnnString;

public DAL()
{
    cnnString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
}

Then each method in here is mapped directly to a stored procedure, and they ALL look something like this:

public bool spInsertFeedback(string name, string subject, string message)
{
    int rows = 0;

    SqlConnection connection = new SqlConnection(cnnString);
    try
    {
        connection.Open();
        SqlCommand command = new SqlCommand("[dbo].[spInsertFeedback]", connection);
        command.CommandType = CommandType.StoredProcedure;

        // params
        SqlParameter messageName = new SqlParameter("@name", SqlDbType.VarChar);
        messageName.Value = name;
        SqlParameter messageSubject = new SqlParameter("@subject", SqlDbType.VarChar);
        messageSubject.Value = subject;
        SqlParameter messageText = new SqlParameter("@message", SqlDbType.VarChar);
        messageText.Value = message;

        // add params
        command.Parameters.Add(messageName);
        command.Parameters.Add(messageSubject);
        command.Parameters.Add(messageText);

        rows = command.ExecuteNonQuery();
    }
    catch
    {
        return (rows != 0);
    }
    finally
    {
        connection.Close();
    }

    return (rows != 0);
}

Obviously some return a DataSet or a list of an object or something, where as this one just returns whether or not any rows were affected.

However, each method does things this way, and I just feel like I have a lot of redundant code, and I'd like to simplify it. From the other classes, I'm calling the DAL like this:

DAL dal = new DAL();
bool success = dal.spInsertFeedback(name, subject, message);
return Json(success);

Thanks guys.


texts: Displaying recent buyers' feedback on games

texts:
I have the following code made to output the following:

Is there an efficient way to simplify it and not have to repeat the same if(!empty($st[$i]['feedback'])) { code block 2 times just to seperate 2 feedback lines with a echo '

';?

<?php

//Get 4 Feedback from Database;
$st = fetch("SELECT username,feedback,feedback_type,feedback_date FROM purchases WHERE feedback IS NOT NULL AND game = :game AND platform = :platform ORDER BY feedback_date DESC LIMIT 4","unfed_payments",array(":game"=>$urlname,":platform"=>$platform));

echo '
';

//Output the first 2 Feedback on line 1;
for($i = 0; $i < 2; $i++) {

    if(!empty($st[$i]['feedback'])) {

        echo '

';
                    echo $st[$i]['feedback'].'

';

    }

}

echo '

';

//Output the last 2 Feedback on line 2;
for($i = 2; $i < 4; $i++) {

    if(!empty($st[$i]['feedback'])) {

        echo '

';
                    echo $st[$i]['feedback'].'

';

    }

}

echo '
';

?>


texts:
The idea is, you enter an amount of ships, for example 10. It will then place 10 ships on a 10x10 grid (0-9). You may enter a coordinate, and it will tell you if it is a hit or a miss. A simplified version of the well-known board game.

C indicates 'Computer'. These are not shown on the grid, but are stored in the 2D array.
H indicates 'Hit'. Self explanatory.
M indicates 'Miss'. Also self explanatory.
Null / whitespace indicates that nothing has been set at that coordinate.

I created this program with the intent of making it as efficient and readable as possible. It's difficult to explain the inner workings of my mind, so I apologize for no comments.

best ran outside of IDE (in console)

code:

import random, os

ships = int(input("Enter ship count: "))
gridSize = 10
game = [[' ' for x in range(gridSize)] for y in range(gridSize)]

def getGrid(x,y):
    return game[x][y]

def setGrid(x,y,char):
    game[x][y] = char

for i in range(ships):
    x = random.randint(0,gridSize-1)
    y = random.randint(0,gridSize-1)
    setGrid(x,y,'C')

xLabel = " " * 3
for i in range(gridSize):
    xLabel += str(i) + " "

result = "Make a move!"
hits = 0

while hits != ships:
    os.system("cls")
    print(" " + result + " [Ships: " + str(ships) + ", Size: " + str(gridSize) + ", Hits: " + str(hits) + "]\n")
    print(xLabel)
    for x in range(gridSize):
        print(" " + str(x) + " ",end="")
        for y in range(gridSize):
            print(" " * 2 if getGrid(x,y) == 'C' else getGrid(x,y) + " ",end="")
        print("")

    xGuess = int(input("\n X: "))
    yGuess = int(input(" Y: "))

    if getGrid(xGuess,yGuess) == 'C':
        result = "Hit! (" + str(xGuess) + ":" + str(yGuess) + ")"
        setGrid(xGuess,yGuess,'H')
        hits += 1
    else:
        result = "Miss! (" + str(xGuess) + ":" + str(yGuess) + ")"
        setGrid(xGuess,yGuess,'M')

print("\nCongratulations, you won the game!")
os.system("pause >nul")


texts:
In computer science, binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array.

The code returns true if an element is present in the array else returns false.

Any suggestion in improving the code is welcome.

Binary_Search.h

#ifndef BINARY_SEARCH_H
#define BINARY_SEARCH_H

bool binary_search(int ar[], int low, int high, int key);

#endif // BINARY_SEARCH_H

Binary_Search.cpp

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

/* search a key in an array using binary search */
bool binary_search(int ar[], int low, int high, int key)
{
  int mid;

  while ( low <= high )
    {
      // find the middle index
      mid = low + ((high - low) >> 1);

      if ( ar[mid] == key ) // key found
        {
          return true;
        }
      else if ( ar[mid] > key ) // key may be on the left half
        {
          high = mid - 1;
        }
      else if ( ar[mid] < key ) // key may be on the right half
        {
          low = mid + 1;
        }
    }

  // key not found
  return false;
}

int main()
{
  int ar[] = {1, 7, 9, 10, 28, 28, 36, 49, 68, 99};

  for ( int i = 0; i < sizeof(ar) / sizeof(ar[0]); ++i )
    {
      if ( binary_search(ar, 0, sizeof(ar) / sizeof(ar[0]) - 1, ar[i]) )
        {
          std::cout << ar[i] << " is present" << std::endl;
        }
      else
        {
          std::cout << ar[i] << " is not present" << std::endl;
        }
    }

  int ar1[] = {-1, 2, 3, 12, 23, 50, 90, 98, 100};
  for ( int i = 0; i < sizeof(ar1) / sizeof(ar1[0]); ++i )
    {
      if ( binary_search(ar, 0, sizeof(ar) / sizeof(ar[0]) - 1, ar1[i]) )
        {
          std::cout << ar1[i] << " is present" << std::endl;
        }
      else
        {
          std::cout << ar1[i] << " is not present" << std::endl;
        }
    }
  return 0;
}