texts: Edit string to concatenate word numbers in javascript

texts:
I would like to replace the string "The quick brown fox jumps over the lazy dog" with the string "The1 quick2 brown3 fox4 jumps5 over6 the7 lazy8 dog9".

Is there an cleaner, more elegant, sexier way?

String.prototype.concatWordNumber = function() {

   var myArray = this.split(' ');
   var myString = "";
   for (var i=0, len = myArray.length; i<len; i++)
   {
        myString += myArray[i]+[i+1]+ " " ;
   }
  return myString;
}

var text = "The quick brown fox jumps over the lazy dog";

console.log(text.concatWordNumber());


texts:
For studying Scala, I wrote some code to solve the Equal problem on HackerRank. But I am stuck on test case #15 due to timeout.

  Christy is interning at HackerRank. One day she has to distribute some
  chocolates to her colleagues. She is biased towards her friends and
  may have distributed the chocolates unequally. One of the program
  managers gets to know this and orders Christy to make sure everyone
  gets equal number of chocolates.

  But to make things difficult for the intern, she is ordered to
  equalize the number of chocolates for every colleague in the following
  manner,

  For every operation, she can choose one of her colleagues and can do
  one of the three things.

  She can give one chocolate to every colleague other than chosen one.
  She can give two chocolates to every colleague other than chosen one.
  She can give five chocolates to every colleague other than chosen one.

  Calculate minimum number of such operations needed to ensure that
  every colleague has the same number of chocolates.

My code is like below I will appreciate your advice to improve performance.

object EqualsTest {
  def main(args: Array[String]): Unit = {
    val numOfTestCases = readInt();
    Range(0, numOfTestCases).foreach(i => {
      val numberCount = readInt();
      var numbers = Array.ofDim[Int](numberCount)
      val inputNumbers = scala.io.StdIn.readLine().split("""\s+""")
      0.until(numberCount).foreach(i => {
        numbers(i) = inputNumbers(i).trim.toInt
      })
      // val numbers = scala.io.StdIn.readLine().split(" ").map(s => s.toInt);
      var baseLine = numbers.min
      println(calOpCount(numbers, baseLine))
    })

    def f(b: Int)(s: Int): Int = {
      val i = s - b
      if (i==0) 0
      else if (i == 1 || i == 2 || i == 5) 1
      else (i/5 + (i%5)/2 + ((i%5)%2))
    }

    def calOpCount(source: Array[Int], baseLine: Int): Int = {
       val baseLines = 0.to(baseLine)
       val result = for {i <- baseLines; f1 = f(i)(_)} yield (source.map(s => f1(s.toInt)).sum)
       result.min
    }
  }
}


texts: Stack implementation with singly linked list

texts:
The following is my implementation of a stack using a linked list.

class EmptyStackError(Exception):
    def __init__(self):
        super().__init__("Stack is empty: Invalid Operation!")

class LinkedList:
    class _Node:
        def __init__(self, data, next_node=None):
            self.data = data
            self.next_node = next_node

    def __init__(self):
        self._head = None
        self._tail = None

    def add_first(self, data):
        """ Add data to the beginning of the linked list"""
        node = self._Node(data)
        if not self._head and not self._head:
            self._head = self._tail = node
            return
        node.next_node = self._head
        self._head = node

    def add_last(self, data):
        """ Add data to the end of the linked list """
        node = self._Node(data)
        if not self._head and not self._tail:
            self._head = self._tail = node
            return
        self._tail.next_node = node
        self._tail = node

    def remove_last(self):
        """ Remove the last element in the linked list """
        if not self._head and not self._tail:  # if linked list is empty
            raise EmptyStackError
        elif self._head is self._tail:  # if only one element
            data = self._head.data  # or data of tail
            self._head = self._tail = None
            return data
        data = self._tail.data
        current = self._head
        while current.next_node.next_node:
            current = current.next_node
        current.next_node = None
        self._tail = current
        return data

    def remove_first(self):
        """ Remove the first element in the linked list """
        if not self._head and not self._tail:  # if linked list is empty
            raise EmptyStackError
        elif self._head is self._tail:  # if only one element
            data = self._head.data
            self._head = self._tail = None
            return data
        data = self._head.data
        self._head = self._head.next_node
        return data

    def __str__(self):
        if not self._head and not self._tail:
            return "Stack is empty!!"
        items = []
        current = self._head
        while current:
            items.append(current.data)
            current = current.next_node
        return " ".join([str(i) for i in items])

class Stack:
    """ A stack implementation using a linked list

    Note: The reason add_first and remove_first are using for push and pop respectively is to keep them O(1).
          If adding and removing last were used, then remove last would O(n).
          This is because deleting the tail would require the traversal of the linked list to delete the last element.
    """
    def __init__(self):
        self.items = LinkedList()

    def push(self, data):
        self.items.add_first(data)

    def pop(self):
        data = self.items.remove_first()
        return data

    def peek(self):
        data = self.items.remove_first()
        self.items.add_first(data)
        return data

    def __str__(self):
        string = self.items.__str__()
        return string

Is there anything I need to improve? whether it's style or logic.

Can you find any bugs? Whether in the linked list or the stack.

My basic tests:

import pytest

def test_push():
    """ This is depending on another method """
    stack = Stack()
    stack.push(5)
    assert stack.peek() == 5

def test_pop():
    stack = Stack()
    stack.push(5)
    data = stack.pop()
    assert data == 5

def test_empty_pop():
    stack = Stack()
    with pytest.raises(EmptyStackError):
        stack.pop()

def test_peek():
    stack = Stack()
    stack.push(5)
    assert stack.peek() == 5

def test_empty_peek():
    stack = Stack()
    with pytest.raises(EmptyStackError):
        stack.peek()

test_push()
test_pop()
test_empty_pop()
test_peek()
test_empty_peek()


texts:
class BencodeObject:

def __init__(self,filename):
    with open(filename,'rb') as diskbytes:
        self.loads(diskbytes)

def _isdictionary(self,bits): return(bits == b"d")
def _isnumber(self,bits): return(bits > b"/" and bits < b":")
def _iscolon(self,bits): return(bits == b":")
def _isint(self,bits): return(bits == b"i")
def _islist(self,bits): return(bits == b"l")
def _isend(self,bits): return(bits == b"e")
def _isnull(self,bits): return(bits == b"")

def loads(self,bcbuffer):
    tokens = []
    null = b""
    numbuffer = null # a buffer for storing number bytes
    last = []
    while True:
        atom = bcbuffer.read(1)
        if self._isdictionary(atom): last.append(atom)
        elif self._isnumber(atom):
            numbuffer += atom
        elif self._iscolon(atom):
            tokens.append(bcbuffer.read(int(numbuffer)))
            numbuffer = null
        elif self._isint(atom): last.append(atom)
        elif self._islist(atom): last.append(atom)
        elif self._isend(atom):
            char = last.pop()
            if self._isint(char):
                tokens.append(int(numbuffer))
                numbuffer = null
        else: break
    self.bytestrings = tokens
    self.trackerURL = str(self.bytestrings[1],"utf-8")

Looking for whatever input I can get.


texts:
I've created a create a console app that would:

