texts:
I'm quite new to the language and I just started using async/await. I've written this function for an API that I'm developing. It checks what is sent by the user, specially the status that he wants to set. The function will just update the application if it gets refused but, in case it gets accepted, it will also create an allocation based on the other fields that the user added.

const application_update = async (request, response) => {
  try {
    const { id } = request.params;
    if (!ObjectId.isValid(id)) throw 'invalid objectid';
    const { status, garden, start_date, end_date } = request.body;
    if (_.isEmpty(status) || !['Aceite', 'Recusado'].includes(status)) throw 'status empty or invalid';
    const { user } = await Application.findById(id);
    if (!user) throw 'invalid application';
    if (status == 'Aceite') {
      const now = moment().format();
      const a = await Allocation
        .findOne({ $or: [{ garden, start_date: { $lt: now }, end_date: { $gt: now } },
          { user, start_date: { $lt: now }, end_date: { $gt: now } }] });
      if (a) throw 'invalid request';
      const body = { user, garden, start_date, end_date };
      const allocation = new Allocation(body);
      const all = await allocation.save();
      if (!all) throw 'error creating the allocation document';
    }
    const app = await Application.findByIdAndUpdate(id, { status }, { new: true, runValidators: true });
    if (!app) throw 'error updating the application document';
    response.status(200).send(app);
  } catch (error) {
    response.status(400).send({ error });
  }
};

The code doesn't include but Mongoose verifications are in place so I can control if he doesn't fill the fields used for the allocation.

What could be improved? I feel like I'm using way too many ifs but I believe they're needed to make sure all the fields exists and to retrieve the response as soon as possible if any of them fail.


texts:
I was trying to optimize the Radix Sort code, because I never found a code that was simple and easy to understand yet wasn't any slower. I have seen codes on web and in some books that implement arbitrary radices such as 10 and others and also do modulo operation rather than bit-shifting. Those codes however have always been slower that their comparison based counterparts in the same language.

Since Radix Sort runs in \$O(n)\$ time, I built up my version of Radix Sort which is coded below in C. I choose C language because of speed, however please correct me if I'm going wrong. The code also works for negative numbers too.

I have optimized the code as far as I could go, and maybe I might have missed some more optimization techniques.

Any ideas with which I can increase the execution speed ?

Motivation for optimization:
http://codercorner.com/RadixSortRevisited.htm
http://stereopsis.com/radix.html
I was unable to implement all the optimizations in the articles, as it was beyond my skills and understanding mostly and somewhat lack of sufficient time. Other techniques not included in them or out of the box would definitely help a lot.

This is the pointer optimized version, "long" on my system is 32 bits.

long* Radix_Sort(long *A, size_t N, long *Temp)
{
    long Z1[256] ;
    long Z2[256] ;
    long Z3[256] ;
    long Z4[256] ;
    long T = 0 ;
    while(T != 256)
    {
        *(Z1+T) = 0 ;
        *(Z2+T) = 0 ;
        *(Z3+T) = 0 ;
        *(Z4+T) = 0 ;
        ++T;
    }
    size_t Jump, Jump2, Jump3, Jump4;

    // Sort-circuit set-up
    Jump = *A & 255 ;
    Z1[Jump] = 1;
    Jump2 = (*A >> 8) & 255 ;
    Z2[Jump2] = 1;
    Jump3 = (*A >> 16) & 255 ;
    Z3[Jump3] = 1;
    Jump4 = (*A >> 24) & 255 ;
    Z4[Jump4] = 1;

    // Histograms creation
    long *swp = A + N;
    long *i = A + 1;
    for( ; i != swp ; ++i)
    {
        ++Z1[*i & 255];
        ++Z2[(*i >> 8) & 255];
        ++Z3[(*i >> 16) & 255];
        ++Z4[(*i >> 24) & 255];
    }

    // 1st LSB byte sort
    if( Z1[Jump] == N );
    else
    {
        swp = Z1+256 ;
        for( i = Z1+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A-1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z1[*i & 255] + Temp) = *i;
        }
        swp = A;
        A = Temp;
        Temp = swp;
    }

    // 2nd LSB byte sort
    if( Z2[Jump2] == N );
    else
    {
        swp = Z2+256 ;
        for( i = Z2+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A-1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z2[(*i >> 8) & 255] + Temp) = *i;
        }
        swp = A;
        A = Temp;
        Temp = swp;
    }

    // 3rd LSB byte sort
    if( Z3[Jump3] == N );
    else
    {
        swp = Z3 + 256 ;
        for( i = Z3+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A-1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z3[(*i >> 16) & 255] + Temp) = *i;
        }
        swp = A;
        A = Temp;
        Temp = swp;
    }

    // 4th LSB byte sort and negative numbers sort
    if( Z4[Jump4] == N );
    else
    {
        swp = Z4 + 256 ;
        for( i = Z4+129 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        *Z4 = *Z4 + *(Z4+255) ;
        swp = Z4 + 128 ;
        for( i = Z4+1 ; i != swp ; ++i )
        {
            *i = *(i-1) + *i;
        }
        swp = A - 1;
        for( i = A+N-1 ; i != swp ; --i )
        {
            *(--Z4[(*i >> 24) & 255] + Temp) = *i;
        }
        return Temp;
    }
    return A;
}


texts: Reading complete contact information in Android

texts:
My goal is to read complete contact information on an Android application. This is very slow and my understanding is that since the contacts are stored locally in a phone database, it shouldn't take long to fetch complete contact details.

public void readContacts() {
    Log.d("TAG", " -> Into readContacts");
    // Get the ContentResolver
    ContentResolver cr = getContentResolver();
    // Get the Cursor of all the contacts
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

    // Move the cursor to first. Also check whether the cursor is empty or not.
    if (cursor.moveToFirst()) {
        // Iterate through the cursor
        do {
            // Get the contacts name
            Contact contactToSave = new Contact();
            contactToSave.setIsUploaded(false);
            String id = cursor.getString(cursor.getColumnIndex(
                    ContactsContract.Contacts._ID));
            Log.d(TAG, " ID " + id);

            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            contactToSave.setFirstName(name);
            Log.d(TAG, " Complete Name " + name);

            String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
            String[] orgWhereParams = new String[]{id,
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
            Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, orgWhereParams, null);

            if (orgCur.moveToFirst()) {
                String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
                String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
                contactToSave.setCompany(orgName);
            }
            orgCur.close();

            Cursor emailCur = cr.query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                    new String[]{id}, null);
            while (emailCur.moveToNext()) {
                // This would allow you get several email addresses
                // if the email addresses were stored in an array
                String email = emailCur.getString(
                        emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                contactToSave.setEmail(email);
            }
            emailCur.close();

            if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(
                    ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneNumber = pCur.getString(pCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Phone.NUMBER));
                    contactToSave.setPhone(phoneNumber);
                }
                pCur.close();
            }
            mAdapter.add(contactToSave);
        } while (cursor.moveToNext());
        mAdapter.sort(new Comparator<Contact>() {
            @Override
            public int compare(Contact o1, Contact o2) {
                return o1.getFirstName().compareTo(o2.getFirstName());
            }
        });
    }
    // Close the cursor
    cursor.close();
}

I think creating multiple cursors for different data may be a performance overhead. Is there any way those can be combined?
Is there any other way to fetch the cursor than running multiple queries using multiple cursors?
If the answer for the above two questions are negative, then is this the best way possible for such a simple requirement?


