texts: Excel sheet code is taking too much time

texts:
I have an Excel sheet with lot of rows with data. I am separating it into 2 sheets with some condition satisfies.

This is taking too much time.  How can I improve the speed?  Please suggest any changes to my code.

Dim bmver As Object(,) = New Object(i20, 36) {}
Dim bmhor As Object(,) = New Object(i20, 36) {}

Dim ik As Integer = 0
Dim ij As Integer = 0
With oWs

    For i As Integer = 2 To i20 - 1
        If (.range("E" & i).value = .range("L" & i).value) Then

            For j As Integer = 0 To 36
                bmhor(ij, j) = .cells(i, j + 1).value
            Next
            ij = ij + 1
        End If

    Next

    For k As Integer = 2 To i20 - 1
        If (.range("C" & k).value = .range("J" & k).value) Then

            For j1 As Integer = 0 To 36
                bmver(ik, j1) = .cells(k, j1 + 1).value
            Next
            ik = ik + 1
        End If

    Next

End With
oWs = oBook.Worksheets("beamhor")
oWs.activate()
Dim r6 As Range = oWs.Range("A2").Resize(bmhor.GetLength(0), 37)
r6.Value2 = bmhor

With oWs

    .Range("A2:AE" & i20).Sort(Key1:=.range("E2"), Order1:=Excel.XlSortOrder.xlAscending, _
         Key2:=.range("L2"), Order2:=Excel.XlSortOrder.xlAscending, _
          Key2:=.range("C2"), Order2:=Excel.XlSortOrder.xlAscending, _
         Key2:=.range("J2"), Order2:=Excel.XlSortOrder.xlAscending, _
           Orientation:=XlSortOrientation.xlSortColumns, _
             Header:=Excel.XlYesNoGuess.xlNo, _
           SortMethod:=XlSortMethod.xlPinYin)

End With
oWs = oBook.Worksheets("beamver")
oWs.activate()
Dim r7 As Range = oWs.Range("A2").Resize(bmver.GetLength(0), 37)
r7.Value2 = bmver
With oWs

    .Range("A2:AE" & i20).Sort(Key1:=.range("E2"), Order1:=Excel.XlSortOrder.xlAscending, _
                  Key2:=.range("L2"), Order2:=Excel.XlSortOrder.xlAscending, _
                 Key2:=.range("C2"), Order2:=Excel.XlSortOrder.xlAscending, _
                   Key2:=.range("J2"), Order2:=Excel.XlSortOrder.xlAscending, _
                   Orientation:=XlSortOrientation.xlSortColumns, _
                  Header:=Excel.XlYesNoGuess.xlNo, _
                 SortMethod:=XlSortMethod.xlPinYin)

End With


texts: Getting a transpose of a matrix of size of n*n where n=2^m using multithreading

texts:
The following is a c++ source code to get a matrix (std::vector<std::vector<T>>) transpose in parallel.

The span is \$\Theta(\lg^2(n))\$ while the work is \$\Theta(n^2)\$

Any suggestion to improve will be appreciated.

#include<vector>
#include<iostream>
#include<future>
#include<iomanip>
template <typename T>
void parallelForColsTrans(std::vector<std::vector<T>>& A, size_t fCol, size_t lCol, size_t i, size_t n)
{
    if (fCol == lCol)
    {
        T temp = A[i][fCol+n];
        A[i][fCol+n] = A[i+n][fCol];
        A[i+n][fCol] = temp;

        return;
    }

    std::async(parallelForColsTrans<T>, std::ref(A), fCol, (fCol + lCol) / 2, i, n);
    std::async(parallelForColsTrans<T>, std::ref(A), (fCol + lCol) / 2 + 1, lCol, i, n);

}

template <typename T>
void parallelForRowsTrans(std::vector<std::vector<T>>& A, size_t fRow, size_t lRow, size_t fCol, size_t lCol, size_t n)
{
    if (fRow == lRow) {
        parallelForColsTrans(A, fCol, lCol, fRow, n);
        return;
    }

    std::async(parallelForRowsTrans<T>, std::ref(A), fRow, (fRow+lRow) / 2, fCol, lCol, n);
    std::async(parallelForRowsTrans<T>, std::ref(A), (fRow + lRow) / 2 + 1, lRow, fCol, lCol, n);
}

template <typename T>
void pMatTransposeRecursive(std::vector<std::vector<T>>& A, size_t firstRow, size_t lastRow, size_t firstColumn, size_t lastColumn)
{
    if (firstRow == lastRow)    return;

    auto t1 =std::async(pMatTransposeRecursive<T>, std::ref(A), firstRow, (firstRow +lastRow)/2, firstColumn, (firstColumn+lastColumn)/2);
    auto t2 =std::async(pMatTransposeRecursive<T>, std::ref(A), (firstRow +lastRow)/2+1, lastRow, firstColumn, (firstColumn+lastColumn)/2);
    auto t3 =std::async(pMatTransposeRecursive<T>, std::ref(A), firstRow, (firstRow +lastRow)/2, (firstColumn+lastColumn)/2+1, lastColumn);
    pMatTransposeRecursive<T>(std::ref(A), (firstRow +lastRow)/2+1, lastRow, (firstColumn+lastColumn)/2+1, lastColumn);
    t1.get();
    t2.get();
    t3.get();
    size_t n = (lastColumn-firstColumn+1)/2;
    parallelForRowsTrans<T>(std::ref(A), firstRow, firstRow+n-1, firstColumn, firstColumn+n-1, n);

}

template <typename T>
void transpose(std::vector<std::vector<T>>& A){
    pMatTransposeRecursive( A, 0, A.size()-1, 0, A[0].size()-1);
}
int main(){

    std::vector<std::vector<int>> A = {{1,2,3,4,7,7,7,8}, {5,6,7,8,4,5,1,1}, {9,10,5,5,11,12,4,79}, {7,8,13,14,15,16,44,6}, {13,-14,7,-7,15,-16,-44,6}, {13,-14,105,106,404,6,9,9}, {13,-14,7,-7,15,-16,-44,6}, {13,-14,105,106,404,6,9,9}};
    transpose(A);
    for(auto & el:A){
        for(auto& ele:el) std::cout << ele << std::setw(4) ;
        std::cout << "\n";

    }
}


texts: Sort a scrambled itinerary (Google apac test problem)

texts:
This is my first time writing ruby - and I was mainly hoping to get some feedback and stylistic pointers.

The algorithm is pretty straight-forward, since Google guarantees airports aren't repeated I store all the tickets in a hash table and then sort from random insertion points, which should be worst case \$O(n \log n)\$.

Original problem description

  Once upon a day, Mary bought a one-way ticket from somewhere to somewhere with some flight transfers. For example: SFO->DFW DFW->JFK JFK->MIA MIA->ORD.

  Unfortunately, after she received the tickets, she messed up the tickets and she forgot the order of the tickets.

  Help Mary rearrange the tickets to make the tickets in correct order.

def merge_ordered_flights(ordered_flights)
    while ordered_flights.size > 1
        flights = ordered_flights.pop
        ordered_flights.each do |a|
            if a[0] == flights[-1]
                a.insert(0, *flights)
                break
            elsif a[-1] == flights[0]
                a.insert(-1, *flights)
                break
            end
        end
    end
    return ordered_flights[0] #flatten
end

def order_flights(tickets)
    ordered_flights = []
    iter = 0
    while true
        #Get an arbitrary arrival, destination flight pair
        arv, dest = tickets.shift
        if arv == nil
            break #Done if we are out of tickets
        end
        ordered_flights[iter] = []
        ordered_flights[iter].push(arv, dest)
        #And append follow-up destinations until we can't find one
        #(It's the final destination, or the other tickets have already been sorted)
        while true
            arv = dest
            dest = tickets.delete(dest)
            if dest == nil
                break #End of current chain
            end
            ordered_flights[iter].push(arv, dest)
        end
        iter += 1
    end
    #Now combine the ordered flight arrays into a single array
    return merge_ordered_flights(ordered_flights)
end

def print_flights(case_num, ordered_flights)
    flights = (0...ordered_flights.size).step(2).map {|i| ordered_flights[i] + '-' + ordered_flights[i+1] }.join ' '
    puts "CASE ##{case_num}: #{flights}"
end

while not $stdin.eof?
    num_cases = $stdin.readline.strip.to_i
    (1..num_cases).each {
        |num|
        tickets = {}
        num_flights = $stdin.readline.strip.to_i
        (0...num_flights).each {
            tickets[$stdin.readline.strip] = $stdin.readline.strip
        }
        ordered_flights = order_flights(tickets)
        print_flights(num, ordered_flights)
    }
end

Example input:

  The first line contains the number of test cases T, after which T cases follow.
  For each case, it starts with an integer N. There are N flight tickets follow.
  Each of the next 2 lines contains the source and destination of a flight ticket.

2
1
SFO
DFW
4
MIA
ORD
DFW
JFK
SFO
DFW
JFK
MIA

Expected output:

Case #1: SFO-DFW
Case #2: SFO-DFW DFW-JFK JFK-MIA MIA-ORD


texts: Counting pairs of numbers that differ by a given amount

texts:
I am trying to do these online competitions where you get the given exercise and are supposed to upload the source file.
The site is not in English so I will try to summarize the exercise.

The first line of input states P, the number of problems ( 1 <= P <= 100 ). Subsequently, there are two lines for each problem. The first contains numbers X and Y ( 1 <= X, Y <= 100000) — X being number of elements and Y being the difference I am looking for. On the next line there are X numbers (0 <= N <= 100000) divided by a space. For every problem, I am supposed to print the number of pairs that differ by Y.

As an example input :

2
5 2
1 5 3 4 2
5 4
6 3 6 2 2

Example output:

3
4

I wrote a simple programme that did the thing but when I uploaded the source file I got "time limit exceeded" error. After that I discovered that my program is unable to handle big input. I tried to move on to the next exercise but I discovered almost all of them have big inputs. I tried to improve it myself, then I tried to google it, but sadly I still cannot get past the error. This is the code I ended up with :

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

#define SIZE 80000

int compare(const void *a, const void *b);

int main(int argc, char const *argv[]) {
  char buffer[SIZE];
  unsigned int numberOfGames, numberOfStudents, wantedDifference;
  unsigned int numberOfDifferentPairs;
  unsigned int counter;
  size_t i, j;

  scanf("%u", &numberOfGames);

  while (numberOfGames--) {
    scanf("%u %u", &numberOfStudents, &wantedDifference);
    scanf("\n");
    unsigned long long int *studentsHeights =
        (unsigned long long int *)malloc(sizeof(unsigned long long int) * numberOfStudents);
    counter = 0;
    numberOfDifferentPairs = 0;
    studentsHeights[counter] = 0;
    while (counter < numberOfStudents) {
      fgets(buffer, SIZE, stdin);
      size_t stringSize = strlen(buffer);
      for (i = 0; i < stringSize; i++) {
        if (buffer[i] == ' ' || buffer[i] == EOF || buffer[i] == '\n') {
          counter++;
          if (counter < numberOfStudents)
            studentsHeights[counter] = 0;
        } else {
          studentsHeights[counter] =
              studentsHeights[counter] * 10 + (buffer[i] - '0');
        }
      }
    }
    qsort(studentsHeights, numberOfStudents, sizeof(unsigned int), compare);
    for (i = 0; i < numberOfStudents - 1; i++) {
      unsigned int lastAddition;
      if (studentsHeights[i] == studentsHeights[i - 1]) {
        numberOfDifferentPairs += lastAddition;
        continue;
      } else {
        lastAddition = 0;
      }
      for (j = i + 1; j < numberOfStudents; j++) {
        if ((studentsHeights[j] - studentsHeights[i]) == wantedDifference) {
          numberOfDifferentPairs++;
          lastAddition++;
        }
      }
    }
    printf("%u\n", numberOfDifferentPairs);
  }
  return 0;
}