Call a method to check an email account (I've done this step)
Convert the attachment to pdf (I've done this step)
Then once the conversion is complete wait 30 seconds
Repeat the previous 3 steps continuously

I've done Step 1 and 2 int the ProcessMailMessages() method.
The following code works but I want to know if I am on the right track or is there a better way to poll a email client?

    private static int secondsToWait = 30 * 1000;

    static void Main(string[] args)
    {
        bool run = true;
        do
        {
            try
            {
                Task theTask = ProcessEmailTaskAsync();
                theTask.Wait();
            }
            catch (Exception e)
            {
                Debug.WriteLine("
Error in Client

Exception

" + e.Message + "

" + e.StackTrace + "
 ");
            }
            GC.Collect();

        } while (run);

    }

    static async Task ProcessEmailTaskAsync()
    {
        var result = await EmailTaskAsync();
    }

    static async Task<int> EmailTaskAsync()
    {
        await ProcessMailMessages();
        await Task.Delay(secondsToWait);
        return 1;
    }

    static async Task ProcessMailMessages()
    {
        ...............................................................................
    }


texts: Optimizing runtime on finding the nth perfect power number

texts:
i was given a task to write a code to find the nth perfect power number. i wrote the following function to find that number but the runtime is long at high number (above 30).
you can assume that the input number is within the range of 1-100.
here's the code:

def perfect(n: int) -> int:
    """
    :param n: enter the n'th place perfect power num you'd like
    :return: the n'th perfect power number
    """
    powers = []
    i = 1
    for i in range(0, n**2+1):
        for k in range(0, i):
            for m in range(0, i):
                if m ** k == i:
                    powers.append(i)
                    i += 1
                    break
        if len(powers) == n:
            break
    return powers[n-1]


texts:
Based off of another SO reply by kennebec, I had problems following the code so I rewrote it to give myself a better understanding of what is being accomplished.

I would be very grateful if you could critique it or point out any problems I have caused or could modify to improve it.

Tested with IE8/9/10/11, FF, Chrome, Opera & Safari.

Original JSFiddle link
Updated with changes from thriggle JSFiddle link

function getBrowser() {
    var userAgent = navigator.userAgent,
        matched = userAgent.match(/(chrome|firefox|opera|safari|msie|trident(?=\/))\/?\s*(\d+)/i) || [],
        version,
        browser = { name: '', version: '' };

    // IE Shells; I gaurantee that you will see this with Dell branded OEM IE 11 installs.
    if(/trident/i.test(matched[1])) {
        version = /\brv[ :]+(\d+)/g.exec(userAgent) || [];

        return { name: 'Internet Explorer', version: (version[1] || '') };
    }

    // Not Chrome; at first glance this looks like a block for chrome identification, but
    // its actually Opera.
    if(matched[1] === 'Chrome') {
        version = userAgent.match(/\b(OPR|Edge)\/(\d+)/);

        if(version !== null) {
            return { name: version[1].replace('OPR', 'Opera'), version: version[2] };
        }
    }

    // The rest; Chrome, Safari, etc
    matched = matched[2] ? [matched[1], matched[2]] : [navigator.appName, navigator.appVersion, '-?'];

    if((version = userAgent.match(/version\/(\d+)/i)) !== null) {
        matched.splice(1, 1, version[1]);
    }

    browser.name = (matched[0] !== "") ? matched[0] : "Unknown";
    browser.version = (matched[1] !== "") ? matched[1] : "Unknown";

    return browser;
}


texts:
I coded a jQuery UI dialog box and want to make sure I'm using the aria accessible attributes properly.

&nbsp;
<button type="button" role="button" aria-disabled="false" title="close">close</button>

Pop-up title

Text

More Text

Lots of text

Full code


texts: Count number of even and odd numbers from input

texts:
I had to write a program that accepted five numbers from the user. Then it will display the number of odd and even numbers, and a total sum of all numbers.

#include <iostream>
using namespace std;

int main()
{
    int a;
    int b;
    int c;
    int d;
    int e;
    int sum;
    int remainder;
    int bremainder;
    int cremainder;
    int dremainder;
    int eremainder;
    int even;
    int odd;
    int total = 0;
    int Ototal = 0;

    cout << "Please enter the 5 numbers you would like calculated: \n";
    cin >> a;
    cin >> b;
    cin >> c;
    cin >> d;
    cin >> e;

    remainder = a % 2;
    bremainder = b % 2;
    cremainder = c % 2;
    dremainder = d % 2;
    eremainder = e % 2;

    sum = (a + b + c + d + e);

    if (remainder = 0)
    {
        total+=remainder;
    }
    else {
        Ototal += remainder;
    }
    if (bremainder = 0)
    {
        total += bremainder;
    }
    else {
        Ototal += bremainder;
    }
    if (cremainder = 0)
    {
        total += cremainder;
    }
    else {
        Ototal += cremainder;
    }
    if (dremainder = 0)
    {
        total += dremainder;
    }
    else {
        Ototal += dremainder;
    }
    if (eremainder = 0)
    {
        total += eremainder;
    }
    else {
        Ototal += eremainder;
    }

    cout << total << "\n";

    cout << Ototal << "\n";

    cout << sum << "\n";
    system("PAUSE");
        return 0;
}


texts:
My objective is to find out on what other subreddit users from r/(subreddit) are posting on; you can see my code below. It works pretty well, but I am curious to know if I could improve it by:
First, restricting my code so that it only considers users only once (i.e. not collect the posting history twice for the same user) and, secondly, by adding a minimum of 5 posts per user before extracting his/her info (i.e. if the user wrote less than 5 posts in his reddit life, my code would not consider him).
import praw
import pandas as data
import datetime as time

reddit = praw.Reddit(client_id = 'XXXX',
                     client_secret = 'XXXX',
                     username = 'XXXX',
                     password = 'XXXX',
                     user_agent = 'XXXX')

collumns = { "User":[], "Subreddit":[], "Title":[], "Description":[], "Timestamp":[]}

for submission in reddit.subreddit("ENTER SUBREDDIT").new(limit=100):
    user = reddit.redditor('{}'.format(submission.author))

    for sub in user.submissions.new(limit=100):
        collumns["User"].append(sub.author)
        collumns["Subreddit"].append(sub.subreddit)
        collumns["Title"].append(sub.title)
        collumns["Description"].append(sub.selftext)
        collumns["Timestamp"].append(sub.created)

collumns_data = data.DataFrame(collumns)

def get_date(Timestamp):
    return time.datetime.fromtimestamp(Timestamp)
_timestamp = collumns_data["Timestamp"].apply(get_date)
collumns_data = collumns_data.assign(Timestamp = _timestamp)

collumns_data.to_csv('DataExport.csv')


texts: Multiple functions to run SQLite queries and save the output to a variable

texts:
I am building an Android quiz app. I want to display a progress bar showing how many questions a user has answered correctly and how many they have left. Questions are split by difficulty level; easy, medium and hard.
All my questions are stored in an SQLite database. The questions table is made up of three columns:
level      question      guessed

The guessed column is a flag (1 or null) to let me know if the user has guessed the question correctly or not.
To build my progress bar, I'm currently running two pieces of SQL code, for each level, to pull out the total number of questions and the total number of questions guessed correctly. This gives me the numbers I need to build the progress bar. However I am doing it by running 6 individual Java functions, one after the other.
Here is my code:
public class DatabaseAccess {

private SQLiteOpenHelper openHelper;
private SQLiteDatabase db;
private static DatabaseAccess instance;
public static String player_name;

Cursor c = null;

// private constructor so that object creation from outside the class is avoided
public DatabaseAccess(Context context) {
    this.openHelper = new DatabaseOpenHelper(context);
}

// to return the single instance of database
public static DatabaseAccess getInstance(Context context) {
    if (instance == null) {
        instance = new DatabaseAccess(context);
    }
    return instance;
}

//to open the database
public void open() {
    this.db = openHelper.getWritableDatabase();
}

//closing the database connection

public void close() {
    if (db != null) {
        this.db.close();
    }
}

public String getEasyMax(String string) {
    c = db.rawQuery("select count(*) FROM player_clues where level = 'easy'", new String[]{});
    StringBuffer buffer = new StringBuffer();
    while (c.moveToNext()) {
        String diff = c.getString(0);
        buffer.append("" + diff);
    }
    return buffer.toString();
}

public String getEasyGuessed(String string) {
    c = db.rawQuery("select count(*) FROM player_clues where level = 'easy' and guessed = 1", new String[]{});
    StringBuffer buffer = new StringBuffer();
    while (c.moveToNext()) {
        String diff = c.getString(0);
        buffer.append("" + diff);
    }
    return buffer.toString();
}

public String getMedGuessed(String string) {
    c = db.rawQuery("select count(*) FROM player_clues where level = 'medium' and guessed = 1", new String[]{});
    StringBuffer buffer = new StringBuffer();
    while (c.moveToNext()) {
        String diff = c.getString(0);
        buffer.append("" + diff);
    }
    return buffer.toString();
}

public String getHardGuessed(String string) {
    c = db.rawQuery("select count(*) FROM player_clues where level = 'hard' and guessed = 1", new String[]{});
    StringBuffer buffer = new StringBuffer();
    while (c.moveToNext()) {
        String diff = c.getString(0);
        buffer.append("" + diff);
    }
    return buffer.toString();
}

public String getMedMax(String string) {
    c = db.rawQuery("select count(*) FROM player_clues where level = 'medium'", new String[]{});
    StringBuffer buffer = new StringBuffer();
    while (c.moveToNext()) {
        String diff = c.getString(0);
        buffer.append("" + diff);
    }
    return buffer.toString();
}

public String getHardMax(String string) {
    c = db.rawQuery("select count(*) FROM player_clues where level = 'hard'", new String[]{});
    StringBuffer buffer = new StringBuffer();
    while (c.moveToNext()) {
        String diff = c.getString(0);
        buffer.append("" + diff);
    }
    return buffer.toString();
}

}

In another class, I call on these functions individually and assign the outputs to variables and use them there.
How can I make this more efficient and better?


texts: Is it reasonable to expect this AngularJS function to perform well?

texts:
I have this function which is associated with a timer that I'm creating in AngualarJS. Should I be concerned about the function being able to execute quickly enough for the timer to be accurate.

$scope.start = function() {
    if($scope.counting === true) return false;
    $scope.counting = true;
    $scope.counter = $timeout(function updateCount() {
        $scope.count++;
        $scope.hh = Math.floor($scope.count / 360000);
        $scope.mm = Math.floor(($scope.count - ($scope.hh * 360000)) / 6000);
        $scope.ss = Math.floor(($scope.count - ($scope.hh * 360000) - ($scope.mm * 6000)) / 100);
        $scope.ms = Math.floor($scope.count - ($scope.hh * 360000) - ($scope.mm * 6000) - ($scope.ss * 100));
        $scope.counter = $timeout(updateCount, 10);
    }, 10);
};


texts: Count the occurence of nucleobases in DNA string

texts:
Inspired by this meta question I decided to take a look at Rosalind. Their first challenge seemed easy enough:

An example of a length 21 DNA string (whose alphabet contains the symbols 'A', 'C', 'G', and 'T') is "ATGCTTCAGAAAGGTCTTACG."
Given: A DNA string s of length at most 1000 nt.
Return: Four integers (separated by spaces) counting the respective number of times that the symbols 'A', 'C', 'G', and 'T' occur in s.
Sample Dataset
AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC

Sample Output
20 12 17 21

Since I'm still on my quest to learn both regex and Ruby, I decided to go that route:
def countACGT(str)
  list = [0,0,0,0]
  str.scan(/A|C|G|T/) do |sub|
    if sub == "A"
      list[0] += 1
    end
    if sub == "C"
      list[1] += 1
    end
    if sub == "G"
      list[2] += 1
    end
    if sub == "T"
      list[3] += 1
    end
  end
  return list
end

I'm not a big fan of long if chains. Luckily, Ruby has a case statement as well:
def countACGT(str)
  list = [0,0,0,0]
  str.scan(/A|C|G|T/) do |sub|
    puts case sub
    when "A"
      list[0] += 1
    when "C"
      list[1] += 1
    when "G"
      list[2] += 1
    when "T"
      list[3] += 1
    end
  end
  return list
end

Both can be invoked like:
p countACGT("TCCCACTTCAGGGTCAGGGAGCTCCAAACTCTCTTTCTAGAGATGACAATCGAGAGTGAGATAAGGTGGATAGCAATCGTTATGGGATGTAAGCGCCAAGCGTTCGGGTAGCCCACGTTGCGGGCTAATCGCTAGGCTAGAACCTCTAAGCTGTACTTCTGTCAAAACGGAAAGAATCATACCGCACACCAACACTCGATGTAATGTAAGGATATCCTGTGCAGATGAGGTGCTTGGTACGCTAGATACTAGTATTACTAACACACAACATTACCGCCCAAGCGTGTCAGCCACGGACCAGATGACTCTTGCCGATTGAATACCTATCATCCTTACGGTCCGGAATCAGTATATCGCGTGCACAGTTACAGTGGTTAACTTGAGCTAGAGCAAGATAATGTGCGATCTGCGCACTCGGTGGGCTTGGATCACCCTACTTCCAATTGCCCGCGTATGATAGTTCCACCACTCACAAGTCTGTCATAGTGATTATCAAGAGTAGGCGTAGTGGGCACCCAAGAAATTAATGAATCTCACAGTCGAGTGTATCTTCGGCCATATCCCTACGGCAAATGGTCGCTCAGCTTGTCTCCGAGAGTTCGTTGGTTCAGAACCTCCGAAGGGTTGGGTGATTGTTGCGGCGCGCATGCGAGCTATGGTGGCTGTGTGTGGAGGTATTATCAGGGGAAATTTATTCCGAGTACTTGCTTGACTGCTCTTTTGTAAGCCGTTTGGGGTGCGTCCTCTGTATAGTCGTCGCCGCGAAGCCGATTCCCTCTAATCAAACACGCCAGAGGATCACTGGTCTTCTTCAAATTCCTGTATACCTCTGGCTAAATGACCCGACGGTACGAGCGTTTACTTCGAAGTG")

Yes, the dataset I had to solve was that long.
However, my interpreter suddenly feels the need to print the updated list[x] every time a new value gets assigned. This leads to a significant decrease in performance.
So I downloaded the official Ruby interpreter via the downloader (version 2.2.3 (x64)) and the exact same thing happens.
It almost looks like case is not the preferred way of doing this, but that's not intuitive.
I'm mainly looking for a definitive answer on which version I should stick with (and why) and general maintainability improvements. I'm perfectly aware regex may not be the optimal solution here, but I'd like to stick with it anyway.


texts: Compute variance via functional programming

texts:
So I'm supposed to calculate variance based on this forumula through functional programming:
$$\sigma^2 = \frac{\sum\limits_{i=0}^{n-1} (X -\mu)^2}{n-1}$$
This is the code that works:
public static double variance1(int[] array)
{
     double mean=mean(array);
     double summation=DoubleStream.iterate(0,idx->idx+1)
                                  .limit(array.length)
                                  .reduce(0,(summation_counter,idx)->
                                   {
                                     return Math.pow(array[(int)idx]-mean, 2)+summation_counter;
                                   });

     return summation/(array.length-1);
}

Although the code works, it's ugly with the typecasts and seems forced.
Initially, I thought of doing something like
double summation=IntStream.rangeClosed(0,array.length-1)
                          .reduce(0, (summation_counter,idx)-> ....

but I couldn't use an IntStream as the body of the reduce method returns double.


texts:
This is the first jQuery program I've written, and it doesn't do much, but I'd appreciate the feedback. Just click on the different colored buttons to do things.

Codepen

var $greenElement = $(
  '
 \

Hello
 \

'
);

var $redElement = $(
  '
 \

Goodbye
 \

'
);

/* Main JQuery loop */
$(document).ready(function() {

  /* Add a red item and fade to the right value*/
  $('.add-item-red').mouseenter(function() {
    $(this).fadeTo('fast', 0.4);
    $(this).click(function() {
      $('.output-start').after($redElement);
    });
  });

  /* Check if the mouse is no longer on red button */
  $('.add-item-red').mouseout(function() {
    $(this).fadeTo('fast', 1);
  });

  /* Add a green item and fade to the right amount */
  $('.add-item-green').mouseenter(function() {
    $(this).fadeTo('fast', 0.4);
    $(this).click(function() {
      $('.output-start').after($greenElement);
    });
  });

  /* Check if mouse is no longer on green button */
  $('.add-item-green').mouseout(function() {
  $(this).fadeTo('fast', 1);
  });

  /* Reset all the items */
  $('.reset-items').mouseenter(function() {
    $(this).fadeTo('fast', 0.4);
    $('.reset-items').click(function() {
      $('.green-bar').remove();
     $('.red-bar').remove();
    });
  });

  /* Check if mouse is no longer on white button */
  $('.reset-items').mouseout(function() {
    $(this).fadeTo('fast', 1);
  });
});
body {
  background-color: black;
}

.button-bar div{
  display: table;
  display: table-cell;
}

.add-item-red {
  width: 50px;
  height: 50px;
  background-color: red;
  border-color: black;
  border-style: solid;
  border-width: 3.5px;
}

.add-item-green {
  width: 50px;
  height: 50px;
  background-color: green;
  border-color: black;
  border-style: solid;
  border-width: 3.5px;
}

.reset-items {
  width: 50px;
  height: 50px;
  background-color: white;
  border-color: black;
  border-style: solid;
  border-width: 3.5px;
}

.output-start {
  width: 50px;
  height: 15px;
}


texts: Security and efficiency for profile picture upload

texts:
I am trying to allow users to upload profile pics on my site. Basically I am following this code: Allow users to upload a pic for their profile.

I don't know if the code is secure enough. I am worried that users may upload malicious files.

Also, I am concerned that if there is many users, I will have many pictures in a single folder and it may slow down the retrieving process. I wonder what is the best practice in storing the profile pics. How many photos maximum should there be in a folder for better efficiency?

if(is_uploaded_file($_FILES['image']['tmp_name']))
{
    uploadImage($_FILES['image']['tmp_name'], 100, 100, "image/users/test2.jpeg");
}

and

function uploadImage($source, $max_width, $max_height, $destination) {

list($width, $height) = getimagesize($source);
if ($width > 150 || $height > 150) {
    $ratioh = $max_height / $height;
    $ratiow = $max_width / $width;
    $ratio = max($ratioh, $ratiow);
    // New dimensions
    $newwidth = intval($ratio * $width);
    $newheight = intval($ratio * $height);

    $newImage = imagecreatetruecolor($newwidth, $newheight);

    $ext = trim(strtolower($_FILES['image']['type']));

    $sourceImage = null;

    // Generate source image depending on file type
    switch ($ext) {
    case "image/jpg":
    case "image/jpeg":
        $sourceImage = imagecreatefromjpeg($source);
        break;
    case "image/gif":
        $sourceImage = imagecreatefromgif($source);
        break;
    case "image/png":
        $sourceImage = imagecreatefrompng($source);
        break;
    }

    imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    // Output file depending on type
    switch ($ext) {
    case "image/jpg":
    case "image/jpeg":
        imagejpeg($newImage, $destination);
        break;
    case "image/gif":
        imagegif($newImage, $destination);
        break;
    case "image/png":
        imagepng($newImage, $destination);
        break;
    }

    // Destroy resources
    imagedestroy($newImage);
    imagedestroy($sourceImage);

}
}


texts:
I'm aware that iterating frames in pandas is a very slow operation.  I've heard vectorization speeds things up. I found a project that I'm using for sentiment analysis on reddit.
The Calculate dataframe method wasn't working for some reason, (maybe different version of panda) I wanted to refactor it to use vectorization but Sadly it took me 2 days to even get the code working.
def calculate_df(df):
    data_df = df.filter(['tickers', 'score', 'sentiment'])

    tickers_processed = pd.DataFrame(df.tickers.explode().value_counts())

    tickers_processed = tickers_processed.rename(columns = {'tickers':'counts'})

    tickers_processed['score'] = 0.0
    tickers_processed['sentiment'] = 0.0

    for idx, row_tick in enumerate(tickers_processed.itertuples(), 1):
        upd_row_sent = row_tick.sentiment
        upd_row_score = row_tick.score
        for row_data in data_df.itertuples():
            if(row_tick.Index in row_data.tickers):
                upd_row_sent += row_data.sentiment['compound'] / row_tick.counts
                upd_row_score += int(row_data.score) / row_tick.counts
                tickers_processed.set_value(row_tick.Index, 'sentiment', upd_row_sent)
                tickers_processed.set_value(row_tick.Index, 'score', upd_row_score)

Calling set value twice seems redundant,  If I could calculate the dataset and update it using vectors I think the code would be a lot nicer


texts:
I have 2 buttons for Terms and Conditions in my project, that I need to implement in multiple activities. I created the following class:

public class TermsAndConditionsView extends LinearLayout implements View.OnClickListener {
    private Context context;

    public TermsAndConditionsView(Context context) {
        super(context);
        this.context = context;
    }

    public TermsAndConditionsView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        setUpLayout();
    }

    private void setUpLayout() {
        LinearLayout container = (LinearLayout) this.getChildAt(1);
        Button terms1 = (Button) container.findViewById(R.id.terms1);
        Button terms2 = (Button) container.findViewById(R.id.terms2);
        terms1.setOnClickListener(this);
        terms2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.terms1) {
            String url = "myUrl1";
            ActivityUtil.openBrowser((Activity) context, url);
        } else if (v.getId() == R.id.terms2) {
            String url = "myUrl2";
            ActivityUtil.openBrowser((Activity) context, url);
        }
    }
}

And the terms.xml file:

 <?xml version="1.0" encoding="utf-8"?>
<com.example.TermsAndConditionsView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">

<TextView
    android:id="@+id/hosted_by_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:textColor="@color/title_grey"
    style="@style/text1"/>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="horizontal">

    <Button
        android:id="@+id/terms1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Terms 1"
        style="@style/Link2"/>

    <Button
        android:id="@+id/terms2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:text="Terms 2"
        style="@style/Link2"/>
</LinearLayout>
</com.example.TermsAndConditionsView>

Is this a good way of reusing a group of views?

My colleagues say that it's not ok to use an XML which can be modified easily because I should modify in the code also (for example changing the order of the views) and if I am not careful the app might crash and it might take some time to figure out from where the problem comes from.

So, what's the best way of reusing this group of Terms and Conditions buttons?


texts:
While I'm not new to Python, this is my first 'bigger' Python program I created, also my first game in Python.

import random

DEBUG = False; # If set to true, displays chosen word before each game. For debugging and cheating only :)

DICT_FILE = "english.txt";
GUESSES   = 10;

def prompt(s):
    while True:
        ans = raw_input(s + " (Y/n) ").lower();
        if ans in ["y", "n"]:
            return ans == "y";

def loadWords():
    with open(DICT_FILE, "r") as f:
        return f.read().strip().split("\n");
                       # Strip in case of newline at end of file

def play(word):
    word = word.lower();
    if DEBUG:
        print "[DEBUG] word is %r" % (word);
    guesses = GUESSES;
    toGuess = set(l for l in word.upper() if l.isalpha()); # Handles apostrophes, etc.
    letters = set();
    while guesses > 0:
        if len(toGuess) == 0:
            print "You win with %d guess%s left!" % (guesses, "" if guesses == 1 else "es");
            print "The word is %r" % (word);
            return True;
        print "=" * 78;
        print "You have %d guess%s left." % (guesses, "" if guesses == 1 else "es");
        print "Word:    " + " ".join("_" if c in toGuess else c for c in word.upper());
        print "Letters: " + " ".join(sorted(letters));
        while True:
            l = raw_input("Choose a letter: ").upper();
            if l.isalpha():
                if l not in letters:
                    letters.add(l);
                    if l in toGuess:
                        toGuess.remove(l);
                        print "Correct!";
                    else:
                        guesses -= 1;
                        print "Sorry, not in the word.";
                    break;
                else:
                    print "You already chose that letter!";
            else:
                print "That's not a letter!";
    print "=" * 78;
    print "Sorry, you lose.";
    print "The word was: %r" % (word);
    return False;

if __name__ == "__main__":
    words = loadWords();
    random.shuffle(words);
    while True:
        play(words.pop()); # Remove a random word so it's not chosen again
        if not prompt("Would you like to play again?"):
            break;

I'd like to know what you think and what I should change.
By the way, english.txt placed in the same folder as the game script contains phrases/words separated by newlines that should appear in the hangman game.


texts:
This is a simple program converting user input decimal numbers into octal ones.

#include <iostream>
using namespace std;
main()
{
    int de,oc,y,i=1,octal;
    float decimal,deci,x;
    cout<<"Enter decimal no :: ";
    cin>>decimal;
    de=decimal;
    deci=decimal-de;
    cout<<"("<<decimal<<")10 = (";
    while(de>0)
    {
        oc=de%8;
        de=de/8;
        octal=octal+(oc*i);
        i=i*10;
    }cout<<octal<<".";
    while(deci>0)
    {
        x=deci*8;
        y=x;
        deci=x-y;
        cout<<y;
    }
    cout<<")8";
}


texts: Reading data from multiple different resource bundle property files in Java

texts:
I have class structure to read the data from resource bundle (property files).
import java.util.Locale;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 * The class will be used to read the resource bundle to achieve localization
 * and internationalization
 *
 */
public class ResourceBundleReader {

  private String resourceBundle = null;

  /**
   * Constructor of the class
   *
   * @param resourceBundle
   * @throws NullPointerException
   *           if resourceBundle is null
   */
  public ResourceBundleReader(final String resourceBundle) {

    Objects.requireNonNull(resourceBundle);

    this.resourceBundle = resourceBundle;
  }

  /**
   * Return message by input key for default locale
   *
   * @param key
   * @return
   */
  public String getMessage(final String key) {

    return getMessage(key, Locale.getDefault());
  }

  /**
   * Return message by input key for input locale locale
   *
   * @param key
   * @return
   */
  public String getMessage(final String key, final Locale locale) {
    final ResourceBundle mybundle = ResourceBundle.getBundle(resourceBundle, locale);
    return mybundle.getString(key);
  }
}

As there are multiple type of resource bundles, I have created individual implementation for that. For example below two:
Exception Message:
public final class ExceptionMessageResolver {

  private static final String EXCEPTION_MESSAGES_RESOURCE = "exceptionmessages"; //$NON-NLS-1$

  private static final ResourceBundleReader RESOURCE_BUNDLE_READER = new ResourceBundleReader(
      EXCEPTION_MESSAGES_RESOURCE);

  /**
   * Private constructor to prevent instantiation Constructor of the class
   */
  private ExceptionMessageResolver() {
    super();
  }

  /**
   * return exception message by default locale
   *
   * @param key
   * @return
   */
  public static String getMessage(final String key) {

    return getMessage(key, Locale.getDefault());
  }

  /**
   * Return exception message for input locale
   *
   * @param key
   * @param locale
   * @return
   */
  public static String getMessage(final String key, final Locale locale) {
    return RESOURCE_BUNDLE_READER.getMessage(key, locale);
  }

}

Label Messages:
public final class ResourceLabelResolver {

  private static final String LABEL_RESOURCE = "resourcelabels"; //$NON-NLS-1$

  private static final ResourceBundleReader RESOURCE_BUNDLE_READER = new ResourceBundleReader(LABEL_RESOURCE);

  /**
   * Private constructor to prevent instantiation Constructor of the class
   */
  private ResourceLabelResolver() {
    super();
  }

  /**
   * return label message by default locale
   *
   * @param key
   * @return
   */
  public static String getMessage(final String key) {

    return getMessage(key, Locale.getDefault());
  }

  /**
   * Return label message for input locale
   *
   * @param key
   * @param locale
   * @return
   */
  public static String getMessage(final String key, final Locale locale) {
    return RESOURCE_BUNDLE_READER.getMessage(key, locale);
  }

}

Is there any more elegant way for this? Or any way to create abase class for my two readers to prevent duplicate methods in code?


texts:
I'm currently trying to write an app with Cordova and ReactJS. I haven't used ReactJS before, so I'm very confused by the mixed usage of Babel, JavaScript and JSX. I try to use JSX where I can because I like it, but I dislike Babel, which is used in many tutorials as well. I haven't quite understood what Babel is used for at all.

const { Router,
        Route,
        IndexRoute,
        Redirect,
        Link,
        IndexLink
      } = ReactRouter

var Header = React.createClass({
    render: function () {
        return (

{this.props.text}

        );
    }
});

var Content = React.createClass({
    render: function() {
      return (

{this.props.text}

      );
    }
});

var Page = React.createClass({
  getInitialState: function(){
    return {
      'title': 'Main Page' + (this.props.title ? ' - ' + this.props.title : '')
    }
  },
  render: function() {
    return (

        <Content text={this.props.text} />

    );
  }
});

var Home = React.createClass({
  getInitialState: function(){
    return {
      'title': 'Home',
      'text': <Link to="/about">About</Link>
    }
  },
  render: function(){
    return (
      <Page title={this.state.title} text={this.state.text} />
    );
  }
});

var About = React.createClass({
  getInitialState: function(){
    return {
      'title': 'About',
      'text': 'Lalal'
    }
  },
  render: function(){
    return (
      <Page title={this.state.title} text={this.state.text} />
    );
  }
});

React.render((
    <Router>
      <Route path="/" component={Home} />
      <Route path="/about" component={About} />
    </Router>
  ),
  document.getElementById('app')
);

I'm wondering if there's a better way to do this or if I'm doing everything correctly. I did my best with the classes (thinking in React stuff) and wanted to make Header a Navigation later on. Is there a good way to separate the routes, and put my views into files and components where needed?


texts:
I am trying to print the Z pattern, but the time complexity is coming to \$O(n^2)\$. Is there any way to reduce the time complexity?

package matrix;

public class ZPattern
{
    public static void main(String[] args) {
        String a[][] = { {"1","2","3","4","5"},
                {"a","b","c","d","e"},
                {"6","7","8","9", "f"},
                {"g","h","i","j","k"},
                {"m","n","o","p","q"}
            };
        for(int i=0;i<a.length;i++)
        {
            for(int j=0;j<a.length;j++)
            {
                if(i==0||i==a.length-1)
                {
                    System.out.print(a[i][j]);
                }
                else if(i+j==a.length-1)
                {
                    System.out.print(a[i][j-1]);
                }
                else
                {
                    System.out.print(" ");
                }
            }
            System.out.println("");
        }
    }
}


texts: Constructing a cumulative distribution function from a histogram

texts:
During some running process, a histogram of values shall be build up. When done, the CDF shall be derived from it and used to get the quantiles for some values.

My current implementation looks as follows:

import java.util.*
import kotlin.math.max
import kotlin.math.min
import kotlin.math.roundToInt
import kotlin.random.Random

// 10 buckets for interval [0, 1000], outliers will be clamped
class Histogram(
    private val data: MutableMap<Int, Int> = mutableMapOf()
) {
    fun add(value: Int) {
        val bucket = max(0, min(1000, value)) / 100
        data[bucket] = data.getOrDefault(bucket, 0) + 1
    }

    fun deriveCDF(): CDF {
        val sum = data.values.sum()
        val pdfData = data.toSortedMap().mapValues { it.value.toDouble() / sum }
        val cdfData: MutableMap<Int, Double> = mutableMapOf()
        var acc = 0.0
        pdfData.forEach {
            acc += pdfData.getOrDefault(it.key, 0.0)
            cdfData[it.key] = acc
        }
        return CDF(cdfData.toSortedMap())
    }
}

// cumulative distribution function
class CDF(
    private val data: SortedMap<Int, Double>
) {
    fun getQuantile(value: Double): Double? {
        val bucket = (10 * value).roundToInt()
        return data[bucket]
    }
}

fun main() {
    val hist = Histogram()
    List(10000) {
        Random.nextInt(0, 1000)
    }.forEach {
        hist.add(it)
    }
    val cdf = hist.deriveCDF()
    println(cdf.getQuantile(0.3))
}

My problem with this is, that is it possible to construct instances of CDF with SortedMaps as data that don't make sense. I would like to prevent this, already at compile time.

The obvious alternative approach is to not have the construction logic (Histogram to CDF) in a Histogram::deriveCDF, but instead have a constructor of CDF take a Histogram instance and do the math there. This however forces Histogram to expose its internals data: MutableMap<Int, Int>, i.e., make them public, for the constructor of CDF to access them. But I would like to keep this implementation detail of Histogram hidden.

How can I escape this dilemma?


texts:
So I am a newbie obviously, This was part of a small assignment I had to do for Uni, and it works alright. It just reads a number from the console and then outputs the Greek letter Φ (sort of). Sure it could use some outofbound exceptions etc, but my question is this: My code overall (not just in this example) seems a little bit messy to me after I read it. My variable names are messy and I need to work on that and perhaps a few methods here and there, even though this assignment wasn't about methods but rather a warm up of basic Java syntax.

I want to write better code, but I don't know where to start.Should I use more variables? I am not greatly familiar with JavaDocs yet, should they be used for small programs as well? How much procedures is too much? Should I break it down more? I feel like my "algorithm" even though it works it could be better. Online tutorials usually teach syntax but I want to make my code as good and readable as possible.

import java.util.*;

public class A11{

    public static void main(String args[]){

        /*Declare Num, then parse the number from the command line
        into the variable,and finaly inform the user before moving on*/
        int temp=0;
        int num =0;
        num=Integer.parseInt(args[0]);
        System.out.println();
        System.out.println("Number = " + num);
        temp=num/2;

        /*Prints the first Line (approp spaces and a Star)*/
        if(num%2==0){
            temp-=1;
        }
        for(int v=0;v<=temp;v++){

            System.out.print(" ");
        }
        System.out.println("*");

        /*Print the remaining Shape according to the input*/

        /* Loop algorithm to calculate and output the appropreate amount of
        characters required to form the TOP half of the shape */
        if(num%2==0){temp=num/2-1;}

        for(int i=1;i<=temp;i++){

            for(int j=0;j<temp-i;j++){
                System.out.print(" ");
            }
            System.out.print("*");
            for(int k=0;k<2;k++){
                for(int j=0;j<i;j++){
                    System.out.print(" ");
                }
                System.out.print("*");
            }
            System.out.println();
        }
    /*Bottom half - if Num is an odd number flip the top shape but loose one line*/
        int space=temp;
         if(num%2==1){
            temp-=1;
         }
        for(int i=temp;i>=1;i--){

            for(int j=space-i;j>0;j--){
                System.out.print(" ");
            }
            System.out.print("*");
            for(int k=0;k<2;k++){
                for(int j=0;j<i;j++){
                    System.out.print(" ");
                }
                System.out.print("*");
}
            System.out.println();
        }
        temp=num/2;
        /*Prints the last line and Star*/
        if(num%2==0){
            temp-=1;
        }
        for(int v=0;v<=temp;v++){

            System.out.print(" ");
        }
        System.out.println("*");
    }
}


texts: Pass logger dependency to PostSharp aspect

texts:
I'm trying to pass my logger to a Logging Aspect that I've created with PostSharp. I have one logger per job run (because I need to send each job's logs to different folders), each job runs in different threads using  BackgroundWorker. This is the code that I have:

[Serializable]
public class LogExecutionTimeAttribute : OnMethodBoundaryAspect
{
    [NonSerialized]
    public static Func<ILog> GetLogger;

    private string methodName;

    public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo)
    {
        this.methodName = method.Name;
    }

    public override void OnEntry(MethodExecutionArgs args)
    {
        args.MethodExecutionTag = Stopwatch.StartNew();
        base.OnEntry(args);
    }

    public override void OnExit(MethodExecutionArgs args)
    {
        Stopwatch sw = (Stopwatch)args.MethodExecutionTag;
        sw.Stop();
        var logger = GetLogger();
        logger.DebugFormat(
            "{0} executed in {1} seconds.",
            this.methodName,
            sw.ElapsedMilliseconds / 1000.0);
        base.OnExit(args);
    }
}

Each thread would do:

var log = CreateLoggerForJobId(jobId);
LogExecutionTimeAttribute.GetLogger = () => log;

I'm doubtful about the Func<ILog> GetLogger being static - How will it work when called from multiple threads? My manual tests seem to suggest that this is working, but I'm not sure if this is thread safe. I am also not sure if using NonSerialized attribute on GetLogger helps.

Entire working code is here:

https://gist.github.com/rnarayana/5518327f9c7c94f8c2fde4ae7fee7733


texts:
Currently I'm overriding create and write to copy the fields onto the partner, is there a cleaner way of updating the partner on save?

@api.multi
def create(self, vals):
    if vals.get('allergy_ids'):
        self.add_partner_allergies(vals.get('allergy_ids')[0][2],
                                   vals.get('partner_id'))
    return super(Order, self).create(vals)

@api.multi
def write(self, vals, context=None):
    if vals.get('allergy_ids'):
        self.add_partner_allergies(
            vals.get('allergy_ids')[0][2],
            vals.get('partner_id', self.partner_id.id))

    return super(Order, self).write(vals)

def add_partner_allergies(self, allergy_ids, partner_id):
    """
    Populates the partner with allergies from the order for the future.
    :param allergy_ids:
    :param partner_id:
    :return:
    """
    domain = [('id', '=', partner_id)]
    partners = self.env['res.partner'].search(domain)
    allergies = copy.deepcopy(allergy_ids)
    partner_allergies = partners[0].allergy_ids.ids
    allergies = list(set(itertools.chain(allergies,
                                         partner_allergies)))

    partners.write({'allergy_ids': [(6, False, allergies)]})

It seems rather excessive to have to handle it with this much code.

Note that the data isn't relational, the partner contains the aggregate of all the allergies that have saved onto their orders, so that we can set defaults on following orders. But it shouldn't be that case that if we delete allergies from the partner, the allergies should disappear from all their orders.


texts: Classifying rows of data by the number of days to close

texts:
DataTable looks like below

I would like to simplify this code in a better manner.

DataTable dt = results.Results[0].DataTable;
dt.Columns.Add("Averagedays", typeof(string));
dt.Columns.Add("0to3", typeof(string));
dt.Columns.Add("4to7", typeof(string));
dt.Columns.Add("Gtrthan7", typeof(string));

foreach (DataRow row in dt.Rows)
{
    if (row["total_daysclose"] != System.DBNull.Value && row["closed_in0to3_count"] != System.DBNull.Value
        && row["closed_in4to7_count"] != System.DBNull.Value && row["closedGtr7_count"] != System.DBNull.Value
        && row["Closed"] != System.DBNull.Value)
    {
        if (Convert.ToDecimal(row["closed"]) > 0)
        {
            decimal value = Convert.ToDecimal(row["total_daysclose"]) / Convert.ToDecimal(row["Closed"]);
            row["Averagedays"] = string.Format("{0:0.#}", Math.Floor(value * 10) / 10);
            row["0to3"] = string.Format("{0:P1}", Convert.ToDecimal(row["closed_in0to3_count"]) / Convert.ToDecimal(row["Closed"]));
            row["4to7"] = string.Format("{0:P1}", Convert.ToDecimal(row["closed_in4to7_count"]) / Convert.ToDecimal(row["Closed"]));
            row["Gtrthan7"] = string.Format("{0:P1}", Convert.ToDecimal(row["closedGtr7_count"]) / Convert.ToDecimal(row["Closed"]));

        }
        else
        {
            row["Averagedays"] = string.Format("{0:0.#}", 0);
            row["0to3"] = string.Format("{0:P1}", 0);
            row["4to7"] = string.Format("{0:P1}", 0);
            row["Gtrthan7"] = string.Format("{0:P1}", 0);

        }
    }
}


texts:
I'm pretty new to AngularJS and have made my first directive. Is this a good or a bad way to do this?  It works, but can't figure out if this is clever or not.

.directive('showWithDelay', function($timeout){
    return {
        restrict: 'A',
        link: function($scope, $element, attrs){
            $element.addClass("ng-hide");
            $timeout(function() {
                $element.removeClass("ng-hide");
            },attrs.showWithDelay);
        }
    }
})

Usage in template

CLICK ME

button will be displayed after 6 sec.


texts: Executing functions and declaring flags with a long battery of if conditions

texts:
I'm only asking because almost the entire code base I've inherited here, in C# and PHP, looks like this:

if (varOne == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varTwo == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varThree == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varFour == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varFive == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varSix == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varSeven == flag) {
    run_some_sql();
    set_some_flag = true;
}

if (varEight == flag) {
    run_some_sql();
    set_some_flag = true;
}

For about ten thousand lines.

I haven't lost my mind, right?  Is this bad? There's only about five loops in the entire code base of about 50,000 lines.

I would normally go about this sort of thing by storing the data into an associated array, and loop over that, rather than adding a new if statement for every variable.

Have I totally lost my mind? Eight people worked on this before me, and I'm seriously worried here. Is there ever a good reason to do this sort of thing?


texts: Algorithm to rotate array elements in Ruby

texts:
I wrote this algorithm to rotate elements in an array. It's not very efficient, but it works. It has another disadvantage that it doesn't rotate right (it would be nice to pass it negative steps, for example).

def rotate_left!(array, steps = 1)
  for i in 0...steps
    first = array[0]
    for j in 1...array.size
      array[j - 1] = array[j]
    end
    array[-1] = first
  end
end

An aside, does this count as \$O(n^2)\$? For each step, we have to iterate over the entire array and shift positions by -1.

Let \$A\$ be the size of the array, \$S\$ be the steps, and \$C\$ be the constant operations of storing the first element then adding it to the end of the array.

$$
T(A, S) = S(A) + S(2C)
$$

This notation is ad-hoc, so excuse me if it doesn't make sense.

I am aware of array#rotate, and of array#shift and array#pop. For example:

def my_rotate!(array, steps = 1)
  for i in 1..steps
    array.push(array.shift)
  end
end
# or
array.push(array.shift(steps)).flatten!

But I'm curious if there are other ways that rely less on Array instance methods.


texts: Threshold an image for a given range and Sobel kernel

texts:
The class defines functions to threshold an image for a given range and Sobel kernel. Each function has similarities, i.e. they share the same following tasks:

each function converts an image to grayscale
take the gradient
rescale to 8 bit
apply a threshold, and create a binary image result

class GRADIENT_THRESHOLD(object):
    '''
    Define functions to threshold an image for a given range and Sobel kernel
    '''

    def __init__(self, args):
        self.args = args

    def gradient_abs_sobel(self, img, orient='x', sobel_kernel=3, thresh=(0, 255)):
        # convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        # take the absolute value of the gradient in given orient = 'x' or 'y'
        if orient == 'x':
            abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0))
        if orient == 'y':
            abs_sobel = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1))
        # scale to 8-bit (0 - 255) then convert to type = np.uint8
        scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
        # create a mask of 1's where the scaled gradient magnitude
        # is > thresh_min and < thresh_max
        binary_output = np.zeros_like(scaled_sobel)
        # return this mask as your binary_output image
        binary_output[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1
        # return the binary image
        return binary_output

    def gradient_magnitude(self, img, sobel_kernel=3, thresh=(0, 255)):
        # convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        # take both Sobel x and y gradients
        sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
        sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
        # calculate the gradient magnitude
        gradmag = np.sqrt(sobelx**2 + sobely**2)
        # rescale to 8 bit
        scale_factor = np.max(gradmag)/255
        gradmag = (gradmag/scale_factor).astype(np.uint8)
        # create a binary image of ones where threshold is met, zeros otherwise
        binary_output = np.zeros_like(gradmag)
        binary_output[(gradmag >= thresh[0]) & (gradmag <= thresh[1])] = 1
        # return the binary image
        return binary_output

    # Define a function to threshold an image for a given range and Sobel kernel
    def gradient_direction(self, img, sobel_kernel=3, thresh=(0, np.pi/2)):
        # convert to grayscale
        gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        # take both Sobel x and y gradients
        sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel)
        sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel)
        # take the absolute value of the gradient direction
        absgraddir = np.arctan2(np.absolute(sobely), np.absolute(sobelx))
        # apply a threshold, and create a binary image result
        binary_output =  np.zeros_like(absgraddir)
        binary_output[(absgraddir >= thresh[0]) & (absgraddir <= thresh[1])] = 1
        # return the binary image
        return binary_output


