Git, GitHub and Vscode

2 software and 1 website :

  • Create an account of github.com in my case, it will be pierre.jean@umontpellier.com
  • Download and install Git from https://git-scm.com/downloads
  • Download Zip version of VScode https://code.visualstudio.com/download according your internal processor (Windows usually x64, Mac usually universal) and unzip the file somewhere you usually install program (on the desktop in my case)

If you want to train more about Git you can use this page for beginner to advanced user : https://pierrejean.wp.imt.fr/2023/09/08/oh-my-git/

F&Q

  • With Git, there are several ways to do the similar thing…
  • The default branch could be main but it was common to have main.
  • Github is not the only website for Git: Gitlab, Sourcesup (Renater), Bitbucket, Amazon, etc. but Github is the most famous
  • VScode is different from Visual Studio from Microsoft

Very simple configuration on Github Website

On the GitHub account opens by click on the top right circle icon, then choose « Settings »

Then at the bottom, choose « Developper settings » at the bottom end :

Then Personal access tokens > Tokens (classic) or just follow https://github.com/settings/tokens , then « Generate a personal access token » :

Then you can provide a name of this token, give an expiration date (not perpetual), give right at least on repo rights and press the bottom button « Generate token » :

Then you have to copy the generated token, please be sure to copy the token because there is no way to give you back this one. If you lost it, you have just to create a new one.

You have to preserve somewhere those three informations from Github:

  • The email account used to create the github account
  • The account name used, you can find by clicking again of the top right small circle
  • The tokens key just generated

Github website provides the basic start we need on the first page you see after login creation or you can return with the Github icon or the « Dashboard » link :

At first, create a new private repository to practice call hello1 :

Then you have the quick look on commands that we will learn bellow:

Also, you need to keep the URL address like just the username of your account and the name of the repository for later as :

https://github.com/pierre-jean-dhm/hello1.git

If you need to change public/private settings or delete the repository, just click « Settings » and top bottom, you will find « Change repository visibility » and « Delete this repository« .


VScode and your folder

We will imagine, we will work into a folder on the desktop call Hello1 that could be empty of not. So create this Hello1 folder where we will work and you can see the full path into the Windows explorer address bar : C:\Users\pierre.jean\Desktop\Hello1\

Open the VScode folder and click on the code program to start it, choose « Open Folder… » and choose C:\Users\pierre.jean\Desktop\Hello1\

You can confirm, you trust the folder content (empty in my demonstration) :

Then, you can close the « welcome tab », open the terminal (Menu View > Terminal) and switch to « Source control » button on the left vertical bar.

So now into this terminal, just enter the following command but replace with the email address from the Github website :

git config user.email "pierre.jean@umontpellier.com"

You should have an error because the current folder is not setup for Git, so at first execute this command :

git init

VScode button « Initialize Repository » could also execute the same command just by pressing but there are so many terminal commands to learn instead…

You can see into the folder with « File explorer » (or Finder) there is a hidden file call .git :

Folder .git hidden visible via Menu « Display/Affichage » « Hidden elements/Elements masqués »

So you can call back the previous command (up arrow) to configure the email you preserve from the Github settings :

git config user.email "pierre.jean@umontpellier.com"

And the account name also from the

git config user.name "pierre-jean-dhm"

NOTE :If you want to change it, just call again the same command. And if you want to « un-git » the project, just delete the .git folder.

You can add a very new useful command line (git lg) with this command, so just copy and paste into the terminal and press ENTER:

git config alias.lg "log --oneline --all --decorate --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"

Enter this command to use the main branch name instead of historical master branch name :

git config  init.defaultBranch main

Now, let’s start on a first project’s file.

NOTE: if a command ouput will not fit into the terminal area missing some place, you will see double dots:

So press SPACE key to see one more page until message END is shows then press Q key to quit.

NOTE2: if you close by mistake terminal, just open it again, Menu View >


Let’s start with versions control (Global Information Tracket)

1/ One new file, add and commit

Into the Hello1 folder, create a file equipe1.txt with menu File > New Text file

On the right, begin to enter text to remove the advice text « Select a language… », so enter :

Pierre

Save the file with equipe1.txt name :

Then we need to ask Git to follow this file equipe1.txt, inside the terminal enter :

git add equipe1.txt

We can also just click into the small + symbol to add this file « Stage Changes »:

Then create a first commit of this version of file with :

git commit -a -m "Initial version"

-a : for all file added previously

-m : to provide a message in this example « Initial version »

The « git commit » action is really to say « All those files are at the same point of development »

F&Q

  • Why to use git add : because some files could be into the folder and you do not want to include them into the version control
  • How to add several files and folders : with git add . or git add :/ to add everything into the current folder or everything into where you execute git init.
  • How to undo git add equipe1.txt : with git reset equipe1.txt
  • Why two command to add and commit : Several raisons, but I like to say: when I create a new file for a project, I add it at this moment into GIT with git add then later, I will include this file and more into the commit « package » with git commit.
  • Git and folders: GIT only manage files, if there is an empty folder, GIT will not manage it, so place a README.md file into and git add :/
  • Editor : You can use any editor as Notepad, UltraEdit, Matlab, etc. to create files but some editors will be updated by Git some other not, later it could be complex to close and reopen file each time to avoid troubles.
  • You can use arrow up to find a previous command
  • You can clear the terminal with cls or clear commands

We want to know what append into GIT so the previous command git lg will show us (or the short version git log –oneline –graph –all –decorate) :

We can display the status of our first commit with git log or git lg :

Each element is very important :

  • * : symbol for the active branch actually the main branch is call « main »
  • 727ce9e: short version of ID of the commit number, each commit will have a different version
  • HEAD : the position of the folder content files at present, the most important element
  • -> : very important symbol HEAD state is link to main state of the main branch
  • main : name of the first branch of commits (It could be master also)
  • Initial commit : the message of this version

The git lg command add more information, date of the commit and user name.

3/ Second version of our file

Edit the equipe1.txt file with this additional content and save it (CTRL+S):

Pierre
Gérard

Then commit this new version with the classical :

git commit -a -m "Team of 2 players"

Display the log via git lg (or git log –oneline –graph –all –decorate) :

We have 2 commits so we have two versions of our group of one file (equipe1.txt), the first version 727ce9e and the second is 939516a.

4/ Time machine

Suppose we can to go back to the first or previous version, you can either:

  • go to the version 727ce9e : with git checkout 727ce9e
  • go to the actual position (HEAD) minus one with : git checkout HEAD^
  • go to the actual position (HEAD) minus a number (here one) with : git checkout HEAD~1 or git checkout HEAD^1
git checkout HEAD^

We see the equipe1.txt file content change to display the previous content. So we move back in time, the content of our file change to display the previous version :

We return to the last commit with git checkout main or git checkout main.

F&Q

  • Version number of position: you should avoid to use version number all the time. There are HEAD~number, and there are branch name and tag and so much
  • How to go back into the future: git checkout main or git switch main
  • Detach HEAD, a HEAD is normally supposed to point on the last element of a branch, without a branch name HEAD is just a flag on the history of commits version.
  • Why you should not do git checkout baf9c8d : the situation is called a detached HEAD, in fact the version control of GIT will keep main branch pointing on the baf9c8d version. So if you created a new commit version you will have the following situation :
* e04c5e7 - (HEAD) version detach of branch (3 seconds ago) 
* 939516a - (main) Team of 2 players (63 minutes ago)
* 727ce9e - First commit (2 hours ago)

So the HEAD moves with the new version, but the branch name stayed on 939516a.

5/ VScode

You can use VScode to avoid most of the command, for example add a new file equipe2.txt into the folder Hello1. We don’t need to add a new file and a new commit, just a way to understand where are the buttons:

But VScode allow only to do git checkout with branch so …

6/ Branches

To avoid mix into the development, you have to think that your work will be share with someone. You should have 3 branches, your main/master branch, a develop/temporary/feature/test branch and the remote main/master branch.

First of all, where are in this situation :

* 939516a - (HEAD -> main) Team of 2 players (63 minutes ago) 
* 727ce9e - First commit (2 hours ago)

One file equipe1.txt with the following content :

Pierre
Gérard

We want to simulate a different way to develop our file. So we go back to the initial commit and we create a develop branch and try to work on :

git checkout HEAD~1
git branch develop

But we have to display the situation with git lg (of git log –oneline –graph –all –decorate) :

* 939516a - (main) Team of 2 players (2 hours ago) 
* 727ce9e - (HEAD, develop) First commit (4 hours ago)

There is a problem, HEAD is not linked to develop, HEAD is linked to 727ce9e and develop is linked alos on 58d31e1.

git checkout develop

Then git lg display :

* 939516a - (main) Team of 2 players (2 hours ago) 
* 727ce9e - (HEAD -> develop) First commit (4 hours ago)

Alternative, to avoid the detach HEAD, you could just, but don’t now :

git switch -c develop

To simulate this situation, we want to delete develop branch to recreate, so we have this situation :

* 939516a - (main) Team of 2 players (2 hours ago) 
* 727ce9e - (HEAD -> develop) First commit (4 hours ago)

Detach the HEAD with git checkout 58d31e1 :

* 939516a - (main) Team of 2 players (2 hours ago) 
* 727ce9e - (HEAD, develop) First commit (4 hours ago)

Then delete the develop branch with :

git branch -d develop

Then we can create the new branch with :

git switch -c develop

Now we will update the file to create a new branch, edit equipe1.txt file as :

EQUIPE
##########
Pierre

Then commit this version and display situation ( -am is equivalent as -a -m) :

git commit -am "Nice version" 

Then display:

* 8c63cc4 - (HEAD -> develop) Nice version (22 seconds ago) 
| * 939516a - (main) Team of 2 players (31 minutes ago)
|/
* 727ce9e - Initial version (53 minutes ago)

Two branches : main to the main software development and develop to try some stuffs

VScode now allows to choose to checkout on a branch easily :

7/ Merge

Suppose we want to simulate some one who works on the main branch adding person to the list :

git checkout main

Then edit the file and save it with a third person as :

Pierre
Gérard
Killian

Then commit this new version with Vscode for example (note the dialog to ask to include -a or always) :

Or from the command line with :

git commit -am "Team of 3"

This is the situation :

* b123fa0 - (HEAD -> main) Team of 3 (3 seconds ago) 
* 939516a - Team of 2 players (39 minutes ago)
| * 8c63cc4 - (develop) Nice version (9 minutes ago)
|/
* 727ce9e - Initial version (62 minutes ago) <pierre-jean-dhm>

Then now return on the develop branch with :

git checkout develop

We want to merge the nice version of develop branch into the main branch with :

Or the command

git merge main

It could be possible the fusion is OK because there is no conflict really with this final result :

*  8c63cc4 - (HEAD -> develop) Merge branch 'main' into develop (71 minutes ago)
|\
| * b123fa0- (main) Team of 3 (74 minutes ago)
| * 939516a - Team of 2 players (4 hours ago)
* | 8c63cc4 - Nice version (78 minutes ago)
|/
* 727ce9e - First commit (5 hours ago)

Often, you will have a conflict with this interface :

Ok a bizarre and historical way to display content is sotred into equipe1.txt file, top a part from develop branch and bottom the part from main branch. You can have common part before and later the series of <<<<< and >>>>>>. But swith to « Merge editor with the nice button » :

Ok on the top left the part from main branch call incoming, on the top right, the part from the HEAD (current) develop branch and bellow, the final combinaison of the merge of content. Of course you can edit this final result content as you wish and then press « Complete Merge » to validate the merge.

BUT, is onlyj ust like we create a new content into the equipe1.txt file, we need to commit this new situation with:

git commit -am "Merge branch 'main' into develop"

What is our situation :

*   36bd9a0 - (HEAD -> develop) Merge branch 'main' into develop (81 seconds ago)
|\
| * b123fa0 - (main) Team of 3 (31 minutes ago)
| * 939516a - Team of 2 players (71 minutes ago)
* | 8c63cc4 - Nice version (40 minutes ago)
|/
* 727ce9e - Initial version (2 hours ago)

Next step a special case of merge

8/ Merge fast-forward

We are in a situation of the develop branch is one step forward the main branch. We can also now merge the develop branch into the main branch to simulate the preparation to share the main branch with other paople.

git checkout main
git merge develop

In this specific situation, Git succed to combine the content from develop branch equipe1.txt into main branch equipe1.txt.

To display difference, you can enter use this command (and yes we use ~1 as HEAD~1) :

git difftool -y -x sdiff develop main~1

Side by side :

EQUIPE                                           EQUIPE
########## ##########
Pierre / Pierre
Gérard <
Killian <

In this particular case, we do not have to commit because the merge succed without conflict.

So suppose we want to cancel this situation and just move the main branch label on the previsous commit identified by b123fa0 – Team of 3, we can have two solutions :

  • First option just move the branch on a spécific commit with :
 git branch -f main b123fa0
  • Second option move the HEAD with the main branch and return the HEAD on the develop branch:
git checkout main
git reset --hard b123fa0
git chechout develop

This initial situation at the end will be :

*   36bd9a0 - (HEAD -> develop) Merge branch 'main' into develop (40 minutes ago)
|\
| * b123fa0 - (main) Team of 3 (70 minutes ago)
| * 939516a - Team of 2 players (2 hours ago)
* | 8c63cc4 - Nice version (79 minutes ago)
|/
* 727ce9e - Initial version (2 hours ago)

This a way to cancel movement of the branch, but be aware that the main branch will be syncrhonise with a remote repository call remote origin/main.

Remote

Ok now everything we done is only local. We need to link to Github, so we need information keep at the begining as the git token (symbolise by ghp_XXXXXXXXX later) and the url :

https://github.com/pierre-jean-dhm/hello1.git

We need to create this termnal command with you information :

git remote add origin https://ghp_XXXXXXXXX@github.com/pierre-jean-dhm/hello1.git

In fac this will create a short name « origin » to your hello1.git repository. You can choose something other than origin as github but origin is really commun.

or we can use the Vscode menu insert at first the link https://ghp_XXXXXXXXX@github.com/pierre-jean-dhm/hello1.git then the name of the link origin as usual:

Please, do not accept Vscode to periodicaly fetch content, we do not need it at first.

We forget something, we want to push main branch and we are at present on develop branch. Think about it all the time please!

So option 1 just with this command line :

git push -u origin main

Or option 2, change to main branch then push :

or the command line :

git checkout main

Then git push to the remote repository with branch publish also:

The purpose at this moment is to have always main branch update and link to the remote branch.

You can go online to reresh the page and find everything:

  • Top left: the main branch
  • Top right: 3 commits from your computer
  • Center: our unique equipe1.txt file

You can open the file to see the last content and you can list all the commit to find history of commit or you can open the equipe1.txt file to see history also.

You can see the commit comments and unique number but only the main branch is uploaded.

In local you can see now there is a new remote origin/main branch with git lg command (or the short version git log –oneline –graph –all –decorate) :

* 36bd9a0 - (develop) Merge branch 'main' into develop (23 hours ago)
|\
| * b123fa0 - (HEAD -> main, origin/main) Team of 3 (23 hours ago)
| * 939516a - Team of 2 players (24 hours ago)
* | 8c63cc4 - Nice version (23 hours ago)
|/
* 727ce9e - Initial version (24 hours ago)

Now it is time to simulate a conflict with an external user.

Remote conflict

We will simulate a conflict between the origin/main branch and your local branch, on the main repository file you can click on the equipe1.txt file :

Then on the right, the pen button or the short menu then « Edit online » let you edit the file :

Change the content Equipe as bellow:

TEAM
##########
Pierre
Gérard
Killian

Then you have to « Commit » this new version with the top right button, this will open a dialog box to enter the messsage :

At this point, the online origin/main is updated but NOT your local version. There are two solutions from here BUT before please backup (see below) :

  • Download the remote origin/main branch to look what it could happen with : git fetch
  • Download the remote origin/main branch to stray away merge to your HEAD: git pull

How to backup this situation for training purpose

Just duplicate (copy/paste) the Hello1 folder somewhere to preserve the local situation. Git stores everything into the .git folder inside Hello1 folder, so backup this folder is equal to backup the local git folder. We can even imagine to delete the Github respository and recreate it (exception the last operation to edit online equipe1.txt will not be backup, because it still only exist online)

We can say « git fetch » and « git merge » is equivalent as « git pull ». Git fetch is the light version, you can download from Github but your ane not sure to use it. Git pull is you will download from Github but you use it at present.

This is the situation with git lg before git fetch:

*   36bd9a0 - (develop) Merge branch 'main' into develop
|\
| * b123fa0 - (HEAD -> main, origin/main) Team of 3
| * 939516a - Team of 2 players
* | 8c63cc4 - Nice version
|/
* 727ce9e - Initial version

after git fetch as a command on via menu

And again git lg to display :

