texts: Python: wild card pattern matching with memoization

texts:
Here is my take on wild card pattern matching with memoization.

I would appreciate comments on clarity of the code, as well as suggested ways to improve readability and maintainability (for bigger projects).

Also, comments on how to change the algorithm to a better one (do it bottom to top instead for example) will also be very welcome.

Last thing I'm looking for are more test cases that will lead to greater code coverage, especially of the edge cases/boundary conditions. Thanks

The commented sections are for collecting and printing out information that I used while debugging. The code is correct and those sections are no longer needed.

class wild_card_pattern_matching:
    def __init__(self, p, s):
        self.m = [[None for _ in range(len(p) + 1)] for _ in range(len(s) + 1)]
        self.p = p
        self.s = s
        self.c = 0

    def match(self):
        def f(p,s,p_idx,s_idx):
            self.c += 1

            # end condition 1
            if p_idx == s_idx == 0:
                self.m[s_idx][p_idx] = True

            # end condition 2
            elif s_idx == 0:
                self.m[s_idx][p_idx] = f(p,s,p_idx-1,s_idx) and p[p_idx-1] == '*'

            # memo table init
            elif p_idx == 0:
                self.m[s_idx][p_idx] = False

            # use memo if possible
            elif self.m[s_idx][p_idx] != None:
                return self.m[s_idx][p_idx]

            # choose between ignoring * and "accepting" it
            elif p[p_idx-1] == '*':
                self.m[s_idx][p_idx] = f(p,s,p_idx-1,s_idx) or f(p,s,p_idx,s_idx-1)

            # matching characters
            elif p[p_idx-1] == '?' or p[p_idx-1] == s[s_idx-1]:
                self.m[s_idx][p_idx] = f(p,s,p_idx-1,s_idx-1)

            # pattern != string
            else:
                self.m[s_idx][p_idx] = False

            return self.m[s_idx][p_idx]

        f(self.p,self.s,len(self.p), len(self.s))

        return self.m[-1][-1]

obj_ls = [wild_card_pattern_matching('*', '')]
obj_ls += [wild_card_pattern_matching('*', 'a')]
obj_ls += [wild_card_pattern_matching('*', 'b')]
obj_ls += [wild_card_pattern_matching('a*', 'ab')]
obj_ls += [wild_card_pattern_matching('*b', 'a')]
obj_ls += [wild_card_pattern_matching('a*a', 'aba')]
obj_ls += [wild_card_pattern_matching('*?*?', 'aa')]
obj_ls += [wild_card_pattern_matching('c*d?*', 'cda')]
obj_ls += [wild_card_pattern_matching('?*?*?*', 'xx0')]
obj_ls += [wild_card_pattern_matching('a', 'a')]
obj_ls += [wild_card_pattern_matching('', 'a')]
obj_ls += [wild_card_pattern_matching('******a*a', 'a')]
obj_ls += [wild_card_pattern_matching('******a*a', 'aa')]
obj_ls += [wild_card_pattern_matching('******?*a', 'a')]
obj_ls += [wild_card_pattern_matching('******a*a**', 'a')]
obj_ls += [wild_card_pattern_matching('******a*a*', 'ababaab')]
obj_ls += [wild_card_pattern_matching('******a*a*', 'ababaa')]

print '         string         pattern    result    counter'
print '='*55
for w in obj_ls:
    print '%15s%15s%10r%10d' % (w.s,w.p,w.match(),w.c)
#    for l in w.m:
#        print l


texts: When to catch/wrap an exception vs declaring that method throws exception

texts:
In the snippet below the three exceptions I declare in the throws clause are all thrown by BeanUtils.setProperty(), which is a third party library.

Is letting these three exceptions "bubble upwards" with a throws declaration bad style?  Is it better to wrap them in my own RoleBeanException and throw that?

public BeanRole getRoleBean(Request request)
    throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
{
    String[] arrayOfProperties = {"application", "environment", "role"};
    BeanRole roleBean = new BeanRole();
    for (String strProperty : arrayOfProperties) {
        String strValue = BeanUtils.getProperty(request, strProperty);
        BeanUtils.setProperty(roleBean, strProperty, strValue);
    }
    return roleBean;
}


texts: Change case of string, replace hyphens with spaces and capitalize first letter

texts:
I'm trying to transform the following string "joe-smith" to "Joe Smith". I have the following code which seems to work okay, but is there a faster, better way?

var prettify = function(str){
   var temp = str.split('-'), i, pretty;

   for(i = 0; i < temp.length; i++){
     temp[i] = temp[i].charAt(0).toUpperCase() + temp[i].slice(1);
   }

   pretty = temp.join(' ');

   return pretty;
 };

 var prettyString = prettify('joe-smith');
// outputs "Joe Smith"


texts:
Consider I have a String:

String value = "Sunday  -  H15,Sunday  -  H03,Sunday  -  H13,Sunday  -  H01,Sunday  -  H05,Friday  -  H23,Saturday  -  H05,Monday  -  H16,Monday  -  H17,Monday  -  H18,Monday  -  H19,Monday  -  H20";

In this String we have Days (Sunday, Monday etc..) and the alphanumeric (H15, H03 etc..) is hours.

Now I want a JSON format for Map<String, Map<String, List<String>>> in which Key should be Day and Value should be the Map having Key as Hours and Values as list of Hours which has same day. Something like this format:

{"Monday":{"Hours":["H16","H17","H18","H19","H20"]},"Thursday":{"Hours":[]},"Friday":{"Hours":["H23"]},"Sunday":{"Hours":["H15","H03","H13","H01","H05"]},"Wednesday":{"Hours":[]},"Tuesday":{"Hours":[]},"Saturday":{"Hours":["H05"]}}

Note: In this example there are some days with valid hours (like Sunday, Monday etc) while other are having empty Hours (like Wednesday and Thursday).

This code is working fine as required but I feel that it can be refactored.

public class DayPartProcessingTest {

  public static void main(String[] args) throws JsonProcessingException {
    String propertyValue = "Sunday  -  H15,Sunday  -  H03,Sunday  -  H13,Sunday  -  H01,Sunday  -  H05,Friday  -  H23,Saturday  -  H05,Monday  -  H16,Monday  -  H17,Monday  -  H18,Monday  -  H19,Monday  -  H20";
    Map<String, List<String>> map = new HashMap<String, List<String>>();
    String[] dayParts = propertyValue.split(",");

    for (String string : dayParts) {
      String[] array = string.split("  -  ");
      if (map.get(array[0]) == null) {
        List<String> list = new ArrayList<>();
        list.add(array[1]);
        map.put(array[0], list);
      } else {
        List<String> tempList = map.get(array[0]);
        tempList.add(array[1]);
        map.put(array[0], tempList);
      }
    }

    Map<String, Map<String, List<String>>> payload = new HashMap<>();
    Map<String, List<String>> hrs1 = new HashMap<>();
    hrs1.put("Hours", new ArrayList<String>());
    payload.put("Sunday", hrs1);
    payload.put("Monday", hrs1);
    payload.put("Tuesday", hrs1);
    payload.put("Wednesday", hrs1);
    payload.put("Thursday", hrs1);
    payload.put("Friday", hrs1);
    payload.put("Saturday", hrs1);
    for (Entry<String, List<String>> entry : map.entrySet()) {
      Map<String, List<String>> hrs = new HashMap<>();
      hrs.put("Hours", entry.getValue());
      if (payload.containsKey(entry.getKey())) {
        payload.put(entry.getKey(), hrs);
      }
    }

    String json = new ObjectMapper().writeValueAsString(payload);
    System.out.println(json);

  }


texts: Effective way to handle multiple time string to timestamp

texts:
I have 4 cases of time string as follow:

s = "July 5, 2016, 12:04 a.m."
s = "July 5, 2016, 7 a.m."
s = "July 5, 2016, midnight."
s = "July 5, 2016, noon."

I want to convert string to timestamps. Based on this question, I need to declare 4 cases of pattern. I am looking forward to improve my solution.

The following code is my solution:

import time
import datetime

s1 = "July 5, 2016, 12:04 a.m."
s2 = "July 5, 2016, 7 a.m."
s3 = "July 5, 2016, midnight."
s4 = "July 5, 2016, noon."

def convert(timestring):
    # clear dot
    timestring = timestring.replace(".","")
    # convert s3 and s4 to s1 and s2
    timestring = timestring.replace("midnight", "12:00 am") if "midnight" in timestring else timestring
    timestring = timestring.replace("noon", "12:00 pm") if "noon" in timestring else timestring
    result = None
    try:
        # try to match s2
        print(timestring)
        result = time.mktime(datetime.datetime.strptime(timestring, "%B %d, %Y, %I %p").timetuple())
    except ValueError as e:
        try:
            result = time.mktime(datetime.datetime.strptime(timestring, "%B %d, %Y, %I:%M %p").timetuple())
        except ValueError as e:
            print(e)
    print(result)

def main():
    convert(s1)
    convert(s2)
    convert(s3)
    convert(s4)

if __name__ == '__main__':
    main()


texts: Read characters from stdin into an resizeable array

texts:
As first steps in C, I'm trying to write a program that reads from stdin into an array allocated on the free store, until an exclamation mark ! is entered. The array should be extended to prevent overflow.

Here is what I've written:

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

char* increase_buffer_size(char *buff_ptr, size_t multiplier);

//==================================================================
int main () {
    // initial buffer size
    size_t buffer_size = 32;

    // allocate 32 bytes of heap memory
    char *buffer_pointer = (char*) malloc(buffer_size);

    // input loop variables
    char input_var;
    size_t counter = 0;
    char sentinel = '!';

    // input loop
    printf("Type input\n>>");
    while (input_var = getchar()) {

        // check termination condition
        if (input_var == sentinel) break;

        // check capacity and double it if maximum is reached
        if (counter == buffer_size - 1) buffer_pointer = increase_buffer_size(buffer_pointer, buffer_size *= 2);

        // populate buffer
        buffer_pointer[counter++] = input_var;
    }

    getchar();

    // print input values
    printf("Buffer content: \n");
    for (auto i = 0; i < counter; ++i) printf("%c %c", buffer_pointer[i], ' ');

    getchar();
}

//==================================================================

char* increase_buffer_size(char *buff_ptr, size_t new_size) {

    char* new_ptr = (char*) realloc(buff_ptr, new_size);

    return new_ptr;
}

As I already mentioned these are my first steps in C, so I was wondering:

Is the above code written in accordance with C conventions?

Is there anything that can be skipped or written better?


texts: Calculating the Percentage of a Pair Occurring Across a Lot of Lists

texts:
I'm looking for a way to speed this code up. It took about 4.5 hours to run on ~20k decks. I'm open to restructuring my SQL query, but feel adjusting the python would be more effective. The goal of this code is to see how many times a pair of cards occurs in all the decks. For example if ("card", "name") appears in 27/100 decks, it returns .27.
This code takes every deck in a format, and returns the cards in those decks. This gives me a list of a lot of cards ((cardId, "card name", deckId), ... (cardId "card name", deckId)). I use the deckId to make a bunch of lists representing each deck (newList). Using those lists I get each unique card and put it into a separate list (superSet).
From there I loop through superSet twice to get each possible pair. Then loop through newList to see if a pair is in a deck.
I know it's somewhat complicated and I probably didn't explain it the best. I'll gladly update this post to clarify anything I can.
from classes.general import Database

def main():
    dbm = Database()
    with dbm.con:
        dbm.cur.execute("""SELECT c.id, c.name, ctd.deckId FROM cards c
        JOIN cardToDeck ctd ON ctd.cardId = c.id
        JOIN deckToEvent dte ON dte.deckId = ctd.deckId
        JOIN eventToFormat etf ON etf.eventId = dte.eventId
        WHERE etf.formatId = 5
        ORDER BY ctd.deckId""")
        decks = dbm.cur.fetchall()

