texts: Assign a unique number to duplicate items in a list

texts:
I made a program, but I not happy with the quantity of code. The end result is good, but I believe it can be made much easier, only I don't know how.

The functionality: If equal items > 1 in list, then assign all equal items a unique set number.  Below I made a unit test. I'm not happy with the class CreatSet. Can somebody advise me on how this can be implemented better?

import unittest

class Curtain(object):
  def __init__(self, type, fabric, number):
      self.type = type
      self.fabric = fabric
      self.number = number
      self.set_number = None

  def __str__(self):
      return '%s %s %s %s' % (self.number, self.type, self.fabric, self.set_name)

  def __eq__(self, other):
      return self.type == other.type and self.fabric == other.fabric

class CreatSet(object):
  def make_unique(self, original_list):
      checked = []
      for e in original_list:
          # If curtain: type and fabric is equal
          if e not in checked:
              checked.append(e)
      return checked

  def create_set(self, curtains):
      # Uniuqe items in list
      unique_list = self.make_unique(curtains)
      result = []
      for x in unique_list:
          # Create set list
          set_range = []
          for y in curtains:
              if y == x:
                  set_range.append(y)
          # Add set range into list
          result.append(set_range)

      # Create set number
      set_result = []
      set_number = 0
      for x in result:
          if len(x) == 1:
              set_result.append(x[0])
          else:
              set_number += 1
              for y in x:
                  y.set_number = set_number
                  set_result.append(y)
      # Return list ordered by number
      return sorted(set_result, key=lambda curtain: curtain.number)

class TestCreateSet(unittest.TestCase):
    def setUp(self):
      self.curtains = []
      self.curtains.append(Curtain('pleatcurtain', 'pattern', 0))
      self.curtains.append(Curtain('pleatcurtain', 'plain', 1))
      self.curtains.append(Curtain('pleatcurtain', 'pattern', 2))
      self.curtains.append(Curtain('foldcurtain', 'pattern', 3))
      self.curtains.append(Curtain('pleatcurtain', 'plain', 4))
      self.curtains.append(Curtain('foldcurtain', 'plain', 5))
      self.curtains.append(Curtain('pleatcurtain', 'pattern', 6))
      self.curtains.append(Curtain('foldcurtain', 'pattern', 7))

    def test_auto_set(self):
      creat_set = CreatSet()
      result = creat_set.create_set(self.curtains)
      # Creating set
      self.assertEqual(result[0].set_number, 1)  # pleatcurtain, pattern
      self.assertEqual(result[1].set_number, 2)  # pleatcurtain, plain
      self.assertEqual(result[2].set_number, 1)  # pleatcurtain, pattern
      self.assertEqual(result[3].set_number, 3)  # foldcurtain, pattern
      self.assertEqual(result[4].set_number, 2)  # pleatcurtain, plain
      self.assertEqual(result[5].set_number, None)  # foldcurtain, plain
      self.assertEqual(result[6].set_number, 1)  # pleatcurtain, pattern
      self.assertEqual(result[7].set_number, 3)  # foldcurtain, pattern

if __name__ == '__main__':
    unittest.main()


texts: Guides the User with Prompts to go through a procedure and Records User Input

texts:
I am making a prototype worksheet that follows 9 step problem solving procedure.

Some improvements I'm considering would be to iterate over some of it instead of making a new code line for every single variant.  More or less I need to optimize this code so I can learn how to do this type of thing in the future.

It's not a very straight looping process and I can't think of any good ways to set it up.

Here is a picture of the sheet that the values will go into.

Here is my code

Sub nine_Step()

Dim step1, step2, step3, step4a, step4b, step4c, step4d, step4e, step5a, step5b, step5c, step5d, step5e, step6a, step6b, step6c, step6d, step6e, step7, step8, step9 As Variant

step1 = InputBox("Step 1: Define the Problem.")
    Cells(2, 3).Value = step1

step2 = InputBox("Step 2: What is the Measured Actual Value?")
    Cells(4, 3).Value = step2

step3 = InputBox("Step 3: What is the Target Value Desired?")
    Cells(6, 3).Value = step3

    If step3 <> "" Then
        Cells(7, 3).Value = step3 - step2
    Else:
    End If

step4a = InputBox("Step 4: Why is " & step1 & " happening?")
    Cells(9, 3).Value = step4a
step4b = InputBox("Step 4: Why is " & step4a & " happening?")
    Cells(10, 3).Value = step4b
step4c = InputBox("Step 4: Why is " & step4b & " happening?")
    Cells(11, 3).Value = step4c
step4d = InputBox("Step 4: Why is " & step4c & " happening?")
    Cells(12, 3).Value = step4d
step4e = InputBox("Step 4: Why is " & step4d & " happening?")
    Cells(13, 3).Value = step4e

step5a = InputBox("Step 5: Describe your First Possible Solution")
    Cells(15, 3).Value = step5a
step5b = InputBox("Step 5: Describe your Second Possible Solution")
    Cells(16, 3).Value = step5b
step5c = InputBox("Step 5: Describe your Third Possible Solution")
    Cells(17, 3).Value = step5c
step5d = InputBox("Step 5: Describe your Fourth Possible Solution")
    Cells(18, 3).Value = step5d
step5e = InputBox("Step 5: Describe your Fifth Possible Solution")
    Cells(19, 3).Value = step5e

step6a = InputBox("Step 6: Experiment Measurement Results Solution 1")
    Cells(21, 3).Value = step6a
step6b = InputBox("Step 6: Experiment Measurement Results Solution 2")
    Cells(22, 3).Value = step6b
step6c = InputBox("Step 6: Experiment Measurement Results Solution 3")
    Cells(23, 3).Value = step6c
step6d = InputBox("Step 6: Experiment Measurement Results Solution 4")
    Cells(24, 3).Value = step6d
step6e = InputBox("Step 6: Experiment Measurement Results Solution 5")
    Cells(25, 3).Value = step6e

step7 = InputBox("Step 7: When did you impliment a solution? Enter a date in
XX/XX/XXXX format")

If step7 = "" Then
    MsgBox ("Find out when you implimented a solution and enter it when you get a chance.")
Else:
    Cells(28, 3).Value = step7
End If

step8 = InputBox("Step 8: Now that the solution is implemented perminently, what is the current measurement?")
    Cells(31, 3).Value = step8

    If step8 <> "" Then
        Cells(32, 3).Value = Cells(6, 3).Value - step8
    Else:
    End If

step9 = InputBox("Step 9: Any other Ideas that have sprung up since you have started this nine step related to this area?")
    Cells(34, 3).Value = step9

MsgBox ("You have successfully completed this 9 Step.  Congrats!")

End Sub


texts:
I need a global data in my application. My application uses several threads to access and add items to my global variable. The global variable is a ConcurrentDictionary I choose to ensure data is added to the variable. What do you think about my approach?

public class GlobalData
{
    private static volatile GlobalData instance;
    private volatile ConcurrentDictionary<string, object> _data = new ConcurrentDictionary<string, object>();
    private static object syncRoot = new Object();

    public static GlobalData Instance
    {
        get
        {
            if (instance == null)
            {
                lock (syncRoot)
                {
                    if (instance == null)
                        instance = new GlobalData();
                }
            }

            return instance;
        }
    }

    public void Add(string id, object obj)
    {
        _data.TryAdd(id, obj);
    }

    public object Get(string id)
    {
        object value;
        _data.TryGetValue(id, out value);
        return value;
    }
}


texts: concatenation of HTML from return functions

texts:
My controller is looking something like this.

Each of the methods called generate some HTML. The concatenated HTML variable gives the final render of the page

Is there a better way to generate my HTML to render coming from different functions:

 $html = $renderer->render($clear_form);
 $html .= $this->render_preview();
 $config = \Drupal::config('amu_import_ldap.settings');
 if (null != $config) {
   $submits = $config->get('import_submits');
   $html .= $this->render_ldap_imports($submits);
 }
 $build = [
  '#markup' => Markup::create("
            {$html}
        "),
];
return $build;


texts:
Anything I can improve?

def main():
    word = 'nedim'
    hidden_word = list('_'*len(word))
    wrong_guess, amount_of_letters, guesses, done = 0, 0, 4, False

    while(wrong_guess != 5 and not done):
        guess = raw_input("Guess a letter: ")
        if len(guess) == 1 and guess.isalpha():
            while(guess in hidden_word):
                if guess in hidden_word:
                    print "Letter already exists!"
                    guess = raw_input('Try again: ')
            for letter in word:
                if letter == guess:
                    hidden_word[word.index(guess)] = guess
                    print ''.join(hidden_word)
                    if ''.join(hidden_word) == word:
                        print "\n ######## \n You won! \n ######## \n"
                        done = True
            if guess not in word:
                wrong_guess += 1
                if(guesses-wrong_guess < 0):
                    print "You have no chances left. Loser!"
                else:
                    print "You have ",guesses-wrong_guess," chances left."
        else:
            print "INVALID GUESS! \nRULES: \n\t > One guess at a time \n\t > Only english alphabet \n\t > Only Letters"

if __name__ == '__main__':
    main()


texts: Sorting and Filtering Maps Using Generics

texts:
I had a test for a Java-position where they asked me to manipulate JSON-data from an API.

Once my overall parsing of the data into Maps were done.

The test required me among other things to implement:

Parameter for sorting the data (ASC, DESC) in Maps.
Parameter for filtering the selection of names in Maps.
Parameter for only showing data with odd or even occurrences in Maps.

I passed the test, but did not get the job with the feedback: "How you implemented the sorting and filtering of the maps seemed sloppy, and it seems like you rushed through that part of the test and there's no real code-maintainability in mind for these."

So my question is: How could I have done this implementation in a better way? What flaws do you see?

These maps contains the parsed JSON-data, you will see these being used below.

public static Map<String, Integer> firstNames; /** K= names, V= occurrences of that name **/
public static Map<String, Integer> surNames;

SortMap.java

public class SortMap {

    /**
     * ascending = 1, descending != 1.
     */
    public static <K, V extends Comparable<V>> Map<K, V> sortByValues (final Map<K, V> unsortedMap, int ascending) {
        Map<K,V> sortedMap = new LinkedHashMap<>();
        unsortedMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue((Comparator<? super V>) (ascending == 1 ? Comparator.naturalOrder() : Comparator.reverseOrder())))
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        return sortedMap;
    }

    public static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> unsortedMap, int ascending) {
        Map<K,V> sortedMap = new LinkedHashMap<>();
        unsortedMap.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey((Comparator<? super K>) (ascending == 1 ? Comparator.naturalOrder() : Comparator.reverseOrder())))
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
        return sortedMap;
    }
}

Usages I provided to solve the tasks:

Map<String, Integer> firstNamesSorted = SortMap.sortByKey(firstNames,-1);
Map<String, Integer> surNamesSorted = SortMap.sortByKey(surNames,1);

FilterMap.java

public class FilterMap {

