IE 172 Codes

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/69

flashcard set

Earn XP

Description and Tags

Ito na yung may code pati how to eme eme

70 Terms

1
New cards

Command to return list of contents in current directory

ls

2
New cards

Command to change directory to specified path

cd “D:\copied_path”

3
New cards

Command to go one folder above current directory

cd ..

4
New cards

Install virtual environment in current directory

Creates new folder for venv named <environment_name>

python -m venv <environment_name>

5
New cards

Command to list all Python packages currently installed in venv

pip freeze

6
New cards

Command to activate the venv (windows)

source <venvname>/Scripts/activate

7
New cards

Command to activate the venv (mac)

source <venvname>/bin/activate

8
New cards

How to check if venv is activated?

(venvname) on the leftmost side

9
New cards

Command to deactivate venv

deactivate

10
New cards

Setting up venv on VS Code

python interpreter > venv folder > Scripts > python

11
New cards

How to know if interpreter active in VS Code

bottom status bar

12
New cards

Command to install dash (package that provides functions for app customization)

pip install dash

13
New cards

Command to install dash_bootstrap_components (for designs)

pip install dash_bootstrap_components

14
New cards

File for blank script named “app”

app.py

15
New cards

How to add the installed packages in the script?

import 


16
New cards

Script to add webbrowser dependency (opens web browser automatically when app is ran)

import webbrowser


17
New cards

Script to add dash

import dash


18
New cards

Script to add dash_bootstrap_components with nickname dbc

import dash_bootstrap_components as dbc


19
New cards

How to pull tools from imported package (ex: dcc [defines interactive elements], html [allows html elements in app] from dash)

from dash import dcc, html


20
New cards

How to update imports for app callbacks?

from dash import Input, Output, State, callback


21
New cards

How to define application object? (app)

Create Dash application with Bootstrap Styling

app = dash.Dash(__name__, external_stylesheets = [dbc.themes.BOOTSTRAP])


22
New cards

How to set up title for application object? (app)

Set title of application object, app, using dash attribute

app.title = “Title”


23
New cards

How to set up initial layout for application object? (app showing Hello World with no extra formatting)

app.layout = html.Div(“Hello World”)


24
New cards

Script that runs the application object app

if __name__ == '__main__':
    webbrowser.open('http://127.0.0.1:8050', autoraise=True)
    app.run()


25
New cards

How to stop/kill the server?

Ctrl+C

26
New cards

Create a function “getFactorial” that returns num’s factorial

def getFactorial(num):
    if num < 0:
        raise Exception("Number must be nonnegative")
    elif num <= 1:
        return 1
    else:
        return num*getFactorial(num-1) 


27
New cards

How do you manually trigger a general exception in Python?

raise Exception("")


28
New cards

How to print value of function getFactorial when you want to get factorial of 2?

print(getFactorial(2))


29
New cards

Create a dbc card with header “First Dash App”

app.layout = html.Div(
	[	
		dbc.Card(
			dbc.CardHeader("First Dash App")
		)
	]
)


30
New cards
<p>Create the code that would reflect this inside of a dbc card </p>

Create the code that would reflect this inside of a dbc card

html.Div(
	[
		dbc.Label("Number"),
		dbc.Input(placeholder ="Place a number here", type="text"),
		dbc.FormText("Negative numbers are not allowed"),
	]
)


31
New cards

Create dash bootstrap component dropdown with options “This” and “That” and id “process_select”

dbc.Select(
	id="process_select",
	options=[
		{"label":"This","value":1},
		{"label":"That", "value":2},
	]
)


32
New cards

Create app callback for (no def yet)

                dbc.CardBody(
                    [
                        html.Div(
                            [
                                dbc.Label("Number"),
                                dbc.Input(placeholder="Place a number here", type="text", id='num_input'),
                                dbc.FormText("Negative numbers are not allowed."),
                            ]
                        ), 
                        html.Div(
                            [
                                dbc.Label("Process"),
                                dbc.Select(
                                    id="process_select",
                                    options=[
                                        {"label": "Get Factorial", "value": 1},
                                        {"label": "Generate Fibonacci", "value": 2},
                                    ],
                                ),
                                dbc.FormText("Select an operation"),
                            ]
                        ), 
                        dbc.Button("Calculate!", id='btn_calculate', color='primary', n_clicks=0),
                        html.Div(id='output_area')
                    ]
                ),


@app.callback(
	[
		Output("output_area","children")	
	],
	[
		Input("btn_calculate","n_clicks")
	],
	[
		State("num_input","value"),
		State("process_select","value")
	],
)


33
New cards

Add style, 2px solid green border, to

html.Div(
	'Hello World'
)


html.Div(
	'Hello World',
	style={'border': '2px solid green'},
)


34
New cards

Use className to style for a bold font with centered text

html.Div(
	'Hello World',
	style={'border': '2px solid green'},
)


html.Div(
	'Hello World',
	style={'border': '2px solid green'},
	className='fw-bold text-center'
)


35
New cards

Create a Data Frame, df, using pandas (shortcut to pd) with sample data

fruits_data = {
    'fruit': ['apple', 'banana', 'mango', 'orange', 'pineapple'],
    'Quantity': [10, 15, 7, 20, 6],
    'Price': [5, 3, 8, 6, 10]
}


import pandas as pd

fruits_data = {...}

df = pd.DataFrame(fruits_data)


36
New cards

Create a column for Totals in data frame df using Quantity and Price columns

df["Totals"] = df["Quantity"]*df["Price"]


37
New cards

