Sunday, September 27, 2020

How to connect to your FREE Autonomous Database using Python from Cloud Shell?

 

Image for post
Cloud Shell open
$ oci db autonomous-database generate-wallet --autonomous-database-id ocid1.autonomousdatabase.oc1.eu-frankfurt-1.abtheljtcwfhy5ohok66arn6ngrpqdigvq7bzcpygtfnkbldvgtk4rv3xhtq --file wallet.zip --password My_Strong_Pa55word$ unzip wallet.zip
$ pwd$ export TNS_ADMIN=/home/loic_lefev$ sed -i 's/?\/network\/admin/$TNS_ADMIN/' sqlnet.ora
$ pip3 install --user cx_Oracle
import cx_Oracle
def connect():
connection = cx_Oracle.connect("dragon", "My_Strong_Pa55word", "dragon_tp")
return connection

def selectdate(connection):
with connection:
cursor = connection.cursor()
result = cursor.execute('''select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual''')
data = result.fetchone()
print("Date is " + data[0])

if __name__ == '__main__':
connection = connect()
selectdate(connection)
$ python3 test.py
Date is 2020-09-27 13:46:02
Image for post
Oracle Cloud Shell running a python script that connects to an Always Free Autonomous Transaction Processing database.

Probability Sampling Methods Explained with Python

 

Why do we need Sampling?

Sampling is used when we try to draw a conclusion without knowing the population. Population refers to the complete collection of observations we want to study, and a sample is a subset of the target population. Here’s an example. A Gallup poll¹, conducted between July 15 to 31 last year, found that 42% of Americans approve of the way Donald Trump is handling his job as president. The results were based on telephone interviews of a random sample of ~4500 calls (assuming one adult per call. ~4500 adults), aged 18 and older, living in the U.S. The poll was conducted during a period of controversy over Trump’s social media comments. For this survey, the population is ALL the U.S citizens aged 18 and older, and the sample is 4500 adults.

If sampling is done wrong, it will lead to biases that affect the accuracy of your research/survey results. To avoid selection biases, we have to carefully choose a subset of a population that can be representative of the group as a whole.

Types of Probability Sampling

Simple Random Sampling

Simple Random Sampling
Image by Author using Powerpoint

Simple random sampling means we randomly select samples from the population where every unit has the same probability of being selected.

Pros: there’s no need to divide the population into subgroups or take any other additional steps before selecting members of the population at random.

Cons: the samples might not be representative, and it could be time-consuming for large populations.

Use Case: it’s used when we don’t know too much about the population.

#let's create a dataframe first!
import numpy as np
import pandas as pd
from numpy.random import randn
# Define total number of customers
number_of_customers = 10
# Create data dictionary
data = {'customer_id':np.arange(1, number_of_customers+1).tolist(),
'customer_life_time_value':randn(10)}
# Transform dictionary into a data frame
df = pd.DataFrame(data)
# View data frame
df
Image for post
Created a data frame (Image by Author)
#only using random(), we can generate 4 samples from this dataset
# Obtain simple random sample
simple_random_sample = df.sample(n=4).sort_values(by='customer_id')
simple_random_sample
Image for post
Randomly selected customers (Image by Author)

Stratified Sampling

Stratified Sampling
Image by Author using Powerpoint

For stratified sampling the population is divided into subgroups (called strata), then randomly select samples from each stratum.

Pros: it captures key population characteristics, so the sample is more representative of the population.

Cons: it’s ineffective if subgroups cannot be formed.

Use Case: it’s commonly used in geographic sampling where strata can be states, countries, or ecoregions.

#Let's add subgroup labels to the datasetdf['strata']=[0, 0, 0, 1, 1, 1, 1, 1, 2, 2]sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)for x, y in sss.split(df, df['strata']):
stratified_random_sample = df.iloc[y].sort_values(by='customer_id')
stratified_random_sample
Image for post
Randomly selected customers from each stratum (Image by Author)

Cluster Sampling

Cluster Sampling
Image by Author using Powerpoint

For clustering sampling, the population is divided into different clusters. Then a fixed number of clusters are randomly sampled and all units within each of the selected clusters are included in the sample.