texts: Multiple SQL statements in a single transaction

texts:
Using the following query I'm doing transactions with two tables

BEGIN TRANSACTION
UPDATE SalaryTrans SET carried_forward_amount = @carriedForwardAmount, net_wage=@netWage, processed_date = @processedDate WHERE employee_id=@employeeID AND reference = @reference
DELETE FROM CarriedForward WHERE employee_id = @employeeID
INSERT INTO CarriedForward (employee_id, carried_forward_amount) VALUES(@employeeID, @carriedForwardAmount)
COMMIT;

First SalaryTrans table is updated. Then all matching records in CarriedForward table are deleted and new details are entered.

I just want to know whether this approach is acceptable or there are better ways to write this.


texts:
Is there a more efficient way to write this? This script will be used heavily and I want to make sure I do not have any memory leaks or speed issues.

This script gets an input from a form and searches the database for that record.

<?php

date_default_timezone_set('America/Los_Angeles');
$hostname='xxx';
$username='xxx';
$password='xxx';
$dbname='xxx';

$db = mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to       database! Please try again later.');
mysql_select_db($dbname);

$input_id = $_POST['id'];

$sql = "SELECT chart_id, CONCAT(first_name,' ',last_name) as full_name, expiration_date as exp, NOW() as now, DATE_FORMAT(date_of_birth,'%m-%d-%Y') as date_of_birth, DATE_FORMAT(expiration_date,'%M %d, %Y') as expiration_date, DATE_FORMAT(recommendation_date,'%M %d, %Y') as recommendation_date, notes
    FROM chart
    WHERE chart_id = '" . mysql_real_escape_string($input_id) . "'
   ";