int compare(const void *a, const void *b) {
  if (*(unsigned int *)a < *(unsigned int *)b)
    return -1;
  else if (*(unsigned int *)a == *(unsigned int *)b)
    return 0;
  else
    return 1;
}

I know I am probably doing some trivial mistake but if you could point it out for me I would be really grateful.

There are the variables I used:

P = numberOfGames
X = numberOfStudents
Y = wantedDifference
N = studentsHeights


texts: Applying DocumentListener on multiple JTextField

texts:
Say I have 5 JTextField: jTextField1, jTextField2...

Now I want them to behave the same on DocumentListener, so I decided to make only one DocumentListener and set it to the 5 components.

Meanwhile I'm doing this:

jTextField1.getDocument().putProperty("owner", jTextField1);
jTextField2.getDocument().putProperty("owner", jTextField2);
..
..

And I have this listener:

DocumentListener documentListener = new DocumentListener() {
    public void changedUpdate(DocumentEvent arg0)
    {
        Object owner = arg0.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }

    public void insertUpdate(DocumentEvent arg0)
    {
        Object owner = arg0.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }

    public void removeUpdate(DocumentEvent arg0)
    {
        Object owner = arg0.getDocument().getProperty("owner");
        enableDetachButton(getContentPane());
        changeColor((JTextField) owner);
    }
};

Finally, I do:

jTextField1.getDocument().addDocumentListener(documentListener);
..
..

Is this approach OK? What improvements can I do?


texts:
I want to make sure find_value_from_key() is safe and efficient.  My constraints are language C++, use of standard library ok, but cannot use Boost or any new C++11 features.

Can anyone offer any comments/criticisms/feedback on my implementation of the function here?  Any flaws in my test cases would also be interesting to hear.

#include <string>
#include <iostream>

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

bool find_value_from_key(const string& source, const string& key, string& value, const string& EndOfValueMarker) {
   bool ret = false;
   size_t pos_start = source.find(key);
   if(pos_start != string::npos) {
      size_t pos_end = source.find_first_of(EndOfValueMarker, pos_start+key.length());
      if(pos_end == string::npos && source.length() > pos_start+key.length())
         pos_end = source.length();

      if(pos_end != string::npos) {
         value = source.substr(pos_start+key.length(), pos_end-pos_start-key.length());
         ret = true;
      }
   }
   return ret;
}

int main(int argc, char* argv[])
{
   //test strings to exercise find_value_from_key function
   const char* test_strings[] = {
      "key1 = value1",
      "   key1 = value1   ",
      "key1 = value1,key2 = value2 ,key3 = value3",
      "_key1 = value1 ,key2 = value2 ,Gkey3 = value3,",
      "key1 = value1,key2 =  value2 ,key3 = value3 x",
      "key1 = value1,key2 = value2key3 = value3\n",
      "key1 = value1_,key2 = value2 ,key3 = value3                    ",
      "key1 = value1$,key2 = value2 ,key3 =   value3",
      "key1 = value1\t,key2 = value2  ,key3 = value3\t" };

   const char* keys[] = {"key1 = ", "key2 = ", "key3 = "};

   int elements = sizeof(test_strings) / sizeof(test_strings[0]);

   for(int i = 0; i < elements; ++i) {
     cout << "processing: " << test_strings[i] << endl;
     string value;
     if(find_value_from_key(test_strings[0], keys[0], value, ", \t\n"))
        cout << value << endl;
   }

   return 0;
}


texts: Alternative to using sleep() to avoid a race condition in PyQt

texts:
I have a situation where I would like to use a single QThread to run two (or more) separate methods at different times. For example, I would like the QThreadto run play() sometimes, and when I am done playing, I want to disconnect the QThread.started() signal from this method so that I may connect it somewhere else. In essence I would like the QThread to act as a container for anything I would like to run in parallel with the main process.

I have run into the problem where starting the QThread and then immediately disconnecting the started() signal it causes strange behavior at runtime. Before I discovered what 'race condition' meant (or really understanding much about multithreading), I had the sneaking suspicion that the thread wasn't fully started before being disconnected. To overcome this, I added a 5 ms sleep in between the start() and disconnect() calls and it works like a charm. It works like a charm but it isn't The Right Way.

How can I implement this functionality with one QThread without making the call to sleep()?

def play(self):

    self.stateLabel.setText("Status: Playback initated ...")

    self.myThread.started.connect(self.mouseRecorder.play)
    self.myThread.start()
    time.sleep(.005)  #This is the line I'd like to eliminate

    self.myThread.started.disconnect()

def record(self):

    self.stateLabel.setText("Status: Recording ...")

    self.myThread.started.connect(self.mouseRecorder.record)
    self.myThread.start()
    time.sleep(.005) #This is the line I'd like to eliminate

    self.myThread.started.disconnect()


texts:
I have some code here that changes the font size depending on what link you clicked and it works perfectly, I now want to add another feature but need some help. I want to add current font size which changes as you press bigger or smaller.

jQuery:

$(document).ready(function() {

    function change_size(element, size) {

        var current = parseInt(element.css('font-size'));

        if (size == 'smaller') {
            var new_size = current - 4;
        } else if (size == 'bigger') {
            var new_size = current + 4;
        }

        element.css('font-size', new_size + 'px');
    }

    $('#smaller').click(function() {
        change_size($('p'), 'smaller');
    });

    $('#bigger').click(function() {
        change_size($('p'), 'bigger');
    });
});

HTML:

Font size: Smaller | Bigger Current Font Size:

This is some text

This is some more text


texts:
This is from Wikipedia:

  In mathematics, Waring's prime number conjecture is a conjecture in number theory, closely related to Vinogradov's theorem. The conjecture is named after the English mathematician Edward Waring and states that every odd integer exceeding 3 is either a prime number or the sum of three prime numbers. The conjecture is known to follow from the generalized Riemann hypothesis.

My code:

 def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

def prime_number(maximum):
  number_list=(i for i in range(1,maximum+1))
  divisor=1
  divisor_list=[]
  prime_number_list=[]
  for e in number_list:
    while divisor<=e:
      if e%divisor==0:
        divisor_list.append(divisor_list)
        divisor+=1
      else:
        divisor+=1
    if len(divisor_list)==2:
      prime_number_list.append(e)
      prime_number_list.append(e)
      prime_number_list.append(e)
      prime_number_list.append(e)
      divisor=1
      divisor_list=[]
    else:
      divisor=1
      divisor_list=[]
  return prime_number_list

def div_by_two(num):
  if num%2==0:
    return False
  else:
    return True

def Waring_Number(maximum):
  input_list=range(5,maximum+1)
  combination_of_prime_number=combinations(prime_number(maximum),3)
  prime_number_list=prime_number(maximum)
  odd_number=[i for i in input_list if div_by_two(i)]
  for e in odd_number:
    if e in prime_number_list:
      print ("{} is a prime number.".format(e))
    else:
        for combination in combination_of_prime_number:
          if sum(combination)==e:
            print ("{}+{}+{}={}".format(combination[0],combination[1],combination[2],e))
            break

Few Notes:

I just copied and pasted the combination function from itertools documentation, I do not know how the function actually works, only how it works.
prime_number_list.append(e) was repeated four times because the combinations had to include prime numbers being repeated three times too. (For example, (3,3,3) has to be created for Waring Number to work) I know this takes up time.
I am a beginner. I have only been doing Python for few months for hobby and only know the basics

Any and all feedback is welcome.


texts:
I have a method to parse strings. It can be used to parse a float using a specific culture and then get a new string with a specific out-culture. The same applies to ints, doubles and decimals.

The code that I've written is quite repetitive for each of the different parse methods which makes it hard to maintain (especially as I am just about to make the method a lot more complex).

Is it possible to make this code less repetitive?

if (mapping.ParseDecimal)
{
    decimal i;
    if (decimal.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a decimal using the culture \"{1}\".", value, inCulture);
    }
}
else if (mapping.ParseDouble)
{
    double i;
    if (double.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a double using the culture \"{1}\".", value, inCulture);
    }
}
else if (mapping.ParseFloat)
{
    float i;
    if (float.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a float using the culture \"{1}\".", value, inCulture);
    }
}
else if (mapping.ParseInt)
{
    int i;
    if (int.TryParse(value, numberStyle, inCulture, out i))
    {
        return i.ToString(outCulture);
    }
    else
    {
        if (logger.IsDebugEnabled)
            logger.DebugFormat("Could not parse value \"{0\" to a int using the culture \"{1}\".", value, inCulture);
    }
}


texts: Show contents in a book chapter and sections in a highly normalized repository

texts:
I want to present books that has chapters and sections, and contents in each book, chapter and section.
This is my schema:
type BookId = string
type ChapterId = string
type SectionId = string
type ContentId = string

export type SourceId =
| ChapterId
| SectionId
| BookId

type Book = {
  id: BookId,
  name: string,
}

type Chapter = {
  id: ChapterId,
  bookId: BookId,
  name: string
}
type Section = {
  id: SectionId,
  chapterId: ChapterId,
  name: string
}

type Content = {
  id: ContentId,
  sourceId: SourceId,
  name: string,
  content: string
}

This is how I query all the books, chapters and sections:
 list() {
    return this.bookRepo.all().then(books =>
      Promise.all(books.map(book =>
        Promise.all([
          this.bookRepo.contents(book.id),
          this.bookRepo.chapters(book.id)
        ]).then(([contents, chapters]) =>
          Promise.all(chapters.map(chapter =>
            Promise.all([
              this.bookRepo.contents(chapter.id),
              this.bookRepo.sections(chapter.id)
            ]).then(([contents, sections]) =>
              Promise.all(sections.map(section =>
                this.bookRepo.contents(section.id).then(contents => [
                  section, contents
                ])))
                .then(sections => [chapter, contents, sections]))))
            .then(chapters => [book, contents, chapters])))));
  }

I just render as json at the moment, but the query code seems hard to maintain.


texts: Emitting event on close of other event (event chaining)

texts:
I have a software that does the following in sequence:

download text files from s3
reads the files
collect the data from files

The program is asynchronous-synchronous - each phase is asynchronous, but it heavily depends on the output of the previous phase, so I'm using Promises for build the chaining.

The problem of this architecture is that is using to much CPU since I'm spawning child processes in the extract and collect phase. So I decide to change to events:

How I'm doing:

I have 3 eventEmitters: downloadFile, extract, collect:

downloadfile.emit("copy", s3file);
downloadfile.on("error", callback);
downloadfile.on("close", (file) => {
 extract.emit("file", file);
 extract.on("error", callback);
 extract.on("close", (file) => {
   collect.emit("data", file.data);
   collect.on("error", callback);
   collect.on("close", (data) => {
      data is here... i can use without waiting all the other files.
   });
 });
});