Pros: it reduces variability, and it’s easy to conduct.

Cons: it is possible to introduce bias during sampling.

Use Case: it’s used when all individuals in each cluster can be representative of the populations.

#create 4 different clusters based on customers' lift time valuesdf['cluster'] = pd.cut(df['customer_life_time_value'], bins=4, labels=False) +1
Image for post
Added “cluster” column (Image by Author)
# predefine which clusters/groups we want to select samples fromn=[2,4]def clustering_sampling(df,n):
df_list=[]
for i in range(len(n)):
df1=df[df['cluster']==n[i]]
df_list.append(df1)
final_df=pd.concat(df_list, ignore_index=True)

return final_df
clustering_sampling(df,n)
Image for post
Selected all customers from cluster 2 and 4 in the sample (Image by Author)

Systematic Sampling

Systematic Sampling
Select every other person from the population (Image by Author using Powerpoint)

A systematic sample is drawn by selecting units systematically from a sample frame. (i.e every other unit is included in the sample)

Pros: it can eliminate clustered selection, and it’s simple to execute.

Cons: we need to predetermine the estimated population size. It doesn’t work well if the population has a type of standardized pattern.

Use Case: it’s used when the relevant data does not exhibit patterns.

def systematic_sampling(df, step):

indexes = np.arange(0,len(df),step=step)
systematic_sample = df.iloc[indexes]
return systematic_sample

systematic_sampling(df, 1)
Image for post
Every other customer_id is included in the sample (Image by Author)

Reference

Tuesday, September 22, 2020

Flutter Reference

 Layouts

Flutter Layout Cheat Sheet - https://medium.com/flutter-community/flutter-layout-cheat-sheet-5363348d037e

Flutter Layouts Walkthrough: Row, Column, Stack, Expanded, Padding - https://www.youtube.com/watch?v=RJEnTRBxaSg

Building Layouts -

https://flutter.dev/docs/development/ui/layout/tutorial

Ux challenge on grid - https://lh3.googleusercontent.com/-MYvBdXoTTyQ/XnH8Eoc9M_I/AAAAAAAAAbw/xsp2g1hbYTgm8Vt5fLtCIzgXP-kf5p_mgCK8BGAsYHg/s0/2020-03-18.png

ux challenge on grid - https://lh3.googleusercontent.com/-Jr5npcZQku8/XnH7kjprZ1I/AAAAAAAAAbo/MneYnj7a03o0d1Y0z3_kgbil8u5wvxFDQCK8BGAsYHg/s0/2020-03-18.png

ux challenge on slider - https://lh3.googleusercontent.com/-5yWQf8ReaD0/XoyA2EXAmEI/AAAAAAAAA04/yV9s1ZHvYa8CDLIwhd00_UKn5QYGtQJTgCK8BGAsYHg/s0/2020-04-07.png

Fetching data from internet

https://flutter.dev/docs/cookbook/networking/fetch-data

Sending Data to the server

https://flutter.dev/docs/cookbook/networking/send-data

Forms

https://flutter.dev/docs/cookbook/forms/validation

Adding Interactivity - https://flutter.dev/docs/development/ui/interactive

Adding interactivity to your Flutter app

Bloc Pattern

Flutter App: fetching data from the API using the BLoC pattern architecture - https://medium.com/zipper-studios/flutter-fetch-data-from-api-and-architect-your-app-using-bloc-pattern-b826f80d6996

Architect your Flutter project using BLOC pattern - https://medium.com/flutterpub/architecting-your-flutter-project-bd04e144a8f1

Flutter: Handling your network API calls like a boss! - https://itnext.io/flutter-handling-your-network-api-calls-like-a-boss-936eef296547

Navigation

Navigate with named routes - https://flutter.dev/docs/cookbook/navigation/named-routes

Best Practicesin Navigation - https://www.filledstacks.com/snippet/clean-navigation-in-flutter-using-generated-routes/

The Best Flutter Responsive UI Pattern https://www.filledstacks.com/post/the-best-flutter-responsive-ui-pattern/

Assignments in this order

Food Delivery App UI with Functionality (They have used "provider concept" in that..along with bloc pattern) - https://www.youtube.com/watch?v=wWH66F9y63U&t=2534s