$today = date("F j, Y");

$result = mysql_query($sql) or die(mysql_error());

if (mysql_num_rows($result) > 0) {
    $row = mysql_fetch_assoc($result);

if ($row['exp'] < $row['now']) {
    $row['status'] = 0;
}
else {
    $row['status'] = 1;
}

mysql_free_result($result);
}
else {
    $row['status'] = 'none';
}

mysql_close($db);

?>


texts: Count character replacements needed to make string a palindrome

texts:
Problem

Count the number of character replacements necessary to convert an input String to a palindrome.
Each character replacement must replace the given character with the character directly before it in the alphabet (sorted A-Z).
In other words, D can only be replaced with C.
For simplicity, only consider Strings that are comprised of alphabetic characters.

Inspired by this HackerRank problem.

Example

A => already palindromic, so 0 character replacements are necessary
ACBD => ABBD => ABBC => ABBB => ABBA, 4 character replacements

Implementation

The solution is pretty basic, so maybe getting feedback is unnecessary, but is there a better implementation?

public class PalindromeConversionCounter {
  public static int count(String s) {
    int count = 0;
    char[] chars = s.toCharArray();
    for (int i = 0; i < Math.ceil(chars.length / 2); i++) {
      char currentChar = Character.toLowerCase(chars[i]);
      char oppositeChar = Character.toLowerCase(chars[chars.length - 1 - i]);
      if (!Character.isAlphabetic(currentChar) || !Character.isAlphabetic(oppositeChar)) {
        throw new IllegalArgumentException("String should contain only alphabetic characters");
      }
      count += Math.abs(currentChar - oppositeChar);
    }
    return count;
  }
}