* 327e940 - (origin/main) Add Team title 
| * 36bd9a0 - (develop) Merge branch 'main' into develop
| |\
| |/
|/|
* | b123fa0 - (HEAD -> main) Team of 3
* | 939516a - Team of 2 players
| * 8c63cc4 - Nice version
|/
* 727ce9e - Initial version

So we have a potentiel conflict display by Vscode betwen the main branch and the remote origin/main branch :

NOTE A optionnal compare with develop : We can also checkout the develop branch to try to merge with the origin/main branch to try to see what inspact it will be on the develop branch. Just try to merge, open the « Resolve into the Merge Editor » then to cancel enter command git merge –abort. Byt the way, how I know the command, just git status to display information. Just think to return on the main branch : git checkout main.

So option 1 : git merge will update directly the equipe1.txt content and the final situation will be main branch is identifical at origin/main branch :

* 327e940 - (HEAD -> main, origin/main) Add Team title 
| * 36bd9a0 - (develop) Merge branch 'main' into develop
| |\
| |/
|/|
* | b123fa0 - Team of 3
* | 939516a - Team of 2 players
| * 8c63cc4 - Nice version
|/
* 727ce9e - Initial version

And we also know a futur conflict will be with develop branch, but we will see that later.


Now go back to test option 2, close VScode, rename Hello1 folder into Hello1-Option1, copy the backup Hello1 into Hello1, restart Vscode, menu View Terminal and button on the top left bar « Source control » :

You can also open the equipe1.txt file (Menu File > Open File … ) Then git lg command :

*   36bd9a0 (develop) Merge branch 'main' into develop
|\
| * b123fa0 (HEAD -> main, origin/main) Team of 3
| * 939516a Team of 2 players
* | 8c63cc4 Nice version
|/
* 727ce9e Initial version

Ok now we wand to download the remote origin/main branch to stray away merge to your HEAD. We know online the last version is the best, we just want this version to be update with the main branch so go on.

At this point, because Git find a way to avoid conflict between the online version and the actual versio, juste equipe1.txt will work perfect and merge. We see on the screen, on the right, lines in yellow are copy to the left so everything is fine :

But suppose we merge with develop that for sure will create a conflict try with git merge develop then use the menu to create your combinaison of setting (Use CTRL+Z to cancel o Menu Edit > Undo)

I choose to create this content with « accept incomming » and edit the last line with ######:

EQUIPE
##########
Pierre
Gérard
Killian
########

Then press « Complete Merge » to finalise the conflict from main and develop, then create the new commit 36bd9a0 with this result from git lg output :

*   eefe254 - (HEAD -> main) Merge branch 'develop' (4 seconds ago) <pierre-jean-dhm>
|\
| * 36bd9a0 - (develop) Merge branch 'main' into develop (29 hours ago) <pierre-jean-dhm>
| |\
| * | 8c63cc4 - Nice version (30 hours ago) <pierre-jean-dhm>
* | | 327e940 - (origin/main) Add Team title (5 hours ago) <pierre-jean-dhm>
| |/
|/|
* | b123fa0 - Team of 3 (29 hours ago) <pierre-jean-dhm>
* | 939516a - Team of 2 players (30 hours ago) <pierre-jean-dhm>
|/
* 727ce9e - Initial version (30 hours ago) <pierre-jean-dhm>

We need to push to update origin/main as we always say to check main equal to origin/main

Ok now we have this situation with git lg :

*   eefe254 - (HEAD -> main, origin/main) Merge branch 'develop' 
|\
| * 36bd9a0 - (develop) Merge branch 'main' into develop
| |\
| * | 8c63cc4 - Nice version
* | | 327e940 - Add Team title
| |/
|/|
* | b123fa0 - Team of 3
* | 939516a - Team of 2 players
|/
* 727ce9e - Initial version

At this point, about develop branch, we could create a new develop branch for a new feature.

  • Delete develop branch and recreate it later
  • Merge develop branch with main branch to start later with this branch
  • Move the flag develop from 36bd9a0 to eefe254 and tag the commit with git tag develop-pretty-title
  • Rename develop branch as develop-pretty-title branch to keep this feature in mind

I recommand to keep the branch attach so rename a develop branch into an explicit name to keep in mind is the best. We will create later a develop-new-feature branch as needed. We don’t push this kind of branch on GitHub is just a way to work on side features instead have too much change on the main branch.

Simulate an other user

Create a new terminal independant of the first one, press ALT key and click to open a parallel terminal :

Enter the following command to go top folder, create a new folder, go insite this folder and then create a git account :

cd    ..
mkdir Hello1-other-user
cd Hello1-other-user
git init

We will create another account just my case swap family name and first name :

git config user.email "jean.pierre@umontpellier.fr"
git config user.name "JEAN Pierre"

Now we will simulate a new challenger on this project who want to clone from the remote GitHub folder the whole project with the same token:

git remote add origin https://ghp_XXXXXX@github.com/pierre-jean-dhm/hello1.git

Then download the whole main branch from origin :

git pull origin main

We are suppose now to image a large contribution from this new user, open the file equipe1.txt in parallel with this combinaison :

Open the menu File > Open files … then move to one up folder, then choose the other sub folder called Hello1-other-user then open equipe1.txt file :

Then you can displays both file, right click on the tab to choose « Split Right » menu

And after close this tab because Split Right duplicate

Now we can display at the left equipe1.txt file from Hello1 and its console and at the right equipe1.txt file from Hello1-other-user and its console :

This exercice suppose to work on this specific situation:

  • The right user will create a new developer-complex-feature branch and create one commit on the files, for example add email for the first person
  • But the left user will works on the main branch and add two more commits with more peoples on the list
  • The right user knows there are update but he needs more time to work on his file but he can wait to receive update

With the right user

git branch developer-complex-feature
git checkout developer-complex-feature
# edit the file adding an email
git commit -am "Update email first person"

With the left user

# edit the file adding one more people
git commit -am "Teams of 4 peoples"
# edit the file adding one more people
git commit -am "Teams of 5 peoples"
git push origin main

With the right user need to receive update

git pull origin main
git checkout main
git merge origin/main

Now we have this situation :

* 629b770 - (HEAD -> main, origin/main) Teams of 5 peoples (4 minutes ago)
| * 19eb774 - (developer-complex-feature) Update email first person (7 minutes ago)
|/
* eefe254 - Merge branch 'develop' (3 days ago)
|\
| * 36bd9a0 - Merge branch 'main' into develop (4 days ago)
| |\
| * | 8c63cc4 - Nice version (4 days ago)

So developer-complex-feature is link to eefe254 commit and it is « too early » we need more time, so we can move the branch (call rebase) from eefe254 to a more recent commit into the timeline, so :

git checkout developer-complex-feature
git rebase main

So the new situation will be :

* d5338af - (HEAD -> developer-complex-feature) Update email first person (5 seconds ago) 
* 629b770 - (origin/main, main) Teams of 5 peoples (5 minutes ago)
* eefe254 - Merge branch 'develop' (3 days ago)
|\
| * 36bd9a0 - Merge branch 'main' into develop (4 days ago)
| |\
| * | 8c63cc4 - Nice version (4 days ago)

And right user can work on more updated content from equipe1.txt file and the content is :

EQUIPE
##########
Pierre p.j@mine_ales.com
Gérard
Killian
Simon
Stéphane
########

A very important information : never rebase a online branches like main branch.

You can simulate more commits for the left user and rebase for the right user until right user finish and push modifications on Github main branch.

At the end, change everything on the developer-new-feature branch, save file and commit the change into a new commit :

git commit -am "Update emails"

We can merge from developer-new-feature branch, we need to move on the main branch and merge and push :

git checkout main
git merge developer-new-feature
git push origin main

You can go online to find the Github commit page and display commit from the right user and commit from the left user :

Ok of course, you can now git pull origin main for the left user and go on simulate conflict and development. We can see also with the classic git lg command :

* 7551fa3 - (HEAD -> main, origin/main) Update emails <JEAN Pierre>
* d5338af - Update email first person <JEAN Pierre>
* 629b770 - Teams of 5 peoples <pierre-jean-dhm>
* eefe254 - Merge branch 'develop' <pierre-jean-dhm>
|\
| * 36bd9a0 - (develop) Merge branch 'main' into develop <pierre-jean-dhm>
| |/
|/|
* | b123fa0 - Team of 3 <pierre-jean-dhm>
* | 939516a - Team of 2 players <pierre-jean-dhm>
|/
* 727ce9e - Initial version (4 days ago) <pierre-jean-dhm>

Additionnals operations

Hide files from Git

Put a word document into the folder, you will see it all the time not « added » (not tracked) by Git :

So you can create a .gitignore file with the following content and save it into the same folder where your execute git init (Hello1 in ours case) :

*.docx
*.pdf
*.xlsx
*.pptx

All files with .docx, .pdf, .xlsx, *.pptx will be ignored by Git. Off couse, you will se that you can tracked (git add) the .gitignore file or you can add .gitignore at the end of your .gitignore file.

Many websites provide sample for .gitignore file: https://github.com/github/gitignore

Move files and git status

Suppose you create a new file equipe2.txt into the folder with the folowing content:

EQUIPE
###########

You can add to git the « untracked/unstaged » file with the git add but you forget. Many time if you need to understand which command will be more usuful just enter git status :

On branch main
Your branch is up to date with 'origin/main'.

Untracked files:
(use "git add <file>..." to include in what will be committed)
equipe2.txt

nothing added to commit but untracked files present (use "git add" to track)

Use git add or the plus button to add the file and enter git status :

On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: equipe2.txt

So to rever the git add command, you will see the command :

git restore --staged equipe2.txt

Now move to develop branch, git add equipe2.txt file and commit

git checkout develop
git add equipe2.txt
git commit -m "Add equipe2 file"

Now suppose you want to cancle last commit has it never exists :

git reset --soft HEAD~1

The git status will display the moment after the git add :

On branch develop
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: equipe2.txt
Publié dans Développement | Laisser un commentaire

Git, Gihub and Github desktop

2 software and 1 website :

  • Create an account of github.com in my case, it will be pierre.jean@umontpellier.com
  • Download and install Git from https://git-scm.com/downloads
  • Download and NOT install Github Desktop for now https://desktop.github.com/

If you want to train of Git you can use this page for beginner to advanced user : https://pierrejean.wp.imt.fr/2023/09/08/oh-my-git/

F&Q

  • With Git, there are several ways to do the similar thing…
  • The default branch could be master or now it is more common to have main as name of the central branch.
  • Github is not the only web site for Git: Gitlab, Sourcesup (Renater), Bitbucket, Amazon, etc but Github is the most famous

Very simple configuration on Github Website

On the Github account opens by click on the top right circle icon, then choose « Settings »

Then at the bottom, choose « Developper settings » at the bottom end :

Then Personal access tokens > Tokens (classic) or just follow https://github.com/settings/tokens , then « Generate a personal access token » :

Then you can provide a name of this token, give an expiration date (not perpetual), give right at least on repo rights and press the bottom button « Generate token » :

Then you have to copy the generated token, please be sure to copy the token because there is no way to give you back this one. If you lost it, you have just to create a new one.

You have to preserve somewhere those three informations from Github:

  • The email account used to create the github account
  • The account name used, you can find by clicking again of the top right small circle
  • The tokens key just generated

Github website provides the basic start we need on the first page you see after login creation or you can return with the Github icon or the « Dashboard » link :

At first, create a new private repository to practice call hello1 :

Then you have the quick look on commands that we will learn bellow:

Also, you need to keep the URL address like just the username of your account and the name of the repository for later as :

https://github.com/pierre-jean-dhm/hello1.git

Git on your computer

Git is an open source software to manage a local version of a hard drive folder with files. Create on your desktop a folder call Projet1 with « File explorer » (Windows) or « Finder » (MacOS). You have to find the path of this folder with « File explorer » is into the top address bar.

C:\Users\pierre.jean\Desktop\Projet1\ in my case (keep into your mind) for the next step :

C:\Users\pierre.jean\Desktop\Projet1\

MacOS users will have to drag and drop the folder to a terminal application to show the path

So open terminal application and enter the following command :

cd "C:\Users\pierre.jean\Desktop\Projet1\"

If the combination of folders named as a path include no spaces you can enter simply :

cd C:\Users\pierre.jean\Desktop\Projet1\

Mac OS user can drag and drop the folder into the terminal to have the path. Windows users can replace into the « file explorer » address bar the content and enter « cmd » and press ENTER to open the terminal into the correct place.

NOTE: cd is fo Change Directory

Configuration of local git settings

So now into this terminal, just enter the following command but replace with the email address from the Github website :

git config user.email "pierre.jean@umontpellier.com"

You should have an error because the current folder is not setup for git so at first execute this command :

git init

You can see into the folder with « File explorer » (or Finder) there is a hidden file call .git :

Folder .git hidden visible via Menu « Display/Affichage » « Hidden elements/Elements masqués »

So you can call back the previous command (up arrow) to configure the email you preserve from the Github settings :

git config user.email "pierre.jean@umontpellier.com"

And the account name also from the

git config user.name "pierre-jean-dhm"

If you want to change it, just call again the same command. And if you want to « un-git » the project, just delete the .git folder.

You can add a very useful command line ( git lg) with this command

git config alias.lg "log --oneline --all --decorate --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%ae>%Creset' --abbrev-commit"

Let’s start with versions control (Global Information Tracket)

1/ One new file, add and commit

Into the Projet1 folder, create a file equipe1.txt with notepad or any text editor to manage information about a team with a line of information as below:

Pierre

Then ask Git to follow this file equipe1.txt, inside :

git add equipe1.txt

Then create a first commit of this version of file with :

git commit -a -m "Initial version"

-a : for all file added previously

-m : to provide a message in this example « Initial version »

The « git commit » action is really to say « All those files are at the same point of developpement »

F&Q

  • Why to use git add : because some files could be into the folder and you do not want to include them into the version control
  • How to add several files and folders : with git add . or git add :/ to add everything into the current folder or everything into where you execute git init.
  • How to undo git add equipe1.txt : with git reset equipe1.txt
  • Why two command to add and commit : Several raisons, but I like to say: when I create a new file for a project, I add it at this moment into GIT with git add then later, I will include this file and more into the commit « package » with git commit.
  • Git and folders: GIT only manage files, if there is an empty folder, GIT will not manage it, so place a README.md file into and git add :/
  • Editor update: some editor will be updated by Git some other not, later it could be complex to close and reopen file each time to avoid troubles.

2/ Check state

We want to know what append into GIT so the previous command git lg will show us (or the short version git log –oneline –graph –all –decorate) :

We can display the status of our first commit with gitlog or git lg :

Initial commit log display short visible version

Each element is very important :

  • * : symbol for the active branch actually the main branch is call « master »
  • 58d31e1 : short version of ID of the commit number, each commit will have a different version
  • HEAD : the position of the folder content files at present, the most important element
  • -> : very important symbol HEAD state is link to master state of the main branch
  • master : name of the first branch of commits (It could be main also)
  • Initial commit : the message of this version

The git lg command add more information, date of the commit and email of the user.

3/ Second version of our file

Edit the equipe1.txt file with this additional content :

Pierre
Gérard

Then commit this new version with the classical :

git commit -a -m "Team of 2 players"

Display the log via gitlog

Git log second commit

We have 2 commits so we have two versions of our group of one file (equipe1.txt), the first version 58d31e1 and the second is baf9c8d.

4/ Time machine

Suppose we can to go back to the first or previous version, you can either:

  • go to the version baf9c8d: with git checkout baf9c8d
  • go to the actual position (HEAD) minus one with : git checkout HEAD^
  • go to the actual position (HEAD) minus a number (here one) with : git checkout HEAD~1 or git checkout HEAD^1

Now reopen the file equipe1.txt to found the previous content. So we move back in time, the content of our file change to rescue the previous version :

Git checkout previous version

We can look the content of the file and find only one line « Pierre » as the content prepare when we create the « Initial commit ».

F&Q

  • Version number of position: you should avoid to use version number all the time. There are HEAD~number, and there are branch name and tag and so much
  • How to go back into the future: git checkout master or git switch master
  • Detach HEAD, a HEAD is normally supposed to point on the last element of a branch, without a branch name HEAD is just a flag on the history of commits version.
  • Why you should not do git checkout baf9c8d : the situation is called a detached HEAD, in fact the version control of GIT will keep master/main branch pointing on the baf9c8d version. So if you created a new commit version you will have the following situation :
* e04c5e7 - (HEAD) version detach of branch (3 seconds ago) 
* baf9c8d - (master) Team of 2 players (63 minutes ago)
* 58d31e1 - First commit (2 hours ago)

So the HEAD moves with the new version but the branch name stayed on baf9c8d. Alway checkout to the last branch name.

5/ Branches

To avoid mix into the development, you have to think that your work will be share with someone. You should have 3 branches, your main/master branch, a develop/temporary/feature/test branch and the remote main/master branch.

