The Programmation Notes
in this book
, i will store my notes
and snippets
of my learning programmation languages, in:
Basics
clc % clear command window
clear % clear memory
; % no result displayed if command is terminated with semikolon
3.1 Comments
% Single Comment
%{
multi
line
comment!
%}
% MATRICES / VECTORS
ones(3,4) generate 3x4 matrix filled with ones
zeros(3,4) generate 3x4 matrix filled with zeros
m = [1,2 ; 3,4]
[1 2]
[3 4]
m[1,2] get value of 1st row, 2nd column of matrix m
m[2,:] generates a vector with values of 2nd row
v = 1:5 generate vector v = [1 2 3 4 5]
numel(x) counts number of elements in x (works for vectors & matrix)
COMMENTS
% code on current line will be ignored
%% new comment-section
CONSTANTS
pi Pi
exp(1) e^1 (Eulersche Zahl)
FUNCTIONS (anonymous)
name =@(x) x^2; define function name=x^2 with x as input
name(2); computes functionvalue of function name at x=2
name2 =@(a,b) a^2 + b^2; define function f=a^2+b^2 with a and b as input
name2(2,3); computes functionvalue of function name2 at 2
IMPLIZIT PLOTS!
ezplot('x.^3 + x.*y + y.^2 - 36',[-10 10 -10 10]);
[x,fval] = fminsearch(@(x) x(1).^2 + x(2).^2, [2 1])
WRITE TO CONSOLE
fprintf('message with %s', 'asd');
disp('message with asd');
ERROR MESSAGE IN RED
fprintf(2,'my error(warning) message in RED!\n' );
CELLS
C = cell(3,1); % initialize cellarray (3x1)
C(1) = cellstr('test1'); % convert string to cellarray
C(3) = cellstr('test2'); % convert string to cellarray
disp(C); % display cellarray (1 empty value)
disp(C(~cellfun('isempty',C)) % delete empty entries
% convert cell to string
C = cell({'t1','t2',''}); % generate cell
str1 = char(C(1)); % convert 1st element of cell-array
str2 = char(C(2)); % convert 2nd element of cell-array
str3 = char(C(3)); % empty 1-by-0 matrix
2.2 Clearing Data
clc % Clear command window (does not clear variables)
clf % Clear figures
clear % Clear everything
clear all % Clear everything
clear <variable> % Clear single variable
2.3 Configure Output
format compact % Keeps output compact!
2.4 Stop Execution
Use CTRL-c
to stop executing a particular command!
2.5 Precision
Precision is set to 15 digits by default. But you can configure that!
3. Basic MATLAB Syntax Reference
Click on New Script to start creating a new script!
3.1 Comments
% Single Comment
%{
multi
line
comment!
%}
You can also use CTRL-r
to comment and CTRL-t
to uncomment!
3.2 Variables
Everything is a double
by default in MATLAB.
a = 5 % a is now 5! Yay!
Data Types:
- int8, int16, int32, int64
- char
- logical (Booleans)
- double
- single (Value without a decimal place)
- uint8
More On Variables
c1 = 'A'
class(c1) % Prints the class/type of the variable!
s1 = 'A string'
class(s1) % With single quotes, the class is 'char'
s2 = "A string"
class(s2) % With double quotes, the class is 'string'
5 > 2 % Logical 1
b1 = true % Logical 1
To get the maximum number you can store, you can use these! The maximum and minimums differ depending on the number type. The example list I'm writing below is non-exhaustive.
% For ints
intmax('int8')
intmin('int8')
% For doubles
realmax
% For singles
realmax('single')
3.3 Basic Operations
I really shouldn't need to explain this... You can use MATLAB like a calculator, and the results can go into variables!
a = 1 + 2 + 3 + 4 + 5
5 + 5 % Add
5 - 5 % Subtract
5 * 5 % Multiply
5 / 5 % Divide
5 ^ 4 % Exponent
mod(5, 4) % Mod (get remainder)
% NOTE! MATLAB doesn't have increment and decrement operators. So you can't do stuff like a++, b--, etc.
3.4 Casting
v2 = 8
v3 = int8(v2) % Like so!
Just write the appropriate class identifier and use it like a function!
3.5 Printing and Displaying
% Use this to display vectors and numbers!
disp(some_vector_variable)
% Use this to print strings!
fprintf("Hello world!")
% sprintf prints as a string
sprintf('5 + 4 = %d\n', 5 + 4)
% With the %d here, it transplants the next variable argument into the string!
3.6 User Input
Using the ;
suppresses the input printout after the user has entered the input!
Note:
"
might not work in some versions of MATLAB as a string delineator. Use'
in that case.
String Input
% String Input
% Notice the '' escapes the second quote
name = input('What''s your name : ', 's');
% Let's use this if statement to print the input out! (~ means not)
if ~isempty(name)
fprinf('Hello %s\n', name)
end
Vector Input
vInput = input('Enter a vector : ');
disp(vInput)
3.7 Useful Math Functions
help elfun
for a whole list of math functions
randi([10, 20]) % Random int
abs(-1) % Returns 1
floor(2.45) % Returns 2
ceil(2.45) % Returns 3
round(2.45) % Returns 2
exp(1) % e^x
log(100) % Log base e (ln)
log10(100) % Log base 10
log2(100) % Log base 2
sqrt(100) % Square root
deg2rad(90)
rad2deg(3.14)
3.8 Conditionals
> % More than
< % Less than
>= % More than or equal to
<= % Less than or equal to
== % Equal to
~= % Not equal to
|| % Or
&& % And
~ % Not
If block
if <condition>
<do something>
elseif <condition>
<do something else>
else
<do something entirely different>
end % REMEMBER TO END!!!
Switch Statement
switch score
case 1
disp("Aw")
case 2
disp("Better")
case 3
disp("You get the point")
otherwise
disp("WHO NAMED IT OTHERWISE OMG")
end % REMEMBER TO END
3.9 Vectors
They're one dimensional rows or columns!
THE INDEXING FOR MATLAB STARTS AT 1, NOT 0!!!!
% Row Vectors
vector_1 = [5 3 2 1] % Yep!
vector_2 [5, 3, 2, 1] % Both are valid ways!
% Column Vectors
vector_3 = [5; 3; 2; 1]
% Index into the vectors
vector_1(1) % 5
vector_1(end) % 1 (Last value)
vector([1 2 3]) % Get first, second, and third value in vector
% Get range
vector_1(1:3) % First to third
% Change at index
vector_1(1) = 6
% Transpose Vector
a = [1 2 3]
a' % This is now 1, 2, 3 as a column!
Vector Operations
a = [2; 3; 4]
b = [1 2 3]
a * b
% 2 4 6
% 3 6 9
% 4 8 2
3.10 Vector Methods
vector_1 = [1 2 3 4 5]
length(vector_1)
sort(vector_1, 'descend')
% Create ranges
5 : 10 % Gives you [5 6 7 8 9 10]
2 : 2 : 10 % Gives you [2 4 6 8 10]
% Concatenate
a = [1 2 3]
b = [4 5 6]
[a b] % [1 2 3 4 5 6]
% Dot Product (Either...)
a * b' % Transpose as needed
dot(a, b) % Self explanatory
% Cross Product
cross(a, b) % Nice
% Linspace
linspace(1, 20, 4) % Generates 4 numbers equally spaced between 1 and 20
% Logspace
logspace(1, 3, 3) % Like linspace, but the spacing is logarithmic
3.11 Matrices
It's MATLAB, not Vector lab.
matrix_a = [2 3 4; 4 6 8] % 2 rows, 3 columns (2x3)
length(matrix_a) % Gets you 3 (columns)
numel(matrix_a) % Number of values in matrix (6)
size(matrix_a) % Rows, then Columns (2 3)
% Generate random matrices!
randi([10, 20], 2)
% Index into matrices
a = [1 2 3; 4 5 6; 7 8 9]
a(1, 2) = 22 % Index into single value
a(1, :) = 25 % Change all row values
a(:, 2) % Change all column values
a(end, 1) % Last row
a(1, end) % Last column
% To delete a value, just literally put a semicolon at the end.
a(1, 2) = ;
% Multiply matrices
a * b
% Element-wise multiplication
a .* b % Take note of the period!
% Other matrix stuffffff
a - b
a + b
3.12 Matrix Methods
The list is not exhaustive!
Construction
Use the help
command to find out how these work! They're overloaded functions.
eye()
ones()
zeros()
diag()
Mathematical Operations
sqrt(a) % Square root all values in matrix
sum(a) % Sum all columns
sum(a, 'all') % Sum all entries
prod(a) % Multiply all column values
cumsum(a, 'reverse') % Cumulative sum. First row stays the same, each row after is the sum of the preceding and current row (reverse makes it go in reverse)
cumsum(a) % Or if you don't want it reversed..
cumprod(a) % Cumulative product.
det() % Determinant
inv() % Inverse
Conditionals and Indexing
isequal(a, b) % Check for equality
a > 3 % Apply conditional to all entries
find(a > 24) % Gives you index of entries that fulfill the condition
Transformations
fliplr(a) % Flip left to right
flipud(a) % Flip up down
rot90(a) % Rotate 90 degrees
rot90(a, 2) % Rotate 180 degrees
reshape(a, 2, 6) % Reshape into 2x6, it's like numpy!
repmat(a, 2, 1) % Duplicate matrix into new matrix. Eg. If original matrix was 3x3, doing repmat(a, 2, 1) makes it 6x3
repelem(m3, 2, 1) % Duplicates ELEMENTS, so in this case, each element is duplicated twice in terms of the row
3.13 For Loops
For loops! It's pretty Pythonic. It iterates through a range.
% Loop from 1 to 10 and print it
for i = 1:10
disp(i)
end % REMEMBER TO END
% MORE EXAMPLES
% Print every value in matrix
a = [1 2 3; 4 5 6]
for i = 1:2
for j = 1:3
disp(a(i, j))
end
end
% Print for undetermined length
b = [6 7 8]
for i = 1:length(b)
disp(b(i))
end
3.14 While Loops
i = 1 % You must create the variable first!
while i < 20
if(mod(i, 2)) == 0
disp(i)
i = i + 1; % Semicolon suppresses the print
continue
end % This end is for i
i = i + 1;
if i >= 10
break
end
end
3.15 Cell Arrays
You can store data of multiple types
cell_A = {'Hi', 35, [25 8 19]}
cell_B = cell(5) % Create the cell spaces first
cell_A{1} % Get first element
cell_A{3}(2) % Index further
cell_A{4} = 'Something else'
cell_A(4) = ; % Delete
for i = 1:length(cell_A)
disp(cell_A{i})
end
% You can cast character arrays into cell arrays too!
a = ['A', 'BB', 'CCC']
char_array = cellstr(a)
3.16 Strings
Strings are vectors of characters!
str_1 = 'I am a string'
length(str_1)
% Index into a string
str_1(1)
str_1(3:4) % Slices
% Concatenation
str = strcat(str1, ' and now I''m longer!')
% Look for substring
strfind(str, 'a') % Returns indexes of all found substrings
% Replace string
strrep(str, 'longer', 'bigger')
% Split string
str_array = strsplit(str, ' ') % Splits at all spaces. Makes a string array
% Convert numbers to string
int2str(99)
num2str(3.14)
% Check for equality
strcmp(str1, str2)
% Check if is char
ischar('Rawr!11!!1')
% Check if a string is just made of letters
isletter('num 2') % Logical 0
isstrprop('word2', 'alpha')
% Check if string is made of alphanumeric characters
isstrprop('word2', 'alphanum') % Logical 1
% Sort
sort(str, 'descend')
% Delete whitespace (it's like .strip() in python)
strtrim(str)
% Lower and Uppercase conversion
lower(str)
upper(str)
3.17 Structures
Custom data types! Think C++ structs! Or Python dictionaries/maps.
methyl_struct = struct('name', 'methylDragon', ... % the ... lets you skip down to the next line (:
'species', ' Dragon')
disp(methyl_struct.name) % methylDragon
% Add a new field!
methyl_struct.sound = 'Rawr'
% Delete a field
methyl_struct = rmfield(methyl_struct, 'sound')
% Check if field exists
isfield(methyl_struct, 'species')
% Get all field names
fieldnames(methyl_struct)
% Store structures in vectors!
a(1) = methyl_struct
3.18 Tables
Tables are labelled rows of data in a table format
Get help table
if you need help.
a = {'A'; 'B'; 'C'; 'D'};
b = [29; 42; 1; 2]
c = {'AA', 'BB', 'CC', 'DD'}
% Create a table!!! We'll specify a as the index now
test_table = table(a, b, c, 'RowName', a)
% You can do cool stuff with tables!
mean(test_table.b) % For example.. find the means
% Add new fields
test_table.d = [1; 2; 3]
% Pull specific entries
test_table({'A', 'B'}, :) % This defaults to using the RowName as indexer
% Pull specific entries, using another row
a(ismember(test_table.b, {29, 42},:)
3.19 File IO
% Let's just make a random matrix first
rand_matrix = randi([10, 50], 8)
% Let's save and load some files!
save sampdata.dat rand_matrix -ascii
load sampdata.dat
disp sampdata
type sampdata.dat
% We can save variables in a file as well!
save params % Leaving no arguments saves all variables you have on hand
load params
who % Display it on the screen
a = 123
save -append params a % This appends to the normal variable
3.20 Eval
If you know Python you should know what this does already.
Eval executes strings as code!
toExecute = spritnf('total = %d + %d', 5, 4)
eval(toExecute) % Executes it as:
% total = 5 + 4
3.21 Pausing
You can pause in MATLAB too! Think of it like Arduino delay()
or Python time.sleep()
pause(5) % Pause for 5 seconds
pause off % Disable pause
pause on % Enable pause
4. Functional and OOP MATLAB
4.1 Functions
Functions have to come at the end of your file!
Local and global variable rules still apply! Local variables defined in functions don't change outside of the function! Just take note!
% Function to calculate volume
% The return is defined by the name preceding the =
% The name of the function is the name following the =
% In this case, the return is 'vol' and the function name is 'cylinderVol'
function vol = cylinderVol(radius, height)
vol = pi radius^2 * height
end
% Let's try another one! This time a function with no arguments
function randNum = getRandomNum
randNum = randi([1, 100])
end
% Return more than one value
[coneV, cylVol] = getVols(10, 20) % I'll call the function here, and define it below
function [coneVol, cylinVol] = getVols(radius, height)
cylinVol = pi * radius^2 * height
coneVol = 1/3 * cylinVol
end
% Variable Number of Arguments
function sum = getSum(varargin)
sum = 0;
for k = 1:length(varargin)
sum = sum + varargin{k}(1);
end
end
% Return variable number of outputs
function [varargout] = getNumbers(howMany)
for k = 1:howMany
varargout{1}(k) = k;
end
end
4.2 Anonymous Functions
No named functions! Think lambda in python
cubeVol = @ (l, w, h) l * w * h; % (input) output
a = cubeVol(2, 2, 2) % Gives you 8! Correct!
Pass Function to another Function
Think decorators!
Source: https://www.youtube.com/watch?v=NSSTkkKRabI
mult3 = @ (x) x * 3;
sol = doMath(mult3, 4)
function sol = doMath(func, num)
sol = func(num);
end
Returning Functions
Source: https://www.youtube.com/watch?v=NSSTkkKRabI
mult4 = doMath2(4);
sol2 = mult4(5)
function func = doMath2(num)
func = @(x) x * num;
end
4.3 Recursive Functions
They call themselves!
function val = factorial(num)
if num == 1
val = 1;
else
val = num * factorial(num - 1);
end
end
4.4 Classes
Static members are shared amongst all members of a class
classdef Shape
properties % Variables!!!
height
width
end
methods(Static)
function out = setGetNumShapes(data)
% Persistent values are shared by all objects also
persistent Var;
if isempty(Var)
Var = 0;
end
if nargin % Number of input arguments
Var = Var + data
end
out = Var;
end
end
methods
% Define a constructor
function obj = Shape(height, width)
obj.height = height
obj.width = width
obj.setGetNumShapes(1)
end
% Overloaded disp function
% If you don't know what overloading is, check my C++ tutorial. It basically overwrites the functionality of a pre-existing function if the argument number matches
function disp(obj)
fprintf('Height : %.2f / Width : %.2f\n', obj.height, obj.width)
end
function area = getArea(obj)
area = obj.height * obj.width;
end
% Overload Greater Than function
function tf = gt(obja, objb)
tf = obja.getArea > objb.getArea
end
end
end
Let's try using it!
a1 = Shape(10, 20)
disp(a1)
Shape.setGetNumShapes
a1.getArea
a2 = Shape(5, 10)
disp(a2)
Shape.setGetNumShapes
a1 > a2
4.5 Class Inheritance
classdef Trapezoid < Shape % Trapezoid inherits from Shape
properties
width2
end
methods
function obj = Trapezoid(height, width, width2)
obj@Shape(height,width) % The @ sign means you're taking it from the parent
% In this case we're using Shape's constructor!
obj.width2 = width2
end
function disp(obj)
fprint('Height : %.2f / Width : %.2f / Width2 : %.2f', obj.height, obj.width, obj.width2);
end
function area = getArea(obj)
area = (obj.height/2) * (obj.width + obj.width2);
end
end
end
Let's try it out!
a3 = Trapezoid(10, 4, 6)
disp(a3)
a3.getArea
5. Plotting
5.1 Plotting in MATLAB
Source: https://www.youtube.com/watch?v=NSSTkkKRabI
help plot
for help!
xVals = 1:5
yVals = [2 4 8 5 9]
yVals2 = [1 5 7 6 8]
figure(1)
plot(xVals, yVals, 'g+', 'LineWidth', 2)
hold on % Draw over what was plotted, keep plot settings
plot(xVals, yVals2, 'k*')
legend('yVals', 'yVals2')
grid on % Turn grid on
xlabel('Days')
ylabel('Money')
title('Money Made Today')
figure(2)
bar(xVals, yVals, 'r')
% Colors : blue(b), black(k), cyan(c), green(g),
% magenta(m), red(r), yellow(y), white(y)
% Plot Symbols : . o x + * s d v ^ < > p h
% Line Types : -, :, -., - -
% Set font weights and the like
% gca is the axis object, gcf is the figure object
set(gca, 'FontWeight', 'bold', 'FontSize', 20, 'color', 'white');
set(gcf, 'color', 'white')
clf % Delete all figures
Example Sinusoid with Time
y = A.*cos(2*pi .* t/T - 2*pi .* x/lambda + phi0);
5.2 3D Plotting in MATLAB
3D Plots and Meshgrids
plot3() % Use this instead of plot2!
% Example
t = 0: pi/50 : 10*pi;
plot3(sin(t), cos(t), t)
% Meshgrids
meshgrid()
Surfaces
% Plot surfaces
cylinder()
sphere()
surf() % Plot a surface
isosurface() % For when plotting normal surfaces are too hard
contour() % Plot a contour map instead
Vector Fields
quiver() % 2D
quiver3() % 3D
colorbar % Add a colorbar!
6. Intermediate and Advanced Math
6.1 Vector Calculus
gradient()
divergence()
curl()
del2() % Discrete laplacian
. .
. |\-^-/| .
/| } O.=.O { |\
Loops / Conditionals
for
for i=start:counter:finish
statement1
statement2
...
end
while
while condition
statement1
statement2
...
end
if else
if condition1
statement1
elseif condition2
statement2
else
statement3
end
Footer
GUI
Create Figure
h.fig = figure('Name', 'titel_der_figur', ...
'NumberTitle', 'off', ...
'position', [left bottom width height], ...
'Resize', 'off', ...
'Menubar', 'none');
static text
h.text = uicontrol('Style', 'text',...
'Parent', h.panelControl, ...
'FontSize', 14, ...
'String', 'CHOOSE ALGORITHM',...
'Units', 'normalized', ...
'Position', [0 0 1 1],...
'Callback', @setmap);
popup menu
h.popupmenu = uicontrol('Style', 'popup',...
'Parent', h.panelControl, ...
'String', {'Entry1','Entry2','Entry3'},...
'Units', 'normalized', ...
'Position', [left bottom width height],...
'Callback', @setmap);
plot inside a panel
h = figure;
hp = uipanel('Title','Main Panel','FontSize',12,...
'BackgroundColor','white',...
'Position',[.25 .1 .67 .67]);
sp1 = subplot(2, 2, 1, 'Parent', hp);
plot(1:10);
sp4 = subplot(2, 2, 4, 'Parent', hp);
surf(peaks);
Bash
random by max number of case
$ echo ${RANDOM:0:3}
substitution
- remove dirname
f="./4-Attya-anatomie/expose.pdf"
echo ${f##*/}
expose.pdf
- extension
file=ra.pdf
echo "${file:0:-4}"
ra
$ f="/etc/resolv.conf"
$ echo "${f#/etc/}"
resolv.conf
- not determiner fisrt match
$ f="/etc/resolv.conf"
$ echo "${f#*/}"
resolv.conf
interpreted var : eval it
hello=2020
var="hello"
echo ${!var}
# 2020
format string like a table
- select words
- add spaces
- trim spaces: by accept only
14
char
sed 's/\(\(\w\|+\| \)\{14\}\) */\1'
loop in array
declare -a arr=(
"already"
"amssymb"
"array"
)
for item in "${arr[@]}";do
#...
done
pass array to function
f() {
declare -a argAry1=("${!1}")
echo "${argAry1[@]}"
}
arr1=(
"a"
"b"
)
f arr1[@] arg2 arg3
readarray -t fr < fr.txt
array_of_lines=("${(@f)$(my_command)}")
use args
while getopts "a:b:r:c:C:T:Kk:l:i:I:s:o:p:v:h" opt; do
case $opt in
a) BASE_ARCH="$OPTARG";;
b) BASE_SYSTEM_PKG="$OPTARG";;
r) XBPS_REPOSITORY="--repository=$OPTARG $XBPS_REPOSITORY";;
c) XBPS_CACHEDIR="$OPTARG";;
K) readonly KEEP_BUILDDIR=1;;
k) KEYMAP="$OPTARG";;
l) LOCALE="$OPTARG";;
i) INITRAMFS_COMPRESSION="$OPTARG";;
I) INCLUDE_DIRECTORY="$OPTARG";;
s) SQUASHFS_COMPRESSION="$OPTARG";;
o) OUTPUT_FILE="$OPTARG";;
p) PACKAGE_LIST="$OPTARG";;
C) BOOT_CMDLINE="$OPTARG";;
T) BOOT_TITLE="$OPTARG";;
v) LINUX_VERSION="$OPTARG";;
h) usage;;
*) usage;;
esac
done
find files that's binaty
find . -type f ! -size 0 -exec grep -IL . "{}" \;
Some color for bash
# Color
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color
function red {
printf "${RED}$@${NC}\n"
}
function green {
printf "${GREEN}$@${NC}\n"
}
function yellow {
printf "${YELLOW}$@${NC}\n"
}
read file by while
while IFS= read -r line; do
echo "Text read from file: $line"
done < my_filename.txt
Hide some error
add this to your script file.sh
# shellcheck disable=SC1117,SC2001
switch case in c
switch (a) {
case 100:
// Code
break;
case 200:
// Code
break;
default:
// Code
break;
}
compare two strings
if (strcmp(s1,s2)==0){
//true
}
multi string concate
strcat(strcat(s1,s2),s3);
strcat(strcat(strcat(s1,s2),s3),s4);
strcat(strcat(strcat(strcat(s1,s2),s3),s4),s5);
#include <criterion/criterion.h>
// https://github.com/Snaipe/Criterion/blob/bleeding/samples/asserts.c
str1 == str2: eq
// need for str,...
#include <criterion/new/assert.h>
Test(..., ...) {
cr_assert(eq(str, "hello", "hello"));
}
function return 1 or bool
Test(..., ...) {
cr_assert(true);
}
str1 == "":
Test(..., ...) {
char s1="";
cr_assert(zero(str, s1));
cr_assert(not (zero(str, s1)));
}
init/finish
void setup(void)
{
puts("Runs before the test");
}
void teardown(void)
{
puts("Runs after the test");
}
// must add this args at the end
Test(..., ..., .init = setup, .fini = teardown){
}
read line by line
while (!feof (fp)) {
if (fgets(line, sizeof (line), fp)) {
printf("next line= %s\n", line);
}
}
read to char or first line
fscanf(fp, "%[^\n]", line);
printf("Data from the file:\n%s", line);
void readFirstLine(char *file,char *line)
inayoub/file
- Give a error whenever a function is used before being declared
$ gcc -Werror-implicit-function-declaration
- Give a error whenever a function is used without prototypes
$ gcc -Wstrict-prototypes -Wmissing-prototypes
- option makes using -S to inspect the assembly output much, much nicer.
$ gcc -masm=intel
- esstentiel
$ gcc -Wall -Wextra -Wfloat-equal -Os -ggdb
- stops the compilation if has and big warrning
$ gcc -Werror
- small executable
$ gcc -s
- cheack printf and scanf
$ gcc -Wformat=2
- gcc version
$ gcc -std=c99
GDB
- string
p s
- first 3 element in any
arrays
p s@3
go back : gdb prev
target record-full
run
reverse-next
reverse-step
change var value from 3 to 7
main(){
int i=7
}
set variable i = 7
change string value
int main(){
char[] person = "Bob";
}
set main::person = "Sam"
gdb config
cat ~/.gdbinit
gdb source view
gdb -tui
gdb in vim
let g:termdebug_wide = 10 | packadd termdebug | Termdebug
MAKE
look some CFLAGS
clang -c a.c # it's create a.o
clang a.o f.o -o a
./a
- use cflags without quote:
'
or"
CFLAGS=-Wno-deprecated-declarations -Wno-format-security -lm `pkg-config --cflags --libs gtk+-3.0` -export-dynamic
LDFLAGS=`pkg-config --libs gtk+-3.0`
- use
all: app
notall app:
- help clangd and ccls
bear -- make > compile_commands.json
my function in mylib
- read first line from
*file
and return fist&line
void readFirstLine(char *file, char *line);
- read nth line from
*file
and return the nth&line
void readOneLine(char *file, char *s, int N);
- read
int
from*file
and returnx
int fgetint(char *file);
- read
*file
and return as&string
void fgetString(char *file, char *s);
- run
shell coomad
and return output as&string
void stdoutOneline(char *s_in, char *s_out);
array of function Pointers
like switch
cases to run the functions
:
- function:
int sum(int a,int b);
int sub(int a,int b);
- main:
int (*option[2])(int,int);
option[1]=sum;
option[2]=sub;
printf("%d",option[1](1,2)); // sum(1,2) --> 3
how to make so/share library
$ gcc -o libx.so -fpic -shared libx.c # libx.c -> libx.so
$ ln -s x.h /usr/include/ayoub/x.h
$ ln -s libx.so /lib #
$ gcc -c main.c -o main.o # main.c -> main.o
$ gcc -o main main.o -lx # main.o + mylib
how to use it in Makefile
just add -lx
to cflags
Check for lib
to view the function
that already define or undefine(need lib.so
)
$ nm a.out
how to view shared lib from app
$ ldd a.aout
how to sleep in c: waiting
#include <unistd.h>
sleep(5);
STRING
pass char[][]
to function
-
function to read char[][]
2D
void readMatrix( char *matrix[][cols]) {
matrix[i][j] = "aaa";
}
char *mat[rows][cols];
readMatrix(mat);
- with maloc and pointer
void readMatrix(char**** matrix){
*matrix = malloc(rowNum*sizeof(char**));
for(int i=0;i<rowNum;i++){
*(*matrix+i) = malloc(columnNum*sizeof(char*));
}
*(*(*matrix+i)+j) = malloc(MAX_WORD_SIZE*sizeof(char));
scanf("%s",*(*(*matrix+i)+j));
}
char*** inputMatrix;
readMatrix(&inputMatrix);
printf("%s ",*(*(inputMatrix+i)+j));
Read string with white space from file with fscanf
char s[40];
fscanf (fp, "%d,%f,%[a-zA-Z ]\n", &i, &x, s);
how to convert str to int
- ust
sprintf()
sprintf(s, "%d", x);
printf("%s\n",s);
pass arry of sruct
- my answer in stackoverflow
- struct:
typedef struct top {
int tot;
char s[100];
} top;
- main:
int main() {
top **t_array = malloc(100 * sizeof(top *));
t_array[0] = malloc(sizeof(top));
t_array[0]->tot = 10;
f1(t_array);
}
- function:
void f1(top **t_array) {
t_array[0] = malloc(sizeof(top));
t_array[0]->tot = 11;
}
without array
typedef struct top {
int tot;
} top;
- main
top *array1 = malloc(MAX * sizeof(top));
array1->tot=11;
swap (permutaion) tow struct
top* tmp = t_trie[j];
t_trie[j] = t_trie[i];
t_trie[i] = tmp;
Get time
struct tm {
int tm_sec; /* seconds, range 0 to 59 */
int tm_min; /* minutes, range 0 to 59 */
int tm_hour; /* hours, range 0 to 23 */
int tm_mday; /* day of the month, range 1 to 31 */
int tm_mon; /* month, range 0 to 11 */
int tm_year; /* The number of years since 1900 */
int tm_wday; /* day of the week, range 0 to 6 */
int tm_yday; /* day in the year, range 0 to 365 */
int tm_isdst; /* daylight saving time */
};
Rust
Notion
mut
, all variables areconst
, to make itmodifiable
added themut
Result
of a.method_name()
is anenum
.- We call each possible state of
Result
avariant
. Result
'svariants
for.read_line()
areOk
andErr
.- The blocks of code after
if
: called arms{}
let mut s="jjj"
not allowed,let mut s=String::from("jjj")
allowed using the heap mémoirelet s2 = s1
:s1
move
tos2
, thens1
will be droped
re-use Var: shadows
#![allow(unused)] fn main() { let x=10; let x="ll"; }
mut
not allowing the shadows
#![allow(unused)] fn main() { let mut x=10 x="ll"; }
variables
#![allow(unused)] fn main() { let x : i32= 4; // u32,u8.. let x : i32= 4_000; // 4_000 == 4000 let y: f32 = 3.0; // defualt is f64 let floored = 2 / 3; // Results in 0 let t: bool = false; let heart_eyed_cat: char = '😻';// 'z' ...should use single for char }
Tuple
#![allow(unused)] fn main() { let tup:(i32, f64, u8) = (500, 6.4, 1.5); let (x, y, z) = tup; println!("The value of z is: {z} or {} or {tup.2} or {}",tup.2); // {tup.2} -> not allowed }
Arr
Unlike a tuple, every element of an array must have the same type. Unlike arrays in some other languages, arrays in Rust have a fixed length.
#![allow(unused)] fn main() { let a = [1, 2, 3, 4, 5]; let first = a[0]; }
What Is Ownership?
Memory is managed through a system of ownership with a set of rules that the compiler checks. If any of the rules are violated, the program won’t compile. None of the features of ownership will slow down your program while it’s running.
- Ownership Rules
- Each value in Rust has an owner.
- There can only be one owner at a time.
- When the owner goes out of scope, the value will be dropped.
- the error
double free error
is solved byshallow copy
shallow copy
: not drop the heap data
of var
if this data
shared between
another var
deep copy
,s1
ands2
will be separated
#![allow(unused)] fn main() { let s1 = String::from("hello"); let s2 = s1.clone(); }
- types that used head memory used move and other used copy function
#![allow(unused)] fn main() { let s = String::from("hello"); takes_ownership(s); s:String("new"); // not allowed because moved from this scope }
C like
import
#![allow(unused)] fn main() { use std::io; }
c scanf in rust
#![allow(unused)] fn main() { io::stdin() .read_line(&mut guess) .expect("Failed to read line"); }
c #define in rust
#![allow(unused)] fn main() { // #define ABC 40 * 60 * 3 const ABC: u32 = 60 * 60 * 3; }
c rand() in rust
#![allow(unused)] fn main() { use rand::Rng; let secret_number = rand::thread_rng().gen_range(1..=100); }
compare value to another value
#![allow(unused)] fn main() { use std::cmp::Ordering; match guess.cmp(&secret_number) { Ordering::Less => println!("Too small!"), Ordering::Greater => println!("Too big!"), Ordering::Equal => println!("You win!"), } }
cast
#![allow(unused)] fn main() { let guess: u32 = "42".parse().expect("Not a number!"); }
if
#![allow(unused)] fn main() { if number < 5 { println!("condition was true"); } else { println!("condition was false"); } }
#![allow(unused)] fn main() { let number = if condition { 5 } else { 6 }; }
loop
- simple break
#![allow(unused)] fn main() { let result = loop { counter += 1; if counter == 10 { break counter * 2; } }; }
- break outside and inside
fn main() {
let mut count = 0;
'counting_up: loop {
println!("count = {count}");
let mut remaining = 10;
loop {
println!("remaining = {remaining}");
if remaining == 9 {
break;
}
if count == 2 {
break 'counting_up;
}
remaining -= 1;
}
count += 1;
}
println!("End count = {count}");
}
while
#![allow(unused)] fn main() { while number != 0 {} }
for
#![allow(unused)] fn main() { let a = [10, 20, 30, 40, 50]; for element in a {} for number in (1..4).rev() {} }
ERROR
- double free error :
#![allow(unused)] fn main() { let s1 = String::from("hello"); let s2 = s1; }
This is a problem: when s2
and s1
go out of scope, they will both try to free
the same memory. This is known as a double free error
and is one of the memory safety bugs
we mentioned previously. Freeing memory twice can lead to memory
corruption, which can potentially lead to security vulnerabilities.
Struct
fn main() { let mut user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; user1.email = String::from("anotheremail@example.com"); }
return a struct
struct User { //... } fn build_user() -> User { User { //... } } fn main() { let user1 = build_user(...); }
Merge tow struct
fn main() { let user1 = User { // .... }; let user2 = User { email: String::from("another@example.com"), ..user1 }; }
struct as tuple
struct Color(i32, i32, i32); struct Point(i32, i32, i32); fn main() { let black = Color(0, 0, 0); let origin = Point(0, 0, 0); }
Ownership of Struct Data
we used the owned String
type rather than the &str
string slice type. for that
data to be valid for as long as the entire struct
is valid.
to store references to data owned by something else, it's require to use the
lifetimes
, to ensure the data referenced by a struct
is valid for
as long as the struct
is.
Methode with struct
struct Rectangle { width: u32, height: u32, } // snip ... impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn can_hold(&self, other: &Rectangle) -> bool { self.width > other.width && self.height > other.height } } fn main() { let rect1 = Rectangle { width: 30, height: 50, }; let rect2 = Rectangle { width: 10, height: 40, }; println!( "The area of the rectangle is {} square pixels.", rect1.area() ); println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2)); }
enum
enum IpAddrKind { V4, V6, } fn main() { let four = IpAddrKind::V4; let six = IpAddrKind::V6; route(IpAddrKind::V4); route(IpAddrKind::V6); } fn route(ip_kind: IpAddrKind) {}
Enum with struct
fn main() { enum IpAddrKind { V4, V6, } struct IpAddr { kind: IpAddrKind, address: String, } let home = IpAddr { kind: IpAddrKind::V4, address: String::from("127.0.0.1"), }; let loopback = IpAddr { kind: IpAddrKind::V6, address: String::from("::1"), }; }
Enum as args as tuple
fn main() { enum IpAddr { V4(u8, u8, u8, u8), V6(String), } let home = IpAddr::V4(127, 0, 0, 1); let loopback = IpAddr::V6(String::from("::1")); }
Example
enum Coin { Penny, Nickel, Dime, Quarter, } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter => 25, } } fn main() { value_in_cents(Coin::Quarter(UsState::Alaska)); }
- how to use
value_in_cents
:- how to call it
- how to receive return value, is there always the same type
u8,int...
- tow to send and
enum
or onevariant
from enum
with if, the expression needs to return a Boolean value, but here, it can return any type. The type of coin in this example is the Coin enum
#[derive(Debug)] // so we can inspect the state in a minute enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() {}
Match
#[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn value_in_cents(coin: Coin) -> u8 { match coin { Coin::Penny => 1, Coin::Nickel => 5, Coin::Dime => 10, Coin::Quarter(state) => { println!("State quarter from {:?}!", state); 25 } } } fn main() { value_in_cents(Coin::Quarter(UsState::Alaska)); }
Option
fn main() { fn plus_one(x: Option<i32>) -> Option<i32> { match x { None => None, Some(i) => Some(i + 1), } } let five = Some(5); let six = plus_one(five); let none = plus_one(None); }
Catch All
fn main() { let dice_roll = 9; match dice_roll { 3 => add_fancy_hat(), 7 => remove_fancy_hat(), other => move_player(other), _ => reroll(), _ => (), } fn add_fancy_hat() {} fn remove_fancy_hat() {} fn move_player(num_spaces: u8) {} }
If let
fn main() { let config_max = Some(3u8); match config_max { Some(max) => println!("The maximum is configured to be {}", max), _ => (), } // equivalent if let Some(max) = config_max { println!("The maximum is configured to be {}", max); } }
#[derive(Debug)] enum UsState { Alabama, Alaska, // --snip-- } enum Coin { Penny, Nickel, Dime, Quarter(UsState), } fn main() { let coin = Coin::Penny; let mut count = 0; match coin { Coin::Quarter(state) => println!("State quarter from {:?}!", state), _ => count += 1, } // equivalent if let Coin::Quarter(state) = coin { println!("State quarter from {:?}!", state); } else { count += 1; } }
how to substitute assets in pebstect.yaml
g/^....assets:/s/....assets:/ assets:\r - assets\/*
flutter run -d linux --pid-file /tmp/flutter.pid
-
if you want to pass function
delete
fromclass A
toclass B
- don't use :
final Function? delete
; - but use :
final VoidCallback? delete
;
- don't use :
-
if you get the error
null
:
useString foo?
;foo!
; -
if you want to use
wait B.fun(await ...)
inclass A
:- you must add
Future<void/int> fun(){await ...}
inclass B
- than use the
await B.fun..
inclass A
- but don't forget to add
async
inclass A
..
- you must add
-
if you want to use the
hot reload
by pluginflutter-tools
- use the script to
kill
thepid
of app that running
- use the script to
List of models
List<Quote> list=[Quote(text: 'll', author: '') ];
map listview
main:
class MyApp....{}
class _MyAppState extends State<MyApp> {
late final Quote quote;
List<Quote> quotes = [
Quote(text: 'fsm mks', author: 'ayoub'),
Quote(text: 'fsm rabat', author: 'aly'),
Quote(text: 'fsm mauritanya', author: 'rachid'),
];
@override
Widget build(BuildContext context) {
return Column(
children: quotes.map((quote) => Text('${quote.text}- ${quote.author}')).toList(),
);
to
- main:
class MyApp....{}
class _MyAppState extends State<MyApp> {
late final Quote quote;
List<Quote> quotes = [
Quote(text: 'fsf mks', author: 'ayoub'),
Quote(text: 'fsm rabat', author: 'aly'),
Quote(text: 'fsm mauritanya', author: 'rachid'),
];
@override
Widget build(BuildContext context) {
return Column(
children: quotes .map((quote) => Mycard(quote:quote)) .toList(),
);
- class:
//import...
class Mycard extends StatelessWidget {
final Quote quote;
const Mycard({Key? key, required this.quote}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
child: Card(child: Text('${quote.text} -- ${quote.author}')),
);
}
}
use keyword require:
class Quote {
String author = "";
String text = "";
Quote({required this.author, required this.text});
}
call:
Quote(text: 'll', author: '')
list of models:
List<Quote> list=[Quote(text: 'll', author: '') ];
rooting
-
use
routes:{key:val,...}
-
import layout
import 'package:app9/pages/choose_location.dart'; import 'package:app9/pages/home.dart'; import 'package:app9/pages/looding.dart'; import 'package:flutter/material.dart'; void main() => runApp(MaterialApp( initialRoute:'/', routes: { '/': (context) => Loading(), '/home': (context) => Home(), }, ));
-
don't use duplique roationg, like:
runApp( Home(), routes:{'/home'} )
alignment: left/start/right ..
child: Column(...,crossAxisAlignment: CrossAxisAlignment.start)
image
flutter:
assets:
- assets/images/
child: Image(
height: 100,
image: AssetImage('assets/images/img1.png'),
),
Text
// const int grey50 = 0xFFFAFAFA;
const Text(
'Name',
style: TextStyle(
fontSize: 14,
color: Color(grey400),
),
),
Separateur Divider
const SizedBox(height: 20),
Column
- column inside scafold
return Scaffold(
appBar: AppBar(
title: const Text('Material App Bar'),
),
body: Column(
children: <Widget>[
const Center(
child: Image(),
),
],
),
);
- scafold->padding...->column
return Scaffold(
body: Padding(
child: Column(
children: <Widget>[
const Center(
child: Image(),
),
],
),
),
);
Icon
children: [Icon(Icons.tv)],
children: [
ElevatedButton.icon(
onPressed: (){},
icon: const Icon(Icons.delete),
label: const Text('delete quote'),
)
],
button
VOID LUNUX
xbps-install -Sy pkg-config gtk+3-devel clang
pubspec.yaml
dependencies:
sprintf:
main.dart
import 'package:sprintf/sprintf.dart';
String numbers = sprintf('Your score is %2.2f points.', [score]);
String sentence = sprintf('Hello %s, You have %d years old.', [name, years]);
string.format
string.format("%s %q", "Hello", "Lua user!") -- string and quoted string
Hello "Lua user!"
string.sub("taaaaaaest.lua",1,-5)
taaaaaaest
gmatch
for word in string.gmatch("Hello Lua user", "%a+") do
print(word)
end
Hello
Lua
user
- match pattern in lua
%d matches a digit
%u matches an uppercase letter
%a: letter %s: whitespace
string.match("%*^", '%%%*%^')
%*^
JavaScript
Install latex on voidlinux
should use `^texlive-20210325_4' is you want to use binary
xbps-install -Sy texlive-20210325_4
Bash Var
export TEXMFHOME=~/.texmf
export PERL5LIB="/usr/share/texmf-dist/tlpkg:<span class="katex"><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:1em;vertical-align:-0.25em;"></span><span class="mord mathnormal" style="margin-right:0.08125em;">H</span><span class="mord mathnormal" style="margin-right:0.05764em;">OME</span><span class="mord">/</span><span class="mord mathnormal">tlp</span><span class="mord mathnormal" style="margin-right:0.03148em;">k</span><span class="mord mathnormal" style="margin-right:0.03588em;">g</span><span class="mspace" style="margin-right:0.2778em;"></span><span class="mrel">:</span></span></span></span>HOME/.cpan/build:PERL5LIB"
Stow
latex
in dotfile continent TLConfig.pm ...
stow latex
link
this version not continent tlpkg/installer/tlconfig.guess
sudo chown {USER}:users /
ln -sf /usr/share/texmf-dist/tlpkg /tlpkg
choose old repo for old latex-2021
tlmgr option repository https://ftp.tu-chemnitz.de/pub/tug/historic/systems/texlive/2021/tlnet-final
tlmgr update
successive
\newcommand{\myitem}{\item[$\blacksquare$]}
\begin{frame}{Historique}
\begin{itemize}[<+-|alert@+>]
\myitem 1950
\myitem 1970
\end{itemize}
\only<1>{
\begin{exampleblock}{XXXX}
...
\end{exampleblock}
}
\only<2>{
\begin{exampleblock} {YYY}
..
\end{exampleblock}
}
\vspace{80mm}
\end{frame}
intalation : latex to text
https://github.com/pkubowicz/opendetex
/projects/c/opendetex
online converter:
https://www.vertopal.com/en/convert/pdf-to-tex
fix luatex/xetex/pdftex
\documentclass[a4paper,11pt,twoside]{report} %twoside pour une présentation différente des pages paires/impaires, car dans la classe report, l'option oneside est par défaut
\usepackage{iftex}
\ifPDFTeX
\usepackage[mathletters]{ucs}
\usepackage[utf8x]{inputenc}
% \usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\else
\ifXeTeX
% \usepackage[mathletters]{ucs}
% \usepackage[utf8x]{inputenc}
\usepackage{fontspec}
\else
\usepackage{luatextra}
\fi
\defaultfontfeatures{Ligatures=TeX}
\fi
zref-abspage.sty
$ set zref set zref zref-abspage.sty zref-abspos.sty zref-base.sty zref-counter.sty zref-dotfill.sty zref-env.sty zref-hyperref.sty zref-lastpage.sty zref-marks.sty zref-nextpage.sty zref-pageattr.sty zref-pagelayout.sty zref-perpage.sty zref-runs.sty zref-savepos.sty zref-thepage.sty zref-titleref.sty zref-totpages.sty zref-user.sty zref-xr.sty zref.sty
$ for file in $zref;wget 'https://raw.githubusercontent.com/manuels/texlive.js/master/texlive/texmf-dist/tex/latex/oberdiek/'$file;end
$ output to $prefix/texmf/tex/latex not $prefix/texmf-dist/tex/latex
$ ln -s /texmf-dist/tex/latex/oberdiek ~/texmf/tex/latex
declare
must start with include then declar command
fix tlmgr usermode+ pacage is 2020 but install 2021
find a userpackage
$ tlmgr search --global --file beamerthemeShadow
create manually pkg in /texmf-dist/tex/latex
$ mkdir /texmf-dist/tex/latex/pkg1
$ texhash /texmf-dist
update 4:
- tlmgr repo is old: i can go back to the old reposotory by change the`tlmgr reposotory`
```bash
$ tlmgr option repository https://ftp.tu-chemnitz.de/pub/tug/historic/systems/texlive/2021/tlnet-fina
```
update 3:
-
latex as bin
$ xbps-install -Sy i texlive-20210325_2
-
latex mk
- already include
-
tlmgr already include
$ ln -s $HOME/scripts/latex/tlmgr /sbin
-
TeXLive/TLPDB.pm
- already include dans
texlive-core-2021.58710_1
$ wget https://raw.githubusercontent.com/TeX-Live/installer/master/tlpkg/TeXLive/TLUtils.pm^C
- already include dans
-
latexpkg: auto install missing pkg
$ ln -s $HOME/scripts/latex/latexpkg /sbin
-
verification de reposotory: not sure
$ # tlmgr init-usertree
-
define tlpkg
$ ln -s /usr/share/texmf-dist/tlpkg /
- luatex & bibtex
$ xbps-install -Sy texlive-LuaTeX texlive-BibTeX
UPDATE 2:
- init tlmgr
$ tlmgr init-usertree
- active usermode for root in voidlinux
- by alias:
$ alias tlmgr='/usr/share/texmf-dist/scripts/texlive/tlmgr.pl --usermode'
- or sumlink
$ cat /sbin/tmlgr #!/bin/sh exec /usr/share/texmf-dist/scripts/texlive/tlmgr.pl --usermode "$@"
- geus
UPDATE:
xbps binary
$ xbps-install -Sy texlive-20210325_2
localte module
if tmlgr can't locate TeXlive::.... - link path that reaserch by tlmgr ln -s /usr/share/texmf-dist /texmf-dist - download module manuly to /texmf-dist/scripts/texlive/TeXLive/... - use alias tl='$(which tlmgr) --usermode'
OLD:
$ xbps-install -Sy texlive2021-bin-2021_1
fix version 2021
$ vim `which tlmgr` or
$ vim TEXMFDIST/scripts/texlive/tlmgr.pl
and replace $Master = "$Master/../.."; with $Master = "${Master}/../../..";
- download la
latexmk
and make symbloic link
$ ln -s /opt/texlive2021-installer/texmf-dist/scripts/latexmk/latexmk.pl /usr/bin/latexmk
- alias use script to create
tlmgr
alias tlmgr="/opt/texlive2021-installer/texmf-dist/scripts/texlive/tlmgr.pl --usermode"
install cpan for latexindent
$ export PERL5LIB="$HOME/.cpan/build:$PERL5LIB"
$ cpan Log::Log4perl File::HomeDir YAML::Tiny Unicode::GCString
- to remove perl/cpan module:
$cpanm --uninstall YAML::Tiny module
- this module install at:
$ ls $HOME/perl5/lib/perl5
insert latex symbols by copy
view wiki/latex/fix.md
fix
make all command \bo
declared after using
position of text
A---------B
1 2 3
for write text below A,
\draw (A) node[below]{1} -- (B) ;
for write text below Midle of (A,B),
\draw (A) -- node[below]{2} (B) ;
for write text below B,
\draw (A) -- (B) node[below]{3};
variable
\pgfmathsetmacro{\angle}{60}
fuction like cos and sin
4*cos{\angle}, % not cos() with parentecise
loop
foreach \x in {0,...,5} {
\draw (A) -- (0,\x)
};
vim
all buffer to splite vertical
:vert sb#
How to change default nvim directory
Fist time:
- change global var to new dirs:
XDG_CONFIG_HOME=~/.config
XDG_DATA_HOME=~/.local
XDG_CONFIG_HOME
change to something like ~/test/
XDG_DATA_HOME
change to something like ~/test/local
mkdir -p ~/test/{local,nvim}
for create this tree of dirs:
test
├── local
└── nvim
~/test/nvim
contian init.vim
or init.lua
~/test/local` contian plug manager as Packer/Plug/Vundel
- Sync plugin for first time by run config file init.lua or init.vim
nvim ~/TEST-Cris/nvim/init.lua
Seconde time:
- run
~/file.txt
for example:
without alias
export XDG_CONFIG_HOME=~/test ;export XDG_DATA_HOME=~/test/local; nvim ~/file.txt
with alias
with alias is fast , you should be add to .bashrc or ...
- alias vi
alias vi='export XDG_CONFIG_HOME=~/test ;export XDG_DATA_HOME=~/test/local; nvim'
- run
~/file.txt
for example:
vi ~/file.txt
how write accenet alphabel fr french françias
é = '
è = `+!
ê = >
ë = :
ç = ,
œ = oe
- change color of
dar1
$ diff lua/gruvebox/color.lua
dark0_soft = hsl("#32302f"),
-dark1 = hsl("#3c3836"),
+dark1 = hsl("#272727"),
dark2 = hsl("#504945"),
- change curlsorline cursor
$ diff lua/gruvebox/base.lua
LineNr {fg = bg4, bg = number_column},
-CursorLineNr {fg = yellow, bg = bg1},
+CursorLineNr {fg = bg4, bg = number_column}
# xbps
$ xbps-install -Sy texlab nuspell clang shfmt shellcheck ccls StyLua
# pip
$ pip install autopep8 isort black yapf cmakelang
# npm
$ npm install -g bash-language-server prettier
luarcks need this app
xbps-install -Sy luarocks lua53-devel libnuspell-devel
make c file
:set makeprg=gcc\ -Wall\ -g\ %\ -o\ %<
:nnoremap ll :silent make<cr>:vs<cr>:term ./tp<cr>
wrap format tex
set tw=70
: 70 char with lineqg<motion>
set formatoptions+=a
: live wraping/formating
how use spell
set spelllang+=fr
setlocal spell
" <F5> :set local spell!<cr>
add new word to spell
- zg
- zG (temp dictionair)
add wrong word
- zw -zW (temp dic)
remove/undo word
- zug,zuw..