texts:
I wrote this Ruby Mod 11 (perhaps it's a bit generous to call it that) implementation to validate Brazilian CPF documents, which use a Mod 11 algorithm. CPF format is a 9 digit number followed by two checksums. It's often presented in this format 012.345.678-90. Feedback is welcome.

class CPF
  attr_reader :digits

  LENGTH = 11

  def self.valid?(number)
    new(number).valid?
  end

  def self.mask(number)
    new(number).mask
  end

  def initialize(number)
    @digits = number.to_s.gsub(/\D/, '').each_char.map(&:to_i)
  end

  def valid?
    correct_length? && !black_listed? && checksums_match?
  end

  # The `black_listed?` method checks common number patterns.
  #
  # It tests to see if the provided CPF is the same digit repeated n times.
  #
  def black_listed?
    digits.join =~ /^12345678909|(\d)\1{10}$/
  end

  # A valid CPF must be 11 digits long.
  #
  def correct_length?
    digits.size == LENGTH
  end

  # A CPF is only valid if the first and second checksum digits are what they should be.
  #
  def checksums_match?
     first_checksum_matches? && second_checksum_matches?
  end

  # This returns the CPF is a human readable format.
  #
  #     CPF.mask("01234567890")
  #     => "012.345.678-90"
  #
  def mask
    [digits.first(9).each_slice(3).map(&:join).join("."), digits.last(2).join].join('-') if valid?
  end

private

  def first_checksum_matches?
    checksum_one == digits.at(9)
  end

  def second_checksum_matches?
    checksum_two == digits.at(10)
  end

  def checksum_one
    digit = sum_at(10)
    digit = calculate(digit)
    digit = 0 if digit > 9
    digit
  end

  def checksum_two
    digit = sum_at(11) + (2 * checksum_one)
    digit = calculate(digit)
    digit = 0 if digit > 9
    digit
  end

  def sum_at(position)
    digits.slice(0..8).collect.with_index { |n, i| n * (position - i) }.reduce(:+)
  end

  def calculate(digit)
    LENGTH - (digit % LENGTH)
  end
end

Tests

require 'test_helper'

class CpfTest < ActiveSupport::TestCase
  test 'black listed numbers are not' do
    black_list = %w(00000000000 11111111111 22222222222 33333333333 44444444444
                    55555555555 66666666666 77777777777 88888888888 99999999999)
    black_list.each do |number|
      assert_invalid number
    end
  end

  test 'nil is not a valid CPF' do
    assert_invalid nil
  end

  test 'blank is not a valid CPF' do
    assert_invalid ''
  end

  test 'valid CPF' do
    assert_valid '01234567890'
  end

  test 'masked valid CPF' do
    assert_valid '012.345.678-90'
  end

  test 'mask returns a masked CPF when CPF is valid' do
    assert_equal '012.345.678-90', CPF.mask('01234567890')
  end

  test 'mask returns nil when CPF is not valid' do
    assert_nil CPF.mask('0123456789')
  end

private

  def assert_invalid(number)
    refute CPF.valid?(number), "Expected #{number || 'nil'} to be an invalid CPF"
  end

  def assert_valid(number)
    assert CPF.valid?(number), "Expected #{number} to be a valid CPF"
  end
end


texts:
I'm using this code to find out the recurring dates, within a given range. Is this the correct way to find out the recurring dates within a range of dates?

between[] contains all the dates calculated within the range provided by the user. I only pasted the code that is relevant to the recurrence part only.

switch (true) {
                case (interval == 7):
                    //weekly
                    //Push in the selected dates in the selected array.
                    for (var i = 0; i < between.length; i += 7) {
                        selected.push(between[i]);

                    }
                break;
                case (interval == 30):
                    //Monthly
                    //Push in the selected dates in the selected array.
                    for (var i = 0; i < between.length; i += 30) {
                        selected.push(between[i]);

                    }
                    break;
                case (interval == 15):
                    //Bi-Monthly
                    //Push in the selected dates in the selected array.
                    for (var i = 1; i < between.length; i += 15) {
                        selected.push(between[i]);

                    }
                    break;
                case (interval == 0):
                    //One time event
                    //Push in the selected dates in the selected array.
                    for (var i = 0; i < 1; i++) {
                        selected.push(between[i]);

                    }
                    break;
                default:
                    return undefined;
            }


texts: Query to plot a histogram of song ratings

texts:
I wrote code to plot a rating distribution, which looks like this:

The most important function is the stats function:

function stats($songID){
    $st=$this->conn->prepare("SELECT
        (SELECT COUNT(*) FROM list WHERE SongID=:songID),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='10'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='9.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='9'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='8.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='8'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='7.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='7'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='6.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='6'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='5.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='4.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='4'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='3.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='3'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='2.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='2'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='1.5'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='1'),
        (SELECT COUNT(*) FROM list WHERE SongID=:songID AND Rating='0.5')
        FROM list WHERE SongID=:songID");
    $st->bindparam(":songID",$songID);
    $st->execute();
    return $st->fetchall();
}

function bars($rate,$percentage,$ratings){
    return <<<HTML

                {$rate}

                {$percentage}%({$ratings} votes)

HTML;
}

And then in another file I use these methods:

$stats=$song->stats($_GET['songid']);
    foreach($stats as $key){
        $total=$key[0];
        $rate=10;
        for($i=1;$i<21;$i++){
            echo $song->bars($rate,round(($key[$i]/$total)*100,2),$key[$i]);
            $rate-=0.5;
            }
            break;
        }

This code works perfectly, but somehow I'm not satisfied with the stats function, the way I solved it. It's just too long, and doesn't look quite good to me.

So the question is: is there a way to make that function a bit shorter, so I wouldn't repeat the same thing 20 times but with different values for the Rating column?

I was thinking that this might actually be the only way to do it, but I thought I'd give it a try here, since there are way smarter programmers here than I am.


texts: Scoring solution for Farkle (dice game)?

texts:
I've written the following function on Python (3.3) to take a list of 6 integers and return the maximum score for a game of Farkle. While the results are correct I don't feel it's a very Pythonic implementation. I'd like to hear from the community on how I could make it better and more Pythonic. Any and all tips are most welcome!

"""
    written and tested in Python 3.3.6
"""

from random import randint

def score(my_roll, sides=6):
    """
        Calculate a Farkle score using the traditional scoring method, which is:
            4 1s:     2,000 points
            3 1s:     1,000 points
            Single 1: 100 points
            Single 5: 50 points
            Triple of any non-1 number:    100 x number showing
            Quadruple of any non-1 number: Double the triple score

        Notes:
            - Doubles score nothing (unless a 1 or a 5) as above
            - All scoring dice must be rolled in a single turn (i.e. they
            are not additive over turns)
            - Rolling all 6 will be two sets and scored accordingly
                [4] + [2]
                [3] + [3]
                [2] + [2] + [2]

        Examples:
            1,1,1,5,5,5 ==> 1500 (1000 for 1s + 250 for 3 5s)
            1,1,1,1,6,6 ==> 2000 (2000 for 4 1s)
            5,3,6,5,3,3 ==> 400 (300 for 3 3s + 100 for 2 5s)
            1,2,2,3,3,5 ==> 150 (100 for a 1 and 50 for a 5)
    """
    #create a table to hold the count of each die roll
    dice_array = [0] * sides
    score = 0

    #add up the number appearances of each die roll and store it in the table
    for dice in my_roll:
        dice_array[dice-1] += 1

    """
        based on the above scoring, determine the MAXIMUM score; in actual Farkle the
        player would choose which die to 'bank' and which to re-roll
    """
    for (i, count) in enumerate(dice_array):
        dice = i + 1  #this makes it easier to keep track of the die we're on

        if dice == 1:
            if count == 6: score += 2200
            if count == 5: score += 2100
            if count == 4: score += 2000
            if count == 3: score += 1000
            if count in [1, 2]: score += (count * 100)
        else:
            if count >= 4: score += (dice * 200)
            if count >= 3: score += (dice * 100)
            if (dice == 5 and count != 3): score += (count * 50)

    return score

#test cases
while True:
    roll = input("Enter 6 values (1-6) separated by a space: ")
    roll = [random.randint(1,6) for i in range(0, 6)] if roll == "" else [int(i) for i in roll.split(' ')]
    print(str(score(roll)) + " : " + str(roll))


texts:
I've created a linked list template class which contains a copy constructor that performs a deep copy of the list.

LinkedList.hpp

template <class T>
class LinkedList {
protected:
    struct Node {
        T value;
        Node *next;
        Node(T val, Node *nxt=NULL) {
            value = val;
            next = nxt;
        }
    };
    Node *head;
public:
    LinkedList();
    LinkedList(LinkedList &obj);
    ~LinkedList();

};

LinkedList.cpp

template <class T>
LinkedList<T>::LinkedList() {
    head = NULL;
}

template <class T>
LinkedList<T>::LinkedList(LinkedList &obj) {
    if (obj.head == NULL) {
        head = NULL;
    }
    else {
        head = new Node(obj.head->value);
        Node *current = head;
        Node *objHead = obj.head;
        Node *currentObj = objHead;
        while (currentObj->next != NULL) {
            current->next = new Node(currentObj->next->value);
            currentObj = currentObj->next;
            current = current->next;
        }
    }
}

template <class T>
LinkedList<T>::~LinkedList() {
    Node *current = head;
    while (current != NULL) {
        Node *garbage = current;
        current = current->next;
        delete garbage;
    }
}

template class LinkedList<int>;
template class LinkedList<double>;
template class LinkedList<bool>;
template class LinkedList<string>;

From what I can tell, the default copy constructor implements this functionality naturally, but I wanted to see if I could create a deep copy of a linked list myself using a self-defined copy constructor.

When I test this using:

LinkedList<int> ll;
ll.add(1);
ll.add(2);
ll.add(3);
ll.add(4);

LinkedList<int> ll2 = ll;
ll.add(5);

ll.displayList();
ll2.displayList();

It prints 1,2,3,4,5 and then 1,2,3,4.  I believe this is correct.  Are there any improvements I can make to the implementation of this?


texts:
In a VB.Net class, I have an method that replaces all square brackets [] in certain properties by normal brackets ().

Edit:
The program allows users to write custom calculations, such as [3-(6-2)]. Being able to use two kinds of brackets makes things easier for them, but when processing the calculation, it's easier to have the same brackets everywhere.

The code is really redundant:

Public Sub removeBadBrackets()
    ValueCalc = Replace(Replace(ValueCalc, "[", "("), "]", ")")
    TargetCalc = Replace(Replace(TargetCalc, "[", "("), "]", ")")
    LLLCalc = Replace(Replace(LLLCalc, "[", "("), "]", ")")
    LLCalc = Replace(Replace(LLCalc, "[", "("), "]", ")")
    LCalc = Replace(Replace(LCalc, "[", "("), "]", ")")
    HCalc = Replace(Replace(HCalc, "[", "("), "]", ")")
    HHCalc = Replace(Replace(HHCalc, "[", "("), "]", ")")
    HHHCalc = Replace(Replace(HHHCalc, "[", "("), "]", ")")
End Sub

I think this could be done in a more efficient way, and I'd like to learn how.

Side note:

Those properties are not the only one of the object.
They are in the same region (although I am not sure regions can be used for anything else than my own convenience).

Thank you for your help improving this.


texts: Excel macro to move data across workbooks using an ADO connection

texts:
I am writing a macro to move data from a CSV to an excel template. Currently, I have the code set to search for a keyword in column A of the CSV, and extract data from specified columns in the keywords row. I would like to know if there is something I can do to simplify the code.

Public Sub MoveData()

    '**defines the project name as a variable
    Dim fileName As String
        fileName = Worksheets("Cover").Range("B5").Value

    '**defines the path of the CSV summary from BlueBeam
    Dim path As String
        path = "C:\Users\(users)\Documents\(folder)\" & fileName & ".csv"

    '**defines the two workbooks that the data will move between
    Dim currentWB As Workbook
    Set currentWB = ThisWorkbook

    Dim openWB As Workbook
    Set openWB = Workbooks.Open(path)

    Dim openWs As Worksheet
    Set openWs = openWB.Sheets(fileName)

    '**connects using ADODB to transfer the data
    Dim cn As ADODB.Connection
    Set cn = New ADODB.Connection
    With cn
        .Provider = "Microsoft.ACE.OLEDB.12.0"
        .ConnectionString = "Data Source=" & path & ";" & _
    "Extended Properties=Excel 12.0 Xml;"
        .Open
    End With

    '**selects the first column to be read and sorted
    Dim subCell As Range
    Dim myRange As Range
    Set myRange = Range("A1:A500")

    Dim cmdOpen1 As Boolean
    cmdOpen1 = False
    Dim cmdOpen2 As Boolean
    cmdOpen2 = False

    For Each subCell In myRange

        If subCell Like "*keyword1*" Then

            strQuery = "SELECT [Measurement] FROM [" & fileName & "$] Where Subject = '" & subCell.Value & "'"

            Set cmd1 = New ADODB.Command
            With cmd1
                .ActiveConnection = cn
                .CommandText = strQuery
            End With

        Dim rst1 As New ADODB.Recordset
            With rst1
                If cmdOpen1 = False Then
                    .Open cmd1
                    cmdOpen1 = True
                End If
            End With

            currentWB.Worksheets("Bms").Range("C7").CopyFromRecordset rst1

        ElseIf subCell Like "*keyword2*" Then

            strQuery = "SELECT [Notes (C)], [Col Top (C)], [Col Base (C)] FROM [" & fileName & "$] Where Subject = '" & subCell.Value & "'"

            Set cmd2 = New ADODB.Command
            With cmd2
                .ActiveConnection = cn
                .CommandText = strQuery
            End With

            Dim rst2 As New ADODB.Recordset
            With rst2
                If cmdOpen2 = False Then
                    .Open cmd2
                    cmdOpen2 = True
                End If
            End With

            currentWB.Worksheets("Cols").Range("B7").CopyFromRecordset rst2

        End If

    Next subCell
    openWB.Close

rst1.Close
rst2.Close
End Sub

I'm fairly new to VBA and extremely new to recordsets, so please let me know if you notice anything that should be changed. In total, I will be writing the code to search for about 6-7 keywords and the columns that the data will change based on the keyword. I'd like to revise this code before I move forward with adding more data selection.

If you need anymore information on what I am trying to accomplish or how I coded an area, please let me know. Any help will be greatly appreciated.


texts:
What I have

I am a bit advanced PHP developer, but now I'm going to college where we are learning Ruby. We got the first homework and I did it. But I wanna make great code - so I looked for standards and found pretty much nothing. I only realized, that variables aren't named with camelCase but_like_this. I edited some things, but still I don't think this is great. Can someone familiar with Ruby tell me, how to improve this code? I am interested in details, because I wanna learn the best practice at the beginning.

Specific questions

Are functions without parameters bad? RubyMine highlights them and tells me "Parentheses around empty arguments list" but I am not sure, what does it mean.
How would be this code divided into more files (what would go where)? // It was task of the homework to make only one file

Long story short - the task

There is someone who lives in 1526. He has chunks of wood, which he can burn to make heat. Then he has logs, which he can split into chunks. Day by day he has four options.

Cut a tree (and get rand(2..4) logs )
Split rand(2..5) logs into chunks and get two chunks for each log
Go to sleep
Die

When he does something the day ends and he burns one chunk. Every day I must write what day it is and how many logs and chunks we have.

My code

def print_status()
  puts "It's day #{$day}. You have #{$logs} logs and #{$chunks} of chunks."
end

def print_action()
  puts "\nWhat will you do? \n 1. Cut a tree \n 2. Split logs into chunks \n 3. Go to sleep \n 4. Die and end the simulation"
  puts "\nYour choice:"
end

def print_delimiter()
  puts "\n------------------------------------------------------------"
end

def user_interaction()
  print_delimiter()
  print_status()
  print_action()
end

def end_day()
  puts "\nDay has passed and you burned a single chunk."
  $day += 1
  $chunks -= 1
end

$day = 1
$logs = 0
$chunks = 3

puts 'You are a logger in 1526. Try to survive.'

while $chunks > 0 do

  user_interaction()
  choice = gets.to_i

  case choice
    when 1
      chopped_trees = rand(2..4)

      $logs += chopped_trees

      puts "\nYou cut #{chopped_trees} trees, you got #{chopped_trees} logs from them."

      end_day()
    when 2
      if $logs == 0
        puts "\nYou have no logs to split."
        end_day()
        next
      end

      logs_to_chop = rand(2..5)

      if logs_to_chop > $logs
        logs_to_chop = $logs
      end

      $logs -= logs_to_chop
      $chunks += logs_to_chop*2

      puts "\nYou split #{logs_to_chop} logs to #{logs_to_chop*2} chunks."

      end_day()
      next
    when 3
      puts "\nYou go to sleep."
      end_day()
      next
    when 4
      puts "\nYou died."
      exit
    else
      puts "\nInvalid input"
      next
  end
end

puts 'You run out of chunks. You froze to death.'
exit

Conclusion

I hope you will tell me those little details to make my code best practice. And by the way - the homework is not in English, so it's not important to correct my grammar mistakes.


texts: Asking for Fibonacci numbers, up till 50

texts:
I am learning Python, and this is one of the program assignments I have to do.

I need to write code to prompt user to enter Fibonacci numbers continuously until it's greater than 50. If everything correct, screen show 'Well done', otherwise 'Try again'.

While my code is working correctly, I would like to know how I should write it better.

My code:

# Init variables
t = 0
prev_2 = 1
prev_1 = 0
run = 1

# Run while loop to prompt user enter Fibonacci number
while (run):
   text = input('Enter the next Fibonacci number >')
   if (text.isdigit()):
      t = int(text)
      if t == prev_2 + prev_1:
         if t <= 50:
            prev_2 = prev_1
            prev_1 = t
         else:
            print('Well done')
            run = 0
      else:
         print('Try again')
         run = 0
   else:
      print('Try again')
      run = 0


texts: Understand the dependency levels of makefiles

texts:
Assume that the project has the following files, where the first files is dependent on the files under it's category in the unordered list:

main.c

global.h         (contains enumerations and #define macros)
sdlevent.h       (generic header file)

sdlevent.c   (contains implementations of sdlevent.h)

sdlshape.h       (generic header file)

sdlshape.c   (contains implementations of sdlshape.h)

Now, I have the following makefile:

CC = gcc
CFLAGS = -g -w -std=c99
LIBS = -lSDL2 -lSDL2_image -lSDL2_ttf

SRCS = main.c sdlshape.c sdlevent.c
OBJS = $(SRCS:.c=.o)
EXE = play

all: $(EXE)

.c.o:
    $(CC) -c $(CFLAGS) $<

$(EXE): $(OBJS)
    $(CC) -o $(EXE) $(OBJS) $(LIBS)

$(OBJS): global.h sdlevent.h sdlshape.h

run : all
    ./$(EXE)

clean:
    rm -f *.o *~ $(EXE)

  The target $(EXE) is dependent on the target .c.o. Do I absolutely need to define the target $(EXE) after the target .c.o?

I don't think so, because even though the target $(EXE) is dependent on the target $(OBJS), the target ($EXE) is declared before $(OBJS).


texts:
I wrote the following method which would just call an API which would then update a user's subscription to something.
void updateSubscription(String userId, boolean subscribed){

        try{
            // some stuff
            restTemplate.exchange(.....)
           // some stuff
        }catch (HttpClientErrorException exception){
            log.error("API EXCEPTION - Received Status: {} - Stack Trace:",exception.getStatusCode(), exception);
            throw new ExternalAPIException("Service unavailable", HttpStatus.SERVICE_UNAVAILABLE);
        }catch (Exception e){
            log.error("API EXCEPTION - Stack Trace:", e);
            throw new ExternalAPIException("Internal Server Error", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

I have two questions in particular:

Is the void return type okay? I am actually leaning towards returning a boolean indicating if the request was successful.
Is the error handling okay?

Note - it is a service class without a controller, so I can't use @controller's advice.


texts: HTML and CSS markup for flexible form layout

texts:
I'm trying to have a HTML / CSS structure for flexible layouts for forms. I tried to look at Bootstrap codes for help with this (without actually using Bootstrap itself). I've gone with something along these lines:

http://cssdeck.com/labs/stidyuic

* {padding: 0; margin: 0; box-sizing: border-box;}
body {width: 80%; margin: 0 auto; margin-top: 30px;}
.form-row {
  display: block;
}
.form-group:first-child {
  padding-left: 0px;
}
.form-group {
  margin-bottom: 20px;
  float: left;
  padding-left: 20px;
}
.col-6 {
  width: 50%;
}
.col-3 {
  width: 25%;
}
label {
  display: block;
  margin-bottom: 10px;
  font-weight: bold;
}
.form-control {
  display: block;
  width: 100%;
  height: 34px;
  padding: 6px 12px;
  font-size: 14px;
  line-height: 1.42857;
  color: #555;
  vertical-align: middle;
  background-color: #FFF;
  background-image: none;
  border: 1px solid #CCC;
  border-radius: 4px;
  box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.075) inset;
  transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
}
input, button, select, textarea {
  font-family: inherit;
  font-size: inherit;
}
form {
  display: block;
  margin-top: 0em;
}

                  Title
                  <input class="form-control" placeholder="Test" size="4" type="text">

                  Category
                  <select class="form-control">
                     <option value="A">
                        A
                     </option>
                     <option value="B">
                        B
                     </option>
                  </select>

                  Type
                  <select class="form-control">
                     <option>
                        A
                     </option>
                     <option>
                        B
                     </option>
                     <option>
                        C
                     </option>
                  </select>

I want to be able to do the following:

Have anywhere from 1 to four inputs on each row.
Have the label above the form
Modify the form layout with CSS when the resolution changes (media query)

Questions:

Is it a sensible approach to use this code structure in order to
achieve this?
Is taking Bootstrap’s form structure a logical approach to this problem?


texts: Keeping UI responsive while performing long running task

texts:
I recently asked for some advice on the best way to structure my code for a program I was writing. (see this question on Programmers.SE).  The solution I was given was quite elegant, however I am less happy with the code that I've written so that the UI remains responsive.

Here is my code, I will outline the reasons I am not happy with it below:

    private void buttonUpdateContacts_Click(object sender, EventArgs e)
    {
        BackgroundWorker worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
        worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        worker.RunWorkerAsync();
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        (sender as BackgroundWorker).ReportProgress(0, "Parsing word document...");

        WordDocumentParser wordDocumentParser;
        try
        {
            wordDocumentParser = new WordDocumentParser(Settings.Default.OohSheetLocation);
        }
        catch (FileNotFoundException exception)
        {
            e.Result = new FileNotFoundException("Could not find the word document. File path is: " + exception.FileName, exception);
            return;
        }

        List<TppContact> oohSheetContacts = wordDocumentParser.GetContacts();

        try
        {
            _contactManager = GoogleContactsManager.CreateContactsManager();
        }
        catch (InvalidCredentialsException argumentException)
        {
            e.Result = argumentException;
            return;
        }
        catch (ArgumentNullException nullArg)
        {
            e.Result = nullArg;
            return;
        }

        (sender as BackgroundWorker).ReportProgress(0, "Comparing Google contacts to the word document...");
        var comparer = new ContactComparer(oohSheetContacts, _contactManager);
        _actions = comparer.Compare();
    }

    void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        labelCurrentStatus.Text = e.UserState.ToString();
    }

    void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        if (e.Result != null)
        {
            MessageBox.Show((e.Result as Exception).Message);
        }
        else
        {
            if (_actions.Count == 0)
            {
                textBoxChanges.Text = "There are no changes to be made.";
                buttonApplyChanges.Enabled = false;
            }
            else
            {
                textBoxChanges.Text = string.Empty;
                _actions.ForEach(action => textBoxChanges.Text += action.ChangeDescription + Environment.NewLine);
                buttonApplyChanges.Enabled = true;
            }
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        labelCurrentStatus.Text = "Updating Google...";
        _contactManager.UpdateContacts(_actions);

        labelCurrentStatus.Text = "Done.";
    }

I don't like how tied up my code is to the background worker.  For example, to handle the exceptions that the various methods can throw, I have to set the result of the background worker to be the exception then handle it in the worker_RunWorkerCompleted method.  This also means that I lose the ability to give the user proper error messages such as "invalid username and password supplied".  Maybe the answer is to set that as the result rather than the exception?
It goes without saying that I probably shouldn't have all this logic being called from the button clicked method but I am unsure of a better way to do it.  This is written in WinForms at the minute but there's very little reason not to write it in WPF.
Am I using the best structure here?  I tried to use Tasks but didn't get very far and I've used background workers in the past so I know how they work.

Can you offer any pointers how to make this code "better" or am I doing it the best I can?


texts:
Project Euler - 22

Names scores

  Using names.txt (right click and 'Save Link/Target As...'), a 46K text
    file containing over five-thousand first names, begin by sorting it
    into alphabetical order. Then working out the alphabetical value for
    each name, multiply this value by its alphabetical position in the
    list to obtain a name score.

  For example, when the list is sorted into alphabetical order, COLIN,
    which is worth \$3 + 15 + 12 + 9 + 14 = 53\$, is the 938th name in the
    list. So, COLIN would obtain a score of \$938 × 53 = 49714\$.

  What is the total of all the name scores in the file?

While being fairly comfortable with the zen of Python, Julia is very new to me. Is the following code in line with Julia's vision?

In particular I feel my handling of the dictionary is sub-optimal and especially the way i hard-code remove the parenthesis in names.

Every hint on how to improve the code is welcome.

ALPHABET_INDEX = Dict( letter => index for (index, letter) in enumerate('A':'Z'))

function namescore(name)
    return sum(ALPHABET_INDEX[letter] for letter in name[2:end-1])
end

function sort_file(filename)
    file = open(filename)
    sort(split(readstring(filename),","))
end

function PE_022(filename="p022_names.txt")

    total = 0
    for (index, name) in enumerate(sort_file(filename))
        total += index*namescore(name)
    end
    total
end

println(PE_022())


texts:
I'm working on a task from the one of Coursera programming courses. The purpose is to estimate the amount of inversions that are required to sort the array of numbers.

Also I'm trying to learn some Haskell basics, here is my solution:

fsthalf :: [a] -> [a]
fsthalf xs = take (length xs `div` 2) xs

sndhalf :: [a] -> [a]
sndhalf xs = drop (length xs `div` 2) xs

union :: ([Int], Int) -> ([Int], Int) -> ([Int], Int)
union (a, ac) (b, bc) = (a++b, ac+bc)

merge :: ([Int], Int) -> ([Int], Int) -> ([Int], Int)
merge ([], ac) (bs, bc) = (bs, ac + bc)
merge (as, ac) ([], bc) = (as, ac + bc)
merge (a:as, ac) (b:bs, bc)
  | a <= b = ([a], 0) `union` merge (as, ac) (b:bs, bc)
  | otherwise = ([b], length(a:as)) `union` merge (a:as, ac) (bs, bc)

mergeSort :: ([Int], Int) -> ([Int], Int)
mergeSort (s, c)
  | length s `elem` [0, 1]  = (s, c)
  | otherwise = merge (mergeSort (fsthalf s, c)) (mergeSort (sndhalf s, c))

main :: IO()
main = do
  _ <- readLn :: IO Int
  rawValues <- getLine
  let intValues = map read $ words rawValues :: [Int]
  print $ snd $ mergeSort (intValues, 0)

It seems to work properly, but exceeds time limits. It takes from 9 to 10 seconds to sort the longest possible list of integers (100000 values), while the limit is 6 seconds. Could anyone please point out some possible optimizations for this solution.


texts: Efficient string concatenations with DOM

texts:
I form DOM nodes as strings and append them to DOM tree like below using jQuery.

var dom = '

first name
'
             '
last name

';

$("#contacts").append(dom);

The above code is a small sample. In most of my cases dom will hold big strings.

When I recently read about JS performance tutorials, I saw this post. It mentioned that this way of string concatenation is not a good practice. It mentioned the use of .join() instead of concatenation. That seems like an old post, so which one is efficient in these days?


texts:
Please review this implementation of thread-safe chache.

public class StaticCacheImpl<T extends Entity> implements StaticCache<T>
{

    private boolean set = false;

    private List<T> cachedObjects = Collections.synchronizedList(new ArrayList<T>());

    @Override
    public synchronized boolean isSet() {
        return set;
    }

    @Override
    public synchronized void put(List<T> cachedList) {
        if (!set) {
            cachedObjects.addAll(cachedList);
            set = true;
        }
    }

    @Override
    public synchronized List<T> get() {
        return cachedObjects;
    }

    @Override
    public synchronized boolean contains(UUID uuid) {
        if(set) {
            for (T t : cachedObjects) {
                if (ObjectUtils.equals(uuid, t.getId())) {
                    return true;
                }
            }
        }

        return false;
    }

    @Override
    public synchronized T getById(UUID uuid) {
        if(set) {
            for (T t : cachedObjects) {
                if (ObjectUtils.equals(uuid, t.getUuid())) {
                    return t;
                }
            }
        }
        return null;
    }
}


texts: jQuery animate opacity, fade, & slide up page load effect

texts:
This is the first time I've actually made my own jQuery script from scratch, because I couldn't find exactly what I was looking for.  My code works how I want it to, although I don't know if I did it correctly.  Just something about it is screaming to me, and although it works, I didn't do it properly.  So I figured I would share what I have and see what you had to offer as a better way to accomplish this.

$(window).load(function() {
    $('.overlay').animate({
        opacity: 1,
        height: '0'
    }, 1000, function(){$(this).remove()});

    $("#frame").delay(300).animate({
        opacity: 1
    }, 300)
});

I have ran it though a JavaScript compressor which removed the ;s, and then through a "beautifier" for readability, but it still seems to work.  I'm not even too sure how important those are in JavaScript.  I'm a CSS guy and I know in CSS the last ; is not required, so figured I'd leave them out since it's working.

I set up an example of this in action here.

If anyone has any suggestions on my code as this being my first real attempt at jQuery, I would love some feedback.


texts:
I put this together and am having some doubts to the number of connections I can make. I also doubt if I can brute force the server to serve up connections and then hang.

Please take a look and tell me what I can do better.

'''
    Simple socket server using threads
'''

import socket
import sys
from thread import *

HOST = '192.168.0.102'   # Symbolic name meaning all available interfaces
PORT = 8887 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Socket created'

#Bind socket to local host and port

try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)

print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
        print data

        reply = 'OK...' + data + str(addr)
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))

