pairwise maximum product

So I started doing the Coursera course for Algorithsm, mostly since I was spending a lot of time on SNS and not really learning anything. I thought to might as well start with a lil programming since I have long left it tbh.

For the first week of the course, I had a very simple problem statement

In this problem, we’re given an array, or a sequence of n numbers. And our goal is to find a number which can be obtained by multiplying some two numbers from this sequence.

So there would be two inputs when you run the program like –

3

1 2 3

The output should be the largest number, which is a multiplication of the pair, in this case it would be 6.

For another sample input

4

-10000 -20000 10 20

The output would be 20000000 because multiplying two negative numbers gives you a positive number. I was able to solve it however only after doing a stress test with multiple implementations and matching the results of each one. It really did take a lot of time to reach the answer or maybe I wasted a lot of time in not going to the stress test option first.

Below is a working and 100% successfuly solution. Do try it out and let me know if you guys have any problems running it.

require 'bigdecimal'
# Input the number of numbers
n = readline
# Input the list of numbers
array_list = readline.split(' ')
# Initializing the variables
max1 = BigDecimal("0")
max2 = BigDecimal("0")
min1 = BigDecimal("0")
min2 = BigDecimal("0")
min1_index = 0
max1_index = 0
# Finding the Biggest and Smallest Number and storing their index
array_list.each_with_index do |value, index|
if BigDecimal(value) > 0
if max1 < BigDecimal(value)
max1 = BigDecimal(value)
max1_index = index
end
end
if BigDecimal(value) < 0
if min1 < BigDecimal(value) * -1
min1 = BigDecimal(value) * -1
min1_index = index
end
end
end
#Finding the second biggest and smallest numbers.
array_list.each_with_index do |value, index|
if BigDecimal(value) > 0
max2 = BigDecimal(value) if BigDecimal(value) <= max1 and BigDecimal(value) > max2 and max1_index != index
end
if BigDecimal(value) < 0
min2 = BigDecimal(value) * -1 if BigDecimal(value) >= min1 * -1 and BigDecimal(value) < min2 * -1 and min1_index != index
end
end
#Checking if any of them is 0, else multiplying them accordingly
if( min1 != 0 or min2!= 0 or max1 != 0 or max2 !=0)
if(max1 * max2 < min1 * min2)
result1 = (min1 * min2)
else
result1 = (max1 * max2)
end
else
result1 = min1 * max1
end
#outputting to a format to pass the tests in Coursera
puts result1.to_s("F").split(".")[0]

Why to-do apps for JavaScript frameworks

Somehow whenever I see some new Javascript framework, most of them always have the same To-Do application as their showcase sample. If someone/ some company is going to build a new framework and going to tell me, we built an awesome framework you can do so much with that and then they go ahead and give me a sample of a To-Do application, anyone would be like meh!!

How difficult can a to-do application be that the said framework is going to make your life much easier.

Just wrote a small to-do app myself, it only needs 1 single line of javascript, yup you read that right.

<!doctype html>
<html>
<head>
<title>Sample To-Do</title>
<style type="text/css">
section {margin: 0 auto;width: 100%;}
h3, h5, li {float: left;width:100%;}
ul {list-style: none;}
input[type=checkbox], p { float:left;margin: 0;}
</style>
</head>
<body>
<section>
<h3> To-Do Application</h3>
<h5> Add your todo below</h5>
<div>
<textarea id="newtodo" placeholder="Enter your todo here..."></textarea>
<button id="newtodosub" onclick="addtodo();">Add</button>
</div>
<ul id="todos"></ul>
</section>
<script type="text/javascript">
function addtodo() {
document.getElementById("todos").insertAdjacentHTML('beforeend',
'<li id="todoitem"><input type="checkbox" onclick="function rem(el) {el.parentElement.lastElementChild.style='
+ '\'float:left;text-decoration:line-through\';el.setAttribute(\'disabled\', \'disabled\')};rem(this);" />'
+ '<p style="float:left;">&nbsp;&nbsp;&nbsp;' + document.getElementById("newtodo").value + '</p>'
+ '</li>'
);
}
</script>
</body>
</html>
view raw todo.html hosted with ❤ by GitHub

All the things you need are –

  1. Text area for the To-do
  2. Button to add it.
  3. Checkbox to mark the todo complete.

The addtodo() function inside the <script> tag is what does all of this.

I feel designers, developers need to come up with something more innovative than a todo list app. Just saying!

Script Processor in EDQ is cool

