Negative index in Python

Python is a versatile language that you can use on the backend, frontend, or full stack of a web application. In this blog post, we will discuss negative indexing in Python. We will cover what it is and how to use it. Negative indexing can be confusing for beginners, but once you understand it, you will find that it is a very powerful tool.

Negative indexes are a way to allow you to index into a list, tuple or other indexable container relative to the end of the container, rather than the start.The reason this is called negative indexing is that the number you are using is less than the 0th element in the list.

They are used because they are more efficient and are considered by much more readable.

l = [0,1,2,3,4,5]
>>> l[-1]
5
>>> l[len(l) – 1]
5

Negative indexing in Python is when you use a negative number to index a list. For example, if we have a list of numbers:

>>> my_list = [0, 1, 2, 3]

And we want to get the last element in the list, we would use negative indexing:

>>> my_list[0] # Get the first element in the list
>>> my_list[-1] # Get the last element in the list

As you can see, we use the – sign to denote that we want to start counting from the end of the list.

012345
Python
-6-5-4-3-2-1

The first one will be significantly quicker.You can also use negative indexes in slices, and as with positive indexes, when you do a slice operation, the last element is not included in the slice

>>> l = [0,1,2,3,4,5]
>>> l[-3:-1]
[3,4]

As with positive indexes, the length of a slice can be calculated by subtracting the start index from the end index – in this case: −1−(−3)=−1+3=2 as demonstrated.you can even use negative indexes with negative steps to make a reversed slice :

> >>l = [0,1,2,3,4,5]
>>> l[-1:-4:-1]
[5,4,3]

here the 3rd value in the slice tells Python to go backwards from index -1 (the last element – number 5 here) to index -4 (i.e. 4th from the end – item 2 here), with the final element in the slice omitted.

use negative index in Python pop method

The pop() method takes a single argument (index) and removes the element at that index from the list. It also returns the removed element.If you don’t pass an index to the pop() method, it removes and returns the last element in the list.

>> my_list = [0, 1, 2, 3]
>>> my_list.pop() # Remove and return the last element in the list
3
>>> my_list.pop(0) # Remove and return the first element in the list
0
>>>my_list = [0, 1, 2, 3]
>>># print(my_list.pop(-1)) # Get the last element in the list

use negative index in Python insert method

The insert() method takes two arguments: the first is the index at which you want to insert the element, and the second is the value you want to insert.

>> my_list = [0, 1, 2, 3]
my_list.insert(1, 4) # Insert the element 4 at index 1
>>> my_list
[0, 4, 1, 2, 3]
>>> my_list.insert(0, -100) # Insert the element -100 at index 0
>>> my_list
[-100, 0, 11, 22, 33]
>>> my_list = [0, 11, 22, 33]
And we want to insert the element 44 at index -1
>>> my_list.insert(-1, 44)
>>> my_list
[0, 11, 22, 44, 33]

[mai mult...]

De ce utilizarea CPU nu este distribuită uniform pe toate nucleele din Linux?

Un sistem are un singur nucleu, dacă există un singur proces care consumă tot timpul CPU, atunci când CPU va arăta o utilizare de 100%. Dar în cazul sistemelor cu mai multe, nu este necesar ca toate CPU-urile să fie folosite pentru a rula tuturor proceselor. În astfel de cazuri, utilizarea neuniformă a CPU-urilor disponibile este un comportament de așteptare.

Motivul din spatele utilizării inegale a procesului este că nu este întotdeauna un lucru util să schimbe procesul. Există mai multe lucruri care trebuie efectuate pe lângă schimbarea contextului. Prin urmare, creșterea comutării de context va crește și mai mult latența. Este util să faceți schimbarea contextului numai dacă un singur CPU nu este capabil să facă față numărului de proces care așteaptă CPU în rulare.

Intenția finală a explicației de mai sus este că, dacă există o utilizare de 100% CPU pe un singur CPU și 20-30% pe CPU-ul rămas, atunci nu este întotdeauna o problemă, cu condiția ca procesul să nu aibă afinitatea CPU setată. . pentru un anumit CPU. În general, sistemul de operare nu implică nicio afinitate CPU în sine. Fie o aplicație, fie un utilizator trebuie să spună nucleului să fixeze un proces la un anumit CPU sau la un set de CPU-uri.

Dacă un proces se confruntă cu o scădere a performanței din cauza utilizării ridicate a procesului, atunci numai acesta ar trebui abordat.

[mai mult...]

How to fix: mv cannot access permission denied in Linux