But this isn't very readable... I prefer the Promise way:

Promise.resolve(options)
  .then(downloadFiles)
  .then(extract)
  .then(collect);

So I was thinking... is it possible to chain the events? I mean, the output of an event will be the input of other, just like the Promises? If so, how could I achieve that?


texts: Thread safe static collection, is this code safe

texts:
A small caching utility, can you tell if it is thread safe?

public static class CacheService
{
    private readonly static object locker = new object();
    private static Dictionary<string, Dictionary<string, object>> data = new Dictionary<string, Dictionary<string, object>>();

    public static void Insert(string partition, string key, object value)
    {
        lock (locker)
        {
            if (!data.ContainsKey(partition))
            {
                var newVal = new Dictionary<string, object>();
                newVal.Add(key, value);
                data.Add(partition, newVal);
            }
            else
            {
                if (!data[partition].ContainsKey(key))
                {
                    data[partition].Add(key, value);
                }
                else
                {
                    data[partition][key] = value;
                }
            }
        }
    }

    public static bool KeyExists(string partition, string key)
    {
        return data[partition] != null && data[partition][key] != null;
    }

    public static V Get<V>(string partition, string key)
    {
        return (V)data[partition][key];
    }

}


texts:
In this function, the copy (Write XML) is inside, but I want it to be separated from the function.  How can I improve this function?

Sub ExporttoFolder(ByVal POSPath As String, ByVal dt As DataSet, ByVal FolderCopyto As String,ByVal SelectedItem As DataTable)