texts:
I've written the following helper class to help serializing objects to and from Json.

I would appreciate some feed back on the style of the class.

using System;
using System.IO;
using Newtonsoft.Json;

namespace Helpers
{
    public static class Json
    {
        public static void SaveContractToJSON<T>(T contract, string filePath)
        {
            using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
            {
                SerializeToStream(contract, fs);
            }
        }

        public static void SaveContractToJSON<T>(T contract, MemoryStream stream)
        {
            SerializeToStream(contract, stream);
        }

        private static void SerializeToStream<T>(T contract, Stream stream)
        {
            var serializer = new JsonSerializer();

            using (var sw = new StreamWriter(stream))
            using (var writer = new JsonTextWriter(sw))
            {
                serializer.Serialize(writer, contract);
            }
        }

        public static T LoadContractFromJSON<T>(string filePath)
        {
            try
            {
                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    return DeserializeFromStream<T>(fileStream);
                }
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        public static T LoadContractFromJSON<T>(MemoryStream stream)
        {
            try
            {
                return DeserializeFromStream<T>(stream);
            }
            catch (Exception)
            {
                return default(T);
            }
        }

        private static T DeserializeFromStream<T>(Stream stream)
        {
            var serializer = new JsonSerializer();

            using (var sr = new StreamReader(stream))
            using (var jsonTextReader = new JsonTextReader(sr))
            {
                return serializer.Deserialize<T>(jsonTextReader);
            }
        }
    }
}


texts: Parallel and Sequential array looping with async/await

texts:
Are these good implementations of parallel and sequential "extension" methods, and do they accomplish what I think they do?

My understanding is that the first one is parallel because the await applies to each invocation of the async lambda that is passed to map. So each invocation will block asynchronously and run in parallel.

In contrast, the await in the sequential function applies to the outer function, so each iteration of the for loop will block, and the next iteration will only occur once the previous one completes.

I based these implementations on the answer found at this SO question: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop

Array.prototype.forEachParallel = async function (
   func: (item: any) => Promise<void>
): Promise<void> {
   await Promise.all(this.map(async (item: any) => await func(item)));
};

Array.prototype.forEachSequential = async function (
   func: (item: any) => Promise<void>
): Promise<void> {
   for (let item of this)
      await func(item);
};

Example usage:

await someList.forEachParallel(item => this.SomeAsyncOperation(item));

A little additional code is:

// type declaration
interface Array<T> {
   ...
   forEachParallel(func: (item: T) => Promise<void>): Promise<void>;
   forEachSequential(func: (item: T) => Promise<void>): Promise<void>;
}

// make sure nothing is already defined on these members
[
   ...
   Array.prototype.forEachParallel,
   Array.prototype.forEachSequential
].forEach(maybeMember => { if (maybeMember) throw new Error("prototype extension collision"); });


texts:
This is just for fun so you will see tons of print statements for trouble shooting. I was hoping on slimming this down some and gain new ideas on what I have. This was a challenge question in a class I'm not in. I know the code i wrote is nightmare-ish anything to slim it down would be nice.

import java.util.*;

public class StackQueue {