        #print(decks)

        #I'm not entirely sure how this works
        #Somehow it takes everything with the same deckId (index:2) and puts them into one list
        values = set(map(lambda x:x[2], decks))
        newlist = [[y[1] for y in decks if y[2] == x] for x in values]

        #print(newlist[0])

        superSet = []
        for l in newlist:
            for c in l:
                if c not in superSet:
                    superSet.append(c)

        #print(superSet)

        count = 0
        for x in superSet:
            for y in superSet:
                if x is y:
                    continue
                #print(x)
                #print(y)
                for d in newlist:
                    #print(d)
                    if x in d and y in d:
                        count += 1
                deckPerc = count / len(newlist)
                if deckPerc != 0.0:
                    print(count / len(newlist)) #needs to go into the db
                count = 0

if __name__== "__main__":
    main()


texts: VBA script too slow - Checks for duplicate school enrollments and keeps more recent enrollment

texts:
I have over 260k lines of data. This code is likely to take more than 30hrs to run. Would like help to speed this up. Or is there a way to use something else like PowerQuery to accomplish this? I am very new so please break it down clearly.

There are 260k rows of student achievement data. Some students may have multiple lines with the same school, meaning that they have math, reading, science achievement at one school (3 rows of data, 1 student, 1 school). But then if they transfer schools, they will have two groups of data (1 student, 2 schools). I need to keep only the information for the most recent school. I want to delete based on date.

Sub RecentEnrollment()

Dim lrow As Long, lcol As Long, frow As Long
Dim i As Integer, r As Long, c As Long
Dim num As Long, pos As Long
Dim myrng As Variant
Dim namerng As Variant
Dim schrange As Variant
Dim RowFirst As Double, _
    RowLast As Double ' Double is used here to handle the large number of
            'rows. Integer and Long are small Bit sizes.

Application.ScreenUpdating = False

With Worksheets(1)
    'Find the last non-blank cell in Column "Student ID"
    lrow = .Cells(Rows.Count, 1).End(xlUp).Row
    lcol = .Cells(1, Columns.Count).End(xlToLeft).Column

    MsgBox "Last Row: " & lrow

    'Define the range to search for duplicates. myrng is student id-name
    'combos and schrange is studentID-sch combos. You may need to change the
    'sheet name.

For r = 2 To lrow

    'Define the range for the studentId-Name column to search for number of
    'times each appears 'num and it's position in the list 'pos

    Set namerng = .Range(Cells(r, 5), Cells(lrow, 5))

   'Find the first instance of the student name in the file

    RowFirst = .Cells.Find(What:=.Cells(r, 2), LookAt:=xlWhole,SearchDirection:=xlNext, MatchCase:=False).Row

   'Find the last instance of the student name in the file

    RowLast = .Cells.Find(What:=.Cells(r, 2), LookAt:=xlWhole, SearchDirection:=xlPrevious, MatchCase:=False).Row

    Set myrng = .Range(Cells(RowFirst, 5), Cells(RowLast, 5))
    Set schrange = .Range(Cells(RowFirst, 3), Cells(RowLast, 3))

For c = 1 To 12
    If Application.WorksheetFunction.CountIf(myrng, Cells(r, 5).Value) >= 1 Then
     'How many times does the student name-school combo appear?
      schs = Application.WorksheetFunction.CountIf(schrange, Cells(r, 3).Value)

     'How many times does the student name appear in the file?
      num = Application.WorksheetFunction.CountIf(myrng, Cells(r, 5).Value)

     'What is the position of this student record relative to the duplicated
      records
      pos = Application.WorksheetFunction.CountIf(namerng, Cells(r, 5).Value)

      'For every student record, print the most recent exit date for all
      enrollments
        MaxDate = WorksheetFunction.Max(.Range(.Cells(RowFirst, 9), .Cells(RowLast, 9)))
        Cells(r, 10) = MaxDate

    Else
        'Print most recent exit date
            Cells(r, 10) = MaxDate

    End If

        If num > schs Then

            If Cells(r, 9) = MaxDate Then

                Cells(r, 11) = "Keep"

            Else

                Cells(r, 11) = "Delete"

        End If

    End If

    Cells(r, 24) = Time
Next c

Next r

End With
Application.ScreenUpdating = True

End Sub


texts: Finding which users have the most questions with unaccepted answers

texts:
I was looking at a few profiles this afternoon and noticed a few users had plenty of open questions.  This led me to wonder which users actually had the highest amount of questions with unaccepted answers (both in size and percent).  So with all the hoopla I kept seeing in the 2nd monitor about SEDE queries, I decided to try my hand at writing one.

with unanswered as (
  select
    posts.Id as PostId
  from
    posts
  where posts.PostTypeId = 1            -- questions
    and posts.OwnerUserId is not null   -- user exists
    and posts.AcceptedAnswerId is null  -- no answer selected
    and posts.ClosedDate is null        -- still open
  group by posts.Id
),

percentages as (
  select
    users.Id as UserId,
    count(posts.Id) as Questions,
    count(unanswered.PostId) as UnansweredQuestions,
    (count(unanswered.PostId) * 100.0 / count(posts.Id)) as UnansweredPct
  from
    users left outer join
    posts on users.Id = posts.OwnerUserId
          left outer join
    unanswered on posts.Id = unanswered.PostId
  where
    posts.PostTypeId = 1
  group by
    users.Id
)

select top ##MaxRowsToSelect:int?100##
  UserId as [User Link],
  UnansweredQuestions as [Unanswered Questions],
  Questions,
  round(UnansweredPct, 1) as [Unanswered %]
from percentages
where UnansweredPct > ##MinUnansweredPct:int?40##
  and UnansweredQuestions > ##MinUnansweredQuestions:int?10##
order by UnansweredPct desc;


texts:
I am creating simple quiz app in Django. It works, but I think that way I've done it is not the best. I have Exam detail view, which display questions related to that exam and answers for these questions. What are your suggests about it? I pasted only models, because I think that this is the problem here.

from django.db import models

class Answer(models.Model):
    """
    Answer's Model, which is used as the answer in Question Model
    """
    text = models.CharField(max_length=128, verbose_name=u'Answer\'s text')
    is_valid = models.BooleanField(default=False)

    def __str__(self):
        return self.text

class Question(models.Model):
    question_text = models.CharField(max_length=256, verbose_name=u'Question\'s text')
    answers = models.ManyToManyField(Answer)
    is_published = models.BooleanField(default=False)

    def __str__(self):
        return "{content} - {published}".format(content=self.question_text, published=self.is_published)

class Exam(models.Model):
    """
    Exam's model, works as a wrapper for the questions
    """
    name = models.CharField(max_length=64, verbose_name=u'Exam name', )
    slug = models.SlugField()
    questions = models.ManyToManyField(Question)

    def __str__(self):
        return self.name


texts:
From the text:

  Exercise 2.68.  The encode procedure
  takes as arguments a message and a
  tree and produces the list of bits
  that gives the encoded message.

(define (encode message tree)
  (if (null? message)
      '()
      (append (encode-symbol (car message) tree)
              (encode (cdr message) tree))))

