Category Archives: Programming

Python Library Tips: timedelta


Timedelta

Timedelta class represent not any particular date or time, but it represents a span of time. This class will be helpful when you need to run some math on date and time. Say what will be this day on after few weeks or what will be this day in future year.

Following example will make it clear

from datetime import date
from datetime import timedelta

print(f'todays date {date.today()} after 1 year will be {date.today()+ timedelta(days=365)}')

Output 
todays date 2020-06-27 after 1 year will be 2021-06-27

Here I used the f.string to construct the message , the timedelta represent one year, 365 days. You can find what will be the date before few weeks back using date -timedelta(weeks=4)

Python Library Tips: strip off letter from list


f.strings

In this series of posts , learn how to use Python Library functions

How to strip off no of letters from a list of strings

The split function of string class can be used to split words from a string. do you know how to creating a abbreviated set of strings from a list. I

With a comprehension statement in Python this can’t be hard

list=['PYTHON','CPYTHON','IPYTHON']
stripped=[ k[:3] for k in list]
print(stripped)
['PYT', 'CPY', 'IPY']

Here we strip of the each list element using : operator in the list and specify the number of characters want to keep.

You can also have the reverse order using k[3:] or can use the starting and ending position as follows

stripped=[ k[0:4] for k in list]
print(stripped)
#['PYTH', 'CPYT', 'IPYT']

stripped=[ k[1:4] for k in list]
print(stripped)
#['YTH', 'PYT', 'PYT']

Python Library Tips: f.strings


f.strings

In Python you can format string in a variety of ways.We learned how to use a %format technique in last post. In Python version 3.7 introduced f.string .

f/F strings are literals begins with letter f/F and It uses { }, curly braces for replacement of expressions with their values

spyder_version=3
python_version=2.7
print(f'I am using Spyder ID {spyder_version} with Python {python_version}')

#Output
I am using Spyder ID 3 with Python 2.7

Arbitrary expression

F"{10*10}"

#Output
100

Function call

We can also call function inside f.strings.

def multi(x,n):
    return x*n
f'{multi(2,2)}'

Multipleline

f-strings are faster than % formatting because they ares constants while f.string expressions are evaluated at runtime.

Also it is possible compose f.strings in multiple line. All strings must begin with ‘f/F’.

>>topic='panda frames'
>>lang='python'
>>version =3.8
>>say=(f'I want to use {topic}'
  f' in {lang}'
  f' version {version}')

>>say
Out[20]: 'I want to use panda frames in python version 3.8'

It can also be rewritten using ‘\’

>>say=f'I want to use {topic}' \
f' in {lang}' \
f' version {version}'

Python Library Tips: str.format


str.format()

In Python you can format string in a variety of ways.We learned how to use a %format technique in last post. In Python version 2.6 introduced str.format() function which is an improvement over % formatting.

It uses { }, curly braces for replacement fields

spyder_version=3
python_version=2.7
print('I am using Spyder ID {} with Python {}' .format(spyder_version,python_version))

#Output
I am using Spyder ID 3 with Python 2.7

You can access variable using digits starting from {0}-{n} as follows

spyder_version=3
python_version=2.7
print('I am using Python {1} and Spyder IDE {0} for data science ' .format(spyder_version,python_version))

#Output
I am using Python 2.7 and Spyder IDE 3 for data science

Python Library Tips: date formatting


Date formatting

In Python you can format date string using following predefined strings ,

%y/%Y –Year %a/A –Week Day %b/B –Month and %d for day

The letter with lowercase (%y/Y%) gives you abbreviated values, say 20 for 2020, Thu for Thursday etc

>>> print( today.strftime("%y %b %a"))
20 Jun Thu
>>> print( today.strftime("%a,%d,%B,%y "))
Thu,18,June,20 

Locale date

Some times your application may be consumed by people for different localities or people from different countries, of course the date and time will be different. Python allows you to format date and time according to locale settings.

>>> print(today.strftime("%c"))
Thu Jun 18 00:00:00 2020
>>> print(today.strftime("%x"))
06/18/20
>>> print(today.strftime("%X"))

Here %c stand for locale’s date and time , %x for locale’s time and %X for locale’s date

You can also use predefined string s for format time . %I/H for 12/24 Hour, %M for Minutes, %S for second and % p for locales’s AM/PM


Python Library Tips: today()


Today()

Today I want to look around Today function which provided by Standard Python Library. This function can offer much of today’s date. Let’s start with printing what’s today date

from datetime import date
today=date.today()
print(today)

today variable also holding today() properties such as day,year,month,weekday etc. You can use them as follows.

Photo by Pixabay on Pexels.com
print(today.weekday())

weekday gives you number representing week day from 0-6, Monday as first day. You can use the weekday for printing days in a week, Monday or Sunday as first day as follows

wdays=['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']
print('Today is %s ' %wdays[today.weekday()])

Python Library Tips: % formatting


% formatting