    public static <K, V> Map<K, V> filterByKey(Map<K, V> map, Predicate<K> predicate) {
        return map.entrySet()
                .stream()
                .filter(entry -> predicate.test(entry.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

    public static <K, V> Map<K, V> filterByValue(Map<K, V> map, Predicate<V> predicate) {
        return map.entrySet()
                .stream()
                .filter(entry -> predicate.test(entry.getValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }

}

Usages I provided to solve the tasks:

Map<String, Integer> filterUnevenNumbers = FilterMap.filterByValue(firstNames, value -> value % 2 == 0);
Map<String, Integer> filterNames = FilterMap.filterByKey(firstNames, value -> value.matches("(?i).*as.*"));

My own reflections of my code is:

Sorting:

-Could have used an enum instead of an int, but using any modern codeeditor you will see my javaDocs comment and also the ascending variable that you provide input for (removed javaDocs comments to reduce clutter in this instance).
+Uses generics.

Filtering:

+Uses generics.
+Dynamic implementation that can filter basically anything as long as you can create the expression using lambdas.
+Can be used for alot more purposes than what they asked for.


texts:
I'm new to JS and trying to improve my code with the use of more organised objects.  I have the following procedural code which I have converted to an object. It does an ajax load within main. Aside from grouping the methods (functions) for better organisation, what other advantages does this approach have?  Is there any way the object version of the code can be further improved?

Procedural approach

var main = $("main"),

    init = function() {

    },

    ajaxLoad = function(html) {
      document.title = html.match(/<h1>(.*?)<\/h1>/)[1].trim();
      main.fadeIn(200);
      init();
    },

    loadPage = function(href) {
      main.fadeOut(200, function() {
        main.load(href + " main>*", ajaxLoad);
      });
    };

    init();

    $(document).on('click', 'header a', function() {
      var href = $(this).attr('href');

      if (href.indexOf(document.domain) > -1 || href.indexOf(':') === -1) {
        history.pushState({}, '', href);
        loadPage(href);
        return false;
      }
    });

Object approach

var pageLoader = {

      main: $('main'),

      init: function() {},

      ajaxLoad: function(html) {
        document.title = html.match(/<h1>(.*?)<\/h1>/)[1].trim();
        pageLoader.main.fadeIn(200);
        pageLoader.init();
      },

      loadPage: function(href) {
        pageLoader.main.fadeOut(200, function() {
          pageLoader.main.load(href + " main>*", pageLoader.ajaxLoad);
        });
      },

      ajaxLink: function(href) {
        if (href.indexOf(document.domain) > -1 || href.indexOf(':') === -1) {
          history.pushState({}, '', href);
          pageLoader.loadPage(href);
        }
      }

    };

    pageLoader.init();

    $(document).on('click', 'header a', function() {

      var href = $(this).attr('href');
      pageLoader.ajaxLink(href);
      return false;

    });


texts: Finding the smallest cube for which exactly five permutations of its digits are cube

texts:
(Project Euler #62)

  The digits of the cube, 41063625 (3453), can be permuted to produce
  two other cubes:

  56623104 (3843) and 66430125 (4053). In fact, 41063625 is the
  smallest cube which has exactly three permutations of its digits which
  are also cube.

  Find the smallest cube for which exactly five permutations of its
  digits are cube.

Here is my code which properly works and prints the number of permutations which are cube for a particular i. I have found numbers which have 1,2,3 permutations as perfect cubes. Here is the output which checked from i=0 to i=999 in around 120~130 seconds and found no such number. I need to increase the efficiency of the code otherwise searching will take a very long time. With increase in i the number of digits in cube of i increases and total permutations increase rapidly, hence a rapid decrease in speed.

It also prints 345,3 (correct) and none of 384 or 405 (good).

boolean[] checked = new boolean[999];
    Arrays.fill(checked, false);
    for (int i = 1; i < 999; i++) {
        if (!checked[i]) {
            int cube_perms = 0;
            long i_3 = i * i * i;
            int len = String.valueOf(i_3).length();
            ArrayList<int[]> perms = getPermutations(longToArray(i_3));
            for (int[] x : perms) {
                int num = arrayToInt(x);
                if (String.valueOf(num).length() < len) {
                    continue;
                }
                int cubrt = (int) Math.round(Math.pow(num, 1.0 / 3.0));
                if (Math.pow(cubrt, 3) == (num)) {
                    checked[cubrt] = true;
                    ++cube_perms;
                }
            }
            if (cube_perms == 5) {
                return i;
            }

            System.out.println(i + "," + cube_perms);
        }
    }
    return 0;

getPermutations()

public static ArrayList<int[]> getPermutations(int[] arr) {
    ArrayList<int[]> al = new ArrayList<int[]>();
    Arrays.sort(arr);
    do {
        al.add(arr.clone());
    } while (getNextPermDistinct(arr));
    return al;
}

getNextPermDistinct()

public static boolean getNextPermDistinct(int[] array) {
    // Find longest non-increasing suffix
    int i = array.length - 1;
    while (i > 0 && array[i - 1] >= array[i])
        i--;
    // Now i is the head index of the suffix

    // Are we at the last permutation already?
    if (i <= 0)
        return false;

    // Let array[i - 1] be the pivot
    // Find rightmost element that exceeds the pivot
    int j = array.length - 1;
    while (array[j] <= array[i - 1])
        j--;
    // Now the value array[j] will become the new pivot
    // Assertion: j >= i

    // Swap the pivot with j
    int temp = array[i - 1];
    array[i - 1] = array[j];
    array[j] = temp;

    // Reverse the suffix
    j = array.length - 1;
    while (i < j) {
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
        i++;
        j--;
    }

    // Successfully computed the next permutation
    return true;
}

longToArray()

public static int[] longToArray(long i) {
    int len = String.valueOf(i).length();
    int[] arr = new int[len];
    for (int j = 0; j < len; j++) {
        arr[j] = (int)i % 10;
        i /= 10;
    }
    return arr;
}

arrayToInt()

public static int arrayToInt(int[] a) {
    int num = 0;
    for (int i = a.length - 1; i >= 0; i--) {
        num += a[i] * Math.pow(10, a.length - i - 1);
    }
    return num;
}


texts: Convert human readable string to TimeSpan

texts:
I want to pass time interval as a string (to program args) and then I want to parse it to TimeSpan. I created simple class:

public static class TimeSpanConverter
    {
        public static TimeSpan Convert(string input)
        {
            var units = new Dictionary<string, int>()
            {
                {@"(\d+)(ms|mili[|s]|milisecon[|s])", 1 },
                {@"(\d+)(s|sec|second[|s])", 1000 },
                {@"(\d+)(m|min[|s])", 60000 },
                {@"(\d+)(h|hour[|s])", 3600000 },
                {@"(\d+)(d|day[|s])", 86400000 },
                {@"(\d+)(w|week[|s])", 604800000 },
            };

            var timespan = new TimeSpan();

            foreach(var x in units)
            {
                var matches = Regex.Matches(input, x.Key);
                foreach(Match match in matches)
                {
                    var amount = System.Convert.ToInt32(match.Groups[1].Value);
                    timespan = timespan.Add(TimeSpan.FromMilliseconds(x.Value * amount));
                }
            }

            return timespan;
        }
    }

Which is working, and I can easly parse like this:

var interval = TimeSpanConverter.Convert("1day13hour2min12s52ms");

What do you think about that? How can I improve that? I have a feeling, that it is not well coded.


texts: Recursive function for listing directories

texts:
The below code is recursive function that list directories in 2 levels:

static  Dictionary<string,string> pList=new Dictionary<string, string>();
static void ListDirec(string path, int start, int end)
{
    var dirInfo = new DirectoryInfo(path);
    var folders = dirInfo.GetDirectories().ToList();

    foreach (var item in folders)
    {
        Console.WriteLine("".PadLeft(start * 4, ' ') + item.Name);
        if (start < end) {
            ListDirec(item.FullName, start + 1, end);
        }
    }
}

Now how can optimize that in this case?

For example, I've these directories with their sub-directories:

folder-A
    folder-A-1
    folder-A-2
    folder-A-3
folder-B
    folder-B-1
    folder-B-2
    folder-B-3
folder-C
    folder-C-1
    folder-C-2
    folder-C-3

Now I want save parents as key and children as value in dictionary, with their relation for example folder-A has these children: folder-A-1, folder-A-2, folder-A-3 and so on.

What's the best way to do that in this function?


texts: Implementing a fast 'split' function on a stream of characters in Java

texts:
I was writing a piece of code (a custom EntityProcessor for Solr, but that isn't too relevant) designed to break lines of input based on a string delimiter (toMatch below).

Characters are read from a stream and then passed to addChar.
The assumption is that each character comes in a stream and look-ahead isn't allowed - the break needs to happen after the last character of a match is passed in.

I wrote two implementations below addChar and addChar2.
The first is a simple, dumb, keep a buffer and compare it each iteration, the second is a simple state machine and the latter is slightly faster.

import java.util.Iterator;
import java.util.LinkedList;

public class CharStreamMatcher {
    protected char[] toMatch = null;

    public MagicCharStreamMatcher(char[] match){
        toMatch = match;
        for(int i=0;i<match.length;i++) li.add((char)0);
    }

    public void clear(){
        correspondences.clear();
    }

    LinkedList<Character> li = new LinkedList<Character>();
    public boolean addChar2(char c){
        li.addLast(c);
        li.removeFirst();
        int i=0;
        for(Character ch : li){
            if(ch.charValue() != toMatch[i++])
                return false;
        }
        return true;
    }

    private class MutableInteger{
        public int i;
        public MutableInteger(int i){
            this.i = i;
        }
    }

    LinkedList<MutableInteger> correspondences = new LinkedList<MutableInteger>();
    public boolean addChar(char c){
        boolean result = false;

        if(c == toMatch[0])
            correspondences.add(new MutableInteger(-1));

        Iterator<MutableInteger> it = correspondences.iterator();
        while(it.hasNext()){
            MutableInteger mi = it.next();
            mi.i++;

            // check the match
            if(c != toMatch[mi.i]){
                it.remove();
            }
            // are we done?
            else if(mi.i == toMatch.length-1){
                result = true;
                it.remove();
            }
        }

        return result;
    }
}


texts:
I am trying to simplify the below if else statement, and I think it can be done.

Algorithm is like this -

  If user_ptr exists, then lock attrmap, find user_ptr. And if it
  is a batch, then don't ping. And else if user_ptr doesn't exists
  and if it is not a batch, then do other stuff.  But if it is a
  batch and user_ptr doesn't exists, then don't do anything.

With the above algorithm, this is what I've came up with, but I'm not sure whether it can be simplified or not.

if (user_ptr) {

    if(batchOrTimestamp != "batch") {
        user_ptr->ping(); // dont ping it if its a batch update
    }

    // lock attribute map from outside access and modification
    AttributeMap::GuardSPtr guard = user_ptr->m_attrMap.get_guard();
    user_ptr->m_attrMap.find(column_key.c_str(), actual_binary_value, attributeLength, schemaId, lastModifiedDate);
} else if(!user_ptr && batchOrTimestamp != "batch") {
    user_ptr = User::MakeUser(user_id);
    user_ptr->m_attrMap.find(column_key.c_str(), actual_binary_value, attributeLength, schemaId, lastModifiedDate);
    User::Find(user_ptr);
}

Any thoughts on this?


texts:
Are  these methods getNewId() & fetchIdsInReserve() thread safe ?

public final class IdManager {

    private static final int NO_OF_USERIDS_TO_KEEP_IN_RESERVE = 200;

    private static final AtomicInteger regstrdUserIdsCount_Cached = new AtomicInteger(100);
    private static int noOfUserIdsInReserveCurrently = 0;

    public static int getNewId(){
          synchronized(IdManager.class){
              if (noOfUserIdsInReserveCurrently <= 20)
                      fetchIdsInReserve();

              noOfUserIdsInReserveCurrently--;
          }
          return regstrdUserIdsCount_Cached.incrementAndGet();
    }

    private static synchronized void fetchIdsInReserve(){
        int reservedInDBTill = DBCountersReader.readCounterFromDB(....); // read column from DB

        if (noOfUserIdsInReserveCurrently + regstrdUserIdsCount_Cached.get() != reservedInDBTill) throw new Exception("Unreserved ids alloted by app before reserving from DB");

        if (DBUpdater.incrementCounter(....)) //if write back to DB is successful
              noOfUserIdsInReserveCurrently += NO_OF_USERIDS_TO_KEEP_IN_RESERVE;
    }

}


texts: Email notifications system in Rails project

texts:
I'm working on the Rails project where I have many-to-many :through relationship.  Each setting has many notifications through email_notification model where the notification can be primary or a secondary.

schema.rb

create_table "email_notifications", :force => true do |t|
  t.integer "setting_id"
  t.integer "notification_id"
  t.boolean "primary"
  t.boolean "secondary"

create_table "notifications", :force => true do |t|
  t.string   "name"

create_table "settings", :force => true do |t|
  t.string   "truck_identification"
  t.string   "email_periods"
  t.integer  "email_recepient_id"
  t.datetime "created_at",                             :null => false
  t.datetime "updated_at",                             :null => false
  t.integer  "truck_fleet_id"

In models

class EmailNotification < ActiveRecord::Base
  attr_accessible :notification_id, :setting_id, :primary, :secondary
  belongs_to :notification
  belongs_to :setting

class Notification < ActiveRecord::Base
  attr_accessible :name

  has_many :settings, :through => :email_notifications
  has_many :email_notifications
end

class Setting < ActiveRecord::Base
  # TODO: refactor this bullshit
  attr_accessible :email_periods, :email_recepient_id, :truck_identification,
                  :truck_fleet_id

  has_many :notifications, :through => :email_notifications
  has_many :email_notifications
  validates_uniqueness_of :truck_fleet_id
  # validates :email, :email_format => true
end

I used this many-to-many relationship because I need flexibility to add up new Notifications over the time, and keep ability to make notifications flexible as possible.  For example, I might add a column frequency, or interval etc.

Let me know if you can find a better solution.


texts:
I have project that uses handlebars and I'm using gulp and gulp-compile-handlebars to watch for changes in the handlebars template as well as the json structure used to compile the template.  I have implemented a watch which seems to work, but it feels like it's doing more work than it should.

My gulpfile looks like this:

var gulp = require('gulp');
var watch = require('gulp-watch');
var handlebars = require('gulp-compile-handlebars');
var rename = require('gulp-rename');
var batch = require('gulp-batch');
var argv = require('yargs').argv // for args parsing
var spawn = require('child_process').spawn;

handlebars.Handlebars.registerHelper('next', function(context, idx, options) {
    if (context[idx + 1]) {
        return options.fn(context[idx + 1])
    } else {
        return "";
    }
});

gulp.task('default', function () {
    var content = require('./content.js')
    var templateData = content
    options = {
        // partials : {
        //     footer : '<footer>the end</footer>'
        // },
        // batch : ['./src/partials'],
        // helpers : {
        //     capitals : function(str){
        //         return str.toUpperCase();
        //     }
        // }
    }

    return gulp.src(['index.handlebars'])
    .pipe(handlebars(templateData, options))
    .pipe(rename('indexCompiled.html'))
    .pipe(gulp.dest('.'));
});

// gulp.task('watch', function () {
//     watch('index.handlebars', batch(function (events, done) {
//         gulp.start('default', done);
//     }));
//     watch('content.js', batch(function (events, done) {
//         gulp.start('default', done);
//     }));
//     watch('gulpfile.js', batch(function (events, done) {
//         gulp.start('default', done);
//     }));
// });

gulp.task('auto-reload', function() {
    var p;

    gulp.watch('content.js', spawnChildren);
    gulp.watch('index.handlebars', spawnChildren);
    spawnChildren();

    function spawnChildren(e) {
        // kill previous spawned process
        if(p) { p.kill(); }

        // `spawn` a child `gulp` process linked to the parent `stdio`
        p = spawn('gulp', [argv.task], {stdio: 'inherit'});
    }
});

As I'm making changes I run gulp auto-reload --task default and any changes to the handlebars template or the json in content.js is re-compiled into indexCompiles.html.  Intially I was just trying to do a simple watch which you can see commented out in the gulp script.

// gulp.task('watch', function () {
//     watch('index.handlebars', batch(function (events, done) {
//         gulp.start('default', done);
//     }));
//     watch('content.js', batch(function (events, done) {
//         gulp.start('default', done);
//     }));
// });

That watch would run for all changes and recompile, but the only changes that were reflected in the new indexCompiled.html were the ones from index.handlebars any changes to the json in content.js was not reflected in the new compiled html I would have to stop the gulp watch and start it again, which is why I eventually made the auto-restart which works.  Why wasn't the original gulp watch working and is there a way to get it to work or do I need to use the auto-restart task?


texts: Printing Gray code through modifying Samuel Beckett's stage instructions

texts:
This is exercise 2.3.24. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Modify Beckett to print the Gray code.
Beckett refers to the following program within the text:
public class Beckett
{
    public static void moves(int n, boolean enter)
    {
        if (n == 0) return;
        moves(n-1, true);
        if (enter) System.out.println("enter " + n);
        else       System.out.println("exit " + n);
        moves(n-1, false);
    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        moves(n, true);
    }
}

As stated in the text:

The playwright Samuel Beckett wrote a play called Quad that had the following property:
starting with an empty stage, characters enter and exit one at a time
so that each subset of characters on the stage appears exactly once.

The above program tries to simulate the above-explained stage instructions. Here is my attempt at turning Beckett into a program that produces Gray code:
public class exercise2_3_24
{
    public static String swap(String s, String t, int n)
    {
        n = n-1;
        return s.substring(0,n) + t + s.substring(n+1);
    }
    public static void beckett(String s, int n)
    {
        if (n == 0) return;
        beckett(s, n-1);
        System.out.println(swap(s, "1", n));
        s = swap(s, "1", n);
        beckett(s, n-1);
    }
    public static void graycodes(int n)
    {
        String s = "";
        for (int i = 0; i < n; i++)
            s += "0";
        System.out.println(s);
        beckett(s, n);
    }
    public static void main(String[] args)
    {
        int n = Integer.parseInt(args[0]);
        graycodes(n);
    }
}

Is there any way that I can improve my program?
Thanks for your attention.


texts:
I'm a complete beginner in Python and programming in general. I made a program for Spotify's Best Before puzzle. It was accepted. I have looked a litle around on internet and looked at other solutions to the problem, and everyone I have seen have importet several modules, inclusive the Calendar module. I understand this is probably a good solution, but I wanted to make everything myself as a practice.

I would really appreciate all tips and hint, but mainly without haveing to import code. It's primarily the printer(a) and det dataMaker() that needs modification.

normYear = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leapYear = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
answerList = []

u''' Check if any of the integers are years '''

def yearCheck():
    for x in xrange(0, 3):
        a = dataList[x]
        if len(a) > 2:
            if not len(a) == 4 and int(a) in xrange(2000,3000):
                if int(a) in xrange(100,1000):
                    dataList[x] = int(a) + 2000
                else:
                    print data + u" is illegal"

u''' Make integers and sort '''

def integer():
    for x in xrange(0, 3):
        dataList[x] = int(dataList[x])
    dataList.sort()

u''' Check for possible leap years '''

def leapYears():
    global leapList
    leapList = []
    for x in xrange(0, 3):
        if dataList[x] % 4 == 0:
            if dataList[x] % 100 == 0:
                if dataList[x] % 400 == 0:
                   leapList.append(x)
            else:
                leapList.append(x)

u''' Changes year type '''

def defYear(a):
    global xYear
    if a in leapList:
        xYear = leapYear
    else:
        xYear = normYear

u''' Printer '''

def printer(a):
    if dataList[a] < 2000:
        dataList[a] += 2000
    year = dataList[a]
    del dataList[a]
    if not dataList[0] == 0:
        month = dataList.pop(0)
        day = dataList.pop(0)
        answerList.append(unicode(year))
        answerList.append(unicode(u'%02d' % month))
        answerList.append(unicode(u'%02d' % day))
        print u'-'.join(answerList)
    else:
        print data + u" is illegal"

u''' Looks for legal dates, first [Y<M<D] then [M<Y<D] then [M,D,Y] '''

def dateMaker():
    for x in xrange(0,4):
        defYear(x)
        if x == 0:
            if dataList[1] <= 12 and dataList[2] <= xYear[dataList[1]-1]:
                printer(x)
                break
        elif x == 1:
            if dataList[0] <= 12 and dataList[2] <= xYear[dataList[0]-1]:
                printer(x)
                break
        elif x == 2:
            if dataList[0] <= 12 and dataList[1] <= xYear[dataList[0]-1]:
                printer(x)
                break
        else:
            print data + u" is illegal"

u''' Program '''

data = raw_input()
dataList = data.split(u"/")
yearCheck()
integer()
leapYears()
dateMaker()


texts: Conditionally deleting rows in a worksheet

texts:
I have used loops to remove lines that are doing various things, but all are deleting rows where certain criteria is met. Some are deleting less than certain numbers, deleting blanks, removing specific rows that contain specific things in columns, remove all the items that don't contain 4 specific parts. This works but it is slow and I'm sure someone can do this in a better way. Can anyone give me any advice?

Sub DeleteRandom()

Worksheets(2).Select
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
ActiveSheet.DisplayPageBreaks = False
Dim r As Integer

'This part deletes out all the non essential items (basically like the filting does)

For r = Worksheets(2).UsedRange.Rows.Count To 1 Step -1
'Amount paid is more than 0
If Cells(r, "C") <= 0 Then
    Worksheets(2).Rows(r).EntireRow.Delete
'Compound Code field is not blank
    ElseIf Cells(r, "AE") = "" Then
        Worksheets(2).Rows(r).EntireRow.Delete
'Compound Code is 0 or 1
    ElseIf Cells(r, "AE") >= 2 Then
        Worksheets(2).Rows(r).EntireRow.Delete
'Claim type is for paid claims only
    ElseIf Cells(r, "L") <> "P" Then
        Worksheets(2).Rows(r).EntireRow.Delete
'Next 3 items remove CICS Claim Status that include CAC, OVR, or PWE
    ElseIf Cells(r, "J") = "CAC" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "J") = "OVR" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "J") = "PWE" Then
        Worksheets(2).Rows(r).EntireRow.Delete
'Next 9 items remove Drug Category Codes D, I, M, N, O, P, Q, R, or S
    ElseIf Cells(r, "S") = "D" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "I" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "M" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "N" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "O" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "P" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "Q" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "R" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "S") = "S" Then
        Worksheets(2).Rows(r).EntireRow.Delete
'Keeps only the Preauth = 0 rows
    ElseIf Cells(r, "N") <> 0 Then
        Worksheets(2).Rows(r).EntireRow.Delete
'Next 8 remove Group IDs that are not DS, GM, HP, or LP
    ElseIf Cells(r, "AD") = "940" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "AD") = "MMPDMBA" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "AD") = "MPXDMBA" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "AD") = "PRODMBA" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "AD") = "SCXFRGN" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "AD") = "SPHDMBA" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "AD") = "SPIDMBA" Then
        Worksheets(2).Rows(r).EntireRow.Delete
    ElseIf Cells(r, "AD") = "SPUDMBA" Then
        Worksheets(2).Rows(r).EntireRow.Delete
