Android App ep.102

My Network Reporter v.2

For this project we are going to be recreating the network reporter application in Kotlin to look at the advantages and uniqueness Kotlin can provide.

Previous application utilizing java: Android App ep.101

Application Purpose:

This will remain the same as the last application….

We want to discern if transmitting a file of a size A across a network with a speed B gives us a reasonable time in seconds.

Our size of the file size is measured in MiB and our network speed is measured in Mbps.

We know that 1 B = 8 b; 1 MiB = 220 B; 1 Mbps = 106 bps.

Video to view in action: https://youtu.be/JUkxk5NhutM

activity_main.xml  Layout


This will remain the same as well since we just want to look at the benefits of Kotlin to Java.

Screen Shot 2018-10-15 at 8.44.27 AM

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingHorizontal="10dp"
        android:text="@string/file_size_label"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textSize="14sp" />

    <EditText
        android:id="@+id/fileSizeInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/file_input_hint"
        android:inputType="number" />

</LinearLayout>

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

    <TextView
        android:id="@+id/networkSpeedLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/network_label"
        android:textAlignment="center"
        android:textSize="14sp" />

    <EditText
        android:id="@+id/networkSpeedInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/network_hint"
        android:inputType="number" />
</LinearLayout>

<TextView
    android:id="@+id/resultDisplay"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Input is needed for both File Size and Network Speed to estimate time"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="18sp" />

On our Kotlin side…


package com.amsuarez.mynetworkreporter

import android.app.Activity
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    fun EditText.changed() {
       this.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
            override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {
                if (fileSizeInput.text.toString() == "" || networkSpeedInput.text.toString() == "") {
                    resultDisplay.text = "Input is needed for both File Size and Network Speed to estimate time"
                } else {
                    val myb = Integer.parseInt(fileSizeInput.text.toString()).toDouble() * Math.pow(2.0, 20.0) * 8.0
                    val mybps = Integer.parseInt(networkSpeedInput.text.toString()) * Math.pow(10.0, 6.0)
                    resultDisplay.setText(String.format("%.1f", myb / mybps) + " seconds")
                }
            }
            override fun afterTextChanged(s: Editable) {}
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        fileSizeInput.changed()
        networkSpeedInput.changed()
    }
}

Here we utilized some really cool features that Kotlin provides us with.

Extension Functions:

We utilized these to extend upon the EditText class to allow us to run a text watcher object in any EditText. This gives us a very clean call in our onCreate fun increasing readability.

Where are the findViewByIds? 👀

Kotlin provides a feature that allows us to reference straight out of our activities.

It is done by importing:

 import kotlinx.android.synthetic.main.activity_main.*

This allows us to no longer need to call findViewById and instead we can reference directly into our activities.

Objects? 🤔

Here we use object as an anonymous class that inherits TextWatcher allowing us to override the TextWatcher without having to “formally declare a new class”.

For more on Objects: https://kotlinlang.org/docs/reference/object-declarations.html

 

Android App ep.101

 

My Network Reporter

For this project we are going to be creating a simple application using TextFields, EditText, and a TextWatcher.

This tutorial assumes you know basic information about widgets and Java programming

Application Purpose:

We want to discern if transmitting a file of a size A across a network with a speed B gives us a reasonable time in seconds.

Our size of the file size is measured in MiB and our network speed is measured in Mbps.

We know that 1 B = 8 b; 1 MiB = 220 B; 1 Mbps = 106 bps.

Video to view in action: https://youtu.be/JUkxk5NhutM

activity_main.xml  Layout


Screen Shot 2018-10-15 at 8.44.27 AM.png

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

    <TextView
        android:id="@+id/textView"
        android:layout_width="96dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:paddingHorizontal="10dp"
        android:text="@string/file_size_label"
        android:textAlignment="center"
        android:textAllCaps="false"
        android:textSize="14sp" />

    <EditText
        android:id="@+id/fileSizeInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/file_input_hint"
        android:inputType="number" />

</LinearLayout>

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

    <TextView
        android:id="@+id/networkSpeedLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/network_label"
        android:textAlignment="center"
        android:textSize="14sp" />

    <EditText
        android:id="@+id/networkSpeedInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/network_hint"
        android:inputType="number" />
</LinearLayout>

<TextView
    android:id="@+id/resultDisplay"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Input is needed for both File Size and Network Speed to estimate time"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="18sp" />

Here we kept it as simple as possible using two linear layouts to block each input and label and a separate TextView to display a result.

 

On our Java side…


public class MainActivity extends AppCompatActivity {
    EditText fileSize;
    EditText networkSpeed;
    TextView result;

     // Here we use a TextWatcher to see if there are any changes.
    TextWatcher watchChange = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if(fileSize.getText().toString().equals("") || networkSpeed.getText().toString().equals("")){
                result.setText("Input is needed for both File Size and Network Speed to estimate time");
            }
            else {
               // this section calculates the time to send.
                Double myb = Integer.parseInt(fileSize.getText().toString()) * Math.pow(2, 20) * 8;
                Double mybps = Integer.parseInt(networkSpeed.getText().toString()) * Math.pow(10, 6);
                result.setText(String.format("%.1f", myb / mybps) + " seconds");
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         // this section assigns our java code to the xml android widgets
        fileSize        = (EditText) findViewById(R.id.fileSizeInput);
        networkSpeed    = (EditText) findViewById(R.id.networkSpeedInput);
        result          = (TextView) findViewById(R.id.resultDisplay);
        
        //this assigns the TextWatcher to both entry fields
        fileSize.addTextChangedListener(watchChange);
        networkSpeed.addTextChangedListener(watchChange);
    }
}