In Python you can format string in a variety of ways. Using the % symbol you can place string almost any where.

print('customer A bought %s Quantity of Goods at %s unit price' %(qty,price))

#Output

customer A bought 100 Quantity of Goods at 70 unit price

The conversion types are:

ConversionMeaningNotes
'd'Signed integer decimal.
'i'Signed integer decimal.
'o'Signed octal value.(1)
'u'Obsolete type – it is identical to 'd'.(6)
'x'Signed hexadecimal (lowercase).(2)
'X'Signed hexadecimal (uppercase).(2)
'e'Floating point exponential format (lowercase).(3)
'E'Floating point exponential format (uppercase).(3)
'f'Floating point decimal format.(3)
'F'Floating point decimal format.(3)
'g'Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'G'Floating point format. Uses uppercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.(4)
'c'Single character (accepts integer or single character string).
'r'String (converts any Python object using repr()).(5)
's'String (converts any Python object using str()).(5)
'a'String (converts any Python object using ascii()).(5)
'%'No argument is converted, results in a '%' character in the result.
Source : https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting

ListCollectionView for sorting,filtering data collection


When we wanted to perform filtering, sorting of data over a binded data collection, collection view might be helpful. If the source collection implements INotifyCollectionChanged interface, the changes raised by the CollectionChanged event are reflected to the views.

ListcollectionView Represents the collection view for collections that implement IList as Mictosoft Doc says.

Create a collection view

In order to use ListCollectionView you have to use ObjectModel

using System.Collections.ObjectModel;

Then you can use any list to create ListCollectionView, in this example I used my observable collection of SalesOrder.

ListCollectionView sorderview = null;
collectionview = new ListCollectionView(salesOrderCollection);

Model View Class

class SalesOrderView
    {   public DateTime Date { get; set; }
        public string Customer{ get; set; }        
        public string Amount{ get; set; }
    }

Create a Custom filter

Let’s play with filter, first up all we need to create some custom filter for searching SalesOrders received from customers on a specific date

collectionview.Filter = (e1) =>
                {
                    SaleOrderView sorder = e1 as SaleOrderView ;
                    if (((Convert.ToDateTime(sorder.Date) >= dtp_from.SelectedDate && 
Convert.ToDateTime(sorder.Date) <= dtp_to.SelectedDate)) )
                        return true;
                    return false;
                };

That is it, now you can simply bind the collection view with DataGrid or Listcontrol. For me it is a Grid

 mydatagrid.ItemsSource = collectionview;

Read data from GitHub hosted json file in Flutter


This is my first flutter tutorial, which explain how you can host and read json data from GitHub repository.

First up all you need to host json in GitHub Page , here is the complete guide. After that you can read the data using http package in Flutter.

First up all you need to specify the pubspec.yml settings as follows

dependencies:
  flutter:
    sdk: flutter
  http: ^0.12.0+2

Go to your pubspec file and add the high lighted sections to use the network/web connection.

Now we need a Model class to read and hold the json object. Eventually the fetchpost Future will extract the data from GitHub.

Future<Post> fetchPost() async {
  final response = await http.get('https://jdata-server.github.io/data.json');
  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}

A special function called FutureBuilder help us to feched post object.Here is the complete main.dart file

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'dart:async';
Future<Post> fetchPost() async {
  final response = await http.get('https://jdata-server.github.io/data.json');
  if (response.statusCode == 200) {
    // If server returns an OK response, parse the JSON
    return Post.fromJson(json.decode(response.body));
  } else {
    // If that response was not OK, throw an error.
    throw Exception('Failed to load post');
  }
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
  Future<Post> post;
  void initState() {
    super.initState();
    post = fetchPost();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
          child: FutureBuilder<Post>(
        future: post,
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return new ListView(children: <Widget>[
              new Text("Q:" + snapshot.data.question),
              new Text("A:" + snapshot.data.answer)
            ]);
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          // By default, show a loading spinner
          return CircularProgressIndicator();
        },
      )),
      floatingActionButton: FloatingActionButton(
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

class Post {
  final String question;
  final String answer;
  final String catagory;
  Post({this.question, this.answer, this.catagory});
  factory Post.fromJson(Map<String, dynamic> json) {
    return Post(
        question: json['question'],
        answer: json['answer'],
        catagory: json['catagory']);
  }
}

How to create json data server with GitHub Pages


json files were widely used for hold data for apps and web services. Reading and writing speed of json will be faster than expected, in effect app using json will fetch data from web in a quick way.

So where should I put the json on the web ?, Google drive formerly support the accessing of json file directly, soon they removed this feature. Or you can host those files on your own server

With GitHub pages can host json file which can accessed by any app. The url would form like

<username>.githubio/<json-file>

You can create one GitHub page per user and unlimited on Organization. In either case you repository name should match the <organisation name> / <username>.github.io. You can add folders and files inside the repository

for more guide how to create GitHub Pages go to the official GitHubPage Site