First of all, where are in this situation :

* baf9c8d - (HEAD -> master) Team of 2 players (63 minutes ago) 
* 58d31e1 - First commit (2 hours ago)

One file equipe1.txt with the following content :

Pierre
Gérard

We want to simulate a different way to develop our file. So we go back to the initial commit and we create a develop branch and try to work on :

git checkout HEAD~1
git branch develop

But we have to display the situation with git lg (of git log –oneline –graph –all –decorate) :

* baf9c8d - (master) Team of 2 players (2 hours ago) 
* 58d31e1 - (HEAD, develop) First commit (4 hours ago)

There is a problem, HEAD is not linked to develop, HEAD is linked to 58d31e1 and develop is linked alos on 58d31e1.

git checkout develop

Then git lg display :

* baf9c8d - (master) Team of 2 players (2 hours ago) 
* 58d31e1 - (HEAD -> develop) First commit (4 hours ago)

Alternative, to avoid the detach HEAD, you could just, but don’t now :

git switch -c develop

To simulate this situation, we want to delete develop branch to recreate, so we have this situation :

* baf9c8d - (master) Team of 2 players (2 hours ago) 
* 58d31e1 - (HEAD -> develop) First commit (4 hours ago)

Detach the HEAD with git checkout 58d31e1 :

* baf9c8d - (master) Team of 2 players (2 hours ago) 
* 58d31e1 - (HEAD, develop) First commit (4 hours ago)

Then delete the develop branch with :

git branch -d develop

Then we can create the new branch with :

git switch -c develop

Now we will update the file to create a new branch, edit equipe1.txt file as :

EQUIPE
##########
Pierre

Then commit this version and display situation ( -am is equivalent as -a -m) :

git commit -am "Nice version" 

Then display:

* d1e4a2c - (HEAD -> develop) Nice version (4 seconds ago) 
| * baf9c8d - (master) Team of 2 players (2 hours ago)
|/
* 58d31e1 - First commit (4 hours ago)

6/ Merge

Suppose we want to simulate some one who works on the master branch adding person to the list or master branch:

git checkout master

Then edit the file with a third person as :

Pierre
Gérard
Killian

Then commit this new version with :

git commit -am "Team of 3"

This is the situation :

* 6eac561 - (HEAD -> master) Team of 3 (2 seconds ago) 
* baf9c8d - Team of 2 players (3 hours ago)
| * d1e4a2c - (develop) Nice version (5 minutes ago)
|/
* 58d31e1 - First commit (4 hours ago)

Then now return on the develop branch with :

git checkout develop

* 6eac561 - (master) Team of 3 (87 seconds ago)
* baf9c8d - Team of 2 players (3 hours ago)
| * d1e4a2c - (HEAD -> develop) Nice version (6 minutes ago)
|/
* 58d31e1 - First commit (4 hours ago)

We want to merge the nice version of develop branch into the master branch with :

git merge master

Then we will have the fusion because there is no conflict with this final result :

*   d153307 - (HEAD -> develop) Merge branch 'main' into develop (71 minutes ago)
|\
| * 6eac561 - (master) Team of 3 (74 minutes ago)
| * baf9c8d - Team of 2 players (4 hours ago)
* | d1e4a2c - Nice version (78 minutes ago)
|/
* 58d31e1 - First commit (5 hours ago)

You can display the merge file equipe1.txt Git succed to combine file in this case:

EQUIPE
##########
Pierre
Gérard
Killian