End If
Next

'This part adds the headers
Worksheets(2).Select
Range("A1").EntireRow.Insert
Worksheets(1).Select
'This part is picking only the specific headers we need (skipping all the other headers)
Range("D1:E1,G1:G1,Q1:Q1,U1:Y1,AK1:AK1,AW1:AW1,BD1:BD1,BK1:BK1,BR1:BS1,BW1:BW1,BY1:CA1,CE1:CE1,CG1:CG1,CI1:CJ1,CL1:CM1,CO1:CP1,CX1:CY1,DD1:DD1,HY1:HY1,KT1:KT1,LI1:LI1,MV1:MW1,NM1:NM1,PL1:PL1,PX1:PX1,QF1:QF1").Copy
 Worksheets(2).Select
Range("A1").Select
ActiveSheet.Paste
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
ActiveSheet.DisplayPageBreaks = True
End Sub


texts: Toggle dropdown menus for different menu items with Jquery

texts:
In a bigger project of mine I'm using angular to create a dropdown menu dynamically and then toggling a dropdown menu for some of the menu items. This is why I got a function that toggles the dropdown menus for only the items that should actually have one. However, I feel like I should try to DRY this out a bit since I'll be repeating the same function even more than what I've done so far. How can I improve this code? Should I create a self invoking function or something similar?