For more on TextWatchers visit Android documentation here : https://developer.android.com/reference/android/text/TextWatcher

Medium: Article: https://medium.com/@austinmsuarez/android-app-ep-101-83e0f0af8aa0

File Transfer Protocol

Here is a project I worked on with python sockets for transferring information to and from a server. I will continue to work on functionalities such as transferring different file types and other improvements.

https://github.com/austinmsuarez/FTP 

Project Description:

This project gives an example of a file transfer protocol client-server model.

Contributors (github)

Austin Suarez: austinmsuarez
Blake Molina:  molinab297
Paul Miller:     
Hassan Hamod: hhamod@csu.fullerton.edu
Curtis Laudenslayer: ibcurly

Language Used

Python 3.6.4 was used for the implementation of this project

How to Execute Program

Open two terminal windows, one for client and one for server.
In one window, type python3 testClient.py <hostname> <port number>
In the other window, type python3 testServer.py <port number>

Commands

ftp> get <file name> (downloads file <file name> from the server)
ftp> put <filename> (uploads file <file name> to the server)
ftp> ls (lists files on the server)
ftp> lls (lists files on the client)
ftp> quit (disconnects from the server and exits)

Reverse Words in a String

Problem 🤔

Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.

Example 1:

Input: “Let’s take LeetCode contest”

Output: “s’teL ekat edoCteeL tsetnoc”

Note: In the string, each word is separated by single space and there will not be any extra space in the string.

Code

def reverseWords(self, s):
    s = s.split(" ")

    for words in range(0,len(s)):
        s[words] = s[words][::-1]

    s = ' '.join(s)
    return s

Developer’s Notes 👨‍💻

Here I took advantage of what python had to offer such as the split and join methods.

I first split the string where there was a ” ” and put them into a list.

I then cycled through the list reassigning the index with the reverse of the word.

    I reversed the word using a reverse step method s[begin:end: step] with step being -1

After I had reversed all the words I joined them back into a string with a space between each index.

Array Partition

Problem 🤔

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).

Code

def quickSort(self,nums, low, high):
    if low < high:
        part = self.partition(nums, low,high)
        self.quickSort(nums,low,part-1)
        self.quickSort(nums,part+1,high)

def partition(self, nums, low, high):
    i = (low - 1)
    pivot = nums[high]
    for j in range(low, high):
        if nums[j] <= pivot:
            i += 1
            nums[i],nums[j] = nums[j],nums[i]
    nums[i+1],nums[high] = nums[high],nums[i+1]
    return(i+1)

def arrayPairSum(self, nums):
    temp = 0
    self.quickSort(nums,0,len(nums)-1)
    for index in range(0,len(nums)-1,2):
        temp += min(nums[index],nums[index+1])
    return temp

Developer’s Notes 👨‍💻

For this I ordered the list using a quicksort, then I cycled through the array took the pairs of numbers and summed the mins. I ordered the array since it would give the largest possible minimum for each pair.

ReverseNum

reverseNum

Problem

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123

Output:  321

Example 2:

Input: -123

Output: -321

Example 3:

Input: 120

Output: 21

Code

def reverse(self, x):

    y = str(x)

    #checks the number if negative it removes the - sign

    if y[0] == '-':

        negative = True

        y = y[1:]

        else:

            negative = False

    #reverses the string [begin:end:step]

    x = y[::-1]

    #if it is negative reverse the sign

    if negative:

        x =  '-' + x

    #checks to make sure it doesnt overflow the 32bit

    if(abs(int(x)) > (2 ** 31 - 1)):

        x = 0

    return(int(x))

Developer’s  Notes

There are a couple of ways to tackle this problem. Here I decide to take advantage of Python’s ability of string manipulation.

I converted the number to a string, checked for a negative, then reversed the string adding the negative if necessary.  At the end of the script, I made sure it was less than the 32bit requirement by a size comparison and returned the result.

Hamming Distance

Problem

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

1   (0 0 0 1)

4   (0 1 0 0)

          

Code

def distanceFinder(self,x,y,count):

    if x%2 != y%2:

        count+=1

    print(count)

    if x/2 == 0 and y/2 == 0:

        return count

    return self.distanceFinder(int(x/2),int(y/2),count)

def hammingDistance(self, x, y):

    return self.distanceFinder(x,y,0)

Developer’s Notes

For this problem, I took a basic recursion approach and tested the distance by finding if then modulus of 2 is different. If it is different then I increment a counter. Once the numbers are 0 then it returns the counter. Since the algorithm uses recursion and depths by half each time the BigO looks to be O(log x). It is due to the fact that x and y are the same lengths.

Back to Basics

It has been a while since I have posted and for somewhat good reasons. This past couple of weeks I have been bombarded with interviews, projects, and an assortment of random things. I have also taken some time to reflect on what I want this blog to be about. At the basic level, I want it to be a place where I can work out my thoughts and post interesting problems and that’s what I’m gonna do. Hope anyone reading this enjoys or can follow my randomness! 🙃