But we are lucky, equipe1.txt file from master/main branch have commun element from equipe1.txt from develop branch. you can display this information with this command (and yes we use ~1 as HEAD~1:

git diff develop~1 master

This will display difference beetwen 6eac561 and d153307 with :

diff --git a/equipe1.txt b/equipe1.txt
index 6eac561..d153307 100644
--- a/equipe1.txt
+++ b/equipe1.txt
@@ -1,3 +1,3 @@
-EQUIPE
-##########

Pierre
+Gérard
+Killian

Red element if for the develop branch, Pierre element is common and green element if for main/master branch.

To cancel and go back to previous situation, you can move the HEAD and develop branch name by moving it (and we will lose d153307)

git reset --hard  d1e4a2c

7/ Merge conflict

Now we want a real conflict, so edit the equipe1.txt file from develop branch and remove Pierre and insert Simon :

EQUIPE
##########
Simon

Now commit this new version with :

git commit -am "Pretty and Simon" 

So now we can look a potential merge conflict before by compare :

git diff --word-diff=color develop master

Result show a conflict on the third line :

-EQUIPE
-##########
Simon
Pierre
Gérard
Killian

So we know it will be a problem with the futur merge.

We can display also side by side with :

 git difftool -y -x sdiff develop master

EQUIPE | Pierre
########## | Gérard
Simon | Killian

So we will create the merge conflict with :

git merge master

This will display the conflict message :

Auto-merging equipe1.txt
CONFLICT (content): Merge conflict in equipe1.txt
Automatic merge failed; fix conflicts and then commit the result.

We can display the file and it is a mess :

<<<<<<< HEAD
EQUIPE
##########
Simon
=======
Pierre
Gérard
Killian
>>>>>>> master

Ok just to read it I had color as git diff

<<<<<<< HEAD
-EQUIPE
##########
Simon

=======
Pierre
Gérard
Killian

>>>>>>> master

The simpliest solution is just remove everything from git merge (<<<<< , >>>>> and =====) to create ours merged version and even add information and save it :

EQUIPE
##########
Simon

Pierre
Gérard
Killian

Adam

Then to finish create the commit :

git commit -am "Combine pretty and team of 3 plus Adam"

Finaly, we have got :

*   9ddbc45 - (HEAD -> develop) Combine pretty and team of 3 plus Adam (22 minutes ago)
|\
| * 6eac561 - (master) Team of 3 (15 hours ago)
| * baf9c8d - Team of 2 players (18 hours ago)
* | 8f1fead - Pretty and Simon (47 minutes ago)
* | d1e4a2c - Nice version (15 hours ago)
|/
* 58d31e1 - First commit (19 hours ago)

But master/main branch is not update, we should move in parallel. Finish, we merge develop to main/master. This time no conflict, Git knows what comme from develop and what comme from main:

git checkout master 
git merge develop

Then we can see HEAD is on master and develop branch is also on the last commit :


* 9ddbc45 - (HEAD -> master, develop) Combine pretty and team of 3 plus Adam (22 minutes ago)
|\
| * 6eac561 - (master) Team of 3 (15 hours ago)
| * baf9c8d - Team of 2 players (18 hours ago)
* | 8f1fead - Pretty and Simon (47 minutes ago)
* | d1e4a2c - Nice version (15 hours ago)
|/
* 58d31e1 - First commit (19 hours ago)

Remote

Ok now everything we done is only local. We need to link to Github, so we need information keep at the begining as the git token (symbolise by ghp_XXXXXXXXX later) and the url :

https://github.com/pierre-jean-dhm/hello1.git

We need to create this command with you information :

git remote add origin https://ghp_XXXXXXXXX@github.com/pierre-jean-dhm/hello1.git

In fac this will create a short name « origin » to your hello1.git repository. You can choose something other than origin as github but origin is really commun.

At first, I want to rename master branch as main with :

git branch -M master main

Then I will push with :

git push -u origin main

The -u parameter (or –set-upstream) is to devine the default branch to later do not have to write all the time you want the main branch.

You can go online to reresh the page and find everything:

  • Top left: the main branch
  • Top right: 6 commits from your computer
  • Center: our unique equipe1.txt file

You can open the file to see the last content and you can list all the commit to find history of commit or you can open the equipe1.txt file to see history also.

You can see the commit comments and unique number but only the main branch is uploaded.

In local you can see now there is a new remote origin/main branch with git lg command (or the short version git log –oneline –graph –all –decorate) :

*   9ddbc45 - (HEAD -> main, origin/main, develop) Combine pretty and team of 3 plus Adam (2 hours ago)
|\
| * 6eac561 - Team of 3 (17 hours ago)
| * 6c6fd31 - Team of 2 players (20 hours ago)
* | 8f1fead - Pretty and Simon (3 hours ago)
* | d1e4a2c - Nice version (17 hours ago)
|/
* 633f1e4 - First commit (21 hours ago)

Remote conflict

We will simulate a conflict between the origin/main branch and your local branch, on the main repository file you can click on the equipe1.txt file :

Then on the right, the pen button or the short menu then « Edit online » let you edit the file :

Change the content Equipe becomes TEAM :

TEAM
##########
Simon
Pierre
Gérard
Killian
Adam

Then you have to « Commit » this new version with the top right button, this will open a dialog box to enter the messsage :

At this point, the online origin/main is updated but not your local version. There are two solutions from here :

  • Download the remote origin/main branch to look what it could happen with : git fetch
  • Download the remote origin/main branch to stray away merge to your HEAD: git pull

We can say « git fetch » and « git merge » is equivalent as « git pull ». Git fetch is the light version, you can download from Github but your ane not sure to use it. Git pull is you will download from Github but you use it at present.

The situation at present with git lg before git fetch:

*   9ddbc45 - (HEAD -> main, origin/main, develop) Combine pretty and team of 3 plus Adam (2 hours ago)

after git fetch and again git lg to display :

* 70735d2 - (origin/main) Change Equipe to Team (6 minutes ago) 
* 9ddbc45 - (HEAD -> main, develop) Combine pretty and team of 3 plus Adam (3 hours ago)

Ok know we can see the the difference :

git diff --word-diff=color origin/main main

This will display :

TEAMEQUIPE
##########
Simon
Pierre
Gérard
Killian
Adam

Ok three strategies :

  • git merge origin/main to have the remote origin/main version with TEAM word
  • git merge –strategy=ours origin/main to have the local main version with EQUIPE word
  • git merge –no-ff origin/main this is a very useful one that will create a new commit from the merge of origin/main and main branches without fast-forward strategy to merge into the actual commit.

Let look the result of this last git merge –no-ff origin/main with git lg command :

*   24e02d5 - (HEAD -> main) Merge remote-tracking branch 'origin/main' (10 seconds ago) 
|\
| * 70735d2 - (origin/main) Change Equipe to Team (71 minutes ago)
|/
* 9ddbc45 - (develop) Combine pretty and team of 3 plus Adam (4 hours ago)

So the equipe1.txt include a merge of the two branch so this is the content :

TEAM
##########
Simon
Pierre
Gérard
Killian
Adam

But we want to decide better how to manage the content into the merge. So now switch to a new tool GitHub Desktop

GitHub Desktop

Install GitHud Desktop now, but we will skip the Github authentication to test again Git.

Step one « Skip the Github authentication » we will authenticate at first with token and later we could « Sign in to Github.com » :

Enter nothing or your username and email as we store at the top of this exercice. Why noting : because informations are store into the .git folder of this repository (remeber git config user.email) :

Then now the important, we ask GitHup Desktop to manage the Git local folder c:\Users\pierre.jean\Dekstop\Projet1\

Let start with the GitHub Desktop :

  • Top left button: to change the repository, at present we have only one Projet1
  • Middle top button, you can see and change branch as git checkout, you can also merge branch into this windows
  • Top right button Git pull origin or the small one git fetch (git pull = git fetch + git merge)
  • History menu : as git lg we will see later
  • Large left white area: List of potential files to git add, at present no file, create a new text file into the Projet1 folder and you will see there, then delete it
  • Git commit message area as we did with git commit -am « message area »
  • Git commit description : not used
  • Commit to main : the commit button to create a new commit

At this point, we have the same operation on the classic process to modify files, add new files, commit and push. One drawback, nothing display the remote origin/main branch at this moment with GitHub Desktop. We will see how to manage this point later.

You can use now the « History » button to display list on the main current branch the evolution of the content of the equipe1.txt file :

On the « First commit », you will find only Pierre, then adding Gérard.

The « Nice version » is suppose to be into the develop branch, but everything is merge into the last commit and so Github Desktop display everything.

GitHub Desktop philosophy

As you can see on the first screen, GitHub Desktop show us this message in blue : « Pull 1 commit from the origin remote » :

In fact, GitHub Desktop wants the main branch is synchronize all the time to the remote origin/main. At present git lg shows us :

* 70735d2 - (origin/main, origin/HEAD) Change Equipe to Team 
* 9ddbc45 - (HEAD -> main, develop) Combine pretty and team of 3 plus Adam
|\
| * 6eac561 - Team of 3
| * 6c6fd31 - Team of 2 players
* | 8f1fead - Pretty and Simon
* | d1e4a2c - Nice version

GitHub Desktop wants you merge local main branch and origin/main. And it also adds origin/HEAD that I don’t know why (event after I delete it, it comes back).

Anyway, we are suppose to have a local main branch always equals to origin/main branch.

So we should develop on the develop branch and then merge to the local main branch and then push to the remote origin/main branch.

So press button : « Pull origin » to receive the last commit « Change Equipe to Team » and the equipe1.txt file contents will be :

TEAM
##########
Simon
Pierre
Gérard
Killian
Adam

So main branch and remote origin/main branche are equals now. I still have develop branch with equipe1.txt contains :

EQUIPE
##########
Simon
Pierre
Gérard
Killian
Adam

Two options:

  • I want to move develop branch on the last commit from the origin/main branch (= main branch)
  • I want to preserve the content from develop branch

1/ Option 1: Develop branch = local main branch = remote origin/main branch

This strategy is remote content is the correct solution with TEAM word.

  • Change to the develop branch
  • Choose to create a merge commit from the main branch.
  • Press « Create a merge commit » to confirm the merge
  • A new commit is « added » to the develop branch and this commit is just the same of main branch, see git lg :
* 70735d2 - (HEAD -> develop, origin/main, origin/HEAD, main) Change Equipe to Team 
* 9ddbc45 - Combine pretty and team of 3 plus Adam
|\
| * 6eac561 - Team of 3

You can go on work on the develop branch until you merge with the main branch.

2/ Option 2: local main branch has to update then remote origin/main branch will be update

This strategy is the local content is the correct solution with EQUIPE word. We cannot merge because develop branch is an ancestror of main branch.

* 70735d2 - (HEAD -> main, origin/main) Change Equipe to Team
* 9ddbc45 - (develop) Combine pretty and team of 3 plus Adam
|\
| * 6eac561 - Team of 3

We could imagine to create a new commit from develop branch change something then merge to simulate and update on the develop.

We will just choose the previous commit and right click to create a new commit with the previous content :

The git lg command will show:

* 161d109 - (HEAD -> main) Revert "Change Equipe to Team"
* 70735d2 - (origin/main, origin/HEAD) Change Equipe to Team
* 9ddbc45 - (develop) Combine pretty and team of 3 plus Adam
|\
| * 6eac561 - Team of 3 (26 hours ago) <pierre.jean@umontpellier.fr>

Now we can push the new modification and delete the develop branch and recreate it on the HEAD.

Publié dans Développement | Laisser un commentaire

Protégé : Git why not full local

Cette publication est protégée par un mot de passe. Pour la voir, veuillez saisir votre mot de passe ci-dessous :

Publié dans Blog, Développement | Saisissez votre mot de passe pour accéder aux commentaires.

Formation Python

PYTHON c’est:

  • un  révolver
  • deux films d’horreurs
  • un serpent de la famille des pythonidae et loxocemidae
  • un langage de programmation

 

http://www.python.org

PREMIER TRUC

Python 3.12  ou  Python 2.7.18

Normalement, le python 2.7.xy n’existe que pour assurer le fonctionnement d’anciens programmes. Vous devriez commencer par la branche 3.x.y.

Les différentes sont minimes sur le fond mais pas sur la forme:

Python 2                            Python 3   
print "Bonjour le monde"        →   print("Bonjour le monde")
print "\n".join([x, y])         →   print(x, y, sep="\n")
xrange()                        →   range()
reduce()                        →   functools.reduce()
intern()                        →   sys.intern()
SimpleDialog                    →   tkinter.simpledialog

 


SECOND TRUC

 

macOS 64-bit universal2 installer macOS for macOS 10.9 and later
Windows installer (64-bit) Windows Recommended
Windows installer (ARM64) Windows Experimental

 

A installer dans un dossier :

Il est à noter que :

  • deux versions de python peuvent cohabiter sur le même ordinateur, mais il faut bien sûr dans ce cas gérer correctement la situation pour éviter de s’emmêler
  • un logiciel de développement PyCharm sera installé par la suite pour nous aider à développer
  • Mes fichiers des programmes sont stockés dans un dossier PyCharmProjects mais ils peuvent tout aussi bien être dans « Mes Documents », sur le bureau, dans n’importe quel dossier, etc.
  • Il vaut mieux se souvenir du chemin complet sur le disque dur du programme c:\Developpement\Python312\python.exe (pour Windows par exemple) /usr/bin/python (pour Mac)

 

Installation de python sous Mac OS

Installation de python 3.6.2 sous Mac OS

 


TROISIEME TRUC

Il n’est pas possible de donner un programme Windows par exemple python.exe à un ordinateur sous Mac et vice-et-versa.

Par contre, un programme écrit en langage python peut être envoyé depuis Windows pour être exécuté sur un Mac qui a l’exécutable python installé.

A l’identique de Matalb par exemple, les programmes ne sont pas exécutés directement par le système d’exploitation Windows ou Mac, mais sont exécutés pas un programme tierce python.exe ou matlab.exe (python et matlab sous MacOs) pour s’exécuter.

On appelle ces programmes des scripts et on peut ouvrir le fichier initial avec un simple éditeur de texte (bloc note sous Windows, text edit sous MacOs).

L’option aujourd’hui d’utiliser Vscode en version .zip  puis de créer dans ce dossier un sous-dossier data (ou code-portable-data à côté du dossier dézipé)  comme expliquer dans ce document rend VScode portable simplement.

NOTA : en fait python compile votre fichier.py en pseudo exécutable fichier.pyc qui sera plus rapidement exécuté ensuite s’il n’est pas modifié

On verra aussi comment utiliser l’interpréteur de commandes de python pour taper rapidement des lignes de scripts et voir le résultat.


EXERCICE 1

 

Après une installation réussie de python, fabriquez le fichier exercice1.py avec le contenu suivant :

# Exercice 1
import time

print ( "Je m'affiche 5 secondes " )

time.sleep(5)
# Fin du programme

Pour fabriquer ce fichier, vous pouvez utiliser de nombreux éditeurs. Personnellement, j’en utilise plusieurs selon la situation (tests d’une fonction, gros projets, proof-of-concepts, etc.) et on peut même entrer du python dans le navigateur via des sites comme http://ideone.com/  ou https://www.tutorialspoint.com//execute_python3_online.php.

Le plus simple pour commencer est d’utiliser l’éditeur IDLE qui est fourni par défaut par python :

IDLE proposé par python par défaut pour Windows

Logiciel IDLE proposé par python pour MacOS

Logiciel IDLE proposé par python pour MacOS

Faites Menu File > New File et entrez le code suivant:

# Exercice 1
import time

print ( "Je m'affiche 5 secondes " )

time.sleep(5)
# Fin du programme

Sauvegarder le fichier en exercice1.py dans un dossier dont vous vous souviendrez par exemple dans « Documents ».

Pour exécuter le programme, le plus simple est d’utiliser la touche F5 ou via le menu
Run > Run Module

 

Une autre solution est d’utiliser l’interpréteur de commande python (appelé aussi shell python). Si vous lancez le programme python sans aucune information, c’est une fenêtre avec ce genre d’informations qui va apparaitre pour vous proposer d’entrer les commandes au prompt (le prompt est les symboles >>> avec le curseur qui attend vos commandes):

Python 3.12.2 (v3.12.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Entrer la ligne suivante au clavier en modifiant le chemin pour correspondre aux dossiers où se trouvent votre programme. (NOTA: il faut saisir une simple quote):

exec( open ('c:/Users/pierre.jean/Desktop/Exercice1.py').read() )

Sous Mac par exemple si le fichier exercices1.py se trouve dans le dossier Documents:

exec( open('/Users/pierre.jean/Documents/exercice1.py').read() )

Cette ligne lance le programme exercice1.py directement python dans l’interpréteur de commandes python.

On pourrait ainsi entrer directement les commandes en appuyant sur entrée à chaque bout de ligne. Essayez de modifier le temps d’attente de 5 secondes et le texte affiché:

import time 
print ( "Je m'affiche 5 secondes " ) 
time.sleep(5) 

 

On peut aussi fabriquer un raccourci sous windows qui va appeler python.exe en lui passant notre programme en paramètre. Clic droit sur bureau puis choisir « Nouveau » puis « Raccourci » dans l’emplacement indiquer le chemin vers le programme python suivi du nom du programme, par exemple (notez l’espace entre les .exe et le chemin du fichier exercice1.py):

c:\Developpement\Python3.11\python.exe c:\User\pierre.jean\Documents\exercice1.py

 

Sous MacOs, cette solution  semble être la plus simple:

Faire click droit sur le fichier python et choisir « Python Launcher ».

 

 

 


QUATRIÈME TRUC

 

Utilisation de l’interpréteur pour tester quelques commandes et afficher des variables pour tester rapidement :

Python 3.12.2 (v3.12.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>notes = [ 10 , 15 ,8 , 6]
>>>print ( notes )
[10, 15, 8, 6]
>>>notes 
[10, 15, 8, 6]
>>> print ( notes [ 2 ] )
8
>>> print ( notes [ 2:4 ] )
[8, 6]
>>> print ( notes [ :3 ] )
[10, 15, 8]
>>>print ( notes [ 1: ] )
[15, 8, 6]
>>>notes.append ( 18 )
>>>print ( notes )
[10, 15, 8, 6, 18]
>>>notes[ 4 ] = 8
>>>print ( notes )
[10, 15, 8, 6, 8] 
>>>print ( [x+1 for x in notes] )

 


EXERCICE 2

Afficher les notes sur 10 en les divisant par deux.

Affecter une variable notesSur10 contenant les notes sur 10. Voici le début de la commande:

notesSur10 =

Faites la moyenne des notes sur 10 avec sachant qu’il y a une fonction sum() et une fonction len() sur une seule ligne.

On pourrait coder bien sûr comme ceci dans un fichier :

# Exercice 1

notesSur10 = [5.0, 7.5, 4.0, 3.0, 2.5]
somme = 0
nombreElement = 0

for x in notesSur10:
 somme = somme + x
 nombreElement = nombreElement + 1

print ( somme / nombreElement )

# Fin du programme

 

RÉPONSE A L’EXERCICE 2

Afficher la réponse pour avoir les notes sur 10 ->
>>> print( [ x /2 for x in notes ] )

Afficher la réponse pour avoir les notes sur 10 dans une variable notesSur10 ->
>>> notesSur10 = [ x /2 for x in notes ]

Créer une variable moyenne contenant la moyenne des notes sur 10 ->
>>> moyenne = sum ( notesSur10 ) / len ( notesSur10 )

 

 


Seconde partie de la formation >>>

 

 

 

Publié dans EuroMov DHM | Laisser un commentaire

Azure Spring deployment

This article is divided into two parts. First about Spring Boot Web Application and the second part is Tomcat Web Application without database.


Spring boot Web Application

1/ Create Web app with Azure account

Then choose to create a Web App of type Web App + Database :

Then provide information at first :

The « Ressource Group » is just a group of several « tools » provide by Azure in ours cases the already created empty group « sftp-test-europe » just provide networks settings, virtual network, database server, web app server and App Service plan.

We need to provide web app name here ceris1 as application name. This information will be used to create URL, database name, etc.

We provide the runtime stack of Java 17, and the Java web server stack  » Java SE (Embedded Web Server) ».

Then we choose MySql database and check « Hosting Basic for hobby or research » to avoid to paid too much for a test.

The second interface provides information to keep about MySQL settings include server host, login, password, and default database name ceris1-database for me. The default MySQL port should be 3306.

2/ Modification Spring application

Change the file applications.properties to provide the azure MySQL settings as :

I change the default Web server port from 8080 to 80 to create classical URL :

http://ceris1.azure.com/ 

We need to generate the final jar of our application, but we also need to avoid tests from Spring. Why, we do not have access to the Azure MySQL server to test our application, so the command will be :

mvn clean install spring-boot:repackage -DskipTests to create 

If the creation is OK, you will find a new jar file into :

C:\Dev23\Workspace-vscode-182.2\todo\target\todo-0.0.1-SNAPSHOT.jar

Then we need FTPS settings to upload the jar file, with « Deployement Center » we can find several methods but historical FTPS is simple :

We need FTPs server name (FTPS endpoint), FTP Username and Password to upload file.

Open Filezilla or any ftps client with settings, remove the default file into « /site/wwwroot » folder and drag and drop the newly created jar file :

You can test running the project with the Azure SSH console with :

The first time, open the consol is really slow, but I use it a lot to understand which settings is not OK about MySQL, port, java version, etc. That really useful.

Enter the command to start spring server with our development after may be a change directory to /home/site/wwwroot/ default folder :

java -jar todo-0.0.1-SNAPSHOT.jar

You should find the classical deployment information :

You should have a port 80 conflit at the end because the default web start application is still alive. Just « Restart » the web app from the Azure interface to let remove it after remove the default file with Filezilla or the Azure console.

Restart the application with the command line and test it online : https://ceris1.azurewebsites.net/.

NOTE: the automatic deployment from git server should be used be the purpose here is to understand the basic deployment from a simple jar application.


Tomcat War Web Application

From Eclipse Java EE, we suppose to have a Dynamic Web Project with servlet and JSP. At present, we will not include a database, but the process will be identical as Spring boot Web Application.

1/ Create Web App with Azure account

Then choose to create a Web App of type Web App :

Then provide information at first :

  • Resource Group : a group of applications of azure, but in our case it will a group of only this Web App
  • Name: Name of the instance just for URL, and to identify this Web App
  • Runtime stack: Java 17 for our web application
  • Java web start stack: Apache Tomcat 9.0
  • Pricing plan: free F1 (Shared infrastructure) to test this application for free

After the creation of the instance of web application (could take several minutes), we will consult the « deployment Center » and « FTPS credentials » that we will use to upload with FTP.

2/ Create and deploy war file

Open Eclipse Java JEE to create a war file from your application :

Right-click on your project, the menu Export > war file then provide the destination to create the file : c:/Dev24/app.war. You have to teep the app.war as the name of the war file.

Then use Filezilla to upload the file, but I find a bug from FTPS credential : use a FTP connection NOT FTPS to simply upload the file from C:\Dev24\ to the /site/wwwroot/ :

I delete the initial hostingstart.html welcome file installed by default by Azure Web App.

Then you can consult your application, which will deployed after a short delay (several minutes) :

The Web application will be slow because we only have a free container for purpose. We can consult the Azure ssh console into the browser to manage logs and information about tomcat.

Publié dans Développement, IMT Mines Alès | Laisser un commentaire

Formation python Seconde partie

 CINQUIÈME TRUC

Utilisation d’un  IDE (integrated development environment) performant pour gérer plusieurs fichiers pythons ou autre, plusieurs fichiers de données, plusieurs versions, etc.

Il y a de nombreux IDEs python, celui que je recommande actuellement est la version gratuite de PyCharm appelé PyCharm Community Edition (Si elle est après la version Pro plus bas dans la page) ; elle est très complète comme version.

A installer sur votre ordinateur comme habituellement, n’importez pas de « settings » et prenez les réglages par défaut.

Créez un nouveau projet, en fait un dossier qui va contenir vos futurs développements en python. Vous pouvez vérifier que PyCharm va bien utiliser python3.x pour vos développements.

Fermer le « Tip of the Day » et vous avez l’interface de PyCharm devant les yeux:

OK c’est ma version car vous n’avez en fait aucun dossier ni aucun fichiers actuellement. Donc par exemple, faites click droit dans la zone « Fichiers et dossier » dans le menu choisir:

New > Directory

Entrez le nom du dossier par exemple test et copier coller le fichier exercice1.py dedans.

Ouvrez le fichier exercice1.py en double cliquant dessus :

On peut exécuter le fichier exercice1 via le bouton en haut à droite ou le raccourci indiqué en survol de ce bouton. Le résultat de l’exécution sera visible donc dans la fenêtre du bas.


EXERCICE QUATRE

Télécharger le fichier de données à cette adresse : traitement_fichier.xls

Copiez le fichier dans PyCharm avec Copier / Coller et profiter pour renommer le fichier en traitement_fichier.txt :

Nous allons manipuler le fichier de données traitement_fichier.txt pour extraire de l’information, vous pouvez l’ouvrir dans PyCharm pour voir sa composition:

timestamp;latitude;longitude;altitude
1491486784141;43.64093363956815;3.851249759920415;109.30910031218662
1491486785141;43.64089947397977;3.8512505542990336;111.87747544303649
1491486786141;43.64088583922287;3.8512393755398326;113.0741231549388

...

Il s’agit des données en provenance d’un vol de planeur enregistré avec le GPS d’un smartphone.

On va donc dans le dossier test avoir le premier fichier exercice1.py, le fichier de données traitement_fichier.txt et on va ajouter un nouveau fichier, manipulation_fichier.py :

On va accéder au fichier pour afficher le contenu avec ces commandes:

with open("traitement_fichier.txt", "r") as fichier:
    contenu = fichier.readlines()
    print( contenu )
fichier.close()

Voici les données obtenus :

['timestamp;latitude;longitude;altitude\n', '1491486784141;43.64093363956815;3.851249759920415;109.30910031218662\n',

Nous devons en premier lieu traiter le problème du retour à la ligne « \n » en le retirant pour chaque ligne.

Voici le code pour traiter ligne à ligne la variable contenu en retirant à chaque fois le retour à la ligne:

with open("traitement_fichier.txt", "r") as fichier:
    contenu = fichier.readlines()
    for ligne in contenu:
        ligne = ligne.rstrip("\n")
        print(ligne)
fichier.close()

Vous pouvez voir que l’indentation du code en python remplace les end du Matlab. Ils ne sont donc pas optionnel, ils donnent un sens à ce qui est dans la boucle et ce qui n’est pas dans la boucle.

% Exemple Matlab valable mais non indenté
for c = 1:10
for r = 1:20
H(r,c) = 1/(r+c-1);
end
end

Nous allons ensuite nous concentrer sur le timestamp et l’altitude en extrayant que ces 2 colonnes:

with open("traitement_fichier.txt", "r") as fichier:
    contenu = fichier.readlines()
    for ligne in contenu:
        ligne = ligne.rstrip("\n")
        data = ligne.split(";")
        # ici afficher les colonnes 0 et 3 
fichier.close()

OK à vous , il faut extraire uniquement les altitudes qui ont été enregistré après le timestamp « 1491486791998 »

RÉPONSE A L’EXERCICE 4

Afficher la réponse pour avoir les altitudes ->


SIXIÈME TRUC

Test de quelques commandes dans l’interpréteur intégré de PyCharm. Nous avons avec PyCharme la possibilité de lancer des programmes dans l’IDE mais pour tester quelques lignes de commandes, l’IDLE est très pratique. Heureusement, nous pouvons avoir l’interpréteur de  commande dans PyCharm via le Menu Tools > Python Console …

Vous aurez ainsi la possibilité de tester quelques commandes avant de les intégrer dans votre fichier de commandes.


 EXERCICE CINQ

Afficher au format CSV les données suivantes pour les timestamps supérieurs à « 1491486791998 » avec un numéro de ligne incrémenté à chaque ligne:

1,1491486784141,109.30910031218662
2,1491486785141,111.87747544303649
3,1491486786141,113.0741231549388
4,1491486787141,112.96381095914386
5,1491486788142,113.037303562919
6,1491486789142,116.63811281139428
7,1491486790142,117.30185665137451

Nous allons donc créer une variable numero_ligne et l’incrémenté à chaque lecture de ligne :

numero_ligne = 0

Ensuite nous allons afficher les informations que nous voulons avec ce genre de ligne qui concatène les informations avec des « , »

print( numero_ligne + "," + data[0] + "," + data[3]  )

Mais malheureusement ou pas si vous essayez cette ligne que vous pouvez tester dans l’IDLE de Python ou en ouvrant l’interpréteur dans PyCharm comme vu précédemment.

numero_ligne = 0
print( numero_ligne + ","  )

Vous avez une erreur de type numero_ligne est de type entier (int en VO) et python ne veut pas prendre la responsabilité de le convertir en chaine de caractère (str en VO).

Essayez donc ceci encore une fois dans l’interpreteur:

unTexte = "1491486791998"
unNombre = int( unTexte )
unNouveauTexte = str( unNombre )

On doit donc convertir notre numero_ligne en str pour l’utiliser pour l’affichage.

En fait depuis le début on manipule des textes et non pas des nombres. Ce qui parfois va entrainer quelques problèmes de conversion que l’on verra plus tard.

RÉPONSE A L’EXERCICE 5

Afficher la réponse pour avoir les altitudes avec des numéro de lignes et un affichage en CSV ->


EXERCICE SIX

Maintenant, pour pouvoir enchainer les futurs traitements sur les données, le plus simple est de sauvegarder notre résultat au lieu de l’afficher à l’écran.

Pour écrire un fichier, on va faire en fin de notre programme comme ceci pour tester la création du fichier:

with open("extraction_fichier.txt", "w") as fichier_sortie:
    fichier_sortie.write( "numero_ligne;timestamp;altitude" )
fichier_sortie.close()

A vous d’intégrer ces modifications pour écrire non plus seulement une ligne d’entête mais toutes les données extraites précédemment dans ce fichier

RÉPONSE A L’EXERCICE 6

Ecrire les données extraites dans un fichier ->


SEPTIÈME TRUC

Le débugger est le meilleurs outil intégré dans les IDEs quelque soit le langage de programmation. Au lieu de ne disposer des erreurs ou des messages à la fin de l’exécution des programmes, le débuggeur fait exécuter étape par étape le programme.

La différence est similaire entre l’exécution d’une action de football en plein vitesse ou au ralenti:

Nous allons donc pour commencer ajouter un point d’arrêt à notre programme puis le faire exécuter ligne par ligne.

Pour bien débuter, nous allons mettre ce point d’arrêt à la première ligne de notre programme; plus tard nous mettrons ce point d’arrêt plus loin dans le programme car ce qui va nous intéresser sera non pas le début mais un endroit spécifique du programme.

C’est similaire avec l’action du but que l’on va décortiquer et non pas tout le début du match.

Placer le point d’arrêt en cliquant à droite du numéro de ligne, normalement un petit point rose indique que le point d’arrêt est actif.
Puis appuyer sur le bouton « Debug » en haut à droite juste à côté du bouton « Run ».

Le programme va démarrer et se mettre en pause sur la ligne avec le point d’arrêt. Pour enchainer ligne par ligne notre programme, nous allons utiliser soit le bouton « Ligne suivante » sur le dessin (Step over en VO) soit pour plus de simplicité la touche Fn+F8 sur MacOs et F6 sous Windows:

Nous pouvons avoir l’état des variables en mémoire soit dans la fenêtre du bas soit dans le code juste à droite de la ligne exécutée. Le mode debugage est très utile pour voir ce qui peut entrainer une erreur dans notre programme et en vérifiant l’enchainement qui est réalisé selon l’état des variables.

Pour retirer le point d’arrêt il faut cliquer de nouveau dessus. Vous pouvez avoir plusieurs points d’arrêt et les options de débogages sont très nombreuses, nous ne rentrerons pas dans les détails pour l’instant.


EXERCICE SEPT

Essaye le mode debugage sur votre programme pour vérifier l’enchainement des étapes.

Faites un point d’arrêt en face de l’instruction :

numero_ligne = numero_ligne + 1

Faites un clic droit sur le point d’arrêt et indiquer comme Condition:

numero_ligne == 10

Relancer le debugogage pour vérifier que le point d’arrêt ne se déclenche que quand cette valeur est atteinte.


EXERCICE HUIT

Nous voudrions obtenir le fichier de données suivant avec les timestamps qui sont transformé en intervalles de temps entre deux échantillonnages depuis un t zéro à la première valeur acquise par le GPS.

Ancien fichier:

timestamp;latitude;longitude;altitude
1491486784141;43.64093363956815;3.851249759920415;109.30910031218662
1491486785141;43.64089947397977;3.8512505542990336;111.87747544303649
1491486786141;43.64088583922287;3.8512393755398326;113.0741231549388
1491486787141;43.64090016392363;3.851241228679665;112.96381095914386

Nouveau fichier avec les intervalles de temps

1,0,109.30910031218662
2,1000,111.87747544303649
3,1000,113.0741231549388
4,1000,112.96381095914386
5,1001,113.037303562919
6,1000,116.63811281139428
7,1000,117.30185665137451
8,1857,117.30387542891553
9,1000,117.57712510977889
10,1000,118.1639542835122
11,1000,118.54163427393473

Calcul des intervalles de temps entre deux acquisitions ->


Troisième partie de la formation >>>

Publié dans EuroMov DHM | Laisser un commentaire

Formation python Troisème partie

 EXERCICE NEUF

Demander une information depuis la ligne de commande, pour filtrer les informations et ne garder que celle dont le numero_ligne est supérieur au numero_ligne_initial indiqué par l’utilisateur.

Pour demander une variable, voici la commande

numero_ligne_initial = input('Numéro de ligne initial: ')
numero_ligne_initial = int(numero_ligne_initial)

Normalement votre console va contenir ce message, avec le curseur pour attendre que vous indiquiez à partir de quel ligne on va traiter l’information

Numéro de ligne initial: _

 

Filtrer les informations à partir d’un numéro de ligne ->

 

 

 


HUITIEME TRUC

Les bibliothèques additionnelles sont très importantes dans python. Par défaut, python ne charge pas toutes les bibliothèques car cela prendrais trop de temps, cela chargerais en mémoire trop d’informations et même il y a risque d’incompatibilités entre certaines bibliothèques. Donc on charge que ce que l’on a besoin et on les importes individuellement.

Par exemple pour faire un graphisme, la bibliothèque que je propose est matplotlib.

Pour l’installer, il faut soit appeler en ligne de commande le logiciel pip par exemple via la commande du système d’exploitation (terminal sous MacOs, cmd sous Windows :

pip install requests

ou on trouve aussi la commande exprimée comme ceci:

python -m pip install <nom de la bibliothèque>

Ce que je conseille sinon c’est ce petit programme python qui exécute pip (qui est développé en python), à exécuté dans l’interpreteur python:

Python 3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)]
 on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>import pip
>>>pip.main(['list'])
>>>pip.main(['install','<nom de la bibliothèque>'])

Mais ce qui est vraiment pratique avec PyCharm c’est que l’on peut faire via l’IDE tout cela:

Allez sur le Menu File > Settings…

NOTA: sous Mac Os le menu settings est déplacé dans le menu le plus à gauche portant le nom de l’application soit ici PyCharm > Settings…

Choisissez « Project: <votre projet> » puis « Project Interpreteur » et complètement à droite le bouton « + » puis vous pouvez chercher une bibliothèque (un package en VO) par exemple « matplotlib » pour l’installer.

Une fois l’installation terminé, on peut constater que matplotlib n’a pas été installé tout seul mais des bibliothèques additionnelles ont été aussi installé pour le faire fonctionner:

On peut constater que la bibliothèque numpy qui est très utile pour le calcul scientifique est aussi installé car elle est nécessaire à matplotlib.

 


NEUVIÈME TRUC

 

Pour l’utilisation de matplotlib et numpy pour faire une figure et des calculs, il faut en premier lieu importer les bibliothèques. Pourquoi indiquer dans un programme ce que l’on veut importer précisément, on pourrait penser que python va charger toutes les bibliothèques que l’on a installer, oui mais dans ce cas là on va avoir un long temps de chargement avant que notre programme ne s’exécute.

Pour importer l’objet qui gère dans la bibliothèque matplotlib l’objet qui gère les diagrammes, on peut écrire ceci:

from matplotlib import pyplot

Mais on trouve la version plus abrégé suivante:

import matplotlib.pyplot

Sauf qu’après on se retrouve à devoir faire préfixer toutes les fonctions de cet objet, par exemple ici la fonction figure() par le nom de la bibliothèque + le nom de l’objet:

matplotlib.pyplot.figure()

Donc on peut faire un alias (le mot après as) pour remplacer le préfixe par quelquechose de plus court

import matplotlib.pyplot as plt

et du coup l’appel se fait avec la version écourtée:

plt.figure()

Par exemple pour numpy la bibliothèque de calcul scientifique, son alias est souvent np.

 

Mais revenons à ce que nous avons besoin d’importer pour faire une courbe :

import matplotlib import pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D as ax3

Voici un petit morceau de programme pour tracer une courbe simple:

donnees = [18,22,4,15,15]
fig = plt.figure()
ax = fig.gca()
ax.plot( donnees , label='parametric curve')
plt.show()

Essayer d’afficher à l’écran cette courbe et modifier les données pour construire un autre exemple.

On peut faire une courbe avec deux dimensions :

donneesX = [1,2,3,15,18]
donneesY = [18,22,4,15,15]
fig = plt.figure()
ax = fig.gca()
ax.plot( donneesX, donneesY , label='parametric curve')
plt.show()

 


 EXERCICE DIX

Cette courbe est le début du vol du planeur enregistré par le GPS d’un smartphone.

Essayons de construire un programme pour l’afficher avec les données du fichier traitement_fichier.txt.

En premier lieu, importer matplotlib et numpy. Ensuite il faut créer trois tableaux pour stocker les informations:

#initialisation des tableaux de données
longitude = []
latitude = []
altitude = []

Puis après avoir passé la première ligne du fichier traitement_fichier.txt qui contient les entête des colonnes. Nous pouvons ajouter les valeurs lu comme str en valeur de type float (nombre à virgule) via ces lignes:

#construction des tableaux de données
latitude.append(float(data[1]))
longitude.append(float(data[2]))
altitude.append(float(data[3]))

Bien sur éviter de lire la colonne data[0] qui contient les timestamps peut utile pour ce diagramme.

A la fin de notre programme après avoir bien construit les 2 tableaux de données voici le code pour afficher le diagramme:

#dessin de la figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(longitude, latitude, altitude, label='parametric curve') 

# Ajouter des labels aux axes
ax.set_xlabel('longitude')
ax.set_ylabel('lattitude')
ax.set_ylabel('altitude')

plt.show()

 

A vous de jouer.

Affichage des données longitude, latitude, altitude ->

 

 


DIXIÈME TRUC

 

Si vous ne codez pas, tout cela ne va pas vraiment être utile.

Mettez des commentaires pour expliquer les morceaux du code.

Indiquez clairement ce que fait une variable, numero_ligne ou numeroLigne.

Faites des fichiers intermédiaires pour pouvoir rejouer l’intégralité ou une partie du processus.

Utilisez le débogage pour tracer l’enchainement du code et l’état des variables.

Installer pyinstaller avec la commande suivante :

pip install -U pyinstaller

Et vous pouvez ensuite créer un exécutable avec la commande suivante :

c:/Python311/Scripts/pyinstaller.exe --onefile ProjetPython\main.py -n projet.exe

L’exécutable se trouve alors dans le dossier dist/

 

Quatrième partie de la formation ⇒

 

 

Publié dans EuroMov DHM | Laisser un commentaire

Formation python Quatrième partie

 EXERCICE ONZE

Manipulons quelques fonction de la bibliothèque numpy:

import numpy as np
donneesX = np.array([[1,2,3,15,18] , [18,22,4,15,15]])
print ( donneesX.shape )

 

Fabrication d’un tableau de séries de données

import numpy as np
temperature = np.arange(25,44.5,0.5)
print( temperature )

print( temperature.mean() )
print( np.mean( temperature ) )

print( np.min( temperature ) )
print( np.max( temperature ) )
print( np.median( temperature ) )
print( np.std( temperature ) )

 

Manipulation de matrice par l’appel de fonction sur chaque élément:

import numpy as np
temperature = np.arange(25,44.5,0.5)

def toKelvin(x):
 return x + 273.15

print( toKelvin( temperature ) )

 

Manipulation des tableaux par réorganisation des lignes et des colonnes

a = np.arange(6)
print( a )
a = np.arange(6).reshape(2,3)
print( a )

Itération sur chaque élément du tableau:

a =np.array([[1,2],[3,4],[5,6]])
for (x,y), valeur in np.ndenumerate(a):
   print( valeur )

Plus compliqué en indiquant que les valeurs pour les indices paires:

a =np.array([[1,2],[3,4],[5,6]])
for (x,y), valeur in np.ndenumerate(a):
   if x % 2 == 0 
      print( valeur )

Ou le second éléments de chaque sous-tableau:

a =np.array([[1,2],[3,4],[5,6]])
for (x,y), valeur in np.ndenumerate(a):
   if y == 1 
      print( valeur )

Attention imaginons ce type de situations et que nous voulons le dernier élément

a =np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
for (x,y), valeur in np.ndenumerate(a):
   if y == 1 
      print( valeur )

Il faudrait alors utiliser

a =np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
[ soustableau[ -1 ] for soustableau in a]

Mais en fait il faudrait écrire plutôt

a =np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12]])
for valeur in ( [ soustableau[ -1 ] for soustableau in a] ):
  print( valeur )

 