Here's the functions (they're part of a controller object that I left out):

    init: function() {

        menuController.toggleDropDown('msg');
        menuController.toggleDropDown('mypages');
        menuController.toggleDropDown('tools');
        menuController.toggleDropDown('administration');
        menuController.toggleDropDown('contactinfo');
        menuController.toggleDropDown('utbildning');
        menuController.toggleDropDown('surveys');
        menuController.toggleDropDown('help');
    },
    toggleDropDown: function (id) {

        $('#main-menu' + ' #' + id + '').hover(function() {
            $('#' + id + ' ul').stop().slideToggle();
        });
    }


texts: Standard Test methods for checking values in Lists, Maps etc

texts:
I needed to check the values in various Lists and Maps. In my case, the various types of Objects that needed checking were of four types:

String
List<String>
Map<String, String>
Map<String, List<String>>

So, I came up with the following types test methods:

@Test
public void testString() {
    Assert.assertEquals("String Mismatch;", providedString, receivedString);
}

@Test
public void testList() {
    Assert.assertNotNull("Provided List is null;", providedList);
    Assert.assertNotNull("Received List is null;", receivedList);
    Assert.assertEquals("Size mismatch for lists;", providedList.size(), receivedList.size());
    Assert.assertTrue("Missing values in received list; Missing: " + CollectionUtils.subtract(providedList, receivedList) + "; ", receivedList.containsAll(providedList));
}

@Test
public void testMap() {
    Assert.assertNotNull("Provided Map is null;", providedMap);
    Assert.assertNotNull("Received Map is null;", receivedMap);
    Assert.assertEquals("Size mismatch for maps;", providedMap.size(), receivedMap.size());
    Assert.assertTrue("Missing keys in received map;", receivedMap.keySet().containsAll(providedMap.keySet()));

    providedMap.keySet().stream().forEach((key) -> {
        Assert.assertEquals("Value mismatch for key '" + key + "';", providedMap.get(key), receivedMap.get(key));
    });
}

@Test
public void testMapList() {
    Assert.assertNotNull("Provided Map is null;", providedMapList);
    Assert.assertNotNull("Received Map is null;", receivedMapList);
    Assert.assertEquals("Size mismatch for maps;", providedMapList.size(), receivedMapList.size());
    Assert.assertTrue("Missing keys in received map;", receivedMapList.keySet().containsAll(providedMapList.keySet()));

    providedMapList.keySet().stream().forEach((key) -> {
        List<String> pList = providedMapList.get(key);
        List<String> rList = receivedMapList.get(key);

        Assert.assertNotNull("Provided List is null for key '" + key + "';", pList);
        Assert.assertNotNull("Received List is null for key '" + key + "';", rList);
        Assert.assertEquals("Size mismatch for lists for key '" + key + "';", pList.size(), rList.size());
        Assert.assertTrue("Missing values in received list for key '" + key + "';", rList.containsAll(pList));
    });
}

The test methods in my project follow the above standard methods depending upon the object that I'm testing for. They are working fine but I'm not completely confident about the coverage.

Also, in the above snippets I've used provided and received as placeholders. In the actual test cases, certain methods are being called to populate the corresponding objects for provided and received. So, they are not necessarily being populated/initialized in @BeforeClass or @Before.

Should I be creating different Test methods for each assert (excluding assertNotNull() methods) that I'm doing? Am I missing any case? Can this be made shorter with the coverage being the same?

Update:

Full Code for testing: Standard Test

Create a TestRunner class to run it and get the results using the following:

Result result = JUnitCore.runClasses(StandardTest.class);


texts: Simulate a pool using multithreading in Python

texts:
I was tasked with solving this particular problem:

  A water pool which can hold a total of 800 liters of water has 3
  pipes. 2 of them pour water in, the third one pours water out. 1st
  pipe pours 100 liters in, 2nd pipe pours 80 liters in and the third
  one pours 110 liters out. The pool must keep its volume between 600 and
  800 liters. When the volume is greater than 700 liters, no water
  should be poured in, when the volume is less than 600, no water should
  be poured out.

This is the code I came up with:

import threading
import logging
import time
import concurrent.futures

class Pipe:
    waterVolume = 0
    def __init__(self, type):
        self.typeOfPipe = type
        self._lock = threading.Lock()

    def behaviour(self, type):
      while True:
        if type == 0:
            if Pipe.waterVolume < 700:
                with self._lock:
                    local_copy = Pipe.waterVolume
                    local_copy += 100
                    Pipe.waterVolume = local_copy
                    print('Pipe %d added 100 liters' % (self.typeOfPipe + 1))
                    print('volume is: %d' % Pipe.waterVolume)
        if type == 1:
            if Pipe.waterVolume < 700:
                with self._lock:
                    local_copy = Pipe.waterVolume
                    local_copy += 80
                    Pipe.waterVolume = local_copy
                    print('Pipe %d added 80 liters' % (self.typeOfPipe + 1))
                    print('volume is: %d' % Pipe.waterVolume)
        if type == 2:
            if Pipe.waterVolume > 600:
                with self._lock:
                    local_copy = Pipe.waterVolume
                    local_copy -= 110
                    Pipe.waterVolume = local_copy
                    print('Pipe %d removed 110 liters' % (self.typeOfPipe + 1))
                    print('volume is: %d' % Pipe.waterVolume)
        time.sleep(1.5)

if __name__ == '__main__':
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        for i in range(3):
            p = Pipe(i)
            executor.submit(p.behaviour, i)

From what I've seen when satisfies the condition 600 < waterVolume < 800 for the first time, it stays there. That combined with the fact that there's no deadlocks or race conditions makes me think that this is a correct solution to the problem. Nevertheless, suggestions about improving the script are very welcome.


texts:
I want to place an element alternatively between any two elements of a list.

l1 = list('abcde')
fill = 'z'

How it should look like:

['a', 'z', 'b', 'z', 'c', 'z', 'd', 'z', 'e']

My solution:

fill = 'z'
l2 = [fill]*(len(l1)-1)
[x for t in map(None, l1, l2) for x in t if x]

Is there a better approach, i.e. that doesn't need to create another list?


texts: Use PreparedStatement to insert into H2 database

texts:
This question is related to my question on Stack Overflow earlier today. After getting suggestions on using the PreparedStatement from Java I changed my code a little.

  EDIT: In my original question on Stack Overflow I attempted to process
  the query in a very messy way, see this short excerpt:

String sqlQuerry = "INSERT INTO TASKS " + "VALUES ("
        + table.getValueAt(i, 0) + ", "
        + table.getValueAt(i, 1) + ", "
        + table.getValueAt(i, 2) + ", "
        + table.getValueAt(i, 3) + ", "

  Even though this might have worked, it would have been harder to
  understand and I ran into issues when the table.getValueAt(X,Y)
  returned "null".

As I am completely new to SQL in Java I want to know if the code below is "good" or at least "okayish" and can be maintained later on. If you got any tips on how to make this cleaner, let me know.

String sqlInsert = "INSERT INTO TASKS " + "VALUES" + "(?,?,?,?,?,?,?,?,?,?,?,?,?)";

for (int i = 0; i < table.getModel().getRowCount(); i++) {

    PreparedStatement sqlState = conn.prepareStatement(sqlInsert);

    int j = 1;

    sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 0).toString()));
    sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 1).toString()));
    sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 2).toString()));
    sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 3).toString()));

    sqlState.setString(j++, table.getValueAt(i, 4).toString());
    sqlState.setString(j++, table.getValueAt(i, 5).toString());
    sqlState.setString(j++, table.getValueAt(i, 6).toString());
    sqlState.setString(j++, table.getValueAt(i, 7).toString());

    sqlState.setInt(j++, Integer.parseInt(table.getValueAt(i, 8).toString()));

    sqlState.setString(j++, table.getValueAt(i, 9).toString());
    sqlState.setString(j++, table.getValueAt(i, 10).toString());
    sqlState.setString(j++, table.getValueAt(i, 11).toString());
    sqlState.setBoolean(j++, (boolean) table.getValueAt(i, 12));

    sqlState.executeUpdate();
}


texts: Detecting cycles in a directed graph without using mutable sets of nodes

texts:
I recently came across the classic algorithm for detecting cycles in a directed graph using recursive DFS. This implementation makes use of a stack to track nodes currently being visited and an extra set of nodes which have already been explored. The second set is not strictly required, but it is an optimization to prevent iterating over path suffixes that have previously been determined not to be part of a cycle.

I had no trouble implementing this in Python by simply creating a (mutable) set object and sharing it between all branches of the recursion.