The error message “mv: cannot access ”: Permission denied” indicates that you are trying to move or rename a directory without the access permissions.

There are a few reasons why this error happens:

  • Insufficient permissions: The directory you are attempting to move or rename is owned by another user, and you do not have the access permissions to perform the operation.
  • File or directory is locked: The directory you are trying to manipulate is currently being used or locked by another process, which prevents you from performing the operation.
Add execute permissions to the directory

The purpose of file permissions in Linux is to control access to files and directories, ensuring data security and maintaining privacy. File permissions determine what actions can be performed on a file or directory by different users or groups of users.

  • In our case, that means the user doesn’t have access permissions to the directory. we need to add it to fix the error.
  • First, let’s check out what access permissions mean for a directory.
  • The “execute” permission allows users to access and traverse the contents of the directory. It grants the permission to enter the directory.
  • Accessing the directory: Without the execute permission on a directory, users won’t be able to access or enter it. They will receive a “permission denied” error when trying to navigate into the directory.

Let’s see how to check the permissions of the directory and how to modify them.

Identify the file or directory: Determine the path and name of the directory that you are trying to move or rename. For example, let’s say you want to move a directory called howtouselinux_dir.

Check the current permissions and owner: Use the ls -ld command to view the current permissions of the directory.

Execute the following command in the terminal:

ls -ld howtouselinux_dir

The output will display detailed information about the directory, including the permissions and owner.

drw--wx---. 1 howtouselinux howtouselinux 0 Jun 16 08:51 howtouselinux_dir

Change the directory permissions: If you are the owner of the directory, you can modify the permissions using the chmod command.

For example, we need to give execute permissions to the directory. Run the following command:

chmod u+x howtouselinux_dir

Replace howtouselinux_dir with the actual name of the directory you are working with.

Retry the move or rename operation: After modifying the permissions, try executing the move or rename operation using the mv command again:

mv howtouselinux_dir destination_directory

If you are not the owner of the directory, you can follow the steps below the change it.

Change the owner: Execute the chown command, providing the desired new owner and the file you want to change.

For example, to change the owner of the directory called howtouselinux_dir to a user named howtouselinux, use the following command:

sudo chown howtouselinux howtouselinux_dir

Note: You need to have sufficient permissions or use sudo to run the chown command.

Now you are the owner of the file and you can follow above steps to fix permission issue.

You can also use add access permission to all the users with the following command.

sudo chmod a+x howtouselinux_dir

use sudo to run mv command

The sudo command in Linux stands for “Superuser Do,” and it is used to execute commands with elevated privileges typically the root user. It allows authorized users to perform administrative tasks and actions that require higher permissions.

For example, let’s say you have a file called example.txt located in your current directory, and you want to move it to the /var/www/html directory. The command would be:

sudo mv example.txt /var/www/html

When you execute this command, you will be prompted to enter the password for the user with sudo privileges. After entering the password, the mv command will be executed with elevated privileges, allowing you to move the file to the specified destination.

While sudo is a powerful tool for granting temporary administrative privileges to users, it also has some potential disadvantages that should be taken into consideration.

Managing the sudo configuration file (/etc/sudoers) can be complex, particularly in environments with multiple users, roles, and systems. Misconfigurations or inconsistent settings can lead to unintended access or difficulties in managing user permissions.

release the file lock

If the file or directory is locked by another process, you will encounter a “cannot access” or “permission denied” error. This means that another program or process has exclusive access to the file or directory, preventing you from performing operations on it.

Identify the process that has locked the file or directory and terminate or release it if possible. You can use tools like lsof or fuser to identify the processes that have a file or directory open.

To resolve this issue, here are the steps to accomplish this:

Identify the process: Tools like lsof (list open files) or fuser (file user) can help you identify the processes that have a particular file or directory open. These tools provide information about the files and directories that processes have opened, along with the corresponding process IDs (PIDs).

Using lsof: Run the following command to list the processes that have the file or directory open:

lsof <file_path>

Using fuser: Execute the following command to display the PIDs of processes that are using the file or directory:

fuser <file_path>

Terminate or release the process: Once you have identified the process(es) using the file or directory, you can proceed to terminate or release them. There are a few approaches you can take:

If the process is not critical or can be stopped without causing any issues, you can manually terminate it. Use the kill command followed by the PID of the process. For example:

kill <PID>

If you are unable to terminate the process gracefully, you may need to force its termination. Use the kill -9 command followed by the PID. This forcibly terminates the process, but it should be used as a last resort if graceful termination fails. For example:

kill -9 <PID>

Alternatively, if the process provides a mechanism to release the file or directory, you can use that specific method to release the lock. Refer to the documentation or resources related to the process for guidance on how to release the lock.

Retry the operation: After terminating or releasing the process that had the file or directory locked, you should be able to perform the desired operation, such as moving the file or directory, without encountering the “cannot access” or “permission denied” error.

[mai mult...]

5 moduri de a verifica adresa IP în Linux

În mediul Linux este esențial să poți verifica adresa IP a sistemului tău. Adresa IP este un identificator unic atribuit fiecărui dispozitiv conectat la o rețea, permițându-i acestuia să comunice cu alte dispozitive din rețea.

Verificarea adresei IP în Linux poate fi utilă pentru depanarea problemelor de rețea, configurarea conexiunilor sau pur și simplu pentru a cunoaște informațiile de rețea ale sistemului. În continuare, vom explora diferite metode pentru a verifica adresa IP pe un sistem Linux.

Comanda „ifconfig”:

Comanda „ifconfig” este un instrument utilizat în mod obișnuit pentru afișarea și configurarea interfețelor de rețea în Linux. Poate fi folosit și pentru a verifica adresa IP atribuită sistemului dumneavoastră. Pentru a-l folosi, deschideți un terminal și rulați următoarea comandă:

ifconfig

Aceasta va afișa o listă de interfețe de rețea de pe sistemul dvs., împreună cu adresa IP atribuită acestora. Căutați interfața dorită și găsiți secțiunea „inet” pentru a vedea adresa IP corespunzătoare.

Comanda „ip”:

Comanda „ip” este un instrument mai modern și mai puternic pentru gestionarea setărilor de rețea în Linux. Poate fi folosit și pentru a verifica adresa IP. Pentru a-l folosi, deschideți un terminal și rulați următoarea comandă:

Afișează adresa ip

Aceasta va afișa o listă detaliată a interfețelor de rețea de pe sistemul dvs., inclusiv adresa IP atribuită fiecărei interfețe. Căutați secțiunea „inet” de lângă numele interfeței pentru a găsi adresa IP corespunzătoare.

Comanda „hostname”:

Comanda „hostname” afișează numele sistemului din rețea. Uneori poate afișa și adresa IP atribuită sistemului. Rulați următoarea comandă în terminal:

numele gazdă -I

Aceasta va afișa adresa IP atribuită sistemului.

Instrument de configurare a rețelei:

În funcție de distribuția Linux pe care o utilizați, acesta poate avea și un instrument de configurare grafică a rețelei. Acest instrument oferă o interfață grafică pentru a gestiona setările de rețea și pentru a verifica adresa IP alocată sistemului.

Îl puteți căuta în meniul de setări sau puteți căuta numele specific pe baza distribuției dvs. Linux.

Site-uri web și instrumente online:

Dacă nu doriți să utilizați linia de comandă, puteți, de asemenea, să vizitați site-uri web sau să utilizați instrumente online pentru a vă verifica adresa IP în Linux.

Există mai multe site-uri web, cum ar fi „https://www.whatismyip.com”, care afișează adresa IP publică atunci când vizitați site-ul. De asemenea, puteți utiliza instrumente online care verifică adresa IP internă și externă a sistemului.

Acestea sunt doar câteva metode de a verifica adresa IP pe un sistem Linux. Alegeți-l pe cel care vi se potrivește cel mai bine în funcție de preferințele și cerințele dvs. Când verificați adresa IP, asigurați-vă că identificați dacă verificați adresa IP internă (atribuită în rețeaua locală) sau adresa IP publică (alocată de furnizorul dvs. de servicii de internet).

Pe scurt, într-un mediu Linux, există mai multe modalități de a verifica adresa IP, cum ar fi utilizarea comenzilor din linia de comandă precum „ifconfig” și „ip”, instrumentul de configurare a rețelei, site-urile web sau instrumentele online.

[mai mult...]

How to install wget on Debian systems

How to install wget

Before using wget, it’s essential to verify if it’s already installed on your system. Open your terminal or command prompt and type:

wget --version

If wget is installed, you will see its version information. If it’s not installed, you will likely get an error message stating that the command is not found.

Step 2: Install Wget (if not found)

The method to install wget depends on your operating system. Here are the installation steps for various systems:

Installation on Debian based systems (e.g., Ubuntu):

To install wget on Debian-based systems, you can use the package manager (apt):

sudo apt update