Drag and Drop - Flutter Tutorial - https://www.youtube.com/watch?v=pKO54ttCV5I

Ux challenge using following widgets - https://dribbble.com/shots/3466120

  1. Shape of View widget https://pub.dev/packages/shape_of_view#-readme-tab-

  2. Circle Avatar https://api.flutter.dev/flutter/material/CircleAvatar-class.html

  3. Stack Widget https://api.flutter.dev/flutter/widgets/Stack-class.html

  4. Positioned Widget https://api.flutter.dev/flutter/widgets/Positioned-class.html

  5. Raised Button with rounded radius https://stackoverflow.com/questions/49991444/create-a-rounded-button-button-with-border-radius-in-flutter

Independent Assignments

Charts - https://google.github.io/charts/flutter/gallery.html

_https://www.filledstacks.com/snippet/quick-and-easy-dialogs-in-flutter-with-rf-flutter/

Quick and Easy Dialogs in Flutter with RfFlutter -

https://www.filledstacks.com/snippet/quick-and-easy-dialogs-in-flutter-with-rf-flutter/

https://dribbble.com/shots/6541291-Snowball-website-alive-Dashboard-page

https://dribbble.com/shots/7036184/attachments/36346?mode=media

Better Animation When Keyboard Opens - https://www.filledstacks.com/snippet/better-animation-when-keyboard-opens/

Dialog Box Service - https://www.filledstacks.com/post/manager-your-flutter-dialogs-with-a-dialog-manager/

Ux Challenge(only left side using card widget) - https://dribbble.com/shots/4486758-Relationship-Coaching-App

in-app notifications and toast messages - https://www.filledstacks.com/snippet/in-app-notifications-in-flutter/
https://www.filledstacks.com/snippet/easy-toasts-with-ok-toast/

Request Permissions in Flutter as a Service - https://www.filledstacks.com/snippet/request-permissions-in-flutter-as-a-service/

Internationalizing Flutter apps - https://flutter.dev/docs/development/accessibility-and-localization/internationalization

Using the Flutter inspector - https://flutter.dev/docs/development/tools/devtools/inspector

Performance - https://flutter.dev/docs/perf

Animations - https://flutter.dev/docs/development/ui/animations

Ux challenge - https://dribbble.com/shots/6191054-Loan-repayment-bill

UX Challenge - https://dribbble.com/shots/6037533-Finance-Mobile-App-UI

UX Challenge(left side animated progress bar) - https://lh3.googleusercontent.com/-5yWQf8ReaD0/XoyA2EXAmEI/AAAAAAAAA04/yV9s1ZHvYa8CDLIwhd00_UKn5QYGtQJTgCK8BGAsYHg/s0/2020-04-07.png

Take a picture using the camera - https://flutter.dev/docs/cookbook/plugins/picture-using-camera

Separating build environments in Flutter apps - https://iiro.dev/2018/03/02/separating-build-environments/

Inherited Widgets Explained - Flutter Widgets 101 Ep. 3 https://www.youtube.com/watch?v=Zbm3hjPjQMk

Setting up Lint Rules in Dart-Flutter

https://medium.com/podiihq/setting-up-lint-rules-in-dart-flutter-1ebbed0418a6

https://dart-lang.github.io/linter/lints/

Shared preferences Login App https://pub.dev/packages/shared_preferences

Resources-
Creating Custom Progress Indicators: https://www.youtube.com/watch?v=TiH0HYBFMMI&pp=wgIECgIIAQ%3D%3D&feature=push-sd&attr_tag=TFGcP0Kx6a9-aL2u%3A6 Mobile Pickers - https://material.io/components/pickers/#mobile-pickers

Quick and Easy Dialogs in Flutter with RfFlutter - https://www.filledstacks.com/snippet/quick-and-easy-dialogs-in-flutter-with-rf-flutter/

Better Animation When Keyboard Opens - https://www.filledstacks.com/snippet/better-animation-when-keyboard-opens/

Dialog Box Service - https://www.filledstacks.com/post/manager-your-flutter-dialogs-with-a-dialog-manager/