    Stack stack1 = new Stack();
    Stack stack2 = new Stack();
    Stack temp   = new Stack();

    public void enqueue(String element) {
        stack1.push(element);
        System.out.println(stack1.toString() + "Stack1");
    }

        public void dequeue(){
            System.out.println(stack1.toString() + "\n\nStack1");

            if(!stack1.empty() & stack1.size()> 1 & !stack2.empty()) {           // if there are elements in both stacks
                System.out.println("IM IN THE BLOCK");
                while (!stack2.empty()) {
                    temp.push(stack2.pop());
                    System.out.println(temp.toString() + " TEMPP----");
                    System.out.println(stack2.toString() + " STACK 2---");
                }
                while (!temp.empty()) {
                    stack1.push(temp.pop());
                    System.out.println(stack1.toString() + " STACK1 ----");
                }
                System.out.println(stack1.pop() + " Has been removed");
                System.out.println(stack1.toString() + "STACK 1----");
                System.out.println(stack2.toString()+ "STACK 2----");

                if(stack2.empty()){
                    while (!stack1.empty()) {
                        temp.push(stack1.pop());
                        System.out.println(temp.toString() + " temp ----");
                    }
                    System.out.println(stack1.addAll(temp));
                    System.out.println(stack1.toString()+ "STACK ! ADD");
                    temp.removeAllElements();
                    System.out.println(temp.toString() + "TEMP _++++_+_+_+_");
                }
                }

           else if(stack1.empty()){

                System.out.println("\n\nstack1 is empty ");
                System.out.println(stack2.pop() + " Has been removed");
            }else {
                System.out.println("\n\n");
                while (!stack1.empty()) {
                    System.out.println(stack2.toString() + "Stack2 - second part");
                    stack2.push(stack1.pop());

                }
            System.out.println(stack1.toString()+ "stack1");
            System.out.println(stack2.toString()+"stack2");
            System.out.println(stack2.pop() + " Has been removed");
                    }

        }
    }

public class Main {
    public static void main(String[] args){
        StackQueue queue = new StackQueue();

        queue.enqueue("hey");
        queue.enqueue("I");
        queue.enqueue("am");
        queue.enqueue("Jeremiah");
        queue.enqueue("now");
        queue.dequeue(); //removes hey
        queue.dequeue(); //removes i
        queue.dequeue();// removes am
        queue.enqueue("one ");
        queue.enqueue("more");
        queue.enqueue("time");
        queue.dequeue();  // removes jeremiah

        // i had to reverse the stack1 order here
        queue.dequeue(); // removes now
        //queue.dequeue(); // removes one
        queue.enqueue("FIRST");
        queue.dequeue();//removes FIRST

        System.out.println(queue.stack1.toString()  + " END S1");
        System.out.println( queue.stack2.toString() + " END S2");
        System.out.println(queue.temp.toString() + " END temp");

    }

}


texts:
In one of my projects I wrote a little tournament platform, but the way I handle participants is a bit messy and I want to clean this up.

So in my case a Tournament can have participants, but either a User or a Team can signup to become a participant. A participant now holds a user_id or a team_id in the database, and depending on which is filled I determine if a User is linked to the participant or if it's a team.

I rewrote the signup part of my Tournament model to accept both a User or a Team as parameter through am interface and was wondering if this is the correct way to go.

ICandidate.php

interface ICandidate
{
    public function getName();
    public function hasCorrectGamesSet($tournamentGame);
}

User.php

class User implements ICandidate
{
    private $game;

    public function __construct($game)
    {
        $this->game = $game;
    }

    public function getName()
    {
        return 'Username';
    }

    public function hasCorrectGamesSet($tournamentGame)
    {
        if($this->game != $tournamentGame){
            throw new Exception('Incorrect name');
        };

        return true;
    }
}

Team.php

class Team implements ICandidate
{
    private $users;

    public function __construct($users)
    {
        $this->users = $users;
    }

    public function getName()
    {
        return 'Teamname';
    }

    public function hasCorrectGamesSet($tournamentGame)
    {
        foreach($this->users as $user){
            $user->hasCorrectGamesSet($tournamentGame);
        }
    }
}

Participant.php

class Participant
{
    private $name;
    private $class;

    public function setName($name)
    {
        $this->name = $name;
    }

    public function setClass($class)
    {
        $this->class = $class;
    }
}

Tournament.php

class Tournament
{
    private $participants;
    private $game;

    public function __construct($game)
    {
        $this->game = $game;
    }

    public function signUp(ICandidate $candidate)
    {
        $candidate->hasCorrectGamesSet($this->game);

        $participant = new Participant();
        $participant->setName($candidate->getName());
        $participant->setClass(get_class($candidate));

        $this->participants[] = $participant;
    }

    public function getParticipants()
    {
        var_dump($this->participants);
    }
}

So with this set, I can signup a User or a Team, do a little check and if that passes, add them as a participant to the tournament.

Logic

$tournament = new Tournament('fifa');

$user1 = new User('fifa');
$user2 = new User('fifa');
$user3 = new User('fifa');
$user4 = new User('fifa');

$team = new Team([$user2, $user3, $user4]);

$tournament->signUp($user1);
$tournament->signUp($team);

$tournament->getParticipants();

Is this a correct way to implement this and make use of the interface?


texts: Display class containing a Canvas in a JFrame

texts:
I've been using this class for so long, I never thought about how terribly big and how bad it looks. Looking back on it, this class looks so out-of-date, and nothing explains itself; I want to get it looking much better, not with all the extra junk that it doesn't need.
Here's the class:

import java.awt.Canvas;
import java.awt.Dimension;

import javax.swing.JFrame;

public class Display {

    private JFrame frame;
    private Canvas canvas;

    private String title;
    private int width, height;

    public Display(String title, int width, int height){
        this.title = title;
        this.width = width;
        this.height = height;

        createDisplay();
    }

    private void createDisplay(){
        frame = new JFrame(title);
        frame.setSize(width, height);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);

        canvas = new Canvas();
        canvas.setPreferredSize(new Dimension(width, height));
        canvas.setMaximumSize(new Dimension(width, height));
        canvas.setMinimumSize(new Dimension(width, height));
        canvas.setFocusable(false);

        frame.add(canvas);
        frame.pack();
    }

    public Canvas getCanvas(){
        return canvas;
    }

    public JFrame getFrame(){
        return frame;
    }

}

Is there anything here I can condense, or any way to make it look cleaner?


texts:
I am a beginner in programming and this is the third program I've written.  This is an interactive game of rock, paper, scissors, capable of being modified to any number of turns.  I would love to see how a more experienced programmer could simplify this and make it smaller.  Please let me know how I could change this program to be easier to understand for other programmers or any general layout/design rules I should keep in mind when writing future programs.  I just have the slightest feeling that this code could be more compact.

args = ['rock', 'paper', 'scissors']
user_score = 0
comp_score = 0
turn = 3
print 'ROCK, PAPER, SCISSORS!'
print 'Best out of %d' % (turn)
while turn > 0:
    user = raw_input('Choose ' + ", ".join(args) + ' > ')
    comp = random.choice(args)
    proof = 'Computer: %s' % (comp)
    if user == 'q':
        break
    elif (user == args[0] and comp == args[2]) or (user == args[1]\
          and comp == args[0]) or (user == args[2] and comp == args[1]):
        print proof
        print 'Win \n'
        turn -= 1
        user_score += 1
    elif user == comp:
        print proof
        print 'Tie \n'
        turn -= 1
    elif user not in args:
        print 'INVALID INPUT \n'
    else:
        print proof
        print 'Lose \n'
        turn -= 1
        comp_score += 1
print '\n User scored: %d \n Computer scored: %d \n' % (user_score,comp_score)
if user_score > comp_score:
    print 'Winner!'
elif user_score < comp_score:
    print 'Loser'
else:
    print 'Draw'


texts:
I'm working on an implementation of the Karazuba Algorithm. I created a class  BN which represents a number in an arbitrary base (and supports elementary operations). The algorithm works - but I'm not sure if I complicated it. Is there a better way to implement it or a way to optimize the code?

def decToBase(n: int, b: int) -> list:
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return list(reversed(digits))

def baseToDec(n: list, b: int) -> int:
    res = 0
    for index, i in enumerate(reversed(n)):
        res += int(i) * b ** index
    return res

from math import log2, ceil, log10, floor

class BN(): # Base Number
    def __init__(self, num, base):
        if type(num) == list:
            self.digits = num
        else:
            self.digits = decToBase(num, base)
        self.base = base
        self.length = len(self.digits)

    def __add__(self, o):
        if self.base != o.base:
            raise ValueError("base of summands must be equal")
        carry = 0
        res = []
        for d1, d2 in zip(reversed(self.digits), reversed(o.digits)):
            s = int(d1) + int(d2) + carry
            res.append(str(s % self.base))
            carry = s // self.base
        return BN(list(reversed(res)), self.base)

    def __mul__(self, o):
        # implementation pending
        return BN(decToBase(self.getDecimalForm() * o.getDecimalForm(), self.base), self.base)

    def __sub__(self, o):
        # implementation pending
        return BN(decToBase(self.getDecimalForm() - o.getDecimalForm(), self.base), self.base)

    def getDecimalForm(self):
        return baseToDec(self.digits, self.base)