Sort data frame, df, values descending order based on Totals column

df.sort_values("Totals", ascending=False, inplace=True)


38
New cards

Use iloc to print value in the 3rd and 4th column of the data frame (df) for the 3rd row

print(df.iloc[[2],[2,3]])


39
New cards

app.py setup: script to make sure that callbacks are not activated when input elements enter the layout

app.config.suppress_callback_exceptions = True


40
New cards

app.py setup: script to get CSS from a local folder

app.css.config.serve_locally = True


41
New cards

app.py setup: script to enable your app to run offline

app.scripts.config.serve_locally = True


42
New cards

app.py setup: script to reduce the logs on your terminal to debug

log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)


43
New cards

SQL Script to create genres table with genre_id and genre_name

CREATE TABLE genres(
	genre_id serial primary key not null,
	genre_name varchar(128)	
);


44
New cards

Create the function “getdblocation” to access SQL database from Python?

def getdblocation():
	db = psycopg2.connect(
		host='',
		database='',
		user='postgres',
		port=0,
		password='',
	)
	return db


45
New cards

Create the function “modifyDB” to modify SQL database from Python

def modifyDB(sql,values):
	db = getdblocation()
	cursor = db.cursor()
	cursor.execute(sql,values)
	db.commit()
	db.close()


46
New cards

Creates a cursor object named “cursor” from open database db

cursor = db.cursor()


47
New cards

Call function to execute the SQL code with the cursor value

cursor.execute(sql,values)


48
New cards

Call function to save changes to db via Python

db.commit()


49
New cards

Use pre-made function to close db connection

db.close()


50
New cards

Create function “getDataFromDB” for querying SQL database from Python

def getDataFromDB(sql,values,dfcolumns):
	db = getdblocation()
	cur=db.cursor()
	cur.execute(sql,values)
	rows = pd.DataFrame(cur.fetchall(), columns=dfcolumns)
	db.close()
	return rows 


51
New cards

Placeholders for where you want the values to go to in sql query

%s

52
New cards

Use pandas to create the variable “rows” to grab all query results from the cursor and converts them into a pandas table labeled with dfcolumns

rows = pd.DataFrame(cur.fetchall(), columns=dfcolumns)


53
New cards

Edit the following code to not make it susceptible to SQL injections

sql = """ SELECT user_id FROM users WHERE user_name = <username_val> AND password = <password_val> """


sql = """ SELECT user_id FROM users WHERE user_name = %s AND password = %s """
values = [username_val, password_val] 


54
New cards

Create the location variable for index.py with ‘url’ id

dcc.Location(id="url", refresh=True)


55
New cards

Create the page content div for index.py with ‘page_content’ id

html.Div(id="page_content") 


56
New cards

Create the initial app layout variable for index.py setup with location variable ‘url’ id and page content div ‘page_content’ id

app.layout = html.Div(
	[
		dcc.Location(id="url", refresh=True),
		html.Div(id="page_content"),
	]	
)


57
New cards

index.py: Callback to update page_content if url changes (home and movies pages)

@app.callback(
	[
		Output("page_content", "children")
	],
	[
		Input("url", "pathname")
	]	
)
def displaypage(pathname):
	ctx = dash.callback_context
	if ctx.triggered:
		eventid = ctx.triggered[0]["prop_id"].split('.')[0]
	else:
		raise PreventUpdate
	if eventid == "url":
		if pathname == "/" or pathname == "/home":
			returnlayout = home.layout
		elif pathname == "/movies":
			returnlayout = movies.layout
		else:
			returnlayout = "error404"
	else:
		raisePreentupdate
	return[returnlayout]


58
New cards

displaypage(pathname) code block to extract event id of triggered input

ctx = dash.callback_context 
if ctx.triggered:
	event_id = ctx.triggered[0]['prop_id'].split(".")[0]
else:
	raise PreventUpdate


59
New cards

displaypage(pathname) code block that executes action based on value of eventid (in this case url pa lang pwede magbago to /home or /movies)

if eventid == "url":
	if pathname == "/" or pathname "/home":
		returnlayout = home.layout
	elif pathname == "/movies":
		returnlayout = movies.layout 
	else:
		returnlayout = "error404"
else:
	raise PreventUpdate

return[returnlayout]


60
New cards

dbc Navbar setup with link to Home and Movies

navbar= dbc.Navbar(
		dbc.Container(
			[
				dbc.NavLink("Home", href="/home"),
				dbc.NavLink("Movies", href="/movies")
			]
		),
	)


61
New cards

Lines to import navbar from commonmodules as cm to index py

from apps import commonmodules as cm


62
New cards

index.py: app layout with common modules navbar, location variable ‘url’ id, and page content div ‘page_content’ id

app.layout = html.Div(
	[
		dcc.Location(id="url", refresh=True),
		cm.navbar,
		html.Div(id="page_content")
		
	]
)


63
New cards

eventid callback: parsing the parameter mode from url (?mode=add or ?mode=edit)

parsed = urlparse(urlsearch)
create_mode = parse_qs(parsed.query)['mode'][0]


64
New cards

Cloning a repository with github link

git clone <github link>


65
New cards

Committing repository changes with comment

git commit -m "comment"


66
New cards

Staging changes (all edited files)

git add .


67
New cards

Full order of pushing all changes to repository

git add . 
git commit -m "comment" 
git push


68
New cards

Pulling changes in repository

git pull


69
New cards

Undoing commit if already pushed

git revert <commit-hash copied from git or vscode>


70
New cards

Undoing commit if not pushed

git reset --soft HEAD~1