So I started with a bit of work on EDQ and I must say its a pretty neat tool. Basically Oracle EDQ stands for Enterprise Data Quality where you get to fix all the invalid, inconsistent and simply put bad, very bad, very very bad data.

I was just playing with it a bit and found the script processor very handy since I could do anything I want with use of a scripting language like javascript or groovy.

I just wrote a sample script to have convert the currency values of products from one currency to another. Maybe this could help someone writing a script for the first time in EDQ.

Here is what my data looks like –

+--------+--------------+------------+-----------------+
| Value | Convert From | Convert To | Converted Value |
+--------+--------------+------------+-----------------+
| 100.14 | INR | USD | |
| 290.19 | INR | GBP | |
| 310.05 | INR | EUR | |
| 110.67 | INR | CAD | |
| 200 | EUR | EUR | |
| 10 | EUR | GBP | |
| 3 | EUR | INR | |
| 6 | GBP | INR | |
| 6 | EUR | INR | |
+--------+--------------+------------+-----------------+

I created a quick web service on mockable.io. It is a pretty neat tool where you can create a web service to output any data that you want to, here is the sample data I created –

{"base":"EUR","rates":{"CAD":1.4469,"HKD":8.4742,"ISK":139.3,"PHP":55.538,"DKK":7.471,"HUF":339.28,"CZK":25.344,"AUD":1.6565,"RON":4.805,"SEK":10.5813,"IDR":15221.86,"INR":77.9195,"BRL":4.7741,"RUB":71.2368,"HRK":7.4605,"JPY":120.13,"THB":34.664,"CHF":1.0606,"SGD":1.5204,"PLN":4.3094,"BGN":1.9558,"TRY":6.6981,"CNY":7.6329,"NOK":10.2113,"NZD":1.7273,"ZAR":16.4555,"USD":1.0875,"MXN":20.806,"ILS":3.7429,"GBP":0.8415,"KRW":1322.29,"MYR":4.5952}}

And finally here is the code of the script processor which will convert the values to specific currency, the data used is pretty self explanatory.

addLibrary("http");
var output1;
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://demo7684243.mockable.io/curr_rates&quot;, false);// Here goes your web service URL
xmlHttp.send();
var responseData = xmlHttp.responseText;
var dataJSON = JSON.parse(responseData);
var baseCurr = dataJSON["base"];
var baseCurrRate = dataJSON["rates"];
var convertFrom = input1[1];
var convertTo = input1[2];
var convertFromRate = dataJSON["rates"][convertFrom];
var convertToRate = dataJSON["rates"][convertTo];
if (convertFrom == convertTo) {
convertToRate = 1;
convertFromRate = 1;
}
if (convertTo == baseCurr) {
convertToRate = 1;
}
if (convertFrom == baseCurr) {
convertFromRate = 1;
}
var convertedVal = (input1[0] * convertToRate) / convertFromRate;
output1 = convertedVal.toFixed(2);

There are few things which I am sure, you would know if you have used EDQ before.

  1. All inputs and outputs have to be used in the form of array. input1[0], input1[1], input1[2] and so on will be automatically mapped with your columns which you would have selected.
  2. There can be only one output of the script and you need to store it in output1 variable only.
  3. You can simply ignore the logic of Currency conversion in the code, since this is for a very specific task.

All this was just to show you how you can manipulate data with the use of Web Services in EDQ. Hope this helps 🙂

Fetch Data from Web Services in Excel Macro

Since the time I have started working in Enterprise Solutions. There is only one universal truth, everything can be done in Microsoft Excel. Murphy Law fits it completely, what can happen will happen in Excel.

Having said that, just wrote a small snippet to call Web Service from Excel Macro. The code is pretty self explanatory.

Private Sub FetchData()
Dim objRequest As Object, strUrl As String, blnAsync As Boolean, strResponse As String
Dim jsonObject As Object, item As Variant
Set objRequest = CreateObject("MSXML2.XMLHTTP")
strUrl = "<URL_GOES_HERE>"
blnAsync = True
With objRequest
.Open "GET", strUrl, blnAsync
.setRequestHeader "Content-Type", "application/json"
.Send
While objRequest.readyState <> 4
DoEvents
Wend
strResponse = .ResponseText
End With
End Sub

“strResponse” will store the return data in requested format”. In my case I had data coming in JSON format, there is however no native support to read that, I had to use a 3rd party JSON library

Dim jsonObject As Object, item As Variant
Set jsonObject = JsonConverter.ParseJson(strResponse)
For Each item In jsonObject
'do something with json object
Next item

Details on the Library @ https://github.com/VBA-tools/VBA-JSON

SOAP XML – A different way to pass nil