in-app notifications and toast messages - https://www.filledstacks.com/snippet/in-app-notifications-in-flutter/
https://www.filledstacks.com/snippet/easy-toasts-with-ok-toast/

JSON and serialization - https://flutter.dev/docs/development/data-and-backend/json

Block Pattern (3 series video)( - https://www.youtube.com/watch?v=pdV2GzstYCQ&feature=youtu.be

firebase - https://github.com/HackerNews/API

Widget — State — BuildContext — InheritedWidget -

Articles - https://medium.com/zipper-studios

https://medium.com/flutter-community/widget-state-buildcontext-inheritedwidget-898d671b7956

https://stackoverflow.com/questions/49100196/what-does-buildcontext-do-in-flutter

Json Data

https://reqres.in/

https://financialmodelingprep.com/api/v3/company/profile/AAPL

used for departure bloc pattern in 3 part series video - http://www3.septa.org/hackathon/Arrivals/Suburban%20Station/5/

https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson - used by Paulo in maps exrthquakes app. Shows 2.5 days earthquakes. can select others also lke per day, etc.

Dart

Dart Cheatsheet - https://dart.dev/codelabs/dart-cheatsheet convert map to list - subjectList = response.map((json) => Subject.fromJson(json)).toList();

Chrome Extensions:

  1. JSON Viewer Awesome - to show JSON in nice format with chart and tree structure
  2. JSON to Dart Converter - https://in.search.yahoo.com/search?fr=mcafee&type=E210IN714G0&p=json+to+dart - Paste the JSON data, it will convert. Copy it and put in the Model class.
  3. https://javiercbk.github.io/json_to_dart/ - to easily convert json to dart models. If this doesn't wok then first parse and correct it in the next one given below.
  4. https://jsonformatter.org/json-parser

Packages:

  1. Geolocator Get the last known location; Get the current location of the device; Get continuous location updates; Check if location services are enabled on the device; Calculate the distance (in meters) between two geocoordinates; Calculate the bearing between two geocoordinates;

example: converting location to getting address of place

Converting this Into an Address We don’t have to stop there though! We can get a Placemark which is essentially an approximation of the user’s current location from the latitude and longitude. Let’s see this in action:

import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:geolocator/geolocator.dart';

class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); }

class _HomePageState extends State { final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;

Position _currentPosition; String _currentAddress;

@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Location"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_currentPosition != null) Text(_currentAddress), FlatButton( child: Text("Get location"), onPressed: () { _getCurrentLocation(); }, ), ], ), ), ); }

_getCurrentLocation() { geolocator .getCurrentPosition(desiredAccuracy: LocationAccuracy.best) .then((Position position) { setState(() { _currentPosition = position; });

  _getAddressFromLatLng();
}).catchError((e) {
  print(e);
});

}

_getAddressFromLatLng() async { try { List p = await geolocator.placemarkFromCoordinates( _currentPosition.latitude, _currentPosition.longitude);

  Placemark place = p[0];

  setState(() {
    _currentAddress =
        "${place.locality}, ${place.postalCode}, ${place.country}";
  });
} catch (e) {
  print(e);
}

} }

  1. GeoLocator -- gives more control on current location. Little advanced than location plugin.

  2. Geocoder - Forward and reverse geocoding.

example: import 'package:geocoder/geocoder.dart';

// From a query final query = "1600 Amphiteatre Parkway, Mountain View"; var addresses = await Geocoder.local.findAddressesFromQuery(query); var first = addresses.first; print("${first.featureName} : ${first.coordinates}");

// From coordinates final coordinates = new Coordinates(1.10, 45.50); addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates); first = addresses.first; print("${first.featureName} : ${first.addressLine}");

This article explains both plugins with map well. https://medium.com/swlh/working-with-geolocation-and-geocoding-in-flutter-and-integration-with-maps-16fb0bc35ede

Explains how to get nearbyplaces and plot on map. gets user location also https://medium.com/flutter-community/building-places-location-search-with-map-view-using-flutter-1-0-alfian-losari-66cacb3bcc24

Must Watch YouTube Videos for Databricks Platform Administrators

  While written word is clearly the medium of choice for this platform, sometimes a picture or a video can be worth 1,000 words. Below are  ...