EXERCICE DOUZE

Virtual env dans python permet de fabriquer une configuration particulière des packages python par projet. Cela évite d’avoir un projet1 qui a besoin de Numpy en version 1.3 et un projet2 qui a besoin de Numpy en version 1.6.

A la création du projet dans PyCharm choisir « Custom environement » qui va se base dans mon exemple sur la version de Python 3.11:

En fait, le dossier indiqué dans Location :

c:\Users\pierre.jean\Desktop\PythonProjet1\pythonProject\.venv\ var convenir 

Va contenir une version de python pour ce projet du coup sur cet exemple on voit que pip est en version 23.2.1 et on peut mettre à jours en version 24 via le bouton upgrade (à gauche de l’oeil dans la barre de menu)

Si après la mise à jours de ce package, on crée un nouveau projet avec une configuration Custom environement », nous allons constater que la version de pip n’est pas à jours car chaque projet à sa propre liste de packages.

Au final, la configuration de python et de ses packages se trouve donc dans le dossier du projet. Pour le partage de projet avec d’autres personnes c’est plus simple pour échanger.

Publié dans EuroMov DHM | Laisser un commentaire

Oh my git

Using GIT command is an important skill to acquire for a developer and even all « code user » generally speaking. I truly recommend the software/serious game, Oh my git ! to learn step by step from the beginning as not an expert but a quiet good deeper into GIT’s mechanisms.

Before create a French translation, I write here my vision of a solute and some additional explanation about this incredible software. On each lesson, you can choose to write the git command line on the top right as a computer terminal or to play one of card which represent git command :

You can find the courses from the level zero at top to advanced level at the bottom and event a sandbox area to train. You do not need to install git, it will package into a subfolder where you install the program. Version is compatible from Windows, Linux and MacOs.

List of lessons by category, first one is green because I succeed, and the small terminal symbol is to show I use no cards only terminal :

The final sandbox category offer you just to practice with no specific goal.

Time to work, it could be useful to use, Oh my git! not in full screen, you can create a text file named override.cfg with the following contains:

display/window/size/fullscreen = false

The game will be into a separate classical window.

1/ Living dangerously (levels\intro\risky)

The first lesson will just to show you how to edit a file into the game :

Only one file « form.txt » where you can edit the content and at any new line content to « win ».

The big dark grey area will be used to display a list of project version. A project with git is usually a folder contains files and even other subfolders. Into this lesson, there are no previous versions.

On the top right, the context and the goal of the lesson is detailed. There are usually not linked of any programming context, just small story on chains of operations on file.

At the bottom, the dark blue area will display cards (none at present) and on the bottom right, black are will display output from git commands (even if you use cards or terminal).

The most bottom right are is to enter git command, usually starting by git. Some additional commands are used commons on Linux system and macOS and most supported by Windows.

The red area just below instructions and goal will turn green if you succeed.

At the top left, 3 buttons to got « back » to the menu, « reload » the exercise, and « Toggle music ». If you succeed, a new button will appear « Next level », we are into a serious game ;- )

2/ Making backups (levels\intro\copies)

The next level is just to show 4 versions of a file, you should recognize a situation into a project with copies of the same growing content with a basic way to label versions.

Just add a content to the last form2_really_final.txt file, and you will learn how GIT will help you to avoid the mess if the number of version grows with collaboration.

3/ Enter the time machine (levels\intro\init)

First playing part, you can even play the « git init » card or enter the « git init » command to start creating a hidden folder .git into your project and start using git. Let’s try :

The result display a « blue squirrel » which represent an important concept of GIT: the HEAD.

Suppose you have 3 versions of one project : V1, V2 and V3. GIT is supposed to reference one version with the HEAD. This is the version that your hard drive will store. If you change the HEAD from V3 to V2, you will see store into the folder of your hard drive files from the V2.

We can say it the cursor of the time machine slider.

Output command of « git init » confirm everything is fine and working.

4/ The command line (levels\intro\cli)

At the bottom right, you can enter command line, and the interface will list you classical command you could use. Here you can see « git init » and « git add » command show. The TAB key will fill the terminal with the first choose.

This level is just to enter command by hand if you want to succeed.

NOTE: you can press UP KEY to browse into the command history list of previous commands to avoid enter and enter command.

5/ Your first commit (levels\intro\commit)

The next level starts with an already initialized with « git init » command project (HEAD / blue squirrel visible). You are supposed to have a file named glass with one line of text :

The glass is full of water.

NOTE: even if the project included the glass file and even if the « git init » command is executed into this folder, GIT do not supervise the glass file.

So the card shows us in fact 2 commands: « git add . » and « git commit ». Those commands are used often together, but let dig in :

  • git add . : will ask GIT to supervise all files and folders inside the project folder. In our case we can execute « git add glass » command to ask GIT to supervise the only glass file but in other lessons we will have different filenames and not only one file, the dot is the common way to ask GIT all files.
  • git commit : This command is not enough, the correct command should be : git commit -m « Description message to this project version/commit version »

We can enter separate commands, but the one line version (separate by semicolon) is a good way to use GIT :

git add . ; git commit -m "Water inside the glass"

Now we will have a stored version of our project called a commit, that’s the yellow square and commit message will be display if you move your mouse over « Water inside the glass » :