s.close()


texts: Authorization checks for editing attributes of a task

texts:
Model:

class Task extends Model {
}

with fields

protected $fillable = ['message', 'due_time', 'status'];

I've added special functions public function getEditableStateForAttributeName().

In my helper function I check that if method_exists($class, 'getEditableStateForFieldName'), then I check the boolean value returned by this method to decide whether to allow editing this field.

Example:

if( ! $cls->getEditableStateForDueTime() ) {
    return "You can not edit field due time";
}

Real code:

private function isCreator() {
     $user = Auth::user();
     if($user) {
         return $user->id === $this->creator_id;
     }
     return false;
}

public function getEditableStateForMessage() {
     return $this->isCreator();
 }

public function getEditableStateForDueTime() {
     return $this->isCreator();
}

public function getEditableStateForStatus() {
    return $this->isCreator() && $this->status === 'CREATED';
}

Is this a good way to do it or it is very bad design because of hidden dependency on Auth::user()?

What is a better way?

I do not want to put this logic inside controllers because this logic propagates to another models and is universal across application.

I've written some helper functions which facilitates validation of my models

Inside controller I simply write

createValidatorForModel(Task::class)

and it returns new validator with custom errors/custom attributes names/additional checks/etc.


texts:
I'm not used with perl but had the need to add a couple of features, I wish I can adopt a more perl-ish  coding.

