Wednesday, March 29, 2023

Python docker SDK how to list all the containers

this can be done by giving all=True parameter like below 

client.containers.list(all=True) 

references:

https://stackoverflow.com/questions/54306722/python-docker-client-only-listing-running-containers

Tuesday, March 28, 2023

Python callback functions

def callbackFunc(s):

    print('Length of the text file is : ', s)


def printFileLength(path, callback):

    f = open(path, "r")

    length = len(f.read())

    f.close()

    callback(length)


if __name__ == '__main__':

    printFileLength("sample.txt", callbackFunc)

references:

 https://pythonexamples.org/python-callback-function/

Sunday, March 26, 2023

React spread operator to operate on array

If you want to use the spread operator to add items to the beginning of an array, just use the spread operator after the new values. For example:


let a = [1, 2, 3, 4, 5];

let b = [0, ...a];


console.log(a);

console.log(b);

Additionally, you can also use .concat:


var a = [1, 2, 3, 4, 5];

var b = [0].concat(a);


console.log(a);

console.log(b);

references: 

https://stackoverflow.com/questions/42160400/react-redux-add-object-to-start-of-array-using-spread-operator

Flask How to send back JSON response

from flask import Flask,jsonify,request

  app =   Flask(__name__)

  

@app.route('/returnjson', methods = ['GET'])

def ReturnJSON():

    if(request.method == 'GET'):

        data = {

            "Modules" : 15,

            "Subject" : "Data Structures and Algorithms",

        }

  

        return jsonify(data)

  

if __name__=='__main__':

    app.run(debug=True) 

references:

https://www.geeksforgeeks.org/how-to-return-a-json-response-form-a-flask-api/

Flask App supporting all type of request methods

Below is how we need to do this 

from flask import Flask

from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        
references:
https://stackoverflow.com/questions/22947905/flask-example-with-post

Saturday, March 25, 2023

A simplest of simple Logistic regression example

This below example loads the data and does logistic regression and stores that in the pickle file and then does the prediction  


# Save Model Using Pickle

import pandas

from sklearn import model_selection

from sklearn.linear_model import LogisticRegression

import pickle

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"

names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']

dataframe = pandas.read_csv(url, names=names)

array = dataframe.values

X = array[:,0:8]

Y = array[:,8]

test_size = 0.33

seed = 7

X_train, X_test, Y_train, Y_test = model_selection.train_test_split(X, Y, test_size=test_size, random_state=seed)

# Fit the model on training set

model = LogisticRegression()

model.fit(X_train, Y_train)

# save the model to disk

filename = 'finalized_model.sav'

pickle.dump(model, open(filename, 'wb'))

 

# some time later...

 

# load the model from disk

loaded_model = pickle.load(open(filename, 'rb'))

result = loaded_model.score(X_test, Y_test)

print(result)


references:

https://machinelearningmastery.com/save-load-machine-learning-models-python-scikit-learn/

How to install Scikit Learn and set it up

Better to use virtualenv 

pip install -U scikit-learn

In order to check your installation you can use


python -m pip show scikit-learn  # to see which version and where scikit-learn is installed

python -m pip freeze  # to see all packages installed in the active virtualenv

python -c "import sklearn; sklearn.show_versions()"


These are some of the outputs 


python -m pip show scikit-learn 

Name: scikit-learn

Version: 1.2.2

Summary: A set of python modules for machine learning and data mining

Home-page: http://scikit-learn.org

Author: None

Author-email: None

License: new BSD

Location: /Users/userrm/Documents/RR/projects/POCs/AIBot/BW2/server/venv/lib/python3.8/site-packages

Requires: threadpoolctl, scipy, numpy, joblib

Required-by: 



python -m pip freeze

bidict==0.22.1

click==8.1.3

Flask==2.2.3

Flask-SocketIO==5.3.3

importlib-metadata==6.1.0

itsdangerous==2.1.2

Jinja2==3.1.2

joblib==1.2.0

MarkupSafe==2.1.2

numpy==1.24.2

pandas==1.5.3

python-dateutil==2.8.2

python-engineio==4.4.0

python-socketio==5.8.0

pytz==2023.2

scikit-learn==1.2.2

scipy==1.10.1

six==1.16.0

threadpoolctl==3.1.0

Werkzeug==2.2.3

zipp==3.15.0


references:

https://scikit-learn.org/stable/install.html