My attempt to reimplement this algorithm in Haskell turned out to be much worse (and still isn't as efficient as the original).

I would like some pointers about how to restructure this so that it isn't a mess of recursive folds, but without giving up the set of visited, nodes, which lets me avoid taking branches that have already been explored.

import Data.Maybe
import qualified Data.IntMap.Strict as M
import qualified Data.Char as C

import Debug.Trace

edges :: String
edges =
  "a b\n\
  \a c\n\
  \b c\n\
  \b d\n\
  \c d\n\
  \c e\n\
  \e f\n\
  \e g\n\
  \f g\n\
  \g c"

type Node = Int

parseGraph :: String -> M.IntMap [Node]
parseGraph = foldr go M.empty . lines
  where go line m = let [key, rule] = map ruleToKey (words line)
                    in M.insertWith inserter key [rule] m
        inserter [rule] olds = rule:olds

ruleToKey :: String -> Node
ruleToKey rule = C.ord (head rule) - 97

keyToRule :: Node -> String
keyToRule key = return $ C.chr (key + 97)

hasCycle :: M.IntMap [Node] -> Maybe [Node]
hasCycle m = reverse <$> ret
  where dummyM = M.insert phantom (reverse $ M.keys m) m
        phantom = -1
        (_, _, ret) = hasCycleHelper dummyM phantom ([], [], Nothing)

hasCycleHelper :: M.IntMap [Node] -> Node -> ([Node], [Node], Maybe [Node]) -> ([Node], [Node], Maybe [Node])
hasCycleHelper rules rule (visited', visiting', cyc) =
  trace rendered $
    case () of
      _ | isJust cyc || rule `elem` visited' -> (visited', visiting', cyc)
        | rule `elem` visiting' -> ([], [], Just (takeWhile (/= rule) visiting' ++ [rule]))
        | otherwise ->  returned
  where
    children = M.findWithDefault [] rule rules
    (visited, _, ret) = foldr (hasCycleHelper rules) acc children
    returned = (rule:visited, visiting', ret)
    acc = (visited', rule:visiting', Nothing)
    rendered =    "Current '" ++ keyToRule rule ++ "', "
               ++ "Visiting '" ++ map (head . keyToRule) visiting' ++ "', "
               ++ "Visited '" ++ map (head . keyToRule) visited' ++ "', "
               ++ "Found " ++ show (map (head . keyToRule) <$> cyc)

main :: IO ()
main = do
  let rules = parseGraph edges
      cyc = map keyToRule <$> hasCycle rules
  print cyc

With output:

Current '`', Visiting '', Visited '', Found Nothing
Current 'a', Visiting '`', Visited '', Found Nothing
Current 'c', Visiting 'a`', Visited '', Found Nothing
Current 'e', Visiting 'ca`', Visited '', Found Nothing
Current 'g', Visiting 'eca`', Visited '', Found Nothing
Current 'c', Visiting 'geca`', Visited '', Found Nothing
Current 'f', Visiting 'eca`', Visited 'g', Found Just "gec"
Current 'd', Visiting 'ca`', Visited 'eg', Found Just "gec"
Current 'b', Visiting 'a`', Visited 'ceg', Found Just "gec"
Current 'b', Visiting '`', Visited 'aceg', Found Just "gec"
Current 'c', Visiting '`', Visited 'aceg', Found Just "gec"
Current 'e', Visiting '`', Visited 'aceg', Found Just "gec"
Current 'f', Visiting '`', Visited 'aceg', Found Just "gec"
Current 'g', Visiting '`', Visited 'aceg', Found Just "gec"
Just ["c","e","g"]

Because I'm using foldr, it can't abort the search after discovering a cycle. It has to iterate over all the nodes in the graph at the top level, carrying along the result. I think that's pretty miserable, but I thought I'd ask about it before rewriting everything.


texts: JavaScript attempt at an aspect oriented logger using proxies and reflect

texts:
I've been playing around with AOP in JavaScript to create a Logger that I can attach to classes and output what is going on (mainly instantiation, calling of functions and the results from functions).  I've done this by creating a static class (static method in a class) that essentially is a factory that uses a proxy to trap the instantiation of a class (or just a function) and applies another proxy to the instantiated class to capture function calls on that class.
Beyond sanity/standards checking what I've written, I must admit I haven't come up with better tests than checking to make sure it instantiates a class correctly and that any function called on a class will return the expected results.  I'd be interested to know of better ways of testing this.
I've had to tell it that it shouldn't try and apply itself, due to it being a static class and my not wanting to instantiate itself.
it takes an eventEmitter object as the first argument that should have a method of publish accepting at least a string.
class Logger {
  static ClassHandler(eventEmitter, obj) {
    const InstanceHandler = {
      get(target, prop, receiver){
        eventEmitter.publish(`${prop} called on ${target.constructor.name}`);
        const orig = Reflect.get(target, prop, receiver);
        if (typeof orig == "function" &&
            prop !== 'Logger') {
          return function (...args) {
            eventEmitter.publish(`Method ${prop} called with ${JSON.stringify(args)}`);
            let result =  orig.apply(this, args);
            eventEmitter.publish(`Result from ${prop} is: ${JSON.stringify(result)}`);
            return result;
          };
        } else {
          return orig;
        }
      }
    }

    const handler = {
      construct(target, args) {
        eventEmitter.publish(`${target.name} instantiated`);
        const instance = Reflect.construct(...arguments);
        return new Proxy(instance, InstanceHandler);
      },
      apply(target, thisArg, argumentsList) {
        eventEmitter.publish(`${target.name} called with with ${JSON.stringify(argumentsList)}`);
        const result =  Reflect.apply(...arguments);
        eventEmitter.publish(`Result from ${target.name} is: ${JSON.stringify(result)}`);
        return result;
      },
    }
    return new Proxy(obj, handler);
  }
}

module.exports = Logger;

So to use it, something like this:
SimpleClass.js
class SimpleClass {
  constructor() {

  }

  shoutOut() {
    return 'hello!';
  }

  returnValue(value) {
    return value;
  }
}

module.exports = SimpleClass;

Publisher.js
class Publisher {
  constructor() {}

  publish(event) {
    console.log(event);
  }
}

module.exports = Publisher;

index.js
const Logger = require('Logger');
const Publisher = require('Publisher');
const publisher = new Publisher();
const SimpleClass = Logger.ClassHandler(publisher, require('SimpleClass'));
const simpleClass = new SimpleClass();
simpleClass.shoutOut();

this is it at it's most simple and should produce the output:

SimpleClass instantiated
shoutOut called on SimpleClass

if you then called the returnValue('hi there') method you'd get;

SimpleClass instantiated
returnValue called on SimpleClass
Method returnValue called with ["hi there"]
Result from returnValue is: "hi there"

How can i better test this?  Can I improve my Logger at all? Have I done the right thing with Proxies and Reflect?


texts:
Here is my code to implement authentication in a Node/Express/Sequelize project. This is my first time using JWT and I would appreciate any help!

// Load required packages
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const config = require('../config');
const User = require('../models').User;

exports.authenticate = function(req, res) {
  const username = req.body.username;
  const password = req.body.password;
  User.findOne({
    where: { username: username }
  }).then((user) => {
    // Make sure the password is correct
    if (user.verifyPassword(password)) {
      const token = jwt.sign({
        username: user.username
      }, config.jwtSecret);
      res.json({
        success: true,
        token: token,
        username: user.username
      });
    }
  }).catch((error) => {
    console.error(error);
    res.sendStatus(404);
  });
}

exports.isAuthenticated = expressJwt({ secret: config.jwtSecret });


texts: Struggling to refactor code to remove duplication

texts:
I really need some help removing some duplicated code. I've linked the methods causing me issues. http://pastebin.com/cZJihM4J

As you can see each method does similar things but retrieve different values. i.e one method to insert a string at a certain line. Another to get the the lines index and another to get the contents at a particular line

There are things like:

String text = textArea.getText();
int start = 0;
int count = 0;
String buildNewTextArea = "";

I could make these values global but not sure if this is the best way to approach this.
My brain can't find away around this :(

Thanks in advance

 public String insertCodeBlock(String newBlock) {
    String text = textArea.getText();
    int start = 0;
    int count = 0;
    String buildNewTextArea = "";
    while (start >= 0) {
        int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length());
        if (nextLineStart == -1) {
            nextLineStart = text.length();
        }
        String[] temp = diffBlocks.get(indexOfLine).split(",");
        int startLine = Integer.valueOf(temp[0]);
        int endLine = (Integer.valueOf(temp[1]) - 1) + startLine;
        if (count == startLine) {
            buildNewTextArea += newBlock;
        } else if (count < startLine || count > (startLine + (endLine - startLine))) {
            buildNewTextArea += text.substring(start, nextLineStart);
        }
        count++;
        start = text.indexOf(NEW_LINE, nextLineStart);
    }
    return buildNewTextArea;
}

private int getLineIndex(int line) {
    String text = textArea.getText();
    int start = 0;
    int count = 0;
    String buildNewTextArea = "";
    int index = 0;
    while (start >= 0) {
        int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length());
        if (nextLineStart == -1) {
            nextLineStart = text.length();
        }
        if (count == line) {
            return index;
        }
        buildNewTextArea = text.substring(start, nextLineStart);
        index += buildNewTextArea.length();
        count++;
        start = text.indexOf(NEW_LINE, nextLineStart);
    }
    return text.length();
}

public String getLineContent(int startLine, int endLine) {
    String text = textArea.getText();
    int start = 0;
    int count = 0;
    String buildNewTextArea = "";
    while (start >= 0) {
        int nextLineStart = text.indexOf(NEW_LINE, start + NEW_LINE.length());
        if (nextLineStart == -1) {
            nextLineStart = text.length();
        }
        if (count >= startLine && count <= endLine) {
            buildNewTextArea += text.substring(start, nextLineStart);
        }
        count++;
        start = text.indexOf(NEW_LINE, nextLineStart);
    }
    return buildNewTextArea;
}


texts:
I have written a little program that converts a CSV-File to an HTML-Table. It works for my purposes. But are there parts in my code that can be written more clean? Can you improve maybe the performance? Are there maybe any bugs? I searched for bugs and fortunately I did not find some.
Postscript
Maybe I should have provided some background information: I am working on a database documentation that I am writing as an HTML document, because I dont like Word-documents. However, creating a tabular description of the columns with dozens of tags is painful. That is why I wrote this script: Now I only have to export the table information as CSV and can convert it directly without having to enter many tags myself. This is why there are no HTML and body tags: The tables created should not be separate HTML documents, but parts of a single, large HTML document.
CsvToHtmlTable.java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.FileWriter;
import java.util.List;
import java.util.ArrayList;