Any help is welcome.

This is to add style classes to paragraphs if strarting with !, ? and a clear: both with %

Original:

foreach (@grafs) {
    unless (defined( $g_html_blocks{$_} )) {
        $_ = _RunSpanGamut($_);
        s/^([ \t]*)/
/;
        $_ .= "
";
    }
}

Modded:

foreach (@grafs) {
    unless (defined( $g_html_blocks{$_} )) {
        $_ = _RunSpanGamut($_);
        if ( m/^[ \t]*\?/ ){
            s/^([ \t]*\?[ \t]*)/
/;
        } elsif ( m/^[ \t]*\!/ ){
            s/^([ \t]*\![ \t]*)/
/;
        } elsif ( m/^[ \t]*%/ ){
            s/^([ \t]*%[ \t]*)/
/;
        } else {
            s/^([ \t]*)/
/;
        }
        $_ .= "
";
    }
}

This is to add float to images like: !<[alt](url) to get a float right (and form this the % above to clear)

if (defined($align)) {
    if ($align eq "<") {
        $result .=  " style=\"float: left; margin: 0 ${padding}px ${padding}px 0;\"";
    } else {
        $result .=  " style=\"float: right; margin: 0 0 ${padding}px ${padding}px;\"";
    }
}


texts:
I am almost completing my BlackJack game in Javascript. But I realize that there must be a way to improve the performance for these two methods. Any pointers?