So now, I can edit the glass file, change content/remove everything, save it and GIT know how to bring me back the glass file at the moment I create the « Water inside the glass » commit.

NOTE: the dark blue label « main » symbolize the main branch of versions and HEAD reference the last version of this branch.

Now, I will edith the glass file, change content (« The glass is empty of water. »), save it and open again to check the content is really not the same :

I can write the command to create a new commit version of the project with glass file modified :

git add . ; git commit -m "Glass is empty"

Then, we can see the first version of the project and the second version (only one message will be display with mouse over). The HEAD reference still moved to the last version.

You can use GIT on your computer to keep several versions of files without other command.

6/ Working together (levels\intro\remote)

Now we will work with a main feature to synchronize your project with a futur students file and an other GIT user named teacher into this example. The game will play the teacher, you are supposed to receive a students file, add you name, commit this version and send it back to the teacher :

You can see a concept not

The first command is « git pull » to copy from the remote teacher repository the students file.

We have a teacher version of his main branch, include the students file.

The file content now :

~ List of current students ~

- Sam
- Alex

So edit and save the students file by adding your name and commit

git add . ; git commit -m "3 students"

You see below the file content already save, and the command GIT prepared to be executed :

Now, you see below, your local version of the students file is the last version and this different of the teacher version. We can imagine got back for example to the previous version, the teacher one. In fact, we will send our version to the teacher repository.

Now, the next command « git push » send your version to the teacher who automatically accept the modification. You see the result, the new version of the students file will be available to the teacher.

This the end of the first part of the game, let’s move to files catagory.

7/ Unexpected Roommates (levels\files\files-delete)

This level is just to learn how to remove files, option one enter command to remove all files with _web at the end of the filename :

rm *_web 

Drag and drop the rm card on each file with _web into the filename.

You should still have bed file.

8/ Interior design (levels\files\files-delete)

This level is to learn how to create file, you have a bed file contains « A yellow cozy bed. ». you are supposed to create 2 additional files with the word « yellow » inside.

The command will be just :

touch lamp

Or you can drag and drop the touch card and fill the table name as see below:

The edit content to add yellow word and save it. The following command creates a file with content :

echo "A yellow lamp" > lamp

You can also create a yellow chair :

echo "A yellow chair " > chair 

The next category branches is really important.

9/ Moving through time (levels\branches\checkout-commit)

The « git checkout » command it is the most GIT important command to change the HEAD and navigate from version to version.

We have 3 commits of the project, with sometime one file, sometime two files.

First commit where the HEAD reference at start :

  • Commit message « The beginning »
  • a piggy_bank file with :
This piggy bank belongs to the big sister.
It contains 10 coins.

Second commit

  • Commit message « Little sister comes in »
  • a piggy_bank file with :
This piggy bank belongs to the big sister.
It contains 10 coins.
  • a little_sister file with :
A young girl with brown, curly hair.

Third commit :

  • Commit message « Little sister does something »
  • a piggy_bank file with :
This piggy bank belongs to the big sister.
It is empty.
  • a little_sister file with :
A young girl with brown, curly hair.
Has 10 coins.

So we understand the story and steps. Now the most important thing to understand with GIT, each commit version create has got a unique number call « chawouane ».

In my screenshot the « git log » command show the « chawouane » ddd8b8ca6fc2891c6311d3ed620d1a2acbb1b74f for the first commit (the HEAD commit)

You can also right-click on the yellow square commit symbol to paste the « chawouane » code into the terminal.

NOTE: you can use the « chawouane » short version, indeed the 7 first characters « ddd8b8c » as equal as the long version.

Now to move forward, we can enter the « git checkout » command and right-click on the next commit to paste the « chawouane » code or play the card on the next commit :

The now, the HEAD is on the second commit, we will see the second file little_sister inside this commit :

Of course, we can move to the last commit with the same method : « git checkout » command with the last « chawouane » code or again drag and drop the card on the rightest yellow square.

Then into this commit version, we will remove the « 10 coins » from the little_sister file and place the phrase « 10 coins » inside piggy_bank file (don’t forget to save file).

Then to validate this version, the command will be :

git add . ; git commit -m "Restore peace"

GIT shows several important information:

  • 2 files changes with this new commit version
  • HEAD reference move to commit « chawouane » code 67db068

10/ Make parallel commits (levels\branches\fork)

This level will let you move back and front into the timeline with « git checkout » command but you can also move backward with « git checkout HEAD^ » command. There is no move forward equivalence, you will have to use « chawouane » code.

Here the timeline of commit message to understand when something goes wrong:

So we can move back from HEAD, as proposed the command could be :

git checkout HEAD~2

Now we have to edit, cage/child file with this content :

A small child.
It's really loves cats.
It's give a lion a lollipop.

Then edit also the cage/lion file with content :

Looks very happy with a lollipop.

Now time to commit to create a new story with :

git add . ; git commit -m "Happy ending"

A new branch is created with a diferent story.

11/ Creating branches (levels\branches\branch-create)

Now we will manage the fork/branch to identify each way individually. We have 3 commits, the initial one where HEAD is placed, here is the name of other commits to understand :

We want to create a name of each branch to easily checkout from one to an other. So move to the « Go to the concert » commit with the « chawouane » code then at this place create a branch :

That will create a branch name concert reference this branch of versions :

NOTE: HEAD is not linked to the « concert » branch only on the last commit of this branch. That could be tricky as we see later. The recent version of git accept a creation and a move of the HEAD with git switch — create new_branch, but we will see later also.

Now go to the birthday branch and create it as we did :

NOTE: we can also delete the concert branch with « git branch -D concert » if needed

ADVANCED TRICK: if you really want all the commit event at the starting point of this level when you are on the first one :

git cat-file --batch-check='%(objectname) %(objecttype)' --batch-all-objects | grep 'commit$'

This command will just display all the « chawouane »code then you can loop on to display comment on :

for chawouane in $(git cat-file --batch-check='%(objectname) %(objecttype)' --batch-all-objects | grep 'commit$' | cut -f1 -d' '); do     git log --format='%s %h' -n1 $chawouane; done 

In fact the first part, will extract the « chawouane » code from commit (and not for blob or three files of git) and remove the word « commit » :

git cat-file --batch-check='%(objectname) %(objecttype)' --batch-all-objects | grep 'commit$' | cut -f1 -d' '

Then we will loop with $chavouane variable do execute on each « chawouane » code

git log --format='%s %h' -n1 $chawouane

This will display the comment and the sort version of the « chawouane » code as :

Evening preparation 2090c72
Go to the birthday  24d1d4
Got to the concert  792b42f

12/ Branches grow with you! (levels\branches\grow)

This level use the previous configuration with 2 branches « concert » and « birthday ».

Do you reminder that we have to find the « chawouane » code to move at the end of a list of commit versions, now with named branches, to go at the end of the concert, just :

git checkout concert

To win this level, just edit the you file and add one line for example : « This is great » and commit as usual :

git add . ; git commit -m "This is great"

The HEAD reference is linked to the concert branch name, so a commit on the HEAD will let move branch name also.

Then you could go to the last birthday commit but not with the branch name only on the last commit, change you file and create the new commit :

git checkout <chawouane code>

Then edit you file and commit the new project :

git add . ; git commit -m "Go to birthday party"

In this situation, our HEAD moves independently with the birthday branch name, creating a top commit not linked directly to the branch birthday.

So in the end, we can succeed the level with this kind of operation :

git checkout concert
echo "It is great to go to concert" >> you
git add . ; git commit -m "This is great"

git checkout birthday
git checkout $(git rev-parse HEAD)
echo "It is great to go to birthday party" >> you
git add . ; git commit -m "Go to birthday"

Command git rev-parse HEAD display the « chawouane » code of the commit referenced by the HEAD

To simulate an edition of the you file by adding content, we can use the following command :

echo "This is great" >> you

This example will use a detached HEAD to concert branch and explain how to managed detached HEAD

We will try something different to learn to manage an interesting case when your HEAD reference is not linked to the concert branch name :

Suppose, we use the « chawouane » code to checkout the last commit version (git checkout <chawouane code>). Then if we create a new commit with the following command :

git add . ; git commit -m "concert alternative"

There will be into this situation with an HEAD reference creating a commit not really inside de concert branch :

To correct the situation, we have to move HEAD from « concert alternative » to « concert » branch with :

git checkout concert

But now we have to move « concert » branch name and HEAD to the last commit unconnected to any branch. There is a new command using with the « chawouane » code of this lonely commit :

git reset --hard 9b58db3

NOTE: We should usually not use git reset –hard because into Oh my git software we are able to find any commit from the graphic interface. Usually, move the HEAD and the branch name on a new commit could lead to lost a whole part. Or, you could maybe use git reflog to display the list of everywhere HEAD was, but it could be long to identify links between commits.

Yes, I used the small « chawouane » code and that will modify at the end HEAD reference and branch name :

Try to avoid detach HEAD from the branch name is a classical way to work with GIT.

14/ Deleting branches (levels\branches\branch-remove)

In this level, you have to find the only way where you arrive at school and delete other branch.

To help you avoid checkout, all commit and open file to find the correct way. The correct one is just leap branch.

Just delete other branch with :

git branch -D friend
git branch -D ice-cream
git branch -D music

You can see, delete branch do not delete commit project version, you still can move HEAD to any commit with the correct « chawouane » code :

15/ Moving branches around (levels\branches\reorder)

This level will learn you to move branch name, at the begining ,the you file :

You do not have a baguette.

You do not have coffee.

You do not have a donut.

On each branch, there are one line slightly different :

  • you file from baguette branch contains « You drank coffee. »
  • you file from coffee branch contains « You ate a baguette. « 
  • you file from donut branch contains « You have a donut. « 

So let’s start with just a modification for donut branch, using command sed to change content of the file (-i operation on the same file, ‘s/have/ate/’ regular expression to substitute have a donut by ate a donut ) :

git checkout donut 
sed -i 's/have a donut/ate a donut/' you
git add . ; git commit -m "Donut eaten"

Then switch branch name with classical command, just store the initial « chawaoum » code of « coffee » branch into a chawaoum.txt (because the oh my git bash do not create variable) :

git checkout coffee
git rev-parse HEAD > chawaoum.txt
git reset --hard baguette

git checkout baguette
git reset --hard $(cat chawaoum.txt) 
rm chawaoum.txt

Ok if we can use a simple bash environment variable, we could simplefy with :

git checkout coffee
chawaoum=$(git rev-parse HEAD)
git reset --hard baguette

git checkout baguette
git reset --hard $chawaoum

This is the end of the branch part of the game, let’s move to merge catagory.

16/ Merging timelines (levels\merge\merge)

After split and move branch, we now learn to combine branches. The level start with the well-known 3 parallels situation:

  • You eat the baguette
  • You drink the coffee
  • You eat the donut (HEAD pointing here)

You can merge without branch name, but it will be more common to at first create branches. It is OK for this training to use only chawaoum code.

The structure of the you file into the initial node ( via command git checkout HEAD~2 ):

You do not have a baguette. 

You do not have coffee. 

You do not have a donut.

You understand on each way, you eat or drink something and each file will have a different line. The baguette branch will be :

You ate a baguette. 

You do not have coffee. 

You do not have a donut.

The purpose of timelines is to regularly merge two branches into a new one. Of course, we hope that each different line on each separate file will be merged.

The most simple solution is just merge all the last commit of each « branch » into the HEAD:

git merge <chawouane of 'You eat the baguette'>
git merge <chawouane of 'You drink a coffee'>

But we will try to find a « chawouane » code from the comment message of a commit. I think at first use this command but that work only into HEAD ancestror :

git log --all --oneline --grep="baguette"

We need to extract all the « chawouane » code from the git and cycle on each of them to display message, so find all « chawouane » code

git cat-file --batch-check='%(objectname) %(objecttype)' --batch-all-objects | grep 'commit$' | cut -f1 -d' '

Suppose we have a « chawouane » code we can display the message and the « chawouane » code with git log command only with the message contains baguette:

git log --format="%s %h" --grep="baguette" -n1 <chawoane code>

This will display the message (with %s) and the short chawouane code (with %h) only with baguette (with –grep) , -n1 switch is is just to avoid duplication.

Then loop on everything :

for chawouane in $(git cat-file --batch-check='%(objectname) %(objecttype)' --batch-all-objects | grep 'commit$' | cut -f1 -d' '); do 
    git log --format="%s %h"  --grep="baguette" -n1 $chawouane; done

This will display :

You buy a baguette 43e1279
You eat the baguette 6a6e2a1

Now we know which « chawouane » code is associated to the final commit message, and you see the importance of a clear and explicit commit message.

So just merge HEAD with the final commit which « chawouane » code is 6a6e2a1 :

git merge 6a6e2a1 

If you open the you file, you find the content merge with the final line changed :

You ate a baguette. 

You do not have coffee. 

You ate a donut.

Now merge with the coffee « branch » (no branch name) by finding the correct commit :

for chawouane in $(git cat-file --batch-check='%(objectname) %(objecttype)' --batch-all-objects | grep 'commit$' | cut -f1 -d' '); do 
    git log --format="%s %h"  --grep="drink.*coffee" -n1 $chawouane; done

I use again regular expression to find the commit message « drink<zero to n caracters>coffee » and then find the only « chawouane » code and merge with :

git merge fa4af5a

Then the final merged file is :

You ate a baguette. 

You drank coffee. 

You ate a donut.

The final situation with merge commit default message, a merge create a new commit :

Of course, you can set a custom message with :

git merge fa4af5a -m "Merge coffee with baguette and donut"

17/ Contradictions (levels\merge\conflict)

This level has 2 different timelines muesli and pancakes, HEAD is on the main branch. For french user, I should rename chocolatine and pain au chocolat.

The sam file will store :

  • At the beginning : « Just woke up. Is hungry. »
  • At Muesli! : « Had muesli with oats and strawberries for breakfast. »
  • At Pancakes! : « Had blueberry pancakes with maple syrup for breakfast. »
  • At Go to work: previous message plus « Is at work. »

We can not merge as we did in the previous level, the sam file will be in conflict.

At first, I need to explain something about 2 very old Linux commands, diff and patch. Suppose a 1-3.txt file with :

one 
two
three

Suppose a 0-2.txt file with :

zero
one
two

The diff command with -u for common line will be :

diff -u 0-2.txt  1-3.txt


--- 0-2.txt
+++ 1-3.txt
@@ -1,3 +1,3 @@
-zero
 one
 two
+three

Symbol minus is linked at 0-2.txt file and symbol + to the other file 1-3.txt. So we can understand the difference between two files and the common lines. If we remove the commons line and redirect to a file :

diff 0-2.txt 1-3.txt > patch-from-0-2-to-1-3.txt

We create in fact a file that the patch command could apply to patch the 0-2.txt with the same content as 1-3.txt file.

patch 0-2.txt  < patch-from-0-2-to-1-3.txt

cat 0-2.txt
one
two
three

So the GIT merging process is really similar, you can try git diff on the initial files 0-2.txt file and 1-3.txt to display the same output as diff :

diff --git a/0-2.txt b/1-3.txt
index af9184c..4cb29ea 100644
--- a/0-2.txt
+++ b/1-3.txt
@@ -1,3 +1,3 @@
-zero
 one
 two
+three

a/ and b/ are simply generic value to manage file with identical name a/sam and b/sam will be used in our future case.

So return to our case with a git diff to show difference on the unique sam file :

git diff muesli pancakes 

diff --git a/sam b/sam
--- a/sam
+++ b/sam
@@ -1,3 +1,3 @@
-Had muesli with oats and strawberries for breakfast.
+Had blueberry pancakes with maple syrup for breakfast.

So we know the conflict that will create the git merge command, now how to manage :

git checkout muesli
git merge pancakes

A message explain the conflict, we can open sam file and try to understand this weird notation :

<<<<<<<< HEAD
Had muesli with oats and strawberries for breakfast.
=======
Had blueberry pancakes with maple syrup for breakfast.
>>>>>>> pancakes

Is a work.

So the HEAD at present is equal to muesli branch then just below HEAD you could see the line in conflict into HEAD then multiples equals separate the line from pancakes branch in conflict.

At the end, the sentence « Is a work. » is common, so no conflict.

GIT ask us to manage the situation, so delete/write and replace everything as and save the file :

Had muesli with oats and strawberries and blueberry pancakes with maple syrup for breakfast.

Is a work.

Then we need to commit the merge :

git add . ; git commit -m "Muesli and pancakes"

Of course, we need to move main branch to the final muesli commit with :

git checkout main
git reset --hard muesli

NOTE: It is clearly possible to at first move the main branch to the muesli with :

git reset --hard muesli
git merge pancakes
echo "Had muesli with oats and strawberries for breakfast." > sam
echo "Had blueberry pancakes with maple syrup for breakfast." >> sam
echo "Is at work." >> sam
git add . ; git commit -m "Muesli and pancakes"