If MsgBox("Do you want to Export Invoice to " & _WhouseToComboBox.textBox.Text & " ? ", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then

Dim Whouse As String
For Each dr As DataRow In SelectedItem.Rows
Whouse = dr.Item("whouseDesc")
ProcessCopy(POSPath, dt, FolderCopyto, Whouse)
Next dr
End If

End Sub

Sub ProcessCopy(ByVal targetDirectory As String, ByVal File As DataSet, ByVal FolderTarget As String, ByVal DirectoryFather As String)

Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
Dim Filepath As String = Nothing
Dim subdirectory As String

For Each subdirectory In subdirectoryEntries
Try

If Path.GetFileName(subdirectory) = DirectoryFather Then

If IO.Directory.Exists(subdirectory & "\" & FolderTarget) Then

File.WriteXml(subdirectory & "\" & FolderTarget & "\" & File.Tables(0).Rows(0).Item("InvoiceID") & ".xml")

End If

End If

ProcessCopy(subdirectory, File, FolderTarget, DirectoryFather)
Catch ex As Exception
End Try

Next subdirectory

End Sub


texts:
I am new in Golang, and decided to create a function that could cater to my needs of reading an integer from stdin. I need the function to be as efficient and fast as possible.

package main
import(
    "fmt"
    "bufio"
    "os"
    "strconv"
)

type NoIntRead int

func (err *NoIntRead) Error() string{
    return fmt.Sprintf("No integer was read!")
}

var(
    inputreader = bufio.NewReader(os.Stdin)
    mybyteslice []byte = make([]byte,11)
)
func ReadInt() (int,error){
    var mybyte byte
    var myint int
    var err error
    var size int = 0
    for{
        mybyte,err = inputreader.ReadByte()
        if mybyte == '\n' || mybyte == ' ' || err != nil{
            if size == 0{
                myerr := NoIntRead(1)
                return 0,&myerr
            }
            mystring := string(mybyteslice[:size])
            myint,err = strconv.Atoi(mystring)
            if err != nil{
                myerr := NoIntRead(1)
                return 0, &myerr
            }
            return myint,nil
        }
        mybyteslice[size] = mybyte
        size++
    }
}
func main(){
    var myint int
    var err error
    for{
        myint,err = ReadInt()
        if err != nil{
            fmt.Println(err)
            break;
        }
        fmt.Println(myint)
    }
}

Is there a more efficient way to read integers from stdin? If yes, I would be more than grateful if someone could point me into the right direction.


texts: Refactoring method to make it unit testing friendly

texts:
I have a completed application which I'm trying to write unit tests for (Yeah I know, talk about bad practices)

I have the following class here

public class UserManagementService : IUserManagementService
{
    private static readonly IUserDao userDao = DataAccess.UserDao;
    private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

    public LoginResponse Login(LoginRequest request)
    {
        var response = new LoginResponse(request.RequestId);
        try
        {
            var user = userDao.GetByUserId(request.UserId);
            if (user != null)
            {
                if (request.Password != "")
                {
                    if (Authenticate(user, request.Password))
                    {
                        return response;
                    }
                    response.ErrorCode = "IncorrectPassword";
                }
                else
                {
                    response.ErrorCode = "PasswordNotFound";
                }
            }
            else
            {
                response.ErrorCode = "UserNotFound";
            }
            response.Acknowledge = AcknowledgeType.Failure;
            return response;
        }
        catch (Exception ex)
        {
            Log.Error(ex);
            response.Acknowledge = AcknowledgeType.Failure;
            response.ErrorCode = "Exception";
            return response;
        }
    }

    public bool Authenticate(User user, string password)
    {
        if (user == null) return false;

        using (var deriveBytes = new Rfc2898DeriveBytes(password, user.Salt))
        {
            var derivedPassword = deriveBytes.GetBytes(20);
            if (!derivedPassword.SequenceEqual(user.Password)) return false;
        }
        return true;
    }
}

userDao follows the singleton pattern and this userDao.GetByUserId(request.UserId); basically makes a call to my DB

I have written the following test, which will definitely give rise to some issues because I haven't figured how to Mock the userDao, and the Log

[Theory]
[InlineData("manager", "manager")]
public void LoginTest(string userId, string password)
{
    // Arrange
    // System under test
    IUserManagementService userService = new UserManagementService();

    var request = new LoginRequest().Prepare();
    request.UserId = userId;
    request.Password = password;

    var expectedResponse = new LoginResponse(request.RequestId)
            {
                Acknowledge = AcknowledgeType.Success
            };

    //Act
    var actualResponse = userService.Login(request);

    //Assert
    Assert.AreEqual(actualResponse.Acknowledge, expectedResponse.Acknowledge);
}

How can I refactor my Login method, and UserManagementService class without breaking too much of its structure to support unit testing so I can inject userDao and Log?

Any help would be great to help me kickstart what is going to be a long tedious process of refactoring the rest of my classes.

EDIT: This is a WCF service which follows the facade pattern. I have removed the 10 other static DAO similar to userDao to lessen the code clutter for this example.


texts: Class that represents a conditional expression

texts:
I have a class with which I want to persist a conditional expression:

boolean x = a [GT] i

I am only concerned with the boolean outcome of that comparison. 'a' '[GT]' and 'i' are supplied as arguments at runtime.

public class RuleClauseCondition {
    RuleClauseOperator operator;
    Double             threshold;
    Double             operand;

    private RuleClauseCondition()
    {
    }

    public RuleClauseCondition(RuleClauseOperator operator, Double threshold, Double operand) {
        this.operator = operator;
        this.threshold = threshold;
        this.operand = operand;
    }

    boolean isValid() {
        return operator.isValid(operand, threshold);
    }

}

public enum RuleClauseOperator{
    EQ {
        @Override
        public boolean isValid(Double inputValue, Double thresholdValue) {
            return inputValue.equals(thresholdValue);
        }

        @Override
        public String toString() {
            return " == ";
        }
    }, LT {
        @Override
        public boolean isValid(Double inputValue, Double thresholdValue) {
            return inputValue < thresholdValue;
        }

        @Override
        public String toString() {
            return " < ";
        }
    }, GT {
        @Override
        public boolean isValid(Double inputValue, Double thresholdValue) {
            return inputValue > thresholdValue;
        }

        @Override
        public String toString() {
            return " > ";
        }
    }

I am looking for better names to represent the left and right side of the operator as well as the class name.

Are current names intuitive and self documenting, or do I need to improve them?


texts:
G'day
Just before I submit this to CFLib, it'd be great to get feedback:

<cfscript>
/**
* @hint CFML implementation of Array.reduce(), similar to Javascript's one ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
* @array Array to reduce
* @callback Callback function to use to reduce. Will receive the following arguments: element (of current iteration of the all), index, array, (optional) result (of preceeding call to callback())
* @initialValue The initial value to use to start the reduction
*/

public any function arrayReduce(required array array, required any callback, any initialValue){
    var startIdx = 1;
    if (!structKeyExists(arguments, "initialValue")){
        if (arrayLen(array) > 0){
            var result = callback(array[1], 1, array);
            startIdx = 2;
        }else{
            return;
        }
    }else{
        var result = initialValue;
    }
    for (var i=startIdx; i <= arrayLen(array); i++){
        result = callback(array[i], i, array, result);
    }
    return result;
}
</cfscript>

I've created proper unit tests as a gist.


texts: Recursive Function to Produce Constrained List of Integer Partitions

texts:
I have modified a recursive function designed to print all the integer partitions of a positive integer to create a function that returns all partitions of the "number" parameter if they include a number contained in the "interesting" parameter. I would like to use this for very large numbers (10-50 million), but am getting errors referring to the recursion depth. My question is whether there is a way to do this more efficiently by recursion, and if not, whether there is another way to do this.
def partition(number, interesting): # returns all the partitions of number that are included in the interesting list
    answer = set()
    if number in interesting:
        answer.add((number, ))

    for x in range(1, number):
        if x in interesting:
            for y in partition(number - x, interesting):
                answer.add(tuple(sorted((x, ) + y)))
    return answer


texts:
Please see the code below:

public bool IsValidateInputSuceeded(string EnteredCost, string EnteredPaymentReceived, out decimal Cost, out decimal PaymentReceived)
{
    bool ValidateInputSuceeded = true;

    EnteredCost= EnteredCost.Substring(EnteredCost.IndexOfAny("0123456789".ToCharArray()));
    EnteredPaymentReceived = EnteredPaymentReceived.Substring(EnteredPaymentReceived.IndexOfAny("0123456789".ToCharArray()));

    if ((Decimal.TryParse(EnteredCost.Replace(" ", "").Replace(",", ""), out Cost)) == false)
    {
        ValidateInputSuceeded = false;
    }

    if ((Decimal.TryParse(EnteredPaymentReceived.Replace(" ", "").Replace(",", ""), out PaymentReceived)) == false)
    {
        ValidateInputSuceeded = false;
    }

    if (ValidateInputSuceeded == false)
    {
        return false;
    }

    if (EnteredCost.IndexOf(" ") > 0|| EnteredPaymentReceived.IndexOf(" ") > 0)
    {
        return false;
    }

    if (EnteredCost[EnteredCost.Length-1] =='.' || EnteredCost[EnteredCost.Length - 2] == '.' || EnteredPaymentReceived[EnteredPaymentReceived.Length - 1]=='.' || EnteredPaymentReceived[EnteredPaymentReceived.Length - 2] == '.')
    {
        return false;
    }

    if (EnteredCost.IndexOf(".") == -1 || EnteredPaymentReceived.IndexOf(".")==-1)
    {
        return false;
    }

    return true;
}

EnteredCost and EnteredPaymentReceived are input parameters from MaskedTextBoxs'(https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(v=vs.110).aspx) both with an input mask of: £999,999.00.  For example, a value of one of them could be: "£   ,  3.22" (without quotes) as an input parameter into the function.

There are two string variables: EnteredCost and PaymentReceived. Should these variables be StringBuilders instead of Strings? The reason I ask is because there are a log of string manipulations going on e.g. using the REPLACE function and the indexOfAny function, which returns more strings.


texts:
Following is the code that I'm currently using to validate the user given IP address (IPV4 and IPV6). It makes use of apache commons-validator's InetAddressValidator. However, their function validates only IPV4 address and not IPV6.

public static boolean isValidInetAddress(final String address){
        boolean isValid = false;
        if(address == null || address.trim().isEmpty())
            return isValid;
        if(InetAddressValidator.getInstance().isValid(address)){
            isValid = true;
        } else { //not an IPV4 address, could be IPV6?
            try {
                isValid = InetAddress.getByName(address) instanceof Inet6Address;
            } catch (UnknownHostException ex) {
                isValid = false;
            }
        }
        return isValid;
    }

Is there a better way?

(P.S commons-validator does regex pattern matching for IPV4 address validation)


texts:
I am studying algorithms and I had to solve this algorithm:

Consider the following problem. You have a car such that if you fill it up to full tank, you can travel with it up to 400 kilometers without refilling it. And you need to get from point A to point B, and the distance between them is 950 kilometers. Of course, you need to refuel on your way, and luckily, there are a few gas stations on your way from A to B. These are denoted by blue circles, and the numbers above them mean the distance from A to the corresponding gas station along the way from A to B. And you need to find the minimum number of refuels to get from A to B.

I came up to a very different solution that the teacher and I would like to know your thoughts:

import java.io.*;
import java.util.*;

public class MinRefill{

 static int getMinRefill(int[] numbers, int refillAt) {
    int lastRefill=0;
    int currentRefill=0;
    int numOfRefills=0;
    int endPoint= numbers.length;

    while(currentRefill<endPoint-1){

        if(numbers[currentRefill+1]-numbers[currentRefill]>refillAt){
            return 0;
        }

        if(lastRefill+refillAt<numbers[currentRefill+1]){
            lastRefill=numbers[currentRefill];
            numOfRefills++;
        }

        currentRefill++;
    }

    return numOfRefills;
}
public static void main(String[] args) {

    Scanner in = new Scanner(System.in);

    int n = in.nextInt();
    int[] numbers = new int[n];

    for (int i = 0; i < n; i++) {
        numbers[i] = in.nextInt();
    }

    System.out.println(getMinRefill(numbers,400));

}
}

Tested input:

0
0 200 375 550 750 950

0 = A and 950 = B


texts: Returning a list of divisors for a number

texts:
This function takes in a number and returns all divisors for that number.  list_to_number() is a function used to retrieve a list of prime numbers up to a limit, but I am not concerned over the code of that function right now, only this divisor code.  I am planning on reusing it when solving various Project Euler problems.

def list_divisors(num):
    ''' Creates a list of all divisors of num
    '''
    orig_num = num
    prime_list = list_to_number(int(num / 2) + 1)
    divisors = [1, num]
    for i in prime_list:
        num = orig_num
        while not num % i:
            divisors.append(i)
            num = int(num / i)
    for i in range(len(divisors) - 2):
            for j in range(i + 1, len(divisors) - 1):
                if i and j and j != num and not orig_num % (i * j):
                    divisors.append(i * j)
    divisors = list(set(divisors))
    divisors.sort()
    return divisors


texts: Find almost-shortest path more efficiently

texts:
I'm trying to solve a SPOJ problem, which is code SAMER08A at this link.

The problem is that when I ran my code in my IDE with all the examples given in the problem, the code works perfectly.  But when running it in SPOJ, it exceeds the time limit of 2 seconds.

I am frustrated because I have worked so hard on it.  I would love some advice and help.

#include <vector>
#include <iostream>
#include <queue>
using namespace std;

typedef pair <int, int> dist_node;
typedef pair <int, int> edge;
const int MAXN = 500;
const int INF = 1 << 30;
vector <edge> g[MAXN];
int d[MAXN];
vector<int> p[MAXN];
int answer[MAXN];
int last_node;
vector<vector<int> > paths;

int dijkstra(int s, int n,int t){
    for (int i = 0; i <= n; ++i){
        d[i] = INF;  p[s].push_back(-1);
    }
    priority_queue < dist_node, vector <dist_node>,greater<dist_node> > q;
    d[s] = 0;
    q.push(dist_node(0, s));
    while (!q.empty()){
        int dist = q.top().first;
        int cur = q.top().second;
        q.pop();
        if (dist > d[cur]) continue;
        for (int i = 0; i < g[cur].size(); ++i){
            int next = g[cur][i].first;
            int w_extra = g[cur][i].second;
            if (d[cur] + w_extra < d[next]){
                d[next] = d[cur] + w_extra;
                p[next].clear();
                p[next].push_back(cur);
                q.push(dist_node(d[next], next));
            }
            else if(d[cur] + w_extra == d[next]){
                p[next].push_back(cur);
            }
        }
    }
    return d[t];
}

void findpath (int t, int depth){
    if(t == 0){
        vector<int> camino;
        for(int i = depth-1; i >= 0; --i){
            camino.push_back(answer[i]);
        }
        camino.push_back(last_node);
        paths.push_back(camino);
        return;
    }
    for(int i = (int)p[t].size()-1; i >= 0; --i){
        answer[depth] = p[t][i];
        findpath(p[t][i], depth+1);
    }
}

void findAlmostShortestPath(){

    for(int k = 0; k<paths.size();k++){
        vector<int> camino = paths[k];
        for(int i = 0;i<camino.size()-1;i++){
            int x = camino[i];
            int y = camino[i+1];
            for(int j = 0; j < g[x].size() ; j++){
                if(g[x][j].first == y){
                    g[x][j].second =INF;
                    break;
                }
            }
            break;
        }
    }
}

int main(){
    int n,m;
    int w,s;
    bool seguir = true;
    while(seguir){
        cin>>n>>m;
        cin>>w>>s;
        last_node=s;

        if(n == 0 & m == 0){
            break;
        }
        for (int i = 0; i < m; ++i){
            int u, v, w;
            cin >> u >> v >> w;
            g[u].push_back(edge(v, w));
        }
        int i;
        i = dijkstra(w, n,s);
        findpath(s, 0);
        findAlmostShortestPath();
        i = dijkstra(w, n, s);

        if(i==INF){
            i =-1;
        }
        cout<<i<<endl;

        for(int i = 0; i < g[i].size(); i++){
            g[i].clear();
        }
    }

    return 0;
}

I would be so grateful if you could help me since I've worked on this for hours, and it's my first SPOJ problem that I have tried to solve.


texts: Basic C++ server and client for chatting over TCP

texts:
#pragma comment(lib, "sfml-network.lib")

#include <iostream>
#include <SFML/Network.hpp>

const unsigned short PORT = 5000;
const std::string IPADDRESS("192.168.0.100");//change to suit your needs

std::string msgSend;

sf::TcpSocket socket;
sf::Mutex globalMutex;
bool quit = false;

void DoStuff(void)
{
    static std::string oldMsg;
    while(!quit)
    {
        sf::Packet packetSend;
        globalMutex.lock();
        packetSend << msgSend;
        globalMutex.unlock();

        socket.send(packetSend);

        std::string msg;
        sf::Packet packetReceive;

        socket.receive(packetReceive);
        if(packetReceive >> msg)
        {
            if(oldMsg != msg)
                if(!msg.empty())
                {
                    std::cout << msg << std::endl;
                    oldMsg = msg;
                }
        }
    }
}
void Server(void)
{
    sf::TcpListener listener;
    listener.listen(PORT);
    listener.accept(socket);
    std::cout << "New client connected: " << socket.getRemoteAddress() << std::endl;
}
bool Client(void)
{
    if(socket.connect(IPADDRESS, PORT) == sf::Socket::Done)
    {
        std::cout << "Connected\n";
        return true;
    }
    return false;
}
void GetInput(void)
{
    std::string s;
    std::cout << "\nEnter \"exit\" to quit or message to send: ";
    std::cin >> s;
    if(s == "exit")
        quit = true;
    globalMutex.lock();
    msgSend = s;
    globalMutex.unlock();
}
int main(int argc, char* argv[])
{
    sf::Thread* thread = 0;

    char who;
    std::cout << "Do you want to be a server (s) or a client (c) ? ";
    std::cin  >> who;

    if(who == 's')
        Server();
    else
        Client();

    thread = new sf::Thread(&DoStuff);
    thread->launch();

    while(!quit)
    {
        GetInput();
    }
    if(thread)
    {
        thread->wait();
        delete thread;
    }
    return 0;
}


texts: Evaluating formulas greater than 255 characters

texts:
Recently I was receiving Error 2015 when trying to use Application.Evaluate, then I realized it was because my formula was greater than 255 characters. As a workaround, I came up with this UDF:

Function AdvancedEvaluate(eformula As String)

    ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Formula = eformula
    AdvancedEvaluate = ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Value
    ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").ClearContents

End Function

Which I use in place of all of my Application.Evaluate. However, I'm not satisfied with this solution... is my solution sufficient, or is there a better way to evaluate a formula of greater than 255 characters?


texts: Find the number in an array which is closest to an given number

texts:
Exercise from an Assembly course I'm enrolled in:

  Find closest number.

  Add the following into the data section:

  nums  dd  23h,75h,111h,0abch,443h,1000h,5h,2213h,433a34h,0deadbeafh

  This is an array of numbers.

  Write a program that receives a number x as input, and finds the dword
  inside the array nums, which is the closest to x. (We define the
  distance between two numbers to be the absolute value of the
  difference: |a-b|).

  Example:

  For the input of 100h, the result will be 111h, because 111h is closer
  to 100h than any other number in the nums array. (|100h - 111h| =
  11h).

Full exercise-sheet on GitHub - xorpd

Here's my approach. Please pay attention to the comments which I've added to explain my ideas.

format PE console
entry start

include 'win32a.inc'

section '.data' data readable writeable
    nums  dd  23h, 75h, 111h, 0abch, 443h, 1000h, 5h, 2213h, 433a34h, 0deadbeafh
    nums_end:

section '.text' code readable executable

start:
    xor         esi,        esi                     ; Current array-index.
    mov         ecx,        (nums_end - nums) / 4   ; Array-length
    mov         ebx,        0x100                   ; Input, Value to compare too.
    mov         edx,        0x7fffffff              ; Smallest value found until now. Start with the greatest value possible.
    mov         edi,        edi                     ; Index of the element with the smallest value.
    ; -------------------------------------------------------------------------------------------------------------------
check_next:
    mov         eax,        ebx                     ; Make a copy compare-value.
    mov         ebp,        dword[nums + 4 * esi]   ; Move the value of the current element to ebp.
    cmp         eax,        ebp                     ; If eax is smaller then ebp then we must not subtract ebp from eax.
    jb          eax_is_smaller                      ;   This would result in a negative number. ...
    sub         eax,        ebp
    jmp         subtraction_done
eax_is_smaller:
    sub         ebp,        eax                     ; ... subtract eax from ebp instead.
    mov         eax,        ebp                     ; ... and move the result to eax.
subtraction_done:
    cmp         eax,        edx                     ; Compare the result to the current smallest value.
    jnb         prepare_next
    mov         edx,        eax                     ; If the result is smaller then the current smallest value the result becomes the smallest value.
    mov         edi,        esi                     ; Save the index of the smallest value.
prepare_next:
    inc         esi                                 ; Increment the array-index.
    loop        check_next                          ; Check the next array-element.
    ; -------------------------------------------------------------------------------------------------------------------
    mov         eax,        dword[nums + 4 * edi]   ; Use the index of the nearest element to get the value. Then print it to stdout.
    call        print_eax                           ; Print to stdout. Function provided by the tutor.
    ; Exit the process:
    push        0
    call        [ExitProcess]

include 'training.inc'

I've tried it with different compare-values and it provided the expected value every time. So I guess it's generally correct. Nevertheless I'm not completely satisfied. I have used a lot of register.

How can I reduce the number of register? I have found a solution for the problem with getting negative values when subtracting a larger number from a smaller number. It works but it isn't elegant. Is there a better solution?


texts: High execution time on number partitioning program in Python 2.7

texts:
I am writing a program to count only the partitions of a number with distinct parts.
I am using a bottom-up approach to dynamic programming to generate partition lists from previously obtained partition lists. I think my program runs correctly, as I have tested for some inputs and verified from OEIS. But it's extremely slow for n>15. I think my algorithm has a complexity currently north of O(n^3), but I couldn't think of a better way to do it. Can anyone help with making it faster?

# Logic - The partition of a number 'n', will be 1 + the partition of 'n-1', 2 + the partition of 'n-2', and so on.
# So we start from 1, and build partition lists based on previously gotten partitions
# The loop doesn't have to go all the way till 1.
# For example, for 6, we only have to go till 'n-3' and stop, because after that, we only get duplicate lists. This is not to say that we don't get
# duplicates before, but after 'n-3', we get JUST duplicates
# So we only have to go till n-x >= x

from collections import Counter
compare = lambda x, y: Counter(x) == Counter(y)

def make_partitions(n):
    # Bottom up approach starts at 1 and goes till n, building on partitions already obtained

    # partitions dictionary contains list of lists of partitions
    # Ex - 1: [[1]]
    # Ex - 2: [[2], [1,1]]
    # Ex - 3: [[3], [2,1], [1,1,1]]
    partitions = {}
    start = 1
    while start <= n:
        partitions[start] = []
        # Appending the number itself as a partition of length 1
        partitions[start].append([start])

        # prev stores the number currently being used to build the partition list
        prev = start - 1
        # pp stores all partition lists obtained so far for the current number
        pp = []

        while prev >= start-prev:
            # curr_partitions stores the partition lists that make up the desired number, FROM the current number
            # Ex - for desired number 6, in first loop, it stores those lists which make up 6 from those of 5; in the second loop, from those of 4 and so on
            curr_partitions = []
            prev_partitions = partitions[prev]
            for p in prev_partitions:
                q = list(p)
                q.append(start-prev)

            # self-explanatory. compare function is used to see if the list already exists
            does_exist_already = False
            for ppp in pp:
                if compare(q, ppp):
                    does_exist_already = True
            if not does_exist_already:
                curr_partitions.append(q)

        # We have got the entire list of partitions that make up the desired number FROM the current number, so we add to the dictionary
        partitions[start].extend(curr_partitions)
        prev -= 1
        pp.extend(curr_partitions)
    start += 1
return partitions

def answer(n):
    partitions = make_partitions(n)
    req_partition_list = partitions[n]
    final_partition_list = []
    count = 0

    # This for loop is to weed out lists which contain duplicate values
    for p in req_partition_list:
        c = Counter(p)
        if all(v==1 for v in c.values()):
            final_partition_list.append(p)
            count += 1
    return count

if __name__ == '__main__':
    n = int(raw_input())
    print answer(n)


texts: Optimise nested loops used to compare champions which have abilities which have effects

texts:
I'm creating a counter picker for a game called League of Legends, and for this I need to compare effects of abilities, which each champion has. For this I'm using 4 lists of champions, the returnList, the banned champion list, the enemy champions list, annd the allied champion lists.

However, seeing that the returnlist, where the champions get there points, contains around 120 instances, which all have 5 abilities, which in turn have around 5 effects each, I feel that my current solution of nesting foreach loops might be really slow.

I was wondering how I could best optimise this

foreach (CounterChampion champion1 in enemyList)
{
    foreach (CounterAbility ability1 in champion1.Abilities)
    {
        foreach (string effects1 in ability1.Effects)
        {
            foreach (CounterChampion champion2 in returnList)
            {
                foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))
                {
                    if (CounterEffectExists(effects2, effects1, CounterEffect.EffectType.Counters))
                    {
                        champion2.AddPoints(1);
                    }
                    if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.Counters))
                    {
                        champion2.AddPoints(-1);
                    }
                }
            }
        }
    }
}
foreach (CounterChampion champion1 in banList)
{
    foreach (CounterAbility ability1 in champion1.Abilities)
    {
        foreach (string effects1 in ability1.Effects)
        {
            foreach (CounterChampion champion2 in returnList)
            {
                foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))
                {
                    if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.Counters))
                    {
                        champion2.AddPoints(1);
                    }
                }
            }
        }
    }
}
foreach (CounterChampion champion1 in allyList)
{
    foreach (CounterAbility ability1 in champion1.Abilities)
    {
        foreach (string effects1 in ability1.Effects)
        {
            foreach (CounterChampion champion2 in returnList)
            {
                foreach (string effects2 in champion2.Abilities.SelectMany(ability2 => ability2.Effects))
                {
                    if (CounterEffectExists(effects2, effects1, CounterEffect.EffectType.WorksWith))
                    {
                        champion2.AddPoints(1);
                    }
                    if (CounterEffectExists(effects1, effects2, CounterEffect.EffectType.WorksWith))
                    {
                        champion2.AddPoints(1);
                    }
                }
            }
        }
    }
}
returnList.Sort(
    delegate (CounterChampion c1,
    CounterChampion c2)
    {
        return c1.GetPoints().CompareTo(c2.GetPoints()) * -1;
    }
);
return returnList;