const hasAceInHand = (cardsOnHand) => {
    for (let key in cardsOnHand) {
        let arr = cardsOnHand[key];
        for (let i = 0; i < arr.length; i++) {
            let obj = arr[i];
            for (let prop in obj) {
                if (prop === "face") {
                    if (obj[prop] === "A") {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

const countHandValue = (cardsOnHand) => {
    //console.log(hasAceInHand(cardsOnHand));
    let sum = 0;
    for (let key in cardsOnHand) {
        let arr = cardsOnHand[key];
        for (let i = 0; i < arr.length; i++) {
            let obj = arr[i];
            for (let prop in obj) {
                if (prop === "faceValue") {
                    //console.log(prop + " = " + obj[prop]);
                    sum = sum + obj[prop];
                    debugger;
                    if (sum > 21 && hasAceInHand(cardsOnHand)) {
                        // Transfer Ace's face value from 11 to 1
                        sum = sum - 11;
                        sum = sum + 1;
                    }
                }
            }
        }
    }

    return sum;
}

This countHandValue method is called at below:

const cardSuit = ["hearts", "diams", "clubs", "spades"];
const cardFace = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"];

// In JavaScript, functions are objects.
// You can work with functions as if they were objects.
function card(suit, face) {
    this.suit = suit;
    this.face = face;

    switch (face) {
        case "A":
            this.faceValue = 11;
            break;
        case "J":
        case "Q":
        case "K":
            this.faceValue = 10;
            break;
        default:
            this.faceValue = parseInt(face);
            break;
    }
};

const deck = {
    cards: []
}

var tempCard;
const player = {
    cards: [],
    handValue: 0
}

const dealer = {
    cards: [],
    handValue: 0
}

const dealOneCardToPlayer = () => {
    // Take a card from the top deck to be assigned to tempcard.
    tempCard = deck.cards.splice(0, 1);
    player.cards.push(tempCard);
    player.handValue = countHandValue(player.cards);
    document.getElementById("handValuePlayer").innerHTML = player.handValue;
    makeCardPlayer(tempCard[0]);
}

I have uploaded the whole program.


texts: Moving from normal threads to ExecutorService thread pools in java

texts:
I had my original threading code which worked well, but since my tasks were shortlived, I decided to use thread pools through ExecutorService.

This was my original code

public class MyRun implements Runnable
{
    private Socket socket = null;
    public MyRun(Socket s)
    {
        socket = s;
        thread = new Thread(this, "SocketThread");
        thread.start();
    }
    public void run()
    {
        // My actual thread code
    }
}

My main program

...
ss = new ServerSocket(port);
....
MyRun st = null;
while (!stop)
{
    st = new MyRun(ss.accept());
    st = null;
}

New code

public MyRun(Socket s)
{
    socket = s;
    thread = new Thread(this, "SocketThread");
}

run() left unchanged

Changed Main program

private static ExecutorService execService = Executors.newCachedThreadPool();
....
....
while (!stop)
{
    execService.execute(new MyRun(ss.accept()));
}

Changed code seems to be working fine, but I just want to make sure there is nothing I am missing. I want all threads to execute simultaneously.


texts:
We have a lot of phone numbers that contain dashes and start with a zero which are from another country.

I am trying to strip the dashes and the one leading zero and select the country code from a drop-down box.

I'm using "raw" JS with DOM here (for the sake of not having to pull in a framework):

<html>
<head><title>Dash Remover</title></head>
<body>
<form method="POST">
<select id="countryCallingCode">
    <option value="0043">+43</option>
    <option value="0044">+44</option>
    <option value="0049">+49</option>
    <option value="">Other</option>
</select>
<input id="numbertodial" type="text" size="16"
       oninput="prepareTelNo()" />

<button name="callBtn" onclick="callTelNo();">Call!</button>
</form>

<script>
function getCCC() { return document.getElementById('countryCallingCode').value; }

function prepareTelNo() {
    var wd = document.getElementById('numbertodial');
    wd.value = wd.value.replace(/-/g, ''); // strip - from the tel. no.

    // Cut off leading zeros
    if(wd.value.charAt(0) === '0' & getCCC() != "")
        wd.value = wd.value.substring(1);
}

function callTelNo() {
    var telNo = document.getElementById('numbertodial').value;
    window.alert('Calling '+getCCC()+telNo);
}
</script>
</body>
</html>

Any room for improvement? I know that oninput is only supported in some browsers.

That's ok, it's for an intranet app that is usually used with IE 10.


texts:
Question: Is having a master class bad practice? I am making a simple pong game, but I'm writing the code as if I were making for something that might be for something more complicated I want to create in the future. Also, am I not doing it in a good manner?

What I am doing: I have a class, in this case "engine", which basically holds everything and runs all of its referenced objects logic inside of its own functions. All of the other objects are then linked to each other by holding the data of the "world or engine" object and use it as a linker to other objects that it can interact with.

NOTE: The sfml media library was used with this project.
note: if you need the ball definitions i'll post them

#include <SFML/Graphics.hpp>

#include <vector>
#include <iostream>
#include <stdlib.h>

class paddle;
class ball;
class enemy;
class player;

class engine{
    ball *gameBall;
    enemy *enemyPaddle;
    player *playerPaddle;
    Clock gameClock;
    RenderWindow &refWindow;
    int gameSpeed;
    Event windowEvent;

    void eventDraw();
    void eventUpdate();
    void handleWindow();

public:
    engine( RenderWindow &rendy);
    ~engine();
    bool start();
    Vector2f getWindowSize();
    void drawPart(Drawable &art);
    Time getGameClock(){ return gameClock.getElapsedTime(); }
};

class ball{
private:
    CircleShape myShape;
    engine& world;
    int radius;
    Color color;
    Vector2f position, velocity;
    short signed int dirX, dirY;
    short signed int getDirection();
    void wallBounce();
public:
    ball( engine& gameEngine);
    void draw();
    CircleShape getCircle(){ return myShape; }
    void pop();
    void update();
};

int main()
{
    RenderWindow window(VideoMode(640, 480), "Pong");
    engine gameEngine( window );
    return (int)gameEngine.start();
}

// Class Prototyes
    // Engine
        engine::engine(RenderWindow &rendy):refWindow(rendy){
            gameBall = new ball(*this);
            enemyPaddle = new enemy;
            playerPaddle = new player;
            gameClock = Clock();
            gameSpeed = (1000/60.0);
            windowEvent = Event();
        }
        engine::~engine(){
            delete enemyPaddle;
            delete playerPaddle;
            delete gameBall;
        }

        void engine::handleWindow(){
            if ( refWindow.pollEvent( windowEvent ) )
            {
                 if ( windowEvent.type == Event::Closed )
                     refWindow.close();
            }
        }

        bool engine::start()
        {
            while( refWindow.isOpen() )
            {

                while( gameClock.getElapsedTime().asMilliseconds() > gameSpeed )
                {
                    eventUpdate();
                    eventDraw();

                    // Restart Clock
                        gameClock.restart();
                }

                handleWindow();
            }

            return true;
        }

        void engine::eventUpdate(){
            gameBall->update();

        }
        void engine::eventDraw(){
            refWindow.clear( Color::Black );

            gameBall->draw();

            refWindow.display();
        }

        Vector2f engine::getWindowSize(){
            Vector2f tempVec;
            tempVec.x = refWindow.getSize().x;
            tempVec.y = refWindow.getSize().y;
            return tempVec;
        }

        void engine::drawPart(Drawable &art){
            refWindow.draw( art );
        }


texts: Hashtag Creator: Find frequent words and display their occurrences

texts:
I've done a Python script to find frequent keywords from raw texts and display them along with source sentences and texts. But, having not exercised my Python for an age, I'm sure the code is full of smell. Any pointers would be warmly appreciated.

import os
import nltk
import string
import json
from datetime import datetime
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords

class Word:
    """Stores data relating to individual words."""

    def __init__(self, spelling):
        self.spelling = spelling
        self.sentences = []
        self.frequency = 0
        self.found_in = []

    def add_sentences(self, *sentences):
        [self.sentences.append(s) for s in sentences]

    def to_json(self):
        structure = {self.spelling: {"Sentences": self.sentences, "Documents": self.found_in}}
        return structure

class Hashtagger:
    """Extracts frequent words from text, and the sentences in which they are found."""

    def __init__(self, raw_text):
        self.raw_text = raw_text
        self.words = []
        self.sentences = []
        self.stopword_list = stopwords.words('english') # words to not process
        self.lemmatizer = nltk.WordNetLemmatizer() # groups inflections to single word
        self.process_text()

    def process_text(self):
        self.process_words(self.raw_text)
        self.deconstruct_sentences(self.raw_text)
        self.allocate_sentences_to_all()

    def process_words(self, text):
        stripped_text = self.strip_punctuation(text)
        tokens = nltk.Text(word_tokenize(stripped_text))
        content = [self.lemmatizer.lemmatize(t.lower()) for t in tokens if t not in self.stopword_list]
        counts = {t: content.count(t) for t in content}

        for token, count in counts.items():
            word = Word(token)
            word.frequency = count
            self.words.append(word)

    def deconstruct_sentences(self, text):
        raw_sentences = nltk.sent_tokenize(text)
        self.sentences = [s.strip(string.punctuation) + '.' for s in raw_sentences]

    def allocate_sentences_to(self, word):
        sentences_containing = [s for s in self.sentences if word.spelling in s.lower()]
        word.add_sentences(*sentences_containing)

    def allocate_sentences_to_all(self):
        [self.allocate_sentences_to(key) for key in self.words]

    def strip_punctuation(self, text):
        for ch in string.punctuation:
            text = text.replace(ch, ' ')
        return text

class ResultsAccumulator:
    """Accumulates the results of many hashtaggers."""

    def __init__(self):
        self.word_tally = []

    def add_tally(self, hashtagger, file=None):
        for h_word in hashtagger.words:
            matched = False
            for word in self.word_tally:
                if word.spelling == h_word.spelling:
                    word.add_sentences(*h_word.sentences)
                    word.frequency += h_word.frequency
                    word.found_in.append(file)
                    matched = True
                    break
            if not matched:
                h_word.found_in.append(file)
                self.word_tally.append(h_word)

    def write_word_json(self):
        total_json = {}
        for word in self.word_tally:
            total_json.update(word.to_json())
        return total_json

def main():
    path = r'test_docs/'

    results = ResultsAccumulator()

    for file in os.listdir(path):
        with open(os.path.join(path, file), encoding='utf8') as d:
            raw_text = d.read()

        hashtagger = Hashtagger(raw_text)
        results.add_tally(hashtagger, file)

    final_tally = results.write_word_json()

    datestring = datetime.strftime(datetime.now(), '%Y-%m-%d-%H-%M-%S')
    with open('word_json_' + datestring + '.txt', 'w') as f:
        json.dump(final_tally, f, indent=4,
              ensure_ascii=False)

if __name__ == '__main__':
    main()


texts: Find sub-list index with the closest to a given number sum

texts:
The task that I have to perform is to take an array of a specific length, and figure out which sub-list has the closest sum to another given number. Then, I need to print the index of that sub-array.
For anyone that doesn't understand this problem, we add up indexes of the given list and the moment their sum exceeds or is equal to the required amount of power (the second number in the second line of the input), we append it to another list and then we append the index of the number we started to count from and the index of the number we stopped adding up to a third list. Afterwards, we start from the next index. For example, in this input, if we start counting from the list index 0, we will see that if we keep adding up until index 6, the sum will be 28. We keep repeating this, but this time from the index 1, then 2, 3, 4 etc. When we finish, we will realise that the number with the closest sum to 23 are the numbers 7, 8, 9 which range from 6 to 8 and have a sum of 24. So, we print: 6 8.
And if anyone is wondering, if we end up with multiple ranges that meet the criteria, we will choose, according to the problem statement, the nearest to the entrance, the one with the
lowest starting index and the lowest ending index. In our case we have looked out for it, because every time time we append the indexes sum in server_lst we append their indexes too at the same time in index_lst. So, the indexes that are printed are the first ones that have the best sum.
num_of_cases = int(input())
for case in range(num_of_cases):
    num_of_servers, c_power = map(int, input().split())
    server_lst = list(map(int, input().split()))
    server_total = []
    server_index = []
    j = 0
    total = 0
    k = 0

    def servers(lst, k):
        global total
        global j
        for i in range(k, len(lst)):
            if total < c_power:
                total += lst[i]
                j += 1
            else:
                server_total.append(total)
                j += k
                server_index.append([k, j-1])
                j = 0
                total = 0
                break

    def execute(server_lst, k):
        for i in range(len(server_lst)):
            k = i
            servers(server_lst, k)
        min_pow = min(server_total)
        winner = server_total.index(min_pow)
        mf = server_index[winner]
        print('Case #{}:'.format(case+1), *mf )

    execute(server_lst, k)

The problem that I am currently encountering is that, although it works, it takes around 10 minutes to run 10MB inputs. Is there anyway that I can improve it so it runs faster?
Here is a very simple input:
1
10 23
1 2 3 4 5 6 7 8 9 10

and the output to this is:
Case #1: 6 8

The constraints are:

1 ≤ num_of_cases ≤ 20.
1 ≤ servers ≤ 100 000.
1 ≤ amount of power required(c_power) ≤ 1 000 000 000.
1 ≤ power of every server(every index in server_lst) ≤ 1 000 000, for i = 0 … N − 1

Thanks in advance.


texts: HttpURLConnection response code handling

texts:
This snippet from a downloader callable handles HTTP status codes. I need critique on both the style (for or do-while loop better here?) and functionality. Should I manage the delay differently? Do I need to handle InterruptedException specifically?

HttpURLConnection connection = null;
boolean connected=false;
outer:
for(int retry=0;retry<=RETRIES&&!connected;retry++)
{
 if(retry>0) {log.warning("retry "+retry+"/"+RETRIES);Thread.sleep(RETRY_DELAY_MS);}
 connection = (HttpURLConnection)entries.openConnection();
 connection.connect();
 switch(connection.getResponseCode())
 {
  case HttpURLConnection.HTTP_OK: log.fine(entries +" **OK**");connected=true;break; // fine, go on
  case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: log.warning(entries+" **gateway timeout**");break;// retry
  case HttpURLConnection.HTTP_UNAVAILABLE: System.out.println(entries+ "**unavailable**");break;// retry, server is unstable
  default: log.severe(entries+" **unknown response code**.");break outer; // abort
 }
}
connection.disconnect();
log.severe("Aborting download of dataset.");


texts:
package com.goman;

public class BST {

    private BST left;
    private BST right;
    private int data;

    public BST(int data, BST left, BST right){
        this.left = left;
        this.right = right;
        this.data = data;
    }

    public BST insert(BST node, BST root){
        if(root == null){
            return node;
        }

        if(root.data > node.data){
            root.left = insert(node, root.left);
        } else if(root.data < node.data){
            root.right = insert(node, root.right);
        } else{
            System.out.println("Duplicate valuesa are not allowed");
            return root;
        }

        return root;
    }

    @Override
    public String toString() {
        return "BST [left=" + left + ",right=" + right + ",data=" + data
                + "]";
    }

    public void inOrder(BST root){
        if(root==null){
            return;
        }
        inOrder(root.left);
        System.out.println(root.data);
        inOrder(root.right);
    }
}

class Test{
    public static void main(String[] a){
        BST root = new BST(5, null, null);
        root.insert(new BST(3, null, null), root);
        root.insert(new BST(8, null, null), root);
        root.insert(new BST(2, null, null), root);
        root.insert(new BST(4, null, null), root);
        root.inOrder(root);
        System.out.println(root);
    }
}


texts:
I currently try to learn some Haskell to improve my overall programming skills. To practice, I implement the C course exercises that I very familiar with. One is this:

  Write a function that finds an array (needle) inside of another array (haystack). Return the index where the first match starts. If it cannot be found, return -1.

So in C, this is implemented using a couple of loops:

int array_find(char *hay, char *nee, int hay_len, int nee_len) {
    int hay_idx, nee_idx;
    for (hay_idx = 0; hay_idx < hay_len - nee_len; hay_idx++) {
        for (nee_idx = 0; nee_idx < nee_len; nee_idx++) {
            if (hay[hay_idx + nee_idx] != nee[nee_idx]) {
                break;
            }
        }
        if (nee_idx == nee_len) {
            return hay_idx;
        }
    }

    return -1;
}

The following is my attempt in Haskell. I made comments which probably state the obvious for Haskell experts but it should make my reasoning clear.

-- Public function, searches the haystack for a needle and returns the index
-- (zero-based).
arraySearch :: (Eq a) => [a] -> [a] -> Maybe Int
arraySearch h n = arraySearchNext (arraySearchBegin h n 0) h n 0

-- Searches the haystack starting from the next position if the last search has
-- failed.
arraySearchNext :: (Eq a) => Maybe Int -> [a] -> [a] -> Int -> Maybe Int
-- The previous search has found something, so that is the first occurence of
-- the needle.
arraySearchNext (Just i) _ _ _ = Just i
-- The previous search has not given us anything but we are out of haystack.
-- Therefore nothing could be found.
arraySearchNext Nothing [] _ _ = Nothing
-- The previous search has not found anything but there is some haystack left.
-- We will try the search again by shifting by one and then shift again.
arraySearchNext Nothing (h:hs) n i =
    arraySearchNext (arraySearchBegin hs n (i + 1)) hs n (i + 1)

-- Looks whether the needle can be found at the beginning of the haystack.
arraySearchBegin :: (Eq a) => [a] -> [a] -> Int -> Maybe Int
-- In case we managed to finish the needle, we must have found something.
arraySearchBegin _ [] i = Just i
-- In case the haystack is empty, but the needle is not (pattern above), we
-- have not found anything.
arraySearchBegin [] _ _ = Nothing
-- There is still some haystack and needle left. If the first element each
-- matches, we must go on. Otherwise this won't be a match.
arraySearchBegin (h:hs) (n:ns) i
    | h == n        = arraySearchBegin hs ns i
    | otherwise     = Nothing

main = print $ arraySearch [1..10] [5..6]

Since there are so many lines and I have a bunch of helper functions, I wonder whether there is some better way‽


texts:
I have been wanting to learn programming for some time now and decided to really give it a shot today. I have edited and read lots of things in Java to fix small issues but never written from scratch. I've tried C and Java but both seemed just a bit too much to teach myself as a first language, so I'm going with Python first.

Can anyone look through this little sample random number generator I made and point out anything I should be doing differently or correctly? It is executing without issues for me but I'm sure I've got extra nonsense in here. I just have all the prints to see a result of each step and I know this is not what a real random number generator would be like.  I'm just testing and learning my way around different aspects of the language.

import random

x = int(raw_input("Please enter a number up to 100. "))
z = random.randint(40,100)
""" x and z can both be used below without errors -- testing/learning"""

randomNumber = random.randint(1,z)
print "first random",randomNumber

if 35 >= randomNumber:
    newRandom = randomNumber * .5
    newRandom = newRandom + 9
    print "second random " "%.f" % newRandom

elif 36 <= randomNumber <= 93:
    newRandom = randomNumber + 7
    print "second random " "%.f" % newRandom

else:
    newRandom = randomNumber
    print "second random",newRandom


texts: Converting from a madlib program using hashmaps to using 3 different arrays to hold the noun, verb, and adjectives

texts:
Using erb and Sinatra, I need to make an array of each variable that can be added in, [noun], [verb] and [adjective], allowing me to return the number of each there are and create the appropriate amount of form boxes for each to take in the user input. Then it would read through the MadLib string again and replace the brackets with the corresponding inputs. I could use some help on refactoring this to use arrays instead of HashMaps.

class MadLib
    def initialize(input)
        @input_string = read_file(input)
        p @parsed_inputs = parse(@input_string)
        @hashed_input_values = {}
    end

    def take_input
        @parsed_inputs.each do |key|
        parse_key = key.match(/:/)
        if parse_key
            print "Enter #{parse_key.post_match}: "
            value = STDIN.gets.chomp
            @hashed_input_values["[#{key}]"] = value
            @hashed_input_values["[#{parse_key.pre_match}]"] = value
            @parsed_inputs.delete(parse_key.pre_match)
        else
            print "Enter #{key}: "
            @hashed_input_values["[#{key}]"] = STDIN.gets.chomp
            p @hashed_input_values
        end
        end
       @hashed_input_values
    end

    def print_output
        @input_string.gsub(/\[(\w*:*\w)]/i, @hashed_input_values)
    end

    def parse(input)
        # f = File.open(input)
        input.scan(/\[(\w*:*\w)]/i).flatten
    end

    def read_file(file_name)
        file = File.read(file_name)
    end
  private :parse

end

madlib = MadLib.new(ARGV[0])
madlib.take_input
puts "#{madlib.print_output}"


texts:
I needed a better string formatting options like ToUpper and ToLower but I also wanted to be able to use the default formattings so I created a custom formatter. It's main purpose is to support a template engine where the user should be able to use different formattings like upper or lower case. I still however couldn't figure out how to be make the date time upper case.

public class ExtendableFormatter : IFormatProvider, ICustomFormatter
{
    public IDictionary<Type, IFormatProvider> FormatProviders { get; set; }

    public ExtendableFormatter()
    {
        FormatProviders = new Dictionary<Type, IFormatProvider>
        {
            { typeof(Byte), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(SByte), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(Int16), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(Int32), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(Int64), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(UInt16), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(UInt32), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(UInt64), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(Single), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(Double), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(Decimal), CultureInfo.InvariantCulture.NumberFormat },
            { typeof(DateTime), CultureInfo.InvariantCulture.DateTimeFormat },
            { typeof(String), new StringCaseFormatter() }
        };
    }

    public object GetFormat(Type formatType)
    {
        return formatType == typeof(ICustomFormatter) ? this : null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        var fp = (IFormatProvider)null;
        if (FormatProviders.TryGetValue(arg.GetType(), out fp))
        {
            formatProvider = fp;
        }

        format = string.IsNullOrEmpty(format) ? string.Empty : ":" + format;
        var result = string.Format(formatProvider, "{0" + format + "}", arg);
        return result;
    }

}

public class StringCaseFormatter : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        return formatType == typeof(ICustomFormatter) ? this : null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        switch (format)
        {
            case "U": return arg.ToString().ToUpper();
            case "L": return arg.ToString().ToLower();
            default: return arg.ToString();
        }
    }
}

Example:

string.Format(
    new ExtendableFormatter(),
    "foo {0:U} baz {1,-5:f1} {2:ddMMMyy}",
    "qux", 1.234f, DateTime.Now).Dump();

Result:

  foo QUX baz 1.2   05Jun16


texts:
Hello all I have a short question. Is this a good and secure way to connect to my DB ?
session_start();

$servername = "localhost";
$un = "username";
$password = "password";
$dbname = "project";

$timezone = date_default_timezone_set("America/New_York");

// Create connection
$con = mysqli_connect($servername, $un, $password, $dbname);

if($con == true) {
}

// Check connection
if ($con->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}


texts: Processing eBay category list for database import

texts:
Although I've been programming a fair while I'm learning Python and would like to know how I can make my code more "Pythonic".

I'm have a CSV file of eBay categories, containing the name and numeric code which I want to import in to my database. Unfortunately the file does not include a 'parent' category ID for each row, instead it uses the ordinal position of the name in row to indicate the nesting level:

L1,L2,L3,L4,L5,L6,Category ID
Antiques,,,,,,20081
,Antique Clocks,,,,,13851
,,Bracket Clocks,,,,100904
,,,Pre-1900,,,66840
,,,Post-1900,,,96762
,,Cuckoo Clocks,,,,13850
,,Longcase/ Grandfather Clocks,,,,100905
,,,Pre-1900,,,60249
,,,Post-1900,,,96763
,Antique Furniture,,,,,20091
,,Armoires/ Wardrobes,,,,98436

I've written a Python script to process the file, which is working correclty and generating the output I need, but I would like to know how it can be improved.

The script below is slightly changed from the one I am using, with simplified output (making it less verbose) but if anyone is interested in the other version which generates a JSON file for importing in to a Django site database, let me know.

I wanted to process the file line-by-line and avoid loading all the data in to memory, in case the file being processed is huge. So it uses a stack to record the parent category ID, other than that very little information is stored.

import csv

class Stack:
    def __init__(self):
        self.items = []

    def push(self, o):
        self.items.append(o)

    def pop(self, n=1):
        while n > 1:
            self.items.pop()
            n -= 1
        return self.items.pop()

    def peek(self, n=1):
        return self.items[-n] if len(self.items) >= n else 'null'

def extract_info(row):
    """
    :param row: data extracted from the csv file
    :return: level (number), the name of the category (string), category ID (number)

    Steps through the csv row until the first populated field (category name)
    and then returns the nesting level, category name and ID (which is always in
    the last field of the row.
    """
    level = 0
    for field in row:
        if field:
            return level, field, row[-1]
        level += 1

id_stack = Stack()

with open('UK_New_Structure_(Oct2015).csv', 'rb') as csvfile:
    rdr = csv.reader(csvfile, delimiter=',', quotechar='"')
    # Skip three header rows
    next(rdr)
    next(rdr)
    next(rdr)
    first_row = next(rdr)
    parent_id = 'null'  # top level categories do not have a parent

    level, name, cat_id = extract_info(first_row)
    print level, name, cat_id, parent_id
    id_stack.push(cat_id)  # Save first parent ID
    last_level = -1

    for row in rdr:
        level, name, cat_id = extract_info(row)

        if level == last_level:  # remove the newly added parent id, last item was not a parent
            id_stack.pop()
            parent_id = id_stack.peek()
            id_stack.push(cat_id)
        elif level < last_level:
            id_stack.pop(last_level - level + 1)
            parent_id = id_stack.peek()
            id_stack.push(cat_id)
            last_level = level
        elif level > last_level:
            parent_id = id_stack.peek()
            id_stack.push(cat_id)
            last_level = level

        print level, '..' * level, name, cat_id, parent_id

I am using Python 2.7.10, but if there are better ways to do this in Python 3, then I'm interested in those as well.


texts: Can I optimize two for loops that look for the closest zip code based on lat/lon?

texts:
I am new to python and I had the task to find the US zip code based on latitude and longitude. After messing with arcgis I realized that this was giving me empty values for certain locations. I ended up coding something that accomplishes my task by taking a dataset containing all US codes and using Euclidean distance to determine the closest zip code based on their lat/lon. However, this takes approximately 1.3 seconds on average to compute which for my nearly million records will take a while as a need a zip code for each entry. I looked that vectorization is a thing on python to speed up tasks. But, I cannot find a way to apply it to my code. Here is my code and any feedback would be appreciated:
for j in range(len(myFile)):
    p1=0
    p1=0
    point1 = np.array((myFile["Latitude"][j], myFile["Longitude"][j]))  # This is the reference point
    i = 0
    resultZip = str(usZips["Zip"][0])
    dist = np.linalg.norm(point1 - np.array((float(usZips["Latitude"][0]), float(usZips["Longitude"][0]))))
    for i in range(0, len(usZips)):
        lat = float(usZips["Latitude"][i])
        lon = float(usZips["Longitude"][i])
        point2 = np.array((lat, lon))  # This will serve as the comparison from the dataset
        temp = np.linalg.norm(point1 - point2)
        if (temp <= dist):  # IF the temp euclidean distance is lower than the alread set it will:
            dist = temp  # set the new distance to temp and...
            resultZip = str(usZips["Zip"][i])  # will save the zip that has the same index as the new temp
            # p1=float(myFile["Latitude"][58435])
            # p2=float(myFile["Longitude"][58435])
        i += 1

I am aware Google also has a reverse geocoder API but it has a request limit per day.
The file called myFile is a csv file with the attributes userId, latitude, longitude, timestamp with about a million entries. The file usZips is public dataset with information about the city, lat, lon, zip and timezone with about 43k records of zips across the US.


texts: Extension methods with reusable logic - passing Action to Func

texts:
I have several extension methods for interacting with the Google Calendar API, and these all use an ExecuteWithRetry function for wrapping API calls within retry logic:

private static readonly int maxAttempts = 4;
private static readonly int retryFirst = 5000;
private static readonly int retryExponent = 4;

private static async Task<TResponse> ExecuteWithRetryAsync<TResponse>(Func<Task<TResponse>> func)
{
  TResponse response = default;
  for (var attempt = 1; attempt <= maxAttempts; attempt++)
  {
    try
    {
      response = await func();
      break;
    }
    catch (Google.GoogleApiException) when (attempt < maxAttempts)
    {
      var backoff = retryFirst * (int)Math.Pow(retryExponent, attempt - 1);
      await Task.Delay(backoff);
    }
  }
  return response;
}

public static async Task<IList<Event>> FetchAllWithRetryAsync(this EventsResource.ListRequest listRequest, DateTime? after = null, DateTime? before = null)
{
  listRequest.TimeMin = after;
  listRequest.TimeMax = before;
  var pageStreamer = new PageStreamer<Event, EventsResource.ListRequest, Events, string>(
    (request, token) => request.PageToken = token,
    response => response.NextPageToken,
    response => response.Items
  );
  return await ExecuteWithRetryAsync(() => pageStreamer.FetchAllAsync(listRequest, CancellationToken.None));
}

public static async Task<TResponse> ExecuteWithRetryAsync<TResponse>(this IClientServiceRequest<TResponse> request)
  => await ExecuteWithRetryAsync(() => request.ExecuteAsync());

public static async Task ExecuteWithRetryAsync(this BatchRequest request)
  => await ExecuteWithRetryAsync(async () => { await request.ExecuteAsync(); return Task.FromResult(0); });

General feedback welcome.

I'm particularly uneasy about the last function. Basically BatchRequest.ExecuteAsync() returns a Task rather than a Task<TResponse>, so I'm using

async () => { await request.ExecuteAsync(); return Task.FromResult(0); }

for it to be accepted as a Func<Task<TResponse>>. Is there a cleaner way of doing this?


texts:
I have written [PHP code][ to upload image/s to server.

(To see the result, open the JavaScript console of your browser, look at the Network tab or the Console tab.)

The code is also available and runnable on paste.ofcode.org.

(Upload images)

I would like to know if this code is secure for uploading valid images.

<?php
$IMAGE_SIZE = 2097152; // 2mb ht tp:/ /ww w.convertunits.com/from/MB/to/byte
$MAX_IMAGES = 30;
if(!empty($_FILES['fileToUpload']['name'][0])) {
    foreach($_FILES["fileToUpload"]['tmp_name'] as $key=>$imgLocation){}
    if($key<$MAX_IMAGES){
        foreach($_FILES["fileToUpload"]['tmp_name'] as $key=>$imgLocation){
            if($imgLocation){//filename exist
                $imageName = $_FILES["fileToUpload"]['name'][$key];
                if(checkMime($imgLocation)&&
                    checkExtension($imageName)&&
                    checkByExif($imgLocation)&&
                    checkSize(filesize($imgLocation))&&
                    checkImageName($imageName)){
                    echo $usr_dir = "img/".changeImageName($imageName).".".getExtension($imageName);
                    if(move_uploaded_file($imgLocation, $usr_dir)){
                        echo "
success full  uploaded
";
                    }else{
                        echo "
 File Not uploaded
";
                    }
                }else{  echo "
Invalid File
";}
            }else{echo " No Image uploaded";}
        }
    }else echo "
 - Only 30 Images are allowed -
";
}else{
    echo "No Image Is selected";
}
function handleError($msg){
    //return json_encode();
}
function checkImageName($imagename){
    $imagename = pathinfo($imagename, PATHINFO_FILENAME);
    if(strpbrk($imagename, "\\/?%*' :|\"<>") === FALSE&&$imagename){
        if (strlen($imagename) >= 1 && strlen($imagename)<= 30){
            return true;
        }else{
            return false;
        //HandleError('Invalid file name');
        }
    }else{
        return false;
    }
}
function issetImage($image_tmpName){
    return (file_exists($image_tmpName) || is_uploaded_file($image_tmpName));//return ture and false
}
function checkMime($image_tmpName){
    if(issetImage($image_tmpName)){
        $whitelist = array("image/gif","image/png","image/jpeg","image/jpg","image/bmp");
        $imageinfos = getimagesize($image_tmpName);
        $imageTypes = $imageinfos['mime'];
        if(in_array($imageTypes, $whitelist)){
            return true;
        }else{
            return false;
        }
    }
    else{
        return false;
    }
}
function checkExtension($imageName){
    $ext = getExtension($imageName);
    if(strtolower($ext) == "jpg" || strtolower($ext) == "png" || strtolower($ext) == "jpeg" || strtolower($ext) == "gif" || strtolower($ext) == "bmp"){
        return true;
    }else{
        return false;
    }
}
function checkByExif($image_tmpName){
    if(issetImage($image_tmpName)){
        $image_type_allowed = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_BMP);
        $filetype =exif_imagetype($image_tmpName);
        if (in_array($filetype, $image_type_allowed)){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
function checkSize($imageSize){
    return ($imageSize<= $GLOBALS["IMAGE_SIZE"] && $imageSize>=1) ? true : false;
}
function changeImageName($imgName){
    return md5(pathinfo($imgName, PATHINFO_FILENAME))."_".time();
}
function getExtension($fullImageName){
    if($fullImageName)
        return pathinfo($fullImageName,PATHINFO_EXTENSION);
}
?>


texts:
I have two functions, one to convert a datetime to a hex word, and one to convert a word to a datetime. I was just wondering if there was a more efficient way to convert back and forth.

/// <summary>
/// Converts a date time to a hexadecimal word
/// </summary>
/// <param name="date">the date time</param>
/// <returns>returns the Hex value of the date</returns>
private int convertToWordFromDate(DateTime date)
{
  int m, d, y;

  int month = date.Month;
  int day = date.Day;
  int year = int.Parse(date.Year.ToString().Substring(2, 2));

  int yearShift = 9;
  int monthShift = 5;
  int word;

  y = year << yearShift;
  m = month << monthShift;
  d = day;

  if (year == 0)
    word = m + d + (y * 100);
  if (year < 10)
    word = (m + d + y) * 16;
  else
    word = m + d + y;

  return word;
}

/// <summary>
/// Converts a hexadecimal word to a valid dateTime
/// </summary>
/// <param name="word">the word</param>
/// <returns>the date time</returns>
private DateTime convertToDateFromWord(int word)
{
  int month, day, year;
  int monthMask = 0x01E0;
  int dayMask = 0x001F;
  int yearMask = 0xFE00;
  int monthShift = 32;
  int yearShift = 512;
  DateTime date = new DateTime();

  try
  {
    year = (word & yearMask) / yearShift;
    month = (word & monthMask) / monthShift;
    day = (word & dayMask);

    if (year >= 80 && year <= 99)
      year += 1900;
    else if (year >= 0 && year <= 79)
      year += 2000;
    else if (year < 0 || month <= 0 || day <= 0)
    {
      year = 1;
      month = 1;
      day = 1;
    }
    else
    {
      year = 1;
      month = 1;
      day = 1;
    }
    date = new DateTime(year, month, day);
  }
  catch
  {
    date = new DateTime(1, 1, 1);
  }

  return date;
}


texts:
This program orders the lines of a text file alphabetically and prints them out to a new text file.

Usage:

java Arranger input.txt output.txt

Is this the best and especially the most performant way?

import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.ArrayList;

/*
 * this program arranges the lines of a text file in it's alphabetical order
 * usage: java Arranger input.txt output.txt
 */

public class Arranger {

    public static void main(String[] args) {

        File inputFile = new File(args[0]);
        File outputFile = new File(args[1]);
        ArrayList<String> words = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
            // read lines of file and order them
            String line = new String();
            while ((line = reader.readLine()) != null) {
                words.add(line);
            }
            words.sort(String::compareToIgnoreCase);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // write ordered list of words to file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
            for (String word : words) {
                writer.write(word + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}


texts: Inventory of objects with item types and quantities

texts:
I am thinking about how an inventory could be designed. The requirements for this inventory will be the following:

There will be predefined item types in the inventory.
The user can define new item types and add them to the inventory.
In the interaction with the GUI the user will be shown the item types contained in the inventory and he will click a "+" or a "-" to increase/decrease the quantity of that item.

The initial design I have come up with is the following:

Item.java

public class Item {

    private String name;
    private String itemId;
    private int quantity;

    public Item(String name, String itemId) {
        this.name=name;
        this.itemId=itemId;
        this.quantity=0;
    }

    public void add() {
        this.quantity++;
    }

    public void remove() {
        this.quantity--;
    }

    public String getName() {
        return this.name;
    }

    public String getItemId() {
        return this.itemId;
    }

    public int getQuantity() {
        return this.quantity;
    }

    public String toString() {
        String s="";
        s+=" name = "+this.name;
        s+=" , id = "+this.itemId;
        s+=" , quantity = "+this.quantity;
        return s;
    }
}

and Inventory.java :

public class Inventory {
    private ArrayList<Item> items = new ArrayList<Item>();

    public Inventory() {
        this.items.add(new Item("Book", "4877326352"));
        this.items.add(new Item("Pen", "21366363636"));
    }

    public void increaseQuantity(String itemName) {
        for (Item item : this.items) {
            if (itemName.equals(item.getName())) {
                item.add();
                return;
            }
        }
    }

    public void decreaseQuantity(String itemName) {
        for (Item item : this.items) {
            if (itemName.equals(item.getName())) {
                if (item.getQuantity()>=0) {
                    item.remove();
                }
                return;
            }
        }
    }

    public void createItem(String name, String itemId) {
        this.items.add(new Item(name,itemId));
    }

    public String toString() {
        String s="";
        s+="Inventory contains:\n";
        for (Item item:this.items) {
            s+='\t'+item.toString();
        }
        return s;
    }

    public void printInventory() {
        System.out.println(this.toString());
    }

    public static void main(String[] args) {
        Inventory inventory = new Inventory();
        inventory.printInventory();
        inventory.increaseQuantity("Book");
        inventory.increaseQuantity("Pen");
        inventory.printInventory();
        inventory.decreaseQuantity("Book");
        inventory.printInventory();
        inventory.createItem("Pencil", "92827234534");
        inventory.printInventory();
        inventory.increaseQuantity("Pencil");
        inventory.printInventory();
    }

}

Now of course there are some issues with this implementation. (e.g there are no checks for creating duplicate item types etc...), yet these issues can be solved easily.

But the thing that worries me the most is the fact that Item has quantity as a field. Is that considered bad design?

If quantity was not a field in item then I guess Inventory would have an ArrayList of items, and increaseQuantity() would invoke items.add(new Item()). But then, isn't it pointless to have duplicate items in an ArrayList when all you need to know is what kind of items you have and in what quantity?


texts: Bash script - compile and run c++ code for coding competitions

texts:
This is a simple bash script that I use to compile and run single C++ files for coding competitions.
Features:

Detects if there is a corresponding .in file next to it, and if so uses that as stdin

e.g. if the file problem1.cpp and problem1.in are in the same directory, the script will redirect stdin from problem1.in

Compile each file to a temp directory so it doesn't clutter the working directory
Configurable g++ warning flags as needed

Note: \033[32m and \033[0m are terminal color codes that make the text green
#!/bin/bash
# Compiles and runs .cpp code
# if there exists an .in file next to the .cpp file
# it will use that as input

if [ -z $1 ]; then
  echo -e "Please choose an input file"
  exit 1
fi

FILE="$1"
FILE_IN="${FILE%.*}.in"

clear
echo -e "\033[32mCompiling...\033[0m"
TMPFILE=$(mktemp /tmp/run-cpp.XXXXXXXXXX)
WARNING_FLAGS="-Wuninitialized -Wmaybe-uninitialized"
g++ $FILE -std=c++17 $WARNING_FLAGS -O3 -o $TMPFILE

if [ $? -eq 0 ]; then
  echo -e "\033[32mRunning...\033[0m"
  if [ -f $FILE_IN ]; then
    $TMPFILE < $FILE_IN
  else
    $TMPFILE
  fi
  ERROR=$?
fi
rm $TMPFILE 2> /dev/null
exit $ERROR

Usage:
./runcpp.sh /path/to/my-cpp-file.cpp


texts:
I am running through a file and inserting elements one by one. The counties all contain specific county codes which are duplicated many times throughout the file. I am looking for a way to assign these codes to a specific county while ignoring duplicate county codes.

I have two versions I wrote below with runtimes:

getCodes()

def get_codes(data):
    code_info = {}
    for row in data:
        county = row["county"]
        code = int(float(row["code"]))
        if code > 100000:
            code = code/100
        if county not in code_info:
            code_info[county] = []
        code_info[county].append(code)
    for county in code_info:
        code_info[county] = list(set(code_info[county]))
    return code_info

get_codes2()

def get_codes2(data):
    code_info = {}
    for row in data:
        county = row["county"]
        code = int(float(row["code"]))
        if code > 100000:
            code = code/100

        if county in code_info:
            if not code in code_info[county]:
                code_info[county].append(code)
        else:
            code_info[county] = []
            code_info[county].append(code)
    return code_info

county_data = csv.DictReader(open("county_file.txt"))
start = time.time()
county_codes = get_codes(county_data)
end = time.time()
print "run time: " + str(end-start)

county_data = csv.DictReader(open("county_file.txt"))
start = time.time()
county_codes = get_codes2(county_data)
end = time.time()
print "run time: " + str(end-start)

Also, it's probably obvious from this, but county codes that are greater than 100000 can have trailing zeroes accidentally added, so I'm removing them by dividing by 100. As another note, the int(float()) conversion is intentional. Sometimes the county codes are values such as "27.7" and need to be converted to "27", other times they are just basic ints.

The runtimes on my system:

get_codes: 9 seconds
get_codes2: 14 seconds

How can I improve this further for better performance?


texts: Grab Text storing it in a var then adding html method and adding animation to it

texts:
I want to know the correct way to finish up this code at the bottom. I'm thinking there has to be a better way to grab content from one section of your site and displaying it somewhere else with animation attached to it. The Code below seems like it can do better. I post the entire code below, but you might be able to understand what i'm trying to accomplish just by reading this few lines of code. I left comments to help

// Find what input field was clicked
var formVaule = $('input[value="' + ValUe + '"]');

// Find the content and store it.
var k = formVaule.next().text();

// Display H2 tag with the content that was stored
$('#' + ValUe).html('
' + k + '
');

// Animated the h2 tag with a background color
$('#' + ValUe).find('h2').animate({ backgroundColor: "#40822B" }, 100,

// Call a callback function with the attention of removing the background.
function() {

    $('#' + ValUe).find('h2').animate({  backgroundColor: "white"}, 500);

});

Full code Below

<form>
    <input type="radio" name="form" value="informed"/>
    INFORMED CONSENT

    <input type="radio" name="form" value="release"/>
    RELEASE OF INFORMATION

    <input type="radio" name="form" value="intake"/>
    INTAKE FORM

    <input type="radio" name="form" value="checklist"/>
    CHECKLIST OF CONCERNS (CHILD & ADOLESCENT AND ADULT)

    <input type="radio" name="form" value="health"/>
    HEALTH INFORMATION PRIVACY FORM

</form>

1

2

3

4

5

6