26 December 2023
22 December 2023
How to use regex in vim to replace with an incrementing number variable
I have a file which content like this:
id phone name
x'1234' 12345 jack
x'4567' 45678 Jojo
x'7890' 89456 Dio
x'4591' 34872 joseph
and i want to parse it into like this:
id phone name
1 12345 jack
2 45678 Jojo
3 89456 Dio
4 34872 joseph
I know basic regular expression could replace all id to any string like this:
:%s/x'\(\w\+\)'/1/g
and it will become:
id phone name
1 12345 jack
1 45678 Jojo
1 89456 Dio
1 34872 joseph
How to replace id to an increment variable ?
===================================
Mind that you can use an expression as the replacement string in the substitute command (:s
). When the replacement string starts with \=
it is evaluated as an expression.
Here, one possible solution is
:let i=1 | g/^x'\d\+'/s//\=i/ | let i=i+1
It finds all occurrences (one per line) of the ^x'\d\+'
pattern and replaces it with the value if i
that is incremented each time the match is found. As has been noted in comments, the |
is a part of the g
replacing "code", as "|
is used to execute more than one command at a time".
Another solution is using the line()
command (taking into account that your file has a header top line, so you should actually subtract 1
from the value returned with line()
):
%s/^x'\d\+'/\=line('.')-1/
The ^x'\d\+'
regex matches
^
- start of a linex'
-x'
string\d\+
- 1+ digits'
- a'
char.
There are other interesting "increment number in regex" examples at the Using an expression in substitute command page:
- Number all the lines in a file (insert line number followed by a tab):
:%s/^/\=line('.')."\t"/- Number a range of lines (from line 10 to line 20):
:10,20s/^/\=line('.')."\t"/- Number a range of lines sequentially starting from 1:
:let counter=0|10,20g//let counter=counter+1|s/^/\=counter."\t"- Number all the paragraphs in range starting from 1 (assuming the paragraphs are separated by one or more blank lines):
:let counter=0|1,20g/^$\n^\s*[^\s]/let counter=counter+1|+1s/^/\=counter."\t"Note: The above command does not work for the first paragraph in the file if there is no blank line above it.
27 November 2023
Keep asking for password when signing in to OneDrive app
* go to 'Control Panel' > 'Credential Manager', delete all credentials.
10 November 2023
08 November 2023
How to install .deb files on Ubuntu?
$ sudo dpkg -i xxx.deb
if you still faces issues with dependencies execute the following command to install the required dependencies.
$ sudo apt-get install -f
23 October 2023
17 October 2023
How to create a bootable usb drive from an iso file?
15 October 2023
10 October 2023
Can not print to Sharp multi-function printer
'Ports' > 'Configure Port'. Change Protocol from 'Raw' into 'LPR'. Enter 'lp' in 'LPR Settings/Queue Name'. OK.
Can print now.
If seeing error, e.g. 'the port is being used', etc., then restart computer. Do the above steps again.
Can print now.
18 September 2023
3 Easy Ways to Download YouTube Videos in Ubuntu and Other Linux Distributions 3. Command line tool for downloading YouTube videos
https://itsfoss.com/download-youtube-videos-ubuntu/
1. Download YouTube Videos using Firefox Add-on ‘Video DownloadHelper’
2. GUI applications to download YouTube videos on Linux
3. Command line tool for downloading YouTube videos
17 September 2023
How to copy from vim to system clipboard on ubuntu?
https://superuser.com/questions/1559544/how-to-copy-from-vim-to-clipboard-on-ubuntu-20-04
You need to make sure clipboard is activated (which is probably not the case).
Run :
vim --version | grep 'clipboard'
if you get "-clipboard" then you would have to install vim again with the "clipboard" functionality.
You can do it it by installing "vim-gtk3" or "gvim".
Solution
sudo apt-get install vim-gtk3 -y
With that, you will be able to copy into clipboard by typing (including the plus) "+y
How to delete content in the system clipboard on ubuntu?
Install xsel -
$ sudo apt install xsel
Run
$ xsel -bc
How to set up a command for toggling line wrapping in vim?
In .vimrc, add a line -
map <C-a> :set wrap!<CR>
Thus you press Ctrl-A and toggle between line wrapping and unwrapping
16 September 2023
Copy text from pictures on Linux with Textsnatcher
https://www.addictivetips.com/ubuntu-linux-tips/copy-text-from-pictures-on-linux-with-textsnatcher/
$ sudo apt install flatpak
$ sudo flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
$sudo flatpak install flathub com.github.rajsolai.textsnatcher
Step 1: With Textsnatcher open, find the “Snatch Now!” button and click on it with the mouse. After selecting this button, Textsnatcher should open up the default screenshot tool for your Linux desktop.
Note: if you use Gnome or a Gnome-based desktop environment, it will launch the Gnome screenshot tool.
Step 2: With the screenshot tool open, find the “Select an area to grab” option and click on it with the mouse. When you select this button, the screenshot tool will allow you to take a screenshot of a selected area on the desktop.
Step 3: After you’ve selected the “select an area to grab” option, your mouse cursor will become a cross icon. Click and drag over the area you wish to extract text from.
Step 4: Once you’ve selected an area on the desktop with the cursor, the screenshot tool will take a picture. It will open up a dialog box that says, “Share this screenshot with TextSnatcher?”
Select the “Share” button to share the screenshot to Textsnatcher so that it can extract the text contents of the image.
Step 5: With the screenshot exported to Textsnatcher, you should see a message that says “Checkout Clipboard.” From here, go to a text editor (or any other text field) and press Ctrl + V hotkey to paste the text.
15 September 2023
How to clone a git repository from GitHub?
14 September 2023
10 September 2023
Time automatically changes Ubuntu Linux
https://askubuntu.com/questions/1451114/find-out-whether-time-is-updated-automatically
$ sudo apt install systemd-timesyncd
02 September 2023
Microsoft 365: Export Distribution List Members to CSV Using Powershell
How to Connect to Exchange Online Using Powershell
But in practice, there is a much more simple way - Open web Outlook. Compose a new email. Click 'To'. Go to GAL. Search for the name of the distribution list. Click the plus sign.
01 September 2023
31 August 2023
22 August 2023
How to Run Your Own Git Server
https://www.linuxfoundation.org/blog/blog/classic-sysadmin-how-to-run-your-own-git-server
This is a classic article written by Swapnil Bhartiya from the Linux.com archives. For more great SysAdmin tips and techniques check out our free intro to Linux course.
Git is a versioning system developed by Linus Torvalds, that is used by millions of users around the globe. Companies like GitHub offer code hosting services based on Git. According to reports, GitHub, a code hosting site, is the world’s largest code hosting service. The company claims that there are 9.2M people collaborating right now across 21.8M repositories on GitHub. Big companies are now moving to GitHub. Even Google, the search engine giant, is shutting it’s own Google Code and moving to GitHub.
Run your own Git server
GitHub is a great service, however there are some limitations and restrictions, especially if you are an individual or a small player. One of the limitations of GitHub is that the free service doesn’t allow private hosting of the code. You have to pay a monthly fee of $7 to host 5 private repositories, and the expenses go up with more repos.
In cases like these or when you want more control, the best path is to run Git on your own server. Not only do you save costs, you also have more control over your server. In most cases a majority of advanced Linux users already have their own servers and pushing Git on those servers is like ‘free as in beer’.
In this tutorial we are going to talk about two methods of managing your code on your own server. One is running a bare, basic Git server and and the second one is via a GUI tool called GitLab. For this tutorial I used a fully patched Ubuntu 14.04 LTS server running on a VPS.
Install Git on your server
In this tutorial we are considering a use-case where we have a remote server and a local server and we will work between these machines. For the sake of simplicity we will call them remote-server and local-server.
First, install Git on both machines. You can install Git from the packages already available via the repos or your distros, or you can do it manually. In this article we will use the simpler method:
sudo apt-get install git-core
Then add a user for Git.
sudo useradd git passwd git
In order to ease access to the server let’s set-up a password-less ssh login. First create ssh keys on your local machine:
ssh-keygen -t rsa
It will ask you to provide the location for storing the key, just hit Enter to use the default location. The second question will be to provide it with a pass phrase which will be needed to access the remote server. It generates two keys – a public key and a private key. Note down the location of the public key which you will need in the next step.
Now you have to copy these keys to the server so that the two machines can talk to each other. Run the following command on your local machine:
cat ~/.ssh/id_rsa.pub | ssh git@remote-server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"
Now ssh into the server and create a project directory for Git. You can use the desired path for the repo.
git@server:~ $ mkdir -p /home/swapnil/project-1.git
Then change to this directory:
cd /home/swapnil/project-1.git
Then create an empty repo:
git init --bare Initialized empty Git repository in /home/swapnil/project-1.git
We now need to create a Git repo on the local machine.
mkdir -p /home/swapnil/git/project
And change to this directory:
cd /home/swapnil/git/project
Now create the files that you need for the project in this directory. Stay in this directory and initiate git:
git init Initialized empty Git repository in /home/swapnil/git/project
Now add files to the repo:
git add .
Now every time you add a file or make changes you have to run the add command above. You also need to write a commit message with every change in a file. The commit message basically tells what changes were made.
git commit -m "message" -a [master (root-commit) 57331ee] message 2 files changed, 2 insertions(+) create mode 100644 GoT.txt create mode 100644 writing.txt
In this case I had a file called GoT (Game of Thrones review) and I made some changes, so when I ran the command it specified that changes were made to the file. In the above command ‘-a’ option means commits for all files in the repo. If you made changes to only one you can specify the name of that file instead of using ‘-a’.
An example:
git commit -m "message" GoT.txt [master e517b10] message 1 file changed, 1 insertion(+)
Until now we have been working on the local server. Now we have to push these changes to the server so the work is accessible over the Internet and you can collaborate with other team members.
git remote add origin ssh://git@remote-server/repo-<wbr< a="">>path-on-server..git
Now you can push or pull changes between the server and local machine using the ‘push’ or ‘pull’ option:
git push origin master
If there are other team members who want to work with the project they need to clone the repo on the server to their local machine:
git clone git@remote-server:/home/swapnil/project.git
Here /home/swapnil/project.git is the project path on the remote server, exchange the values for your own server.
Then change directory on the local machine (exchange project with the name of project on your server):
cd /project
Now they can edit files, write commit change messages and then push them to the server:
git commit -m 'corrections in GoT.txt story' -a And then push changes:
git push origin master
I assume this is enough for a new user to get started with Git on their own servers. If you are looking for some GUI tools to manage changes on local machines, you can use GUI tools such as QGit or GitK for Linux.
Us
15 August 2023
How to contribute to a software development on Git?
e.g.
1. Log in to GitHub, and on this project's page, click "Fork" to your own repository.
2. Clone your repository to your local machine:
$ git clone https://github.com/xxx/Ansible-VIM-IDE.git
3. Add the original repository as the upstream branch on the master branch:
$ git remote add upstream https://github.com/Hello-Linux/Ansible-VIM-IDE.git
4. Create a new development branch locally:
$ git checkout -b dev
5. Make code changes and commit on the development branch:
$ git add .
$ git commit -am 'xx change description'
6. Switch to the master branch and synchronize with the original repository:
$ git checkout master
$ git pull upstream master
7. Switch to the dev branch, merge the local master branch (which is now synced with the original repository), resolving any conflicts if needed:
$ git checkout dev
$ git merge master
8. Push the local dev branch to your remote dev repository:
$ git push origin dev
9. On your GitHub repository page, click "Compare & pull request" to send a pull request to the original repository.
10. Wait for the original author's response (accept/reject).
12 August 2023
How to install NERDTree for vim? | How to always display a file explorer at the left side in vim?
https://github.com/preservim/nerdtree#readme
How to install NERDTree?
Pathogen
Pathogen is more of a runtime path manager than a plugin manager. You must clone the plugins' repositories yourself to a specific location, and Pathogen makes sure they are available in Vim.- In the terminal,
git clone https://github.com/preservim/nerdtree.git ~/.vim/bundle/nerdtree
- In your
vimrc
,call pathogen#infect() syntax on filetype plugin indent on
- Restart Vim, and run
:helptags ~/.vim/bundle/nerdtree/doc/
or:Helptags
.
How to display file explorer in vim?
:NERDTree
06 August 2023
My .vimrc
set textwidth=78
set encoding=utf-8
set fileencoding=utf-8
" enable syntax highlighting
syntax enable
" show line numbers
set number
" set tabs to have 4 spaces
set ts=4
" indent when moving to the next line while writing code
set autoindent
" expand tabs into spaces
set expandtab
" when using the >> or << commands, shift lines by 4 spaces
set shiftwidth=4
" show a visual line under the cursor's current line
" set cursorline
" show the matching part of the pair for [] {} and ()
set showmatch
set guifont=Consolas:h11
" avoid word breaking at end of each screen line
set linebreak
" enable all Python syntax highlighting features
let python_highlight_all = 1
set splitbelow
set splitright
nmap <C-h> <C-w>h
nmap <C-j> <C-w>j
nmap <C-k> <C-w>k
nmap <C-l> <C-w>l
" vim-pathogen
execute pathogen#infect()
syntax on
filetype plugin indent on
" Ctrl-P
set runtimepath^=~/.vim/bundle/ctrlp.vim
" *'g:ctrlp_map'*
" Use this option to change the mapping to invoke CtrlP in |Normal| mode:
let g:ctrlp_map = '<c-p>'
" *'g:ctrlp_cmd'*
" Set the default opening command to use when pressing the above mapping:
let g:ctrlp_cmd = 'CtrlP'
" *'g:ctrlp_working_path_mode'*
" When starting up, CtrlP sets its local working directory according to this
" variable: >
let g:ctrlp_working_path_mode = 'ra'
set colorcolumn=5,9,13,17,21
" NERDTree settings
"
" Start NERDTree. If a file is specified, move the cursor to its window.
autocmd StdinReadPre * let s:std_in=1
autocmd VimEnter * NERDTree | if argc() > 0 || exists("s:std_in") | wincmd p | endif
" Open the existing NERDTree on each new tab.
autocmd BufWinEnter * if getcmdwintype() == '' | silent NERDTreeMirror | endif
let NERDTreeWinSize = 20
" toggle between line wrapping and unwrapping
map <C-a> :set wrap!<CR>
" set colorcolumn color
:hi ColorColumn ctermbg=lightgrey guibg=lightgrey
28 July 2023
24 July 2023
Adding locally hosted code to GitHub
Adding locally hosted code to GitHub
Adding Locally Hosted Code to GitHub
====================================
Initializing a Git repository
=============================
1. Open Terminal.
2. Navigate to the root directory of your project.
3. Initialize the local directory as a Git repository. By default, the initial branch is called main.
If you’re using Git 2.28.0 or a later version, you can set the name of the default branch using -b. ::
$ git init -b main
4. Add the files in your new local repository. This stages them for the first
commit. ::
# Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.
$ git add .
5. Commit the files that you've staged in your local repository. ::
# Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
$ git commit -m "First commit"
Importing a Git repository with the command line
================================================
1. Create a new repository on GitHub.com. To avoid errors, do not initialize the new repository with README, license, or gitignore files. You can add these files after your project has been pushed to GitHub. For more information, see "Creating a new repository."
2. At the top of your repository on GitHub.com's Quick Setup page, click to copy the remote repository URL.
3. Open Terminal.
4. Change the current working directory to your local project.
5. Add the URL for the remote repository where your local repository will be pushed. ::
# Sets the new remote
$ git remote add origin <REMOTE_URL>
# Verifies the new remote URL
$ git remote -v
6. Push the changes in your local repository to GitHub.com. ::
# Pushes the changes in your local repository up to the remote repository you specified as the origin
$ git push origin main
23 July 2023
22 July 2023
Software for live vedio streaming, for different contents presentation - vmix
20 July 2023
19 July 2023
logical drive is undergoing parity initialization for ages
Click 'Modify Controller Settings' > 'Surface Scan Analysis Priority'. Change 'Idle (with delay)' into 'High'. Click 'Save Settings'.
05 July 2023
24 June 2023
23 June 2023
17 June 2023
05 June 2023
10 Useful Websites for Web Developers to Boost Productivity
03 June 2023
Hide/unhide from Global Address List Office 365 not working Open PowerShell
Open PowerShell
Hide:
Set-ADUser adusername -Replace @{msExchHideFromAddressLists=$true}
Unhide:
Set-ADUser adusername -Replace @{msExchHideFromAddressLists=$false}
23 May 2023
How to convert texts into speech using AI?
Tips on how to use Narakeet to create phone greetings https://www.narakeet.com/languages/canadian-accent-text-to-s...
- Write a clear phone script: "Thank you for calling the Centre for Immigrant and Community Services. Please note that our offices are closed on Monday, July 3rd, 2023, in observance of Canada Day. All of our offices will open on Tuesday, July 4th. We hope you have a wonderful and joyous celebration, and happy Canada Day!"
- Type the script into Narakeet, including all the punctuations and spaces. The system will pause and adjust the greeting accordingly, regardless of the language.
- For Mandarin greeting, please type the Chinese greeting and choose the voice: "Zhihan" (芷涵).
- For Cantonese greeting, please adjust the wording of the Chinese greeting to make it sound more natural in Cantonese, and then choose the voice "Pak-chi" (柏芝).
- For the English greeting, choose Canadian English and then select "Pamela" as the voice.
- Note that Narakeet is a free online tool that only allows 20 free greetings. However, this quote resets once the IP address changes.
- After downloading all the greetings, you can combine them using Chipchamp. Remember to leave a 0.5-second pause between each greeting.
- Finally, export the greeting after reviewing everything to obtain the final audio file.
- TIP: ChatGPT is a good tool for reviewing the clarity of the greetings.
====================================================
English
==============================================
Mandarin
https://ttsfree.com/text-to-speech/chinese-mandarin-simplified
==============================================
Cantonese
https://ttsfree.com/text-to-speech/chinese-cantonese-traditional
======================
Concatenate Audio files
12 May 2023
11 May 2023
How to install Control-P for vim?
https://ctrlpvim.github.io/ctrlp.vim/
-
Clone the plugin into a separate directory:
$ cd ~/.vim $ git clone https://github.com/ctrlpvim/ctrlp.vim.git bundle/ctrlp.vim
-
Add to your
~/.vimrc
:set runtimepath^=~/.vim/bundle/ctrlp.vim
-
Run at Vim's command line:
:helptags ~/.vim/bundle/ctrlp.vim/doc
-
Restart Vim and check
:help ctrlp.txt
(or simply :help ctrlp) for usage instructions and configuration details. - When CtrlP helps find the file you want to open, if you simple press Enter, it will fill the current full window. Maybe that is not what you want.
- If you want to split the current window vertically and open it, press Ctrl-V;
- If you want to split the current window horizontally,, and open it, press Ctrl-S.
- If you want to open the file on a new tab, press Ctrl-T.
900 Free Computer Science Courses from the World’s Top Universities
08 May 2023
05 May 2023
03 May 2023
02 May 2023
How to install Google Chrome browser on Ubuntu 22.04?
https://linuxhint.com/install-google-chrome-on-ubuntu-22-04/
$ sudo apt update
$ sudo apt install wget
$ wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
$ sudo dpkg -i google-chrome-stable_current_amd64.deb
To run Google Chrome,
$ google-chrome
30 April 2023
How to install supertab plug-in for vim?
https://github.com/ervandew/supertab
Use vim 8+ plugins:
$ mkdir -p ~/.vim/pack/plugins/start $ git clone --depth=1 https://github.com/ervandew/supertab.git ~/.vim/pack/plugins/start/supertab
How to install jedi-vim for Python automatic code completion?
Step 1. Install Pathogen vim plug-in manager
https://github.com/tpope/vim-pathogen
Installation
Install to ~/.vim/autoload/pathogen.vim
.
Or copy and paste the following into your terminal/shell:
mkdir -p ~/.vim/autoload ~/.vim/bundle && \
curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
(If you're using Windows, change all occurrences of ~/.vim
to ~\vimfiles
.)
Runtime Path Manipulation
Add this to your vimrc:
execute pathogen#infect()
If you're brand new to Vim and lacking a vimrc, vim ~/.vimrc
and paste
in the following super-minimal example:
execute pathogen#infect()
syntax on
filetype plugin indent on
Now any plugins you wish to install can be extracted to a subdirectory
under ~/.vim/bundle
, and they will be added to the 'runtimepath'
.
Observe:
cd ~/.vim/bundle && \
git clone https://github.com/tpope/vim-sensible.git
Now sensible.vim is installed.
Step 2. Install jedi-vim plug-in
Installation
Requirements
You need a VIM version that was compiled with Python 3 or later
(+python3
). You can check this from within VIM using
:python3 import sys; print(sys.version)
.
Manual installation
You might want to use pathogen to install jedi-vim.
(The first thing you need after that is an up-to-date version of Jedi. Install
git submodule update --init --recursive
in your jedi-vim repository.)
Example installation command using Pathogen:
git clone --recursive https://github.com/davidhalter/jedi-vim.git ~/.vim/bundle/jedi-vim
23 April 2023
22 April 2023
How to change any version of python as default at any time? (Do NOT do it, otherwise you will not be able to open terminal))
$ sudo update-alternatives --config python3
https://shermanit.blogspot.com/2023/03/how-to-install-python-pip-and-venv-on.html
Python 3.11 Released! How to Install in Ubuntu 22.04 | 20.04 | 22.10
19 April 2023
04 April 2023
Can not connect sftp - "Warning: Permanently added to the list of known hosts"
Create a ~/.ssh/config
file and insert the line:
UserKnownHostsFile ~/.ssh/known_hosts
You will then see the message the next time you access Github (or any other sftp server), but
after that you'll not see it anymore because the host is added to the known_hosts
file. This fixes the issue, rather than just hiding the log message.
02 April 2023
Using Python, how can I access a shared folder on windows network?
Use forward slashes to specify the UNC Path:
open('//HOST/share/path/to/file')
(if your Python client code is also running under Windows)
How to resolve merge conflicts in Git
https://stackoverflow.com/questions/161813/how-do-i-resolve-merge-conflicts-in-a-git-repository
Try:
git mergetool
It opens a GUI that steps you through each conflict, and you get to choose how to merge. Sometimes it requires a bit of hand editing afterwards, but usually it's enough by itself. It is much better than doing the whole thing by hand certainly.
As per Josh Glover's comment:
[This command] doesn't necessarily open a GUI unless you install one. Running
git mergetool
for me resulted invimdiff
being used. You can install one of the following tools to use it instead:meld
,opendiff
,kdiff3
,tkdiff
,xxdiff
,tortoisemerge
,gvimdiff
,diffuse
,ecmerge
,p4merge
,araxis
,vimdiff
,emerge
.
Below is a sample procedure using vimdiff
to resolve merge conflicts, based on this link.
Run the following commands in your terminal
git config merge.tool vimdiff git config merge.conflictstyle diff3 git config mergetool.prompt false
This will set
vimdiff
as the default merge tool.Run the following command in your terminal
git mergetool
You will see a
vimdiff
display in the following format:╔═══════╦══════╦════════╗ ║ ║ ║ ║ ║ LOCAL ║ BASE ║ REMOTE ║ ║ ║ ║ ║ ╠═══════╩══════╩════════╣ ║ ║ ║ MERGED ║ ║ ║ ╚═══════════════════════╝
These 4 views are
- LOCAL: this is the file from the current branch
- BASE: the common ancestor, how this file looked before both changes
- REMOTE: the file you are merging into your branch
- MERGED: the merge result; this is what gets saved in the merge commit and used in the future
You can navigate among these views using ctrl+w. You can directly reach the MERGED view using ctrl+w followed by j.
You can edit the MERGED view like this:
If you want to get changes from REMOTE
:diffg RE
If you want to get changes from BASE
:diffg BA
If you want to get changes from LOCAL
:diffg LO
Save, Exit, Commit, and Clean up
:wqa
save and exit from vigit commit -m "message"
git clean
Remove extra files (e.g.*.orig
). Warning: It will remove all untracked files, if you won't pass any arguments.
30 March 2023
29 March 2023
28 March 2023
How to Use ChatGPT 4 For Free
23 March 2023
How to install Python, pip, and venv on Ubuntu 22.04?
Method 1. Simpler Method
$ sudo apt update
19 March 2023
How to sort a 2 dimensional list by 2 or more keys in different orders in Python?
Operator Module Functions
The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter, attrgetter, and starting in Python 2.6 a methodcaller function.
Using those functions, the above examples become simpler and faster.
>>> from operator import itemgetter, attrgetter, methodcaller >>> sorted(student_tuples, key=itemgetter(2)) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] >>> sorted(student_objects, key=attrgetter('age')) [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:
>>> sorted(student_tuples, key=itemgetter(1,2)) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)] >>> sorted(student_objects, key=attrgetter('grade', 'age')) [('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
The third function from the operator module, methodcaller is used in the following example in which the weighted grade of each student is shown before sorting on it:
>>> [(student.name, student.weighted_grade()) for student in student_objects] [('john', 0.13333333333333333), ('jane', 0.08333333333333333), ('dave', 0.1)] >>> sorted(student_objects, key=methodcaller('weighted_grade')) [('jane', 'B', 12), ('dave', 'B', 10), ('john', 'A', 15)]
Ascending and Descending
Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is using to flag descending sorts. For example, to get the student data in reverse age order:
>>> sorted(student_tuples, key=itemgetter(2), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] >>> sorted(student_objects, key=attrgetter('age'), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
Sort Stability and Complex Sorts
Starting with Python 2.2, sorts are guaranteed to be stable. That means that when multiple records have the same key, their original order is preserved.
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)] >>> sorted(data, key=itemgetter(0)) [('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
Notice how the two records for 'blue' retain their original order so that ('blue', 1) is guaranteed to precede ('blue', 2).
This wonderful property lets you build complex sorts in a series of sorting steps. For example, to sort the student data by descending grade and then ascending age, do the age sort first and then sort again using grade:
>>> s = sorted(student_objects, key=attrgetter('age')) # sort on secondary key >>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
The Timsort algorithm used in Python does multiple sorts efficiently because it can take advantage of any ordering already present in a dataset.
18 March 2023
17 March 2023
15 March 2023
"+y, "+p do not work in vim
14 March 2023
How to install Chinese input on Ubuntu?
- Open Settings, go to
Region & Language
->Manage Installed Languages
->Install / Remove languages
. - Select
Chinese (Simplified)
. Make sureKeyboard Input method system
hasIbus
selected. Apply. - Reboot
- Log back in, reopen Settings, go to
Keyboard
. - Click on the "+" sign under
Input sources
. - Select
Chinese (China)
and thenChinese (Intelligent Pinyin)
.
In newer version of Ubuntu, I seem to have to install ibus-pinyin
$ sudo apt-get install ibus-pinyin
$ ibus restart
11 March 2023
How to generate the RealTimeSync command line?
2. Then, next to the selected folder on the left side, there is a "green plus."
3. Click the "green plus" and it will add another line for an additional folder pair to sync in addition to the first one you selected.
4. Continue hitting the "green plus" until you've listed all the folders you want to sync between the two locations.
5. Run the FFS Compare and Synchronize buttons.
6. After completed, click on the File menu. Select "Save as batch job...".
7. Save the batch job file (you can rename it, but in the below example, I'm just going to use the automatic name FFS provides) to a convenient location - it doesn't matter where - Desktop or Root C:\ are good recommendations. I suggest using the normal batch job file name (BatchRun.ffs_batch). Then close FFS.
8. Open RealTimeSync (RTS).
9. In the command line in RTS, first enter the folder path to the FFS .EXE file in quotes. E.g., "C:\Program Files\FreeFileSync\FreeFileSync.exe"
10. After entering the FFS .EXE location in quotes, enter a Space.
11. After the Space in the command line field, in quotes, enter the direct path to the batch job that was saved from FFS. E.g., "C:\BatchRun.ffs_batch"
12. In my example, the full RTS command line would look like this: "C:\Program Files\FreeFileSync\FreeFileSync.exe" "C:\BatchRun.ffs_batch"
13. Then run RTS, and it should start automatically monitoring all of the folder pairs initially selected in FFS (one or more) that created the batch job file. You can always go back to FFS to add/remove any folders selected, then repeat Steps 6 & 7 above. If you never changed the name of the FFS batch job file, then no command line updates will be required in RTS. RTS will automatically start using the same/updated batch file with any FFS sync changes made to it.
14. Profit!
Note 1: Once you create a batch job file from FFS, it's strongly suggested that the file name is never changed, and that it is continuously updated (overwritten) from FFS. I.e., if you have RTS set up now, don't change the name of the batch job file, or move it to a different computer location.
Note 2: This should go without saying, but also make sure all of the folders being monitored for changes in RTS have been listed. In RTS, under the "Folders to watch:" section, make sure all the same folders being monitored match the same ones selected in FFS when the batch job file was created and/or latest overwritten.
Note 3: You can't enter multiple batch job files in the RTS command line. So, creating the singular batch job file and making updates to it, then overwriting the same old batch job file each time a change to the folders in FFS is made, is (probably) the best way to continuously auto-sync multiple folders with RTS.
All of this is working for me (as of when I'm posting this) - I monitored RTS multiple times and for a while, and it does work, following the above steps! I really hope this helps! Good luck!
K
08 March 2023
How to install .deb files on Ubuntu?
https://linuxconfig.org/install-deb-file-on-ubuntu-22-04-jammy-jellyfish-linux
$ sudo dpkg -i example.deb
If the package requires dependencies that aren’t already on your system, you will see
this error in the terminal:
dpkg: error processing package
Don’t fret, because we can install the required dependencies with a single command,
assuming that they are available in Ubuntu’s package repository. Just run this command
to install the dependencies:
$ sudo apt install -f
06 March 2023
23 February 2023
35 Best Free Open Source Software For Windows11
https://beebom.com/best-open-source-apps-software-windows-11/
1. VLC - media player
2. ShareX - take screenshots, record screen, create GIF's
3. OBS Studio - professional-grade software used by streamers and
broadcasters. Live streaming directly on YouTube, Facebook, Twitter. Record
screen
4. Rufus - create a bootable usb, bypass many of system requirements of
Windows 11. Define partition scheme, directly pull Windows 11 from
Microsoft's website, select file system. Perform a clean install of Windows
11.
5. Lively Wallpaper
6. Rise Media Player
7. Cider - alternative to Apple Music
8. KDE Connect - Alternative to Phone Link. Enables deeper communication
between smart phone and PC. Effortlessly share files and links between the
two devices. Get phone notifications on your PC. Remotely control music on
your PC using your phone
9. GIMP - free alternative to Adobe Photoshop
10. Audacity - audo editing and manipulation.
11. Shotcut - free alternative to Adobe Premiere Pro. Video editing. Other
than Shotcut, you can also try Kdenlive and OpenShot.
12. 7-Zip
13. LibreOfice - free alternative to Microsoft Office
14. QuickLook - quickly preview files and folders.
15. Files - an alternative to File Explorer
16. ScreenToGif - a full-blown GIF editor.
17. Brave browser
18. Tor browser - use it if you want complete anonymity online
19. Bitwarden - the best password manager for Windows 11
20. Blender - free alternative to Autodesk Maya and Cinema 4D. A
professional-grade 3D creation software, which has been used to create many
popular films.
21. Okular - free alternative to paid PDF editors. It was developed for Linux
systems mainly.
22. Krita - free alternative to Adobe Illustrator and Adobe Animate
23. HandBrake - convert videos to other formats.
24. Psiphon - circumvent restrictions on Internet. You can think of it as a
VPN, but it is more than that. it uses a combination of VPN, SSH, and web
proxy to establish a secure connection amid Internet censorship.
25. FreeCAD - free alternative to AutoCAD
26. VirtualBox - open source alternative to VMware. Create a virtual machine
on Windows 11, or run Android, Linux, and other operating systems on a VM.
27. VeraCrypt - Disk encryption. It allows you to password-protect your
encrypted volumes on Windows.
28. Joplin - free alternative to OneNote and Evernote. To take notes, and
create your to-do list as well.
29. BleachBit - a light-weight disk cleaner.
30. Clonezilla - free alternative to Macrium Reflect. To create a full backup
of your system. It can fully clone the system images and disks. No matter if
you have a disk with different file systems, Clonezilla can mirror the disk
effortlessly.
31. Mailspring - an alternative to Thunderbird.
32. Transmission - a free and open-source torrent client for Windows 11. It is
very lightweight and does not consume system resources needlessly.
33. Notepad++
34. Microsoft PowerToys - You can enable PowerToys Run to get a Spotlight-like
Search tool on Windows 11. Quickly extract text from images on Windows 11, no
need to download a separate OCR software.
35. ExplorerPatcher - can restore most Windows 10 functionalities on Windows
11.
06 February 2023
Python Automation Scripts You Should Know
04 February 2023
How to rename multiple file names all at once?
https://ostechnix.com/how-to-rename-multiple-files-at-once-in-linux/
Method 4 - Rename multiple files at once using vimv
As the name says, Vimv is a command line utility to bulk rename files using Vim editor. You can, of course, change the editor by changing the value of $EDITOR
environment variable.
To install Vimv, git clone the repository:
$ git clone https://github.com/thameera/vimv.git
Copy the vimv binary to your $PATH
, for example /usr/local/bin/
.
$ sudo cp vimv/vimv /usr/local/bin/
Finally, make it executable:
$ sudo chmod +x /usr/local/bin/vimv
Now go to the directory and run the following command to edit the filenames.
$ vimv
You will see the filenames in Vi editor. Press i to switch to interactive mode and edit the filenames as the way you edit text in Vi editor. Once done, press ESC
key and type :wq
to save and exit.
The files inside the directory should be renamed now.
Method 3 - Rename files using renameutils
The renameutils is a set of programs that is designed to batch renaming files and directories faster and easier.
Renameutils consists of the following five programs:
- qmv (quick move),
- qcp (quick copy),
- imv (interactive move),
- icp (interactive copy),
- deurlname (delete URL).
Install renameutils in Linux
Renameutils is available in the default repositories of most Linux distributions. To install it on Arch-based systems, enable the community repository and run:
$ sudo pacman -Syu renameutils
On Debian-based systems:
$ sudo apt install renameutils
Now, let us see some examples.
1. qmv
The qmv program will open the filenames in a directory in your default text editor and allows you to edit them.
I have the following three files in a directory named 'ostechnix'.
$ ls ostechnix/ abcd1.txt abcd2.txt abcd3.txt
To rename the filenames in the 'ostechnix' directory, simply do:
$ qmv ostechnix/
Now, change the filenames as you wish. You will see the live preview as you edit the filenames.
Alternatively, you can cd into the directory and simply run 'qmv'
.
Once you opened the files, you will see the two columns as shown in the following screenshot.
The left column side displays the source filenames and the right column displays the destination names (the output filenames that you will get after editing).
Now, rename all the output names on the right side as you wish.
After renaming filenames, save and quit the file.
Finally, you will see the following output:
Plan is valid. abcd1.txt -> xyzd1.txt abcd2.txt -> xyzd2.txt abcd3.txt -> xyzd3.txt Regular rename abcd1.txt -> xyzd1.txt abcd2.txt -> xyzd2.txt abcd3.txt -> xyzd3.txt
Now, check if the changes have actually been made using 'ls'
command:
$ ls ostechnix/ xyzd1.txt xyzd2.txt xyzd3.txt
See? All files are renamed. Not just files, the renameutils will also rename the directory names as well.
Here is a quick video demo of qmv program:
If you don't want to edit the filenames in dual-column format, use the following command to display the destination file column only.
$ qmv -f do ostechnix/
Where, '-f'
refers the format
and 'do'
refers destination-only
.
Now, you will see only the destination column. That's the column we make the changes.
Once done, save and close the file.
For more details, refer man pages.
$ man qmv