18/ Abort the merge (levels\merge\merge-abort) Optional

My Oh my git version include into the folder levels/merge/ a level not visible by default, you have to edit the sequence file into this folder, then add merge-abort at the end of this file and restart the program.

This level is just to checkout to a « Main Lane » commit or to « Side Lane » commit then try to merge but a the end just cancel the operation with :

git merge --abort

This situation is just to understand how to undo the git merge in conflict :

You can use the previous level : Contradictions to undo the merge conflict with :

git checkout muesli
git merge pancakes
cat sam
git merge --abort

This will cancel the merge. Now a new category : index.

19/ Step by step (levels\index\conflict)

The next level will go deeper into GIT command :

But in fact, I think there is a problem with this exercise, to win we have to change the content of smoke_detector file into step-by-step branch, remove « absolutely silent » and create a new commit.

git checkout step-by-step
sed -i 's/absolutely silent/absolutely noisy/' smoke_detector
git add . ; git commit -m "remove silent"

I think the purpose is to show several commits with step-by-step branch is better than the short lonely commit with all-at-once branch.

20/ Add new files to the index (levels\index\new)

The next level will learn how to add a file to the initial HEAD main. You can also find the label refs/heads/main, in fact into the hidden .git folder, a subfolder named refs store all references include branches, tags and all heads, the subfolder heads will store heads and branches names, then a file main. This file store the commit chawouane code.

This level contains only one candle file, so add it to the index and commit :

git add candle
git commit -m "Initial commit"

We can look into the .git folder, with command to see the content of file. But Git provides tools to manage some troubles, so we will use then on this basic sample. Restart the whole level and at first we will find the content of the folder .git/objects/ with this command :

ls .git/objects/

So the output, will display only two folders : info and pack. Then just git add candle and list again the folder

ls .git/objects/
pack
info
70

The new folder 70 will store the content of our candle file so we can output the ls content of this 70 folder into a candle_code.txt file with (note the folder name ) :

ls .git/objects/70/ > candle_code.txt

So now open the candle_code.txt file to discover the « chawouane » code of our file in my case 47e0416f37d1ce42a87358f2d7aa2aeb443af3 that can copy. So now I can open a content file with the concatenation of folder name (70) and the « chawouane » (47e0416f37d1ce42a87358f2d7aa2aeb443af3 ):

git cat-file -p 7047e0416f37d1ce42a87358f2d7aa2aeb443af3 

This will display the content of the candle file.

NOTE: you can think to add any files and folder from the root git file with :

git add :/

21/ Update files in the index (levels\index\change)

The next exercise is to index the candle file with a simple modificaiton change the color blue into yellow :

sed -i 's/blue/yellow/' candle
git add candle
git commit -m "Initial commit"

22/ Resetting files in the index (levels\index\reset)

This level works with 3 files : blue_candle, green_candle and red_candle contains at first « It’s burning! » then into the second commit « It’s been blown out. ».

From the beginning, we used to follow files states from commit to commit. But suppose, we work on blue_candle and green_candle adding information :

echo "The small rope (the wick) of the candle is red" >> blue_candle
echo "The small rope (the wick) of the candle is red" >> green_candle

Now we want to come back to the last commit, but we are AT the last commit, so git checkout HEAD could not work, but we can restore files :

git restore blue_candle green_candle

But sometime, you want to keep the content of your working project folder but go back to a previous commit version, so let’s start again same level :

echo "The small rope (the wick) of the candle is red" >> blue_candle
echo "The small rope (the wick) of the candle is red" >> green_candle
git add . ; git commit -m "Blue and green candle wicks are red"
git reset HEAD^

This situation will be as a « move backward » into history of commits (green arrow) but if you open blue_candle and green_candle files, you fill find the new line about the wick.

The git reset command work only on branches and HEAD index and preserve file content.

But we work only on the full project files, the level asks us to only preserve some files. Suppose a modification on red_candle, blue_candle and green_candle files :

echo "The small rope (the wick) of the candle is red" >> blue_candle
echo "The small rope (the wick) of the candle is red" >> green_candle
echo "The small rope (the wick) of the candle is red" >> red_candle
git reset green_candle blue_candle
git add red_candle; git commit -m "Only red candle will versionning"

But now move to the previous commit with git checkout HEAD^ :

cat blue_candle 

It's been blown out.
The small rope (the wick) of the candle is red


cat red_candle

It's burning.


cat green_candle
It's been blown out.
The small rope (the wick) of the candle is red

So even if we move back into the commit history, we still have unsupervised blue_candle and green_candle files, which still the same content.

This is a situation, you work on a new feature and change all the 3 candles files, but the feature is canceled, and you want to go back and keep the blue_candle and green_candle files content.

As you can see, the git reset remove the commit supervision on a file, red_candle file still supervised and its contain history could be checkout.

To solve the level, just again :

echo "The small rope (the wick) of the candle is red" >> blue_candle
echo "The small rope (the wick) of the candle is red" >> green_candle
echo "The small rope (the wick) of the candle is red" >> red_candle
git reset green_candle blue_candle
git add red_candle; git commit -m "Only red candle will versionning"

If you want to restore un-hide blue_candle and green_candle file , you can restore them with a basic git checkout HEAD^, you will see only the red_candle version of file is changed.

NOTE: to understand the git reset and the git checkout difference, please read the Stackoverflow content and study the diagram below :

By my way :

  • git reset –hard HEAD~3 : move the HEAD/master flag to 3 commits in the past, the working directory is from b325c, so it is git checkout HEAD~3 and move HEAD/master flag a true time machine.
  • git reset HEAD~3 : same but also the list of managed/supervision files by git, so the working directory is from ed489 commit, but the list of files will be from b325c. So if you add a new file between c10b9 and ed489, the tracking by git into its index will be forgotten but the new file still exist
  • git reset –soft HEAD~3: just keep the file from ed489 and keep the list of managed/supervision files by git from ed489 including a new file creates from c10b9 and ed489
  • git reset file: this command reverse gid add file, should replace by git restore –staged file
  • git reset –keep file: should be used instead of git reset –hard because preserve the working directory from ed489
  • git reset –merge file: same of keep but also preserve not supervised file

If you want the list of managed/supervised files use on main branch :

git ls-tree -r main --name-only

NOTE: suppose your work on many files in a commit, and you want to reset to the initial situation, git reset –hard HEAD will cancel everything for this commit.

23/ Adding changes step by step (levels\index\steps)

This level contains 3 files :

  • hammer file : « A hammer, balancing on its handle. »
  • bottle : « A bottle, containing a clear liquid. »
  • sugar_white : « A white sugar cube. »

In fact, our story misses several element included a candle_added file

echo "A candle burns the rope" > candle_added
echo "Hammer smashes the bottle" >> hammer
echo "Bottle explodes" >> bottle
echo "The sugar melts" >> sugar_cube
 
git add candle_added
git commit -m "First accident"


echo "The hammer explodes the windows " >> hammer
git add hammer
git commit -m "Second accident"

echo "The candle burns the carpet" >> candle_added
git add candle_added
git commit -m "Third accident"

But if you git checkout HEAD~2 (commit message is First accident), you will not find « Hammer smatchs the bottle » into the hammer file :

A hammer, balancing on its handle.

But you find inside the next commit :

git checkout main 
git checkout HEAD^
cat hammer 

A hammer, balancing on its handle. 
Hammer smatchs the bottle
The hammer exploses the windows

The content of the file is not stores if you do not specify it each time with a git add command.

NOTE: Usually it is really common to add everything with git add . command to be sure to avoid different version control of file with index of git.

The new catagory will be remotes.

24/ Friend (levels\remotes\friend)

In this level, we find out again a remote friend repository as GitHub server.

Always start with a git pull command if you work with a friend who add regularly content.

git pull 

cat essay 

Line 1
Line 2, gnihihi

We need to correct the file and add a third line :

echo "Line 3," >> essay
git add . ; git commit -m "3 lines"
git push 

Now the program will simulate a friend adding a fourth line, so :

git pull

cat essay 

Line 1
Line 2, gnihihi
Line 3,
Line 4, blurbblubb

Add content and push again:

echo "Line 5," >> essay
git add . ; git commit -m "5 lines"
git push 

You are lucky, you friend and you are not working on the same line of the same file.

25/ Problems (levels\remotes\problems)

There are two ways to manage this level:

  • First option, you are supposed to finish edit the file and want to commit your new version
  • Second option, start with a « git pull » before commit your work.

Let’s start with the first option, we are supposed to be in a middle of modification and change the file content from « The bike shed should be ??? » to your proposal : « The bike shed should green ».

So at first, create a commit of your version with :

git add . ; git commit -m "green"

Then you can try to push :

git push 

But, you have got an error because, your local branch call friend/main is not update, so now :

git pull

So our local main branch and our local friend/main branch are in conflict. A git pull included a git merge command, so you have a try to merge from the local version to your version.

You can compare from your version with git diff command :

git diff main:file friend/main:file

diff --git a/file b/file
index 076b9c8..60823c8 100644
--- a/file
+++ b/file
@@ -1 +1 @@
-The bike shed should be green
+The bike shed should be blue

Or of course open the file :

<<<<<<< HEAD
The bike shed should be green
=======
The bike shed should be blue
>>>>>>> fb733ac9b8d350147249588e849c4686b85c6a78

Now, it is not technical, it is a compromise with your friend to yellow :

echo "The bike shed should be yellow" > file

Then commit this new version :

git add . ; git commit -m "yellow"

The git push to upload your proposal and the compromise :

git push 

You can see there are all the proposal, your friend says blue, you say green and the final version is yellow. But you can also imagine going back because blue is OK.

Restart the level to try the second option. When you work with someone, you can at first get the latest version from the remote repository with :

git pull

And then, you know the local friend/main version is different of your working version.

You can compare the last commit file content from main branch to the remote friend/main branch with :

git diff main:file friend/main:file
diff --git a/file b/file
index 076b9c8..60823c8 100644
--- a/file
+++ b/file
@@ -1 +1 @@
-The bike shed should be ???
+The bike shed should be blue

So change yellow to your color :

sed -i 's/green/yellow/' file
git add . ; git commit -m "yellow"
git merge friend/main

At this moment, the conflict about bike color appear :

cat file 
<<<<<<< HEAD
The bike shed should be yellow
=======
The bike shed should be blue
>>>>>>> 9e15575465664addhbsjdsbhjqbsdhjdsq

Now we have to set our color, so edit the conflict file as you which, merge and push to the server :

echo "The bike shed should you be yellow" > file
git add . ; git commit -m "yellow"
git push 

Now new category changing-the-past :

26/ Rebasing (levels\changing-the-past\rebase)

At the beginning, you file is close to lesson 16 with coffee, donut and baguette branch name :

You do not have a baguette. 

You do not have coffee. 

You do not have a donut.

On each branch, you eat or drink the corresponding element, but in this level we DO NOT want to merge. This is what we do NOT want to do :

The git rebase command will try to merge but on the same HEAD branch, suppose we check out to donut branch and rebase with branch coffeee, the situation will be :

git checkout donut
git rebase coffee

The donut branch is added to the coffee branch, adding content inside and of course the you file content is :

You do not have a baguette.

You drank coffee

You ate donut.

Again, git checkout and git rebase with baguette branch, to create one big donut or baguette branch with you file :

You ate a baguette.

You drank coffee

You ate donut.

Now, 2 ways to correct other branch names:

  • create a final branch name, return to main commit and rebase it : git branch final ; git checkout main ; git rebase donut;
  • Rename the main branch as the new branch: git branch final; git checkout main; git branch –move main initial; git checkout final; git branch main;
  • Or move the main branch at the beginning as the future commit branch with git checkout main ; git reset –hard donut

27/ Reordering events (levels\changing-the-past\reorder)

This level is to learn how to use git cherry-pick command or git rebase -i command. The you file at the main branch commit contains :

You just woke up.

You are wearing underwear.

You are wearing pants. 

You are wearing a shirt.

You are wearing shoes. 

But the trouble is more with the commit order :

We are supposed to start with underwear then pants then shoes (shirt is not checked).

As explain, you can use git cherry-pick command with list of command and use the notation branch name~# to identify easily the order :

  • main~1 : Put on underwear
  • main~2: Put on pants
  • main~3: Put on shoes
  • main: Put on shirt
git checkout HEAD~4
git cherry-pick main~1
git cherry-pick main~2
git cherry-pick main
git cherry-pick main~3
git branch main-correct-order
git checkout main; git reset --hard  main-correct-order

The final solution creates a copy of each commit into a separate branch and move at the end the main branch name to the new created main-correct-order branch name.

IS like if we copy/paste from on commit to another commit on a separate branch, just a the end we move the branch main and abandon the old one.

NOTE: to use the second version, Oh-my-git software misses somes setting, so we have to open the folder from outisde of the software with a git command. At first find the location on your drive of the correct folder with pwd command. in my case, it will be into the following folder:

C:\Users\pierre.jean\AppData\Roaming\Oh My Git\tmp\repos\yours

Then check the git log classical command with :

"C:\Program Files\Git\cmd\git.exe" log --oneline --graph --all --decorate

So you can work outside of the Oh-my-git software to manage additional operations.

Option number 2, use git rebase -i to open a file contains the list of operation so again, same starting point :

So our command will start on the very first commit to restart from scratch :

git rebase HEAD~4 -i 

This command will display an editor to manage the content, you will see (chawaouan numbers are difference) the following content and remeber each line starting with # is a comment :

pick 044e7b9 Put on shoes
pick b4fcfbe Put on pants
pick 22446fb Put on underwear
pick 8f8d77c Put on shirt

# Rebase instructions ... 

Just change the order from top to bottom as following example :

pick 22446fb Put on underwear
pick b4fcfbe Put on pants
pick 044e7b9 Put on shoes
pick 8f8d77c Put on shirt

Force update of Oh-my-git with a git log command and then you will have (without branch name main-correct-order) :

You can read instructions into the interactive editor of git rebase to learn how to change commits.

NOTE: instead of moving the main reference with git reset –hard, you can rename the branch with :

git branch -m main incorrect-order-main
git branch -m inccorrect-order main

Then a new category sh**-happens

28/ Restore a deleted file (levels\shit-happens\restore-a-file)

This level is really easy now you know git, just git restore essay to reload file from the last commit.

29/ Restore a file from the past (levels\shit-happens\restore-a-file-from-the-past)

This level is really easy now you know git, several way to reload file from the first commit.

You can also :

  • git checkout HEAD^ essay; git add essay; git commit -m « Rescue good version »
  • git checkout HEAD^ — essay ; git add essay; git commit -m « Rescue good version »
  • git checkout HEAD^ ; git branch rescue ; git checkout rescue; git checkout main; git reset –hard rescue
  • git branch -m main main_bad ; git checkout HEAD^ ; git branch main
  • git reset –hard HEAD~1
  • git reset –hard HEAD^

The first version is to rescue from the previous version the file into the actual working directory then add this version to the index then commit. The double dash — is to manage this example working with a file named main : git checkout — main will work.

The third version is go back into the past, create a new branch called rescue, then replace the flag main on the same rescue branch.

The fourth version is the best, rename the branch from main to main_bad then go back and create a new branch call main.

Fifth and sith versions are lightly worse but use the git reset –hard trick to move the reference main and HEAD on another commit.

30/ Undo a bad commit (levels\shit-happens\bad-commit)

In this level, the numbers file into the actual commit contains :

1 2 3 4 5 6 7 8 9 11

The last commit contains a typo « More numberrrrrs ». We want to preserve the numbers file content from the last commit, but we want to go back to the previous commit to start over to a next commit.

To go back preserve the file content with git reset HEAD^:

The solution would be git reset the previous commit, then correct the numbers file and at the end create a new commit :

git reset HEAD^ 
sed -i 's/11/10/' numbers
git commit -a -m "More numbers"

This example used a switch -a to automatically « git add » any previous file already follow by GIT. Many times we used git add . command to let know to GIT any new files into the current folder. I could be important to keep a git add <list of file or folder> command to be precise into the list of files and folder supervised by GIT. But if you know that you will work all the time with the same list of files, that could be better to use -a -m or -am switches.

31/ I pushed something broken (levels\shit-happens\pushed-something-broken)

In this level, a local and a team repository are used with 4 commits and only on text file.

  • First commit with message « fine » : file contains « this is fine » and empty line, new line with question mark and empty line, new line with question mark, and empty line, new line with question mark ( so 4 individual questions marks with an empty line previsouly)
  • Second commit with message « also fine »: same contains of the previous commit file, but the first question mark is replaced by « this is also fine »
  • Third commit with message « very bad » : same contains of the previous commit file but the next avalaible question mark is substitute by « this is very bad »
  • Final commit with message « fine again », the text file contains :
this is fine 

also fine