I have been working on some standard Oracle ERP Cloud SOAP payloads and found something different.

Suppose you want to update the End Date field on the Trading Partner Item, you can simply send the below request to set the date.

<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/&quot;
xmlns:typ="http://xmlns.oracle.com/apps/scm/productModel/items/tradingPartnerItems/tradingPartnerItemServiceV2/types/&quot;
xmlns:trad="http://xmlns.oracle.com/apps/scm/productModel/items/tradingPartnerItems/tradingPartnerItemServiceV2/&quot; >
<soapenv:Header/>
<soapenv:Body>
<typ:updateTradingPartnerItem>
<typ:tradingPartnerItem>
<trad:TradingPartnerItemId>300000063693002</trad:TradingPartnerItemId>
<trad:EndDate>2019-09-21</trad:EndDate>
</typ:tradingPartnerItem>
</typ:updateTradingPartnerItem>
</soapenv:Body>
</soapenv:Envelope>

However what if you want to make the field update to no value or null value, or simply blank, however you want to put it.

In that scenario, you cannot simply use any of the below forms of the XML Attributes.

<!-- 1. --> <trad:EndDate>NULL</trad:EndDate>
<!-- 2. --> <trad:EndDate>nil</trad:EndDate>
<!-- 3. --> <trad:EndDate></trad:EndDate>

The only way in which you can achieve the operation i.e. setting the attribute to no value in the database is, if you pass it in the below format.

<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/&quot;
xmlns:typ="http://xmlns.oracle.com/apps/scm/productModel/items/tradingPartnerItems/tradingPartnerItemServiceV2/types/&quot;
xmlns:trad="http://xmlns.oracle.com/apps/scm/productModel/items/tradingPartnerItems/tradingPartnerItemServiceV2/&quot;
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;
<soapenv:Header/>
<soapenv:Body>
<typ:updateTradingPartnerItem>
<typ:tradingPartnerItem>
<trad:TradingPartnerItemId>300000063693002</trad:TradingPartnerItemId>
<trad:EndDate xsi:nil="true" />
</typ:tradingPartnerItem>
</typ:updateTradingPartnerItem>
</soapenv:Body>
</soapenv:Envelope>

A different namespace is also required for setting the xsi:nil=”true”. Make sure you include that in your request.

5000+ lines of SQL Query

Why you should not use online code formatting tools? Coz most of them suck at their job.

A friend wrote a query for an Oracle Report which had 52 unions and spanned over 5000 lines. Tested and all working fine, before saving the report, she decided to format and indent the code using an online code formatter one of many many available all across the internet.

And it broke it just enough to not run anymore and just not enough to notice the difference immediately.

The error message was pretty clear that one of the unions had less/more number of selected columns but no message on which union, thanks to the bad code analyzer of Oracle BI EE.

As always, ruby magic always comes to rescue when you are in a tight pinch.

def analyse file_path
file = File.open(file_path, "r")
counter = 0 # counter for having a 2D Array
writefile = false
array = Array.new
file.readlines.each do |line|
if line.start_with? "SELECT"
writefile = true;
array[counter] = Array.new
end
if line.start_with? "FROM"
writefile = false;
counter = counter + 1
end
array[counter].push line.strip if writefile == true
end
require 'csv'
CSV.open('.\working_output_analysis.csv', 'w+') do |csv|
array.each { |ar| csv << ar }
end
end

The code is pretty straight forward to read. It starts with the line starting with “SELECT” and ends before the line starting with “FROM”. We had a total of 52 unions, so I just needed to store that list of selected columns from all these 52 unions in an Array. We cannot really define a 2-D array in Ruby however we can always define an Array within an Array and that solves our purpose of Multi dimensional Array.

The script provided us a nice sheet with all the column names and helped in figuring out the incorrect SELECTED list of columns from a specific union list.

Phew!!

Light it up!

So I got myself a 1m strip of WS2812B LEDs or commonly known as individually addressable 5050 LED ICs. I saw a lot of youtube videos on infinity mirror and thought if the same concept can be applied to creating a clock and voila! lots of people have already done that in the past.

To be very honest it doesn’t not look like a very difficult project to accomplish. So I went ahead and got myself an Arduino Mega Rev 3.

Here are the steps I used to make the LEDs glow like a clock hands move.

  • My first step was to find a suitable power supply, I didn’t get one with the strip so I just had to search for my mobile chargers and check which one was suitable. Most of them had a voltage rating of 5V but I needed one with a higher Ampere rating.

Each 5050 LED IC needs around 60mA and I had a total of 60 LED ICs.