def karazubaMultiply(a, b, base=2**64):
    if a < b:
        a, b = b, a # ensure a >= b
    next2 = 2 ** ceil(log2(floor(log10(a))+1)) # next power of 2
    a, b = BN(a, base), BN(b, base)
    a.digits, b.digits = ['0'] * (next2 - a.length) + a.digits, ['0'] * (next2 - b.length) + b.digits
    n = next2 // 2
    x2, x1 = BN(a.digits[:n], base), BN(a.digits[n:], base)
    y2, y1 = BN(b.digits[:n], base), BN(b.digits[n:], base)
    p1, p2, p3 = x2 * y2, x1 * y1, (x1 + x2) * (y1 + y2)
    p1, p2, p3 = p1.getDecimalForm(), p2.getDecimalForm(), p3.getDecimalForm()

    xy = p1 * base ** (2*n) + (p3 - (p1 + p2)) * base ** n + p2

    return xy


texts: Lombokython - Automatic __eq__, __hash__, __repr__

texts:
I recently decided to code some in Python after coding in Java using lombok for quite some time. However, I got bit real hard when I forgot to implement __eq__, since Lombok normally does it for you.

I decided to try to implement something similar to Lombok's @EqualsAndHashCode, which I called eqhash. Then, I added a similar way to generate a __repr__ method.

How well did I follow python style? I developed this using TDD, so I would like to know how my tests are as well.

genmethods.py

def eqhash(cls: type):
    """Adds __eq__, __ne__, and __hash__ methods to the class"""
    class NewCls(cls):
        def __eq__(self, other):
            if self is other: return True
            if not isinstance(other, NewCls): return False
            svars = vars(self)
            ovars = vars(other)
            return svars == ovars

        def __ne__(self, other):
            return not (self == other)

        def __hash__(self):
            return hash(vars(self).values())

    return _pass_attrs(NewCls, cls)

def repr_(cls: type):
    """Adds a __repr__ method to the class"""
    class NewCls(cls):
        def __repr__(self):
            return '{clsname}({variables})'.format(
                clsname=cls.__name__,
                variables=', '.join(repr(o) for o in vars(self).values())
            )

    return _pass_attrs(NewCls, cls)

def _pass_attrs(new_cls, cls):
    new_cls.__name__ = cls.__name__
    new_cls.__qualname__ = cls.__qualname__
    for attr, value in vars(cls).items():
        try:
            setattr(new_cls, attr, value)
        except AttributeError:
            pass

    return new_cls

test_genmethods.py

import unittest
import genmethods

class SData:
    def __init__(self, value):
        self._value = value

    def test(self):
        return self._value

def ensure_not_mangled(self: unittest.TestCase, cls: type, name: str):
    self.assertEqual((1, 2), cls((1, 2)).test())
    self.assertEqual(name, cls.__name__)

class EqHashTest(unittest.TestCase):
    @genmethods.eqhash
    class Data(SData):
        pass

    def test_eq_genned(self):
        self.assertEqual(EqHashTest.Data((1, 2)), EqHashTest.Data((1, 2)))
        self.assertNotEqual(EqHashTest.Data((1, 2)), EqHashTest.Data((1, 4)))

    def test_hash_genned(self):
        v1 = EqHashTest.Data(1)
        v2 = EqHashTest.Data(1)
        self.assertEqual(hash(v1), hash(v2))

    def test_not_mangled(self):
        ensure_not_mangled(self, EqHashTest.Data, "Data")

class ReprTest(unittest.TestCase):
    @genmethods.repr_
    class Data(SData):
        pass

    def test_repr_genned(self):
        self.assertEqual('Data(1)', repr(ReprTest.Data(1)))

    def test_not_mangled(self):
        ensure_not_mangled(self, EqHashTest.Data, "Data")

class ReprEqHashTest(unittest.TestCase):
    @genmethods.repr_
    @genmethods.eqhash
    class Data(SData):
        pass

    def test_eq_genned(self):
        self.assertEqual(ReprEqHashTest.Data((1, 2)), ReprEqHashTest.Data((1, 2)))
        self.assertNotEqual(ReprEqHashTest.Data((1, 2)), ReprEqHashTest.Data((1, 4)))

    def test_hash_genned(self):
        v1 = ReprEqHashTest.Data(1)
        v2 = ReprEqHashTest.Data(1)
        self.assertEqual(hash(v1), hash(v2))

    def test_repr_genned(self):
        self.assertEqual('Data(1)', repr(ReprEqHashTest.Data(1)))

    def test_not_mangled(self):
        ensure_not_mangled(self, EqHashTest.Data, "Data")

class EqHashReprTest(unittest.TestCase):
    @genmethods.eqhash
    @genmethods.repr_
    class Data(SData):
        pass

    def test_eq_genned(self):
        self.assertEqual(ReprEqHashTest.Data((1, 2)), ReprEqHashTest.Data((1, 2)))
        self.assertNotEqual(ReprEqHashTest.Data((1, 2)), ReprEqHashTest.Data((1, 4)))

    def test_hash_genned(self):
        v1 = ReprEqHashTest.Data(1)
        v2 = ReprEqHashTest.Data(1)
        self.assertEqual(hash(v1), hash(v2))

    def test_repr_genned(self):
        self.assertEqual('Data(1)', repr(ReprEqHashTest.Data(1)))

    def test_not_mangled(self):
        ensure_not_mangled(self, EqHashTest.Data, "Data")


texts: Read coordinates from many files and calculate polygon areas

texts:
My goal with this snippet is to create an array of coordinates which in turn is a tuple of 68 elements, area and modified area array for all 10k elements and assign it to the df column.

Running the complete code results in 5.3, 4.8, 4.6, 4.5 seconds.

#%%

arrayc = [] #array for array of coordinates
areaAr = [] #area type 1
modifiedarea = [] #area type 2
ts = time.time()

for i in range(10708): #number of files
        f = open(df["filepath"][i], "r") #df has column of filepaths
        x,y = [], []
        for l in f:
            row = l.split()
            x.append(int(float(row[0]))) #68 pairs are of kind 3.82382323e+02 4.563524234e+02.
            y.append(int(float(row[1]))) #I am taking int rounded off to three digits.
        arrayc.append((x,y))
        f.close()
        #x= arrayc[i][0]
        #y = arrayc[i][1]
        areaAr.append(PolyArea(x[36:41],y[36:41]))
        distance = max(np.abs(x[36]-x[39]),np.abs(x[42]-x[45]))
        modifiedarea.append((PolyArea(x[36:41],y[36:41]))/distance)

te = time.time()
print(-ts+te)
def PolyArea(x,y):
        return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

How can I minimise the execution time ?

Updates:

File generator code:

import numpy as np
filepath = []
root = '~/Desktop/test/'
for i in range(10):
    for j in range(68):
        numx = ( np.random.randint(100,200))
        numy = np.random.randint(100,200)
        f = open(root + str(i) + ".txt","a")
        f.write(str(numx) + " " + str(numy) + "\n")

The numbers 36 41 etc are the coordinates of the polygon of interest on the image. It is fixed that the polygon will always be marked by these coordinates.


texts:
Github

Github for easy testing

I'm currently undertaking a training course to try & further develop my skills in

C#. The latest exercise was to create a basic stopwatch class that meets the following criteria -

  Design a class called Stopwatch. The job of this class is to simulate
  a stopwatch. It should provide two methods: Start and Stop. We call
  the start method first, and the stop method next. Then we ask the
  stopwatch about the duration between start and stop. Duration should
  be a value in TimeSpan. Display the duration on the console. We should
  also be able to use a stopwatch multiple times. So we may start and
  stop it and then start and stop it again. Make sure the duration value
  each time is calculated properly. We should not be able to start a
  stopwatch twice in a row (because that may overwrite the initial start
  time). So the class should throw an InvalidOperationException if its
  started twice.

  Educational tip: The aim of this exercise is to make you understand
  that a class should be always in a valid state. We use encapsulation
  and information hiding to achieve that. The class should not reveal
  its implementation detail. It only reveals a little bit, like a
  blackbox. From the outside, you should not be able to misuse a class
  because you shouldn’t be able to see the implementation detail.

I'm sure someone is bound to mention it, but yes I'm aware that there is already a stopwatch class in the .NET framework, but as this was the exercise I wanted to try & accomplish it based on the requirements.

The class is as follows -

public class Stopwatch
{
    private TimeSpan _duration;
    // private TimeSpan _start;
    private DateTime _start;

    public Stopwatch()
    {
        ZeroStart();
    }

    public void Start()
    {
        // if (_start != TimeSpan.Zero)
        if (_start != DateTime.Min)
            throw new InvalidOperationException("The stopwatch has already been started.");

        _start = DateTime.Now;
    }

    public TimeSpan Stop()
    {
        // if (_start == TimeSpan.Zero)
        if (_start == DateTime.Min)
            throw new InvalidOperationException("The stopwatch has not been started.");

        _duration = DateTime.Now- _start;
        ZeroStart();
        return _duration;
    }

    private void ZeroStart()
    {
        // _start = TimeSpan.Zero;
        _start = DateTime.Min;
    }
}

I haven't done an awful lot of OOP or even effective work with classes. Most of the stuff I have done in the past has been more procedural based stuff, just a long list of static methods in static classes etc...

I'm not sure if this is really enough to go on for anyone to actually critique me on so I'm sorry if that's the case.

I've tested the code using the following -

class Program
{
    static void Main(string[] args)
    {
        UsingStopwatch();
    }

    static void UsingStopwatch()
    {
        Console.WriteLine("This is a stop watch. Type 'start' to start it & 'stop' to stop it.");
        var stopwatch = new Stopwatch();

        while (true)
        {
            var input = Console.ReadLine();

            switch (input.ToLower())
            {
                case "start":
                    stopwatch.Start();
                    break;
                case "stop":
                    Console.WriteLine(stopwatch.Stop());
                    break;
                default:
                    Console.WriteLine("Sorry I don't recognize that.");
                    break;
            }
        }
    }
}

Update

Thanks to jandotnet I have made some updates to how I store some of the data. _start is now DateTime & I have comparing values with DateTime.MinValue. I have updated the above with the full snippet.


texts: TabController for handling opening and closing of tabs

texts:
I created a class TabController to handle opening and closing of tabs. It needs some data from my viewModel, so should I pass in the viewmodel via the constructor or is that overkill? It really only needs the parameters browserCollection and activeWindow, so I could just pass those two in if that's better. I'm just starting learning about design patterns so I can code well but am having trouble wiring everything up.

public abstract class TabController
{
    ViewModel vm;

    #region constructor
    public TabController(ViewModel vm)
    {
        this.vm = vm;
    }
    #endregion

    public abstract void go(Uri address);
    public abstract void newTabGo(Uri address);
    public abstract void newEmptyTab();

    public void newTab(Uri address, int insertionIndex)
    {
        vm.browserCollection.Insert(insertionIndex, new MyBrowserControl(address));
    }
}

//first class, starts out this way when the program starts -- no tabs are open
public class NoTabsOpen : TabController
{
    ViewModel vm;