public class CsvToHtmlTable {
    public static void main(String[] args) {
        // print info and show user how to call the program if needed
        System.out.println("This program is tested only for UTF-8 files.");
        if (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("-help") || args.length != 2) {
            System.out.println("java CsvToHtmlTable <input file> <output file>");
            System.out.println("Example: java CsvToHtmlTable nice.csv nice.html");
            System.exit(0);
        }

        String csvFile = args[0];
        String outputFile = args[1];

        // read lines of csv to a string array list
        List<String> lines = new ArrayList<String>();
        try (BufferedReader reader = new BufferedReader(new FileReader(csvFile))) {
            String currentLine;
            while ((currentLine = reader.readLine()) != null) {
                lines.add(currentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        //embrace  and
 for lines and columns
        for (int i = 0; i < lines.size(); i++) {
            lines.set(i, "
" + lines.get(i) + "
");
            lines.set(i, lines.get(i).replaceAll(",", "	"));
        }

        // embrace
 and

        lines.set(0, "
" + lines.get(0));
        lines.set(lines.size() - 1, lines.get(lines.size() - 1) + "
");

        // output result
        try (FileWriter writer = new FileWriter(outputFile)) {
            for (String line : lines) {
                writer.write(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to call the program:
java CsvToHtmlTable ExampleInput.csv ExampleOutput.html

ExampleInput.csv
Name,Vorname,Alter
Ulbrecht,Klaus Dieter,12
Meier,Bertha,102

ExampleOutput.html

Name	Vorname	Alter

Ulbrecht	Klaus Dieter	12

Meier	Bertha	102


texts: How would I format this JavaScript code so it's more readable

texts:
How can I format this code so it's more readable?

$(".card").click(function(){
        $(this).stop().animate({
            width:'0px',
            marginLeft: margin+'px',
            opacity: 0.5},
            500,
            function(){
               $(this).siblings('.card').animate({
                   width: width + 'px',
                   marginLeft:'0px',
                   opacity:'1'},500);
            });
});


texts:
This is my first program using classes. How could this be improved?

#include <iostream>

class TicTacToe
{
    char m_field[3][3];
    char sign;
public:
    char Sign(char x) {sign=x;};
    void MakeField();
    void DrawField();
    bool IsFree(int y, int x);
    bool FindAndReplace(int x,int y);
    bool Row();
    bool Column();
    bool Diagonal();
    bool Win();
    bool IsFull();
    TicTacToe(){MakeField();DrawField();}
};

void TicTacToe::MakeField()
    {
        for (int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++)
                m_field[i][j]=' ';
    }

void TicTacToe::DrawField()
    {
        std::cout << " ";
        for(int i = 0; i < 3; i++)
            std::cout << " " << i;

        std::cout << "\n  - - -\n";
        for(int i = 0; i < 3; i++)
        {
            std::cout << i;
            for(int j = 0; j < 3; j++)
            {
                std::cout << "|" << m_field[i][j];
            }
            std::cout << "|\n  - - -\n";
        }
    }

bool TicTacToe::IsFree(int y, int x)
    {
        if(m_field[y][x]==' ')
            return true;
        return false;
    }

bool TicTacToe::FindAndReplace(int x,int y)
    {
        if(IsFree(y,x))
        {
            m_field[y][x]=sign;
            return true;
        }
        return false;
    }

bool TicTacToe::Row()
    {
        for (int i = 0; i < 3; i++)
            if(!IsFree(i,0)&&!IsFree(i,1)&&!IsFree(i,2))
            if(m_field[i][0]==m_field[i][1]&&m_field[i][0]==m_field[i][2])
                return true;
        return false;
    }

bool TicTacToe::Column()
    {
        for (int i = 0; i < 3; i++)
            if(!IsFree(0,i)&&!IsFree(1,i)&&!IsFree(2,i))
            if(m_field[0][i]==m_field[1][i]&&m_field[0][i]==m_field[2][i])
                return true;
        return false;
    }

bool TicTacToe::Diagonal()
    {
        if(!IsFree(1,1))
        {
            if(m_field[2][0]==m_field[1][1]&&m_field[1][1]==m_field[0][2])
                return true;
                if(m_field[0][0]==m_field[1][1]&&m_field[0][0]==m_field[2][2])
                return true;
        }
        return false;
    }

bool TicTacToe::Win()
    {
        return Row()||Column()||Diagonal();
    }

bool TicTacToe::IsFull()
    {
        for (int i = 0; i < 3; i++)
            for(int j = 0; j < 3; j++)
                if(IsFree(i,j))
                    return false;
        return true;
    }

int main()
{
    int x,y,i=0;
    char sign;
    TicTacToe field;
    while(!field.IsFull())
    {
        i++;
        sign=i%2==0?'o':'x';
        std::cout << "Turn " << sign << ": Get x cordinate:";
        std::cin >> x;
        std::cout << "Get y cordinate:";
        std::cin >> y;
        if(x>2||y>2)
        {
            std::cout << "this coordinates does not exist! Try again\n";
            i--;
            continue;
        }

        field.Sign(sign);
        if(field.FindAndReplace(x,y))
            field.DrawField();
        else
        {
            std::cout << "is full!";
            i--;
        }
        if(field.Win())
        {
            std::cout << "Winned sign " << sign;
            break;
        }
    }
    std::cout << "\nEnd!\n";
    return 0;
}


texts: Read numbers until a prime is entered then print non-primes

texts:
I'm a beginner at C#. I just want to know what is the C# way to do this by its convention and a better algorithm as well.

using System;
using System.Collections.Generic;

public class Program
{
    static public void Main()
    {
        bool prime = false;
        List<int> non_primes = new List<int>();

        while (prime == false)
        {
            int number = 0;

            Console.Write("#: ");
            number = Convert.ToInt32(Console.ReadLine());

            prime = true;
            for (int i = 2; i <= number / 2; i++)
            {
                if (number % i == 0)
                    prime = false;

                if (prime == false)
                    non_primes.Add(number);
            }
        }

        if (non_primes.Count != 0)
            Console.WriteLine("none-primes: {0}", string.Join(" ", non_primes.ToArray()));
        else
            Console.WriteLine("none-primes: zero");

        Console.WriteLine("press any key to continue");
        Console.ReadKey();
    }
}


texts: Nested while loop for getting db data. Timing out at random times because of the PHP. Any way to make this more efficient?

texts:
So today I jumbled together a script that would get data from a database, from different tables and such.  I had wanted to just use simple ifs without the whiles, but I couldn't make it possible. The code I posted is useable but randomly times out when testing, and i'm afraid of how it would perform under stress.  Is there any way to improve this code to stop the timing out?

<?php
    $getConference = sprintf("SELECT DISTINCT confName, tableName FROM conferences WHERE enabled='1' ORDER BY id DESC");
    $catConference = mysql_query($getConference);
    while($conference = mysql_fetch_array($catConference)) {
        echo "
".$conference['confName']."

";
        $getExistingEvent = sprintf("SELECT DISTINCT event FROM " . $conference['tableName']);
        $catExistingEvent = mysql_query($getExistingEvent);
        while($existingevent = mysql_fetch_array($catExistingEvent)) {
            $getCat = sprintf("SELECT * FROM event WHERE id='".$existingevent['event']."'");
            $catResult = mysql_query($getCat);
            while($row = mysql_fetch_array($catResult)) {
                $getWinner = sprintf("SELECT place, name, event FROM 2012rlc WHERE event='".$row['id']."' ORDER BY place");
                $catWinner = mysql_query($getWinner);
                echo "

".$row['eventName']."

                    ";

                while($winner = mysql_fetch_array($catWinner)) {
                    echo "
".$winner['place']. " ".$winner['name']."
";
                }
                echo "

";
            }
        }
        echo "
";
    }
    mysql_free_result($catResult);
    mysql_free_result($catWinner);
    mysql_free_result($catExistingEvent);
    mysql_free_result($catConference);
?>

Some have asked for the database schema, which I have included below:

CREATE TABLE `2012rlc` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `place` varchar(4) default '',
    `name` varchar(255) default NULL,
    `event` int(5) default NULL,
    PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=52 DEFAULT CHARSET=latin1;

CREATE TABLE `conferences` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `confName` varchar(255) default NULL,
    `tableName` varchar(50) default NULL,
    `enabled` tinyint(1) default '0',
    PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

CREATE TABLE `event` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `eventName` varchar(255) default NULL,
    `teamEvent` tinyint(1) default '0',
    PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=47 DEFAULT CHARSET=latin1;

Output to EXPLAIN MySQL command:

id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  conferences ALL NULL    NULL    NULL    NULL    4   Using where; Using temporary; Using filesort


texts:
I have list of tuples like so:

lst = [(106, 210, 108, 134, 134),
       (106, 210, 108, 134, 210),
       (106, 210, 108, 168, 268),
       (106, 210, 108, 168, 671),
       ...]

I need to only keep the tuples that contain:

keep = (106, 210, 108, 168)

Which I am currently doing using this statement:

kept = [item for item in lst if set(keep) < set(item)]

This works but it is too slow for me since the actual list I am working with contains 2.6 million items. It takes about 1.5 seconds now. Is there a good way to significantly speed this up?


texts: NodeJS Module Exports: Export multiple functions vs Exporting a single function

texts:
To update parameters in our main.js file, which has a lot of configurable variables, we can do the following

A .

 module.exports.setVarA = function(val){
    VarA = val;
}
module.exports.setVarB = function(val){
    VarB = val;
}
...so on for VarC up to VarZ

B.

module.exports.setAllVariables = function(valA, valB.... valZ){
    VarA = valA;
    VarB = valB;

    ...
    VarZ = valZ;
}

Which one is a better approach to setting up variables in NodeJS? (faster, easier to maintain, not an antipattern)


texts:
I'm simply getting the 3 future days from an array of objects based on the current day to display for a weather component.

This is the first time I've attempted using ES6 and it's features so please take this into consideration.

Is there a better way to do this and save the values? Have I overcomplicated the whole thing?

const days = [
  {0: 'Sun'},
  {1: 'Mon'},
  {2: 'Tue'},
  {3: 'Wed'},
  {4: 'Thu'},
  {5: 'Fri'},
  {6: 'Sat'}
];
let currentDay = new Date(Date.now()).getDay();
const offset = currentDay + 1;
const daysLength = days.length;
let counter = 0;
let newDays = [];

for (const [i, day] of days.entries()) {
  // set the index start point.
  let pointer = (i + offset) % daysLength;
  newDays.push(days[pointer][pointer]);
  counter++
  if (counter === 3) { break; }
}


texts:
Consider an array of numeric strings where each string is a positive whole number. Sort the array's string elements in ascending order of their numeric values, and return the sorted array.
Return: string[n]: the array sorted in numeric order.
Constraints: Each string is guaranteed to represent a positive whole integer. There will be no leading zeros.
Sample Input:
6
31415926535897932384626433832795
1
3
10
3
5

Sample Output:
1
3
3
5
10
31415926535897932384626433832795

Code:
using System;
using System.IO;
using System.Linq;

namespace Big_Sorting
{
    class Solution
    {
        static string[] BigSorting(string[] unsorted) => unsorted.OrderBy(s => s.Length).ThenBy(s => s).ToArray();

        static void Main()
        {
            TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

            int n = Convert.ToInt32(Console.ReadLine());

            string[] unsorted = new string[n];

            for (int i = 0; i < n; i++)
            {
                unsorted[i] = Console.ReadLine();
            }

            textWriter.WriteLine(string.Join("\n", BigSorting(unsorted)));

            textWriter.Flush();
            textWriter.Close();
        }
    }
}

I need to improve upon this code.  Priority for me is performance here.  If the array is becomes long in length this begins to slow down. This is functional and working. I just want to get it as fast as possible.
The code works fine for test cases like this.
But has trouble with test case like this


texts:
I had come up with the following code:

hello_worlds 0 = putStr ""
hello_worlds x = do putStrLn "Hello World"
                    hello_worlds (x-1)
main = do
   n <- readLn :: IO Int
   hello_worlds n

I am aware that it is making one extra call to putStr.

Is there any better way of doing this? If so, please give some advice regarding why I shouldn't go this way.


texts:
Is there a tighter (less characters) way to use perl on the command line to search and replace text from STDIN than I've got here? The code below works.

echo hi | perl -e '$a = <STDIN>; $a =~ s/i/o/g; print $a;'


texts:
I'm learning Haskell at the moment, and have just written my first useful module - a parser fo INI files. I used Parsec. I'd like to know what can be improved here - or maybe I did some things completely wrong and there is a better way. Thanks.

module IniFile (iniFileToMap) where

import Text.ParserCombinators.Parsec
import qualified Data.Map as Map
import Char

parseIniFile :: Parser ([(String, [(String, String)])])
parseSection :: Parser (String, [(String, String)])
parseSectionHeader :: Parser String
parseNameValue :: Parser (String, String)
parseComment :: Parser ()
parseNormalValue :: Parser String
parseQuotedValue :: Parser String
parseValue :: Parser String
parseName :: Parser String
parseInsideQuotes :: Parser String
parseCmtOrSpace :: Parser ()
iniFileToMap :: FilePath -> IO (Map.Map String (Map.Map String String))

parseCmtOrSpace = do{
   spaces;
   skipMany parseComment;
}

parseInsideQuotes = many (noneOf "\"")

parseQuotedValue = between (char '"') (char '"') parseInsideQuotes

parseNormalValue = many1 (satisfy (\c -> isPrint c && not (isSpace c)))

parseValue = parseQuotedValue <|> parseNormalValue

parseName =  many1 (satisfy (\c -> isAlpha c || isDigit c || c == '_' || c == '.'));

parseComment = do{
   skipMany1 (char ';');
   skipMany (noneOf "\n");
   spaces;
}

parseNameValue = do{
   name <-  parseName;
   between (skipMany (oneOf " \t")) (skipMany (oneOf " \t")) (char '=');
   value <- parseValue;
   return (name, value);
}

parseSectionHeader = do{
   name <- between (char '[') (char ']') parseName;
   return name;
}

parseSection = do{
   name <- between parseCmtOrSpace parseCmtOrSpace parseSectionHeader;
   values <- endBy1 (parseNameValue) (parseCmtOrSpace);
   return (name, values);
}

parseIniFile  = do{
   result <- many1 (parseSection);
   return result;
}

list2Map list = Map.fromList (map (\e -> (fst e, Map.fromList (snd e))) list)

iniFileToMap path = do{
   result <- parseFromFile parseIniFile path;
      case (result) of
         Left err -> error (show err)
         Right xs -> return (list2Map(xs));
}


texts: Basic function to output repeating dates from iCal format

texts:
I have a function that implements parts of reading iCal repetition rules, and returns a list of dates when a certain event takes place.

Questions/Concerns of mine

Any comments on the use of anonymous functions? I added them to keep the code as DRY as possible.
One thing I rather dislike is the line return strtotime('+' . $increment . ' ' . $rrule_freq_map[$rrule['FREQ']], $start_timestamp); which casts from integer to string and back for no good reason. Couldn't think of a better way to accomplish the adding of time.
On a Drupal specific note, maybe the use of date in $single_day_output() should be replaced with format_date, but I'm not sure if there are any gains from that.
$next_timestamp() will break if used in more than one location. Currently not an issue, would be interesting to hear suggestions on that.

/**
 * Render the date and times of events.
 *
 * Has some internal helper functions do not make sense outside of this scope.
 */
function _bornholm_custom_calendar_event_dates($datetime) {
  // Ensure we have the date_repeat_split_rrule().
  module_load_include('inc', 'date_api', 'date_api_ical');

  $start_timestamp = strtotime($datetime['value']);
  $start_day = date('Y-m-d', strtotime($datetime['value']));
  $end_day = (isset($datetime['value2'])) ? date('Y-m-d', strtotime($datetime['value2'])) : NULL;
  $end_timestamp = (isset($datetime['value2'])) ? strtotime($datetime['value2']) : NULL;
  $output = '';

  // Build the output for a single days event information.
  $single_day_output = function($timestamp) {
    $output = t('@day d. @date t. @time', array(
      '@day' => t(date('D', $timestamp)),
      '@date' => date('d.m.Y', $timestamp),
      '@time' => date('H:i', $timestamp),
    ));

    return ucfirst($output);
  };

  // Check whether or not the current has a repeat rule.
  $repeats = function ($datetime) {
    if ($datetime['rrule'] !== NULL) {
      list($rrule, $exceptions, $additions) = date_repeat_split_rrule($datetime['rrule']);
      if ($rrule['FREQ'] !== 'NONE') {
        return $rrule;
      }
    }

    return NULL;
  };

  // When an event repeats, step forward the timestamp once.
  $next_timestamp = function($rrule, $start_timestamp) {
    static $count = 0;

    $rrule_freq_map = array(
      'DAILY' => 'day',
      'WEEKLY' => 'week',
      'MONTHLY' => 'month',
    );

    $increment = $count++ * $rrule['INTERVAL'];

    return strtotime('+' . $increment . ' ' . $rrule_freq_map[$rrule['FREQ']], $start_timestamp);
  };

  if ($rrule = $repeats($datetime)) {
    for ($i = 0; $i < $rrule['COUNT'] && $i < 100; $i++) {
      $new_timestamp = $next_timestamp($rrule, $start_timestamp);

      if ($end_day === NULL || $start_day === $end_day) {
        $output .= $single_day_output($new_timestamp);

        if ($end_timestamp) {
          $output .= ' - ' . date('H:i', $new_timestamp + ($end_timestamp - $start_timestamp));
        }
      }
      else {
        $output .= $single_day_output($new_timestamp) . ' ' . t('until') . '
' . $single_day_output($new_timestamp + ($end_timestamp - $start_timestamp)) . '
';
      }
    }
  }
  else {
    if ($end_day === NULL || $start_day === $end_day) {
      $output = $single_day_output($start_timestamp);
      if ($end_timestamp) {
        $output .= ' - ' . date('H:i', $end_timestamp);
      }
    }
    else {
      $output = $single_day_output($start_timestamp) . ' ' . t('until') . '
' . $single_day_output($end_timestamp);
    }
  }

  return $output;
}


texts: Project Euler problem # 3 is this the most efficient approach in Python or can I do better?

texts:
The problem statement: The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

This code takes 9 seconds!, is there a better way?

from time import time

def is_prime(number):
    for divisor in range(2, int(number ** 0.5) + 1):
        if number % divisor == 0:
            return False
    return True

def calculate_largest(number):
    # checking backwards to get the largest number first
    for divisor in range(int(number ** 0.5) + 1, 0, -1):
        if is_prime(divisor) and number % divisor == 0:
            return divisor

if __name__ == '__main__':
    time1 = time()
    print(calculate_largest(600851475143))
    print(time() - time1)


texts: Code and Inputs on to use AWS temporary Credentials

texts:
I am adding below code for review as i am bit new to boto3. This Script adds tags (key and value) to All Volumes of EC2 listed in Excel. Is there any more effective way i could have written this? Also I am using AWS temporary credentials by editing ~/aws/config and making profiles. Is there any other way i can use w.r.t login with temporary credentials in boto3 ?

def tagging(profilename):

    print("")
    print("Using Profile: {}".format(profilename))
    print("")
    path = input("Please enter the full path of Excel to execute: ")
    wb=load_workbook('Data_TagVolumes.xlsx')
    Sheet1 = wb.active
    max_row=Sheet1.max_row
    max_column=Sheet1.max_column
    Tag_Key = Sheet1.cell(2,1).value
    Tag_Value = Sheet1.cell(2,2).value
    print("")
    print("All Volumes of each Below EC2 Servers will be Tagged:")
    print("")
    tag_vm = []
    for each in range(2,max_row+1):
        print("{}".format(Sheet1.cell(each,3).value))
        tag_vm.append(Sheet1.cell(each,3).value)
    print("")
    print("With Tag Key as : {}".format(Tag_Key))
    print("")
    print("And Tag Value as : {}".format(Tag_Value))
    print("")
    confirm = input("Please Confirm Yes to proceed or No to exit: ").lower()
    print("")
    if confirm == 'yes':
        session = boto3.Session(profile_name=profilename)
        ec2 = session.client('ec2')
        tag_vol = []
        for vm in tag_vm:
            response = ec2.describe_instances(
                Filters=[
                            {
                            'Name': 'tag:Name',
                            'Values': [vm]
                            },
                        ],
                    )
            for each in list(range(len(response['Reservations'][0]['Instances'][0]['BlockDeviceMappings']))):
                vm_vol = response['Reservations'][0]['Instances'][0]['BlockDeviceMappings'][each]['Ebs']['VolumeId']
                print("{}   {}".format(vm,vm_vol))
                tag_vol.append(vm_vol)
        ec2.create_tags(Resources= tag_vol,
            Tags=[
                    {
                    'Key': Tag_Key,
                    'Value': Tag_Value
                    },
                ]
            )
        print("")
        print("All Volumes Tagged. please validate on AWS Console")
        print("")
    else:
        print("")
        print ("OK Exited")
        print("")

     def main():
       profilename = input("Please enter aws credentials profile name: ")
       tagging(profilename)

 if __name__ == '__main__':
      main()


texts: Try every option for a command and make anagrams out of the successful ones

texts:
What I have: I am trying to find what words you can make out of Linux command options like ls -cat or ps -elf. To do that I am iterating through an array of 50 commands, trying to run each with flags -[a-z] and then making anagrams out of the successful options. It is working and here is what I have:

#!/bin/bash

# Pull in a list of common Linux commands
commandList=( $(
  curl 'http://www.thegeekstuff.com/2010/11/50-linux-commands/' 2> /dev/null \
    | grep -o '<h3>\([0-9].*[a-z][a-z][a-z].*\)</h3>' \
    | awk '{ print $(NF-2) }' \
    | sed -nr '/rm|wget|less|shutdown|<h3>/!p'
) );

# Pipe successful "$command -$option" pairs to 'an' to generate anagrams
for command in ${commandList[@]} ; do
    (for option in {a..z} ; do
        timeout -k 5 5 "$command" -"$option" > /dev/null 2>&1;
            if (($? == 0)); then
                printf "$option" | tr -d '\n'
            else
                    :
            fi
    done) | xargs an -w -d saneWordlist -m 3 2> /dev/null \
          | sed 's/^/\ '$command' -/' >> commandOptions.log
done

Self Criticism:
I know it is unreliable to rely on exit codes that are not at all consistent and just hoping the devs used 0 to indicate success. I also know I abused sed and awk a lot. I also didn't try to write this in a very POSIX-y way.

What I want help on:
I am not too worried about the web scraping part, I know it is cheap and messy. But, how can I improve the core section where I misuse sed and awk so much? I know there cleaner ways to accomplish what I want, but can't think of anything.


texts:
For this HackerRank warmup challenge, I was wondering if there was a way I could improve the selection of my indices for the minSum:

Here is the problem:

  Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than 32 bit integer.)

  Sample Input

1 2 3 4 5

  Sample Output

10 14

Here is the solution:

function miniMaxSum(inArr) {
    // Complete this function

    let maxSum = 0,
        minSum = 0;
   inArr.sort();

    for (var i = arr.length - 1, o = 0; i >= arr.length - 4, o < 4; i--, o++){
       maxSum += arr[i];
       minSum += arr[o];
    }
    console.log(minSum, maxSum)
}

Is there a way I could have avoided the o counter in my for loop and instead selected the array in a different way? Like minSum += arr[some math computation].

Also, any performance optimizations are welcome too.


texts:
The following code is to enlarge pictures using bilinear interpolation.  What can be modified in the function of slow_rescale to make it more efficient?  I expect to modify it from the view of Principles of Computer Organization.

unsigned char *slow_rescale(unsigned char *src, int src_x, int src_y, int dest_x, int dest_y)
{
 double step_x,step_y;          // Step increase as per instructions above
 unsigned char R1,R2,R3,R4;     // Colours at the four neighbours
 unsigned char G1,G2,G3,G4;
 unsigned char B1,B2,B3,B4;
 double RT1, GT1, BT1;          // Interpolated colours at T1 and T2
 double RT2, GT2, BT2;
 unsigned char R,G,B;           // Final colour at a destination pixel
 unsigned char *dst;            // Destination image - must be allocated here!
 int x,y;               // Coordinates on destination image
 double fx,fy;              // Corresponding coordinates on source image
 double dx,dy;              // Fractional component of source image    coordinates

 dst=(unsigned char *)calloc(dest_x*dest_y*3,sizeof(unsigned char));   // Allocate and clear   destination image
 if (!dst) return(NULL);                           // Unable to allocate image

 step_x=(double)(src_x-1)/(double)(dest_x-1);
 step_y=(double)(src_y-1)/(double)(dest_y-1);

 for (x=0;x<dest_x;x++)         // Loop over destination image
 for (y=0;y<dest_y;y++)
  {
fx=x*step_x;
fy=y*step_y;
dx=fx-(int)fx;
dy=fy-(int)fy;
getPixel(src,floor(fx),floor(fy),src_x,&R1,&G1,&B1);    // get N1 colours
getPixel(src,ceil(fx),floor(fy),src_x,&R2,&G2,&B2); // get N2 colours
getPixel(src,floor(fx),ceil(fy),src_x,&R3,&G3,&B3); // get N3 colours
getPixel(src,ceil(fx),ceil(fy),src_x,&R4,&G4,&B4);  // get N4 colours
   // Interpolate to get T1 and T2 colours
   RT1=(dx*R2)+(1-dx)*R1;
   GT1=(dx*G2)+(1-dx)*G1;
   BT1=(dx*B2)+(1-dx)*B1;
   RT2=(dx*R4)+(1-dx)*R3;
   GT2=(dx*G4)+(1-dx)*G3;
   BT2=(dx*B4)+(1-dx)*B3;
   // Obtain final colour by interpolating between T1 and T2
   R=(unsigned char)((dy*RT2)+((1-dy)*RT1));
   G=(unsigned char)((dy*GT2)+((1-dy)*GT1));
   B=(unsigned char)((dy*BT2)+((1-dy)*BT1));
  // Store the final colour
  setPixel(dst,x,y,dest_x,R,G,B);
 }
  return(dst);
}
void getPixel(unsigned char *image, int x, int y, int sx, unsigned char *R, unsigned char *G, unsigned char *B)
{
 // Get the colour at pixel x,y in the image and return it using the provided RGB pointers
 // Requires the image size along the x direction!
 *(R)=*(image+((x+(y*sx))*3)+0);
 *(G)=*(image+((x+(y*sx))*3)+1);
 *(B)=*(image+((x+(y*sx))*3)+2);
}

void setPixel(unsigned char *image, int x, int y, int sx, unsigned char R, unsigned char G, unsigned char B)
{
 // Set the colour of the pixel at x,y in the image to the specified R,G,B
 // Requires the image size along the x direction!
 *(image+((x+(y*sx))*3)+0)=R;
 *(image+((x+(y*sx))*3)+1)=G;
 *(image+((x+(y*sx))*3)+2)=B;
}


texts: Generate every unique combination using all elements from array

texts:
I am trying to make a script that generates every possible combination from an array of elements. I have found a script that does it, but it is too intensive and takes extremely long to generate anything that has more than 7 elements inside the array.

I am trying to achieve, where from an array of:

array("Quick", "Brown", "Fox");

I would get a result of:

Quick Brown Fox
Quick Fox Brown
Brown Quick Fox
Brown Fox Quick
Fox Quick Brown
Fox Brown Quick

As you can see, that a single word never repeats itself, and there are only unique generations, as well as it always uses all elements of the array, so it never returns less elements than the length of array.

Here is the code that I am currently using:

function f_($n) {
    if($n<2) { return 1; }
    for($x = 2;$n-1>1;$x*=$n--);
    return $x;
}

function array_restore($r) {
    $clean = array();
    if(is_array($r)) {
        foreach($r as $k) {
            $clean[] = $k;
        }
    }

    return $clean;
}

function connect($arr){
    $back = "";
    foreach($arr as $a){
        if($back != ""){
            $back .= " ";
        }

        $back .= $a;
    }
    return $back;
}

function cmb($v) {
    $str = count($v);
    $tot = f_($str);

    $combo = array();
    for($i=0;$i<$tot*8;$i++) {
        shuffle($v);
        $sf = connect($v);
        if(!in_array($sf, $combo)){
            $combo[] = $sf;
        }
    }

    $x = array_unique($combo);
    return array_restore($x);
}

var_dump(cmb(array("Quick", "Brown", "Fox")));

EDIT: I found a bit better algorithm, seems like its impossible to make anything even quicker, so I will have to find a different way to approach my problem.

function pc_permute($items, $perms = array( )) {
    $back = array();
    if (empty($items)) {
        $back[] = join(' ', $perms);
    } else {
        for ($i = count($items) - 1; $i >= 0; --$i) {
             $newitems = $items;
             $newperms = $perms;
             list($foo) = array_splice($newitems, $i, 1);
             array_unshift($newperms, $foo);
             $back = array_merge($back, pc_permute($newitems, $newperms));
         }
    }
    return $back;
}


texts: One consumer and two producers using threads

texts:
I have based this code on Producer-Consumer Threading on Real Python.

The idea is that I have 2 producers:

One producer  will give result every 0.4 to 0.7 seconds, depending on REST call.
The second producer will be a web socket that will forward filtered information to consumer.

And one consumer that needs to act on results from producers.

This code is working fine, but I'd like a second opinion on what I can improve from design/architecture side.

import concurrent.futures
import logging
import queue
import random
import threading
import time

def producer_1(queue_1, event_1):
    """Pretend we're getting a number from the network."""
    while True:
        time.sleep(1)
        message = random.randint(1, 101)
        logging.info("Producer_1 got message: %s", message)
        queue_1.put(message)
        event_1.set()

    logging.info("Producer_1 Exiting")

def producer_2(queue_2, event_2):
    """Pretend we're getting a number from the network."""
    while True:
        time.sleep(0.5)
        message = random.randint(1, 101)
        logging.info("Producer_2 got message: %s", message)
        queue_2.put(message)
        event_2.set()

    logging.info("Producer_2 Exiting")

def consumer(queue_1, queue_2, event_1):
    """Pretend we're saving a number in the database."""

    while True:
        event_1.wait()
        logging.info("Consumer START")

        if not queue_1.empty():
            message = queue_1.get()
            logging.info("Consumer storing message_1: %s (size=%d)", message, queue_1.qsize())

            if queue_1.empty():
                event_1.clear()
                logging.info("Queue_1 EMPTY")

        if not queue_2.empty():
            message = queue_2.get()
            logging.info("Consumer storing message_2: %s (size=%d)", message, queue_2.qsize())

            if queue_2.empty():
                event_1.clear()
                logging.info("Queue_2 EMPTY")

        logging.info("Consumer END")

    logging.info("Consumer Exiting")

if __name__ == "__main__":
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,
                        datefmt="%H:%M:%S")

    pipeline_1 = queue.Queue(maxsize=10)
    event_1 = threading.Event()

    pipeline_2 = queue.Queue(maxsize=10)

    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        #executor.submit(consumer, pipeline_1, event_1, pipeline_2, event_2)
        executor.submit(consumer, pipeline_1, pipeline_2, event_1)
        executor.submit(producer_1, pipeline_1, event_1)
        executor.submit(producer_2, pipeline_2, event_1)

        logging.info("Main: about to set event")


texts: Eliminate copy/paste and Factor logic out of foreach loop

texts:
I have two conditions that need to traverse the same data but inside the traversal the logic changes slightly for each respective condition and in different places. If it was the same place that would be easy to factor out, but what's the best approach if it's not all in the same place for every condition? I seem to run into this situation often when parsing data.

switch(batch.DocumentType.ImportedFileDisposition)
{
    case ImportedFileDispositionActions.Delete:
        foreach (string documentMetadataFile in documentMetadataPaths)
        {
            string documentPath = Path.GetDirectoryName(documentMetadataFile);
            XDocument metadata = XDocument.Load(documentMetadataFile);
            foreach (var pageElement in metadata.Root.Element("Pages").Elements("Page"))
            {
                string pageName = null;
                XAttribute attribute = pageElement.Attribute("FileName");
                if (attribute != null)
                    pageName = attribute.Value;

                string pagePath = null;
                string originalPagePath = null;
                if (!string.IsNullOrWhiteSpace(pageName))
                {
                    pagePath = IOUtility.PathCombine(documentPath, pageName);
                    File.Delete(pagePath);
                }
            }
            File.Delete(documentMetadataFile);
            Directory.Delete(documentPath, true);
        }
        break;
    case ImportedFileDispositionActions.Archive:
        foreach (string documentMetadataFile in documentMetadataPaths)
        {
            string documentPath = Path.GetDirectoryName(documentMetadataFile);
            string baseImportDirectory = documentPath;
            string archiveDirectory = GenerateArchiveDirectory(batch, documentPath);
            XDocument metadata = XDocument.Load(documentMetadataFile);
            foreach (var pageElement in metadata.Root.Element("Pages").Elements("Page"))
            {
                string pageName = null;
                XAttribute attribute = pageElement.Attribute("FileName");
                if (attribute != null)
                    pageName = attribute.Value;

                string pagePath = null;
                string originalPagePath = null;
                if (!string.IsNullOrWhiteSpace(pageName))
                {
                    pagePath = IOUtility.PathCombine(documentPath, pageName);
                    string newArchivePath = IOUtility.PathCombine(archiveDirectory, pageName);
                    try
                    {
                        IOUtility.MoveFile(pagePath, newArchivePath);
                    }
                    catch
                    {
                        try
                        {
                            IOUtility.CopyFile(pagePath,newArchivePath, true);
                        }
                        catch (Exception ex)
                        {
                            throw new IOException("Failed to move or copy file: " + pagePath + " to archive: " + newArchivePath, ex);
                        }
                    }
                    File.Delete(pagePath);
                }
            }
            File.Delete(documentMetadataFile);
            Directory.Delete(documentPath, true);
        }
        break;
}


texts: F# program to generate a Map of substrings frequencies

texts:
I wrote the following F# program that takes an input txt file and create a Map that contains all possible substrings of size N and their frequency in the file.

In other words if I call the program with a text file with the following content:

  James John Max Gary Jess Gilles Mary

With a length of 2, the probabilityTable contains a value with a key of "ar" with a value of 0.054054.

Here is the program:

module NameGenerator

open System
open System.Collections.Generic

// Open a file and read all lines into IEnumerable<string>
let readInputFile (filePath:string) =
    System.IO.File.ReadAllText(filePath)

// Parses a string and count the total number of occurrences of substrings of size length
let rec countOccurrences (input:string) (occurrenceTable:Map<string, float>) length =
    let adjLen = length - 1

    match input |> Seq.toList with
    | head :: tail when tail.Length >= adjLen ->
        let other = Seq.take adjLen tail |> Seq.toList
        let occurrence = (head :: other |> Array.ofList |> String)

        // add current occurrence to the occurrence table
        let updatedMap = match occurrenceTable.ContainsKey (occurrence) with
                         | true -> occurrenceTable.Add(occurrence, occurrenceTable.[occurrence] + 1.0)
                         | false -> occurrenceTable.Add(occurrence, 1.0)

        // call the function recursively with the rest of the string
        countOccurrences (tail |> Array.ofList |> String) updatedMap length
    | _ -> occurrenceTable

// Given a map that contains the a collection of string and their respective counts, return a
// frequency map that is obtained by count / total count
let buildFrenquencyTable (occurrenceTable:Map<string, float>) =
    // fold occurence dict, count total
    let total = Map.fold (fun acc key value -> acc + value) 0.0 occurrenceTable

    // map over previous map and replace values with count / total count
    Map.map (fun key value -> Math.Round(value / total, 6)) occurrenceTable

// Given an input file create a probability table for the different letters in the file
let buildProbabilityTable (filePath:string) length =
    let input = readInputFile filePath
    let initialDictionary = Map.empty

    countOccurrences input initialDictionary length
    |> buildFrenquencyTable

I would like a review on how I could do things better and use a more functional style.