texts: Proper use of type_info in relation to mapping components to a type

texts:
I'm trying to map a components type to the component value itself in a map. The following code all works properly. My main question is this. Is storing the map key as std::type_info* the best way to accomplish what I'm doing? I'm also not digging the ugly static_cast<T*> I'm doing during the usage part.

Entity.h

#pragma once
#include "IComponent.h"
#include <map>
#include <typeinfo>

class Entity
{
public:
    Entity(void);
    ~Entity(void);
    void AddComponent(IComponent* component);
    IComponent* GetComponent(const std::type_info* typeInfo);
private:
    std::map<const std::type_info*, IComponent*> components;
};

Entity.cpp

#include "Entity.h"

Entity::Entity(void)
{
}

Entity::~Entity(void)
{
    for (auto &mapValue : components)
    {
        delete mapValue.second;
    }
}

void Entity::AddComponent(IComponent* component)
{
    const type_info* info = &typeid(*component);
    components.insert (std::pair<const std::type_info*,IComponent*>(info, component));
}

IComponent* Entity::GetComponent(const std::type_info* typeInfo)
{
    return components.at(typeInfo);
}

Example Usage

IComponent* baseComponent = entity->GetComponent(&typeid(PerkList));
PerkList* perkList = static_cast<PerkList*>(baseComponent);


texts: Getting UI Buttons to move across the screen for a nice effect using HaxeFlixel

texts:
I'll start off by saying I'm way off in how this should be done. After spending much time on getting this to be clean it wasn't going to happen so I just did it anyway I could.

I'm trying to make some FlxStates that will show off some nice menus that I want to create. What I'm doing in this code is moving UI buttons from off the screen to their final position.

What I tried to do in this class was take the button and place it in my own custom Class that would hold all the needed information so that it would be easy to read. Instead I needed to put everything in the MenuState2 because I needed the _btnMenu1 to have the callback call clickMenu1(). If I didn't create the button in MenuState2 then I couldn't use the callback.

MenuState2:

package;

import flixel.FlxG;
import flixel.FlxObject;
import flixel.FlxState;
import flixel.math.FlxPoint;
import flixel.text.FlxText;
import flixel.ui.FlxButton;

class MenuState2 extends FlxState
{
    var _organizer:ObjectOrganizer;

    private var _txtTitle:FlxText;

    //One button
    private var _btnMenu1:FlxButton;
    private var _btnMenu1FinalPosistion:FlxPoint;
    private var _btnMenu1Flag:Bool;

    override public function create():Void
    {
        _organizer = new ObjectOrganizer();

        _txtTitle = new FlxText(0,0, "Slide Right", 27);
        _organizer.positionObjectInCenter(_txtTitle);
        add(_txtTitle);

        _btnMenu1FinalPosistion = new FlxPoint(0,0);//Init FlxPoint
        _btnMenu1 = new FlxButton(0,0, "Main Menu", clickMenu1);//Init FlxButton
        _organizer.positionObjectInCenter(_btnMenu1);//Use helper class to layout buttons

        _btnMenu1FinalPosistion = _organizer.trackFinalPosition(_btnMenu1);//Find buttons final position
        _btnMenu1.x = 0 - _btnMenu1.width;//Move Button off screen
        _btnMenu1Flag = false;//Mark button dirty to allow update() to move it
        add(_btnMenu1);

        super.create();
    }

    override public function update(elapsed:Float):Void
    {
        if (_btnMenu1Flag == false) {//Check to see if we should move button
            _btnMenu1.x = _btnMenu1.x + (600 * elapsed);//Move button
            if (_btnMenu1.x >= _btnMenu1FinalPosistion.x) {//Check to see if we should stop moving button
                _btnMenu1.x = _btnMenu1FinalPosistion.x;//Correct for overshoot
                _btnMenu1Flag = true;//Button is clean
        }
    }
    super.update(elapsed);
    }

    private function clickMenu1():Void {
        FlxG.switchState(new MenuState1());
    }
}

ObjectOrganizer:

import flixel.FlxG;
import flixel.FlxObject;
import flixel.math.FlxPoint;

class ObjectOrganizer extends FlxG{
    var numberOfItems:Int = 1;
    var amountOfSpaceBetweenObjects:Float = 40;

    public function new() {

    }

    public function positionObjectInCenter(item:flixel.FlxObject):Void {
        var screenWidth = FlxG.width;
        //Check to see if designer has changed placement of object
        //Changed placement indicates a desire to place the object by hand and should be left alone
        if (item.x == 0) {
            item.x = (screenWidth / 2) - (item.width / 2);
        }
        if (item.y == 0) {
            item.y = numberOfItems * amountOfSpaceBetweenObjects;
        }
        if (item.x != 0 || item.y != 0) {
            numberOfItems ++;
        }
        // add(item);
    }

    public function trackFinalPosition(obj:FlxObject):FlxPoint {
        var finalPosition = new FlxPoint(0,0);
        finalPosition.x = obj.x;
        finalPosition.y = obj.y;
        return(finalPosition);
    }
}

I picked up HaxeFlixel because it was more programming centric and I to learn how to code this myself rather then have Unity or Game Maker do it for me.


texts: LeetCode: Divide Array in Sets of K Consecutive Numbers C#

texts:
https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/

  Given an array of integers nums and a positive integer k, find whether
  it's possible to divide this array into sets of k consecutive numbers
  Return True if its possible otherwise return False.

