Lnx Flashcards

(332 cards)

1
Q

tcpdump

What is tcpdump command to get traffic to/from port 3000

A
>  tcpdump -i any port 3000
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

vimdiff

What are vimdiff commands?

A
  • CTL-ww swhitches windows
  • do: diff obtain, get difference from other window
  • dp: diff put: send difference to other window
  • ]c: go to next diff
  • [c: go to previous diff
  • zo: open zip
  • zc: close zip
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Remote command execution

Linux: How to run a command on a remote machine.

A

Use ssh,

> ssh  laeeq@192.168.0.49    ls  /tmp
> ssh  laeeq@192.168.0.49    date

you may have to give absolute path of the command you want to execute.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

core file

How to force core file generation from a crashing program.

A
> ulimit   -c  unlimited
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to display current resource limits for a user?

A
> ulimit    -a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

gdb

How to set a conditional break point in gdb.

A
b  fileName.c:56  if x==50
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Dangling symbolic links

What happens when you delete a symbolic link.

A

The target or actual file remains unaffected.
However, if u delete the target, the symbolic link continues to point to non-existing target file (this called dangling/orphaned symbolic links).

Soft link = Symbolic link

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

what does the tee command do?

A

tee cmd is used to copy the output of a command to a file.

In addition to displaying normal output of the command, the output is also written to a file.

It is used with pipe symbol

> wc -l   prog.c   |   tee    file1.txt

to append to a file instead of overwriting,

> wc -l  prog.c   |   tee -a   file1.txt
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How is HereDocument used?

A

When a large amount of textual multiline data is needed as argument to a command, we can use Here Docuement and provide data inside shell script itself, rather than providing data in a file.

cat << ABCD
line 1111
line 222
line 333
ABCD
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Pass envirenment variable to a script

How to make a variable available inside a shell script?

A
> TARGET=x86       ./script.sh

Value of TARGET will be available inside script.sh

Assign values to env variables just before calling the script on the same line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to read a variable inside a shell script from keyboard?

A

Use read command,

read    variableName
echo    $variableName
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a common usage of xargs?

A

When a command generates a list of files, such as find command. We can make this file list available to another command like grep or rm etc, so that these commands can work on the files list generated by the first command.

Following can be used to delete all header files found by cmd find

> find   .   -name   "*.h"  |  xargs  rm  -v

args is normally used after a pipe symbol

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Errors in make file recipes

In make file what happens when an error occurs at any time?

A

Default behaviour: Make program is aborts immediately, no further commands are executed.

If you pre-append minus sign ‘-‘ to any command, error in that command will be ignored and next command will be executed.

If you pre-append ‘@’ to any command, make will not print that command before executing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are common automatic variables in makefiles?

A
  • $@ : Name of current target.
  • $^ : List of all dependencies
  • $< : First dependency in the list of dependencies.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

gdb: How to get the sequence of function calls leading to current point of execution?

A
bt
backtrace

Each stack frame will have a number associated with it. Top most stack frame is the most recent one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

gdb: How to get the local variables in current function?

A
info  locals
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Command line editing: Go to begining of line.

A
CTL  a

a = begining

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Command line editing: Go to end of line.

A
CTL  e

e = end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Command line editing

Command line editing: Delete from curser positionn to the end of line?

A
CTL  k

k = Kill

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Command line editing

Command line editing: Clear the whole current line

A
CTL ak

ak = All Kill

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

iptables: name three chains

A

INPUT chain, OUTPUT chain, FORWARD chain

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is an iptables policy?

A

Each chain has a policy, ACCEPT or DROP.

ACCEPT: Allow all pkts unless a specific rule forbids that kind of pkt.

DROP: Disallow all pkts unless a specific rule allows that kind of pkt.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are primary and secondary groups in Linux?

A

Primary group: Has the same name as user name. Created at the time when user is created. Newly created user has membership of this group immediately.

Secondary group: Other groups created separately. Users need to be made members of secondary groups explictly using cmd gpasswd

> gpasswd     groupName    -a     userName
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Linux user groups

How to find to which groups a user belongs to?

A
>  groups         laeeq
>  groups           # will give info about current user.

You can also use,

~~~

> id laeeq
id # Lists groups which logged in user is member of
```

You can also read /etc/group file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Which file contains group information
/etc/group
26
How to create a new group in Linux?
``` addgroup newGroupName # Ubuntu etc groupadd newGroupName # Redhat etc ``` ## Footnote Verify using `cat /etc/group`
27
# Add a user to a Linux group How to make user1 a member of group1
Use command gpasswd `gpasswd group1 -a user1` ## Footnote You can also use `usermod` command.
28
# Revoke the membership from a group How to remove a user from a group? ## Footnote User will no longer have that group's permissions
`gpasswd groupName -d userName` ## Footnote Verify using `groups userName`
29
# Linux user groups How to modify a groups details, like change group name etc.
Use command `groupmod` ## Footnote Modify group
30
How is the owner group of a file determined?
Owner group of a file is the **primary group of the user who created the file**
31
# Linux gropus What are `system` & `non-system` of groups in Linux?
There are two kind of groups, 1. non-system groups 2. system gropus Non-system groups are used for managing user permissions and access. System groups are used by system services & daemons to allow system processes to share access to resources, files, directories etc. non-system group gid is normally greater than 1000. System group gid is normally less than 1000.
32
# system groups How to create a **system group** in Linux?
``` addgroup newGroupName --system ``` ## Footnote Normally group id (gid) is less then 1000 for these groups
33
# Linux system users How to create a system user?
``` > adduser newUserName --system ``` ## Footnote * Normally UID of system users is less than 1000. * They may not have home dir. * They may not have human login capability.
34
# Linux directory permissions How to interpret the permissions of a directory as opposed to a file? | as opposed to a permissions of a file.
* **read:** Ability to list dir contents * **write:** Ability to create/delete files in this dir. * **execute:** Ability to cd into this dir.
35
# setuid What is the purpose of setuid on an executable file?
When you set the `setuid` on an executable file, then when that file is executed by a non-owner user, the resulting process will still have all permissions of the real owner of that file. Even though the real owner did not run that program. ## Footnote -rwS Capital S means, original file did not have execute permission. lower case s means, original file had execute permission too.
36
How to set sticky bit on a file?
``` chmod +t fileName ``` ## Footnote other's permission will become --T
37
# Linux groups How to change the owner group of a file?
Use `chgrp` command ``` > chgrp groupName fileName ```
38
# Linux groups How to change the owner group of a file?
Use `chgrp` command, ``` chgrp groupName fileName ```
39
# C++ scoped enum What are scoped enums in C++
Define like this, ``` enum class Fruit { banana, apple, }; Fruit frt; frt = Fruit::apple; ```
40
What is the benefit of curly brace initialization of variables, like ``` int x{10}; // Rather than, int x = 10; // or int x(10); ```
Compiler enforces exact type match. ``` int x = 5.1; // works int y(6.2); // works // but int z{7.3}; // compilation error ``` ## Footnote A conversion from floating point to integer is not done at initialization.
41
# Ubuntu packages How to list all ubuntu packages?
``` > apt list > apt list --installed ``` ## Footnote Use grep for specific pkg
42
How to un-install an ubuntu package?
``` > apt remove pwgen # Does not remove config files > apt purge pwgen # Removes all config files ```
43
How to remove unnecessary dependencies from Ubuntu?
``` > apt autoremove ```
44
How to check if a specific pkg is installed on ubuntu system?
``` > apt search pwgen ``` ## Footnote If it is insalled, it will show `[installed]`
45
How to `autoclean` old downloaded archive files in `ubuntu`?
``` > apt autoclean ```
46
How to get information about an `ubuntu` package liks `pwgen`?
``` > apt show pwgen ``` ## Footnote *Does not show if a pkg is installed*. Use `apt list pwgen` for that.
47
Does each ubuntu release have a `codename`?
Yes, use following command, ``` > lsb_release -a ``` ## Footnote Examples are `jammy`, `Bionic Bever`, `Focal Fossa` etc.
48
How to create netcat chat between two computers?
Create listner/server ``` > nc -l -p 1299 # -l for listen, -p port num ``` Create netcat client, ``` > nc 192.168.1.100 1299 # dont use -p on listener ```
49
How to check if a port is open on a machine using `telnet`
``` > telnet 192.168.1.100 22 ``` * connected to 192.168.1.100 ==> Open * Trying 192.168.1.100...... ==> Not open More examples, ``` > telnet google.com 443 ``` ## Footnote * telnet google.com 443
50
On Redhat Linux, how do you list `package groups`
``` > dnf group list > dnf group list --hidden > dnf group list --installed ```
51
How to install `Development Tools` in RHEL?
``` > dnf groupinstall "Development Tools" ```
52
In Redhat linux, how to get info about a `package group`?
``` > dnf group info "Development Tools" ```
53
How to check the status of network manager?
``` > systemctl status NetworkManager > nmcli general ``` ## Footnote Do `double tab` after each part to see options available
54
| How to get info about NICs?
``` > nmcli device status > nmcli device show > nmcli device show eth0 > nmcli connection show > nmcli connection show eth0 ```
55
How to easily create a new network profile in Linux.
* Go to network settings (Wired) * Locate the interface name you want to use, press `+` * Add details such as DNS etc. * To activate new profile, disconnect networking, and connect using new profile.
56
What are the major components of a `connection profile`?
* interface name (eth0, enp3s0) * profile name (user defined text) * Type (ethernet, wireless) * IP4 address * subnet mask * Default gateway (gw4) * DNS addresses
57
How to create a connection profile using `nmcli` command?
``` > nmcli connection add type ethernet ifname eth0 con-name my_new_conn ip4 192.168.1.111/24 gw4 192.168j.1.1 ``` Specify following parameters, * connection type (ethernet / radio) * NIC name (eth0, enp7s0) * New profile name (my_new_conn) * ip4 (192.168.1.111/24) * Default gateway (192.168.1.1)
58
How to activate an already created connection profile?
``` > nmcli connection up my_conn_profile_1 ```
59
How to de-activate an active connection profile?
``` > nmcli connection down my_conn_profile_1 ```
60
How do you modify the parameters of a network profile? ## Footnote e.g., add a DNS address.
``` > nmcli connection modify my_connection ipv4.dns "8.8.8.8 8.8.4.4" > nmcli connection modify my_connection ipv4.address "192.168.1.100/24" > nmcli connection modify my_connection ipv4.gateway "192.168.1.1" ``` ## Footnote Take network profile down and up again to take effect.
61
How to make output of `nmcli` cmd more readable?
Use `-p pretty` option, ``` nmcli -p connetion show ``` ## Footnote Use `-p` with all nmcli operations.
62
How to restrict a network profile usage to a set of users?
``` > nmcli con mod my_connection connection.permissions mujid > nmcli con mod my_connection connection.permissions user:mujid,farooq ```
63
How do you delete a network/connection profile?
``` > nmcli connection delete my_connection_profile ``` ## Footnote Use `nmcli connection show` to list all known connections/profiles.
64
| While entering `nmcli` command, how can you get help while typing?
By pressing TAB twice.
65
What are some common DNS addresses?
* 75.75.75.75 * 75.75.76.76 * 8.8.8.8 * 8.8.4.4
66
How to get `overall` info about all NIC cards in a Linux system?
``` > nmcli device status ``` ## Footnote This is the first command you type. From here, you can drill down further using `nmcli device show eth0` etc.
67
In `nmcli` lingo, what is another name for a `profile`?
`connection name` or `con-name` ## Footnote connection name or profile name is listed as `CONNECTION` in last column of , `nmcli device status`
68
When creating/adding a new connection profile using `nmcli`, what are the first three parameters?
**con-name, type, ifname** * ifname (an existing NIC name, u can get it by `> mcli device status`) * profile name/connection name: A text name you choose. * type (ethernet, wifi etc) ## Footnote `> nmcli connection add type ethernet con-name my_new_profile ifname enp3s0`
69
When you create a file using `touch` commmand, does it have execute permissions by anybody?
**NO** By default, when you create a file, it does not have execute permissions by user, group or others. You can of course give execute permissions later using `chmod` command.
70
What is the role of `umask`
When you create a file, the bits in `umask` are *removed* from just created file. E.g., umask=0002 will make sure `others` don't have write permissions to created files. umask=0333 will make sure that newly created files will have only read permissions by everybody.
71
How to find current `umask` value?
``` > umask ``` ## Footnote likely output is 0002, this will remove write permission for `others` on newly created files.
72
How to make `umask` equal to 0333
``` > umask 0333 ``` ## Footnote This will make sure newly created files have only read permissions by everybody. -r--r--r--
73
How to find what the permissions on a newly created file be, with currently set value of `umask`
``` umask -S ```
74
How to list all services/units by `systemd`
``` > systemctl list-units > systemctl list-units --type=service > systemctl list-units --all > systemctl list-unit-files > systemctl list-unit-files | grep NetworkManager ```
75
How to find all journal entries related to a service/unit
``` > journalctl -u NetworkManager > journalctl -u ssh -f # follow similar to tail -f ```
76
How to view a systemd service's configuration file?
``` > systemctl cat NetworkManager ``` ## Footnote `cat /etc/systemd/system/NetworkManager.service`
77
How to list dependencies of a systemd service?
``` systemctl list-dependencies NetowrkManager systemctl list-dependencies --all NetworkManager ```
78
How to get low level details about a systemd service?
``` > systemctl show NetworkManager ```
79
After modifying a systemd service, how to reload systemd process to pickup modifications?
``` > systemctl daemon-reload ```
80
What is the basic format of a systemd service file?
``` cat /etc/systemd/system/test.service [Unit] Description=Example systemd service unit file. [Service] ExecStart=/bin/bash /usr/sbin/example.sh [Install] WantedBy=multi-user.target ```
81
What is the equivalent of `system V run-levels` in `systemd`?
**Targets**
82
Where should you keep your service files?
in **/etc/systemd/system**
83
How to list all `systemd` targets?
``` > systemctl list-units --type=target ```
84
Name some `systemd` targets
* multi-user.target * network-online.target * rescue.target * graphical.target
85
How to find default `systemd` target, that system tries to reach after booting?
``` > systemctl get-default ```
86
How to enforce strict ordering of `systemd` service starting?
By using `Before` and `After` in service file. ## Footnote `wants` and `requires` are not strict.
87
What are the things that `systemd` manages?
**units** Some unit types are, * services * timers * mounts
88
How do `systemd` timers work? ## Footnote timer is a kind of unit that systemd manages apart from services.
* You create a unit file `abc.timer`. * Specify periodicity in this file * You create a service file `abc.service` * You start timer unit * Now abc.service will be started periodically as per timer period. ## Footnote *timer unit file has same name as service file*
89
How do you create an infinite loop in a bash script?
``` while true do echo "Test - 1" sleep 1 done ```
90
| In Linux, how to nicely display an XML file?
``` > xmllint --format abc.xml ``` | ```
91
How to kill all processes run by a user hamid?
``` > sudo killall -u hamid ```
92
How to create a (normal) user in Linux?
``` > sudo adduser hamid ``` You can leave fields like room/phone etc blank. ## Footnote You can login as this user by doing ``` > su - hamid ```
93
How to create a Linux user and make his login shell `rbash`
``` > sudo adduser hamid --shell /bin/rbash ```
94
In Linux, how to find user-id and group-id of a user?
``` > id # gives info about logged in user > id hamid # info about another user ``` ## Footnote Default values are taken from `/etc/adduser.conf` file.
95
How to remove a Linux user?
Ubuntu ``` > sudo deluser hamid # home dir wont be deleted > sudo deluser hamid --remove-home > sudo deluser hamid --remove-all-files ``` Redhat may not have `deluser` cmd. Use `userdel` ``` > userdel hamid > userdel -r hamid # remove home-dir etc ```
96
How to become root user in Linux?
``` > sudo su - ```
97
How to check ACL permissions for a file?
# file: youtube/ ``` > getfacl fileName.txt ``` Typical output ``` owner: root # group: root user::rwx user:user1:rwx group::r-x mask::rwx other::r-x ```
98
How to give ACL permissions "rwx" for user `hamid` for a specific file?
``` > setfacl -m u:hamid:rwx fileName.txt ```
99
How do you check if a file has ACL permissions associated with it?
Normal files have only -rwxrwxrwx permissions. But a file with ACL permissions also has a "+" symbo at the end, like -rwxrwxrwx+
100
How to revoke some ACL permissions for a user or group?
Set new permissions explicitly. For removing write permissions for a user on a file, ``` > setfacl -m -u:hamid:r-x fileName.txt ```
101
How to find details of a `Linux` distribution?
``` > lsb_release -a > ls /etc/*rel* > cat /etc/lsb-release > cat /etc/os-release ```
102
What are some `systemd` directives to start programs
``` ExecStart /full/pathname/of/binary ExecStartPost /bin/bash /path/name/script.bash ExecStartPre /bin/bash /fullPath/script.bash ExecStop /bin/bash /full/path/endingScript.sh ``` * ExecStartPost starts the program immediately after starting the main program. NOT after main program finishes.
103
When does systemd service directive `ExecStop` take effect?
**Upon graceful shutdown of servcie.** * When you stop service using `systemctl stop svcName` * When the main program normally finishes It DOES NOT run when the service crashes due to signal etc.
104
How can I restart a systemd service after a crash, e.g., when underlying process receives a signal (9).
Use `Restart=on-failure` ``` [Unit] Description = A demo service [Service] ExecStart = /bin/bash /path/to/script.bash Restart=on-failure RestartSec=30s # waits of 30 sec before restarting. ``` ## Footnote Google: Setup self-healing services with systemd
105
What is the `id` of `super user` in Linux?
**0, zero** uid=0(root) gid=0(root) ## Footnote Use command `id` to get user identifier.
106
How to delete a group in Linux?
``` > groupdel groupName ``` ## Footnote All group names are listed in `/etc/group` This file has one line for each group. That line also contains all users belonging to this group.
107
In RedHat Linux, what is group `wheel`?
In RHEL, `wheel` is the name of a group. All members of this group have `sudo` capability. If you want to give `sudo` capability to any user, just add him to group wheel. ``` > gpasswd wheel -a hamid # hamid can now do sudo > gpasswd wheel -d hamid # hamid cannot do sudo ``` In `Ubuntu` this kind of group is named `sudo`
108
In Redhat Linux, how do you list packages?
``` > dnf list > dnf list installed > dnf list | grep tmux > dnf list installed | grep tmux ```
109
How to find which `systemd` units have failed?
``` > systemctl --failed > systemctl --failed --all ```
110
What Linux cmd is used to get info about power sources to the board?
``` > upower --enumerate > upower -d ```
111
How the cmd `pstree` works?
``` > pstree > pstree - u user1 > pstree -p -u hamid # with PIDs ``` ## Footnote Login with `su - hamid` for cleaner outputs.
112
How are threads shown in `pstree` cmd output?
{} means threads of a process ``` |--2*{thread} ``` The process has 2 threads running at the momemnt.
113
How does `pstree` show, when `a.out` spawns two threads?
``` pstree -u hamid bash ---a.out---2*{a.out} Default compact format ``` ``` pstree hamid -c --a.out-------{a.out} | ---{a.out} Non-compact format, each thread in its own line. ``` ``` pstree hamid -T --a.out-------{a.out} No thread information ```
114
How to find parents of a process with `pstree` cmd?
Fisrt find PID with `pstree hamid -p -c` Then find parents using `-s` option ``` > pstree -s 1234 > pstree -s -p 1234 ``` ***Don't*** use username (hamid) with above cmds
115
In Linux, how to print all `environment variables`?
* `env` cmd gives only `exported` variables * `set` cmd gives `exported` as well as `un-exported` variables. * `set` cmd gives more variables. * `env` output is a subset of `set` output
116
# m How to `unset` a variable in `bash`?
``` > unset VarName ```
117
How to get the value of a shell variable?
``` echo $VarName echo ${VarName} # better way ``` Using curly braces {} is always better
118
How is `alias` cmd used in Linux?
``` > alias cl=clear > unalias cl # remove alias ```
119
How to create exported shell variables for **all users** in Linux?
Declare them in `/etc/environment` file.
120
How to use `CTL R` interactive history?
* Keep pressing `CTL R` to keep going back. * Press left or right arrow key to copy currently displayed cmd to cmd-line. You can edit this cmd now. * Press `CTL S` to go forward. * If going forward with `CTL S` doesn't work, type `stty -ixon`
121
What are some important shell variables?
* $USER * $HOME * $SHELL * $PWD *$UID * $HOSTNAME * $PS1, $PS4
122
How to get details about a process, given its PID?
``` > ps -f 1234 > ps -ef # all processes > ps -ef | grep cmdName ```
123
How to find the exit status of last command?
Use `$?` 0 means success, 1 means failure. Try `true` and `false` cmds. Then do `$?` ``` > true > echo $? # should print 0 > false > echo $? # should print 1 ```
124
Give some example usages of `test` cmd in bash scripts.
``` test 1 -eq 1 # $? = 0 test 1 -gt 2 # $? = 1 false test 1 -eq 1 -a 2 -gt 1 # -a = AND, -o = OR test -f fileName test -d dirName ``` ## Footnote Using single or double square brackets is more convenient. [], [[]]
125
In shell scripts, how to test conditions using single square brackets?
``` [ 1 -eq 1 ] # $? = 0 [ ! 1 -eq 1 ] # $? = 1 false [ -f fileName ] [ ! -d dirName ] # return 0 if dirName is not a directory ``` ## Footnote If you use double brackets, you can use ==, >, < instead of -eq, -gt, -lt
126
In bash scripting, how is double square bracket method different from single square bracket method?
Difference is in condition representation. With single sqr brkt, you use `-eq, -lt, -gt, -a, -o` etc for comparision. With double sqr brkt, you can use usual algebraic symbols `==, >, < &&, ||` for comparision.
127
How to check if a user by name `hamid` exists in Linux?
Use `id` command ``` > id hamid ```
128
How to check if `ubuntu` has a specific package installed?
``` > apt search pwgen ``` Output should have `[installed]` in it.
129
In `ubuntu` where is the info about repositories?
* /etc/apt/sources.list * /etc/apt/sources.list.d Each line represents one repository, or package source. A repository line can be commented out by `#` in the begining.
130
Give an example of arithmatic operation in shell script using double parenthesis.
``` a=$(( 3 + 5 - 2)) echo $a # 6 a= $(( 2**10)) # 1024 ``` * No floating point arithmetic * Don't use $ sign with variables inside double paranthesis.
131
How is `bc` used to perform floating point arithmetic in shell scripts?
``` echo "1.5 + 2.7" | bc # 4.2 echo "scale=2; 1/3" | bc # .33 a=.5 b=$( echo "$a + 0.3) echo $b #.8 ```
132
What is the meaning of ``` const int *ptr; ```
``` const int *ptr; ``` * `ptr` points to an integer * `ptr` cannot be used to modify the integer it is pointing to. * `*ptr` cannot appear on the LHS of `=` * While `ptr` cannot change the object it is pointing to, `ptr` itself can be changed to point to different objects. ``` int x=5, y = 10; const int *ptr; ptr = &x; ptr = &y; // Both valid *ptr = 20; // This is wrong ``` It is *not* necessary to initialize ptr to some integer at the time of declaration.
133
What the meaning of following, ``` int x=10, y=20; int * const ptr = &x; ```
* `ptr` points to an integer `x` * `ptr` cannot point to any other integer * `ptr` can be used to modify the value of integer it is pointing to. ``` *ptr = 25; // is valid. Value of x is now 25 ptr = &y; // Not valid. ptr cannot point to other integers. ``` `ptr` must be initialized to point to an integer at the time of declaration. ``` int * const ptr; // Invalid, ptr must point to some int at the time of declaration. ```
134
What is the meaning of ``` int x=10, y=20; const int * const ptr = &x; ```
* `ptr` is pointing to an integer * `ptr` cannot point to any other integer * `ptr` cannot be used to modify the value of integer ptr is pointing to. * Neither `ptr` nor `*ptr` can appear on LHS of `=1
135
What is a `mutable` member variable in a C++ class?
A `mutable` member variable can be modified inside a `const` function.
136
What is C++11 way of forcing the compiler to generate a default Xtor, even though, the class already has non-default Xtors?
``` class A { public: A(int x); // Non default xtor A() = default; // Compiler generated }; ```
137
How to delete/remove a docker image?
``` docker rmi image_id ```
138
How to list all docker containers?
``` > docker container ls # only running containers > docker container ls -a # whether running or not running ```
139
How to start/stop an already existing container
``` > docker start abcd > docker stop abcd ```
140
How to go inside a running container? ## Footnote Attaching to a container
``` docker exec -it abcdef bash ``` ## Footnote abcdef should be started first with `docker start abcdef`
141
How to create a docker container and go inside it from an image?
``` > docker run -it img_name bash // Following will give container a name > docker run -it --name khan_container alpine ash // Run container in detached mode > docker run -dit alpine ash ```
142
How to list all docker images on my local machine?
``` > docker image ls ```
143
How to run a cmd on a running container and get the output? ## Footnote Don't want to go inside the container.
``` > docker exec container_id cmd_name ``` ## Footnote Note there is no `-it` in command, since we don't want interactive.
144
How to create a docker image from a `Dockerfile`? ## Footnote `Dockerfile` is in the current directory.
``` > docker build -t newImageName . ``` ## Footnote `Dockerfile` must be in the current direcotry
145
How to get details about a docker container?
``` docker inspect container_id ``` Following info is available in JSON object * Status (exited, running, ...) * Running (false, true) * Image (sha256) * NetworkSettings: Networks:IPAddress
146
Alpine Linux: How to add packages
Use `apk` ``` > apk update > apk add pwgen ```
147
How to create a docker container in detached mode from a given image_id?
``` > docker run -dit alpine ash // To go inside this container > docker attach container_id // To detach from this container, press CTL p q ```
148
How to list all available docker networks?
``` > docker network ls ``` Default network for a container is `bridge`
149
How to see which docker containers are connected to the `bridge` network?
``` > docker network inspect bridge ``` containers: {Name..., IP4Address...} .... "IPAM"."Config"."Subnet" contains the subnet address which all attached containers will have.
150
Docker: How to create a new `bridge` type network?
``` > docker network create --driver bridge khan_bridge_nw_1 > docker network inspect khan_bridge_nw_1 // To delete this network, > docker network rm khan_bridge_nw_1 // To create a container connected to this netowrk, > docker run -it --network khan_bridge_nw1 alpine ash ```
151
How to ping a machine only 5 times?
``` > ping -c 5 192.168.0.100 ``` statistics will be printed after 5 pings.
152
How to connect an already running container to a docker network?
``` > docker network connect khan_nw_1 container_id ``` ## Footnote At the time of creation of container, it can be connected to only one network. Later it can be connected to any number of networks using this method. One network at a time.
153
What is the difference between `docker run` and `docker exec` cmds?
* `docker run` takes an image_id as a parameter & creates & run a new container * `docker exed` takes container_id of an existing container. Examples, ``` > docker run -it ubuntu /bin/bash > docker exec -it sad_khan /bin/bash ```
154
How to create a docker image from an existing container along with all its current data?
``` > docker commit container_id new_img_id ```
155
At what state in a container's lifetime, is port mapping done?
Port mapping is done when creating the container from the image (with `docker run -p 80:80` cmd. Once a container is created, we cannot map more ports to an existing container. A new container from the image will need to be created. | Port mapping is done with `docker run` cmd, NOT with `docker exec` com
156
What is `upcasting` in C++
When we declare a pointer to Base class, and make it point to a Derived class object. It is always allowed in public inheritance. Only Base class members can be accessed this way. Additional Derived class members cannot be accessed this way. `Object slicing` is involved here. We are making a Derived class object `pretend` as if it is a Base class object. It is always safe. No typecasting is needed for this.
157
What is `downcasting` in C++
When we make a Base class object pretend as if it is indeed a Derived class object. Accessing additional derived class members (which are non-existant in Base class obj) will result in unpredictable behaviour. Compilation will go through but run time behaviour will be unpredictable. We declare a pointer to Derived class and make it point to a Base class object by explicit type-casting. ``` Derived *ptrD; Base b; // Base class object ptrD = (Derived *) b; ``` It is dangerous.
158
In `C++` what is `lambda introducer`?
`lambda introducer` is the square brackets just after `=` and before the round brkts in lambda definition. ``` auto greet = []() { cout << "Hello from lambda\n"; }; ``` in above exmpl `[]` is the `lambda introducer.
159
What is `lvalue` and `rvalue` in C++?
lvalue is a variable with address like `int x` rvalue is a temporary value or literal that appears in an expression, like ``` x = 17; // 17 is rvalue x = a + b; // a + b is rvalue ``` rvalues don't have an address and can only appear on RHS. When a function returns value `by value`, it is an rvalue, and cannot appear on LHS. when a function returns value `by reference` it is an lvalue and can appear on LHS.
160
What's the correct name for old C++ reference variable.
lvalue reference.
161
What is a `const reference` in C++?
It is a constant reference to an existing variable. It can be used to read the variable, but not to modify it. ``` int x = 100; const int& cref = x; // cref is a constant reference cout << cref << endl; // good, only reading. crfef = 20; // compile error, cannot modify ``` const reference can also be used with literal values, ``` const int& k = 50; // works fine ```
162
How to define an `rvalue reference` in C++?
By using `&&` ``` int&& rref = 50; rref = 100; // Allowed ```
163
How is a `unique pointer` to an integer created in C++?
``` unique_ptr up1( new int(17) ); ``` Create a raw pointer at the same time you create the unique pointer and pass the raw pointer to the constructor. Unique pointers cannot be copied to other unique pointers, that's a compilation error. There destructor gets called automatically when they go out of scope.
164
How is a unique pointer to an integer created using `make_unique` template function?
``` unique_ptr uptr1 = make_unique(42); ``` In last round brackets, give all Xtor parameters.
165
How to release memory held by unique_ptr?
``` // uptr is a unique pointer, uptr.reset(); // uptr is now NULL, destructor will be called. uptr.reset( new int(25) ); // This will call Dtor of old object, create new object and uptr will point to new object. // Get the underlying raw/classical pointer, int *rawPtr = uptr.release(); // uptr is now NULL // rawPtr holds the classical pointer to the object. // You can now `delete` it, but it won't get deleted automatically. ```
166
How is a shared pointer created?
``` shared_ptr sp1 = make_shared(25); shared_ptr sp2(new int(47)); ``` Shared pointers can be copied to each other. You can use reset() to delete the object. You can use get() to get a raw pointer to the underlying object (non-owning). You can use use_count() to get the reference count. Shared pointers can be passed to functions. `make_shared<>()` **CANNOT** be used to create an array of objects in this form. We have to specify a `deleter function`, or use vector.
167
What is a `weak pointer` in C++?
A weak_ptr is a non-owning pointer. It is assigned a value from a `shared_ptr`. It CANNOT be constructed directly from a raw pointer. Weak pointer cannot be dereferenced directly using a `*`. They have to be locked first to make sure they are not dangling. ``` shared_ptr sp1 = make_shared(43); weak_ptr wp1 = ip1; if(auto shared2 = wp1.lock()) { cout << "Weak ptr points to " << *shared2 << endl; cout << "sp1 ref count is " << sp1.use_count() << endl; // 2 } else cout << "wp1 is pointing to NULL\n"; ``` Weak pointers have no say in life time of objects they are pointing to.
168
What is the use of `explicit` in C++?
In C++, `explicit` is used to prevent type conversion introduced by single parameter constructors. ``` ClassName obj = 35; // Implicit type conversion from int to ClassName. ``` `explicit` is used to prevent inadvertant type conversion.
169
How do `public, private, protected` access specifiers work in C++ classes?
* `public` members can be accessed from anywhere. * `private` members can only be accessed from within the methods of the class. They *cannot* be accessed from derived class implementation code. * `protected` members can only be accessed from within the methods of the class *and also from the methods of derived classes*. A good guideline is, * All members can be accessed from anywhere within the implementation code for that class. * All `public` members can be accessed from anywhere. * In a derived class, the protected members of parents are ALSO accessible.
170
In `C++` what is a `Pure Abstract Class` (PAC)?
A `Pure Abstract Class` has * No data members * No concrete functions/methods (all pure virtual) A `PAC` provides no implementation, only API interface definitions.
171
How to find the architecture of an ubuntu machine?
``` > dpkg --print-architecture ```
172
How to check if MQTT (mosquitto) service is running? ## Footnote MQTT functionality is provided by mosquitto package in ubuntu.
``` > systemctl status mosquitto ``` ## Footnote MQTT is a communication protocol used in IoT systems.
173
How to find wich port `mosquitto` service is using? ## Footnote mosquitto service provides MQTT functionality.
``` mosquitto -v ```
174
How to publish and receive messages using `MQTT/mosquitto` system? ## Footnote MQTT or mosquitto us widely used for IoT communications.
* You should know the IP address of the publisher (say localhost) * You should know the topic string (say "tpk_1") Open two terminals, one for publisher and one for subscriber. On subscriber terminal, type ``` mosquitto_sub -h localhost -t tpk_1 ``` On publisher terminal, type, ``` > mosquitto_pub -h localhost -t tpk_1 -m "Hello World MQTT" ``` This message should appear on subscriber terminals.
175
How to get info about `CPU` in a linux system?
``` > lscpu > cat /proc/cpuinfo ```
176
`QEMU:` How to list all virtual machines?
``` > virsh list --all ```
177
What is the starting point for learning `rvalue and move` stuff?
**const reference or const lvalue refere** An lvalue reference cannot refer to a literal. But a `const lvalue reference` CAN refer to a literal. ``` int& ref = 10; // wont compile const int& ref = 10; // WILL compile ```
178
What is the `rule of three` in C++
In a class if you need to implement *any* of the following, 1. Destructor 2. Copy Constructor 3. Assignment operator Then you should implement **ALL** of them.
179
How to debug a shell script?
Run the script with `-x` or `-v` option, ``` > bash -x scr_1.bash > bash -v scr_1.bash # same as -x but without + signs ``` You can aslo insert `set -x and set +x` inside bash script around the portion you want to debug ``` set -x shell command 1 shell command 2 .... set +x ``` This will ONLY print info about included portion. You can also add following in the very first line of script, ``` #!/bin/bash -x or #!/bin/bash -v ``` You can syntax check a script without running it with `-n` ``` > bash -n scr_1.bash ``` **Detecting unset/undefined variables using -u option** Normally, shell script does not flag when undefined/unset variables are getting used inside the script. It just assumes there value to be zero or empty string. But if we run the script with `-u` option it flags such usages, ``` > bash -u scr_1.bash > bash -uv scr_1.bash ```
180
In bash scripting, what is the main difference between `[` and `[[` for conditions?
With `[[` we can use `&&` for `AND`, where as with `[` we have to use `-a` and `-o` for `AND OR`.
181
In bash scripts what is the best way of doing maths?
use `(( ... ))` ``` a=5 b=8 c=$((a +b)) echo $c ((c++)) ``` Don't use `$` with variables inside `(( ... ))`
182
How to list all python modules installed?
``` > pip list ```
183
How to create a python `virtual environment`?
``` > python3 -m venv khan_virt_env ``` A directory with name `khan_virt_env` will be created. Activate this virtual environment with ``` > source khan_virt_env/bin/activate ``` Prompt will show the virtual environment name. Deactivate this virtual environment with ``` > deactivate ``` ## Footnote You need to install on ubuntu, `apt install python3.10-venv`
184
How to practice 'HTTP' messages?
Use python module `requests` to send test `HTTP` messages. Send them to the site `https://httpbin.org`
185
In `Python`, can we get pointer to an object or variable?
We can use `id(obj)`. `id` of an object is unique. We CANNOT do pointer arithmetic on `id`s.
186
In Python, what happens when you equate `=` an object (eg list) to a different variable? Is a new copy of object gets created?
**NO** The variable points to the same old underlying object. Any change made to the object using either variable will be visible to the other variable. ``` a = [1, 2, 3] b = a a is b # True b.append(4) # b is now [1,2,3,4] print(a) # [1, 2, 3, 4] a is b # True ``` | This does **NOT** apply to integers. ## Footnote Assignment DOES **NOT** COPY an object. IT ONLY binds a new variable name.
187
In `Python`, what are `mutable` and `immutable` objects?
A `mutabe type` can have its value modified `in place` without modifying its `id` (List, Dict, user defined class/objects). An `immutable` type cannot have its value modified `in place`. A new variable with new `id` needs to be created and old variable will be destroyed (if not referenced by any other variable) (e.g., `int, string, tuple`) Assignment (`=`) behaves differently for mutable and immutable types. Python **DOES NOT MAKE SHALLOW COPY BY DEFAULT** like C++ does.
188
In Python, how is assignment operation (`=`) differ for `mutable` and `immutable` types?
**Mutable type assignment** With mutable type assignment, new variable points/refers to same old object, and no new object is created. Any change made by either variable is visible to the other variable. Both variables always have same `id` ``` a = [1, 2, 3] b = a # b and a are both [1, 2, 3], they have same ids b[0] = 25 # a and b both are [25, 2, 3], they still have same ids ``` Python does **NOT** make a shallow copy by default like C++. **Immutable type assignment** With immutable types, assignment does ***lazy copying***. Initially both variables point/refer to the same underlying object, they both have same `id`. If any change is made by one variable, a new copy of the object is created (with new id) and change is applied to that copy. `ids` of two variables are now different. This change does not affect the other variable. ``` x = "ABC" y = x # x and y are both "ABC", their ids are also same at this time y = "DEF" # Now y = "DEF" and x = "ABC", id(y) is also different now ```
189
How is `std::array` defined in C++
``` std::array arr = {1, 2, 3, 4, 5}; ``` ## Footnote use normal [] to access elements wo range checking. Or, use arr.at(2); that throws exception on out of range. arr.size() will give the array size.
190
How to iterate over `std::array` in C++
``` std::array arr; for(int x: arr) { cout << x << endl; } ```
191
What is the basic usage of `cmake`?
Go to directory containing `CMakeLists.txt` ``` > cmake -B build ``` A folder with name `build will be created. - OR Go to directory contaning `CMakeLists.txt`. Manually create a folder named `build` ``` > cd build > cmake .. ``` This will create the `Makefile` To run the Make file and create the target binary, ``` > cmake --build build # last one is folder name. ```
192
In C++, what is the use of keyword `final`?
* A class declared `final` cannot be inherited from. * A virtual function declared `final` cannot be redefined or overridden in a derived class. * A class declared `final` cannot be used as a base class to create derived classes.
193
In `git` how do you see the differences between two commits?
``` > git diff abcd 1234 > git diff --name-only abcd 1234 > git diff branch1 branch2 ```
194
In Visual Studio Code (VSCode) how to comment out a block of lines?
Select all lines to be commented. Click on `Edit` then choose, * Toggle Line Comment or CTL + / * Toggle Block Comment or Shift + Alt + A
195
In Visual Studio Code (VS Code) how to go to matching bracket?
`CTL + SHIFT + \`
196
In Visual Studio Code (VS Code) how to go top of the function (where function signature is)?
`CTL + Shift + O`
197
In Visual Studio Code (VS Code) how to insert a comment so it is visible in `minimap`?
Insert your comment as follows, ``` // Mark: Your comment here ``` Now "Your comment here" will be visible in `minimap`.
198
In Visual Studio Code (VS Code) how can we keep the code header (eg function name, or for loop header) from scrolling off the screen as we scroll through the code?
Use `Sticky Scroll` View --> Appearance --> Sticky Scroll
199
In Visual Studio Code (VS Code) what is `Sticky Scroll`?
It keeps the code headers like function names, for loop headers etc., visible and keep them from scrolling off the screen. It is useful when viewing long function or loops etc. Enable/Disable it with View --> Appearance --> Sticky Scroll
200
When using `CubeIDE` for code editing, how to do `code completion`?
Type partial code, press `CTL + Space` Choose complete code from the list.
201
While using `CubeIDE` how to jump to function/Struct/class definition and come back?
Press `CTL` and right click on function/class/struct definition. You can get back to previous location by, `ALT + Left Arrow`
202
What do you know about `Blue Pill` STM32 board?
* Microcontroller: STM32F103C8T6 * Red LED on board is connnected to PC13
203
What is the basic code structure of a program generated by `CubeIDE` for STM32 microcontroller?
``` int main() { HAL_Init(); SystemClock_Config(); MX_GPIO_Init(); while(1) { } } ```
204
What's the best place to find the pin diagram of an `STM32` nucleo board?
ST microelectronics `user manual`. Often represented as `um` This has info and diagrams of many nucleo boards at about page 32.
205
In `STM32` what are the steps to configuring a pin `PA8` for `external interrup`?
**YT: Aleksandar Haber PhD (External Interrupts and Hardware Demonstration using LED-Button)** * In CubeMX diagram, choose pin for external interrupt, make it `GPIO_EXTI8`. * Categories --> GPIO --> Make sure "External Interrupt with rising edge detection" is chosen. * NVIC tab: Enable EXTI line[9..5] * GPIO tab: make sure "Modified" is checked. * Generate code * In main.c, go to impl of MX_GPIO_Init() * Go to impl of HAL_GPIO_Init() * In file stm32l4xx_hal_gpio.c at about line 524, look for following function (weak) * void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); * Implement this function in main.c (without weak) ======== Alternatively ======= YT: Terminal Two "#8 STM32 GPIO button Interrupt" Core/Src/stm32l4xx_it.c void EXTI15_10_IRQHandler(); HAL_GPIO_EXTI_IRQHandler(pin_num); weak HAL_GPIO_EXTI_Callback(pin_num) Re-implement this function in main.c without *weak*.
206
What's a good source of info to set up UART on STM32 nucleo board?
**YT: "Aleksandar Haber PhD"** STM32 Microcontroller Tutorial 6: UART Serial Communication and Send Messages to Computer
207
In an STM32 board, how to setup UART (serial communication) between the board and PuTTy on a laptop?
Check YT: Aleksandar Haber PhD * Create STM32 project * In IOC file, make sure USART_TX & USART_RX pins (normally PA2 & PA3) are green. * Note their USART number (USART2) * Categories --> Connectivity --> USART2 --> * Mode : Asynchronous * Parameter settings: Note baud rate (115200) * Use this baud rate in PuTTy) * In main.c, note `huart2` handle ``` UART_HandleTypeDef huart2; // Note this char msg[64] = "Hello Wold\r\n"; // In loop HAL_UART_Transmit(&huart2, (uint8_t *)msg, sizeof(msg), 100); HAL_Delay(1000); ```
208
In `STM32 CubeIDE` what is a good place to get the example `HAL GPIO` function definitions & parameters?
``` bliky_proj/Drivers/STM32L4xx_hal_gpio.h ``` go to end, you will see, ``` /* IO operation functions *****************************************************/ HAL_GPIO_ReadPin(GPIO_TypeDef* , uint16_t ); HAL_GPIO_WritePin(GPIO_TypeDef* , GPIO_Pin, GPIO_PinState); void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); ```
209
In `STM32` microcontrollers, what are some of the clocks?
* LSI (Low Speed Internal, 32 KHz, RTC) * LSE (Low speed External) * HSI (High Speed Internal, 16 MHz) * HSE (High Speed External) MSI (Multi Speed Internal, between LSI & HSI, selectable frequency) Internal clocks are not very accurate, temperature dependent. PLLs can be used to multiply/divide clock signals. `HCLK` is the most important clock. It feeds the CPU. Different buses inside the microcontroller (like APB1, AHPB etc.) have different clocks. Different peripherals, like RTC, ADC, UART, I2C etc are conntected to different buses operating at different clock speeds.
210
What is `I2S` protocol?
`Inter IC sound` Used to transfer hight quality stereo audio data between ICs. * microphone and DAC * ADC and DSP
211
In `CubeIDE`, we can go to a function definition by pressing `CTL + Left click`. How can we get back to the previous location?
`ALT + Left Arrow`
212
What are some of the buses inside STM32 microcontroller?
* AHB: Advanced High Performance Bus (connecting uC, SRAM, Flash and other peripheral buses) * AHPB: Advanced High Performance Peripheral Bus. * APB1, APB2 ... : Advanced Peripheral Bus 1, 2, ... RTC is connected to APB2 Buses use `AMBA` protocol. Advanced Microcontroller Bus Archtectue.
213
How to use a `Timer` in **STM32**?
* In .ioc file, choose timer, say TIM16 * From uC datasheet bus diagram, note down on which bus the TIM16 is connected, say APB2. * From clock diagram in .ioc, note down that bus's frequency * In categories --> Timers --> TIM16, Check "activated" box. * Choose pre-scaler value. (10-1) will divide the clock by 10. In main.c ``` HAL_TIM_Base_Start(&htim16); current_timer_count_val = __HAL_TIM_GET_COUNTER(&tim16); ``` If you want to use this timer in `interrupt mode`, meaning, we want a function to get called each time the counter overflows, we need to start the timer in interrupt mode, and implement a `timer interrupt callback function` ``` HAL_TIM_Base_Start_IT(&htim16); /* USER CODE BEGIN 4 */ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) { if(htim == &htim16) { HAL_GPIO_TogglePin(GPIOA, GPIO_PIN_5); } } /* USER CODE END 4 */ ```
214
In `VS Code` how to navigage opened files easily?
`CTL TAB`
215
In `VS Code` how to open `Command Palette`?
`CTL Shift P`
216
In `VS Code` how to indent a block of lines?
`CTL ]` `CTL [`
217
In `VS Code` how to see two files at the same time?
Drag the tab of the other file inside and to the right. `Editor Groups`
218
In `git` what is the meaning of `working tree`?
Raw files on disk we are editing. As opposed to `staged files` or `index`.
219
Show me a simple `CMakeLists.txt` file.
``` cmake_minimum_required(VERSION 3.22) project(hello_world) add_executable(${PROJECT_NAME} main.cpp) ``` This will create an executable named hello_world from the source file main.cpp Create a folder named `build` in the same directory where CMakeLists.txt is. ``` mkdir build cd build cmake .. # Makefile will be created in folder build make # Executable hello_world will be created ``` Or, don't manually create folder `build`. From the folder where CMakeLists.txt is, do following, ``` cmake -B build # creates fldr build and puts Makefile in it cd build cmake --build . # Runs Makefile and creates executable ```
220
In `CMake` what is `FetchContent` used for?
`FetchContent` is used to download & locally install a library & make it linkable to the current project. The library is downloaded and built in following folder ``` build/_deps ``` Sample usage showing use of doctest library ``` project(Demo_FetchDoctest) include(FetchContent) # Always needed FetchContent_Declare( doctest GIT_REPOSITORY https://github.com/doctest/doctest.git GIT_TAG V2.4.11 ) FetchContent_MakeAvailable(doctest) # Now linkable add_executable(${PJCT_NM test.cpp) # test.cpp is ours target_link_libraries(${PJCT_NM PRIVATE doctest::doctest) ``` When you create a library from your own sources in the project, you use `add_library`. When you download the library from internet, you use `FetchContent`
221
In `CMake` how do you create a library from your sources in the project & link it to the executable?
You use `add_library(libName src_files)` In the following example, Files mylibrary.cpp & mylibrary.h are used to create the library named libmylibrary.a The executable is created from helloworld.cpp Then that library is linked to the executable. ``` project(HelloWorld) add_library(mylibrary mylibrary.cpp mylibrary.h) add_executable(HelloWorld helloworld.cpp) target_link_libraries(HelloWorld mylibrary) ``` If you want to download the library from the internet (github) rather then from your own sources, use `FetchContent`.
222
In MS Windows, how to compare two src files, like Linux diff?
Use fc.exe command ``` > fc.exe file1.c file2.c > fc.exe /N file1.c file2.c # With line nums > fc.exe /W file1.c file2.c # ignore white spaces ```
223
In C++ how does `enum class` or `scoped enum` work?
``` enum class coffee_size {small, medium, large}; enum class fry_size {small, medium, large}; coffee_size cf_sz = coffee_size::medium; fry_size fr_sz = fry_size::large; ```
224
In C++, what does `std::move(obj)` do?
It is used to convert an Lvalue to Rvalue. If an object contains pointers, after `std::move()`, its resources can be transferred to another object without deep copying. Like, ``` b = std::move(a); // Now b has acquired a's resources. a is empty now. ``` std::move() can be used to call `move Xtor` ``` A a1; A a2(a1); // Calls A's copy xtor A a3(std::move(a1)); // Calls A's move Xtor. a1 is now khukkal. ``` ## Footnote std::move(obj) *loosens* obj's hold over resources it contains.
225
Using `awk`, how to print first and third colum of a file?
``` > awk '{print $1, $3}' data.txt ```
226
Using `awk`, how to print all lines where 4th column is greater than 169
``` > awk '$4 > 169' data.txt ```
227
Using `awk` how to print all lines containing the substring "John"?
``` > awk '/John/' data.txt ```
228
Using `sed`, how to substitute a word for a different word in a file?
``` > sed 's/Linux/Unix/g' file_1.txt ```
229
Using `cut` command, how to print various fields from a comma separated file (csv)
``` > cut -d',' -f 3 data.txt # print third field > cut -d',' -f1,3 data.txt # print 1 & 3 fields > cut -d ',' -f1-3 data.txt # print 1 through 3 fields ``` -d' ' speciies space delimiter symbol -d':' specifies colon delimiter symbol | specify field delimiter with -d ## Footnote use -c to specify characters rather than fields.
230
In C++, how is `std::function` used to store and call normal functions.
std::function() type variable has to be defined with matching signature. To store and call normal functions that take two ints and return a double, do the following, ``` #include double retDiv(int x, int y) { return x/y; } function f; f = retDiv; f(7, 3); ``` This can also work with lambdas and class member methods. | This works like C function pointers.
231
In C++, how is `std::function` used with lambdas?
A variable of type `std::function` with matching signature has to be defined. Use following examples, ``` auto addLambda = [](int x, int y) { return x+y }; auto diffLambda = [](int x, int y) { return x-y; }; function f; f = addLambda; f(3, 4); f = diffLambda; f(3, 4); ```
232
In C++l, how is `std::function` used with class methods?
You have to have an object of the class first. Define an `std::function` with right signature. Use following example, ``` #include class MyClass { public: void disp(int x) const { cout << x << endl; } void showDec(int x) const { cout << (x-1) << endl; } }; function f; f = &MyClass::disp; f(15); f = &MyClass::showDec; f(27); ```
233
Can we send a function or a lambda as a parameter to another function?
**Yes**, Use `std::function` type variable to receive the function or lambda. Signature should match. ``` auto arith_mean = [](int a, int b) { return (a+b)/2.0; }; auto geom_mean = [](int a, int b) { return sqrt(a*b); }; void disp_avg(int x, int y, function mean_kind) { double avg; avg = mean_kind(x, y); cout << avg << endl; } int main() { disp_mean(5, 2, arith_mean); disp_mean(2, 5, geom_mean); return 0; } ```
234
What are common ways to initialize an `STL vector`?
``` vector vec1(5); // A vector of 5 chars vector vec2(5, 'H'); // A vector of 5 chars each initialized to 'H' ``` More elements can be added or removed normally.
235
How to create a two dimentional int array (matrix)?
Use a vector of vectors. Each inner vector being a row. ``` vector< vector > vec1{ {1, 2, 3}, {4, 5, 6} }; // Two rows, three columns // Elements can be accessed as vec1[1][2] etc. ```
236
In C++, how to display a floating pt number with an exact number of decimal places?
``` cout << fixed << setprecision(6) << 1.0/3.0 << endl; ```
237
In `C` language, how to convert a numeric string to equivalent integer?
Use `atoi()` function. ``` const char *numStr1 = "1234" int num = atoi(numStr1); ```
238
In `C++` how is `using` used to create new names of data types?
``` using counter = int; counter x = 7; using intVec = vector; intVec vec1{23, 29, 31, 37, 43}; ```
239
How to quickly sum up elements of a vector?
``` vector vec1 = {1, 2, 3, 4, 5}; int sm = accumulate(vec1.begin(), vec1.end(), 0); ``` We can also define custom functions or lambdas ``` int prod = accumulate(vec1.begin(), vec1.end(), 1, [](int a, int b) { return a*b; }); ```
240
How to see if a value is present in a vector?
Use `std::find()` ``` vector vec1 = {5, 1, 3, 8, 4}; auto itr = find(vec1.begin(), vec1.end(), 3); // Check if 3 is present if(itr == vec1.end) cout << "Not found\n"; else cout << "Element found\n" ```
241
How does `find_if` works on STL containers?
Define a function or lambda that takes an element type & returns a bool. ``` bool greater_then_7(int x) { if(x > 7) return true; else return false; } list lst1 = {1, 4, 6, 8, 3}; auto itr = find_if(lst1.begin(), lst1.end(), greater_then_7); if(itr != lst1.end) cout << "Found " << *itr << endl; else cout << "Not found\n"; ```
242
How does, `find()` works with `STL maps`?
With maps, `find()` works with `keys`, not values. ``` map mp = {{1, "Ek"}, {5, "Paanch"}, {3, "Teen}}; auto itr = mp.find(5); if(itr != mp.end()) cout << "Found : " << itr->second << endl; else cout << "Not Found\n"; ```
243
How does `emplace` work with STL vectors?
emplace_back() creates an object at the end. You don't pass the object, rather you pass all the arguments of the constructor. emplace(), creates an object at the given iterator position. You don't pass the object, rather you pass all the arguments of the constructor. ``` class Point { public: int x, y; Point(int a, int b): x(a), y(b) {} }; vector dots; dots.emplace_back(5, 7); dots.emplace_back(13, 45); dots.emplace(dots.begin()+1, 8, 9); // Insert Point(8, 9) ``` With `emplace`, copy or move constructor is not called. Object directly gets created at the desired location using normal Xtor.
244
How does `reverse()` function work with STL containers/iterators?
reverse(), reverses the container in place. ``` vector vec1 = {'H', 'u', 'm', 'k', ' ', 'K', 'h', 'a', 'n'}; reverse(vec1.begin(), vec1.end()); // vec1 is now reversed. ``` If you want to keep original vector intact, and make a new vector reversed, use `reverse_copy()` ``` vector vec1 = {'H', 'u', 'm', 'k', ' ', 'K', 'h', 'a', 'n'} vector vec2(vec1.size); // should have enough space. reverse(vec1.begin(), vec1.end(), vec2.begin()); ``` Create space for new vector first.
245
How to use `std::find()` function to check if an element is present in a `C` array?
Need to determine the number of elements in the array first. ``` char arr[] = {'G', 'e', 'o', 'r', 'g', 'e'}; int numElems = sizeof(arr)/sizeof(arr[0]); char *ptr; ptr = std::find(arr, arr+numElems, 'g'); if(ptr == arr + numElems) cout << "Not Found\n"; else cout << "Found " << *ptr << endl; ``` ## Footnote You can use std::find() with other STL containers too.
246
How does `std::begin()` & `std::end()` functions work with standard raw C++ arrays?
These functions return raw pointers. ``` char name[] = {'G', 'e', 'o', 'r', 'g', 'e'}; char *b, *e; b = std::begin(name); e = std::end(name); cout << *b << *(e - 1) << endl; // G e ``` Now with these pointers/iterators, you can use all STL algorithms, such as, * std::find() * std::find_if() * std::sort() * std::reverse()
247
How does `std::count()` function work?
It returns the number of occurences of a value in a container. ``` char name[] = {'r', 'a', 's', 'h', 'e', 'e', 'd'}; char *b, *e; int num; b = std::begin(name); e = std::end(name); num = std::count(b, e, 'e'); // returns 2 num = std::count(b, e, 'k'); // return 0 ``` std::find() returns the first occurrence. std::count() returns total number of occurrences.
248
How does `std::count_if()` function work in C++?
It returns the number of elements satisfying a specific condition (determinned by a function or lambda, returning bool). ``` bool isOdd(int x) { return x%2; } int arr[] = {7, 3, 9, 11, 4, 141}; int num_odds = std::count_if(begin(arr), end(arr), isOdd); // 5 num_odds = count_if(begin(arr), end(arr), [](int x){ return x%2; }) ```
249
How does the `std::min_element()` & `std::max_element()` functions work in C++?
They return an iterator to min or max element. Remember to check for empty range. ``` int arr[] = {7, 39, 9, 181, 4, 141}; int *ptr; ptr = std::min_element(std::begin(arr), std::end(arr)); if(ptr == std::end(arr)) cout << "Empty range\n"; else cout << "Minimum element is: " << *ptr << endl; ``` `std::max_element()` works similarly.
250
How to declare a `const` STL vector?
``` const vector vec1 = {10, 20, 30}; vec1[1] = 0; // Compilation error vector::const_iterator itr1 = vec1.begin(); ```
251
In Python, how to get the type of a variable?
Use `type()` ``` x = 34 y = "Hello" print(type(x)) print(type(y)) ```
252
Give some examples of type casting in Python.
``` x = 57 y = str(x) ```
253
In Python, how do you iterate through a string?
``` for x in "Banana" print(x) ```
254
In Python, how do you find length of a string?
``` a = "ABC" print(len(a)) ```
255
In Python, how to check if a substring is present in a string?
Use `in` ``` txt = "The best things in life are free" if "free" in txt: print("Found") else print("Not Found") ```
256
In Python, how to get slices of strings?
``` a = "ABCDEFG" print(a[2:4]) # "CD" print(a[-1]) # "G" print(a[-3:-1]) # "EF” print(a[ : 4]) # "ABCD" print(a[ 4: ]) # "EFG” ```
257
In Python, how to change a string to upper/lower case?
``` a = "Hello" a.upper() # "HELLO" a.lower() # "hello" ```
258
In Python, how to remove outer white spaces from a string?
Use `strip()` ``` a = " Hello World " a.strip() # "Hello World" ```
259
In Python, how to replace each instance of a character with another character?
``` a = "Hello World" print(a.replace("o", "A") # HellA WArld # Returns a copy. Original string is not changed. ```
260
In Python, how to split a string into individual tokens. Store them in a list?
``` a = " Shashi Mohan Sharma " b = a.split() # b is ["Shashi", "Mohan", "Sharma"] a = "aaa-bbb_ccc-ddd" b = a.split("-") # b is ["aaa", "bbb_ccc", "ddd"] ```
261
In Python, how are `f strings` used.
The are used to for mixing print strings with variables and numbers etc. ``` weight = 150 age = 45 a = f"My name is Khan, I am {age} years old and weigh {weight} lbs" print(a) ```
262
In Python, how is `in` used?
To check if something is contained in another (sequence, list, range etc) ``` nums = [1, 2, 3, 4] if 3 in nums: print("Found" # Check substring s = "hello world" if "world" in s: print("Substring found") ``` With Dictionaries it checks only keys, not values ``` d = {1 : "Ek", 2 : "Do", 3 : "Teen"} 2 in d # True To check values, do following, "Teen" in d.values() # True ``` For iterating over elements ``` for x in [7, 11, 13, 17]: print(x) for ch in "Hello": print(ch) for key in dict1: print(key) for key, val in dict1: print(key, val) ```
263
In Python, how to add new elements to a list.
``` fruits = ["Apple", "Banana", "Grapes", "Plum"] fruits.insert(2, "Pear") # "Grapes", Plum" Will be pushed to right fruits.append("Orange") ```
264
In Python, how to remove items from a list?
``` a = ["apple", "banana", "cherry", "orange"] a.remove("cherry") # No value returned x = a.pop() # Last value returned y = a.pop(1) # indexed value returned. ```
265
266
In python, how to sort and reverse a list?
``` a = [7, 8, 5, 3, 25, 14] a.sort() a.reverse() ```
267
In Python, how to find the number of occurences of an element in a list/tuple?
# works with lists too Use `count()` ``` a = ("kk", "hh", "cc", "hh", "ss") c = a.count("hh") # 2 If not found, returns 0 # Works with lists too # If you want index of element, use index() function ```
268
How to find index of an element in a list/tuple?
Use `index()` function. ``` a = ("kk", "ss", "hh", "rr", "ss", "mm", "aa", "ss") c = a.index("ss") # Returns 1 // You can specify starting index, inclusive c = a.index("ss", 2) # Returns 4 You can specify both starting and ending index (exclusive) c = a.index("ss", 2, 6) # index 6 is excluded ```
269
In Python, how to add new elements to a set?
Use `add()` or `update()` ``` a = {"apple", "banana", "orange"} a.add("grape") b = {"aam", "amrood"} a.update(b) ```
270
In Python, how to remove elements?
Use `remove()` or `discard()` ``` a = {"apple", "banana", "orange"} a.remove("banana") # remove() objects when element is not found. a.discard("banana") # discard() does not object if does not exist. ```
271
In Python, what set operations are available?
``` set1 = { ....} set2 = {....} # union set3 = set1 | set2 Intersection set3 = set1 & set2 difference set3 = set1 - set2 Symmetric difference set3 = set1 ^ set2 ```
272
In Python, what are `Frozen sets`?
They are like sets, but no addition or deletion of elements is allowed.
273
Give an example of Python switch/match.
``` day 6 match day: case 6: print("Saturday") case 7: print("Sunday") case _: print("Weekday") ```
274
Give examples of Python `range()` function.
``` for x in range(6): print(x) # 0, 1, 2, 3, 4, 5 range(2, 6) # 2, 3, 4, 5 range(2, 13, 3) # 2, 5, 8, 11 print(list(range(6))) # can't print range directly, make list first ```
275
In Python, what is `kwargs`?
**Keyword Arguments** You can pass function arguments in any order by explicitly naming them when calling the function. You can choose to not name some parameters, but they should appear before keyword arguments. (Positional arguments) Keyword arguments must be in the end. ``` def func1(a, b, c, d) pass func1(7, 4, 8, 2) func1(c=8, b=4, d=2, a=7) func1(7, 4, d=2, c=8) ```
276
In Python, what is `*args`?
It is used in function definition. It can receive any number of arguments in the form of a tuple. ``` def func1(*args) # Receives all arguments def func2(a, b, *args) # a & b are received as position arguments, remaining are received as a tuple ``` args is used at the time of function definition. **Not** at the time of calling.
277
In Python, what is `**kwargs`?
It is used at the time of defining the function. It can receive any number of Keyword arguments (name value pairs) in the form of a dictionary. ``` def func1(**myvar): pass func1(name="aa", age=45, weight=121) # myvar dict = ("name" : "aa", "age" : 45, "weight" : 121) ``` We can combine normal positional arguments with `**kwargs` pairs. But all normal positional parameters must be specified first. ``` def func2(name, **otherDetails): print(name) for key, val in otherDetails.items(): print(key, val) func2("Hamid", age=50, wt=160, hight=6.5) ```
278
In Python, how to combine `*args`, `**kwargs` along with normal positional arguments.
When calling the function, * Put positional parameters first * Then put unnamed parameters (without name-value pair) * Then put name-value pair parameters. When the function definition receives the parameters, * all positional parameters will be matched first. * Then all remaining unnamed (without pair) parameters will be received by `*args` tuple. * In the end, all name value pair parameters will be received by `**kwargs` dictionary. ``` def student(name, rollNum, *args, *kwargs) # name = "John", rollNum = 567 # args = (70, 160) # kwargs = {school="JMI", salary=2500, city="Delhi"} pass student_info("John", 567, 70, 160, school="JMI", salary=2500, city="Delhi") ```
279
Give a simple example of Python lambda.
``` x = lambda a : a+5 print(x(10)) # 15 ``` Functions can return lambdas. ``` def myfunc(n): return lambda a : a*n # Returns lambda myDoubler = myfunc(2) # Actually: myDoubler = lambda a : a*2 print(myDoubler(7)) # 14 ```
280
In Python classes, who does `__str__()` method work?
It returns a string representing information inside the object.
281
In a Python class, how to make a member `private` or `protected`?
To make a member private, name should start with double underscores, lke __age, __salary etc. You cannot access them from outside the class. With in the class you can access them. To make a member protected, name should start with a single underscore, like _age or _salary etc. Compiler does not enforce it. It is **ONLY A CONVENTION**.
282
In Python, how to create an `iterator` to a list/tuple/dictionary/set etc?
Use `iter()` ``` lst1 = [25, 15, 21] # Arbit list itr1 = iter(lst1) print(next(itr1)) # 25 print(next(itr1)) # 15 print(next(itr1)) # 21 print(next(itr1)) # Exception ```
283
In C++, is it possible to have a `templated` function and a `non-templated` function with same name?
Yes, it is possible. When a function is called and its signature matches exactly with `non-templated` function, then non-templated function is called.
284
In C++, how is `reinterpret_cast<>` used?
It is very risky to use. It is normally used to convert a pointer of one type to another. ``` int x = 5; double *y; y = reinterpret_cast(&x); cout << *y << endl; // most likely wont print 5 ```
285
In C++ classes, how are `static const int` member variables different from other static member variables?
`const static` integral member variables need not be declared and given value outside the class. They can be declared & given value inside the class definition itself.
286
How is `static_cast<>` used in C++?
It is used for type conversion among related types.. ``` // Between char and int, char c = 'a'; cout << a << endl; // prints a cout << static_cast(c) << endl; // prints 97 ``` Similarly you can do type conversion among * signed & unsigned * integer and float * base and derived classes.
287
In C++, how is `assert` used with error message?
Use `comma operator`. Use comma to separate error message string from `condition`. Make sure to use double parentheses. ``` int evenNum = 7; assert(("Number should be even" , evenNum%2 == 0)); ```
288
In C++ what are the two kinds of `expressions`?
* Run-time expressions (Normal) * Constant expressions (evaluatable at compile time) Later are `constexpr`
289
In C++ what is `brace initialization`?
More strict variable initialization. ``` int x = 13.7; // Allowed int y{13.7}; // compilation error. ``` `Brace initialization` does NOT allow, * Implicit conversions * Narrowing.
290
In C++ what are `constexpr` functions?
`constexpr` functions have `constexpr` pre-appended to their signature. They are ***evaluatable*** at compile time (with all constexpr arguments). These functions can ***also*** be called like normal run-time functions without any restrictions on argument constantness. ``` constexpr double calcCirc(double radius) { constexpr double pi {3.1416}; return 2.0 * pi * radius; } // Call the function to initialize a constexpr variable. constexpr double circ { calcCirc(3.0) }; cout << circ << endl; ``` constexpr functions CAN be used as initializers of constexpr variables like circ above. It is **NOT** necessary that constexpr functions to be called/evaluated at compile time. The compiler **WILL** be evaluate/call them at compile time if **circumstances** make it necessary.
291
How is `lock_guard` used with mutexes in Linux?
* Create a mutex (say khan_mtx) ``` mutex khan_mtx; // For locking, lock_guard laeeq_lock(khan_mtx); // .... do your stuff here // No need for explicitly unlocking, mutex will get unlocked when laeeq_lock variable goes out of scope. ```
292
In C++, what does `std::atomic x{0};` do?
It defines an integer with `atomic operations` for following operations. * X++, ++x, x--, --x * x.load() // Atomic read * x.store(7); // Atomic write. * x.fetch_add(5); // Atomically read, add, store * x.fetch_sub(3); It provides `indivisible operations` on variables. Other threads cannot see incomplete results. It provides atomicity `only to simple variable operations`. Mutex is suitable for protecting whole sections of code. Atomic types can be used with * Integral types * Boolean * Double, float * Pointers Don't use atomic with user defined structures and classes.
293
What does C++ `std::bind()` do?
It specializes functions with a specific set of arguments. ``` void func(int x, int y) { // prints x & y } auto f = std::bind(func, 10, 20); // x = 10, y = 20 f(); // same as calling func(10, 20); // Specialize by specifying only some arguments. auto f1 = std::bind(func, 10, std::placeholders::_1); f1(3); // Same as calling func(10, 3); // Change order of arguments, auto f2 = std::bind(func, std::placeholders::_2, std::placeholders::_1); f2(7, 4); // func(4, 7); ``` std::bind() can be used to specialize class member functions and lambdas. ``` class C1 { int func(int x) { return x*x; } }; C1 obj1; auto f = bind(&C1::func, obj1, placeholders::_1); int retVal = f(7); // same as obj1.func(7) ```
294
In C++, what does it mean when we say something is `not copy assignable`?
You cannot use assignment operator ( = ) between two *existing* objects. ``` // If Class XYZ is not copy assignaable, then XYZ a, b; a = b; // Compilation error. ``` This is possible in many scenarios, e.g., when a member variable of the class is a reference. Compiler deletes the default assignment operator of the class.
295
In C++, what is the use of `std::ref`?
* std::bind() * std::thread() * std::function() only work with pass by value arguments. They cannot work with reference parameters directly. To make them work with reference parameters we use `std::ref()` ``` void increment(int& a) // Need reference parameter { ++a; } int x = 5; auto f = std::bind(increment, x); // Wont work auto f = std::bind(increment, std::ref(x) ); // Fine f(); ``` std::ref() is used to construct references out of variable names, if they are needed in `std::bind(), std::thread() or std::function()`.
296
In python, how does `list slicing` work?
`L[start indx : stop indx : step size]` * Absent start = start index is 0 * Absent stop = Go to end of list * Absent step size = step sz is one. Don't skip any element. * Element at last index is excluded.
297
In Python string slicing, how does -ve indexes and -ve step size work?
Negative indexes work from the end of list/string. Last element is indexed -1. In a slice with negative indexes, start value should be `more negative` then stop value. Like [-7 : -4] With -ve step size, the string is traversed in reverse direction, from bigger to lower indexes. Hence if step size if -ve, then start index should be ***bigger than*** end index. See below, ``` str[10 : 3 : -1] # Start index is bigger str[ : : -1] # reverses the string. ```
298
In Python, how is `range()` function used?
Mostly used with for loops. ``` for x in range(5): print(x) # 0, 1, 2, 3, 4 range(3, 8) # 3, 4, 5, 6, 7 range(3, 8, 2) # 3, 5, 7 range(10, 3, -2) # 10, 8, 6, 4 range(start, stop, step) ```
299
`MATLAB:`, how to avoid printing of result from a command?
Put semicolon at the end. ``` x = 5; # will print the result on screen x = 5; # Will not print result on screen ```
300
`MATLAB:` How to save all workspace variables in a file name khanFile.mat?
``` > save khanFile; > clear; # Clears the workspace of all vars > load khanFile; # Loads all vars from named file ``` More commands ``` load khanFile x; # Load only variable x from file save khanFile x; # Save only variable x to file ```
301
`MATLAB:` How to clear the workspace screen, but retain the variables and their values?
``` clc; ```
302
`MATLAB:` How to create arrays?
Row elements are separated by spaces or commans. Rows are separated from other rows by semicolons. ``` row_vec = [ 6 8 7]; # Space separated row_vec2 = [3 , 9 , 5]; # comma seperated col_vec = [13 ; 17 ; 47]; mtx_2x3 = [4 5 9 ; 2 1 7]; # 2 X 3 ```
303
`MATLAB:` How to create a row vector of equally spaced elements?
Use`:` notation. start : step : end (inclusive) ``` x = 7 : 2 : 13 # [7, 9, 11, 13] Default step size is one y = 5 : 8; # [5, 6, 7, 8] z = 2 : 0.5 : 4; # [2.0, 2.5, 3.0, 3.5, 4.0] ```
304
`MATLAB:` How to create a row vector by specifying start, end, total number of elements? | Stuff equally spaced elements in a closed interval.
Use `linspace()` linspace(start, end, totalNumber); ``` x = linspace(1, 2, 5); # Five elems between 1 & 2 ``` | *Linear Space*
305
`Matlab:` Name some special matrices.
``` rand(3, 5) # 3X5 random nums zeros(5, 2) # 5X2 zeros ```
306
`MATLAB:` How to get documentation about a something.
``` > doc random numbers ```
307
How do you compile an `Ada` program in Linux?
``` > gnatmake hello.adb ```
308
In C++, what does `std::boolalpha` do?
Normally, bool values are printed as `0` or `1`. But if we first do `cout << boolalpha;` then, bool values will be printed as text, `true` or `false`. It **only** affects the printing format of bool values.
309
In C++, what are `type traits`?
Type trait is a structure that contains info about data types (like int, double, char etc). ``` cout << is_integral::value; # true cout << is_integral::value; # false cout << is_integral::value; # true is_pointer::value; # false is_pointer::value; # true ``` It helps get info about data types. It is useful in `templates` where types are generic, and we can get info about data types in the code and write program accordingly. | Questions abt data type by typ traits are fly answered at compile time
310
In C++, how does `enable_if` work?
`enable_if` works with templated functions. It enables function for some data types and disables (or makes them invisible/undefined) them for some other data types. It will be compilation error to use the function with types which are prohibited by `enable_if`. It works with `type traits`.
311
In Python, how is `argparse` module used to handle command line arguments?
First create a parser at the begining of the program, then add `positional parameters` in correct order, then call `parser.parse_args()`, this will return an object with a field for each positional command line argument. ``` import argparse parser = argparse.ArgumentParser("Laeeqs program") parser.add_argument("name", help="Admi ka naam") parser.add_argument("age", help="Admi ki umj") lmkArgs = parser.parse_args() print("Aap ka naam: " + lmkArgs.name) print("Aap ki umr: " + lmkArgs.age) ```
312
In Python, how does `type hints` work?
``` name : str = "Haamid" age : int = 25 function definition def jor(a : int, b : int) -> int : return (a + b) # Multiple type hints value : int | str # value can either be int or string value = 25 value = "Shamsi" # Both are intententional ``` Type hints are not enforced. They are for documentation a ease in code reading. Some libraries like `numpy` detects them
313
How to create a hellow_world project in `Rust`?
``` > cargo new hello_world > cd hello_world > cargo build > cargo run > ./target/debug/hello_world ``` Or create a hello.rs file manually, then, > rustc hello.rs
314
What are basic data-types in `Rust`?
* i8, i16, i32, i64, i123 * u8, u16, u32, u64, u128 * f64 * bool (true, false) * char ('a', 'B', 'g'...) ``` let x : i32 = -76; let pi : f64 = 3.14; let flag : bool = true; let letter : char = 'H'; println!("Pi is {}", pi); // integer array let numbers: [i32; 5] = [10, 20, 30, 40, 50]; println!("Num array: {:?}", numbers}; // string array let fruits : [&str; 3] = ["Apple", "Banana", "Orange"]; println!("Fruits are {:?}", fruits); // tuples can have mixture of data types. () let tpl = ("Danish", 47, false, [59, 61, 67]); println!("my tpl is {:?}", tpl); ```
315
In C++, how to obtain the `raw pointer` from a `shared pointer`?
Use get() function, ``` shared_ptr p1 = make_shared(49); int *raw_ptr = p1.get(); ``` Avoid doing this, since it is risky.
316
What is the difference between, * docker run * docker exec
`docker run` creates a new container from the image. `docker exec` makes use of an already running container. If a container already exists on your local machine, you can start it with `docker start abcd` and, you can stop a running container with `docker stop abcd`
317
What is `docker compose`?
With docker compose, you can specify a number of docker containers along with their, * image names * ports * environment variables etc in a YAML file `docker-compose.yml` With command, `docker compose up` All containers will start. And with command `docker compose down` all containers will get deleted.
318
Give me a high level overview of Docker networking.
Docker containers are inside a host machine. Host machine also has simulated networks for docker containers. There are some default docker networks inside the host machine and we can also create additional networks. By default, when we don't specify any network at the time of container creation, it is connected to default bridge network. These containers can ping google by default. There are three kind of docker networks * Bridge network * Host network * None network Containers connected to host network use the same network interface as host machine. They don't need to expose/map any ports. We can list all existing networks. We can inspect any network to see what containers are connected to it.
319
Give me an over all description of kubernetese.
``` # Nodes = Physical machines, # Pods = containers # Replica sets # Deployments # Rollouts # Services # kubelets > sudo systemctl status rke2-server # start, stop > kubectl get nodes > kubectl get pods -A # pods -w > kubectl get deployments > kubectl get replicasets ```
320
How to run a Python program as a kubernetese workload?
* Create Python files (Also requirements.txt with modules) * Create Dockerfile to create the Docker image * Build Docker image (> docker build -t image_name . * Create tarball from the image * Make image available to RKE2 (see below) * Copy tarball to k8s image registery (directory) * Create Kubernetese Manifest file (YAML file) * Apply the manifest (see below) * kubectl apply -f my-flask-app.yaml * Re-start rke2-server service if needed * Verify with kubectl get deployments / pods / svc
321
In a `Rust` project, how to add dependency for a `crate`?
Add the dependency in `Cargo.toml` manifest file. Under [dependencies] section along with version number. ``` # Cargo.toml file [dependencies] rand = "0.8.5" ```
322
What is the registery of Rust's crates?
`crates.io`
323
In `Rust`, how are strings compared?
`use std::cmp::Ordering` use cmp function on strings, ``` let s1 : &str = "apple"; let s2 : &str = "banana"; let result = s1.cmp(s2); The value of result will be Ordering::Less, Ordering::Equal or Ordering::Greater ```
324
`Rust:` Show some usage of `enum` in rust language.
enum values can be just a list of labels, ``` enum Color { Red, Green, Blue } let rang : Color = Color::Blue; ``` enum items can be data of different kinds, like integers, strings etc ``` enum Value { Number(i32), Text(&'static str) } let v : Value = Value::Number(37); // let v : Value = Value::Text("Haamid"); match v { Value::Number(n) => println!("Got Number: {n}"), Value::Text(s) => println!("Got Text: {s}") } ``` So a label can also contain a value of certain type. When the label mach is found, the associated value can also be extracted.
325
In `Rust`, how is a parameter passed to a function by `reference`?
When we pass a parameter to a function by `reference`, we pre-append `&` to the parameter both in function definition and also at function call point. ``` fn calculate_length(s : &String) -> usize { s.len() } fn main() { let s1 = String::from("Hello"); let sz = calculate_length( &s1 ); // Passing s1 by reference println!("Size of string is {sz}"); } ``` `&mut` is added both in function definition as well as at the time of function call. If you want the function to be able to modify a parameter by reference, you make the reference mutable (`&mut`) ``` fn change(some_string : &mut String) { some_string.push(" world"); // Reference modifies received parameter } fn main() { let mut s : String = String::from("hello"); // mutable variable change(&mut s); println!("{s}"); } ```
326
In Rust, what are `tuple structs`?
`tuple structs` are like structs, but individual fields are not named. ``` struct Color(i32, i32, i32); struct Point(i32, i32, i32); let sabz : Color = Color(0, 255, 0); println!("Hara value = {}", sabz.1); ```
327
Show me a hello world program in `GoLang`.
Create file hello.go ``` package main import "fmt" func main() { fmt.Println("Hello world"); } ``` Compile and run, ``` > go build hello.go > ./hello > -- or --- > go run hello.go ```
328
Show a basic usage of arrays & slices in `Go Lang`.
``` // Fixed size array var people [50]string // Variable size array (slice) var books []string // Variable size // Append element to slice books = append(books, "Republic") ```
329
In `Rust`, what is the idea behind `Option`, `Some` and `if let`?
`Option` is a `variable type` `Option` type is an integer or *no value at all*. ``` let x : Option = Some(17); if let Some(v) = x { println!("x contains value {}", v); } else { println!("x does not contain a value"); // None } ```
330
In `rust`, how to easily print a `struct` using println!()
pre-append the struct with `#[derive(Debug)]` and, in println!() use {:?} ``` #[derive(Debug)] struct Anumber { num : i32 } fn main() { let age : Anumber = Anumber{ num : 25}; println!("age struct is {:?}", age); } ``` This makes compiler generate code in struct so prnintln!() can format the struct and print it.
331
How does the `linspace()` of numpy (Python) work?
numpy.linspace(start_val, end_val, num_of_vals) gives an ndArray of num_of_vals, equally spaced, begining from start_val and ending in end_val. Both start_val and end_val are included.
332
Please show the basic procedure for plotting a graph using Python's `matplotlib`
``` import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [10, 20, 30, 40, 50] plt.plot(x, y) plt.show() ``` We can generate x an y data using numpy's `linspace()` function. Using pyplot's functions, we can, * We can add labels to X and Y axes. * We can add a title to the graph * We can draw multiple graphs with different data points.