sudo apt install wget

Installation on Red Hat based systems (e.g., CentOS, Fedora):

On Red Hat-based systems, you can use the package manager (yum or dnf) for installation:

# For CentOS 6 and earlier or RHEL 6 and earlier

sudo yum install wget 

# For CentOS 8, CentOS 7, RHEL 8, RHEL 7, Fedora, etc.

sudo dnf install wget 

[mai mult...]

How to install Software in Linux

În orice sistem de operare trebuie să instalăm aplicații pentru a ne îndeplini sarcinile de zi cu zi. În lumea Windows, fiecare program are un simplu Setup.exe sau un fișier program.zip. Pe un Mac, un pachet este un program.dmg sau un fișier program.sit. În ambele sisteme de operare puteți, pur și simplu, să faceți click pe acesta și vă va pune câteva întrebări de configurare foarte de bază.

Al doilea format de manager de pachete este DEB, înseamnă Debian. Pachetele Debian și APT (Advanced Packagin Tool) au creat caracteristici avansate care sunt acum utilizate în mod obișnuit, cum ar fi rezolvarea automată a dependenței și pachetele semnate. Pachetele Debian sunt folosite de Debian/Linux și unele dintre cele mai utilizate distribuții Linux, cum ar fi Ubuntu, Linux Mint, Mepis etc. Fișierele .deb/Debian arată ca acest program-version-other.deb

APT Pentru distribuțiile bazate pe Debian, cum ar fi Ubuntu, Linux Mint

APT este instrumentul, folosit în mod obișnuit pentru a instala pachete, de la distanță din depozitul de software. Pe scurt, este un instrument simplu bazat pe comandă pe care îl utilizați pentru a instala fișiere/software. Comanda completă este apt-get și este cea mai simplă modalitate de a instala fișiere/pachete de software. Acest instrument simplu vă informează despre pachetele care sunt instalate în prezent și, de asemenea, vă informează despre pachetele care sunt disponibile în depozite. 

apt-get install ${packagename}
Pentru a elimina/dezinstala orice software, trebuie doar să utilizați remove
apt-get remove ${packagename}

The software packages are somewhere in the online repositoies, APT handles a local database on the user’s hard drive that contains informations about the available packages and where they are located. So when the types the command, apt-get install conky, the APT will start finding the package named conky in the database and will install conky once user types ‘y’ (yes). To get the all newly uploaded packages on the repositories, user need to update APT regularly.To update APT database:

apt-get update
To update the APT database and also upgrade the security updates and patches that might be available for some installed softwares, users may do it at once just by using the commands like this:
apt-get update; apt-get upgrade

Și amintiți-vă că toate instrumentele de gestionare a pachetelor pe care le discut, vor avea nevoie ca utilizatorul să fie în root sau superutilizator, de exemplu pentru a instala software în distribuțiile bazate pe Debian, veți folosi apt-get urmat de sudo, apoi vă va cere să introduceți parola.

sudo apt-get install conky
sudo apt-get remove conky
sudo apt-get update
[mai mult...]

How to turn off/on firewall on Windows 11 from Registry

To turn off the Windows 11 (Pro) firewall through the Registry, use these steps:

  1. Open Start
  2. Search for regedit and click the top result to open the Registry
  3. Open the following path:
    HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall
  4. Right-click the “WindowsFirewall” key, select the New menu, and choose the Key option.
  5. Name the key StandardProfile and press Enter
  6. Right-click the “StandardProfile” key, select the New menu, and choose the “DWORD (32-bit) Value” option.
  7. Name the EnableFirewall name and press Enter
  8. Double-click the newly created key and make sure the value is set to “0”.
  9. Click the OK button.
  10. Restart the computer.

Once you complete the steps, the firewall will be disabled after the device startup process.

Enable firewall using Registry

To turn on the Windows 11 firewall through the Registry, use these steps:

  1. Open Start
  2. Search for regedit and click the top result to open the Registry
  3. Open the following path:
    HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\WindowsFirewall\StandardProfile
  4. Right-click the EnableFirewall key and choose the Delete option.
  5. Click the OK button.
  6. Restart the computer.

After you complete the steps, the system firewall will enable on Windows 11.

[mai mult...]

Create Clonezilla bootable USB with Tuxboot

Create Clonezilla bootable USB with Tuxboot