  Encode-symbol is a procedure, which
  you must write, that returns the list
  of bits that encodes a given symbol
  according to a given tree. You should
  design encode-symbol so that it
  signals an error if the symbol is not
  in the tree at all. Test your
  procedure by encoding the result you
  obtained in exercise 2.67 with the
  sample tree and seeing whether it is
  the same as the original sample
  message.

The textbook provides the following definitions:

(define (make-leaf symbol weight)
  (list 'leaf symbol weight))
(define (leaf? object)
  (eq? (car object) 'leaf))
(define (symbol-leaf x) (cadr x))
(define (weight-leaf x) (caddr x))

(define (make-code-tree left right)
  (list left
        right
        (append (symbols left) (symbols right))
        (+ (weight left) (weight right))))

(define (left-branch tree) (car tree))

(define (right-branch tree) (cadr tree))
(define (symbols tree)
  (if (leaf? tree)
      (list (symbol-leaf tree))
      (caddr tree)))

(define (weight tree)
  (if (leaf? tree)
      (weight-leaf tree)
      (cadddr tree)))

(define (decode bits tree)
  (define (decode-1 bits current-branch)
    (if (null? bits)
        '()
        (let ((next-branch
               (choose-branch (car bits) current-branch)))
          (if (leaf? next-branch)
              (cons (symbol-leaf next-branch)
                    (decode-1 (cdr bits) tree))
              (decode-1 (cdr bits) next-branch)))))
  (decode-1 bits tree))
(define (choose-branch bit branch)
  (cond ((= bit 0) (left-branch branch))
        ((= bit 1) (right-branch branch))
        (else (error "bad bit -- CHOOSE-BRANCH" bit))))
(define (adjoin-set x set)
  (cond ((null? set) (list x))
        ((< (weight x) (weight (car set))) (cons x set))
        (else (cons (car set)
                    (adjoin-set x (cdr set))))))

(define (make-leaf-set pairs)
  (if (null? pairs)
      '()
      (let ((pair (car pairs)))
        (adjoin-set (make-leaf (car pair)    ; symbol
                               (cadr pair))  ; frequency
                    (make-leaf-set (cdr pairs))))))

(define sample-tree
  (make-code-tree (make-leaf 'A 4)
                  (make-code-tree
                   (make-leaf 'B 2)
                   (make-code-tree (make-leaf 'D 1)
                                   (make-leaf 'C 1)))))

(define sample-message '(0 1 1 0 0 1 0 1 0 1 1 1 0))

(define (encode message tree)
  (if (null? message)
      '()
      (append (encode-symbol (car message) tree)
              (encode (cdr message) tree))))

And I wrote the following answer:

(define (member? x set)
  (not (equal? (member x set) false)))

(define (encode-branch symbol tree)
  (let ((left (left-branch tree))
        (right (right-branch tree)))
    (cond ((member? symbol (symbols left)) (list 0 left))
          ((member? symbol (symbols right)) (list 1 right))
          (else (error "Symbol is not a member of either left or right branches of the tree - can't encode" symbol tree)))))

(define (encode-symbol symbol tree)
  (if (leaf? tree) '()
      (let ((new-branch (encode-branch symbol tree)))
        (cons (car new-branch) (encode-symbol symbol (cadr new-branch))))))

How can I improve my solution?


texts: My first (simple) template that does more than storing a value of type T

texts:
I just decided to get a bit more acustomed to using templates. Maybe this is a stupid question, but in my experience in C++ there is always some pitfall lurking aroung the corner. Thus I prefer the danger of embarresment instead of building up on bad habbits. Mainly as an exercise I wrote this:

#include <functional>
#include <string>
#include <sstream>

template <typename V,template <class> class R = std::greater,typename I=void>
struct Extremum {
    typedef V    value_type;
    typedef I    index_type;
    typedef R<V> relation_type;
    V value;
    I index;
    R<V> r;
    bool operator() (V v,I i){
        bool result = r(v,value);
        if (result){
            value = v;
            index = i;
        }
        return result;
    }
    Extremum(V v,I i) : value(v),index(i) {}
    std::string toString(){
        std::stringstream s;
        s << "value= " << value << " index= " << index;
        return s.str();
    }
};

template <typename V,template <class> class R>
struct Extremum<V,R,void> {
    typedef V    value_type;
    typedef void index_type;
    typedef R<V> realtion_type;
    V value;
    R<V> r;
    bool operator() (V v){
        bool result = r(v,value);
        if (result){ value = v; }
        return result;
    }
    Extremum(V v) : value(v) {}
    std::string toString(){
        std::stringstream s;
        s << "value= " << value;
        return s.str();
    }
};

which would be used like this:

Extremum<int,std::greater,int > e(0,0);
e(10,3);
e(123,5);
std::cout << e.toString() << std::endl;

Extremum<int> g(0);
g(123);
g(1234);
g(1);
std::cout << g.toString() << std::endl;

I used a ´toString()´ because it is for debugging and printing to the screen while I might want to overload in/output operators for real in/output.

I dont like so much the ordering of the template parameters, as both the second and the third parameter would make a good fit as the last parameter so it can be ommited on the instantiation. However, I guess there is no better solution than simply choosing one ordering.

I have no idea how to provide good initial values. My idea was to use something like std::numeric_limits<V>::max, however, it depends too much on the choosen relation whether it should be max, min or something completely different. Maybe the easiest is  let the user choose them when calling the constructor.

Aside from its functionaliy, which probably could be achieved with less code and a simple lambda or the like, is there anything inherently broken with this code? Anything obvious that could be improved?

Note that this is pre-C++11, but I would also be interested in any post-C++11 stuff.


texts:
I am swapping structure lexicographically by name.
Is there any way to improve the code when the structure entries are heavy.

Here is the code

#include<stdio.h>
#include<string.h>
struct College
{
    char name[100];
    char city[100];
    int yearOfEstablishment;
    float passPercentage;
};
void displayCollegeDetails(struct College c)
{
    printf("Name : %s\n",c.name);
    printf("City: %s\n",c.city);
    printf("Year of establishment : %d\n",c.yearOfEstablishment);
    printf("Pass percentage: %.2f\n",c.passPercentage);
}
void swap(struct College *a,struct College *b)
{
    struct College temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
int main()
{

    int n,i,j;
    //char name[100],city[100];
    //float paasPercentage;
    printf("Enter the number of colleges\n");
    scanf("%d",&n);
    struct College c[n];
    if(n<=0)
    {
        printf("Invalid Input\n");
        return 0;
    }

    for(i=0; i<n; i++)
    {
        fflush(stdin);
        printf("Enter the details of college %d\n",i+1);
        printf("Enter name\n");
        scanf("%s",c[i].name);
        printf("Enter city\n");
        scanf("%s",c[i].city);
        printf("Enter year of establishment\n");
        scanf("%d",&c[i].yearOfEstablishment);
        printf("Enter pass percentage\n");
        scanf("%f",&c[i].passPercentage);
    }
    for(i=0; i<n-1; i++)
    {
        for(j=i+1; j<n; j++)
        {
            if(strcmp(c[i].name,c[j].name)>0)
            {
                swap(&c[i],&c[j]);
            }
        }
    }
    printf("Details of colleges\n");
    for(i=0; i<n; i++)
    {
        fflush(stdin);
        printf("College %d\n",i+1);
        displayCollegeDetails(c[i]);
    }
    return 0;
    }


texts:
This code outputs the smallest number with more divisors than the input:

from operator import mul
from math import sqrt, ceil

def next_prime_factor(n):
    if n % 2 == 0:
        return 2
    for x in range(3, int(ceil(sqrt(n)) + 1), 2):
        if n % x == 0:
            return x
    return int(n)

def factor(n):
    factors=[]
    number=int(n)
    while number > 1:
                f=next_prime_factor(number)
                factors.append(f)
                number /= float(f)
                number=int(number)
                if number==1:break

    return list(factors)

def sundaram(max_n):
    numbers = range(3, max_n+1, 2)
    half = (max_n)/2
    initial = 4
    for step in xrange(3, max_n+1, 2):
        for i in xrange(initial, half, step):
            numbers[i-1] = 0
        initial += 2*(step+1)

        if initial > half:
            x=filter(None, numbers) + [2] if filter(None, numbers) != None else [2]
            return sorted(x)

def factor_count(n):
    factors=factor(n)
    primecounts=[]
    primes_list=sundaram(int(sqrt(n)))
    primes_list = primes_list if primes_list != None else [2]
    for i in primes_list:
        primecounts.append(factors.count(i))
    return primecounts

def div_exps(pcount):
    return [i+1 for i in pcount if i!=0]

def div_count(n):
    pcount=factor_count(n)
    div_count=reduce(mul,div_exps(pcount),1)
    return div_count

def next_num(last_num):
    if last_num == 1:
        return 2
    if last_num in sundaram(last_num+1):
        return 4

    plist=sundaram(int(sqrt(last_num))+1)

    div_count_factors=factor(div_count(last_num))
    num=1
    for i in enumerate(div_count_factors):
        num*=plist[i[0]]**(i[1]-1)

    end_num=num
    while 1:
        if div_count(end_num)<=div_count(last_num):
            end_num*=min(div_count_factors)
        else:
            break
    return end_num

ans=next_num(input('Input the last number chosen: '))
print 'The smallest number with more divisors than the inputted number is',ans,'.'

It was written to help win aid a number game.  The game is simple: somebody says a number, you say a number with more divisors than that number.

You get a point if your number is smaller.  So if Bob says "5", you can say "4" and get a point. The winner is first to 3 points.

This code outputs the next best number given the previous number as input.


texts: Finding longest list in list of lists in Python

texts:
I have the following code to find the longest list in a list of lists:

max_len = max([len(path) for path in paths])
[path for path in paths if len(path) == max_len][0]

Each path is a list of integers.  paths doesn't have to be a list.  So if I have, for example:

path_a = [1, 2, 3]
path_b = [1, 4]
path_c = [3, 5, 6, 2, 7]

Then the code should give me path_c.  In case of ties, it doesn't matter what's returned as long as it has the correct (longest) length.

Is there a more pythonic way?


texts:
I'd like to restrict user input in a form to a decimal with max two numbers before and 4 after decimal point.

Valid values would be:

50
0.1
1.23
4.5678
12.943

I'm currently doing the following:

$(function() {
  $('input').on('input', function() {
    this.value = this.value
      .replace(/[^\d.]/g, '')             // numbers and decimals only
      .replace(/(^[\d]{2})[\d]/g, '$1')   // not more than 2 digits at the beginning
      .replace(/(\..*)\./g, '$1')         // decimal can't exist more than once
      .replace(/(\.[\d]{4})./g, '$1');    // not more than 4 digits after decimal
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

This works just fine and I'm happy with the JS replace() method of restricting form input (yes I am doing server side validation as well).

I'm mostly interested to know if there is a more concise way to set up the regex(es) so I can reduce and/or eliminate some of the code here.  It seems like I should be able to get the same result with fewer replacements.


texts: How best to keep track of an unknown number of objects?

texts:
I have a manager class that will manage an unknown number of objects.  I'm currently storing the objects in a NSMutableArray object, and when I need to find one, I iterate through the array comparing pointers.

For example, I have an array called managedObjects.  I get a delegate method call:

- (void)someDelegateMethod:sender withResults:results {
    for (NSDictionary *managedObjectDict in managedObjects) {
        if (sender == [managedObjectDict objectForKey:@"DelegatedObject"]) {
            NSLog(@"%@",[managedObjectDict objectForKey:@"Value"]);
            break;
        }
    }
}

Now, Objective-C forin loops are handled in batches and are extremely fast... but if I were managing thousands of objects, this could potentially take a bit of time to find the right one.

How can I improve this efficiency?


texts:
The basic requirement of my code is to accept a file input, parse it, convert it to a java type (A DTO essentially) for use in another component of the system.

I should also note that I am not actually parsing a file from a filesystem, the FileParser will be used by a Message Driven Bean that has the contents of the file as a String already.

I am looking for input and general design/code review, thanks for your time.

I have 4 classes:

FileParser
Message
MessageFactory
MessageFieldTypes

The format of the file is as follows:

FIELDONETYPE/FIELDONEVALUE
FIELDTWOTYPE/FIELDTWOVALUE
FIELDTHREETYPE/FIELDTHREEVALUE
FIELDFOURTYPE/FIELDFOURVALUE
FIELDFIVETYPE/FIELDFIVEVALUE

etc.

There are roughly 20 fields.

My initial thought was to parse the file into a hashmap and then create the object. Here is the code listing for the parser:

final public class FileParser
{
    public static final Message parse(String text) {

    Map<MessageFieldTypes, String> map = new LinkedHashMap<MessageFieldTypes, String>();

    for(String line : text.split(" *\n *")) {
        String[] keyValuePair = line.split(" */ *");
        map.put(MessageFieldTypes.valueOf(keyValuePair[0]),
                keyValuePair.length == 1 ? "" : keyValuePair[1]);
    }

    return MessageFactory.createFromHashMap(map);
    }
}

Here is the code listing for the factory:

public class MessageFactory {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("ddMMMyyyy");

    public static Message createFromHashMap(Map<MessageFieldTypes, String> map) {
        Message message = new Message();

        message.setFieldOne(new FieldOneType(map.get(MessageFieldTypes.FIELDONE),
                            map.get(MessageFieldTypes.FIELDTWO),
                            DATE_TIME_FORMATTER.parseDateTime(map.get(MessageFieldTypes.FIELDTHREE)).toLocalDate()));
        message.setFieldFour(new FieldFourType(map.get(MessageFieldTypes.FIELDFOUR)));
        message.setFieldFive(map.get(MessageFieldTypes.FIELDFIVE)));

        return message;
    }
}

And the Enum:

public enum MessageFieldTypes {
    FIELDONE,
    FIELDTWO,
    FIELDTHREE,
    FIELDFOUR,
    FIELDFIVE
}


texts:
The following query lists all domains from multiple companies in which a value occurs in an XML set. This is filtered to the most recent occurrence within a provided date range.

On large databases the query has performance problems. Is there a more efficient method to retrieve the most recent query results within the provided date range?

SELECT Company.Name,
       Domain.Name,
       Collection.CollectedOn
FROM Collection
INNER JOIN Domain ON Domain.DomainID = Collection.DomainID
INNER JOIN Company ON Domain.CompanyID = Company.CompanyID
WHERE CollectedOn = (SELECT MAX(CollectedOn)
                     FROM Collection
                     INNER JOIN QResult ON QResult.CollectionID = Collection.CollectionID
                     INNER JOIN QVersion ON QVersion.QVersionID = QResult.QVersionID
                     INNER JOIN QLibrary ON QLibrary.QueryID = QVersion.QueryID
                     WHERE Collection.DomainID = Domain.DomainID
                            AND CollectedOn >= :CollectedAfter
                            AND CollectedOn <= :CollectedBefore
                            AND QLibrary.Name LIKE 'Some_Table_Name_That_Only_Occurs_Once_or_Twice'
                            AND QResult.QResults.exist('/DataSet/some_table/name/text()[contains(., ''Error_value_here'')]') = 1)

If having a visual representation of the tables would be helpful I can post requested tables.

Explanation and information:

A company can have multiple domains.
A domain can have multiple collections. For the purpose of this query, collections are essentially a grouping of previously run queries executed on external (other companies) machines.
There are around 100 companies. Each company generally has 1-10 Domains. There are hundreds of collections for each domain.
QLibrary is a small table. The name I'm searching for with the LIKE param only occurs a few times. Some of the tables I'm retrieving have additional characters concatenated to the searched for name. Thus using LIKE instead of strict equality comparison.
The QResult is a large set of XML. I'm not sure how expensive this is to search in an SQL statement. If this could significantly contribute to a performance problem, I can search through this in a different language after the query is returned.  I've tried to restrict this based on QLibrary.Name. Most of the tables searched in this query should be around 5MB.

Tables (Edit)

Company Table:
╔═══════════╦═══════╗
║ CompanyID ║ Name  ║
╠═══════════╬═══════╣
║         1 ║ name1 ║
║         2 ║ name2 ║
╚═══════════╩═══════╝

Domain Table:
╔══════════╦═══════════╦═══════╗
║ DomainID ║ CompanyID ║ Name  ║
╠══════════╬═══════════╬═══════╣
║        3 ║         1 ║ name1 ║
║        4 ║         1 ║ name2 ║
║        6 ║         4 ║ name3 ║
╚══════════╩═══════════╩═══════╝

Collection Table:
╔══════════════╦══════════╦═════════════╗
║ CollectionID ║ DomainID ║ CollectedOn ║
╠══════════════╬══════════╬═════════════╣
║            1 ║        1 ║ 2016-01-03  ║
║            2 ║        1 ║ 2016-05-11  ║
║            3 ║        2 ║ 2015-09-04  ║
╚══════════════╩══════════╩═════════════╝

QResult Table:
╔════════════╦══════════════╦══════════════════╗
║ QVersionID ║ CollectionID ║     QResult      ║
╠════════════╬══════════════╬══════════════════╣
║          1 ║            1 ║ <bunch><of><xml> ║
║          2 ║            1 ║ <other><xml>     ║
╚════════════╩══════════════╩══════════════════╝

QVersion Table:
╔════════════╦═════════╗
║ QVersionID ║ QueryID ║
╠════════════╬═════════╣
║          1 ║       1 ║
║          2 ║       2 ║
║          3 ║       2 ║
╚════════════╩═════════╝

QLibrary Table:
╔═════════╦═════════════╗
║ QueryID ║  QueryName  ║
╠═════════╬═════════════╣
║       1 ║ some_name_1 ║
║       2 ║ some_name_2 ║
╚═════════╩═════════════╝


texts:
I would like to be specific in parameter types or write something like this:

Test test = (Json<Test>)"{\"age\": 46}";

Where:

public class Test
{
    public int Age { get; set; }
}

My helper is:

public struct Json<T>
{
    public static implicit operator string(Json<T> json) => json.JObject.ToString();
    public static explicit operator Json<T>(string json) => new Json<T>(json);

    public static implicit operator T(Json<T> json) => json.JObject.ToObject<T>();
    public static implicit operator Json<T>(T obj) => new Json<T>(JObject.FromObject(obj));

    static readonly JObject Default = JObject.FromObject(new { });

    Json(string json) : this(JObject.Parse(json)) { }
    Json(JObject jObject) : this() => _jObject = jObject ??
        throw new ArgumentNullException(nameof(jObject));

    JObject JObject => _jObject ?? Default;
    readonly JObject _jObject;
}


texts:
Challenge
Write a program which reads a file and outputs a specified number of lines, sorted on length in descending order.
Specifications

The first argument is a path to a file.
The file contains multiple lines.
The first line indicates the number of lines to output.
The following lines are of differing lengths and presented randomly.
Print the specified number of lines in descending order of length.

Constraints

The number in the first line is a valid positive integer.
The input file is correctly formatted.

Input Sample

2
Hello World
Code Reviews
Quick Fox
A
San Francisco

Output Sample

San Francisco
Code Reviews

Source
Solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.NavigableMap;
import java.util.Scanner;
import java.util.TreeMap;

public class Solution {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner input = new Scanner(new File(args[0]));
        int numberOfLinesToPrint = Integer.parseInt(input.nextLine());

        NavigableMap<Integer, String> lineMap = new TreeMap<>();
        while (input.hasNextLine()) {
            addLine(lineMap, input.nextLine());
        }
        printLongestLines(lineMap, numberOfLinesToPrint);
    }

    private static void printLongestLines(NavigableMap<Integer, String> lineMap, int numberOfLinesToPrint) {
        for (int i = 0; i < numberOfLinesToPrint; i++) {
            System.out.println(lineMap.pollLastEntry().getValue());
        }
    }

    private static void addLine(NavigableMap<Integer, String> lineMap, String line) {
        lineMap.put(line.length(), line);
    }
}

I thought about implementing a data structure based on the size of the input that would sort itself right after adding an input -- if the input was a valid addition, but then I remembered TreeMap and thought why reinvent the wheel? This works, but I'm curious if I've misjudged and the alternative would've been more efficient.


texts: Edge cases for simulated malloc function

texts:
I'm trying to simulate the malloc function in C by using mmap and having 2 linked lists to act as memory blocks. The program works by reserving a region of memory and then keeps track of the free and allocated memory address with size in the linked lists. I have tested the program with normal cases like

free memory > needed to be allocate
free memory < needed to be allocate
free memory == needed to be allocate

… but couldn't think of special cases.  Are there cases where the program fails?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>

struct block {
void *addr; /*start address of memory for this block */
int size;
struct block *next;
};

void *mem;
struct block *freelist;
struct block *allocated_list;

void *smalloc(unsigned int nbytes) {
struct block *cur = freelist;

 while(cur!=NULL){

        if (cur ->size >= nbytes){
            struct block *tempBlock;
            tempBlock= malloc(sizeof(struct block));
            tempBlock->addr = cur ->addr;
            tempBlock->size = nbytes;
            tempBlock->next = NULL;

            cur->addr = cur->addr + nbytes;
            cur ->size = cur ->size - nbytes;

                if(allocated_list == NULL){
                    allocated_list = tempBlock;
                }
                else{
                    cur = allocated_list;
                    while(cur->next!=NULL){
                        cur =cur->next;
                    }
                    cur->next=tempBlock;
                }

            return (tempBlock->addr);

        }
        cur = cur->next;

}

return NULL;
}

int sfree(void *addr) {
struct block *cur = allocated_list;
struct block *tempBlock;
while(cur!=NULL){
        if (cur ->next->addr == addr){
            tempBlock=cur->next;        //disjoint the matched block from the allocated_list
            cur->next = cur->next->next;
            tempBlock->next = NULL;     // set the matched block pointing to null

            cur = freelist;
            while(cur->next!=NULL){
                cur =cur->next;
                }
            cur->next=tempBlock;

            return(0);
        }
        cur= cur->next;

}
return -1;
}

void mem_init(int size) {
mem = mmap(NULL, size,  PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
if(mem == MAP_FAILED) {
     perror("mmap");
     exit(1);
}
else {
    freelist = malloc(sizeof(struct block));
    freelist ->size = size;
    freelist ->next = NULL;
    freelist ->addr = mem;

    allocated_list= NULL;

}

/* NOTE: this function is incomplete */

}

void mem_clean(){
struct block *cur = freelist;
struct block *tempBlock;
while(cur!=NULL){
    tempBlock = cur->next;
    munmap(cur->addr,cur->size);
    free(cur);
    cur = tempBlock;
}
cur = allocated_list;
while(cur!=NULL){
    tempBlock = cur->next;
    munmap(cur->addr,cur->size);
    free(cur);
    cur = tempBlock;
}

}


texts: Update only modified fields in Entity Framework

texts:
I'm working on a website on ASP.NET MVC4 and EF5. I want to ensure that only modified values are updated in the database.  I'm using a unit of work pattern and repositories for data work. Here's the code for a generic repository. I've two questions, and need a code review for the following code.

Is the code to update only modified fields good? It works, but I don't know if this is the best way. I especially don't like that I have to do this loop through the properties myself (can't EF do this?). I also don't like the cast to object and the comparison.
How are my Add and Update methods? I'm planning the clients (MVC/API controllers) to use a service (passing in a unit of work) to get the work done. They will not directly use the repository. The repository will not have a Save() method, only the UnitOfWork will have one. I can ensure within the service that I will use the same context to update/add entities. Given this, are there any scenarios where my Add/Update code is going to fail?

public class EFRepository<T> : IRepository<T> where T : class
{
    protected DbContext DbContext { get; set; }
    protected DbSet<T> DbSet { get; set; }

    public EFRepository(DbContext dbContext)
    {
        if (dbContext == null)
            throw new ArgumentNullException("dbContext");
        DbContext = dbContext;
        DbSet = DbContext.Set<T>();
    }

    public virtual void Add(T entity)
    {
        DbContext.Entry(entity).State = EntityState.Added;
    }

    public virtual void Update(T entity)
    {
        //dbEntityEntry.State = EntityState.Modified; --- I cannot do this.

        //Ensure only modified fields are updated.
        var dbEntityEntry = DbContext.Entry(entity);
        foreach (var property in dbEntityEntry.OriginalValues.PropertyNames)
        {
            var original = dbEntityEntry.OriginalValues.GetValue<object>(property);
            var current = dbEntityEntry.CurrentValues.GetValue<object>(property);
            if (original != null && !original.Equals(current))
                dbEntityEntry.Property(property).IsModified = true;
        }
    }

    //... Other methods ...
}


texts: Implementation of binary min-heap data structure

texts:
What do you think is wrong with this code, and how can it be improved?  What corner case have I overlooked, if any?

Note: I do not want to use any STL features here, but I'm okay with anything else from C++11.

class min_heap{
    int pvt,P;
    int arr[10000];
public:

    min_heap(){
        P=1;
    }
    void add(int x){
        pvt=P;
        arr[P]=x;

        while(pvt>1){
            if(arr[pvt]<arr[pvt/2]){
                int temp=arr[pvt];
                arr[pvt]=arr[pvt/2];
                arr[pvt/2]=temp;
                pvt=pvt/2;

            }
            else
                break;
        }
        P++;
    }

    int extract(){
        int ans=arr[1];
        arr[1]=arr[P-1];
        int elm=arr[1];
        int x=1;
        while(x*2+1<=P-1){
            int exc=1;
            int temp=arr[x];

            if(arr[x*2]>arr[x*2+1]&&(elm>arr[x*2]||elm>arr[x*2+1])){
                arr[x]=arr[x*2+1];
                arr[x*2+1]=temp;
                x=x*2+1;
                continue;
            }
            if(arr[x*2]<=arr[x*2+1]&&(elm>arr[x*2]||elm>arr[x*2+1])){
                arr[x]=arr[x*2];
                arr[x*2]=temp;
                x=x*2;
                continue;
            }
            break;

        }
        if(P-1>=x*2&&arr[x*2]<arr[x]){
            int temp=arr[x];
            arr[x]=arr[x*2];
            arr[x*2]=temp;
        }
        P--;
        return ans;
    }
};

int main()
{
    min_heap min1;
    for(int i=1;i<=50;i++)
    {
        int x1;
        std::cin>>x1;
        min1.add(x1);
    }
    std::cout<<std::endl;
    for(int i=1;i<=50;i++){
        int x1=min1.extract();
        std::cout<<x1<<std::endl;
    }

}


texts:
Here is my answer to the question, which I think is quite inefficient considering its length:

$('document').ready(function() {
 function makeEqual(blocks,dash) {
  var n =blocks;
  var widthSize = dash *10;
  var i=0;
  var equal = "";
  var contentName = "";
for(i=0;i<n;i++) {

  if(i==(n-1)) {
   contentName='contentL'+i;
  equal = "
"+produceDashStructure(dash*3)+"
";
  $("#main").append(equal);
  $("#"+contentName).css({marginLeft:i*widthSize , width:widthSize*3});
   for(j=i;j>0;j--) {
     contentName='contentR'+j;
      equal = "
"+produceDashStructure(dash)+"
";
      $("#main").append(equal);
      $("#"+contentName).css({marginLeft:((n-j)+i+2)*widthSize , width:widthSize , bottom: (((n-j)*2))*55 , position: "relative" });
    }
  }
   else {
    contentName='contentL'+i;
      equal = "
"+produceDashStructure(dash)+"
";
      $("#main").append(equal);
  $("#"+contentName).css({marginLeft:i*widthSize , width:widthSize});
    }
  }

  }
  function produceDashStructure(dash) {
      var dashedStructure = "";
    for(var i=0;i<dash;i++) {
         dashedStructure += "- ";
      }
       return dashedStructure+"

"+dashedStructure;
  }

  makeEqual(5,5);
})
#main {
  top: 10px;
  left: 10px;
  width: 30 px;
  position: relative;
}

I have written a lot of code for a small problem which I think is time-inefficient too, and I'm using the same methodology in my projects. Any improvement in this question will help me make all my projects more efficient.


texts:
This code is supposed to search for a specific key in a object or an array or a mix between both. Is there anything I can improve?

function getAllObjectsIn(key, data, casesensitive){

    var returns = [];
    var searchForInner = function (key, data, returnParameter, casesensitive){

        if(typeof(data) === 'object'){
            for (var i in Object.keys(data)){
                if(!(casesensitive)){
                    var searchTerm = Object.keys(data)[i].toLowerCase();
                    var key = key.toLowerCase();
                };
                if(searchTerm === key){
                    returns.push(data[Object.keys(data)[i]]);
                }
                else if (typeof(data[Object.keys(data)[i]]) === 'object'){
                    searchForInner(key,data[Object.keys(data)[i]],returnParameter);
                };
            };
        };
    };

    searchForInner(key,data,returns,casesensitive);
    return(returns);
};


texts: Reading a textfile and calling a class with each text file line

texts:
How could I get a better performance in my C# application? Or what should I change in my source code?

I would appreciate any kind of help.

This code is reading each line of a textfile which stores values like var1:var2 and calls a class with those values.

Function which calls the class:

private void bunifuFlatButton2_Click(object sender, EventArgs e)
{
    using (var streamReader = File.OpenText(filePath))
    {
        var lines = streamReader.ReadToEnd().Split(new char[] { '\n' });
        var count = lines.Count();

        bunifuProgressBar1.MaximumValue = count;

        for (int i = 0; i < count; i++)
        {
            string[] words = lines[i].Split(':');
            string hash = mega.GenerateHash(words[0].ToLowerInvariant(), mega.PrepareKey(words[1].ToBytes()));

            bunifuCustomLabel4.Text = "Working: Total: " + count + ". Currently: " + (i + 1) + ".";
            bunifuCustomLabel4.Update();
            bunifuProgressBar1.Value = i + 1;
        }
    }
}

The class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace MegaTool
{
    public static class mega
    {

        private static readonly Rijndael RijndaelCbc;
        private static readonly byte[] DefaultIv = new byte[16];

        static mega()
        {
            RijndaelCbc = Rijndael.Create();
            RijndaelCbc.Padding = PaddingMode.None;
            RijndaelCbc.Mode = CipherMode.CBC;
        }

        public static byte[] ToBytes(this string data)
        {
            return Encoding.UTF8.GetBytes(data);
        }

        public static byte[] PrepareKey(byte[] data)
        {
            byte[] pkey = new byte[] { 0x93, 0xC4, 0x67, 0xE3, 0x7D, 0xB0, 0xC7, 0xA4, 0xD1, 0xBE, 0x3F, 0x81, 0x01, 0x52, 0xCB, 0x56 };

            for (int it = 0; it < 65536; it++)
            {
                for (int idx = 0; idx < data.Length; idx += 16)
                {
                    byte[] key = data.CopySubArray(16, idx);

                    pkey = EncryptAes(pkey, key);
                }
            }

            return pkey;
        }

        public static byte[] EncryptAes(byte[] data, byte[] key)
        {
            using (ICryptoTransform encryptor = RijndaelCbc.CreateEncryptor(key, DefaultIv))
            {
                return encryptor.TransformFinalBlock(data, 0, data.Length);
            }
        }

        public static T[] CopySubArray<T>(this T[] source, int length, int offset = 0)
        {
            T[] result = new T[length];
            while (--length >= 0)
            {
                if (source.Length > offset + length)
                {
                    result[length] = source[offset + length];
                }
            }

            return result;
        }

        public static string GenerateHash(string email, byte[] passwordAesKey)
        {
            byte[] emailBytes = email.ToBytes();
            byte[] hash = new byte[16];

            for (int i = 0; i < emailBytes.Length; i++)
            {
                hash[i % 16] ^= emailBytes[i];
            }

            for (int it = 0; it < 16384; it++)
            {
                hash = EncryptAes(hash, passwordAesKey);
            }

            byte[] result = new byte[8];
            Array.Copy(hash, 0, result, 0, 4);
            Array.Copy(hash, 8, result, 4, 4);

            return result.ToBase64();
        }

        public static string ToBase64(this byte[] data)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Convert.ToBase64String(data));
            sb.Replace('+', '-');
            sb.Replace('/', '_');
            sb.Replace("=", string.Empty);

            return sb.ToString();
        }
    }
}


texts: Environment-specific code in @Async mail method with Spring

texts:
I have a Spring @Service to asynchronously send emails.  The part that seems to be a bit off to me is some code that is specific to our QA environment.  We want to send and receive all emails through a test email account so that it does not impact live users if we work with real data imported to QA.  I check for the environment and some settings in .properties files and adjust the outgoing email accordingly.

Is there a better way to handle this?

@Async
public void send(String email, String subject, String body) {

    if (email == null) {
        log.error("Not sending; null input: email");
        return;
    }
    try {
        MimeMessage message = this.mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        helper.setFrom(mailSender.getUsername(), getFrom());
        helper.setReplyTo(mailSender.getUsername());
        helper.setSubject(subject);

        //HERE IS THE PART THAT'S IFFY:

        if ("QA".equalsIgnoreCase(EmailManager.getEnvironmentName())) {
            if (isTestMode()) {
                if (!email.equals(getTestEmailAddress())) {
                    helper.setTo(getTestEmailAddress());
                    body += "<br/>This email was originally intended for " + email +
                            " but was redirected to " + getTestEmailAddress() + " for testing.";
                    helper.setText(body, true); //HTML on
                }
            }
        }
        else {
            helper.setTo(email);
            helper.setText(body, true); //HTML on
        }

        if (message == null) {
            log.error("Email message to send is null.  Email={}, Subject={}", email, subject);
            log.error("Body:");
            log.error(body);
            return;
        }
        this.mailSender.send(message);
    }
    catch (MailException | UnsupportedEncodingException | MessagingException e) {
        log.error(e.toString());
        e.printStackTrace();
    }
}

private static String getFrom() {
    Locale defaultLocale = Locale.getDefault();
    ResourceBundle bundle = ResourceBundle.getBundle("messages", defaultLocale);
    return bundle.getString("label.project.name");
}

protected static String getTestEmailAddress() {
    return ResourceBundle.getBundle(AbstractEnvironment.ENVIRONMENT)
            .getString("testEmailAddress");
}

protected static Boolean isTestMode() {
    return Boolean.valueOf(ResourceBundle.getBundle(AbstractEnvironment.ENVIRONMENT)
                                   .getString("redirectAllEmailsToTestEmailAddress"));
}

@Autowired
private JavaMailSenderImpl mailSender;

//setter needed for Junit
public void setMailSender(JavaMailSenderImpl mailSender) {
    this.mailSender = mailSender;
}


texts: Replacing multiple substrings in a string

texts:
Here are 2 functions defined that do the exactly same thing: take input a template (in which one wants to replace some substrings) and array of strings values (key value pair to replace, such as [subStrToReplace1,value1,subStrToReplace1,value2,.....]) and returns the replaced String.

In second function I am iterating over words of the templates and searching for the relevant key if exist in a HashMap and then next word. If I want to replace a word with some substring, which I again want to replace with some other key in values, I need to iterate over template twice.

I would like to know which one should I use and why. Any better alternative than these are also welcome.

1st function

public static String populateTemplate1(String template, String... values) {
        String populatedTemplate = template;
        for (int i = 0; i < values.length; i += 2) {
            populatedTemplate = populatedTemplate.replace(values[i], values[i + 1]);
        }

        return populatedTemplate;
    }

2nd function

   public static String populateTemplate2(String template, String... values) {

        HashMap<String, String> map = new HashMap<>();
        for (int i = 0; i < values.length; i += 2) {
            map.put(values[i],values[i+1]);
        }

        StringBuilder regex = new StringBuilder();
        boolean first = true;
        for (String word : map.keySet()) {
            if (first) {
                first = false;
            } else {
                regex.append('|');
            }
            regex.append(Pattern.quote(word));
        }
        Pattern pattern = Pattern.compile(regex.toString());

        int N0OfIterationOverTemplate =2;
        // Pattern allowing to extract only the words
        // Pattern pattern = Pattern.compile("\\w+");
        StringBuilder populatedTemplate=new StringBuilder();;

        String temp_template=template;

        while(N0OfIterationOverTemplate!=0){
        populatedTemplate = new StringBuilder();
        Matcher matcher = pattern.matcher(temp_template);
        int fromIndex = 0;
        while (matcher.find(fromIndex)) {
            // The start index of the current word
            int startIdx = matcher.start();
            if (fromIndex < startIdx) {
                // Add what we have between two words
                populatedTemplate.append(temp_template, fromIndex, startIdx);
            }
            // The current word
            String word = matcher.group();
            // Replace the word by itself or what we have in the map
            // populatedTemplate.append(map.getOrDefault(word, word));

            if (map.get(word) == null) {
                populatedTemplate.append(word);
            }
            else {
                populatedTemplate.append(map.get(word));
            }

            // Start the next find from the end index of the current word
            fromIndex = matcher.end();
        }
        if (fromIndex < temp_template.length()) {
            // Add the remaining sub String
            populatedTemplate.append(temp_template, fromIndex, temp_template.length());
        }

        N0OfIterationOverTemplate--;
        temp_template=populatedTemplate.toString();
    }
        return populatedTemplate.toString();
}


texts: Simulate the way that PHP receives the form

texts:
Let's say I have this form:

<form action="/user/store" method="POST" enctype="multipart/form-data">
    Name: <input type="text" name="name">

    Male: <input type="radio" name="gender" value="male">

    Female: <input type="radio" name="gender" value="female">

    Photo: <input type="file" name="photo">

    Hobbies: <select name="hobbies[]" multiple>
        <option value="sport">Sport</option>
        <option value="movies">Movies</option>
        <option value="music">Music</option>
        <option value="games">Games</option>
    </select>

    Accept the terms?<input type="checkbox" name="terms">

    <input type="submit">
</form>

If I submit it to a PHP server with my data, this is the result:

array (size=5)
  'name' => string 'John' (length=4)
  'gender' => string 'male' (length=4)
  'hobbies' =>
    array (size=2)
      0 => string 'sport' (length=5)
      1 => string 'music' (length=5)
  'terms' => string 'on' (length=2)
  'photo' =>
    object(Symfony\Component\HttpFoundation\File\UploadedFile)[9]
      private 'test' => boolean false
      private 'originalName' => string 'test.jpg' (length=8)
      private 'mimeType' => string 'image/jpeg' (length=10)
      private 'size' => int 130677
      private 'error' => int 0

I want to have similar results with JavaScript, so I wrote this function:

//Add event listener for the form submit to the document
$(document).on('submit', 'form', function(e){
    //Prevent form submitting
    e.preventDefault();
    var form = $(':input').not(':submit,:button,:image,:radio,:checkbox');
    $.merge(form, $(':checked').not('option'));
    var data = [], input, name;

    form.each(function(i, obj){
        input = {};
        name = obj.name;
        if(name.indexOf('[]') < 0) {
            input['name'] = name;
            if(obj.type==='file'){
                var files = obj.files;
                input['value'] = files[files.length - 1];
            } else {
                input['value'] = obj.value;
            }
        } else {
            name = name.replace('[]', '');
            if(name in data){
                var tmp = input['value'];
                if(obj.type==='file'){
                    input['value'] = $.merge(tmp, obj.files);
                } else if(obj.type === 'select-multiple') {
                    input['value'] = $.merge(tmp, $.map(obj.selectedOptions, function(option, i){
                        return option.value;
                    }));
                } else {
                    input['value'] = $.merge(tmp, obj.value);
                }
            } else {
                data[name] = {};
                if(obj.type === 'file'){
                    input['value'] = obj.files;
                } else if(obj.type === 'select-multiple') {
                    input['value'] = $.map(obj.selectedOptions, function(option, i){
                        return option.value;
                    });
                } else {
                    input['value'] = [];
                    input['value'].push(obj.value);
                }
            }
        }
        data.push(input);
     });
});

And this return (JSON format):

[
    {"name":"firstname","value":"John"},
    {"name":"photo","value":
        {
            "webkitRelativePath":"",
            "lastModifiedDate":"2014-09-08T18:29:36.000Z",
            "name":"test.jpg",
            "type":"image/jpeg","size":130677
        }
    },
    {"name":"hobbies","value":["sport","music"]},
    {"name":"gender","value":"male"},
    {"name":"terms","value":"on"}
]

Is there any better way to do that? By better code, I mean less code. I don't mind if it will become slower.


texts: C random walk the alphabet on a small grid

texts:
I'm teaching myself C, with an older edition of K. N. King's C Programming: A Modern Approach. I come from a Python and JavaScript background as far as programming goes, but not a strong foundation in theoretical CS concepts. I'm currently up to Chapter 8 of the book, which introduces one- and multi-dimensional arrays in C. The final exercise of the chapter is to write a program that takes a 10x10 grid and prints the letters of the alphabet in sequence, but picking one of the open adjacent squares to the last-placed character in order to place the next character in sequence. The result resembles a "random walk" through the grid. The program must terminate early if it reaches a point with no open spaces to continue the sequence. My attempt is below. I'm looking for general feedback. I know that there are almost certainly better data structures I could be using, but bear in mind that I haven't even started reading the chapter on functions: so I've only been exposed to elementary types, arrays, some operators, conditional expressions, etc. Bear those constraints in mind if you can.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define N 10
#define TRUE 1
#define FALSE 0
#define START 'A'
#define END 'Z'

typedef int Bool;

int main() {
  char grid[N][N] = {};
  int i = 0;
  int j = 0;
  int next_j = 0;
  int next_i = 0;
  int move, open_spaces;
  Bool placed = FALSE;
  Bool examined_spaces[4] = {};
  // Initialise a random number generator using current time,
  // to ensure it's different each loop
  srand((unsigned) time(NULL));
  // Loop alphabet
  for (char c = START; c <= END; c++) {
    open_spaces = 4;
    memset(examined_spaces, 0, sizeof(Bool)*4); // Empty examined spaces array

    grid[i][j] = c;
    // Determine the next position
    if (c == END) {
      // end of iteration
      placed = TRUE;
    } else {
      // Need to determine the position of the next character
      placed = FALSE;
    }
    // Placed, calculating position of next character
    while ((!placed) && (open_spaces > 0)) {
      next_i = i;
      next_j = j;
      move = rand() % 4;
      if (examined_spaces[move] == TRUE) {
        // Already examined this move
        continue;
      }
      if (examined_spaces[move] == FALSE) {
        // A new move
        open_spaces--;
        examined_spaces[move] = TRUE;
      }
      switch (move) {
        case 0: next_j--; break; // up
        case 1: next_i++; break; // right
        case 2: next_j++; break; // down
        case 3: next_i--; break; // left
      }
      if (next_j + 1 > N || next_j < 0 || next_i + 1 > N || next_i < 0) {
        // Out of bounds
        continue;
      } else if (grid[next_i][next_j] != 0) {
        // Already occupied by a character
        continue;
      } else {
        // Successful placement
        placed = TRUE;
        i = next_i;
        j = next_j;
      }
    }
    if (open_spaces <= 0 && !placed) {
      // No more empty spaces
      break;
    }
  }
  for (i = 0; i < N; i++) {
    for (j = 0; j < N; j++) {
      if (grid[i][j] == 0) {
        printf(". ");
      } else {
        printf("%c ", grid[i][j]);
      }
      if (!((j + 1) % 10)) {
        printf("\n");
      }
    }
  }
  return 0;
}


texts: Access to a pimpl's members from another pimpl

texts:
I am writing an audio engine that must be multi-platform (win/linux). Basically, a CSound represents a sound file, and CSoundInstance represents one playing of a CSound. Obviously, playing sound is very different on Windows than it is on linux.

A CSoundInstance needs access to some data from its corresponding CSound. The data is heavily implementation-dependent and cannot really be abstracted.

Here are the API headers for the two classes. I omitted operator= overloads / unique_ptr use etc.

API/Sound.hpp

class CSound
{
public:
    CSound(...file...);
    ~CSound();
private:
    CSoundImpl *impl;
};

API/SoundInstance.hpp

class CSoundInstance
{
public:
    CSoundInstance(CSound *); // going to need access to source voice buffer
    ~CSoundInstance();
    Play();
private:
    CSoundInstanceImpl *impl;
};

I guess it is clear where this is going. You would first instanciate a CSound, then acquire a CSoundInstance and Play it.

I Intend to have a specific XXImpl class for each system and platform. Under Windows, I use XAudio2, which needs several members in CSoundImpl (buffer + waveform descriptor), as well as CSoundInstanceImpl (voice + fx + sends + callbacks).

Here are the problems that I had using the pimpl idiom:

To play a sound, a CSoundInstanceImpl ultimately needs a reference to a CSoundImpl, on Windows and linux, but I cannot write this constructor:

CSoundInstance::CSoundInstance(CSound *sound)
    : impl(sound->impl)
{
    ...
}

Not only is sound->impl private, but it would also mess up unique_ptr use.

Another thing I tried is not using the constructor CSoundInstance(CSound *) at all, and adding a factory method with the signature CSoundInstance CSound::CreateInstance(), like this:

CSoundInstance CSound::CreateInstance()
{
    return this->impl->CreateInstance();
}

CSoundInstance CSoundImpl::CreateInstance()
{
    // here I have access to the CSoundImpl instance, that I need: this
    CSoundInstance instance(this);
}

But that would imply that I have this constructor:

CSoundInstance::CSoundInstance(CSoundImpl *soundImpl)
    : impl(new CSoundInstanceImpl(soundImpl))
{
    ...
}

Using a pointer to an implementation in the constructor of a non-implementation API class doesn't look right to me.

Maybe pimpl is not the right thing for this? Is there a way how I could tackle this problem better?


texts: Slick Slider – change contents based on current slide data-index

texts:
I wrote the following code for Slick Slider, which changes the content below based on the current slide data-index. I just wonder if there is a more efficient way to do it?

http://codepen.io/pjmtokyo/pen/JYyjew

$('.slider').on('afterChange', function(event, slick, currentSlide, nextSlide){
    var elSlide = $(slick.$slides[currentSlide]);
    var dataIndex = elSlide.data('index');

  $('.content').each(function(){
    if ($(this).data('id') == dataIndex) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });

});


texts: Program for converting a boring text into a stylish written text

texts:
I have written a program that makes it possible to write as cool as the cool kids. All you have to do is enter the boring, normal text, which is then transformed into an exciting, stylish text.
Is there a possibilty to make the code more performant without decreasing it's readability?

Example Output:

I H@Ve wRITTen @ Pr0qR@M tH@T m@KEZ IT P0ZzIblE t0 wriTE @z C00L @z the c00L KIdZ :) All Y0U h@Ve T0 D0 iZ eNter thE B0rinQ, n0rm@L teXt, whIch iZ tHeN TR@nZF0RmED int0 @n exCiTInq, ztyLIZh TExT. :D

Source code

import java.util.Random;
import java.util.Scanner;

public class Program {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Input: ");
        String text = input.nextLine();
        String trendyText = convertToTrendyText(text);
        System.out.println(trendyText);
    }

    public static String convertToTrendyText(String string) {
        string = string.replace("g", "q");
        string = string.replace("s", "z");
        string = string.replace("a", "@");
        string = string.replace("o", "0");
        string = string.replace(". ", " " + generateRandomSmiley() + " ");
        string = string.replace("! ", " " + generateRandomSmiley() + " ");
        string = string.replace("? ", " " + generateRandomSmiley() + " ");
        string = string.concat(" " + generateRandomSmiley());

        StringBuilder text = new StringBuilder(string);
        Random random = new Random();
        for (int i = 0; i < text.length(); i++) {
            if (random.nextBoolean()) {
                text.setCharAt(i, Character.toUpperCase(text.charAt(i)));
            }
        }

        return text.toString();
    }

    public static String generateRandomSmiley() {
        Random random = new Random();

        switch (random.nextInt(10)) {
            case 0: return ":)";
            case 1: return ":D";
            case 2: return ":*";
            case 3: return "<3";
            case 4: return "o.O";
            case 5: return "x3";
            case 7: return "xD";
            case 8: return ":o";
            default: return ";D";
        }
    }
}


texts:
#include "fmt/format.h"
#include <cstdint>
#include <cstdio>
#include <event2/event-config.h>
#include <event2/util.h>
#include <evhttp.h>
#include <memory>
#include <type_traits>
auto
main() -> int
{
    constexpr char host[] = "127.0.0.1";
    std::uint16_t port = 5555;

    using event_base_new_type
        = std::pointer_traits<decltype(event_base_new())>::element_type;
    using event_base_deleter_type = decltype(&event_base_free);
    auto event_base
        = std::unique_ptr<event_base_new_type, event_base_deleter_type>(
            event_base_new(), &event_base_free);

    if(!(event_base))
    {
        fmt::print(stderr, "Failed to init libevent.\n");
        return -1;
    }

    using evhttp_new_type
        = std::pointer_traits<decltype(evhttp_new(event_base.get()))>::element_type;
    using evhttp_deleter_type = decltype(&evhttp_free);
    auto http = std::unique_ptr<evhttp_new_type, evhttp_deleter_type>(evhttp_new(event_base.get()), &evhttp_free);

    auto handle = evhttp_bind_socket_with_handle(http.get(), host, port);
    if(!handle)
    {
        fmt::print(stderr, "Failed to init http server.\n");
        return -1;
    }
    auto callback = [](evhttp_request* req, void*) {
        auto* OutBuf = evhttp_request_get_output_buffer(req);
        if(!OutBuf)
            return;
        evbuffer_add_printf(OutBuf,
            "
Hello World!
");
        evhttp_send_reply(req, HTTP_OK, "", OutBuf);
    };
    evhttp_set_gencb(http.get(), callback, nullptr);
    if(event_base_dispatch(event_base.get()) == -1)
    {
        fmt::print(stderr, "Failed to run messahe loop.\n");
        return -1;
    }

    return 0;
}

Compile

g++ a.cpp -lfmt -levent

Run

$ ./a.out
$ ab -c 1000 -k -r -t 10 http://127.0.0.1:5555/

Open http://127.0.0.1:5555/ in browser

What I want to know:

Is my unique_ptr necessary? valgrind reports no memory leak even though I don't use unique_ptr nor free manually.
more elegant/correct code.


texts:
In C++ (and C++11), classes defining a + and += operators often define a - and -= operators that do nearly the same thing (except + is replaced with - in the function).

What is the best way to avoid duplicated code here (and still achieve good performance)? I am sure there is a good way to do it with functors:

Here's what I've tried:

#include <iostream>
#include <functional>

struct num {
  int val;

  const num & operator +=(const num & rhs) {
    return op_equals<std::plus<int> >(rhs);
  }
  const num & operator -=(const num & rhs) {
    return op_equals<std::minus<int> >(rhs);
  }

  template <typename op>
  const num & op_equals(const num & rhs) {
    op operation;
    val = operation(val, rhs.val);
    return *this;
  }
};

int main() {
  num x{1};
  num y{2};
  x += y;

  std::cout << x.val << std::endl;
  return 0;
}

Note that this is a simple example; in reality the code in the += and -= operators is more complex.

Also, I am not married to functors in the solution-- any suggestions or advice?


texts:
I have to write a little social network for a case study at university. I have done some simple webapps before but nothing that required authentication, login and so on. So I wrote this little application after reading several guides on how this is usually implemented.

What I came up with is a simple login.html file in my server's public directory that contains a form with username and password. After submitting, the server looks up the username in a HashMap and checks firstly if the user exists and secondly if the password is correct. If both criteria are met, I set a cookie via response that contains a random UUID that the server keeps track of in an ArrayList. Lastly, the before filter checks if any protected page is being accessed, and if so, checks the requests cookies and looks them up in the ArrayList. If the cookie is known to the server I grant access to whatever is under /protected/.

Apart from encryption, is this code doing what I want? For me it looks like it works: login sets the cookie, logout removes it, /protected/ path can't be accessed without a known cookie. But I don't exactly know if I am missing something critical that might allow people to access pages without my knowledge.

package co.selim;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import spark.Spark;

public class Router {
    public static void main(String[] args) {
        Map<String, String> credentials = new HashMap<>();
        credentials.put("root", "passw0rd");

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

        Spark.staticFileLocation("public");

        Spark.exception(Exception.class, (exception, request, response) -> {
            exception.printStackTrace();
        });

        Spark.before("/protected/*", (req, res) -> {
            if (!tokens.contains(req.cookie("token")))
                Spark.halt(401, "You can't access this page.");
        });

        Spark.post("/login", (req, res) -> {
            String username = req.queryParams("user");
            String password = req.queryParams("password");

            String storedPassword = credentials.get(username);
            if (storedPassword != null && password.equals(storedPassword)) {
                String token = UUID.randomUUID().toString();
                tokens.add(token);
                res.cookie("token", token, 3600);
            } else
                return "Username or password wrong.";
            return "";
        });

        Spark.get("/logout", (req, res) -> {
            String token = req.cookie("token");
            if (tokens.remove(token)) {
                res.removeCookie("token");
                return "Successfully logged out.";
            } else
                return "You were not logged in.";
        });

        Spark.get("/protected/controlPanel", (req, res) -> {
            return "<button>Launch nukes</button>";
        });
    }
}


texts: Find the shortest path between two points in a 2D matrix with obstacles

texts:
I need to find shortest path between two points in a grid given an obstacles..

  Given a 2 dimensional matrix where some of the elements are filled
  with 1 and rest of the elements are filled. Here X means you cannot
  traverse to that particular points. From a cell you can either
  traverse to left, right, up or down. Given two points in the matrix
  find the shortest path  between these points. Here S is the starting
  point and E is the Ending point.

I came up with below code which BFS but I wanted to understand from the interview point of view what is the most efficient algorithm to solve this problem? Is there any better way to do this? Can we optimize below code?

  public static void main(String[] args) {
    char[][] matrix =  {{'1','1','1', '1'},
                        {'1','S','1', '1'},
                        {'1','1','X', '1'},
                        {'1','1','1', 'E'}};

    System.out.println(shortestPath(matrix));
  }

  public static int shortestPath(char[][] matrix) {
    int s_row = 0, s_col = 0;
    boolean flag = false;
    for (s_row = 0; s_row < matrix.length; s_row++) {
      for (s_col = 0; s_col < matrix[0].length; s_col++) {
        if (matrix[s_row][s_col] == 'S')
          flag = true;
        if (flag)
          break;
      }
      if (flag)
        break;
    }
    return shortestPath(matrix, s_row, s_col);
  }

  public static int shortestPath(char[][] matrix, int s_row, int s_col) {
    int count = 0;
    Queue<int[]> nextToVisit = new LinkedList<>();
    nextToVisit.offer(new int[] {s_row, s_col});
    Set<int[]> visited = new HashSet<>();
    Queue<int[]> temp = new LinkedList<>();

    while (!nextToVisit.isEmpty()) {
      int[] position = nextToVisit.poll();
      int row = position[0];
      int col = position[1];

      if (matrix[row][col] == 'E')
        return count;
      if (row > 0 && !visited.contains(new int[] {row - 1, col}) && matrix[row - 1][col] != 'X')
        temp.offer(new int[] {row - 1, col});
      if (row < matrix.length - 1 && !visited.contains(new int[] {row + 1, col})
          && matrix[row + 1][col] != 'X')
        temp.offer(new int[] {row + 1, col});
      if (col > 0 && !visited.contains(new int[] {row, col - 1}) && matrix[row][col - 1] != 'X')
        temp.offer(new int[] {row, col - 1});
      if (col < matrix[0].length - 1 && !visited.contains(new int[] {row, col + 1})
          && matrix[row][col + 1] != 'X')
        temp.offer(new int[] {row, col + 1});

      if (nextToVisit.isEmpty() && !temp.isEmpty()) {
        nextToVisit = temp;
        temp = new LinkedList<>();
        count++;
      }

    }

    return count;
  }


texts:
I'm writing a small guessing game. I'm writing a points calculation algorithm.

I wrote the following, and it works. But I feel like I'm bringing over procedural background into Ruby, or not leveraging Ruby properly.

How would an experienced Ruby programmer approach the problem? You can test the code on TryRuby.com (copy and paste code in the browser interpreter).

# g = guesses
g = [{ id: 1, elmer: 5, roger: 7, outcome: "Roger Win" },{ id: 2, elmer: 5, roger: 1, outcome: "Elmer Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# r = actual results
r = [{ id: 1, elmer: 3, roger: 9, outcome: "Roger Win" },{ id: 2, elmer: 7, roger: 9, outcome: "Roger Win" },{ id: 3, elmer: 4, roger: 8, outcome: "Roger Win" }]
# points table
p = []
# rules: correct outcome = 1 point, perfect match = 5 points.

# Loop over results.
r.each do |result|

  # Loop over guesses.
  g.each do |guess|

    # Make sure we compare corresponding ids.
    # So, compare result 1 to guess 1, r2 to g2, etc....
    if result[:id] == guess[:id]

      # Init a hash to store score
      score = {}

      # Did they guess the correct outcome?
      if result[:outcome] == guess[:outcome]

        # Correct outcome guessed! Make a score hash, give'em a point.
        score[:id]     = result[:id]  # game id
        score[:points] = 1            # point

        # Was it a perfect match?
        if result[:elmer] == guess[:elmer] && result[:roger] == guess[:roger]

          # Perfect match! Give them 4 points.
          # They already got 1 point for guessing the correct outcome.
          score[:points] += 4
        end
      end

      # Add the score to the points table
      p.push(score) unless score.empty?
    end
  end
end


texts:
I am developing a chat system including chat bots and human chat users.
Every user must be stored in one large list.

Possible implementation using multiple type constructors:

data User = Human { humanName :: String, humanAge :: Int }
          | Bot { botName :: String, botAge :: Int }
            deriving (Show, Eq)

users :: [User]
users = [Human "Peter" 31, Bot "Your nice chat bot" 12]

To implement the nextMessage function taking the last message and returning
a response, I could do this with pattern matching:

type Message = String

nextMessage :: User -> Message -> IO Message
nextMessage (Human _ _) msg = putStr ("New Message: " ++ msg ++ " \n> ") >> getLine
nextMessage (Bot _ _) msg = return $ unwords [msg, "is", "an", "interesting", "question!"]

But this implementation leads to the problem, that pattern matching wont work anymore if I decide to add any fields to the Human or Bot constructors later, so I would have to adjust this every time I change the constructors.

That's why I decided to use the option described here to implement a heterogenous list using type classes.

This is my approach:

{-# LANGUAGE ExistentialQuantification #-}

type Message = String

-- | User wrapper
data SomeUser = forall u. (User u, Show u) => SU u

-- | User type class
class User a where
    -- just getter functions
    getName :: a -> String
    getAge :: a -> Int

    -- function to get the next message, responding to the previous one
    nextMessage :: a -> Message -> IO Message

-- access packed type to implement functions
instance User SomeUser where
    getName (SU u) = getName u
    getAge (SU u) = getAge u
    nextMessage (SU u) = nextMessage u

-- make the wrapper type showable
instance Show SomeUser where
    show (SU u) = show u

-- human chat user
-- gets new messages from user input
data Human = Human { humanName :: String, humanAge :: Int }
             deriving (Show, Eq)

-- automated chat bot
-- calculates new messages
data Bot = Bot { botName :: String, botAge :: Int }
           deriving (Show, Eq)

instance User Human where
    -- implementing the getter functions (annoying)
    getName = humanName
    getAge = humanAge

    -- only function to be implemented differently for different types
    nextMessage human msg = putStr ("New Message: " ++ msg ++ " \n> ") >> getLine

instance User Bot where
    -- implementing the getter functions (annoying)
    getName = botName
    getAge = botAge

    -- only function to be implemented differently for different types
    -- does not need any IO, but has to use it, because of the type declaration
    -- in the type class definition
    nextMessage bot msg = return $ unwords [msg, "is", "an", "interesting", "question!"]

-- list containing every chat user
users :: [SomeUser]
users = [SU (Human "Peter" 31), SU (Bot "Your nice chat bot" 3)]

I like this because it seems to be more generic than the first version, but for every field I need to add a getter, or if needed even a setter, function to the interface to access the values in the same way no matter whether the object is a Human or a Bot.

The second issue, related to both implementations, is the type of the nextMessage function. Because the Human type needs the IO monad to get
its answer, every User-like type has to do the calculation inside the IO monad which implies the calculations to be impure although those of the Bot type are perfectly fine, pure code.

Main questions:

How to get rid of the annoying getter / (setter) functions in the second implementation?
How to handle the need of the IO monad for some types?

See the module at work:

ghci> getName (head users)
"Peter"
ghci> getName (last users)
"Your nice chat bot"
ghci> nextMessage (head users) "Hey, how are you?"
New Message: Hey, how are you?
> I'm fine!
"I'm fine!"
ghci> nextMessage (last users) "Hey, how are you?"
"Hey, how are you? is an interesting question!"


texts:
This program is working correctly, but I need to check if the structure is good or can be improved. Plus, if I called ra.area() immediately after declaring ra, I get 687194768. Why is that?

#include "stdafx.h"
#include "iostream"
using namespace std;
class rectangleclass
{
 int w,h;
public:
void setnum(int x, int y)
{
w=x;
h=y;
}
int area()
{
    return w*h;
}
};
int main()
{
rectangleclass ra;
int l;
int L;
cout<<"please write the height and width in m\n" ;
cin>>L;
cin>>l;
ra.setnum(L,l);
cout<<ra.area()<<"m^2";
 system("pause");
 }


texts: For loop that iterates through files and iteratively appends lists storing values from the read file

texts:
How can I fasten this code, that reads a text file sequentially and appends a list? fp and fp_2 reads two different files from the same sub-sirectory here

import os
import glob
from IPython import embed
import numpy as np

dirs = os.listdir("/home/Set/")

poseList = [] #Store poses for all files
featuresList = [] # Store features

def data():
    for dir_name in dirs:
        fp = '/home/Set/left'
        fp_2 =  '/home/Set/fc/fc2_0.npy'
        if os.path.exists(fp) and os.path.exists(fp_2):
            files = glob.glob(fp+"/*.txt")
            curr_pose = []  #Store curr pose
            for f in files:
                with open(f) as pose:
                    pl = pose.readlines()
                    pl = [p.strip() for p in pl]
                    pl = map(float, pl)  # str ->float
                    curr_pose.append((pl))
            poseList.append(curr_pose)   #append to main list
            featuresList.append(np.load(fp_2))
        print "Not available", dir_name

data()
embed()


texts: Functional translation of dice simulation

texts:
I have tried my hands at "functionalising" a toy problem I had: find the expected number of throws of a six sided die until all sides have been seen (the answer is 14.7)

My starting point is my imperative solution

import scala.collection.mutable.SortedSet
import scala.util.Random

def dice(nsim:Int) : Double = {
    val nsides = 6
    val r = Random
    val throws = SortedSet[Int]()
    var nthrows = 0
    var res = 0.0

    for (i <- 1 to nsim) {
        throws.clear
        nthrows = 0
        while ( throws.size != nsides) {
            nthrows += 1
            throws += r.nextInt(nsides) + 1
        }
        res += nthrows
    }
    res / nsim
}

dice(10000) // ~14.7

I initialise an empty set, and keep adding my thrown dice until i have seen all sides (the set length equals six), while keeping track of how many die I have thrown. The expected number is just the sum of all these throws divided by the number of simulations (repetitions) I perform: approx 14.7

And here is my functional attempt (almost half a day went into this, including plenty of googling, outofmemory errors etc) - and I am not sure if this is considered good.

def throwdie(nsides:Int) : Int = {
    val r = Random
    r.nextInt(nsides) + 1
}

def nthrows(seen:SortedSet[Int], count:Int, nsides:Int) : Int = {
    if (seen.size == nsides)
        return count
    return nthrows(seen + throwdie(nsides), count + 1, nsides)
}

def fdice(nsim:Int, nsides:Int) : Double = {
    val runs = Iterator.fill(nsim)(SortedSet[Int]())
    runs.map( x=> nthrows(x, 0, nsides) ).reduceLeft(_+_) * 1.0 / nsim
}

fdice(10000, 6) // ~14.7

explanation

So I start with a function throwdie that just returns the outcome of rolling a single die.

Next I have tried to rewrite the while loop using recursion. I came up with nthrows which takes an empty set, a zero count, and the number of die sides, and returns the number of throws until all sides have been seen for one "simulation". I use a mutable data structure here, which as I understand is a nono in functional programming, but it is all I came up with.

Next I run the simulation in fdice where I fill an Iterator with nsim instances of the empty SortedSet, and apply nthrows to all of these and sum the result.


texts:
I have 2 classes that do extremely similar things. The only differences are that they draw using different colors, and that one draws in the back.

The classes NeuronOutput and NeuronReciever are very similar.

class NeuronOutput():
    """The place where a Neuron outputs its signal"""
    def __init__(self,neuron):
        self.neuron=neuron

        width=self.neuron.width*0.5
        offset=width/2
        distance=self.neuron.width*0.4
        self.pos=[self.neuron.x+math.sin(self.neuron.angle)*distance,self.neuron.y-math.cos(self.neuron.angle)*distance]
        self.drawRect=[self.pos[0]-offset,self.pos[1]-offset,width,width]
    def draw(self,surf):
        pygame.draw.ellipse(surf,[200,150,200],self.drawRect)
class NeuronReciever():
    """Where a Neuron recieves input"""
    def __init__(self,neuron):
        self.neuron=neuron

        width=self.neuron.width*0.5
        offset=width/2
        distance=self.neuron.width*0.4
        self.pos=[self.neuron.x-math.sin(self.neuron.angle)*distance,self.neuron.y+math.cos(self.neuron.angle)*distance]
        self.drawRect=[self.pos[0]-offset,self.pos[1]-offset,width,width]
    def draw(self,surf):
        pygame.draw.ellipse(surf,[200,255,200],self.drawRect)

There is also a class Neuron that uses instances of the two above classes as properties. It is also fairly similar to them, however it is a bit different in the way it initializes and draws.

class Neuron():
    """A single neuron with Synapses that connect to others"""
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.pos=[x,y]
        self.width=30
        self.drawOffset=self.width/2;
        self.connections=[]
        self.angle=math.radians(random.randint(0,360))
        self.drawRect=[self.x-self.drawOffset,self.y-self.drawOffset,self.width,self.width]
        self.output=NeuronOutput(self)
        self.input=NeuronReciever(self)

    def draw(self,surf):

        pygame.draw.ellipse(surf,[200,150,50],self.drawRect)
        self.output.draw(surf)
        self.input.draw(surf)
        self.syn.draw(surf)

(The code is the beginning of a neuron simulation.)

I want to keep all these as separate classes for the sake of readability and ease of use. How can I reduce the repetitiveness of this code, while still keeping it readable?


texts:
I wrote a code where customer can buy an item according to customer balance, price and quantity of item to be bought. Here is the code:

#include "bits/stdc++.h"
using namespace std;

class Item{
private:
string itemName;
string itemidNo;
int itemQuantity;
double itemPrice;
public:
Item(){
    itemPrice = 500;
    itemQuantity = 1;
}
//getters and setters
void setName(string name){itemName = name;}
void setId(string id){itemidNo = id;}
void setQuantity(int quantity){itemQuantity = quantity;}
void setPrice(double price){itemPrice = price;}

string getName(){return itemName;}
string getId(){return itemidNo;}
int getQuantity(){return itemQuantity;}
double getPrice(){return itemPrice;}

};

class customer {
private:
string Custname;
string CustidNo;
double Custbalance;
Item Custitem;
public:
customer(){
    Custbalance = 5000;
}
//getters and setters
void setName(string name){Custname = name;}
void setidNo(string id){CustidNo = id;}
void setbalance(double balance){Custbalance = balance;}

string getName(){return Custname;}
string getidNo(){return CustidNo;}
double getbalance(){return Custbalance;}

void print(){
    cout << Custitem.getName() << " " << Custitem.getId() << " " << Custitem.getQuantity() << " " << Custitem.getPrice() << "\n";
    Custbalance -= Custitem.getQuantity()*Custitem.getPrice();
    cout << Custbalance << "\n";
}

void buyItem(Item item){
    if(Custbalance < (item.getQuantity()*item.getPrice())){
        cout << "Insufficient Balance for " << item.getName() << "\n";
        return ;
    }
    if(item.getQuantity() < 1){
        cout << "order not valid";
        return;
    }
    Custitem = item;
    print();
}
};

int main(int argc, char const *argv[])
{
customer harsh;
harsh.setName("harsh");
harsh.setidNo("23");

Item item1;
item1.setName("mobile");
item1.setId("44");

harsh.buyItem(item1);

Item item2;
item2.setName("speakers");
item2.setId("F&D");
item2.setQuantity(2);
item2.setPrice(3000);

harsh.buyItem(item2);

return 0;
}

I am a bit confused as I think there is too much redundancy in my code, such as the getters and setters.  How can I make my code more object-oriented?


texts: Create pairs of items with similarity constraints

texts:
I want to create N unordered pairs of items (no repeat pairs, no pairs with repeated items), where each item is only used twice. For example, given the minimal amount of integers greater than 0, one possible set of 4 items would be:

[(0, 1), (0, 2), (3, 1), (3, 2)]

Another valid example would be:

[(0, 1), (1, 2), (2, 3), (3, 0)]

This would be invalid due to repeated pair:

[(0, 1), (0, 1), (2, 3), (3, 1)]

This would be invalid due to the item 0 being used three times:

[(0, 1), (0, 2), (0, 3), (3, 2)]

Also, to be clear the pair (0, 0) is invalid because it is a pair with a repeated item.

My current code for accomplishing this is clumsy and only works multiples of 4. For now, let's assume the code only needs to work for multiples of 4. How could I do this with a better iterator?

num_set = range(4)
res = []
for n1, n2, n3, n4 in zip(num_set[::4], num_set[3::4], num_set[1::4], num_set[2::4]):
    res.append((n1, n3))
    res.append((n1, n4))
    res.append((n2, n3))
    res.append((n2, n4))

print(res)

I feel like I should be able to use itertools.combinations(range(4), 2) and some filtering to accomplish this, but I'm not sure how.