this is very bad

this is fine again

So we want to undo only the modification into text file the line with « this is very bad », we want the following file :

this is fine 

also fine

?

this is fine again

The reverse of the merge processing will be :

git revert --no-edit HEAD~1 

The option –no-edit avoid to open the interactive editor and create a new commit with the modification :

So now the text file is reverted as and you just push to the team repository.

We do not have on the git revert command line the option -m to edit the commit message (-m switch is for something different), but we can change the commit message with :

git commit --amend -m "Change the line 'very bad' into ? "

This will create a new commit with the new message « Change the line ‘very bad’ into ? « . If you do not push already to the team repository, you can go on with a simple git push. But if you did this scenario :

git revert --no-edit HEAD~1 
git push 
git commit --amend -m "Change the line 'very bad' into ? "

You are working into a previous version of the project but because this last commit is just a light « amend » commit, you can force the team repository with git push –force.

The « wrong message » commit is an orphan without impact but avoid to force for other users.

32/ Go back to where you were before (levels\shit-happens\reflog)

This level contains a very long list of commits (10 commits) and each commit has a diffrent branch name (same number) but no file :

The git reflog command just shows the list of the previous position of the HEAD :

git reflog 

d087659 (HEAD -> main, 10) HEAD@{0}: checkout: moving from 3 to main
64ef148 (3) HEAD@{1}: checkout: moving from main to 3
d087659 (HEAD -> main, 10 HEAD@{2}: commit:10
9ea5730 (9) HEAD@{3}: commit: 9
411e7a1 (8) HEAD@{4}: commit: 8
b7a475f (7) HEAD@{5}: commit: 7
a464650 (6) HEAD@{6}: commit: 6
75c829d (5) HEAD@{7}: commit: 5
64ef148 (4) HEAD@{8}: commit: 4
c372d04 (3) HEAD@{9}: commit: 3
046a26a (2) HEAD@{10}: commit: 2
75c829d (1) HEAD@{11}: commit (initial): 1

We have the history of operation on the HEAD reference, so just git checkout 3 to return to the commit reference by the « 3 » branch name as shows at the first line. You can also :

git HEAD@{1}

If you open the file levels\shit-happens\reflog into the software installation folder, you will find the list of operation to create the level into [setup] category :

[setup]

for i in {1..10}; do
    git commit --allow-empty -m $i
    git branch $i
done
git checkout 3
git checkout main

The setup will create from 1 to 10 commit, git checkout 3 to finish the level.

The next category is workflows.

33/ Cloning a repo (levels\workflows\pr)

This level is quite simple but include one important feature, cloning someone else repository.

But this level supposes that you can access to the repository directly from your hard drive. This is not the common situation, usually you access remotely to someone repository.

I try to copy everything (including .git folder) from the friend project folder, and it’s works until you have to send back to your friend modifications. The only option will be to erase everything I work to put your folder. This is not a very collaborative way.

The git clone will keep the link between the 2 repositories and will manage exchange. The clone will be from one folder ../friend to your actual folder ./ as a copy but link to update from and to each folder.

git clone ../friend ./

You can see origin/main and origin/HEAD into your git projet. The word origin symbolize this initial git folder from the clone folder was created .

Now we can correct the file content, commit into your folder and create a separate branch.

sed -i 's/= /= 5/' file
git commit -am "Solution is 5"
git branch "solution"

This lesson needs a final command, that could be uses sometime just to make a kind of label associated to a commit. This is not a branch, just a label to symbolize a very important commit as a milestone of your project.

git tag pr

It could also be possible to push a tag remotely :

git push origin v1.0.0

NOTE: One additional lesson exists into the levels/workflows to manage .gitignore file, this lesson is just to add a chicken file into the .gitignore file. Then git add . command will ignore this file, that classical to avoid to import temporary generated files as .class .so, etc.

Next category will be bisect.

34/Yellow brick road (levels\bisect\bisect)

This level show 30 commits on the main branch with HEAD on the final commit. Each commit message is a number from 1 to 30 include a

Commits from 1 to 11 include a you file contains : « You still have your key. »

12th commit include 2 files :

  • you file contains : « Your pocket is empty. »
  • key file contains : « Is on the ground. »

13th commit include 2 files:

  • you file contains : « Your pocket is empty. »
  • bird file contains : « Is holding a key i its beak. »

Commits from 14 to 30 include a you file contains : « Your pocket is empty. »

We can image go front and back until finding the moment when something « wrong happen » that the mechanism includes into git.

Let suppose we know something bad happen at the 20th commit, so we want to start searching by bijection from there:

git checkout HEAD~10
git bisect start

Now we declare this git commit as bad with :

git bisect bad

Then we will go to 10th commit because we remember this commit is OK.

git checkout HEAD~10
git bisect good

The command git bisect good will check out to 15th commit in the middle between 20th commit and 10th commit. We see the actual HEAD between the 10th and 20th commits.

So the 15th commit the you file contains : « Your pocket is empty. », so we enter git bisect bad and check out another version :

We can see the new refs/bisect/bad label is now on the 15th commit, not on the 20th commit.

The 12th commit is not event good the you file contains « Your pocket is empty. » so git bisect bad command again.

We are on the 11th git commit with a valid you file contains « You still have your key. »

Now we can move the main branch name to this commit, but we have threes options to mark the good place (because we will not easily use the generated name from the git bisect good (refs/bisect/good-04448cd8cd7cd614cd7f42635959946f9946270)).

We will create a new branch named main-key-is-ok (with option -b to attach HEAD to this new created branch), then rename main branch as main-lost-key and rename main-key-is-ok as main :

git checkout -b main-key-is-ok

git branch -m main main-lost-key
git branch -m main-key-is-ok  main

or we can use the new git switch –create main-key-is-ok to create a new branch and place HEAD on and I the end I will use it again to keep two branch main and main-key-is-ok for historical information

git switch --create main-key-is-ok
git branch -m main main-lost-key
git switch --create main

or we can use a tag to flag the position with :

git tag key-into-pocket
git branch -m main main-lost-key
git switch --create main

If you do not want to preserve the main branch, you can just move the main and HEAD with git reset –hard using the reference

git checkout main 
git reset --hard refs/bisect/bad~1

or before return the HEAD to the main branch :

git tag key-into-pocket
git checkout main
git reset --hard key-into-pocket

Next category is « stash »

35/Stashing (levels\stash\stash)

This level begin to let you use the concept of stash, you can imagine that you start from initial commit and work on files, but you are far from the moment you want to commit. You have to think that commit with a project into a team could trigger deployment and unit test, so you do not commit often.

You have a recipe file with the following content :

Apple Pie:
- 4 Apples
- 500g Flour

Add a new line like :

Apple Pie:
- 4 Apples
- 500g Flour
- Secret ingredient

The command, git stash push, will create two temporaries commits to let you work on something different.

The important element is the HEAD on the main branch contains only recipe file with the following content as the initial commit was created:

Apple Pie:
- 4 Apples

You can use the git stash command as well

36/Pop from Stash (levels\stash\stash-pop)

The next level works with the previous example (without the secret ingredient line).

The git stash pop command is just the « undo » from git to reverse the situation to the initial one but preserve commits create to temporary stash.

The git stash apply command will just keep the branch reference of the stash in case of need:

You can remove the stash with git stash drop command to keep the initial situation ( the green area is supposed to be black to hide the previous refs/stash temporary branch):

37/Clear the Stash (levels\stash\stash-clear)

If you have so many stashes, you can list then, clear them or clear one :

  • git stash list: to list all stashes
  • git stash clear: to clear all stashes
  • git stash drop : this command must be follow with the stash id stash@{0} for the last one, stash@{1} for the previous, etc

I think it is better to preserve one stash and avoir this situation.

38/Branch from stash (levels\stash\stash-branch)

A more common situation is to transform a stash commit into a new alternative branch to go on with :

git stash branch alternative

39/Merging popped stash (levels\stash\stash-merge)

A classical situation, you want to merge content from the recipe main branch commit and the recipe main into the stash commit :

The git stash pop command will create a conflict into the recipe file :

Apple Pie: 
- 4 Apples
<<<<<<<<< Updated upstream
- Pinch of Salt
========
- 500g Flour
>>>>>>>>>> Stashed changes

Just edit the file to correct the situation, as for example :

Apple Pie: 
- 4 Apples
- Pinch of Salt
- 500g Flour

The following command will create a classical situation:

 git add . ; git commit -m "Include salt and flour"

Do not forget to clear the stash with git stash drop command.

The next category will work with tags.

40/Creating tags (levels\tags\add-tag)

This level is just to create a tag with the classical git command. The feature-list file contains :

Adding feature 1
Adding feature 2
Adding feature 3
git tag v3

I suggest creating a tag to indicate version is 3

41/Removing tags (levels\tags\remove-tag)

The next level contains 3 tags to remove as :

git tag -d v1
git tag -d v2
git tag -d v3

42/Tagging later (levels\tags\add-tag-later)

This level is just to understand that you can tag previous commit into the history of commit with :

git tag v1 HEAD~1

43/Remote Tags (levels\tags\add-tag-later)

This level manage to push your tag that are not usually suppose to be share (branches are supposed), but this is the initial situation :

If you create on local HEAD a new tag v2 you can share with the remote friend repository :

git tag v2
git push friend v2

Then you can delete it remotely :

git push friend --delete v2

You can also rescue the v1 tag from friend repository with :

git fetch friend 

If you wan to delete you local tags if there are not into your friend repository :

git fetch friend --prune --prune-tags

The next category is sandbox.

44/ Sandbox (levels\sandbox\)

There are 3 levels without goals just to work on git with 3 differents situations. Name of exercises are explicit :

  • Empty sandbox
  • Sandbox with a remote
  • Sandbox with three commits

Do not forget you can add your own exercice into Oh my git a very good tool to create situation to learn git.


Using Github with Oh-My-git

The Oh-my-git software is design to train you using git on your computer, but you can manage to let it works with the GitHub.com website. Github is not the only website providing git server storage, Gitlab software could be installed, Amazon, Sourcesup (Renater), Bitbucket, etc. provide also git server storage.

At first, you have to create a Github account, then open You Menu > « settings » > Developer settings > Personal access tokens > Tokens (classic) or just follow https://github.com/settings/tokens , then « Generate a personal access token » :

Then you can provide a name of this token, give an expiration date (not perpetual), give right at least on repo rights and press the bottom button « Generate token » :

Then you have to copy the generated token, please be sure to copy the token because there is no way to give you back this one. If you lost it, you have to create a new one.

Github website provides the basic start we need on the first page you see after login creation.

At first, create a new private repository to practice :

Then you have the quick setup listing commands to Oh-my-git could use with the token modification :

Let’s start to use GitHub with Oh-My-git, open the « Empty sandbox » level and delete the initial configuration :

rm -rf .git 

Then you can enter the quick setup commands, except adding your token into the URL :

echo "# hello1" >> README.md
git init
git add . ; git commit -m "First commit"
git branch -M main
git remote add origin https://<token>@github.com/pierrejean/hello1.git
git push -u origin main

This will create the README.md file into your Github repository.

More important information about remote connection :

The following command creates an alias origin to link git push command to a server :

git remote add origin https://<token>@github.com/pierrejean/hello1.git

We saw the remote repository as friend or teacher in previous levels:

git remote add friend https://<token>@github.com/pierrejean/hello1.git

If you want to change the URL to use origin as classical alias, the command is :

git remote set-url origin https://<token>@github.com/pierrejean/hello2.git

In fact, Oh-Myt-git do not provide a secure way to login/password from https/ssh default solution with Git/GitHub so using a token is a simple solution also for integration but keep the token as safe and secret as any password.

But please add default user and email for your local account :

git config --global user.name "pierrejean"
git config --global user.email "pierre.jean@mines-ales.fr"

You can create prefill a new github repository from your browser with this URL :

https://<token>@github.com/new?name=hello2&owner=pierrejean&visibility=private

More stuff

After train with Oh-my-git, you should use a more advanced tool to work with Git as GitHub Desktop, Git Kraken, IDE plugin for git, but it is important to know what GIT commands do.

But if you want to display into the terminal as close as Oh my git, you could use this command :

git log --oneline --graph --all --decorate

To output branches, commits, commits messages in parentheses, tags (here all version vX ), etc.

* 2a6cf7f (deadend) v6
* 06c61e4 (HEAD -> main) v5
| * b8b1318 (alternative) v4
|/
*   1fe4f31 v3
|\
| * 7dc37f1 (first) v2
* | 58d7bb0 v2.a
|/
* 598c50e v1

You can add color, date of commit and email with

To avoid to all the time call git log with all options, you can create an alias with :

git config --global alias.lg "log --oneline --all --decorate --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%ae>%Creset' --abbrev-commit"

The new git lg command will produce :

* 2a6cf7f (deadend) v6 (19 hours ago) <pierre.jean@mines-ales.fr>

Two more stuff

You can add one file or one folder with git add . or git add README.md or you can :

git add :/

This will add all file from the top folder where you enter git init command.

And more important, two commands to compare difference on one file, suppose one file equipe1.txt file, one version is :

Equipe1
********

The other version is :

Equipe1
------

The classical conflict will show :

Equipe1
<<<<<<< HEAD
**********
=======
-------
>>>>>>> 50b69dcb7523fbe3e051e695ae5f3ffb21068013

To show difference on the HEAD and the 50b69dc, I can :

git diff HEAD 50b69dc .\equipe1.txt

to show difference :

diff --git a/equipe1.txt b/equipe1.txt
index c62584c..8856277 100644
--- a/equipe1.txt
+++ b/equipe1.txt
@@ -1,2 +1,2 @@
 Equipe1
-**********
+-------

Or we can use a word difference on the same line to display more nicely :

git diff --word-diff=color HEAD 50b69dc .\equipe1.txt

Then on the same line difference are visible :

diff --git a/equipe1.txt b/equipe1.txt
index c62584c..8856277 100644
--- a/equipe1.txt
+++ b/equipe1.txt
@@ -1,2 +1,2 @@
 Equipe1
**********-------

We can see the difference more easily, but a better way is to show in parallel :

 git difftool -y -x sdiff HEAD 50b69dc .\equipe1.txt

To display just side by side difference :

Equipe1                      Equipe1
**********                  | -------

Evolution of git with git switch

The initial git checkout command covers so many different operations that git try to create new commands that cover some as an alternative. This link provides some corresponding conversion: https://stackoverflow.com/questions/57265785/whats-the-difference-between-git-switch-and-git-checkout-branch

Mainly, you can understand :

git initial commandnew git alternative command
git branch new_branch && git checkout new_branchgit switch –create new_branch
git checkout — <file>git restore — <file>
Publié dans Blog, Développement | Laisser un commentaire

Master m-Rehab

Cliquer pour télécharger la présentation du cours

Installation des logiciels :

NOTE Mysql installation avec Windows:

  • Windows 64-bit, ZIP Archive puis ne pas « créer de compte » juste « No thanks, just start my download. »
  • Installation si nécessaire de « Redistribuable Visual C++ pour Visual Studio 2012 » fichiers vcredist_x64.exe et vcredist_x86.exe depuis https://www.microsoft.com/fr-fr/download/details.aspx?id=30679
  • En cas de soucis, possibilité d’installer MAMP : https://www.mamp.info/en/downloads/

Accès aux fichiers pour TP

Liens vers le fichier SQL ci-dessous pour importation dans une base de données :


Accès à la base de données depuis R

install.packages("RMySQL")
library(RMySQL)

L’accès à un serveur de base de données Mysql suppose plusieurs informations techniques, l’adresse du serveur de base de données (ici 127.0.0.1), un compte sur cette base de données (ici root), un mot de passe correspondant à ce compte (ici «  » pour indiquer mot de passe vide), un port de base de données (ici et par défaut 3306 mais sur Mamp cela peut être 8889) et enfin une base de données (ici sante)

DB <- dbConnect(MySQL(), user="root", host="127.0.0.1", password="",dbname="sante" , port=3306)

Une fois la connexion réalisée, on peut lister les tables dans cette base de données sante.

dbListTables(DB)

Et enfin poser des questions en SQL

resultat <- dbGetQuery(DB, "SELECT * FROM data")
print( resultat )

Importation en CSV

La première étape est de trouver le dossier dans lequel Mysql accepte l’importation d’un fichier CSV, la requête SQL est la suivante :

SHOW VARIABLES LIKE "secure_file_priv"
Dossier Mysql autorisé pour importation de fichier CSV

Dans mon cas le dossier est dans c:\Developpement\Wamp64\tmp\ du coup je peux placer mon fichier analyse.csv dans ce dossier et lancé cette requête SQL après avoir créé la table analyse :

LOAD DATA INFILE 'c:/Developpement/wamp64/tmp/analyse.csv' 
INTO TABLE analyse 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 ROWS;

Publié dans Médecine | Laisser un commentaire