You can create a Clonezilla USB with the Tuxboot open-source app with these steps:

  1. Download tuxboot from SourceForge. (Select the latest stable version available.)
  2. Double-click the tuxboot-x.x.x.exe file.
  3. Click the Yes button to bypass the warning.
  4. Select the “On-Line Distribution” option.
  5. Use the drop-down menu and select the Clonezilla-live-stable option.
  6. Select the USB Drive option from the “Type” setting.
  7. Select the flash drive from the “Drive” setting.

  •  Click the OK button.
  • Once you complete the steps, before starting your device with the tool, you need to ensure that your device can boot from USB.
  • Typically, you will need to access your device’s Basic Input/Output System (BIOS) or Unified Extensible Firmware Interface (UEFI) by hitting one of the function keys (F1, F2, F3, F10, or F12), the ESC, or the Delete key during boot.
  • Once inside the firmware, look for the Boot section and make sure the boot order is set to the drive that contains the Windows 10 installation files and do not forget to save the configuration.
  • The BIOS/UEFI can differ depending on the manufacturer and per computer model. As such, check your manufacturer support website for more specific instructions.
[mai mult...]

Create a vpn profile and connect to a vpn in Windows 11

Before you can connect to a VPN, you must have a VPN profile on your PC. You can either create a VPN profile on your own or set up a work account to get a VPN profile from your company.

Before you start:

  • If it’s for work, look for VPN settings or a VPN app on your company’s intranet site while you’re at work, or contact your company’s support person.
  • If it’s for a VPN service you subscribe to for personal use, visit the Microsoft Store to see if there’s an app for that service, then go to the VPN service’s website to see if the VPN connection settings to use are listed there.

Once you have your work or personal VPN settings ready:

  1. Select Start  > Settings  > Network & internet VPN > Add VPN.
  2. Under Add a VPN connection, do the following:
    • For VPN provider, choose Windows (built-in).
    • In the Connection name box, enter a name you’ll recognize (for example, My Personal VPN). This is the VPN connection name you’ll look for when connecting.
    • In the Server name or address box, enter the address for the VPN server.
    • For VPN type, choose the type of VPN connection you want to create. You’ll need to know which kind of VPN connection your company or VPN service uses.
    • For Type of sign-in info, choose the type of sign-in info (or credentials) to use. This might be a username and password, one-time password, certificate, or a smart card if you’re connecting to a VPN for work. Enter your username and password in the respective boxes (if required).
  3. Select Save.

If you need to edit the VPN connection info or specify additional settings, such as proxy settings:

  • From the VPN settings page, select the VPN connection you want to edit, select Advanced options, then select Edit next to the details you want to update. Once you’ve made the updates needed select either Save or Apply.
Connect to a VPN

When you have a VPN profile, you’re ready to connect.

Connect to a VPN quickly from your taskbar:

  1. On your taskbar, select the Network, Volume, Battery    icon > VPN.
  2. From the list of VPN connection names, select the one you want, and then select Connect.
  3. If prompted, enter your username and password or other sign in info.

Connect to a VPN from the Windows Settings page: 

  1. Select Start  > Settings  > Network & internet VPN.
  2. Next to the VPN connection you want to use, select Connect.
  3. If prompted, enter your username and password or other sign in info.

You’ll know you’re connected to a VPN in the following two ways:

  • On the VPN settings page, the VPN connection name will display Connected underneath it.
  • On the taskbar, a blue shield will display when you’re connected to a recognized VPN.
[mai mult...]

How to enable/disable Remote Desktop using Command Prompt on

To enable the remote desktop protocol with Command Prompt, use these steps:

  1. Open Start on Windows 10
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option
  3. Type the following command to enable the remote desktop protocol and press Enter:
    reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
  4. (Optional) Type the following command to enable remote desktop through the Windows Firewall and press Enter:
    netsh advfirewall firewall set rule group="remote desktop" new enable=Yes

Once you complete the steps, the protocol will enable on Windows 10, and you will be able to access the device remotely.

Disable Remote Desktop from Command Prompt

To turn off the remote desktop protocol with Command Prompt, use these steps:

  1. Open Start.
  2. Search for Command Prompt, right-click the top result, and select the Run as administrator option.
  3. Type the following command to disable the remote desktop protocol and press Enter:
    reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 1 /f
  4. (Optional) Type the following command to disable Remote Desktop through the Windows Firewall and press Enter:
    netsh advfirewall firewall set rule group="remote desktop" new enable=No

After you complete the steps, the Remote Desktop service will be turned off, and the Windows Firewall port will be closed. This guide focuses on Command Prompt, but you can use the same commands to manage the remote desktop protocol using PowerShell.

[mai mult...]