So power required is simply = 60 * 60 mA = 3.6 A

Thankfully my One Plus phone charger had a 4A rating. So it fit the budget just fine.

  • I simply cut the USB cable I had with the charger and found the two thicker wires which had to be the ones with +5V and Neutral. I checked it with my newly bought Mastech Multimeter to confirm.

Excited that the power supply of my mobile charger met my LED requirements so amazingly I connected both and turned on the power.

Aaanddd!! it did not light up 😦 I thought maybe my connections are weak, so I redid them again and again and again and it never worked. The LEDs just wouldn’t light up.

I tried to measure the current flowing through the LED strip and there was definitely current flowing through so the circuit was continuous. So even if some of the LEDs were not working, some of them should have lit up. I spend the next few hours trying to test if power is flowing through LEDs randomly and it was.

But still no glow.

Google didn’t help all that much since I never thought that the strip didn’t light up coz I was not sending any control/data signals to it.

Finally I figured it out the next day, I connected it to my arduino and imported the FASTLED library. The code sample was easy enough to test and I modified it as per my LED Strip and here is the code to run a simple clock on a LED Strip with 60 LEDs.

#include <FastLED.h>
int led = 13; // Usually the orangle led is set at pin 13.
#define LED_PIN 6 // data pin to be connected to WS2812B
#define NUM_LEDS 60
#define LED_TYPE WS2812B // make sure to choose the correct LED TYPE.
#define COLOR_ORDER GRB
#define BRIGHTNESS 200
#define FRAMES_PER_SECOND 60
bool gReverseDirection = true;
CRGB leds[NUM_LEDS];
void setup() {
pinMode(led, OUTPUT);
delay(2000);
FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.setBrightness( BRIGHTNESS );
}
// the loop routine runs over and over again forever:
void loop() {
delay(1000); // wait for a second
leds[0] = CRGB::Red;
leds[1] = CRGB::Orange;
leds[2] = CRGB::Green;
FastLED.show();
delay(1000);
FastLED.clear();
}

Hope this helps anyone who is just starting up. I will post the code for lighting up the LEDs like a clock in the next blog post.

Oracle why you bug!!

So I have been using OBIEE for some time now for reporting purpose in my organization. Although its an easy to use tool there are good amount of bugs in it and for such a widely used tool some of the bugs outright seems stupid.

For instance you cannot delete records properly from a Fixed Value List if it has more than 10 records.

Here is a sample of that, I created a Fixed list with 10 + records. See how it asks for deletion of the element correctly but deletes an element different altogether. It should have deleted “Record 12” but deleted “Record 2”

The reason is simply bad coding. So there is a javascript function “LovPanel.NVEntry.remove” which does the removal of record from the list. But it does not work!!

Oracle if you are listening fix this.

How to send Notification in Android App

We are going to do a quick tutorial today on how we can generate notifications in Android. Although the standard Android Guide does explain it, but I dont think its a very quick way to understand stuff.

So here we go.

Here are the basic steps –

  1. Create a notification channel
  2. Build a notification
  3. Send a notitification.

How do we create a notitification channel, we do it simply by keeping in mind that we need a unique channel id(“1000111”) and channel name(“cld_notif_channel”). The values do not matter, however they need to be unique.

private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("1000111", "cld_notif_channel", NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("cld_notif_desc");
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}

The notitification channel can be invoked as many number times as required, although once invoked and available it will just not create another if its already present. I would suggest to create your notitification channels as soon as your application opens.

The way you do it is simply by calling the createNotificationChannel() function in your Main Activity.

Step 2 involves creating the notification itself. There are few basic things we need to take care of, it must have a Small Icon available, this one is mandatory along with the Channel Id, which we created above.

final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "1000111")
.setContentTitle("Notification Title")
.setSmallIcon(R.drawable.ic_stat_name)
.setContentText("Notification Text")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);

Step 2.5 involves creating a notification manager which is actually going to be responsible for sending out notifications.

final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

Step 3 involves obviously firing the notification and sadly this again requires a unique id(“1001”) to uniquely identify the notification and send it.

notificationManager.notify("1001", builder.build());

And there you go, its so simple it hardly would take 10 minutes of your time to learn how to send notifications in your Android application.

*Note – where you see *this* that is android.content.Context so this goes inside your class for the activity.

A blog a day challenge

I am going to start with the blog a day challenge. Simply put for the next 100 days I am going to write a blog every single day without fail on any topic.

I need to invest a considerable amount of time in learning new things for career growth and my own as well. Having a regular blog should help in prioritising the activities in that direction.