Example 1:

Input: nums = [1,2,3,3,4,4,5,6], k = 4
Output: true
Explanation: Array can be divided into [1,2,3,4] and [3,4,5,6].

Example 2:

Input: nums = [3,2,1,2,3,4,3,4,5,9,10,11], k = 3
Output: true
Explanation: Array can be divided into [1,2,3] , [2,3,4] , [3,4,5] and [9,10,11].

Example 3:

Input: nums = [3,3,2,2,1,1], k = 3
Output: true

Example 4:

Input: nums = [1,2,3,4], k = 3
Output: false
Explanation: Each array should be divided in subarrays of size 3.

Constraints:

1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
1 <= k <= nums.length

Please review for performance.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ArrayQuestions
{
    /// <summary>
    /// https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers/
    /// </summary>
    [TestClass]
    public class DivideArrayinSetsofKConsecutiveNumbersTest
    {
        [TestMethod]
        public void TestExample()
        {
            int[] nums = {1, 2, 3, 3, 4, 4, 5, 6};
            int k = 4;
            Assert.IsTrue(DivideArrayinSetsofKConsecutiveNumbers.IsPossibleDivide(nums, k));
        }

        [TestMethod]
        public void TestFailed()
        {
            int[] nums = { 1, 2, 3,4};
            int k = 3;
            Assert.IsFalse(DivideArrayinSetsofKConsecutiveNumbers.IsPossibleDivide(nums, k));
        }
    }

    public class DivideArrayinSetsofKConsecutiveNumbers
    {
        public static bool IsPossibleDivide(int[] nums, int k)
        {
            if (nums.Length % k != 0)
            {
                return false;
            }

            var dict = new SortedDictionary<int, int>();
            foreach (var num in nums)
            {
                if (!dict.TryGetValue(num, out var value))
                {
                    value = dict[num] = 0;
                }

                dict[num] = value+1;
            }

            for (int i = 0; i < nums.Length / k; i++)
            {
                int start = dict.FirstOrDefault(x=>x.Value >0).Key;
                dict[start]--;
                for (int j = 1; j < k; j++)
                {
                    if (!dict.ContainsKey(start + j) || dict[start + j] < 1)
                    {
                        return false;
                    }

                    dict[start + j]--;
                }
            }

            return true;
        }
    }
}


texts:
The program takes 2 decimals as input and an operator (+, -, *, /, ^) so far. Any suggestions to make this code cleaner or shorter?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a number: ");
            Decimal n1 = Convert.ToDecimal(Console.ReadLine());

            Console.Write("Enter an operator: ");
            string op = Console.ReadLine();

            Console.Write("Enter a number: ");
            Decimal n2 = Convert.ToDecimal(Console.ReadLine());

            if (op == "+")
            {
                Console.WriteLine(Sum(n1, n2));
                Console.ReadLine();
            }

            else if (op == "-")
            {
                Console.WriteLine(Dif(n1, n2));
                Console.ReadLine();
            }

            else if (op == "*")
            {
                Console.WriteLine(Prod(n1, n2));
                Console.ReadLine();
            }

            else if (op == "/")
            {
                Console.WriteLine(Div(n1, n2));
                Console.ReadLine();
            }

            else if (op == "^")
            {
                Console.WriteLine(Pow(n1, n2));
                Console.ReadLine();
            }

            else
            {
                Console.WriteLine("Invalid Operator! Only '+', '-', '*', '/', or '^' allowed.");
                Console.ReadLine();
            }
        }

        static Decimal Sum(Decimal n1, Decimal n2)
        {
            Decimal sum;
            sum = n1 + n2;
            return sum;
        }

        static Decimal Dif(Decimal n1, Decimal n2)
        {
            Decimal dif;
            dif = n1 - n2;
            return dif;
        }

        static Decimal Prod(Decimal n1, Decimal n2)
        {
            Decimal prod;
            prod = n1 * n2;
            return prod;
        }

        static Decimal Div(Decimal n1, Decimal n2)
        {
            Decimal div;
            div = n1 / n2;
            return div;
        }

        static Decimal Pow(Decimal n1, Decimal n2)
        {
            Decimal pow;
            pow = (decimal)Math.Pow((double)n1, (double)n2);
            return pow;
        }
    }
}


texts:
This my implementation of the Merge Sorting Algorithm:

def merge(series1, series2):
    output = []
    while series1 != [] or series2 != []:
        if series1 == []:
            output.append(series2[0])
            series2.pop(0)
            continue
        if series2 == []:
            output.append(series1[0])
            series1.pop(0)
            continue
        last1 = series1[0]
        last2 = series2[0]
        if last1 <= last2:
            series1.pop(0)
            output.append(last1)
            continue
        if last2 < last1:
            series2.pop(0)
            output.append(last2)
            continue
    return output

def is_even(x):
    if x%2 == 0:
        return True
    return False

def merge_sort(series):
    iseries = []
    for i in series:
        iseries.append([i])
    while len(iseries) > 1:
        output = []
        length = len(iseries)
        if not is_even(length):
            length -= 1
            for i in range(0, (length-1), 2):
                a = iseries[i]
                b = iseries[i+1]
                output.append(merge(a, b))
            output.append(iseries[-1])
        else:
            for i in range(0, (length-1), 2):
                a = iseries[i]
                b = iseries[i+1]
                output.append(merge(a, b))
        iseries = []
        iseries += output
    return iseries[0]

Basically it splits the items in the initial series into lists of one item (series to iseries). Then I merge the items two-by-two appending the new items to another list (output), and set the main series equals to output. I do this until it's 1 item only and return the 1st item (return iseries[0]).


texts:
I've decided to reproduce the JQuery selector - specifically for finding elements by class name, ID, and tag

So for example the tests could be written like

$('.box') === domSelector('.box') // Class
$('#box') === domSelector('#box') // ID
$('input') === domSelector('input') // Tag

Here is my approach to the problem. It works good, and I'd like to hear the ideas to simplify it or improve it in any way.