    #region constructor
    public NoTabsOpen(ViewModel vm)
        : base(vm)
    {
        this.vm = vm;
    }
    #endregion

    public override void go(Uri address)
    {
        if (address != null)
            vm.browserCollection.Add(new MyBrowserControl(address));
    }

    public override void newTabGo(Uri address)
    {
        if (address != null)
            base.newTab(address, 0);
    }

    public override void newEmptyTab()
    {
        base.newTab(null, 0);
    }

}

//second class - active when at least one tab is open
public class TabsOpen : TabController
{
    ViewModel vm;

    #region constructor
    public TabsOpen(ViewModel vm)
        : base(vm)
    {
        this.vm = vm;
    }
    #endregion

    public override void go(Uri address)
    {
        if (address != null)
        {
            MyBrowserControl mbc = vm.browserCollection[vm.activeWindow];
            mbc.mySource = address;
        }
    }

    public override void newTabGo(Uri address)
    {
        if (address != null)
        base.newTab(address, vm.activeWindow + 1);
    }

    public override void newEmptyTab()
    {
        base.newTab(null, vm.activeWindow + 1);
    }
}


texts: CyclicBarrier and Thread for optimize for element for tags in Java

texts:
How can I use a CyclicBarrier with N-THREAD according to my core for optimize this code?

My code has an input like this:

i 3
a duna automobile deserto -1
a nissan auto automobile -1
s aut -1

i 2
a pesca sport frutta -1
s sport -1

END

i = 3 means that there are 3 lines.
"a" means that I'm adding an element (first occurrence after "a") and the other words after the element are my "tags".
"s" means that I have to find the tags that have as substring the word "aut" for the first block and "sport" for the second block.

At the end the output is like this:

2

1

"2" means that I have two elements "duna" & "nissan" that have tags (auto, automobile, auto) that start with the word "aut".
"1" means that I have the element "pesca" that has tag (sport) that starts with the sub-tag "sport".

With END, the program is finished.

package Prove;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

class FinalMap {

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

        HashMap<String, Set<String>> map = new HashMap<String, Set<String>>();
        java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in);
        java.io.BufferedReader stdin = new java.io.BufferedReader(isr, 16 * 1024);

        String line = stdin.readLine();
        final String ADD_COMMAND = "a";
        final String ITEM_COMMAND = "i";
        final String SEARCH_COMMAND = "s";
        final String END_MARKER = "<END>";

        while (!line.equals("<END>")) {

            String elemento = "" ;

            if (line.startsWith(ITEM_COMMAND))
            {
                map = new HashMap<String, Set<String>>();
            }

            else if (line.startsWith(ADD_COMMAND)) {

                String[] parts = line.split("\\s+");

                for (int i = 2; i < parts.length - 1; ++i) {
                    String element = parts[1];
                    String tag = parts[i];
                    for (int j = 1; j <= parts[i].length(); ++j) {
                        String tagPrefix = tag.substring(0, j);
                        Set<String> elements = map.get(tagPrefix);
                        if (elements == null) {
                            elements = new HashSet<String>();
                            map.put(tagPrefix, elements);
                        }
                        elements.add(element);
                    }
                }

            }

            else if (line.startsWith(SEARCH_COMMAND)) {
                String subtag = line.substring(2,line.length()-3);
                if (map.containsKey(subtag)) {
                    System.out.println(map.get(subtag).size());
                } else {
                    System.out.println("missing");
                }
            }
           line = stdin.readLine();
        }
        stdin.close();
    }
}


texts: Right structure, three-layered architecture webdevelopment

texts:
My question is have i gotten the three-layered architecture right with error handling etc. I have a webpage containing different resources. The code works but I am not sure if have structured it correct.
This is a function located in the BLL
createPost: function (accountId, title, body, callback) {
    postValidator.validatePost(title, body, function (error) {
        if (error) {
            callback(error, null)
        } else {
            postRepository.createPost(title, body, accountId, function (error, postId) {
                if (error) {
                    callback(new BusinessError(BusinessErrorType.DATA_LAYER_ERROR, "Error creating post"), null)
                } else {
                    callback(null, postId)
                }
            })
        }
    })
}

Basically it sends a request to create desired post in the DL if the DL returns the error value the BLL will return it to the PL. My function in the PL that communicates with the BLL:
router.post("/new", function (request, response) {
   const title = request.body.title
   const body = request.body.body
   const account = request.session.account
   loginManager.isLoggedIn(request.session.login, function (error, IsLoggedIn) {
       if (IsLoggedIn) {
            postManager.createPost(account.id, title, body, function (error, createdPostId) {
                if (error) {
                    response.render("new-post.hbs", { title: title, body: body, notification: error.description, notificationType: "danger" })
                } else {
                    response.redirect("/posts/" + createdPostId)
                }
            })
        } else {
            response.render("accounts-sign-in.hbs", { notification: error.description, notificationType: "danger" })
        }
    })
})

Is this the correct way to go about?


texts: Django class-based generic views - am I doing it right?

texts:
I am working on a simple "to do list" app in Django (two models: List and Item).  I'm trying to learn and make use of class-based generic views. I have the following three display views working, but am requesting a quick code review to see if there's anything I can do to improve my usage/understanding of Django's ListView and DetailView before I move on to creating, updating and deleting.

# class-based generic views for my lists, a list's items, and item detail...
class MyListsView(ListView):
    """Display the current user's Lists"""
    template_name = 'cmv_app/my_lists.html'
    context_object_name = 'my_lists'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(MyListsView, self).dispatch(*args, **kwargs)

    def get_queryset(self):
        return List.objects.filter(user=self.request.user).order_by('-last_modified')

class ListItemsView(ListView):
    """Display a list's items"""
    template_name = 'cmv_app/list_items.html'
    context_object_name = 'list_items'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.list = get_object_or_404(List, pk=kwargs['list_id'])
        request = list_valid_for_user(request, self.list) # security check
        return super(ListItemsView, self).dispatch(request, *args, **kwargs)

    def get_queryset(self):
        return Item.objects.filter(list=self.list).order_by('-created_date')

    def get_context_data(self, **kwargs):
        context = super(ListItemsView, self).get_context_data(**kwargs)
        context['list'] = self.list
        return context

class ItemDetailView(DetailView):
    """Display detail for one list item"""
    template_name = 'cmv_app/item_detail.html'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        self.list = get_object_or_404(List, pk=kwargs['list_id'])
        self.item = get_object_or_404(Item, pk=kwargs['item_id'])
        request = list_valid_for_user(request, self.list)  # security check
        request = item_valid_for_list(request, self.item, self.list)  # security check
        return super(ItemDetailView, self).dispatch(request, *args, **kwargs)

    def get_object(self):
        return self.item

    def get_context_data(self, **kwargs):
        context = super(ItemDetailView, self).get_context_data(**kwargs)
        context['list'] = self.list
        return context


texts:
What do I need to do to prevent injections?  In addition, if I have any statement/parameter errors, please tell me.

 <?
 $username  = 'username';
 $pass      = 'pass';
 $cpass     = 'cpass';
 $email     = 'email';
 $gender    = 'gender';
 $firstname = 'firstname';
 $lastname  = 'lastname';
 $phone     = 'phone';
 $address   = 'address';

 $username    = htmlspecialchars($username, ENT_QUOTES);
 $pass        = htmlspecialchars($pass, ENT_QUOTES);
 $cpass       = htmlspecialchars($cpass, ENT_QUOTES);
 $email       = htmlspecialchars($email, ENT_QUOTES);
 $gender      = htmlspecialchars($gender, ENT_QUOTES);
 $firstname   = htmlspecialchars($firstname, ENT_QUOTES);
 $lastname    = htmlspecialchars($lastname, ENT_QUOTES);
 $phone       = htmlspecialchars($phone, ENT_QUOTES);
 $address     = htmlspecialchars($address, ENT_QUOTES);

 $uLength     = strlen($username);
 $pLength     = strlen($pass);
 $cpLength    = strlen($cpass);
 $emailLength = strlen($email);
 if ($uLength >= 6 && $uLength <= 35) {

} else {

$errorMessage = $errorMessage . "Username must be between 6 and 35 characters" . "
";

}
if ($emailLength >= 3 && $emailLength <= 42) {

} else {

$errorMessage = $errorMessage . "Email must be between 3 and 42 characters" . "
";

}

if ($pLength >= 8 && $pLength <= 64) {

} else {

$errorMessage = $errorMessage . "Password must be between 8 and 64 characters" . "
";

}
if ($cpLength >= 8 && $cpLength <= 64) {

} else {

$errorMessage = $errorMessage . "Confirmation password must be between 8 and 64 characters" . "
";
}
$user_name    = 'u904609109_dev';
$pass_word    = '_____';
$database     = 'u904609109_users';
$server       = 'mysql.2freehosting.com';

$con = mysqli_connect($server, $user_name, $pass_word, $database);
if (mysqli_connect_error()) {
    die('Connect Error: (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
}

echo 'Connect Error:' . $mysqli->host_info . "\n";

$result = mysqli_query($con, $database);
if (!$result) {
    die("Failed to load " . mysqli_error($con));
}

$dblink = "SELECT * FROM users WHERE (username= '" . $username . "')";
$dblink->bind_param('username', $username);
if ($dblink) {
}

$result2  = mysqli_query($result, ($dblink));
$num_rows = mysqli_num_rows($result);

if ($num_rows > 0) {

    $errorMessage = "Username already taken";

} else {
}
$dblink = $mysqli_query("SELECT * FROM users WHERE (email = '" . $email . "')");
$dblink->bind_param('username', $username);
if ($dblink) {
}
$result2  = mysqli_query($result, $dblink);
$num_rows = mysqli_num_rows($result);

if ($num_rows > 0) {

    $errorMessage = "Email already taken";

} else {
}
$username = mysqli_real_escape_string($username);
$pass = mysqli_real_escape_string($pass);
$cpass = mysqli_real_escape_string($cpass);
$gender = mysqli_real_escape_string($gender);
$email = mysqli_real_escape_string($email);
$firstname = mysqli_real_escape_string($firstname);
$lastname = mysqli_real_escape_string($lastname);
$address = mysqli_real_escape_string($address);
$phone = mysqli_real_escape_string($phone);

$username= $_POST[($username)];
$pass= $_POST[($pass)];
$cpass= $_POST[($cpass)];
$gender= $_POST[($gender)];
$email= $_POST[($email)];
$firstname= $_POST[($firstname)];
$lastname= $_POST[($lastname)];
$address= $_POST[($address)];
$phone= $_POST[($phone)];

mysqli_select_db($database, $con);

$sql = "INSERT INTO users(username, pass, cpass, gender, email, firstname, lastname, address, phone) VALUES ('" . $username . "', '" . $pass . "', '" . $cpass . "', '" . $gender . "', '" . $email . "', '" . $firstname . "',  '" . $lastname . "', '" . $address . "', '" . $phone . "')";

$result1 = mysqli_query($con, $sql);
if (!$result1 || mysqli_query($con, $sql)) {
    die('Invalid query: ' . mysqli_error());
}
echo htmlentities($sql);

header("Location: finished.html"); {
    mysqli_close($con);
}
}
?>