var domSelector = function(selectors) {
  if (selectors.startsWith('.')) {
    return Array.from(document.getElementsByClassName(selectors.substring(1)));
  }
  else if (selectors.startsWith('#')) {
    return [document.getElementById(selectors.substring(1))];
  }
  else if (!/^[a-zA-Z0-9!@#\$%\^\&*\)\(+=._-]+$/g.test(selectors)) {
    throw Error('Invalid Selector');
  }
  else {
    return Array.from(document.getElementsByTagName(selectors));
  }
};

1st If - Check if passed value is class. (if it starts with a dot, it is a class)
2nd If - Check if a passed value is an ID (if it starts with #, it is an ID)
3rd If - Now since I already checked for both characters # and dot , I check if passed value starts with special character (Remember that it cannot start with dot or # as I already did that check). If it starts with a special character - I throw an exception that identifier is not in a valid format
4th If - The only left option is that element is tag. No further check needs to be done as if selector doesn't match any tags it will return an empty array.


texts:
How can this be optimized?

char *crunch(char *s)
{
  char *temp,buff[MAX];
  int repeat,count,i,j,k;

  if (*s == '\0')
    return NULL;
  temp = (char*)malloc((strlen(s) + 1) * sizeof(char));
  if (isdigit(*s))
    return NULL;
  repeat = 0;
  for (i = 0, j = 0;i < strlen(s);)
  {
    temp[j++] = s[i++];
    count = 1;
    while (s[i] == s[i - 1])
    {
      count++;
      i++;
      repeat = 1;
    }
    if (isdigit(s[i]) && repeat == 1)
      return NULL;
    if (isdigit(s[i]) && count != 1)
      return NULL;
    else if (isalpha(s[i]) && count != 1)
    {
      temp[j++] = count + 48;
    }
    else if (isdigit(s[i]))
    {
      for (k = 1;k < (s[i] - 48);k++)
        temp[j++] = s[i - 1];
      i++;
    }
  }
  temp[j] = '\0';
  return temp;
}

Examples:

Input: "aabbccdef"
Output: "a2b2c2def"

Input: "a4bd2g4"
Output: "aaaabddgggg"


texts: Print diagonal numbers of matrix in ascending order

texts:
Today I attempted an interview problem:

  Q: An n×n matrix contains numbers from 1 to n×n and is generated in the
  fashion:

  The first row is of numbers starting from 1 to n left to right, Second row is from n+1 to 2n right to left, 3rd row is from 2n+1 to 3n left to right and so on.

  Example n = 4

  Matrix would look something like

 1  2  3  4
 8  7  6  5
 9 10 11 12
16 15 14 13

  Diagonal elements: 1, 4, 6, 7, 10, 11, 13, 16.

Wrote this code, got an feedback as space and time complexity could be further improved.
How to improve it?

def create_matrix(n):
    mat = []
    num = 1
    reverse_flag = True
    for i in range(n):
        row = []
        reverse_flag = False if reverse_flag else True
        for j in range(n):
            row.append(num)
            num += 1
        if reverse_flag:
            row.reverse()
        mat.append(row)
    print_matrix(mat, n)

def print_matrix(mat, n):
    reverse_flag = True
    for i in range(n):
        reverse_flag = False if reverse_flag else True
        if reverse_flag:
            if i == n-1-i:
                print mat[i][i]
            else:
                print mat[i][n-1-i], mat[i][i]
        else:
            if i == n-1-i:
                print mat[i][i]
            else:
                print mat[i][i], mat[i][n-1-i]

create_matrix(4)


texts:
How can I optimize checking a value in recursion before operating on it? I'm using Array.indexOf (this is Javascript)

var nums = [], lengths = [];
function findNumLength(n) {
    //preliminary check to see if
    //we've done this number before
    var indexOf = nums.indexOf(n);
    if(indexOf !== -1) {
        return lengths[indexOf];
    }
    function even (n2) { return n2%2===0; }
    if(n===1) {
        return 1;
    }
    if(even(n)) {
        l = findNumLength(n/2) + 1;
        if(indexOf===-1) {
            lengths.splice(0,0 ,l);
            nums.push(n);
        }
        return l;
    }
    else {
        l = findNumLength(3*n + 1) + 1;
        if(indexOf===-1){
            lengths.splice(0,0,l);
            nums.push(n);
        }
        return l;
    }
}

(note: I've answered my own question with one solution I've found; it is by no means the only solution (though it may be the best. I don't know). Please, still answer.)


texts: Reading and processing a file using Pandas

texts:
I am trying to read a file using pandas and then process it. For opening the file I use the following function:

import os
import pandas as pd

def read_base_file(data_folder, base_file):
    files = map(lambda x: os.path.join(data_folder, x), os.listdir(data_folder))
    if base_file in files:
        try:
            df = pd.read_csv(base_file, na_values=["", " ", "-"])
        except Exception, e:
            print "Error in reading", base_file
            print e
            df = pd.DataFrame()

    else:
        print "File Not Found."
        df = pd.DataFrame()
    return df

My main concerns are the if statement and what I should return if there is an error.


texts: Optimised Python Code gives TLE for PRIME1

texts:
PRIME1 is a codechef problem which states:

  Shridhar wants to generate some prime numbers for his cryptosystem.
  Help him! Your task is to generate all prime numbers between two given
  numbers.

  Input

  The first line contains t, the number of test cases (less then or
  equal to 10). Followed by t lines which contain two numbers m and n (1
  <= m <= n <= 1000000000, n-m<=100000) separated by a space.

  Output

  For every test case print all prime numbers p such that m <= p <= n,
  one number per line. Separate the answers for each test case by an
  empty line.

I have optimised my code according to suggestions given here. But, my edits were rolled back when I tried to post my optimised code. So, I am still getting a TLE error and I don't understand why. Help me optimise this code further:

import math
def sieve_basic_list(list_prime):
    max_n=10**9
    m = int(math.sqrt(max_n))
    lim = int(math.sqrt(m))+1
    arr = [True]*(m+1)
    arr[0]=arr[1]=False

    #Calculate primes upto m only so loop runs sqrt(m) times.
    for x in xrange(2,lim):
        if arr[x]==False:
            continue
        for i in xrange(x*x,m+1,x):
            arr[i]=False
    for i,each in enumerate(arr):
        if each:
            list_prime.append(i)

def mnsieve(list_prime):
    #program tc input and mnrange calc
    for _ in xrange(int(raw_input().strip())):
        m,n = map(int,raw_input().split())
        mnrange = [True]*(n-m+1)
        mnrange[0] = False if m==1 else True
        for each in list_prime:
            firstfactor = ((m-1)/each)*each #firstfactor nearest to m i.e firstfactor-m gives index
            for x in xrange(firstfactor,n+1,each):
                try:
                    if x not in list_prime:
                        mnrange[x-m]=False
                except:
                    pass
        for i,each in enumerate(mnrange):
            if each:
                print i+m
        print

list_prime=[]
sieve_basic_list(list_prime)
mnsieve(list_prime)


texts: Best approach for the Design Pattern for multiple schedulers using interface and abstract class

texts:
I have a requirement to fetch data for different types of Users (Customers, Publishers etc) for three different timelines (retro, current, and past), all have different URLs. There is a scheduler which will run at the different interval (for example 2 minute for retro data, 5 minutes for current data and 10 minutes for Future Dated Data). I have attached an image for better understanding.

 interface IDataPublisher {
   void GetUrl();
   void Publish();
 }

  interface ITimeLineGrabber {
     TimeSpan GetTimeSpanForNextRun();
  }

 abstract class BasePublisher : IDataPublisher, ITimeLineGrabber, BackgroundService
 {
    private readonly ILogger<BasePublisher> _logger;
    public BasePublisher (ILogger<BasePublisher> logger)
    {
        _logger = logger;
    }

    public abstract string GetUserType();
    public abstract string GetDataType();
    public abstract TimeSpan GetTimeSpanForNextRun();
    public abstract string GetUrl();

    public override async Task StartAsync(CancellationToken cancellationToken)
    {
      await base.StartAsync(cancellationToken);
    }

    public override async Task StopAsync(CancellationToken cancellationToken)
    {
      await base.StopAsync(cancellationToken);
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
      var userType = GetUserType();
      var dataType = GetDataType();
      TimeSpan timeSpan = GetTimeSpanForNextRun();

      while (!stoppingToken.IsCancellationRequested)
      {
            try
            {
                // Do Something with userType and dataType
                await Task.Delay(timeSpan , stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error - {ex.Message}", DateTimeOffset.Now);
            }
        }
   }

  public sealed class CustomerRetroPublisher: BasePublisher
  {
    public override string GetUserType()
    {
       return "Customer";
    }

    public override string GetDataType()
    {
      return "Retro";
    }

    public override Timespan GetTimeSpanForNextRun()
    {
      return Timespan.FromMinutes(2); // read from config file..
    }

    public override string GetUrl()
    {
       return "CustomerRetroUrl";
    }
  }

but this will end up with 12 different classes and loads of code will be duplicated/ over complicated. I have a feeling there must be a simple approach to all this. Just wondering what could be the best approach for my requirement.


texts:
During the past few days, I played around a bit with an SVG file, trying to minimize its size. One thing I stumbled upon was this transformation:

<path d="..." transform="translate(186 188) rotate(-63) scale(41)" />

I had forgotten everything I ever knew about affine transformations, therefore I didn't know how to combine them into a single transformation matrix. Two days later, I had this program:

public enum AffineTransformations {
    ;

    public static void main(String[] args) {
        System.out.println(new Transformer()
                .translate(186, 188)
                .rotate(63)
                .scale(41));
    }

    static class Transformer {

        private double a = 1, b, c, d = 1, e, f;

        public Transformer scale(double x) {
            a *= x;
            b *= x;
            c *= x;
            d *= x;
            return this;
        }

        public Transformer translate(double x, double y) {
            e += a * x + c * y;
            f += b * x + d * y;
            return this;
        }

        public Transformer rotate(double deg) {
            double alpha = deg * Math.PI / 180.0;
            double sin = StrictMath.sin(alpha);
            double cos = StrictMath.cos(alpha);
            double aa = a, bb = b, cc = c, dd = d;
            a = aa * cos - cc * sin;
            b = bb * cos - dd * sin;
            c = aa * sin + cc * cos;
            d = bb * sin + dd * cos;
            return this;
        }

        @Override
        public String toString() {
            return String.format("matrix(%s %s %s %s %s %s)",
                    rd(a), rd(b), rd(c), rd(d), rd(e), rd(f));
        }

        private double rd(double x) {
            return Math.floor(1000 * x + 0.5) / 1000;
        }
    }
}

It provides a minimalistic API to combine arbitrary scalings, rotations and translations. It outputs a transformation matrix suitable to be inserted into an SVG file.

Having 3 decimal places seemed enough to me for use in SVGs, therefore the rounding. I chose half-up rounding instead of half-even since I was annoyed some days ago by the Android renderer that uses half-even rounding, which created some visual artifacts (the coordinates 1.5 and 2.5 map to the same screen coordinate, even though their distance is 1.0).

I started the above code by copying a standard matrix multiplication routine, but then I thought about the many zeroes and ones that are involved in the matrixes, so I inlined all calculations to avoid the useless multiplications by 1.0 and 0.0. Now there's hardly anything left to inline. This optimization was just for fun rather than because of an actual need.

The short variable names follow the SVG specification.

Anything else left to criticize?


texts: Initializing an array of relative coordinates of all adjacent 2D matrix cells

texts:
The program should output this:

_1 _1
_1  0
_1  1
 0 _1
 0  1
 1 _1
 1  0
 1  1

Currently I have this code:

(4 ~: i.9) # (3 # i:1) ,. 9 $ i:1

But I think it can be better.


texts: Copy and in-place transformation of strings to lowercase/uppercase

texts:
I have the following code that transforms a string to upper/lowercase:

#include <iterator>
#include <algorithm>
#include <type_traits>
#include <vector>
#include <vector>
#include <iostream>
#include <string>
#include <locale>
#include <functional>

namespace ae
{
    template <typename StrT>
    auto toLower(StrT& str)
    {
        std::transform(str.begin(), str.end(), str.begin(), [](const auto& c)
        {
            static const auto loc{ std::locale() };
            return std::tolower(c, loc);
        });
    }

    template <typename StrT>
    auto toUpper(StrT& str)
    {
        std::transform(str.begin(), str.end(), str.begin(), [](const auto& c)
        {
            static const auto loc{ std::locale() };
            return std::toupper(c, loc);
        });
    }

    template <typename StrT>
    auto toLowerCopy(StrT& str)
    {
        auto newStr{ str };
        std::transform(str.begin(), str.end(), newStr.begin(), [](const auto& c)
        {
            static const auto loc{ std::locale() };
            return std::tolower(c, loc);
        });
        return newStr;
    }

    template <typename StrT>
    auto toUpperCopy(StrT& str)
    {
        auto newStr{ str };
        std::transform(str.begin(), str.end(), newStr.begin(), [](const auto& c)
        {
            static const auto loc{ std::locale() };
            return std::toupper(c, loc);
        });
        return newStr;
    }
}

// Example usage
int main()
{
    std::wstring my_str{ L"Test" };
    ae::toLower(my_str);
    std::wcout << my_str << std::endl;

    std::string my_str2{ "This is a test aswell" };
    auto new_str{ ae::toUpperCopy(my_str2) };
    std::cout << new_str << std::endl;

    return 0;
}

All of the 4 functions are pretty much exact copies of each other, just minor variations. I dont want to repeat myself in this way, but im unsure how to make one function that does all of this functionality. How can I improve the code?


texts: Implementation of insertion sort in JavaScript

texts:
I have written an insertion sort algorithm in JavaScript:

function insertionSort(inputArray){
  var totalElements = inputArray.length - 1;
  var temp = 0;
  var lastIndex = 0;
  var prevIndex = 0;
  for(var i = 0; i <= totalElements; i++){
    for(var currentIndex = i; currentIndex > lastIndex; currentIndex--){
        prevIndex = currentIndex - 1;
        if(inputArray[currentIndex] < inputArray[prevIndex]){
            temp = inputArray[currentIndex];
            inputArray[currentIndex] = inputArray[prevIndex];
            inputArray[prevIndex] = temp;
        }else{
            break;
        }
    }

  }

  return inputArray;
}

console.log(insertionSort([1,31,26,4,3,12]));
console.log(insertionSort([5,6,1,2,3,4]));

The output is also proper:

rahul@rahul:~/myPractise/Algo$ node sorting.js
[ 1, 3, 4, 12, 26, 31 ]
[ 1, 2, 3, 4, 5, 6 ]
rahul@rahul:~/myPractise/Algo$

Can this be further improved?


texts: Need a feedback on my Javascript code and app implementation idea

texts:
I'm new into Javascript, and I'm not sure that is a good approach. The code works, and does what I need it to do but I'm sure I didn't do the things the right way.

Can you give me feedback about the implementation idea and code?

So, let's say that in index.html I have the following code into body section.

<script type="text/javascript" src="js/main.js" language="javascript"></script>

The content of the main.js file is the following:

document.write('<script language="javascript" type="text/javascript" >');

function loaded() {
}

loaded();
document.write('</script>');

I know that using document.write it is not a smart thing at all. I'm sure that other things are faulty, but I'm newbie and I'm looking for your feedback.


texts:
This is a comment system that I wrote, is it secure?

<!doctype html>

<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<?PHP

//Turn off error reporting (Not Necessary)
    error_reporting(E_ALL ^ E_NOTICE);

//Connect to the database
    if (!@mysql_connect('localhost', 'user', '') or !@mysql_select_db('comments')) {
        die('Could not connect, please check back later.');
    }

//Variables
    $guest_name = htmlentities(str_replace(' ', '',$_POST['guest_name']));
    $comment = htmlentities($_POST['comment']);
    $time = date('g:i A', time());
    $date = date('n/j/Y');
    $query = "INSERT INTO `user_comments` VALUES(
        '".mysql_real_escape_string('')."',
        '".mysql_real_escape_string($guest_name)."',
        '".mysql_real_escape_string($comment)."',
        '".mysql_real_escape_string($date)."',
        '".mysql_real_escape_string($time)."'
        )";
    $array_query = mysql_query("SELECT * FROM `comments` ORDER BY `ID` DESC");

//Insert comment into the database
    if (isset($_POST['submit_comment']) && !empty($comment) && !empty($guest_name)) {
        if(mysql_query($query)) {
            header('Location: index.php');
        }
    }

//Check if user has filled in all fields
    if (isset($_POST['submit_comment']) && empty($guest_name)) {
        echo '*Please enter a Guest Name*
';
    }

    if (isset($_POST['submit_comment']) && empty($comment)) {
        echo '*Please enter a Comment*';
    }

//List comments
    function list_comments () {
        $query = "SELECT * FROM `user_comments` ORDER BY `ID` DESC";
        $query_run = mysql_query($query);
        while ($result = mysql_fetch_array($query_run)) {
            echo '
' . $result['Guest Name'] . ' - ' . $result['Date'] . ' - ' . $result['Time'] . '
' . $result['Comment'] . '

';
        }
    };

?>
<title>Main_Page</title>

<form method="post" action="index.php">

    <input type="text" name="guest_name" maxlength="15" placeholder="Guest Name">

    <textarea cols="70" rows="5" name="comment" maxlength="512" placeholder="Comment"></textarea>
    <input type="submit" name="submit_comment">

</form>

Comments

<?PHP

    list_comments();

?>


texts: A function that moves a tile in the game of fifteen

texts:
I've created a a function that will move a tile that a user specifies within the game board.

The game board can be from 3*3 up to 9*9 and is filled with values 1 to d - 1.
This function is called within another function that keeps track of "space" array and the 2d "board"array.

This function works however, I feel that I might be using too many constants? How can I make this better?

/**
* If tile borders empty space, moves tile and returns true, else
* returns false.
*
* @param   int     tile    The tile the user wants to move
* @param   int[]   space   Space keeps track of where the space is on the board
* @return  bool
*/
bool move(int tile, int space[])
{
  //check the tile to the left of the space tile so we can swap the space tile with the tile the user wanted
  if ( board[ space[0] ][ space[1] + 1 ] == tile ) {

    board[ space[0] ][ space[1] + 1 ] = 0;

    board[ space[0] ][ space[1] ] = tile;
    space[1]++;

    return true;

  //check the tile to the right of the space tile so we can swap the space tile with the tile the user selected
  }else if ( board[ space[0] ][ space[1] - 1] == tile ) {

    board[ space[0] ][ space[1] - 1 ] = 0;

    board[ space[0] ][space[1] ] = tile;
    space[1]--;

    return true;

  //check the tile to the top of the space tile so we can swap the space tile with the tile the user selected
  }else if ( board[ space[0] + 1 ][ space[1] ] == tile ) {

    board[ space[0] + 1 ][ space[1] ] = 0;

    board[ space[0] ][space[1] ] = tile;
    space[0]++;

    return true;

  //check the tile to the bottom of the space tile so we can swap the space tile with the tile the user selected
  }else if ( board[ space[0] - 1 ][ space[1] ] == tile ) {

    board[ space[0] - 1 ][ space[1] ] = 0;

    board[ space[0] ][space[1] ] = tile;
    space[0]--;

    return true;

  } else {
    //the tile does not border the space tile
    return false;
  }
}


texts: Workaround for the precision limitation for Python's round() function

texts:
I'm trying to come up with a general way to correctly round floats with Python, given the known limitation of round():

  Note: The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. This is not a bug: it’s a result of the fact that most decimal fractions can’t be represented exactly as a float. See Floating Point Arithmetic: Issues and Limitations for more information.

I thought that a simple way to correct for this effect is to add a small value to every float that ends with a 5, like so:

a = 7.85
b = a + 0.001
round(b, 1)
> 7.9

Below is the function I've written to do this. I've tested it and it seems to work fine, but I'd like some input on possible caveats I might be overlooking (or ways to improve it)

import numpy as np
from decimal import Decimal
from random import randint

def floats_5(N):
    """
    Generate random floats between a random range, where all floats
    end with a '5'.
    """
    rang = randint(1, 10000)
    flts = np.random.uniform(-1.*rang, 1.*rang, N)

    # Add '5' to the end of each random float, with different lengths.
    fl_5 = []
    for f in flts:
        # Trim float.
        i = randint(2, len(str(f).split('.')[1]))
        # Create trimmed float that ends with a '5' .
        f = Decimal(str(f).split('.')[0] + '.' + str(f).split('.')[1][:i] +
                    '5')
        fl_5.append(f)

    return fl_5

def format_5(f):
    """
    Take float and add a decimal '1' to the end of it.

    Return the number of decimal paces and the new float.
    """
    # Count number of decimal places.
    n = len(str(f).split('.')[1])

    # Decimal '1'  to add to the end of the float.
    d = '0.' + '0'*n + '1'

    # Add or subtract depending on the sign of the float.
    c = -1. if str(f)[0] == '-' else 1.

    # New augmented float.
    new_float = f + Decimal(c)*Decimal(d)

    # Return number of decimals and float with the small value added.
    return n, new_float

# Get some random floats.
fl_5 = floats_5(10)

# Compare float, round(float), and round(new_float)
print 'Original   round(f)   round(new_f)'
for f in fl_5:
    n, new_float = format_5(f)
    print f, round(f, n-1), round(new_float, n-1), '\n'


texts: Generate String with Random Consonants and Vowels in C

texts:
Replace all c / C / v / V in stdin with lower case, upper case consonants / vowels respectively. All other input is passed through.

Anything that can be improved? Looking at maintainability first, performance second.

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

static const char lower_consonants[] = "bcdfghjklmnpqrstvwxyz";
static const char upper_consonants[] = "BCDFGHJKLMNPQRSTVWXYZ";
static const char lower_vowels[] = "aeiou";
static const char upper_vowels[] = "AEIOU";

#define RND_CHAR(str) ((str)[rand() % (sizeof(str) - 1)])

char to_char(char c)
{
    switch (c) {
    case 'c': return RND_CHAR(lower_consonants); break;
    case 'C': return RND_CHAR(upper_consonants); break;
    case 'v': return RND_CHAR(lower_vowels); break;
    case 'V': return RND_CHAR(upper_vowels); break;
    default: return c;
    }
}

int main(void)
{
    srand(time(NULL));
    for (int c; (c = getchar()) != EOF;)
        putchar(to_char(c));
    fflush(stdout);
}

Makefile:

CFLAGS:=-std=c11 -W -Wall -pedantic -O2 -g

.PHONY: all
all: wordify

.PHONY: clean
clean::
    $(RM) wordify *.[adios] *.gcda *.gcno *.gcov


texts:
Is this the correct way of chaining promises when it comes to express-validator? I am using express node and this is the endpoint for a get request

Something about it seems a bit messy, but I can't think of a cleaner way to do it.

function exitChain() {
  return Promise.reject();
}

function getUserByID(req, res) {

  const id = req.query.id;
  req.checkQuery('id', 'ID is not a number').isInt();

  const q = 'select * from users where user_id=$1';
  const p = [id];

  req.getValidationResult()
    .then(function(vRes) {
      if (!vRes.isEmpty()) {
        exitChain();
        return res.status(400).send('Validation Fail: ' + util.inspect(vRes.array()));
      }
    })
    .then(function() {
      pg.connect(postgresConfig)
        .then(function(client) {
          return client.query(q, p).execute();
        })
        .then(function(result) {
          result.client.done();
          return res.status(200).send(res.json(result.rows));
        })
        .catch(function(err) {
          console.log(err);
          return res.status(400).send('Error: ' + err);
        });
    })
    .catch(function(err) {
      console.log(err);
      return res.status(400).send('Error: ' + err);
    });
}


texts: I need to know that if everything okay in my BTS put and get method

texts:
I implement  BinaryTree  (K extends Comparable, V) concept to binarySearchTree and I have written get and put method. As far as I check, there is no problem in my code. So now I wonder that are there any problem or weak point in my code? and m,

   public void put(K key, V value) {
        Node newNode = new Node(key, value, null, null);
        Node current = root;
        if (root == null) {
            root = newNode;
            return;
        }
        while (true) {
            int cmd = key.compareTo(current.key);
            if (cmd > 0) {
                if (current.right == null) {
                    current.right = newNode;
                    break;
                } else {
                    current = current.right;
                }
            } else if (cmd < 0) {
                if (current.left == null) {
                    current.left = newNode;
                    break;
                } else {
                    current = current.left;
                }

            } else  {
                current.value = newNode.value;
                break;
            }
        }

  public V get(K key)  {
        Node curr = root;
        if (curr == null) {
            throw new NoSuchElementException("There is no such a element");
        }
        while (true) {
            int cmd = key.compareTo(curr.key);
            if (cmd > 0) {
                curr = curr.right;
            } else if (cmd < 0) {
                curr = curr.left;
            } else {
                return curr.value;
            }
        }
    }

And i check these and it worked

   BinaryTree<Integer,String> binaryTree = new BinaryTree<Integer, String>();

        binaryTree.put(8,"8");
        binaryTree.put(4,"4");
        binaryTree.put(5,"5");
        binaryTree.put(1,"1");
        binaryTree.put(2,"2");
        binaryTree.put(3,"3");
        binaryTree.put(65,"65");
        binaryTree.put(4,"4 (2)");

        System.out.println(binaryTree.get(8));
        System.out.println(binaryTree.get(4));
        System.out.println(binaryTree.get(65));
        System.out.println(binaryTree.get(5));


texts:
How can I improve up this code?
Is it ok to write code using Invoke and Action so liberally or is this bad?

Performance is not an issue as I'm not using Invoke 50,000x in a a row (a lot of other things will be done in-between, making the performance hit null).

The primary goal is to run my list of tasks either by Item first or task first. The secondary goal is to NOT write a massively long method where each method is written out in each way they can be completed. Doing so makes adding new tasks later much easier.

Code: (Updated with pseudo extras)

public class TaskObject
{
    public bool RunPerItem = true; //PLACEHOLDER, normally derived externally from view model
    public bool RunPerTask = false; //PLACEHOLDER, normally derived externally from view model

    public Dictionary<string, Item>() TaskItems = new Dictionary<string, Item>()
    {
        { "ItemA", new Item() {} },
        { "ItemB", new Item() {} },
        { "ItemC", new Item() {} },
    }

    private List<Action<TaskObject, Item>> Tasks = new List<Action<TaskObject, Item>>()
    {
        (TO, I) => { TO.TaskA(I); },
        (TO, I) => { TO.TaskB(I); },
        (TO, I) => { TO.TaskC(I); }
    };

    public void RunTasks()
    {
        //RunPerItem & RunPerTask are type `bool`
        if (this.RunPerItem)
        {
            foreach (var I in this.TaskItems)
            {
                foreach (var T in this.Tasks)
                {
                    T.Invoke(this, I.Value);
                }
            }
        }
        else if (this.RunPerTask)
        {
            foreach (var T in this.Tasks)
            {
                foreach (var I in this.TaskItems)
                {
                    T.Invoke(this, I.Value);
                }
            }
        }
    }

    public void TaskA(Item I) { /*...*/ }
    public void TaskB(Item I) { /*...*/ }
    public void TaskC(Item I) { /*...*/ }
}

public class Item
{
    public string ItemName { get; set; }
}

Thanks for any advice/help!!!

Edit/Clarification/Extra Details:

The above code describes 2 different loops with different orders of task completion.

Example Orders:
this.RunPerItem
ItemA
-TaskA
-TaskB
-TaskC

ItemB
-TaskA
-TaskB
-TaskC

this.RunPerTask
ItemA
-TaskA

ItemB
-TaskA