From 7758d8795e06b1ae8d0c750d92fd62da7e9eb804 Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Mon, 21 Oct 2019 08:52:30 +0200 Subject: [PATCH 001/392] [sql/de] Translate sql to german --- de-de/sql-de.html.markdown | 116 +++++++++++++++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 de-de/sql-de.html.markdown diff --git a/de-de/sql-de.html.markdown b/de-de/sql-de.html.markdown new file mode 100644 index 00000000..fcf3a36e --- /dev/null +++ b/de-de/sql-de.html.markdown @@ -0,0 +1,116 @@ +--- +language: SQL +filename: learnsql-de.sql +contributors: + - ["Bob DuCharme", "http://bobdc.com/"] +translators: + - ["denniskeller", "https://github.com/denniskeller"] +lang: de-de +--- + +Die Structured Query Language (SQL) ist eine ISO Standardsprache zum Erstellen und Arbeiten mit Datenbanken, die in einem Set von Tabellen gespeichert sind. Implementiereungen fügen in der Regel eigene Erweiterungen zur Sprache hinzu; [Der Vergleich von verschiedenen SQL Implementierungen](http://troels.arvin.dk/db/rdbms/) ist eine gute Referenz für Produktunterschiede. + +Implementierungen bieten typischerweise eine Eingabeaufforderung, in den du die hier gezeigten Befehle interaktiv eingeben kannst. Sie bieten auch einen Weg, um Serien von Befehlen in einer Skript auszuführen. (Die Anzeige, dass du fertig mit der interaktiven Eingabeaufforderung bist, ist ein gutes Beispiel für etwas, was nicht standardisiert ist. Die meisten SQL Implementierungen unterstützen die Schlüsselwörter QUIT, EXIT oder beides. +Einige dieser Beispielbefehle gehen davon aus, dass sie die [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/), verfügbar auf [github](https://github.com/datacharmer/test_db), schon geladen wurde. Die Github Dateien sind Skripte von Befehlen, ähnlich wie die entsprechenden Befehle unten, die Tabellen mit Daten über die Mitarbeiter einer fiktionale Firma erstellen und füllen. Die Syntax für die Ausführung dieser Skripte hängt von der verwendeten SQL-Implementierung ab. Ein Dienstprogramm, das man über die Betriebssystemeingabeaufforderung ausführen kann, ist typisch. + + +```sql +-- Kommentare starten mit zwei Bindestrichen. Jeder Befehl endet mit einem Semikolon. + +-- SQL unterscheidet nicht zwischen Groß- und Kleinschreibung bei +-- Schlüsselwörtern. Die Beispielbefehele folgen der Konvention der +-- Schreibweise in Großbuchstaben, damit sie leichter von Datebank-, +-- Tabellen- und Spaltennamen zu unterscheiden sind. + +-- Erstellen und Löschen einer Datenbank. Bei Datenbank- und Tabellennamen +-- wird zwischen Groß- und Kleinschreibung unterschieden. +CREATE DATABASE someDatabase; +DROP DATABASE someDatabase; + +-- Liste verfügbare Datenbanken. +SHOW DATABASES; + +-- Verwende eine bestimmte Datenbank. +USE employees; + +-- Wähle alle Zeilen und Spalten aus der Tabelle departmens aus der aktuellen +-- Datenbank aus. +-- Das Standardverhalten für den Interpreter ist die Ergebnisse auf +-- dem Bildschirm zu scrollen. +SELECT * FROM departments; + +-- Hole dir alle Zeilen aus der departments Tabelle, +-- aber nur die dept_no und die dept_name Spalten. +-- Das Aufteilen von Befehlen auf mehrere Zeilen ist in Ordnung. +SELECT dept_no, + dept_name FROM departments; + +-- Hole dir alle departments Spalten, aber nur 5 Zeilen. +SELECT * FROM departments LIMIT 5; + +-- Hole dir die dept_name Spaltenwerte aus der departments Tabelle, +-- in der der Wert dept_name die Teilzeichenfolge 'en' hat. +SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; + +-- Hole dir alle Spalten von der departments Tabele, in der die dept_name +-- Spalte mit einem 'S' beginnt und exakt 4 Zeichen danach besitzt. +SELECT * FROM departments WHERE dept_name LIKE 'S____'; + +-- Wähle die Titelwerte aus der Titeltabelle, aber zeige keine Duplikate an. +SELECT DISTINCT title FROM titles; + +-- Das Gleiche wie oben, aber sortiert nach den Titelwerten, mit Beachtung +-- der Groß und Kleinschreibung. +SELECT DISTINCT title FROM titles ORDER BY title; + +-- Zeige die Anzahl der Zeilen in der departments Tabelle an. +SELECT COUNT(*) FROM departments; + +-- Zeige die Anzahl der Zeilen in der departments Tabelle an, die 'en' als +-- Teilezeichenkette des Wertes dept_name haben. +SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; + +-- Eine Vereinigung von Informatione von mehreren Tabellen: +-- Die titles Tabelle zeigt, wer welche Jobtitel hatte, wer welche Mitarbeiter- +-- nummer hat, von welchen Startdatum und zu welchen Enddatum +-- Wir rufen diese Information ab, aber anstelle der Mitarbeiternummer, +-- verwenden wir die Mitarbeiternummer als Querverweis auf die empoyees Tabelle +-- um die die Vor- und Nachnamen jedes Mitarbeiters zu erhalten. +-- (und nur 10 Reihen) +SELECT employees.first_name, employees.last_name, + titles.title, titles.from_date, titles.to_date +FROM titles INNER JOIN employees ON + employees.emp_no = titles.emp_no LIMIT 10; + +-- Liste alle Tabellen in allen Datenbanken auf. Verschiedene Implementierungen +-- stellen typischerweise einen eigenen Abkürzungsbefehl zur Verfügung für +-- die aktuell verwendete Datenbank. +SELECT * FROM INFORMATION_SCHEMA.TABLES +WHERE TABLE_TYPE='BASE TABLE'; + +-- Erstelle eine Tabelle in der aktuell verwedeten Datenbank +-- mit dem Namen tablename1, in der die beiden Spalten angezeigt werden +-- Es gibt viele weiteren Optionen, wie man die Spalten spezifizieren kann, +-- wie z.B. deren Datentyp. +CREATE TABLE tablename1 (fname VARCHAR(20), lname VARCHAR(20)); + +-- Füge eine Zeile mit Daten in die Tabelle tablename1. Dies setzt voraus, +-- das die Tabelle so definiert worden ist, dass sie die geeigneten +-- Werte akzeptiert. +INSERT INTO tablename1 VALUES('Richard','Mutt'); + +-- Verändere den fname Wert zu 'John' für alle Zeilen, +-- die einen lname Wert von 'Mutt' haben. +UPDATE tablename1 SET fname='John' WHERE lname='Mutt'; + +-- Lösche Zeilen aus der tablename1 Tabelle, +-- deren lname Wert mit dem Wert 'M' beginnen. +DELETE FROM tablename1 WHERE lname like 'M%'; + +-- Lösche alle Zeilen von der tablename1 Tabelle, hinterlasse nur eine leere +-- Tabelle. +DELETE FROM tablename1; + +-- Lösche die gesamte tablename1 Tabelle. +DROP TABLE tablename1; +``` From 3999e9d011a6db91ad1d8f3f6d5108d251a31524 Mon Sep 17 00:00:00 2001 From: Miltiadis Stouras Date: Thu, 31 Oct 2019 18:43:05 +0200 Subject: [PATCH 002/392] [haskell/el-gr] Add Greek translation for Haskell --- el-gr/haskell-gr.html.markdown | 476 +++++++++++++++++++++++++++++++++ 1 file changed, 476 insertions(+) create mode 100644 el-gr/haskell-gr.html.markdown diff --git a/el-gr/haskell-gr.html.markdown b/el-gr/haskell-gr.html.markdown new file mode 100644 index 00000000..1560e32e --- /dev/null +++ b/el-gr/haskell-gr.html.markdown @@ -0,0 +1,476 @@ +--- +language: Haskell +filename: haskell-gr.html.markdown +contributors: + - ["Miltiadis Stouras", "https://github.com/mstou"] +--- + +Η Haskell σχεδιάστηκε για να είναι μια πρακτική, αγνή συναρτησιακή γλώσσα προγραμματισμού. +Είναι διάσημη για τα monads και το σύστημα τύπων της, αλλά χρησιμοποιείται από πολλούς +κυρίως για την κομψότητά της. Προσωπικά θεωρώ ότι είναι από τις πιο όμορφες, αν όχι +η πιο όμορφη, γλώσσα προγραμματισμού. + +```haskell +-- Τα σχόλια μιας γραμμής ξεκινούν με 2 παύλες. +{- Ενώ τα σχόλια πολλών γραμμών βρίσκονται +μέσα σε blocks σαν αυτό +-} + +---------------------------------------------------- +-- 1. Πρωτόγονοι Τύποι Δεδομένων (Primitive datatype) και Τελεστές +---------------------------------------------------- + +-- Οι αριθμοί είναι ένα primitive datatype +3 -- 3 + +-- Και οι τελεστές κάνουν αυτό που θα περιμέναμε +1 + 1 -- 2 +8 - 1 -- 7 +10 * 2 -- 20 +35 / 5 -- 7.0 + +-- Η καθιερωμένη διαίρεση δεν είναι ακέραια +35 / 4 -- 8.75 + +-- Η ακέραια διαίρεση γίνεται με την συνάρτηση div +35 `div` 4 -- 8 + +-- Και οι boolean μεταβλητές ειναι primitives +True +False + +-- Πράξεις με booleans +not True -- False +not False -- True +1 == 1 -- True +1 /= 1 -- False +1 < 10 -- True + +-- Στα παραπάνω παραδείγματα, το `not` είναι μια συνάρτηση που παίρνει ένα όρισμα +-- Στην Haskell δεν χρειάζονται παρενθέσεις για τις κλήσεις συναρτήσεων, όλες οι παράμετροι +-- γράφονται με κενά αμέσως μετά την συνάρτηση. Στην γενική περίπτωση, +-- η κλήση συνάρτησης μοιάζει κάπως έτσι: func arg1 arg2 arg3... +-- Για το πως να ορίσετε τις δικές σας συναρτήσεις διαβάστε το κεφάλαιο των συναρτήσεων παρακάτω + +-- Συμβολοσειρές και χαρακτήρες +"This is a string." -- συμβολοσειρά +'a' -- χαρακτήρας +'You cant use single quotes for strings.' -- error! +-- δεν μπορούμε να γράψουμε συμβολοσειρές ανάμεσα από '' + +-- Οι συμβολοσειρές μπορούν να συννενωθούν με την χρήση του τελεστή ++ +"Hello " ++ "world!" -- "Hello world!" + +-- Η συμβολοσειρά είναι ουσιαστικά μια λίστα χαρακτήρων +['H', 'e', 'l', 'l', 'o'] -- "Hello" +"This is a string" !! 0 -- 'T' + + +---------------------------------------------------- +-- 2. Λίστες και διατεταγμένα σύνολα (tuples) +---------------------------------------------------- + +-- Όλα τα στοιχεία μιας λίστας πρέπει να είναι του ίδιου τύπου +-- Οι δύο παρακάτω λίστες είναι οι ίδιες: +[1, 2, 3, 4, 5] +[1..5] -- διάστημα ή range + +-- Τα διαστήματα μπορούν να χρησιμοποιηθούν και για άλλους τύπους εκτός από αριθμούς +['A'..'F'] -- "ABCDEF" + +-- Μπορούμε ακόμη να ορίσουμε και ένα βήμα +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- [] (Το default βήμα της Haskell είναι το 1, επομένως η διπλανή λίστα είναι κενή) +[5,4..1] -- [5, 4, 3, 2, 1] + +-- Προσπέλαση στοιχείου σε τυχαία θέση +[1..10] !! 3 -- 4 (οι δείκτες των θέσεων ξεκινούν από το 0) + +-- Στην Haskell υπάρχουν και άπειρες λίστες! +[1..] -- η λίστα των φυσικών αριθμών + +-- Οι άπειρες λίστες μπορούν να λειτουργούν επειδή η Haksell έχει "lazy evaluation". +-- Αυτό σημαίνει ότι η Haskell κάνει υπολογισμούς μόνο όταν πραγματικά χρειάζεται! +-- οπότε αν ζητήσουμε το 1000στό στοιχείο μιας άπειρης λίστας θα μας το δώσει, +-- ξέρει ότι δεν χρειάζεται να υπολογίσει όλη την άπειρη λίστα πρώτα! + +[1..] !! 999 -- 1000 + +-- Στο παραπάνω παράδειγμα η Haskell υπολόγισε τα στοιχεία 1 μέχρι 1000...τα υπόλοιπα +-- στοιχεία της άπειρης λίστας δεν υπάρχουν ακόμα! Η Haskell θα τα υπολογίσει +-- μόνο αν κάποια στιγμή τα χρειαστεί. + +-- συνένωση δύο λιστών με τον τελεστή ++ (σε γραμμικό χρόνο) +[1..5] ++ [6..10] + +-- προσθήκη στοιχείου στην αρχή της λίστας (σε σταθερό χρόνο) +0:[1..5] -- [0, 1, 2, 3, 4, 5] + +-- περισσότερες συναρτήσεις για τις λίστες +head [1..5] -- 1 +tail [1..5] -- [2, 3, 4, 5] +init [1..5] -- [1, 2, 3, 4] +last [1..5] -- 5 + +-- list comprehensions +-- ένας άλλος τρόπος να ορίζουμε τις λίστες που θυμίζει πολύ τον ορισμό συνόλων στα μαθηματικά! +[x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] + +-- list comprehension με συνθήκη +[x*2 | x <- [1..5], x*2 > 4] -- [6, 8, 10] + +-- Κάθε στοιχείο ενός tuple μπορεί να έχει διαφορετικό τύπο, όμως το tuple έχει σταθερό μέγεθος. +-- Ένα tuple: +("haskell", 1) + +-- προσπέλαση στοιχείων ενός ζεύγους στοιχείων (δηλαδή ενός tuple μεγέθους 2) +fst ("haskell", 1) -- "haskell" +snd ("haskell", 1) -- 1 + +-- οι παραπάνω συναρτήσεις δεν λειτουργούν σε tuples μεγαλύτερου μεγέθους +snd ("snd", "can't touch this", "da na na na") -- error! + +---------------------------------------------------- +-- 3. Συναρτήσεις +---------------------------------------------------- +-- Μια απλή συνάρτηση που παίρνει 2 μεταβλητές a, b και επιστρέφει το άθροισμά τους +add a b = a + b + +-- Προσέξτε ότι αν χρησιμοποιείτε το διαδραστικό περιβάλλον της Haskell (ghci), δηλαδή +-- τον interpreter, θα πρέπει να προσθέσετε ενα `let` πριν τον ορισμό της συνάρτησης: +-- let add a b = a + b + +-- Κλήση της συνάρτησης +add 1 2 -- 3 + +-- Μπορούμε να καλέσουμε την συνάρτηση και σαν τελεστή ανάμεσα στα 2 ορίσματα +-- γράφοντας το όνομα της συνάρτησης μέσα σε backticks: +1 `add` 2 -- 3 + +-- Μπορούμε να ορίσουμε και συναρτήσεις που δεν έχουν γράμματα στο όνομά τους! +-- Αυτό μας επιτρέπει να ορίσουμε δικούς μας τελεστές, όπως για παράδειγμα την ακέραια διάιρεση: + +(//) a b = a `div` b +35 // 4 -- 8 + +-- Guards: ένας εύκολος τρόπος να υλοποιήσουμε διακλαδώσεις σε μια συνάρτηση +fib x + | x < 2 = 1 + | otherwise = fib (x - 1) + fib (x - 2) + +-- Το ταίριασμα προτύπων (Pattern matching) είναι παρόμοιο. +-- Εδώ δίνουμε 3 διαφορετικούς ορισμούς για την συνάρτηση fib +-- H Haskell θα χρησιμοποιήσει αυτόματα τον πρώτο ορισμό το οποίου οι παράμετροι +-- ταιριάζουν με τις παραμέτρους της κλήσης + +fib 1 = 1 +fib 2 = 2 +fib x = fib (x - 1) + fib (x - 2) + +-- Pattern matching σε tuples +sndOfTriple (_, y, _) = y +-- η κάτω παύλα χρησιμοποιείται για να μην δίνουμε ονόματα +-- σε μεταβλητές που δεν θα χρησιμοποιήσουμε και +-- ταιριάζει με όλους τους τύπους + +-- Pattern matching σε λίστες. +-- Στο παρακάτω παράδειγμα, το `x` είναι το πρώτο στοιχείο της λίστας +-- και τo `xs` είναι η λίστα με τα υπόλοιπα στοιχεία + +myMap func [] = [] +myMap func (x:xs) = func x : (myMap func xs) + +-- Μπορούμε να ορίσουμε και ανώνυμες συναρτήσεις (lambdas) χρησιμοποιώντας το +-- backslash (που μοιάζει με λ) ακολουθούμενο από τις παραμέτρους: +myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] + +-- χρήση της συνάρτησης fold με μία ανώνυμη συνάρτηση +-- Το foldl1 είναι σαν fold από αριστερά, αλλά χρησιμοποιεί σαν αρχική τιμή του +-- accumulator το πρώτο στοιχείο της λίστας. +foldl1 (\acc x -> acc + x) [1..5] -- 15 + +---------------------------------------------------- +-- 4. Περισσότερες συναρτήσεις +---------------------------------------------------- + +-- Μερική κλήση: αν δεν περάσουμε όλες τις μεταβλητές σε μια συνάρτηση, +-- τότε αυτή "καλείται μερικώς". Αυτό σημαίνει ότι μας επιστρέφει μια συνάρτηση +-- η οποία παίρνει ως ορίσματα τις εναπομείναντες μεταβλητές + +add a b = a + b +foo = add 10 -- η foo είναι μια συνάρτηση που περιμένει 1 αριθμό και του προσθέτει 10 +foo 5 -- 15 + +-- Ένας άλλος τρόπος να γράψουμε το ίδιο πράγμα: +foo = (10+) +foo 5 -- 15 + +-- Σύνθεση συναρτήσεων +-- Ο τελεστής `.` χρησιμοποιείται για την σύνθεση ("αλυσίδωση") συναρτήσεων. +-- Για παράδειγμα, η foo παρακάτω είναι μια συνάρτηση που παίρνει ως όρισμα 1 αριθμό. +-- Πρώτα προσθέτει 10 στον αριθμό που δώσαμε και μετά πολλαπλασιάζει το αποτέλεσμα με 4 +foo = (4*) . (10+) + +-- 4*(10+5) = 60 +foo 5 -- 60 + +-- διόρθωση προτεραιότητας +-- Στην Haskell υπάρχει ο τελεστής `$`. Ο τελεστής αυτός εφαρμόζει μια συνάρτηση +-- σε μία παράμετρο. Σε αντίθεση με την απλή εφαρμογή συνάρτησης, η οποία έχει +-- την μεγαλύτερη πιθανή προτεραιότητα και είναι αριστερά προσεταιριστική, +-- ο τελεστής `$` έχει την ελάχιστη προτεραιότητας και είναι δεξιά προσεταιριστικός. +-- Λόγω της χαμηλής του προτεραιότητας, η έκφραση που βρίσκεται στα δεξιά του +-- θα υπολογιστεί και θα περαστεί σαν παράμετρος στην συνάρτηση που βρίσκεται στα αριστερά του + + +-- πριν +even (fib 7) -- false + +-- ισοδύναμα +even $ fib 7 -- false + +-- χρησιμοποιόντας σύνθεση συναρτήσεων +even . fib $ 7 -- false + + +---------------------------------------------------- +-- 5. Τύποι +---------------------------------------------------- + +-- Η Haskell έχει ένα πολύ ισχυρό σύστημα τύπων, στο οποίο κάθε έκφραση έχει έναν τύπο + +-- Κάποιο βασικοί τύποι: +5 :: Integer +"hello" :: String +True :: Bool + +-- Και οι συναρτήσεις έχουν κάποιο τύπο +-- Η συνάρτηση`not` παίρνει ένα boolean και επιστρέφει ένα boolean: +-- not :: Bool -> Bool + +-- Παρακάτω βλέπετε μια συνάρτηση που παίρνει 2 ορίσματα: +-- add :: Integer -> Integer -> Integer + +-- Όταν ορίζουμε μια συνάρτηση ή μεταβλητή, είναι καλή πρακτική να γράφουμε +-- και τον τύπο της: +double :: Integer -> Integer +double x = x * 2 + +---------------------------------------------------- +-- 6. Έλεγχος ροής και συνθήκες +---------------------------------------------------- + +-- if-expressions +haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" + +-- τα if-expressions μπορούν να πιάνουν και πολλές γραμμές +-- αλλά η στοίχιση είναι σημαντική! +haskell = if 1 == 1 + then "awesome" + else "awful" + +-- case expressions: Με τον παρακάτω τρόπο θα μπορούσαμε να κάνουμε parse +-- command line arguments +case args of + "help" -> printHelp + "start" -> startProgram + _ -> putStrLn "bad args" + +-- Η Haskell δεν έχει βρόχους επανάληψης; αντιθέτως, χρησιμοποιούμε αναδρομή. +-- Η συνάρτηση map εφαρμόζει μια συνάρτηση σε κάθε στοιχείο μιας λίστας + +map (*2) [1..5] -- [2, 4, 6, 8, 10] + +-- μπορούμε να κατασκευάσουμε τον βρόχο for χρησιμοποιώντας την map +for array func = map func array + +-- και να τον χρησιμοποιήσουμε +for [0..5] $ \i -> show i + +-- το παραπάνω θα μπορούσε να γραφτεί και έτσι: +for [0..5] show + +-- Μπορούμε να χρησιμοποιήσουμε τις συναρτήσεις foldl και foldr +-- για να υπολογίζουμε μια τιμή από μια λίστα (πχ άθροισμα ή γινόμενο) +-- foldl +foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 + +-- Η παραπάνω κλήση είναι η ίδια με: +(2 * (2 * (2 * 4 + 1) + 2) + 3) + +-- Η foldl γίνεται από τα αριστερά ενώ η foldr από τα δεξιά +foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 + +-- Η παραπάνω κλήση είναι τώρ: +(2 * 1 + (2 * 2 + (2 * 3 + 4))) + +---------------------------------------------------- +-- 7. Τύποι δεδομένων +---------------------------------------------------- + +-- Με τον παρακάτω τρόπο μπορούμε να ορίζουμε δικούς μας τύπους +-- δεδομένων στην Haskell + +data Color = Red | Blue | Green + +-- Τώρα μπορούμε να χρησιμοποιήσουμε τον τύπο μας και σε συναρτήσεις: + +say :: Color -> String +say Red = "You are Red!" +say Blue = "You are Blue!" +say Green = "You are Green!" + +-- Οι τύποι δεδομένων μας μπορεί να είναι και παραμετρικοί, να δέχονται δηλαδή +-- κάποιον τύπο ως παράμετρο + +data Maybe a = Nothing | Just a + +-- Όλες οι παρακάτω τιμές έχουν τύπο Maybe +Just "hello" -- of type `Maybe String` +Just 1 -- of type `Maybe Int` +Nothing -- of type `Maybe a` for any `a` + +---------------------------------------------------- +-- 8. Haskell IO +---------------------------------------------------- + +-- Αν και το IO δεν μπορεί να εξηγηθεί σε βάθος χωρίς να εξηγήσουμε +-- πρώτα τα monads, δεν είναι δύσκολο να το εξηγήσουμε αρκετά ώστε να μπορεί +-- κάποιος να το χρησιμοποιήσει + +-- Όταν ένα πρόγραμμα Haskell εκτελείται, καλείται η συνάρτηση `main` +-- Η συνάρτηση αυτή πρέπει να επιστρέφει τύπο `IO a` για κάποιο τύπο `a`. +-- Για παράδειγμα: + +main :: IO () +main = putStrLn $ "Hello, sky! " ++ (say Blue) +-- η συνάρτηση putStrLn έχει τύπο: String -> IO () + +-- Είναι πιο εύκολο να χρησιμοποιήσουμε IO αν μπορούμε να γράψουμε το πρόγραμμά μας +-- ως μια συνάρτηση από String σε String. Η συνάρτηση +-- interact :: (String -> String) -> IO () +-- παίρνει ως είσοδο ένα string, τρέχει μια συνάρτηση πάνω στην είσοδο +-- και τυπώνει την έξοδο + +countLines :: String -> String +countLines = show . length . lines + +main' = interact countLines + +-- Μπορείτε να σκεφτείτε μια συνάρτηση που επιστρέφει τιμή με τύπο `IO ()` +-- ως μια ακολουθία πράξεων, περίπου όπως και σε μια imperative γλώσσα +-- Μπορούμε να χρησιμοποιήσουμε το `do` και να ενώσουμε αυτές τις κλήσεις +-- Για παράδειγμα: + +sayHello :: IO () +sayHello = do + putStrLn "What is your name?" + name <- getLine -- η συνάρτηση αυτή διαβάζει μια γραμμή και την αναθέτει στην μετβαλήτη name + putStrLn $ "Hello, " ++ name + +-- Δοκιμάστε να γράψετε την συνάρτηση `interact` που θα διαβάζει μια γραμμή + +-- Ωστόσο ο κώδικας της συνάρτησης `sayHello` δεν θα εκτελεστεί ποτέ. Η μόνη συνάρτηση +-- που εκτελείται όταν κάνουμε compile ένα αρχείο haskell είναι η `main`. +-- Αν θέλετε να τρέξετε την sayHello (εκτός από το να φορτώσετε τον κώδικα στο +-- ghci) μπορείτε να βάλετε σε σχόλια τον προηγούμενο ορισμό της main +-- και να την ορίσετε ως: +-- main = sayHello + +-- Ας προσπαθήσουμε να καταλάβουμε πως λειτουργεί η συνάρτηση `getLine` +-- Ο τύπος της είναι: +-- getLine :: IO String +-- Μπορείτε να φανταστείτε ότι μια τιμή με τύπο `IO a` θα παραχθεί +-- από ένα πρόγραμμα που παράγει μια τιμή με τύπο `a` (ενώ παράλληλα κάνει και κάτι άλλο) +-- Μπορούμε να πάρουμε και να επαναχρησιμοποιήσουμε αυτήν την τιμή χρησιμοποιώντας +-- το `<-`. Μπορούμε ακόμα και να φτιάξουμε την δική μας συνάρτηση με τύπο +-- `IO String`: + +action :: IO String +action = do + putStrLn "This is a line. Duh" + input1 <- getLine + input2 <- getLine + -- Ο τύπος του `do` μπλοκ είναι εκείνος της τελευταίας γραμμής. + -- Το `return` δεν είναι κάποια ειδική λέξη, αλλά απλώς μια συνάρτηση + return (input1 ++ "\n" ++ input2) -- return :: String -> IO String + +-- Μπορούμε να χρησιμοποιήσουμε την παραπάνω συνάρτηση ακριβώς όπως την `getLine`: + +main'' = do + putStrLn "I will echo two lines!" + result <- action + putStrLn result + putStrLn "This was all, folks!" + +-- Ο τύπος `IO` είναι παράδειγμα ενός "monad". Χρησιμοποιώντας τα monads για το +-- ΙΟ, η Haskell καταφέρνει να είναι αγνή συναρτησιακή γλώσσα. Κάθε συνάρτηση που +-- αλληλεπιδρά με τον έξω κόσμο (δηλαδή κάνει IO), έχει το IO (ή κάποιο άλλο monad) +-- στον τύπο της. Αυτό μας διευκολύνει να γνωρίζουμε ποιές συναρτήσεις είναι αγνές +-- (μαθηματικές -- δεν αλληλεπιδρούν με τον έξω κόσμο ούτε αλλάζουν κάποιο state) +-- και ποιες δεν είναι. + +-- Αυτό είναι ένα πολύ ισχυρό χαρακτηριστικό γιατί είναι πολύ εύκολο να +-- εκτελούμε παράλληλα αγνές συναρτήσεις! Οπότε η παραλληλοποίηση στην Haskell +-- είναι αρκετά πιο εύκολη + +---------------------------------------------------- +-- 9. Haskell REPL +---------------------------------------------------- + +-- Μπορείτε να ξεκινήσετε το διαδραστικό περιβάλλον της Haskell με την εντολή `ghci`. +-- Εδώ μπορείτε να γράψετε και να εκτελέσετε κώδικα haskell. +-- Κάθε νέα τιμή πρέπει να ορίζεται με το `let` + +let foo = 5 + +-- Μπορείτε να βρείτε τον τύπο μιας συνάρτησης με το `:t`: + +> :t foo +foo :: Integer + +-- Οι τελεστές, όπως οι `+`, `:` και `$`, είναι επίσης συναρτήσεις. +-- Μπορούμε να δούμε τον τύπο τους βάζοντας τους μέσα σε παρενθέσεις: + +> :t (:) +(:) :: a -> [a] -> [a] + +-- Για περισσότερες πληροφορίες για οποιαδήποτε συνάρτηση ή τύπο, +-- μπορείτε να χρησιμοποιήσετε το `:i`: + +> :i (+) +class Num a where + (+) :: a -> a -> a + ... + -- Defined in ‘GHC.Num’ +infixl 6 + + +-- Μπορείτε επίσης να τρέξετε κάθε συνάρτηση με τύπο `IO ()` + +> sayHello +What is your name? +Friend! +Hello, Friend! + +``` + +Υπάρχουν πολλά ακόμα πράγματα να εξερευνήσετε στην Haskell, όπως τα typeclasses +και διάφορα monads! Αυτές οι μαθηματικά ορισμένες έννοιες είναι που κάνουν την +Haskell αυστηρή, αγνή και κομψή! Θα τελειώσουμε αυτήν την σύντομη περιήγηση με +ένα τελευταίο παράδειγμα, η υλοποίηση της QuickSort σε Haskell: + +```haskell +qsort [] = [] +qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater + where lesser = filter (< p) xs + greater = filter (>= p) xs +``` + +Υπάρχουν 2 παραδοσιακοί τρόποι να εγκαταστήσετε την Haskell: +- [Cabal-based installation](http://www.haskell.org/platform/), +- [Stack-based process](https://www.stackage.org/install). + +Στις παρακάτω πηγές μπορείτε να βρείτε αρκετά κομψές εισαγωγές στην Haskell +- [Learn you a Haskell](http://learnyouahaskell.com/), +- [Happy Learn Haskell Tutorial](http://www.happylearnhaskelltutorial.com/), +- [Real World Haskell](http://book.realworldhaskell.org/) From b38d4437120e700646a45dff68b7c4ff3f7109c0 Mon Sep 17 00:00:00 2001 From: Xing Zheng Date: Tue, 8 Jun 2021 09:55:56 +0800 Subject: [PATCH 003/392] `<<` is an expression, not a regex --- yaml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index 6dc5905e..fa7485b8 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -123,7 +123,7 @@ other_anchor: *anchor_name base: &base name: Everyone has same name -# The regexp << is called Merge Key Language-Independent Type. It is used to +# The expression << is called Merge Key Language-Independent Type. It is used to # indicate that all the keys of one or more specified maps should be inserted # into the current map. From 740316311312f4141b6b2184de62836a87672a87 Mon Sep 17 00:00:00 2001 From: Mikhail Krylatykh Date: Thu, 7 Apr 2022 16:58:24 +0300 Subject: [PATCH 004/392] Make some russian spellcheck --- ru-ru/html-ru.html.markdown | 56 ++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 28 deletions(-) diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown index 120981b9..720151a4 100644 --- a/ru-ru/html-ru.html.markdown +++ b/ru-ru/html-ru.html.markdown @@ -8,28 +8,28 @@ translators: lang: ru-ru --- -HTML расшифровывается как Hypertext Markup Language(гипертекстовый язык разметки). -Это язык используют для написания страниц для World Wide Web(всемирной паутины). -Это язык разметки позволяет писать веб-страниц с помощью кода, чтобы определять, -как должны быть отображены текст и данные. +HTML расшифровывается как Hypertext Markup Language (гипертекстовый язык разметки). +Это язык используют для написания страниц для World Wide Web (всемирной паутины). +Этот язык разметки позволяет описать веб-страницу с помощью кода, чтобы определить, +как на ней должны быть отображены текст и данные. На самом деле, HTML файлы представляют собой простые текстовые файлы. -Что такое разметка? Это способ организации данных страницы, -путем открытия и закрытия тегов(помещая данные внутрь этих тегов). -Эта разметка служит, чтобы придать значение тексту, который он окружает. +Что такое разметка? Это способ организации данных страницы +путем открытия и закрытия тегов и помещения данных внутрь этих тегов. +Эта разметка служит, чтобы придать значение тексту, который она окружает. Как и в других языках программирования, HTML имеет много версий. Здесь мы будем говорить о HTML5. **Примечание:** Вы можете тестировать различные теги и элементы по мере продвижения -через учебник на сайте, как [codepen](http://codepen.io/pen/) для того, чтобы увидеть +через учебник на сайте [codepen](http://codepen.io/pen/) для того, чтобы увидеть их влияние, понять, как они работают и ознакомиться с языком. -В данной статье рассматривается в основном HTML синтаксис и некоторые полезные советы. +В данной статье рассматривается в основном HTML-синтаксис и некоторые полезные советы. ```html - + - + @@ -39,7 +39,7 @@ HTML расшифровывается как Hypertext Markup Language(гипе

Привет, мир!

- Переходите сюда, чтоб посмотреть как это выглядит. + Переходите сюда, чтобы посмотреть, как это выглядит.

Это параграф.

Это другой параграф.

@@ -51,41 +51,41 @@ HTML расшифровывается как Hypertext Markup Language(гипе - + - + - + - + - + - Мой сайт + Мой сайт - - - + + +

Hello, world!

- - Переходите сюда, чтоб посмотреть как это выглядит. - -

Это параграф.

+ + Переходите сюда, чтобы посмотреть, как это выглядит. + +

Это параграф.

Это другой параграф.

    - -
  • Это элемент в не нумерованном списке (маркированный список)
  • + +
  • Это элемент в ненумерованном списке (маркированный список)
  • Это еще один элемент
  • И это последний пункт в списке
From e50b23f751d514f17f072d11feae2b55fd14acff Mon Sep 17 00:00:00 2001 From: Mikhail Krylatykh Date: Fri, 8 Apr 2022 11:16:06 +0300 Subject: [PATCH 005/392] Update ru-ru/html-ru.html.markdown Co-authored-by: Andre Polykanine --- ru-ru/html-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown index 720151a4..64ce3fda 100644 --- a/ru-ru/html-ru.html.markdown +++ b/ru-ru/html-ru.html.markdown @@ -9,7 +9,7 @@ lang: ru-ru --- HTML расшифровывается как Hypertext Markup Language (гипертекстовый язык разметки). -Это язык используют для написания страниц для World Wide Web (всемирной паутины). +Этот язык используют для написания страниц для World Wide Web (всемирной паутины). Этот язык разметки позволяет описать веб-страницу с помощью кода, чтобы определить, как на ней должны быть отображены текст и данные. На самом деле, HTML файлы представляют собой простые текстовые файлы. From c76b8f690a577d9ff89947d79c36a96a7c3b4deb Mon Sep 17 00:00:00 2001 From: Mikhail Krylatykh Date: Fri, 8 Apr 2022 11:18:05 +0300 Subject: [PATCH 006/392] Update ru-ru/html-ru.html.markdown Co-authored-by: Andre Polykanine --- ru-ru/html-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown index 64ce3fda..51a2e6a2 100644 --- a/ru-ru/html-ru.html.markdown +++ b/ru-ru/html-ru.html.markdown @@ -51,7 +51,7 @@ HTML расшифровывается как Hypertext Markup Language (гипе - + From 247dc6e86c1421fa031e4b61c42c05ca6e09bfb0 Mon Sep 17 00:00:00 2001 From: Tanay Parikh Date: Sun, 19 Jun 2022 11:33:07 -0700 Subject: [PATCH 007/392] Python Update `open` File Open `mode` Per https://docs.python.org/3.7/library/functions.html#open, the `+` is for `open a disk file for updating (reading and writing)`. Per the example, if we're looking to just read/write, the `+` isn't necessary. --- python.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index 0bd16a80..e46d726e 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -492,19 +492,19 @@ with open("myfile.txt") as f: # Writing to a file contents = {"aa": 12, "bb": 21} -with open("myfile1.txt", "w+") as file: +with open("myfile1.txt", "w") as file: file.write(str(contents)) # writes a string to a file -with open("myfile2.txt", "w+") as file: +with open("myfile2.txt", "w") as file: file.write(json.dumps(contents)) # writes an object to a file # Reading from a file -with open('myfile1.txt', "r+") as file: +with open('myfile1.txt', "r") as file: contents = file.read() # reads a string from a file print(contents) # print: {"aa": 12, "bb": 21} -with open('myfile2.txt', "r+") as file: +with open('myfile2.txt', "r") as file: contents = json.load(file) # reads a json object from a file print(contents) # print: {"aa": 12, "bb": 21} From e617660ad5c1885e524bcdb82df5bf3f7c2c14ee Mon Sep 17 00:00:00 2001 From: Alexey Berezuev Date: Wed, 15 Jun 2022 12:17:20 +0300 Subject: [PATCH 008/392] Fix some typos of russian translations --- ru-ru/asymptotic-notation-ru.html.markdown | 6 +++--- ru-ru/binary-search-ru.html.markdown | 2 +- ru-ru/c++-ru.html.markdown | 2 +- ru-ru/c-ru.html.markdown | 2 +- ru-ru/css-ru.html.markdown | 6 +++--- ru-ru/forth-ru.html.markdown | 2 +- ru-ru/haml-ru.html.markdown | 10 ++++----- ru-ru/haskell-ru.html.markdown | 4 ++-- ru-ru/html-ru.html.markdown | 16 +++++++-------- ru-ru/javascript-ru.html.markdown | 2 +- ru-ru/linker-ru.html.markdown | 24 +++++++++++----------- ru-ru/markdown-ru.html.markdown | 2 +- ru-ru/php-ru.html.markdown | 22 ++++++++++---------- ru-ru/pyqt-ru.html.markdown | 2 +- ru-ru/qt-ru.html.markdown | 2 +- ru-ru/sql-ru.html.markdown | 4 ++-- ru-ru/tmux-ru.html.markdown | 2 +- ru-ru/typescript-ru.html.markdown | 4 ++-- ru-ru/vim-ru.html.markdown | 6 +++--- ru-ru/xml-ru.html.markdown | 2 +- ru-ru/yaml-ru.html.markdown | 10 ++++----- 21 files changed, 66 insertions(+), 66 deletions(-) diff --git a/ru-ru/asymptotic-notation-ru.html.markdown b/ru-ru/asymptotic-notation-ru.html.markdown index 7fd02c47..cb276ec1 100644 --- a/ru-ru/asymptotic-notation-ru.html.markdown +++ b/ru-ru/asymptotic-notation-ru.html.markdown @@ -48,7 +48,7 @@ f(n) — время выполнения. Тогда для данного ал С помощью О-символики можно оценить функцию или алгоритм несколькими различными способами. Например, можно оценить алгоритм исходя из нижней оценки, верхней оценки, тождественной оценки. Чаще всего встречается -анализ на основе верхней оценки. Как правило не используется нижняя оценка, +анализ на основе верхней оценки. Как правило, не используется нижняя оценка, потому что она не подходит под планируемые условия. Отличный пример — алгоритмы сортировки, особенно добавление элементов в древовидную структуру. Нижняя оценка большинства таких алгоритмов может быть дана как одна операция. В то время как в @@ -155,8 +155,8 @@ c (c > 0) и n0 (n0 > 0), такие, что `f(n)` >= `c ### Примечание -Асимптотические оценки, сделаные при помощи О Большого и Омега Большого, могут -как являться, так и не являться точными. Для того, чтобы обозначить, что границы не +Асимптотические оценки, сделанные при помощи О Большого и Омега Большого, могут +как являться, так и не являться точными. Для того чтобы обозначить, что границы не являются асимптотически точными, используются записи О Малое и Омега Малое. ### О Малое diff --git a/ru-ru/binary-search-ru.html.markdown b/ru-ru/binary-search-ru.html.markdown index 9ed62cb8..ab1a1585 100644 --- a/ru-ru/binary-search-ru.html.markdown +++ b/ru-ru/binary-search-ru.html.markdown @@ -55,7 +55,7 @@ def search(arr, x): ### На заметку -Существует и другая форма двоичного поиска, которая можеть быть полезна. +Существует и другая форма двоичного поиска, которая может быть полезна. ## На почитать diff --git a/ru-ru/c++-ru.html.markdown b/ru-ru/c++-ru.html.markdown index 3acfafa3..787d31e8 100644 --- a/ru-ru/c++-ru.html.markdown +++ b/ru-ru/c++-ru.html.markdown @@ -17,7 +17,7 @@ C++ - компилируемый, статически типизированн - "лучшая замена C" - язык с поддержкой абстракции данных -- язык с поддержкой объектно-ориентированого программирования +- язык с поддержкой объектно-ориентированного программирования - язык с поддержкой обобщенного программирования Хотя его синтаксис может показаться более трудным или сложным для понимания, чем в более современных языках, diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index cc68d620..2d06a2d0 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -476,7 +476,7 @@ void str_reverse_through_pointer(char *str_in) { Если у вас появился вопрос, почитайте [compl.lang.c Frequently Asked Questions](http://c-faq.com). Очень важно использовать правильные отступы и ставить пробелы в нужных местах. -Читаемый код лучше чем красивый или быстрый код. +Читаемый код лучше, чем красивый или быстрый код. Чтобы научиться писать хороший код, почитайте [Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle). Также не забывайте, что [Google](http://google.com) и [Яндекс](http://yandex.ru) – ваши хорошие друзья. diff --git a/ru-ru/css-ru.html.markdown b/ru-ru/css-ru.html.markdown index e0e5e30b..b543bfeb 100644 --- a/ru-ru/css-ru.html.markdown +++ b/ru-ru/css-ru.html.markdown @@ -20,12 +20,12 @@ HTML элементы и определять их внешний вид. **ВАЖНО:** Так как результатом применения CSS является изменение внешнего вида элементов, постарайтесь использовать CSS-песочницы при изучении языка. -Например [dabblet](http://dabblet.com/). +Например, [dabblet](http://dabblet.com/). В данной статье рассматриваются в первую очередь синтаксис и общие рекомендации. ```css -/* Для комментариев используется слеш-астериск, как на этой строчке. +/* Для комментариев используется слэш-астериск, как на этой строчке. В CSS нет однострочных комментариев; все комментарии записываются таким способом */ /* #################### @@ -104,7 +104,7 @@ div.some-parent.class-name {} .i-am-any-before ~ .this-element {} -/* Существуют псевдо-классы, позволяющие изменять внешний вид элемента +/* Существуют псевдоклассы, позволяющие изменять внешний вид элемента в зависимости от событий, произошедших с элементом */ /* например, когда курсор наведен на элемент */ diff --git a/ru-ru/forth-ru.html.markdown b/ru-ru/forth-ru.html.markdown index 2fc4ad7c..90936b19 100644 --- a/ru-ru/forth-ru.html.markdown +++ b/ru-ru/forth-ru.html.markdown @@ -10,7 +10,7 @@ lang: ru-ru Форт создан Чарлзом Муром в 70-е годы. Это императивный, стековый язык программирования и среда исполнения программ. Использовался в таких проектах как Open Firmware. Продолжает применятся в проектах. Применяется в НАСА. -Внимание: эта материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах. +Внимание: этот материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах. ``` diff --git a/ru-ru/haml-ru.html.markdown b/ru-ru/haml-ru.html.markdown index c2f8852e..ed823496 100644 --- a/ru-ru/haml-ru.html.markdown +++ b/ru-ru/haml-ru.html.markdown @@ -39,7 +39,7 @@ $ haml input_file.haml output_file.html / Комментарии / ------------------------------------------- -/ Комментари начинается с символа косой черты. +/ Комментарии начинается с символа косой черты. / Для написания многострочного комментария расположите ваш комментарий @@ -94,7 +94,7 @@ $ haml input_file.haml output_file.html / выведет 'Да & да' / - Чтобы выполнять Ruby-код без экранрования, можно использовать + Чтобы выполнять Ruby-код без экранирования, можно использовать "восклицательный знак" и "равно" (!=) %p @@ -196,13 +196,13 @@ $ haml input_file.haml output_file.html / ------------------------------------------- / - Фильтры передают связанный блок текста в соотвествующую + Фильтры передают связанный блок текста в соответствующую фильтрующую программу и возвращают результат в Haml Фильтр обозначается двоеточием и названием фильтра: / Markdown filter :markdown - # Заголовк + # Заголовок Текст **внутри** *блока* @@ -221,7 +221,7 @@ $ haml input_file.haml output_file.html / - Существует множество типов фильров (:markdown, :javascript, :coffee, + Существует множество типов фильтров (:markdown, :javascript, :coffee, :css, :ruby и так далее). Вы можете определить собственный фильтр c помощью Haml::Filters. diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown index b1b8eb79..a090ab65 100644 --- a/ru-ru/haskell-ru.html.markdown +++ b/ru-ru/haskell-ru.html.markdown @@ -8,7 +8,7 @@ translators: lang: ru-ru --- -Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. [Меня][autor] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и [я][autor] получаю истинное удовольствие, программируя на Haskell. +Haskell разрабатывался, как чистый функциональный язык программирования, применимый на практике. Язык известен благодаря своей системе типов, и "знаменит" благодаря монадам. [Меня][author] же Haskell заставляет возвращаться к себе снова и снова именно своей элегантностью и [я][author] получаю истинное удовольствие, программируя на Haskell. ```haskell -- Однострочные комментарии начинаются с двух дефисов @@ -544,4 +544,4 @@ Haskell прост в установке, забирайте [здесь](http:/ [Learn you a Haskell](http://learnyouahaskell.com/) и [Real World Haskell](http://book.realworldhaskell.org/). -[autor]: http://adit.io имеется в виду автор оригинального текста Adit Bhargava *(примечание переводчика)* +[author]: http://adit.io имеется в виду автор оригинального текста Adit Bhargava *(примечание переводчика)* diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown index 120981b9..4220902e 100644 --- a/ru-ru/html-ru.html.markdown +++ b/ru-ru/html-ru.html.markdown @@ -25,7 +25,7 @@ HTML расшифровывается как Hypertext Markup Language(гипе В данной статье рассматривается в основном HTML синтаксис и некоторые полезные советы. ```html - + @@ -71,19 +71,19 @@ HTML расшифровывается как Hypertext Markup Language(гипе Мой сайт - - - + + +

Hello, world!

Переходите сюда, чтоб посмотреть как это выглядит. - -

Это параграф.

+ +

Это параграф.

Это другой параграф.

    -
  • Это элемент в не нумерованном списке (маркированный список)
  • Это еще один элемент
  • @@ -124,6 +124,6 @@ HTML файлы имеют окончание(расширение) `.html`. ## Узнать больше -* [википедиа](https://ru.wikipedia.org/wiki/HTML) +* [википедия](https://ru.wikipedia.org/wiki/HTML) * [HTML учебник](https://developer.mozilla.org/ru/docs/Web/HTML) * [htmlbook](http://htmlbook.ru/) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 4556b425..4c4fa503 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -504,7 +504,7 @@ if (Object.create === undefined) { // не перезаписываем мето [Mozilla Developer Network](https://developer.mozilla.org/ru/docs/Web/JavaScript) — предоставляет отличную документацию для JavaScript, как он используется в браузерах. -Кроме того, это вики, поэтому, если вы знаете больше, вы можете помочь другим, +Кроме того, это вики. Поэтому, если вы знаете больше, вы можете помочь другим, делясь своими знаниями. [JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) — это diff --git a/ru-ru/linker-ru.html.markdown b/ru-ru/linker-ru.html.markdown index 7df29c23..14cfd229 100644 --- a/ru-ru/linker-ru.html.markdown +++ b/ru-ru/linker-ru.html.markdown @@ -34,11 +34,11 @@ lang: ru-ru # Определяем точку входа в программу ENTRY(Reset_Handler) -# Определяем перемнную которая содержит адрес вершины стека +# Определяем переменную которая содержит адрес вершины стека _estack = 0x20020000; -# Определяем перемнную которая содержит значение размера кучи +# Определяем переменную которая содержит значение размера кучи _Min_Heap_Size = 0x200; -# Определяем перемнную которая содержит значение размера стека +# Определяем переменную которая содержит значение размера стека _Min_Stack_Size = 0x400; # Описание карты памяти доступной для данного процессора @@ -50,7 +50,7 @@ _Min_Stack_Size = 0x400; # RAM - начинается с адреса 0x20000000 и занимает 128 Кбайт; # CCMRAM - начинается с адреса 0x10000000и занимает 64 Кбайт; # FLASH - начинается с адреса 0x8000000 занимает 1024 Кбайт; -# Причем RAM память доступка для чтения, записи и исполнения. +# Причем RAM память доступна для чтения, записи и исполнения. # CCMRAM память доступна только на чтение и запись. # FLASH память доступна на чтение и исполнение. MEMORY @@ -70,7 +70,7 @@ SECTIONS . = ALIGN(4); # Существует опция --gc-sections, которая позволяет собирать мусор из неиспользуемых - # входных разделов. И если есть разделы, которые сборщик муссора не должен трогать, + # входных разделов. И если есть разделы, которые сборщик мусора не должен трогать, # то их необходимо указать в качестве аргумента функции KEEP() (аналог ключевого слова # volatile). # Запись (*(.isr_vector)) означает разделы .isr_vector во всех объектных файлах. Т.к. @@ -80,8 +80,8 @@ SECTIONS # Выравниваем текущую позицию на границу 4-х байт. . = ALIGN(4); - # Выражение ">ОБЛАСТЬ_ПАМЯТИ" указывает в какую именно область памяти будет помещенна - # данная секция. В нашем слущае секция .isr_vector будет размещена во FLASH памяти. + # Выражение ">ОБЛАСТЬ_ПАМЯТИ" указывает в какую именно область памяти будет помещена + # данная секция. В нашем случае секция .isr_vector будет размещена во FLASH памяти. } >FLASH # ИТОГО: Секция .isr_vector, которая содержит таблицу векторов прерываний выравнивается @@ -125,7 +125,7 @@ SECTIONS # Выравниваем текущую позицию на границу 4-х байт. . = ALIGN(4); - # Указываем, что в данной секции будут хранится области .rodataвсех + # Указываем, что в данной секции будут хранится области .rodata всех # объектных файлов *(.rodata) *(.rodata*) @@ -158,13 +158,13 @@ SECTIONS _edata = .; # Функция AT указывает на то, что данный сектор хранится в одной области памяти - # (в нашем случае FLASH), а исполняться будет из другой обасти памяти (в нашем случае RAM). - # Есть два типа адрессов: - # * VMA (Virtual memory address) - это run-time адрес по которому уомпилятор ожидает + # (в нашем случае FLASH), а исполняться будет из другой области памяти (в нашем случае RAM). + # Есть два типа адресов: + # * VMA (Virtual memory address) - это run-time адрес по которому компилятор ожидает # видеть данные. # * LMA (Load memory address) - это адрес по которому линкер хранит данные. - #Startup должен код скопировать секцию .data из адрессов LMA в адресса VMA. + #Startup должен код скопировать секцию .data из адресов LMA в адреса VMA. } >RAM AT> FLASH diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index 579a9a20..728741af 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -294,7 +294,7 @@ Markdown также позволяет размечать ссылку в вид ```md ![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка") ``` -Изображения тоже могут быть оформлены, как сноски. +Изображения тоже могут быть оформлены как сноски.
    ![Это альтернативный текст.][myimage]
     
    diff --git a/ru-ru/php-ru.html.markdown b/ru-ru/php-ru.html.markdown
    index af77a9ca..4a508cfc 100644
    --- a/ru-ru/php-ru.html.markdown
    +++ b/ru-ru/php-ru.html.markdown
    @@ -125,7 +125,7 @@ echo 'Multiple', 'Parameters', 'Valid'; // печатает 'MultipleParametersV
     // и никогда не может быть изменена во время выполнения программы!
     
     // Правильное имя константы начинается с буквы или символа подчеркивания
    -// и содержит любое колличество букв, цифр или символов подчеркивания.
    +// и содержит любое количество букв, цифр или символов подчеркивания.
     define("FOO", "something");
     
     // Доступ к константе возможен через прямое указание её имени без знака $
    @@ -224,7 +224,7 @@ assert($c > $b); // больше
     assert($a <= $b); // меньше или равно
     assert($c >= $d); // больше или равно
     
    -// Следующие утверждения истинны, если переменные имеют одинаковые тип.
    +// Следующие утверждения истинны, если переменные имеют одинаковый тип.
     assert($c === $d);
     assert($a !== $d);
     assert(1 == '1');
    @@ -251,7 +251,7 @@ echo $string + $string; // => 2 (строка превращается в чис
     $string = 'one';
     echo $string + $string; // => 0
     
    -// Приведение типов (type casting) может быть использовано для преобразование
    +// Приведение типов (type casting) может быть использовано для преобразования
     // переменной в другой тип
     $boolean = (boolean) 1; // => true
     
    @@ -458,7 +458,7 @@ include_once 'my-file.php';
     require 'my-file.php';
     require_once 'my-file.php';
     
    -// Действует также как и include(), но если файл не удалось подключить,
    +// Действует так же как и include(), но если файл не удалось подключить,
     // функция выдает фатальную ошибку
     
     // Содержимое файла my-include.php:
    @@ -497,7 +497,7 @@ class MyClass
     
         // Конструктор описывается с помощью __construct
         public function __construct($instanceProp) {
    -        // Доступ к эземпляру класса с помощью $this
    +        // Доступ к экземпляру класса с помощью $this
             $this->instanceProp = $instanceProp;
         }
     
    @@ -661,7 +661,7 @@ $cls->myTraitMethod(); // Напечатает "I have MyTrait"
     
    +
     
     
     
    diff --git a/ru-ru/yaml-ru.html.markdown b/ru-ru/yaml-ru.html.markdown
    index ddaed2b6..693848fc 100644
    --- a/ru-ru/yaml-ru.html.markdown
    +++ b/ru-ru/yaml-ru.html.markdown
    @@ -12,7 +12,7 @@ lang: ru-ru
     YAML как язык сериализации данных предназначен прежде всего для использования людьми.
     
     Это строгое надмножество JSON с добавлением синтаксически значимых переносов строк и 
    -отступов как в Python. Тем не менее, в отличие от Python, YAML запрещает 
    +отступов как в Python. Тем не менее в отличие от Python, YAML запрещает 
     использование табов для отступов.
     
     ```yaml
    @@ -53,7 +53,7 @@ literal_block: |
             Любые строки с большим отступом сохраняют остатки своего отступа -  
             эта строка будет содержать дополнительно 4 пробела.
     folded_style: >
    -    Весь блок этого тектса будет значением 'folded_style', но в данном случае
    +    Весь блок этого текста будет значением 'folded_style', но в данном случае
         все символы новой строки будут заменены пробелами.
     
         Пустые строки будут преобразованы в перенос строки.
    @@ -76,7 +76,7 @@ a_nested_map:
     0.25: a float key
     
     # Ключи также могут быть сложными, например многострочными.
    -# Мы используем ? с последующим пробелом чтобы обозначить начало сложного ключа.
    +# Мы используем ? с последующим пробелом, чтобы обозначить начало сложного ключа.
     ? |
       Этот ключ
       который содержит несколько строк
    @@ -124,7 +124,7 @@ base: &base
       name: Каждый будет иметь одинаковое имя
     
     # Регулярное выражение << называется ключом объединения независимо от типа языка.
    -# Он используется чтобы показать что все ключи одного или более словарей должны быть
    +# Он используется, чтобы показать что все ключи одного или более словарей должны быть
     # добавлены в текущий словарь.
     
     foo: &foo
    @@ -185,5 +185,5 @@ set2:
     
     ### Больше информации
     
    -+ [YAML оффициальный вебсайт](http://yaml.org/)
    ++ [YAML официальный вебсайт](http://yaml.org/)
     + [YAML онлайн валидатор](http://www.yamllint.com/)
    
    From b5ab0b79282ff1ddf8b5f60e45a7326c84c9b5dd Mon Sep 17 00:00:00 2001
    From: Charliecoolblue <89911250+Charliecoolblue@users.noreply.github.com>
    Date: Tue, 4 Oct 2022 17:15:08 +0200
    Subject: [PATCH 009/392] [powershell/en] correct examples for arrays
    
    Fixed incorrect examples for arrays.
    Added information for tuple
    Fixed wording for Hashtables
    ---
     powershell.html.markdown | 53 +++++++++++++++++++---------------------
     1 file changed, 25 insertions(+), 28 deletions(-)
    
    diff --git a/powershell.html.markdown b/powershell.html.markdown
    index 033d6c25..5d21ef67 100644
    --- a/powershell.html.markdown
    +++ b/powershell.html.markdown
    @@ -221,7 +221,7 @@ $defaultArray.Add("thing4") # => Exception "Collection was of a fixed size."
     # ArrayLists store sequences
     [System.Collections.ArrayList]$array = @()
     # You can start with a prefilled ArrayList
    -[System.Collections.ArrayList]$otherArray = @(4, 5, 6)
    +[System.Collections.ArrayList]$otherArray = @(5, 6, 7, 8)
     
     # Add to the end of a list with 'Add' (Note: produces output, append to $null)
     $array.Add(1) > $null    # $array is now [1]
    @@ -237,25 +237,14 @@ $array.Add(3) > $null   # array is now [1, 2, 4, 3] again.
     $array[0]   # => 1
     # Look at the last element
     $array[-1]  # => 3
    -
     # Looking out of bounds returns nothing
     $array[4]  # blank line returned
     
    -# You can look at ranges with slice syntax.
    -# The start index is included, the end index is not
    -# (It's a closed/open range for you mathy types.)
    -$array[1..3]   # Return array from index 1 to 3 => [2, 4]
    -$array[2..-1]    # Return array starting from index 2 => [4, 3]
    -$array[0..3]    # Return array from beginning until index 3  => [1, 2, 4]
    -$array[0..2]   # Return array selecting every second entry => [1, 4]
    -$array.Reverse()  # mutates array to reverse order => [3, 4, 2, 1]
    -# Use any combination of these to make advanced slices
    +# Remove elements from a array
    +$array.Remove($array[3])  # $array is now [1, 2, 4]
     
    -# Remove arbitrary elements from a array with "del"
    -$array.Remove($array[2])  # $array is now [1, 2, 3]
    -
    -# Insert an element at a specific index
    -$array.Insert(1, 2)  # $array is now [1, 2, 3] again
    +# Insert at index an element 
    +$array.Insert(2, 3)  # $array is now [1, 2, 3, 4]
     
     # Get the index of the first item found matching the argument
     $array.IndexOf(2)  # => 1
    @@ -263,16 +252,24 @@ $array.IndexOf(6)  # Returns -1 as "outside array"
     
     # You can add arrays
     # Note: values for $array and for $otherArray are not modified.
    -$array + $otherArray  # => [1, 2, 3, 4, 5, 6]
    +$array + $otherArray  # => [1, 2, 3, 4, 5, 6, 7, 8]
     
     # Concatenate arrays with "AddRange()"
    -$array.AddRange($otherArray)  # Now $array is [1, 2, 3, 4, 5, 6]
    +$array.AddRange($otherArray)  # Now $array is [1, 2, 3, 4, 5, 6, 7, 8]
     
     # Check for existence in a array with "in"
     1 -in $array  # => True
     
     # Examine length with "Count" (Note: "Length" on arrayList = each items length)
    -$array.Count  # => 6
    +$array.Count  # => 8
    +
    +# You can look at ranges with slice syntax.
    +$array[1,3,5]     # Return selected index  => [2, 4, 6]
    +$array[1..3]      # Return from index 1 to 3 => [2, 3, 4]
    +$array[-3..-1]    # Return from last 3 to last 1 => [6, 7, 8]
    +$array[-1..-3]    # Return from last 1 to last 3 => [8, 7, 6]
    +$array[2..-1]     # Return from index 2 to last (NOT as most expect) => [3, 2, 1, 8]
    +$array[0,2+4..6]  # Return multiple ranges with the + => [1, 3, 5, 6, 7]
     
     
     # Tuples are like arrays but are immutable.
    @@ -284,13 +281,14 @@ $tuple.Item(0) = 3  # Raises a TypeError
     # You can do some of the array methods on tuples, but they are limited.
     $tuple.Length       # => 3
     $tuple + (4, 5, 6)  # => Exception
    -$tuple[0..2]        # => $null
    +$tuple[0..2]        # => $null (in powershell 5)    => [1, 2, 3] (in powershell 7)
     2 -in $tuple        # => False
     
     
    -# Hashtables store mappings from keys to values, similar to Dictionaries.
    +# Hashtables store mappings from keys to values, similar to (but distinct from) Dictionaries.
    +# Hashtables do not hold entry order as arrays do. 
     $emptyHash = @{}
    -# Here is a prefilled dictionary
    +# Here is a prefilled hashtable
     $filledHash = @{"one"= 1 
                     "two"= 2 
                     "three"= 3}
    @@ -299,7 +297,6 @@ $filledHash = @{"one"= 1
     $filledHash["one"]  # => 1
     
     # Get all keys as an iterable with ".Keys".
    -# items maintain the order at which they are inserted into the dictionary.
     $filledHash.Keys  # => ["one", "two", "three"]
     
     # Get all values as an iterable with ".Values".
    @@ -307,18 +304,18 @@ $filledHash.Values  # => [1, 2, 3]
     
     # Check for existence of keys or values in a hash with "-in"
     "one" -in $filledHash.Keys  # => True
    -1 -in $filledHash.Values    # => False
    +1 -in $filledHash.Values    # => False (in powershell 5)    => True (in powershell 7)
     
     # Looking up a non-existing key returns $null
     $filledHash["four"]  # $null
     
    -# Adding to a dictionary
    +# Adding to a hashtable
     $filledHash.Add("five",5)  # $filledHash["five"] is set to 5
     $filledHash.Add("five",6)  # exception "Item with key "five" has already been added"
    -$filledHash["four"] = 4 # $filledHash["four"] is set to 4, running again does nothing
    +$filledHash["four"] = 4    # $filledHash["four"] is set to 4, running again does nothing
     
    -# Remove keys from a dictionary with del
    -$filledHash.Remove("one") # Removes the key "one" from filled dict
    +# Remove keys from a hashtable
    +$filledHash.Remove("one") # Removes the key "one" from filled hashtable
     
     
     ####################################################
    
    From 02724e0fd19ccbaf843b0ca312115b198916750e Mon Sep 17 00:00:00 2001
    From: Takashicc <105186894+Takashicc@users.noreply.github.com>
    Date: Sat, 5 Nov 2022 11:27:20 +0900
    Subject: [PATCH 010/392] feat: Add traslate for rust in ja-jp
    
    ---
     ja-jp/rust-jp.html.markdown | 351 ++++++++++++++++++++++++++++++++++++
     1 file changed, 351 insertions(+)
     create mode 100644 ja-jp/rust-jp.html.markdown
    
    diff --git a/ja-jp/rust-jp.html.markdown b/ja-jp/rust-jp.html.markdown
    new file mode 100644
    index 00000000..3eb381ab
    --- /dev/null
    +++ b/ja-jp/rust-jp.html.markdown
    @@ -0,0 +1,351 @@
    +---
    +language: Rust
    +contributors:
    +    - ["P1start", "http://p1start.github.io/"]
    +filename: learnrust-jp.rs
    +translators:
    +    - ["Takashi Takeda", "https://github.com/Takashicc"]
    +lang: ja-jp
    +---
    +
    +RustはMozilla Researchによって開発されたプログラミング言語です。
    +Rustは低レベルの性能制御と高レベルの利便性と、安全性の保証を兼ね備えています。
    +
    +ガベージコレクションやランタイムを必要としないことから上記の目標が達成出来ます。
    +それによってRustライブラリをC言語の「完全互換品」として使用することが可能です。
    +
    +Rustの最初のリリースである0.1は、2012年1月にリリースされ、
    +その後3年間の開発は非常に速く進み、最近までは安定板リリースの利用は推奨されていませんでした。
    +代わりにナイトリービルドを使用することが一般的なアドバイスでした。
    +
    +2015年5月15日、後方互換性を完全に保障したRust 1.0がリリースされました。
    +コンパイル時間などの改善は、現在ナイトリービルドで提供されています。
    +Rustはトレインリリースモデルを採用しており、6週間ごとにリリースしています。
    +Rust 1.1 ベータ版は、Rust 1.0がリリースされたのと同時にリリースされました。
    +
    +Rustは比較的低レベルの言語ですが、一般的に高水準言語に見られるようないくつかの概念を持っています。
    +これによりRustはただ速いだけではなく、コーディングが簡単で効率的に書くことが出来ます。
    +
    +```rust
    +// これはコメントです。 行コメントはこのように書けます...
    +// そしてこのように複数行に分けて書くこともできます。
    +
    +/// ドキュメントコメントはこのように書けて、マークダウン記法をサポートしています。
    +/// # Examples
    +///
    +/// ```
    +/// let five = 5
    +/// ```
    +
    +////////////
    +// 1. 基本 //
    +////////////
    +
    +#[allow(dead_code)]
    +// 関数
    +// `i32` は32ビットの符号付き整数の型です
    +fn add2(x: i32, y: i32) -> i32 {
    +    // 暗黙の戻り値 (セミコロンなし)
    +    x + y
    +}
    +
    +#[allow(unused_variables)]
    +#[allow(unused_assignments)]
    +#[allow(dead_code)]
    +// Main関数
    +fn main() {
    +    // 数値 //
    +
    +    // 不変な変数
    +    let x: i32 = 1;
    +
    +    // 整数/浮動小数点の型を数値の末尾に
    +    let y: i32 = 13i32;
    +    let f: f64 = 1.3f64;
    +
    +    // 型推論
    +    // ほとんどの場合、Rustコンパイラは変数の型を推測することができるため、
    +    // 明示的に型アノテーションを書く必要はありません。
    +    // このチュートリアルでは、多くの場所で明示的に型がアノテーションされていますが、
    +    // あくまで説明目的です。型推論はほとんどの場合処理することができます。
    +    let implicit_x = 1;
    +    let implicit_f = 1.3;
    +
    +    // 算術
    +    let sum = x + y + 13;
    +
    +    // 可変な変数
    +    let mut mutable = 1;
    +    mutable = 4;
    +    mutable += 2;
    +
    +    // 文字列 //
    +
    +    // 文字列リテラル
    +    let x: &str = "hello world!";
    +
    +    // プリント
    +    println!("{} {}", f, x); // 1.3 hello world
    +
    +    // `String`はヒープに割り当てられた文字列です。
    +    // `Vec`としてヒープに格納され、
    +    // 常に有効なUTF-8シーケンス(ヌル文字で終了していない)を保持します。
    +    let s: String = "hello world".to_string();
    +
    +    // 文字列スライスは不変なビューを別の文字列に変換します。
    +    // これは基本的に文字列への不変のポインタのペアを保持しており、
    +    // 文字そのものは保持していません。
    +    // 文字列バッファの先頭と末尾へのポイントだけを保持しています。
    +    // 静的割り当てられるか、別のオブジェクトに含まれます。(この場合は`s`)
    +    // 文字列スライスは`&[u8]`を`Vec`に変換するようなものです。
    +    let s_slice: &str = &s;
    +
    +    println!("{} {}", s, s_slice); // hello world hello world
    +
    +    // ベクター/配列 //
    +
    +    // 固定サイズの配列
    +    let four_ints: [i32; 4] = [1, 2, 3, 4];
    +
    +    // 動的配列(ベクター)
    +    let mut vector: Vec = vec![1, 2, 3, 4];
    +    vector.push(5);
    +
    +    // スライスは不変なビューをベクターまたは配列に変換します。
    +    // これは文字列スライスによく似ていますが、ベクターに対してのものです。
    +    let slice: &[i32] = &vector;
    +
    +    // デバッグ形式で何かを表示する際は、`{:?}`を使用できます。
    +    println!("{:?} {:?}", vector, slice); // [1, 2, 3, 4, 5] [1, 2, 3, 4, 5]
    +
    +    // タプル //
    +
    +    // タプルは固定サイズの値の集合でできており、値それぞれが異なる型でもよい
    +    let x: (i32, &str, f64) = (1, "hello", 3.4);
    +
    +    // `let`をデストラクト
    +    let (a, b, c) = x;
    +    println!("{} {} {}", a, b, c); // 1 hello 3.4
    +
    +    // インデックス
    +    println!("{}", x.1); // hello
    +
    +    ///////////
    +    // 2. 型 //
    +    ///////////
    +
    +    // 構造体
    +    struct Point {
    +        x: i32,
    +        y: i32,
    +    }
    +
    +    let origin: Point = Point { x: 0, y: 0 };
    +
    +    // 名前のないフィールドで構成された構造体は、タプル構造体と言われる。
    +    struct Point2(i32, i32);
    +
    +    let origin2 = Point2(0, 0);
    +
    +    // C言語風列挙型
    +    enum Direction {
    +        Left,
    +        Right,
    +        Up,
    +        Down,
    +    }
    +
    +    let up = Direction::Up;
    +
    +    // フィールドがある列挙型
    +    enum OptionalI32 {
    +        AnI32(i32),
    +        Nothing,
    +    }
    +
    +    let two: OptionalI32 = OptionalI32::AnI32(2);
    +    let nothing = OptionalI32::Nothing;
    +
    +    // ジェネリクス //
    +
    +    struct Foo { bar: T }
    +
    +    // 以下は標準ライブラリで定義されている`Option`です。
    +    enum Optional {
    +        SomeVal(T),
    +        NoVal,
    +    }
    +
    +    // メソッド //
    +
    +    impl Foo {
    +        // メソッドは明示的に`self`パラメータを受け取ります。
    +        fn bar(&self) -> &T { // `self`は借用されています。
    +            &self.bar
    +        }
    +        fn bar_mut(&mut self) -> &mut T { // `self`は可変に借用されています。
    +            &mut self.bar
    +        }
    +        fn into_bar(self) -> T { // `self`は消費されています。
    +            self.bar
    +        }
    +    }
    +
    +    let a_foo = Foo { bar: 1 };
    +    println!("{}", a_foo.bar()); // 1
    +
    +    // トレイト (他の言語ではインターフェースや型クラスとして知られています) //
    +
    +    trait Frobnicate {
    +        fn frobnicate(self) -> Option;
    +    }
    +
    +    impl Frobnicate for Foo {
    +        fn frobnicate(self) -> Option {
    +            Some(self.bar)
    +        }
    +    }
    +
    +    let another_foo = Foo { bar: 1 };
    +    println!("{:?}", another_foo.frobnicate()); // Some(1)
    +
    +    // 関数ポインタの種類 // 
    +
    +    fn fibonacci(n: u32) -> u32 {
    +        match n {
    +            0 => 1,
    +            1 => 1,
    +            _ => fibonacci(n - 1) + fibonacci(n - 2),
    +        }
    +    }
    +
    +    type FunctionPointer = fn(u32) -> u32;
    +
    +    let fib : FunctionPointer = fibonacci;
    +    println!("Fib: {}", fib(4));
    +
    +    /////////////////////////
    +    // 3. パターンマッチング //
    +    /////////////////////////
    +
    +    let foo = OptionalI32::AnI32(1);
    +    match foo {
    +        OptionalI32::AnI32(n) => println!("it’s an i32: {}", n),
    +        OptionalI32::Nothing  => println!("it’s nothing!"),
    +    }
    +
    +    // 応用的なパターンマッチング
    +    struct FooBar { x: i32, y: OptionalI32 }
    +    let bar = FooBar { x: 15, y: OptionalI32::AnI32(32) };
    +
    +    match bar {
    +        FooBar { x: 0, y: OptionalI32::AnI32(0) } =>
    +            println!("The numbers are zero!"),
    +        FooBar { x: n, y: OptionalI32::AnI32(m) } if n == m =>
    +            println!("The numbers are the same"),
    +        FooBar { x: n, y: OptionalI32::AnI32(m) } =>
    +            println!("Different numbers: {} {}", n, m),
    +        FooBar { x: _, y: OptionalI32::Nothing } =>
    +            println!("The second number is Nothing!"),
    +    }
    +
    +    //////////////////
    +    // 4. 制御フロー //
    +    //////////////////
    +
    +    // `for`ループ/イテレーション
    +    let array = [1, 2, 3];
    +    for i in array {
    +        println!("{}", i);
    +    }
    +
    +    // 範囲
    +    for i in 0u32..10 {
    +        print!("{} ", i);
    +    }
    +    println!("");
    +    // 右記にある文をプリントします `0 1 2 3 4 5 6 7 8 9 `
    +
    +    // `if`
    +    if 1 == 1 {
    +        println!("Maths is working!");
    +    } else {
    +        println!("Oh no...");
    +    }
    +
    +    // 式として使う`if`
    +    let value = if true {
    +        "good"
    +    } else {
    +        "bad"
    +    };
    +
    +    // `while` loop
    +    while 1 == 1 {
    +        println!("The universe is operating normally.");
    +        // break文でwhileループから抜け出せます。
    +        // 無駄な繰り返しを避けることができます。
    +        break
    +    }
    +
    +    // 無限ループ
    +    loop {
    +        println!("Hello!");
    +        // break文でループから抜け出せます。
    +        break
    +    }
    +
    +    ///////////////////////////
    +    // 5. メモリ安全とポインタ //
    +    ///////////////////////////
    +
    +    // 所有ポインタはポインタを「所有」できるのは、一度に1つだけです。
    +    // つまり、`Box`がそのスコープから離れると、自動的に安全に解放されます。
    +    let mut mine: Box = Box::new(3);
    +    *mine = 5; // デリファレンス
    +    // ここで`now_its_mine`が`mine`の所有権を取得します。言い換えると`mine`がムーブしました。
    +    let mut now_its_mine = mine;
    +    *now_its_mine += 2;
    +
    +    println!("{}", now_its_mine); // 7
    +    // println!("{}", mine); // これは`now_its_mine`がポインタを所有しているため、コンパイルができません。
    +
    +    // 参照は他のデータを参照する不変なポインタです。
    +    // 値を参照する場合、値を「借用」したと言います。
    +    // 値が不変に借用されている間は、値を変更したり、ムーブすることはできない。
    +    // 借用は借用されている変数が使用されている最後まで有効です。
    +    let mut var = 4;
    +    var = 3;
    +    let ref_var: &i32 = &var;
    +
    +    println!("{}", var); // `mine`と違って、`var`はまだ使用できます。
    +    println!("{}", *ref_var);
    +    // var = 5; // `var`が借用されているため、コンパイルができません。
    +    // *ref_var = 6; // `ref_var`が不変な参照であるため、コンパイルできません。
    +    ref_var; // 操作は行っていませんが、使用されているとみなされ、借用が有効になります。
    +    var = 2; // `ref_var`上記行以降使用されていないため、借用は終了しています。
    +
    +    // 可変な参照
    +    // 値が可変な借用である間は、一切アクセスできません。
    +    let mut var2 = 4;
    +    let ref_var2: &mut i32 = &mut var2;
    +    *ref_var2 += 2;         // '*'は可変な参照をされた`var2`を指すために使用されます。
    +
    +    println!("{}", *ref_var2); // 6 , // `var2`はコンパイルされません。
    +    // `ref_var2`は型が&mut i32であるため、i32への可変な参照が格納されています。値は入っていません。
    +    // var2 = 2; // `var2`が借用されているため、コンパイルできません。
    +    ref_var2; // 操作は行っていませんが、使用されているとみなされ、借用が有効になります。
    +}
    +```
    +
    +## 補足資料
    +
    +Rustにはまだまだ多くの魅力がありますが、ここではRustの基本的な知識をお伝えします。
    +Rustについてもっと知りたい場合は、[The Rust Programming
    +Language](http://doc.rust-lang.org/book/index.html)
    +を読んで、[/r/rust](http://reddit.com/r/rust)をチェックしてみてください。
    +irc.mozilla.orgの#rustチャンネルにいる人たちも、新参者にも熱心に助けてくれます。
    +
    +また、Rustの機能を公式のオンラインコンパイラで試すこともできます。
    +[Rust playpen](http://play.rust-lang.org) またはメインの
    +[Rust website](http://rust-lang.org).
    
    From 7479c4db9044c0e438fa565f9319527164280ee6 Mon Sep 17 00:00:00 2001
    From: SrMarques 
    Date: Thu, 24 Nov 2022 08:30:26 +0100
    Subject: [PATCH 011/392] Update incorrect variables
    
    ---
     es-es/python-es.html.markdown | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown
    index 7deec286..08cf9769 100644
    --- a/es-es/python-es.html.markdown
    +++ b/es-es/python-es.html.markdown
    @@ -421,7 +421,7 @@ map(sumar_10, [1,2,3]) #=> [11, 12, 13]
     filter(lambda x: x > 5, [3, 4, 5, 6, 7]) #=> [6, 7]
     
     # Podemos usar listas por comprensión para mapeos y filtros agradables
    -[add_10(i) for i in [1, 2, 3]]  #=> [11, 12, 13]
    +[sumar_10(i) for i in [1, 2, 3]]  #=> [11, 12, 13]
     [x for x in [3, 4, 5, 6, 7] if x > 5] #=> [6, 7]
     # también hay diccionarios
     {k:k**2 for k in range(3)} #=> {0: 0, 1: 1, 2: 4}
    @@ -548,7 +548,7 @@ def pedir(_decir):
     
     
     @pedir
    -def say(decir_por_favor=False):
    +def decir(decir_por_favor=False):
         mensaje = "¿Puedes comprarme una cerveza?"
         return mensaje, decir_por_favor
     
    
    From 743e59dba4bcbcdd08d63a3f164c0b656595d73d Mon Sep 17 00:00:00 2001
    From: Graham Christensen 
    Date: Tue, 14 Feb 2023 15:06:48 -0500
    Subject: [PATCH 012/392] nix: add additional further reading
    
    ---
     de-de/nix-de.html.markdown | 5 ++++-
     nix.html.markdown          | 5 ++++-
     sv-se/nix-sv.html.markdown | 5 ++++-
     3 files changed, 12 insertions(+), 3 deletions(-)
    
    diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown
    index ffe8dffc..a55a91c7 100644
    --- a/de-de/nix-de.html.markdown
    +++ b/de-de/nix-de.html.markdown
    @@ -356,6 +356,9 @@ with builtins; [
     
     * [Susan Potter - Nix Cookbook - Nix By Example]
       (https://ops.functionalalgebra.com/nix-by-example/)
    -  
    +
    +* [Zero to Nix - Nix Tutorial]
    +  (https://zero-to-nix.com/)
    +
     * [Rommel Martinez - A Gentle Introduction to the Nix Family]
       (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
    diff --git a/nix.html.markdown b/nix.html.markdown
    index 1d5a7778..cc31cbe4 100644
    --- a/nix.html.markdown
    +++ b/nix.html.markdown
    @@ -375,6 +375,9 @@ with builtins; [
     
     * [Susan Potter - Nix Cookbook - Nix By Example]
       (https://ops.functionalalgebra.com/nix-by-example/)
    -  
    +
    +* [Zero to Nix - Nix Tutorial]
    +  (https://zero-to-nix.com/)
    +
     * [Rommel Martinez - A Gentle Introduction to the Nix Family]
       (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
    diff --git a/sv-se/nix-sv.html.markdown b/sv-se/nix-sv.html.markdown
    index 647575fe..9069c286 100644
    --- a/sv-se/nix-sv.html.markdown
    +++ b/sv-se/nix-sv.html.markdown
    @@ -366,6 +366,9 @@ with builtins; [
     
     * [Susan Potter - Nix Cookbook - Nix By Example]
       (https://ops.functionalalgebra.com/nix-by-example/)
    -  
    +
    +* [Zero to Nix - Nix Tutorial]
    +  (https://zero-to-nix.com/)
    +
     * [Rommel Martinez - A Gentle Introduction to the Nix Family]
       (https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix)
    
    From e5dd7ddcf62738af93333bb675a03a414b4a021a Mon Sep 17 00:00:00 2001
    From: homedirectory <47361170+homedirectory@users.noreply.github.com>
    Date: Fri, 17 Mar 2023 19:21:54 +0200
    Subject: [PATCH 013/392] Update bash-ua.html.markdown
    
    Fix some typos, improve grammar and enrich examples
    ---
     uk-ua/bash-ua.html.markdown | 20 ++++++++++----------
     1 file changed, 10 insertions(+), 10 deletions(-)
    
    diff --git a/uk-ua/bash-ua.html.markdown b/uk-ua/bash-ua.html.markdown
    index c6e9ebb1..9375d5f3 100644
    --- a/uk-ua/bash-ua.html.markdown
    +++ b/uk-ua/bash-ua.html.markdown
    @@ -19,7 +19,7 @@ lang: uk-ua
     
     Bash - командна оболонка unix (unix shell), що також розповсюджувалась як оболонка для
     операційної системи GNU і зараз використовується як командна оболонка за замовчуванням
    -для Linux i Max OS X.
    +для Linux i Mac OS X.
     Майже всі приклади, що наведені нижче можуть бути частиною shell-скриптів або
     виконані в оболонці
     
    @@ -52,9 +52,9 @@ VARIABLE= 'Просто рядок'
     # виконання команди 'Просто рядок')
     
     # Використання змінних:
    -echo $VARIABLE
    -echo "$VARIABLE"
    -echo '$VARIABLE'
    +echo $VARIABLE     # Просто рядок
    +echo "$VARIABLE"   # Просто рядок
    +echo '$VARIABLE'   # $VARIABLE
     # Коли ви використовуєте змінну - присвоюєте значення, експортуєте і т.д. -
     # пишіть її імя без $. А для отримання значення змінної використовуйте $.
     # Одинарні лапки ' не розкривають значення змінних
    @@ -96,12 +96,12 @@ else
         echo "Ім’я збігаєтьяс з іменем користувача"
     fi
     
    -# Зауважте! якщо $Name пуста, bash інтерпретує код вище як:
    +# Зауважте! якщо $NAME пуста, bash інтерпретує код вище як:
     if [ -ne $USER ]
     # що є неправильним синтаксисом
     # тому безпечний спосіб використання потенційно пустих змінних має вигляд:
    -if [ "$Name" -ne $USER ] ...
    -# коли $Name пуста, інтерпретується наступним чином:
    +if [ "$NAME" -ne $USER ] ...
    +# коли $NAME пуста, інтерпретується наступним чином:
     if [ "" -ne $USER ] ...
     # що працює як і очікувалося
     
    @@ -205,7 +205,7 @@ do
         echo $a
     done
     
    -# Цикл for можно використати, щоб виконувати дії над файлами.
    +# Цикл for можна використати, щоб виконувати дії над файлами.
     # Цей код запустить команду 'cat' для файлів file1 и file2
     for VARIABLE in file1 file2
     do
    @@ -259,12 +259,12 @@ uniq -d file.txt
     cut -d ',' -f 1 file.txt
     # замінити кожне 'okay' на 'great' у файлі file.txt (підтримується regex)
     sed -i 's/okay/great/g' file.txt
    -# вивести в stdout всі рядки з file.txt, що задовольняють шаблону regex;
    +# вивести в stdout всі рядки з file.txt, що відповідають шаблону regex;
     # цей приклад виводить рядки, що починаються на foo і закінчуються на bar:
     grep "^foo.*bar$" file.txt
     # використайте опцію -c, щоб вивести кількість входжень
     grep -c "^foo.*bar$" file.txt
    -# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrea (або grep -F)
    +# щоб здійснити пошук по рядку, а не по шаблону regex, використовуйте fgrep (або grep -F)
     fgrep "^foo.*bar$" file.txt 
     
     # Читайте вбудовану документацію Bash командою 'help':
    
    From 971b483fe40e4b57d09d0a56a76e447f60d11ca0 Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Matt=20S=C3=A1rdi?= 
    Date: Fri, 31 Mar 2023 22:47:46 +0200
    Subject: [PATCH 014/392] Update pythonlegacy-hu.html.markdown
    
    ---
     hu-hu/pythonlegacy-hu.html.markdown | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/hu-hu/pythonlegacy-hu.html.markdown b/hu-hu/pythonlegacy-hu.html.markdown
    index b5922766..483784ba 100644
    --- a/hu-hu/pythonlegacy-hu.html.markdown
    +++ b/hu-hu/pythonlegacy-hu.html.markdown
    @@ -20,7 +20,7 @@ bele. Tulajdonképpen futtatható pszeudokód.
     Szívesen fogadok visszajelzéseket! Elérsz itt: [@louiedinh](http://twitter.com/louiedinh)
     vagy pedig a louiedinh [kukac] [google email szolgáltatása] címen.
     
    -Figyelem: ez a leírás a Python 2.7 verziójára vonatkozok, illetve
    +Figyelem: ez a leírás a Python 2.7 verziójára vonatkozik, illetve
     általánosságban a 2.x verziókra. A Python 2.7 azonban már csak 2020-ig lesz
     támogatva, ezért kezdőknek ajánlott, hogy a Python 3-mal kezdjék az
     ismerkedést. A Python 3.x verzióihoz a [Python 3 bemutató](http://learnxinyminutes.com/docs/python/)
    
    From 4e88b2cdba021d9be72d8e64793d6cd086e8710b Mon Sep 17 00:00:00 2001
    From: weirdvic <56339132+weirdvic@users.noreply.github.com>
    Date: Wed, 12 Apr 2023 19:51:05 +0300
    Subject: [PATCH 015/392] Added russian translation for Tcl page
    
    ---
     ru-ru/tcl-ru.html.markdown | 589 +++++++++++++++++++++++++++++++++++++
     1 file changed, 589 insertions(+)
     create mode 100644 ru-ru/tcl-ru.html.markdown
    
    diff --git a/ru-ru/tcl-ru.html.markdown b/ru-ru/tcl-ru.html.markdown
    new file mode 100644
    index 00000000..723efe30
    --- /dev/null
    +++ b/ru-ru/tcl-ru.html.markdown
    @@ -0,0 +1,589 @@
    +---
    +language: Tcl
    +contributors:
    +    - ["Poor Yorick", "https://pooryorick.com/"]
    +translators:
    +    - ["Viktor Sokhranov", "https://github.com/weirdvic"]
    +filename: learntcl.tcl
    +---
    +
    +Tcl был создан [Джоном Оустерхаутом](https://ru.wikipedia.org/wiki/Оустерхаут,_Джон)
    +в качестве скриптового языка в своих инструментах проектирования электрических цепей.
    +В 1997 году за разработку языка Tcl автор получил [ACM](https://ru.wikipedia.org/wiki/ACM)
    + Software System Award. Tcl может использоваться и как встраиваемый скриптовый язык,
    +и как язык программирования общего назначения. Кроме того, он может быть использован как
    +библиотека в программах на C, даже в случаях когда не требуется написание скриптов,
    +поскольку Tcl может предоставить программе на C различные типы данных, такие как
    +динамические строки, списки и хэш-таблицы. Также с помощью этой библиотеки возможно
    +использовать форматирование строк, операции с файловой системой, работу с кодировками и
    +динамически загружаемые библиотеки. К другим особенностям Tcl относятся:
    +
    +* Удобный кроссплатформенный API для работы с сетью
    +
    +* Поддержка виртуальной файловой системы(VFS)
    +
    +* Стекируемые каналы ввода-вывода
    +
    +* Асинхронность в ядре языка
    +
    +* Поддержка корутин
    +
    +* Простая и надёжная модель потоков выполнения
    +
    +Tcl имеет много общего с Lisp, но в отличие от списков, в Tcl "валютой" языка
    +являются строки. Все значения являются строками. Список в Tcl это просто строка в
    +определённом формате, а тело процедуры(скрипт) это ещё одна строка, а не блок.
    +С целью увеличения производительности, интерпретатор Tcl использует кэшированные
    +внутренние представления различных типов данных. Например, рутины(routines), работающие
    +со списками, фактически используют внутреннее представление списков, а интерпретатор
    +Tcl обновляет строковое представление в том случае если оно используется в скрипте.
    +В Tcl используется подход copy-on-write, позволяющий оперировать большими объёмами
    +данных без дополнительного оверхеда. Процедуры в Tcl автоматически компилируются
    +в байткод, кроме случаев когда в процедуре используются динамические рутины, такие
    +как "uplevel", "upvar" и "trace"
    +
    +Программировать на Tcl приятно. Его находят привлекательным хакеры, которым интересны
    +Lisp, Forth или Smalltalk, а также инженеры и учёные, которым просто необходим
    +гибкий инструмент для выполнения их задач. В Tcl языковые конструкции, включая
    +циклы и математические операторы, представлены в виде изменяемых рутин, в отличие
    +от других языков программирования, где они закреплены в синтаксисе, что позволяет
    +синтаксису Tcl не мешать работать с предметной областью проекта. Синтаксис Tcl в этом
    +смысле даже более минималистичен чем у Lisp.
    +
    +
    +
    +```tcl
    +#! /bin/env tclsh
    +
    +###############################################################################
    +## 1. Рекомендации
    +###############################################################################
    +
    +# Tcl это не shell или C! Этот момент требует уточнения, поскольку привычки
    +# написания shell-скриптов почти работают в Tcl и часто люди начинают
    +# изучать Tcl со знанием синтаксиса других языков. Поначалу это работает, но
    +# когда скрипты становятся сложнее, наступает фрустрация.
    +
    +# Фигурные скобки {} в Tcl используются не для построения блоков кода или
    +# списков, а как механизм экранирования(quoting) для кода. Фактически в Tcl
    +# нет ни списков, ни блоков кода. Фигурные скобки использутся для
    +# экранирования специальных символов и потому подходят для представления
    +# тела процедур и строк, которые должны интерпретироваться как списки.
    +
    +
    +###############################################################################
    +## 2. Синтаксис
    +###############################################################################
    +
    +# Скрипт состоит из команд, разделённых символами перевода строки или символами
    +# точки с запятой. Каждая команда представляет собой вызов рутины. Первое слово
    +# это имя вызываемой рутины, а последующие слова это аргументы. Слова разделены
    +# пробелами. Так как каждый аргумент это слово в команде, он является строкой и
    +# может быть неэкранирован:
    +set part1 Sal
    +set part2 ut; set part3 ations
    +
    +
    +# символ доллара используется для подставления значения переменных:
    +set greeting $part1$part2$part3
    +
    +
    +# Когда "set" получает только имя переменной, возвращается значение переменной:
    +set part3 ;# Возвращает значение переменной
    +
    +
    +# Содержимое квадратных скобок заменяется на результат выполнения:
    +set greeting $part1$part2[set part3]
    +
    +
    +# Встроенный таким образов скрипт может состоять из нескольких команд, но
    +# результат подстановки определяется последней командой:
    +set greeting $greeting[
    +    incr i
    +    incr i
    +    incr i
    +]
    +puts $greeting ;# Выведет "Salutations3"
    +
    +# Каждое слово в команде является строкой, включая имя рутины, поэтому
    +# подстановки могут быть использованы и таким образом:
    +set action pu
    +
    +# следующие команды эквивалентны:
    +puts $greeting
    +${action}ts $greeting
    +[set action]ts $greeting
    +
    +
    +# Обратный слэш экранирует специальные символы:
    +set amount \$16.42
    +
    +
    +# и он же используется для ввода специальных символов:
    +puts lots\nof\n\n\n\n\n\nnewlines
    +
    +
    +# Слово в фигурных скобках никак не интерпретируется и в нём не работают
    +# никакие подстановки, за исключением экранирования закрывающей скобки:
    +set somevar {
    +    Это литерал знака $, а это \} экранированная закрывающая скобка
    +}
    +
    +
    +# В слове внутри двойных кавычек, пробельные символы теряют своё
    +# специальное значение:
    +set name Neo
    +set greeting "Hello, $name"
    +
    +
    +# Имя переменной может быть любой строкой:
    +set {first name} New
    +
    +
    +# Фигурные скобки используются для доступа к переменным с составными именами:
    +set greeting "Hello, ${first name}"
    +
    +
    +# "set" всегда можно использовать вместо подстановки переменной:
    +set greeting "Hello, [set {first name}]"
    +
    +
    +# Чтобы "распаковать" список в команду используется оператор расширения "{*}"
    +# Эти две команды эквивалентны:
    +set name Neo
    +set {*}{name Neo}
    +
    +
    +# Массив это особая переменная, являющаяся контейнером для других переменных.
    +set person(name) Neo
    +set person(destiny) {The One}
    +set greeting "Hello, $person(name)"
    +
    +
    +# "variable" может быть использована для объявления или установки переменных.
    +# В отличие от "set", которая использует глобальное и локальное пространство
    +# имён, "variable" работает только с локальным пространством:
    +variable name New
    +
    +
    +# "namespace eval" создаёт новое пространство имён, если его не существует.
    +# Пространство имён может содержать рутины и переменные:
    +namespace eval people {
    +    namespace eval person1 {
    +        variable name Neo
    +    }
    +}
    +
    +
    +# Двумя или более двоеточиями в именах переменных отделяется название
    +# пространства имён:
    +namespace eval people {
    +    set greeting "Hello $person1::name"
    +}
    +
    +# Два или более двоеточия также отделяют название пространства имён
    +# в имени рутины:
    +proc people::person1::speak {} {
    +    puts {I am The One.}
    +}
    +
    +# Полные(fully-qualified) имена начинаются с двух двоеточий:
    +set greeting "Hello $::people::person1::name"
    +
    +
    +
    +###############################################################################
    +## 3. Больше никакого синтаксиса
    +###############################################################################
    +
    +# Все остальные функции реализованы посредством рутин. С этого момента и далее
    +# больше нет нового синтаксиса. Всё остальное что можно изучить о Tcl это
    +# поведение отдельных рутин и какие значения они присваивают своим аргументам.
    +
    +
    +
    +###############################################################################
    +## 4. Переменные и пространства имён
    +###############################################################################
    +
    +# Каждая переменная и рутина связанс с пространством имён.
    +
    +# Чтобы получить интерпретатор, которые не может сделать ничего, достаточно
    +# удалить глобальное пространство имён. Особой пользы в этом нет, но это хорошо
    +# иллюстрирует природу Tcl. Фактически имя глобального пространства имён это
    +# пустая строка, но единственный способ представить её -- в виде полного имени:
    +proc delete_global_namespace {} {
    +    namespace delete ::
    +}
    +
    +# Поскольку "set" всегда учитывает и глобальное, и текущее пространства имён,
    +# более безопасно использовать "variable" чтобы объявить новую переменную или
    +# задать значение переменной. Если переменная с именем "name" уже существует
    +# в глобальном пространстве имён, использование "set" задаст значение
    +# глобальной переменной, тогда как "variable" работает только с текущим
    +# пространством имён.
    +
    +namespace eval people {
    +    namespace eval person1 {
    +        variable name Neo
    +    }
    +}
    +
    +# После объявления переменной в пространстве имён, [set] видит её, а не
    +# одноимённую переменную в глобальном пространстве имён:
    +
    +namespace eval people {
    +    namespace eval person1 {
    +        variable name
    +        set name Neo
    +    }
    +}
    +
    +# Но если "set" приходится создать новую переменную, он всегда делает это
    +# с учётом текущего пространства имён:
    +unset name
    +namespace eval people {
    +    namespace eval person1 {
    +        set name neo
    +    }
    +
    +}
    +set people::person1::name
    +
    +
    +# Абсолютное имя всегда начинается с имени глобального пространства имён, то
    +# есть с пустой строки, за которой следует два двоеточия:
    +set ::people::person1::name Neo
    +
    +
    +# В пределах процедуры "variable" связывает перменную в текущем пространстве
    +# имён с локальной областью видимости:
    +namespace eval people::person1 {
    +    proc fly {} {
    +        variable name
    +        puts "$name is flying!"
    +    }
    +}
    +
    +
    +
    +
    +###############################################################################
    +## 5. Встроенные рутины
    +###############################################################################
    +
    +# Математические операции можно выполнять при помощи "expr":
    +set a 3
    +set b 4
    +set c [expr {$a + $b}]
    +
    +# Поскольку "expr" самостоятельно занимается подстановкой значений переменных,
    +# математическое выражение нужно оборачивать в фигурные скобки чтобы отключить
    +# подстановку значений переменных интерпретатором Tcl.
    +# Подробнее об этом можно прочесть здесь:
    +# "https://wiki.tcl-lang.org/page/Brace+your+expr-essions"
    +
    +
    +# "expr" выполняет подстановку переменных и результатов команд:
    +set c [expr {$a + [set b]}]
    +
    +
    +# "expr" предоставляет разные математические функции:
    +set c [expr {pow($a,$b)}]
    +
    +
    +# Математические операторы сами по себе доступны в виде рутин в
    +# пространстве имён ::tcl::mathop
    +::tcl::mathop::+ 5 3
    +
    +# Рутины могут быть импортированы из других пространств имён:
    +namespace import ::tcl::mathop::+
    +set result [+ 5 3]
    +
    +
    +# Не числовые значения должны быть квотированы. Такие операторы как "eq"
    +# Могут быть использованы чтобы провести строковое сравнение:
    +set name Neo
    +expr {{Bob} eq $name}
    +
    +# Общие операторы сравнения тоже работают со строками если числовое значение
    +# операнда недоступно:
    +expr {{Bob} == $name}
    +
    +
    +# "proc" создаёт новые рутины:
    +proc greet name {
    +    return "Hello, $name!"
    +}
    +
    +# можно указать несколько параметров:
    +proc greet {greeting name} {
    +    return "$greeting, $name!"
    +}
    +
    +
    +# Как было отмечено ранее, фигурные скобки не обозначают блок кода.
    +# Любое значение, даже третий аргумент "proc" является строкой.
    +# Предыдущая команда может быть переписана без использования фигурных скобок:
    +
    +# As noted earlier, braces do not construct a code block.  Every value, even
    +# the third argument to "proc", is a string.  The previous command
    +# can be rewritten using no braces:
    +proc greet greeting\ name return\ \"\$greeting,\ \$name!\"
    +
    +
    +
    +# Если последний параметр называется "args", все дополнительные аргументы,
    +# переданные рутине, собираются в список и передаются как "args":
    +proc fold {cmd first args} {
    +    foreach arg $args {
    +        set first [$cmd $first $arg]
    +    }
    +    return $first
    +}
    +fold ::tcl::mathop::* 5 3 3 ;# ->  45
    +
    +
    +# Условное выполнение тоже реализовано как рутина:
    +if {3 > 4} {
    +    puts {This will never happen}
    +} elseif {4 > 4} {
    +    puts {This will also never happen}
    +} else {
    +    puts {This will always happen}
    +}
    +
    +
    +# Циклы реализованы как рутины. Первый и третий аргументы для "for"
    +# обрабатываются как скрипты, а второй аргумент как выражение:
    +set res 0
    +for {set i 0} {$i < 10} {incr i} {
    +    set res [expr {$res + $i}]
    +}
    +unset res
    +
    +
    +# Первый аргумент для "while" тоже обрабатывается как выражение:
    +set i 0
    +while {$i < 10} {
    +    incr i 2
    +}
    +
    +
    +# Список это строка, а элементы списка разделены пробелами:
    +set amounts 10\ 33\ 18
    +set amount [lindex $amounts 1]
    +
    +# Если элемент списка содержит пробел, его надо экранировать:
    +set inventory {"item 1" item\ 2 {item 3}}
    +
    +
    +# Хорошая практика использовать списковые рутины для обработки списков:
    +lappend inventory {item 1} {item 2} {item 3}
    +
    +
    +# Фигурные скобки и бэкслеш могут быть использованы чтобы хранить более
    +# комплексные структуры внутри списков. Список выглядит как скрипт, за
    +# исключением того, что перевод строки и точка с запятой теряют своё
    +# специальное значение, а также не производится подстановка значений.
    +# Эта особенность Tcl называется гомоиконичность
    +# https://ru.wikipedia.org/wiki/Гомоиконичность
    +# В приведённом списке есть три элемента:
    +set values {
    +
    +    one\ two
    +
    +    {three four}
    +
    +    five\{six
    +
    +}
    +
    +
    +# Поскольку как и все значения, список является строкой, строковые
    +# операции могут выполняться и над списком, с риском повреждения:
    +set values {one two three four}
    +set values [string map {two \{} $values] ;# $values больше не \
    +    правильно отформатированный список
    +
    +
    +# Безопасный способ работать со списками — использовать "list" рутины:
    +set values [list one \{ three four]
    +lappend values { } ;# добавить символ пробела как элемент в список
    +
    +
    +# Использование "eval" для вычисления значения скрипта:
    +eval {
    +    set name Neo
    +    set greeting "Hello, $name"
    +}
    +
    +
    +# Список всегда можно передать в "eval" как скрипт, содержащий одну команду:
    +eval {set name Neo}
    +eval [list set greeting "Hello, $name"]
    +
    +
    +# Следовательно, когда используется "eval", используйте "list" чтобы собрать
    +# необходимую команду:
    +set command {set name}
    +lappend command {Archibald Sorbisol}
    +eval $command
    +
    +
    +# Частая ошибка: не использовать списковые функции для построения команды:
    +set command {set name}
    +append command { Archibald Sorbisol}
    +try {
    +    eval $command ;# Здесь будет ошибка, превышено количество аргументов \
    +        к "set" в {set name Archibald Sorbisol}
    +} on error {result eoptions} {
    +    puts [list {received an error} $result]
    +}
    +
    +# Эта ошибка запросто может произойти с "subst":
    +
    +set replacement {Archibald Sorbisol}
    +set command {set name $replacement}
    +set command [subst $command]
    +try {
    +    eval $command ;# Та же ошибка, лишние аргументы к \
    +        {set name Archibald Sorbisol}
    +} trap {TCL WRONGARGS} {result options} {
    +    puts [list {received another error} $result]
    +}
    +
    +
    +# "list" корректно форматирует значение для подстановки:
    +set replacement [list {Archibald Sorbisol}]
    +set command {set name $replacement}
    +set command [subst $command]
    +eval $command
    +
    +
    +# "list" обычно используется для форматирования значений для подстановки в
    +# скрипты, вот несколько примеров:
    +
    +
    +# "apply" вычисляет список из двух элементов как рутину:
    +set cmd {{greeting name} {
    +    return "$greeting, $name!"
    +}}
    +apply $cmd Whaddup Neo
    +
    +# Третий элемент может быть использован для указания пространства имён рутины:
    +set cmd [list {greeting name} {
    +    return "$greeting, $name!"
    +} [namespace current]]
    +apply $cmd Whaddup Neo
    +
    +
    +# "uplevel" вычисляет скрипт на уровень выше в списке вызовов:
    +proc greet {} {
    +    uplevel {puts "$greeting, $name"}
    +}
    +
    +proc set_double {varname value} {
    +    if {[string is double $value]} {
    +        uplevel [list variable $varname $value]
    +    } else {
    +        error [list {not a double} $value]
    +    }
    +}
    +
    +
    +# "upvar" связывает переменную на текущем уровне вызовов с переменной на
    +# более высоком уровне:
    +proc set_double {varname value} {
    +    if {[string is double $value]} {
    +        upvar 1 $varname var
    +        set var $value
    +    } else {
    +        error [list {not a double} $value]
    +    }
    +}
    +
    +
    +# Избавляемся от встроенной рутины "while" и используем "proc" чтобы написать
    +# свою версию:
    +rename ::while {}
    +# обработка оставлена как упражнение:
    +proc while {condition script} {
    +    if {[uplevel 1 [list expr $condition]]} {
    +        uplevel 1 $script
    +        tailcall [namespace which while] $condition $script
    +    }
    +}
    +
    +
    +# "coroutine" создаёт новый стек вызовов, новую рутину для входа в этот стек
    +# и вызывает эту рутину. "yield" приостанавливает вычисления в этом стеке и
    +# возвращает управление вызывавшему стеку:
    +proc countdown count {
    +    # отправить что-нибудь обратно создателю корутины, фактически
    +    # останавливая стек вызовов на время.
    +    yield [info coroutine]
    +
    +    while {$count > 1} {
    +        yield [incr count -1]
    +    }
    +    return 0
    +}
    +coroutine countdown1 countdown 3
    +coroutine countdown2 countdown 5
    +puts [countdown1] ;# -> 2
    +puts [countdown2] ;# -> 4
    +puts [countdown1] ;# -> 1
    +puts [countdown1] ;# -> 0
    +catch {
    +    puts [coundown1] ;# -> invalid command name "countdown1"
    +} cres copts
    +puts $cres
    +puts [countdown2] ;# -> 3
    +
    +
    +# Стеки корутин могут передавать контроль друг другу:
    +
    +proc pass {whom args} {
    +    return [yieldto $whom {*}$args]
    +}
    +
    +coroutine a apply {{} {
    +        yield
    +        set result [pass b {please pass the salt}]
    +        puts [list got the $result]
    +        set result [pass b {please pass the pepper}]
    +        puts [list got the $result]
    +}}
    +
    +coroutine b apply {{} {
    +    set request [yield]
    +    while 1 {
    +        set response [pass c $request]
    +        puts [list [info coroutine] is now yielding]
    +        set request [pass a $response]
    +    }
    +}}
    +
    +coroutine c apply {{} {
    +    set request [yield]
    +    while 1 {
    +        if {[string match *salt* $request]} {
    +            set request [pass b salt]
    +        } else {
    +            set request [pass b huh?]
    +        }
    +    }
    +}}
    +
    +
    +
    +```
    +
    +## Ссылки
    +
    +[Официальная документация Tcl](https://www.tcl-lang.org)
    +
    +[Tcl Wiki](https://wiki.tcl-lang.org)
    +
    +[Tcl на Reddit](http://www.reddit.com/r/Tcl)
    
    From 3e22775a641831a82c59a3b6197240b2fcd9a76b Mon Sep 17 00:00:00 2001
    From: =?UTF-8?q?Joel=20Juc=C3=A1?= 
    Date: Thu, 27 Apr 2023 17:09:38 -0300
    Subject: [PATCH 016/392] Fix bad case in the Elixir language
    
    ---
     de-de/elixir-de.html.markdown |  2 +-
     elixir.html.markdown          | 19 +++++++++----------
     es-es/elixir-es.html.markdown | 18 +++++++++---------
     fr-fr/elixir-fr.html.markdown |  2 +-
     it-it/elixir-it.html.markdown | 18 +++++++++---------
     pt-br/elixir-pt.html.markdown | 18 +++++++++---------
     ro-ro/elixir-ro.html.markdown |  4 ++--
     ru-ru/elixir-ru.html.markdown |  2 +-
     sk-sk/elixir-sk.html.markdown | 14 +++++++-------
     zh-cn/elixir-cn.html.markdown |  2 +-
     zh-tw/elixir-tw.html.markdown | 16 ++++++++--------
     11 files changed, 57 insertions(+), 58 deletions(-)
    
    diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown
    index 254cca51..ec933696 100644
    --- a/de-de/elixir-de.html.markdown
    +++ b/de-de/elixir-de.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
     translators:
    diff --git a/elixir.html.markdown b/elixir.html.markdown
    index 9f96be49..2748a983 100644
    --- a/elixir.html.markdown
    +++ b/elixir.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "https://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    @@ -13,16 +13,15 @@ It's fully compatible with Erlang, but features a more standard syntax
     and many more features.
     
     ```elixir
    -
     # Single line comments start with a number symbol.
     
     # There's no multi-line comment,
     # but you can stack multiple comments.
     
    -# To use the elixir shell use the `iex` command.
    +# To use the Elixir shell use the `iex` command.
     # Compile your modules with the `elixirc` command.
     
    -# Both should be in your path if you installed elixir correctly.
    +# Both should be in your path if you installed Elixir correctly.
     
     ## ---------------------------
     ## -- Basic types
    @@ -50,7 +49,7 @@ elem({1, 2, 3}, 0) #=> 1
     head #=> 1
     tail #=> [2,3]
     
    -# In elixir, just like in Erlang, the `=` denotes pattern matching and
    +# In Elixir, just like in Erlang, the `=` denotes pattern matching and
     # not an assignment.
     #
     # This means that the left-hand side (pattern) is matched against a
    @@ -83,7 +82,7 @@ string.
     <> #=> "abc"
     [?a, ?b, ?c]   #=> 'abc'
     
    -# `?a` in elixir returns the ASCII integer for the letter `a`
    +# `?a` in Elixir returns the ASCII integer for the letter `a`
     ?a #=> 97
     
     # To concatenate lists use `++`, for binaries use `<>`
    @@ -116,7 +115,7 @@ genders.gillian #=> "female"
     5 * 2  #=> 10
     10 / 2 #=> 5.0
     
    -# In elixir the operator `/` always returns a float.
    +# In Elixir the operator `/` always returns a float.
     
     # To do integer division use `div`
     div(10, 2) #=> 5
    @@ -174,7 +173,7 @@ else
       "This will"
     end
     
    -# Remember pattern matching? Many control-flow structures in elixir rely on it.
    +# Remember pattern matching? Many control-flow structures in Elixir rely on it.
     
     # `case` allows us to compare a value against many patterns:
     case {:one, :two} do
    @@ -307,7 +306,7 @@ Geometry.area({:circle, 3})       #=> 28.25999999999999801048
     # Geometry.area({:circle, "not_a_number"})
     #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
     
    -# Due to immutability, recursion is a big part of elixir
    +# Due to immutability, recursion is a big part of Elixir
     defmodule Recursion do
       def sum_list([head | tail], acc) do
         sum_list(tail, acc + head)
    @@ -382,7 +381,7 @@ end
     ## ---------------------------
     
     # Elixir relies on the actor model for concurrency. All we need to write
    -# concurrent programs in elixir are three primitives: spawning processes,
    +# concurrent programs in Elixir are three primitives: spawning processes,
     # sending messages and receiving messages.
     
     # To start a new process we use the `spawn` function, which takes a function
    diff --git a/es-es/elixir-es.html.markdown b/es-es/elixir-es.html.markdown
    index 885165a6..37acf6ad 100644
    --- a/es-es/elixir-es.html.markdown
    +++ b/es-es/elixir-es.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    @@ -23,10 +23,10 @@ y otras características más.
     # No hay comentarios multilinea,
     # pero se pueden apilar varios comentarios.
     
    -# Para usar el shell de elixir se usa el comando `iex`.
    +# Para usar el shell de Elixir se usa el comando `iex`.
     # Los módulos se compilan con el comando `elixirc`.
     
    -# Ambos deberían estar en la ruta si elixir se instaló correctamente.
    +# Ambos deberían estar en la ruta si Elixir se instaló correctamente.
     
     ## ---------------------------
     ## -- Tipos básicos
    @@ -55,7 +55,7 @@ elem({1, 2, 3}, 0) #=> 1
     head #=> 1
     tail #=> [2,3]
     
    -# En elixir, solo como Erlang, el `=` denota la coincidencia de patrones y
    +# En Elixir, solo como Erlang, el `=` denota la coincidencia de patrones y
     # no una asignación.
     #
     # This is how the above example of accessing the head and tail of a list works.
    @@ -87,7 +87,7 @@ string.
     <> #=> "abc"
     [?a, ?b, ?c]   #=> 'abc'
     
    -# `?a` en elixir devuelve el valor ASCII para el caracter `a`
    +# `?a` en Elixir devuelve el valor ASCII para el caracter `a`
     ?a #=> 97
     
     # Para concatenar listas se usa `++`, para binarios `<>`
    @@ -120,7 +120,7 @@ genders.gillian #=> "female"
     5 * 2  #=> 10
     10 / 2 #=> 5.0
     
    -# En elixir el operador `/` siempre devuelve un número flotante
    +# En Elixir el operador `/` siempre devuelve un número flotante
     
     # Para hacer la división de número entero se debe usar `div`
     div(10, 2) #=> 5
    @@ -175,7 +175,7 @@ else
     end
     
     # Se acuerda de la coincidencia de patrones?
    -# Muchas estructuras de control de flujo en elixir confían en ella.
    +# Muchas estructuras de control de flujo en Elixir confían en ella.
     
     # `case` permite comparar un valor con muchos patrones:
     case {:one, :two} do
    @@ -305,7 +305,7 @@ Geometry.area({:circle, 3})       #=> 28.25999999999999801048
     # Geometry.area({:circle, "not_a_number"})
     #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
     
    -# Debido a la inmutabilidad, la recursión es una gran parte de elixir
    +# Debido a la inmutabilidad, la recursión es una gran parte de Elixir
     defmodule Recursion do
       def sum_list([head | tail], acc) do
         sum_list(tail, acc + head)
    @@ -380,7 +380,7 @@ end
     ## ---------------------------
     
     # Elixir confía en el modelo actor para la concurrencia. Todo lo que se necesita para escribir
    -# programas concurrentes en elixir son tres primitivas: procesos de desove,
    +# programas concurrentes en Elixir son tres primitivas: procesos de desove,
     # envío de mensajes y recepción de mensajes.
     
     # Para empezar un nuevo proceso se usa la función `spawn`,
    diff --git a/fr-fr/elixir-fr.html.markdown b/fr-fr/elixir-fr.html.markdown
    index 90cdad7c..f8250e16 100644
    --- a/fr-fr/elixir-fr.html.markdown
    +++ b/fr-fr/elixir-fr.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    diff --git a/it-it/elixir-it.html.markdown b/it-it/elixir-it.html.markdown
    index 48afe0c8..ce3e4535 100644
    --- a/it-it/elixir-it.html.markdown
    +++ b/it-it/elixir-it.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Luca 'Kino' Maroni", "https://github.com/kino90"]
         - ["Joao Marques", "http://github.com/mrshankly"]
    @@ -21,11 +21,11 @@ e molte altre funzionalità.
     # Non esistono commenti multilinea,
     # ma puoi concatenare più commenti.
     
    -# Per usare la shell di elixir usa il comando `iex`.
    +# Per usare la shell di Elixir usa il comando `iex`.
     # Compila i tuoi moduli con il comando `elixirc`.
     
     # Entrambi i comandi dovrebbero già essere nel tuo PATH se hai installato
    -# elixir correttamente.
    +# Elixir correttamente.
     
     ## ---------------------------
     ## -- Tipi di base
    @@ -87,7 +87,7 @@ multi-linea.
     <> #=> "abc"
     [?a, ?b, ?c]   #=> 'abc'
     
    -# `?a` in elixir restituisce il valore ASCII della lettera `a`
    +# `?a` in Elixir restituisce il valore ASCII della lettera `a`
     ?a #=> 97
     
     # Per concatenare liste si usa `++`, per binari si usa `<>`
    @@ -112,7 +112,7 @@ minore..maggiore = 1..10 # Puoi fare pattern matching anche sugli intervalli
     5 * 2  #=> 10
     10 / 2 #=> 5.0
     
    -# In elixir l'operatore `/` restituisce sempre un decimale.
    +# In Elixir l'operatore `/` restituisce sempre un decimale.
     
     # Per fare una divisione intera si usa `div`
     div(10, 2) #=> 5
    @@ -173,7 +173,7 @@ else
     end
     
     # Ti ricordi il pattern matching?
    -# Moltre strutture di controllo di flusso in elixir si basano su di esso.
    +# Moltre strutture di controllo di flusso in Elixir si basano su di esso.
     
     # `case` ci permette di confrontare un valore a diversi pattern:
     case {:uno, :due} do
    @@ -307,7 +307,7 @@ Geometria.area({:cerchio, 3})       #=> 28.25999999999999801048
     # Geometria.area({:cerchio, "non_un_numero"})
     #=> ** (FunctionClauseError) no function clause matching in Geometria.area/1
     
    -# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in elixir
    +# A causa dell'immutabilità dei dati, la ricorsione è molto frequente in Elixir
     defmodule Ricorsione do
       def somma_lista([testa | coda], accumulatore) do
         somma_lista(coda, accumulatore + testa)
    @@ -382,7 +382,7 @@ end
     ## ---------------------------
     
     # Elixir si basa sul modello degli attori per la concorrenza.
    -# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in elixir
    +# Tutto ciò di cui abbiamo bisogno per scrivere programmi concorrenti in Elixir
     # sono tre primitive: creare processi, inviare messaggi e ricevere messaggi.
     
     # Per creare un nuovo processo si usa la funzione `spawn`, che riceve una
    @@ -434,7 +434,7 @@ self() #=> #PID<0.27.0>
     
     ## Referenze
     
    -* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di elixir](http://elixir-lang.org)
    +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) dalla [pagina web ufficiale di Elixir](http://elixir-lang.org)
     * [Documentazione Elixir](https://elixir-lang.org/docs.html)
     * ["Programming Elixir"](https://pragprog.com/book/elixir/programming-elixir) di Dave Thomas
     * [Elixir Cheat Sheet](http://media.pragprog.com/titles/elixir/ElixirCheat.pdf)
    diff --git a/pt-br/elixir-pt.html.markdown b/pt-br/elixir-pt.html.markdown
    index 4ba78f52..06ea8fbb 100644
    --- a/pt-br/elixir-pt.html.markdown
    +++ b/pt-br/elixir-pt.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    @@ -20,7 +20,7 @@ e muitos outros recursos.
     # Não há comentários de múltiplas linhas,
     # mas você pode empilhar os comentários.
     
    -# Para usar o shell do elixir use o comando `iex`.
    +# Para usar o shell do Elixir use o comando `iex`.
     # Compile seus módulos com o comando `elixirc`.
     
     # Ambos devem estar em seu path se você instalou o Elixir corretamente.
    @@ -51,7 +51,7 @@ elem({1, 2, 3}, 0) #=> 1
     head #=> 1
     tail #=> [2,3]
     
    -# Em elixir, bem como em Erlang, o sinal `=` denota pattern match,
    +# Em Elixir, bem como em Erlang, o sinal `=` denota pattern match,
     # e não uma atribuição.
     #
     # Isto significa que o que estiver à esquerda (pattern) é comparado com o que
    @@ -85,7 +85,7 @@ linhas.
     <> #=> "abc"
     [?a, ?b, ?c]   #=> 'abc'
     
    -# `?a` em elixir retorna o valor ASCII para a letra `a`
    +# `?a` em Elixir retorna o valor ASCII para a letra `a`
     ?a #=> 97
     
     # Para concatenar listas use `++`, para binários use `<>`
    @@ -110,7 +110,7 @@ menor..maior = 1..10 # Pattern matching pode ser usada em ranges também
     5 * 2  #=> 10
     10 / 2 #=> 5.0
     
    -# Em elixir o operador `/` sempre retorna um float.
    +# Em Elixir o operador `/` sempre retorna um float.
     
     # Para divisão de inteiros use `div`
     div(10, 2) #=> 5
    @@ -167,7 +167,7 @@ else
       "Isso será"
     end
     
    -# Lembra do patter matching? Muitas estruturas de fluxo de controle em elixir contam com ela.
    +# Lembra do patter matching? Muitas estruturas de fluxo de controle em Elixir contam com ela.
     
     # `case` nos permite comparar um valor com muitos patterns:
     case {:um, :dois} do
    @@ -296,7 +296,7 @@ Geometry.area({:circle, 3})       #=> 28.25999999999999801048
     # Geometry.area({:circle, "not_a_number"})
     #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
     
    -# Devido à imutabilidade, recursão é uma grande parte do elixir
    +# Devido à imutabilidade, recursão é uma grande parte do Elixir
     defmodule Recursion do
       def sum_list([head | tail], acc) do
         sum_list(tail, acc + head)
    @@ -309,7 +309,7 @@ end
     
     Recursion.sum_list([1,2,3], 0) #=> 6
     
    -# Módulos do elixir suportam atributos, hpa atributos embutidos e você
    +# Módulos do Elixir suportam atributos, hpa atributos embutidos e você
     # pode também adicionar os seus próprios.
     defmodule MyMod do
       @moduledoc """
    @@ -361,7 +361,7 @@ end
     ## ---------------------------
     
     # Elixir conta com o modelo de ator para concorrência. Tudo o que precisamos para
    -# escrever programas concorrentes em elixir são três primitivos: spawning processes,
    +# escrever programas concorrentes em Elixir são três primitivos: spawning processes,
     # sending messages e receiving messages.
     
     # Para iniciar um novo processo usamos a função `spawn`, a qual leva uma função
    diff --git a/ro-ro/elixir-ro.html.markdown b/ro-ro/elixir-ro.html.markdown
    index 10fec3c5..60500d64 100644
    --- a/ro-ro/elixir-ro.html.markdown
    +++ b/ro-ro/elixir-ro.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    @@ -22,7 +22,7 @@ posibilități.
     # Pentru comentarii pe mai multe linii nu există sintaxă separată,
     # de aceea folosiți mai multe linii cu comentarii.
     
    -# Pentru a folosi shell-ul elixir utilizați comanda `iex`.
    +# Pentru a folosi shell-ul Elixir utilizați comanda `iex`.
     # Compilați modulele cu comanda `elixirc`.
     
     # Ambele comenzi vor lucra în terminal, dacă ați instalat Elixir corect.
    diff --git a/ru-ru/elixir-ru.html.markdown b/ru-ru/elixir-ru.html.markdown
    index c8c2c060..8dd48ba7 100644
    --- a/ru-ru/elixir-ru.html.markdown
    +++ b/ru-ru/elixir-ru.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    diff --git a/sk-sk/elixir-sk.html.markdown b/sk-sk/elixir-sk.html.markdown
    index 2401f92e..d5159610 100644
    --- a/sk-sk/elixir-sk.html.markdown
    +++ b/sk-sk/elixir-sk.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    @@ -24,7 +24,7 @@ a množstvo funkcií.
     # Pre spustenie Elixir shellu zadajte príkaz `iex`
     # Kompiláciu zdrojových kódov vykonáte príkazom `elixirc`
     
    -# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali elixir
    +# Obe príkazy by sa už mali nachádzať v path pokiaľ ste nainštalovali Elixir
     # správne.
     
     ## ---------------------------
    @@ -86,7 +86,7 @@ reťazec.
     <> #=> "abc"
     [?a, ?b, ?c]   #=> 'abc'
     
    -# `?a` v elixire vráti ASCII číselnú reprezentáciu pre znak `a`
    +# `?a` v Elixir vráti ASCII číselnú reprezentáciu pre znak `a`
     ?a #=> 97
     
     # Pre spájanie zoznamov sa používa `++`, pre binárne typy `<>`
    @@ -119,7 +119,7 @@ pohlavia.gillian #=> "žena"
     5 * 2  #=> 10
     10 / 2 #=> 5.0
     
    -# V elixire operátor `/` vždy vráti float (reálne číslo).
    +# V Elixir operátor `/` vždy vráti float (reálne číslo).
     
     # Pre celočíselné delenie sa používa `div`
     div(10, 2) #=> 5
    @@ -182,7 +182,7 @@ else
     end
     
     # Pamätáte sa na pattern matching? Mnoho štruktúr pre riadenie toku v
    -# elixire sa spoliehajú práve na pattern matching.
    +# Elixir sa spoliehajú práve na pattern matching.
     
     # `case` dovolí nám porovnať hodnotu oproti mnohým vzorom:
     case {:one, :two} do
    @@ -314,7 +314,7 @@ Geometria.oblast({:kruh, 3})       #=> 28.25999999999999801048
     # Geometria.oblast({:kruh, "nie_je_cislo"})
     #=> ** (FunctionClauseError) no function clause matching in Geometria.oblast/1
     
    -# Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou elixiru
    +# Vďaka nemeniteľnosti (immutability) je rekurzia významnou časťou Elixir
     defmodule Rekurzia do
       def sumuj_zoznam([hlavicka | schvost], acc) do
         sumuj_zoznam(chvost, acc + hlavicka)
    @@ -389,7 +389,7 @@ end
     ## ---------------------------
     
     # Elixir sa pri konkurencii spolieha na Actor model. Všetko čo je
    -# potrebné na písanie konkuretných programov v elixire sú tri primitívy:
    +# potrebné na písanie konkuretných programov v Elixir sú tri primitívy:
     # spawning procesy, posielanie a prijímanie správ.
     
     # Na spustnenie nového procesu použijeme `spawn` funkciu, ktorá má ako
    diff --git a/zh-cn/elixir-cn.html.markdown b/zh-cn/elixir-cn.html.markdown
    index daee8d3c..0ed1d823 100644
    --- a/zh-cn/elixir-cn.html.markdown
    +++ b/zh-cn/elixir-cn.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
     translators:
    diff --git a/zh-tw/elixir-tw.html.markdown b/zh-tw/elixir-tw.html.markdown
    index c15f90c1..3dba95b3 100644
    --- a/zh-tw/elixir-tw.html.markdown
    +++ b/zh-tw/elixir-tw.html.markdown
    @@ -1,5 +1,5 @@
     ---
    -language: elixir
    +language: Elixir
     contributors:
         - ["Joao Marques", "http://github.com/mrshankly"]
         - ["Dzianis Dashkevich", "https://github.com/dskecse"]
    @@ -19,10 +19,10 @@ Elixir 是一門建構在 Erlang 虛擬機上的現代函數式語言。它完
     # 沒有多行註解的功能
     # 但你可以連續使用多個單行
     
    -# 用 `iex` 來進入 elixir shell
    +# 用 `iex` 來進入 Elixir shell
     # 用 `elixirc` 來編譯你的模組
     
    -# 如果你已成功安裝 elixir 的話,這兩個命令應已在你的 path 下。
    +# 如果你已成功安裝 Elixir 的話,這兩個命令應已在你的 path 下。
     
     ## ---------------------------
     ## -- 基本型別
    @@ -50,7 +50,7 @@ elem({1, 2, 3}, 0) #=> 1
     head #=> 1
     tail #=> [2,3]
     
    -# 在 elixir 中,就如同 Erlang 裡一樣,`=` 代表的是模式比對,而非指派。
    +# 在 Elixir 中,就如同 Erlang 裡一樣,`=` 代表的是模式比對,而非指派。
     #
     # 這代表將使用左手邊的模式 (pattern) 去與右手邊的值進行比對。
     #
    @@ -80,7 +80,7 @@ string.
     <> #=> "abc"
     [?a, ?b, ?c]   #=> 'abc'
     
    -# `?a` 在 elixir 中會回傳字母 `a` 的 ASCII 整數
    +# `?a` 在 Elixir 中會回傳字母 `a` 的 ASCII 整數
     ?a #=> 97
     
     # 用 `++` 來合併串列,而合併二進位則要用 `<>`
    @@ -105,7 +105,7 @@ lower..upper = 1..10 # 可以對 range 進行模式比對
     5 * 2  #=> 10
     10 / 2 #=> 5.0
     
    -# 在 elixir 中, `/` 運算元永遠回傳浮點數。
    +# 在 Elixir 中, `/` 運算元永遠回傳浮點數。
     
     # 若需要回傳整數的除法,用 `div`
     div(10, 2) #=> 5
    @@ -290,7 +290,7 @@ Geometry.area({:circle, 3})       #=> 28.25999999999999801048
     # Geometry.area({:circle, "not_a_number"})
     #=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
     
    -# 由於不可變特性 (immutability),遞迴在 elixir 中扮演重要的角色。
    +# 由於不可變特性 (immutability),遞迴在 Elixir 中扮演重要的角色。
     defmodule Recursion do
       def sum_list([head | tail], acc) do
         sum_list(tail, acc + head)
    @@ -356,7 +356,7 @@ end
     ## -- 平行處理
     ## ---------------------------
     
    -# Elixir 依靠 actor 模式來進行平行處理。在 elixir 中要寫出平行處理程式,
    +# Elixir 依靠 actor 模式來進行平行處理。在 Elixir 中要寫出平行處理程式,
     # 只需要三個基本要素:建立行程,發送訊息及接收訊息。
     
     # 我們用 `spawn` 函式來建立行程,它接收一個函式當參數。
    
    From 26db60dad15a5fb2003715b0fc376c9086a86fa3 Mon Sep 17 00:00:00 2001
    From: Thiago Lages de Alencar 
    Date: Tue, 9 May 2023 13:55:29 -0300
    Subject: [PATCH 017/392] Update csharp-pt.html.markdown
    
    ---
     pt-br/csharp-pt.html.markdown | 4 ++--
     1 file changed, 2 insertions(+), 2 deletions(-)
    
    diff --git a/pt-br/csharp-pt.html.markdown b/pt-br/csharp-pt.html.markdown
    index 87e5b3a4..d464a639 100644
    --- a/pt-br/csharp-pt.html.markdown
    +++ b/pt-br/csharp-pt.html.markdown
    @@ -252,7 +252,7 @@ on a new line! ""Wow!"", the masses cried";
                 {
                     // Inicia a interação 100 vezes, fooDoWhile 0->99
                     if (false)
    -                    continue; // pule a intereção atual para apróxima
    +                    continue; // pule a intereção atual para a próxima
     
                     fooDoWhile++;
     
    @@ -269,7 +269,7 @@ on a new line! ""Wow!"", the masses cried";
     
                 // For Each Loop
                 // Estrutura do foreach  => foreach(  in )
    -            // O laço foreach  percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable
    +            // O laço foreach percorre sobre qualquer objeto que implementa IEnumerable ou IEnumerable
                 // Toda a coleção de tipos  (Array, List, Dictionary...) no .Net framework
                 // implementa uma ou mais destas interfaces.
                 // (O ToCharArray() pode ser removido, por que uma string também implementa IEnumerable)
    
    From 937125b5a481b6481dd4d4e2aeabd81728d42f51 Mon Sep 17 00:00:00 2001
    From: kenryuS 
    Date: Sat, 27 May 2023 00:41:10 -0400
    Subject: [PATCH 018/392] [css/ja-jp] Added New Translated Document:
     css-jp.html.markdown
    
    ---
     ja-jp/css-jp.html.markdown | 332 +++++++++++++++++++++++++++++++++++++
     1 file changed, 332 insertions(+)
     create mode 100644 ja-jp/css-jp.html.markdown
    
    diff --git a/ja-jp/css-jp.html.markdown b/ja-jp/css-jp.html.markdown
    new file mode 100644
    index 00000000..2baaee8d
    --- /dev/null
    +++ b/ja-jp/css-jp.html.markdown
    @@ -0,0 +1,332 @@
    +---
    +language: css
    +contributors:
    +    - ["Mohammad Valipour", "https://github.com/mvalipour"]
    +    - ["Marco Scannadinari", "https://github.com/marcoms"]
    +    - ["Geoffrey Liu", "https://github.com/g-liu"]
    +    - ["Connor Shea", "https://github.com/connorshea"]
    +    - ["Deepanshu Utkarsh", "https://github.com/duci9y"]
    +    - ["Brett Taylor", "https://github.com/glutnix"]
    +    - ["Tyler Mumford", "https://tylermumford.com"]
    +translators:
    +    - ["Kenryu Shibata", "https://github.com/kenryuS"]
    +filename: learncss-jp.css
    +lang: ja-jp
    +---
    +
    +ウェブサイトはHTMLでページの構造を指定します。
    +CSS (カスケーディングスタイルシート) はページの**見た目**を指定する別の言語です。
    +
    +CSSは単純な*ルール*で構成されています。それぞれが1つ以上の*セレクター*の視覚的*要素*を
    +指定した*値*にします。
    +
    +この解説ページではCSS 2で書かれいていますが、CSS 3でより拡張性のある、
    +より新しい機能を使うことが出来ます。
    +
    +**注釈:** CSSは視覚的な情報として出力するので、[dabblet](http://dabblet.com/)の様な、
    +CSSをすぐに試せる環境で学習することを勧めます。
    +この解説ページの主な目的は構文と小技の紹介です。
    +
    +## 構文
    +
    +```css
    +/* コメントはスラッシュ・アスタリスクの中に書きます。
    +   1行コメントはありません。*/
    +
    +/* ####################
    +   ##   セレクター   ##
    +   #################### */
    +
    +/* セレクターはページにある要素を指定します。 */
    +selector { property: value; /* その他のプロパティ...*/ }
    +
    +/*
    +例となる要素:
    +
    +
    +*/ + +/* 一つのクラスでセレクトする */ +.class1 { } + +/* または、両方を使う */ +.class1.class2 { } + +/* または、要素名だけで */ +div { } + +/* または、ID名で */ +#anID { } + +/* または、属性名で */ +[attr] { font-size:smaller; } + +/* または、指定された値を持つ属性で */ +[attr='value'] { font-size:smaller; } + +/* 指定した値で始まる属性 (CSS 3) */ +[attr^='val'] { font-size:smaller; } + +/* または、値で終わる属性 (CSS 3) */ +[attr$='ue'] { font-size:smaller; } + +/* または、半角スペースで分けられた値の持つどれかの属性 */ +[otherAttr~='foo'] { } +[otherAttr~='bar'] { } + +/* または、ダッシュで区切られた値のどれかの属性 例: "-" (U+002D) */ +[otherAttr|='en'] { font-size:smaller; } + + +/* 様々なセレクターを組み合わせることで限定されたセレクターを作ることができます。 + その場合は、間に半角スペースを入れないでください。*/ +div.some-class[attr$='ue'] { } + +/* 他の要素の子要素を指定することができます。*/ +div.some-parent > .class-name { } + +/* または、要素の子孫を指定できます。子要素は親要素の直接的な子孫です。 + (親要素からインデンテーション一回分)子孫は親要素からすべての + インデンテーションされた階を含みます。*/ +div.some-parent .class-name { } + +/* 注意:半角スペースのない同じセレクターは別の意味になります。 + なんだと思いますか。*/ +div.some-parent.class-name { } + +/* 一個前の要素を選択することもできます。*/ +.i-am-just-before + .this-element { } + +/* または、その要素の前のすべての要素をすべて選択できます。*/ +.i-am-any-element-before ~ .this-element { } + +/* いくつかのセレクターには擬似クラスがあり、要素が特定の状態のときだけ + 適用するスタイルを指定できます。*/ + +/* 例えば、マウスカーソルが要素の上にホバーしている状態のスタイルを + 指定するときは、*/ +selector:hover { } + +/* リンク先にすでに訪れている状態を指定する場合は、*/ +selector:visited { } + +/* または訪れていない場合は、*/ +selected:link { } + +/* 要素が選択されている場合は、*/ +selected:focus { } + +/* 親要素内の最初の子要素を指定する場合は、*/ +selector:first-child {} + +/* 最後の要素を指定する場合は、*/ +selector:last-child {} + +/* 擬似クラスのように、疑似子要素を使えば、特定の部分のスタイルを + 指定できます。*/ + +/* 選択された要素の最初の疑似子要素を指定する。*/ +selector::before {} + +/* 選択された要素の最後の疑似子要素を指定する。*/ +selector::after {} + +/* アスタリスクを適切な場所に記述すれば、 + ワイルドカードとしてすべての要素を指定することができます。 */ +* { } /* すべての要素 */ +.parent * { } /* すべての子孫要素 */ +.parent > * { } /* すべての子要素 */ + +/* セレクタを一度にグループで複数選択して同じスタイルを + 適用することができます。*/ +selector1, selector2 { } + +/* #################### + ## プロパティー ## + #################### */ + +selector { + + /* 長さの単位は画面の大きさに対して相対的か絶対的なものを選べます */ + + /* 相対的単位 */ + width: 50%; /* 親要素の幅に対する割合で指定する */ + font-size: 2em; /* フォントサイズの何倍かで指定する */ + font-size: 2rem; /* か、ルート要素のフォントサイズを元にする */ + font-size: 2vw; /* ビューポートの幅1パーセントの何倍かで指定する (CSS 3) */ + font-size: 2vh; /* ビューポートの高さでの指定 */ + font-size: 2vmin; /* vhかvwのどちらかの小さい方を選びます */ + font-size: 2vmax; /* または、大きい方 */ + + /* 絶対的単位 */ + width: 200px; /* ピクセル */ + font-size: 20pt; /* ポイント */ + width: 5cm; /* センチメートル */ + min-width: 50mm; /* ミリメートル */ + max-width: 5in; /* インチ */ + + /* 色 */ + color: #F6E; /* 省略された六進法値での色 */ + color: #FF66EE; /* 六進法値での色 */ + color: tomato; /* 名前の付いた色 */ + color: rgb(255, 255, 255); /* rgb値での色 */ + color: rgb(10%, 20%, 50%); /* rgbの割合での色 */ + color: rgba(255, 0, 0, 0.3); /* rgba値での色(CSS3) 値は0 <= a <= 1 */ + color: transparent; /* アルファ値を0にするのと同じ効果 */ + color: hsl(0, 100%, 50%); /* hsl割合(CSS 3)での色 */ + color: hsla(0, 100%, 50%, 0.3); /* アルファ値を含んだhsl割合での色 */ + + /* ボーダー */ + border-width:5px; /* 幅を指定*/ + border-style:solid; /* 線のスタイルを指定 */ + border-color:red; /* 背景色を指定するときと似たようなこと */ + border: 5px solid red; /* 上記の3つのプロパティーを一つのプロパティーで書く */ + border-radius:20px; /* CSS3での新しいプロパティーです(ボーダー角半径) */ + + /* 画像を要素の背景として使う */ + background-image: url(/img-path/img.jpg); /* url()内のクォーテーションは必須ではありません */ + + /* フォント */ + font-family: Arial; + + /* フォント名に半角空白がある場合にはクォーテーションで囲む必要があります。 */ + font-family: "Courier New"; + + /* もしフォントが存在しないなら、ブラウザが定義されたフォントを探します。 */ + font-family: "Courier New", Trebuchet, Arial, sans-serif; +} +``` + +## 使い方 + +CSSファイルを`.css`拡張子で保存する. + +```html + + + + + + + +
    +
    +``` + +## 順序と数珠繋ぎ性質 + +ある要素が複数のセレクタの対象となり、複数のプロパティが設定されることがあります。 +このような場合、いずれかのルールが他よりも優先されます。より具体的なセレクタを持つルールは +具体的でないセレクタより優先され、スタイルシートの後で使用されるルールは前のものを上書きします。 +(これは、リンクされた二つの異なるスタイルシートがある要素に対するルールを含み、 +ルールが同じ具体性を持つ場合、リンクの順序が優先され、一番最初にリンクしたシートが +スタイルを決定する、ということでもあります)。 + +この性質がキャスケーディング(数珠繋ぎ)と呼ばれ、CSSの名前もこの言葉からきています。 + +このようなCSSを考慮する: + +```css +/* A */ +p.class1[attr='value'] + +/* B */ +p.class1 { } + +/* C */ +p.class2 { } + +/* D */ +p { } + +/* E */ +p { property: value !important; } +``` + +そしてこのようなHTML: + +```html +

    +``` + +スタイルの優先順位は次の通りです。 優先順位はブロック全体ではなく、 +それぞれの**プロパティ**に対してであることを忘れないでください。 + +* `E`は、`!important`というキーワードがあるため、最も優先順位が高いです。 +ただし、その使用は避けることが推奨されます。 +* `F` はインラインスタイルなので、その次です。 +* `A` は、他の何よりも「具体的」であるため、その次になります。 + これは3つの指定子を持っています: 要素名 `p`、クラス名 `class1`、 + 属性名 `attr='value'` です。 +* `C` is next, even though it has the same specificity as `B`. + This is because it appears after `B`. +* `B`が次で、 +* `D` が最後になります。 + +## メディアクエリ + +CSSメディアクエリとは、CSS 3の機能で、印刷時や、特定の寸法やピクセル密度の画面上で、特定のCSSルールを適用する際の条件を指定できるものです。 セレクタの具体性を高めるものではありません。 + +```css +/* すべてのデバイスで使われるルール */ +h1 { + font-size: 2em; + color: white; + background-color: black; +} + +/* 印刷するときにh1タグの印刷に使われるインクの量を減らす。 */ +@media print { + h1 { + color: black; + background-color: white; + } +} + +/* 画面の幅が480ピクセルより小さいときにフォントサイズを大きくする。 */ +@media screen and (min-width: 480px) { + h1 { + font-size: 3em; + font-weight: normal; + } +} +``` + +メディアクエリには次の機能があります: +`width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid` +`min-` や `max-`は多くの機能名に前置することができます。 + +`resolution`機能は古いデバイスでは対応しておらず、`device-pixel-ratio`を代わりに使います。 + +多くのスマホやタブレットはウェブページに`viewport`メタタグをつけない限り、デスクトップに表示されるサイズで表示します。 + +```html + + + +``` + +## 互換性 + +大抵のCSS2(または多くのCSS3)の機能はすべてのブラウザやデバイスで機能します。 +しかしそれでも、1度ちゃんと新しい機能が動作するかを確認するのが無難です。 + +## その他の資料(英語) + +* [CanIUse](http://caniuse.com) (互換性に関する細かい情報) +* [Dabblet](http://dabblet.com/) (CSS テスター) +* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS) (チュートリアルとレファレンス) +* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/) (レファレンス) +* [DevTips' CSS Basics](https://www.youtube.com/playlist?list=PLqGj3iMvMa4IOmy04kDxh_hqODMqoeeCy) (チュートリアル) + +## 関連記事(英語) + +* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) +* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/) +* [QuirksMode CSS](http://www.quirksmode.org/css/) +* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) と [LESS](http://lesscss.org/) でCSSプリプロセッシング。 +* [CSS-Tricks](https://css-tricks.com) From 05f21578b23557f1c8dce31ddd13d4bffea3033c Mon Sep 17 00:00:00 2001 From: Kenryu Shibata Date: Wed, 12 Jul 2023 22:28:05 -0400 Subject: [PATCH 019/392] Update python-jp.html.markdown --- ja-jp/python-jp.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/ja-jp/python-jp.html.markdown b/ja-jp/python-jp.html.markdown index 18e7d1b8..363d00a0 100644 --- a/ja-jp/python-jp.html.markdown +++ b/ja-jp/python-jp.html.markdown @@ -11,6 +11,7 @@ contributors: translators: - ["kakakaya", "https://github.com/kakakaya"] - ["Ryota Kayanuma", "https://github.com/PicoSushi"] + - ["Kenryu Shibata", "https://github.com/kenryuS"] filename: learnpython-jp.py lang: ja-jp --- @@ -180,7 +181,7 @@ bool({}) # => False bool(()) # => False #################################################### -# 2. Variables and Collections +# 2. 変数と集合 #################################################### # Python にはprint関数があります。 @@ -400,7 +401,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} #################################################### -# 3. 制御の流れとiterable +# 3. 制御の流れと反復可能オブジェクト #################################################### # まずは変数を作りましょう。 @@ -429,7 +430,7 @@ for animal in ["dog", "cat", "mouse"]: print("{} is a mammal".format(animal)) """ -"range(数値)" は、ゼロから与えられた数値までのiterableを返します。 +"range(数値)" は、ゼロから与えられた数値までのiterable(反復可能オブジェクト)を返します。 出力: 0 1 @@ -649,7 +650,7 @@ print(ceil(3.7)) # => 4.0 print(floor(3.7)) # => 3.0 # 全部の関数をモジュールからインポートすることができます。 -# Warning: この方法は推奨されません。 +# 注意: この方法は推奨されません。 from math import * # 短い名前でモジュールをインポートすることができます。 @@ -990,9 +991,9 @@ print(say()) # Can you buy me a beer? print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` -## Ready For More? +## さらなる学習の準備ができましたか? -### Free Online +### 無料のオンラインコンテンツ * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) * [Ideas for Python Projects](http://pythonpracticeprojects.com) From b0410c0919900aa094cf83950c9140930b80c268 Mon Sep 17 00:00:00 2001 From: FeepingCreature Date: Sat, 30 Sep 2023 21:38:48 +0200 Subject: [PATCH 020/392] Remove Neat Language. That compiler is extremely dead; I'm working on the next generation of the language, so for now avoid confusing the namespace with the old version. --- neat.html.markdown | 297 --------------------------------------------- 1 file changed, 297 deletions(-) delete mode 100644 neat.html.markdown diff --git a/neat.html.markdown b/neat.html.markdown deleted file mode 100644 index f02461ee..00000000 --- a/neat.html.markdown +++ /dev/null @@ -1,297 +0,0 @@ ---- -language: neat -contributors: - - ["Feep", "https://github.com/FeepingCreature"] -filename: LearnNeat.nt ---- - -Neat is basically a smaller version of D1 with some experimental syntax and a focus on terseness without losing the basic C-like syntax. - -[Read more here.](https://github.com/FeepingCreature/fcc/wiki) - -```c -// single line comments start with // -/* - multiline comments look like this -*/ -/+ - or this - /+ these can be nested too, same as D +/ -+/ - -// Module name. This has to match the filename/directory. -module LearnNeat; - -// Make names from another module visible in this one. -import std.file; -// You can import multiple things at once. -import std.math, std.util; -// You can even group up imports! -import std.(process, socket); - -// Global functions! -void foo() { } - -// Main function, same as in C. -// string[] == "array of strings". -// "string" is just an alias for char[], -void main(string[] args) { - // Call functions with "function expression". - writeln "Hello World"; - // You can do it like in C too... if you really want. - writeln ("Hello World"); - // Declare a variable with "type identifier" - string arg = ("Hello World"); - writeln arg; - // (expression, expression) forms a tuple. - // There are no one-value tuples though. - // So you can always use () in the mathematical sense. - // (string) arg; <- is an error - - /* - byte: 8 bit signed integer - char: 8 bit UTF-8 byte component. - short: 16 bit signed integer - int: 32 bit signed integer - long: 64 bit signed integer - - float: 32 bit floating point - double: 64 bit floating point - real: biggest native size floating point (80 bit on x86). - - bool: true or false - */ - int a = 5; - bool b = true; - // as in C, && and || are short-circuit evaluating. - b = b && false; - assert(b == false); - // "" are "format strings". So $variable will be substituted at runtime - // with a formatted version of the variable. - writeln "$a"; - // This will just print $a. - writeln `$a`; - // you can format expressions with $() - writeln "$(2+2)"; - // Note: there is no special syntax for characters. - char c = "a"; - // Cast values by using type: expression. - // There are three kinds of casts: - // casts that just specify conversions that would be happening automatically - // (implicit casts) - float f = float:5; - float f2 = 5; // would also work - // casts that require throwing away information or complicated computation - - // those must always be done explicitly - // (conversion casts) - int i = int:f; - // int i = f; // would not work! - // and, as a last attempt, casts that just reinterpret the raw data. - // Those only work if the types have the same size. - string s = "Hello World"; - // Arrays are (length, pointer) pairs. - // This is a tuple type. Tuple types are (type, type, type). - // The type of a tuple expression is a tuple type. (duh) - (int, char*) array = (int, char*): s; - // You can index arrays and tuples using the expression[index] syntax. - writeln "pointer is $(array[1]) and length is $(array[0])"; - // You can slice them using the expression[from .. to] syntax. - // Slicing an array makes another array. - writeln "$(s[0..5]) World"; - // Alias name = expression gives the expression a name. - // As opposed to a variable, aliases do not have an address - // and can not be assigned to. (Unless the expression is assignable) - alias range = 0 .. 5; - writeln "$(s[range]) World"; - // You can iterate over ranges. - for int i <- range { - write "$(s[i])"; - } - writeln " World"; - // Note that if "range" had been a variable, it would be 'empty' now! - // Range variables can only be iterated once. - // The syntax for iteration is "expression <- iterable". - // Lots of things are iterable. - for char c <- "Hello" { write "$c"; } - writeln " World"; - // For loops are "for test statement"; - alias test = char d <- "Hello"; - for test write "$d"; - writeln " World\t\x05"; // note: escapes work - // Pointers: function the same as in C, btw. The usual. - // Do note: the pointer star sticks with the TYPE, not the VARIABLE! - string* p; - assert(p == null); // default initializer - p = &s; - writeln "$(*p)"; - // Math operators are (almost) standard. - int x = 2 + 3 * 4 << 5; - // Note: XOR is "xor". ^ is reserved for exponentiation (once I implement that). - int y = 3 xor 5; - int z = 5; - assert(z++ == 5); - assert(++z == 7); - writeln "x $x y $y z $z"; - // As in D, ~ concatenates. - string hewo = "Hello " ~ "World"; - // == tests for equality, "is" tests for identity. - assert (hewo == s); - assert !(hewo is s); - // same as - assert (hewo !is s); - - // Allocate arrays using "new array length" - int[] integers = new int[] 10; - assert(integers.length == 10); - assert(integers[0] == 0); // zero is default initializer - integers = integers ~ 5; // This allocates a new array! - assert(integers.length == 11); - - // This is an appender array. - // Instead of (length, pointer), it tracks (capacity, length, pointer). - // When you append to it, it will use the free capacity if it can. - // If it runs out of space, it reallocates - but it will free the old array automatically. - // This makes it convenient for building arrays. - int[auto~] appender; - appender ~= 2; - appender ~= 3; - appender.free(); // same as {mem.free(appender.ptr); appender = null;} - - // Scope variables are automatically freed at the end of the current scope. - scope int[auto~] someOtherAppender; - // This is the same as: - int[auto~] someOtherAppender2; - onExit { someOtherAppender2.free; } - - // You can do a C for loop too - // - but why would you want to? - for (int i = 0; i < 5; ++i) { } - // Otherwise, for and while are the same. - while int i <- 0..4 { - assert(i == 0); - break; // continue works too - } then assert(false); // if we hadn't break'd, this would run at the end - // This is the height of loopdom - the produce-test-consume loop. - do { - int i = 5; - } while (i == 5) { - assert(i == 5); - break; // otherwise we'd go back up to do { - } - - // This is a nested function. - // Nested functions can access the surrounding function. - string returnS() { return s; } - writeln returnS(); - - // Take the address of a function using & - // The type of a global function is ReturnType function(ParameterTypeTuple). - void function() foop = &foo; - - // Similarly, the type of a nested function is ReturnType delegate(ParameterTypeTuple). - string delegate() returnSp = &returnS; - writeln returnSp(); - // Class member functions and struct member functions also fit into delegate variables. - // In general, delegates are functions that carry an additional context pointer. - // ("fat pointers" in C) - - // Allocate a "snapshot" with "new delegate". - // Snapshots are not closures! I used to call them closures too, - // but then my Haskell-using friends yelled at me so I had to stop. - // The difference is that snapshots "capture" their surrounding context - // when "new" is used. - // This allows things like this - int delegate(int) add(int a) { - int add_a(int b) { return a + b; } - // This does not work - the context of add_a becomes invalid - // when add returns. - // return &add_a; - // Instead: - return new &add_a; - } - int delegate(int) dg = add 2; - assert (dg(3) == 5); - // or - assert (((add 2) 3) == 5); - // or - assert (add 2 3 == 5); - // add can also be written as - int delegate(int) add2(int a) { - // this is an implicit, nameless nested function. - return new λ(int b) { return a + b; } - } - // or even - auto add3(int a) { return new λ(int b) -> a + b; } - // hahahaaa - auto add4 = λ(int a) -> new λ(int b) -> a + b; - assert(add4 2 3 == 5); - // If your keyboard doesn't have a λ (you poor sod) - // you can use \ too. - auto add5 = \(int a) -> new \(int b) -> a + b; - // Note! - auto nestfun = λ() { } // There is NO semicolon needed here! - // "}" can always substitute for "};". - // This provides syntactic consistency with built-in statements. - - - // This is a class. - // Note: almost all elements of Neat can be used on the module level - // or just as well inside a function. - class C { - int a; - void writeA() { writeln "$a"; } - // It's a nested class - it exists in the context of main(). - // so if you leave main(), any instances of C become invalid. - void writeS() { writeln "$s"; } - } - C cc = new C; - // cc is a *reference* to C. Classes are always references. - cc.a = 5; // Always used for property access. - auto ccp = &cc; - (*ccp).a = 6; - // or just - ccp.a = 7; - cc.writeA(); - cc.writeS(); // to prove I'm not making things up - // Interfaces work same as in D, basically. Or Java. - interface E { void doE(); } - // Inheritance works same as in D, basically. Or Java. - class D : C, E { - override void writeA() { writeln "hahahahaha no"; } - override void doE() { writeln "eeeee"; } - // all classes inherit from Object. (toString is defined in Object) - override string toString() { return "I am a D"; } - } - C cd = new D; - // all methods are always virtual. - cd.writeA(); - E e = E:cd; // dynamic class cast! - e.doE(); - writeln "$e"; // all interfaces convert to Object implicitly. - - // Templates! - // Templates are parameterized namespaces, taking a type as a parameter. - template Templ(T) { - alias hi = 5, hii = 8; - // Templates always have to include something with the same name as the template - // - this will become the template's _value_. - // Static ifs are evaluated statically, at compile-time. - // Because of this, the test has to be a constant expression, - // or something that can be optimized to a constant. - static if (types-equal (T, int)) { - alias Templ = hi; - } else { - alias Templ = hii; - } - } - assert(Templ!int == 5); - assert(Templ!float == 8); -} -``` - -## Topics Not Covered - - * Extended iterator types and expressions - * Standard library - * Conditions (error handling) - * Macros From b8d2f410a838c49836e2572c8a3c682709153671 Mon Sep 17 00:00:00 2001 From: Edoardo La Greca <35077726+EdoardoLaGreca@users.noreply.github.com> Date: Sat, 10 Feb 2024 14:37:32 +0100 Subject: [PATCH 021/392] [swift/en] describe convenience initializers (#4836) --- swift.html.markdown | 3 +++ 1 file changed, 3 insertions(+) diff --git a/swift.html.markdown b/swift.html.markdown index e46dcc75..36124e11 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -679,6 +679,9 @@ class Rect: Shape { // A simple class `Square` extends `Rect` class Square: Rect { + // Use a convenience initializer to make calling a designated initializer faster and more "convenient". + // Convenience initializers call other initializers in the same class and pass default values to one or more of their parameters. + // Convenience initializers can have parameters as well, which are useful to customize the called initializer parameters or choose a proper initializer based on the value passed. convenience init() { self.init(sideLength: 5) } From 1c33cd1a9a09b310937f753920ccd149550a71c2 Mon Sep 17 00:00:00 2001 From: qlikwer Date: Mon, 12 Feb 2024 16:58:50 +0500 Subject: [PATCH 022/392] Update go.html.markdown (#4838) corrected an error in the number pi --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 2eb40939..d6468f58 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -95,7 +95,7 @@ can include line breaks.` // Same string type. // Non-ASCII literal. Go source is UTF-8. g := 'Σ' // rune type, an alias for int32, holds a unicode code point. - f := 3.14195 // float64, an IEEE-754 64-bit floating point number. + f := 3.14159 // float64, an IEEE-754 64-bit floating point number. c := 3 + 4i // complex128, represented internally with two float64's. // var syntax with initializers. From 3914133997b74a9fedf402d2cf345125f0c59ca0 Mon Sep 17 00:00:00 2001 From: qlikwer Date: Mon, 12 Feb 2024 17:18:44 +0500 Subject: [PATCH 023/392] corrected an error in the number pi (#4839) * Update go-de.html.markdown corrected an error in the number pi * Update go.html.markdown corrected an error in the number pi * Update go-pt.html.markdown corrected an error in the number pi * Update go-hu.html.markdown corrected an error in the number pi * Update go-cn.html.markdown corrected an error in the number pi * Update go-kr.html.markdown corrected an error in the number pi * Update go-ca.html.markdown corrected an error in the number pi * Update go-es.html.markdown corrected an error in the number pi * Update go-fi.html.markdown corrected an error in the number pi * Update go-fr.html.markdown corrected an error in the number pi * Update go-ru.html.markdown corrected an error in the number pi * Update go-it.html.markdown corrected an error in the number pi * Update go.html.markdown corrected an error in the number pi --- ca-es/go-ca.html.markdown | 2 +- cs-cz/go.html.markdown | 2 +- de-de/go-de.html.markdown | 2 +- es-es/go-es.html.markdown | 2 +- fi-fi/go-fi.html.markdown | 2 +- fr-fr/go-fr.html.markdown | 2 +- hu-hu/go-hu.html.markdown | 2 +- it-it/go-it.html.markdown | 2 +- ko-kr/go-kr.html.markdown | 2 +- pt-br/go-pt.html.markdown | 2 +- ru-ru/go-ru.html.markdown | 2 +- zh-cn/go-cn.html.markdown | 2 +- 12 files changed, 12 insertions(+), 12 deletions(-) diff --git a/ca-es/go-ca.html.markdown b/ca-es/go-ca.html.markdown index 99f0d393..591ce837 100644 --- a/ca-es/go-ca.html.markdown +++ b/ca-es/go-ca.html.markdown @@ -95,7 +95,7 @@ salts de línia.` // El mateix tipus // literals Non-ASCII literal. El tipus de Go és UTF-8. g := 'Σ' // El tipus rune, és un àlies de int32 conté un caràcter unicode. - f := 3.14195 // float64, un número de 64 bits amb coma flotant IEEE-754. + f := 3.14159 // float64, un número de 64 bits amb coma flotant IEEE-754. c := 3 + 4i // complex128, representat internament amb dos float64. // Sintaxi amb var i inicialitzadors. diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown index cef8c5ab..4f8569bf 100644 --- a/cs-cz/go.html.markdown +++ b/cs-cz/go.html.markdown @@ -90,7 +90,7 @@ může obsahovat nové řádky` // Opět typ řetězec. // Můžeme použít ne ASCII znaky, Go používá UTF-8. g := 'Σ' // type runa, což je alias na int32 a ukládá se do něj znak UTF-8 - f := 3.14195 // float64, je IEEE-754 64-bit číslem s plovoucí čárkou. + f := 3.14159 // float64, je IEEE-754 64-bit číslem s plovoucí čárkou. c := 3 + 4i // complex128, interně uložené jako dva float64. // takhle vypadá var s inicializací diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 9409e181..30a660fa 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -82,7 +82,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // nicht-ASCII Literal. Go Quelltext ist UTF-8 kompatibel. g := 'Σ' // Ein Runen-Typ, alias int32, gebraucht für unicode code points. - f := 3.14195 // float64, eine IEEE-754 64-bit Dezimalzahl + f := 3.14159 // float64, eine IEEE-754 64-bit Dezimalzahl c := 3 + 4i // complex128, besteht intern aus zwei float64-er // "var"-Syntax mit Initalwert diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 78267695..2d1dbce7 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -88,7 +88,7 @@ saltos de línea.` // mismo tipo cadena // Literal no ASCII. Los ficheros fuente de Go son UTF-8. g := 'Σ' // Tipo rune, un alias de int32, alberga un carácter unicode. - f := 3.14195 // float64, el estándar IEEE-754 de coma flotante 64-bit. + f := 3.14159 // float64, el estándar IEEE-754 de coma flotante 64-bit. c := 3 + 4i // complex128, representado internamente por dos float64. // Sintaxis var con iniciadores. var u uint = 7 // Sin signo, pero la implementación depende del tamaño diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index 15acdbae..a7337250 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -90,7 +90,7 @@ voi sisältää rivinvaihtoja.` // Sama merkkijonotyyppi. // Ei-ASCII todellisarvo. Go-lähdekoodi on UTF-8. g := 'Σ' // riimutyyppi, lempinimi int32:lle, sisältää unicode-koodipisteen. - f := 3.14195 //float64, IEEE-754 64-bittinen liukuluku. + f := 3.14159 //float64, IEEE-754 64-bittinen liukuluku. c := 3 + 4i // complex128, sisäisesti ilmaistu kahdella float64:lla. // var -syntaksi alkuarvoilla. diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index 38cc3b52..a002acfc 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -87,7 +87,7 @@ sauts de ligne.` // Chaîne de caractère. g := 'Σ' // type rune, un alias pour le type int32, contenant un caractère // unicode. - f := 3.14195 // float64, un nombre flottant IEEE-754 de 64-bit. + f := 3.14159 // float64, un nombre flottant IEEE-754 de 64-bit. c := 3 + 4i // complex128, considéré comme deux float64 par le compilateur. // Syntaxe "var" avec une valeur d'initialisation. diff --git a/hu-hu/go-hu.html.markdown b/hu-hu/go-hu.html.markdown index 638c9489..1a96b8c3 100644 --- a/hu-hu/go-hu.html.markdown +++ b/hu-hu/go-hu.html.markdown @@ -89,7 +89,7 @@ func learnTypes() { g := 'Σ' // rúna(rune) típus, megegyezik az uint32-vel, egy UTF-8 karaktert // tárol - f := 3.14195 // float64, az IEEE-754 szabványnak megfelelő 64-bites + f := 3.14159 // float64, az IEEE-754 szabványnak megfelelő 64-bites // lebegőpontos szám c := 3 + 4i // complex128, belsőleg két float64-gyel tárolva diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index 2af2468d..d88e8741 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -91,7 +91,7 @@ può includere andata a capo.` // Sempre di tipo stringa. // Stringa letterale non ASCII. I sorgenti Go sono in UTF-8. g := 'Σ' // Il tipo runa, alias per int32, è costituito da un code point unicode. - f := 3.14195 // float64, un numero in virgola mobile a 64-bit (IEEE-754) + f := 3.14159 // float64, un numero in virgola mobile a 64-bit (IEEE-754) c := 3 + 4i // complex128, rappresentato internamente con due float64. diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index 3012c04f..42360294 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -81,7 +81,7 @@ func learnTypes() { // non-ASCII 리터럴. Go 소스는 UTF-8로 작성해야 한다. g := 'Σ' // 유니코드 코드 포인트를 담고 있고, int32 타입의 가칭(alias)인 rune 타입 - f := 3.14195 // float64, an IEEE-754 64-bit 부동소수 타입 + f := 3.14159 // float64, an IEEE-754 64-bit 부동소수 타입 c := 3 + 4i // complex128, 내부적으로는 두 개의 float64 타입으로 표현됨 // 초기값과 함께 사용하는 var 키워드. diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index f68d63eb..60b3a472 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -77,7 +77,7 @@ pode incluir quebras de linha.` // mesmo tipo string // literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8. g := 'Σ' // tipo rune, um alias para int32, que contém um código unicode - f := 3.14195 // float64, número de vírgula flutuante de 64bit (IEEE-754) + f := 3.14159 // float64, número de vírgula flutuante de 64bit (IEEE-754) c := 3 + 4i // complex128, representado internamente com dois float64s // Declaração de variáveis, com inicialização. diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 8d2eac90..40b32816 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -82,7 +82,7 @@ func learnTypes() { // Символ не из ASCII. Исходный код Go в кодировке UTF-8. g := 'Σ' // тип rune, это алиас для типа int32, содержит символ юникода. - f := 3.14195 // float64, 64-х битное число с плавающей точкой (IEEE-754). + f := 3.14159 // float64, 64-х битное число с плавающей точкой (IEEE-754). c := 3 + 4i // complex128, внутри себя содержит два float64. // Синтаксис var с инициализациями. diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 0123c0a6..8afacf2a 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -78,7 +78,7 @@ func learnTypes() { // 非ascii字符。Go使用UTF-8编码。 g := 'Σ' // rune类型,int32的别名,使用UTF-8编码 - f := 3.14195 // float64类型,IEEE-754 64位浮点数 + f := 3.14159 // float64类型,IEEE-754 64位浮点数 c := 3 + 4i // complex128类型,内部使用两个float64表示 // var变量可以直接初始化。 From 224e01864a73eb306f23a18f32490c1dd51addee Mon Sep 17 00:00:00 2001 From: ven Date: Wed, 14 Feb 2024 11:01:52 +0100 Subject: [PATCH 024/392] Fix 4841 --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index cb530bbb..08f1d8fb 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -655,7 +655,7 @@ attached terminal [Javascript: The Right Way][10] is a guide intended to introduce new developers to JavaScript and help experienced developers learn more about its best practices. -[Javascript:Info][11] is a modern javascript tutorial covering the basics (core language and working with a browser) +[javascript.info][11] is a modern javascript tutorial covering the basics (core language and working with a browser) as well as advanced topics with concise explanations. From 60e5d32ff9dbfe7695dce05a0034ee662e467776 Mon Sep 17 00:00:00 2001 From: Flavio <77132531+flavin27@users.noreply.github.com> Date: Wed, 14 Feb 2024 10:22:59 -0300 Subject: [PATCH 025/392] [c/pt-br] fix untranslated english section (#4842) * fix: unstranslated section * fix: miss clicked --------- Co-authored-by: Flavio <77132531+flaviodev27@users.noreply.github.com> --- pt-br/c++-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/c++-pt.html.markdown b/pt-br/c++-pt.html.markdown index 7d8b75f1..ca289001 100644 --- a/pt-br/c++-pt.html.markdown +++ b/pt-br/c++-pt.html.markdown @@ -363,7 +363,7 @@ void OwnedDog::print() const { Dog::print(); // Chame a função de impressão na classe Dog base de std::cout << "Dog is owned by " << owner << "\n"; - // Prints "Dog is and weights " + // Imprime "Dog is and weights " // "Dog is owned by " } From ebd63d9299dbcb007185fa7e4b377893466b73c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Sun, 25 Feb 2024 08:27:16 -0300 Subject: [PATCH 026/392] [toml/pt-br] Add translation for TOML docs (#4846) * feat(pt-br/toml-pt.html.markdown): Add translation for TOML docs Translate the TOML file into Portuguese (Brazilian Portuguese). * fix(pt-br/toml-pt.html.markdown): Add language code in filename Add portuguese language code in filename to be unique. --- pt-br/toml-pt.html.markdown | 232 ++++++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) create mode 100644 pt-br/toml-pt.html.markdown diff --git a/pt-br/toml-pt.html.markdown b/pt-br/toml-pt.html.markdown new file mode 100644 index 00000000..bdb1decf --- /dev/null +++ b/pt-br/toml-pt.html.markdown @@ -0,0 +1,232 @@ +--- +language: toml +filename: learntoml-pt.toml +contributors: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +translators: + - ["Adaías Magdiel", "https://adaiasmagdiel.com/"] +lang: pt-br +--- + +TOML significa Tom's Obvious, Minimal Language. É uma linguagem de serialização de dados projetada para ser um formato de arquivo de configuração mínimo que é fácil de ler devido à semântica óbvia. + +É uma alternativa ao YAML e JSON. Tem como objetivo ser mais amigável para humanos do que JSON e mais simples que YAML. TOML é projetado para mapear de forma inequívoca para uma tabela de hash e deve ser fácil de converter em estruturas de dados em uma ampla variedade de linguagens. + +Cuidado, a especificação do TOML ainda passa por muitas mudanças. Até que seja marcado como 1.0, você deve assumir que é instável e agir de acordo. Este documento segue o TOML v0.4.0. + +```toml +# Comentários em TOML são feitos desta forma. + +################### +# TIPOS ESCALARES # +################### + +# Nosso objeto raiz (que continuará por todo o documento) será um mapa, +# que é equivalente a um dicionário, hash ou objeto em outras linguagens. + +# A chave, o sinal de igual e o valor precisam estar na mesma linha +# (embora alguns valores possam ser quebrados em várias linhas). +chave = "valor" +string = "Olá" +number = 42 +float = 3.14 +boolean = true +dateTime = 2002-07-16T20:32:00-03:00 +scientificNotation = 1e+12 +"chaves podem estar entre aspas" = true # Tanto " quanto ' são aceitáveis +"chaves podem conter" = "letras, números, underscores e hífens" + +# Uma chave não pode ser vazia, mas uma chave vazia entre aspas é permitido +"" = "blank" # VÁLIDO mas não é recomendado +'' = 'blank' # VÁLIDO mas não é recomendado + +########## +# String # +########## + +# Todas as strings precisam ter apenas caracteres UTF-8 válidos. +# Podemos escapar caracteres e alguns deles têm uma sequência de escape compacta. +# Por exemplo: \t adiciona uma tabulação. Leia a spec para conhecer todos. +basicString = "São cercadas por aspas. \"Sou digno de citação\". Nome\tJosé." + +multiLineString = """ +são cercadas por três aspas +em cada lado e permitem novas linhas.""" + +literalString = 'são cercadas por aspas simples. Escape de caracteres não é permitido.' + +multiLineString = ''' +são cercadas por três aspas simples em cada lado +e permitem novas linhas. Escape de caracteres também não é permitido. +A primeira quebra de linha é removida em strings brutas + Todo outro espaço em branco + é preservado. #! foi preservado? +''' + +# Para dados binários é recomendado que você use Base64, outra codificação ASCII ou UTF8. +# A manipulação dessa codificação será específico da aplicação. + +############ +# Inteiros # +############ + +## Inteiros podem começar com um +, um -, ou nada. +## Zeros à frente não são permitidos. +## Formatos em hexadecimal, octal e binário são permitidos. +## Não são permitidos valores que não podem ser expressados como uma série de dígitos. +int1 = +42 +int2 = 0 +int3 = -21 +int4 = 0xcafebabe +int5 = 0o755 +int6 = 0b11011100 +integerRange = 64 + +## Você pode usar underscores para melhorar a legibilidade. +## Cada underscore precisa estar entre, pelo menos, um dígito. +int7 = 5_349_221 +int8 = 1_2_3_4_5 # VÁLIDO, mas não é recomendado + +######### +# Float # +######### + +# Floats são inteiros seguidos por uma fração e/ou de um expoente. +flt1 = 3.1415 +flt2 = -5e6 +flt3 = 6.626E-34 + +############# +# Booleanos # +############# + +bool1 = true +bool2 = false +booleanosPrecisamEstarEmMinusculo = true + +############ +# Datetime # +############ + +date1 = 1979-05-27T07:32:00Z # Tempo UTC, seguindo especificação RFC 3339/ISO 8601 +date2 = 1979-05-26T15:32:00+08:00 # com um deslocamento segundo a RFC 3339/ISO 8601 +date3 = 1979-05-27T07:32:00 # sem deslocamento +date4 = 1979-05-27 # sem as horas e sem deslocamento + +#################### +# TIPOS DE COLEÇÃO # +#################### + +######### +# Array # +######### + +array1 = [ 1, 2, 3 ] +array2 = [ "Vírgulas", "são", "delimitadores" ] +array3 = [ "Não misture", "tipos", "diferentes" ] +array4 = [ [ 1.2, 2.4 ], ["todas as", 'strings', """são do mesmo""", '''tipo'''] ] +array5 = [ + "Espaços em branco", "são", "ignorados" +] + +########## +# Tabela # +########## + +# Tabelas (ou tabelas de hash, ou dicionários) é uma coleção de pares chave/valor. +# Eles aparecem entre colchetes em uma linha separada. +# Tabelas vazias são permitidas e simplesmente não possuem chave/valor associado. +[tabela] + +# Abaixo disso, e até a próxima tabela ou final do arquivo, estão as chaves/valores dessa tabela. +# Os pares de chave/valor dentro das tabelas não têm garantia de estar em nenhuma ordem específica. +[table-1] +chave1 = "algum texto" +chave2 = 123 + +[table-2] +chave1 = "outro texto" +chave2 = 456 + +# Pontos são proibidos em chaves simples porque são usados para indicar tabelas aninhadas. +# As regras de nomenclatura para cada parte separada por ponto são as mesmas que para chaves. +[dog."tater.man"] +type = "pug" + +# Na terra do JSON, você teria a seguinte estrutura: +# { "dog": { "tater.man": { "type": "pug" } } } + +# Espaços em branco em torno das partes separadas por pontos são ignorados, de qualquer forma, +# é sempre recomendado não utilizar espaços em branco desnecessários. +[a.b.c] # isso é o recomendado +[ d.e.f ] # mesmo que [d.e.f] +[ j . "ʞ" . 'l' ] # mesmo que [j."ʞ".'l'] + +# Você não precisa especificar todas as super-tabelas se não quiser. TOML sabe +# como lidar com isso para você. +# [x] você +# [x.y] não precisa +# [x.y.z] disso +[x.y.z.w] # para isso funcionar + +# Mesmo que uma super-tabela não tenha sido definida diretamente e não tenha definido uma +# chave específica, ainda é possível escrever nela. +[a.b] +c = 1 + +[a] +d = 2 + +# Irá gerar o seguinte JSON: +# { "a": {"b": {"c": 1}, "d": 2 } } + +# Você não pode definir uma chave ou tabela mais de uma vez. É inválido fazer isso. + +# NÃO FAÇA ISSO +[a] +b = 1 + +[a] +c = 2 + +# NEM MESMO ISSO +[a] +b = 1 + +[a.b] +c = 2 + +# O nome de todas as tabelas não pode ser vazio. +[] # INVÁLIDO +[a.] # INVÁLIDO +[a..b] # INVÁLIDO +[.b] # INVÁLIDO +[.] # INVÁLIDO + +#################### +# Tabelas em linha # +#################### + +tabelasEmLinha = { sãoFechadasCom = "{ e }", precisamEstarEmUmaLinha = true } +ponto = { x = 1, y = 2 } + +#################### +# Array de Tabelas # +#################### + +# Um array de tabelas pode ser expresso usando um nome de tabela entre colchetes duplos. +# Cada tabela com o mesmo nome entre colchetes duplos será um item no array. +# As tabelas são inseridas na ordem em que são encontradas. + +[[produtos]] +nome = "array de tabelas" +sku = 738594937 +tabelasVaziasSaoPermitidas = true + +[[produtos]] + +[[produtos]] +nome = "Unhas" +sku = 284758393 +color = "cinza" +``` From 16fa336a43a16c9515cdaa8a18276b05f47f3ffe Mon Sep 17 00:00:00 2001 From: Ricardo Islas Ruiz Date: Sun, 25 Feb 2024 14:46:12 -0700 Subject: [PATCH 027/392] [go/en]: Clarify comment related to the append function in slices. (#4780) --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index d6468f58..0631ffab 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -130,7 +130,7 @@ can include line breaks.` // Same string type. // Because they are dynamic, slices can be appended to on-demand. // To append elements to a slice, the built-in append() function is used. // First argument is a slice to which we are appending. Commonly, - // the array variable is updated in place, as in example below. + // the slice variable is updated in place, as in example below. s := []int{1, 2, 3} // Result is a slice of length 3. s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] From 665c28c90e6c051f43d1fa3e3c2fe7543f3ae742 Mon Sep 17 00:00:00 2001 From: Adrien LUDWIG <42720099+Adrien-LUDWIG@users.noreply.github.com> Date: Sun, 25 Feb 2024 22:48:09 +0100 Subject: [PATCH 028/392] [MongoDB] Fix comment: wrong method (#4779) --- mongodb.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mongodb.html.markdown b/mongodb.html.markdown index 5633f3f9..f4e7d709 100644 --- a/mongodb.html.markdown +++ b/mongodb.html.markdown @@ -228,7 +228,7 @@ db.engineers.update({ name: 'Foo Baz' }, ) /////////////////////// Delete ///////////////////////// -// Queries are in the form of db.collectionName.find() +// Queries are in the form of db.collectionName.delete() // Delete first document matching query, always returns deletedCount db.engineers.deleteOne({ name: 'Foo Baz' }) From 51efc479330cb85c919222af054e82fb9f7e47d5 Mon Sep 17 00:00:00 2001 From: KIM Taegyoon Date: Mon, 26 Feb 2024 06:50:46 +0900 Subject: [PATCH 029/392] [F#/en] added mutation (#4763) --- fsharp.html.markdown | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/fsharp.html.markdown b/fsharp.html.markdown index c140d6b1..f1f8e95d 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -33,6 +33,21 @@ let myInt = 5 let myFloat = 3.14 let myString = "hello" // note that no types needed +// Mutable variables +let mutable a=3 +a <- 4 // a is now 4. + +// Somewhat mutable variables +// Reference cells are storage locations that enable you to create mutable values with reference semantics. +// See https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/reference-cells +let xRef = ref 10 +printfn "%d" xRef.Value // 10 +xRef.Value <- 11 +printfn "%d" xRef.Value // 11 + +let a=[ref 0; ref 1] // somewhat mutable list +a[0].Value <- 2 + // ------ Lists ------ let twoToFive = [2; 3; 4; 5] // Square brackets create a list with // semicolon delimiters. From d123cd4a5c6599401e20c5d4190173d75cddd520 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Peeters?= Date: Sun, 25 Feb 2024 23:36:47 +0100 Subject: [PATCH 030/392] [powershell/en] Fix and clarify -eq operator on (some) objects (#4333) --- powershell.html.markdown | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index 0383035b..2e7539a5 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -118,14 +118,15 @@ $False - 5 # => -5 2 -lt 3 -and 3 -lt 2 # => False # (-is vs. -eq) -is checks if two objects are the same type. -# -eq checks if the objects have the same values. +# -eq checks if the objects have the same values, but sometimes doesn't work +# as expected. # Note: we called '[Math]' from .NET previously without the preceeding # namespaces. We can do the same with [Collections.ArrayList] if preferred. [System.Collections.ArrayList]$a = @() # Point a at a new list $a = (1,2,3,4) $b = $a # => Point b at what a is pointing to $b -is $a.GetType() # => True, a and b equal same type -$b -eq $a # => True, a and b values are equal +$b -eq $a # => None! See below [System.Collections.Hashtable]$b = @{} # => Point a at a new hash table $b = @{'one' = 1 'two' = 2} @@ -154,6 +155,13 @@ $age = 22 "$name's name is $($name.Length) characters long." # => "Steve's name is 5 characters long." +# Strings can be compared with -eq, but are case insensitive. We can +# force with -ceq or -ieq. +"ab" -eq "ab" # => True +"ab" -eq "AB" # => True! +"ab" -ceq "AB" # => False +"ab" -ieq "AB" # => True + # Escape Characters in Powershell # Many languages use the '\', but Windows uses this character for # file paths. Powershell thus uses '`' to escape characters @@ -274,6 +282,10 @@ $array.AddRange($otherArray) # Now $array is [1, 2, 3, 4, 5, 6] # Examine length with "Count" (Note: "Length" on arrayList = each items length) $array.Count # => 6 +# -eq doesn't compare array but extract the matching elements +$array = 1,2,3,1,1 +$array -eq 1 # => 1,1,1 +($array -eq 1).Count # => 3 # Tuples are like arrays but are immutable. # To use Tuples in powershell, you must use the .NET tuple class. From d1d16b4a0de1e834c5a99c9a05a5a1026ae361a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Mon, 26 Feb 2024 10:49:23 -0300 Subject: [PATCH 031/392] chore(pug): Update include paths to use .pug extension (#4848) Previously, the include paths in pug.html.markdown were referencing .png files. This commit updates the paths to use .pug extensions for better clarity and consistency. - Updated include paths to point to .pug files - Ensures correct file references are used throughout the project --- pug.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pug.html.markdown b/pug.html.markdown index 1bc49f64..9badee92 100644 --- a/pug.html.markdown +++ b/pug.html.markdown @@ -158,13 +158,13 @@ case orderStatus //-

    Your order is pending

    //- --INCLUDE-- -//- File path -> "includes/nav.png" +//- File path -> "includes/nav.pug" h1 Company Name nav a(href="index.html") Home a(href="about.html") About Us -//- File path -> "index.png" +//- File path -> "index.pug" html body include includes/nav.pug From 048addeaada37f8e64b37a8046f3283c3e2d7eb4 Mon Sep 17 00:00:00 2001 From: ven Date: Mon, 26 Feb 2024 14:51:00 +0100 Subject: [PATCH 032/392] Remove one of the es/CSS tutorials #4825 --- es-es/css-es.html.markdown | 253 ------------------------------------- 1 file changed, 253 deletions(-) delete mode 100644 es-es/css-es.html.markdown diff --git a/es-es/css-es.html.markdown b/es-es/css-es.html.markdown deleted file mode 100644 index 6395f5fd..00000000 --- a/es-es/css-es.html.markdown +++ /dev/null @@ -1,253 +0,0 @@ ---- -language: css -filename: learncss-es.css -contributors: - - ["Mohammad Valipour", "https://github.com/mvalipour"] - - ["Marco Scannadinari", "https://github.com/marcoms"] -translators: - - ["Daniel Zendejas","https://github.com/DanielZendejas"] -lang: es-es ---- - -Tutorial de CSS en español - -En los primeros días de la web no había elementos visuales, todo -era texto plano. Pero después, con el desarrollo de los navegadores, -las páginas con contenido visual empezaron a ser más comunes. -CSS es el lenguaje estándar que existe para separar el contenido -(HTML) y el aspecto visual de las páginas web. - -Lo que CSS hace es proveer con una sintaxis que te permite apuntar a distintos -elementos HTML y asignarles diferentes propiedades visuales. - -CSS, como cualquier otro lenguaje, tiene múltiples versiones. Aquí nos enfocamos -en CSS 2.0. No es la versión más reciente pero sí la más soportada y compatible. - -**NOTA:** Como los resultados de CSS son efectos visuales, para aprenderlo, -necesitarás probar todo tipo de cosas en ambientes como -[dabblet](http://dabblet.com/). Este artículo se enfoca, principalmente, en -la sintaxis y consejos generales. - -```css -/* ¡Los comentarios aparecen dentro de diagonal-asterisco, justo como esta línea! */ - -/* #################### - ## SELECTORES - ####################*/ - -/* Generalmente, la sentencia principal en CSS es muy simple. */ -selector { propiedad: valor; /* más propiedades separados por punto y coma...*/ } - -/* El selector es usado para apuntar a (seleccionar) un elemento en la página. - -¡Puedes apuntar a todos los elementos en la página con el asterisco! */ -* { color:red; } - -/* -Dado un elemento como este en la página: - -
    -*/ - -/* puedes seleccionar el
    por el nombre de su clase */ -.una-clase { } - -/*¡O por sus dos clases! */ -.una-clase.clase2 { } - -/* O por el nombre de su elemento */ -div { } - -/* O por su Id */ -#unaId { } - -/* ¡O por el hecho de que tiene un atributo! */ -[attr] { font-size:smaller; } - -/* O por el hecho de que el atributo tiene un valor determinado */ -[attr='valor'] { font-size:smaller; } - -/* Empieza con un valor ('val' en este caso)*/ -[attr^='val'] { font-size:smaller; } - -/* O termina con un valor ('or' en este caso) */ -[attr$='or'] { font-size:smaller; } - -/* O incluso contiene un valor ('lo' en este caso) */ -[attr~='lo'] { font-size:smaller; } - -/*Más importante, puedes combinar estos criterios de búsqueda entre sí. -No debe existir ningún espacio entre estas partes porque hace que el -significado cambie.*/ -div.una-clase[attr$='or'] { } - -/* También puedes seleccionar un elemento HTML basándote en sus padres*/ - -/* Un elemento que es hijo directo de otro elemento (Seleccionado de la forma que -vimos anteriormente) */ - -div.un-padre > .nombre-clase {} - -/* O cualquiera de sus ancestros en la jerarquía*/ -/* La siguiente sentencia selecciona a cualquier elemento que tenga una clase -"nombre-clase" y sea hijo de un div con clase "un-padre" EN CUALQUIER PROFUNDIDAD*/ -div.un-padre .nombre-clase {} - -/* advertencia: el mismo selector sin espacio tiene otro significado. ¿Puedes -identificar la diferencia?*/ - -/* También puedes seleccionar un elemento basado en su hermano inmediato previo*/ -.yo-estoy-antes + .este-elemento { } - -/*o cualquier hermano previo */ -.yo-soy-cualquiera-antes ~ .estes-elemento {} - -/* Existen algunas pseudo-clases que permiten seleccionar un elemento -basado en el comportamiendo de la página (a diferencia de la estructura de -la página) */ - -/* Por ejemplo, para cuando pasas el mouse por encima de un elemento */ -:hover {} - -/* o una liga visitada*/ -:visited {} - -/* o una liga no visitada aún*/ -:link {} - -/* o un elemento de un formulario que esté seleccionado */ -:focus {} - - -/* #################### - ## PROPIEDADES - ####################*/ - -selector { - - /* Unidades */ - width: 50%; /* en porcentaje */ - font-size: 2em; /* dos veces el tamaño de la fuente actual */ - width: 200px; /* en pixeles */ - font-size: 20pt; /* en puntos */ - width: 5cm; /* en centimetros */ - width: 50mm; /* en milimetros */ - width: 5in; /* en pulgadas */ - - /* Colores */ - background-color: #F6E; /* en hexadecimal corto */ - background-color: #F262E2; /* en hexadecimal largo */ - background-color: tomato; /* puede ser un color con nombre */ - background-color: rgb(255, 255, 255); /* en rgb */ - background-color: rgb(10%, 20%, 50%); /* en rgb percent */ - background-color: rgba(255, 0, 0, 0.3); /* en rgb semi-transparente (con valor alfa)*/ - - /* Imagenes */ - background-image: url(/ruta-a-la-imagen/imagen.jpg); - - /* Fuentes */ - font-family: Arial; - font-family: "Courier New"; /* si el nombre contiene espacios, debe ir entre comillas */ - font-family: "Courier New", Trebuchet, Arial; /* si la primera fuente no se encontró - entonces se busca la seguna, o la tercera, así recursivamente*/ -} - -``` - -## Uso - -Guarda cualquier CSS que quieras en un archivo con extensión `.css`. - -```xml - - - - - - - -
    -
    - -``` - -## Preferencia y orden - -Como te habrás dado cuenta un elemento puede ser seleccionado por más -de un selector. En este caso alguna de las reglas cobra preferencia -sobre las otras: - -Dado el siguiente CSS: - -```css -/*A*/ -p.clase1[attr='valor'] - -/*B*/ -p.clase1 {} - -/*C*/ -p.clase2 {} - -/*D*/ -p {} - -/*E*/ -p { propiedad: valor !important; } - -``` - -Y el siguiente HTML: - -```xml -

    -

    -``` - -El orden respetado es el siguiente: -Recuerda, la preferencia es por cada **property**, no para el bloque completo. - -* `E` tiene la preferencia más elevada gracias a la palabra `!important`. - Es recomendado evitar esto a menos que sea estrictamente necesario incluirlo. -* `F` le sigue, porque es estilo incrustado directamente en el HTML. -* `A` le sigue, porque es más específico que cualquier otra opción. - más específico = más especificadores. Aquí hay tres especificadores: elemento `p` + - nombre de la clase `clase1` + un atributo `attr='valor'` -* `C` le sigue. Aunque tiene el mismo número de especificadores como `B` - pero aparece después. -* Luego va `B` -* y al final `D`. - -## Compatibilidad - -La mayoría de las funcionalidades de CSS2 (y gradualmente de CSS3) son compatibles -en todos los navegadores y dispositivos. Pero siempre es vital tener en mente la -compatibilidad y disponibilidad del CSS que uses con respecto a los navegadores -y dispositivos para los que desarrolles. - -[QuirksMode CSS](http://www.quirksmode.org/css/) es una excelente referencia para esto. - -## Recursos - -* Para ejecutar un test de compatibilidad, revisa [CanIUse](http://caniuse.com). -* CSS Playground [Dabblet](http://dabblet.com/). -* [Mozilla Developer Network's CSS documentation](https://developer.mozilla.org/en-US/docs/Web/CSS). -* [Codrops' CSS Reference](http://tympanus.net/codrops/css_reference/). - -## Otras lecturas - -* [Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/). -* [Selecting elements using attributes](https://css-tricks.com/almanac/selectors/a/attribute/). -* [QuirksMode CSS](http://www.quirksmode.org/css/). -* [Z-Index - The stacking context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -* [SASS](http://sass-lang.com/) y [LESS](http://lesscss.org/) para preprocesamiento CSS. -* [CSS-Tricks](https://css-tricks.com). - From a7b13739905a46403ca962357671afd033973454 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Mon, 26 Feb 2024 12:58:11 -0300 Subject: [PATCH 033/392] [pug/pt-br] Add translation for Pug documentation (#4847) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * docs(pt-br): Add translation for Pug documentation This commit adds the translation for the Pug documentation from English to Brazilian Portuguese. The translated content includes an introduction to Pug, syntax examples for tags, attributes, JavaScript usage, loops, conditionals, including content, mixins, and additional resources. This translation aims to make the Pug documentation more accessible to Portuguese-speaking users. It covers the basic concepts and functionalities of Pug, providing a comprehensive guide for developers interested in using the Pug templating engine for HTML generation in their projects. * docs(pt-br): Add translation for Pug documentation Translate the last section "Additional Resources" * docs(pug): Update comments in Portuguese translation Update the comments to better reflect the behavior of the code. - Changed "Tags com filhos" to "Tags aninhadas" for clarity. * feat: Update Portuguese text in Pug guide Update Portuguese text in the Pug guide to improve readability and consistency with the rest of the document. - Changed "Hello there" to "Olá, pessoas" - Adjusted multi-line text from English to Portuguese for alignment. - Made sure all text aligns with the same language throughout the guide. --- pt-br/pug-pt.html.markdown | 211 +++++++++++++++++++++++++++++++++++++ 1 file changed, 211 insertions(+) create mode 100644 pt-br/pug-pt.html.markdown diff --git a/pt-br/pug-pt.html.markdown b/pt-br/pug-pt.html.markdown new file mode 100644 index 00000000..a74666fb --- /dev/null +++ b/pt-br/pug-pt.html.markdown @@ -0,0 +1,211 @@ +--- +language: Pug +contributors: + - ["Michael Warner", "https://github.com/MichaelJGW"] +filename: index-pt.pug +translators: + - ["Adaías Magdiel", "https://adaiasmagdiel.com/"] +lang: pt-br +--- + +## Começando com Pug + +Pug é uma pequena linguagem que compila para HTML. Possui uma sintaxe limpa +com algumas funcionalidades adicionais, como declarações if e loops. Também pode ser utilizada +como uma linguagem de templates no lado do servidor para tecnologias como o Node.js. + +### The Language +```pug + +//- Comentário de uma linha + +//- Comentário de + várias linhas + +//- ---TAGS--- +//- Básico +div +//-
    +h1 +//-

    +minha-propriaTag +//- + +//- Tags irmãs +div +div +//-
    +
    + +//- Tags aninhadas +div + div +//-
    +
    +
    + +//- Textos +h1 Olá, pessoas +//-

    Olá, pessoas

    + +//- Texto de várias linhas +div. + Oi, + tudo bem? +//-
    + Oi, + tudo bem? +
    + +//- ---ATRIBUTOS--- +div(class="minha-class" id="meu-id" meu-proprio-atributo="data" enabled) +//-
    + +//- Abreviações +span.minha-class +//- +.minha-class +//-
    +div#meu-id +//-
    +div#meu-id.minha-class +//-
    + + +//- ---JAVASCRIPT--- +- const lang = "pug"; + +//- Javascript em várias linhas +- + const lang = "pug"; + const awesome = true; + +//- Classes com Javascript +- const myClass = ['class1', 'class2', 'class3'] +div(class=myClass) +//-
    + +//- Estilos com Javascript +- const myStyles = {'color':'white', 'background-color':'blue'} +div(styles=myStyles) +//-
    + +//- Atributos com Javascript +- const myAttributes = {"src": "photo.png", "alt": "My Photo"} +img&attributes(myAttributes) +//- My Photo +- let disabled = false +input(type="text" disabled=disabled) +//- +- disabled = true +input(type="text" disabled=disabled) +//- + +//- Templates com Javascript +- const name = "Bob"; +h1 Olá, #{name} +h1= name +//-

    Olá, Bob

    +//-

    Bob

    + +//- ---LOOPS--- + +//- 'each' e 'for' tem a mesma função, aqui nós usaremos apenas 'each'. + +each value, i in [1,2,3] + p=value +//- +

    1

    +

    2

    +

    3

    + +each value, index in [1,2,3] + p=value + '-' + index +//- +

    1-0

    +

    2-1

    +

    3-2

    + +each value in [] + p=value +//- + +each value in [] + p=value +else + p Sem valores + +//-

    Sem valores

    + +//- ---CONDICIONAIS--- + +- const number = 5 +if number < 5 + p o número é menor do que 5 +else if number > 5 + p o número é maior do que 5 +else + p o número é 5 +//-

    o número é 5

    + +- const orderStatus = "Aguardando"; +case orderStatus + when "Aguardando" + p.warn Seu pedido está em espera + when "Completado" + p.success Seu pedido foi completado. + when -1 + p.error Ocorreu algum erro + default + p Nenhum registro de pedido encontrado +//-

    Seu pedido está em espera

    + +//- --INCLUINDO CONTEÚDOS-- +//- Caminho do arquivo -> "includes/nav.pug" +h1 Indústrias ACME +nav + a(href="index.html") Início + a(href="about.html") Sobre Nós + +//- Caminho do arquivo -> "index.pug" +html + body + include includes/nav.pug +//- + + +

    Indústrias ACME

    + + + + +//- Importando Javascript e CSS +script + include scripts/index.js +style + include styles/theme.css + +//- ---MIXIN--- +mixin basic + div Olá ++basic +//-
    Olá
    + +mixin comment(nome, comentario) + div + span.comment-name= nome + div.comment-text= comentario ++comment("Gil", "Tudo é divino, tudo é maravilhoso") +//- +
    + Gil +
    Tudo é divino, tudo é maravilhoso
    +
    + +``` + + +### Saiba Mais +- [Site Oficial](https://pugjs.org/) +- [Documentação](https://pugjs.org/api/getting-started.html) +- [Repositório no Github](https://github.com/pugjs/pug) From 137f298f16fa393459de0243e3414137c8a1ffac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Tue, 27 Feb 2024 14:39:01 -0300 Subject: [PATCH 034/392] fix(pt-br/css): Corrections made to some errors in the last translation. - There are some errors in the css presented that have also been corrected in this version --- pt-br/css-pt.html.markdown | 232 +++++++++++++++++++------------------ 1 file changed, 121 insertions(+), 111 deletions(-) diff --git a/pt-br/css-pt.html.markdown b/pt-br/css-pt.html.markdown index e4f55276..4c52942a 100644 --- a/pt-br/css-pt.html.markdown +++ b/pt-br/css-pt.html.markdown @@ -8,33 +8,36 @@ contributors: - ["Connor Shea", "https://github.com/connorshea"] - ["Deepanshu Utkarsh", "https://github.com/duci9y"] translators: + - ["Adaías Magdiel", "https://adaiasmagdiel.com/"] - ["Gabriel Gomes", "https://github.com/gabrielgomesferraz"] - ["Gabriele Luz", "https://github.com/gabrieleluz"] - lang: pt-br --- -No início da web não havia elementos visuais, apenas texto puro. Mas com maior desenvolvimento de navegadores da web, páginas web totalmente visuais também se tornaram comuns. +Páginas web são feitas utilizando HTML para demarcar o conteúdo. +O CSS (Cascading Style Sheets) é uma linguagem separada que é responsável +especificamente pela **aparência** da página. -CSS ajuda a manter a separação entre o conteúdo (HTML) e o visual de uma página web. +Códigos CSS são construídos utilizando várias regras estáticas. Cada regra aceita um ou mais *seletores* +e aplica *valores* específicos de propriedades visuais. Essas propriedades são aplicadas +nos elementos da página indicados pelos seletores. -CSS permite atingir diferentes elementos em uma página HTML e atribuir diferentes propriedades visuais para eles. +Este guia foi escrito com o CSS 2 em mente, complementado pelas novas +funcionalidades do CSS 3. -Este guia foi escrito para CSS2, embora CSS3 esteja rapidamente se tornando popular. - -**NOTA:** Porque CSS produz resultados visuais, a fim de aprender, você precisa treinar em um playground CSS como [dabblet](http://dabblet.com/). -O foco principal deste artigo é sobre a sintaxe e algumas dicas gerais. +**NOTA:** Devido ao fato do CSS produzir resultados visuais, a fim de aprender, você precisa treinar em um playground CSS como [dabblet](http://dabblet.com/). +O foco principal deste artigo é a sintaxe e algumas dicas gerais. ```css -/* Comentários aparecem dentro do slash-asterisk, tal como esta linha! - Não há "comentários de uma linha"; este é o único estilo de comentário * / +/* Comentários aparecem dentro de blocos com / e *, tal como esta linha! + Não há "comentários de uma linha"; este é o único estilo de comentário. * / /* #################### ## SELETORES #################### */ -/* O seletor é usado para direcionar um elemento em uma página. - seletor { propriedade: valor; / * Mais propriedades ... * / } +/* O seletor é usado para selecionar um elemento em uma página. */ +seletor { propriedade: valor; /* Mais propriedades... */ } /* Abaixo um elemento de exemplo: @@ -42,63 +45,62 @@ Abaixo um elemento de exemplo:
    */ -/* Você pode direcioná-lo usando uma das suas classes CSS */ +/* Você pode seleciona-lo usando uma das suas classes CSS */ .class1 { } -/* ou ambas as classes! */ +/* Ou ambas as classes! */ .class1.class2 { } -/* ou o seu nome */ +/* Ou o seu nome */ div { } -/* ou o seu id */ +/* Ou o seu id */ #anID { } -/* ou utilizando o fator de que tem um atributo!*/ -[attr] { font-size:smaller; } +/* Ou através de um dos seus atributos! */ +[attr] { font-size: smaller; } -/* ou que o atributo tem um valor específico */ -[attr='value'] { font-size:smaller; } +/* Ou utilizando um atributo com um valor específico */ +[attr='value'] { font-size: smaller; } -/* começa com um valor (CSS 3) */ +/* Um atributo que começa com um valor (CSS 3) */ [attr^='val'] { font-size:smaller; } -/* ou terminando com um valor (CSS 3) */ -[attr$='ue'] { font-size:smaller; } - +/* Ou termina com um valor (CSS 3) */ +[attr$='ue'] { font-size: smaller; } /* Ou contém um valor em uma lista separada por espaços */ -[otherAttr ~ = 'foo'] {} -[otherAttr ~ = 'bar'] {} +[otherAttr~='foo'] {} +[otherAttr~='bar'] {} /* Ou contém um valor em uma lista separada por hífen, ou seja, "-" (U + 002D) */ -[otherAttr | = 'en'] {font-size: smaller; } +[otherAttr|='pt'] {font-size: smaller; } -/* Você pode concatenar diferentes seletores para criar um seletor mais estreito. Não -   colocar espaços entre eles. */ -classe div.some [attr $ = 'ue'] {} +/* Você pode combinar diferentes seletores para criar um seletor mais específica. Lembre-se + de não colocar espaço entre eles */ +div.some-class[attr$='ue'] {} -/* Você pode selecionar um elemento que é filho de outro elemento */ -div.some-parent> .class-name {} +/* Você pode selecionar um elemento que está diretamento dentro de outro elemento */ +div.some-parent > .class-name {} -/* Ou um descendente de um outro elemento. Os filhos são os descendentes diretos de -   seu elemento pai, apenas um nível abaixo da árvore. Pode ser quaisquer descendentes -   nivelados por baixo da árvore. */ -div.some-parent class-name {} +/* Ou um descendente desse elemento. Os filhos são os descendentes diretos de + um elemento pai, apenas um nível abaixo. Da seguinte forma, você pode seleciona qualquer + elemento que esteja dentro do elemento principal. */ +div.some-parent .class-name {} /* Atenção: o mesmo seletor sem espaço tem um outro significado. -   Você consegue adivinhar o que? */ + Dessa forma você estará selecionando um elemento que contenha as duas classes. */ div.some-parent.class-name {} -/* Você também pode selecionar um elemento com base em seu irmão adjacente */ -.i am just-antes + .Este elemento {} +/* Você também pode selecionar um elemento com base em seu irmão mais próximo */ +.i-am-just-before + .this-element {} /* Ou qualquer irmão que o precede */ -.i am-qualquer-elemento antes ~ .Este elemento {} +.i-am-any-element-before ~ .this-element { } -/* Existem alguns seletores chamados pseudo classes que podem ser usados para selecionar um -   elemento quando ele está em um determinado estado */ +/* Existem alguns seletores, chamados pseudo classes, que podem ser usados para selecionar um + elemento quando ele está em um determinado estado */ /* Por exemplo, quando o cursor passa sobre um elemento */ seletor:hover {} @@ -112,10 +114,10 @@ seletor:link {} /* Ou um elemento em foco */ seletor:focus {} -/* Qualquer elemento que é o primeiro filho de seu pai */ +/* Qualquer elemento que é o primeiro filho */ seletor:first-child {} -/* Qualquer elemento que é o último filho de seu pai */ +/* Qualquer elemento que é o último filho */ seletor:last-child {} /* Assim como pseudo classes, pseudo elementos permitem que você estilize certas partes de um documento */ @@ -126,88 +128,91 @@ seletor::before {} /* Corresponde a um último filho virtual do elemento selecionado */ seletor::after {} -/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar todos -   os elementos */ -* {} /* */ Todos os elementos -.parent * {} /* */ todos os descendentes -.parent> * {} /* */ todos os filhos +/* Nos locais apropriados, um asterisco pode ser utilizado como um curinga para selecionar + todos os elementos */ + +* {} /* Todos os elementos */ +.parent * {} /* todos os descendentes */ +.parent > * {} /* todos os filhos */ /* #################### -   ## PROPRIEDADES -   #################### */ + ## PROPRIEDADES + #################### */ seletor { + /* Unidades de comprimento pode ser absoluta ou relativa. */ -    /* Unidades de comprimento pode ser absoluta ou relativa. */ + /* Unidades relativas */ + width: 50%; /* Percentagem de largura do elemento pai */ + font-size: 2em; /* Múltiplos de font-size original de elemento */ + font-size: 2rem; /* Ou do elemento raiz font-size */ + font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */ + font-size: 2vh; /* Ou a sua altura */ + font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */ + font-size: 2vmax; /* Ou superior */ -    /* Unidades relativas */ -    width: 50%; /* Percentagem de largura do elemento pai */ -    font-size: 2em; /* Múltiplos de font-size original de elemento */ -    font-size: 2rem; /* Ou do elemento raiz font-size */ -    font-size: 2vw; /* Múltiplos de 1% da largura da janela de exibição (CSS 3) */ -    font-size: 2vh; /* Ou a sua altura */ -    font-size: 2vmin; /* Qualquer um de VH ou um VW é menor */ -    font-size: 2vmax; /* Ou superior */ + /* Unidades absolutas */ + width: 200px; /* Píxeis */ + font-size: 20pt; /* Pontos */ + width: 5cm; /* Centímetros */ + min-width: 50mm; /* Milímetros */ + max-width: 5 polegadas; /* Polegadas */ -    /* Unidades absolutas */ -    width: 200px; /* píxeis */ -    font-size: 20pt; /* Pontos */ -    width: 5cm; /* Centímetros */ -    min-width: 50mm; /* Milímetros */ -    max-width: 5 polegadas; /* Polegadas */ + /* Cores */ + color: #F6E; /* Formato hexadecimal curto */ + color: #FF66EE; /* Formato hexadecimal longo */ + color: tomato; /* Uma cor nomeada */ + color: rgb(255, 255, 255); /* Como valores rgb */ + color: RGB(10%, 20%, 50%); /* Como porcentagens rgb */ + color: rgba(255, 0, 0, 0,3); /* Como valores RGBA (CSS 3) NOTA: 0 . Isto é o -     método recomendado. Consulte http://stackoverflow.com/questions/8284365 --> - +```html + + - + - +
    ``` ## Precedência ou Cascata -Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades em que mais de uma vez. Nestes casos, uma das regras tem precedência sobre as outras. Geralmente, uma regra em um seletor mais específico têm precedência sobre um menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior. +Um elemento pode ser alvo de vários seletores e pode ter um conjunto de propriedades que +são adicionados mais de uma vez. Nestes casos, uma das regras tem precedência sobre as +outras. Geralmente, uma regra em um seletor mais específico têm precedência sobre um +menos específico, e uma regra que ocorre mais tarde na folha de estilo substitui uma anterior. -Este processo é chamado de cascata, portanto, as Fichas de nome de estilo em cascata. +Este processo é chamado de cascata, daí vem o nome: Cascading Style Sheets (Folhas de Estilo em Cascata). Dado o seguinte CSS: ```css -/* UMA */ +/* A */ p.class1[attr="value"] /* B */ @@ -225,20 +230,22 @@ p { property: value !important; } e a seguinte marcação: -```xml +```html

    ``` -A precedência de estilo é a seguinte. Lembre-se, a precedência é para cada **propriedade**, não para todo o bloco. +A precedência de estilo é a seguinte: Lembre-se, a precedência se aplica a +cada **propriedade**, não ao bloco como um todo. -* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendável que você evitar seu uso. -* `F` é a próxima, porque é um estilo interno. -* `A` é a próxima, porque é mais" específico "do que qualquer outra coisa. Tem 3 especificadores: O nome do elemento `p`, o seu `class1` classe, um atributo `attr='value'`. -* `C` está próximo, mesmo que ele tenha a mesma especificidade que `B`. Isso é porque ele aparece depois de `B`. -* `B` é o próximo. -* `D` é a última. +* `E` tem a precedência mais alta por causa de uma palavra-chave`!important`. É recomendado evitar seu uso. +* `F` é o seguinte, porque é um estilo interno. +* `A` é o seguinte, porque é "mais específico" do que os outros. Tem 3 especificadores: O nome do elemento `p`, a sua classe `class1` e um atributo `attr="value"`. +* `C` é o seguinte, mesmo que ele tenha a mesma especificidade que `B`. Isso acontece porque ele aparece logo após o `B`. +* `B` é o seguinte. +* `D` é o último. ## Media Queries + Media queries são recursos do CSS3 que permitem especificar quando determinadas regras de CSS devem ser aplicadas; é possível aplicar regras diferentes quando a página é impressa, quando a tela possui determinadas dimensões ou densidade de pixels e quando é lida por um leitor de tela. Media queries não adicionam especificidade ao seletor. ```css @@ -265,7 +272,8 @@ h1 { } } ``` -Media queries podem incluir os seguintes atributos: `width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan`, `grid`. A maioria desses atributos pode ser prefixada com `min-` ou `max-`. + +Media queries podem incluir os seguintes atributos: `width`, `height`, `device-width`, `device-height`, `orientation`, `aspect-ratio`, `device-aspect-ratio`, `color`, `color-index`, `monochrome`, `resolution`, `scan` e `grid`. A maioria desses atributos pode ser prefixada com `min-` ou `max-`. O atributo `resolution` não é suportado em dispositivos mais antigos. Em vez disso, use `device-pixel-ratio`. @@ -279,20 +287,22 @@ Muitos smartphones e tablets tentarão renderizar a página como se estivesse nu ## Compatibilidade -A maior parte dos recursos do CSS 2 (e muitos em CSS 3) estão disponíveis em todos os navegadores e dispositivos. Mas é sempre boa prática verificar antes de usar um novo recurso. +A maioria dos recursos do CSS 2 (e muitos do CSS 3) está disponível em todos os navegadores +e dispositivos. -## Recursos +## Recursos Adicionais * Para executar uma verificação de compatibilidade rápida, [CanIUse](http://caniuse.com). * CSS Playground [Dabblet](http://dabblet.com/). -* [Documentação CSS Mozilla Developer Rede](https://developer.mozilla.org/en-US/docs/Web/CSS) -* [Codrops 'Referência CSS](http://tympanus.net/codrops/css_reference/) +* [Documentação CSS Mozilla Developer](https://developer.mozilla.org/en-US/docs/Web/CSS) +* [Codrops Referência CSS](http://tympanus.net/codrops/css_reference/) +* [DevTips CSS Basics](https://www.youtube.com/playlist?list=PLqGj3iMvMa4IOmy04kDxh_hqODMqoeeCy) (Tutorials) ## Leitura adicional * [Entendendo Estilo Precedência em CSS: Especificidade, Herança, e o Cascade](http://www.vanseodesign.com/css/css-specificity-inheritance-cascaade/) * [Selecionando elementos usando atributos](https://css-tricks.com/almanac/selectors/a/attribute/) * [QuirksMode CSS](http://www.quirksmode.org/css/) -* [Z-Index - O empilhamento context](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) -* [SASS](http://sass-lang.com/) e [Less](http://lesscss.org/) para CSS pré-processamento +* [Z-Index - O contexto de empilhamento](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index/The_stacking_context) +* [SASS](http://sass-lang.com/) e [Less](http://lesscss.org/) para pré-processamento do CSS * [CSS-Tricks](https://css-tricks.com) From fb5b9818e18932d928eb43ae2e55ea77cd03bb3a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Wed, 28 Feb 2024 05:50:17 -0300 Subject: [PATCH 035/392] fix(de-de/pug): Fix file extension in section include (#4851) Adjusting file paths in the German language file to match the updated Pug file names for consistency and clarity of the project structure. - Updated references from "index.png" to "index.pug" - Updated references from "includes/nav.png" to "includes/nav.pug" --- de-de/pug-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown index c86494ce..10172d6b 100644 --- a/de-de/pug-de.html.markdown +++ b/de-de/pug-de.html.markdown @@ -162,13 +162,13 @@ case bestellungsStatus //-

    Deine Bestellung steht noch aus

    //- --INCLUDE-- -//- File path -> "includes/nav.png" +//- File path -> "includes/nav.pug" h1 Firmenname nav a(href="index.html") Home a(href="about.html") Über uns -//- Dateipfad -> "index.png" +//- Dateipfad -> "index.pug" html body include includes/nav.pug From 33284311ef1ba37d92c3b28afe81ff55f1441651 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Wed, 6 Mar 2024 05:03:30 -0300 Subject: [PATCH 036/392] [httpie/en] Add guide for using HTTPie (#4853) - Add a comprehensive guide on using HTTPie as a powerful command-line HTTP client. The guide covers basic usage, URL shortcuts, optional GET and POST methods, querystring parameters, sending data in JSON, form data, and files, managing headers and authentication, as well as response handling options. - The guide aims to provide developers, testers, and system administrators with a simple and intuitive reference for interacting with HTTP servers using HTTPie. --- httpie.html.markdown | 120 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 httpie.html.markdown diff --git a/httpie.html.markdown b/httpie.html.markdown new file mode 100644 index 00000000..390e7b35 --- /dev/null +++ b/httpie.html.markdown @@ -0,0 +1,120 @@ +--- +category: tool +tool: httpie +contributors: + - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"] +filename: learn-httpie.sh +--- + +HTTPie is a powerful command-line HTTP client designed for easy interaction +with HTTP servers. It provides a simple and intuitive interface, making it an +excellent tool for developers, testers, and system administrators. + +## Basic Usage + +HTTPie follows a simple syntax: http [flags] [METHOD] URL [items]. + +```bash +http GET https://api.example.com/posts +``` + +You can print the request without sending it by using the `--offline` flag. + +```bash +http --offline https://api.example.com/posts +``` + +### URL shortcuts for `localhost` + +HTTPie supports a curl-like shorthand for localhost. For instance, ":3000" +expands to "http://localhost:3000". If the port is omitted, it assumes port 80. + +```bash +http :/users # http://localhost/users +http :5000/rss # http://localhost:5000/rss +``` + +### Optional GET and POST + +If you don't specify the METHOD, the HTTPie will use: + +- GET for requests without body +- POST for requests with body + +```bash +http https://api.example.com/tags # GET tags +http https://api.example.com/tags title="Tutorial" slug="tutorial" # POST a new tag +``` + +## Querystring Parameters + + +If you're manually adding query string parameters in the terminal, try the +`param==value` syntax. It avoids shell escaping for & separators and +automatically URL-escapes special characters in parameter names and values. +This differs from parameters in the full URL, which HTTPie doesn't modify. + +```bash +http https://api.example.com/search q==httpie per_page==20 +``` + +## Sending Data + +You can send data in various formats such as JSON, form data, or files. + +### JSON Data + +```bash +http POST https://api.example.com/posts title="Hello" body="World" +``` + +### Form Data + +```bash +http -f POST https://api.example.com/submit name=John email=john@example.com +``` + +### Files + +```bash +http --form POST https://api.example.com/upload file@/path/to/file.txt +``` + +## Headers and Authentication + +HTTPie allows you to set headers and handle authentication easily. + +### Headers + +```bash +http GET https://api.example.com/posts Authorization:"Bearer Token" User-Agent:"HTTPie" +``` + +### Basic Authentication + +```bash +http -a username:password GET https://api.example.com/protected +``` + +### Bearer Authentication + +```bash +https -A bearer -a token https://api.example.com/admin +``` + +## Response Handling + +HTTPie provides various options for handling responses. + +```bash +http GET https://api.example.com/data Accept:application/json # Pretty Print JSON + +http GET https://api.example.com/image --output image.png # Save Response to File + +http --follow GET https://example.com # Follow Redirects +``` + +## Further Reading + +- [Official Documentation](https://httpie.io/docs/cli). +- [Github](https://github.com/httpie). From 057e1d1b10b7e36e01a382c88fa1e22711e10b73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Wed, 6 Mar 2024 05:08:16 -0300 Subject: [PATCH 037/392] [jinja/en] Create page about Jinja (#4852) * feat(jinja): Add Jinja template introduction and examples - Added a detailed introduction to Jinja templating engine for Python - Included examples for variables, template inheritance, including content and loops - Provided explanations and syntax for delimiters, template inheritance, variables, loops, conditionals, and including content - Demonstrated how to use Jinja for web development, such as creating HTML templates and including dynamic content displayed within a browser * [jinja/en] Create Jinja documentation - Improved the readability and consistency of the content in the file by adjusting the line breaks and formatting of the text. - Corrected the whitespace and formatting issues in the code snippets. - Unified the style of the text by keeping similar instructions on the same text alignment level for easier comprehension. - Ensured proper spacing and indentation in the 'Template Inheritance' section for a better display and understanding of the concept. - Updated the 'Including Content' section to fix a typo in the include tag. - Streamlined the 'Variables passed to the main template' section by refining the explanation and enhancing clarity. - Consolidated information in the 'Conditionals, Macros, and Official Documentation' sections to provide a clearer and consistent documentation style. - Incorporated a link to the official Jinja documentation for further reference. * chore: Organize Jinja's template inheritance section --- jinja.html.markdown | 270 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 jinja.html.markdown diff --git a/jinja.html.markdown b/jinja.html.markdown new file mode 100644 index 00000000..7e5b8e96 --- /dev/null +++ b/jinja.html.markdown @@ -0,0 +1,270 @@ +--- +language: Jinja +contributors: + - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"] +filename: learn-jinja.j2 +--- + +## Getting Started with Jinja + +Jinja is a fast, expressive, and extensible templating engine for Python +applications. + +Jinja includes a lot of functionalities, such as: +- Template inheritance and inclusion; +- Defining and importing macros within templates; +- Security mechanisms to prevent XSS attacks; +- A sandboxed environment that can safely render untrusted templates; +- Extensible filters, tests, functions, and even syntax. + +A Jinja template is simply a text file. Jinja doesn't require a specific +extension, but it's common to use `.j2` or `.jinja` to make it easier for +some IDEs. + +There are a few kinds of delimiters. The default Jinja delimiters are configured +as follows: + +- `{% ... %}` for Statements +- `{{ ... }}` for Expressions to print to the template output +- `{# ... #}` for Comments not included in the template output + +```jinja +{# This is an example of a comment. #} + +{# + You can use this syntax + to write multiline comments + as well. +#} +``` + + +## VARIABLES + +```jinja +{# You have the option to access variables from the context passed to the template #} + +{{ foo }} + +{# + Additionally, you can use a dot (.) to access attributes of a variable or + use Python syntax, using [] +#} + +{{ foo.bar }} +{{ foo['bar'] }} + +{# Within the template, you can define variables as well #} + +{% set name = "Magdiel" %} +{{ name }} +``` + +## Loops + +```html +

    Members

    +
      +{% for user in users %} +
    • {{ user.username }}
    • +{% endfor %} +
    + + +
    +{% for key, value in my_dict.items() %} +

    {{ key }}

    -

    {{ value }}

    +{% endfor %} +
    + + +
    +``` + +## Conditionals + +The if statement in Jinja is similar to the if statement in Python. It is +commonly used to check if a variable is defined, not empty, and not false in +its most basic form. + +```html +{% if users %} +
      +{% for user in users %} +
    • {{ user.username }}
    • +{% endfor %} +
    +{% endif %} + + +{# For multiple branches, elif and else can be used like in Python. #} + + +{% if message.status == "error" %} +

    {{ message.content }}

    +{% elif message.status == "success" %} +

    {{ message.content }}

    +{% else %} +

    {{ message.content }}

    +{% endif %} +``` + +## Template Inheritance + +One of the most powerful features of Jinja is template inheritance. You can +create a base layout with predefined blocks that you can extend in another file +and override with your own content. + +```html +{# file: base.html.j2 #} + + + + + {% block head %} + + + {% block title %}{% endblock title %} - Learning Jinja + {% endblock head %} + + +
    + {% block content %}{% endblock %} + {# the endblock tag doesn't need the name of the block #} +
    + + + + + +{# file: child.html.j2 #} + +{% extends "base.html.j2" %} + +{% block head %} + {{ super() }} + +{% endblock %} + +{% block title %}Home{% endblock %} + +{% block content %} +

    Index

    +

    Welcome to my home homepage.

    +{% endblock %} + + + +{# RESULT #} + + + + + + + Home - Learning Jinja + + + +
    +

    Index

    +

    Welcome to my home homepage.

    +
    + + + +``` + +### Including Content + +You can include content from another template on your current template using +the `{% include "template/path" %}` tag. + +```html + +{# file: footer.html.j2 #} + +
    +

    © 2024 - John Doe

    +
    + + + +{# file: index.html.j2 #} +... + +
    +

    Hi! I'm John Doe!

    +
    + {% include "footer.html.j2" %} + +... + + + +{# RESULT #} + +... + +
    +

    Hi! I'm John Doe!

    +
    +
    +

    © 2024 - John Doe

    +
    + +... +``` + +Variables passed to the main template can also be used in the include, as the +included template has access to the context of the main template. + +```html +{# file: greetings.html.j2 #} + +

    I'm the {{ name }} and i like to {{ hobby }}.

    + + + +{# file: index.html.j2 #} + +{% set name = "Captain Nemo" %} +{% set hobby = "navigate through the depths of the ocean" %} + +
    + {% include "greetings.html.j2" %} +
    + + + +{# RESULT #} + +
    +

    I'm the Captain Nemo and i like to navigate through the depths of the ocean.

    +
    +``` + +## Macros + +Macros are basically like functions in another languages. You can define macros with or without arguments and reuse them in various parts of your template. + +```html +{% macro input(value="", type="text", placeholder="") -%} + +{%- endmacro %} + +

    {{ input(placeholder="Your username") }}

    +

    {{ input(type="password") }}

    +``` + +## Official Documentation + +To learn more, access the [official documentation](https://jinja.palletsprojects.com/en/). From c2c7195779196280f914c2b20b2ef4a811924385 Mon Sep 17 00:00:00 2001 From: CatfishWen Date: Sun, 10 Mar 2024 19:41:06 +0800 Subject: [PATCH 038/392] [csharp/zh-cn] update translation (#4856) --- zh-cn/csharp-cn.html.markdown | 828 ++++++++++++++++++++++++++++------ 1 file changed, 687 insertions(+), 141 deletions(-) diff --git a/zh-cn/csharp-cn.html.markdown b/zh-cn/csharp-cn.html.markdown index 0bad34ce..b6cc70c0 100644 --- a/zh-cn/csharp-cn.html.markdown +++ b/zh-cn/csharp-cn.html.markdown @@ -5,45 +5,64 @@ contributors: - ["Max Yankov", "https://github.com/golergka"] - ["Melvyn Laïly", "http://x2a.yt"] - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] + - ["Wouter Van Schandevijl", "http://github.com/laoujin"] + - ["Jo Pearce", "http://github.com/jdpearce"] + - ["Chris Zimmerman", "https://github.com/chriszimmerman"] + - ["Shawn McGuire", "https://github.com/bigbash"] translators: - ["Jakukyo Friel", "http://weakish.github.io"] + - ["CatfishWen", "http://catfishwen.github.io"] filename: LearnCSharp-cn.cs lang: zh-cn --- +C#是一种优雅且类型安全的面向对象的语言,使开发人员能够构建运行在跨平台的.NET框架上,安全且健壮的应用程序。 -C#是一个优雅的、类型安全的面向对象语言。使用C#,开发者可以在.NET框架下构建安全、健壮的应用程序。 - -[更多关于C#的介绍](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) +[更多关于C#的介绍](https://learn.microsoft.com/zh-cn/dotnet/csharp/tour-of-csharp/) ```c# // 单行注释以 // 开始 /* 多行注释是这样的 */ -/// -/// XML文档注释 -/// -// 声明应用用到的命名空间 +/// +/// 这是 XML文档注释 +/// 可用于生成外部文档或在 IDE 中提供上下文帮助 +/// +/// 这是 firstParam 参数的文档 +/// 这是函数返回值的信息 +public void MethodOrClassOrOtherWithParsableHelp(string firstParam) { } + +// 声明这段源码使用到的命名空间 +// 下面的命名空间都是标准 .NET Framework 类库的一部分 using System; using System.Collections.Generic; -using System.Data.Entity; using System.Dynamic; using System.Linq; -using System.Linq.Expressions; using System.Net; using System.Threading.Tasks; using System.IO; -// 定义作用域,将代码组织成包 +// 但是这个并不是标准类库: +using System.Data.Entity; +// 为了在下方使用它,你需要添加一个 dll 引用 +// 你可以使用 NuGet 包管理器进行安装 +// `Install-Package EntityFramework` + +// 命名空间 Namespaces 可用于将一定的代码组织为 “包” 或者 “模块” +// 你可以在其他文件中这样引用:using Learning.CSharp; + +// 在 C# 10 以后,你也可以这样定义命名空间。这被称为 file-scoped namespaces(文件范围的命名空间). +// namespace Learning.CSharp; + namespace Learning { // 每个 .cs 文件至少需要包含一个和文件名相同的类 - // 你可以不这么干,但是这样不好。 + // 你可以不这么干,但是这样并不推荐。 public class LearnCSharp { - // 基本语法 - 如果你以前用过 Java 或 C++ 的话,可以直接跳到后文「有趣的特性」 + // 基本语法 - 如果你以前用过 Java 或 C++ 的话,可以直接跳到后文「有趣的特性」 public static void Syntax() { // 使用 Console.WriteLine 打印信息 @@ -53,7 +72,7 @@ namespace Learning " Double: " + 3.14 + " Boolean: " + true); - // 使用 Console.Write 打印,不带换行符号 + // 使用 Console.Write 打印将不会换行 Console.Write("Hello "); Console.Write("World"); @@ -113,7 +132,7 @@ namespace Learning char charFromString = fooString[1]; // => 'e' // 字符串不可修改: fooString[1] = 'X' 是行不通的; - // 根据当前的locale设定比较字符串,大小写不敏感 + // 根据当前的区域格式设置比较字符串,大小写不敏感 string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); // 基于sprintf的字符串格式化 @@ -123,12 +142,13 @@ namespace Learning DateTime fooDate = DateTime.Now; Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - // 使用 @ 符号可以创建跨行的字符串。使用 "" 来表示 " + // 逐字字符串 + // 使用 @ 符号可以创建跨行的字符串。使用 "" 来表示 " string bazString = @"Here's some stuff on a new line! ""Wow!"", the masses cried"; - // 使用const或read-only定义常量 - // 常量在编译期演算 + // 使用 const 或 read-only 定义常量 + // 常量在编译阶段演算 const int HOURS_I_WORK_PER_WEEK = 9001; /////////////////////////////////////////////////// @@ -136,7 +156,7 @@ on a new line! ""Wow!"", the masses cried"; /////////////////////////////////////////////////// // 数组 - 从0开始计数 - // 声明数组时需要确定数组长度 + // 声明数组时需要指定数组长度 // 声明数组的格式如下: // [] = new []; int[] intArray = new int[10]; @@ -155,8 +175,8 @@ on a new line! ""Wow!"", the masses cried"; // List = new List(); List intList = new List(); List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; // i - // <>用于泛型 - 参考下文 + List z = new List { 9000, 1000, 1337 }; // 初始化 + // <> 用于泛型 - 参考下文 // 列表无默认值 // 访问列表元素时必须首先添加元素 @@ -164,18 +184,18 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine("intList @ 0: " + intList[0]); // 其他数据结构: - // 堆栈/队列 - // 字典 (哈希表的实现) - // 哈希集合 - // 只读集合 - // 元组 (.Net 4+) + // Stack 堆栈 / Queue 队列 + // Dictionary 字典 (哈希表的实现) + // HashSet 哈希集合 + // Read-only Collections 只读集合 + // Tuple 元组 (.Net 4+) /////////////////////////////////////// // 操作符 /////////////////////////////////////// Console.WriteLine("\n->Operators"); - int i1 = 1, i2 = 2; // 多重声明的简写形式 + int i1 = 1, i2 = 2; // 声明多个变量的简写形式 // 算术直截了当 Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 @@ -214,7 +234,7 @@ on a new line! ""Wow!"", the masses cried"; /////////////////////////////////////// Console.WriteLine("\n->Control Structures"); - // 类似C的if语句 + // 类似 C 的 if 语句 int j = 10; if (j == 10) { @@ -239,7 +259,7 @@ on a new line! ""Wow!"", the masses cried"; int fooWhile = 0; while (fooWhile < 100) { - //迭代 100 次, fooWhile 0->99 + // 迭代 100 次, fooWhile 0->99 fooWhile++; } @@ -247,14 +267,21 @@ on a new line! ""Wow!"", the masses cried"; int fooDoWhile = 0; do { - //迭代 100 次, fooDoWhile 0->99 + // 迭代 100 次, fooDoWhile 0->99 + if (false) + continue; // 跳过本次迭代 + fooDoWhile++; + + if (fooDoWhile == 50) + break; // 结束整个循环 + } while (fooDoWhile < 100); - //for 循环结构 => for(<初始条件>; <条件>; <步>) + // for 循环结构 => for(<初始条件>; <条件>; <步>) for (int fooFor = 0; fooFor < 10; fooFor++) { - //迭代10次, fooFor 0->9 + // 迭代10次, fooFor 0->9 } // foreach循环 @@ -269,7 +296,7 @@ on a new line! ""Wow!"", the masses cried"; } // Switch 语句 - // switch 适用于 byte、short、char和int 数据类型。 + // switch 适用于 byte、short、char 和 int 数据类型。 // 同样适用于可枚举的类型 // 包括字符串类, 以及一些封装了原始值的类: // Character、Byte、Short和Integer。 @@ -307,46 +334,63 @@ on a new line! ""Wow!"", the masses cried"; // 转换字符串为整数 // 转换失败会抛出异常 - int.Parse("123");//返回整数类型的"123" + int.Parse("123"); // 返回整数类型的"123" - // TryParse会尝试转换类型,失败时会返回缺省类型 + // TryParse 会尝试转换类型,失败时会返回缺省类型 // 例如 0 int tryInt; if (int.TryParse("123", out tryInt)) // Funciton is boolean Console.WriteLine(tryInt); // 123 // 转换整数为字符串 - // Convert类提供了一系列便利转换的方法 + // Convert 类提供了一系列方便转换类型的方法 + + // 比如 字符串 与 int 之间 + + // 最佳方法 + bool result = int.TryParse(string, out var integer) + int.Parse(string); + + // 不推荐 Convert.ToString(123); - // or + + // Int 到字符串 tryInt.ToString(); + + // 转换 + // 显式转换 decimal 类型的 15 为 int 类型 + // 然后隐式转换为 long 类型 + long x = (int) 15M; } /////////////////////////////////////// - // 类 + // 类 - 请参阅文件末尾的定义 /////////////////////////////////////// public static void Classes() { // 参看文件尾部的对象声明 - // 使用new初始化对象 + // 使用 new 初始化对象 Bicycle trek = new Bicycle(); // 调用对象的方法 - trek.SpeedUp(3); // 你应该一直使用setter和getter方法 + trek.SpeedUp(3); // 你应该一直使用 setter 和 getter 方法 trek.Cadence = 100; // 查看对象的信息. Console.WriteLine("trek info: " + trek.Info()); - // 实例化一个新的Penny Farthing + // 实例化一个新的 Penny Farthing 对象 PennyFarthing funbike = new PennyFarthing(1, 10); Console.WriteLine("funbike info: " + funbike.Info()); Console.Read(); } // 结束main方法 - // 终端程序 终端程序必须有一个main方法作为入口 + // record 在 C# 9 及以后可用, 这基本上是类的语法糖. record 对象是不可变的 immutable*. + public record ARecord(string Csharp); + + // 终端程序入口 终端程序必须有一个 main 方法作为入口 public static void Main(string[] args) { OtherInterestingFeatures(); @@ -359,11 +403,11 @@ on a new line! ""Wow!"", the masses cried"; // 默认方法签名 public // 可见性 - static // 允许直接调用类,无需先创建实例 - int, //返回值 + static // 允许从类直接调用,无需先创建实例 + int // 返回值类型 MethodSignatures( - int maxCount, // 第一个变量,类型为整型 - int count = 0, // 如果没有传入值,则缺省值为0 + int maxCount, // 第一个参数,类型为整型 + int count = 0, // 如果没有传入值,则缺省值为 0 int another = 3, params string[] otherParams // 捕获其他参数 ) @@ -371,17 +415,22 @@ on a new line! ""Wow!"", the masses cried"; return -1; } - // 方法可以重名,只要签名不一样 - public static void MethodSignature(string maxCount) + // 方法可以重名,只要方法签名不一样 + // 一个只有返回值类型不同的方法 + public static void MethodSignatures( + ref int maxCount, // 通过引用传递 + out int count) { + // 通过 'count' 参数传入的值将在该方法外保留值 15 + count = 15; // 必须在离开方法之前为 out 参数赋值 } - //泛型 - // TKey和TValue类由用用户调用函数时指定。 - // 以下函数模拟了Python的SetDefault + // 泛型 + // TKey 和 TValue 由用户调用方法时指定 + // 以下函数模拟了 Python 的 SetDefault public static TValue SetDefault( - IDictionary dictionary, - TKey key, + IDictionary dictionary, + TKey key, TValue defaultItem) { TValue result; @@ -393,55 +442,125 @@ on a new line! ""Wow!"", the masses cried"; // 你可以限定传入值的范围 public static void IterateAndPrint(T toPrint) where T: IEnumerable { - // 我们可以进行迭代,因为T是可枚举的 + // 我们可以进行迭代,因为 T 是可枚举的 foreach (var item in toPrint) - // ittm为整数 + // item 为整数 Console.WriteLine(item.ToString()); } + // YIELD + // 使用 "yield" 关键字表明它出现的方法是一个迭代器 Iterator + // (这意味着你可以在 foreach 循环中使用它) + public static IEnumerable YieldCounter(int limit = 10) + { + for (var i = 0; i < limit; i++) + yield return i; + } + + // 你可以这样调用它 + public static void PrintYieldCounterToConsole() + { + foreach (var counter in YieldCounter()) + Console.WriteLine(counter); + } + + // 你可以在一个方法中使用多个 "yield return" + public static IEnumerable ManyYieldCounter() + { + yield return 0; + yield return 1; + yield return 2; + yield return 3; + } + + // 你也可以使用 "yield break" 停止该迭代器 + // 此方法只会返回从 0 到 limit 的一半值。 + public static IEnumerable YieldCounterWithBreak(int limit = 10) + { + for (var i = 0; i < limit; i++) + { + if (i > limit / 2) yield break; + yield return i; + } + } + public static void OtherInterestingFeatures() { - // 可选参数 + // 可选参数 MethodSignatures(3, 1, 3, "Some", "Extra", "Strings"); MethodSignatures(3, another: 3); // 显式指定参数,忽略可选参数 + // 使用 ref 和 out 参数 + int maxCount = 0, count; // ref 参数必须有值 + MethodSignatures(ref maxCount, out count); + // 扩展方法 int i = 3; - i.Print(); // 参见下面的定义 + i.Print(); // 参见下面的定义 - // 可为null的类型 对数据库交互、返回值很有用 + // 可为 null 的类型 对数据库交互、返回值很有用 // 任何值类型 (i.e. 不为类) 添加后缀 ? 后会变为可为null的值 // <类型>? <变量名> = <值> int? nullable = null; // Nullable 的简写形式 Console.WriteLine("Nullable variable: " + nullable); bool hasValue = nullable.HasValue; // 不为null时返回真 + // ?? 是用于指定默认值的语法糖 // 以防变量为null的情况 int notNullable = nullable ?? 0; // 0 + // ?. 是另一个可空类型的操作符 - 简写 null 检查 + nullable?.Print(); // 当可空类型值不为 null 的时候调用 Print() 拓展方法 + // 变量类型推断 - 你可以让编译器推断变量类型: var magic = "编译器确定magic是一个字符串,所以仍然是类型安全的"; - // magic = 9; // 不工作,因为magic是字符串,而不是整数。 + // magic = 9; // 不工作,因为magic是字符串,而不是整数。 // 泛型 // - var phonebook = new Dictionary() { + var phonebook = new Dictionary() { {"Sarah", "212 555 5555"} // 在电话簿中加入新条目 }; - // 调用上面定义为泛型的SETDEFAULT - Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // 没有电话 - // 你不用指定TKey、TValue,因为它们会被隐式地推导出来 + // 调用上面定义为泛型的 SETDEFAULT + Console.WriteLine(SetDefault(phonebook, "Shaun", "No Phone")); // No Phone + // 你不用指定 TKey、TValue 的类型 + // 因为它们会被隐式地推导出来 Console.WriteLine(SetDefault(phonebook, "Sarah", "No Phone")); // 212 555 5555 // lambda表达式 - 允许你用一行代码搞定函数 Func square = (x) => x * x; // 最后一项为返回值 Console.WriteLine(square(3)); // 9 - // 可抛弃的资源管理 - 让你很容易地处理未管理的资源 - // 大多数访问未管理资源 (文件操作符、设备上下文, etc.)的对象 - // 都实现了IDisposable接口。 - // using语句会为你清理IDisposable对象。 + // 错误处理 - 应对不确定的世界 + try + { + var funBike = PennyFarthing.CreateWithGears(6); + + // 将不再执行,因为 CreateWithGears 抛出异常 + string some = ""; + if (true) some = null; + some.ToLower(); // 抛出 NullReferenceException + } + catch (NotSupportedException) + { + Console.WriteLine("Not so much fun now!"); + } + catch (Exception ex) // 捕获所有其他异常 + { + throw new ApplicationException("It hit the fan", ex); + // throw; // 重新抛出异常并保留调用堆栈 + } + // catch { } // 捕获所有没有捕获的异常 + finally + { + // 在 try 或 catch 之后执行 + } + + // 可抛弃的资源管理 - 让你很容易地处理未托管的资源 + // 大多数访问未托管资源 (文件句柄、设备上下文, etc.) 的对象 + // 都实现了 IDisposable 接口。 + // using语句会为你清理 IDisposable 对象 using (StreamWriter writer = new StreamWriter("log.txt")) { writer.WriteLine("这里没有什么可疑的东西"); @@ -450,29 +569,23 @@ on a new line! ""Wow!"", the masses cried"; } // 并行框架 - // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx - var websites = new string[] { - "http://www.google.com", "http://www.reddit.com", - "http://www.shaunmccarthy.com" - }; - var responses = new Dictionary(); - - // 为每个请求新开一个线程 - // 在运行下一步前合并结果 - Parallel.ForEach(websites, - new ParallelOptions() {MaxDegreeOfParallelism = 3}, // max of 3 threads - website => - { - // Do something that takes a long time on the file - using (var r = WebRequest.Create(new Uri(website)).GetResponse()) - { - responses[website] = r.ContentType; - } - }); + // https://learn.microsoft.com/zh-cn/dotnet/standard/parallel-programming/data-parallelism-task-parallel-library - // 直到所有的请求完成后才会运行下面的代码 - foreach (var key in responses.Keys) - Console.WriteLine("{0}:{1}", key, responses[key]); + var words = new List {"dog", "cat", "horse", "pony"}; + + Parallel.ForEach(words, + new ParallelOptions() { MaxDegreeOfParallelism = 4 }, + word => + { + Console.WriteLine(word); + } + ); + + // 运行它会产生不同的输出 + // 因为每个线程在不同的时间完成 + // 一些可能的输出是: + // cat dog horse pony + // dog horse pony cat // 动态对象(配合其他语言使用很方便) dynamic student = new ExpandoObject(); @@ -486,10 +599,10 @@ on a new line! ""Wow!"", the masses cried"; // IQUERYABLE - 几乎所有的集合都实现了它, // 带给你 Map / Filter / Reduce 风格的方法 var bikes = new List(); - bikes.Sort(); // Sorts the array + bikes.Sort(); // 排序 array bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); // 根据车轮数排序 var result = bikes - .Where(b => b.Wheels > 3) // 筛选 - 可以连锁使用 (返回IQueryable) + .Where(b => b.Wheels > 3) // 筛选 - 可以连锁使用 (返回 IQueryable) .Where(b => b.IsBroken && b.HasTassles) .Select(b => b.ToString()); // Map - 这里我们使用了select,所以结果是IQueryable @@ -502,19 +615,19 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(bikeSummary.Name); // ASPARALLEL - // 邪恶的特性 —— 组合了linq和并行操作 + // 这就是事情开始棘手的地方 —— 组合了 linq 和并行操作 var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); // 以上代码会并发地运行。会自动新开线程,分别计算结果。 // 适用于多核、大数据量的场景。 - // LINQ - 将IQueryable映射到存储,延缓执行 + // LINQ - 映射一组 IQueryable 对象,并延迟执行 // 例如 LinqToSql 映射数据库, LinqToXml 映射XML文档 var db = new BikeRespository(); - // 执行被延迟了,这对于查询数据库来说很好 + // 执行被延迟了,这对于查询数据库来说非常好 var filter = db.Bikes.Where(b => b.HasTassles); // 不运行查询 if (42 > 6) // 你可以不断地增加筛选,包括有条件的筛选,例如用于“高级搜索”功能 - filter = filter.Where(b => b.IsBroken); // 不运行查询 + filter = filter.Where(b => b.IsBroken); // 不运行查询 var query = filter .OrderBy(b => b.Wheels) @@ -541,15 +654,64 @@ on a new line! ""Wow!"", the masses cried"; Console.WriteLine(obj.ToString()); } } + + + // 委托 和 事件 + public class DelegateTest + { + public static int count = 0; + public static int Increment() + { + // 增加 count 然后返回它 + return ++count; + } + + // 委托是一个方法的引用. + // 要引用 Increment 方法, + // 首先声明一个具有相同签名的委托, + // i.e. 不带参数并返回 int + public delegate int IncrementDelegate(); + + // 事件也可用于触发委托 + // 使用委托类型创建事件 + public static event IncrementDelegate MyEvent; + + static void Main(string[] args) + { + // 通过实例化委托来引用 Increment 方法 + // 并将方法本身作为参数传递 + IncrementDelegate inc = new IncrementDelegate(Increment); + Console.WriteLine(inc()); // => 1 + + // 委托可以用 + 运算符组合 + IncrementDelegate composedInc = inc; + composedInc += inc; + composedInc += inc; + + // composedInc 将执行 Increment 3 次 + Console.WriteLine(composedInc()); // => 4 + + + // 为事件订阅与委托 + MyEvent += new IncrementDelegate(Increment); + MyEvent += new IncrementDelegate(Increment); + + // 触发事件 + // ie. 运行这个事件所有的委托订阅 + Console.WriteLine(MyEvent()); // => 6 + } + } + + // 声明类的语法: // class <类名>{ - // //数据字段, 构造器, 内部函数. - / // 在Java中函数被称为方法。 + // // 数据字段, 构造器, 内部函数 + // // 在Java中函数被称为方法 // } public class Bicycle { - // 自行车的字段、变量 + // 自行车的字段/变量 public int Cadence // Public: 任何地方都可以访问 { get // get - 定义获取属性的方法 @@ -558,30 +720,35 @@ on a new line! ""Wow!"", the masses cried"; } set // set - 定义设置属性的方法 { - _cadence = value; // value是被传递给setter的值 + _cadence = value; // value 是被传递给 setter 的值 } } private int _cadence; - protected virtual int Gear // 类和子类可以访问 + protected virtual int Gear // Protected: 类和子类可以访问 { get; // 创建一个自动属性,无需成员字段 set; } - internal int Wheels // Internal:在同一程序集内可以访问 + internal int Wheels // Internal: 在同一程序集内可以访问 { get; - private set; // 可以给get/set方法添加修饰符 + private set; // 可以给 get/set 方法添加修饰符 } - int _speed; // 默认为private: 只可以在这个类内访问,你也可以使用`private`关键词 + int _speed; // 类中的任何内容默认为 private: 只可以在这个类内访问 + // 你也可以使用 `private` 关键词显式指定 public string Name { get; set; } - // enum类型包含一组常量 + // 当您想要一个仅返回表达式结果的只读属性时, + // 属性还具有特殊的语法 + public string LongName => Name + " " + _speed + " speed"; + + // enum 枚举是一种值类型,由一组命名常量组成 // 它将名称映射到值(除非特别说明,是一个整型) - // enmu元素的类型可以是byte、sbyte、short、ushort、int、uint、long、ulong。 - // enum不能包含相同的值。 + // enmu 元素的类型可以是 byte、sbyte、short、ushort、int、uint、long、ulong + // enum 不能包含相同的值 public enum BikeBrand { AIST, @@ -589,13 +756,32 @@ on a new line! ""Wow!"", the masses cried"; Electra = 42, //你可以显式地赋值 Gitane // 43 } - // 我们在Bicycle类中定义的这个类型,所以它是一个内嵌类型。 - // 这个类以外的代码应当使用`Bicycle.Brand`来引用。 + // 我们在 Bicycle 类中定义的这个类型,所以它是一个内嵌类型 + // 这个类以外的代码应当使用 `Bicycle.Brand` 来引用 - public BikeBrand Brand; // 声明一个enum类型之后,我们可以声明这个类型的字段 + public BikeBrand Brand; // 声明一个 enum 类型之后,我们可以声明这个类型的字段 - // 静态方法的类型为自身,不属于特定的对象。 - // 你无需引用对象就可以访问他们。 + // 使用 FlagsAttribute 定义枚举,表示有多个值可以被匹配 + // 任何从 Attribute 派生的类都可以用来修饰类型、方法、参数等 + // 位运算符 & 和 | 可用于 和/或 操作 + + [Flags] + public enum BikeAccessories + { + None = 0, + Bell = 1, + MudGuards = 2, // 需要手动设定值! + Racks = 4, + Lights = 8, + FullPackage = Bell | MudGuards | Racks | Lights + } + + // 用法: aBike.Accessories.HasFlag(Bicycle.BikeAccessories.Bell) + // 在 .NET 4 之前: (aBike.Accessories & Bicycle.BikeAccessories.Bell) == Bicycle.BikeAccessories.Bell + public BikeAccessories Accessories { get; set; } + + // 静态方法属于类型自身,不属于特定的对象 + // 你无需通过对象就可以访问他们 // Console.WriteLine("Bicycles created: " + Bicycle.bicyclesCreated); static public int BicyclesCreated = 0; @@ -607,7 +793,7 @@ on a new line! ""Wow!"", the masses cried"; // 下面是一个默认的构造器 public Bicycle() { - this.Gear = 1; // 你可以使用关键词this访问对象的成员 + this.Gear = 1; // 你可以使用关键词 this 访问对象的成员 Cadence = 50; // 不过你并不总是需要它 _speed = 5; Name = "Bontrager"; @@ -618,7 +804,7 @@ on a new line! ""Wow!"", the masses cried"; // 另一个构造器的例子(包含参数) public Bicycle(int startCadence, int startSpeed, int startGear, string name, bool hasCardsInSpokes, BikeBrand brand) - : base() // 首先调用base + : base() // 显式调用基类的无参构造方法 { Gear = startGear; Cadence = startCadence; @@ -637,8 +823,9 @@ on a new line! ""Wow!"", the masses cried"; // 函数语法 // <返回值> <函数名称>(<参数>) - // 类可以为字段实现 getters 和 setters 方法 for their fields - // 或者可以实现属性(C#推荐使用这个) + // 类可以为其字段实现 getters 和 setters 方法 + // 或者可以使用属性封装字段(C#推荐使用这个) + // 方法的参数可以有默认值 // 在有默认值的情况下,调用方法的时候可以省略相应的参数 public void SpeedUp(int increment = 1) @@ -652,8 +839,8 @@ on a new line! ""Wow!"", the masses cried"; } // 属性可以访问和设置值 - // 当只需要访问数据的时候,考虑使用属性。 - // 属性可以定义get和set,或者是同时定义两者 + // 当只需要外部访问数据的时候,考虑使用属性。 + // 属性可以定义 get 和 set,或者是同时定义两者 private bool _hasTassles; // private variable public bool HasTassles // public accessor { @@ -663,7 +850,7 @@ on a new line! ""Wow!"", the masses cried"; // 你可以在一行之内定义自动属性 // 这个语法会自动创建后备字段 - // 你可以给getter或setter设置访问修饰符 + // 你可以给 getter 或 setter 设置访问修饰符 // 以便限制它们的访问 public bool IsBroken { get; private set; } @@ -671,12 +858,29 @@ on a new line! ""Wow!"", the masses cried"; public int FrameSize { get; - // 你可以给get或set指定访问修饰符 - // 以下代码意味着只有Bicycle类可以调用Framesize的set + // 你可以给 get 或 set 指定访问修饰符 + // 以下代码意味着只有 Bicycle 类可以调用 Framesize 的 set private set; } - //显示对象属性的方法 + // 还可以在对象上定义自定义索引器 + // 尽管这在本例中并不完全有用, you + // 你可以使用 bicycle[0] 返回 "chris" 来获得第一项 + // 或者 bicycle[1] = "lisa" 来设定值 + private string[] passengers = { "chris", "phil", "darren", "regina" }; + + public string this[int i] + { + get { + return passengers[i]; + } + + set { + passengers[i] = value; + } + } + + // 显示对象属性的方法 public virtual string Info() { return "Gear: " + Gear + @@ -698,7 +902,7 @@ on a new line! ""Wow!"", the masses cried"; } // Bicycle类结束 - // PennyFarthing是Bicycle的一个子类 + // PennyFarthing 是 Bicycle 的一个子类 class PennyFarthing : Bicycle { // (Penny Farthings是一种前轮很大的自行车。没有齿轮。) @@ -717,10 +921,17 @@ on a new line! ""Wow!"", the masses cried"; } set { - throw new ArgumentException("你不可能在PennyFarthing上切换齿轮"); + throw new ArgumentException("你不可能在 PennyFarthing 上切换齿轮"); } } + public static PennyFarthing CreateWithGears(int gears) + { + var penny = new PennyFarthing(1, 1); + penny.Gear = gears; // 你不能这样做! + return penny; + } + public override string Info() { string result = "PennyFarthing bicycle "; @@ -732,7 +943,7 @@ on a new line! ""Wow!"", the masses cried"; // 接口只包含成员的签名,而没有实现。 interface IJumpable { - void Jump(int meters); // 所有接口成员是隐式地公开的 + void Jump(int meters); // 所有接口成员是隐式地公开的 public } interface IBreakable @@ -741,6 +952,8 @@ on a new line! ""Wow!"", the masses cried"; } // 类只能继承一个类,但是可以实现任意数量的接口 + // 但是基类名称必须是列表中的第一个,所有接口都在后面 + class MountainBike : Bicycle, IJumpable, IBreakable { int damage = 0; @@ -759,41 +972,374 @@ on a new line! ""Wow!"", the masses cried"; } /// - /// 连接数据库,一个 LinqToSql的示例。 + /// 连接数据库,一个 LinqToSql 的示例。 /// EntityFramework Code First 很棒 (类似 Ruby的 ActiveRecord, 不过是双向的) - /// http://msdn.microsoft.com/en-us/data/jj193542.aspx + /// https://learn.microsoft.com/zh-cn/ef/ef6/modeling/code-first/workflows/new-database /// - public class BikeRespository : DbSet + public class BikeRepository : DbContext { - public BikeRespository() + public BikeRepository() : base() { } public DbSet Bikes { get; set; } } + + // 一个类可以通过 partial 关键字分别写在多个 .cs 文件中 + // A1.cs + public partial class A + { + public static void A1() + { + Console.WriteLine("Method A1 in class A"); + } + } + + // A2.cs + public partial class A + { + public static void A2() + { + Console.WriteLine("Method A2 in class A"); + } + } + + // 使用 partial 类 "A" + public class Program + { + static void Main() + { + A.A1(); + A.A2(); + } + } + + // 通过在字符串前加上 $ 前缀来进行字符串插值 + // 并用 { 大括号 } 包裹要插值的表达式 + // 您还可以将插值字符串和逐字字符串与 $@ 组合起来 + public class Rectangle + { + public int Length { get; set; } + public int Width { get; set; } + } + + class Program + { + static void Main(string[] args) + { + Rectangle rect = new Rectangle { Length = 5, Width = 3 }; + Console.WriteLine($"The length is {rect.Length} and the width is {rect.Width}"); + + string username = "User"; + Console.WriteLine($@"C:\Users\{username}\Desktop"); + } + } + + // C# 6 新特性 + class GlassBall : IJumpable, IBreakable + { + // 自动属性设置初始值 + public int Damage { get; private set; } = 0; + + // 为仅有 getter 的自动属性设定初始值 + public string Name { get; } = "Glass ball"; + + // 在构造函数中初始化的仅有 getter 的自动属性 + public string GenieName { get; } + + public GlassBall(string genieName = null) + { + GenieName = genieName; + } + + public void Jump(int meters) + { + if (meters < 0) + // 新的 nameof() 表达式; 编译器将检查标识符是否存在 + // nameof(x) == "x" + // 预防 例如 参数名称已更改但错误消息中未更新 + throw new ArgumentException("Cannot jump negative amount!", nameof(meters)); + + Damage += meters; + } + + // 表达式主体 expression-bodied 属性 ... + public bool Broken + => Damage > 100; + + // ... 刚发 + public override string ToString() + // 插值字符串 + => $"{Name}. Damage taken: {Damage}"; + + public string SummonGenie() + // Null 条件运算符 + // x?.y 如果 x 为 null 将立即返回 null; y 将不会求值 + => GenieName?.ToUpper(); + } + + static class MagicService + { + private static bool LogException(Exception ex) + { + // 记录某处的异常 + return false; + } + + public static bool CastSpell(string spell) + { + try + { + // 假设我们在这里调用 API + throw new MagicServiceException("Spell failed", 42); + + // Spell succeeded + return true; + } + // 仅当 Code 为 42(Spell failed)时才捕获 + catch(MagicServiceException ex) when (ex.Code == 42) + { + // Spell failed + return false; + } + // 其他异常,或 MagicServiceException 的 Code 不是 42 + catch(Exception ex) when (LogException(ex)) + { + // 永远不会执行到这块代码 + // 堆栈未展开 + } + return false; + // 请注意,捕获 MagicServiceException + // 并在 Code 不是 42 或 117 时重新抛出是不同的 + // 因为最终的 catch-all 块将不会捕获重新抛出的异常 + } + } + + public class MagicServiceException : Exception + { + public int Code { get; } + + public MagicServiceException(string message, int code) : base(message) + { + Code = code; + } + } + + public static class PragmaWarning { + // 过时的属性 + [Obsolete("Use NewMethod instead", false)] + public static void ObsoleteMethod() + { + // obsolete code + } + + public static void NewMethod() + { + // new code + } + + public static void Main() + { + ObsoleteMethod(); // CS0618: 'ObsoleteMethod 已过时:使用 NewMethod 代替' +#pragma warning disable CS0618 + ObsoleteMethod(); // no warning +#pragma warning restore CS0618 + ObsoleteMethod(); // CS0618: 'ObsoleteMethod 已过时:使用 NewMethod 代替' + } + } } // 结束 Namespace + +using System; +// C# 6, 静态引用 +using static System.Math; + +namespace Learning.More.CSharp +{ + class StaticUsing + { + static void Main() + { + // 不使用静态引用时.. + Console.WriteLine("The square root of 4 is {}.", Math.Sqrt(4)); + // 使用时 + Console.WriteLine("The square root of 4 is {}.", Sqrt(4)); + } + } +} + +// C# 7 新特性 +// 使用 Nuget 安装 Microsoft.Net.Compilers 最新版 +// 使用 Nuget 安装 System.ValueTuple 最新版 +using System; +namespace Csharp7 +{ + // 元组 TUPLES, 析构 DECONSTRUCTION 和 弃元 DISCARDS + class TuplesTest + { + public (string, string) GetName() + { + // 元组中的字段默认命名为 Item1、Item2... + var names1 = ("Peter", "Parker"); + Console.WriteLine(names1.Item2); // => Parker + + // 字段可以显式命名 + // 第 1 种声明 + (string FirstName, string LastName) names2 = ("Peter", "Parker"); + + // 第 2 种声明 + var names3 = (First:"Peter", Last:"Parker"); + + Console.WriteLine(names2.FirstName); // => Peter + Console.WriteLine(names3.Last); // => Parker + + return names3; + } + + public string GetLastName() { + var fullName = GetName(); + + // 元组可以被析构 + (string firstName, string lastName) = fullName; + + // 析构获得的字段可以使用 弃元 _ 丢弃 + var (_, last) = fullName; + return last; + } + + // 通过指定析构方法, + // 可以以相同的方式解构任何类型 + public int randomNumber = 4; + public int anotherRandomNumber = 10; + + public void Deconstruct(out int randomNumber, out int anotherRandomNumber) + { + randomNumber = this.randomNumber; + anotherRandomNumber = this.anotherRandomNumber; + } + + static void Main(string[] args) + { + var tt = new TuplesTest(); + (int num1, int num2) = tt; + Console.WriteLine($"num1: {num1}, num2: {num2}"); // => num1: 4, num2: 10 + + Console.WriteLine(tt.GetLastName()); + } + } + + // 模式匹配 + class PatternMatchingTest + { + public static (string, int)? CreateLogMessage(object data) + { + switch(data) + { + // 使用 when 进行附加过滤 + case System.Net.Http.HttpRequestException h when h.Message.Contains("404"): + return (h.Message, 404); + case System.Net.Http.HttpRequestException h when h.Message.Contains("400"): + return (h.Message, 400); + case Exception e: + return (e.Message, 500); + case string s: + return (s, s.Contains("Error") ? 500 : 200); + case null: + return null; + default: + return (data.ToString(), 500); + } + } + } + + // Reference 变量 / ref 局部变量 + // 允许返回对象的引用而不仅仅是其值 + class RefLocalsTest + { + // 返回值前标明 ref + public static ref string FindItem(string[] arr, string el) + { + for(int i=0; i apple + } + } + + // 本地函数 LOCAL FUNCTIONS + class LocalFunctionTest + { + private static int _id = 0; + public int id; + public LocalFunctionTest() + { + id = generateId(); + + // 这个本地函数只能在此作用域中被访问 + int generateId() + { + return _id++; + } + } + + public static void AnotherMethod() + { + var lf1 = new LocalFunctionTest(); + var lf2 = new LocalFunctionTest(); + Console.WriteLine($"{lf1.id}, {lf2.id}"); // => 0, 1 + + int id = generateId(); + // error CS0103: 当前上下文中不存在名称“generateId” + } + } +} + ``` ## 没有涉及到的主题 +✨ 新的, 👍 旧的, 🎈 长期支持的, 🔥 跨平台的, 🎁 只支持Windows的 - * Flags - * Attributes - * 静态属性 - * Exceptions, Abstraction - * ASP.NET (Web Forms/MVC/WebMatrix) - * Winforms - * Windows Presentation Foundation (WPF) + * 特性 Attributes + + * 异步编程 + + * Web 开发 + * ASP.NET Core ✨ + + * 桌面应用开发 Development + * Windows Presentation Foundation (WPF) 👍 🎈 🎁 + * Universal Windows Platform (UWP) ✨ 🎁 + * Uno Platform 🔥 ✨ + * WinForms 👍 🎈 🎁 + * Avalonia 🔥 ✨ + * WinUI ✨ 🎁 + + * 跨平台开发 + * Xamarin.Forms 👍 + * MAUI ✨ ## 扩展阅读 + * [C# language reference](https://docs.microsoft.com/dotnet/csharp/language-reference/) + * [Learn .NET](https://dotnet.microsoft.com/learn) + * [C# Coding Conventions](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions) * [DotNetPerls](http://www.dotnetperls.com) * [C# in Depth](http://manning.com/skeet2) - * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) - * [LINQ](http://shop.oreilly.com/product/9780596519254.do) - * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) - * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) - * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) - * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Programming C# 5.0](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ Pocket Reference](http://shop.oreilly.com/product/9780596519254.do) * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) - * [C# Coding Conventions](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) + * [freeCodeCamp - C# Tutorial for Beginners](https://www.youtube.com/watch?v=GhQdlIFylQ8) From 8a7cdc171f9e56fc54227720acaa78db3948747a Mon Sep 17 00:00:00 2001 From: mihleonid <37627696+mihleonid@users.noreply.github.com> Date: Mon, 11 Mar 2024 14:42:55 +0300 Subject: [PATCH 039/392] Update haskell-ru.html.markdown (#4696) "fib" is mentioned three times in this document. First and last time fib 2 = 1. I suppose that in the second time fib 2 = 2 was a typo. --- ru-ru/haskell-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/haskell-ru.html.markdown b/ru-ru/haskell-ru.html.markdown index b1b8eb79..f04c45e2 100644 --- a/ru-ru/haskell-ru.html.markdown +++ b/ru-ru/haskell-ru.html.markdown @@ -172,7 +172,7 @@ fib x первое определение, к образцу которого "подойдет" набор аргументов -} fib 1 = 1 -fib 2 = 2 +fib 2 = 1 fib x = fib (x - 1) + fib (x - 2) -- Pattern matching для кортежей выглядит так From 4fafc296669ffccab831bcd5d3407cf934f0d228 Mon Sep 17 00:00:00 2001 From: Federico <96267363+dalps@users.noreply.github.com> Date: Thu, 14 Mar 2024 02:40:43 +0100 Subject: [PATCH 040/392] Quote this keyword in explanation (#4862) --- javascript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/javascript.html.markdown b/javascript.html.markdown index 08f1d8fb..4e7c5c09 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -405,7 +405,7 @@ myObj = { }; myObj.myFunc(); // = "Hello world!" -// What this is set to has to do with how the function is called, not where +// What `this` is set to has to do with how the function is called, not where // it's defined. So, our function doesn't work if it isn't called in the // context of the object. var myFunc = myObj.myFunc; From 32cac749fdf88b7033eb4ba7c47d1e407bc9ac0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Thu, 14 Mar 2024 15:31:33 -0300 Subject: [PATCH 041/392] docs(pt-br): Start Portuguese translation for HTTPie article - Start translation of the HTTPie article to Portuguese language for better accessibility and understanding. --- pt-br/httpie-pt.html.markdown | 122 ++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 pt-br/httpie-pt.html.markdown diff --git a/pt-br/httpie-pt.html.markdown b/pt-br/httpie-pt.html.markdown new file mode 100644 index 00000000..9a601fb2 --- /dev/null +++ b/pt-br/httpie-pt.html.markdown @@ -0,0 +1,122 @@ +--- +category: tool +tool: httpie +filename: learn-httpie-pt.sh +contributors: + - ["Adaías Magdiel", "https://github.com/AdaiasMagdiel"] +translators: + - ["Adaías Magdiel", "https://adaiasmagdiel.com/"] +lang: pt-br +--- + +HTTPie é um poderoso cliente HTTP para linha de comando, projetado para uma +integração suave com servidores HTTP. Oferece uma interface simples e intuitiva, +tornando-se uma excelente ferramenta para desenvolvedores, testadores e administradores de sistemas. + +## Uso Básico + +HTTPie possui uma sintaxe simples: http [flags] [MÉTODO] URL [itens]. + +```bash +http GET https://api.example.com/posts +``` + +Você pode exibir a requisição sem executá-la, de fato, usando a flag `--offline`. + +```bash +http --offline https://api.example.com/posts +``` + +### Encurtando URLs `localhost` + +HTTPie fornece suporte a atalhos para o localhost, similares aos do `curl`. Por exemplo, ":3000" +expande para "http://localhost:3000". Se a porta for omitida, o padrão será a porta 80. + +```bash +http :/users # http://localhost/users +http :5000/rss # http://localhost:5000/rss +``` + +### Métodos Opcionais GET e POST + +Se você não especificar o método, o HTTPie usará o seguinte: + +- GET para requisições sem corpo +- POST para requisições com corpo + +```bash +http https://api.example.com/tags # GET - Seleciona as tags +http https://api.example.com/tags title="Tutorial" slug="tutorial" # POST - Cria uma nova tag +``` + +## Parâmetros Querystring + +Se você adiciona querystrings manualmente no terminal, tente a seguinte sintaxe: +`param==value`. Isso evita que o shell tente reconhecer o operador & como comando +e automaticamente escape caracteres especiais nos parâmetros. +Isso difere dos parâmetros na URL completa, que o HTTPie não modifica. + +```bash +http https://api.example.com/search q==httpie per_page==20 +``` + +## Enviando Dados + +Você pode enviar dados nos mais diversos formatos, como JSON, formulários ou arquivos. + +### JSON Data + +```bash +http POST https://api.example.com/posts title="Hello" body="World" +``` + +### Form Data + +```bash +http -f POST https://api.example.com/submit name=John email=john@example.com +``` + +### Files + +```bash +http --form POST https://api.example.com/upload file@/path/to/file.txt +``` + +## Headers and Authentication + +HTTPie allows you to set headers and handle authentication easily. + +### Headers + +```bash +http GET https://api.example.com/posts Authorization:"Bearer Token" User-Agent:"HTTPie" +``` + +### Basic Authentication + +```bash +http -a username:password GET https://api.example.com/protected +``` + +### Bearer Authentication + +```bash +https -A bearer -a token https://api.example.com/admin +``` + +## Response Handling + +HTTPie provides various options for handling responses. + +```bash +http GET https://api.example.com/data Accept:application/json # Pretty Print JSON + +http GET https://api.example.com/image --output image.png # Save Response to File + +http --follow GET https://example.com # Follow Redirects +``` + +## Further Reading + +- [Official Documentation](https://httpie.io/docs/cli). +- [Github](https://github.com/httpie). From 1575bceff3e6d0676884d6b0300bece62f9930ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Fri, 15 Mar 2024 08:41:01 -0300 Subject: [PATCH 042/392] docs(httpie-pt): Add Portuguese translation - Updated the Portuguese translation for better clarity and consistency throughout the document. - Updated references to HTTP methods for sending JSON, forms, and files to use native Portuguese terms. - Improved the translations of headers, authentication methods, and response handling instructions to make them more understandable for Portuguese speakers. - Updated URLs in the "Further Reading" section to point to the correct Portuguese resources. --- pt-br/httpie-pt.html.markdown | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/pt-br/httpie-pt.html.markdown b/pt-br/httpie-pt.html.markdown index 9a601fb2..9ef515bc 100644 --- a/pt-br/httpie-pt.html.markdown +++ b/pt-br/httpie-pt.html.markdown @@ -64,27 +64,27 @@ http https://api.example.com/search q==httpie per_page==20 Você pode enviar dados nos mais diversos formatos, como JSON, formulários ou arquivos. -### JSON Data +### Enviando JSON ```bash -http POST https://api.example.com/posts title="Hello" body="World" +http POST https://api.example.com/posts title="Olá" body="Mundo" ``` -### Form Data +### Enviando Formulário ```bash http -f POST https://api.example.com/submit name=John email=john@example.com ``` -### Files +### Enviando Arquivos ```bash -http --form POST https://api.example.com/upload file@/path/to/file.txt +http --form POST https://api.example.com/upload file@/caminho/do/arquivo.txt ``` -## Headers and Authentication +## Headers e Autenticação -HTTPie allows you to set headers and handle authentication easily. +HTTPie permite que você adicione headers e lide com autenticação de uma forma fácil. ### Headers @@ -92,31 +92,31 @@ HTTPie allows you to set headers and handle authentication easily. http GET https://api.example.com/posts Authorization:"Bearer Token" User-Agent:"HTTPie" ``` -### Basic Authentication +### Autenticação Básica ```bash -http -a username:password GET https://api.example.com/protected +http -a usuario:senha GET https://api.example.com/protected ``` -### Bearer Authentication +### Autenticação Bearer ```bash https -A bearer -a token https://api.example.com/admin ``` -## Response Handling +## Lidando com Respostas -HTTPie provides various options for handling responses. +HTTPie fornece várias opções para lidar com respostas. ```bash -http GET https://api.example.com/data Accept:application/json # Pretty Print JSON +http GET https://api.example.com/data Accept:application/json # Exibe o JSON de uma forma legível -http GET https://api.example.com/image --output image.png # Save Response to File +http GET https://api.example.com/image --output image.png # Grava a resposta em um arquivo -http --follow GET https://example.com # Follow Redirects +http --follow GET https://example.com # Segue redirecionamentos ``` -## Further Reading +## Leitura Adicional -- [Official Documentation](https://httpie.io/docs/cli). +- [Documentação Oficial](https://httpie.io/docs/cli). - [Github](https://github.com/httpie). From d72ab67435028216145e2cdb579df7f3cf6154ff Mon Sep 17 00:00:00 2001 From: inkling <27819662+driftsignal@users.noreply.github.com> Date: Sat, 23 Mar 2024 00:32:38 -0400 Subject: [PATCH 043/392] Update hy.html.markdown for 0.28.0 (#4867) for looping seems to have updated in this version --- hy.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/hy.html.markdown b/hy.html.markdown index f6bdead0..5eddbf55 100644 --- a/hy.html.markdown +++ b/hy.html.markdown @@ -174,10 +174,10 @@ True ; => True ; create lexical bindings with `let', all variables defined thusly ; have local scope -(let [[nemesis {"superman" "lex luther" +(let [nemesis {"superman" "lex luther" "sherlock" "moriarty" - "seinfeld" "newman"}]] - (for [(, h v) (.items nemesis)] + "seinfeld" "newman"}] + (for [[h v] (.items nemesis)] (print (.format "{0}'s nemesis was {1}" h v)))) ;; classes From 4273e67f566ad82d657ef8692e22f06a01d8bda1 Mon Sep 17 00:00:00 2001 From: Preetham Pemmasani <75422607+Preetham-ai@users.noreply.github.com> Date: Sat, 23 Mar 2024 11:04:39 +0530 Subject: [PATCH 044/392] [osl/en] Added OSL and covered almost everything (#4857) * added OSL language Added most of the basics * Update osl.html.markdown * Updated Datatypes * Added some functions * Update osl.html.markdown * Added Pattern Generations, Calculus, Texture and Light functions * Final * fixed 80 words * Added Examples --- osl.html.markdown | 751 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 751 insertions(+) create mode 100644 osl.html.markdown diff --git a/osl.html.markdown b/osl.html.markdown new file mode 100644 index 00000000..af5f83bc --- /dev/null +++ b/osl.html.markdown @@ -0,0 +1,751 @@ +--- +language: osl +filename: learnosl.osl +contributors: + - ["Preetham Pemmasani", "https://github.com/Preetham-ai"] +--- + +OSL (Open Shading Language) is a programming language designed by Sony for Arnold Renderer used for creating shaders. + +[Read more here.](https://raw.githubusercontent.com/imageworks/OpenShadingLanguage/master/src/doc/osl-languagespec.pdf) + +```c + + +// Single-line comments start with // + +/* Multi line comments are preserved. */ + +// Statements can be terminated by ; +divide(1,2); + +/////////////// +// 1. Basics // +/////////////// + +// Declating variables +color Blue; // Initializing a variable +int _num = 3; +float Num = 3.00; +float c[3] = {0.1, 0.2, 3.14}; // Array + +// Math works as you would expect +3 + 1; // 4 +74 - 3; // 71 +20 * 2; // 40 +75/3; // 25.0 + +// And modulo division only works with integers +10 % 2; // 0 +31 % 4; // 1 + +// Bitwise operations only works with integers +- 0 // 1 (Unary Negation) +~ 00100011 // 11011100 (bitwise Compliment) +1 << 2; // 4 (shift Left) +12 >> 1; // 3 (shift Right) +1 & 0; // 0 (bitwise AND) +1 | 0; // 1 (bitwise OR) +1 ^ 1; // 0 (bitwise XOR) + +// We also have booleans +true; +false; + +// Booleans can't be compared to integers +true == 1 // Error +false == 0 // Error + +// Negation uses the ! symbol +!0; // 1 +!1; // 0 +!2; // 0 +//... and so on + +// Relation Operators are defined like: +0 == 0 // true (equal to) +0 != 1 // true (not equal to) +5 < 3 // false (less then) +3 <= 3 // true (less than or equal to) +69 > 69 // false (greater than) +99 >= 52 // true (greater than or equal) + + +// Functions are same as C and C++ +float sum(float a, float b){ + return a+b; +} + +int subtract(int a, int b){ + return a-b; +} + +sum(2,3); // 5 + +//////////////// +// 2. Shaders // +//////////////// + +// Shaders explain the custom behavior of materials and light +// Shader's syntax is similar to the main function in C +// The inputs and the outputs should be initialized to default types +shader multiply(float a = 0.0, + float b = 0.0, + output float c = 0.0){ + c = a*b; +} + +// Double brackets[[ ]] is used to classify metadata of a shader +surface plastic + [[ string help = "Realistic wood shader" ]] +( + color Plastic = color (0.7, 0.5, 0.3) [[ string help = "Base color" ]], + float Reflectivity = 0.5 [[ float min = 0, float max = 1 ]], +){...} + +/////////////////////////////////////// +// Metadata Types +/////////////////////////////////////// + +[[ string label = "IOR" ]] // Display-name in UI of the parameter +[[ string help = "Change Refractive Index" ]] // Info about the parameter +[[ string help = "widget" // Gives widgets to input the parameter + string widget = "number" ]] // input float or int + string widget = "string" ]] // String input + string widget = "boolean" ]] // yes/no (or) 1/0 + string widget = "popup", options = "smooth|rough" ]] // Drop-down list + // enum Drop-down list can also be made + string widget = "mapper", options = "smooth:0|rough:1" ]] + string widget = "filename" ]] // Input files externally + string widget = "null" ]] // null input + +[[ float min = 0.0 ]] // Minimum value of parameter +[[ float max = 0.5 ]] // Maximum value of parameter +[[ int slider = 3.0 // Adds a slider as an input + int slidermin = -1]] // minimum value of the slider + int slidermax = 3]] // maximum value of the slider + int slidercenter = 2]] // origin value of the slider + +[[ float sensitivity = 0.5 ]] // step size for incrementing the parameter +[[ string URL = www.example.com/ ]] // URL of shader's documentation + + + +// There are different types of shaders + +/* Surface shaders determine the basic material properties of a surface and +how it reacts to light */ +// Light shaders are a type of SURFACE shaders used for emissive objects. +// Displacement shaders alter the geometry using position and normals. +// Volume shaders adds a medium like air/smoke/dust into the scene. + +volume multiply(float a = 0.0, float b = 0.0, output float c = 0.0){ + c = 2*a+b; +} + +//////////////////////////////////////// +// 3. Data Types and Global Variables // +//////////////////////////////////////// + +// Data Types + +// 1. The void type indicates a function that doesn't return any value + +// 2. int (Integer) + int x = -12; // Minimum size of 32-bits + int new2 = 0x01cf; // Hexadecimal can also be specified + + /////////////////////////////////////// + // Order of Evaluation + /////////////////////////////////////// + + // From top to bottom, top has higher precedence + //--------------------------// + // Operators // + //--------------------------// + // int++, int-- // + // ++ int --int - ~ ! // + // * / % // + // + - // + // << >> // + // < <= > >= // + // == != // + // & // + // ^ // + // | // + // && // + // || // + // ?: // + // = += -= *= /= // + //--------------------------// + +// 3. float (Floating-point number) + float A = 2.3; // minimum IEEE 32-bit float + float Z = -4.1e2; // Z = -4.1 * 10^2 + + // Order of evaluation is similar to int. + // Operations like ( ~ ! % << >> ^ | & && || ) aren't available in float + +// 4. string + // The syntax is similar to C + string new = "Hello World"; + // some Special characters: + /* + '\"'; // double quote + '\n'; // newline character + '\t'; // tab character (left justifies text) + '\v'; // vertical tab + '\\'; // back slash + '\r'; // carriage return + '\b'; // backspace character + */ + + // Strings are concatenated with whitespace + "Hello " "world!"; // "Hello world!" + // concat function can also be used + string concat ("Hello ","World!"); // "Hello world!" + + // printf function is same as C + int i = 18; + printf("I am %d years old",i); // I am 18 years old + + // String functions can alse be used + int strlen (string s); // gives the length of the string + int len = strlen("Hello, World!"); // len = 13 + + // startswith returns 1 if string starts with prefix, else returns 0 + int starts = startswith("The quick brown fox", "The"); // starts = 1 + + // endswith returns 1 if string starts with suffix, else returns 0 + int ends = endswith("The quick brown fox", "fox"); // ends will be 1 + +// 5. color (Red, Green, Blue) + color p = color(0,1,2); // black + color q = color(1); // white ( same as color(1,1,1) ) + color r = color("rgb", 0.23, 0.1, 0.8); // explicitly specify in RGB + color s = color("hsv", 0.23, 0.1, 0.8); // specify in HSV + // HSV stands for (Hue, Saturation, Luminance) + // HSL stands for (Hue, Saturation, Lightness) + // YIQ, XYZ and xyY formats can also be used + // We can also access the indivudual values of (R,G,B) + float Red = p[0]; // 0 (access the red component) + float Green = p[1]; // 1 (access the green component) + float Blue = p[2]; // 2 (access the blue component) + + // They can also be accessed like this + float Red = p.r; // 0 (access the red component) + float Green = p.g; // 1 (access the green component) + float Blue = p.b; // 2 (access the blue component) + + // Math operators work like this with decreasing precedence + color C = (3,2,3) * (1,0,0); // (3, 0, 0) + color D = (1,1,1) * 255; // (255, 255, 255) + color E = (25,5,125) / 5; // (5, 1, 25) + color F = (30,40,50) / (3,4,5); // (10, 10, 10) + color A = (1,2,3) + (1,0,0); // (2, 2, 3) + color B = (1,2,3) - (1,0,0); // (0, 2, 3) + // Operators like ( - == != ) are also used + + // Color Functions + color blackbody (1500) // Gives color based on temperature (in Kelvin) + float luminance (0.5, 0.3, 0.8) // 0.37 gives luminance cd/m^2 + // Luminance is calculated by 0.2126R+0.7152G+0.0722B + color wavelength color (700) // (1, 0, 0) Gives color based on wavelength + color transformc ("hsl", "rgb") // converts one system to another + +// 6. point (x,y,z) is position of a point in the 3D space +// 7. vector (x,y,z) has length and direction but no position +// 8. normal (x,y,z) is a special vector perpendicular to a surface + // These Operators are the same as color and have the same precedence + L = point(0.5, 0.6, 0.7); + M = vector(30, 100, 70); + N = normal(0, 0, 1); + + // These 3 types can be assigned to a coordinate system + L = point("object", 0.5, 0.6, 0.7); // relative to local space + M = vector("common", 30, 100, 70); // relative to world space + // There's also ("shader", "world", "camera", "screen", "raster", "NDC") + + float x = L[0]; // 0.5 (access the x-component) + float y = L[1]; // 0.6 (access the y-component) + float z = L[2]; // 0.7 (access the z-component) + + // They can also be accessed like this + float x = M.x; // 30 (access the x-component) + float y = M.y; // 100 (access the y-component) + float z = M.z; // 70 (access the z-component) + + float a = dot ((1,2,3), (1,2,3)); // 14 (Dot Product) + vector b = cross ((1,2,3), (1,2,3)); // (0,0,0) (Cross Product) + float l = length(L); // 1.085 (length of vector) + vector normalize (vector L); // (0.460, 0.552, 0.644) Normalizes the vector + + point p0 = point(1, 2, 3); + point p1 = point(4, 5, 6); + point Q = point(0, 0, 0); + + // Finding distance between two points + float len = distance(point(1, 2, 3), point(4, 5, 6)); // 5.196 + // Perpendicular distance from Q to line joining P0 and P1 + float distance (point P0, point P1, point Q); // 2.45 + + +// 9. matrix + // Used for transforming vectors between different coordinate systems. + // They are usually 4x4 (or) 16 floats + matrix zero = 0; // makes a 4x4 zero matrix + /* 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0, + 0.0, 0.0, 0.0, 0.0 */ + + matrix ident = 1; // makes a 4x4 identity matrix + /* 1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0 */ + + matrix m = 7; // Maked a 4x4 scalar matrix with scaling factor of 7 + /* 7.0, 0.0, 0.0, 0.0, + 0.0, 7.0, 0.0, 0.0, + 0.0, 0.0, 7.0, 0.0, + 0.0, 0.0, 0.0, 7.0 */ + + float x = m[1][1]; // 7 + + // matrices can be constructed using floats in row-major order + // matrices are usually 4x4 with 16 elements + matrix myMatrix = matrix(1.0, 0.0, 0.0, 0.0, // Row 1 + 0.0, 2.0, 0.0, 0.0, // Row 2 + 0.0, 0.0, 3.0, 0.0, // Row 3 + 0.0, 0.0, 0.0, 4.0); // Row 4 + + // matrix transformations are easy to implement + matrix a = matrix ("shader", 1); // converted shader to common + matrix m = matrix ("object", "world"); // converted object to world + + // Operations that can be used with decreasing precedence are: + // ( - * / == !=) + + float determinant (matrix M) // 24 (returns the determinant of the matrix) + float transpose (matrix M) // returns the transpose of the matrix + /* 1.0, 0.0, 0.0, 0.0, + 0.0, 2.0, 0.0, 0.0, + 0.0, 0.0, 3.0, 0.0, + 0.0, 0.0, 0.0, 4.0 */ + +// 10. array + // Arrays in OSL are similar to C + float a[5]; // initialize array a with size 5 + int b[3] = {90,80,70}; // declare array with size 3 + int len = arraylength(b); // 3 + int f = b[1]; // 80 + float anotherarray[3] = b; // arrays can be copied if same type + +// 11. struct (Structures) + // Structures in OSL are similar to C and C++. + struct RGBA { // Defining a structure + color rgb; + float alpha; + }; + + + RGBA col; // Declaring a structure + RGBA b = { color(0.1, 0.2, 0.3), 1 }; // Can also be declared like this + + r.rgb = color (1, 0, 0); // Assign to one field + color c = r.rgb; // Read from a structure field + +// 12. closure + // Closure is used to store data that aren't considered when it executes. + // It cannot be manipulated or read. + // A null closure can always be assigned. + // OSL currently only supports color as their closure. + + // A few examples of closures are: + + // Diffuse BSDF closures: + closure color oren_nayar_diffuse_bsdf(normal N, color alb, float roughness) + closure color burley_diffuse_bsdf(normal N, color alb, float roughness); + + // Dielectric BSDF closure: + closure color dielectric_bsdf(normal N, vector U, color reflection_tint, + color transmission_tint, float roughness_x, float roughness_y, + float ior, string distribution); + + // Conductor BSDF closure: + closure color conductor_bsdf(normal N, vector U, float roughness_x, + float roughness_y, color ior, color extinction, string distribution); + + // Generalized Schlick BSDF closure: + closure color generalized_schlick_bsdf(normal N, vector U, + color reflection_tint, color transmission_tint, + float roughness_x, float roughness_y, color f0, color f90, + float exponent, string distribution); + + // Translucent BSDF closure: + closure color translucent_bsdf(normal N, color albedo); + + // Transparent BSDF closure: + closure color transparent_bsdf(); + + // Subsurface BSSRDF closure: + closure color subsurface_bssrdf(); + + // Sheen BSDF closure: + closure color sheen_bsdf(normal N, color albedo, float roughness); + + // Anisotropic VDF closure: (Volumetric) + closure color anisotropic_vdf(color albedo, color extinction, + float anisotropy); + + // Medium VDF closure: (Volumetric) + closure color medium_vdf(color albedo, float transmission_depth, + color transmission_color, float anisotropy, float ior, int priority); + + closure color uniform edf(color emittance); // Emission closure + closure color holdout(); // Holdout Hides objects beneath it + + // BSDFs can be layered using this closure + closure color layer (closure color top, closure color base); + + + +// Global Variables +// Contains info that the renderer knows +// These variables need not be declared + +point P // Position of the point you are shading +vector I // Incident ray direction from viewing position to shading position +normal N // Normal of the surface at P +normal Ng // Normal of the surface at P irrespective of bump mapping +float u // UV 2D x - parametric coordinate of geometry +float v // UV 2D y - parametric coordinate of geometry +vector dPdu // change of P with respect to u tangent to the surface +vector dPdv // change of P with respect to v tangent to the surface +float time // Current time +float dtime // Time covered +vector dPdtime // change of P with respect to time + +///////////////////// +// 4. Control flow // +///////////////////// + +// Conditionals in OSL are just like in C or C++. + +// If/Else +if (5>2){ + int x = s; + int l = x; +} +else{ + int x = s + l; +} + +// 'while' loop +int i = 0; +while (i < 5) { + i += 1; + printf("Current value of i: %d\n", i); +} + +// 'do-while' loop is where test happens after the body of the loop +int i = 0; +do { + printf("Current value of i: %d\n", i); + i += 1; +} while (i < 5); + +// 'for' loop +for (int i = 0; i < 5; i += 1) { + printf("Current value of i: %d\n", i); +} + +///////////////////// +// 5. Functions // +///////////////////// + +// Math Constants + M_PI // π + M_PI_35 // π/35 + m_E // e + M_LN2 // ln 2 + M_SQRT2 // √2 + M_SQRT1_2 // √(1/2) + +// Geometry Functions + vector N = vector(0.1, 1, 0.2); // Normal vector + vector I = vector(-0.5, 0.2, 0.8); // Incident vector + + // Faceforward tells the direction of vector + vector facing_dir = faceforward(N, I); // facing_dir = (-0.5, 0.2, 0.8) + + // faceforward with three arguments + vector ref = vector(0.3, -0.7, 0.6); // Reference normal + facing_dir = faceforward(N, I, ref); // facing_dir = (0.5, -0.2, -0.8) + + // reflect gives the reflected vector along normal + vector refl = reflect(I, N); // refl = (-0.7, -0.4, 1.4)\ + + // refract gives the refracted vector along normal + float ior = 1.5; // Index of refraction + vector refr = refract(I, N, ior); // refr = (-0.25861, 0.32814, 0.96143) + + /* Fresnel computes the Reflection (R) and Transmission (T) vectors, along + with the scaling factors for reflected (Kr) and transmitted (Kt) light. */ + float Kr, Kt; + vector R, T; + fresnel(I, N, ior, Kr, Kt, R, T); +/* Kr = 0.03958, Kt = 0.96042 + R = (-0.19278, -0.07711, 0.33854) + T = (-0.25861, 0.32814, 0.96143) */ + + // Rotating a point along a given axis + point Q = point(1, 0, 0); + float angle = radians(90); // 90 degrees + vector axis = vector(0, 0, 1); + point rotated_point = rotate(Q, angle, axis); + // rotated_point = point(0, 1, 0) + + // Rotating a point along a line made by 2 points + point P0 = point(0, 0, 0); + point P1 = point(1, 1, 0); + angle = radians(45); // 45 degrees + Q = point(1, 0, 0); + rotated_point = rotate(Q, angle, P0, P1); + // rotated_point = point(0.707107, 0.707107, 0) + + // Calculating normal of surface at point p + point p1 = point(1, 0, 0); // Point on the sphere of radius 1 + vector normal1 = calculatenormal(p1); + // normal1 = vector(1, 0, 0) + + // Transforming units is easy + float transformu ("cm", float x) // converts to cm + float transformu ("cm", "m", float y) // converts cm to m + +// Displacement Functions + void displace (float 5); // Displace by 5 amp units + void bump (float 10); // Bump by 10 amp units + + +// Noise Generation + + type noise (type noise (string noisetype, float u, float v, ...)); // noise + type noise (string noisetype, point p,...); // point instead of coordinates + /* some noises are ("perlin", "snoise", "uperlin", "noise", "cell", "hash" + "simplex", "usimplex", "gabor", etc) */ + + // Noise Names + + // 1. Perlin Noise (perlin, snoise): + // Creates smooth, swirling noise often used for textures. + // Range: [-1, 1] (signed) + color cloud_texture = noise("perlin", P); + + // 2. Simplex Noise (simplex, usimplex): + // Similar to Perlin noise but faster. + // Range: [-1, 1] (signed) for simplex, [0, 1] (unsigned) for usimplex + float bump_amount = 0.2 * noise("simplex", P * 5.0); + + // 3. UPerlin Noise (uperlin, noise): + // Similar to peril + // Range: [0, 1] (unsigned) + color new_texture = noise("uperlin", P); + + // 4. Cell Noise (cell): + // Creates a blocky, cellular and constant values within each unit block + // Range: [0, 1] (unsigned) + color new_texture = noise("cell", P); + + // 5. Hash Noise (hash): + // Generates random, uncorrelated values at each point. + // Range: [0, 1] (unsigned) + color new_texture = noise("hash", P); + + // Gabor Noise (gabor) + // Gabor Noise is advanced version of Perin noies and gives more control + // Range: [-1, 1] (signed) + // Gabor Noise Parameters + + // Anisotropic (default: 0) + // Controls anisotropy: + // 0: Isotropic (equal frequency in all directions) + // 1: Anisotropic with user-defined direction vector (defaults to (1,0,0)) + /* 2: Hybrid mode,anisotropic along direction vector but radially isotropic + perpendicularly. */ + + // Direction (default: (1,0,0)) + // Specifies the direction of anisotropy (used only if anisotropic is 1). + + // bandwidth (default: 1.0) + // Controls the frequency range of the noise. + + // impulses (default: 16) + // Controls the number of impulses used per cell, affecting detail level. + + // do_filter (default: 1) + // Enables/disables antialiasing (filtering). + + result = noise( + "gabor", + P, + "anisotropic", anisotropic, + "direction", direction, + "bandwidth", bandwidth, + "impulses", impulses, + "do_filter", do_filter + ); + + // Specific noises can also be used instead of passing them as types + // pnoise is periodic noise + float n1 = pnoise("perlin", 0.5, 1.0); + // 2D periodic noise with Gabor type + float n2 = pnoise("gabor", 0.2, 0.3, 2.0, 3.0); + // 2D non-periodic simplex noise + float n3 = snoise(0.1, 0.7); + // 2D periodic simplex noise + type psnoise (float u, float v, float uperiod, float vperiod); + float n4 = psnoise(0.4, 0.6, 0.5, 0.25); + // 2D cellular noise + float n5 = cellnoise(0.2, 0.8); + // 2D hash noise + int n6 = hash(0.7, 0.3); + +// Step Function + // Step Functions are used to compare input and threshold + + // The type may be of float, color, point, vector, or normal. + type step (type edge, type x); // Returns 1 if x ≥ edge, else 0 + color checker = step(0.5, P); // P is a point on the surface + /* Pixels with P values below 0.5 will be black, those above or equal will + be white */ + float visibility = step(10, distance(P, light_position)); + // Light is fully visible within 10 units, completely invisible beyond + + type linearstep (type edge0, type edge1, type x); /* Linearstep Returns 0 + if x ≤ edge0, and 1 if x ≥ edge1, with linear interpolation */ + color gradient = linearstep(0, 1, P); + // P is a point on the surface between 0 and 1 + // Color will graduate smoothly from black to white as P moves from 0 to 1 + float fade = linearstep(0.85, 1, N.z); // N.z is the z-component + // Object edges with normals close to vertical (N.z near 1) will fade out + + type smoothstep (type edge0, type edge1, type x); /* smoothstep Returns 0 + if x ≤ edge0, and 1 if x ≥ edge1, with Hermite interpolation */ + float soft_mask = smoothstep(0.2, 0.8, noise(P)); /* noise(P) is a noisy + value between 0 and 1. soft_mask will vary smoothly between 0 and 1 based + on noise(P), with a smoother curve than linearstep */ + +// Splines + // Splines are smooth curves based on a set of control points + + /* The type of interpolation ranges from "catmull-rom", "bezier", + "bspline", "hermite", "linear", or "constant" */ + + // Spline with knot vector + float[] knots = {0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1}; + point[] controls = {point(0),point(1, 2, 1),point(2, 1, 2),point(3, 3, 1)}; + spline curve1 = spline("bezier", 0.5, len(knots), controls); + // curve1 is a Bezier spline evaluated at u = 0.5 + + // Spline with control points + spline curve2 = spline("catmull-rom", 0.25, point(0, 0, 0), point(1, 2, 1), + point(2, 1, 2), point(3, 3, 1)); + // curve2 is a Catmull-Rom spline evaluated at u = 0.25 + + // Constant spline with a single float value + float value = 10; + u = 0.1; + spline curve5 = spline("constant", u, value); + // curve5 is a constant spline with value 10 evaluated at u = 0.1 + + // Hermite spline with point and vector controls + point q0 = point(0, 0, 0), q1 = point(3, 3, 3); + vector t0 = vector(1, 0, 0), t1 = vector(-1, 1, 1); + u = 0.75; + spline curve3 = spline("hermite", u, q0, t0, q1, t1); + // curve3 is a Hermite spline evaluated at u = 0.75 + + // Linear spline with float controls + float f0 = 0, f1 = 1, f2 = 2, f3 = 3; + u = 0.4; + spline curve4 = spline("linear", u, f0, f1, f2, f3); + // curve4 is a linear spline evaluated at u = 0.4 + + // InverseSplines also exist + + // Inverse spline with control values + float y0 = 0, y1 = 1, y2 = 2, y3 = 3; + float v = 1.5; + float u1 = splineinverse("linear", v, y0, y1, y2, y3); + // u1 = 0.5 (linear interpolation between y1 and y2) + + // Inverse spline with knot vector + float[] knots = {0, 0, 0, 0.25, 0.5, 0.75, 1, 1, 1}; + float[] values = {0, 1, 4, 9}; + v = 6; + float u2 = splineinverse("bezier", v, len(knots), values); + // u2 = 0.75 (Bezier spline inverse evaluated at v = 6) + + // Inverse spline with constant value + v = 10; + float u3 = splineinverse("constant", v, 10); + // u3 = 0 (since the constant spline always returns 10) + + // Inverse spline with periodic values + float y4 = 0, y5 = 1, y6 = 0; + v = 0.5; + float u4 = splineinverse("periodic", v, y4, y5, y6); + // u4 = 0.75 (periodic spline inverse evaluated at v = 0.5) + + + +// Calculus Operators + // Partial derivative of f with respect to x, y and z using Dx, Dy, Dz + float a = 3.14; + float dx = Dx(a); // partial derivative of a with respect to x + + point p = point(1.0, 2.0, 3.0); + vector dp_dx = Dx(p); // partial derivative of p with respect to x + + vector dv_dy = Dy(N); // partial derivative of normal with respect to y + + color c = color(0.5, 0.2, 0.8); + color dc_dz = Dz(c); // partial derivative of c with respect to z + + + float area (point p) // gives the surface area at the position p + + float filterwidth (float x) // gives the changes of x in adjacent samples + +// Texture Functions + // lookup for a texture at coordinates (x,y) + color col1 = texture("texture.png", 0.5, 0.2); + // Lookup color at (0.5, 0.2) in texture.png + + // 3D lookup for a texture at coordinates (x,y) + color col3 = texture3d("texture3d.vdb", point(0.25, 0.5, 0.75)); + + // parameters are ("blur","width","wrap","fill","alpha","interp", ...) + color col2 = texture("texture.png",1.0,0.75,"blur",0.1,"wrap", "periodic"); + // Lookup color at (1.0, 0.75) with blur 0.1 and periodic wrap mode + +// Light Functions + + float surfacearea (); // Returns the surface area of area light covers + int backfacing (); // Outputs 1 if the normals are backfaced, else 0 + int raytype (string name); // returns 1 if the ray is a particular raytype + + // Tracing a ray from a position in a direction + point pos = point(0, 0, 0); // Starting position of the ray + vector dir = vector(0, 0, 1); // Direction of the ray + int hit = trace(pos, dir); // returns 1 if it hits, else 0 + +``` +### Further reading + +* [Blender Docs for OSL](https://docs.blender.org/manual/en/latest/render/shader_nodes/osl.html) +* [C4D Docs for OSL](https://docs.otoy.com/cinema4d//OpenShadingLanguageOSL.html) +* Open Shading Language on [Github](https://github.com/AcademySoftwareFoundation/OpenShadingLanguage) +* [Official OSL Documentation](https://open-shading-language.readthedocs.io/en/main/) \ No newline at end of file From 111033f74247a84067e6ea370db41c71cad9702d Mon Sep 17 00:00:00 2001 From: A1EF <18084006+A1EF@users.noreply.github.com> Date: Sun, 24 Mar 2024 14:35:08 +0300 Subject: [PATCH 045/392] Reconcile ZFS pool names for all examples and remove some garbage (#4868) --- zfs.html.markdown | 72 +++++++++++++++++++++++------------------------ 1 file changed, 36 insertions(+), 36 deletions(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index 6795b1fa..3f5a76b5 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -3,6 +3,7 @@ category: tool tool: zfs contributors: - ["sarlalian", "http://github.com/sarlalian"] + - ["A1EF", "https://github.com/A1EF"] filename: LearnZfs.txt --- @@ -25,7 +26,6 @@ RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. Types of VDEV's -* stripe (a single disk, no redundancy) * mirror (n-way mirrors supported) * raidz * raidz1 (1-disk parity, similar to RAID 5) @@ -71,7 +71,7 @@ List zpools ```bash # Create a raidz zpool -$ zpool create bucket raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 +$ zpool create zroot raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 # List ZPools $ zpool list @@ -160,22 +160,22 @@ Create datasets ```bash # Create dataset -$ zfs create tank/root/data +$ zfs create zroot/root/data $ mount | grep data -tank/root/data on /data (zfs, local, nfsv4acls) +zroot/root/data on /data (zfs, local, nfsv4acls) # Create child dataset -$ zfs create tank/root/data/stuff +$ zfs create zroot/root/data/stuff $ mount | grep data -tank/root/data on /data (zfs, local, nfsv4acls) -tank/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) +zroot/root/data on /data (zfs, local, nfsv4acls) +zroot/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) # Create Volume $ zfs create -V zroot/win_vm $ zfs list zroot/win_vm NAME USED AVAIL REFER MOUNTPOINT -tank/win_vm 4.13G 17.9G 64K - +zroot/win_vm 4.13G 17.9G 64K - ``` List datasets @@ -213,28 +213,28 @@ zroot/var/tmp@daily-2015-10-15 Rename datasets ```bash -$ zfs rename tank/root/home tank/root/old_home -$ zfs rename tank/root/new_home tank/root/home +$ zfs rename zroot/root/home zroot/root/old_home +$ zfs rename zroot/root/new_home zroot/root/home ``` Delete dataset ```bash # Datasets cannot be deleted if they have any snapshots -$ zfs destroy tank/root/home +$ zfs destroy zroot/root/home ``` Get / set properties of a dataset ```bash # Get all properties -$ zfs get all zroot/usr/home │157 # Create Volume -NAME PROPERTY VALUE SOURCE │158 $ zfs create -V zroot/win_vm -zroot/home type filesystem - │159 $ zfs list zroot/win_vm -zroot/home creation Mon Oct 20 14:44 2014 - │160 NAME USED AVAIL REFER MOUNTPOINT -zroot/home used 11.9G - │161 tank/win_vm 4.13G 17.9G 64K - -zroot/home available 94.1G - │162 ``` -zroot/home referenced 11.9G - │163 +$ zfs get all zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home type filesystem - +zroot/home creation Mon Oct 20 14:44 2014 - +zroot/home used 11.9G - +zroot/home available 94.1G - +zroot/home referenced 11.9G - zroot/home mounted yes - ... @@ -244,7 +244,7 @@ NAME PROPERTY VALUE SOURCE zroot/home compression off default # Set property on dataset -$ zfs set compression=gzip-9 mypool/lamb +$ zfs set compression=lz4 zroot/lamb # Get a set of properties from all datasets $ zfs list -o name,quota,reservation @@ -283,16 +283,16 @@ Create snapshots ```bash # Create a snapshot of a single dataset -zfs snapshot tank/home/sarlalian@now +zfs snapshot zroot/home/sarlalian@now # Create a snapshot of a dataset and its children -$ zfs snapshot -r tank/home@now +$ zfs snapshot -r zroot/home@now $ zfs list -t snapshot NAME USED AVAIL REFER MOUNTPOINT -tank/home@now 0 - 26K - -tank/home/sarlalian@now 0 - 259M - -tank/home/alice@now 0 - 156M - -tank/home/bob@now 0 - 156M - +zroot/home@now 0 - 26K - +zroot/home/sarlalian@now 0 - 259M - +zroot/home/alice@now 0 - 156M - +zroot/home/bob@now 0 - 156M - ... ``` @@ -300,10 +300,10 @@ Destroy snapshots ```bash # How to destroy a snapshot -$ zfs destroy tank/home/sarlalian@now +$ zfs destroy zroot/home/sarlalian@now # Delete a snapshot on a parent dataset and its children -$ zfs destroy -r tank/home/sarlalian@now +$ zfs destroy -r zroot/home/sarlalian@now ``` @@ -311,10 +311,10 @@ Renaming Snapshots ```bash # Rename a snapshot -$ zfs rename tank/home/sarlalian@now tank/home/sarlalian@today -$ zfs rename tank/home/sarlalian@now today +$ zfs rename zroot/home/sarlalian@now zroot/home/sarlalian@today +$ zfs rename zroot/home/sarlalian@now today -$ zfs rename -r tank/home@now @yesterday +$ zfs rename -r zroot/home@now @yesterday ``` Accessing snapshots @@ -328,26 +328,26 @@ Sending and Receiving ```bash # Backup a snapshot to a file -$ zfs send tank/home/sarlalian@now | gzip > backup_file.gz +$ zfs send zroot/home/sarlalian@now | gzip > backup_file.gz # Send a snapshot to another dataset -$ zfs send tank/home/sarlalian@now | zfs recv backups/home/sarlalian +$ zfs send zroot/home/sarlalian@now | zfs recv backups/home/sarlalian # Send a snapshot to a remote host -$ zfs send tank/home/sarlalian@now | ssh root@backup_server 'zfs recv tank/home/sarlalian' +$ zfs send zroot/home/sarlalian@now | ssh root@backup_server 'zfs recv zroot/home/sarlalian' # Send full dataset with snapshots to new host -$ zfs send -v -R tank/home@now | ssh root@backup_server 'zfs recv tank/home' +$ zfs send -v -R zroot/home@now | ssh root@backup_server 'zfs recv zroot/home' ``` Cloning Snapshots ```bash # Clone a snapshot -$ zfs clone tank/home/sarlalian@now tank/home/sarlalian_new +$ zfs clone zroot/home/sarlalian@now zroot/home/sarlalian_new # Promoting the clone so it is no longer dependent on the snapshot -$ zfs promote tank/home/sarlalian_new +$ zfs promote zroot/home/sarlalian_new ``` ### Putting it all together From 5e324773191c7539aa4c9394fe538eebc6043927 Mon Sep 17 00:00:00 2001 From: A1EF <18084006+A1EF@users.noreply.github.com> Date: Sun, 24 Mar 2024 18:33:57 +0300 Subject: [PATCH 046/392] [zfs/ru] Add russian translation for ZFS doc (#4084) --- ru-ru/zfs-ru.html.markdown | 406 +++++++++++++++++++++++++++++++++++++ 1 file changed, 406 insertions(+) create mode 100644 ru-ru/zfs-ru.html.markdown diff --git a/ru-ru/zfs-ru.html.markdown b/ru-ru/zfs-ru.html.markdown new file mode 100644 index 00000000..46a3fbb5 --- /dev/null +++ b/ru-ru/zfs-ru.html.markdown @@ -0,0 +1,406 @@ +--- +category: tool +tool: zfs +contributors: + - ["sarlalian", "http://github.com/sarlalian"] + - ["A1EF", "https://github.com/A1EF"] +filename: LearnZfs-ru.txt +translators: + - ["A1EF", "https://github.com/A1EF"] +lang: ru-ru +--- + + +[ZFS](http://open-zfs.org/wiki/Main_Page) +представляет собой переосмысление системы хранения данных, комбинирующее в едином инструменте +традиционные файловые системы и системы управления томами. ZFS обладает некоторой специфичной +терминологией, которая отличает её от более традиционных систем хранения данных, однако имеет +отличный набор возможностей, акцентированных на удобстве использования системными администраторами. + + +## Концепции ZFS + +### Виртуальные устройства + +Виртуальное устройство (VDEV) подобно устройству RAID, представляемого RAID-контроллером. +Есть несколько типов виртуальных устройств (VDEV), которые предлагают различные преимущества, +включая отказоустойчивость и скорость доступа. В основном виртуальные устройства (VDEV) +предоставляют лучшую отказоустойчивость и безопасность, нежели RAID-контроллеры. Не рекомендуется +использовать установку RAID с ZFS, поскольку ZFS рассчитывает непосредственно управлять дисками. + +Типы виртуальных устройств (VDEV) + +* mirror (поддерживается n-кратное зеркалирование) +* raidz + * raidz1 (1-диск четности, аналог RAID 5) + * raidz2 (2-диска четности, аналог RAID 6) + * raidz3 (3-диска четности, нет имеет аналогичного RAID-массива) +* disk +* file (не рекомендовано для промышленного применения из-за добавления нежелательного промежуточного слоя иной файловой системы) + +Ваши данные распределяются среди всех виртуальных устройств (VDEV), представленных в пуле хранения, +так что увеличив число виртуальных устройств (VDEV), вы увеличите количество IOPS. + +### Пулы хранения + +ZFS использует пулы хранения как абстракцию над нижним уровнем провайдера хранения (VDEV), позволяя вам отделить видимые пользователю +файловые системы от физического их размещения. + +### ZFS датасеты + +ZFS датасеты подобны традиционным файловым системам, но имеют гораздо больше возможностей, обеспечивающих обилие преимуществ ZFS. +Датасеты поддерживают [Copy on Write](https://ru.wikipedia.org/wiki/%D0%9A%D0%BE%D0%BF%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BF%D1%80%D0%B8_%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B8), снапшоты, квоты, сжатие и дедубликацию. + + +### Ограничения + +Один каталог может содержать до 2^48 файлов, каждый до 16 эксабайт. Один пул хранения может содержать до 256 зеттабайт (2^78) данных +и может быть распределён по 2^64 устройствам. А один хост может иметь 2^64 пула хранения. Лимиты огромны. + + +## Команды + +### Пулы хранения + +Действия: + +* Просмотр +* Статус +* Удаление +* Получение/установка свойств + +Просмотр пулов + +```bash +# Создание пула типа raidz +$ zpool create zroot raidz1 gpt/zfs0 gpt/zfs1 gpt/zfs2 + +# Просмотр пулов +$ zpool list +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + +# Просмотр детализованной информации о конкретном пуле +$ zpool list -v zroot +NAME SIZE ALLOC FREE EXPANDSZ FRAG CAP DEDUP HEALTH ALTROOT +zroot 141G 106G 35.2G - 43% 75% 1.00x ONLINE - + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 141G 106G 35.2G - 43% 75% +``` + +Статус пулов + +```bash +# Получение информации о статусе пулов +$ zpool status + pool: zroot + state: ONLINE + scan: scrub repaired 0 in 2h51m with 0 errors on Thu Oct 1 07:08:31 2015 +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors + +# Скрабинг пула для исправления любых ошибок +$ zpool scrub zroot +$ zpool status -v zroot + pool: zroot + state: ONLINE + scan: scrub in progress since Thu Oct 15 16:59:14 2015 + 39.1M scanned out of 106G at 1.45M/s, 20h47m to go + 0 repaired, 0.04% done +config: + + NAME STATE READ WRITE CKSUM + zroot ONLINE 0 0 0 + gptid/c92a5ccf-a5bb-11e4-a77d-001b2172c655 ONLINE 0 0 0 + +errors: No known data errors +``` + +Свойства пулов + +```bash + +# Получение свойств пула, свойства могут быть заданы пользователем или системой. +$ zpool get all zroot +NAME PROPERTY VALUE SOURCE +zroot size 141G - +zroot capacity 75% - +zroot altroot - default +zroot health ONLINE - +... + +# Установка значения свойства пула +$ zpool set comment="Storage of mah stuff" zroot +$ zpool get comment +NAME PROPERTY VALUE SOURCE +tank comment - default +zroot comment Storage of mah stuff local +``` + +Удаление пула + +```bash +$ zpool destroy test +``` + + +### Датасеты + +Действия: + +* Создание +* Просмотр +* Переименование +* Удаление +* Получение/установка свойств + +Создание датасетов + +```bash +# Создание датасета +$ zfs create zroot/root/data +$ mount | grep data +zroot/root/data on /data (zfs, local, nfsv4acls) + +# Создание дочернего датасета +$ zfs create zroot/root/data/stuff +$ mount | grep data +zroot/root/data on /data (zfs, local, nfsv4acls) +zroot/root/data/stuff on /data/stuff (zfs, local, nfsv4acls) + + +# Создание тома +$ zfs create -V zroot/win_vm +$ zfs list zroot/win_vm +NAME USED AVAIL REFER MOUNTPOINT +zroot/win_vm 4.13G 17.9G 64K - +``` + +Просмотр датасетов + +```bash +# Просмотр всех датасетов +$ zfs list +NAME USED AVAIL REFER MOUNTPOINT +zroot 106G 30.8G 144K none +zroot/ROOT 18.5G 30.8G 144K none +zroot/ROOT/10.1 8K 30.8G 9.63G / +zroot/ROOT/default 18.5G 30.8G 11.2G / +zroot/backup 5.23G 30.8G 144K none +zroot/home 288K 30.8G 144K none +... + +# Просмотр конкретного датасета +$ zfs list zroot/home +NAME USED AVAIL REFER MOUNTPOINT +zroot/home 288K 30.8G 144K none + +# Просмотр снапшотов +$ zfs list -t snapshot +zroot@daily-2015-10-15 0 - 144K - +zroot/ROOT@daily-2015-10-15 0 - 144K - +zroot/ROOT/default@daily-2015-10-15 0 - 24.2G - +zroot/tmp@daily-2015-10-15 124K - 708M - +zroot/usr@daily-2015-10-15 0 - 144K - +zroot/home@daily-2015-10-15 0 - 11.9G - +zroot/var@daily-2015-10-15 704K - 1.42G - +zroot/var/log@daily-2015-10-15 192K - 828K - +zroot/var/tmp@daily-2015-10-15 0 - 152K - +``` + +Переименование датасетов + +```bash +$ zfs rename zroot/root/home zroot/root/old_home +$ zfs rename zroot/root/new_home zroot/root/home +``` + +Удаление датасета + +```bash +# Датасеты не могут быть удалены, если у них имеются какие-то снапшоты +$ zfs destroy zroot/root/home +``` + +Получение / установка свойств датасета + +```bash +# Получение всех свойств +$ zfs get all zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home type filesystem - +zroot/home creation Mon Oct 20 14:44 2014 - +zroot/home used 11.9G - +zroot/home available 94.1G - +zroot/home referenced 11.9G - +zroot/home mounted yes - +... + +# Получения свойства для датасета +$ zfs get compression zroot/usr/home +NAME PROPERTY VALUE SOURCE +zroot/home compression off default + +# Установка значения свойства на датасете +$ zfs set compression=lz4 zroot/lamb + +# Получение значений выбранных свойств всех датасетов +$ zfs list -o name,quota,reservation +NAME QUOTA RESERV +zroot none none +zroot/ROOT none none +zroot/ROOT/default none none +zroot/tmp none none +zroot/usr none none +zroot/home none none +zroot/var none none +... +``` + + +### Снапшоты + +ZFS снапшоты -- одна из очень важных особенностей zfs + +* Место, которое они занимают, равно разнице данных между файловой системой и её снапшотом +* Время создания занимает считанные секунды +* Восстановление настолько быстро, насколько позволяет вам запись данных +* Они очень просты в автоматизации + +Действия: + +* Создание +* Удаление +* Переименование +* Получение доступа к снапшотам +* Отправка / Получение +* Клонирование + + +Создание снапшотов + +```bash +# Создание снапшота единственного датасета +zfs snapshot zroot/home/sarlalian@now + +# Создание снапшота для родительского и дочерних датасетов +$ zfs snapshot -r zroot/home@now +$ zfs list -t snapshot +NAME USED AVAIL REFER MOUNTPOINT +zroot/home@now 0 - 26K - +zroot/home/sarlalian@now 0 - 259M - +zroot/home/alice@now 0 - 156M - +zroot/home/bob@now 0 - 156M - +... +``` + +Удаление снапшотов + +```bash +# Как удалить снапшот +$ zfs destroy zroot/home/sarlalian@now + +# Удаление снапшота в родительском и дочерних датасетах +$ zfs destroy -r zroot/home/sarlalian@now + +``` + +Переименование снапшотов + +```bash +# Переименование снапшота +$ zfs rename zroot/home/sarlalian@now zroot/home/sarlalian@today +$ zfs rename zroot/home/sarlalian@now today + +$ zfs rename -r zroot/home@now @yesterday +``` + +Получение доступа к спапшотам + +```bash +# CD в каталог снапшота +$ cd /home/.zfs/snapshot/ +``` + +Отправка и получение + +```bash +# Сохранение снапшота в файл +$ zfs send zroot/home/sarlalian@now | gzip > backup_file.gz + +# Отправка снапшота в другой датасет +$ zfs send zroot/home/sarlalian@now | zfs recv backups/home/sarlalian + +# Отправка снапшота на удаленный хост +$ zfs send zroot/home/sarlalian@now | ssh root@backup_server 'zfs recv zroot/home/sarlalian' + +# Отправка полного датасета со снапшотами на новый хост +$ zfs send -v -R zroot/home@now | ssh root@backup_server 'zfs recv zroot/home' +``` + +Клонирование снапшотов + +```bash +# Клонирование снапшота +$ zfs clone zroot/home/sarlalian@now zroot/home/sarlalian_new + +# Повышение клона, чтобы он больше не зависел от снапшота +$ zfs promote zroot/home/sarlalian_new +``` + +### Собираем всё вместе + +Нижеследующий скрипт использует FreeBSD, jails и ZFS для автоматизации +подготовки чистой копии стейджинговой базы mysql с живой реплики слейв-ноды. + +```bash +#!/bin/sh + +echo "==== Остановка стейджингового сервера баз данных ====" +jail -r staging + +echo "==== Очистка существующих стейджингового сервера и снапшота ====" +zfs destroy -r zroot/jails/staging +zfs destroy zroot/jails/slave@staging + +echo "==== Фиксация базы на слейве ====" +echo "FLUSH TABLES WITH READ LOCK;" | /usr/local/bin/mysql -u root -pmyrootpassword -h slave + +echo "==== Сохранение снапшота файлов базы слейва как zroot/jails/slave@staging ====" +zfs snapshot zroot/jails/slave@staging + +echo "==== Запуск слейв-ноды сервера баз данных ====" +jail -c slave + +echo "==== Клонирование снапшота слейва на стейджинговый сервер ====" +zfs clone zroot/jails/slave@staging zroot/jails/staging + +echo "==== Установка конфига стейджингово mysql ====" +mv /jails/staging/usr/local/etc/my.cnf /jails/staging/usr/local/etc/my.cnf.slave +cp /jails/staging/usr/local/etc/my.cnf.staging /jails/staging/usr/local/etc/my.cnf + +echo "==== Настройка стейджингового файла rc.conf ====" +mv /jails/staging/etc/rc.conf.local /jails/staging/etc/rc.conf.slave +mv /jails/staging/etc/rc.conf.staging /jails/staging/etc/rc.conf.local + +echo "==== Запуск стейджингово сервера баз данных ====" +jail -c staging + +echo "==== Отключение синхронизации стейджинговой базы с мастером ====" +echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging +``` + + +### Почитать дополнительно + +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [FreeBSD Handbook on ZFS](https://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/zfs.html) +* [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) +* [Oracle's Tuning Guide](http://www.oracle.com/technetwork/articles/servers-storage-admin/sto-recommended-zfs-settings-1951715.html) +* [OpenZFS Tuning Guide](http://open-zfs.org/wiki/Performance_tuning) +* [FreeBSD ZFS Tuning Guide](https://wiki.freebsd.org/ZFSTuningGuide) From c2878077cb0b08b47506787bf719b1430e5a6b42 Mon Sep 17 00:00:00 2001 From: Kelli Rockwell Date: Mon, 1 Apr 2024 00:35:55 -0700 Subject: [PATCH 047/392] Update Go official site links from golang.org -> go.dev (#4871) --- ca-es/go-ca.html.markdown | 12 ++++++------ cs-cz/go.html.markdown | 12 ++++++------ de-de/go-de.html.markdown | 6 +++--- es-es/go-es.html.markdown | 10 +++++----- fi-fi/go-fi.html.markdown | 12 ++++++------ fr-fr/go-fr.html.markdown | 8 ++++---- go.html.markdown | 12 ++++++------ hu-hu/go-hu.html.markdown | 2 +- it-it/go-it.html.markdown | 12 ++++++------ ko-kr/go-kr.html.markdown | 6 +++--- pt-br/go-pt.html.markdown | 6 +++--- ru-ru/go-ru.html.markdown | 6 +++--- uk-ua/go-ua.html.markdown | 10 +++++----- zh-cn/go-cn.html.markdown | 8 ++++---- 14 files changed, 61 insertions(+), 61 deletions(-) diff --git a/ca-es/go-ca.html.markdown b/ca-es/go-ca.html.markdown index 591ce837..7bec4ba4 100644 --- a/ca-es/go-ca.html.markdown +++ b/ca-es/go-ca.html.markdown @@ -433,25 +433,25 @@ func requestServer() { ## Més informació L'arrel de tot en Go és la web oficial [official Go web site] -(http://golang.org/). Allà es pot seguir el tutorial, jugar interactivament +(https://go.dev/). Allà es pot seguir el tutorial, jugar interactivament i llegir molt més del que hem vist aquí.En el "tour", -[the docs](https://golang.org/doc/) conté informació sobre com escriure codi +[the docs](https://go.dev/doc/) conté informació sobre com escriure codi net i efectiu en Go, comandes per empaquetar i generar documentació, i història de les versions. És altament recomanable llegir La definició del llenguatge. És fàcil de llegir i sorprenentment curta (com la definició del llenguatge en aquests dies). -Es pot jugar amb codi a [Go playground](https://play.golang.org/p/tnWMjr16Mm). +Es pot jugar amb codi a [Go playground](https://go.dev/play/p/tnWMjr16Mm). Prova de fer canvis en el codi i executar-lo des del navegador! Es pot fer -servir [https://play.golang.org](https://play.golang.org) com a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per provar coses i codi +servir [https://go.dev/play/](https://go.dev/play/) com a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per provar coses i codi en el navegador sense haver d'instal·lar Go. En la llista de lectures pels estudiants de Go hi ha -[el codi font de la llibreria estàndard](http://golang.org/src/pkg/). +[el codi font de la llibreria estàndard](https://go.dev/src/). Ampliament comentada, que demostra el fàcil que és de llegir i entendre els programes en Go, l'estil de programació, i les formes de treballar-hi. O es -pot clicar en un nom de funció en [la documentació](http://golang.org/pkg/) +pot clicar en un nom de funció en [la documentació](https://go.dev/pkg/) i veure'n el codi! Un altre gran recurs per aprendre Go és diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown index 4f8569bf..18880a3b 100644 --- a/cs-cz/go.html.markdown +++ b/cs-cz/go.html.markdown @@ -408,20 +408,20 @@ func requestServer() { ## Kam dále -Vše hlavní o Go se nachází na [oficiálních stránkách go](http://golang.org/). +Vše hlavní o Go se nachází na [oficiálních stránkách go](https://go.dev/). Tam najdete tutoriály, interaktivní konzolu a mnoho materiálu ke čtení. -Kromě úvodu, [dokumenty](https://golang.org/doc/) tam obsahují jak psát čistý kód v Go +Kromě úvodu, [dokumenty](https://go.dev/doc/) tam obsahují jak psát čistý kód v Go popis balíčků (package), dokumentaci příkazové řádky a historii releasů. Také doporučujeme přečíst si definici jazyka. Je čtivá a překvapivě krátká. Tedy alespoň proti jiným současným jazyků. -Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://play.golang.org/p/r46YvCu-XX). -Můžete tam spouštět programy s prohlížeče. Také můžete [https://play.golang.org](https://play.golang.org) použít jako +Pokud si chcete pohrát s Go, tak navštivte [hřiště Go](https://go.dev/play/p/r46YvCu-XX). +Můžete tam spouštět programy s prohlížeče. Také můžete [https://go.dev/play/](https://go.dev/play/) použít jako [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop), kde si v rychlosti vyzkoušíte věci, bez instalace Go. -Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](http://golang.org/src/pkg/). -Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](http://golang.org/pkg/) +Na vašem knižním seznamu, by neměly chybět [zdrojáky stadardní knihovny](https://go.dev/src/). +Důkladně popisuje a dokumentuje Go, styl zápisu Go a Go idiomy. Pokud kliknete na [dokumentaci](https://go.dev/pkg/) tak se podíváte na dokumentaci. Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/). diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 30a660fa..1b09a1e1 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -308,13 +308,13 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ``` ## Weitere Resourcen -Informationen zu Go findet man auf der [offiziellen Go Webseite](http://golang.org/). +Informationen zu Go findet man auf der [offiziellen Go Webseite](https://go.dev/). Dort gibt es unter anderem ein Tutorial und interaktive Quelltext-Beispiele, vor allem aber Dokumentation zur Sprache und den Paketen. Auch zu empfehlen ist die Spezifikation von Go, die nach heutigen Standards sehr kurz und gut verständlich formuliert ist. Auf der Leseliste von Go-Neulingen -ist außerdem der Quelltext der [Go standard Bibliothek](http://golang.org/src/pkg/) +ist außerdem der Quelltext der [Go standard Bibliothek](https://go.dev/src/) einzusehen. Dieser kann als Referenz für leicht zu verstehendes und im idiomatischen Stil verfasstes Go dienen. Erreichbar ist der Quelltext auch durch das Klicken der Funktionsnamen -in der [offiziellen Dokumentation von Go](http://golang.org/pkg/). +in der [offiziellen Dokumentation von Go](https://go.dev/pkg/). diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 2d1dbce7..17bf4a22 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -425,7 +425,7 @@ func consultaAlServidor() { ## Más información La raíz de todas las cosas sobre Go es el -[sitio web oficial de Go](http://golang.org/). +[sitio web oficial de Go](https://go.dev/). Allí puedes seguir el tutorial, jugar interactivamente y leer mucho más. La definición del lenguaje es altamente recomendada. Es fácil de leer y @@ -433,17 +433,17 @@ sorprendentemente corta (como la definición del lenguaje Go en estos días). Puedes jugar con el código en el -[parque de diversiones Go](https://play.golang.org/p/ncRC2Zevag). ¡Trata +[parque de diversiones Go](https://go.dev/play/p/ncRC2Zevag). ¡Trata de cambiarlo y ejecutarlo desde tu navegador! Ten en cuenta que puedes -utilizar [https://play.golang.org]( https://play.golang.org) como un +utilizar [https://go.dev/play/]( https://go.dev/play/) como un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) para probar cosas y el código en el navegador, sin ni siquiera instalar Go. En la lista de lecturas para estudiantes de Go está el -[código fuente de la biblioteca estándar](http://golang.org/src/pkg/). +[código fuente de la biblioteca estándar](https://go.dev/src/). Ampliamente documentado, que demuestra lo mejor del legible y comprensible Go, con su característico estilo y modismos. ¡O puedes hacer clic en un -nombre de función en [la documentación](http://golang.org/pkg/) y +nombre de función en [la documentación](https://go.dev/pkg/) y aparecerá el código fuente! Otro gran recurso para aprender Go está en diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index a7337250..ef88a96e 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -418,21 +418,21 @@ func requestServer() { ## Lisää luettavaa -Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(http://golang.org/). +Go-tietämyksen alku ja juuri on sen [virallinen verkkosivu]()(https://go.dev/). Siellä voit seurata oppitunteja, askarrella vuorovaikutteisesti sekä lukea paljon. -Kierroksen lisäksi [dokumentaatio](https://golang.org/doc/) pitää sisällään tietoa +Kierroksen lisäksi [dokumentaatio](https://go.dev/doc/) pitää sisällään tietoa siistin Go-koodin kirjoittamisesta, pakettien ja komentojen käytöstä sekä julkaisuhistoriasta. Kielen määritelmä itsessään on suuresti suositeltavissa. Se on helppolukuinen ja yllättävän lyhyt (niissä määrin kuin kielimääritelmät nykypäivänä ovat.) -Voit askarrella parissa kanssa [Go playgroundissa](https://play.golang.org/p/tnWMjr16Mm). -Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://play.golang.org](https://play.golang.org) +Voit askarrella parissa kanssa [Go playgroundissa](https://go.dev/play/p/tnWMjr16Mm). +Muuttele sitä ja aja se selaimestasi! Huomaa, että voit käyttää [https://go.dev/play/](https://go.dev/play/) [REPL:na](https://en.wikipedia.org/wiki/Read-eval-print_loop) testataksesi ja koodataksesi selaimessasi, ilman Go:n asentamista. -Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](http://golang.org/src/pkg/). +Go:n opiskelijoiden lukulistalla on [oletuskirjaston lähdekoodi](https://go.dev/src/). Kattavasti dokumentoituna se antaa parhaan kuvan helppolukuisesta ja ymmärrettävästä Go-koodista, --tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](http://golang.org/pkg/) ja +-tyylistä ja -tavoista. Voit klikata funktion nimeä [doukumentaatiossa](https://go.dev/pkg/) ja lähdekoodi tulee esille! Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/). diff --git a/fr-fr/go-fr.html.markdown b/fr-fr/go-fr.html.markdown index a002acfc..5468096a 100644 --- a/fr-fr/go-fr.html.markdown +++ b/fr-fr/go-fr.html.markdown @@ -422,18 +422,18 @@ func requestServer() { ## En savoir plus -La référence Go se trouve sur [le site officiel de Go](http://golang.org/). +La référence Go se trouve sur [le site officiel de Go](https://go.dev/). Vous pourrez y suivre le tutoriel interactif et en apprendre beaucoup plus. Une lecture de la documentation du langage est grandement conseillée. C'est facile à lire et très court (comparé aux autres langages). -Vous pouvez exécuter et modifier le code sur [Go playground](https://play.golang.org/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://play.golang.org](https://play.golang.org) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. +Vous pouvez exécuter et modifier le code sur [Go playground](https://go.dev/play/p/tnWMjr16Mm). Essayez de le modifier et de l'exécuter à partir de votre navigateur! Prennez en note que vous pouvez utiliser [https://go.dev/play/](https://go.dev/play/) comme un [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) pour tester et coder dans votre navigateur, sans même avoir à installer Go. Sur la liste de lecteur des étudiants de Go se trouve le [code source de la -librairie standard](http://golang.org/src/pkg/). Bien documentée, elle démontre +librairie standard](https://go.dev/src/). Bien documentée, elle démontre le meilleur de la clarté de Go, le style ainsi que ses expressions. Sinon, vous pouvez cliquer sur le nom d'une fonction dans [la -documentation](http://golang.org/pkg/) et le code source apparaît! +documentation](https://go.dev/pkg/) et le code source apparaît! Une autre excellente ressource pour apprendre est [Go par l'exemple](https://gobyexample.com/). diff --git a/go.html.markdown b/go.html.markdown index 0631ffab..59ba2e4f 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -456,21 +456,21 @@ func requestServer() { ## Further Reading -The root of all things Go is the [official Go web site](http://golang.org/). +The root of all things Go is the [official Go web site](https://go.dev/). There you can follow the tutorial, play interactively, and read lots. -Aside from a tour, [the docs](https://golang.org/doc/) contain information on +Aside from a tour, [the docs](https://go.dev/doc/) contain information on how to write clean and effective Go code, package and command docs, and release history. -The [Go language specification](https://golang.org/ref/spec) itself is highly recommended. It's easy to read +The [Go language specification](https://go.dev/ref/spec) itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) -You can play around with the code on [Go playground](https://play.golang.org/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://play.golang.org](https://play.golang.org) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. +You can play around with the code on [Go playground](https://go.dev/play/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://go.dev/play/](https://go.dev/play/) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. On the reading list for students of Go is the [source code to the standard -library](http://golang.org/src/pkg/). Comprehensively documented, it +library](https://go.dev/src/). Comprehensively documented, it demonstrates the best of readable and understandable Go, Go style, and Go idioms. Or you can click on a function name in [the -documentation](http://golang.org/pkg/) and the source code comes up! +documentation](https://go.dev/pkg/) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). diff --git a/hu-hu/go-hu.html.markdown b/hu-hu/go-hu.html.markdown index 1a96b8c3..451f9147 100644 --- a/hu-hu/go-hu.html.markdown +++ b/hu-hu/go-hu.html.markdown @@ -325,7 +325,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## További olvasmányok -Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](http://golang.org/). +Minden Go-val kapcsolatos megtaláható a [hivatalos Go weboldalon](https://go.dev/). Ott követhetsz egy tutorialt, játszhatsz a nyelvvel az interneten, és sok érdekességet olvashatsz. A nyelv specifikációját kifejezetten érdemes olvasni, viszonylag rövid és sokat tanul belőle az ember. diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index d88e8741..6f974c91 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -422,9 +422,9 @@ func richiediServer() { ## Letture consigliate -La risorsa più importante per imparare il Go è il [sito ufficiale di Go](http://golang.org/). +La risorsa più importante per imparare il Go è il [sito ufficiale di Go](https://go.dev/). Qui puoi seguire i tutorial, scrivere codice in modo interattivo, e leggere tutti i dettagli. -Oltre al tour, [la documentazione](https://golang.org/doc/) contiene informazioni su +Oltre al tour, [la documentazione](https://go.dev/doc/) contiene informazioni su come scrivere ottimo codice in Go, documentazione sui package e sui comandi, e la cronologia delle release. @@ -432,17 +432,17 @@ Anche il documento che definisce il linguaggio è un'ottima lettura. E' semplice da leggere e incredibilmente corto (rispetto ad altri documenti riguardanti la creazione di linguaggi). -Puoi giocare con il codice visto finora nel [Go playground](https://play.golang.org/p/Am120Xe7qf). +Puoi giocare con il codice visto finora nel [Go playground](https://go.dev/play/p/Am120Xe7qf). Prova a cambiarlo e ad eseguirlo dal browser! -Osserva che puoi usare [https://play.golang.org](https://play.golang.org) come +Osserva che puoi usare [https://go.dev/play/](https://go.dev/play/) come una [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) per scrivere codice all'interno del browser, senza neanche installare Go! Una lettura importante per capire Go in modo più profondo è il [codice -sorgente della libreria standard](http://golang.org/src/pkg/). Infatti è +sorgente della libreria standard](https://go.dev/src/). Infatti è molto ben documentato e costituisce quanto più chiaro e conciso ci sia riguardo gli idiomi e le buone pratiche del Go. Inoltre, clickando sul nome di una -funzione [nella documentazione](http://golang.org/pkg/) compare il relativo +funzione [nella documentazione](https://go.dev/pkg/) compare il relativo codice sorgente! Un'altra ottima risorsa per imparare è [Go by example](https://gobyexample.com/). diff --git a/ko-kr/go-kr.html.markdown b/ko-kr/go-kr.html.markdown index 42360294..aed0918e 100644 --- a/ko-kr/go-kr.html.markdown +++ b/ko-kr/go-kr.html.markdown @@ -332,15 +332,15 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## 더 읽어볼 것들 -Go에 대한 모든 것들은 [Go 공식 웹 사이트](http://golang.org/)를 참고하자. +Go에 대한 모든 것들은 [Go 공식 웹 사이트](https://go.dev/)를 참고하자. 여기에는 따라해볼 튜토리얼, 웹 기반의 인터랙티브 실행환경과 많은 읽을거리들이 있다. Go 언어 자체에 대한 스펙도 읽어보기를 적극 추천한다. 읽기 쉽게 되어있고 그리 길지는 않다. -Go 소스코드에 대해 좀더 알아보고 싶다면 [Go 표준 라이브러리](http://golang.org/src/pkg/)를 +Go 소스코드에 대해 좀더 알아보고 싶다면 [Go 표준 라이브러리](https://go.dev/src/)를 분석해보기 바란다. 이해하기 쉽게 문서화되어 있고, Go 스타일 그리고 Go에서의 -관례 배우기에 가장 좋은 방법일 것이다. 또는 [문서](http://golang.org/pkg/) 안에서 +관례 배우기에 가장 좋은 방법일 것이다. 또는 [문서](https://go.dev/pkg/) 안에서 함수 이름 하나를 클릭해보면 소스코드를 브라우저에서 살펴볼 수도 있다. Go를 배울수 있는 또하나의 좋은 방법은 [Go by example](https://gobyexample.com/). diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index 60b3a472..ce10e079 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -295,17 +295,17 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { ## Leitura Recomendada -A principal fonte de informação é o [web site oficial Go](http://golang.org/). +A principal fonte de informação é o [web site oficial Go](https://go.dev/). Lá é possível seguir o tutorial, experimentar de forma iterativa, e ler muito. A própria especificação da linguagem é altamente recomendada. É fácil de ler e incrivelmente curta (em relação ao que é habitual hoje em dia). Na lista de leitura para os aprendizes de Go deve constar o [código fonte da -biblioteca padrão](http://golang.org/src/pkg/). Exaustivamente documentado, é +biblioteca padrão](https://go.dev/src/). Exaustivamente documentado, é a melhor demonstração de código fácil de ler e de perceber, do estilo Go, e da sua escrita idiomática. Ou então clique no nome de uma função na [documentação] -(http://golang.org/pkg/) e veja o código fonte aparecer! +(https://go.dev/pkg/) e veja o código fonte aparecer! Outra ótima fonte para aprender Go é o [Go by example](https://gobyexample.com/). Apesar de ser em inglês, é possível recodificar os exemplos para aprender sobre diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 40b32816..22249a6e 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -334,12 +334,12 @@ func requestServer() { ## Что дальше -Основа всех основ в Go это [официальный веб сайт](http://golang.org/). +Основа всех основ в Go это [официальный веб сайт](https://go.dev/). Там можно пройти туториал, поиграться с интерактивной средой Go и почитать объёмную документацию. Для живого ознакомления рекомендуется почитать исходные коды [стандартной -библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она +библиотеки Go](https://go.dev/src/). Отлично задокументированная, она является лучшим источником для чтения и понимания Go, его стиля и идиом. Либо -можно, кликнув на имени функции в [документации](http://golang.org/pkg/), +можно, кликнув на имени функции в [документации](https://go.dev/pkg/), перейти к ее исходным кодам. diff --git a/uk-ua/go-ua.html.markdown b/uk-ua/go-ua.html.markdown index f980f7b1..6f294b1f 100644 --- a/uk-ua/go-ua.html.markdown +++ b/uk-ua/go-ua.html.markdown @@ -434,15 +434,15 @@ func requestServer() { ## Подальше вивчення -Основним джерелом всієї інформації про Go залишається [офіційна веб-сторінка](http://golang.org/). Там можна знайти уроки, інтерактивно пограти та багато про що почитати. -Окрім туру, у [документації](https://golang.org/doc/) міститься інформація як писати чистий та ефективний код на Go, документація пакетів та окремих команд, а також історія релізів. +Основним джерелом всієї інформації про Go залишається [офіційна веб-сторінка](https://go.dev/). Там можна знайти уроки, інтерактивно пограти та багато про що почитати. +Окрім туру, у [документації](https://go.dev/doc/) міститься інформація як писати чистий та ефективний код на Go, документація пакетів та окремих команд, а також історія релізів. Надзвичайно рекомендується ознайомитись із визначенням мови. Вона легко читається та на диво коротка (в порівнянні з іншими сучасними мовами). -Можна погратись з кодом вище на [Go playground](https://play.golang.org/p/tnWMjr16Mm). Спробуй змінити його та запустити із свого браузера. Поміть, що можна використовувати [https://play.golang.org](https://play.golang.org) як [REPL](https://uk.wikipedia.org/wiki/REPL) до тестів та коду в твоєму браузері, без встановлення Go. +Можна погратись з кодом вище на [Go playground](https://go.dev/play/p/tnWMjr16Mm). Спробуй змінити його та запустити із свого браузера. Поміть, що можна використовувати [https://go.dev/play/](https://go.dev/play/) як [REPL](https://uk.wikipedia.org/wiki/REPL) до тестів та коду в твоєму браузері, без встановлення Go. -В списку для прочитання новачкам в Go - [вихідний код стандартної бібліотеки](http://golang.org/src/pkg/). Код всеосяжно задокоментований, тому є найкращим прикладом з боку зручного для прочитання та швидкості розуміння коду на цій мові програмування. Приведений стиль та ідіоми Go. -Крім того, можна просто натиснути на назву функції в [документації](http://golang.org/pkg/), щоб перейти до її реалізації. +В списку для прочитання новачкам в Go - [вихідний код стандартної бібліотеки](https://go.dev/src/). Код всеосяжно задокоментований, тому є найкращим прикладом з боку зручного для прочитання та швидкості розуміння коду на цій мові програмування. Приведений стиль та ідіоми Go. +Крім того, можна просто натиснути на назву функції в [документації](https://go.dev/pkg/), щоб перейти до її реалізації. Іншим прекрасним посиланням для вивчення Go є [Go by example](https://gobyexample.com/). diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index 8afacf2a..a2b71761 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -392,15 +392,15 @@ func requestServer() { ## 更进一步 -关于Go的一切你都可以在[Go官方网站](http://golang.org/)找到。 +关于Go的一切你都可以在[Go官方网站](https://go.dev/)找到。 在那里你可以获得教程参考,在线试用,和更多的资料。 -在简单的尝试过后,在[官方文档](https://golang.org/doc/)那里你会得到你所需要的所有资料、关于编写代码的规范、库和命令行工具的文档与Go的版本历史。 +在简单的尝试过后,在[官方文档](https://go.dev/doc/)那里你会得到你所需要的所有资料、关于编写代码的规范、库和命令行工具的文档与Go的版本历史。 强烈推荐阅读语言定义部分,很简单而且很简洁!(赶时髦!) -你还可以前往[Go在线体验中心](https://play.golang.org/p/tnWMjr16Mm)进,在浏览器里修改并运行这些代码,一定要试一试哦!你可以将[https://play.golang.org](https://play.golang.org)当作一个[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop),在那里体验语言特性或运行自己的代码,连环境都不用配! +你还可以前往[Go在线体验中心](https://go.dev/play/p/tnWMjr16Mm)进,在浏览器里修改并运行这些代码,一定要试一试哦!你可以将[https://go.dev/play/](https://go.dev/play/)当作一个[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop),在那里体验语言特性或运行自己的代码,连环境都不用配! -学习Go还要阅读Go[标准库的源代码](http://golang.org/src/),全部文档化了,可读性非常好,可以学到go,go style和go idioms。在[文档](http://golang.org/pkg/)中点击函数名,源代码就出来了! +学习Go还要阅读Go[标准库的源代码](https://go.dev/src/),全部文档化了,可读性非常好,可以学到go,go style和go idioms。在[文档](https://go.dev/pkg/)中点击函数名,源代码就出来了! [Go by example](https://gobyexample.com/)也是一个学习的好地方。 From f9e182b42b3d90a08fa4808b7467d78acf0cd6c2 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 1 Apr 2024 22:02:50 -0700 Subject: [PATCH 048/392] Mark Zig code as zig --- zig.html.markdown | 135 +++++++++++++++++++++++----------------------- 1 file changed, 68 insertions(+), 67 deletions(-) diff --git a/zig.html.markdown b/zig.html.markdown index f8c866e5..65fd1e6b 100644 --- a/zig.html.markdown +++ b/zig.html.markdown @@ -5,24 +5,19 @@ contributors: - ["Philippe Pittoli", "https://karchnu.fr/"] --- - [Zig][ziglang] aims to be a replacement for the C programming language. **WARNING**: this document expects you to understand a few basic concepts in computer science, such as pointers, stack and heap memory, etc. **WARNING**: Zig isn't considered as ready for production. Bugs are expected. -DO NOT TRY ZIG AS YOUR FIRST PROGRAMMING EXPERIENCE. -The compiler, even the language and its libraries aren't ready, yet. -You've been warned. Prior knowledge of C is recommended. - ## Quick overview: Zig compared to C - Syntax is mostly the same, with some improvements (less ambiguity). - Zig introduces namespaces. -- Try and catch mechanism, which is both convenient, efficient and optional. +- `try` and `catch` mechanism, which is both convenient, efficient and optional. - Most of the C undefined behaviors (UBs) are fixed. - Compared to C, raw pointers are safer to use and less likely to be needed. * The type system distinguishes between a pointer to a single value, or multiple values, etc. @@ -38,8 +33,7 @@ Prior knowledge of C is recommended. ## Zig language - -``` +```zig //! Top-level documentation. /// Documentation comment. @@ -47,9 +41,9 @@ Prior knowledge of C is recommended. // Simple comment. ``` - ### Hello world. -``` + +```zig // Import standard library, reachable through the "std" constant. const std = @import("std"); @@ -67,7 +61,8 @@ pub fn main() void { ``` ### Booleans, integers and float. -``` + +```zig // Booleans. // Keywords are preferred to operators for boolean operations. print("{}\n{}\n{}\n", .{ @@ -109,7 +104,8 @@ i <<| 8 == 255 // u8: won't go higher than 255 ``` ### Arrays. -``` + +```zig // An array is a well-defined structure with a length attribute (len). // 5-byte array with undefined content (stack garbage). @@ -156,8 +152,8 @@ try some_integers[i]; // Runtime error 'index out of bounds'. ``` ### Multidimensional arrays. -``` +```zig const mat4x4 = [4][4]f32{ [_]f32{ 1.0, 0.0, 0.0, 0.0 }, [_]f32{ 0.0, 1.0, 0.0, 1.0 }, @@ -177,8 +173,8 @@ for (mat4x4) |row, row_index| { ``` ### Strings. -``` +```zig // Simple string constant. const greetings = "hello"; // ... which is equivalent to: @@ -195,8 +191,8 @@ print("string: {s}\n", .{greetings}); ``` ### Slices. -``` +```zig // A slice is a pointer and a size, an array without compile-time known size. // Slices have runtime out-of-band verifications. @@ -206,8 +202,8 @@ const slice = array[0..array.len]; // "slice" represents the whole array. ``` ### Pointers. -``` +```zig // Pointer on a value can be created with "&". const x: i32 = 1; const pointer: *i32 = &x; // "pointer" is a pointer on the i32 var "x". @@ -223,7 +219,8 @@ const foo = pointer.?; // Get the pointed value, otherwise crash. ``` ### Optional values (?). -``` + +```zig // An optional is a value than can be of any type or null. // Example: "optional_value" can either be "null" or an unsigned 32-bit integer. @@ -239,7 +236,8 @@ if (x) |value| { ``` ### Errors. -``` + +```zig // Zig provides an unified way to express errors. // Errors are defined in error enumerations, example: @@ -299,7 +297,7 @@ var value = try some_function(); ### Control flow. -``` +```zig // Conditional branching. if (condition) { @@ -384,8 +382,8 @@ const result = for (items) |value| { ``` ### Labels. -``` +```zig // Labels are a way to name an instruction, a location in the code. // Labels can be used to "continue" or "break" in a nested loop. outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| { @@ -434,8 +432,8 @@ const result = for (items) |value| { // First: loop. ``` ### Switch. -``` +```zig // As a switch in C, but slightly more advanced. // Syntax: // switch (value) { @@ -454,15 +452,15 @@ var x = switch(value) { // A slightly more advanced switch, accepting a range of values: const foo: i32 = 0; const bar = switch (foo) { - 0 => "zero", - 1...std.math.maxInt(i32) => "positive", - else => "negative", + 0 => "zero", + 1...std.math.maxInt(i32) => "positive", + else => "negative", }; ``` ### Structures. -``` +```zig // Structure containing a single value. const Full = struct { number: u16, @@ -564,7 +562,8 @@ print("p.y: {}\n", .{p.y}); // 30 ``` ### Tuples. -``` + +```zig // A tuple is a list of elements, possibly of different types. const foo = .{ "hello", true, 42 }; @@ -572,33 +571,33 @@ const foo = .{ "hello", true, 42 }; ``` ### Enumerations. -``` +```zig const Type = enum { ok, not_ok }; const CardinalDirections = enum { North, South, East, West }; const direction: CardinalDirections = .North; const x = switch (direction) { - // shorthand for CardinalDirections.North - .North => true, - else => false + // shorthand for CardinalDirections.North + .North => true, + else => false }; // Switch statements need exhaustiveness. // WARNING: won't compile. East and West are missing. const x = switch (direction) { - .North => true, - .South => true, + .North => true, + .South => true, }; // Switch statements need exhaustiveness. // Won't compile: East and West are missing. const x = switch (direction) { - .North => true, - .South => true, - .East, // Its value is the same as the following pattern: false. - .West => false, + .North => true, + .South => true, + .East, // Its value is the same as the following pattern: false. + .West => false, }; @@ -606,12 +605,12 @@ const x = switch (direction) { ``` ### Unions. -``` +```zig const Bar = union { - boolean: bool, - int: i16, - float: f32, + boolean: bool, + int: i16, + float: f32, }; // Both syntaxes are equivalent. @@ -622,8 +621,8 @@ const foo: Bar = .{ .int = 42 }; ``` ### Tagged unions. -``` +```zig // Unions can be declared with an enum tag type, allowing them to be used in // switch expressions. @@ -653,8 +652,8 @@ switch (nay) { ``` ### Defer and errdefer. -``` +```zig // Make sure that an action (single instruction or block of code) is executed // before the end of the scope (function, block of code). // Even on error, that action will be executed. @@ -695,24 +694,25 @@ Thus, the standard library lets developers handle memory as they need, through s **NOTE**: the choice of the allocator isn't in the scope of this document. A whole book could be written about it. However, here are some examples, to get an idea of what you can expect: -- page_allocator. +- `page_allocator`. Allocate a whole page of memory each time we ask for some memory. Very simple, very dumb, very wasteful. -- GeneralPurposeAllocator. +- `GeneralPurposeAllocator`. Get some memory first and manage some buckets of memory in order to reduce the number of allocations. A bit complex. Can be combined with other allocators. Can detect leaks and provide useful information to find them. -- FixedBufferAllocator. +- `FixedBufferAllocator`. Use a fixed buffer to get its memory, don't ask memory to the kernel. Very simple, limited and wasteful (can't deallocate), but very fast. -- ArenaAllocator. +- `ArenaAllocator`. Allow to free all allocated memory at once. To use in combinations with another allocator. Very simple way of avoiding leaks. A first example. -``` + +```zig // "!void" means the function doesn't return any value except for errors. // In this case we try to allocate memory, and this may fail. fn foo() !void { @@ -735,8 +735,8 @@ fn foo() !void { ``` ### Memory allocation combined with error management and defer. -``` +```zig fn some_memory_allocation_example() !void { // Memory allocation may fail, so we "try" to allocate the memory and // in case there is an error, the current function returns it. @@ -759,8 +759,8 @@ fn some_memory_allocation_example() !void { ``` ### Memory allocators: a taste of the standard library. -``` +```zig // Allocators: 4 main functions to know // single_value = create (type) // destroy (single_value) @@ -846,8 +846,8 @@ fn gpa_arena_allocator_fn() !void { ``` ### Comptime. -``` +```zig // Comptime is a way to avoid the pre-processor. // The idea is simple: run code at compilation. @@ -883,7 +883,8 @@ list.items[0] = 10; ``` ### Conditional compilation. -``` + +```zig const available_os = enum { OpenBSD, Linux }; const myos = available_os.OpenBSD; @@ -905,7 +906,8 @@ const myprint = switch(myos) { ``` ### Testing our functions. -``` + +```zig const std = @import("std"); const expect = std.testing.expect; @@ -936,45 +938,44 @@ There are more than a hundred built-ins, allowing very low-level stuff: - etc. Example: enums aren't integers, they have to be converted with a built-in. -``` + +```zig const Value = enum { zero, stuff, blah }; if (@enumToInt(Value.zero) == 0) { ... } if (@enumToInt(Value.stuff) == 1) { ... } if (@enumToInt(Value.blah) == 2) { ... } ``` - ### A few "not yourself in the foot" measures in the Zig language. -- Namespaces: names conflicts are easily avoided. - In practice, that means an unified API between different structures (data types). +- Namespaces: name conflicts are easily avoided. + In practice, that means a unified API between different structures (data types). - Enumerations aren't integers. Comparing an enumeration to an integer requires a conversion. - Explicit casts, coercion exists but is limited. Types are slightly more enforced than in C, just a taste: Pointers aren't integers, explicit conversion is necessary. - You won't lose precision by accident, implicit coercions are only authorized in case no precision can be lost. - Unions cannot be reinterpreted (in an union with an integer and a float, one cannot take a value for another by accident). + You won't lose precision by accident, implicit coercions are only authorized in cases where no precision can be lost. + Unions cannot be reinterpreted (in a union with an integer and a float, one cannot take a value for another by accident). Etc. - Removing most of the C undefined behaviors (UBs), and when the compiler encounters one, it stops. - Slice and Array structures are preferred to pointers. Types enforced by the compiler are less prone to errors than pointer manipulations. - Numerical overflows produce an error, unless explicitly accepted using wrapping operators. -- Try and catch mechanism. +- `try` and `catch` mechanism. It's both handy, trivially implemented (simple error enumeration), and it takes almost no space nor computation time. -- Unused variables are considered as errors by the compiler. -- Many pointer types exist in order to represent what is pointed. +- Unused variables are considered to be errors by the compiler. +- Many pointer types exist in order to represent what is pointed to. Example: is this a single value or an array, is the length known, etc. -- Structures need a value for their attributes, and it still is possible to give an undefined value (stack garbage), but at least it is explicitly undefined. +- Structures need a value for their attributes, and it is still possible to give an undefined value (stack garbage), but at least it is explicitly undefined. ## Further Reading -For a start, some concepts are presented on the [Zig learn website][ziglearn]. +For a start, some concepts are presented on [zig.guide][zigguide]. -The [official website][zigdoc] provides a reference documentation to the language. - -For now, documentation for standard library is WIP. +The [official website][zigdoc] provides the reference documentation of the language. The standard library [has its own documentation][zigstd]. [ziglang]: https://ziglang.org -[ziglearn]: https://ziglearn.org/ +[zigguide]: https://zig.guide/ [zigdoc]: https://ziglang.org/documentation/ +[zigstd]: https://ziglang.org/documentation/master/std/ From 6fdb6315e50396001cac9a14fcf3b3266de171e2 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 2 Apr 2024 17:46:08 -0700 Subject: [PATCH 049/392] Fix a few broken files --- ada.html.markdown | 8 +- es-es/{css-es.html => css-es.html.markdown} | 0 ...ml.markdown.tex => latex-sk.html.markdown} | 0 sk-sk/learn-latex-sk.tex | 209 ------------------ 4 files changed, 4 insertions(+), 213 deletions(-) rename es-es/{css-es.html => css-es.html.markdown} (100%) rename sk-sk/{latex-sk.html.markdown.tex => latex-sk.html.markdown} (100%) delete mode 100644 sk-sk/learn-latex-sk.tex diff --git a/ada.html.markdown b/ada.html.markdown index a06792b3..7191c5dc 100644 --- a/ada.html.markdown +++ b/ada.html.markdown @@ -2,10 +2,10 @@ language: Ada filename: learn.ada contributors: - ["Luke A. Guest", "https://github.com/Lucretia"] - ["Fernando Oleo Blanco", "https://github.com/Irvise"] - ["Fabien Chouteau", "https://github.com/Fabien-Chouteau"] - ["Manuel", "https://github.com/mgrojo"] + - ["Luke A. Guest", "https://github.com/Lucretia"] + - ["Fernando Oleo Blanco", "https://github.com/Irvise"] + - ["Fabien Chouteau", "https://github.com/Fabien-Chouteau"] + - ["Manuel", "https://github.com/mgrojo"] --- Ada is a strong statically typed imperative, [object-oriented](https://ada-lang.io/docs/arm/AA-3/AA-3.9), [real-time](https://ada-lang.io/docs/arm/AA-D), [parallel](https://ada-lang.io/docs/arm/AA-9) and [distributed](https://ada-lang.io/docs/arm/AA-9) programming language from the Pascal/Algol family of languages, but nowadays, it only has a passing resemblance to Pascal, with the only remnants left being the ```begin/end``` keyword pair, the ```:=``` assignment symbol, records and ```if/case``` control statement structures. diff --git a/es-es/css-es.html b/es-es/css-es.html.markdown similarity index 100% rename from es-es/css-es.html rename to es-es/css-es.html.markdown diff --git a/sk-sk/latex-sk.html.markdown.tex b/sk-sk/latex-sk.html.markdown similarity index 100% rename from sk-sk/latex-sk.html.markdown.tex rename to sk-sk/latex-sk.html.markdown diff --git a/sk-sk/learn-latex-sk.tex b/sk-sk/learn-latex-sk.tex deleted file mode 100644 index 5cc7b11f..00000000 --- a/sk-sk/learn-latex-sk.tex +++ /dev/null @@ -1,209 +0,0 @@ -% Všetky komentáre začínajú s % -% Viac-riadkové komentáre sa nedajú urobiť - -% LaTeX NIE JE WYSIWY ("What You See Is What You Get") software ako MS Word, alebo OpenOffice Writer - -% Každý LaTeX príkaz začína s opačným lomítkom (\) - -% LaTeX dokumenty začínajú s definíciou typu kompilovaného dokumentu -% Ostatné typy sú napríklad kniha (book), správa (report), prezentácia (presentation), atď. -% Možnosti dokumentu sa píšu do [] zátvoriek. V tomto prípade tam upresňujeme veľkosť (12pt) fontu. -\documentclass[12pt]{article} - -% Ďalej definujeme balíčky, ktoré dokuemnt používa. -% Ak chceš zahrnúť grafiku, farebný text, či zdrojový kód iného jazyka, musíš rozšíriť možnosti LaTeXu dodatočnými balíčkami. -% Zahŕňam float a caption. Na podporu slovenčiny treba zahrnúť aj utf8 balíček. -\usepackage{caption} -\usepackage{float} -\usepackage[utf8]{inputenc} -% Tu môžme definovať ostatné vlastnosti dokumentu! -% Autori tohto dokumentu, "\\*" znamená "choď na nový riadok" -\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu, \\*Preklad: Terka Slanináková} -% Vygeneruje dnešný dátum -\date{\today} -\title{Nauč sa LaTeX za Y Minút!} -% Teraz môžme začať pracovať na samotnom dokumente. -% Všetko do tohto riadku sa nazýva "Preambula" ("The Preamble") -\begin{document} -% ak zadáme položky author, date a title, LaTeX vytvorí titulnú stranu. -\maketitle - -% Väčšina odborných článkov má abstrakt, na jeho vytvorenie môžeš použiť preddefinované príkazy. -% Ten by sa mal zobraziť v logickom poradí, teda po hlavičke, -% no pred hlavnými sekciami tela.. -% Tento príkaz je tiež dostupný v triedach article a report. -% Tzv. makro "abstract" je fixnou súčasťou LaTeXu, ak chceme použiť abstract -% a napísať ho po slovensky, musíme ho redefinovať nasledujúcim príkazom -\renewcommand\abstractname{Abstrakt} - -\begin{abstract} -LaTeX dokumentácia v LaTeXe! Aké netradičné riešenie cudzieho nápadu! -\end{abstract} - -% Príkazy pre sekciu sú intuitívne -% Všetky nadpisy sekcií sú pridané automaticky do obsahu. -\section{Úvod} -Čaute, volám sa Colton a spoločne sa pustíme do skúmania LaTeXu (toho druhého)! - -\section{Ďalšia sekcia} -Toto je text ďalšej sekcie. Myslím, že potrebuje podsekciu. - -\subsection{Toto je podsekcia} % Podsekcie sú tiež intuitívne. -Zdá sa mi, že treba ďalšiu. - -\subsubsection{Pytagoras} -To je ono! -\label{subsec:pytagoras} - -% Použitím '*' môžeme potlačiť zabudované číslovanie LaTeXu. -% Toto funguje aj na iné príkazy. -\section*{Toto je nečíslovaná sekcia} -Všetky číslované byť nemusia! - -\section{Nejaké poznámočky} -Zarovnávať veci tam, kde ich chceš mať, je všeobecne ľahké. Ak -potrebuješ \\ nový \\ riadok \\ pridaj \textbackslash\textbackslash do -zdrojového kódu. \\ - -\section{Zoznamy} -Zoznamy sú jednou z najjednoduchších vecí vôbec! Treba mi zajtra nakúpiť, urobím si zoznam. -\begin{enumerate} % "enumerate" spustí číslovanie prvkov. - % \item povie LaTeXu, ako že treba pripočítať 1 - \item Vlašský šalát. - \item 5 rožkov. - \item 3 Horalky. - % číslovanie môžeme pozmeniť použitím [] - \item[koľko?] Stredne veľkých guličkoviek. - - Ja už nie som položka zoznamu, no stále som časť "enumerate". - -\end{enumerate} % Všetky prostredia končia s "end". - -\section{Matika} - -Jedným z primárnych použití LaTeXu je písanie akademických, či technických prác. Zvyčajne za použitia matematiky a vedy. Podpora špeciálnych symbolov preto nemôže chýbať!\\ - -Matematika má veľa symbolov, omnoho viac, než by klávesnica mohla reprezentovať; -Množinové a relačné symboly, šípky, operátory a Grécke písmená sú len malou ukážkou.\\ - -Množiny a relácie hrajú hlavnú rolu v mnohých matematických článkoch. -Takto napíšeš, že niečo platí pre všetky x patriace do X, $\forall$ x $\in$ X. \\ -% Všimni si, že som pridal $ pred a po symboloch. Je to -% preto, lebo pri písaní sme v textovom móde, -% no matematické symboly existujú len v matematickom. -% Vstúpime doňho z textového práve '$' znamienkami. -% Platí to aj opačne. Premenná môže byť zobrazená v matematickom móde takisto. -% Do matematického módu sa dá dostať aj s \[\] - -\[a^2 + b^2 = c^2 \] - -Moje obľúbené Grécke písmeno je $\xi$. Tiež sa mi pozdávajú $\beta$, $\gamma$ a $\sigma$. -Ešte som neprišiel na Grécke písmeno, ktoré by LaTeX nepoznal! - -Operátory sú dôležitou súčasťou matematických dokumentov: -goniometrické funkcie ($\sin$, $\cos$, $\tan$), -logaritmy and exponenciálne výrazy ($\log$, $\exp$), -limity ($\lim$), atď. -majú pred-definované LaTeXové príkazy. -Napíšme si rovnicu, nech vidíme, ako to funguje: \\ - -$\cos(2\theta) = \cos^{2}(\theta) - \sin^{2}(\theta)$ - -Zlomky(Čitateľ-menovateľ) sa píšu v týchto formách: - -% 10 / 7 -$^{10}/_{7}$ - -% Relatívne komplexné zlomky sa píšu ako -% \frac{čitateľ}{menovateľ} -$\frac{n!}{k!(n - k)!}$ \\ - -Rovnice tiež môžeme zadať v "rovnicovom prostredí". - -% Takto funguje rovnicové prostredie -\begin{equation} % vstúpi do matematického módu - c^2 = a^2 + b^2. - \label{eq:pythagoras} % na odkazovanie -\end{equation} % všetky \begin príkazy musia mať konečný príkaz. - -Teraz môžeme odkázať na novovytvorenú rovnicu! -Rovn.~\ref{eq:pythagoras} je tiež známa ako Pytagorova Veta, ktorá je tiež predmetom Sekc.~\ref{subsec:pytagoras}. Odkazovať môžme na veľa vecí, napr na: čísla, rovnice, či sekcie. - -Sumácie a Integrály sa píšu príkazmi sum a int: - -% Niektoré prekladače LaTeXu sa môžu sťažovať na prázdne riadky (ak tam sú) -% v rovnicovom prostredí. -\begin{equation} - \sum_{i=0}^{5} f_{i} -\end{equation} -\begin{equation} - \int_{0}^{\infty} \mathrm{e}^{-x} \mathrm{d}x -\end{equation} - -\section{Obrázky} - -Vloženie obrázku môže byť zložitejšie. Ja si vždy možnosti vloženia pozerám pre každý obrázok. -\renewcommand\figurename{Obrázok} -\begin{figure}[H] % H značí možnosť zarovnania. - \centering % nacentruje obrázok na stránku - % Vloží obrázok na 80% šírky stránky. - %\includegraphics[width=0.8\linewidth]{right-triangle.png} - % Zakomentované kvôli kompilácií, použi svoju predstavivosť :). - \caption{Pravouhlý trojuholník so stranami $a$, $b$, $c$} - \label{fig:right-triangle} -\end{figure} -% Opäť, fixné makro "table" nahradíme slovenskou tabuľkou. Pokiaľ preferuješ table, nasledujúci riadok nepridávaj -\renewcommand\tablename{Tabuľka} - -\subsection{Tabuľky} -Tabuľky sa vkládajú podobne ako obrázky. - -\begin{table}[H] - \caption{Nadpis tabuľky.} - % zátvorky: {} hovoria ako sa vykreslí každý riadok. - % Toto si nikdy nepamätám a vždy to musím hľadať. Všetko. Každý. Jeden. Raz! - \begin{tabular}{c|cc} - Číslo & Priezvisko & Krstné meno \\ % Stĺpce sú rozdelené $ - \hline % horizontálna čiara - 1 & Ladislav & Meliško \\ - 2 & Eva & Máziková - \end{tabular} -\end{table} - -% \section{Hyperlinks} % Už čoskoro :) - -\section{Prikáž LaTeXu nekompilovať (napr. Zdrojový Kód)} -Povedzme, že chceme do dokumentu vložiť zdrojový kód, budeme musieť LaTeXu povedať, nech sa ho nesnaží skompilovať, ale nech s ním pracuje ako s textom. -Toto sa robí vo verbatim prostredí. - -% Tiež sú na to špeciálne balíčky, (napr. minty, lstlisting, atď.) -% ale verbatim je to najzákladnejšie, čo môžeš použiť. -\begin{verbatim} - print("Hello World!") - a%b; pozri! Vo verbatime môžme použiť % znamienka. - random = 4; #priradené randomným hodom kockou -\end{verbatim} - -\section{Kompilácia} - -Už by bolo načase túto nádheru skompilovať a zhliadnuť jej úžasnú úžasnosť v podobe LaTeX pdfka, čo povieš? -(áno, tento dokument sa musí kompilovať). \\ -Cesta k finálnemu dokumentu pomocou LaTeXu pozostáva z nasledujúcich krokov: - \begin{enumerate} - \item Napíš dokument v čistom texte (v "zdrojáku"). - \item Skompiluj zdroják na získanie pdfka. - Kompilácia by mala vyzerať nasledovne (v Linuxe): \\ - \begin{verbatim} - $pdflatex learn-latex.tex learn-latex.pdf - \end{verbatim} - \end{enumerate} - -Mnoho LaTeX editorov kombinuje Krok 1 a Krok 2 v jednom prostredí. Krok 1 teda uvidíš, krok 2 už nie. -Ten sa deje za oponou. Kompilácia v 2. kroku sa postará o produkciu dokumentu v tebou zadanom formáte. - -\section{Koniec} - -To je zatiaľ všetko! - -% koniec dokumentu -\end{document} From 21baba2003994bfe7f8787e20bbd3d56deb56323 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Tue, 2 Apr 2024 18:16:01 -0700 Subject: [PATCH 050/392] css-es.html -> css-es.html.markdown --- es-es/{css-es.html => css-es.html.markdown} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename es-es/{css-es.html => css-es.html.markdown} (100%) diff --git a/es-es/css-es.html b/es-es/css-es.html.markdown similarity index 100% rename from es-es/css-es.html rename to es-es/css-es.html.markdown From 49c50ce28fea0c8db81c31d0b57995f82fde6259 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 2 Apr 2024 21:21:36 -0700 Subject: [PATCH 051/392] Rename template file --- file.erb => file.html.erb | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename file.erb => file.html.erb (100%) diff --git a/file.erb b/file.html.erb similarity index 100% rename from file.erb rename to file.html.erb From db75ea1b4d16d46a55173e1dc7cb762ba668b1cc Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Wed, 3 Apr 2024 02:31:00 -0700 Subject: [PATCH 052/392] Update ru-ru/html-ru.html.markdown --- ru-ru/html-ru.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ru-ru/html-ru.html.markdown b/ru-ru/html-ru.html.markdown index 72af0120..e18fb8a0 100644 --- a/ru-ru/html-ru.html.markdown +++ b/ru-ru/html-ru.html.markdown @@ -25,7 +25,7 @@ HTML расшифровывается как Hypertext Markup Language (гипе В данной статье рассматривается в основном HTML-синтаксис и некоторые полезные советы. ```html - + From 3c918ac30ecd153be7b3dfbae8b7966cb8f5ceb2 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Wed, 3 Apr 2024 03:18:08 -0700 Subject: [PATCH 053/392] Proofread tcl-ru.html.markdown --- ru-ru/tcl-ru.html.markdown | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/ru-ru/tcl-ru.html.markdown b/ru-ru/tcl-ru.html.markdown index 723efe30..380d7b05 100644 --- a/ru-ru/tcl-ru.html.markdown +++ b/ru-ru/tcl-ru.html.markdown @@ -1,10 +1,11 @@ --- language: Tcl +lang: ru-ru contributors: - ["Poor Yorick", "https://pooryorick.com/"] translators: - ["Viktor Sokhranov", "https://github.com/weirdvic"] -filename: learntcl.tcl +filename: learntcl-ru.tcl --- Tcl был создан [Джоном Оустерхаутом](https://ru.wikipedia.org/wiki/Оустерхаут,_Джон) @@ -20,7 +21,7 @@ Tcl был создан [Джоном Оустерхаутом](https://ru.wikip * Удобный кроссплатформенный API для работы с сетью -* Поддержка виртуальной файловой системы(VFS) +* Поддержка виртуальной файловой системы (VFS) * Стекируемые каналы ввода-вывода @@ -32,15 +33,15 @@ Tcl был создан [Джоном Оустерхаутом](https://ru.wikip Tcl имеет много общего с Lisp, но в отличие от списков, в Tcl "валютой" языка являются строки. Все значения являются строками. Список в Tcl это просто строка в -определённом формате, а тело процедуры(скрипт) это ещё одна строка, а не блок. +определённом формате, а тело процедуры (скрипт) это ещё одна строка, а не блок. С целью увеличения производительности, интерпретатор Tcl использует кэшированные -внутренние представления различных типов данных. Например, рутины(routines), работающие +внутренние представления различных типов данных. Например, рутины (routines), работающие со списками, фактически используют внутреннее представление списков, а интерпретатор Tcl обновляет строковое представление в том случае если оно используется в скрипте. В Tcl используется подход copy-on-write, позволяющий оперировать большими объёмами данных без дополнительного оверхеда. Процедуры в Tcl автоматически компилируются в байткод, кроме случаев когда в процедуре используются динамические рутины, такие -как "uplevel", "upvar" и "trace" +как `uplevel`, `upvar` и `trace`. Программировать на Tcl приятно. Его находят привлекательным хакеры, которым интересны Lisp, Forth или Smalltalk, а также инженеры и учёные, которым просто необходим @@ -50,8 +51,6 @@ Lisp, Forth или Smalltalk, а также инженеры и учёные, к синтаксису Tcl не мешать работать с предметной областью проекта. Синтаксис Tcl в этом смысле даже более минималистичен чем у Lisp. - - ```tcl #! /bin/env tclsh @@ -65,7 +64,7 @@ Lisp, Forth или Smalltalk, а также инженеры и учёные, к # когда скрипты становятся сложнее, наступает фрустрация. # Фигурные скобки {} в Tcl используются не для построения блоков кода или -# списков, а как механизм экранирования(quoting) для кода. Фактически в Tcl +# списков, а как механизм экранирования (quoting) для кода. Фактически в Tcl # нет ни списков, ни блоков кода. Фигурные скобки использутся для # экранирования специальных символов и потому подходят для представления # тела процедур и строк, которые должны интерпретироваться как списки. @@ -206,9 +205,9 @@ set greeting "Hello $::people::person1::name" ## 4. Переменные и пространства имён ############################################################################### -# Каждая переменная и рутина связанс с пространством имён. +# Каждая переменная и рутина связана с пространством имён. -# Чтобы получить интерпретатор, которые не может сделать ничего, достаточно +# Чтобы получить интерпретатор, который не может сделать ничего, достаточно # удалить глобальное пространство имён. Особой пользы в этом нет, но это хорошо # иллюстрирует природу Tcl. Фактически имя глобального пространства имён это # пустая строка, но единственный способ представить её -- в виде полного имени: @@ -323,12 +322,8 @@ proc greet {greeting name} { # Как было отмечено ранее, фигурные скобки не обозначают блок кода. -# Любое значение, даже третий аргумент "proc" является строкой. +# Любое значение, даже третий аргумент "proc", является строкой. # Предыдущая команда может быть переписана без использования фигурных скобок: - -# As noted earlier, braces do not construct a code block. Every value, even -# the third argument to "proc", is a string. The previous command -# can be rewritten using no braces: proc greet greeting\ name return\ \"\$greeting,\ \$name!\" @@ -354,7 +349,7 @@ if {3 > 4} { } -# Циклы реализованы как рутины. Первый и третий аргументы для "for" +# Циклы реализованы как рутины. Первый и третий аргумент для "for" # обрабатываются как скрипты, а второй аргумент как выражение: set res 0 for {set i 0} {$i < 10} {incr i} { From 365200ce0aa1ee13fe48ef939b9bfc1da136044d Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Wed, 3 Apr 2024 03:53:28 -0700 Subject: [PATCH 054/392] Fix syntax highlighting for Markdown --- cs-cz/markdown.html.markdown | 10 +++--- fr-fr/markdown-fr.html.markdown | 55 +++++++++++++++++---------------- it-it/markdown.html.markdown | 13 +++++--- ko-kr/markdown-kr.html.markdown | 53 +++++++++++++++++++++++-------- markdown.html.markdown | 33 ++++++++++++-------- pt-br/markdown-pt.html.markdown | 39 +++++++++++++---------- ru-ru/markdown-ru.html.markdown | 39 ++++++++++++++--------- vi-vn/markdown-vi.html.markdown | 40 ++++++++++++++++-------- zh-cn/markdown-cn.html.markdown | 16 +++++----- 9 files changed, 184 insertions(+), 114 deletions(-) diff --git a/cs-cz/markdown.html.markdown b/cs-cz/markdown.html.markdown index 50a69107..e1a96f32 100644 --- a/cs-cz/markdown.html.markdown +++ b/cs-cz/markdown.html.markdown @@ -215,7 +215,7 @@ Pro ještě hlubší odsazení můžete přidat další 4 mezery nebo další ta ```md moje_pole.each do |i| - puts i + puts i end ``` @@ -228,11 +228,13 @@ Honza neměl tušení, co dělá funkce `go_to()`! V Markdownu od GitHubu, můžete použít speciální syntaxi pro kód: -
    ```ruby
    +````md
    +```ruby
     def neco
    -    puts "Ahoj světe!"
    +  puts "Ahoj světe!"
     end
    -```
    +``` +```` Text výše nepotřebuje čtyřmezerové odsazení a parser navíc použije zvýraznění syntaxe pro zvolený jazyk. diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown index 1fd22883..91894787 100644 --- a/fr-fr/markdown-fr.html.markdown +++ b/fr-fr/markdown-fr.html.markdown @@ -178,7 +178,7 @@ Vous pouvez également utiliser des sous-listes. 1. Item un 2. Item deux 3. Item trois - * Sub-item + * Sub-item * Sub-item 4. Item quatre ``` @@ -210,7 +210,7 @@ l'intérieur du bloc de code. ```md my_array.each do |item| - puts item + puts item end ``` @@ -223,13 +223,15 @@ La fonction `run()` ne vous oblige pas à aller courir! En Markdown GitHub, vous pouvez utiliser des syntaxes spécifiques. - ```ruby - def foobar - puts "Hello world!" - end - ``` +````md +```ruby +def foobar + puts "Hello world!" +end +``` +```` -Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub +Pas besoin d'indentation pour le code juste au-dessus, de plus, GitHub va utiliser une coloration syntaxique pour le langage indiqué après les ```. ## Ligne Horizontale @@ -267,13 +269,13 @@ Markdown supporte aussi les liens relatifs. Les liens de références sont eux aussi disponibles en Markdown. -
    -[Cliquez ici][link1] pour plus d'information!
    -[Regardez aussi par ici][foobar] si vous voulez.
    +```md
    +[Cliquez ici][link1] pour plus d'information!
    +[Regardez aussi par ici][foobar] si vous voulez.
     
    -[link1]: http://test.com/ "Cool!"
    -[foobar]: http://foobar.biz/ "Génial!"
    -
    +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Génial!" +``` Le titre peut aussi être entouré de guillemets simples, ou de parenthèses, ou absent. Les références peuvent être placées où vous voulez dans le document et @@ -282,11 +284,11 @@ les identifiants peuvent être n'importe quoi tant qu'ils sont uniques. Il y a également le nommage implicite qui transforme le texte du lien en identifiant. -
    -[Ceci][] est un lien.
    +```md
    +[Ceci][] est un lien.
     
    -[Ceci]:http://ceciestunlien.com/
    -
    +[Ceci]:http://ceciestunlien.com/ +``` Mais ce n'est pas beaucoup utilisé. @@ -301,12 +303,11 @@ d'un point d'exclamation! Là aussi, on peut utiliser le mode "références". +```md +![Ceci est l'attribut ALT de l'image][monimage] -
    -![Ceci est l'attribut ALT de l'image][monimage]
    -
    -[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici."
    -
    +[monimage]: relative/urls/cool/image.jpg "si vous voulez un titre, c'est ici." +``` ## Divers @@ -348,10 +349,10 @@ Les tableaux ne sont disponibles que dans le "GitHub Flavored Markdown" et ne sont pas tres agréable d'utilisation. Mais si vous en avez besoin : ```md -| Col1 | Col2 | Col3 | -| :----------- | :------: | ------------: | -| Alignement Gauche | Centré | Alignement Droite | -| bla | bla | bla | +| Col1 | Col2 | Col3 | +| :---------------- | :------: | ----------------: | +| Alignement Gauche | Centré | Alignement Droite | +| bla | bla | bla | ``` ou bien, pour un résultat équivalent : diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index c14bc175..ff6f0aed 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -183,7 +183,7 @@ Potete inoltre inserire un altro tab (o altri quattro spazi) per indentare il vo ```md my_array.each do |item| - puts item + puts item end ``` @@ -194,12 +194,15 @@ Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! ``` In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice -
    -```ruby
    +
    +````md
    +```ruby
     def foobar
    -    puts "Hello world!"
    +  puts "Hello world!"
     end
    -```
    +``` +```` + Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali ## Linea orizzontale diff --git a/ko-kr/markdown-kr.html.markdown b/ko-kr/markdown-kr.html.markdown index 397e9f30..0167f0ff 100644 --- a/ko-kr/markdown-kr.html.markdown +++ b/ko-kr/markdown-kr.html.markdown @@ -25,15 +25,18 @@ lang: ko-kr ## HTML 요소 HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마크다운이라는 것입니다. + ```md ``` + ## 제목 텍스트 앞에 붙이는 우물 정 기호(#)의 갯수에 따라 `

    `부터 `

    `까지의 HTML 요소를 손쉽게 작성할 수 있습니다. + ```md #

    입니다. ##

    입니다. @@ -42,7 +45,9 @@ HTML은 마크다운의 수퍼셋입니다. 모든 HTML 파일은 유효한 마 #####

    입니다. ######
    입니다. ``` + 또한 h1과 h2를 나타내는 다른 방법이 있습니다. + ```md h1입니다. ============= @@ -50,9 +55,11 @@ h1입니다. h2입니다. ------------- ``` + ## 간단한 텍스트 꾸미기 마크다운으로 쉽게 텍스트를 기울이거나 굵게 할 수 있습니다. + ```md *기울인 텍스트입니다.* _이 텍스트도 같습니다._ @@ -64,10 +71,13 @@ __이 텍스트도 같습니다.__ **_이 텍스트도 같습니다._** *__이것도 같습니다.__* ``` + 깃헙 전용 마크다운에는 취소선도 있습니다. + ```md ~~이 텍스트에는 취소선이 그려집니다.~~ ``` + ## 문단 문단은 하나 이상의 빈 줄로 구분되는, 한 줄 이상의 인접한 텍스트입니다. @@ -103,6 +113,7 @@ HTML `
    ` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 ## 목록 순서가 없는 목록은 별표, 더하기, 하이픈을 이용해 만들 수 있습니다. + ```md * 이거 * 저거 @@ -140,6 +151,7 @@ HTML `
    ` 태그를 삽입하고 싶으시다면, 두 개 이상의 띄어 1. 둘 1. 셋 ``` + (위의 예시와 똑같이 나타납니다.) 목록 안에 목록이 올 수도 있습니다. @@ -176,7 +188,7 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. ```md my_array.each do |item| - puts item + puts item end ``` @@ -188,12 +200,13 @@ x가 없는 박스들은 체크되지 않은 HTML 체크박스입니다. 깃헙 전용 마크다운에서는 코드를 나타내기 위해 특별한 문법을 쓸 수 있습니다. -
    -```ruby
    +````md
    +```ruby
     def foobar
    -    puts "Hello world!"
    +  puts "Hello world!"
     end
    -```
    +``` +```` 위의 경우에 들여쓰기가 필요없을 뿐 아니라 \`\`\` 뒤에 특정해 준 언어의 문법에 따라 색을 입혀줄 것입니다. @@ -202,12 +215,14 @@ end 수평선(`
    `)은 셋 이상의 별표나 하이픈을 이용해 쉽게 나타낼 수 있습니다. 띄어쓰기가 포함될 수 있습니다. + ```md *** --- - - - **************** ``` + ## 링크 마크다운의 장점 중 하나는 링크를 만들기 쉽다는 것입니다. 대괄호 안에 나타낼 텍스트를 쓰고 @@ -231,20 +246,24 @@ end 참조하는 식으로 링크를 걸 수도 있습니다. -
    [][링크]에서 더 알아보세요!
    -[원하신다면 ][foobar]도 참고하세요.
    +```md
    +[이 ][링크]에서 더 알아보세요!
    +[원하신다면 ][foobar]도 참고하세요.
     
    -[링크]: http://test.com/ "좋아!"
    -[foobar]: http://foobar.biz/ "됐다!"
    +[링크]: http://test.com/ "좋아!" +[foobar]: http://foobar.biz/ "됐다!" +``` 제목은 작은 따옴표나 괄호에 들어갈 수도 있고, 완전히 생략할 수도 있습니다. 참조는 문서의 어느 곳에든 올 수 있고 참조 ID는 유일하다면 무엇이든 될 수 있습니다. 링크 텍스트를 ID로 사용하는 "묵시적 이름"도 있습니다. -
    [이것][]은 링크입니다.
    +```md
    +[이것][]은 링크입니다.
     
    -[이것]: http://thisisalink.com/
    +[이것]: http://thisisalink.com/ +``` 하지만 보통 그렇게 추천하지는 않습니다. @@ -257,9 +276,11 @@ end 참조 방식도 가능합니다. -
    ![alt 속성][이미지]
    +```md
    +![alt 속성][이미지]
     
    -[이미지]: relative/urls/cool/image.jpg "제목이 필요하다면 여기에"
    +[이미지]: relative/urls/cool/image.jpg "제목이 필요하다면 여기에" +``` ## 기타 ### 자동 링크 @@ -270,9 +291,11 @@ end ``` ### 이메일 자동 링크 + ```md ``` + ### 탈출 문자 ```md @@ -292,17 +315,21 @@ end ### 표 표는 깃헙 전용 마크다운에서만 쓸 수 있고 다소 복잡하지만, 정말 쓰고 싶으시다면 + ```md | 1열 | 2열 | 3열 | | :--------| :-------: | --------: | | 왼쪽 정렬 | 가운데 정렬 | 오른쪽 정렬 | | 머시기 | 머시기 | 머시기 | ``` + 혹은 + ```md 1열 | 2열 | 3열 :-- | :-: | --: 으악 너무 못생겼어 | 그만 | 둬 ``` + --- 추가 정보를 위해, 존 그루버의 공식 문법 [(영어) 문서](http://daringfireball.net/projects/markdown/syntax)와 애덤 프릿차드의 훌륭한 [(영어) 치트싯](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)을 확인하세요. diff --git a/markdown.html.markdown b/markdown.html.markdown index fefb60f6..ee213083 100644 --- a/markdown.html.markdown +++ b/markdown.html.markdown @@ -207,7 +207,7 @@ inside your code. ```md my_array.each do |item| - puts item + puts item end ``` @@ -219,12 +219,13 @@ John didn't even know what the `go_to()` function did! In GitHub Flavored Markdown, you can use a special syntax for code. -
    -```ruby
    +````md
    +```ruby
     def foobar
    -    puts "Hello world!"
    +  puts "Hello world!"
     end
    -```
    +``` +```` The above text doesn't require indenting, plus GitHub will use syntax highlighting of the language you specify after the opening ```. @@ -264,11 +265,13 @@ Relative paths work too. Markdown also supports reference style links. -
    [Click this link][link1] for more info about it!
    -[Also check out this link][foobar] if you want to.
    +```md
    +[Click this link][link1] for more info about it!
    +[Also check out this link][foobar] if you want to.
     
    -[link1]: http://test.com/ "Cool!"
    -[foobar]: http://foobar.biz/ "Alright!"
    +[link1]: http://test.com/ "Cool!" +[foobar]: http://foobar.biz/ "Alright!" +``` The title can also be in single quotes or in parentheses, or omitted entirely. The references can be anywhere in your document and the reference IDs @@ -276,9 +279,11 @@ can be anything so long as they are unique. There is also "implicit naming" which lets you use the link text as the id. -
    [This][] is a link.
    +```md
    +[This][] is a link.
     
    -[This]: http://thisisalink.com/
    +[This]: http://thisisalink.com/ +``` But it's not that commonly used. @@ -311,9 +316,11 @@ Images are done the same way as links but with an exclamation point in front! And reference style works as expected. -
    ![This is the alt-attribute.][myimage]
    +```md
    +![This is the alt-attribute.][myimage]
     
    -[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
    +[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here" +``` ## Miscellany diff --git a/pt-br/markdown-pt.html.markdown b/pt-br/markdown-pt.html.markdown index 7960a59a..fca864bb 100644 --- a/pt-br/markdown-pt.html.markdown +++ b/pt-br/markdown-pt.html.markdown @@ -8,7 +8,7 @@ translators: - ["Monique Baptista", "https://github.com/bfmonique"] - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"] -lang: pt-br +lang: pt-br filename: learnmarkdown-pt.md --- @@ -213,8 +213,8 @@ adicionais) para indentação no seu código. ```md my_array.each do |item| - puts item - end + puts item + end ``` Código embutido pode ser criado usando o caractere de crase `` ` ``. @@ -225,13 +225,13 @@ John não sabia nem o que a função `go_to()` fazia! No GitHub Flavored Markdown, você pode usar uma sintaxe especial para código. -
    -```ruby
    +````md
    +```ruby
     def foobar
    -    puts "Olá mundo!"
    +  puts "Olá mundo!"
     end
    -```
    - +``` +```` O texto acima não requer indentação, além disso o GitHub vai usar o destaque de sintaxe da linguagem qeu você especificar após a tag ```. @@ -272,11 +272,13 @@ Caminhos relativos funcionam também. O Markdown também suporta links para referências no texto. -
    [Clique nesse link][link1] para mais informações!
    -[Também cheque esse link][foobar] se você quiser.
    +```md
    +[Clique nesse link][link1] para mais informações!
    +[Também cheque esse link][foobar] se você quiser.
     
    -[link1]: http://test.com/ "Legal!"
    -[link2r]: http://foobar.biz/ "Certo!"
    +[link1]: http://test.com/ "Legal!" +[link2r]: http://foobar.biz/ "Certo!" +``` O título também pode estar entre aspas simples ou entre parênteses, ou omitido inteiramente. As referências podem estar em qualquer lugar no documento e os @@ -285,10 +287,11 @@ IDs de referência podem ser qualquer um, desde que eles sejam únicos. Existe também a "nomeação implícita", que permite que você use o texto do link como o id: -
    [Isso][] é um link.
    -
    -[Isso]: http://thisisalink.com/
    +```md +[Isso][] é um link. +[Isso]: http://thisisalink.com/ +``` Mas geralmente não são usados. @@ -322,9 +325,11 @@ exclamação na frente! E estilo de referência funciona como esperado -
    ![Esse é o alt-attribute.][myimage]
    +```md
    +![Esse é o alt-attribute.][myimage]
     
    -[Minha imagem]: relative/urls/cool/image.jpg "se precisar de um título, está aqui"
    +[Minha imagem]: relative/urls/cool/image.jpg "se precisar de um título, está aqui" +``` ## Miscelânea diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index 728741af..4692e628 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -45,7 +45,7 @@ Markdown является надмножеством HTML, поэтому люб HTML-элементов --> ``` -## Заголовки +## Заголовки HTML-элементы от

    до

    размечаются очень просто: текст, который должен стать заголовком, предваряется @@ -110,7 +110,7 @@ __И этот тоже.__ Для вставки принудительных переносов можно завершить абзац двумя дополнительными пробелами: ```md -Эта строка завершается двумя пробелами (выделите, чтобы увидеть!). +Эта строка завершается двумя пробелами (выделите, чтобы увидеть!). Над этой строкой есть
    ! ``` @@ -208,7 +208,7 @@ __И этот тоже.__ ```md my_array.each do |item| - puts item + puts item end ``` @@ -223,12 +223,11 @@ __И этот тоже.__ В Github Flavored Markdown для блоков кода можно использовать специальный синтаксис: -
    -```ruby
    +```ruby
     def foobar
    -    puts "Привет, мир!"
    +  puts "Привет, мир!"
     end
    -```
    +``` Во фрагменте, приведённом выше, отступ не требуется. Кроме того, Github подсветит синтаксис языка, указанного после \`\`\` @@ -255,6 +254,7 @@ end ```md [Ссылка!](http://test.com/) ``` + Также для ссылки можно указать всплывающую подсказку (`title`), используя кавычки внутри круглых скобок: @@ -269,11 +269,13 @@ end Markdown также позволяет размечать ссылку в виде сноски: -
    [Щёлкните эту ссылку][link1] для подробной информации!
    -[Также посмотрите эту ссылку,][foobar] если хотите.
    +```md
    +[Щёлкните эту ссылку][link1] для подробной информации!
    +[Также посмотрите эту ссылку,][foobar] если хотите.
     
    -[link1]: http://test.com/ "Круто!"
    -[foobar]: http://foobar.biz/ "Нормально!"
    +[link1]: http://test.com/ "Круто!" +[foobar]: http://foobar.biz/ "Нормально!" +``` `Title` также может быть в одинарных кавычках или круглых скобках, а также отсутствовать вовсе. Ссылки на сноски могут быть в любом месте документа, @@ -281,9 +283,11 @@ Markdown также позволяет размечать ссылку в вид Существует также неявное именование, когда ссылка является идентификатором. -
    [Это][] ссылка.
    +```md
    +[Это][] ссылка.
     
    -[это]: http://thisisalink.com/
    +[это]: http://thisisalink.com/ +``` Правда, эта возможность не очень распространена. @@ -294,11 +298,15 @@ Markdown также позволяет размечать ссылку в вид ```md ![Альтернативный текст для изображения](http://imgur.com/myimage.jpg "Подсказка") ``` + Изображения тоже могут быть оформлены как сноски. -
    ![Это альтернативный текст.][myimage]
    +```md
    +![Это альтернативный текст.][myimage]
    +
    +[myimage]: relative/urls/cool/image.jpg "Если нужна подсказка, её можно добавить"
    +```
     
    -[myimage]: relative/urls/cool/image.jpg "Если нужна подсказка, её можно добавить"
    ## Разное ### Автоссылки @@ -341,6 +349,7 @@ Markdown также позволяет размечать ссылку в вид | Выравнивание | Выравнивание | Выравнивание | | влево | по центру | вправо | ``` + Или более компактно ```md diff --git a/vi-vn/markdown-vi.html.markdown b/vi-vn/markdown-vi.html.markdown index 89b59253..52c2df42 100644 --- a/vi-vn/markdown-vi.html.markdown +++ b/vi-vn/markdown-vi.html.markdown @@ -48,6 +48,7 @@ bằng cách thêm số lượng dấu thăng (#) đằng trước chuỗi cần ##### Đây là đầu mục
    ###### Đây là đầu mục
    ``` + Markdown còn cung cấp cách khác để tạo đầu mục hạng nhất h1 và hạng nhì h2. ```md @@ -79,6 +80,7 @@ Trong cài đặt Markdown để hiển thị file của GitHub,ta còn có gạ ```md ~~Đoạn văn bản này được gạch ngang.~~ ``` + ## Đoạn văn Đoạn văn bao gồm một hay nhiều dòng văn bản liên tiếp nhau được phân cách @@ -153,6 +155,7 @@ Ta không nhất thiết phải điền số thứ thự cho chỉ mục đúng 1. Mục thứ hai 1. Mục thứ ba ``` + (Sẽ hiển thị như ví dụ trước đó) Ta còn có thể sử dụng danh sách con @@ -189,7 +192,7 @@ Ta còn có thể thêm dấu nhảy (hoặc thêm vào bốn dấu cách nữa) ```md my_array.each do |item| - puts item + puts item end ``` @@ -201,12 +204,13 @@ John didn't even know what the `go_to()` function did! Trong Markdown của GitHub, ta còn có thêm cách để hiển thị code: -
    -```ruby
    +````md
    +```ruby
     def foobar
    -    puts "Hello world!"
    +  puts "Hello world!"
     end
    -```
    +``` +```` The above text doesn't require indenting, plus GitHub will use syntax highlighting of the language you specify after the \`\`\` @@ -231,11 +235,13 @@ Một trong những thứ tốt nhất khi làm việc với Markdown là khả ```md [Click me!](http://test.com/) ``` + Ta còn có thể tạo tiêu đề cho liên kết sử dụng cặp ngoặc nháy bên trong cặp ngoặc tròn ```md [Click me!](http://test.com/ "Link to Test.com") ``` + Đường dẫn tương đối cũng hoạt động. ```md @@ -244,19 +250,23 @@ Ta còn có thể tạo tiêu đề cho liên kết sử dụng cặp ngoặc nh Markdown còn hỗ trợ liên kết kiểu tham chiếu. -
    [Nhấn vào đây][link1] để xem thêm!
    -[Ngoài ra nhấn vào đây][foobar] nếu bạn muốn xem qua.
    +```md
    +[Nhấn vào đây][link1] để xem thêm!
    +[Ngoài ra nhấn vào đây][foobar] nếu bạn muốn xem qua.
     
    -[link1]: http://test.com/ "Tuyệt!"
    -[foobar]: http://foobar.biz/ "Tốt!"
    +[link1]: http://test.com/ "Tuyệt!" +[foobar]: http://foobar.biz/ "Tốt!" +``` Tiêu đề có thể được đóng trong dấu nháy hay ngoặc đơn, hoặc có thể được bỏ qua. Tham chiếu có thể được đặt bất kì đâu trong văn bản và ID của tham chiếu có thể là bất kì gì miễn là nó độc nhất. Ngoài ra còn có kiểu đặt tên ngầm cho phép ta sử dụng đường dẫn làm ID. -
    [This][] is a link.
    +```md
    +[This][] is a link.
     
    -[this]: http://thisisalink.com/
    +[this]: http://thisisalink.com/ +``` Nhưng nó không được sử dụng rộng rãi. @@ -270,9 +280,11 @@ Hiển thị ảnh tương tự như liên kết nhưng có thêm dấu chấm t Và kiểu tham chiếu cũng hoạt động như vậy. -
    ![Đây là thuộc tính alt.][myimage]
    +```md
    +![Đây là thuộc tính alt.][myimage]
     
    -[myimage]: relative/urls/cool/image.jpg "Đây là tiêu đề"
    +[myimage]: relative/urls/cool/image.jpg "Đây là tiêu đề" +``` ## Khác @@ -303,6 +315,7 @@ Trong Markdown của Github, ta có thể sử dụng thẻ `` để thay c Máy treo? Thử bấm tổ hợp Ctrl+Alt+Del ``` + ### Bảng biểu Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v và khá khó viết: @@ -313,6 +326,7 @@ Bảng biểu được hỗ trợ trên Markdown của GitHub, Jira, Trello, v.v | Căn trái | Căn giữa | Căn phải | | blah | blah | blah | ``` + Hoặc có thể sử dụng kết quả dưới đây ```md diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 707d6927..23f27dda 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -147,7 +147,6 @@ GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以 - 项目 - 项目 - 最后一个项目 - ``` 有序序列可由数字加上点 `.` 来实现 @@ -188,6 +187,7 @@ GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以 下面这个选择框将会是选中状态 - [x] 这个任务已经完成 ``` + - [ ] 你看完了这个任务(注:此选择框是无法直接更改的,即禁用状态。) ## 代码块 @@ -204,7 +204,7 @@ GitHub 也支持 Markdown,在 GitHub 的 Markdown 解析器中,我们可以 ```md my_array.each do |item| - puts item + puts item end ``` @@ -216,12 +216,13 @@ John 甚至不知道 `go_to()` 函数是干嘛的! 在GitHub的 Markdown(GitHub Flavored Markdown)解析器中,你可以使用特殊的语法表示代码块 -
    -```ruby
    +````md
    +```ruby
     def foobar
    -    puts "Hello world!"
    +  puts "Hello world!"
     end
    -```
    +``` +```` 以上代码不需要缩进,而且 GitHub 会根据\`\`\`后指定的语言来进行语法高亮显示 @@ -246,7 +247,6 @@ Markdown 最棒的地方就是便捷的书写链接。把链接文字放在中 ```md [点我点我!](http://test.com/) - ``` 你也可以在小括号内使用引号,为链接加上一个标题(title) @@ -345,6 +345,7 @@ Markdown同样支持引用形式的链接 | 我是左对齐 | 居个中 | 右对齐 | | 注意 | 冒 | 号 | ``` + 好吧,强行对齐字符是很难的。但是,至少比下面这种写法好一点—— ```md @@ -352,6 +353,7 @@ Markdown同样支持引用形式的链接 :-- | :-: | --: 这真的太丑了 | 药不能 | 停!!!! ``` + 真的是*看着令人头晕* From cdb92f27d08d72f5a0ec63249b8b78a581dc1e60 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Wed, 3 Apr 2024 04:08:59 -0700 Subject: [PATCH 055/392] Fix files that error when building --- cue.html.markdown | 4 ++-- es-es/raku-es.html.markdown | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cue.html.markdown b/cue.html.markdown index a1b76ada..a1ff0822 100644 --- a/cue.html.markdown +++ b/cue.html.markdown @@ -1,7 +1,7 @@ --- name: CUE category: language -language: cue +language: CUE filename: learncue.cue contributors: - ["Daniel Cox", "https://github.com/danielpcox"] @@ -24,7 +24,7 @@ disposition: "oblivious" Now we can unify and export to JSON: ```bash -% cue export name.cue disposition.cue +% cue export name.cue disposition.cue { "name": "Daniel", "disposition": "oblivious" diff --git a/es-es/raku-es.html.markdown b/es-es/raku-es.html.markdown index e916d0fd..09341056 100644 --- a/es-es/raku-es.html.markdown +++ b/es-es/raku-es.html.markdown @@ -1,5 +1,5 @@ --- -name: perl6 +name: Raku category: language language: Raku filename: learnraku-es.raku From f5516715c094a7f4ed78f5cfd4099edf112350bd Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Wed, 3 Apr 2024 04:13:28 -0700 Subject: [PATCH 056/392] [pyqt/*] fix formatting rouge doesn't work with uppercase language names, also cleaned up whitespace --- de-de/pyqt-de.html.markdown | 8 ++++---- es-es/pyqt-es.html.markdown | 6 +++--- fr-fr/pyqt-fr.html.markdown | 10 +++++----- id-id/pyqt-id.html.markdown | 6 +++--- it-it/pyqt-it.html.markdown | 8 ++++---- pt-br/pyqt-pt.html.markdown | 6 +++--- pyqt.html.markdown | 20 ++++++++++---------- ru-ru/pyqt-ru.html.markdown | 16 ++++++++-------- zh-cn/pyqt-cn.html.markdown | 6 +++--- 9 files changed, 43 insertions(+), 43 deletions(-) diff --git a/de-de/pyqt-de.html.markdown b/de-de/pyqt-de.html.markdown index 93ee20d4..3b9b6ebb 100644 --- a/de-de/pyqt-de.html.markdown +++ b/de-de/pyqt-de.html.markdown @@ -21,7 +21,7 @@ Diese Version wurde in pyqt erstellt. ```python import sys from PyQt4 import QtGui - + def window(): # Erschafft ein Anwendungsobjekt. app = QtGui.QApplication(sys.argv) @@ -48,10 +48,10 @@ if __name__ == '__main__': Damit wir weitere fortgeschrittene Funktionen in **pyqt** verwenden können, müssen wir anfangen zusätzliche Elemente zu bauen. -Hier zeigen wir wie man eine Dialog Popup Box einführt. +Hier zeigen wir wie man eine Dialog Popup Box einführt. Diese ist nützlich, um den Benutzer eine Entscheidung zu bestätigen oder um Informationen anzuzeigen. -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -70,7 +70,7 @@ def window(): w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) - + # Diese Funktion soll ein Dialogfenster mit einem Knopf erschaffen. # Der Knopf wartet bis er geklickt wird und beendet das Programm def showdialog(): diff --git a/es-es/pyqt-es.html.markdown b/es-es/pyqt-es.html.markdown index 6d4fdde7..9a5eab8c 100644 --- a/es-es/pyqt-es.html.markdown +++ b/es-es/pyqt-es.html.markdown @@ -16,7 +16,7 @@ Esta es una adaptación de la introducción a QT con C++ por [Aleksey Kholovchuk ```python import sys from PyQt4 import QtGui - + def window(): # Crear el objeto de la aplicación app = QtGui.QApplication(sys.argv) @@ -44,7 +44,7 @@ if __name__ == '__main__': Para poder hacer uso de las funciones más avanzades en **pyqt** necesitamos agregar elementos adicionales. Aquí mostramos cómo introducir una caja de diálogo popup, útil para permitir al usuario confirmar su decisión o para brindarnos información. -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -63,7 +63,7 @@ def window(): w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) - + # Esta función debería crear una ventana de diálogo con un botón # que espera a recibir un click y luego sale del programa def showdialog(): diff --git a/fr-fr/pyqt-fr.html.markdown b/fr-fr/pyqt-fr.html.markdown index 6da9a380..7f0f018b 100644 --- a/fr-fr/pyqt-fr.html.markdown +++ b/fr-fr/pyqt-fr.html.markdown @@ -14,14 +14,14 @@ lang: fr-fr Ceci est une adaptation de l'intro C++ à QT par [Aleksey Kholovchuk](https://github.com/vortexxx192 ), certains exemples du code doivent avoir la même fonctionnalité, -cette version ayant juste été faite en utilisant pyqt! +cette version ayant juste été faite en utilisant pyqt! ```python import sys from PyQt4 import QtGui - + def window(): - # Création de l'objet application + # Création de l'objet application app = QtGui.QApplication(sys.argv) # Création d'un widget où notre label sera placé w = QtGui.QWidget() @@ -47,7 +47,7 @@ if __name__ == '__main__': Pour obtenir certaines des fonctionnalités les plus avancées de **pyqt** nous devons commencer par chercher à construire des éléments supplémentaires. Ici nous voyons comment introduire une boîte de dialogue popup, utile pour demander une confirmation à un utilisateur ou fournir des informations. -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -66,7 +66,7 @@ def window(): w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) - + # Cette fonction devrait créer une fenêtre de dialogue avec un bouton # qui attend d'être cliqué puis quitte le programme def showdialog(): diff --git a/id-id/pyqt-id.html.markdown b/id-id/pyqt-id.html.markdown index c4833d06..a9163326 100644 --- a/id-id/pyqt-id.html.markdown +++ b/id-id/pyqt-id.html.markdown @@ -15,10 +15,10 @@ lang: id-id Tulisan ini diadaptasi dari **Intro Qt untuk C++** oleh [Aleksey Kholovchuk](https://github.com/vortexxx192). Kode-kode yang tertulis di sini akan menghasilkan fungsionalitas yang sama. Bedanya, versi ini dibangun menggunakan **PyQt**! -```Python +```python import sys from PyQt4 import QtGui - + def window(): # Buat objek aplikasi app = QtGui.QApplication(sys.argv) @@ -45,7 +45,7 @@ if __name__ == '__main__': Untuk menunjukkan beberapa fitur yang lebih canggih di **PyQt**, kita akan membangun elemen tambahan. Di sini, kita akan membuat Kotak Popup Dialog, yang berguna untuk meminta pengguna untuk mengkonfirmasi keputusan atau untuk menampilkan informasi. -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * diff --git a/it-it/pyqt-it.html.markdown b/it-it/pyqt-it.html.markdown index 7238dd7b..7b5a98c2 100644 --- a/it-it/pyqt-it.html.markdown +++ b/it-it/pyqt-it.html.markdown @@ -14,12 +14,12 @@ lang: it-it Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192 ), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità -che avrebbero se fossero fatte usando pyqt! +che avrebbero se fossero fatte usando pyqt! ```python import sys from PyQt4 import QtGui - + def window(): # Crea un oggetto applicazione app = QtGui.QApplication(sys.argv) @@ -47,7 +47,7 @@ if __name__ == '__main__': Per ottenere alcune delle funzionalità più avanzate in **pyqt**, dobbiamo iniziare a cercare di creare elementi aggiuntivi. Qui mostriamo come creare una finestra popup di dialogo, utile per chiedere all'utente di confermare una decisione o fornire informazioni -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -66,7 +66,7 @@ def window(): w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) - + # Questa funzione dovrebbe creare una finestra di dialogo con un pulsante # che aspetta di essere cliccato e quindi esce dal programma def showdialog(): diff --git a/pt-br/pyqt-pt.html.markdown b/pt-br/pyqt-pt.html.markdown index 40fe82d5..42f744e2 100644 --- a/pt-br/pyqt-pt.html.markdown +++ b/pt-br/pyqt-pt.html.markdown @@ -24,7 +24,7 @@ o pyqt! ```python import sys from PyQt4 import QtGui - + def window(): # Cria um objeto para a aplicação app = QtGui.QApplication(sys.argv) @@ -54,7 +54,7 @@ outros elementos. Aqui mostraremos como criar uma janela popup, muito útil para perguntar ao usuário qual decisão tomar ou exibir alguma informação. -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -73,7 +73,7 @@ def window(): w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) - + # Essa função deve criar uma janela de diálogo com um botão, # aguarda ser clicado e encerra o programa def showdialog(): diff --git a/pyqt.html.markdown b/pyqt.html.markdown index 6bdb6488..2b331874 100644 --- a/pyqt.html.markdown +++ b/pyqt.html.markdown @@ -11,25 +11,25 @@ contributors: This is an adaption on the C++ intro to QT by [Aleksey Kholovchuk](https://github.com/vortexxx192 ), some of the code examples should result in the same functionality -this version just having been done using pyqt! +this version just having been done using pyqt! ```python import sys from PyQt4 import QtGui - + def window(): - # Create an application object + # Create an application object app = QtGui.QApplication(sys.argv) # Create a widget where our label will be placed in w = QtGui.QWidget() - # Add a label to the widget + # Add a label to the widget b = QtGui.QLabel(w) - # Set some text for the label + # Set some text for the label b.setText("Hello World!") - # Give some size and placement information + # Give some size and placement information w.setGeometry(100, 100, 200, 50) b.move(50, 20) - # Give our window a nice title + # Give our window a nice title w.setWindowTitle("PyQt") # Have everything display w.show() @@ -41,10 +41,10 @@ if __name__ == '__main__': ``` -In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements. +In order to get some of the more advanced features in **pyqt** we need to start looking at building additional elements. Here we show how to introduce a dialog popup box, useful for asking the user to confirm a decision or to provide information. -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -63,7 +63,7 @@ def window(): w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) - + # This function should create a dialog window with a button # that waits to be clicked and then exits the program def showdialog(): diff --git a/ru-ru/pyqt-ru.html.markdown b/ru-ru/pyqt-ru.html.markdown index 13b91d2d..a7e14c02 100644 --- a/ru-ru/pyqt-ru.html.markdown +++ b/ru-ru/pyqt-ru.html.markdown @@ -11,7 +11,7 @@ translators: **Qt** - широко известный кросс-платформенный фреймворк для разработки программного обеспечения, который может быть использован на различных софтварных и хардварных платформах без какого-либо -изменения в коде. Данный фреймворк при этом обладает мощью и скоростью нативных приложений. +изменения в коде. Данный фреймворк при этом обладает мощью и скоростью нативных приложений. Qt и был изначально написан на *C++*. Данный текст является адаптацией введения в Qt на C++ под авторством Алексея Ковальчука для pyqt. @@ -20,7 +20,7 @@ Qt и был изначально написан на *C++*. ```python def window(): - # Создайте объект приложения + # Создайте объект приложения app = QtGui.QApplication(sys.argv) # Создайте виджет, где будет находиться наш лейбл w = QtGui.QWidget() @@ -28,10 +28,10 @@ def window(): b = QtGui.QLabel(w) # Задайте текст для лейбла b.setText("Hello World!") - # Задайте информация о размере и расположении + # Задайте информация о размере и расположении w.setGeometry(100, 100, 200, 50) b.move(50, 20) - # Задайте заголовок окна + # Задайте заголовок окна w.setWindowTitle("PyQt") # Все ранее написанное выводится на экран w.show() @@ -43,11 +43,11 @@ if __name__ == '__main__': ``` -Для того чтобы получить более продвинутые функции приложения в pyqt, нам необходимо -обратить внимание на создание дополнительных элементов. Ниже представлено создание всплывающего диалогового окна, которое просит пользователя подтвердить его решение или предоставить какую-либо +Для того чтобы получить более продвинутые функции приложения в pyqt, нам необходимо +обратить внимание на создание дополнительных элементов. Ниже представлено создание всплывающего диалогового окна, которое просит пользователя подтвердить его решение или предоставить какую-либо информацию. -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -67,7 +67,7 @@ def window(): w.show() sys.exit(app.exec_()) -Данная функция должна создавать диалоговое окно с кнопкой, которая ждет клика по себе +Данная функция должна создавать диалоговое окно с кнопкой, которая ждет клика по себе и затем завершает программу. def showdialog(): diff --git a/zh-cn/pyqt-cn.html.markdown b/zh-cn/pyqt-cn.html.markdown index 55e5bbe3..04041c83 100644 --- a/zh-cn/pyqt-cn.html.markdown +++ b/zh-cn/pyqt-cn.html.markdown @@ -19,7 +19,7 @@ lang: zh-cn ```python import sys from PyQt4 import QtGui - + def window(): # 创建应用对象 app = QtGui.QApplication(sys.argv) @@ -44,7 +44,7 @@ if __name__ == '__main__': 为了运用 pyqt 中一些更高级的功能,我们需要开始学习使用其他控件。下文演示了如何弹出对话框,该对话框在用户确认操作或输入信息等情况下经常用到。 -```Python +```python import sys from PyQt4.QtGui import * from PyQt4.QtCore import * @@ -62,7 +62,7 @@ def window(): w.setWindowTitle("PyQt Dialog") w.show() sys.exit(app.exec_()) - + # 对话框窗口创建函数 # 当窗口中的按钮被点击时退出本程序 def showdialog(): From ae7197c6a692f9b67e98a721ed5debb582bfa599 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Wed, 3 Apr 2024 04:14:45 -0700 Subject: [PATCH 057/392] [powershell/*] fix syntax highlighting --- es-es/powershell-es.html.markdown | 6 +++--- powershell.html.markdown | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/es-es/powershell-es.html.markdown b/es-es/powershell-es.html.markdown index 9eb35967..5b12b961 100644 --- a/es-es/powershell-es.html.markdown +++ b/es-es/powershell-es.html.markdown @@ -34,7 +34,7 @@ $PSVersionTable Para obtener ayuda: -``` +```powershell # Si necesita encontrar algún comando Get-Command about_* # tiene por abreviación (o alias): gcm Get-Command -Verb Add # lista todos los comandos que tienen por verbo 'Add' @@ -51,7 +51,7 @@ Update-Help # Actualiza la ayuda (debe ser ejecutado en una consola elevada como Acá inicia el tutorial: -``` +```powershell # Como ya lo notó, los comentarios empiezan con # # Ejemplo de un simple hola mundo: @@ -299,7 +299,7 @@ $Shortcut.Save() Configurando el shell -``` +```powershell # $Profile es la ruta completa para su `Microsoft.PowerShell_profile.ps1` # Todo el código alojado allí será ejecutado cuando se ejecuta una nueva sesión de PS if (-not (Test-Path $Profile)) { diff --git a/powershell.html.markdown b/powershell.html.markdown index 2e7539a5..50e1e27e 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -677,7 +677,7 @@ Powershell as a Tool: Getting Help: -```Powershell +```powershell # Find commands Get-Command about_* # alias: gcm Get-Command -Verb Add @@ -694,7 +694,7 @@ Update-Help # Run as admin If you are uncertain about your environment: -```Powershell +```powershell Get-ExecutionPolicy -List Set-ExecutionPolicy AllSigned # Execution policies include: @@ -708,7 +708,7 @@ help about_Execution_Policies # for more info $PSVersionTable ``` -```Powershell +```powershell # Calling external commands, executables, # and functions with the call operator. # Exe paths with arguments passed or containing spaces can create issues. From 787e9710b9af69eec7dcb72f12af34aef870951e Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Wed, 3 Apr 2024 04:16:08 -0700 Subject: [PATCH 058/392] Syntax highlighting --- CONTRIBUTING.markdown | 10 +++-- de-de/visualbasic-de.html.markdown | 2 +- es-es/forth-es.html.markdown | 2 +- es-es/visualbasic-es.html.markdown | 2 +- es-es/wolfram-es.html.markdown | 2 +- fa-ir/css-fa.html.markdown | 50 ++++++++++++------------- fr-fr/wolfram-fr.html.markdown | 2 +- id-id/coffeescript-id.html.markdown | 2 +- pt-br/visualbasic-pt.html.markdown | 2 +- qsharp.html.markdown | 2 +- ru-ru/forth-ru.html.markdown | 2 +- ru-ru/learnvisualbasic-ru.html.markdown | 2 +- sk-sk/elixir-sk.html.markdown | 2 +- visualbasic.html.markdown | 2 +- wolfram.html.markdown | 2 +- zh-cn/visualbasic-cn.html.markdown | 2 +- zh-cn/wolfram-cn.html.markdown | 2 +- 17 files changed, 47 insertions(+), 43 deletions(-) diff --git a/CONTRIBUTING.markdown b/CONTRIBUTING.markdown index 430ecea0..f3556efa 100644 --- a/CONTRIBUTING.markdown +++ b/CONTRIBUTING.markdown @@ -34,7 +34,7 @@ review them more effectively and/or individually. * **Use UTF-8** * For translations (or EN articles with non-ASCII characters) please ensure your file is UTF-8 encoded. - * Try to leave out the byte-order-mark at the start of the file (in Vim, use + * Leave out the byte-order-mark (BOM) at the start of the file (in Vim, use `:set nobomb`). * You can check if the file contains a BOM on Linux/Unix systems by running `file language.html.markdown` You will see this if it uses a BOM: @@ -58,7 +58,7 @@ Other fields: *tool* or *Algorithms & Data Structures*. Defaults to *language* if omitted. * **filename**: The filename for this article's code. It will be fetched, mashed together, and made downloadable. - * For non-English articles, *filename* should have a language-specific + * For non-English articles, *filename* should have a language-specific suffix. * **lang**: For translations, the human language this article is in. For categorization, mostly. @@ -76,7 +76,11 @@ lang: ep-ep *-- ``` -### Should I add myself as a Contributor? +### Syntax highlighter + +[Rouge](https://github.com/rouge-ruby/rouge/wiki/List-of-supported-languages-and-lexers) is used for syntax highlighting. + +### Should I add myself as a contributor? If you want to add yourself to contributors, keep in mind that contributors get equal billing, and the first contributor usually wrote the whole article. Please diff --git a/de-de/visualbasic-de.html.markdown b/de-de/visualbasic-de.html.markdown index a0dde471..6194e906 100644 --- a/de-de/visualbasic-de.html.markdown +++ b/de-de/visualbasic-de.html.markdown @@ -8,7 +8,7 @@ filename: learnvisualbasic-de.vb lang: de-de --- -``` +```visualbasic Module Modul1 Sub Main() diff --git a/es-es/forth-es.html.markdown b/es-es/forth-es.html.markdown index edc5d38c..61123151 100644 --- a/es-es/forth-es.html.markdown +++ b/es-es/forth-es.html.markdown @@ -13,7 +13,7 @@ Forth fue criado por Charles H. Moore en los 70s. Forth es un lenguaje imperativ Nota: Este articulo enfoca predominantemente en la Gforth implementación de Forth, pero casi todo de lo que esta escrito aquí debe funcionar en otro sitio. -``` +```forth \ Este es un comentario ( Este es un comentario también pero solo esta usado cuando definiendo palabras. ) diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown index c677c20f..fb0b1d27 100644 --- a/es-es/visualbasic-es.html.markdown +++ b/es-es/visualbasic-es.html.markdown @@ -8,7 +8,7 @@ filename: learnvisualbasic-es.vb lang: es-es --- -``` +```visualbasic Module Module1 Sub Main() diff --git a/es-es/wolfram-es.html.markdown b/es-es/wolfram-es.html.markdown index 44ec9e09..6858c286 100644 --- a/es-es/wolfram-es.html.markdown +++ b/es-es/wolfram-es.html.markdown @@ -15,7 +15,7 @@ El lenguaje de Wolfram tiene varias interfaces: El código de este ejemplo se puede escribir en cualquier interfaz y editarlo con Wolfram Workbench. Cargar directamente en Matematica puede resultar incómodo porque el archivo no contiene información de formato de celda (lo que haría que el archivo sea un desastre enorme para ser leído como texto) - puede ser visto / editado pero tal vez requerira algún ajuste. -``` +```mathematica (* Esto es un comentario *) (* En Mathematica en lugar de utilizar estos comentarios, puede crear una celda de texto diff --git a/fa-ir/css-fa.html.markdown b/fa-ir/css-fa.html.markdown index 4e222eb2..93af9132 100644 --- a/fa-ir/css-fa.html.markdown +++ b/fa-ir/css-fa.html.markdown @@ -29,21 +29,21 @@ filename: learncss-fa.css

    در CSS همه توضیحات داخل ستاره-بروم نوشته میشوند زیرا CSS دستوری برای توضیحات تک خطی مثل C ندارد

    -```CSS +```css /* comments appear inside slash-asterisk, just like this line! there are no "one-line comments"; this is the only comment style */ ```

    به طور کلی دستورات CSS بسیار ساده هستند که در آن یک انتخابگر (selector) عنصری را در روی صفحه هدف قرار میدهد.

    -```CSS +```css selector { property: value; /* more properties...*/ } ```

    با استفاده از ستاره می توان برای همه عناصر روی صفحه استایل تعریف کرد

    -```CSS +```css * { color:red; } ``` @@ -55,129 +55,129 @@ selector { property: value; /* more properties...*/ }

    شما میتوانید با استفاده از نام کلاس آنرا انتخاب کنید

    -```CSS +```css .some-class { } ```

    یا با استفاده از نام دو کلاس

    -```CSS +```css .some-class.class2 { } ```

    یا با استفاده از نام id

    -```CSS +```css #someId { } ```

    یا با استفاده از نام خود عنصر

    -```CSS +```css div { } ```

    یا با استفاده از `attr`

    -```CSS +```css [attr] { font-size:smaller; } ```

    یا با استفاده از ارزشی که برای `attr` مشخص شده

    -```CSS +```css [attr='value'] { font-size:smaller; } ```

    با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `val` شروع میشود در CSS3

    -```CSS +```css [attr^='val'] { font-size:smaller; } ```

    با استفاده از ارزشی که برای `attr` مشخص شده و آن ارزش با `ue` به پایان میرسد در CSS3

    -```CSS +```css [attr$='ue'] { font-size:smaller; } ```

    یا با انتخاب بوسیله یکی از ارزشهایی که در لیست `otherAttr` بوسیله فاصله از هم جدا شده اند در CSS3

    -```CSS +```css [attr$='ue'] { font-size:smaller; } ```

    یا ارزش(`value`) دقیقاً خود ارزش(`value`) یا بوسیله `-` که یونیکد (U+002D) از حرف بعدی جدا شود

    -```CSS +```css [otherAttr|='en'] { font-size:smaller; } ```

    و مهمتر از همه اینکه میتوان آنها را ترکیب کرد. نکته مهمی که در اینجا باید مد نظر داشته باشید این است که هنگام ترکیب نباید هیچگونه فاصله ای بین آنها قرار گیرد زیرا در این حالت معنای دستور تغییر میکند

    -```CSS +```css div.some-class[attr$='ue'] { } ```

    CSS این امکان را به شما میدهد که یک عنصر را بوسیله والدین آن انتخاب کنید

    برای مثال دستور زیر همه عناصری را که نام کلاس آنها `.class-name` و دارای پدر و مادری با این مشخصه `div.some-parent` هستند را انتخاب میکند.

    -```CSS +```css div.some-parent > .class-name {} ```

    یا دستور زیر که همه عناصری را که نام کلاس آنها `.class-name` و داخل عنصری با مشخصه `div.some-parent` هستند را در هر عمقی که باشند (یعنی فرزندی از فرزندان `div.some-parent` باشند) انتخاب میکند.

    -```CSS +```css div.some-parent .class-name {} ```

    نکته ای که در اینجا باید به آن توجه کنید این است که این رستور با فاصله ای بین نام دو کلاس همراه است و با مثال زیر که در بالا هم ذکر شد تفاوت دارد.

    -```CSS +```css div.some-parent.class-name {} ```

    دستور زیر همه عناصری را که نام کلاس آنها `.this-element` و بلافاصله بعد از عنصری با مشخصه `.i-am-before` قرار دارد را انتخاب میکند.

    -```CSS +```css .i-am-before + .this-element { } ```

    هر خواهر یا برادری که بعد از `.i-am-before` بیاید در اینجا لازم نیست بلافاصله بعد از هم قرار بگیرند ولی باید دارای پدر و مادری یکسان باشند.

    -```CSS +```css .i-am-any-before ~ .this-element {} ```

    در زیر چند نمونه از شبه کلاسها را معرفی میکنیم که به شما اجازه میدهد عناصر را بر اساس رفتار آنها در صفحه انتخاب کنید.

    برای مثال زمانی که اشاره گر ماوس روی عنصری بر روی صفحه قرار دارد.

    -```CSS +```css selector:hover {} ```

    یا زمانی از یک لینک بازید کردید.

    -```CSS +```css selected:visited {} ```

    یا زمانی از لینکی بازید نشده است.

    -```CSS +```css selected:link {} ```

    یا زمانی که روی یک عنصر ورودی متمرکز شده.

    -```CSS +```css selected:focus {} ```

    واحدها

    -```CSS +```css selector { /* واحدها اندازه */ @@ -247,7 +247,7 @@ selector {

    به مثال زیر توجه کنید:

    -```CSS +```css /*A*/ p.class1[attr='value'] diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 7b446259..10a37994 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -21,7 +21,7 @@ Ce code d'exemple peut être utilisé et modifié dans ces logiciels. Cependant, copier-coller directement dans Mathematica peut causer des problèmes de formatage, car il ne contient aucune information de mise en page. -``` +```mathematica (* Ceci est un commentaire *) (* Dans Mathematica, au lieu d'utiliser ces commentaires, vous pouvez créer des diff --git a/id-id/coffeescript-id.html.markdown b/id-id/coffeescript-id.html.markdown index 7fa40bb6..fc876184 100644 --- a/id-id/coffeescript-id.html.markdown +++ b/id-id/coffeescript-id.html.markdown @@ -16,7 +16,7 @@ dan kompatibel dengan semua *runtime* JavaScript. Lihat juga [website CoffeeScript](http://coffeescript.org/) yang memiliki tutorial lengkap tentang CoffeeScript. -```CoffeeScript +```coffeescript # CoffeeScript adalah bahasa hipster. # Mengikuti tren bahasa modern lainnya. # Sehingga, seperti Ruby dan Python, untuk komentar digunakan tanda pagar. diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown index 81292798..dcc72c04 100644 --- a/pt-br/visualbasic-pt.html.markdown +++ b/pt-br/visualbasic-pt.html.markdown @@ -8,7 +8,7 @@ lang: pt-br filename: learnvisualbasic-pt.vb --- -``` +```visualbasic Module Module1 module Module1 diff --git a/qsharp.html.markdown b/qsharp.html.markdown index 10015d7f..04e697a4 100644 --- a/qsharp.html.markdown +++ b/qsharp.html.markdown @@ -9,7 +9,7 @@ filename: LearnQSharp.qs Q# is a high-level domain-specific language which enables developers to write quantum algorithms. Q# programs can be executed on a quantum simulator running on a classical computer and (in future) on quantum computers. -```C# +```c# // Single-line comments start with // diff --git a/ru-ru/forth-ru.html.markdown b/ru-ru/forth-ru.html.markdown index 90936b19..96fa0941 100644 --- a/ru-ru/forth-ru.html.markdown +++ b/ru-ru/forth-ru.html.markdown @@ -13,7 +13,7 @@ lang: ru-ru Внимание: этот материал использует реализацию Форта - Gforth, но большая часть написанного будет работать в других средах. -``` +```forth \ Это комментарий ( Это тоже комментарий, но используется для предоределённых слов ) diff --git a/ru-ru/learnvisualbasic-ru.html.markdown b/ru-ru/learnvisualbasic-ru.html.markdown index 72e1358c..6242fc42 100644 --- a/ru-ru/learnvisualbasic-ru.html.markdown +++ b/ru-ru/learnvisualbasic-ru.html.markdown @@ -8,7 +8,7 @@ filename: learnvisualbasic-ru.vb lang: ru-ru --- -```vbnet +```visualbasic Module Module1 Sub Main() diff --git a/sk-sk/elixir-sk.html.markdown b/sk-sk/elixir-sk.html.markdown index d5159610..c9522b49 100644 --- a/sk-sk/elixir-sk.html.markdown +++ b/sk-sk/elixir-sk.html.markdown @@ -14,7 +14,7 @@ Elixir je moderný funkcionálny jazyk vytvorený nad Erlang VM (virtuálnym strojom). Je plne kompatibilný s Erlangom, ale ponúka viac štandardnú syntax a množstvo funkcií. -```Elixir +```elixir # Jednoriadkový komentár začína symbolom # diff --git a/visualbasic.html.markdown b/visualbasic.html.markdown index a253af48..b79017dc 100644 --- a/visualbasic.html.markdown +++ b/visualbasic.html.markdown @@ -5,7 +5,7 @@ contributors: filename: learnvisualbasic.vb --- -``` +```visualbasic Module Module1 Sub Main() diff --git a/wolfram.html.markdown b/wolfram.html.markdown index 5fddbc82..fa8ee078 100644 --- a/wolfram.html.markdown +++ b/wolfram.html.markdown @@ -14,7 +14,7 @@ Wolfram Language has several interfaces: The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. -``` +```mathematica (* This is a comment *) (* In Mathematica instead of using these comments you can create a text cell diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown index e30041b3..cda7b864 100644 --- a/zh-cn/visualbasic-cn.html.markdown +++ b/zh-cn/visualbasic-cn.html.markdown @@ -8,7 +8,7 @@ lang: zh-cn filename: learnvisualbasic-cn.vb --- -``` +```visualbasic Module Module1 Sub Main() diff --git a/zh-cn/wolfram-cn.html.markdown b/zh-cn/wolfram-cn.html.markdown index 9d6ef54f..64990234 100644 --- a/zh-cn/wolfram-cn.html.markdown +++ b/zh-cn/wolfram-cn.html.markdown @@ -18,7 +18,7 @@ Wolfram 语言有几个界面。 本例中的代码可以在任何界面中输入,并使用 Wolfram Workbench 进行编辑。直接加载到 Mathematica 中可能会很不方便,因为该文件不包含单元格格式化信息(这将使该文件作为文本阅读时变得一团糟)--它可以被查看/编辑,但可能需要一些设置。 -```mma +```mathematica (* 这是一个注释 *) (* 在Mathematica中,您可以创建一个文本单元格,用排版好的文本和图像来注释您的代码,而不是使用这些注释 *) From 818b8eec46b11b36b5235ecbce540557afec4687 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 4 Apr 2024 00:27:01 -0700 Subject: [PATCH 059/392] Convert \r\n to \n --- amd.html.markdown | 424 ++--- de-de/csharp-de.html.markdown | 1780 ++++++++++---------- de-de/elixir-de.html.markdown | 846 +++++----- de-de/javascript-de.html.markdown | 1050 ++++++------ de-de/make-de.html.markdown | 526 +++--- docker.html.markdown | 562 +++--- es-es/docker-es.html.markdown | 334 ++-- it-it/toml-it.html.markdown | 552 +++--- make.html.markdown | 492 +++--- opengl.html.markdown | 1530 ++++++++--------- pt-br/make-pt.html.markdown | 490 +++--- ru-ru/asymptotic-notation-ru.html.markdown | 450 ++--- tr-tr/sql-tr.html.markdown | 248 +-- vi-vn/git-vi.html.markdown | 776 ++++----- vi-vn/objective-c-vi.html.markdown | 632 +++---- zh-cn/c++-cn.html.markdown | 1144 ++++++------- zh-cn/elisp-cn.html.markdown | 690 ++++---- zh-cn/matlab-cn.html.markdown | 1008 +++++------ 18 files changed, 6767 insertions(+), 6767 deletions(-) diff --git a/amd.html.markdown b/amd.html.markdown index d7fb41ba..fc8f20a4 100644 --- a/amd.html.markdown +++ b/amd.html.markdown @@ -1,212 +1,212 @@ ---- -category: tool -tool: amd -contributors: - - ["Frederik Ring", "https://github.com/m90"] -filename: learnamd.js ---- - -## Getting Started with AMD - -The **Asynchronous Module Definition** API specifies a mechanism for defining -JavaScript modules such that the module and its dependencies can be asynchronously -loaded. This is particularly well suited for the browser environment where -synchronous loading of modules incurs performance, usability, debugging, and -cross-domain access problems. - -### Basic concept -```javascript -// The basic AMD API consists of nothing but two methods: `define` and `require` -// and is all about module definition and consumption: -// `define(id?, dependencies?, factory)` defines a module -// `require(dependencies, callback)` imports a set of dependencies and -// consumes them in the passed callback - -// Let's start by using define to define a new named module -// that has no dependencies. We'll do so by passing a name -// and a factory function to define: -define('awesomeAMD', function(){ - var isAMDAwesome = function(){ - return true; - }; - // The return value of a module's factory function is - // what other modules or require calls will receive when - // requiring our `awesomeAMD` module. - // The exported value can be anything, (constructor) functions, - // objects, primitives, even undefined (although that won't help too much). - return isAMDAwesome; -}); - -// Now, let's define another module that depends upon our `awesomeAMD` module. -// Notice that there's an additional argument defining our -// module's dependencies now: -define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ - // dependencies will be passed to the factory's arguments - // in the order they are specified - var tellEveryone = function(){ - if (awesomeAMD()){ - alert('This is sOoOo rad!'); - } else { - alert('Pretty dull, isn\'t it?'); - } - }; - return tellEveryone; -}); - -// As we do know how to use define now, let's use `require` to -// kick off our program. `require`'s signature is `(arrayOfDependencies, callback)`. -require(['loudmouth'], function(loudmouth){ - loudmouth(); -}); - -// To make this tutorial run code, let's implement a very basic -// (non-asynchronous) version of AMD right here on the spot: -function define(name, deps, factory){ - // notice how modules without dependencies are handled - define[name] = require(factory ? deps : [], factory || deps); -} - -function require(deps, callback){ - var args = []; - // first let's retrieve all the dependencies needed - // by the require call - for (var i = 0; i < deps.length; i++){ - args[i] = define[deps[i]]; - } - // satisfy all the callback's dependencies - return callback.apply(null, args); -} -// you can see this code in action here: http://jsfiddle.net/qap949pd/ -``` - -### Real-world usage with require.js - -In contrast to the introductory example, `require.js` (the most popular AMD library) actually implements the **A** in **AMD**, enabling you to load modules and their dependencies asynchronously via XHR: - -```javascript -/* file: app/main.js */ -require(['modules/someClass'], function(SomeClass){ - // the callback is deferred until the dependency is loaded - var thing = new SomeClass(); -}); -console.log('So here we are, waiting!'); // this will run first -``` - -By convention, you usually store one module in one file. `require.js` can resolve module names based on file paths, so you don't have to name your modules, but can simply reference them using their location. In the example `someClass` is assumed to be in the `modules` folder, relative to your configuration's `baseUrl`: - -* app/ - * main.js - * modules/ - * someClass.js - * someHelpers.js - * ... - * daos/ - * things.js - * ... - -This means we can define `someClass` without specifying a module id: - -```javascript -/* file: app/modules/someClass.js */ -define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ - // module definition, of course, will also happen asynchronously - function SomeClass(){ - this.method = function(){/**/}; - // ... - } - return SomeClass; -}); -``` -To alter the default path mapping behavior use `requirejs.config(configObj)` in your `main.js`: - -```javascript -/* file: main.js */ -requirejs.config({ - baseUrl : 'app', - paths : { - // you can also load modules from other locations - jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } -}); -require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ - // a `main` file needs to call require at least once, - // otherwise no code will ever run - coolLib.doFancyStuffWith(helpers.transform($('#foo'))); -}); -``` -`require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload: - -```html - - - - A hundred script tags? Never again! - - - - - -``` - -### Optimizing a whole project using r.js - -Many people prefer using AMD for sane code organization during development, but still want to ship a single script file in production instead of performing hundreds of XHRs on page load. - -`require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption. - -Install it using `npm`: -```shell -$ npm install requirejs -g -``` - -Now you can feed it with a configuration file: -```shell -$ r.js -o app.build.js -``` - -For our above example the configuration might look like: -```javascript -/* file : app.build.js */ -({ - name : 'main', // name of the entry point - out : 'main-built.js', // name of the file to write the output to - baseUrl : 'app', - paths : { - // `empty:` tells r.js that this should still be loaded from the CDN, using - // the location specified in `main.js` - jquery : 'empty:', - coolLibFromBower : '../bower_components/cool-lib/coollib' - } -}) -``` - -To use the built file in production, simply swap `data-main`: -```html - -``` - -An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo. - -### Topics not covered in this tutorial -* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) -* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) -* [Advanced configuration](http://requirejs.org/docs/api.html#config) -* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) -* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) -* [Using almond.js for builds](https://github.com/jrburke/almond) - -### Further reading: - -* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) -* [Why AMD?](http://requirejs.org/docs/whyamd.html) -* [Universal Module Definition](https://github.com/umdjs/umd) - -### Implementations: - -* [require.js](http://requirejs.org) -* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) -* [cujo.js](http://cujojs.com/) -* [curl.js](https://github.com/cujojs/curl) -* [lsjs](https://github.com/zazl/lsjs) -* [mmd](https://github.com/alexlawrence/mmd) +--- +category: tool +tool: amd +contributors: + - ["Frederik Ring", "https://github.com/m90"] +filename: learnamd.js +--- + +## Getting Started with AMD + +The **Asynchronous Module Definition** API specifies a mechanism for defining +JavaScript modules such that the module and its dependencies can be asynchronously +loaded. This is particularly well suited for the browser environment where +synchronous loading of modules incurs performance, usability, debugging, and +cross-domain access problems. + +### Basic concept +```javascript +// The basic AMD API consists of nothing but two methods: `define` and `require` +// and is all about module definition and consumption: +// `define(id?, dependencies?, factory)` defines a module +// `require(dependencies, callback)` imports a set of dependencies and +// consumes them in the passed callback + +// Let's start by using define to define a new named module +// that has no dependencies. We'll do so by passing a name +// and a factory function to define: +define('awesomeAMD', function(){ + var isAMDAwesome = function(){ + return true; + }; + // The return value of a module's factory function is + // what other modules or require calls will receive when + // requiring our `awesomeAMD` module. + // The exported value can be anything, (constructor) functions, + // objects, primitives, even undefined (although that won't help too much). + return isAMDAwesome; +}); + +// Now, let's define another module that depends upon our `awesomeAMD` module. +// Notice that there's an additional argument defining our +// module's dependencies now: +define('loudmouth', ['awesomeAMD'], function(awesomeAMD){ + // dependencies will be passed to the factory's arguments + // in the order they are specified + var tellEveryone = function(){ + if (awesomeAMD()){ + alert('This is sOoOo rad!'); + } else { + alert('Pretty dull, isn\'t it?'); + } + }; + return tellEveryone; +}); + +// As we do know how to use define now, let's use `require` to +// kick off our program. `require`'s signature is `(arrayOfDependencies, callback)`. +require(['loudmouth'], function(loudmouth){ + loudmouth(); +}); + +// To make this tutorial run code, let's implement a very basic +// (non-asynchronous) version of AMD right here on the spot: +function define(name, deps, factory){ + // notice how modules without dependencies are handled + define[name] = require(factory ? deps : [], factory || deps); +} + +function require(deps, callback){ + var args = []; + // first let's retrieve all the dependencies needed + // by the require call + for (var i = 0; i < deps.length; i++){ + args[i] = define[deps[i]]; + } + // satisfy all the callback's dependencies + return callback.apply(null, args); +} +// you can see this code in action here: http://jsfiddle.net/qap949pd/ +``` + +### Real-world usage with require.js + +In contrast to the introductory example, `require.js` (the most popular AMD library) actually implements the **A** in **AMD**, enabling you to load modules and their dependencies asynchronously via XHR: + +```javascript +/* file: app/main.js */ +require(['modules/someClass'], function(SomeClass){ + // the callback is deferred until the dependency is loaded + var thing = new SomeClass(); +}); +console.log('So here we are, waiting!'); // this will run first +``` + +By convention, you usually store one module in one file. `require.js` can resolve module names based on file paths, so you don't have to name your modules, but can simply reference them using their location. In the example `someClass` is assumed to be in the `modules` folder, relative to your configuration's `baseUrl`: + +* app/ + * main.js + * modules/ + * someClass.js + * someHelpers.js + * ... + * daos/ + * things.js + * ... + +This means we can define `someClass` without specifying a module id: + +```javascript +/* file: app/modules/someClass.js */ +define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ + // module definition, of course, will also happen asynchronously + function SomeClass(){ + this.method = function(){/**/}; + // ... + } + return SomeClass; +}); +``` +To alter the default path mapping behavior use `requirejs.config(configObj)` in your `main.js`: + +```javascript +/* file: main.js */ +requirejs.config({ + baseUrl : 'app', + paths : { + // you can also load modules from other locations + jquery : '//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}); +require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolLib, helpers){ + // a `main` file needs to call require at least once, + // otherwise no code will ever run + coolLib.doFancyStuffWith(helpers.transform($('#foo'))); +}); +``` +`require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload: + +```html + + + + A hundred script tags? Never again! + + + + + +``` + +### Optimizing a whole project using r.js + +Many people prefer using AMD for sane code organization during development, but still want to ship a single script file in production instead of performing hundreds of XHRs on page load. + +`require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption. + +Install it using `npm`: +```shell +$ npm install requirejs -g +``` + +Now you can feed it with a configuration file: +```shell +$ r.js -o app.build.js +``` + +For our above example the configuration might look like: +```javascript +/* file : app.build.js */ +({ + name : 'main', // name of the entry point + out : 'main-built.js', // name of the file to write the output to + baseUrl : 'app', + paths : { + // `empty:` tells r.js that this should still be loaded from the CDN, using + // the location specified in `main.js` + jquery : 'empty:', + coolLibFromBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +To use the built file in production, simply swap `data-main`: +```html + +``` + +An incredibly detailed [overview of build options](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is available in the GitHub repo. + +### Topics not covered in this tutorial +* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) +* [Advanced configuration](http://requirejs.org/docs/api.html#config) +* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) +* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Using almond.js for builds](https://github.com/jrburke/almond) + +### Further reading: + +* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Why AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementations: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) diff --git a/de-de/csharp-de.html.markdown b/de-de/csharp-de.html.markdown index 18a23017..662c2e76 100644 --- a/de-de/csharp-de.html.markdown +++ b/de-de/csharp-de.html.markdown @@ -1,890 +1,890 @@ ---- -language: C# -contributors: - - ["Irfan Charania", "https://github.com/irfancharania"] - - ["Max Yankov", "https://github.com/golergka"] - - ["Melvyn Laïly", "http://x2a.yt"] - - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] -translators: - - ["Frederik Ring", "https://github.com/m90"] -filename: LearnCSharp-de.cs -lang: de-de ---- -C# ist eine elegante, typsichere und objektorientierte Sprache, mit der Entwickler eine Vielzahl sicherer und robuster Anwendungen erstellen können, die im .NET Framework ausgeführt werden. - -[Mehr über C# erfährst du hier.](http://msdn.microsoft.com/de-de/library/vstudio/z1zx9t92.aspx) - -```c# -// Einzeilige Kommentare starten mit zwei Schrägstrichen: // -/* -Mehrzeile Kommentare wie in C Schrägstrich / Stern -*/ -/// -/// XML-Kommentare können zur automatisierten Dokumentation verwendet werden -/// - -// Zu Beginn werden die in der Datei verwendeten Namespaces aufgeführt -using System; -using System.Collections.Generic; -using System.Data.Entity; -using System.Dynamic; -using System.Linq; -using System.Linq.Expressions; -using System.Net; -using System.Threading.Tasks; -using System.IO; - -// definiert einen Namespace um Code in "packages" zu organisieren -namespace Learning -{ - // Jede .cs-Datei sollte zumindest eine Klasse mit dem Namen der Datei - // enthalten. Das ist zwar nicht zwingend erforderlich, es anders zu - // handhaben führt aber unweigerlich ins Chaos (wirklich)! - public class LearnCSharp - { - // Zuerst erklärt dieses Tutorial die Syntax-Grundlagen, - // wenn du bereits Java oder C++ programmieren kannst: - // lies bei "Interessante Features" weiter! - public static void Syntax() - { - // Mit Console.WriteLine kannst du einfachen Text ausgeben: - Console.WriteLine("Hallo Welt"); - Console.WriteLine( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // Console.Write erzeugt keinen Zeilenumbruch - Console.Write("Hallo "); - Console.Write("Welt"); - - /////////////////////////////////////////////////// - // Typen & Variablen - /////////////////////////////////////////////////// - - // Deklariere eine Variable mit - - // Sbyte - Vorzeichenbehaftete 8-Bit Ganzzahl - // (-128 <= sbyte <= 127) - sbyte fooSbyte = 100; - - // Byte - Vorzeichenlose 8-Bit Ganzzahl - // (0 <= byte <= 255) - byte fooByte = 100; - - // Short - 16-Bit Ganzzahl - // Vorzeichenbehaftet - (-32,768 <= short <= 32,767) - // Vorzeichenlos - (0 <= ushort <= 65,535) - short fooShort = 10000; - ushort fooUshort = 10000; - - // Integer - 32-bit Ganzzahl - int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) - uint fooUint = 1; // (0 <= uint <= 4,294,967,295) - - // Long - 64-bit Ganzzahl - long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) - // Ganze Zahlen werden standardmäßig - je nach Größe - als int oder - // uint behandelt. Ein nachgestelltes L markiert den Wert als long - // oder ulong. - - // Double - Double-precision 64-bit IEEE 754 Fließkommazahl - double fooDouble = 123.4; // Genauigkeit: 15-16 Stellen - - // Float - Single-precision 32-bit IEEE 754 Fließkommazahl - float fooFloat = 234.5f; // Genauigkeit: 7 Stellen - // Das nachgestellte f zeigt an dass es sich um einen Wert vom Typ - // float handelt - - // Decimal - ein 128-Bit-Datentyp mit größerer Genauigkeit als - // andere Fließkommatypen, und somit bestens geeignet für - // die Berechnung von Geld- und Finanzwerten - decimal fooDecimal = 150.3m; - - // Boolean - true & false - bool fooBoolean = true; // oder false - - // Char - Ein einzelnes 16-Bit Unicode Zeichen - char fooChar = 'A'; - - // Strings - im Gegensatz zu allen vorhergehenden Basistypen, die - // alle Werttypen sind, ist String ein Referenztyp. Strings sind - // somit nullable, Werttypen sind dies nicht. - string fooString = "\"maskiere\" Anführungszeichen, und füge \n (Umbrüche) und \t (Tabs) hinzu"; - Console.WriteLine(fooString); - - // Jeder Buchstabe eines Strings kann über seinen Index - // referenziert werden: - char charFromString = fooString[1]; // => 'e' - // Strings sind unveränderlich: - // `fooString[1] = 'X';` funktioniert nicht - - // Ein Vergleich zweier Strings, unter Berücksichtigung der - // aktuellen, sprachspezifischen Gegebenheiten (also z.B. a,ä,b,c - // in deutschsprachigen Umgebungen), und ohne Beachtung von - // Groß- und Kleinschreibung: - string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); - - // Formatierung, genau wie "sprintf" - string fooFs = string.Format("Mikrofon Check, {0} {1}, {0} {1:0.0}", 1, 2); - - // Datumsangaben und Formatierung - DateTime fooDate = DateTime.Now; - Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); - - // Durch ein vorangestelltes @ lässt sich ein mehrzeiliger String - // schreiben. Um " zu maskieren benutzt man "" - string bazString = @"Hier geht es -zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; - - // Die Keywords const oder readonly kennzeichnen eine - // unveränderliche Variable/Konstante. Die Werte von Konstanten - // werden übrigens bereits zur Compile-Zeit berechnet. - const int HOURS_I_WORK_PER_WEEK = 9001; - - /////////////////////////////////////////////////// - // Datenstrukturen - /////////////////////////////////////////////////// - - // Arrays - Index beginnt bei Null - // Die Größe des Arrays wird bei der Deklaration festgelegt. - // Die syntaktische Struktur um ein neues Array zu erzeugen sieht - // folgendermaßen aus: - // [] = new []; - int[] intArray = new int[10]; - - // Arrays können auch über ein Array-Literal deklariert werden: - int[] y = { 9000, 1000, 1337 }; - - // Indizierung eines Arrays - Zugriff auf ein bestimmtes Element - Console.WriteLine("intArray @ 0: " + intArray[0]); - // Arrays sind veränderbar - intArray[1] = 1; - - // Listen - // Durch ihre größere Flexibilität kommen Listen in C# weit - // häufiger zum Einsatz als Arrays. Eine Liste wird so deklariert: - // List = new List(); - List intList = new List(); - List stringList = new List(); - List z = new List { 9000, 1000, 1337 }; - // Die <> kennzeichnen "Generics", mehr dazu unter "Coole Sachen" - - // Listen haben keinen Default-Wert. - // Bevor auf einen Index zugegriffen werden kann, muss dieser - // auch gesetzt worden sein: - intList.Add(1); - Console.WriteLine("intList @ 0: " + intList[0]); - - // Andere interessante Datenstrukturen sind: - // Stack/Queue - // Dictionary (entspricht einer Hash Map) - // HashSet - // Read-only Collections - // Tuple (.Net 4+) - - /////////////////////////////////////// - // Operatoren - /////////////////////////////////////// - Console.WriteLine("\n->Operatoren"); - - // kurze Schreibweise um mehrere Deklarationen zusammenzufassen: - // (Benutzung vom C# Styleguide aber ausdrücklich abgeraten!) - int i1 = 1, i2 = 2; - - // Arithmetik funktioniert wie erwartet: - Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 - - // Modulo - Console.WriteLine("11%3 = " + (11 % 3)); // => 2 - - // Vergleiche - Console.WriteLine("3 == 2? " + (3 == 2)); // => false - Console.WriteLine("3 != 2? " + (3 != 2)); // => true - Console.WriteLine("3 > 2? " + (3 > 2)); // => true - Console.WriteLine("3 < 2? " + (3 < 2)); // => false - Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true - Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true - - // Bitweise Operatoren - /* - ~ Unäres bitweises NICHT - << Verschieben nach links - >> Verschieben nach rechts - & Bitweises UND - ^ Bitweises exklusives ODER - | Bitweises inklusives ODER - */ - - // Inkremente - int i = 0; - Console.WriteLine("\n->Inkrement / Dekrement"); - Console.WriteLine(i++); //i = 1. Post-Inkrement - Console.WriteLine(++i); //i = 2. Pre-Inkrement - Console.WriteLine(i--); //i = 1. Post-Dekrement - Console.WriteLine(--i); //i = 0. Pre-Dekrement - - /////////////////////////////////////// - // Kontrollstrukturen - /////////////////////////////////////// - Console.WriteLine("\n->Kontrollstrukturen"); - - // If-Statements funktionieren wie in C - int j = 10; - if (j == 10) - { - Console.WriteLine("Ich werde ausgegeben"); - } - else if (j > 10) - { - Console.WriteLine("Ich nicht"); - } - else - { - Console.WriteLine("Ich leider auch nicht"); - } - - // Ternärer Operator - // Anstatt eines einfachen if/else lässt sich auch folgendes schreiben: - // ? : - int zumVergleich = 17; - string isTrue = zumVergleich == 17 ? "Ja" : "Nein"; - - // while-Schleife - int fooWhile = 0; - while (fooWhile < 100) - { - // Wird 100mal wiederholt, fooWhile 0->99 - fooWhile++; - } - - // do-while-Schleife - int fooDoWhile = 0; - do - { - // Wird 100mal wiederholt, fooDoWhile 0->99 - fooDoWhile++; - } while (fooDoWhile < 100); - - //for-Schleifen => for(; ; ) - for (int fooFor = 0; fooFor < 10; fooFor++) - { - // Wird 10mal wiederholt, fooFor 0->9 - } - - // foreach-Schleife - // Die normale Syntax für eine foreach-Schleife lautet: - // foreach( in ) - // foreach kann mit jedem Objekt verwendet werden das IEnumerable - // oder IEnumerable implementiert. Alle Auflistungs-Typen - // (Array, List, Dictionary...) im .NET Framework implementieren - // eines dieser beiden Interfaces. - - foreach (char character in "Hallo Welt".ToCharArray()) - { - // Ein Durchgang für jedes Zeichen im String - } - // (ToCharArray() könnte man hier übrigens auch weglassen, - // da String IEnumerable bereits implementiert) - - // Switch Struktur - // Ein Switch funktioniert mit byte, short, char und int Datentypen. - // Auch Aufzählungstypen können verwendet werden, genau wie - // die Klasse String, und ein paar Sonderklassen, die Wrapper für - // Primitives sind: Character, Byte, Short und Integer - int month = 3; - string monthString; - switch (month) - { - case 1: - monthString = "Januar"; - break; - case 2: - monthString = "Februar"; - break; - case 3: - monthString = "März"; - break; - // Man kann für mehrere Fälle auch das selbe Verhalten - // definieren. Jeder Block muss aber mit einem break-Statement - // abgeschlossen werden. Einzelne Fälle können über - // `goto case x` erreicht werden - case 6: - case 7: - case 8: - monthString = "Sommer!!"; - break; - default: - monthString = "Irgendein anderer Monat"; - break; - } - - /////////////////////////////////////// - // Umwandlung von Datentypen und Typecasting - /////////////////////////////////////// - - // Umwandlung - - // von String nach Integer - // bei einem Fehler wirft diese Code eine Exception - int.Parse("123"); //gibt die Ganzzahl 123 zurück - - // TryParse gibt bei einem Fehler den Default-Wert zurück - // (im Fall von int: 0) - int tryInt; - if (int.TryParse("123", out tryInt)) // gibt true oder false zurück - { - Console.WriteLine(tryInt); // 123 - } - - // von Integer nach String - // Die Klasse Convert stellt Methoden zur Konvertierung von - // unterschiedlichsten Daten zur Verfügung: - Convert.ToString(123); // "123" - // oder - tryInt.ToString(); // "123" - } - - /////////////////////////////////////// - // Klassen - /////////////////////////////////////// - public static void Classes() - { - - // Benutze das new-Keyword um eine Instanz einer Klasse zu erzeugen - Bicycle trek = new Bicycle(); - - // So werden Methoden der Instanz aufgerufen - trek.SpeedUp(3); // Es empfiehlt sich immer Getter und Setter zu benutzen - trek.Cadence = 100; - - // ToString ist eine Konvention über die man üblicherweiser - // Informationen über eine Instanz erhält - Console.WriteLine("Infos zu trek: " + trek.ToString()); - - // Wir instantiieren ein neues Hochrad - PennyFarthing funbike = new PennyFarthing(1, 10); - Console.WriteLine("Infos zu funbike: " + funbike.ToString()); - - Console.Read(); - } // Ende der Methode main - - // Main als Konsolenstartpunkt - // Eine Konsolenanwendung muss eine Methode Main als Startpunkt besitzen - public static void Main(string[] args) - { - OtherInterestingFeatures(); - } - - /////////////////////////////////////// - // Interessante Features - /////////////////////////////////////// - - // Methodensignaturen - - public // Sichtbarkeit - static // Erlaubt einen Zugriff auf der Klasse (nicht auf einer Instanz) - int // Typ des Rückgabewerts, - MethodSignatures( - // Erstes Argument, erwartet int - int maxCount, - // setzt sich selbst auf 0 wenn kein anderer Wert übergeben wird - int count = 0, - int another = 3, - // enthält alle weiteren der Methode übergebenen Parameter (quasi Splats) - params string[] otherParams - ) - { - return -1; - } - - // Methoden können überladen werden, solange sie eindeutige - // Signaturen haben - public static void MethodSignatures(string maxCount) - { - } - - // Generische Typen - // Die Typen für TKey und TValue werden erst beim Aufruf der Methode - // festgelegt. Diese Methode emuliert z.B. SetDefault aus Python: - public static TValue SetDefault( - IDictionary dictionary, - TKey key, - TValue defaultItem) - { - TValue result; - if (!dictionary.TryGetValue(key, out result)) - { - return dictionary[key] = defaultItem; - } - return result; - } - - // Möglichen Typen lassen sich auch über ihr Interface beschränken: - public static void IterateAndPrint(T toPrint) where T: IEnumerable - { - // Da T ein IEnumerable ist können wir foreach benutzen - foreach (var item in toPrint) - { - // Item ist ein int - Console.WriteLine(item.ToString()); - } - } - - public static void OtherInterestingFeatures() - { - // Optionale Parameter - MethodSignatures(3, 1, 3, "Ein paar", "extra", "Strings"); - // setzt explizit einen bestimmten Parameter, andere werden übersprungen - MethodSignatures(3, another: 3); - - // Erweiterungsmethoden - int i = 3; - i.Print(); // Weiter unten definiert - - // Nullables - perfekt für die Interaktion mit - // Datenbanken / Rückgabewerten - // Jeder Wert (d.h. keine Klassen) kann durch das Nachstellen eines ? - // nullable gemacht werden: ? = - int? nullable = null; // Die explizite Langform wäre Nullable - Console.WriteLine("Mein Nullable: " + nullable); - bool hasValue = nullable.HasValue; // true wenn nicht null - - // ?? ist "syntaktischer Zucker" um einen Defaultwert für den Fall - // dass die Variable null ist festzulegen. - int notNullable = nullable ?? 0; // 0 - - // Implizit typisierte Variablen - // Man kann auch den Typ einer Variable auch vom Compiler - // bestimmen lassen: - var magic = "magic ist zur Compile-Zeit ein String, folglich geht keine Typsicherheit verloren"; - magic = 9; // funktioniert nicht da magic vom Typ String ist - - // Generics - var phonebook = new Dictionary() { - {"Resi", "08822 / 43 67"} // Fügt einen Eintrag zum Telefonbuch hinzu - }; - - // Hier könnte man auch unser generisches SetDefault von - // weiter oben benutzen: - Console.WriteLine(SetDefault(phonebook, "Xaver", "kein Telefon")); // kein Telefon - // TKey und TValue müssen nicht zwingend angegeben werden, da sie - // auch implizit vom Compiler ermittelt werden können - Console.WriteLine(SetDefault(phonebook, "Resi", "kein Telefon")); // 08822 / 43 67 - - // Lambdas - konzise Syntax für Inline-Funktionen - Func square = (x) => x * x; // Das letzte Element vom Typ T ist der Rückgabewert - Console.WriteLine(square(3)); // 9 - - // Disposables - einfaches Management von nicht verwalteten Ressourcen - // So gut wie alle Objekte die auf nicht verwaltete Ressourcen - // (Dateien, Geräte, ...) zugreifen, implementieren das Interface - // IDisposable. Das using Statement stellt sicher dass die vom - // IDisposable benutzten Ressourcen nach der Benutzung wieder - // freigegeben werden: - using (StreamWriter writer = new StreamWriter("log.txt")) - { - writer.WriteLine("Alles bestens!"); - // Am Ende des Codeblocks werden die Ressourcen wieder - // freigegeben - auch im Falle einer Exception - } - - // Parallel Klasse - // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx - var websites = new string[] { - "http://www.google.com", "http://www.reddit.com", - "http://www.shaunmccarthy.com" - }; - var responses = new Dictionary(); - - // Für jeden Request wird ein neuer Thread erzeugt, der nächste - // Schritt wird erst nach Beendigung aller Tasks ausgeführt - Parallel.ForEach(websites, - // maximal 3 Threads gleichzeitig - new ParallelOptions() {MaxDegreeOfParallelism = 3}, - website => - { - // Hier folgt eine langwierige, asynchrone Operation - using (var r = WebRequest.Create(new Uri(website)).GetResponse()) - { - responses[website] = r.ContentType; - } - }); - - // Dieser Code wird erst nach Beendigung aller Requests ausgeführt - foreach (var key in responses.Keys) - { - Console.WriteLine("{0}:{1}", key, responses[key]); - } - - // Dynamische Objekte (gut um mit anderen Sprachen zu arbeiten) - dynamic student = new ExpandoObject(); - // hier muss keine Typ angegeben werden - student.FirstName = "Christian"; - - // Einem solchen Objekt kann man sogar Methoden zuordnen. - // Das Beispiel gibt einen String zurück und erwartet einen String - student.Introduce = new Func( - (introduceTo) => string.Format("Hallo {0}, das ist {1}", student.FirstName, introduceTo)); - Console.WriteLine(student.Introduce("Bettina")); - - // IQueryable - So gut wie alle Aufzählungstypen implementieren - // dieses Interface, welches eine Vielzahl von funktionalen Methoden - // wie Map / Filter / Reduce zur Verfügung stellt: - var bikes = new List(); - // sortiert die Liste - bikes.Sort(); - // sortiert nach Anzahl Räder - bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); - var result = bikes - // diese Filter können auch aneinandergehängt werden - .Where(b => b.Wheels > 3) // (gibt ein IQueryable des vorherigen Typs zurück) - .Where(b => b.IsBroken && b.HasTassles) - // diese Zuordnung gibt ein IQueryable zurück - .Select(b => b.ToString()); - - // "Reduce" - addiert alle Räder der Aufzählung zu einem Wert - var sum = bikes.Sum(b => b.Wheels); - - // So erzeugt man ein implizit typisiertes Objekt, basierend auf - // den Parametern der Elemente: - var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); - // Auch wenn wir es hier nicht demonstrieren können: - // In einer IDE wie VisualStudio kriegen wir hier sogar TypeAhead, - // da der Compiler in der Lage ist, die passenden Typen zu erkennen. - foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) - { - Console.WriteLine(bikeSummary.Name); - } - - // AsParallel-Methode - // Jetzt kommen die Schmankerl! Die AsParallel-Methode kombiniert - // LINQ und parallele Operationen: - var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); - // Diese Berechnung passiert parallel! Benötigte Threads werden - // automatisch erzeugt, und die Rechenlast unter ihnen aufgeteilt. - // Ein Traum für die Verarbeitung von großen Datenmengen - // auf mehreren Cores! - - // LINQ - bildet einen Datenspeicher auf IQueryable Objekte ab - // LinqToSql beispielsweise speichert und liest aus einer - // SQL-Datenbank, LinqToXml aus einem XML-Dokument. - // LINQ-Operationen werden "lazy" ausgeführt. - var db = new BikeRepository(); - - // Die verzögerte Ausführung ist optimal für Datenbankabfragen - var filter = db.Bikes.Where(b => b.HasTassles); // noch keine Abfrage - // Es können noch mehr Filter hinzugefügt werden (auch mit - // Bedingungen) - ideal für z.B. "erweiterte Suchen" - if (42 > 6) - { - filter = filter.Where(b => b.IsBroken); // immer noch keine Abfrage - } - - var query = filter - .OrderBy(b => b.Wheels) - .ThenBy(b => b.Name) - .Select(b => b.Name); // auch hier: immer noch keine Abfrage - - // Erst hier wird die Datenbankabfrage wirklich ausgeführt, - // limitiert auf die Elemente die der foreach-Loop verwendet - foreach (string bike in query) - { - Console.WriteLine(result); - } - - } - - } // Ende der Klasse LearnCSharp - - // Eine .cs-Datei kann auch mehrere Klassen enthalten - - public static class Extensions - { - // Erweiterungsmethoden - public static void Print(this object obj) - { - Console.WriteLine(obj.ToString()); - } - } - - // Syntax zur Deklaration einer Klasse: - // class { - // // Datenfelder, Konstruktoren und Methoden leben alle - // // innerhalb dieser Deklaration - // } - - public class Bicycle - { - // Felder/Variablen der Klasse "Bicycle" - // Das Keyword public macht das Member von überall zugänglich - public int Cadence - { - get // get definiert eine Methode um die Eigenschaft abzurufen - { - return _cadence; - } - set // set definiert eine Methode um die Eigenschaft zu setzen - { - _cadence = value; // value ist der dem Setter übergebene Wert - } - } - private int _cadence; - - // Das Keyword protected macht das Member nur für die Klasse selbst - // und ihre Subklassen zugänglich - protected virtual int Gear - { - get; // erzeugt eine Eigenschaft für die kein "Zwischenwert" benötigt wird - set; - } - - // Das Keyword internal macht das Member innerhalb der Assembly zugänglich - internal int Wheels - { - get; - private set; // get/set kann auch über Keywords modifiziert werden - } - - int _speed; // Member ohne vorangestellte Keywords sind standardmäßig - // private, sie sind nur innerhalb der Klasse zugänglich. - // Man kann aber natürlich auch das Keyword private benutzen. - private string Name { get; set; } - - // Ein Enum ist ein klar definierter Satz an benannten Konstanten. - // Eigentlich ordnet es diese Konstanten nur bestimmten Werten zu - // (einer int-Zahl, solange nicht anders angegeben). Mögliche Typen für - // die Werte eines Enums sind byte, sbyte, short, ushort, int, uint, - // long, oder ulong. Alle Werte in einem Enum sind eindeutig. - public enum BikeBrand - { - Colnago, - EddyMerckx, - Bianchi = 42, // so kann man den Wert explizit setzen - Kynast // 43 - } - // Nachdem dieser Typ in der Klasse "Bicycle" definiert ist, - // sollte Code ausserhalb der Klasse den Typen als Bicycle.Brand referenzieren - - // Nachdem das Enum deklariert ist, können wir den Typen verwenden: - public BikeBrand Brand; - - // Als static gekennzeichnete Member gehören dem Typ selbst, - // nicht seinen Instanzen. Man kann sie also ohne Referenz zu einem - // Objekt benutzen - // Console.WriteLine("Schon " + Bicycle.BicyclesCreated + " Fahrräder, nur für dieses Tutorial!"); - static public int BicyclesCreated = 0; - - // readonly-Werte werden zur Laufzeit gesetzt - // Ihr Wert kann nur bei ihrer Deklaration, oder in einem Konstruktor - // festgelegt werden - readonly bool _hasCardsInSpokes = false; // readonly und private - - // Konstruktoren bestimmen was bei einer Instantiierung passiert. - // Das ist ein Default-Konstruktor: - public Bicycle() - { - // Member der Klasse können über das Keyword this erreicht werden - this.Gear = 1; - // oft ist das aber gar nicht nötig - Cadence = 50; - _speed = 5; - Name = "Bonanzarad"; - Brand = BikeBrand.Kynast; - BicyclesCreated++; - } - - // Das ist ein spezifischer Konstruktor (d.h. er erwartet Argumente): - public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes, BikeBrand brand) - : base() // ruft zuerst den "base"-Konstruktor auf - { - Gear = startGear; - Cadence = startCadence; - _speed = startSpeed; - Name = name; - _hasCardsInSpokes = hasCardsInSpokes; - Brand = brand; - } - - // Konstruktoren können aneinandergehängt werden: - public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : - this(startCadence, startSpeed, 0, "richtig große Räder", true, brand) - { - } - - // Syntax für Methoden: - // () - - // Klassen können Getter und Setter für Werte definieren, - // oder diese Werte direkt als Eigenschaft implementieren - // (in C# der bevorzugte Weg) - - // Parameter von Methoden können Default-Werte haben. - // "SpeedUp" kann man also auch ohne Parameter aufrufen: - public void SpeedUp(int increment = 1) - { - _speed += increment; - } - - public void SlowDown(int decrement = 1) - { - _speed -= decrement; - } - - // Eigenschaften mit get/set - // wenn es nur um den Zugriff auf Daten geht, ist eine Eigenschaft zu - // empfehlen. Diese können Getter und Setter haben, oder auch nur - // einen Getter bzw. einen Setter - private bool _hasTassles; // private Variable - public bool HasTassles // öffentliches Interface - { - get { return _hasTassles; } - set { _hasTassles = value; } - } - - // Das kann man auch kürzer schreiben: - // Dieser Syntax erzeugt automatisch einen hinterlegten Wert, - // (entsprechend `private bool _isBroken`) der gesetzt - // bzw. zurückgegeben wird: - public bool IsBroken { get; private set; } - public int FrameSize - { - get; - // für Getter und Setter kann der Zugriff auch einzeln - // beschränkt werden, FrameSize kann also nur von innerhalb - // der Klasse "Bicycle" gesetzt werden - private set; - } - - // Diese Methode gibt eine Reihe an Informationen über das Objekt aus: - public virtual string ToString() - { - return "Gang: " + Gear + - " Kadenz: " + Cadence + - " Geschwindigkeit: " + _speed + - " Name: " + Name + - " Hipster-Karten zwischen den Speichen: " + (_hasCardsInSpokes ? "Na klar!" : "Bloß nicht!") + - "\n------------------------------\n" - ; - } - - // Auch Methoden können als static gekennzeichnet werden, nützlich - // beispielsweise für Helper-Methoden - public static bool DidWeCreateEnoughBicyclesYet() - { - // In einer statischen Methode können wir natürlich auch nur - // statische Member der Klasse referenzieren - return BicyclesCreated > 9000; - } - // Wenn eine Klasse nur statische Member enthält, kann es eine gute Idee - // sein die Klasse selbst als static zu kennzeichnen - - } // Ende der Klasse "Bicycle" - - // "PennyFarthing" ist eine Unterklasse von "Bicycle" - class PennyFarthing : Bicycle - { - // (Hochräder - englisch Penny Farthing - sind diese antiken Fahrräder - // mit riesigem Vorderrad. Sie haben keine Gangschaltung.) - - // hier wird einfach der Elternkonstruktor aufgerufen - public PennyFarthing(int startCadence, int startSpeed) : - base(startCadence, startSpeed, 0, "Hochrad", true, BikeBrand.EddyMerckx) - { - } - - protected override int Gear - { - get - { - return 0; - } - set - { - throw new ArgumentException("Ein Hochrad hat keine Gangschaltung, doh!"); - } - } - - public override string ToString() - { - string result = "Hochrad "; - result += base.ToString(); // ruft die "base"-Version der Methode auf - return result; - } - } - - // Interfaces (auch Schnittstellen genant) definieren nur die Signaturen - // ihrer Member, enthalten aber auf keinen Fall ihre Implementierung: - interface IJumpable - { - // Alle Member eines Interfaces sind implizit public - void Jump(int meters); - } - - interface IBreakable - { - // Interfaces können Eigenschaften, Methoden und Events definieren - bool Broken { get; } - } - - // Eine Klasse kann nur von einer Klasse erben, kann aber eine beliebige - // Anzahl von Interfaces implementieren - class MountainBike : Bicycle, IJumpable, IBreakable - { - int damage = 0; - - public void Jump(int meters) - { - damage += meters; - } - - public bool Broken - { - get - { - return damage > 100; - } - } - } - - // Das hier stellt eine Datenbankverbindung für das LinqToSql-Beispiel her. - // EntityFramework Code First ist großartig - // (ähnlich zu Ruby's ActiveRecord, aber bidirektional) - // http://msdn.microsoft.com/de-de/data/jj193542.aspx - public class BikeRepository : DbSet - { - public BikeRepository() - : base() - { - } - - public DbSet Bikes { get; set; } - } -} // Ende des Namespaces -``` - -## In dieser Übersicht nicht enthalten sind die Themen: - - * Flags - * Attributes - * Statische Eigenschaften - * Exceptions, Abstraction - * ASP.NET (Web Forms/MVC/WebMatrix) - * Winforms - * Windows Presentation Foundation (WPF) - -## Zum Weiterlesen gibt es viele gute Anlaufpunkte: - - * [DotNetPerls](http://www.dotnetperls.com) - * [C# in Depth](http://manning.com/skeet2) - * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) - * [LINQ](http://shop.oreilly.com/product/9780596519254.do) - * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) - * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) - * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix) - * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) - * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) - -[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx) +--- +language: C# +contributors: + - ["Irfan Charania", "https://github.com/irfancharania"] + - ["Max Yankov", "https://github.com/golergka"] + - ["Melvyn Laïly", "http://x2a.yt"] + - ["Shaun McCarthy", "http://www.shaunmccarthy.com"] +translators: + - ["Frederik Ring", "https://github.com/m90"] +filename: LearnCSharp-de.cs +lang: de-de +--- +C# ist eine elegante, typsichere und objektorientierte Sprache, mit der Entwickler eine Vielzahl sicherer und robuster Anwendungen erstellen können, die im .NET Framework ausgeführt werden. + +[Mehr über C# erfährst du hier.](http://msdn.microsoft.com/de-de/library/vstudio/z1zx9t92.aspx) + +```c# +// Einzeilige Kommentare starten mit zwei Schrägstrichen: // +/* +Mehrzeile Kommentare wie in C Schrägstrich / Stern +*/ +/// +/// XML-Kommentare können zur automatisierten Dokumentation verwendet werden +/// + +// Zu Beginn werden die in der Datei verwendeten Namespaces aufgeführt +using System; +using System.Collections.Generic; +using System.Data.Entity; +using System.Dynamic; +using System.Linq; +using System.Linq.Expressions; +using System.Net; +using System.Threading.Tasks; +using System.IO; + +// definiert einen Namespace um Code in "packages" zu organisieren +namespace Learning +{ + // Jede .cs-Datei sollte zumindest eine Klasse mit dem Namen der Datei + // enthalten. Das ist zwar nicht zwingend erforderlich, es anders zu + // handhaben führt aber unweigerlich ins Chaos (wirklich)! + public class LearnCSharp + { + // Zuerst erklärt dieses Tutorial die Syntax-Grundlagen, + // wenn du bereits Java oder C++ programmieren kannst: + // lies bei "Interessante Features" weiter! + public static void Syntax() + { + // Mit Console.WriteLine kannst du einfachen Text ausgeben: + Console.WriteLine("Hallo Welt"); + Console.WriteLine( + "Integer: " + 10 + + " Double: " + 3.14 + + " Boolean: " + true); + + // Console.Write erzeugt keinen Zeilenumbruch + Console.Write("Hallo "); + Console.Write("Welt"); + + /////////////////////////////////////////////////// + // Typen & Variablen + /////////////////////////////////////////////////// + + // Deklariere eine Variable mit + + // Sbyte - Vorzeichenbehaftete 8-Bit Ganzzahl + // (-128 <= sbyte <= 127) + sbyte fooSbyte = 100; + + // Byte - Vorzeichenlose 8-Bit Ganzzahl + // (0 <= byte <= 255) + byte fooByte = 100; + + // Short - 16-Bit Ganzzahl + // Vorzeichenbehaftet - (-32,768 <= short <= 32,767) + // Vorzeichenlos - (0 <= ushort <= 65,535) + short fooShort = 10000; + ushort fooUshort = 10000; + + // Integer - 32-bit Ganzzahl + int fooInt = 1; // (-2,147,483,648 <= int <= 2,147,483,647) + uint fooUint = 1; // (0 <= uint <= 4,294,967,295) + + // Long - 64-bit Ganzzahl + long fooLong = 100000L; // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) + ulong fooUlong = 100000L; // (0 <= ulong <= 18,446,744,073,709,551,615) + // Ganze Zahlen werden standardmäßig - je nach Größe - als int oder + // uint behandelt. Ein nachgestelltes L markiert den Wert als long + // oder ulong. + + // Double - Double-precision 64-bit IEEE 754 Fließkommazahl + double fooDouble = 123.4; // Genauigkeit: 15-16 Stellen + + // Float - Single-precision 32-bit IEEE 754 Fließkommazahl + float fooFloat = 234.5f; // Genauigkeit: 7 Stellen + // Das nachgestellte f zeigt an dass es sich um einen Wert vom Typ + // float handelt + + // Decimal - ein 128-Bit-Datentyp mit größerer Genauigkeit als + // andere Fließkommatypen, und somit bestens geeignet für + // die Berechnung von Geld- und Finanzwerten + decimal fooDecimal = 150.3m; + + // Boolean - true & false + bool fooBoolean = true; // oder false + + // Char - Ein einzelnes 16-Bit Unicode Zeichen + char fooChar = 'A'; + + // Strings - im Gegensatz zu allen vorhergehenden Basistypen, die + // alle Werttypen sind, ist String ein Referenztyp. Strings sind + // somit nullable, Werttypen sind dies nicht. + string fooString = "\"maskiere\" Anführungszeichen, und füge \n (Umbrüche) und \t (Tabs) hinzu"; + Console.WriteLine(fooString); + + // Jeder Buchstabe eines Strings kann über seinen Index + // referenziert werden: + char charFromString = fooString[1]; // => 'e' + // Strings sind unveränderlich: + // `fooString[1] = 'X';` funktioniert nicht + + // Ein Vergleich zweier Strings, unter Berücksichtigung der + // aktuellen, sprachspezifischen Gegebenheiten (also z.B. a,ä,b,c + // in deutschsprachigen Umgebungen), und ohne Beachtung von + // Groß- und Kleinschreibung: + string.Compare(fooString, "x", StringComparison.CurrentCultureIgnoreCase); + + // Formatierung, genau wie "sprintf" + string fooFs = string.Format("Mikrofon Check, {0} {1}, {0} {1:0.0}", 1, 2); + + // Datumsangaben und Formatierung + DateTime fooDate = DateTime.Now; + Console.WriteLine(fooDate.ToString("hh:mm, dd MMM yyyy")); + + // Durch ein vorangestelltes @ lässt sich ein mehrzeiliger String + // schreiben. Um " zu maskieren benutzt man "" + string bazString = @"Hier geht es +zur nächsten Zeile, ""Wahnsinn!"", die Massen waren kaum zu bändigen"; + + // Die Keywords const oder readonly kennzeichnen eine + // unveränderliche Variable/Konstante. Die Werte von Konstanten + // werden übrigens bereits zur Compile-Zeit berechnet. + const int HOURS_I_WORK_PER_WEEK = 9001; + + /////////////////////////////////////////////////// + // Datenstrukturen + /////////////////////////////////////////////////// + + // Arrays - Index beginnt bei Null + // Die Größe des Arrays wird bei der Deklaration festgelegt. + // Die syntaktische Struktur um ein neues Array zu erzeugen sieht + // folgendermaßen aus: + // [] = new []; + int[] intArray = new int[10]; + + // Arrays können auch über ein Array-Literal deklariert werden: + int[] y = { 9000, 1000, 1337 }; + + // Indizierung eines Arrays - Zugriff auf ein bestimmtes Element + Console.WriteLine("intArray @ 0: " + intArray[0]); + // Arrays sind veränderbar + intArray[1] = 1; + + // Listen + // Durch ihre größere Flexibilität kommen Listen in C# weit + // häufiger zum Einsatz als Arrays. Eine Liste wird so deklariert: + // List = new List(); + List intList = new List(); + List stringList = new List(); + List z = new List { 9000, 1000, 1337 }; + // Die <> kennzeichnen "Generics", mehr dazu unter "Coole Sachen" + + // Listen haben keinen Default-Wert. + // Bevor auf einen Index zugegriffen werden kann, muss dieser + // auch gesetzt worden sein: + intList.Add(1); + Console.WriteLine("intList @ 0: " + intList[0]); + + // Andere interessante Datenstrukturen sind: + // Stack/Queue + // Dictionary (entspricht einer Hash Map) + // HashSet + // Read-only Collections + // Tuple (.Net 4+) + + /////////////////////////////////////// + // Operatoren + /////////////////////////////////////// + Console.WriteLine("\n->Operatoren"); + + // kurze Schreibweise um mehrere Deklarationen zusammenzufassen: + // (Benutzung vom C# Styleguide aber ausdrücklich abgeraten!) + int i1 = 1, i2 = 2; + + // Arithmetik funktioniert wie erwartet: + Console.WriteLine(i1 + i2 - i1 * 3 / 7); // => 3 + + // Modulo + Console.WriteLine("11%3 = " + (11 % 3)); // => 2 + + // Vergleiche + Console.WriteLine("3 == 2? " + (3 == 2)); // => false + Console.WriteLine("3 != 2? " + (3 != 2)); // => true + Console.WriteLine("3 > 2? " + (3 > 2)); // => true + Console.WriteLine("3 < 2? " + (3 < 2)); // => false + Console.WriteLine("2 <= 2? " + (2 <= 2)); // => true + Console.WriteLine("2 >= 2? " + (2 >= 2)); // => true + + // Bitweise Operatoren + /* + ~ Unäres bitweises NICHT + << Verschieben nach links + >> Verschieben nach rechts + & Bitweises UND + ^ Bitweises exklusives ODER + | Bitweises inklusives ODER + */ + + // Inkremente + int i = 0; + Console.WriteLine("\n->Inkrement / Dekrement"); + Console.WriteLine(i++); //i = 1. Post-Inkrement + Console.WriteLine(++i); //i = 2. Pre-Inkrement + Console.WriteLine(i--); //i = 1. Post-Dekrement + Console.WriteLine(--i); //i = 0. Pre-Dekrement + + /////////////////////////////////////// + // Kontrollstrukturen + /////////////////////////////////////// + Console.WriteLine("\n->Kontrollstrukturen"); + + // If-Statements funktionieren wie in C + int j = 10; + if (j == 10) + { + Console.WriteLine("Ich werde ausgegeben"); + } + else if (j > 10) + { + Console.WriteLine("Ich nicht"); + } + else + { + Console.WriteLine("Ich leider auch nicht"); + } + + // Ternärer Operator + // Anstatt eines einfachen if/else lässt sich auch folgendes schreiben: + // ? : + int zumVergleich = 17; + string isTrue = zumVergleich == 17 ? "Ja" : "Nein"; + + // while-Schleife + int fooWhile = 0; + while (fooWhile < 100) + { + // Wird 100mal wiederholt, fooWhile 0->99 + fooWhile++; + } + + // do-while-Schleife + int fooDoWhile = 0; + do + { + // Wird 100mal wiederholt, fooDoWhile 0->99 + fooDoWhile++; + } while (fooDoWhile < 100); + + //for-Schleifen => for(; ; ) + for (int fooFor = 0; fooFor < 10; fooFor++) + { + // Wird 10mal wiederholt, fooFor 0->9 + } + + // foreach-Schleife + // Die normale Syntax für eine foreach-Schleife lautet: + // foreach( in ) + // foreach kann mit jedem Objekt verwendet werden das IEnumerable + // oder IEnumerable implementiert. Alle Auflistungs-Typen + // (Array, List, Dictionary...) im .NET Framework implementieren + // eines dieser beiden Interfaces. + + foreach (char character in "Hallo Welt".ToCharArray()) + { + // Ein Durchgang für jedes Zeichen im String + } + // (ToCharArray() könnte man hier übrigens auch weglassen, + // da String IEnumerable bereits implementiert) + + // Switch Struktur + // Ein Switch funktioniert mit byte, short, char und int Datentypen. + // Auch Aufzählungstypen können verwendet werden, genau wie + // die Klasse String, und ein paar Sonderklassen, die Wrapper für + // Primitives sind: Character, Byte, Short und Integer + int month = 3; + string monthString; + switch (month) + { + case 1: + monthString = "Januar"; + break; + case 2: + monthString = "Februar"; + break; + case 3: + monthString = "März"; + break; + // Man kann für mehrere Fälle auch das selbe Verhalten + // definieren. Jeder Block muss aber mit einem break-Statement + // abgeschlossen werden. Einzelne Fälle können über + // `goto case x` erreicht werden + case 6: + case 7: + case 8: + monthString = "Sommer!!"; + break; + default: + monthString = "Irgendein anderer Monat"; + break; + } + + /////////////////////////////////////// + // Umwandlung von Datentypen und Typecasting + /////////////////////////////////////// + + // Umwandlung + + // von String nach Integer + // bei einem Fehler wirft diese Code eine Exception + int.Parse("123"); //gibt die Ganzzahl 123 zurück + + // TryParse gibt bei einem Fehler den Default-Wert zurück + // (im Fall von int: 0) + int tryInt; + if (int.TryParse("123", out tryInt)) // gibt true oder false zurück + { + Console.WriteLine(tryInt); // 123 + } + + // von Integer nach String + // Die Klasse Convert stellt Methoden zur Konvertierung von + // unterschiedlichsten Daten zur Verfügung: + Convert.ToString(123); // "123" + // oder + tryInt.ToString(); // "123" + } + + /////////////////////////////////////// + // Klassen + /////////////////////////////////////// + public static void Classes() + { + + // Benutze das new-Keyword um eine Instanz einer Klasse zu erzeugen + Bicycle trek = new Bicycle(); + + // So werden Methoden der Instanz aufgerufen + trek.SpeedUp(3); // Es empfiehlt sich immer Getter und Setter zu benutzen + trek.Cadence = 100; + + // ToString ist eine Konvention über die man üblicherweiser + // Informationen über eine Instanz erhält + Console.WriteLine("Infos zu trek: " + trek.ToString()); + + // Wir instantiieren ein neues Hochrad + PennyFarthing funbike = new PennyFarthing(1, 10); + Console.WriteLine("Infos zu funbike: " + funbike.ToString()); + + Console.Read(); + } // Ende der Methode main + + // Main als Konsolenstartpunkt + // Eine Konsolenanwendung muss eine Methode Main als Startpunkt besitzen + public static void Main(string[] args) + { + OtherInterestingFeatures(); + } + + /////////////////////////////////////// + // Interessante Features + /////////////////////////////////////// + + // Methodensignaturen + + public // Sichtbarkeit + static // Erlaubt einen Zugriff auf der Klasse (nicht auf einer Instanz) + int // Typ des Rückgabewerts, + MethodSignatures( + // Erstes Argument, erwartet int + int maxCount, + // setzt sich selbst auf 0 wenn kein anderer Wert übergeben wird + int count = 0, + int another = 3, + // enthält alle weiteren der Methode übergebenen Parameter (quasi Splats) + params string[] otherParams + ) + { + return -1; + } + + // Methoden können überladen werden, solange sie eindeutige + // Signaturen haben + public static void MethodSignatures(string maxCount) + { + } + + // Generische Typen + // Die Typen für TKey und TValue werden erst beim Aufruf der Methode + // festgelegt. Diese Methode emuliert z.B. SetDefault aus Python: + public static TValue SetDefault( + IDictionary dictionary, + TKey key, + TValue defaultItem) + { + TValue result; + if (!dictionary.TryGetValue(key, out result)) + { + return dictionary[key] = defaultItem; + } + return result; + } + + // Möglichen Typen lassen sich auch über ihr Interface beschränken: + public static void IterateAndPrint(T toPrint) where T: IEnumerable + { + // Da T ein IEnumerable ist können wir foreach benutzen + foreach (var item in toPrint) + { + // Item ist ein int + Console.WriteLine(item.ToString()); + } + } + + public static void OtherInterestingFeatures() + { + // Optionale Parameter + MethodSignatures(3, 1, 3, "Ein paar", "extra", "Strings"); + // setzt explizit einen bestimmten Parameter, andere werden übersprungen + MethodSignatures(3, another: 3); + + // Erweiterungsmethoden + int i = 3; + i.Print(); // Weiter unten definiert + + // Nullables - perfekt für die Interaktion mit + // Datenbanken / Rückgabewerten + // Jeder Wert (d.h. keine Klassen) kann durch das Nachstellen eines ? + // nullable gemacht werden: ? = + int? nullable = null; // Die explizite Langform wäre Nullable + Console.WriteLine("Mein Nullable: " + nullable); + bool hasValue = nullable.HasValue; // true wenn nicht null + + // ?? ist "syntaktischer Zucker" um einen Defaultwert für den Fall + // dass die Variable null ist festzulegen. + int notNullable = nullable ?? 0; // 0 + + // Implizit typisierte Variablen + // Man kann auch den Typ einer Variable auch vom Compiler + // bestimmen lassen: + var magic = "magic ist zur Compile-Zeit ein String, folglich geht keine Typsicherheit verloren"; + magic = 9; // funktioniert nicht da magic vom Typ String ist + + // Generics + var phonebook = new Dictionary() { + {"Resi", "08822 / 43 67"} // Fügt einen Eintrag zum Telefonbuch hinzu + }; + + // Hier könnte man auch unser generisches SetDefault von + // weiter oben benutzen: + Console.WriteLine(SetDefault(phonebook, "Xaver", "kein Telefon")); // kein Telefon + // TKey und TValue müssen nicht zwingend angegeben werden, da sie + // auch implizit vom Compiler ermittelt werden können + Console.WriteLine(SetDefault(phonebook, "Resi", "kein Telefon")); // 08822 / 43 67 + + // Lambdas - konzise Syntax für Inline-Funktionen + Func square = (x) => x * x; // Das letzte Element vom Typ T ist der Rückgabewert + Console.WriteLine(square(3)); // 9 + + // Disposables - einfaches Management von nicht verwalteten Ressourcen + // So gut wie alle Objekte die auf nicht verwaltete Ressourcen + // (Dateien, Geräte, ...) zugreifen, implementieren das Interface + // IDisposable. Das using Statement stellt sicher dass die vom + // IDisposable benutzten Ressourcen nach der Benutzung wieder + // freigegeben werden: + using (StreamWriter writer = new StreamWriter("log.txt")) + { + writer.WriteLine("Alles bestens!"); + // Am Ende des Codeblocks werden die Ressourcen wieder + // freigegeben - auch im Falle einer Exception + } + + // Parallel Klasse + // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", + "http://www.shaunmccarthy.com" + }; + var responses = new Dictionary(); + + // Für jeden Request wird ein neuer Thread erzeugt, der nächste + // Schritt wird erst nach Beendigung aller Tasks ausgeführt + Parallel.ForEach(websites, + // maximal 3 Threads gleichzeitig + new ParallelOptions() {MaxDegreeOfParallelism = 3}, + website => + { + // Hier folgt eine langwierige, asynchrone Operation + using (var r = WebRequest.Create(new Uri(website)).GetResponse()) + { + responses[website] = r.ContentType; + } + }); + + // Dieser Code wird erst nach Beendigung aller Requests ausgeführt + foreach (var key in responses.Keys) + { + Console.WriteLine("{0}:{1}", key, responses[key]); + } + + // Dynamische Objekte (gut um mit anderen Sprachen zu arbeiten) + dynamic student = new ExpandoObject(); + // hier muss keine Typ angegeben werden + student.FirstName = "Christian"; + + // Einem solchen Objekt kann man sogar Methoden zuordnen. + // Das Beispiel gibt einen String zurück und erwartet einen String + student.Introduce = new Func( + (introduceTo) => string.Format("Hallo {0}, das ist {1}", student.FirstName, introduceTo)); + Console.WriteLine(student.Introduce("Bettina")); + + // IQueryable - So gut wie alle Aufzählungstypen implementieren + // dieses Interface, welches eine Vielzahl von funktionalen Methoden + // wie Map / Filter / Reduce zur Verfügung stellt: + var bikes = new List(); + // sortiert die Liste + bikes.Sort(); + // sortiert nach Anzahl Räder + bikes.Sort((b1, b2) => b1.Wheels.CompareTo(b2.Wheels)); + var result = bikes + // diese Filter können auch aneinandergehängt werden + .Where(b => b.Wheels > 3) // (gibt ein IQueryable des vorherigen Typs zurück) + .Where(b => b.IsBroken && b.HasTassles) + // diese Zuordnung gibt ein IQueryable zurück + .Select(b => b.ToString()); + + // "Reduce" - addiert alle Räder der Aufzählung zu einem Wert + var sum = bikes.Sum(b => b.Wheels); + + // So erzeugt man ein implizit typisiertes Objekt, basierend auf + // den Parametern der Elemente: + var bikeSummaries = bikes.Select(b=>new { Name = b.Name, IsAwesome = !b.IsBroken && b.HasTassles }); + // Auch wenn wir es hier nicht demonstrieren können: + // In einer IDE wie VisualStudio kriegen wir hier sogar TypeAhead, + // da der Compiler in der Lage ist, die passenden Typen zu erkennen. + foreach (var bikeSummary in bikeSummaries.Where(b => b.IsAwesome)) + { + Console.WriteLine(bikeSummary.Name); + } + + // AsParallel-Methode + // Jetzt kommen die Schmankerl! Die AsParallel-Methode kombiniert + // LINQ und parallele Operationen: + var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); + // Diese Berechnung passiert parallel! Benötigte Threads werden + // automatisch erzeugt, und die Rechenlast unter ihnen aufgeteilt. + // Ein Traum für die Verarbeitung von großen Datenmengen + // auf mehreren Cores! + + // LINQ - bildet einen Datenspeicher auf IQueryable Objekte ab + // LinqToSql beispielsweise speichert und liest aus einer + // SQL-Datenbank, LinqToXml aus einem XML-Dokument. + // LINQ-Operationen werden "lazy" ausgeführt. + var db = new BikeRepository(); + + // Die verzögerte Ausführung ist optimal für Datenbankabfragen + var filter = db.Bikes.Where(b => b.HasTassles); // noch keine Abfrage + // Es können noch mehr Filter hinzugefügt werden (auch mit + // Bedingungen) - ideal für z.B. "erweiterte Suchen" + if (42 > 6) + { + filter = filter.Where(b => b.IsBroken); // immer noch keine Abfrage + } + + var query = filter + .OrderBy(b => b.Wheels) + .ThenBy(b => b.Name) + .Select(b => b.Name); // auch hier: immer noch keine Abfrage + + // Erst hier wird die Datenbankabfrage wirklich ausgeführt, + // limitiert auf die Elemente die der foreach-Loop verwendet + foreach (string bike in query) + { + Console.WriteLine(result); + } + + } + + } // Ende der Klasse LearnCSharp + + // Eine .cs-Datei kann auch mehrere Klassen enthalten + + public static class Extensions + { + // Erweiterungsmethoden + public static void Print(this object obj) + { + Console.WriteLine(obj.ToString()); + } + } + + // Syntax zur Deklaration einer Klasse: + // class { + // // Datenfelder, Konstruktoren und Methoden leben alle + // // innerhalb dieser Deklaration + // } + + public class Bicycle + { + // Felder/Variablen der Klasse "Bicycle" + // Das Keyword public macht das Member von überall zugänglich + public int Cadence + { + get // get definiert eine Methode um die Eigenschaft abzurufen + { + return _cadence; + } + set // set definiert eine Methode um die Eigenschaft zu setzen + { + _cadence = value; // value ist der dem Setter übergebene Wert + } + } + private int _cadence; + + // Das Keyword protected macht das Member nur für die Klasse selbst + // und ihre Subklassen zugänglich + protected virtual int Gear + { + get; // erzeugt eine Eigenschaft für die kein "Zwischenwert" benötigt wird + set; + } + + // Das Keyword internal macht das Member innerhalb der Assembly zugänglich + internal int Wheels + { + get; + private set; // get/set kann auch über Keywords modifiziert werden + } + + int _speed; // Member ohne vorangestellte Keywords sind standardmäßig + // private, sie sind nur innerhalb der Klasse zugänglich. + // Man kann aber natürlich auch das Keyword private benutzen. + private string Name { get; set; } + + // Ein Enum ist ein klar definierter Satz an benannten Konstanten. + // Eigentlich ordnet es diese Konstanten nur bestimmten Werten zu + // (einer int-Zahl, solange nicht anders angegeben). Mögliche Typen für + // die Werte eines Enums sind byte, sbyte, short, ushort, int, uint, + // long, oder ulong. Alle Werte in einem Enum sind eindeutig. + public enum BikeBrand + { + Colnago, + EddyMerckx, + Bianchi = 42, // so kann man den Wert explizit setzen + Kynast // 43 + } + // Nachdem dieser Typ in der Klasse "Bicycle" definiert ist, + // sollte Code ausserhalb der Klasse den Typen als Bicycle.Brand referenzieren + + // Nachdem das Enum deklariert ist, können wir den Typen verwenden: + public BikeBrand Brand; + + // Als static gekennzeichnete Member gehören dem Typ selbst, + // nicht seinen Instanzen. Man kann sie also ohne Referenz zu einem + // Objekt benutzen + // Console.WriteLine("Schon " + Bicycle.BicyclesCreated + " Fahrräder, nur für dieses Tutorial!"); + static public int BicyclesCreated = 0; + + // readonly-Werte werden zur Laufzeit gesetzt + // Ihr Wert kann nur bei ihrer Deklaration, oder in einem Konstruktor + // festgelegt werden + readonly bool _hasCardsInSpokes = false; // readonly und private + + // Konstruktoren bestimmen was bei einer Instantiierung passiert. + // Das ist ein Default-Konstruktor: + public Bicycle() + { + // Member der Klasse können über das Keyword this erreicht werden + this.Gear = 1; + // oft ist das aber gar nicht nötig + Cadence = 50; + _speed = 5; + Name = "Bonanzarad"; + Brand = BikeBrand.Kynast; + BicyclesCreated++; + } + + // Das ist ein spezifischer Konstruktor (d.h. er erwartet Argumente): + public Bicycle(int startCadence, int startSpeed, int startGear, + string name, bool hasCardsInSpokes, BikeBrand brand) + : base() // ruft zuerst den "base"-Konstruktor auf + { + Gear = startGear; + Cadence = startCadence; + _speed = startSpeed; + Name = name; + _hasCardsInSpokes = hasCardsInSpokes; + Brand = brand; + } + + // Konstruktoren können aneinandergehängt werden: + public Bicycle(int startCadence, int startSpeed, BikeBrand brand) : + this(startCadence, startSpeed, 0, "richtig große Räder", true, brand) + { + } + + // Syntax für Methoden: + // () + + // Klassen können Getter und Setter für Werte definieren, + // oder diese Werte direkt als Eigenschaft implementieren + // (in C# der bevorzugte Weg) + + // Parameter von Methoden können Default-Werte haben. + // "SpeedUp" kann man also auch ohne Parameter aufrufen: + public void SpeedUp(int increment = 1) + { + _speed += increment; + } + + public void SlowDown(int decrement = 1) + { + _speed -= decrement; + } + + // Eigenschaften mit get/set + // wenn es nur um den Zugriff auf Daten geht, ist eine Eigenschaft zu + // empfehlen. Diese können Getter und Setter haben, oder auch nur + // einen Getter bzw. einen Setter + private bool _hasTassles; // private Variable + public bool HasTassles // öffentliches Interface + { + get { return _hasTassles; } + set { _hasTassles = value; } + } + + // Das kann man auch kürzer schreiben: + // Dieser Syntax erzeugt automatisch einen hinterlegten Wert, + // (entsprechend `private bool _isBroken`) der gesetzt + // bzw. zurückgegeben wird: + public bool IsBroken { get; private set; } + public int FrameSize + { + get; + // für Getter und Setter kann der Zugriff auch einzeln + // beschränkt werden, FrameSize kann also nur von innerhalb + // der Klasse "Bicycle" gesetzt werden + private set; + } + + // Diese Methode gibt eine Reihe an Informationen über das Objekt aus: + public virtual string ToString() + { + return "Gang: " + Gear + + " Kadenz: " + Cadence + + " Geschwindigkeit: " + _speed + + " Name: " + Name + + " Hipster-Karten zwischen den Speichen: " + (_hasCardsInSpokes ? "Na klar!" : "Bloß nicht!") + + "\n------------------------------\n" + ; + } + + // Auch Methoden können als static gekennzeichnet werden, nützlich + // beispielsweise für Helper-Methoden + public static bool DidWeCreateEnoughBicyclesYet() + { + // In einer statischen Methode können wir natürlich auch nur + // statische Member der Klasse referenzieren + return BicyclesCreated > 9000; + } + // Wenn eine Klasse nur statische Member enthält, kann es eine gute Idee + // sein die Klasse selbst als static zu kennzeichnen + + } // Ende der Klasse "Bicycle" + + // "PennyFarthing" ist eine Unterklasse von "Bicycle" + class PennyFarthing : Bicycle + { + // (Hochräder - englisch Penny Farthing - sind diese antiken Fahrräder + // mit riesigem Vorderrad. Sie haben keine Gangschaltung.) + + // hier wird einfach der Elternkonstruktor aufgerufen + public PennyFarthing(int startCadence, int startSpeed) : + base(startCadence, startSpeed, 0, "Hochrad", true, BikeBrand.EddyMerckx) + { + } + + protected override int Gear + { + get + { + return 0; + } + set + { + throw new ArgumentException("Ein Hochrad hat keine Gangschaltung, doh!"); + } + } + + public override string ToString() + { + string result = "Hochrad "; + result += base.ToString(); // ruft die "base"-Version der Methode auf + return result; + } + } + + // Interfaces (auch Schnittstellen genant) definieren nur die Signaturen + // ihrer Member, enthalten aber auf keinen Fall ihre Implementierung: + interface IJumpable + { + // Alle Member eines Interfaces sind implizit public + void Jump(int meters); + } + + interface IBreakable + { + // Interfaces können Eigenschaften, Methoden und Events definieren + bool Broken { get; } + } + + // Eine Klasse kann nur von einer Klasse erben, kann aber eine beliebige + // Anzahl von Interfaces implementieren + class MountainBike : Bicycle, IJumpable, IBreakable + { + int damage = 0; + + public void Jump(int meters) + { + damage += meters; + } + + public bool Broken + { + get + { + return damage > 100; + } + } + } + + // Das hier stellt eine Datenbankverbindung für das LinqToSql-Beispiel her. + // EntityFramework Code First ist großartig + // (ähnlich zu Ruby's ActiveRecord, aber bidirektional) + // http://msdn.microsoft.com/de-de/data/jj193542.aspx + public class BikeRepository : DbSet + { + public BikeRepository() + : base() + { + } + + public DbSet Bikes { get; set; } + } +} // Ende des Namespaces +``` + +## In dieser Übersicht nicht enthalten sind die Themen: + + * Flags + * Attributes + * Statische Eigenschaften + * Exceptions, Abstraction + * ASP.NET (Web Forms/MVC/WebMatrix) + * Winforms + * Windows Presentation Foundation (WPF) + +## Zum Weiterlesen gibt es viele gute Anlaufpunkte: + + * [DotNetPerls](http://www.dotnetperls.com) + * [C# in Depth](http://manning.com/skeet2) + * [Programming C#](http://shop.oreilly.com/product/0636920024064.do) + * [LINQ](http://shop.oreilly.com/product/9780596519254.do) + * [MSDN Library](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx) + * [ASP.NET MVC Tutorials](http://www.asp.net/mvc/tutorials) + * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/overview/exploring-webmatrix) + * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) + * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) + +[C# Coding Conventions](http://msdn.microsoft.com/de-de/library/vstudio/ff926074.aspx) diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown index ec933696..4acb8e23 100644 --- a/de-de/elixir-de.html.markdown +++ b/de-de/elixir-de.html.markdown @@ -1,423 +1,423 @@ ---- -language: Elixir -contributors: - - ["Joao Marques", "http://github.com/mrshankly"] -translators: - - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"] -filename: learnelixir-de.ex -lang: de-de ---- - -Elixir ist eine moderne, funktionale Sprache für die Erlang VM. Sie ist voll -kompatibel mit Erlang, verfügt aber über eine freundlichere Syntax und bringt -viele Features mit. - -```ruby - -# Einzeilige Kommentare werden mit der Raute gesetzt. - -# Es gibt keine mehrzeiligen Kommentare; -# es ist aber problemlos möglich mehrere einzeilige Kommentare hintereinander -# zu setzen (so wie hier). - -# Mit 'iex' ruft man die Elixir-Shell auf. -# Zum kompilieren von Modulen dient der Befehl 'elixirc'. - -# Beide Befehle sollten als Umgebungsvariable gesetzt sein, wenn Elixir korrekt -# installiert wurde. - -## --------------------------- -## -- Basistypen -## --------------------------- - -# Es gibt Nummern: -3 # Integer -0x1F # Integer -3.0 # Float - -# Für bessere Lesbarkeit des Codes können Unterstriche "_" als Trennzeichen verwendet werden -1_000_000 == 1000000 # Integer -1_000.567 == 1000.567 # Float - -# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem -# ':'. -:hello # Atom - -# Außerdem gibt es Tupel, deren Werte im Arbeitsspeicher vorgehalten werden. -{1,2,3} # Tupel - -# Die Werte innerhalb eines Tupels können mit der 'elem'-Funktion ausgelesen -# werden: -elem({1, 2, 3}, 0) # => 1 - -# Listen sind als verkettete Listen implementiert. -[1, 2, 3] # list - -# Auf Kopf und Rest einer Liste kann wie folgt zugegriffen werden: -[ kopf | rest ] = [1,2,3] -kopf # => 1 -rest # => [2, 3] - -# In Elixir, wie auch in Erlang, kennzeichnet '=' ein 'pattern matching' -# (Musterabgleich) und keine Zuweisung. -# Das heißt, dass die linke Seite auf die rechte Seite 'abgeglichen' wird. -# Auf diese Weise kann im Beispiel oben auf Kopf und Rest der Liste zugegriffen -# werden. - -# Ein Musterabgleich wird einen Fehler werfen, wenn die beiden Seiten nicht -# zusammenpassen. -# Im folgenden Beispiel haben die Tupel eine unterschiedliche Anzahl an -# Elementen: -{a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} - -# Es gibt außerdem 'binaries', -<<1,2,3>> # binary. - -# Strings und 'char lists' -"hello" # String -'hello' # Char-Liste - -# ... und mehrzeilige Strings -""" -Ich bin ein -mehrzeiliger String. -""" -#=> "Ich bin ein\nmehrzeiliger String.\n" - -# Alles Strings werden in UTF-8 enkodiert: -"héllò" #=> "héllò" - -# Eigentlich sind Strings in Wahrheit nur binaries und 'char lists' einfach -# Listen. -<> #=> "abc" -[?a, ?b, ?c] #=> 'abc' - -# In Elixir gibt `?a` den ASCII-Integer für den Buchstaben zurück. -?a #=> 97 - -# Um Listen zu verbinden gibt es den Operator '++', für binaries nutzt man '<>' -[1,2,3] ++ [4,5] #=> [1,2,3,4,5] -'hello ' ++ 'world' #=> 'hello world' - -<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> -"hello " <> "world" #=> "hello world" - -## --------------------------- -## -- Operatoren -## --------------------------- - -# Einfache Arithmetik -1 + 1 #=> 2 -10 - 5 #=> 5 -5 * 2 #=> 10 -10 / 2 #=> 5.0 - -# In Elixir gibt der Operator '/' immer einen Float-Wert zurück. - -# Für Division mit ganzzahligen Ergebnis gibt es 'div' -div(10, 2) #=> 5 - -# Um den Rest der ganzzahligen Division zu erhalten gibt es 'rem' -rem(10, 3) #=> 1 - -# Natürlich gibt es auch Operatoren für Booleans: 'or', 'and' und 'not'. Diese -# Operatoren erwarten einen Boolean als erstes Argument. -true and true #=> true -false or true #=> true -# 1 and true #=> ** (ArgumentError) argument error - -# Elixir bietet auch '||', '&&' und '!', die Argumente jedweden Typs -# akzeptieren. Alle Werte außer 'false' und 'nil' werden zu wahr evaluiert. -1 || true #=> 1 -false && 1 #=> false -nil && 20 #=> nil - -!true #=> false - -# Für Vergleiche gibt es die Operatoren `==`, `!=`, `===`, `!==`, `<=`, `>=`, -# `<` und `>` -1 == 1 #=> true -1 != 1 #=> false -1 < 2 #=> true - -# '===' und '!==' sind strikter beim Vergleich von Integern und Floats: -1 == 1.0 #=> true -1 === 1.0 #=> false - -# Es ist außerdem möglich zwei verschiedene Datentypen zu vergleichen: -1 < :hello #=> true - -# Die gesamte Ordnung über die Datentypen ist wie folgt definiert: -# number < atom < reference < functions < port < pid < tuple < list < bitstring - -# Um Joe Armstrong zu zitieren: "The actual order is not important, but that a -# total ordering is well defined is important." - -## --------------------------- -## -- Kontrollstrukturen -## --------------------------- - -# Es gibt die `if`-Verzweigung -if false do - "Dies wird nie jemand sehen..." -else - "...aber dies!" -end - -# ...und ebenso `unless` -unless true do - "Dies wird nie jemand sehen..." -else - "...aber dies!" -end - -# Du erinnerst dich an 'pattern matching'? Viele Kontrollstrukturen in Elixir -# arbeiten damit. - -# 'case' erlaubt es uns Werte mit vielerlei Mustern zu vergleichen. -case {:one, :two} do - {:four, :five} -> - "Das wird nicht passen" - {:one, x} -> - "Das schon und außerdem wird es ':two' dem Wert 'x' zuweisen." - _ -> - "Dieser Fall greift immer." -end - -# Es ist eine übliche Praxis '_' einen Wert zuzuweisen, sofern dieser Wert -# nicht weiter verwendet wird. -# Wenn wir uns zum Beispiel nur für den Kopf einer Liste interessieren: -[kopf | _] = [1,2,3] -kopf #=> 1 - -# Für bessere Lesbarkeit können wir auch das Folgende machen: -[kopf | _rest] = [:a, :b, :c] -kopf #=> :a - -# Mit 'cond' können diverse Bedingungen zur selben Zeit überprüft werden. Man -# benutzt 'cond' statt viele if-Verzweigungen zu verschachteln. -cond do - 1 + 1 == 3 -> - "Ich werde nie aufgerufen." - 2 * 5 == 12 -> - "Ich auch nicht." - 1 + 2 == 3 -> - "Aber ich!" -end - -# Es ist üblich eine letzte Bedingung einzufügen, die immer zu wahr evaluiert. -cond do - 1 + 1 == 3 -> - "Ich werde nie aufgerufen." - 2 * 5 == 12 -> - "Ich auch nicht." - true -> - "Aber ich! (dies ist im Grunde ein 'else')" -end - -# 'try/catch' wird verwendet um Werte zu fangen, die zuvor 'geworfen' wurden. -# Das Konstrukt unterstützt außerdem eine 'after'-Klausel die aufgerufen wird, -# egal ob zuvor ein Wert gefangen wurde. -try do - throw(:hello) -catch - nachricht -> "#{nachricht} gefangen." -after - IO.puts("Ich bin die 'after'-Klausel.") -end -#=> Ich bin die 'after'-Klausel. -# ":hello gefangen" - -## --------------------------- -## -- Module und Funktionen -## --------------------------- - -# Anonyme Funktionen (man beachte den Punkt) -square = fn(x) -> x * x end -square.(5) #=> 25 - -# Anonyme Funktionen unterstützen auch 'pattern' und 'guards'. Guards erlauben -# es die Mustererkennung zu justieren und werden mit dem Schlüsselwort 'when' -# eingeführt: -f = fn - x, y when x > 0 -> x + y - x, y -> x * y -end - -f.(1, 3) #=> 4 -f.(-1, 3) #=> -3 - -# Elixir bietet zahlreiche eingebaute Funktionen. Diese sind im gleichen -# Geltungsbereich ('scope') verfügbar. -is_number(10) #=> true -is_list("hello") #=> false -elem({1,2,3}, 0) #=> 1 - -# Mehrere Funktionen können in einem Modul gruppiert werden. Innerhalb eines -# Moduls ist es möglich mit dem Schlüsselwort 'def' eine Funktion zu -# definieren. -defmodule Math do - def sum(a, b) do - a + b - end - - def square(x) do - x * x - end -end - -Math.sum(1, 2) #=> 3 -Math.square(3) #=> 9 - -# Um unser einfaches Mathe-Modul zu kompilieren muss es unter 'math.ex' -# gesichert werden. Anschließend kann es mit 'elixirc' im Terminal aufgerufen -# werden: elixirc math.ex - -# Innerhalb eines Moduls definieren wir private Funktionen mit 'defp'. Eine -# Funktion, die mit 'def' erstellt wurde, kann von anderen Modulen aufgerufen -# werden; eine private Funktion kann nur lokal angesprochen werden. -defmodule PrivateMath do - def sum(a, b) do - do_sum(a, b) - end - - defp do_sum(a, b) do - a + b - end -end - -PrivateMath.sum(1, 2) #=> 3 -# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) - -# Auch Funktionsdeklarationen unterstützen 'guards' und Mustererkennung: -defmodule Geometry do - def area({:rectangle, w, h}) do - w * h - end - - def area({:circle, r}) when is_number(r) do - 3.14 * r * r - end -end - -Geometry.area({:rectangle, 2, 3}) #=> 6 -Geometry.area({:circle, 3}) #=> 28.25999999999999801048 -# Geometry.area({:circle, "not_a_number"}) -#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 - -# Wegen der Unveränderlichkeit von Variablen ist Rekursion ein wichtiger -# Bestandteil von Elixir. -defmodule Recursion do - def sum_list([head | tail], acc) do - sum_list(tail, acc + head) - end - - def sum_list([], acc) do - acc - end -end - -Recursion.sum_list([1,2,3], 0) #=> 6 - -# Elixir-Module unterstützen Attribute. Es gibt eingebaute Attribute, ebenso -# ist es möglich eigene Attribute hinzuzufügen. -defmodule MyMod do - @moduledoc """ - Dies ist ein eingebautes Attribut in einem Beispiel-Modul - """ - - @my_data 100 # Dies ist ein selbst-definiertes Attribut. - IO.inspect(@my_data) #=> 100 -end - -## --------------------------- -## -- 'Records' und Ausnahmebehandlung -## --------------------------- - -# 'Records' sind im Grunde Strukturen, die es erlauben einem Wert einen eigenen -# Namen zuzuweisen. -defrecord Person, name: nil, age: 0, height: 0 - -joe_info = Person.new(name: "Joe", age: 30, height: 180) -#=> Person[name: "Joe", age: 30, height: 180] - -# Zugriff auf den Wert von 'name' -joe_info.name #=> "Joe" - -# Den Wert von 'age' überschreiben -joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] - -# Der 'try'-Block wird zusammen mit dem 'rescue'-Schlüsselwort dazu verwendet, -# um Ausnahmen beziehungsweise Fehler zu behandeln. -try do - raise "Irgendein Fehler." -rescue - RuntimeError -> "Laufzeit-Fehler gefangen." - _error -> "Und dies fängt jeden Fehler." -end - -# Alle Ausnahmen haben das Attribut 'message' -try do - raise "ein Fehler" -rescue - x in [RuntimeError] -> - x.message -end - -## --------------------------- -## -- Nebenläufigkeit -## --------------------------- - -# Elixir beruht auf dem Aktoren-Model zur Behandlung der Nebenläufigkeit. Alles -# was man braucht um in Elixir nebenläufige Programme zu schreiben sind drei -# Primitive: Prozesse erzeugen, Nachrichten senden und Nachrichten empfangen. - -# Um einen neuen Prozess zu erzeugen nutzen wir die 'spawn'-Funktion, die -# wiederum eine Funktion als Argument entgegen nimmt. -f = fn -> 2 * 2 end #=> #Function -spawn(f) #=> #PID<0.40.0> - -# 'spawn' gibt eine pid (einen Identifikator des Prozesses) zurück. Diese kann -# nun verwendet werden, um Nachrichten an den Prozess zu senden. Um -# zu senden nutzen wir den '<-' Operator. Damit das alles Sinn macht müssen wir -# in der Lage sein Nachrichten zu empfangen. Dies wird mit dem -# 'receive'-Mechanismus sichergestellt: -defmodule Geometry do - def area_loop do - receive do - {:rectangle, w, h} -> - IO.puts("Area = #{w * h}") - area_loop() - {:circle, r} -> - IO.puts("Area = #{3.14 * r * r}") - area_loop() - end - end -end - -# Kompiliere das Modul, starte einen Prozess und gib die 'area_loop' Funktion -# in der Shell mit, etwa so: -pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> - -# Sende eine Nachricht an die 'pid', die ein Muster im 'receive'-Ausdruck -# erfüllt: -pid <- {:rectangle, 2, 3} -#=> Area = 6 -# {:rectangle,2,3} - -pid <- {:circle, 2} -#=> Area = 12.56000000000000049738 -# {:circle,2} - -# Die Shell selbst ist ein Prozess und mit dem Schlüsselwort 'self' kann man -# die aktuelle pid herausfinden. -self() #=> #PID<0.27.0> - -``` - -## Referenzen und weitere Lektüre - -* [Getting started guide](http://elixir-lang.org/getting_started/1.html) auf der [elixir Website](http://elixir-lang.org) -* [Elixir Documentation](http://elixir-lang.org/docs/master/) -* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) von Fred Hebert -* "Programming Erlang: Software for a Concurrent World" von Joe Armstrong +--- +language: Elixir +contributors: + - ["Joao Marques", "http://github.com/mrshankly"] +translators: + - ["Gregor Große-Bölting", "http://www.ideen-und-soehne.de"] +filename: learnelixir-de.ex +lang: de-de +--- + +Elixir ist eine moderne, funktionale Sprache für die Erlang VM. Sie ist voll +kompatibel mit Erlang, verfügt aber über eine freundlichere Syntax und bringt +viele Features mit. + +```ruby + +# Einzeilige Kommentare werden mit der Raute gesetzt. + +# Es gibt keine mehrzeiligen Kommentare; +# es ist aber problemlos möglich mehrere einzeilige Kommentare hintereinander +# zu setzen (so wie hier). + +# Mit 'iex' ruft man die Elixir-Shell auf. +# Zum kompilieren von Modulen dient der Befehl 'elixirc'. + +# Beide Befehle sollten als Umgebungsvariable gesetzt sein, wenn Elixir korrekt +# installiert wurde. + +## --------------------------- +## -- Basistypen +## --------------------------- + +# Es gibt Nummern: +3 # Integer +0x1F # Integer +3.0 # Float + +# Für bessere Lesbarkeit des Codes können Unterstriche "_" als Trennzeichen verwendet werden +1_000_000 == 1000000 # Integer +1_000.567 == 1000.567 # Float + +# Atome, das sind Literale, sind Konstanten mit Namen. Sie starten mit einem +# ':'. +:hello # Atom + +# Außerdem gibt es Tupel, deren Werte im Arbeitsspeicher vorgehalten werden. +{1,2,3} # Tupel + +# Die Werte innerhalb eines Tupels können mit der 'elem'-Funktion ausgelesen +# werden: +elem({1, 2, 3}, 0) # => 1 + +# Listen sind als verkettete Listen implementiert. +[1, 2, 3] # list + +# Auf Kopf und Rest einer Liste kann wie folgt zugegriffen werden: +[ kopf | rest ] = [1,2,3] +kopf # => 1 +rest # => [2, 3] + +# In Elixir, wie auch in Erlang, kennzeichnet '=' ein 'pattern matching' +# (Musterabgleich) und keine Zuweisung. +# Das heißt, dass die linke Seite auf die rechte Seite 'abgeglichen' wird. +# Auf diese Weise kann im Beispiel oben auf Kopf und Rest der Liste zugegriffen +# werden. + +# Ein Musterabgleich wird einen Fehler werfen, wenn die beiden Seiten nicht +# zusammenpassen. +# Im folgenden Beispiel haben die Tupel eine unterschiedliche Anzahl an +# Elementen: +{a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2} + +# Es gibt außerdem 'binaries', +<<1,2,3>> # binary. + +# Strings und 'char lists' +"hello" # String +'hello' # Char-Liste + +# ... und mehrzeilige Strings +""" +Ich bin ein +mehrzeiliger String. +""" +#=> "Ich bin ein\nmehrzeiliger String.\n" + +# Alles Strings werden in UTF-8 enkodiert: +"héllò" #=> "héllò" + +# Eigentlich sind Strings in Wahrheit nur binaries und 'char lists' einfach +# Listen. +<> #=> "abc" +[?a, ?b, ?c] #=> 'abc' + +# In Elixir gibt `?a` den ASCII-Integer für den Buchstaben zurück. +?a #=> 97 + +# Um Listen zu verbinden gibt es den Operator '++', für binaries nutzt man '<>' +[1,2,3] ++ [4,5] #=> [1,2,3,4,5] +'hello ' ++ 'world' #=> 'hello world' + +<<1,2,3>> <> <<4,5>> #=> <<1,2,3,4,5>> +"hello " <> "world" #=> "hello world" + +## --------------------------- +## -- Operatoren +## --------------------------- + +# Einfache Arithmetik +1 + 1 #=> 2 +10 - 5 #=> 5 +5 * 2 #=> 10 +10 / 2 #=> 5.0 + +# In Elixir gibt der Operator '/' immer einen Float-Wert zurück. + +# Für Division mit ganzzahligen Ergebnis gibt es 'div' +div(10, 2) #=> 5 + +# Um den Rest der ganzzahligen Division zu erhalten gibt es 'rem' +rem(10, 3) #=> 1 + +# Natürlich gibt es auch Operatoren für Booleans: 'or', 'and' und 'not'. Diese +# Operatoren erwarten einen Boolean als erstes Argument. +true and true #=> true +false or true #=> true +# 1 and true #=> ** (ArgumentError) argument error + +# Elixir bietet auch '||', '&&' und '!', die Argumente jedweden Typs +# akzeptieren. Alle Werte außer 'false' und 'nil' werden zu wahr evaluiert. +1 || true #=> 1 +false && 1 #=> false +nil && 20 #=> nil + +!true #=> false + +# Für Vergleiche gibt es die Operatoren `==`, `!=`, `===`, `!==`, `<=`, `>=`, +# `<` und `>` +1 == 1 #=> true +1 != 1 #=> false +1 < 2 #=> true + +# '===' und '!==' sind strikter beim Vergleich von Integern und Floats: +1 == 1.0 #=> true +1 === 1.0 #=> false + +# Es ist außerdem möglich zwei verschiedene Datentypen zu vergleichen: +1 < :hello #=> true + +# Die gesamte Ordnung über die Datentypen ist wie folgt definiert: +# number < atom < reference < functions < port < pid < tuple < list < bitstring + +# Um Joe Armstrong zu zitieren: "The actual order is not important, but that a +# total ordering is well defined is important." + +## --------------------------- +## -- Kontrollstrukturen +## --------------------------- + +# Es gibt die `if`-Verzweigung +if false do + "Dies wird nie jemand sehen..." +else + "...aber dies!" +end + +# ...und ebenso `unless` +unless true do + "Dies wird nie jemand sehen..." +else + "...aber dies!" +end + +# Du erinnerst dich an 'pattern matching'? Viele Kontrollstrukturen in Elixir +# arbeiten damit. + +# 'case' erlaubt es uns Werte mit vielerlei Mustern zu vergleichen. +case {:one, :two} do + {:four, :five} -> + "Das wird nicht passen" + {:one, x} -> + "Das schon und außerdem wird es ':two' dem Wert 'x' zuweisen." + _ -> + "Dieser Fall greift immer." +end + +# Es ist eine übliche Praxis '_' einen Wert zuzuweisen, sofern dieser Wert +# nicht weiter verwendet wird. +# Wenn wir uns zum Beispiel nur für den Kopf einer Liste interessieren: +[kopf | _] = [1,2,3] +kopf #=> 1 + +# Für bessere Lesbarkeit können wir auch das Folgende machen: +[kopf | _rest] = [:a, :b, :c] +kopf #=> :a + +# Mit 'cond' können diverse Bedingungen zur selben Zeit überprüft werden. Man +# benutzt 'cond' statt viele if-Verzweigungen zu verschachteln. +cond do + 1 + 1 == 3 -> + "Ich werde nie aufgerufen." + 2 * 5 == 12 -> + "Ich auch nicht." + 1 + 2 == 3 -> + "Aber ich!" +end + +# Es ist üblich eine letzte Bedingung einzufügen, die immer zu wahr evaluiert. +cond do + 1 + 1 == 3 -> + "Ich werde nie aufgerufen." + 2 * 5 == 12 -> + "Ich auch nicht." + true -> + "Aber ich! (dies ist im Grunde ein 'else')" +end + +# 'try/catch' wird verwendet um Werte zu fangen, die zuvor 'geworfen' wurden. +# Das Konstrukt unterstützt außerdem eine 'after'-Klausel die aufgerufen wird, +# egal ob zuvor ein Wert gefangen wurde. +try do + throw(:hello) +catch + nachricht -> "#{nachricht} gefangen." +after + IO.puts("Ich bin die 'after'-Klausel.") +end +#=> Ich bin die 'after'-Klausel. +# ":hello gefangen" + +## --------------------------- +## -- Module und Funktionen +## --------------------------- + +# Anonyme Funktionen (man beachte den Punkt) +square = fn(x) -> x * x end +square.(5) #=> 25 + +# Anonyme Funktionen unterstützen auch 'pattern' und 'guards'. Guards erlauben +# es die Mustererkennung zu justieren und werden mit dem Schlüsselwort 'when' +# eingeführt: +f = fn + x, y when x > 0 -> x + y + x, y -> x * y +end + +f.(1, 3) #=> 4 +f.(-1, 3) #=> -3 + +# Elixir bietet zahlreiche eingebaute Funktionen. Diese sind im gleichen +# Geltungsbereich ('scope') verfügbar. +is_number(10) #=> true +is_list("hello") #=> false +elem({1,2,3}, 0) #=> 1 + +# Mehrere Funktionen können in einem Modul gruppiert werden. Innerhalb eines +# Moduls ist es möglich mit dem Schlüsselwort 'def' eine Funktion zu +# definieren. +defmodule Math do + def sum(a, b) do + a + b + end + + def square(x) do + x * x + end +end + +Math.sum(1, 2) #=> 3 +Math.square(3) #=> 9 + +# Um unser einfaches Mathe-Modul zu kompilieren muss es unter 'math.ex' +# gesichert werden. Anschließend kann es mit 'elixirc' im Terminal aufgerufen +# werden: elixirc math.ex + +# Innerhalb eines Moduls definieren wir private Funktionen mit 'defp'. Eine +# Funktion, die mit 'def' erstellt wurde, kann von anderen Modulen aufgerufen +# werden; eine private Funktion kann nur lokal angesprochen werden. +defmodule PrivateMath do + def sum(a, b) do + do_sum(a, b) + end + + defp do_sum(a, b) do + a + b + end +end + +PrivateMath.sum(1, 2) #=> 3 +# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError) + +# Auch Funktionsdeklarationen unterstützen 'guards' und Mustererkennung: +defmodule Geometry do + def area({:rectangle, w, h}) do + w * h + end + + def area({:circle, r}) when is_number(r) do + 3.14 * r * r + end +end + +Geometry.area({:rectangle, 2, 3}) #=> 6 +Geometry.area({:circle, 3}) #=> 28.25999999999999801048 +# Geometry.area({:circle, "not_a_number"}) +#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1 + +# Wegen der Unveränderlichkeit von Variablen ist Rekursion ein wichtiger +# Bestandteil von Elixir. +defmodule Recursion do + def sum_list([head | tail], acc) do + sum_list(tail, acc + head) + end + + def sum_list([], acc) do + acc + end +end + +Recursion.sum_list([1,2,3], 0) #=> 6 + +# Elixir-Module unterstützen Attribute. Es gibt eingebaute Attribute, ebenso +# ist es möglich eigene Attribute hinzuzufügen. +defmodule MyMod do + @moduledoc """ + Dies ist ein eingebautes Attribut in einem Beispiel-Modul + """ + + @my_data 100 # Dies ist ein selbst-definiertes Attribut. + IO.inspect(@my_data) #=> 100 +end + +## --------------------------- +## -- 'Records' und Ausnahmebehandlung +## --------------------------- + +# 'Records' sind im Grunde Strukturen, die es erlauben einem Wert einen eigenen +# Namen zuzuweisen. +defrecord Person, name: nil, age: 0, height: 0 + +joe_info = Person.new(name: "Joe", age: 30, height: 180) +#=> Person[name: "Joe", age: 30, height: 180] + +# Zugriff auf den Wert von 'name' +joe_info.name #=> "Joe" + +# Den Wert von 'age' überschreiben +joe_info = joe_info.age(31) #=> Person[name: "Joe", age: 31, height: 180] + +# Der 'try'-Block wird zusammen mit dem 'rescue'-Schlüsselwort dazu verwendet, +# um Ausnahmen beziehungsweise Fehler zu behandeln. +try do + raise "Irgendein Fehler." +rescue + RuntimeError -> "Laufzeit-Fehler gefangen." + _error -> "Und dies fängt jeden Fehler." +end + +# Alle Ausnahmen haben das Attribut 'message' +try do + raise "ein Fehler" +rescue + x in [RuntimeError] -> + x.message +end + +## --------------------------- +## -- Nebenläufigkeit +## --------------------------- + +# Elixir beruht auf dem Aktoren-Model zur Behandlung der Nebenläufigkeit. Alles +# was man braucht um in Elixir nebenläufige Programme zu schreiben sind drei +# Primitive: Prozesse erzeugen, Nachrichten senden und Nachrichten empfangen. + +# Um einen neuen Prozess zu erzeugen nutzen wir die 'spawn'-Funktion, die +# wiederum eine Funktion als Argument entgegen nimmt. +f = fn -> 2 * 2 end #=> #Function +spawn(f) #=> #PID<0.40.0> + +# 'spawn' gibt eine pid (einen Identifikator des Prozesses) zurück. Diese kann +# nun verwendet werden, um Nachrichten an den Prozess zu senden. Um +# zu senden nutzen wir den '<-' Operator. Damit das alles Sinn macht müssen wir +# in der Lage sein Nachrichten zu empfangen. Dies wird mit dem +# 'receive'-Mechanismus sichergestellt: +defmodule Geometry do + def area_loop do + receive do + {:rectangle, w, h} -> + IO.puts("Area = #{w * h}") + area_loop() + {:circle, r} -> + IO.puts("Area = #{3.14 * r * r}") + area_loop() + end + end +end + +# Kompiliere das Modul, starte einen Prozess und gib die 'area_loop' Funktion +# in der Shell mit, etwa so: +pid = spawn(fn -> Geometry.area_loop() end) #=> #PID<0.40.0> + +# Sende eine Nachricht an die 'pid', die ein Muster im 'receive'-Ausdruck +# erfüllt: +pid <- {:rectangle, 2, 3} +#=> Area = 6 +# {:rectangle,2,3} + +pid <- {:circle, 2} +#=> Area = 12.56000000000000049738 +# {:circle,2} + +# Die Shell selbst ist ein Prozess und mit dem Schlüsselwort 'self' kann man +# die aktuelle pid herausfinden. +self() #=> #PID<0.27.0> + +``` + +## Referenzen und weitere Lektüre + +* [Getting started guide](http://elixir-lang.org/getting_started/1.html) auf der [elixir Website](http://elixir-lang.org) +* [Elixir Documentation](http://elixir-lang.org/docs/master/) +* ["Learn You Some Erlang for Great Good!"](http://learnyousomeerlang.com/) von Fred Hebert +* "Programming Erlang: Software for a Concurrent World" von Joe Armstrong diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index f817ee9f..a71d4316 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -1,525 +1,525 @@ ---- -language: javascript -contributors: - - ["Leigh Brenecki", "https://leigh.net.au"] -translators: - - ["ggb", "http://www.ideen-und-soehne.de"] -filename: learnjavascript-de.js -lang: de-de ---- - -(Anmerkungen des Original-Autors:) -JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzend zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java. - -Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer. - -Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@excitedleigh](https://twitter.com/excitedleigh) oder [l@leigh.net.au](mailto:l@leigh.net.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de). - -```js -// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei -// Slashes -/* während mehrzeilige Kommentare mit einem -Slash und einem Stern anfangen und enden */ - -// Statements können mit einem Semikolon beendet werden -machWas(); - -// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn -// eine neue Zeile beginnt, abgesehen von einigen Ausnahmen. -machWas() - -// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist -// es besser die Semikola immer zu setzen. - -/////////////////////////////////// -// 1. Nummern, Strings und Operationen - -// JavaScript hat einen Nummern-Typ (64-bit IEEE 754 double). -3; // = 3 -1.5; // = 1.5 - -// Beinahe alle grundlegenden arithmetischen Operationen arbeiten wie erwartet. -1 + 1; // = 2 -0.1 + 0.2; // = 0.30000000000000004 -10 * 2; // = 20 -35 / 5; // = 7 - -// Division funktioniert auch mit einem Ergebnis nach dem Komma. -5 / 2; // = 2.5 - -// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation -// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit -// Vorzeichen) umgewandelt. -1 << 2; // = 4 - -// Die Rangfolge der Operationen kann mit Klammern erzwungen werden. -(1 + 3) * 2; // = 8 - -// Es gibt drei spezielle, nicht-reale Nummern-Werte: -Infinity; // Ergebnis von z. B. 1 / 0 --Infinity; // Ergebnis von z. B. -1 / 0 -NaN; // Ergebnis von z. B. 0 / 0 - -// Es gibt auch einen Boolean-Typ (für Wahrheitswerte). -true; -false; - -// Strings werden mit ' oder " erzeugt. -'abc'; -"Hello, world"; - -// Für die Negation wird das ! benutzt. -!true; // = false -!false; // = true - -// Gleichheit wird mit === geprüft. -1 === 1; // = true -2 === 1; // = false - -// Ungleichheit wird mit !== überprüft. -1 !== 1; // = false -2 !== 1; // = true - -// Andere Vergleichsoperatoren sind -1 < 10; // = true -1 > 10; // = false -2 <= 2; // = true -2 >= 2; // = true - -// Strings können mit + verbunden -"Hello " + "world!"; // = "Hello world!" - -// und mit < und > verglichen werden. -"a" < "b"; // = true - -// Für den Vergleich von Werten mit "==" wird eine Typumwandlung erzwungen... -"5" == 5; // = true - -// ...solange man nicht === verwendet. -"5" === 5; // = false - -// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode -// 'charAt' zugegriffen werden -"This is a string".charAt(0); // = "T" - -// Die Methode 'substring' gibt Teilbereiche eines Strings zurück -"Hello world".substring(0, 5); // = "Hello" - -// 'length' ist eine Eigenschaft und wird folglich ohne '()' benutzt -"Hello".length; // = 5 - -// Es gibt außerdem die Werte 'null' und 'undefined' -null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen -undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht - // verfügbar ist (obwohl genau genommen undefined selbst einen Wert - // darstellt) - -// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist -// wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0". - -/////////////////////////////////// -// 2. Variablen, Arrays und Objekte - -// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren -// Bezeichner deklariert. JavaScript ist dynamisch typisiert, so dass man einer -// Variable keinen Typ zuweisen muss. Die Zuweisung verwendet ein einfaches =. -var einWert = 5; - - // Wenn man das Schlüsselwort 'var' weglässt, bekommt man keinen Fehler -einAndererWert = 10; - -// ...aber die Variable wird im globalen Kontext erzeugt, nicht in dem Kontext, -// in dem sie erzeugt wurde. - -// Variablen die erzeugt wurden ohne ihnen einen Wert zuzuweisen, erhalten den -// Wert 'undefined'. -var einDritterWert; // = undefined - -// Es existiert eine Kurzform, um mathematische Operationen mit Variablen -// auszuführen: -einWert += 5; // äquivalent zu einWert = einWert + 5; einWert ist nun also 10 -einWert *= 10; // einWert ist nach dieser Operation 100 - -// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren -// oder zu subtrahieren -einWert++; // nun ist einWert 101 -einWert--; // wieder 100 - -// Arrays sind geordnete Listen von Werten irgendeines Typs -var myArray = ["Hello", 45, true]; - -// Auf einzelne Elemente eines Arrays kann zugegriffen werden, in dem der Index -// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung -// beginnt bei 0. -myArray[1]; // = 45 - -// Arrays haben keine feste Länge -myArray.push("World"); -myArray.length; // = 4 - -// und sind veränderlich -myArray[3] = "Hello"; - -// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen -// Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare. -var myObj = { key1: "Hello", key2: "World" }; - -// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt, -// sofern es sich um reguläre JavaScript-Bezeichner handelt. Werte können von -// jedem Typ sein. -var myObj = { myKey: "myValue", "my other key": 4 }; - -// Auf Attribute von Objekten kann ebenfalls mit eckigen Klammern zugegriffen -// werden, -myObj["my other key"]; // = 4 - -// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt -// sich bei dem Schlüssel um einen validen Bezeichner. -myObj.myKey; // = "myValue" - -// Objekte sind veränderlich, Werte können verändert und neue Schlüssel -// hinzugefügt werden. -myObj.myThirdKey = true; - -// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein -// undefined. -myObj.myFourthKey; // = undefined - -/////////////////////////////////// -// 3. Logik und Kontrollstrukturen - -// Die if-Struktur arbeitet, wie man es erwartet. -var count = 1; -if (count == 3){ - // wird evaluiert, wenn count gleich 3 ist -} else if (count == 4) { - // wird evaluiert, wenn count gleich 4 ist -} else { - // wird evaluiert, wenn es weder 3 noch 4 ist -} - -// Genauso 'while'. -while (true) { - // Eine unendliche Schleife! -} - -// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie -// immer mindestens einmal ausgeführt werden. -var input; -do { - input = getInput(); -} while ( !isValid( input ) ) - -// Die for-Schleife arbeitet genau wie in C und Java: -// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird; -// Iteration. -for ( var i = 0; i < 5; i++ ) { - // wird 5-mal ausgeführt -} - -// '&&' ist das logische und, '||' ist das logische oder -if (house.size == "big" && house.colour == "blue"){ - house.contains = "bear"; - // Die Größe des Hauses ist groß und die Farbe blau. -} -if (colour == "red" || colour == "blue"){ - // Die Farbe ist entweder rot oder blau. -} - -// Die Auswertung von '&&' und '||' erfolgt so, dass abgebrochen wird, wenn die -// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist -// nützlich, um einen Default-Wert zu setzen. -var name = otherName || "default"; - -// Ein 'switch' Statement prüft Gleichheit mit === -// ohne ein 'break' nach jedem Fall -// werden auch die Fälle nach dem korrekten aufgerufen -grade = 'B'; -switch (grade) { - case 'A': - console.log("Great job"); - break; - case 'B': - console.log("OK job"); - break; - case 'C': - console.log("You can do better"); - break; - default: - console.log("Oy vey"); - break; -} - -/////////////////////////////////// -// 4. Funktionen, Geltungsbereich und Closures - -// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert. -function myFunction(thing){ - return thing.toUpperCase(); -} -myFunction("foo"); // = "FOO" - -// Vorsicht: der Ausdruck der den Rückgabewert einer Funktion bildet muss -// auf der selben Zeile beginnen auf der auch das 'return' Keyword steht -// Sonst wird hier ein automatisches Semikolon eingefügt und die Funktion -// gibt 'undefined' zurück -function myFunction() -{ - return // <- Hier wird automatisch ein Semikolon eingefügt - { - thisIsAn: 'object literal' - } -} -myFunction(); // = undefined - -// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie -// Variablen verwendet und als Parameter anderen Funktionen übergeben werden -// - zum Beispiel, um einen 'event handler' zu 'beliefern'. -function myFunction() { - // wird ausgeführt, nachdem 5 Sekunden vergangen sind -} -setTimeout(myFunction, 5000); - -// Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen. -// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument -// einer anderen Funktion zu definieren. -setTimeout(function(){ - // wird ausgeführt, nachdem 5 Sekunden vergangen sind -}, 5000); - -// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt: -// Funktionen haben ihren eigenen Geltungsbereich, andere Blöcke nicht. -if(true) { - var i = 5; -} -i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die - // ihren Geltungsbereich nach Blöcken richtet - -// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme -// Funktionen, die es vermeiden, dass der globale Geltungsbereich von Variablen -// 'verschmutzt' wird. -(function(){ - var temporary = 5; - // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden, - // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist - // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js, - // kann das anders aussehen). - window.permanent = 10; -})(); -temporary; // wirft einen ReferenceError -permanent; // = 10 - -// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird -// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die -// innere Funktion Zugriff auf alle Variablen der äußeren Funktion, sogar dann, -// wenn die äußere Funktion beendet wurde. -function sayHelloInFiveSeconds(name){ - var prompt = "Hello, " + name + "!"; - function inner(){ - alert(prompt); - } - setTimeout(inner, 5000); - // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds - // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' - // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere - // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die - // Variable prompt. -} -sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der - // Nachricht "Hello, Adam!" öffnen. - -/////////////////////////////////// -// 5. Mehr über Objekte, Konstruktoren und Prototypen - -// Objekte können Funktionen enthalten. -var myObj = { - myFunc: function(){ - return "Hello world!"; - } -}; -myObj.myFunc(); // = "Hello world!" - -// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie -// auf das eigene Objekt mit dem Schlüsselwort 'this' zugreifen. -myObj = { - myString: "Hello world!", - myFunc: function(){ - return this.myString; - } -}; -myObj.myFunc(); // = "Hello world!" - -// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen -// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht -// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen -// wird. -var myFunc = myObj.myFunc; -myFunc(); // = undefined - -// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch -// Zugriff auf den this-Kontext zu erhalten, sogar dann, wenn die Funktion dem -// Objekt nach dessen Definition zugewiesen wird. -var myOtherFunc = function(){ - return this.myString.toUpperCase(); -} -myObj.myOtherFunc = myOtherFunc; -myObj.myOtherFunc(); // = "HELLO WORLD!" - -// Mit den Methoden 'call' und 'apply' kann der Kontext eines Funktionsaufrufs -// verändert werden - -var anotherFunc = function(s){ - return this.myString + s; -} -anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" - -// 'apply' funktioniert beiahe identisch, erwartet die übergebenen Argumente -// aber in einem Array - -anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" - -// Das ist hilfreich wenn man einer Funktion eine beliebige Zahl Argumente -// übergeben kann - -Math.min(42, 6, 27); // = 6 -Math.min([42, 6, 27]); // = NaN (uh-oh!) -Math.min.apply(Math, [42, 6, 27]); // = 6 - -// 'call' und 'apply' beeinflussen aber nur den spezifischen Aufruf. -// Um den Kontext einer Funktion dauerhaft zu ändern wird 'bind' benutzt. - -var boundFunc = anotherFunc.bind(myObj); -boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" - -// Mit 'bind' lassen sich Funktionen auch teilweise anwenden / "curryen". -var product = function(a, b){ return a * b; } -var doubler = product.bind(this, 2); -doubler(8); // = 16 - -// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird -// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser -// Art aufgerufen zu werden, werden Konstruktoren genannt. -var MyConstructor = function(){ - this.myNumber = 5; -} -myNewObj = new MyConstructor(); // = {myNumber: 5} -myNewObj.myNumber; // = 5 - -// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine -// Eigenschaft des Objekts zuzugreifen, das nicht im Objekt selbst existiert, -// schaut der Interpreter in dessen Prototyp nach. - -// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den -// Prototyp eines Objekts durch die magische Eigenschaft __proto__. Obwohl das -// nützlich ist, um Prototypen im Allgemeinen zu erklären, ist das nicht Teil -// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir -// später. -var myObj = { - myString: "Hello world!", -}; -var myPrototype = { - meaningOfLife: 42, - myFunc: function(){ - return this.myString.toLowerCase() - } -}; -myObj.__proto__ = myPrototype; -myObj.meaningOfLife; // = 42 - -// Das funktioniert auch bei Funktionen. -myObj.myFunc(); // = "hello world!" - -// Sollte die Eigenschaft nicht im Prototypen des Objekts enthalten sein, dann -// wird im Prototypen des Prototypen nachgesehen und so weiter. -myPrototype.__proto__ = { - myBoolean: true -}; -myObj.myBoolean; // = true - -// Dafür wird nichts hin und her kopiert; jedes Objekt speichert eine Referenz -// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann -// werden die Änderungen überall sichtbar. -myPrototype.meaningOfLife = 43; -myObj.meaningOfLife; // = 43 - -// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es -// gibt ebenso keinen Standard-Weg, um den Prototyp eines existierenden Objekts -// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem -// gegebenen Prototypen erzeugt. - -// Der erste Weg ist die Methode Object.create, die eine jüngere Ergänzung des -// JavaScript-Standards ist und daher noch nicht in allen Implementierungen -// verfügbar. -var myObj = Object.create(myPrototype); -myObj.meaningOfLife; // = 43 - -// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun. -// Konstruktoren haben eine Eigenschaft, die Prototyp heißt. Dabei handelt es -// sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt -// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es -// mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird. -MyConstructor.prototype = { - getMyNumber: function(){ - return this.myNumber - } -}; -var myNewObj2 = new MyConstructor(); -myNewObj2.getMyNumber(); // = 5 - -// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren, -// die zu dem Typ äquivalente Wrapper-Objekte erzeugen. -var myNumber = 12; -var myNumberObj = new Number(12); -myNumber == myNumberObj; // = true - -// Genau genommen: Sie sind nicht exakt äquivalent. -typeof myNumber; // = 'number' -typeof myNumberObj; // = 'object' -myNumber === myNumberObj; // = false -if (0){ - // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist. -} - -// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen -// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen -// hinzuzufügen. -String.prototype.firstCharacter = function(){ - return this.charAt(0); -} -"abc".firstCharacter(); // = "a" - -// Diese Tatsache wird häufig bei einer Methode mit dem Namen 'polyfilling' -// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren -// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in -// älteren Umgebungen und Browsern verwendet werden können. - -// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in -// allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem -// 'polyfill': -if (Object.create === undefined){ // überschreib nichts, was eventuell bereits - // existiert - Object.create = function(proto){ - // erstelle einen vorübergehenden Konstruktor mit dem richtigen - // Prototypen - var Constructor = function(){}; - Constructor.prototype = proto; - // verwende es dann, um ein neues Objekt mit einem passenden - // Prototypen zurückzugeben - return new Constructor(); - } -} -``` - -## Zur weiteren Lektüre (englisch) - -Das [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) bietet eine ausgezeichnete Dokumentation für die Verwendung von JavaScript im Browser. Es ist außerdem ein Wiki und ermöglicht es damit anderen zu helfen, wenn man selbst ein wenig Wissen angesammelt hat. - -MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus. - -Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen. - -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache. - -[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) ist ein Klassiker unter den Referenzen. - -Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden. +--- +language: javascript +contributors: + - ["Leigh Brenecki", "https://leigh.net.au"] +translators: + - ["ggb", "http://www.ideen-und-soehne.de"] +filename: learnjavascript-de.js +lang: de-de +--- + +(Anmerkungen des Original-Autors:) +JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzend zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java. + +Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer. + +Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@excitedleigh](https://twitter.com/excitedleigh) oder [l@leigh.net.au](mailto:l@leigh.net.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de). + +```js +// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei +// Slashes +/* während mehrzeilige Kommentare mit einem +Slash und einem Stern anfangen und enden */ + +// Statements können mit einem Semikolon beendet werden +machWas(); + +// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn +// eine neue Zeile beginnt, abgesehen von einigen Ausnahmen. +machWas() + +// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist +// es besser die Semikola immer zu setzen. + +/////////////////////////////////// +// 1. Nummern, Strings und Operationen + +// JavaScript hat einen Nummern-Typ (64-bit IEEE 754 double). +3; // = 3 +1.5; // = 1.5 + +// Beinahe alle grundlegenden arithmetischen Operationen arbeiten wie erwartet. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +10 * 2; // = 20 +35 / 5; // = 7 + +// Division funktioniert auch mit einem Ergebnis nach dem Komma. +5 / 2; // = 2.5 + +// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation +// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit +// Vorzeichen) umgewandelt. +1 << 2; // = 4 + +// Die Rangfolge der Operationen kann mit Klammern erzwungen werden. +(1 + 3) * 2; // = 8 + +// Es gibt drei spezielle, nicht-reale Nummern-Werte: +Infinity; // Ergebnis von z. B. 1 / 0 +-Infinity; // Ergebnis von z. B. -1 / 0 +NaN; // Ergebnis von z. B. 0 / 0 + +// Es gibt auch einen Boolean-Typ (für Wahrheitswerte). +true; +false; + +// Strings werden mit ' oder " erzeugt. +'abc'; +"Hello, world"; + +// Für die Negation wird das ! benutzt. +!true; // = false +!false; // = true + +// Gleichheit wird mit === geprüft. +1 === 1; // = true +2 === 1; // = false + +// Ungleichheit wird mit !== überprüft. +1 !== 1; // = false +2 !== 1; // = true + +// Andere Vergleichsoperatoren sind +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Strings können mit + verbunden +"Hello " + "world!"; // = "Hello world!" + +// und mit < und > verglichen werden. +"a" < "b"; // = true + +// Für den Vergleich von Werten mit "==" wird eine Typumwandlung erzwungen... +"5" == 5; // = true + +// ...solange man nicht === verwendet. +"5" === 5; // = false + +// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode +// 'charAt' zugegriffen werden +"This is a string".charAt(0); // = "T" + +// Die Methode 'substring' gibt Teilbereiche eines Strings zurück +"Hello world".substring(0, 5); // = "Hello" + +// 'length' ist eine Eigenschaft und wird folglich ohne '()' benutzt +"Hello".length; // = 5 + +// Es gibt außerdem die Werte 'null' und 'undefined' +null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen +undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht + // verfügbar ist (obwohl genau genommen undefined selbst einen Wert + // darstellt) + +// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist +// wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0". + +/////////////////////////////////// +// 2. Variablen, Arrays und Objekte + +// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren +// Bezeichner deklariert. JavaScript ist dynamisch typisiert, so dass man einer +// Variable keinen Typ zuweisen muss. Die Zuweisung verwendet ein einfaches =. +var einWert = 5; + + // Wenn man das Schlüsselwort 'var' weglässt, bekommt man keinen Fehler +einAndererWert = 10; + +// ...aber die Variable wird im globalen Kontext erzeugt, nicht in dem Kontext, +// in dem sie erzeugt wurde. + +// Variablen die erzeugt wurden ohne ihnen einen Wert zuzuweisen, erhalten den +// Wert 'undefined'. +var einDritterWert; // = undefined + +// Es existiert eine Kurzform, um mathematische Operationen mit Variablen +// auszuführen: +einWert += 5; // äquivalent zu einWert = einWert + 5; einWert ist nun also 10 +einWert *= 10; // einWert ist nach dieser Operation 100 + +// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren +// oder zu subtrahieren +einWert++; // nun ist einWert 101 +einWert--; // wieder 100 + +// Arrays sind geordnete Listen von Werten irgendeines Typs +var myArray = ["Hello", 45, true]; + +// Auf einzelne Elemente eines Arrays kann zugegriffen werden, in dem der Index +// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung +// beginnt bei 0. +myArray[1]; // = 45 + +// Arrays haben keine feste Länge +myArray.push("World"); +myArray.length; // = 4 + +// und sind veränderlich +myArray[3] = "Hello"; + +// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen +// Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare. +var myObj = { key1: "Hello", key2: "World" }; + +// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt, +// sofern es sich um reguläre JavaScript-Bezeichner handelt. Werte können von +// jedem Typ sein. +var myObj = { myKey: "myValue", "my other key": 4 }; + +// Auf Attribute von Objekten kann ebenfalls mit eckigen Klammern zugegriffen +// werden, +myObj["my other key"]; // = 4 + +// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt +// sich bei dem Schlüssel um einen validen Bezeichner. +myObj.myKey; // = "myValue" + +// Objekte sind veränderlich, Werte können verändert und neue Schlüssel +// hinzugefügt werden. +myObj.myThirdKey = true; + +// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein +// undefined. +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. Logik und Kontrollstrukturen + +// Die if-Struktur arbeitet, wie man es erwartet. +var count = 1; +if (count == 3){ + // wird evaluiert, wenn count gleich 3 ist +} else if (count == 4) { + // wird evaluiert, wenn count gleich 4 ist +} else { + // wird evaluiert, wenn es weder 3 noch 4 ist +} + +// Genauso 'while'. +while (true) { + // Eine unendliche Schleife! +} + +// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie +// immer mindestens einmal ausgeführt werden. +var input; +do { + input = getInput(); +} while ( !isValid( input ) ) + +// Die for-Schleife arbeitet genau wie in C und Java: +// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird; +// Iteration. +for ( var i = 0; i < 5; i++ ) { + // wird 5-mal ausgeführt +} + +// '&&' ist das logische und, '||' ist das logische oder +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; + // Die Größe des Hauses ist groß und die Farbe blau. +} +if (colour == "red" || colour == "blue"){ + // Die Farbe ist entweder rot oder blau. +} + +// Die Auswertung von '&&' und '||' erfolgt so, dass abgebrochen wird, wenn die +// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist +// nützlich, um einen Default-Wert zu setzen. +var name = otherName || "default"; + +// Ein 'switch' Statement prüft Gleichheit mit === +// ohne ein 'break' nach jedem Fall +// werden auch die Fälle nach dem korrekten aufgerufen +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + +/////////////////////////////////// +// 4. Funktionen, Geltungsbereich und Closures + +// In JavaScript werden Funktionen mit dem Schlüsselwort 'function' deklariert. +function myFunction(thing){ + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// Vorsicht: der Ausdruck der den Rückgabewert einer Funktion bildet muss +// auf der selben Zeile beginnen auf der auch das 'return' Keyword steht +// Sonst wird hier ein automatisches Semikolon eingefügt und die Funktion +// gibt 'undefined' zurück +function myFunction() +{ + return // <- Hier wird automatisch ein Semikolon eingefügt + { + thisIsAn: 'object literal' + } +} +myFunction(); // = undefined + +// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie +// Variablen verwendet und als Parameter anderen Funktionen übergeben werden +// - zum Beispiel, um einen 'event handler' zu 'beliefern'. +function myFunction() { + // wird ausgeführt, nachdem 5 Sekunden vergangen sind +} +setTimeout(myFunction, 5000); + +// Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen. +// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument +// einer anderen Funktion zu definieren. +setTimeout(function(){ + // wird ausgeführt, nachdem 5 Sekunden vergangen sind +}, 5000); + +// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt: +// Funktionen haben ihren eigenen Geltungsbereich, andere Blöcke nicht. +if(true) { + var i = 5; +} +i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die + // ihren Geltungsbereich nach Blöcken richtet + +// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme +// Funktionen, die es vermeiden, dass der globale Geltungsbereich von Variablen +// 'verschmutzt' wird. +(function(){ + var temporary = 5; + // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden, + // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist + // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js, + // kann das anders aussehen). + window.permanent = 10; +})(); +temporary; // wirft einen ReferenceError +permanent; // = 10 + +// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird +// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die +// innere Funktion Zugriff auf alle Variablen der äußeren Funktion, sogar dann, +// wenn die äußere Funktion beendet wurde. +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds + // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' + // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere + // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die + // Variable prompt. +} +sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der + // Nachricht "Hello, Adam!" öffnen. + +/////////////////////////////////// +// 5. Mehr über Objekte, Konstruktoren und Prototypen + +// Objekte können Funktionen enthalten. +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie +// auf das eigene Objekt mit dem Schlüsselwort 'this' zugreifen. +myObj = { + myString: "Hello world!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Hello world!" + +// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen +// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht +// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen +// wird. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch +// Zugriff auf den this-Kontext zu erhalten, sogar dann, wenn die Funktion dem +// Objekt nach dessen Definition zugewiesen wird. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +} +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "HELLO WORLD!" + +// Mit den Methoden 'call' und 'apply' kann der Kontext eines Funktionsaufrufs +// verändert werden + +var anotherFunc = function(s){ + return this.myString + s; +} +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// 'apply' funktioniert beiahe identisch, erwartet die übergebenen Argumente +// aber in einem Array + +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// Das ist hilfreich wenn man einer Funktion eine beliebige Zahl Argumente +// übergeben kann + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (uh-oh!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// 'call' und 'apply' beeinflussen aber nur den spezifischen Aufruf. +// Um den Kontext einer Funktion dauerhaft zu ändern wird 'bind' benutzt. + +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// Mit 'bind' lassen sich Funktionen auch teilweise anwenden / "curryen". +var product = function(a, b){ return a * b; } +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird +// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser +// Art aufgerufen zu werden, werden Konstruktoren genannt. +var MyConstructor = function(){ + this.myNumber = 5; +} +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine +// Eigenschaft des Objekts zuzugreifen, das nicht im Objekt selbst existiert, +// schaut der Interpreter in dessen Prototyp nach. + +// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den +// Prototyp eines Objekts durch die magische Eigenschaft __proto__. Obwohl das +// nützlich ist, um Prototypen im Allgemeinen zu erklären, ist das nicht Teil +// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir +// später. +var myObj = { + myString: "Hello world!", +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function(){ + return this.myString.toLowerCase() + } +}; +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// Das funktioniert auch bei Funktionen. +myObj.myFunc(); // = "hello world!" + +// Sollte die Eigenschaft nicht im Prototypen des Objekts enthalten sein, dann +// wird im Prototypen des Prototypen nachgesehen und so weiter. +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Dafür wird nichts hin und her kopiert; jedes Objekt speichert eine Referenz +// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann +// werden die Änderungen überall sichtbar. +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es +// gibt ebenso keinen Standard-Weg, um den Prototyp eines existierenden Objekts +// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem +// gegebenen Prototypen erzeugt. + +// Der erste Weg ist die Methode Object.create, die eine jüngere Ergänzung des +// JavaScript-Standards ist und daher noch nicht in allen Implementierungen +// verfügbar. +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun. +// Konstruktoren haben eine Eigenschaft, die Prototyp heißt. Dabei handelt es +// sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt +// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es +// mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird. +MyConstructor.prototype = { + getMyNumber: function(){ + return this.myNumber + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 + +// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren, +// die zu dem Typ äquivalente Wrapper-Objekte erzeugen. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Genau genommen: Sie sind nicht exakt äquivalent. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist. +} + +// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen +// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen +// hinzuzufügen. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +} +"abc".firstCharacter(); // = "a" + +// Diese Tatsache wird häufig bei einer Methode mit dem Namen 'polyfilling' +// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren +// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in +// älteren Umgebungen und Browsern verwendet werden können. + +// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in +// allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem +// 'polyfill': +if (Object.create === undefined){ // überschreib nichts, was eventuell bereits + // existiert + Object.create = function(proto){ + // erstelle einen vorübergehenden Konstruktor mit dem richtigen + // Prototypen + var Constructor = function(){}; + Constructor.prototype = proto; + // verwende es dann, um ein neues Objekt mit einem passenden + // Prototypen zurückzugeben + return new Constructor(); + } +} +``` + +## Zur weiteren Lektüre (englisch) + +Das [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) bietet eine ausgezeichnete Dokumentation für die Verwendung von JavaScript im Browser. Es ist außerdem ein Wiki und ermöglicht es damit anderen zu helfen, wenn man selbst ein wenig Wissen angesammelt hat. + +MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus. + +Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen. + +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache. + +[JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) ist ein Klassiker unter den Referenzen. + +Zusätzlich zu direkten Beiträgen zu diesem Artikel ist der Inhalt in Anlehnung an Louie Dinh's Python-Tutorial auf dieser Seite und das [JS Tutorial](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) des Mozilla Developer Network entstanden. diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown index 1bae332c..3674f2f5 100644 --- a/de-de/make-de.html.markdown +++ b/de-de/make-de.html.markdown @@ -1,263 +1,263 @@ ---- -category: tool -tool: make -contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] -translators: - - ["Martin Schimandl", "https://github.com/Git-Jiro"] -filename: Makefile-de -lang: de-de ---- - -Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele) -zu erzeugen. Es dient dazu, die geringste Menge an Arbeit zu verrichten um -ein Ziel in Einklang mit dem Quellcode zu bringen. Make wurde berühmterweise -von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer -sehr verbreitet (vorallem im Unix Umfeld) obwohl es bereits sehr viel -Konkurrenz und Kritik zu Make gibt. - -Es gibt eine Vielzahl an Varianten von Make, dieser Artikel beschäftigt sich -mit der Version GNU Make. Diese Version ist Standard auf Linux. - -```make - -# Kommentare können so geschrieben werden. - -# Dateien sollten Makefile heißen, denn dann können sie als `make ` -# aufgerufen werden. Ansonsten muss `make -f "dateiname" ` verwendet -# werden. - -# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet -# werden. Niemals Leerzeichen! - -#----------------------------------------------------------------------- -# Grundlagen -#----------------------------------------------------------------------- - -# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt -# nicht existiert. -file0.txt: - echo "foo" > file0.txt - # Selbst Kommentare in der 'Rezept' Sektion werden an die Shell - # weitergegeben. Versuche `make file0.txt` oder einfach `make` - # die erste Regel ist die Standard-Regel. - - -# Diese Regel wird nur abgearbeitet, wenn file0.txt aktueller als file1.txt ist. -file1.txt: file0.txt - cat file0.txt > file1.txt - # Verwende die selben Quoting-Regeln wie die Shell - @cat file0.txt >> file1.txt - # @ unterdrückt die Ausgabe des Befehls an stdout. - -@echo 'hello' - # - bedeutet, dass Make die Abarbeitung fortsetzt auch wenn Fehler - # passieren. - # Versuche `make file1.txt` auf der Kommandozeile. - -# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben. -file2.txt file3.txt: file0.txt file1.txt - touch file2.txt - touch file3.txt - -# Make wird sich beschweren, wenn es mehrere Rezepte für die gleiche Regel gibt. -# Leere Rezepte zählen nicht und können dazu verwendet werden weitere -# Voraussetzungen hinzuzufügen. - -#----------------------------------------------------------------------- -# Phony-Ziele -#----------------------------------------------------------------------- - -# Ein Phony-Ziel ist ein Ziel, das keine Datei ist. -# Es wird nie aktuell sein, daher wird Make immer versuchen, es abzuarbeiten -all: maker process - -# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren. -maker: - touch ex0.txt ex1.txt - -# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den -# selben namen wie ein Phony-Ziel hat: -.PHONY: all maker process -# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon. - -# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet -ex0.txt ex1.txt: maker - -# Häufige Phony-Ziele sind: all make clean install ... - -#----------------------------------------------------------------------- -# Automatische Variablen & Wildcards -#----------------------------------------------------------------------- - -process: file*.txt # Eine Wildcard um Dateinamen zu vergleichen - @echo $^ # $^ ist eine Variable die eine Liste aller - # Voraussetzungen enthält. - @echo $@ # Namen des Ziels ausgeben. - #(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung - #der Regel.) - @echo $< # Die erste Voraussetzung aus der Liste - @echo $? # Nur die Voraussetzungen, die nicht aktuell sind. - @echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich) - #@echo $| # Alle 'order only' Voraussetzungen - -# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden. -process: ex1.txt file0.txt -# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert. - -#----------------------------------------------------------------------- -# Muster -#----------------------------------------------------------------------- - -# Mit Mustern kann man make beibringen wie Dateien in andere Dateien -# umgewandelt werden. - -%.png: %.svg - inkscape --export-png $^ - -# Muster-Vergleichs-Regeln werden nur abgearbeitet, wenn make entscheidet das -# Ziel zu erzeugen - -# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert. -# Aber make wird versuchen die am besten passende Regel zu verwenden. -small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ - -# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden, die es -# findet. -%.png: %.svg - @echo this rule is chosen - -# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden, die das -# Ziel erzeugen kann. -%.png: %.ps - @echo this rule is not chosen if *.svg and *.ps are both present - -# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel -# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt. - -# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt -# Muster-Vergleichs-Regeln. -.png.ps: - @echo this rule is similar to a pattern rule. - -# Aktivieren der Suffix-Regel -.SUFFIXES: .png - -#----------------------------------------------------------------------- -# Variablen -#----------------------------------------------------------------------- -# auch Makros genannt. - -# Variablen sind im Grunde genommen Zeichenketten-Typen. - -name = Ted -name2="Sarah" - -echo: - @echo $(name) - @echo ${name2} - @echo $name # Das funktioniert nicht, wird als $(n)ame behandelt. - @echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt. - -# Es git 4 Stellen um Variablen zu setzen. -# In Reihenfolge der Priorität von höchster zu niedrigster: -# 1: Befehls-Zeilen Argumente -# 2: Makefile -# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch. -# 3: MAke hat einige vordefinierte Variablen. - -name4 ?= Jean -# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch -# nicht gibt. - -override name5 = David -# Verhindert, dass Kommando-Zeilen Argumente diese Variable ändern können. - -name4 +=grey -# Werte an eine Variable anhängen (inkludiert Leerzeichen). - -# Muster-Spezifische Variablen Werte (GNU Erweiterung). -echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb - # rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören - # kann, wenn es zu kompilizert wird!) - -# Ein paar Variablen, die von Make automatisch definiert werden. -echo_inbuilt: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} - -#----------------------------------------------------------------------- -# Variablen 2 -#----------------------------------------------------------------------- - -# Der erste Typ von Variablen wird bei jeder Verwendung ausgewertet. -# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen. -# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung) - -var := hello -var2 ::= $(var) hello -#:= und ::= sind äquivalent. - -# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie -# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache! - -# Das funktioniert nicht -var3 ::= $(var4) and good luck -var4 ::= good night - -#----------------------------------------------------------------------- -# Funktionen -#----------------------------------------------------------------------- - -# Make verfügt über eine Vielzahl von Funktionen. - -sourcefiles = $(wildcard *.c */*.c) -objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) - -# Das Format ist $(func arg0,arg1,arg2...) - -# Ein paar Beispiele -ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) - -#----------------------------------------------------------------------- -# Direktiven -#----------------------------------------------------------------------- - -# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code -include foo.mk - -sport = tennis -# Konditionale kompiliereung -report: -ifeq ($(sport),tennis) - @echo 'game, set, match' -else - @echo "They think it's all over; it is now" -endif - -# Es gibt auch ifneq, ifdef, ifndef - -foo = true - -ifdef $(foo) -bar = 'hello' -endif -``` - - -### Mehr Resourcen - -+ [gnu make documentation](https://www.gnu.org/software/make/manual/) -+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) -+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) - +--- +category: tool +tool: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] +translators: + - ["Martin Schimandl", "https://github.com/Git-Jiro"] +filename: Makefile-de +lang: de-de +--- + +Eine Makefile definiert einen Graphen von Regeln um ein Ziel (oder Ziele) +zu erzeugen. Es dient dazu, die geringste Menge an Arbeit zu verrichten um +ein Ziel in Einklang mit dem Quellcode zu bringen. Make wurde berühmterweise +von Stuart Feldman 1976 übers Wochenende geschrieben. Make ist noch immer +sehr verbreitet (vorallem im Unix Umfeld) obwohl es bereits sehr viel +Konkurrenz und Kritik zu Make gibt. + +Es gibt eine Vielzahl an Varianten von Make, dieser Artikel beschäftigt sich +mit der Version GNU Make. Diese Version ist Standard auf Linux. + +```make + +# Kommentare können so geschrieben werden. + +# Dateien sollten Makefile heißen, denn dann können sie als `make ` +# aufgerufen werden. Ansonsten muss `make -f "dateiname" ` verwendet +# werden. + +# Warnung - Es sollten nur TABULATOREN zur Einrückung im Makefile verwendet +# werden. Niemals Leerzeichen! + +#----------------------------------------------------------------------- +# Grundlagen +#----------------------------------------------------------------------- + +# Eine Regel - Diese Regel wird nur abgearbeitet wenn die Datei file0.txt +# nicht existiert. +file0.txt: + echo "foo" > file0.txt + # Selbst Kommentare in der 'Rezept' Sektion werden an die Shell + # weitergegeben. Versuche `make file0.txt` oder einfach `make` + # die erste Regel ist die Standard-Regel. + + +# Diese Regel wird nur abgearbeitet, wenn file0.txt aktueller als file1.txt ist. +file1.txt: file0.txt + cat file0.txt > file1.txt + # Verwende die selben Quoting-Regeln wie die Shell + @cat file0.txt >> file1.txt + # @ unterdrückt die Ausgabe des Befehls an stdout. + -@echo 'hello' + # - bedeutet, dass Make die Abarbeitung fortsetzt auch wenn Fehler + # passieren. + # Versuche `make file1.txt` auf der Kommandozeile. + +# Eine Regel kann mehrere Ziele und mehrere Voraussetzungen haben. +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make wird sich beschweren, wenn es mehrere Rezepte für die gleiche Regel gibt. +# Leere Rezepte zählen nicht und können dazu verwendet werden weitere +# Voraussetzungen hinzuzufügen. + +#----------------------------------------------------------------------- +# Phony-Ziele +#----------------------------------------------------------------------- + +# Ein Phony-Ziel ist ein Ziel, das keine Datei ist. +# Es wird nie aktuell sein, daher wird Make immer versuchen, es abzuarbeiten +all: maker process + +# Es ist erlaubt Dinge ausserhalb der Reihenfolge zu deklarieren. +maker: + touch ex0.txt ex1.txt + +# Um das Fehlschlagen von Phony-Regeln zu vermeiden wenn eine echte Datei den +# selben namen wie ein Phony-Ziel hat: +.PHONY: all maker process +# Das ist ein spezielles Ziel. Es gibt noch ein paar mehr davon. + +# Eine Regel mit einem Phony-Ziel als Voraussetzung wird immer abgearbeitet +ex0.txt ex1.txt: maker + +# Häufige Phony-Ziele sind: all make clean install ... + +#----------------------------------------------------------------------- +# Automatische Variablen & Wildcards +#----------------------------------------------------------------------- + +process: file*.txt # Eine Wildcard um Dateinamen zu vergleichen + @echo $^ # $^ ist eine Variable die eine Liste aller + # Voraussetzungen enthält. + @echo $@ # Namen des Ziels ausgeben. + #(Bei mehreren Ziel-Regeln enthält $@ den Verursacher der Abarbeitung + #der Regel.) + @echo $< # Die erste Voraussetzung aus der Liste + @echo $? # Nur die Voraussetzungen, die nicht aktuell sind. + @echo $+ # Alle Voraussetzungen inklusive Duplikate (nicht wie Üblich) + #@echo $| # Alle 'order only' Voraussetzungen + +# Selbst wenn wir die Voraussetzungen der Regel aufteilen, $^ wird sie finden. +process: ex1.txt file0.txt +# ex1.txt wird gefunden werden, aber file0.txt wird dedupliziert. + +#----------------------------------------------------------------------- +# Muster +#----------------------------------------------------------------------- + +# Mit Mustern kann man make beibringen wie Dateien in andere Dateien +# umgewandelt werden. + +%.png: %.svg + inkscape --export-png $^ + +# Muster-Vergleichs-Regeln werden nur abgearbeitet, wenn make entscheidet das +# Ziel zu erzeugen + +# Verzeichnis-Pfade werden normalerweise bei Muster-Vergleichs-Regeln ignoriert. +# Aber make wird versuchen die am besten passende Regel zu verwenden. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# Make wird die letzte Version einer Muster-Vergleichs-Regel verwenden, die es +# findet. +%.png: %.svg + @echo this rule is chosen + +# Allerdings wird make die erste Muster-Vergleicher-Regel verwenden, die das +# Ziel erzeugen kann. +%.png: %.ps + @echo this rule is not chosen if *.svg and *.ps are both present + +# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel +# weiß Make wie man aus *.c Dateien *.o Dateien erzeugt. + +# Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt +# Muster-Vergleichs-Regeln. +.png.ps: + @echo this rule is similar to a pattern rule. + +# Aktivieren der Suffix-Regel +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variablen +#----------------------------------------------------------------------- +# auch Makros genannt. + +# Variablen sind im Grunde genommen Zeichenketten-Typen. + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Das funktioniert nicht, wird als $(n)ame behandelt. + @echo $(name3) # Unbekannte Variablen werden als leere Zeichenketten behandelt. + +# Es git 4 Stellen um Variablen zu setzen. +# In Reihenfolge der Priorität von höchster zu niedrigster: +# 1: Befehls-Zeilen Argumente +# 2: Makefile +# 3: Shell Umbebungs-Variablen - Make importiert diese automatisch. +# 3: MAke hat einige vordefinierte Variablen. + +name4 ?= Jean +# Setze die Variable nur wenn es eine gleichnamige Umgebungs-Variable noch +# nicht gibt. + +override name5 = David +# Verhindert, dass Kommando-Zeilen Argumente diese Variable ändern können. + +name4 +=grey +# Werte an eine Variable anhängen (inkludiert Leerzeichen). + +# Muster-Spezifische Variablen Werte (GNU Erweiterung). +echo: name2 = Sara # Wahr innerhalb der passenden Regel und auch innerhalb + # rekursiver Voraussetzungen (ausser wenn es den Graphen zerstören + # kann, wenn es zu kompilizert wird!) + +# Ein paar Variablen, die von Make automatisch definiert werden. +echo_inbuilt: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variablen 2 +#----------------------------------------------------------------------- + +# Der erste Typ von Variablen wird bei jeder Verwendung ausgewertet. +# Das kann aufwendig sein, daher exisitert ein zweiter Typ von Variablen. +# Diese werden nur einmal ausgewertet. (Das ist eine GNU make Erweiterung) + +var := hello +var2 ::= $(var) hello +#:= und ::= sind äquivalent. + +# Diese Variablen werden prozedural ausgwertet (in der Reihenfolge in der sie +# auftauchen), die stehen daher im wiederspruch zum Rest der Sprache! + +# Das funktioniert nicht +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funktionen +#----------------------------------------------------------------------- + +# Make verfügt über eine Vielzahl von Funktionen. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# Das Format ist $(func arg0,arg1,arg2...) + +# Ein paar Beispiele +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Direktiven +#----------------------------------------------------------------------- + +# Inkludiere andere Makefile, sehr praktisch für platformspezifischen Code +include foo.mk + +sport = tennis +# Konditionale kompiliereung +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# Es gibt auch ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + + +### Mehr Resourcen + ++ [gnu make documentation](https://www.gnu.org/software/make/manual/) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) + diff --git a/docker.html.markdown b/docker.html.markdown index 17f803f4..ec6abe7e 100644 --- a/docker.html.markdown +++ b/docker.html.markdown @@ -1,281 +1,281 @@ ---- -category: tool -tool: docker -filename: docker.bat -contributors: - - ["Ruslan López", "http://javapro.org/"] - - ["Michael Chen", "https://github.com/ML-Chen"] - - ["Akshita Dixit", "https://github.com/akshitadixit"] - - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"] ---- - -Docker is a tool that helps you build, test, ship and run applications -seamlessly across various machines. It replicates the environment our software -needs on any machine. You can get Docker for your machine from -https://docs.docker.com/get-docker/ - -It has grown in popularity over the last decade due to being lightweight and -fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker -does not need a full blown OS of its own to be loaded to start and does not -compete for resources other than what the application it is running will use. -VMs on the other hand are pretty resource intensive on our processors, disks and -memory hence running multiple VMs for various applications becomes a challenge -in a limited capacity architecture. - -
    -┌────────────────────────┐ ┌───────────────────────┐
    -│      ┌───────────┐     │ │      ┌───────────┐    │
    -│      │   App     │     │ │      │   App     │    │
    -│      └───────────┘     │ │      └───────────┘    │
    -│  ┌────────┐ ┌────────┐ │ │  ┌────────┐ ┌───────┐ │
    -│  │  Libs  │ │  Deps  │ │ │  │  Libs  │ │  Deps │ │
    -│  └────────┘ └────────┘ │ │  └────────┘ └───────┘ │
    -│  ┌───────────────────┐ │ │  ┌──────────────────┐ │
    -│  │      Guest OS     │ │ │  │     Guest OS     │ │
    -│  └───────────────────┘ │ │  └──────────────────┘ │
    -│           VM1          │ │           VM2         │
    -└────────────────────────┘ └───────────────────────┘
    -┌──────────────────────────────────────────────────┐
    -│                     Hypervisor                   │
    -└──────────────────────────────────────────────────┘
    -┌──────────────────────────────────────────────────┐
    -│                      Host OS                     │
    -└──────────────────────────────────────────────────┘
    -┌──────────────────────────────────────────────────┐
    -│             Hardware Infrastructure              │
    -└──────────────────────────────────────────────────┘
    -              (VM based architecture)
    -
    -┌────────────────────────┐ ┌───────────────────────┐
    -│      ┌───────────┐     │ │      ┌───────────┐    │
    -│      │   App     │     │ │      │   App     │    │
    -│      └───────────┘     │ │      └───────────┘    │
    -│  ┌────────┐ ┌────────┐ │ │  ┌────────┐ ┌───────┐ │
    -│  │  Libs  │ │  Deps  │ │ │  │  Libs  │ │  Deps │ │
    -│  └────────┘ └────────┘ │ │  └────────┘ └───────┘ │
    -│        Container1      │ │       Container2      │
    -└────────────────────────┘ └───────────────────────┘
    -┌──────────────────────────────────────────────────┐
    -│                       Docker                     │
    -└──────────────────────────────────────────────────┘
    -┌──────────────────────────────────────────────────┐
    -│                        OS                        │
    -└──────────────────────────────────────────────────┘
    -┌──────────────────────────────────────────────────┐
    -│             Hardware Infrastructure              │
    -└──────────────────────────────────────────────────┘
    -            (Docker based architecture)
    -
    -
    - -Couple of terms we will encounter frequently are Docker Images and Docker -Containers. Images are packages or templates of containers all stored in a -container registry such as [Docker Hub](https://hub.docker.com/). Containers -are standalone, executable instances of these images which include code, -runtime, system tools, system libraries and settings - everything required to -get the software up and running. Coming to Docker, it follows a client-server -architecture wherein the CLI client communicates with the server component, -which here is, the Docker Engine using RESTful API to issue commands. - -## The Docker CLI -```bash -# after installing Docker from https://docs.docker.com/get-docker/ -# To list available commands, either run `docker` with no parameters or execute -# `docker help` -$ docker - ->>> docker [OPTIONS] COMMAND [ARG...] - docker [ --help | -v | --version ] - - A self-sufficient runtime for containers. - - Options: - --config string Location of client config files (default "/root/.docker") - -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use") - -D, --debug Enable debug mode - --help Print usage - -H, --host value Daemon socket(s) to connect to (default []) - -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") - --tls Use TLS; implied by --tlsverify - --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem") - --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") - --tlskey string Path to TLS key file (default "/root/.docker/key.pem") - --tlsverify Use TLS and verify the remote - -v, --version Print version information and quit - - Commands: - attach Attach to a running container - # […] - -$ docker run hello-world -# `docker run ` is used to run a container, it will pull the -# images from Docker Hub if they don't already exist in your system. Here the -# docker client connects to the daemon which in turn pulls the "hello-world" -# image from the Docker Hub. The daemon then builds a new container from the -# image which runs the executable that produces the output streamed back to the -# client that we see on our terminals. - -$ docker run -d ubuntu sleep 60s -# The -d (or --detach) flag is when we want to run a container in the background -# and return back to the terminal. Here we detach an ubuntu container from the -# terminal, the output should be the id and the command exits. If we check -# running containers, we should still see ours there: -# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -# 133261b4894a ubuntu "sleep 60s" 3 seconds ago Up 2 seconds vigorous_gould - -$ docker run -p 3000:8000 -# The -p (or --publish) flag is used to expose port 8000 inside the container to -# port 3000 outside the container. This is because the app inside the container -# runs in isolation, hence the port 8000 where the app runs is private to the -# container. - -$ docker run -i -# or -$ docker run -it -# Docker runs our containers in a non-interactive mode i.e. they do not accept -# inputs or work dynamically while running. The -i flag keeps input open to the -# container, and the -t flag creates a pseudo-terminal that the shell can attach -# to (can be combined as -it) - -$ docker ps -a -# The `docker ps` command only shows running containers by default. To see all -# containers, use the -a (or --all) flag -# Running the above command should output something similar in the terminal: -# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -# 82f84bf6912b hello-world "/hello" 9 minutes ago Exited (0) 9 minutes ago eloquent_sammet - - -$ docker stop hello-world -# or -$ docker start hello-world -# The stop command simply stops one or more containers, and the start command -# starts the container(s) up again! `docker start -a ubuntu` will attach our -# detached container back to the terminal i.e. runs in the foreground - -$ docker create alpine -# `docker create` creates a new container for us with the image specified (here, -# alpine), the container does not auto-start unlike `docker run`. This command -# is used to set up a container configuration and then `docker start` to shoot -# it up when required. Note that the status is "Created": -# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES -# 4c71c727c73d alpine "/bin/sh" 29 seconds ago Created naughty_ritchie - -$ docker rm 82f84 -# Removes one or more containers using their container ID. -# P.S.: we can use only the first few characters of the entire ID to identify -# containers - -$ docker images -# Displays all images and their information, created here means the latest image -# tag updated on Docker Hub: -# REPOSITORY TAG IMAGE ID CREATED SIZE -# ubuntu latest a8780b506fa4 9 days ago 77.8MB -# alpine latest 9c6f07244728 3 months ago 5.54MB -# hello-world latest feb5d9fea6a5 13 months ago 13.3kB - -$ docker rmi -# Removes one or more images from your system which do not have their instances -# (or containers as we know them) running. If the image has an attached -# container, either delete the container first or use the -f (or --force) flag -# to forcefully delete both the container and image. - -$ docker pull busybox -# The pull command downloads the specified image on our system from Docker Hub. - -$ docker exec -it 7b272 bash -# This command is used to run a command in the running container's default -# directory. Here 7b272 was our ubuntu container and the above command would -# help us interact with the container by opening a bash session. - -$ docker logs -# Displays the information logged by the specified container -# root@7b27222e4bb7:/# whoami -# root -# root@7b27222e4bb7:/# pwd -# / -# root@7b27222e4bb7:/# ls -# bin boot dev etc home lib lib32 lib64 libx3 srv sys tmp usr var -# root@7b27222e4bb7:/# exit -# exit - -# More commands can be found at https://docs.docker.com/engine/reference/commandline/docker/ -``` -## The Dockerfile -The Dockerfile is a blueprint of a Docker image. We can mention the artifacts -from our application along with their configurations into this file in the -specific syntax to let anyone create a Docker image of our application. - -### A few things to keep in mind: -* It is always strictly named `Dockerfile` without any extensions -* We have to build our custom image on top of some already available Docker base -image. (there is an empty image called `scratch` which literally lets you build -an image from scratch) -* All capitalised commands are part of the syntax, they are not case-sensitive -but used like a convention -* Below is a sample Dockerfile but you can read in depth from the [official docs](https://docs.docker.com/engine/reference/builder/). - -```Dockerfile -FROM -# define base image - -ENV USERNAME='admin'\ - PWD='****' -# optionally define environmental variables - -RUN apt-get update -# run linux commands inside container env, does not affect host env -# This executes during the time of image creation - -COPY -# executes on the host, copies files from src (usually on the host) to target -# on the container - -ENTRYPOINT ["some-script.sh"] -# executes an entire script as an entrypoint - -CMD [,...] -# always part of dockerfile, introduces entry point linux command e.g. -# `CMD node server.js` -# This executes after image creation only when the container from the image -# is running. -``` -### Build your images -Use the `docker build` command after wrapping your application into a Docker -image to run ( or build) it. - -```bash - -$ docker build -# used to build an image from the specified Dockerfile -# instead of path we could also specify a URL -# -t tag is optional and used to name and tag your images for e.g. -# `$ docker build -t my-image:0.1 ./home/app` -# rebuild images everytime you make changes in the dockerfile -``` - -## Push your image to DockerHub -If you want your application's Docker image to be made publicly available for -any Docker user, you might wanna push it to the [Docker Hub](https://hub.docker.com/) which is a -registry of Docker images. Make sure you have an account with a username and -password on Docker Hub. - -When pushing an image to Docker Hub, we must specify our Docker Hub username -as part of the source image name. We need to create the target image with the -tag name of username/image-name much like GitHub repositories. - -```bash -$ docker login -# to login to Docker Hub using your username and password - -$ docker tag [:] [:] -# this tags a local src-image to a public target-image -# e.g. `docker tag my-sample-app:1.0.0 akshitadixit/my-sample-app` -# if tags are not specified, they're defaulted to `latest` - -$ docker push [:] -# uploads our image to Docker Hub -# e.g. `docker push akshitadixit/my-sample-app` -# this image will be accessible under your profile's repositories as -# `https://hub.docker.com/r/username/image-name` - -``` +--- +category: tool +tool: docker +filename: docker.bat +contributors: + - ["Ruslan López", "http://javapro.org/"] + - ["Michael Chen", "https://github.com/ML-Chen"] + - ["Akshita Dixit", "https://github.com/akshitadixit"] + - ["Marcel Ribeiro-Dantas", "https://github.com/mribeirodantas"] +--- + +Docker is a tool that helps you build, test, ship and run applications +seamlessly across various machines. It replicates the environment our software +needs on any machine. You can get Docker for your machine from +https://docs.docker.com/get-docker/ + +It has grown in popularity over the last decade due to being lightweight and +fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker +does not need a full blown OS of its own to be loaded to start and does not +compete for resources other than what the application it is running will use. +VMs on the other hand are pretty resource intensive on our processors, disks and +memory hence running multiple VMs for various applications becomes a challenge +in a limited capacity architecture. + +
    +┌────────────────────────┐ ┌───────────────────────┐
    +│      ┌───────────┐     │ │      ┌───────────┐    │
    +│      │   App     │     │ │      │   App     │    │
    +│      └───────────┘     │ │      └───────────┘    │
    +│  ┌────────┐ ┌────────┐ │ │  ┌────────┐ ┌───────┐ │
    +│  │  Libs  │ │  Deps  │ │ │  │  Libs  │ │  Deps │ │
    +│  └────────┘ └────────┘ │ │  └────────┘ └───────┘ │
    +│  ┌───────────────────┐ │ │  ┌──────────────────┐ │
    +│  │      Guest OS     │ │ │  │     Guest OS     │ │
    +│  └───────────────────┘ │ │  └──────────────────┘ │
    +│           VM1          │ │           VM2         │
    +└────────────────────────┘ └───────────────────────┘
    +┌──────────────────────────────────────────────────┐
    +│                     Hypervisor                   │
    +└──────────────────────────────────────────────────┘
    +┌──────────────────────────────────────────────────┐
    +│                      Host OS                     │
    +└──────────────────────────────────────────────────┘
    +┌──────────────────────────────────────────────────┐
    +│             Hardware Infrastructure              │
    +└──────────────────────────────────────────────────┘
    +              (VM based architecture)
    +
    +┌────────────────────────┐ ┌───────────────────────┐
    +│      ┌───────────┐     │ │      ┌───────────┐    │
    +│      │   App     │     │ │      │   App     │    │
    +│      └───────────┘     │ │      └───────────┘    │
    +│  ┌────────┐ ┌────────┐ │ │  ┌────────┐ ┌───────┐ │
    +│  │  Libs  │ │  Deps  │ │ │  │  Libs  │ │  Deps │ │
    +│  └────────┘ └────────┘ │ │  └────────┘ └───────┘ │
    +│        Container1      │ │       Container2      │
    +└────────────────────────┘ └───────────────────────┘
    +┌──────────────────────────────────────────────────┐
    +│                       Docker                     │
    +└──────────────────────────────────────────────────┘
    +┌──────────────────────────────────────────────────┐
    +│                        OS                        │
    +└──────────────────────────────────────────────────┘
    +┌──────────────────────────────────────────────────┐
    +│             Hardware Infrastructure              │
    +└──────────────────────────────────────────────────┘
    +            (Docker based architecture)
    +
    +
    + +Couple of terms we will encounter frequently are Docker Images and Docker +Containers. Images are packages or templates of containers all stored in a +container registry such as [Docker Hub](https://hub.docker.com/). Containers +are standalone, executable instances of these images which include code, +runtime, system tools, system libraries and settings - everything required to +get the software up and running. Coming to Docker, it follows a client-server +architecture wherein the CLI client communicates with the server component, +which here is, the Docker Engine using RESTful API to issue commands. + +## The Docker CLI +```bash +# after installing Docker from https://docs.docker.com/get-docker/ +# To list available commands, either run `docker` with no parameters or execute +# `docker help` +$ docker + +>>> docker [OPTIONS] COMMAND [ARG...] + docker [ --help | -v | --version ] + + A self-sufficient runtime for containers. + + Options: + --config string Location of client config files (default "/root/.docker") + -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use") + -D, --debug Enable debug mode + --help Print usage + -H, --host value Daemon socket(s) to connect to (default []) + -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") + --tls Use TLS; implied by --tlsverify + --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem") + --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") + --tlskey string Path to TLS key file (default "/root/.docker/key.pem") + --tlsverify Use TLS and verify the remote + -v, --version Print version information and quit + + Commands: + attach Attach to a running container + # […] + +$ docker run hello-world +# `docker run ` is used to run a container, it will pull the +# images from Docker Hub if they don't already exist in your system. Here the +# docker client connects to the daemon which in turn pulls the "hello-world" +# image from the Docker Hub. The daemon then builds a new container from the +# image which runs the executable that produces the output streamed back to the +# client that we see on our terminals. + +$ docker run -d ubuntu sleep 60s +# The -d (or --detach) flag is when we want to run a container in the background +# and return back to the terminal. Here we detach an ubuntu container from the +# terminal, the output should be the id and the command exits. If we check +# running containers, we should still see ours there: +# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +# 133261b4894a ubuntu "sleep 60s" 3 seconds ago Up 2 seconds vigorous_gould + +$ docker run -p 3000:8000 +# The -p (or --publish) flag is used to expose port 8000 inside the container to +# port 3000 outside the container. This is because the app inside the container +# runs in isolation, hence the port 8000 where the app runs is private to the +# container. + +$ docker run -i +# or +$ docker run -it +# Docker runs our containers in a non-interactive mode i.e. they do not accept +# inputs or work dynamically while running. The -i flag keeps input open to the +# container, and the -t flag creates a pseudo-terminal that the shell can attach +# to (can be combined as -it) + +$ docker ps -a +# The `docker ps` command only shows running containers by default. To see all +# containers, use the -a (or --all) flag +# Running the above command should output something similar in the terminal: +# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +# 82f84bf6912b hello-world "/hello" 9 minutes ago Exited (0) 9 minutes ago eloquent_sammet + + +$ docker stop hello-world +# or +$ docker start hello-world +# The stop command simply stops one or more containers, and the start command +# starts the container(s) up again! `docker start -a ubuntu` will attach our +# detached container back to the terminal i.e. runs in the foreground + +$ docker create alpine +# `docker create` creates a new container for us with the image specified (here, +# alpine), the container does not auto-start unlike `docker run`. This command +# is used to set up a container configuration and then `docker start` to shoot +# it up when required. Note that the status is "Created": +# CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES +# 4c71c727c73d alpine "/bin/sh" 29 seconds ago Created naughty_ritchie + +$ docker rm 82f84 +# Removes one or more containers using their container ID. +# P.S.: we can use only the first few characters of the entire ID to identify +# containers + +$ docker images +# Displays all images and their information, created here means the latest image +# tag updated on Docker Hub: +# REPOSITORY TAG IMAGE ID CREATED SIZE +# ubuntu latest a8780b506fa4 9 days ago 77.8MB +# alpine latest 9c6f07244728 3 months ago 5.54MB +# hello-world latest feb5d9fea6a5 13 months ago 13.3kB + +$ docker rmi +# Removes one or more images from your system which do not have their instances +# (or containers as we know them) running. If the image has an attached +# container, either delete the container first or use the -f (or --force) flag +# to forcefully delete both the container and image. + +$ docker pull busybox +# The pull command downloads the specified image on our system from Docker Hub. + +$ docker exec -it 7b272 bash +# This command is used to run a command in the running container's default +# directory. Here 7b272 was our ubuntu container and the above command would +# help us interact with the container by opening a bash session. + +$ docker logs +# Displays the information logged by the specified container +# root@7b27222e4bb7:/# whoami +# root +# root@7b27222e4bb7:/# pwd +# / +# root@7b27222e4bb7:/# ls +# bin boot dev etc home lib lib32 lib64 libx3 srv sys tmp usr var +# root@7b27222e4bb7:/# exit +# exit + +# More commands can be found at https://docs.docker.com/engine/reference/commandline/docker/ +``` +## The Dockerfile +The Dockerfile is a blueprint of a Docker image. We can mention the artifacts +from our application along with their configurations into this file in the +specific syntax to let anyone create a Docker image of our application. + +### A few things to keep in mind: +* It is always strictly named `Dockerfile` without any extensions +* We have to build our custom image on top of some already available Docker base +image. (there is an empty image called `scratch` which literally lets you build +an image from scratch) +* All capitalised commands are part of the syntax, they are not case-sensitive +but used like a convention +* Below is a sample Dockerfile but you can read in depth from the [official docs](https://docs.docker.com/engine/reference/builder/). + +```Dockerfile +FROM +# define base image + +ENV USERNAME='admin'\ + PWD='****' +# optionally define environmental variables + +RUN apt-get update +# run linux commands inside container env, does not affect host env +# This executes during the time of image creation + +COPY +# executes on the host, copies files from src (usually on the host) to target +# on the container + +ENTRYPOINT ["some-script.sh"] +# executes an entire script as an entrypoint + +CMD [,...] +# always part of dockerfile, introduces entry point linux command e.g. +# `CMD node server.js` +# This executes after image creation only when the container from the image +# is running. +``` +### Build your images +Use the `docker build` command after wrapping your application into a Docker +image to run ( or build) it. + +```bash + +$ docker build +# used to build an image from the specified Dockerfile +# instead of path we could also specify a URL +# -t tag is optional and used to name and tag your images for e.g. +# `$ docker build -t my-image:0.1 ./home/app` +# rebuild images everytime you make changes in the dockerfile +``` + +## Push your image to DockerHub +If you want your application's Docker image to be made publicly available for +any Docker user, you might wanna push it to the [Docker Hub](https://hub.docker.com/) which is a +registry of Docker images. Make sure you have an account with a username and +password on Docker Hub. + +When pushing an image to Docker Hub, we must specify our Docker Hub username +as part of the source image name. We need to create the target image with the +tag name of username/image-name much like GitHub repositories. + +```bash +$ docker login +# to login to Docker Hub using your username and password + +$ docker tag [:] [:] +# this tags a local src-image to a public target-image +# e.g. `docker tag my-sample-app:1.0.0 akshitadixit/my-sample-app` +# if tags are not specified, they're defaulted to `latest` + +$ docker push [:] +# uploads our image to Docker Hub +# e.g. `docker push akshitadixit/my-sample-app` +# this image will be accessible under your profile's repositories as +# `https://hub.docker.com/r/username/image-name` + +``` diff --git a/es-es/docker-es.html.markdown b/es-es/docker-es.html.markdown index 93e17f02..81e3cefe 100644 --- a/es-es/docker-es.html.markdown +++ b/es-es/docker-es.html.markdown @@ -1,167 +1,167 @@ ---- -language: docker -filename: docker-es.bat -contributors: - - ["Ruslan López", "http://javapro.org/"] - - ["Michael Chen", "https://github.com/ML-Chen"] -lang: es-es ---- - -```bat -:: descargar, instalar y ejecutar la imágen del hola mundo -docker run hello-world - -:: Si esta es la primera vez, deberíais de poder ver el mensaje -:: Unable to find image 'hello-world:latest' locally -:: latest: Pulling from library/hello-world -:: 1b930d010525: Pull complete -:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064 -:: Status: Downloaded newer image for hello-world:latest -:: -:: Hello from Docker! -:: This message shows that your installation appears to be working correctly. -:: -:: To generate this message, Docker took the following steps: -:: 1. The Docker client contacted the Docker daemon. -:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. -:: (amd64) -:: 3. The Docker daemon created a new container from that image which runs the -:: executable that produces the output you are currently reading. -:: 4. The Docker daemon streamed that output to the Docker client, which sent it -:: to your terminal. -:: -:: To try something more ambitious, you can run an Ubuntu container with: -:: $ docker run -it ubuntu bash -:: -:: Share images, automate workflows, and more with a free Docker ID: -:: https://hub.docker.com/ -:: -:: For more examples and ideas, visit: -:: https://docs.docker.com/get-started/ -:: El susodicho mensaje se podría traducir como: -:: -:: Hola desde Docker! -:: Este mensaje muestra que su instalación parece estar funcionando crrectamente. -:: -:: Para generar este mensaje, Docker realizó los siguientes pasos: -:: 1. El cliente de Docker contactó a Docker daemon. -:: 2. El Docker daemon obtubo la imágen "hello-world" desde Docker Hub. -:: (amd64) -:: 3. El Docker daemon creó un nuevo contenedor a partir de esa imagen con la cual ejecuta el -:: ejecutable que produce la salida que estás leyendo. -:: 4. El Docker daemon transmitió dicha salida el cliente Docker, el cual -:: la envió a tu terminal. -:: -:: Para intentar algo más ambicioso, puede correr un contenedor Ubuntu mediante: -:: $ docker run -it ubuntu bash -:: -:: Comparte imágenes, automatice flujos y más con un Docker ID gratuito: -:: https://hub.docker.com/ - -:: ahora veamos las imágenes que se están ejecutando actualmente -docker ps -:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS -:: NAMES - -:: veamos las imágenes que hemos ejecutado previamente -docker ps -a - -:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS -:: NAMES -:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago -:: happy_poincare -:: la parte del nombre se genera automáticamente, así que probablemente sea diferente para vos - -:: eliminemos nuestra imagen previamente generada -docker rm happy_poincare - -:: verifiquemos si realmente fue borrada -docker ps -a -:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS -:: NAMES - -:: especifiquemos un nombre personalizado para el contenedor -docker run --name test_container hello-world -:: Hello from Docker! -:: This message shows that your installation appears to be working correctly. -:: -:: To generate this message, Docker took the following steps: -:: 1. The Docker client contacted the Docker daemon. -:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. -:: (amd64) -:: 3. The Docker daemon created a new container from that image which runs the -:: executable that produces the output you are currently reading. -:: 4. The Docker daemon streamed that output to the Docker client, which sent it -:: to your terminal. -:: -:: To try something more ambitious, you can run an Ubuntu container with: -:: $ docker run -it ubuntu bash -:: -:: Share images, automate workflows, and more with a free Docker ID: -:: https://hub.docker.com/ -:: -:: For more examples and ideas, visit: -:: https://docs.docker.com/get-started/ - -docker ps -a -:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS -:: NAMES -:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago -:: test_container -:: tal como podeis ver el nombre es el que especificamos - -:: obtener los registros de un contenedor nombrado -docker logs test_container -:: Hello from Docker! -:: This message shows that your installation appears to be working correctly. -:: -:: To generate this message, Docker took the following steps: -:: 1. The Docker client contacted the Docker daemon. -:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. -:: (amd64) -:: 3. The Docker daemon created a new container from that image which runs the -:: executable that produces the output you are currently reading. -:: 4. The Docker daemon streamed that output to the Docker client, which sent it -:: to your terminal. -:: -:: To try something more ambitious, you can run an Ubuntu container with: -:: $ docker run -it ubuntu bash -:: -:: Share images, automate workflows, and more with a free Docker ID: -:: https://hub.docker.com/ -:: -:: For more examples and ideas, visit: -:: https://docs.docker.com/get-started/ - -docker rm test_container - -docker run ubuntu -:: Unable to find image 'ubuntu:latest' locally -:: latest: Pulling from library/ubuntu -:: 2746a4a261c9: Pull complete -:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4 -:: Status: Downloaded newer image for ubuntu:latest - -docker ps -a -:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS -:: NAMES -:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago -:: relaxed_nobel - -:: ejecutando un contenedor en modo interactivo -docker run -it ubuntu -:: root@e2cac48323d2:/# uname -:: Linux -:: root@e2cac48323d2:/# exit -:: exit - -docker rm relaxed_nobel - -docker ps -a -:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS -:: NAMES -:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago -:: nifty_goldwasser - -docker rm nifty_goldwasser -``` +--- +language: docker +filename: docker-es.bat +contributors: + - ["Ruslan López", "http://javapro.org/"] + - ["Michael Chen", "https://github.com/ML-Chen"] +lang: es-es +--- + +```bat +:: descargar, instalar y ejecutar la imágen del hola mundo +docker run hello-world + +:: Si esta es la primera vez, deberíais de poder ver el mensaje +:: Unable to find image 'hello-world:latest' locally +:: latest: Pulling from library/hello-world +:: 1b930d010525: Pull complete +:: Digest: sha256:4fe721ccc2e8dc7362278a29dc660d833570ec2682f4e4194f4ee23e415e1064 +:: Status: Downloaded newer image for hello-world:latest +:: +:: Hello from Docker! +:: This message shows that your installation appears to be working correctly. +:: +:: To generate this message, Docker took the following steps: +:: 1. The Docker client contacted the Docker daemon. +:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. +:: (amd64) +:: 3. The Docker daemon created a new container from that image which runs the +:: executable that produces the output you are currently reading. +:: 4. The Docker daemon streamed that output to the Docker client, which sent it +:: to your terminal. +:: +:: To try something more ambitious, you can run an Ubuntu container with: +:: $ docker run -it ubuntu bash +:: +:: Share images, automate workflows, and more with a free Docker ID: +:: https://hub.docker.com/ +:: +:: For more examples and ideas, visit: +:: https://docs.docker.com/get-started/ +:: El susodicho mensaje se podría traducir como: +:: +:: Hola desde Docker! +:: Este mensaje muestra que su instalación parece estar funcionando crrectamente. +:: +:: Para generar este mensaje, Docker realizó los siguientes pasos: +:: 1. El cliente de Docker contactó a Docker daemon. +:: 2. El Docker daemon obtubo la imágen "hello-world" desde Docker Hub. +:: (amd64) +:: 3. El Docker daemon creó un nuevo contenedor a partir de esa imagen con la cual ejecuta el +:: ejecutable que produce la salida que estás leyendo. +:: 4. El Docker daemon transmitió dicha salida el cliente Docker, el cual +:: la envió a tu terminal. +:: +:: Para intentar algo más ambicioso, puede correr un contenedor Ubuntu mediante: +:: $ docker run -it ubuntu bash +:: +:: Comparte imágenes, automatice flujos y más con un Docker ID gratuito: +:: https://hub.docker.com/ + +:: ahora veamos las imágenes que se están ejecutando actualmente +docker ps +:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS +:: NAMES + +:: veamos las imágenes que hemos ejecutado previamente +docker ps -a + +:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS +:: NAMES +:: 4a76281f9c53 hello-world "/hello" 2 minutes ago Exited (0) 2 minutes ago +:: happy_poincare +:: la parte del nombre se genera automáticamente, así que probablemente sea diferente para vos + +:: eliminemos nuestra imagen previamente generada +docker rm happy_poincare + +:: verifiquemos si realmente fue borrada +docker ps -a +:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS +:: NAMES + +:: especifiquemos un nombre personalizado para el contenedor +docker run --name test_container hello-world +:: Hello from Docker! +:: This message shows that your installation appears to be working correctly. +:: +:: To generate this message, Docker took the following steps: +:: 1. The Docker client contacted the Docker daemon. +:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. +:: (amd64) +:: 3. The Docker daemon created a new container from that image which runs the +:: executable that produces the output you are currently reading. +:: 4. The Docker daemon streamed that output to the Docker client, which sent it +:: to your terminal. +:: +:: To try something more ambitious, you can run an Ubuntu container with: +:: $ docker run -it ubuntu bash +:: +:: Share images, automate workflows, and more with a free Docker ID: +:: https://hub.docker.com/ +:: +:: For more examples and ideas, visit: +:: https://docs.docker.com/get-started/ + +docker ps -a +:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS +:: NAMES +:: d345fe1a4f41 hello-world "/hello" About a minute ago Exited (0) About a minute ago +:: test_container +:: tal como podeis ver el nombre es el que especificamos + +:: obtener los registros de un contenedor nombrado +docker logs test_container +:: Hello from Docker! +:: This message shows that your installation appears to be working correctly. +:: +:: To generate this message, Docker took the following steps: +:: 1. The Docker client contacted the Docker daemon. +:: 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. +:: (amd64) +:: 3. The Docker daemon created a new container from that image which runs the +:: executable that produces the output you are currently reading. +:: 4. The Docker daemon streamed that output to the Docker client, which sent it +:: to your terminal. +:: +:: To try something more ambitious, you can run an Ubuntu container with: +:: $ docker run -it ubuntu bash +:: +:: Share images, automate workflows, and more with a free Docker ID: +:: https://hub.docker.com/ +:: +:: For more examples and ideas, visit: +:: https://docs.docker.com/get-started/ + +docker rm test_container + +docker run ubuntu +:: Unable to find image 'ubuntu:latest' locally +:: latest: Pulling from library/ubuntu +:: 2746a4a261c9: Pull complete +:: 4c1d20cdee96: Pull complete 0d3160e1d0de: Pull complete c8e37668deea: Pull complete Digest: sha256:250cc6f3f3ffc5cdaa9d8f4946ac79821aafb4d3afc93928f0de9336eba21aa4 +:: Status: Downloaded newer image for ubuntu:latest + +docker ps -a +:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS +:: NAMES +:: c19e9e5b000a ubuntu "/bin/bash" 5 seconds ago Exited (0) 4 seconds ago +:: relaxed_nobel + +:: ejecutando un contenedor en modo interactivo +docker run -it ubuntu +:: root@e2cac48323d2:/# uname +:: Linux +:: root@e2cac48323d2:/# exit +:: exit + +docker rm relaxed_nobel + +docker ps -a +:: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS +:: NAMES +:: e2cac48323d2 ubuntu "/bin/bash" 2 minutes ago Exited (0) About a minute ago +:: nifty_goldwasser + +docker rm nifty_goldwasser +``` diff --git a/it-it/toml-it.html.markdown b/it-it/toml-it.html.markdown index 99082048..beb63096 100644 --- a/it-it/toml-it.html.markdown +++ b/it-it/toml-it.html.markdown @@ -1,276 +1,276 @@ ---- -language: toml -filename: learntoml-it.toml -contributors: - - ["Alois de Gouvello", "https://github.com/aloisdg"] -translators: - - ["Christian Grasso", "https://grasso.io"] -lang: it-it ---- - -TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la -serializzazione di dati, progettato per i file di configurazione. - -È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile -per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza -semplice nella maggior parte dei linguaggi di programmazione, in quanto è -progettato per essere tradotto senza ambiguità in una hash table. - -Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è -ancora stabile. Questo documento utilizza TOML 0.4.0. - -```toml -# I commenti in TOML sono fatti così. - -################ -# TIPI SCALARI # -################ - -# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa, -# anche chiamata dizionario, hash o oggetto in altri linguaggi. - -# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga, -# eccetto per alcuni tipi di valori. -key = "value" -stringa = "ciao" -numero = 42 -float = 3.14 -boolean = true -data = 1979-05-27T07:32:00-08:00 -notazScientifica = 1e+12 -"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure ' -"la key può contenere" = "lettere, numeri, underscore e trattini" - -############ -# Stringhe # -############ - -# Le stringhe possono contenere solo caratteri UTF-8 validi. -# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze -# di escape compatte. Ad esempio, \t corrisponde al TAB. -stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"." - -stringaMultiriga = """ -Racchiusa da tre virgolette doppie all'inizio e -alla fine - consente di andare a capo.""" - -stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.' - -stringaMultirigaLiteral = ''' -Racchiusa da tre virgolette singole all'inizio e -alla fine - consente di andare a capo. -Anche in questo caso non si può fare escape. -Il primo ritorno a capo viene eliminato. - Tutti gli altri spazi aggiuntivi - vengono mantenuti. -''' - -# Per i dati binari è consigliabile utilizzare Base64 e -# gestirli manualmente dall'applicazione. - -########## -# Interi # -########## - -## Gli interi possono avere o meno un segno (+, -). -## Non si possono inserire zero superflui all'inizio. -## Non è possibile inoltre utilizzare valori numerici -## non rappresentabili con una sequenza di cifre. -int1 = +42 -int2 = 0 -int3 = -21 - -## Puoi utilizzare gli underscore per migliorare la leggibilità. -## Fai attenzione a non inserirne due di seguito. -int4 = 5_349_221 -int5 = 1_2_3_4_5 # VALIDO, ma da evitare - -######### -# Float # -######### - -# I float permettono di rappresentare numeri decimali. -flt1 = 3.1415 -flt2 = -5e6 -flt3 = 6.626E-34 - -########### -# Boolean # -########### - -# I valori boolean (true/false) devono essere scritti in minuscolo. -bool1 = true -bool2 = false - -############ -# Data/ora # -############ - -data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC) -data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset - -###################### -# TIPI DI COLLECTION # -###################### - -######### -# Array # -######### - -array1 = [ 1, 2, 3 ] -array2 = [ "Le", "virgole", "sono", "delimitatori" ] -array3 = [ "Non", "unire", "tipi", "diversi" ] -array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ] -array5 = [ - "Gli spazi vuoti", "sono", "ignorati" -] - -########### -# Tabelle # -########### - -# Le tabelle (o hash table o dizionari) sono collection di coppie key/value. -# Iniziano con un nome tra parentesi quadre su una linea separata. -# Le tabelle vuote (senza alcun valore) sono valide. -[tabella] - -# Tutti i valori che si trovano sotto il nome della tabella -# appartengono alla tabella stessa (finchè non ne viene creata un'altra). -# L'ordine di questi valori non è garantito. -[tabella-1] -key1 = "una stringa" -key2 = 123 - -[tabella-2] -key1 = "un'altra stringa" -key2 = 456 - -# Utilizzando i punti è possibile creare delle sottotabelle. -# Ogni parte suddivisa dai punti segue le regole delle key per il nome. -[tabella-3."sotto.tabella"] -key1 = "prova" - -# Ecco l'equivalente JSON della tabella precedente: -# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } } - -# Gli spazi non vengono considerati, ma è consigliabile -# evitare di usare spazi superflui. -[a.b.c] # consigliato -[ d.e.f ] # identico a [d.e.f] - -# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella. -# [x] queste -# [x.y] non -# [x.y.z] servono -[x.y.z.w] # per creare questa tabella - -# Se non è stata già creata prima, puoi anche creare -# una tabella superiore più avanti. -[a.b] -c = 1 - -[a] -d = 2 - -# Non puoi definire una key o una tabella più di una volta. - -# ERRORE -[a] -b = 1 - -[a] -c = 2 - -# ERRORE -[a] -b = 1 - -[a.b] -c = 2 - -# I nomi delle tabelle non possono essere vuoti. -[] # NON VALIDO -[a.] # NON VALIDO -[a..b] # NON VALIDO -[.b] # NON VALIDO -[.] # NON VALIDO - -################## -# Tabelle inline # -################## - -tabelleInline = { racchiuseData = "{ e }", rigaSingola = true } -punto = { x = 1, y = 2 } - -#################### -# Array di tabelle # -#################### - -# Un array di tabelle può essere creato utilizzando due parentesi quadre. -# Tutte le tabelle con questo nome saranno elementi dell'array. -# Gli elementi vengono inseriti nell'ordine in cui si trovano. - -[[prodotti]] -nome = "array di tabelle" -sku = 738594937 -tabelleVuoteValide = true - -[[prodotti]] - -[[prodotti]] -nome = "un altro item" -sku = 284758393 -colore = "grigio" - -# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie -# parentesi quadre apparterranno alla tabella più vicina sopra di esse. - -[[frutta]] - nome = "mela" - - [frutto.geometria] - forma = "sferica" - nota = "Sono una proprietà del frutto" - - [[frutto.colore]] - nome = "rosso" - nota = "Sono un oggetto di un array dentro mela" - - [[frutto.colore]] - nome = "verde" - nota = "Sono nello stesso array di rosso" - -[[frutta]] - nome = "banana" - - [[frutto.colore]] - nome = "giallo" - nota = "Anche io sono un oggetto di un array, ma dentro banana" -``` - -Ecco l'equivalente JSON dell'ultima tabella: - -```json -{ - "frutta": [ - { - "nome": "mela", - "geometria": { "forma": "sferica", "nota": "..."}, - "colore": [ - { "nome": "rosso", "nota": "..." }, - { "nome": "verde", "nota": "..." } - ] - }, - { - "nome": "banana", - "colore": [ - { "nome": "giallo", "nota": "..." } - ] - } - ] -} -``` - -### Altre risorse - -+ [Repository ufficiale di TOML](https://github.com/toml-lang/toml) +--- +language: toml +filename: learntoml-it.toml +contributors: + - ["Alois de Gouvello", "https://github.com/aloisdg"] +translators: + - ["Christian Grasso", "https://grasso.io"] +lang: it-it +--- + +TOML è l'acronimo di _Tom's Obvious, Minimal Language_. È un linguaggio per la +serializzazione di dati, progettato per i file di configurazione. + +È un'alternativa a linguaggi come YAML e JSON, che punta ad essere più leggibile +per le persone. Allo stesso tempo, TOML può essere utilizzato in modo abbastanza +semplice nella maggior parte dei linguaggi di programmazione, in quanto è +progettato per essere tradotto senza ambiguità in una hash table. + +Tieni presente che TOML è ancora in fase di sviluppo, e la sua specifica non è +ancora stabile. Questo documento utilizza TOML 0.4.0. + +```toml +# I commenti in TOML sono fatti così. + +################ +# TIPI SCALARI # +################ + +# Il nostro oggetto root (corrispondente all'intero documento) sarà una mappa, +# anche chiamata dizionario, hash o oggetto in altri linguaggi. + +# La key, il simbolo di uguale e il valore devono trovarsi sulla stessa riga, +# eccetto per alcuni tipi di valori. +key = "value" +stringa = "ciao" +numero = 42 +float = 3.14 +boolean = true +data = 1979-05-27T07:32:00-08:00 +notazScientifica = 1e+12 +"puoi utilizzare le virgolette per la key" = true # Puoi usare " oppure ' +"la key può contenere" = "lettere, numeri, underscore e trattini" + +############ +# Stringhe # +############ + +# Le stringhe possono contenere solo caratteri UTF-8 validi. +# Possiamo effettuare l'escape dei caratteri, e alcuni hanno delle sequenze +# di escape compatte. Ad esempio, \t corrisponde al TAB. +stringaSemplice = "Racchiusa tra virgolette. \"Usa il backslash per l'escape\"." + +stringaMultiriga = """ +Racchiusa da tre virgolette doppie all'inizio e +alla fine - consente di andare a capo.""" + +stringaLiteral = 'Virgolette singole. Non consente di effettuare escape.' + +stringaMultirigaLiteral = ''' +Racchiusa da tre virgolette singole all'inizio e +alla fine - consente di andare a capo. +Anche in questo caso non si può fare escape. +Il primo ritorno a capo viene eliminato. + Tutti gli altri spazi aggiuntivi + vengono mantenuti. +''' + +# Per i dati binari è consigliabile utilizzare Base64 e +# gestirli manualmente dall'applicazione. + +########## +# Interi # +########## + +## Gli interi possono avere o meno un segno (+, -). +## Non si possono inserire zero superflui all'inizio. +## Non è possibile inoltre utilizzare valori numerici +## non rappresentabili con una sequenza di cifre. +int1 = +42 +int2 = 0 +int3 = -21 + +## Puoi utilizzare gli underscore per migliorare la leggibilità. +## Fai attenzione a non inserirne due di seguito. +int4 = 5_349_221 +int5 = 1_2_3_4_5 # VALIDO, ma da evitare + +######### +# Float # +######### + +# I float permettono di rappresentare numeri decimali. +flt1 = 3.1415 +flt2 = -5e6 +flt3 = 6.626E-34 + +########### +# Boolean # +########### + +# I valori boolean (true/false) devono essere scritti in minuscolo. +bool1 = true +bool2 = false + +############ +# Data/ora # +############ + +data1 = 1979-05-27T07:32:00Z # Specifica RFC 3339/ISO 8601 (UTC) +data2 = 1979-05-26T15:32:00+08:00 # RFC 3339/ISO 8601 con offset + +###################### +# TIPI DI COLLECTION # +###################### + +######### +# Array # +######### + +array1 = [ 1, 2, 3 ] +array2 = [ "Le", "virgole", "sono", "delimitatori" ] +array3 = [ "Non", "unire", "tipi", "diversi" ] +array4 = [ "tutte", 'le stringhe', """hanno lo stesso""", '''tipo''' ] +array5 = [ + "Gli spazi vuoti", "sono", "ignorati" +] + +########### +# Tabelle # +########### + +# Le tabelle (o hash table o dizionari) sono collection di coppie key/value. +# Iniziano con un nome tra parentesi quadre su una linea separata. +# Le tabelle vuote (senza alcun valore) sono valide. +[tabella] + +# Tutti i valori che si trovano sotto il nome della tabella +# appartengono alla tabella stessa (finchè non ne viene creata un'altra). +# L'ordine di questi valori non è garantito. +[tabella-1] +key1 = "una stringa" +key2 = 123 + +[tabella-2] +key1 = "un'altra stringa" +key2 = 456 + +# Utilizzando i punti è possibile creare delle sottotabelle. +# Ogni parte suddivisa dai punti segue le regole delle key per il nome. +[tabella-3."sotto.tabella"] +key1 = "prova" + +# Ecco l'equivalente JSON della tabella precedente: +# { "tabella-3": { "sotto.tabella": { "key1": "prova" } } } + +# Gli spazi non vengono considerati, ma è consigliabile +# evitare di usare spazi superflui. +[a.b.c] # consigliato +[ d.e.f ] # identico a [d.e.f] + +# Non c'è bisogno di creare le tabelle superiori per creare una sottotabella. +# [x] queste +# [x.y] non +# [x.y.z] servono +[x.y.z.w] # per creare questa tabella + +# Se non è stata già creata prima, puoi anche creare +# una tabella superiore più avanti. +[a.b] +c = 1 + +[a] +d = 2 + +# Non puoi definire una key o una tabella più di una volta. + +# ERRORE +[a] +b = 1 + +[a] +c = 2 + +# ERRORE +[a] +b = 1 + +[a.b] +c = 2 + +# I nomi delle tabelle non possono essere vuoti. +[] # NON VALIDO +[a.] # NON VALIDO +[a..b] # NON VALIDO +[.b] # NON VALIDO +[.] # NON VALIDO + +################## +# Tabelle inline # +################## + +tabelleInline = { racchiuseData = "{ e }", rigaSingola = true } +punto = { x = 1, y = 2 } + +#################### +# Array di tabelle # +#################### + +# Un array di tabelle può essere creato utilizzando due parentesi quadre. +# Tutte le tabelle con questo nome saranno elementi dell'array. +# Gli elementi vengono inseriti nell'ordine in cui si trovano. + +[[prodotti]] +nome = "array di tabelle" +sku = 738594937 +tabelleVuoteValide = true + +[[prodotti]] + +[[prodotti]] +nome = "un altro item" +sku = 284758393 +colore = "grigio" + +# Puoi anche creare array di tabelle nested. Le sottotabelle con doppie +# parentesi quadre apparterranno alla tabella più vicina sopra di esse. + +[[frutta]] + nome = "mela" + + [frutto.geometria] + forma = "sferica" + nota = "Sono una proprietà del frutto" + + [[frutto.colore]] + nome = "rosso" + nota = "Sono un oggetto di un array dentro mela" + + [[frutto.colore]] + nome = "verde" + nota = "Sono nello stesso array di rosso" + +[[frutta]] + nome = "banana" + + [[frutto.colore]] + nome = "giallo" + nota = "Anche io sono un oggetto di un array, ma dentro banana" +``` + +Ecco l'equivalente JSON dell'ultima tabella: + +```json +{ + "frutta": [ + { + "nome": "mela", + "geometria": { "forma": "sferica", "nota": "..."}, + "colore": [ + { "nome": "rosso", "nota": "..." }, + { "nome": "verde", "nota": "..." } + ] + }, + { + "nome": "banana", + "colore": [ + { "nome": "giallo", "nota": "..." } + ] + } + ] +} +``` + +### Altre risorse + ++ [Repository ufficiale di TOML](https://github.com/toml-lang/toml) diff --git a/make.html.markdown b/make.html.markdown index eecc96bf..f5352f9e 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -1,246 +1,246 @@ ---- -category: tool -tool: make -contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] -filename: Makefile ---- - -A Makefile defines a graph of rules for creating a target (or targets). -Its purpose is to do the minimum amount of work needed to update a -target to the most recent version of the source. Famously written over a -weekend by Stuart Feldman in 1976, it is still widely used (particularly -on Unix and Linux) despite many competitors and criticisms. - -There are many varieties of make in existence, however this article -assumes that we are using GNU make which is the standard on Linux. - -```make - -# Comments can be written like this. - -# File should be named Makefile and then can be run as `make `. -# Otherwise we use `make -f "filename" `. - -# Warning - only use TABS to indent in Makefiles, never spaces! - -#----------------------------------------------------------------------- -# Basics -#----------------------------------------------------------------------- - -# Rules are of the format -# target: -# where prerequisites are optional. - -# A rule - this rule will only run if file0.txt doesn't exist. -file0.txt: - echo "foo" > file0.txt - # Even comments in these 'recipe' sections get passed to the shell. - # Try `make file0.txt` or simply `make` - first rule is the default. - -# This rule will only run if file0.txt is newer than file1.txt. -file1.txt: file0.txt - cat file0.txt > file1.txt - # use the same quoting rules as in the shell. - @cat file0.txt >> file1.txt - # @ stops the command from being echoed to stdout. - -@echo 'hello' - # - means that make will keep going in the case of an error. - # Try `make file1.txt` on the commandline. - -# A rule can have multiple targets and multiple prerequisites -file2.txt file3.txt: file0.txt file1.txt - touch file2.txt - touch file3.txt - -# Make will complain about multiple recipes for the same rule. Empty -# recipes don't count though and can be used to add new dependencies. - -#----------------------------------------------------------------------- -# Phony Targets -#----------------------------------------------------------------------- - -# A phony target. Any target that isn't a file. -# It will never be up to date so make will always try to run it. -all: maker process - -# We can declare things out of order. -maker: - touch ex0.txt ex1.txt - -# Can avoid phony rules breaking when a real file has the same name by -.PHONY: all maker process -# This is a special target. There are several others. - -# A rule with a dependency on a phony target will always run -ex0.txt ex1.txt: maker - -# Common phony targets are: all make clean install ... - -#----------------------------------------------------------------------- -# Automatic Variables & Wildcards -#----------------------------------------------------------------------- - -process: file*.txt #using a wildcard to match filenames - @echo $^ # $^ is a variable containing the list of prerequisites - @echo $@ # prints the target name - #(for multiple target rules, $@ is whichever caused the rule to run) - @echo $< # the first prerequisite listed - @echo $? # only the dependencies that are out of date - @echo $+ # all dependencies including duplicates (unlike normal) - #@echo $| # all of the 'order only' prerequisites - -# Even if we split up the rule dependency definitions, $^ will find them -process: ex1.txt file0.txt -# ex1.txt will be found but file0.txt will be deduplicated. - -#----------------------------------------------------------------------- -# Patterns -#----------------------------------------------------------------------- - -# Can teach make how to convert certain files into other files. - -%.png: %.svg - inkscape --export-png $^ - -# Pattern rules will only do anything if make decides to create the -# target. - -# Directory paths are normally ignored when matching pattern rules. But -# make will try to use the most appropriate rule available. -small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ - -# make will use the last version for a pattern rule that it finds. -%.png: %.svg - @echo this rule is chosen - -# However make will use the first pattern rule that can make the target -%.png: %.ps - @echo this rule is not chosen if *.svg and *.ps are both present - -# make already has some pattern rules built-in. For instance, it knows -# how to turn *.c files into *.o files. - -# Older makefiles might use suffix rules instead of pattern rules -.png.ps: - @echo this rule is similar to a pattern rule. - -# Tell make about the suffix rule -.SUFFIXES: .png - -#----------------------------------------------------------------------- -# Variables -#----------------------------------------------------------------------- -# aka. macros - -# Variables are basically all string types - -name = Ted -name2="Sarah" - -echo: - @echo $(name) - @echo ${name2} - @echo $name # This won't work, treated as $(n)ame. - @echo $(name3) # Unknown variables are treated as empty strings. - -# There are 4 places to set variables. -# In order of priority from highest to lowest: -# 1: commandline arguments -# 2: Makefile -# 3: shell environment variables - make imports these automatically. -# 4: make has some predefined variables - -name4 ?= Jean -# Only set the variable if environment variable is not already defined. - -override name5 = David -# Stops commandline arguments from changing this variable. - -name4 +=grey -# Append values to variable (includes a space). - -# Pattern-specific variable values (GNU extension). -echo: name2 = Sara # True within the matching rule - # and also within its remade recursive dependencies - # (except it can break when your graph gets too complicated!) - -# Some variables defined automatically by make. -echo_inbuilt: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} - -#----------------------------------------------------------------------- -# Variables 2 -#----------------------------------------------------------------------- - -# The first type of variables are evaluated each time they are used. -# This can be expensive, so a second type of variable exists which is -# only evaluated once. (This is a GNU make extension) - -var := hello -var2 ::= $(var) hello -#:= and ::= are equivalent. - -# These variables are evaluated procedurally (in the order that they -# appear), thus breaking with the rest of the language ! - -# This doesn't work -var3 ::= $(var4) and good luck -var4 ::= good night - -#----------------------------------------------------------------------- -# Functions -#----------------------------------------------------------------------- - -# make has lots of functions available. - -sourcefiles = $(wildcard *.c */*.c) -objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) - -# Format is $(func arg0,arg1,arg2...) - -# Some examples -ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) - -#----------------------------------------------------------------------- -# Directives -#----------------------------------------------------------------------- - -# Include other makefiles, useful for platform specific code -include foo.mk - -sport = tennis -# Conditional compilation -report: -ifeq ($(sport),tennis) - @echo 'game, set, match' -else - @echo "They think it's all over; it is now" -endif - -# There are also ifneq, ifdef, ifndef - -foo = true - -ifdef $(foo) -bar = 'hello' -endif -``` - -### More Resources - -+ [gnu make documentation](https://www.gnu.org/software/make/manual/) -+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) -+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) +--- +category: tool +tool: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] +filename: Makefile +--- + +A Makefile defines a graph of rules for creating a target (or targets). +Its purpose is to do the minimum amount of work needed to update a +target to the most recent version of the source. Famously written over a +weekend by Stuart Feldman in 1976, it is still widely used (particularly +on Unix and Linux) despite many competitors and criticisms. + +There are many varieties of make in existence, however this article +assumes that we are using GNU make which is the standard on Linux. + +```make + +# Comments can be written like this. + +# File should be named Makefile and then can be run as `make `. +# Otherwise we use `make -f "filename" `. + +# Warning - only use TABS to indent in Makefiles, never spaces! + +#----------------------------------------------------------------------- +# Basics +#----------------------------------------------------------------------- + +# Rules are of the format +# target: +# where prerequisites are optional. + +# A rule - this rule will only run if file0.txt doesn't exist. +file0.txt: + echo "foo" > file0.txt + # Even comments in these 'recipe' sections get passed to the shell. + # Try `make file0.txt` or simply `make` - first rule is the default. + +# This rule will only run if file0.txt is newer than file1.txt. +file1.txt: file0.txt + cat file0.txt > file1.txt + # use the same quoting rules as in the shell. + @cat file0.txt >> file1.txt + # @ stops the command from being echoed to stdout. + -@echo 'hello' + # - means that make will keep going in the case of an error. + # Try `make file1.txt` on the commandline. + +# A rule can have multiple targets and multiple prerequisites +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make will complain about multiple recipes for the same rule. Empty +# recipes don't count though and can be used to add new dependencies. + +#----------------------------------------------------------------------- +# Phony Targets +#----------------------------------------------------------------------- + +# A phony target. Any target that isn't a file. +# It will never be up to date so make will always try to run it. +all: maker process + +# We can declare things out of order. +maker: + touch ex0.txt ex1.txt + +# Can avoid phony rules breaking when a real file has the same name by +.PHONY: all maker process +# This is a special target. There are several others. + +# A rule with a dependency on a phony target will always run +ex0.txt ex1.txt: maker + +# Common phony targets are: all make clean install ... + +#----------------------------------------------------------------------- +# Automatic Variables & Wildcards +#----------------------------------------------------------------------- + +process: file*.txt #using a wildcard to match filenames + @echo $^ # $^ is a variable containing the list of prerequisites + @echo $@ # prints the target name + #(for multiple target rules, $@ is whichever caused the rule to run) + @echo $< # the first prerequisite listed + @echo $? # only the dependencies that are out of date + @echo $+ # all dependencies including duplicates (unlike normal) + #@echo $| # all of the 'order only' prerequisites + +# Even if we split up the rule dependency definitions, $^ will find them +process: ex1.txt file0.txt +# ex1.txt will be found but file0.txt will be deduplicated. + +#----------------------------------------------------------------------- +# Patterns +#----------------------------------------------------------------------- + +# Can teach make how to convert certain files into other files. + +%.png: %.svg + inkscape --export-png $^ + +# Pattern rules will only do anything if make decides to create the +# target. + +# Directory paths are normally ignored when matching pattern rules. But +# make will try to use the most appropriate rule available. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# make will use the last version for a pattern rule that it finds. +%.png: %.svg + @echo this rule is chosen + +# However make will use the first pattern rule that can make the target +%.png: %.ps + @echo this rule is not chosen if *.svg and *.ps are both present + +# make already has some pattern rules built-in. For instance, it knows +# how to turn *.c files into *.o files. + +# Older makefiles might use suffix rules instead of pattern rules +.png.ps: + @echo this rule is similar to a pattern rule. + +# Tell make about the suffix rule +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables +#----------------------------------------------------------------------- +# aka. macros + +# Variables are basically all string types + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # This won't work, treated as $(n)ame. + @echo $(name3) # Unknown variables are treated as empty strings. + +# There are 4 places to set variables. +# In order of priority from highest to lowest: +# 1: commandline arguments +# 2: Makefile +# 3: shell environment variables - make imports these automatically. +# 4: make has some predefined variables + +name4 ?= Jean +# Only set the variable if environment variable is not already defined. + +override name5 = David +# Stops commandline arguments from changing this variable. + +name4 +=grey +# Append values to variable (includes a space). + +# Pattern-specific variable values (GNU extension). +echo: name2 = Sara # True within the matching rule + # and also within its remade recursive dependencies + # (except it can break when your graph gets too complicated!) + +# Some variables defined automatically by make. +echo_inbuilt: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables 2 +#----------------------------------------------------------------------- + +# The first type of variables are evaluated each time they are used. +# This can be expensive, so a second type of variable exists which is +# only evaluated once. (This is a GNU make extension) + +var := hello +var2 ::= $(var) hello +#:= and ::= are equivalent. + +# These variables are evaluated procedurally (in the order that they +# appear), thus breaking with the rest of the language ! + +# This doesn't work +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Functions +#----------------------------------------------------------------------- + +# make has lots of functions available. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# Format is $(func arg0,arg1,arg2...) + +# Some examples +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directives +#----------------------------------------------------------------------- + +# Include other makefiles, useful for platform specific code +include foo.mk + +sport = tennis +# Conditional compilation +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# There are also ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + +### More Resources + ++ [gnu make documentation](https://www.gnu.org/software/make/manual/) ++ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) ++ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) diff --git a/opengl.html.markdown b/opengl.html.markdown index 993402f7..f6a9085f 100644 --- a/opengl.html.markdown +++ b/opengl.html.markdown @@ -1,765 +1,765 @@ ---- -category: tool -tool: OpenGL -filename: learnopengl.cpp -contributors: - - ["Simon Deitermann", "s.f.deitermann@t-online.de"] ---- - -**Open Graphics Library** (**OpenGL**) is a cross-language cross-platform application programming interface -(API) for rendering 2D computer graphics and 3D vector graphics.[1] In this tutorial we will be -focusing on modern OpenGL from 3.3 and above, ignoring "immediate-mode", Displaylists and -VBO's without use of Shaders. -I will be using C++ with SFML for window, image and context creation aswell as GLEW -for modern OpenGL extensions, though there are many other librarys available. - -```cpp -// Creating an SFML window and OpenGL basic setup. -#include -#include -#include -#include - -int main() { - // First we tell SFML how to setup our OpenGL context. - sf::ContextSettings context{ 24, // depth buffer bits - 8, // stencil buffer bits - 4, // MSAA samples - 3, // major opengl version - 3 }; // minor opengl version - // Now we create the window, enable VSync - // and set the window active for OpenGL. - sf::Window window{ sf::VideoMode{ 1024, 768 }, - "opengl window", - sf::Style::Default, - context }; - window.setVerticalSyncEnabled(true); - window.setActive(true); - // After that we initialise GLEW and check if an error occurred. - GLenum error; - glewExperimental = GL_TRUE; - if ((err = glewInit()) != GLEW_OK) - std::cout << glewGetErrorString(err) << std::endl; - // Here we set the color glClear will clear the buffers with. - glClearColor(0.0f, // red - 0.0f, // green - 0.0f, // blue - 1.0f); // alpha - // Now we can start the event loop, poll for events and draw objects. - sf::Event event{ }; - while (window.isOpen()) { - while (window.pollEvent(event)) { - if (event.type == sf::Event::Closed) - window.close; - } - // Tell OpenGL to clear the color buffer - // and the depth buffer, this will clear our window. - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - // Flip front- and backbuffer. - window.display(); - } - return 0; -} -``` - -## Loading Shaders - -After creating a window and our event loop we should create a function, -that sets up our shader program. - -```cpp -GLuint createShaderProgram(const std::string& vertexShaderPath, - const std::string& fragmentShaderPath) { - // Load the vertex shader source. - std::stringstream ss{ }; - std::string vertexShaderSource{ }; - std::string fragmentShaderSource{ }; - std::ifstream file{ vertexShaderPath }; - if (file.is_open()) { - ss << file.rdbuf(); - vertexShaderSource = ss.str(); - file.close(); - } - // Clear the stringstream and load the fragment shader source. - ss.str(std::string{ }); - file.open(fragmentShaderPath); - if (file.is_open()) { - ss << file.rdbuf(); - fragmentShaderSource = ss.str(); - file.close(); - } - // Create the program. - GLuint program = glCreateProgram(); - // Create the shaders. - GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); - GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); - // Now we can load the shader source into the shader objects and compile them. - // Because glShaderSource() wants a const char* const*, - // we must first create a const char* and then pass the reference. - const char* cVertexSource = vertexShaderSource.c_str(); - glShaderSource(vertexShader, // shader - 1, // number of strings - &cVertexSource, // strings - nullptr); // length of strings (nullptr for 1) - glCompileShader(vertexShader); - // Now we have to do the same for the fragment shader. - const char* cFragmentSource = fragmentShaderSource.c_str(); - glShaderSource(fragmentShader, 1, &cFragmentSource, nullptr); - glCompileShader(fragmentShader); - // After attaching the source and compiling the shaders, - // we attach them to the program; - glAttachShader(program, vertexShader); - glAttachShader(program, fragmentShader); - glLinkProgram(program); - // After linking the shaders we should detach and delete - // them to prevent memory leak. - glDetachShader(program, vertexShader); - glDetachShader(program, fragmentShader); - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); - // With everything done we can return the completed program. - return program; -} -``` - -If you want to check the compilation log you can add the following between glCompileShader() and glAttachShader(). - -```cpp -GLint logSize = 0; -std::vector logText{ }; -glGetShaderiv(vertexShader, // shader - GL_INFO_LOG_LENGTH, // requested parameter - &logSize); // return object -if (logSize > 0) { - logText.resize(logSize); - glGetShaderInfoLog(vertexShader, // shader - logSize, // buffer length - &logSize, // returned length - logText.data()); // buffer - std::cout << logText.data() << std::endl; -} -``` - -The same is possible after glLinkProgram(), just replace glGetShaderiv() with glGetProgramiv() -and glGetShaderInfoLog() with glGetProgramInfoLog(). - -```cpp -// Now we can create a shader program with a vertex and a fragment shader. -// ... -glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - -GLuint program = createShaderProgram("vertex.glsl", "fragment.glsl"); - -sf::Event event{ }; -// ... -// We also have to delete the program at the end of the application. -// ... - } - glDeleteProgram(program); - return 0; -} -// ... -``` - -Ofcourse we have to create the vertex and fragment shader before we can load them, -so lets create two basic shaders. - -**Vertex Shader** - -```glsl -// Declare which version of GLSL we use. -// Here we declare, that we want to use the OpenGL 3.3 version of GLSL. -#version 330 core -// At attribute location 0 we want an input variable of type vec3, -// that contains the position of the vertex. -// Setting the location is optional, if you don't set it you can ask for the -// location with glGetAttribLocation(). -layout(location = 0) in vec3 position; -// Every shader starts in it's main function. -void main() { - // gl_Position is a predefined variable that holds - // the final vertex position. - // It consists of a x, y, z and w coordinate. - gl_Position = vec4(position, 1.0); -} -``` - -**Fragment Shader** - -```glsl -#version 330 core -// The fragment shader does not have a predefined variable for -// the vertex color, so we have to define a output vec4, -// that holds the final vertex color. -out vec4 outColor; - -void main() { - // We simply set the output color to red. - // The parameters are red, green, blue and alpha. - outColor = vec4(1.0, 0.0, 0.0, 1.0); -} -``` - -## VAO and VBO -Now we need to define some vertex position we can pass to our shaders. Lets define a simple 2D quad. - -```cpp -// The vertex data is defined in a counter-clockwise way, -// as this is the default front face. -std::vector vertexData { - -0.5f, 0.5f, 0.0f, - -0.5f, -0.5f, 0.0f, - 0.5f, -0.5f, 0.0f, - 0.5f, 0.5f, 0.0f -}; -// If you want to use a clockwise definition, you can simply call -glFrontFace(GL_CW); -// Next we need to define a Vertex Array Object (VAO). -// The VAO stores the current state while its active. -GLuint vao = 0; -glGenVertexArrays(1, &vao); -glBindVertexArray(vao); -// With the VAO active we can now create a Vertex Buffer Object (VBO). -// The VBO stores our vertex data. -GLuint vbo = 0; -glGenBuffers(1, &vbo); -glBindBuffer(GL_ARRAY_BUFFER, vbo); -// For reading and copying there are also GL_*_READ and GL_*_COPY, -// if your data changes more often use GL_DYNAMIC_* or GL_STREAM_*. -glBufferData(GL_ARRAY_BUFFER, // target buffer - sizeof(vertexData[0]) * vertexData.size(), // size - vertexData.data(), // data - GL_STATIC_DRAW); // usage -// After filling the VBO link it to the location 0 in our vertex shader, -// which holds the vertex position. -// ... -// To ask for the attribute location, if you haven't set it: -GLint posLocation = glGetAttribLocation(program, "position"); -// .. -glEnableVertexAttribArray(0); -glVertexAttribPointer(0, 3, // location and size - GL_FLOAT, // type of data - GL_FALSE, // normalized (always false for floats) - 0, // stride (interleaved arrays) - nullptr); // offset (interleaved arrays) -// Everything should now be saved in our VAO and we can unbind it and the VBO. -glBindVertexArray(0); -glBindBuffer(GL_ARRAY_BUFFER, 0); -// Now we can draw the vertex data in our render loop. -// ... -glClear(GL_COLOR_BUFFER_BIT); -// Tell OpenGL we want to use our shader program. -glUseProgram(program); -// Binding the VAO loads the data we need. -glBindVertexArray(vao); -// We want to draw a quad starting at index 0 of the VBO using 4 indices. -glDrawArrays(GL_QUADS, 0, 4); -glBindVertexArray(0); -window.display(); -// ... -// Ofcource we have to delete the allocated memory for the VAO and VBO at -// the end of our application. -// ... -glDeleteBuffers(1, &vbo); -glDeleteVertexArrays(1, &vao); -glDeleteProgram(program); -return 0; -// ... -``` - -You can find the current code here: [OpenGL - 1](https://pastebin.com/W8jdmVHD). - -## More VBO's and Color -Let's create another VBO for some colors. - -```cpp -std::vector colorData { - 1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, 0.0f -}; -``` - -Next we can simply change some previous parameters to create a second VBO for our colors. - -```cpp -// ... -GLuint vbo[2]; -glGenBuffers(2, vbo); -glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); -// ... -glDeleteBuffers(2, vbo); -/ ... -// With these changes made we now have to load our color data into the new VBO -// ... -glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); - -glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); -glBufferData(GL_ARRAY_BUFFER, sizeof(colorData[0]) * colorData.size(), - colorData.data(), GL_STATIC_DRAW); -glEnableVertexAttribArray(1); -glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); - -glBindVertexArray(0); -// ... -``` - -Next we have to change our vertex shader to pass the color data to the fragment shader.
    -**Vertex Shader** - -```glsl -#version 330 core - -layout(location = 0) in vec3 position; -// The new location has to differ from any other input variable. -// It is the same index we need to pass to -// glEnableVertexAttribArray() and glVertexAttribPointer(). -layout(location = 1) in vec3 color; - -out vec3 fColor; - -void main() { - fColor = color; - gl_Position = vec4(position, 1.0); -} -``` - -**Fragment Shader** - -```glsl -#version 330 core - -in vec3 fColor; - -out vec4 outColor; - -void main() { - outColor = vec4(fColor, 1.0); -} -``` - -We define a new input variable ```color``` which represents our color data, this data -is passed on to ```fColor```, which is an output variable of our vertex shader and -becomes an input variable for our fragment shader. -It is imporatant that variables passed between shaders have the exact same name -and type. - -## Handling VBO's - -```cpp -// If you want to completely clear and refill a VBO use glBufferData(), -// just like we did before. -// ... -// There are two mains ways to update a subset of a VBO's data. -// To update a VBO with existing data -std::vector newSubData { - -0.25f, 0.5f, 0.0f -}; -glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); -glBufferSubData(GL_ARRAY_BUFFER, // target buffer - 0, // offset - sizeof(newSubData[0]) * newSubData.size(), // size - newSubData.data()); // data -// This would update the first three values in our vbo[0] buffer. -// If you want to update starting at a specific location just set the second -// parameter to that value and multiply by the types size. -// ... -// If you are streaming data, for example from a file, -// it is faster to directly pass the data to the buffer. -// Other access values are GL_READ_ONLY and GL_READ_WRITE. -glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); -// You can static_cast() the void* to be more safe. -void* Ptr = glMapBuffer(GL_ARRAY_BUFFER, // buffer to map - GL_WRITE_ONLY); // access to buffer -memcpy(Ptr, newSubData.data(), sizeof(newSubData[0]) * newSubData.size()); -// To copy to a specific location add a destination offset to memcpy(). -glUnmapBuffer(GL_ARRAY_BUFFER); -// ... -// There is also a way to copy data from one buffer to another, -// If we have two VBO's vbo[0] and vbo[1], we can copy like so -// You can also read from GL_ARRAY_BUFFER. -glBindBuffer(GL_COPY_READ_BUFFER, vbo[0]); -// GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER are specifically for -// copying buffer data. -glBindBuffer(GL_COPY_WRITE_BUFFER, vbo[1]); -glCopyBufferSubData(GL_COPY_READ_BUFFER, // read buffer - GL_COPY_WRITE_BUFFER, // write buffer - 0, 0, // read and write offset - sizeof(vbo[0]) * 3); // copy size -// This will copy the first three elements from vbo[0] to vbo[1]. -``` - -## Uniforms - -**Fragment Shader** - -```glsl -// Uniforms are variables like in and out, however, -// we can change them easily by passing new values with glUniform(). -// Lets define a time variable in our fragment shader. -#version 330 core -// Unlike a in/out variable we can use a uniform in every shader, -// without the need to pass it to the next one, they are global. -// Don't use locations already used for attributes! -// Uniform layout locations require OpenGL 4.3! -layout(location = 10) uniform float time; - -in vec3 fColor; - -out vec4 outColor; - -void main() { - // Create a sine wave from 0 to 1 based on the time passed to the shader. - float factor = (sin(time * 2) + 1) / 2; - outColor = vec4(fColor.r * factor, fColor.g * factor, fColor.b * factor, 1.0); -} -``` - -Back to our source code. - -```cpp -// If we haven't set the layout location, we can ask for it. -GLint timeLocation = glGetUniformLocation(program, "time"); -// ... -// Also we should define a Timer counting the current time. -sf::Clock clock{ }; -// In out render loop we can now update the uniform every frame. - // ... - window.display(); - glUniform1f(10, // location - clock.getElapsedTime().asSeconds()); // data -} -// ... -``` - -With the time getting updated every frame the quad should now be changing from -fully colored to pitch black. -There are different types of glUniform() you can find simple documentation here: -[glUniform - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml) - -## Indexing and IBO's - -Element Array Buffers or more commonly Index Buffer Objects (IBO) allow us to use the -same vertex data again which makes drawing a lot easier and faster. here's an example: - -```cpp -// Lets create a quad from two rectangles. -// We can simply use the old vertex data from before. -// First, we have to create the IBO. -// The index is referring to the first declaration in the VBO. -std::vector iboData { - 0, 1, 2, - 0, 2, 3 -}; -// That's it, as you can see we could reuse 0 - the top left -// and 2 - the bottom right. -// Now that we have our data, we have to fill it into a buffer. -// Note that this has to happen between the two glBindVertexArray() calls, -// so it gets saved into the VAO. -GLuint ibo = 0; -glGenBufferrs(1, &ibo); -glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); -glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iboData[0]) * iboData.size(), - iboData.data(), GL_STATIC_DRAW); -// Next in our render loop, we replace glDrawArrays() with: -glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr); -// Remember to delete the allocated memory for the IBO. -``` - -You can find the current code here: [OpenGL - 2](https://pastebin.com/R3Z9ACDE). - -## Textures - -To load out texture we first need a library that loads the data, for simplicity I will be -using SFML, however there are a lot of librarys for loading image data. - -```cpp -// Lets save we have a texture called "my_tex.tga", we can load it with: -sf::Image image; -image.loadFromFile("my_tex.tga"); -// We have to flip the texture around the y-Axis, because OpenGL's texture -// origin is the bottom left corner, not the top left. -image.flipVertically(); -// After loading it we have to create a OpenGL texture. -GLuint texture = 0; -glGenTextures(1, &texture); -glBindTexture(GL_TEXTURE_2D, texture); -// Specify what happens when the coordinates are out of range. -glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); -glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); -// Specify the filtering if the object is very large. -glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); -glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); -// Load the image data to the texture. -glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, - 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr()); -// Unbind the texture to prevent modifications. -glBindTexture(GL_TEXTURE_2D, 0); -// Delete the texture at the end of the application. -// ... -glDeleteTextures(1, &texture); -``` - -Ofcourse there are more texture formats than only 2D textures, -You can find further information on parameters here: -[glBindTexture - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindTexture.xhtml)
    -[glTexImage2D - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml)
    -[glTexParameter - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexParameter.xhtml)
    - -```cpp -// With the texture created, we now have to specify the UV, -// or in OpenGL terms ST coordinates. -std::vector texCoords { - // The texture coordinates have to match the triangles/quad - // definition. - 0.0f, 1.0f, // start at top-left - 0.0f, 0.0f, // go round counter-clockwise - 1.0f, 0.0f, - 1.0f, 1.0f // end at top-right -}; -// Now we increase the VBO's size again just like we did for the colors. -// ... -GLuint vbo[3]; -glGenBuffers(3, vbo); -// ... -glDeleteBuffers(3, vbo); -// ... -// Load the texture coordinates into the new buffer. -glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); -glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords[0]) * texCoords.size(), - texCoords.data(), GL_STATIC_DRAW); -glEnableVertexAttribArray(2); -glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr); -// Because the VAO does not store the texture we have to bind it before drawing. -// ... -glBindVertexArray(vao); -glBindTexture(GL_TEXTURE_2D, texture); -glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr); -// ... -``` - -Change the shaders to pass the data to the fragment shader.
    - -**Vertex Shader** - -```glsl -#version 330 core - -layout(location = 0) in vec3 position; -layout(location = 1) in vec3 color; -layout(location = 2) in vec2 texCoords; - -out vec3 fColor; -out vec2 fTexCoords; - -void main() { - fColor = color; - fTexCoords = texCoords; - gl_Position = vec4(position, 1.0); -} -``` - -**Fragment Shader** - -```glsl -#version 330 core -// sampler2D represents our 2D texture. -uniform sampler2D tex; -uniform float time; - -in vec3 fColor; -in vec2 fTexCoords; - -out vec4 outColor; - -void main() { - // texture() loads the current texure data at the specified texture coords, - // then we can simply multiply them by our color. - outColor = texture(tex, fTexCoords) * vec4(fColor, 1.0); -} -``` - -You can find the current code here: [OpenGL - 3](https://pastebin.com/u3bcwM6q) - -## Matrix Transformation - -**Vertex Shader** - -```glsl -#version 330 core - -layout(location = 0) in vec3 position; -layout(location = 1) in vec3 color; -layout(location = 2) in vec2 texCoords; -// Create 2 4x4 matricies, 1 for the projection matrix -// and 1 for the model matrix. -// Because we draw in a static scene, we don't need a view matrix. -uniform mat4 projection; -uniform mat4 model; - -out vec3 fColor; -out vec2 fTexCoords; - -void main() { - fColor = color; - fTexCoords = texCoords; - // Multiplay the position by the model matrix and then by the - // projection matrix. - // Beware order of multiplication for matricies! - gl_Position = projection * model * vec4(position, 1.0); -} -``` - -In our source we now need to change the vertex data, create a model- and a projection matrix. - -```cpp -// The new vertex data, counter-clockwise declaration. -std::vector vertexData { - 0.0f, 1.0f, 0.0f, // top left - 0.0f, 0.0f, 0.0f, // bottom left - 1.0f, 0.0f, 0.0f, // bottom right - 1.0f, 1.0f, 0.0f // top right -}; -// Request the location of our matricies. -GLint projectionLocation = glGetUniformLocation(program, "projection"); -GLint modelLocation = glGetUniformLocation(program, "model"); -// Declaring the matricies. -// Orthogonal matrix for a 1024x768 window. -std::vector projection { - 0.001953f, 0.0f, 0.0f, 0.0f, - 0.0f, -0.002604f, 0.0f, 0.0f, - 0.0f, 0.0f, -1.0f, 0.0f, - -1.0f, 1.0f, 0.0f, 1.0f -}; -// Model matrix translating to x 50, y 50 -// and scaling to x 200, y 200. -std::vector model { - 200.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 200.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 50.0f, 50.0f, 0.0f, 1.0f -}; -// Now we can send our calculated matricies to the program. -glUseProgram(program); -glUniformMatrix4fv(projectionLocation, // location - 1, // count - GL_FALSE, // transpose the matrix - projection.data()); // data -glUniformMatrix4fv(modelLocation, 1, GL_FALSE, model.data()); -glUseProgram(0); -// The glUniform*() calls have to be done, while the program is bound. -``` - -The application should now display the texture at the defined position and size.
    -You can find the current code here: [OpenGL - 4](https://pastebin.com/9ahpFLkY) - -```cpp -// There are many math librarys for OpenGL, which create -// matricies and vectors, the most used in C++ is glm (OpenGL Mathematics). -// Its a header only library. -// The same code using glm would look like: -glm::mat4 projection{ glm::ortho(0.0f, 1024.0f, 768.0f, 0.0f) }; -glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, - glm::value_ptr(projection)); -// Initialise the model matrix to the identity matrix, otherwise every -// multiplication would be 0. -glm::mat4 model{ 1.0f }; -model = glm::translate(model, glm::vec3{ 50.0f, 50.0f, 0.0f }); -model = glm::scale(model, glm::vec3{ 200.0f, 200.0f, 0.0f }); -glUniformMatrix4fv(modelLocation, 1, GL_FALSE, - glm::value_ptr(model)); -``` - -## Geometry Shader - -Geometry shaders were introduced in OpenGL 3.2, they can produce vertices -that are send to the rasterizer. They can also change the primitive type e.g. -they can take a point as an input and output other primitives. -Geometry shaders are inbetween the vertex and the fragment shader. - -**Vertex Shader** - -```glsl -#version 330 core - -layout(location = 0) in vec3 position; -layout(location = 1) in vec3 color; -// Create an output interface block passed to the next shadaer stage. -// Interface blocks can be used to structure data passed between shaders. -out VS_OUT { - vec3 color; -} vs_out; - -void main() { - vs_out.color = color - gl_Position = vec4(position, 1.0); -} -``` - -**Geometry Shader** - -```glsl -#version 330 core -// The geometry shader takes in points. -layout(points) in; -// It outputs a triangle every 3 vertices emitted. -layout(triangle_strip, max_vertices = 3) out; -// VS_OUT becomes an input variable in the geometry shader. -// Every input to the geometry shader in treated as an array. -in VS_OUT { - vec3 color; -} gs_in[]; -// Output color for the fragment shader. -// You can also simply define color as 'out vec3 color', -// If you don't want to use interface blocks. -out GS_OUT { - vec3 color; -} gs_out; - -void main() { - // Each emit calls the fragment shader, so we set a color for each vertex. - gs_out.color = mix(gs_in[0].color, vec3(1.0, 0.0, 0.0), 0.5); - // Move 0.5 units to the left and emit the new vertex. - // gl_in[] is the current vertex from the vertex shader, here we only - // use 0, because we are receiving points. - gl_Position = gl_in[0].gl_Position + vec4(-0.5, 0.0, 0.0, 0.0); - EmitVertex(); - gs_out.color = mix(gs_in[0].color, vec3(0.0, 1.0, 0.0), 0.5); - // Move 0.5 units to the right and emit the new vertex. - gl_Position = gl_in[0].gl_Position + vec4(0.5, 0.0, 0.0, 0.0); - EmitVertex(); - gs_out.color = mix(gs_in[0].color, vec3(0.0, 0.0, 1.0), 0.5); - // Move 0.5 units up and emit the new vertex. - gl_Position = gl_in[0].gl_Position + vec4(0.0, 0.75, 0.0, 0.0); - EmitVertex(); - EndPrimitive(); -} -``` - -**Fragment Shader** - -```glsl -in GS_OUT { - vec3 color; -} fs_in; - -out vec4 outColor; - -void main() { - outColor = vec4(fs_in.color, 1.0); -} -``` - -If you now store a single point with a single color in a VBO and draw them, -you should see a triangle, with your color mixed half way between -red, green and blue on each vertex. - - -## Quotes -[1][OpenGL - Wikipedia](https://en.wikipedia.org/wiki/OpenGL) - -## Books - -- OpenGL Superbible - Fifth Edition (covering OpenGL 3.3) -- OpenGL Programming Guide - Eighth Edition (covering OpenGL 4.3) +--- +category: tool +tool: OpenGL +filename: learnopengl.cpp +contributors: + - ["Simon Deitermann", "s.f.deitermann@t-online.de"] +--- + +**Open Graphics Library** (**OpenGL**) is a cross-language cross-platform application programming interface +(API) for rendering 2D computer graphics and 3D vector graphics.[1] In this tutorial we will be +focusing on modern OpenGL from 3.3 and above, ignoring "immediate-mode", Displaylists and +VBO's without use of Shaders. +I will be using C++ with SFML for window, image and context creation aswell as GLEW +for modern OpenGL extensions, though there are many other librarys available. + +```cpp +// Creating an SFML window and OpenGL basic setup. +#include +#include +#include +#include + +int main() { + // First we tell SFML how to setup our OpenGL context. + sf::ContextSettings context{ 24, // depth buffer bits + 8, // stencil buffer bits + 4, // MSAA samples + 3, // major opengl version + 3 }; // minor opengl version + // Now we create the window, enable VSync + // and set the window active for OpenGL. + sf::Window window{ sf::VideoMode{ 1024, 768 }, + "opengl window", + sf::Style::Default, + context }; + window.setVerticalSyncEnabled(true); + window.setActive(true); + // After that we initialise GLEW and check if an error occurred. + GLenum error; + glewExperimental = GL_TRUE; + if ((err = glewInit()) != GLEW_OK) + std::cout << glewGetErrorString(err) << std::endl; + // Here we set the color glClear will clear the buffers with. + glClearColor(0.0f, // red + 0.0f, // green + 0.0f, // blue + 1.0f); // alpha + // Now we can start the event loop, poll for events and draw objects. + sf::Event event{ }; + while (window.isOpen()) { + while (window.pollEvent(event)) { + if (event.type == sf::Event::Closed) + window.close; + } + // Tell OpenGL to clear the color buffer + // and the depth buffer, this will clear our window. + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + // Flip front- and backbuffer. + window.display(); + } + return 0; +} +``` + +## Loading Shaders + +After creating a window and our event loop we should create a function, +that sets up our shader program. + +```cpp +GLuint createShaderProgram(const std::string& vertexShaderPath, + const std::string& fragmentShaderPath) { + // Load the vertex shader source. + std::stringstream ss{ }; + std::string vertexShaderSource{ }; + std::string fragmentShaderSource{ }; + std::ifstream file{ vertexShaderPath }; + if (file.is_open()) { + ss << file.rdbuf(); + vertexShaderSource = ss.str(); + file.close(); + } + // Clear the stringstream and load the fragment shader source. + ss.str(std::string{ }); + file.open(fragmentShaderPath); + if (file.is_open()) { + ss << file.rdbuf(); + fragmentShaderSource = ss.str(); + file.close(); + } + // Create the program. + GLuint program = glCreateProgram(); + // Create the shaders. + GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); + GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); + // Now we can load the shader source into the shader objects and compile them. + // Because glShaderSource() wants a const char* const*, + // we must first create a const char* and then pass the reference. + const char* cVertexSource = vertexShaderSource.c_str(); + glShaderSource(vertexShader, // shader + 1, // number of strings + &cVertexSource, // strings + nullptr); // length of strings (nullptr for 1) + glCompileShader(vertexShader); + // Now we have to do the same for the fragment shader. + const char* cFragmentSource = fragmentShaderSource.c_str(); + glShaderSource(fragmentShader, 1, &cFragmentSource, nullptr); + glCompileShader(fragmentShader); + // After attaching the source and compiling the shaders, + // we attach them to the program; + glAttachShader(program, vertexShader); + glAttachShader(program, fragmentShader); + glLinkProgram(program); + // After linking the shaders we should detach and delete + // them to prevent memory leak. + glDetachShader(program, vertexShader); + glDetachShader(program, fragmentShader); + glDeleteShader(vertexShader); + glDeleteShader(fragmentShader); + // With everything done we can return the completed program. + return program; +} +``` + +If you want to check the compilation log you can add the following between glCompileShader() and glAttachShader(). + +```cpp +GLint logSize = 0; +std::vector logText{ }; +glGetShaderiv(vertexShader, // shader + GL_INFO_LOG_LENGTH, // requested parameter + &logSize); // return object +if (logSize > 0) { + logText.resize(logSize); + glGetShaderInfoLog(vertexShader, // shader + logSize, // buffer length + &logSize, // returned length + logText.data()); // buffer + std::cout << logText.data() << std::endl; +} +``` + +The same is possible after glLinkProgram(), just replace glGetShaderiv() with glGetProgramiv() +and glGetShaderInfoLog() with glGetProgramInfoLog(). + +```cpp +// Now we can create a shader program with a vertex and a fragment shader. +// ... +glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + +GLuint program = createShaderProgram("vertex.glsl", "fragment.glsl"); + +sf::Event event{ }; +// ... +// We also have to delete the program at the end of the application. +// ... + } + glDeleteProgram(program); + return 0; +} +// ... +``` + +Ofcourse we have to create the vertex and fragment shader before we can load them, +so lets create two basic shaders. + +**Vertex Shader** + +```glsl +// Declare which version of GLSL we use. +// Here we declare, that we want to use the OpenGL 3.3 version of GLSL. +#version 330 core +// At attribute location 0 we want an input variable of type vec3, +// that contains the position of the vertex. +// Setting the location is optional, if you don't set it you can ask for the +// location with glGetAttribLocation(). +layout(location = 0) in vec3 position; +// Every shader starts in it's main function. +void main() { + // gl_Position is a predefined variable that holds + // the final vertex position. + // It consists of a x, y, z and w coordinate. + gl_Position = vec4(position, 1.0); +} +``` + +**Fragment Shader** + +```glsl +#version 330 core +// The fragment shader does not have a predefined variable for +// the vertex color, so we have to define a output vec4, +// that holds the final vertex color. +out vec4 outColor; + +void main() { + // We simply set the output color to red. + // The parameters are red, green, blue and alpha. + outColor = vec4(1.0, 0.0, 0.0, 1.0); +} +``` + +## VAO and VBO +Now we need to define some vertex position we can pass to our shaders. Lets define a simple 2D quad. + +```cpp +// The vertex data is defined in a counter-clockwise way, +// as this is the default front face. +std::vector vertexData { + -0.5f, 0.5f, 0.0f, + -0.5f, -0.5f, 0.0f, + 0.5f, -0.5f, 0.0f, + 0.5f, 0.5f, 0.0f +}; +// If you want to use a clockwise definition, you can simply call +glFrontFace(GL_CW); +// Next we need to define a Vertex Array Object (VAO). +// The VAO stores the current state while its active. +GLuint vao = 0; +glGenVertexArrays(1, &vao); +glBindVertexArray(vao); +// With the VAO active we can now create a Vertex Buffer Object (VBO). +// The VBO stores our vertex data. +GLuint vbo = 0; +glGenBuffers(1, &vbo); +glBindBuffer(GL_ARRAY_BUFFER, vbo); +// For reading and copying there are also GL_*_READ and GL_*_COPY, +// if your data changes more often use GL_DYNAMIC_* or GL_STREAM_*. +glBufferData(GL_ARRAY_BUFFER, // target buffer + sizeof(vertexData[0]) * vertexData.size(), // size + vertexData.data(), // data + GL_STATIC_DRAW); // usage +// After filling the VBO link it to the location 0 in our vertex shader, +// which holds the vertex position. +// ... +// To ask for the attribute location, if you haven't set it: +GLint posLocation = glGetAttribLocation(program, "position"); +// .. +glEnableVertexAttribArray(0); +glVertexAttribPointer(0, 3, // location and size + GL_FLOAT, // type of data + GL_FALSE, // normalized (always false for floats) + 0, // stride (interleaved arrays) + nullptr); // offset (interleaved arrays) +// Everything should now be saved in our VAO and we can unbind it and the VBO. +glBindVertexArray(0); +glBindBuffer(GL_ARRAY_BUFFER, 0); +// Now we can draw the vertex data in our render loop. +// ... +glClear(GL_COLOR_BUFFER_BIT); +// Tell OpenGL we want to use our shader program. +glUseProgram(program); +// Binding the VAO loads the data we need. +glBindVertexArray(vao); +// We want to draw a quad starting at index 0 of the VBO using 4 indices. +glDrawArrays(GL_QUADS, 0, 4); +glBindVertexArray(0); +window.display(); +// ... +// Ofcource we have to delete the allocated memory for the VAO and VBO at +// the end of our application. +// ... +glDeleteBuffers(1, &vbo); +glDeleteVertexArrays(1, &vao); +glDeleteProgram(program); +return 0; +// ... +``` + +You can find the current code here: [OpenGL - 1](https://pastebin.com/W8jdmVHD). + +## More VBO's and Color +Let's create another VBO for some colors. + +```cpp +std::vector colorData { + 1.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 0.0f +}; +``` + +Next we can simply change some previous parameters to create a second VBO for our colors. + +```cpp +// ... +GLuint vbo[2]; +glGenBuffers(2, vbo); +glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); +// ... +glDeleteBuffers(2, vbo); +/ ... +// With these changes made we now have to load our color data into the new VBO +// ... +glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr); + +glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); +glBufferData(GL_ARRAY_BUFFER, sizeof(colorData[0]) * colorData.size(), + colorData.data(), GL_STATIC_DRAW); +glEnableVertexAttribArray(1); +glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr); + +glBindVertexArray(0); +// ... +``` + +Next we have to change our vertex shader to pass the color data to the fragment shader.
    +**Vertex Shader** + +```glsl +#version 330 core + +layout(location = 0) in vec3 position; +// The new location has to differ from any other input variable. +// It is the same index we need to pass to +// glEnableVertexAttribArray() and glVertexAttribPointer(). +layout(location = 1) in vec3 color; + +out vec3 fColor; + +void main() { + fColor = color; + gl_Position = vec4(position, 1.0); +} +``` + +**Fragment Shader** + +```glsl +#version 330 core + +in vec3 fColor; + +out vec4 outColor; + +void main() { + outColor = vec4(fColor, 1.0); +} +``` + +We define a new input variable ```color``` which represents our color data, this data +is passed on to ```fColor```, which is an output variable of our vertex shader and +becomes an input variable for our fragment shader. +It is imporatant that variables passed between shaders have the exact same name +and type. + +## Handling VBO's + +```cpp +// If you want to completely clear and refill a VBO use glBufferData(), +// just like we did before. +// ... +// There are two mains ways to update a subset of a VBO's data. +// To update a VBO with existing data +std::vector newSubData { + -0.25f, 0.5f, 0.0f +}; +glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); +glBufferSubData(GL_ARRAY_BUFFER, // target buffer + 0, // offset + sizeof(newSubData[0]) * newSubData.size(), // size + newSubData.data()); // data +// This would update the first three values in our vbo[0] buffer. +// If you want to update starting at a specific location just set the second +// parameter to that value and multiply by the types size. +// ... +// If you are streaming data, for example from a file, +// it is faster to directly pass the data to the buffer. +// Other access values are GL_READ_ONLY and GL_READ_WRITE. +glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); +// You can static_cast() the void* to be more safe. +void* Ptr = glMapBuffer(GL_ARRAY_BUFFER, // buffer to map + GL_WRITE_ONLY); // access to buffer +memcpy(Ptr, newSubData.data(), sizeof(newSubData[0]) * newSubData.size()); +// To copy to a specific location add a destination offset to memcpy(). +glUnmapBuffer(GL_ARRAY_BUFFER); +// ... +// There is also a way to copy data from one buffer to another, +// If we have two VBO's vbo[0] and vbo[1], we can copy like so +// You can also read from GL_ARRAY_BUFFER. +glBindBuffer(GL_COPY_READ_BUFFER, vbo[0]); +// GL_COPY_READ_BUFFER and GL_COPY_WRITE_BUFFER are specifically for +// copying buffer data. +glBindBuffer(GL_COPY_WRITE_BUFFER, vbo[1]); +glCopyBufferSubData(GL_COPY_READ_BUFFER, // read buffer + GL_COPY_WRITE_BUFFER, // write buffer + 0, 0, // read and write offset + sizeof(vbo[0]) * 3); // copy size +// This will copy the first three elements from vbo[0] to vbo[1]. +``` + +## Uniforms + +**Fragment Shader** + +```glsl +// Uniforms are variables like in and out, however, +// we can change them easily by passing new values with glUniform(). +// Lets define a time variable in our fragment shader. +#version 330 core +// Unlike a in/out variable we can use a uniform in every shader, +// without the need to pass it to the next one, they are global. +// Don't use locations already used for attributes! +// Uniform layout locations require OpenGL 4.3! +layout(location = 10) uniform float time; + +in vec3 fColor; + +out vec4 outColor; + +void main() { + // Create a sine wave from 0 to 1 based on the time passed to the shader. + float factor = (sin(time * 2) + 1) / 2; + outColor = vec4(fColor.r * factor, fColor.g * factor, fColor.b * factor, 1.0); +} +``` + +Back to our source code. + +```cpp +// If we haven't set the layout location, we can ask for it. +GLint timeLocation = glGetUniformLocation(program, "time"); +// ... +// Also we should define a Timer counting the current time. +sf::Clock clock{ }; +// In out render loop we can now update the uniform every frame. + // ... + window.display(); + glUniform1f(10, // location + clock.getElapsedTime().asSeconds()); // data +} +// ... +``` + +With the time getting updated every frame the quad should now be changing from +fully colored to pitch black. +There are different types of glUniform() you can find simple documentation here: +[glUniform - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glUniform.xhtml) + +## Indexing and IBO's + +Element Array Buffers or more commonly Index Buffer Objects (IBO) allow us to use the +same vertex data again which makes drawing a lot easier and faster. here's an example: + +```cpp +// Lets create a quad from two rectangles. +// We can simply use the old vertex data from before. +// First, we have to create the IBO. +// The index is referring to the first declaration in the VBO. +std::vector iboData { + 0, 1, 2, + 0, 2, 3 +}; +// That's it, as you can see we could reuse 0 - the top left +// and 2 - the bottom right. +// Now that we have our data, we have to fill it into a buffer. +// Note that this has to happen between the two glBindVertexArray() calls, +// so it gets saved into the VAO. +GLuint ibo = 0; +glGenBufferrs(1, &ibo); +glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo); +glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(iboData[0]) * iboData.size(), + iboData.data(), GL_STATIC_DRAW); +// Next in our render loop, we replace glDrawArrays() with: +glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr); +// Remember to delete the allocated memory for the IBO. +``` + +You can find the current code here: [OpenGL - 2](https://pastebin.com/R3Z9ACDE). + +## Textures + +To load out texture we first need a library that loads the data, for simplicity I will be +using SFML, however there are a lot of librarys for loading image data. + +```cpp +// Lets save we have a texture called "my_tex.tga", we can load it with: +sf::Image image; +image.loadFromFile("my_tex.tga"); +// We have to flip the texture around the y-Axis, because OpenGL's texture +// origin is the bottom left corner, not the top left. +image.flipVertically(); +// After loading it we have to create a OpenGL texture. +GLuint texture = 0; +glGenTextures(1, &texture); +glBindTexture(GL_TEXTURE_2D, texture); +// Specify what happens when the coordinates are out of range. +glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); +glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); +// Specify the filtering if the object is very large. +glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); +glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); +// Load the image data to the texture. +glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, + 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr()); +// Unbind the texture to prevent modifications. +glBindTexture(GL_TEXTURE_2D, 0); +// Delete the texture at the end of the application. +// ... +glDeleteTextures(1, &texture); +``` + +Ofcourse there are more texture formats than only 2D textures, +You can find further information on parameters here: +[glBindTexture - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindTexture.xhtml)
    +[glTexImage2D - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml)
    +[glTexParameter - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexParameter.xhtml)
    + +```cpp +// With the texture created, we now have to specify the UV, +// or in OpenGL terms ST coordinates. +std::vector texCoords { + // The texture coordinates have to match the triangles/quad + // definition. + 0.0f, 1.0f, // start at top-left + 0.0f, 0.0f, // go round counter-clockwise + 1.0f, 0.0f, + 1.0f, 1.0f // end at top-right +}; +// Now we increase the VBO's size again just like we did for the colors. +// ... +GLuint vbo[3]; +glGenBuffers(3, vbo); +// ... +glDeleteBuffers(3, vbo); +// ... +// Load the texture coordinates into the new buffer. +glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); +glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords[0]) * texCoords.size(), + texCoords.data(), GL_STATIC_DRAW); +glEnableVertexAttribArray(2); +glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, nullptr); +// Because the VAO does not store the texture we have to bind it before drawing. +// ... +glBindVertexArray(vao); +glBindTexture(GL_TEXTURE_2D, texture); +glDrawElements(GL_TRIANGLES, iboData.size(), GL_UNSIGNED_INT, nullptr); +// ... +``` + +Change the shaders to pass the data to the fragment shader.
    + +**Vertex Shader** + +```glsl +#version 330 core + +layout(location = 0) in vec3 position; +layout(location = 1) in vec3 color; +layout(location = 2) in vec2 texCoords; + +out vec3 fColor; +out vec2 fTexCoords; + +void main() { + fColor = color; + fTexCoords = texCoords; + gl_Position = vec4(position, 1.0); +} +``` + +**Fragment Shader** + +```glsl +#version 330 core +// sampler2D represents our 2D texture. +uniform sampler2D tex; +uniform float time; + +in vec3 fColor; +in vec2 fTexCoords; + +out vec4 outColor; + +void main() { + // texture() loads the current texure data at the specified texture coords, + // then we can simply multiply them by our color. + outColor = texture(tex, fTexCoords) * vec4(fColor, 1.0); +} +``` + +You can find the current code here: [OpenGL - 3](https://pastebin.com/u3bcwM6q) + +## Matrix Transformation + +**Vertex Shader** + +```glsl +#version 330 core + +layout(location = 0) in vec3 position; +layout(location = 1) in vec3 color; +layout(location = 2) in vec2 texCoords; +// Create 2 4x4 matricies, 1 for the projection matrix +// and 1 for the model matrix. +// Because we draw in a static scene, we don't need a view matrix. +uniform mat4 projection; +uniform mat4 model; + +out vec3 fColor; +out vec2 fTexCoords; + +void main() { + fColor = color; + fTexCoords = texCoords; + // Multiplay the position by the model matrix and then by the + // projection matrix. + // Beware order of multiplication for matricies! + gl_Position = projection * model * vec4(position, 1.0); +} +``` + +In our source we now need to change the vertex data, create a model- and a projection matrix. + +```cpp +// The new vertex data, counter-clockwise declaration. +std::vector vertexData { + 0.0f, 1.0f, 0.0f, // top left + 0.0f, 0.0f, 0.0f, // bottom left + 1.0f, 0.0f, 0.0f, // bottom right + 1.0f, 1.0f, 0.0f // top right +}; +// Request the location of our matricies. +GLint projectionLocation = glGetUniformLocation(program, "projection"); +GLint modelLocation = glGetUniformLocation(program, "model"); +// Declaring the matricies. +// Orthogonal matrix for a 1024x768 window. +std::vector projection { + 0.001953f, 0.0f, 0.0f, 0.0f, + 0.0f, -0.002604f, 0.0f, 0.0f, + 0.0f, 0.0f, -1.0f, 0.0f, + -1.0f, 1.0f, 0.0f, 1.0f +}; +// Model matrix translating to x 50, y 50 +// and scaling to x 200, y 200. +std::vector model { + 200.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 200.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 50.0f, 50.0f, 0.0f, 1.0f +}; +// Now we can send our calculated matricies to the program. +glUseProgram(program); +glUniformMatrix4fv(projectionLocation, // location + 1, // count + GL_FALSE, // transpose the matrix + projection.data()); // data +glUniformMatrix4fv(modelLocation, 1, GL_FALSE, model.data()); +glUseProgram(0); +// The glUniform*() calls have to be done, while the program is bound. +``` + +The application should now display the texture at the defined position and size.
    +You can find the current code here: [OpenGL - 4](https://pastebin.com/9ahpFLkY) + +```cpp +// There are many math librarys for OpenGL, which create +// matricies and vectors, the most used in C++ is glm (OpenGL Mathematics). +// Its a header only library. +// The same code using glm would look like: +glm::mat4 projection{ glm::ortho(0.0f, 1024.0f, 768.0f, 0.0f) }; +glUniformMatrix4fv(projectionLocation, 1, GL_FALSE, + glm::value_ptr(projection)); +// Initialise the model matrix to the identity matrix, otherwise every +// multiplication would be 0. +glm::mat4 model{ 1.0f }; +model = glm::translate(model, glm::vec3{ 50.0f, 50.0f, 0.0f }); +model = glm::scale(model, glm::vec3{ 200.0f, 200.0f, 0.0f }); +glUniformMatrix4fv(modelLocation, 1, GL_FALSE, + glm::value_ptr(model)); +``` + +## Geometry Shader + +Geometry shaders were introduced in OpenGL 3.2, they can produce vertices +that are send to the rasterizer. They can also change the primitive type e.g. +they can take a point as an input and output other primitives. +Geometry shaders are inbetween the vertex and the fragment shader. + +**Vertex Shader** + +```glsl +#version 330 core + +layout(location = 0) in vec3 position; +layout(location = 1) in vec3 color; +// Create an output interface block passed to the next shadaer stage. +// Interface blocks can be used to structure data passed between shaders. +out VS_OUT { + vec3 color; +} vs_out; + +void main() { + vs_out.color = color + gl_Position = vec4(position, 1.0); +} +``` + +**Geometry Shader** + +```glsl +#version 330 core +// The geometry shader takes in points. +layout(points) in; +// It outputs a triangle every 3 vertices emitted. +layout(triangle_strip, max_vertices = 3) out; +// VS_OUT becomes an input variable in the geometry shader. +// Every input to the geometry shader in treated as an array. +in VS_OUT { + vec3 color; +} gs_in[]; +// Output color for the fragment shader. +// You can also simply define color as 'out vec3 color', +// If you don't want to use interface blocks. +out GS_OUT { + vec3 color; +} gs_out; + +void main() { + // Each emit calls the fragment shader, so we set a color for each vertex. + gs_out.color = mix(gs_in[0].color, vec3(1.0, 0.0, 0.0), 0.5); + // Move 0.5 units to the left and emit the new vertex. + // gl_in[] is the current vertex from the vertex shader, here we only + // use 0, because we are receiving points. + gl_Position = gl_in[0].gl_Position + vec4(-0.5, 0.0, 0.0, 0.0); + EmitVertex(); + gs_out.color = mix(gs_in[0].color, vec3(0.0, 1.0, 0.0), 0.5); + // Move 0.5 units to the right and emit the new vertex. + gl_Position = gl_in[0].gl_Position + vec4(0.5, 0.0, 0.0, 0.0); + EmitVertex(); + gs_out.color = mix(gs_in[0].color, vec3(0.0, 0.0, 1.0), 0.5); + // Move 0.5 units up and emit the new vertex. + gl_Position = gl_in[0].gl_Position + vec4(0.0, 0.75, 0.0, 0.0); + EmitVertex(); + EndPrimitive(); +} +``` + +**Fragment Shader** + +```glsl +in GS_OUT { + vec3 color; +} fs_in; + +out vec4 outColor; + +void main() { + outColor = vec4(fs_in.color, 1.0); +} +``` + +If you now store a single point with a single color in a VBO and draw them, +you should see a triangle, with your color mixed half way between +red, green and blue on each vertex. + + +## Quotes +[1][OpenGL - Wikipedia](https://en.wikipedia.org/wiki/OpenGL) + +## Books + +- OpenGL Superbible - Fifth Edition (covering OpenGL 3.3) +- OpenGL Programming Guide - Eighth Edition (covering OpenGL 4.3) diff --git a/pt-br/make-pt.html.markdown b/pt-br/make-pt.html.markdown index 40ac733a..d908435a 100644 --- a/pt-br/make-pt.html.markdown +++ b/pt-br/make-pt.html.markdown @@ -1,245 +1,245 @@ ---- -category: tool -tool: make -contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] -translators: - - ["Rogério Gomes Rio", "https://github.com/rogerlista"] -filename: Makefile-pt - -lang: pt-br ---- - -Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas. - -Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux. - -```make - -# Comentários podem ser escritos assim. - -# O arquivo deve ser nomeado Makefile e então pode ser executado como `make `. -# Caso contrário, nós usamos `make -f "nome-do-arquivo" `. - -# Aviso - use somente TABS para identar em Makefiles, nunca espaços! - -#----------------------------------------------------------------------- -# Noções básicas -#----------------------------------------------------------------------- - -# Regras são do formato -# alvo: -# onde os pré-requisitos são opcionais. - -# Uma regra - esta regra só será executada se o arquivo0.txt não existir. -arquivo0.txt: - echo "foo" > arquivo0.txt - # Mesmo os comentários nestas seções da 'receita' são passados ​​para o shell. - # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão. - -# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt. -arquivo1.txt: arquivo0.txt - cat arquivo0.txt > arquivo1.txt - # se as mesmas regras de citação do shell. - @cat arquivo0.txt >> arquivo1.txt - # @ pára o comando de ser ecoado para stdout. - -@echo 'hello' - # - significa que make continuará em caso de erro. - # Experimentar `make arquivo1.txt` na linha de comando. - -# Uma regra pode ter vários alvos e vários pré-requisitos -arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt - touch arquivo2.txt - touch arquivo3.txt - -# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar -# receitas não contam e podem ser usadas para adicionar novas dependências. - -#----------------------------------------------------------------------- -# Alvos falsos -#----------------------------------------------------------------------- - -# Um alvo falso. Qualquer alvo que não seja um arquivo. -# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo. -all: maker process - -# Podemos declarar as coisas fora de ordem. -maker: - touch ex0.txt ex1.txt - -# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome -.PHONY: all maker process -# Este é um alvo especial. Existem vários outros. - -# Uma regra com dependência de um alvo falso sempre será executada -ex0.txt ex1.txt: maker - -# Alvos falsos comuns são: todos fazem instalação limpa ... - -#----------------------------------------------------------------------- -# Variáveis ​​Automáticas e Curingas -#----------------------------------------------------------------------- - -process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos - @echo $^ # $^ é uma variável que contém a lista de pré-requisitos - @echo $@ # imprime o nome do alvo - #(fpara várias regras alvo, $@ é o que causou a execução da regra) - @echo $< # o primeiro pré-requisito listado - @echo $? # somente as dependências que estão desatualizadas - @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal) - #@echo $| # todos os pré-requisitos 'somente pedidos' - -# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los -process: ex1.txt arquivo0.txt -# ex1.txt será encontrado, mas arquivo0.txt será desduplicado. - -#----------------------------------------------------------------------- -# Padrões -#----------------------------------------------------------------------- - -# Pode ensinar make a converter certos arquivos em outros arquivos. - -%.png: %.svg - inkscape --export-png $^ - -# As regras padrões só farão qualquer coisa se decidirem criar o alvo. - -# Os caminhos de diretório são normalmente ignorados quando as regras de -# padrões são correspondentes. Mas make tentará usar a regra mais -# apropriada disponível. -small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ - -# make utilizará a última versão para uma regra de padrão que encontrar. -%.png: %.svg - @echo esta regra é escolhida - -# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo -%.png: %.ps - @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes - -# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe -# como transformar arquivos *.c em arquivos *.o. - -# Makefiles antigos podem usar regras de sufixo em vez de regras padrões -.png.ps: - @echo essa regra é semelhante a uma regra de padrão. - -# make sobre a regra de sufixo -.SUFFIXES: .png - -#----------------------------------------------------------------------- -# Variáveis -#----------------------------------------------------------------------- -# aka. macros - -# As variáveis ​​são basicamente todos os tipos de string - -name = Ted -name2="Sarah" - -echo: - @echo $(name) - @echo ${name2} - @echo $name # Isso não funcionará, tratado como $ (n)ame. - @echo $(name3) # Variáveis ​​desconhecidas são tratadas como strings vazias. - -# Existem 4 lugares para definir variáveis. -# Em ordem de prioridade, do maior para o menor: -# 1: argumentos de linha de comando -# 2: Makefile -# 3: variáveis ​​de ambiente do shell - faça importações automaticamente. -# 4: make tem algumas variáveis ​​predefinidas - -name4 ?= Jean -# Somente defina a variável se a variável de ambiente ainda não estiver definida. - -override name5 = David -# Pára os argumentos da linha de comando de alterar essa variável. - -name4 +=grey -# Anexar valores à variável (inclui um espaço). - -# Valores variáveis ​​específicos de padrões (extensão GNU). -echo: name2 = Sara # Verdadeiro dentro da regra de correspondência - # e também dentro de suas recursivas dependências - # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!) - -# Algumas variáveis ​​definidas automaticamente pelo make -echo_inbuilt: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} - -#----------------------------------------------------------------------- -# Variáveis 2 -#----------------------------------------------------------------------- - -# O primeiro tipo de variáveis ​​é avaliado a cada vez que elas são usadas. -# TIsso pode ser caro, então existe um segundo tipo de variável que é -# avaliado apenas uma vez. (Esta é uma extensão do GNU make) - -var := hello -var2 ::= $(var) hello -#:= e ::= são equivalentes. - -# Essas variáveis ​​são avaliadas procedimentalmente (na ordem em que -# aparecem), quebrando assim o resto da línguagem! - -# Isso não funciona -var3 ::= $(var4) and good luck -var4 ::= good night - -#----------------------------------------------------------------------- -# Funções -#----------------------------------------------------------------------- - -# make tem muitas funções disponíveis. - -sourcefiles = $(wildcard *.c */*.c) -objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) - -# O formato é $(func arg0,arg1,arg2...) - -# Alguns exemplos -ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) - -#----------------------------------------------------------------------- -# Diretivas -#----------------------------------------------------------------------- - -# Inclua outros makefiles, úteis para código específico da plataforma -include foo.mk - -sport = tennis -# Compilação condicional -report: -ifeq ($(sport),tennis) - @echo 'game, set, match' -else - @echo "They think it's all over; it is now" -endif - -# Há também ifneq, ifdef, ifndef - -foo = true - -ifdef $(foo) -bar = 'hello' -endif -``` - -### More Resources - -+ [documentação gnu make](https://www.gnu.org/software/make/manual/) -+ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/) -+ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) +--- +category: tool +tool: make +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] +translators: + - ["Rogério Gomes Rio", "https://github.com/rogerlista"] +filename: Makefile-pt + +lang: pt-br +--- + +Um Makefile define um gráfico de regras para criar um alvo (ou alvos). Sua finalidade é fazer o mínimo de trabalho necessário para atualizar um alvo para a versão mais recente da fonte. Famosamente escrito ao longo de um fim de semana por Stuart Feldman em 1976, ainda é amplamente usada (particularmente no Unix e no Linux) apesar de muitos concorrentes e críticas. + +Existem muitas variedades de make na existência, no entanto, este artigo pressupõe que estamos usando o GNU make, que é o padrão no Linux. + +```make + +# Comentários podem ser escritos assim. + +# O arquivo deve ser nomeado Makefile e então pode ser executado como `make `. +# Caso contrário, nós usamos `make -f "nome-do-arquivo" `. + +# Aviso - use somente TABS para identar em Makefiles, nunca espaços! + +#----------------------------------------------------------------------- +# Noções básicas +#----------------------------------------------------------------------- + +# Regras são do formato +# alvo: +# onde os pré-requisitos são opcionais. + +# Uma regra - esta regra só será executada se o arquivo0.txt não existir. +arquivo0.txt: + echo "foo" > arquivo0.txt + # Mesmo os comentários nestas seções da 'receita' são passados ​​para o shell. + # Experimentar `make arquivo0.txt` or simplyou simplesmente `make` - primeira regra é o padrão. + +# Esta regra só será executada se arquivo0.txt for mais recente que arquivo1.txt. +arquivo1.txt: arquivo0.txt + cat arquivo0.txt > arquivo1.txt + # se as mesmas regras de citação do shell. + @cat arquivo0.txt >> arquivo1.txt + # @ pára o comando de ser ecoado para stdout. + -@echo 'hello' + # - significa que make continuará em caso de erro. + # Experimentar `make arquivo1.txt` na linha de comando. + +# Uma regra pode ter vários alvos e vários pré-requisitos +arquivo2.txt arquivo3.txt: arquivo0.txt arquivo1.txt + touch arquivo2.txt + touch arquivo3.txt + +# Make vai reclamar sobre várias receitas para a mesma regra. Esvaziar +# receitas não contam e podem ser usadas para adicionar novas dependências. + +#----------------------------------------------------------------------- +# Alvos falsos +#----------------------------------------------------------------------- + +# Um alvo falso. Qualquer alvo que não seja um arquivo. +# Ele nunca será atualizado, portanto, o make sempre tentará executá-lo. +all: maker process + +# Podemos declarar as coisas fora de ordem. +maker: + touch ex0.txt ex1.txt + +# Pode evitar quebrar regras falsas quando um arquivo real tem o mesmo nome +.PHONY: all maker process +# Este é um alvo especial. Existem vários outros. + +# Uma regra com dependência de um alvo falso sempre será executada +ex0.txt ex1.txt: maker + +# Alvos falsos comuns são: todos fazem instalação limpa ... + +#----------------------------------------------------------------------- +# Variáveis ​​Automáticas e Curingas +#----------------------------------------------------------------------- + +process: Arquivo*.txt # Usando um curinga para corresponder nomes de arquivos + @echo $^ # $^ é uma variável que contém a lista de pré-requisitos + @echo $@ # imprime o nome do alvo + #(fpara várias regras alvo, $@ é o que causou a execução da regra) + @echo $< # o primeiro pré-requisito listado + @echo $? # somente as dependências que estão desatualizadas + @echo $+ # todas as dependências, incluindo duplicadas (ao contrário do normal) + #@echo $| # todos os pré-requisitos 'somente pedidos' + +# Mesmo se dividirmos as definições de dependência de regra, $^ vai encontrá-los +process: ex1.txt arquivo0.txt +# ex1.txt será encontrado, mas arquivo0.txt será desduplicado. + +#----------------------------------------------------------------------- +# Padrões +#----------------------------------------------------------------------- + +# Pode ensinar make a converter certos arquivos em outros arquivos. + +%.png: %.svg + inkscape --export-png $^ + +# As regras padrões só farão qualquer coisa se decidirem criar o alvo. + +# Os caminhos de diretório são normalmente ignorados quando as regras de +# padrões são correspondentes. Mas make tentará usar a regra mais +# apropriada disponível. +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# make utilizará a última versão para uma regra de padrão que encontrar. +%.png: %.svg + @echo esta regra é escolhida + +# No entanto, o make usará a primeira regra padrão que pode se tornar o alvo +%.png: %.ps + @echo esta regra não é escolhida se *.svg and *.ps estão ambos presentes + +# make já tem algumas regras padrões embutidas. Por exemplo, ele sabe +# como transformar arquivos *.c em arquivos *.o. + +# Makefiles antigos podem usar regras de sufixo em vez de regras padrões +.png.ps: + @echo essa regra é semelhante a uma regra de padrão. + +# make sobre a regra de sufixo +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variáveis +#----------------------------------------------------------------------- +# aka. macros + +# As variáveis ​​são basicamente todos os tipos de string + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Isso não funcionará, tratado como $ (n)ame. + @echo $(name3) # Variáveis ​​desconhecidas são tratadas como strings vazias. + +# Existem 4 lugares para definir variáveis. +# Em ordem de prioridade, do maior para o menor: +# 1: argumentos de linha de comando +# 2: Makefile +# 3: variáveis ​​de ambiente do shell - faça importações automaticamente. +# 4: make tem algumas variáveis ​​predefinidas + +name4 ?= Jean +# Somente defina a variável se a variável de ambiente ainda não estiver definida. + +override name5 = David +# Pára os argumentos da linha de comando de alterar essa variável. + +name4 +=grey +# Anexar valores à variável (inclui um espaço). + +# Valores variáveis ​​específicos de padrões (extensão GNU). +echo: name2 = Sara # Verdadeiro dentro da regra de correspondência + # e também dentro de suas recursivas dependências + # (exceto que ele pode quebrar quando seu gráfico ficar muito complicado!) + +# Algumas variáveis ​​definidas automaticamente pelo make +echo_inbuilt: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variáveis 2 +#----------------------------------------------------------------------- + +# O primeiro tipo de variáveis ​​é avaliado a cada vez que elas são usadas. +# TIsso pode ser caro, então existe um segundo tipo de variável que é +# avaliado apenas uma vez. (Esta é uma extensão do GNU make) + +var := hello +var2 ::= $(var) hello +#:= e ::= são equivalentes. + +# Essas variáveis ​​são avaliadas procedimentalmente (na ordem em que +# aparecem), quebrando assim o resto da línguagem! + +# Isso não funciona +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funções +#----------------------------------------------------------------------- + +# make tem muitas funções disponíveis. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# O formato é $(func arg0,arg1,arg2...) + +# Alguns exemplos +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Diretivas +#----------------------------------------------------------------------- + +# Inclua outros makefiles, úteis para código específico da plataforma +include foo.mk + +sport = tennis +# Compilação condicional +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# Há também ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + +### More Resources + ++ [documentação gnu make](https://www.gnu.org/software/make/manual/) ++ [tutorial de carpintaria de software](http://swcarpentry.github.io/make-novice/) ++ aprenda C da maneira mais difícil [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) diff --git a/ru-ru/asymptotic-notation-ru.html.markdown b/ru-ru/asymptotic-notation-ru.html.markdown index cb276ec1..02ebd205 100644 --- a/ru-ru/asymptotic-notation-ru.html.markdown +++ b/ru-ru/asymptotic-notation-ru.html.markdown @@ -1,225 +1,225 @@ ---- -category: Algorithms & Data Structures -name: Asymptotic Notation -contributors: - - ["Jake Prather", "http://github.com/JakeHP"] - - ["Divay Prakash", "http://github.com/divayprakash"] -translators: - - ["pru-mike", "http://github.com/pru-mike"] -lang: ru-ru ---- - -# О-символика - -## Что это такое? - -О-символика, или асимптотическая запись, — это система символов, позволяющая -оценить время выполнения алгоритма, устанавливая зависимость времени выполнения -от увеличения объёма входных данных. Она также известна как оценка -сложности алгоритмов. Станет ли алгоритм невероятно медленным, когда -объём входных данных увеличится? Будет ли алгоритм выполняться достаточно быстро, -если объём входных данных возрастёт? О-символика позволяет ответить на эти -вопросы. - -## Можно ли по-другому найти ответы на эти вопросы? - -Один способ — это подсчитать число элементарных операций в зависимости от -различных объёмов входных данных. Хотя это и приемлемое решение, тот объём -работы, которого оно потребует, даже для простых алгоритмов делает его -использование неоправданным. - -Другой способ — это измерить, какое время алгоритм потребует для завершения на -различных объёмах входных данных. В то же время, точность и относительность -этого метода (полученное время будет относиться только к той машине, на которой -оно вычислено) зависит от среды выполнения: компьютерного аппаратного -обеспечения, мощности процессора и т.д. - -## Виды О-символики - -В первом разделе этого документа мы определили, что О-символика -позволяет оценивать алгоритмы в зависимости от изменения размера входных -данных. Представим, что алгоритм — это функция f, n — размер входных данных и -f(n) — время выполнения. Тогда для данного алгоритма f с размером входных -данных n получим какое-то результирующее время выполнения f(n). -Из этого можно построить график, где ось y — время выполнения, ось x — размер входных -данных, а точки на графике — это время выполнения для заданного размера входных -данных. - -С помощью О-символики можно оценить функцию или алгоритм -несколькими различными способами. Например, можно оценить алгоритм исходя -из нижней оценки, верхней оценки, тождественной оценки. Чаще всего встречается -анализ на основе верхней оценки. Как правило, не используется нижняя оценка, -потому что она не подходит под планируемые условия. Отличный пример — алгоритмы -сортировки, особенно добавление элементов в древовидную структуру. Нижняя оценка -большинства таких алгоритмов может быть дана как одна операция. В то время как в -большинстве случаев добавляемые элементы должны быть отсортированы -соответствующим образом при помощи дерева, что может потребовать обхода целой -ветви. Это и есть худший случай, для которого планируется верхняя оценка. - -### Виды функций, пределы и упрощения - -``` -Логарифмическая функция — log n -Линейная функция — an + b -Квадратичная функция — an^2 + bn +c -Степенная функция — an^z + . . . + an^2 + a*n^1 + a*n^0, где z — константа -Показательная функция — a^n, где a — константа -``` - -Приведены несколько базовых функций, используемых при определении сложности в -различных оценках. Список начинается с самой медленно возрастающей функции -(логарифм, наиболее быстрое время выполнения) и следует до самой быстро -возрастающей функции (экспонента, самое медленное время выполнения). Отметим, -что в то время, как «n», или размер входных данных, возрастает в каждой из этих функций, -результат намного быстрее возрастает в квадратичной, степенной -и показательной по сравнению с логарифмической и линейной. - -Крайне важно понимать, что при использовании описанной далее нотации необходимо -использовать упрощённые выражения. -Это означает, что необходимо отбрасывать константы и слагаемые младших порядков, -потому что если размер входных данных (n в функции f(n) нашего примера) -увеличивается до бесконечности (в пределе), тогда слагаемые младших порядков -и константы становятся пренебрежительно малыми. Таким образом, если есть -константа, например, размера 2^9001 или любого другого невообразимого размера, -надо понимать, что её упрощение внесёт значительные искажения в точность -оценки. - -Т.к. нам нужны упрощённые выражения, немного скорректируем нашу таблицу... - -``` -Логарифм — log n -Линейная функция — n -Квадратичная функция — n^2 -Степенная функция — n^z, где z — константа -Показательная функция — a^n, где a — константа -``` - -### О Большое -О Большое, записывается как **О**, — это асимптотическая запись для оценки худшего -случая, или для ограничения заданной функции сверху. Это позволяет сделать -_**асимптотическую оценку верхней границы**_ скорости роста времени выполнения -алгоритма. Пусть `f(n)` — время выполнения алгоритма, а `g(n)` — заданная временная -сложность, которая проверяется для алгоритма. Тогда `f(n)` — это O(g(n)), если -существуют действительные константы c (c > 0) и n0, такие, -что `f(n)` <= `c g(n)` выполняется для всех n, начиная с некоторого n0 (n > n0). - -*Пример 1* - -``` -f(n) = 3log n + 100 -g(n) = log n -``` - -Является ли `f(n)` O(g(n))? -Является ли `3 log n + 100` O(log n)? -Посмотрим на определение О Большого: - -``` -3log n + 100 <= c * log n -``` - -Существуют ли константы c и n0, такие, что выражение верно для всех n > n0? - -``` -3log n + 100 <= 150 * log n, n > 2 (не определенно для n = 1) -``` - -Да! По определению О Большого `f(n)` является O(g(n)). - -*Пример 2* - -``` -f(n) = 3 * n^2 -g(n) = n -``` - -Является ли `f(n)` O(g(n))? -Является ли `3 * n^2` O(n)? -Посмотрим на определение О Большого: - -``` -3 * n^2 <= c * n -``` - -Существуют ли константы c и n0, такие, что выражение верно для всех n > n0? -Нет, не существуют. `f(n)` НЕ ЯВЛЯЕТСЯ O(g(n)). - -### Омега Большое -Омега Большое, записывается как **Ω**, — это асимптотическая запись для оценки -лучшего случая, или для ограничения заданной функции снизу. Это позволяет сделать -_**асимптотическую оценку нижней границы**_ скорости роста времени выполнения -алгоритма. - -`f(n)` является Ω(g(n)), если существуют действительные константы -c (c > 0) и n0 (n0 > 0), такие, что `f(n)` >= `c g(n)` для всех n > n0. - -### Примечание - -Асимптотические оценки, сделанные при помощи О Большого и Омега Большого, могут -как являться, так и не являться точными. Для того чтобы обозначить, что границы не -являются асимптотически точными, используются записи О Малое и Омега Малое. - -### О Малое -O Малое, записывается как **о**, — это асимптотическая запись для оценки верхней -границы времени выполнения алгоритма при условии, что граница не является -асимптотически точной. - -`f(n)` является o(g(n)), если можно подобрать такие действительные константы, -что для всех c (c > 0) найдётся n0 (n0 > 0), так -что `f(n)` < `c g(n)` выполняется для всех n (n > n0). - -Определения О-символики для О Большого и О Малого похожи. Главное отличие в том, -что если f(n) = O(g(n)), тогда условие f(n) <= c g(n) выполняется, если _**существует**_ -константа c > 0, но если f(n) = o(g(n)), тогда условие f(n) < c g(n) выполняется -для _**всех**_ констант c > 0. - -### Омега Малое -Омега Малое, записывается как **ω**, — это асимптотическая запись для оценки -верхней границы времени выполнения алгоритма при условии, что граница не является -асимптотически точной. - -`f(n)` является ω(g(n)), если можно подобрать такие действительные константы, -что для всех c (c > 0) найдётся n0 (n0 > 0), так -что `f(n)` > `c g(n)` выполняется для всех n (n > n0). - -Определения Ω-символики и ω-символики похожи. Главное отличие в том, что -если f(n) = Ω(g(n)), тогда условие f(n) >= c g(n) выполняется, если _**существует**_ -константа c > 0, но если f(n) = ω(g(n)), тогда условие f(n) > c g(n) -выполняется для _**всех**_ констант c > 0. - -### Тета -Тета, записывается как **Θ**, — это асимптотическая запись для оценки -_***асимптотически точной границы***_ времени выполнения алгоритма. - -`f(n)` является Θ(g(n)), если для некоторых действительных -констант c1, c2 и n0 (c1 > 0, c2 > 0, n0 > 0) -`c1 g(n)` < `f(n)` < `c2 g(n)` для всех n (n > n0). - -∴ `f(n)` является Θ(g(n)) означает, что `f(n)` является O(g(n)) -и `f(n)` является Ω(g(n)). - -О Большое — основной инструмент для анализа сложности алгоритмов. -Также см. примеры по ссылкам. - -### Заключение -Такую тему сложно изложить кратко, поэтому обязательно стоит пройти по ссылкам и -посмотреть дополнительную литературу. В ней даётся более глубокое описание с -определениями и примерами. - - -## Дополнительная литература - -* [Алгоритмы на Java](https://www.ozon.ru/context/detail/id/18319699/) -* [Алгоритмы. Построение и анализ](https://www.ozon.ru/context/detail/id/33769775/) - -## Ссылки - -* [Оценки времени исполнения. Символ O()](http://algolist.manual.ru/misc/o_n.php) -* [Асимптотический анализ и теория вероятностей](https://www.lektorium.tv/course/22903) - -## Ссылки (англ.) - -* [Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1) -* [Cheatsheet 1](http://web.mit.edu/broder/Public/asymptotics-cheatsheet.pdf) -* [Cheatsheet 2](http://bigocheatsheet.com/) - +--- +category: Algorithms & Data Structures +name: Asymptotic Notation +contributors: + - ["Jake Prather", "http://github.com/JakeHP"] + - ["Divay Prakash", "http://github.com/divayprakash"] +translators: + - ["pru-mike", "http://github.com/pru-mike"] +lang: ru-ru +--- + +# О-символика + +## Что это такое? + +О-символика, или асимптотическая запись, — это система символов, позволяющая +оценить время выполнения алгоритма, устанавливая зависимость времени выполнения +от увеличения объёма входных данных. Она также известна как оценка +сложности алгоритмов. Станет ли алгоритм невероятно медленным, когда +объём входных данных увеличится? Будет ли алгоритм выполняться достаточно быстро, +если объём входных данных возрастёт? О-символика позволяет ответить на эти +вопросы. + +## Можно ли по-другому найти ответы на эти вопросы? + +Один способ — это подсчитать число элементарных операций в зависимости от +различных объёмов входных данных. Хотя это и приемлемое решение, тот объём +работы, которого оно потребует, даже для простых алгоритмов делает его +использование неоправданным. + +Другой способ — это измерить, какое время алгоритм потребует для завершения на +различных объёмах входных данных. В то же время, точность и относительность +этого метода (полученное время будет относиться только к той машине, на которой +оно вычислено) зависит от среды выполнения: компьютерного аппаратного +обеспечения, мощности процессора и т.д. + +## Виды О-символики + +В первом разделе этого документа мы определили, что О-символика +позволяет оценивать алгоритмы в зависимости от изменения размера входных +данных. Представим, что алгоритм — это функция f, n — размер входных данных и +f(n) — время выполнения. Тогда для данного алгоритма f с размером входных +данных n получим какое-то результирующее время выполнения f(n). +Из этого можно построить график, где ось y — время выполнения, ось x — размер входных +данных, а точки на графике — это время выполнения для заданного размера входных +данных. + +С помощью О-символики можно оценить функцию или алгоритм +несколькими различными способами. Например, можно оценить алгоритм исходя +из нижней оценки, верхней оценки, тождественной оценки. Чаще всего встречается +анализ на основе верхней оценки. Как правило, не используется нижняя оценка, +потому что она не подходит под планируемые условия. Отличный пример — алгоритмы +сортировки, особенно добавление элементов в древовидную структуру. Нижняя оценка +большинства таких алгоритмов может быть дана как одна операция. В то время как в +большинстве случаев добавляемые элементы должны быть отсортированы +соответствующим образом при помощи дерева, что может потребовать обхода целой +ветви. Это и есть худший случай, для которого планируется верхняя оценка. + +### Виды функций, пределы и упрощения + +``` +Логарифмическая функция — log n +Линейная функция — an + b +Квадратичная функция — an^2 + bn +c +Степенная функция — an^z + . . . + an^2 + a*n^1 + a*n^0, где z — константа +Показательная функция — a^n, где a — константа +``` + +Приведены несколько базовых функций, используемых при определении сложности в +различных оценках. Список начинается с самой медленно возрастающей функции +(логарифм, наиболее быстрое время выполнения) и следует до самой быстро +возрастающей функции (экспонента, самое медленное время выполнения). Отметим, +что в то время, как «n», или размер входных данных, возрастает в каждой из этих функций, +результат намного быстрее возрастает в квадратичной, степенной +и показательной по сравнению с логарифмической и линейной. + +Крайне важно понимать, что при использовании описанной далее нотации необходимо +использовать упрощённые выражения. +Это означает, что необходимо отбрасывать константы и слагаемые младших порядков, +потому что если размер входных данных (n в функции f(n) нашего примера) +увеличивается до бесконечности (в пределе), тогда слагаемые младших порядков +и константы становятся пренебрежительно малыми. Таким образом, если есть +константа, например, размера 2^9001 или любого другого невообразимого размера, +надо понимать, что её упрощение внесёт значительные искажения в точность +оценки. + +Т.к. нам нужны упрощённые выражения, немного скорректируем нашу таблицу... + +``` +Логарифм — log n +Линейная функция — n +Квадратичная функция — n^2 +Степенная функция — n^z, где z — константа +Показательная функция — a^n, где a — константа +``` + +### О Большое +О Большое, записывается как **О**, — это асимптотическая запись для оценки худшего +случая, или для ограничения заданной функции сверху. Это позволяет сделать +_**асимптотическую оценку верхней границы**_ скорости роста времени выполнения +алгоритма. Пусть `f(n)` — время выполнения алгоритма, а `g(n)` — заданная временная +сложность, которая проверяется для алгоритма. Тогда `f(n)` — это O(g(n)), если +существуют действительные константы c (c > 0) и n0, такие, +что `f(n)` <= `c g(n)` выполняется для всех n, начиная с некоторого n0 (n > n0). + +*Пример 1* + +``` +f(n) = 3log n + 100 +g(n) = log n +``` + +Является ли `f(n)` O(g(n))? +Является ли `3 log n + 100` O(log n)? +Посмотрим на определение О Большого: + +``` +3log n + 100 <= c * log n +``` + +Существуют ли константы c и n0, такие, что выражение верно для всех n > n0? + +``` +3log n + 100 <= 150 * log n, n > 2 (не определенно для n = 1) +``` + +Да! По определению О Большого `f(n)` является O(g(n)). + +*Пример 2* + +``` +f(n) = 3 * n^2 +g(n) = n +``` + +Является ли `f(n)` O(g(n))? +Является ли `3 * n^2` O(n)? +Посмотрим на определение О Большого: + +``` +3 * n^2 <= c * n +``` + +Существуют ли константы c и n0, такие, что выражение верно для всех n > n0? +Нет, не существуют. `f(n)` НЕ ЯВЛЯЕТСЯ O(g(n)). + +### Омега Большое +Омега Большое, записывается как **Ω**, — это асимптотическая запись для оценки +лучшего случая, или для ограничения заданной функции снизу. Это позволяет сделать +_**асимптотическую оценку нижней границы**_ скорости роста времени выполнения +алгоритма. + +`f(n)` является Ω(g(n)), если существуют действительные константы +c (c > 0) и n0 (n0 > 0), такие, что `f(n)` >= `c g(n)` для всех n > n0. + +### Примечание + +Асимптотические оценки, сделанные при помощи О Большого и Омега Большого, могут +как являться, так и не являться точными. Для того чтобы обозначить, что границы не +являются асимптотически точными, используются записи О Малое и Омега Малое. + +### О Малое +O Малое, записывается как **о**, — это асимптотическая запись для оценки верхней +границы времени выполнения алгоритма при условии, что граница не является +асимптотически точной. + +`f(n)` является o(g(n)), если можно подобрать такие действительные константы, +что для всех c (c > 0) найдётся n0 (n0 > 0), так +что `f(n)` < `c g(n)` выполняется для всех n (n > n0). + +Определения О-символики для О Большого и О Малого похожи. Главное отличие в том, +что если f(n) = O(g(n)), тогда условие f(n) <= c g(n) выполняется, если _**существует**_ +константа c > 0, но если f(n) = o(g(n)), тогда условие f(n) < c g(n) выполняется +для _**всех**_ констант c > 0. + +### Омега Малое +Омега Малое, записывается как **ω**, — это асимптотическая запись для оценки +верхней границы времени выполнения алгоритма при условии, что граница не является +асимптотически точной. + +`f(n)` является ω(g(n)), если можно подобрать такие действительные константы, +что для всех c (c > 0) найдётся n0 (n0 > 0), так +что `f(n)` > `c g(n)` выполняется для всех n (n > n0). + +Определения Ω-символики и ω-символики похожи. Главное отличие в том, что +если f(n) = Ω(g(n)), тогда условие f(n) >= c g(n) выполняется, если _**существует**_ +константа c > 0, но если f(n) = ω(g(n)), тогда условие f(n) > c g(n) +выполняется для _**всех**_ констант c > 0. + +### Тета +Тета, записывается как **Θ**, — это асимптотическая запись для оценки +_***асимптотически точной границы***_ времени выполнения алгоритма. + +`f(n)` является Θ(g(n)), если для некоторых действительных +констант c1, c2 и n0 (c1 > 0, c2 > 0, n0 > 0) +`c1 g(n)` < `f(n)` < `c2 g(n)` для всех n (n > n0). + +∴ `f(n)` является Θ(g(n)) означает, что `f(n)` является O(g(n)) +и `f(n)` является Ω(g(n)). + +О Большое — основной инструмент для анализа сложности алгоритмов. +Также см. примеры по ссылкам. + +### Заключение +Такую тему сложно изложить кратко, поэтому обязательно стоит пройти по ссылкам и +посмотреть дополнительную литературу. В ней даётся более глубокое описание с +определениями и примерами. + + +## Дополнительная литература + +* [Алгоритмы на Java](https://www.ozon.ru/context/detail/id/18319699/) +* [Алгоритмы. Построение и анализ](https://www.ozon.ru/context/detail/id/33769775/) + +## Ссылки + +* [Оценки времени исполнения. Символ O()](http://algolist.manual.ru/misc/o_n.php) +* [Асимптотический анализ и теория вероятностей](https://www.lektorium.tv/course/22903) + +## Ссылки (англ.) + +* [Algorithms, Part I](https://www.coursera.org/learn/algorithms-part1) +* [Cheatsheet 1](http://web.mit.edu/broder/Public/asymptotics-cheatsheet.pdf) +* [Cheatsheet 2](http://bigocheatsheet.com/) + diff --git a/tr-tr/sql-tr.html.markdown b/tr-tr/sql-tr.html.markdown index 54007d32..2e91e9f8 100644 --- a/tr-tr/sql-tr.html.markdown +++ b/tr-tr/sql-tr.html.markdown @@ -1,125 +1,125 @@ ---- -language: SQL -contributors: - - ["Metin Yalçınkaya", "https://github.com/mtnylnky"] -lang: tr-tr -filename: learnsql-tr.sql ---- - - -```sql --- Yorumlar iki tire ile başlar - --- KISITLAR -Not null -- Bir kolon asla boş olamaz -default -- Boş olan yerlere varsayılan bir değer atar -unique -- Bir kolondaki tüm değerlerin farklı olması kısıtlaması -primary key -- Bir tablodaki her veri için kimlik bilgisi niteliğindedir -check -- Bir kolondaki değerlerin belli bir kısıtlamayı sağlamasını sağlar - --- Tablo oluşturulur -CREATE TABLE tablo1 (); - --- Tabloyu içerisinde kolonlar ile oluşturma -CREATE TABLE tablo1(id INTEGER PRIMARY KEY NOT NULL UNIQUE, ad TEXT, soyad TEXT, yas INTEGER); - --- TABLO varlığını kontrol eder -.table - --- Veri tabanında olan bütün tabloları görüntüler. -.schema - --- Satır ekle -INSERT INTO tablo1 ( ad, soyad) VALUES ("Deger1","Deger2"); - --- Veritabanında tablo üzerindeki verileri görüntüle --- Sadece 'ad' gibi sınırlı bir veri için -SELECT ad FROM tablo1; --- Bütün veriler için -SELECT * FROM tablo1; - --- Veri güncelleme -UPDATE tablo1 SET ad = "deger1-2"; WHERE name = "Deger1"; - --- Satır sil -DELETE FROM tablo1 WHERE id = 1; -DELETE FROM tablo1 WHERE ad = "Deger1" OR ad = "Deger2"; - --- Tabloya sonradan kolon ekleme -ALTER TABLE tablo1 ADD COLUMN email TEXT; - --- Tablodaki kolon adı değiştirme -EXEC sp_rename ' tablo1.[ad]', Ad, 'COLUMN'; - --- Tablo adı değiştirme -ALTER TABLE table1 RENAME TO Table1; - --- Tabloyu silme -DROP TABLE Table1; - --- BİR TABLOYU BAŞKA TABLO KULLANARAK DOLDURMAK -INSERT INTO Tablo2 SELECT id,ad, soyad, email from Tablo1; - --- LIKE KOMUTU --- Belirli bir kritere göre arama yaparken kullanılır --- Adı 'A' ile başlayan veriler -SELECT * FROM tablo1 WHERE adi LIKE "A%"; --- İçinde 'A' olan veriler -SELECT * FROM tablo1 WHERE adi LIKE "%A%"; - --- LIMIT KOMUTU --- Gösterilen satır sayısını sınırlamak için -SELECT * FROM Tablo1 LIMIT 6; --- Gösterilen satırları belirli bir noktadan başlamak üzere sınırlamak için -SELECT * FROM Tablo1 LIMIT 6 OFFSET 3; - --- ORDER BY KOMUTU --- Herhangi bir kolona göre gösterilen değerleri azalan veya artan şekilde sıralamak için -SELECT kolon FROM tablo1 WHERE yas ORDER BY column1, column2, .. columnN] [ASC | DESC]; -SELECT * FROM Tablo1 ORDER BY yas ASC -SELECT * FROM Tablo1 ORDER BY yas DESC - --- DISTINCT ANAHTAR SÖZCÜĞÜ --- Bu anahtar sözcükle sadece farklı değerler gösterilir. -SELECT DISTINCT yas FROM tablo1; - --- JOIN KOMUTU --- CROSS JOIN --- Cross join bir tablodaki her satırı ikinci tablodaki bir satır ile eşleştirmek için kulanılır. --- Eğer birinci tabloda x satır ikinci tabloda y satır varsa sonuçta x*y satır olur. -SELECT ... FROM table1 CROSS JOIN table2 … -SELECT ad, yas FROM Tablo1 CROSS JOIN Tablo2; - --- INNER JOIN --- Inner join iki tablodaki ortak kolon değerlerini kullanarak bir sonuç üretir. -SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression … -SELECT ad, yas FROM Tablo1 INNER JOIN Tablo2 ON Tablo1.ad = Tablo2.soyad; - --- OUTER JOIN --- Outer join iki tablodaki ortak kolon değerlerinin dışında kalanları kullanarak bir sonuç üretir. -SELECT isci_num, isim, dept FROM Tablo1 LEFT OUTER JOIN Tablo2 ON Tablo1.id = Tablo2.isci_num; - --- ÇEKİRDEK FONKSİYONLAR -COUNT -- Sayma -AVG -- Ortalama -ABS -- Mutlak değer -SUM -- Toplam -RANDOM -- Rastgele -ROUND -- Yuvarlama -MAX -- Maksimim -MIN -- Minimum -UPPER -- Büyük Harf -LOWER -- Küçük Harf -LENGTH -- Uzunluk -CURRENT_TIMESTAMP -- Zaman - -SELECT max(yas) FROM Table1; -SELECT min(yas) FROM Table1; -SELECT avg(yas) FROM Table1; -SELECT * From Table1 WHERE yas ==18; -SELECT sum(yas) FROM Table1; -SELECT random() AS Random; -SELECT upper(ad) FROM Table1; -SELECT lower(ad) FROM Table1; -SELECT ad, length(ad) FROM Table1; +--- +language: SQL +contributors: + - ["Metin Yalçınkaya", "https://github.com/mtnylnky"] +lang: tr-tr +filename: learnsql-tr.sql +--- + + +```sql +-- Yorumlar iki tire ile başlar + +-- KISITLAR +Not null -- Bir kolon asla boş olamaz +default -- Boş olan yerlere varsayılan bir değer atar +unique -- Bir kolondaki tüm değerlerin farklı olması kısıtlaması +primary key -- Bir tablodaki her veri için kimlik bilgisi niteliğindedir +check -- Bir kolondaki değerlerin belli bir kısıtlamayı sağlamasını sağlar + +-- Tablo oluşturulur +CREATE TABLE tablo1 (); + +-- Tabloyu içerisinde kolonlar ile oluşturma +CREATE TABLE tablo1(id INTEGER PRIMARY KEY NOT NULL UNIQUE, ad TEXT, soyad TEXT, yas INTEGER); + +-- TABLO varlığını kontrol eder +.table + +-- Veri tabanında olan bütün tabloları görüntüler. +.schema + +-- Satır ekle +INSERT INTO tablo1 ( ad, soyad) VALUES ("Deger1","Deger2"); + +-- Veritabanında tablo üzerindeki verileri görüntüle +-- Sadece 'ad' gibi sınırlı bir veri için +SELECT ad FROM tablo1; +-- Bütün veriler için +SELECT * FROM tablo1; + +-- Veri güncelleme +UPDATE tablo1 SET ad = "deger1-2"; WHERE name = "Deger1"; + +-- Satır sil +DELETE FROM tablo1 WHERE id = 1; +DELETE FROM tablo1 WHERE ad = "Deger1" OR ad = "Deger2"; + +-- Tabloya sonradan kolon ekleme +ALTER TABLE tablo1 ADD COLUMN email TEXT; + +-- Tablodaki kolon adı değiştirme +EXEC sp_rename ' tablo1.[ad]', Ad, 'COLUMN'; + +-- Tablo adı değiştirme +ALTER TABLE table1 RENAME TO Table1; + +-- Tabloyu silme +DROP TABLE Table1; + +-- BİR TABLOYU BAŞKA TABLO KULLANARAK DOLDURMAK +INSERT INTO Tablo2 SELECT id,ad, soyad, email from Tablo1; + +-- LIKE KOMUTU +-- Belirli bir kritere göre arama yaparken kullanılır +-- Adı 'A' ile başlayan veriler +SELECT * FROM tablo1 WHERE adi LIKE "A%"; +-- İçinde 'A' olan veriler +SELECT * FROM tablo1 WHERE adi LIKE "%A%"; + +-- LIMIT KOMUTU +-- Gösterilen satır sayısını sınırlamak için +SELECT * FROM Tablo1 LIMIT 6; +-- Gösterilen satırları belirli bir noktadan başlamak üzere sınırlamak için +SELECT * FROM Tablo1 LIMIT 6 OFFSET 3; + +-- ORDER BY KOMUTU +-- Herhangi bir kolona göre gösterilen değerleri azalan veya artan şekilde sıralamak için +SELECT kolon FROM tablo1 WHERE yas ORDER BY column1, column2, .. columnN] [ASC | DESC]; +SELECT * FROM Tablo1 ORDER BY yas ASC +SELECT * FROM Tablo1 ORDER BY yas DESC + +-- DISTINCT ANAHTAR SÖZCÜĞÜ +-- Bu anahtar sözcükle sadece farklı değerler gösterilir. +SELECT DISTINCT yas FROM tablo1; + +-- JOIN KOMUTU +-- CROSS JOIN +-- Cross join bir tablodaki her satırı ikinci tablodaki bir satır ile eşleştirmek için kulanılır. +-- Eğer birinci tabloda x satır ikinci tabloda y satır varsa sonuçta x*y satır olur. +SELECT ... FROM table1 CROSS JOIN table2 … +SELECT ad, yas FROM Tablo1 CROSS JOIN Tablo2; + +-- INNER JOIN +-- Inner join iki tablodaki ortak kolon değerlerini kullanarak bir sonuç üretir. +SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression … +SELECT ad, yas FROM Tablo1 INNER JOIN Tablo2 ON Tablo1.ad = Tablo2.soyad; + +-- OUTER JOIN +-- Outer join iki tablodaki ortak kolon değerlerinin dışında kalanları kullanarak bir sonuç üretir. +SELECT isci_num, isim, dept FROM Tablo1 LEFT OUTER JOIN Tablo2 ON Tablo1.id = Tablo2.isci_num; + +-- ÇEKİRDEK FONKSİYONLAR +COUNT -- Sayma +AVG -- Ortalama +ABS -- Mutlak değer +SUM -- Toplam +RANDOM -- Rastgele +ROUND -- Yuvarlama +MAX -- Maksimim +MIN -- Minimum +UPPER -- Büyük Harf +LOWER -- Küçük Harf +LENGTH -- Uzunluk +CURRENT_TIMESTAMP -- Zaman + +SELECT max(yas) FROM Table1; +SELECT min(yas) FROM Table1; +SELECT avg(yas) FROM Table1; +SELECT * From Table1 WHERE yas ==18; +SELECT sum(yas) FROM Table1; +SELECT random() AS Random; +SELECT upper(ad) FROM Table1; +SELECT lower(ad) FROM Table1; +SELECT ad, length(ad) FROM Table1; ``` \ No newline at end of file diff --git a/vi-vn/git-vi.html.markdown b/vi-vn/git-vi.html.markdown index f5454ebf..47485bd9 100644 --- a/vi-vn/git-vi.html.markdown +++ b/vi-vn/git-vi.html.markdown @@ -1,328 +1,328 @@ ---- -category: tool -tool: git -contributors: +--- +category: tool +tool: git +contributors: - ["Jake Prather", "http://github.com/JakeHP"] - - ["Vinh Nguyen", "https://twitter.com/vinhnx"] -filename: LearnGit-vi.txt -lang: vi-vn ---- - -Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system). - -Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, và nó hoạt động -với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và -quản lý mã nguồn của bạn. - -## Khái Niệm Versioning - -### Version Control là gì? - -Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian. - -### So sánh giữa Centralized Versioning và Distributed Versioning - -* Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin. -* Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất. -* Các hệ phân tán không có cấu trúc định sẵn. Bạn có thể thay đổi một kiểu SVN, hệ phân tán, với git. - -[Thông tin thêm](http://git-scm.com/book/en/Getting-Started-About-Version-Control) - -### Tại Sao Dùng Git? - -* Có thể hoạt động offline. -* Cộng tác với nhau rất dễ dàng! -* Phân nhánh dễ dàng! -* Trộn (Merging) -* Git nhanh. -* Git linh hoạt. - -## Kiến Trúc Git - - -### Repository - -Một nhóm các tập tin, thư mục, các ghi chép trong quá khứ, commit, và heads. Tưởng tượng nó như là một cấu trúc dữ liệu mã nguồn, -với thuộc tính mà một "nhân tố" mã nguồn cho bạn quyền truy cập đến lịch sử sửa đổi, và một số thứ khác. - -Một git repository bao gồm thư mục .git & tree đang làm việc. - -### Thư mục .git (thành phần của một repository) - -Thư mục .git chứa tất cả các cấu hình, log, nhánh, HEAD, và hơn nữa. -[Danh Sách Chi Tiết.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) - -### Tree Đang Làm (thành phần của một repository) - -Đây cơ bản là các thư mục và tập tin trong repository của bạn. Nó thường được tham chiếu -thư mục đang làm việc của bạn - -### Chỉ mục (thành phần của một thư mục .git) - -Chỉ mục của là một staging area trong git. Nó đơn giản là một lớp riêng biệt với tree đang làm việc của bạn -từ Git repository. Điều này cho nhà phát triền nhiều lựa chọn hơn trong việc xem xét những gì được gửi đến Git -repository. - -### Commit - -Một git commit là một snapshot của một nhóm các thay đổi, hoặc các thao tác Working Tree của bạn. -Ví dụ, nếu bạn thêm 5 tập tin, và xóa 2 tập tin khác, những thay đổi này sẽ được chứa trong -một commit (hoặc snapshot). Commit này có thể được đẩy đến các repo khác, hoặc không! - -### Nhánh - -Nhánh thực chất là một con trỏ đến commit mới nhất mà bạn vừa thực hiện. Khi bạn commit, -con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nhất. - -### HEAD và head (thành phần của thư mục .git) - -HEAD là một con trỏ đến branch hiện tại. Một repo chỉ có một HEAD *đang hoạt động*. -head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head. - -### Các Tài Nguyên Mang Tính Khái Niệm - -* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) -* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) - - -## Các Lệnh - - -### init - -Tạo một repo Git rỗng. Các cài đặt, thông tin lưu trữ... của Git -được lưu ở một thư mục tên là ".git". - -```bash -$ git init -``` - -### config - -Để chỉnh tùy chọn. Bất kể là cho repo, hay cho hệ thống, hay điều chỉnh -toàn cục (global) - - - -```bash -# In Ra & Và Gán Một Số Biến Tùy Chỉnh Cơ Bản (Toàn cục - Global) -$ git config --global user.email -$ git config --global user.name - -$ git config --global user.email "MyEmail@Zoho.com" -$ git config --global user.name "My Name" -``` - -[Tìm hiểu thêm về git config.](http://git-scm.com/docs/git-config) - -### help - -Để cho bạn lối truy cập nhanh đến một chỉ dẫn cực kỳ chi tiết của từng lệnh. Hoặc chỉ để -nhắc bạn một số cú pháp. - -```bash -# Xem nhanh các lệnh có sẵn -$ git help - -# Xem tất các các lệnh -$ git help -a - -# Lệnh help riêng biệt - tài liệu người dùng -# git help -$ git help add -$ git help commit -$ git help init -``` - -### status - -Để hiển thị sự khác nhau giữa tập tin index (cơ bản là repo đang làm việc) và HEAD commit -hiện tại. - - -```bash -# Sẽ hiển thị nhánh, các tập tin chưa track (chưa commit), các thay đổi và những khác biệt khác -$ git status - -# Để xem các "tid bits" về git status -$ git help status -``` - -### add - -Để thêm các tập vào tree/thư mục/repo hiện tại. Nếu bạn không `git add` các tập tin mới đến -tree/thư mục hiện tại, chúng sẽ không được kèm theo trong các commit! - -```bash -# thêm một file vào thư mục hiện tại -$ git add HelloWorld.java - -# thêm một file vào một thư mục khác -$ git add /path/to/file/HelloWorld.c - -# Hỗ trợ Regular Expression! -$ git add ./*.java -``` - -### branch - -Quản lý nhánh (branch). Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này. - -```bash -# liệt kê các branch đang có và ở remote -$ git branch -a - -# tạo branch mới -$ git branch myNewBranch - -# xóa một branch -$ git branch -d myBranch - -# đặt tên lại một branch -# git branch -m -$ git branch -m myBranchName myNewBranchName - -# chỉnh sửa diễn giải của một branch -$ git branch myBranchName --edit-description -``` - -### checkout - -Cập nhật tất cả các file trong tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể. - -```bash -# Checkout (chuyển) một repo - mặc định là nhánh master -$ git checkout -# Checkout một nhánh cụ thể -$ git checkout branchName -# Tạo một nhánh mới và chuyển đến nó, tương tự: "git branch ; git checkout " -$ git checkout -b newBranch -``` - -### clone - -Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm -các branch có remote-tracking cho mỗi branch trong một repo được nhân bản, mà -cho phép bạn push đến một remote branch. - -```bash -# Nhân bản learnxinyminutes-docs -$ git clone https://github.com/adambard/learnxinyminutes-docs.git -``` - -### commit - -Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một ghi chú tạo ra bởi người dùng. - -```bash -# commit với một ghi chú -$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" -``` - -### diff - -Hiển thị sự khác biệt giữa một file trong thư mục hiện tại, index và commits. - -```bash -# Hiển thị sự khác biệt giữa thư mục hiện tại và index -$ git diff - -# Hiển thị khác biệt giữa index và commit mới nhất. -$ git diff --cached - -# Hiển thị khác biệt giữa thư mục đang làm việc và commit mới nhất -$ git diff HEAD -``` - -### grep - -Cho phép bạn tìm kiếm nhanh một repo. - -Các tinh chỉnh tùy chọn: - -```bash -# Cảm ơn Travis Jeffery vì những lệnh này -# Đặt số của dòng được hiển thị trong kết quả tìm kiếm grep -$ git config --global grep.lineNumber true - -# Làm cho kết quả tìm kiếm dễ đọc hơn, bao gồm cả gom nhóm -$ git config --global alias.g "grep --break --heading --line-number" -``` - -```bash -# Tìm "variableName" trong tất cả các file Java -$ git grep 'variableName' -- '*.java' - -# Tìm một dòng mà có chứa "arrayListName" và, "add" hoặc "remove" -$ git grep -e 'arrayListName' --and \( -e add -e remove \) -``` - -Google để xem thêm các ví dụ -[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) - -### log - -Hiển thị các commit đến repo. - -```bash -# Hiện tất cả các commit -$ git log - -# Hiện X commit -$ git log -n 10 - -# Chỉ hiện các commit đã merge merge commits -$ git log --merges -``` - -### merge - -"Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại. - -```bash -# Merge branch cụ thể vào branch hiện tại. -$ git merge branchName - -# Luôn khởi tạo một merge commit khi trộn (merge) -$ git merge --no-ff branchName -``` - -### mv - -Đặt lại tên hoặc di chuyển một file - -```bash -# Đặt lại tên một file -$ git mv HelloWorld.c HelloNewWorld.c - -# Di chuyển một file -$ git mv HelloWorld.c ./new/path/HelloWorld.c - -# Buộc đặt lại tên hoặc di chuyển -# "existingFile" đã tồn tại trong thự mục, sẽ bị ghi đè -$ git mv -f myFile existingFile -``` - -### pull - -Pull về từ một repo và merge nó vào branch khác. - -```bash -# Cập nhật repo local của bạn, bằng cách merge các thay đổi mới -# từ remote "origin" và nhánh "master". -# git pull -# git pull => hoàn toàn mặc định như => git pull origin master -$ git pull origin master - -# Merge các thay đổi từ remote branch và rebase -# các commit trong branch lên trên local repo, như sau: "git pull , git rebase " -$ git pull origin master --rebase -``` - -### push - -push và merge các thay đổi từ một branch đến một remote & branch. - + - ["Vinh Nguyen", "https://twitter.com/vinhnx"] +filename: LearnGit-vi.txt +lang: vi-vn +--- + +Git là một hệ quản lý mã nguồn và phiên bản phân tán (distributed version control and source code management system). + +Nó làm được điều này là do một loạt các snapshot từ đề án của bạn, và nó hoạt động +với các snapshot đó để cung cấp cho bạn với chức năng đến phiên bản và +quản lý mã nguồn của bạn. + +## Khái Niệm Versioning + +### Version Control là gì? + +Version Control là một hệ thống ghi lại những thay đổi ở một tập tin, hay một nhóm các tập tin, theo thời gian. + +### So sánh giữa Centralized Versioning và Distributed Versioning + +* Quản lý phiên bản tập trung (Centralized Versioning) tập trung vào việc đồng bộ hóa, theo dõi, và lưu trữ tập tin. +* Quản lý phiên bản phân tán (Distributed Versioning) tập trung vào việc chia sẻ các thay đổi. Mỗi sự thay đổi có một mã định dạng (id) duy nhất. +* Các hệ phân tán không có cấu trúc định sẵn. Bạn có thể thay đổi một kiểu SVN, hệ phân tán, với git. + +[Thông tin thêm](http://git-scm.com/book/en/Getting-Started-About-Version-Control) + +### Tại Sao Dùng Git? + +* Có thể hoạt động offline. +* Cộng tác với nhau rất dễ dàng! +* Phân nhánh dễ dàng! +* Trộn (Merging) +* Git nhanh. +* Git linh hoạt. + +## Kiến Trúc Git + + +### Repository + +Một nhóm các tập tin, thư mục, các ghi chép trong quá khứ, commit, và heads. Tưởng tượng nó như là một cấu trúc dữ liệu mã nguồn, +với thuộc tính mà một "nhân tố" mã nguồn cho bạn quyền truy cập đến lịch sử sửa đổi, và một số thứ khác. + +Một git repository bao gồm thư mục .git & tree đang làm việc. + +### Thư mục .git (thành phần của một repository) + +Thư mục .git chứa tất cả các cấu hình, log, nhánh, HEAD, và hơn nữa. +[Danh Sách Chi Tiết.](http://gitready.com/advanced/2009/03/23/whats-inside-your-git-directory.html) + +### Tree Đang Làm (thành phần của một repository) + +Đây cơ bản là các thư mục và tập tin trong repository của bạn. Nó thường được tham chiếu +thư mục đang làm việc của bạn + +### Chỉ mục (thành phần của một thư mục .git) + +Chỉ mục của là một staging area trong git. Nó đơn giản là một lớp riêng biệt với tree đang làm việc của bạn +từ Git repository. Điều này cho nhà phát triền nhiều lựa chọn hơn trong việc xem xét những gì được gửi đến Git +repository. + +### Commit + +Một git commit là một snapshot của một nhóm các thay đổi, hoặc các thao tác Working Tree của bạn. +Ví dụ, nếu bạn thêm 5 tập tin, và xóa 2 tập tin khác, những thay đổi này sẽ được chứa trong +một commit (hoặc snapshot). Commit này có thể được đẩy đến các repo khác, hoặc không! + +### Nhánh + +Nhánh thực chất là một con trỏ đến commit mới nhất mà bạn vừa thực hiện. Khi bạn commit, +con trỏ này sẽ cập nhật tự động và trỏ đến commit mới nhất. + +### HEAD và head (thành phần của thư mục .git) + +HEAD là một con trỏ đến branch hiện tại. Một repo chỉ có một HEAD *đang hoạt động*. +head là một con trỏ đến bất kỳ commit nào. Một repo có thể có nhiều head. + +### Các Tài Nguyên Mang Tính Khái Niệm + +* [Git For Computer Scientists](http://eagain.net/articles/git-for-computer-scientists/) +* [Git For Designers](http://hoth.entp.com/output/git_for_designers.html) + + +## Các Lệnh + + +### init + +Tạo một repo Git rỗng. Các cài đặt, thông tin lưu trữ... của Git +được lưu ở một thư mục tên là ".git". + +```bash +$ git init +``` + +### config + +Để chỉnh tùy chọn. Bất kể là cho repo, hay cho hệ thống, hay điều chỉnh +toàn cục (global) + + + +```bash +# In Ra & Và Gán Một Số Biến Tùy Chỉnh Cơ Bản (Toàn cục - Global) +$ git config --global user.email +$ git config --global user.name + +$ git config --global user.email "MyEmail@Zoho.com" +$ git config --global user.name "My Name" +``` + +[Tìm hiểu thêm về git config.](http://git-scm.com/docs/git-config) + +### help + +Để cho bạn lối truy cập nhanh đến một chỉ dẫn cực kỳ chi tiết của từng lệnh. Hoặc chỉ để +nhắc bạn một số cú pháp. + +```bash +# Xem nhanh các lệnh có sẵn +$ git help + +# Xem tất các các lệnh +$ git help -a + +# Lệnh help riêng biệt - tài liệu người dùng +# git help +$ git help add +$ git help commit +$ git help init +``` + +### status + +Để hiển thị sự khác nhau giữa tập tin index (cơ bản là repo đang làm việc) và HEAD commit +hiện tại. + + +```bash +# Sẽ hiển thị nhánh, các tập tin chưa track (chưa commit), các thay đổi và những khác biệt khác +$ git status + +# Để xem các "tid bits" về git status +$ git help status +``` + +### add + +Để thêm các tập vào tree/thư mục/repo hiện tại. Nếu bạn không `git add` các tập tin mới đến +tree/thư mục hiện tại, chúng sẽ không được kèm theo trong các commit! + +```bash +# thêm một file vào thư mục hiện tại +$ git add HelloWorld.java + +# thêm một file vào một thư mục khác +$ git add /path/to/file/HelloWorld.c + +# Hỗ trợ Regular Expression! +$ git add ./*.java +``` + +### branch + +Quản lý nhánh (branch). Bạn có thể xem, sửa, tạo, xóa các nhánh bằng cách dùng lệnh này. + +```bash +# liệt kê các branch đang có và ở remote +$ git branch -a + +# tạo branch mới +$ git branch myNewBranch + +# xóa một branch +$ git branch -d myBranch + +# đặt tên lại một branch +# git branch -m +$ git branch -m myBranchName myNewBranchName + +# chỉnh sửa diễn giải của một branch +$ git branch myBranchName --edit-description +``` + +### checkout + +Cập nhật tất cả các file trong tree hiện tại để cho trùng khớp với phiên bản của index, hoặc tree cụ thể. + +```bash +# Checkout (chuyển) một repo - mặc định là nhánh master +$ git checkout +# Checkout một nhánh cụ thể +$ git checkout branchName +# Tạo một nhánh mới và chuyển đến nó, tương tự: "git branch ; git checkout " +$ git checkout -b newBranch +``` + +### clone + +Nhân bản, hoặc sao chép, một repo hiện có thành một thư mục mới. Nó cũng thêm +các branch có remote-tracking cho mỗi branch trong một repo được nhân bản, mà +cho phép bạn push đến một remote branch. + +```bash +# Nhân bản learnxinyminutes-docs +$ git clone https://github.com/adambard/learnxinyminutes-docs.git +``` + +### commit + +Lưu trữ nội dung hiện tại của index trong một "commit" mới. Điều này cho phép tạo ra thay đổi và một ghi chú tạo ra bởi người dùng. + +```bash +# commit với một ghi chú +$ git commit -m "Added multiplyNumbers() function to HelloWorld.c" +``` + +### diff + +Hiển thị sự khác biệt giữa một file trong thư mục hiện tại, index và commits. + +```bash +# Hiển thị sự khác biệt giữa thư mục hiện tại và index +$ git diff + +# Hiển thị khác biệt giữa index và commit mới nhất. +$ git diff --cached + +# Hiển thị khác biệt giữa thư mục đang làm việc và commit mới nhất +$ git diff HEAD +``` + +### grep + +Cho phép bạn tìm kiếm nhanh một repo. + +Các tinh chỉnh tùy chọn: + +```bash +# Cảm ơn Travis Jeffery vì những lệnh này +# Đặt số của dòng được hiển thị trong kết quả tìm kiếm grep +$ git config --global grep.lineNumber true + +# Làm cho kết quả tìm kiếm dễ đọc hơn, bao gồm cả gom nhóm +$ git config --global alias.g "grep --break --heading --line-number" +``` + +```bash +# Tìm "variableName" trong tất cả các file Java +$ git grep 'variableName' -- '*.java' + +# Tìm một dòng mà có chứa "arrayListName" và, "add" hoặc "remove" +$ git grep -e 'arrayListName' --and \( -e add -e remove \) +``` + +Google để xem thêm các ví dụ +[Git Grep Ninja](http://travisjeffery.com/b/2012/02/search-a-git-repo-like-a-ninja) + +### log + +Hiển thị các commit đến repo. + +```bash +# Hiện tất cả các commit +$ git log + +# Hiện X commit +$ git log -n 10 + +# Chỉ hiện các commit đã merge merge commits +$ git log --merges +``` + +### merge + +"Trộn" các thay đổi từ commit bên ngoài vào trong nhánh hiện tại. + +```bash +# Merge branch cụ thể vào branch hiện tại. +$ git merge branchName + +# Luôn khởi tạo một merge commit khi trộn (merge) +$ git merge --no-ff branchName +``` + +### mv + +Đặt lại tên hoặc di chuyển một file + +```bash +# Đặt lại tên một file +$ git mv HelloWorld.c HelloNewWorld.c + +# Di chuyển một file +$ git mv HelloWorld.c ./new/path/HelloWorld.c + +# Buộc đặt lại tên hoặc di chuyển +# "existingFile" đã tồn tại trong thự mục, sẽ bị ghi đè +$ git mv -f myFile existingFile +``` + +### pull + +Pull về từ một repo và merge nó vào branch khác. + +```bash +# Cập nhật repo local của bạn, bằng cách merge các thay đổi mới +# từ remote "origin" và nhánh "master". +# git pull +# git pull => hoàn toàn mặc định như => git pull origin master +$ git pull origin master + +# Merge các thay đổi từ remote branch và rebase +# các commit trong branch lên trên local repo, như sau: "git pull , git rebase " +$ git pull origin master --rebase +``` + +### push + +push và merge các thay đổi từ một branch đến một remote & branch. + ```bash # Push và merge các thay đổi từ một repo local đến một # remote có tên là "origin" và nhánh "master". @@ -334,68 +334,68 @@ $ git push origin master $ git push -u origin master # Từ lúc này, bất cứ khi nào bạn muốn push từ cùng một nhánh local đó, sử dụng lối tắt: $ git push -``` - -### rebase (thận trọng) - -Lấy tất cả các thay đổi mà đã được commit trên một nhánh, và replay (?) chúng trên một nhánh khác. -*Không rebase các commit mà bạn đã push đến một repo công khai*. - -```bash -# Rebase experimentBranch lên master -# git rebase -$ git rebase master experimentBranch -``` - -[Đọc Thêm.](http://git-scm.com/book/en/Git-Branching-Rebasing) - -### reset (thận trọng) - -Thiết lập lạo HEAD hiện tại đến một trạng thái cụ thể. Điều này cho phép bạn làm lại các merges, -pulls, commits, thêm, and hơn nữa. Nó là một lệnh hay nhưng cũng nguy hiểm nếu bạn không -biết mình đang làm gì. - -```bash -# Thiết lập lại staging area, để trùng với commit mới nhất (để thư mục không thay đổi) -$ git reset - -# Thiết lập lại staging area, để trùng với commit mới nhất, và ghi đè lên thư mục hiện tại -$ git reset --hard - -# Di chuyển nhánh hiện tại đến một commit cụ thể (để thư mục không thay đổi) -# tất cả thay đổi vẫn duy trì trong thư mục. -$ git reset 31f2bb1 - -# Di chuyển nhánh hiện tại lùi về một commit cụ thể -# và làm cho thư mục hiện tại trùng (xóa các thay đổi chưa được commit và tất cả các commit -# sau một commit cụ thể). -$ git reset --hard 31f2bb1 -``` - -### rm - -Ngược lại với git add, git rm xóa file từ tree đang làm việc. - -```bash -# xóa HelloWorld.c -$ git rm HelloWorld.c - -# Xóa file từ thư mục khác -$ git rm /pather/to/the/file/HelloWorld.c -``` - -## Thông tin thêm - -* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) - -* [git-scm - Video Tutorials](http://git-scm.com/videos) - -* [git-scm - Documentation](http://git-scm.com/docs) - -* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) - -* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) - -* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) - +``` + +### rebase (thận trọng) + +Lấy tất cả các thay đổi mà đã được commit trên một nhánh, và replay (?) chúng trên một nhánh khác. +*Không rebase các commit mà bạn đã push đến một repo công khai*. + +```bash +# Rebase experimentBranch lên master +# git rebase +$ git rebase master experimentBranch +``` + +[Đọc Thêm.](http://git-scm.com/book/en/Git-Branching-Rebasing) + +### reset (thận trọng) + +Thiết lập lạo HEAD hiện tại đến một trạng thái cụ thể. Điều này cho phép bạn làm lại các merges, +pulls, commits, thêm, and hơn nữa. Nó là một lệnh hay nhưng cũng nguy hiểm nếu bạn không +biết mình đang làm gì. + +```bash +# Thiết lập lại staging area, để trùng với commit mới nhất (để thư mục không thay đổi) +$ git reset + +# Thiết lập lại staging area, để trùng với commit mới nhất, và ghi đè lên thư mục hiện tại +$ git reset --hard + +# Di chuyển nhánh hiện tại đến một commit cụ thể (để thư mục không thay đổi) +# tất cả thay đổi vẫn duy trì trong thư mục. +$ git reset 31f2bb1 + +# Di chuyển nhánh hiện tại lùi về một commit cụ thể +# và làm cho thư mục hiện tại trùng (xóa các thay đổi chưa được commit và tất cả các commit +# sau một commit cụ thể). +$ git reset --hard 31f2bb1 +``` + +### rm + +Ngược lại với git add, git rm xóa file từ tree đang làm việc. + +```bash +# xóa HelloWorld.c +$ git rm HelloWorld.c + +# Xóa file từ thư mục khác +$ git rm /pather/to/the/file/HelloWorld.c +``` + +## Thông tin thêm + +* [tryGit - A fun interactive way to learn Git.](http://try.github.io/levels/1/challenges/1) + +* [git-scm - Video Tutorials](http://git-scm.com/videos) + +* [git-scm - Documentation](http://git-scm.com/docs) + +* [Atlassian Git - Tutorials & Workflows](https://www.atlassian.com/git/) + +* [SalesForce Cheat Sheet](https://na1.salesforce.com/help/doc/en/salesforce_git_developer_cheatsheet.pdf) + +* [Git - the simple guide](http://rogerdudler.github.io/git-guide/index.html) + diff --git a/vi-vn/objective-c-vi.html.markdown b/vi-vn/objective-c-vi.html.markdown index 4656cf38..b01ce806 100644 --- a/vi-vn/objective-c-vi.html.markdown +++ b/vi-vn/objective-c-vi.html.markdown @@ -1,316 +1,316 @@ ---- -language: Objective-C -contributors: - - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] - - ["Yannick Loriot", "https://github.com/YannickL"] -lang: vi-vn -filename: LearnObjectiveC-vi.m ---- - -Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành macOS, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch. -Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C. - -```objective-c -// Chú thích dòng đơn bắt đầu với // - -/* -Chú thích đa dòng trông như thế này. -*/ - -// Nhập các headers của framework Foundation với cú pháp #import -#import -#import "MyClass.h" - -// Đầu vào chương trình của bạn là một hàm gọi là -// main với một kiểu trả về kiểu integer. -int main (int argc, const char * argv[]) -{ - // Tạo một autorelease pool để quản lý bộ nhớ vào chương trình - NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; - - // Sử dụng hàm NSLog() để in ra các dòng lệnh vào console - NSLog(@"Hello World!"); // Print the string "Hello World!" - - /////////////////////////////////////// - // Kiểu & Biến (Types & Variables) - /////////////////////////////////////// - - // Khai báo số nguyên - int myPrimitive1 = 1; - long myPrimitive2 = 234554664565; - - // Khai báo đối tượng - // Đặt dấu nháy * vào trước tên biến cho khai báo đối tượng strong - MyClass *myObject1 = nil; // Strong - id myObject2 = nil; // Weak - // %@ là một đối tượng - // 'miêu tả' ('desciption') là thông lệ để trình bày giá trị của các Đối tượng - NSLog(@"%@ và %@", myObject1, [myObject2 description]); // In ra "(null) và (null)" - - // Chuỗi - NSString *worldString = @"World"; - NSLog(@"Hello %@!", worldString); // In ra "Hello World!" - - // Ký tự literals - NSNumber *theLetterZNumber = @'Z'; - char theLetterZ = [theLetterZNumber charValue]; - NSLog(@"%c", theLetterZ); - - // Số nguyên literals - NSNumber *fortyTwoNumber = @42; - int fortyTwo = [fortyTwoNumber intValue]; - NSLog(@"%i", fortyTwo); - - NSNumber *fortyTwoUnsignedNumber = @42U; - unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; - NSLog(@"%u", fortyTwoUnsigned); - - NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; - short fortyTwoShort = [fortyTwoShortNumber shortValue]; - NSLog(@"%hi", fortyTwoShort); - - NSNumber *fortyTwoLongNumber = @42L; - long fortyTwoLong = [fortyTwoLongNumber longValue]; - NSLog(@"%li", fortyTwoLong); - - // Dấu phẩy động (floating point) literals - NSNumber *piFloatNumber = @3.141592654F; - float piFloat = [piFloatNumber floatValue]; - NSLog(@"%f", piFloat); - - NSNumber *piDoubleNumber = @3.1415926535; - double piDouble = [piDoubleNumber doubleValue]; - NSLog(@"%f", piDouble); - - // BOOL literals - NSNumber *yesNumber = @YES; - NSNumber *noNumber = @NO; - - // Đối tượng Mảng - NSArray *anArray = @[@1, @2, @3, @4]; - NSNumber *thirdNumber = anArray[2]; - NSLog(@"Third number = %@", thirdNumber); // In ra "Third number = 3" - - // Đối tượng Từ điển - NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; - NSObject *valueObject = aDictionary[@"A Key"]; - NSLog(@"Đối tượng = %@", valueObject); // In ra "Object = (null)" - - /////////////////////////////////////// - // Toán Tử (Operators) - /////////////////////////////////////// - - // Các toán tử cũng hoạt động giống như ngôn ngữ C - // Ví dụ: - 2 + 5; // => 7 - 4.2f + 5.1f; // => 9.3f - 3 == 2; // => 0 (NO) - 3 != 2; // => 1 (YES) - 1 && 1; // => 1 (Logical and) - 0 || 1; // => 1 (Logical or) - ~0x0F; // => 0xF0 (bitwise negation) - 0x0F & 0xF0; // => 0x00 (bitwise AND) - 0x01 << 1; // => 0x02 (bitwise dịch trái (bởi 1)) - - ///////////////////////////////////////////// - // Cấu Trúc Điều Khiển (Controls Structures) - ///////////////////////////////////////////// - - // Câu lệnh If-Else - if (NO) - { - NSLog(@"I am never run"); - } else if (0) - { - NSLog(@"I am also never run"); - } else - { - NSLog(@"I print"); - } - - // Câu lệnh Switch - switch (2) - { - case 0: - { - NSLog(@"I am never run"); - } break; - case 1: - { - NSLog(@"I am also never run"); - } break; - default: - { - NSLog(@"I print"); - } break; - } - - // Câu lệnh vòng lặp While - int ii = 0; - while (ii < 4) - { - NSLog(@"%d,", ii++); // ii++ tăng dần, sau khi sử dụng giá trị của nó. - } // => in ra "0," - // "1," - // "2," - // "3," - - // Câu lệnh vòng lặp For - int jj; - for (jj=0; jj < 4; jj++) - { - NSLog(@"%d,", jj); - } // => in ra "0," - // "1," - // "2," - // "3," - - // Câu lệnh Foreach - NSArray *values = @[@0, @1, @2, @3]; - for (NSNumber *value in values) - { - NSLog(@"%@,", value); - } // => in ra "0," - // "1," - // "2," - // "3," - - // Câu lệnh Try-Catch-Finally - @try - { - // Your statements here - @throw [NSException exceptionWithName:@"FileNotFoundException" - reason:@"Không Tìm Thấy Tập Tin trên Hệ Thống" userInfo:nil]; - } @catch (NSException * e) - { - NSLog(@"Exception: %@", e); - } @finally - { - NSLog(@"Finally"); - } // => in ra "Exception: Không Tìm Thấy Tập Tin trên Hệ Thống" - // "Finally" - - /////////////////////////////////////// - // Đối Tượng (Objects) - /////////////////////////////////////// - - // Tạo một thực thể đối tượng bằng cách phân vùng nhớ và khởi tạo đối tượng đó. - // Một đối tượng sẽ không thật sự hoạt động cho đến khi cả 2 bước alloc] init] được hoàn thành - MyClass *myObject = [[MyClass alloc] init]; - - // Mô hình lập trình hướng đối tượng của Objective-C dựa trên việc truyền thông điệp (message) - // và các thực thể đối tượng với nhau. - // Trong Objective-C một đối tượng không đơn thuần gọi phương thức; nó truyền thông điệp. - [myObject instanceMethodWithParameter:@"Steve Jobs"]; - - // Dọn dẹp vùng nhớ mà bạn đã dùng ở chương trình - [pool drain]; - - // Kết thúc chương trình - return 0; -} - -/////////////////////////////////////// -// Lớp và Hàm (Classes & Functions) -/////////////////////////////////////// - -// Khai báo lớp của bạn ở một tập tin header (MyClass.h): -// Cú pháp Khai Báo Lớp: -// @interface ClassName : ParentClassName -// { -// Khai báo biến thành viên; -// } -// -/+ (type) Khai báo method; -// @end -@interface MyClass : NSObject -{ - int count; - id data; - NSString *name; -} -// Ký hiệu (notation) tiện ích để tự động khởi tạo public getter và setter -@property int count; -@property (copy) NSString *name; // Sao chép đối tượng trong quá trình gán. -@property (readonly) id data; // Chỉ khai báo phương thức getter. - -// Phương thức -+/- (return type)methodSignature:(Parameter Type *)parameterName; - -// dấu '+' cho phương thức lớp -+ (NSString *)classMethod; - -// dấu '-' cho phương thức thực thể -- (NSString *)instanceMethodWithParameter:(NSString *)string; -- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; - -@end - -// Thực thi các phương thức trong một tập tin thực thi (MyClass.m): - -@implementation MyClass - -// Gọi khi đối tượng được release -- (void)dealloc -{ -} - -// Phương thức khởi tạo (Constructors) là một cách để tạo các lớp -// Đây là phương thức khởi tạo mặc định được gọi khi đối tượng được khởi tạo -- (id)init -{ - if ((self = [super init])) - { - self.count = 1; - } - return self; -} - -+ (NSString *)classMethod -{ - return [[self alloc] init]; -} - -- (NSString *)instanceMethodWithParameter:(NSString *)string -{ - return @"New string"; -} - -- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number -{ - return @42; -} - -// Các phương thức được khai báo vào MyProtocol -- (void)myProtocolMethod -{ - // câu lệnh -} - -@end - -/* - * Một protocol khai báo các phương thức mà có thể thực thi bởi bất kỳ lớp nào. - * Các protocol chính chúng không phải là các lớp. Chúng chỉ đơn giản là định ra giao diện (interface) - * mà các đối tượng khác có trách nhiệm sẽ thực thi. - */ -@protocol MyProtocol - - (void)myProtocolMethod; -@end - - - -``` -## Xem Thêm - -+ [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) - -+ Apple Docs': - + [Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) - - + [Programming With Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html) - - + [Object-Oriented Programming with Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005149) - - + [Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html) - -+ [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) +--- +language: Objective-C +contributors: + - ["Eugene Yagrushkin", "www.about.me/yagrushkin"] + - ["Yannick Loriot", "https://github.com/YannickL"] +lang: vi-vn +filename: LearnObjectiveC-vi.m +--- + +Objective-C là ngôn ngữ lập trình chính được sử dụng bởi Apple cho các hệ điều hành macOS, iOS và các framework tương ứng của họ, Cocoa và Cocoa Touch. +Nó là một ngôn ngữ lập trình mục đích tổng quát, hướng đối tượng có bổ sung thêm kiểu truyền thông điệp giống Smalltalk vào ngôn ngữ lập trình C. + +```objective-c +// Chú thích dòng đơn bắt đầu với // + +/* +Chú thích đa dòng trông như thế này. +*/ + +// Nhập các headers của framework Foundation với cú pháp #import +#import +#import "MyClass.h" + +// Đầu vào chương trình của bạn là một hàm gọi là +// main với một kiểu trả về kiểu integer. +int main (int argc, const char * argv[]) +{ + // Tạo một autorelease pool để quản lý bộ nhớ vào chương trình + NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; + + // Sử dụng hàm NSLog() để in ra các dòng lệnh vào console + NSLog(@"Hello World!"); // Print the string "Hello World!" + + /////////////////////////////////////// + // Kiểu & Biến (Types & Variables) + /////////////////////////////////////// + + // Khai báo số nguyên + int myPrimitive1 = 1; + long myPrimitive2 = 234554664565; + + // Khai báo đối tượng + // Đặt dấu nháy * vào trước tên biến cho khai báo đối tượng strong + MyClass *myObject1 = nil; // Strong + id myObject2 = nil; // Weak + // %@ là một đối tượng + // 'miêu tả' ('desciption') là thông lệ để trình bày giá trị của các Đối tượng + NSLog(@"%@ và %@", myObject1, [myObject2 description]); // In ra "(null) và (null)" + + // Chuỗi + NSString *worldString = @"World"; + NSLog(@"Hello %@!", worldString); // In ra "Hello World!" + + // Ký tự literals + NSNumber *theLetterZNumber = @'Z'; + char theLetterZ = [theLetterZNumber charValue]; + NSLog(@"%c", theLetterZ); + + // Số nguyên literals + NSNumber *fortyTwoNumber = @42; + int fortyTwo = [fortyTwoNumber intValue]; + NSLog(@"%i", fortyTwo); + + NSNumber *fortyTwoUnsignedNumber = @42U; + unsigned int fortyTwoUnsigned = [fortyTwoUnsignedNumber unsignedIntValue]; + NSLog(@"%u", fortyTwoUnsigned); + + NSNumber *fortyTwoShortNumber = [NSNumber numberWithShort:42]; + short fortyTwoShort = [fortyTwoShortNumber shortValue]; + NSLog(@"%hi", fortyTwoShort); + + NSNumber *fortyTwoLongNumber = @42L; + long fortyTwoLong = [fortyTwoLongNumber longValue]; + NSLog(@"%li", fortyTwoLong); + + // Dấu phẩy động (floating point) literals + NSNumber *piFloatNumber = @3.141592654F; + float piFloat = [piFloatNumber floatValue]; + NSLog(@"%f", piFloat); + + NSNumber *piDoubleNumber = @3.1415926535; + double piDouble = [piDoubleNumber doubleValue]; + NSLog(@"%f", piDouble); + + // BOOL literals + NSNumber *yesNumber = @YES; + NSNumber *noNumber = @NO; + + // Đối tượng Mảng + NSArray *anArray = @[@1, @2, @3, @4]; + NSNumber *thirdNumber = anArray[2]; + NSLog(@"Third number = %@", thirdNumber); // In ra "Third number = 3" + + // Đối tượng Từ điển + NSDictionary *aDictionary = @{ @"key1" : @"value1", @"key2" : @"value2" }; + NSObject *valueObject = aDictionary[@"A Key"]; + NSLog(@"Đối tượng = %@", valueObject); // In ra "Object = (null)" + + /////////////////////////////////////// + // Toán Tử (Operators) + /////////////////////////////////////// + + // Các toán tử cũng hoạt động giống như ngôn ngữ C + // Ví dụ: + 2 + 5; // => 7 + 4.2f + 5.1f; // => 9.3f + 3 == 2; // => 0 (NO) + 3 != 2; // => 1 (YES) + 1 && 1; // => 1 (Logical and) + 0 || 1; // => 1 (Logical or) + ~0x0F; // => 0xF0 (bitwise negation) + 0x0F & 0xF0; // => 0x00 (bitwise AND) + 0x01 << 1; // => 0x02 (bitwise dịch trái (bởi 1)) + + ///////////////////////////////////////////// + // Cấu Trúc Điều Khiển (Controls Structures) + ///////////////////////////////////////////// + + // Câu lệnh If-Else + if (NO) + { + NSLog(@"I am never run"); + } else if (0) + { + NSLog(@"I am also never run"); + } else + { + NSLog(@"I print"); + } + + // Câu lệnh Switch + switch (2) + { + case 0: + { + NSLog(@"I am never run"); + } break; + case 1: + { + NSLog(@"I am also never run"); + } break; + default: + { + NSLog(@"I print"); + } break; + } + + // Câu lệnh vòng lặp While + int ii = 0; + while (ii < 4) + { + NSLog(@"%d,", ii++); // ii++ tăng dần, sau khi sử dụng giá trị của nó. + } // => in ra "0," + // "1," + // "2," + // "3," + + // Câu lệnh vòng lặp For + int jj; + for (jj=0; jj < 4; jj++) + { + NSLog(@"%d,", jj); + } // => in ra "0," + // "1," + // "2," + // "3," + + // Câu lệnh Foreach + NSArray *values = @[@0, @1, @2, @3]; + for (NSNumber *value in values) + { + NSLog(@"%@,", value); + } // => in ra "0," + // "1," + // "2," + // "3," + + // Câu lệnh Try-Catch-Finally + @try + { + // Your statements here + @throw [NSException exceptionWithName:@"FileNotFoundException" + reason:@"Không Tìm Thấy Tập Tin trên Hệ Thống" userInfo:nil]; + } @catch (NSException * e) + { + NSLog(@"Exception: %@", e); + } @finally + { + NSLog(@"Finally"); + } // => in ra "Exception: Không Tìm Thấy Tập Tin trên Hệ Thống" + // "Finally" + + /////////////////////////////////////// + // Đối Tượng (Objects) + /////////////////////////////////////// + + // Tạo một thực thể đối tượng bằng cách phân vùng nhớ và khởi tạo đối tượng đó. + // Một đối tượng sẽ không thật sự hoạt động cho đến khi cả 2 bước alloc] init] được hoàn thành + MyClass *myObject = [[MyClass alloc] init]; + + // Mô hình lập trình hướng đối tượng của Objective-C dựa trên việc truyền thông điệp (message) + // và các thực thể đối tượng với nhau. + // Trong Objective-C một đối tượng không đơn thuần gọi phương thức; nó truyền thông điệp. + [myObject instanceMethodWithParameter:@"Steve Jobs"]; + + // Dọn dẹp vùng nhớ mà bạn đã dùng ở chương trình + [pool drain]; + + // Kết thúc chương trình + return 0; +} + +/////////////////////////////////////// +// Lớp và Hàm (Classes & Functions) +/////////////////////////////////////// + +// Khai báo lớp của bạn ở một tập tin header (MyClass.h): +// Cú pháp Khai Báo Lớp: +// @interface ClassName : ParentClassName +// { +// Khai báo biến thành viên; +// } +// -/+ (type) Khai báo method; +// @end +@interface MyClass : NSObject +{ + int count; + id data; + NSString *name; +} +// Ký hiệu (notation) tiện ích để tự động khởi tạo public getter và setter +@property int count; +@property (copy) NSString *name; // Sao chép đối tượng trong quá trình gán. +@property (readonly) id data; // Chỉ khai báo phương thức getter. + +// Phương thức ++/- (return type)methodSignature:(Parameter Type *)parameterName; + +// dấu '+' cho phương thức lớp ++ (NSString *)classMethod; + +// dấu '-' cho phương thức thực thể +- (NSString *)instanceMethodWithParameter:(NSString *)string; +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number; + +@end + +// Thực thi các phương thức trong một tập tin thực thi (MyClass.m): + +@implementation MyClass + +// Gọi khi đối tượng được release +- (void)dealloc +{ +} + +// Phương thức khởi tạo (Constructors) là một cách để tạo các lớp +// Đây là phương thức khởi tạo mặc định được gọi khi đối tượng được khởi tạo +- (id)init +{ + if ((self = [super init])) + { + self.count = 1; + } + return self; +} + ++ (NSString *)classMethod +{ + return [[self alloc] init]; +} + +- (NSString *)instanceMethodWithParameter:(NSString *)string +{ + return @"New string"; +} + +- (NSNumber *)methodAParameterAsString:(NSString*)string andAParameterAsNumber:(NSNumber *)number +{ + return @42; +} + +// Các phương thức được khai báo vào MyProtocol +- (void)myProtocolMethod +{ + // câu lệnh +} + +@end + +/* + * Một protocol khai báo các phương thức mà có thể thực thi bởi bất kỳ lớp nào. + * Các protocol chính chúng không phải là các lớp. Chúng chỉ đơn giản là định ra giao diện (interface) + * mà các đối tượng khác có trách nhiệm sẽ thực thi. + */ +@protocol MyProtocol + - (void)myProtocolMethod; +@end + + + +``` +## Xem Thêm + ++ [Wikipedia Objective-C](http://en.wikipedia.org/wiki/Objective-C) + ++ Apple Docs': + + [Learning Objective-C](http://developer.apple.com/library/ios/referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/) + + + [Programming With Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html) + + + [Object-Oriented Programming with Objective-C](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/OOP_ObjC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005149) + + + [Coding Guidelines for Cocoa](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html) + ++ [iOS For High School Students: Getting Started](http://www.raywenderlich.com/5600/ios-for-high-school-students-getting-started) diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index a6a61949..db36ebc4 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -1,572 +1,572 @@ ---- -language: C++ -filename: learncpp-cn.cpp -contributors: - - ["Steven Basart", "http://github.com/xksteven"] - - ["Matt Kline", "https://github.com/mrkline"] -translators: - - ["Arnie97", "https://github.com/Arnie97"] -lang: zh-cn ---- - -C++是一种系统编程语言。用它的发明者, -[Bjarne Stroustrup的话](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)来说,C++的设计目标是: - -- 成为“更好的C语言” -- 支持数据的抽象与封装 -- 支持面向对象编程 -- 支持泛型编程 - -C++提供了对硬件的紧密控制(正如C语言一样), -能够编译为机器语言,由处理器直接执行。 -与此同时,它也提供了泛型、异常和类等高层功能。 -虽然C++的语法可能比某些出现较晚的语言更复杂,它仍然得到了人们的青睞—— -功能与速度的平衡使C++成为了目前应用最广泛的系统编程语言之一。 - -```c++ -//////////////// -// 与C语言的比较 -//////////////// - -// C++_几乎_是C语言的一个超集,它与C语言的基本语法有许多相同之处, -// 例如变量和函数的声明,原生数据类型等等。 - -// 和C语言一样,在C++中,你的程序会从main()开始执行, -// 该函数的返回值应当为int型,这个返回值会作为程序的退出状态值。 -// 不过,大多数的编译器(gcc,clang等)也接受 void main() 的函数原型。 -// (参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息) -int main(int argc, char** argv) -{ - // 和C语言一样,命令行参数通过argc和argv传递。 - // argc代表命令行参数的数量, - // 而argv是一个包含“C语言风格字符串”(char *)的数组, - // 其中每个字符串代表一个命令行参数的内容, - // 首个命令行参数是调用该程序时所使用的名称。 - // 如果你不关心命令行参数的值,argc和argv可以被忽略。 - // 此时,你可以用int main()作为函数原型。 - - // 退出状态值为0时,表示程序执行成功 - return 0; -} - -// 然而,C++和C语言也有一些区别: - -// 在C++中,字符字面量的大小是一个字节。 -sizeof('c') == 1 - -// 在C语言中,字符字面量的大小与int相同。 -sizeof('c') == sizeof(10) - - -// C++的函数原型与函数定义是严格匹配的 -void func(); // 这个函数不能接受任何参数 - -// 而在C语言中 -void func(); // 这个函数能接受任意数量的参数 - -// 在C++中,用nullptr代替C语言中的NULL -int* ip = nullptr; - -// C++也可以使用C语言的标准头文件, -// 但是需要加上前缀“c”并去掉末尾的“.h”。 -#include - -int main() -{ - printf("Hello, world!\n"); - return 0; -} - -/////////// -// 函数重载 -/////////// - -// C++支持函数重载,你可以定义一组名称相同而参数不同的函数。 - -void print(char const* myString) -{ - printf("String %s\n", myString); -} - -void print(int myInt) -{ - printf("My int is %d", myInt); -} - -int main() -{ - print("Hello"); // 解析为 void print(const char*) - print(15); // 解析为 void print(int) -} - -/////////////////// -// 函数参数的默认值 -/////////////////// - -// 你可以为函数的参数指定默认值, -// 它们将会在调用者没有提供相应参数时被使用。 - -void doSomethingWithInts(int a = 1, int b = 4) -{ - // 对两个参数进行一些操作 -} - -int main() -{ - doSomethingWithInts(); // a = 1, b = 4 - doSomethingWithInts(20); // a = 20, b = 4 - doSomethingWithInts(20, 5); // a = 20, b = 5 -} - -// 默认参数必须放在所有的常规参数之后。 - -void invalidDeclaration(int a = 1, int b) // 这是错误的! -{ -} - - -/////////// -// 命名空间 -/////////// - -// 命名空间为变量、函数和其他声明提供了分离的的作用域。 -// 命名空间可以嵌套使用。 - -namespace First { - namespace Nested { - void foo() - { - printf("This is First::Nested::foo\n"); - } - } // 结束嵌套的命名空间Nested -} // 结束命名空间First - -namespace Second { - void foo() - { - printf("This is Second::foo\n") - } -} - -void foo() -{ - printf("This is global foo\n"); -} - -int main() -{ - // 如果没有特别指定,就从“Second”中取得所需的内容。 - using namespace Second; - - foo(); // 显示“This is Second::foo” - First::Nested::foo(); // 显示“This is First::Nested::foo” - ::foo(); // 显示“This is global foo” -} - -//////////// -// 输入/输出 -//////////// - -// C++使用“流”来输入输出。<<是流的插入运算符,>>是流提取运算符。 -// cin、cout、和cerr分别代表 -// stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。 - -#include // 引入包含输入/输出流的头文件 - -using namespace std; // 输入输出流在std命名空间(也就是标准库)中。 - -int main() -{ - int myInt; - - // 在标准输出(终端/显示器)中显示 - cout << "Enter your favorite number:\n"; - // 从标准输入(键盘)获得一个值 - cin >> myInt; - - // cout也提供了格式化功能 - cout << "Your favorite number is " << myInt << "\n"; - // 显示“Your favorite number is ” - - cerr << "Used for error messages"; -} - -///////// -// 字符串 -///////// - -// C++中的字符串是对象,它们有很多成员函数 -#include - -using namespace std; // 字符串也在std命名空间(标准库)中。 - -string myString = "Hello"; -string myOtherString = " World"; - -// + 可以用于连接字符串。 -cout << myString + myOtherString; // "Hello World" - -cout << myString + " You"; // "Hello You" - -// C++中的字符串是可变的,具有“值语义”。 -myString.append(" Dog"); -cout << myString; // "Hello Dog" - - -///////////// -// 引用 -///////////// - -// 除了支持C语言中的指针类型以外,C++还提供了_引用_。 -// 引用是一种特殊的指针类型,一旦被定义就不能重新赋值,并且不能被设置为空值。 -// 使用引用时的语法与原变量相同: -// 也就是说,对引用类型进行解引用时,不需要使用*; -// 赋值时也不需要用&来取地址。 - -using namespace std; - -string foo = "I am foo"; -string bar = "I am bar"; - - -string& fooRef = foo; // 建立了一个对foo的引用。 -fooRef += ". Hi!"; // 通过引用来修改foo的值 -cout << fooRef; // "I am foo. Hi!" - -// 这句话的并不会改变fooRef的指向,其效果与“foo = bar”相同。 -// 也就是说,在执行这条语句之后,foo == "I am bar"。 -fooRef = bar; - -const string& barRef = bar; // 建立指向bar的常量引用。 -// 和C语言中一样,(指针和引用)声明为常量时,对应的值不能被修改。 -barRef += ". Hi!"; // 这是错误的,不能修改一个常量引用的值。 - -/////////////////// -// 类与面向对象编程 -/////////////////// - -// 有关类的第一个示例 -#include - -// 声明一个类。 -// 类通常在头文件(.h或.hpp)中声明。 -class Dog { - // 成员变量和成员函数默认情况下是私有(private)的。 - std::string name; - int weight; - -// 在这个标签之后,所有声明都是公有(public)的, -// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止 -public: - - // 默认的构造器 - Dog(); - - // 这里是成员函数声明的一个例子。 - // 可以注意到,我们在此处使用了std::string,而不是using namespace std - // 语句using namespace绝不应当出现在头文件当中。 - void setName(const std::string& dogsName); - - void setWeight(int dogsWeight); - - // 如果一个函数不对对象的状态进行修改, - // 应当在声明中加上const。 - // 这样,你就可以对一个以常量方式引用的对象执行该操作。 - // 同时可以注意到,当父类的成员函数需要被子类重写时, - // 父类中的函数必须被显式声明为_虚函数(virtual)_。 - // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。 - virtual void print() const; - - // 函数也可以在class body内部定义。 - // 这样定义的函数会自动成为内联函数。 - void bark() const { std::cout << name << " barks!\n" } - - // 除了构造器以外,C++还提供了析构器。 - // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。 - // 这使得RAII这样的强大范式(参见下文)成为可能。 - // 为了衍生出子类来,基类的析构函数必须定义为虚函数。 - virtual ~Dog(); - -}; // 在类的定义之后,要加一个分号 - -// 类的成员函数通常在.cpp文件中实现。 -void Dog::Dog() -{ - std::cout << "A dog has been constructed\n"; -} - -// 对象(例如字符串)应当以引用的形式传递, -// 对于不需要修改的对象,最好使用常量引用。 -void Dog::setName(const std::string& dogsName) -{ - name = dogsName; -} - -void Dog::setWeight(int dogsWeight) -{ - weight = dogsWeight; -} - -// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复 -void Dog::print() const -{ - std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; -} - -void Dog::~Dog() -{ - std::cout << "Goodbye " << name << "\n"; -} - -int main() { - Dog myDog; // 此时显示“A dog has been constructed” - myDog.setName("Barkley"); - myDog.setWeight(10); - myDog.print(); // 显示“Dog is Barkley and weighs 10 kg” - return 0; -} // 显示“Goodbye Barkley” - -// 继承: - -// 这个类继承了Dog类中的公有(public)和保护(protected)对象 -class OwnedDog : public Dog { - - void setOwner(const std::string& dogsOwner) - - // 重写OwnedDogs类的print方法。 - // 如果你不熟悉子类多态的话,可以参考这个页面中的概述: - // http://zh.wikipedia.org/wiki/%E5%AD%90%E7%B1%BB%E5%9E%8B - - // override关键字是可选的,它确保你所重写的是基类中的方法。 - void print() const override; - -private: - std::string owner; -}; - -// 与此同时,在对应的.cpp文件里: - -void OwnedDog::setOwner(const std::string& dogsOwner) -{ - owner = dogsOwner; -} - -void OwnedDog::print() const -{ - Dog::print(); // 调用基类Dog中的print方法 - // "Dog is and weights " - - std::cout << "Dog is owned by " << owner << "\n"; - // "Dog is owned by " -} - -///////////////////// -// 初始化与运算符重载 -///////////////////// - -// 在C++中,通过定义一些特殊名称的函数, -// 你可以重载+、-、*、/等运算符的行为。 -// 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。 - -#include -using namespace std; - -class Point { -public: - // 可以以这样的方式为成员变量设置默认值。 - double x = 0; - double y = 0; - - // 定义一个默认的构造器。 - // 除了将Point初始化为(0, 0)以外,这个函数什么都不做。 - Point() { }; - - // 下面使用的语法称为初始化列表, - // 这是初始化类中成员变量的正确方式。 - Point (double a, double b) : - x(a), - y(b) - { /* 除了初始化成员变量外,什么都不做 */ } - - // 重载 + 运算符 - Point operator+(const Point& rhs) const; - - // 重载 += 运算符 - Point& operator+=(const Point& rhs); - - // 增加 - 和 -= 运算符也是有意义的,但这里不再赘述。 -}; - -Point Point::operator+(const Point& rhs) const -{ - // 创建一个新的点, - // 其横纵坐标分别为这个点与另一点在对应方向上的坐标之和。 - return Point(x + rhs.x, y + rhs.y); -} - -Point& Point::operator+=(const Point& rhs) -{ - x += rhs.x; - y += rhs.y; - return *this; -} - -int main () { - Point up (0,1); - Point right (1,0); - // 这里使用了Point类型的运算符“+” - // 调用up(Point类型)的“+”方法,并以right作为函数的参数 - Point result = up + right; - // 显示“Result is upright (1,1)” - cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; - return 0; -} - -/////////// -// 异常处理 -/////////// - -// 标准库中提供了一些基本的异常类型 -// (参见http://en.cppreference.com/w/cpp/error/exception) -// 但是,其他任何类型也可以作为一个异常被拋出 -#include - -// 在_try_代码块中拋出的异常可以被随后的_catch_捕获。 -try { - // 不要用 _new_关键字在堆上为异常分配空间。 - throw std::exception("A problem occurred"); -} -// 如果拋出的异常是一个对象,可以用常量引用来捕获它 -catch (const std::exception& ex) -{ - std::cout << ex.what(); -// 捕获尚未被_catch_处理的所有错误 -} catch (...) -{ - std::cout << "Unknown exception caught"; - throw; // 重新拋出异常 -} - -/////// -// RAII -/////// - -// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization), -// 它被视作C++中最强大的编程范式之一。 -// 简单说来,它指的是,用构造函数来获取一个对象的资源, -// 相应的,借助析构函数来释放对象的资源。 - -// 为了理解这一范式的用处,让我们考虑某个函数使用文件句柄时的情况: -void doSomethingWithAFile(const char* filename) -{ - // 首先,让我们假设一切都会顺利进行。 - - FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 - - doSomethingWithTheFile(fh); - doSomethingElseWithIt(fh); - - fclose(fh); // 关闭文件句柄 -} - -// 不幸的是,随着错误处理机制的引入,事情会变得复杂。 -// 假设fopen函数有可能执行失败, -// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。 -// (虽然异常是C++中处理错误的推荐方式, -// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。 -// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。 -bool doSomethingWithAFile(const char* filename) -{ - FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 - if (fh == nullptr) // 当执行失败是,返回的指针是nullptr - return false; // 向调用者汇报错误 - - // 假设每个函数会在执行失败时返回false - if (!doSomethingWithTheFile(fh)) { - fclose(fh); // 关闭文件句柄,避免造成内存泄漏。 - return false; // 反馈错误 - } - if (!doSomethingElseWithIt(fh)) { - fclose(fh); // 关闭文件句柄 - return false; // 反馈错误 - } - - fclose(fh); // 关闭文件句柄 - return true; // 指示函数已成功执行 -} - -// C语言的程序员通常会借助goto语句简化上面的代码: -bool doSomethingWithAFile(const char* filename) -{ - FILE* fh = fopen(filename, "r"); - if (fh == nullptr) - return false; - - if (!doSomethingWithTheFile(fh)) - goto failure; - - if (!doSomethingElseWithIt(fh)) - goto failure; - - fclose(fh); // 关闭文件 - return true; // 执行成功 - -failure: - fclose(fh); - return false; // 反馈错误 -} - -// 如果用异常捕获机制来指示错误的话, -// 代码会变得清晰一些,但是仍然有优化的余地。 -void doSomethingWithAFile(const char* filename) -{ - FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 - if (fh == nullptr) - throw std::exception("Could not open the file."); - - try { - doSomethingWithTheFile(fh); - doSomethingElseWithIt(fh); - } - catch (...) { - fclose(fh); // 保证出错的时候文件被正确关闭 - throw; // 之后,重新抛出这个异常 - } - - fclose(fh); // 关闭文件 - // 所有工作顺利完成 -} - -// 相比之下,使用C++中的文件流类(fstream)时, -// fstream会利用自己的析构器来关闭文件句柄。 -// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。 -void doSomethingWithAFile(const std::string& filename) -{ - // ifstream是输入文件流(input file stream)的简称 - std::ifstream fh(filename); // 打开一个文件 - - // 对文件进行一些操作 - doSomethingWithTheFile(fh); - doSomethingElseWithIt(fh); - -} // 文件已经被析构器自动关闭 - -// 与上面几种方式相比,这种方式有着_明显_的优势: -// 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。 -// 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。 -// 2. 可以注意到,通过这种方式写出来的代码十分简洁。 -// 析构器会在后台关闭文件句柄,不再需要你来操心这些琐事。 -// 3. 这种方式的代码具有异常安全性。 -// 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。 - -// 地道的C++代码应当把RAII的使用扩展到各种类型的资源上,包括: -// - 用unique_ptr和shared_ptr管理的内存 -// - 各种数据容器,例如标准库中的链表、向量(容量自动扩展的数组)、散列表等; -// 当它们脱离作用域时,析构器会自动释放其中储存的内容。 -// - 用lock_guard和unique_lock实现的互斥 -``` -扩展阅读: - -* [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。 -* 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。 -* 可以在 [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)上找到涵盖语言基础和设置编码环境的教程。 +--- +language: C++ +filename: learncpp-cn.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +translators: + - ["Arnie97", "https://github.com/Arnie97"] +lang: zh-cn +--- + +C++是一种系统编程语言。用它的发明者, +[Bjarne Stroustrup的话](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)来说,C++的设计目标是: + +- 成为“更好的C语言” +- 支持数据的抽象与封装 +- 支持面向对象编程 +- 支持泛型编程 + +C++提供了对硬件的紧密控制(正如C语言一样), +能够编译为机器语言,由处理器直接执行。 +与此同时,它也提供了泛型、异常和类等高层功能。 +虽然C++的语法可能比某些出现较晚的语言更复杂,它仍然得到了人们的青睞—— +功能与速度的平衡使C++成为了目前应用最广泛的系统编程语言之一。 + +```c++ +//////////////// +// 与C语言的比较 +//////////////// + +// C++_几乎_是C语言的一个超集,它与C语言的基本语法有许多相同之处, +// 例如变量和函数的声明,原生数据类型等等。 + +// 和C语言一样,在C++中,你的程序会从main()开始执行, +// 该函数的返回值应当为int型,这个返回值会作为程序的退出状态值。 +// 不过,大多数的编译器(gcc,clang等)也接受 void main() 的函数原型。 +// (参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息) +int main(int argc, char** argv) +{ + // 和C语言一样,命令行参数通过argc和argv传递。 + // argc代表命令行参数的数量, + // 而argv是一个包含“C语言风格字符串”(char *)的数组, + // 其中每个字符串代表一个命令行参数的内容, + // 首个命令行参数是调用该程序时所使用的名称。 + // 如果你不关心命令行参数的值,argc和argv可以被忽略。 + // 此时,你可以用int main()作为函数原型。 + + // 退出状态值为0时,表示程序执行成功 + return 0; +} + +// 然而,C++和C语言也有一些区别: + +// 在C++中,字符字面量的大小是一个字节。 +sizeof('c') == 1 + +// 在C语言中,字符字面量的大小与int相同。 +sizeof('c') == sizeof(10) + + +// C++的函数原型与函数定义是严格匹配的 +void func(); // 这个函数不能接受任何参数 + +// 而在C语言中 +void func(); // 这个函数能接受任意数量的参数 + +// 在C++中,用nullptr代替C语言中的NULL +int* ip = nullptr; + +// C++也可以使用C语言的标准头文件, +// 但是需要加上前缀“c”并去掉末尾的“.h”。 +#include + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////// +// 函数重载 +/////////// + +// C++支持函数重载,你可以定义一组名称相同而参数不同的函数。 + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // 解析为 void print(const char*) + print(15); // 解析为 void print(int) +} + +/////////////////// +// 函数参数的默认值 +/////////////////// + +// 你可以为函数的参数指定默认值, +// 它们将会在调用者没有提供相应参数时被使用。 + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // 对两个参数进行一些操作 +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// 默认参数必须放在所有的常规参数之后。 + +void invalidDeclaration(int a = 1, int b) // 这是错误的! +{ +} + + +/////////// +// 命名空间 +/////////// + +// 命名空间为变量、函数和其他声明提供了分离的的作用域。 +// 命名空间可以嵌套使用。 + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // 结束嵌套的命名空间Nested +} // 结束命名空间First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // 如果没有特别指定,就从“Second”中取得所需的内容。 + using namespace Second; + + foo(); // 显示“This is Second::foo” + First::Nested::foo(); // 显示“This is First::Nested::foo” + ::foo(); // 显示“This is global foo” +} + +//////////// +// 输入/输出 +//////////// + +// C++使用“流”来输入输出。<<是流的插入运算符,>>是流提取运算符。 +// cin、cout、和cerr分别代表 +// stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。 + +#include // 引入包含输入/输出流的头文件 + +using namespace std; // 输入输出流在std命名空间(也就是标准库)中。 + +int main() +{ + int myInt; + + // 在标准输出(终端/显示器)中显示 + cout << "Enter your favorite number:\n"; + // 从标准输入(键盘)获得一个值 + cin >> myInt; + + // cout也提供了格式化功能 + cout << "Your favorite number is " << myInt << "\n"; + // 显示“Your favorite number is ” + + cerr << "Used for error messages"; +} + +///////// +// 字符串 +///////// + +// C++中的字符串是对象,它们有很多成员函数 +#include + +using namespace std; // 字符串也在std命名空间(标准库)中。 + +string myString = "Hello"; +string myOtherString = " World"; + +// + 可以用于连接字符串。 +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// C++中的字符串是可变的,具有“值语义”。 +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// 引用 +///////////// + +// 除了支持C语言中的指针类型以外,C++还提供了_引用_。 +// 引用是一种特殊的指针类型,一旦被定义就不能重新赋值,并且不能被设置为空值。 +// 使用引用时的语法与原变量相同: +// 也就是说,对引用类型进行解引用时,不需要使用*; +// 赋值时也不需要用&来取地址。 + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // 建立了一个对foo的引用。 +fooRef += ". Hi!"; // 通过引用来修改foo的值 +cout << fooRef; // "I am foo. Hi!" + +// 这句话的并不会改变fooRef的指向,其效果与“foo = bar”相同。 +// 也就是说,在执行这条语句之后,foo == "I am bar"。 +fooRef = bar; + +const string& barRef = bar; // 建立指向bar的常量引用。 +// 和C语言中一样,(指针和引用)声明为常量时,对应的值不能被修改。 +barRef += ". Hi!"; // 这是错误的,不能修改一个常量引用的值。 + +/////////////////// +// 类与面向对象编程 +/////////////////// + +// 有关类的第一个示例 +#include + +// 声明一个类。 +// 类通常在头文件(.h或.hpp)中声明。 +class Dog { + // 成员变量和成员函数默认情况下是私有(private)的。 + std::string name; + int weight; + +// 在这个标签之后,所有声明都是公有(public)的, +// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止 +public: + + // 默认的构造器 + Dog(); + + // 这里是成员函数声明的一个例子。 + // 可以注意到,我们在此处使用了std::string,而不是using namespace std + // 语句using namespace绝不应当出现在头文件当中。 + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // 如果一个函数不对对象的状态进行修改, + // 应当在声明中加上const。 + // 这样,你就可以对一个以常量方式引用的对象执行该操作。 + // 同时可以注意到,当父类的成员函数需要被子类重写时, + // 父类中的函数必须被显式声明为_虚函数(virtual)_。 + // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。 + virtual void print() const; + + // 函数也可以在class body内部定义。 + // 这样定义的函数会自动成为内联函数。 + void bark() const { std::cout << name << " barks!\n" } + + // 除了构造器以外,C++还提供了析构器。 + // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。 + // 这使得RAII这样的强大范式(参见下文)成为可能。 + // 为了衍生出子类来,基类的析构函数必须定义为虚函数。 + virtual ~Dog(); + +}; // 在类的定义之后,要加一个分号 + +// 类的成员函数通常在.cpp文件中实现。 +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// 对象(例如字符串)应当以引用的形式传递, +// 对于不需要修改的对象,最好使用常量引用。 +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复 +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + std::cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // 此时显示“A dog has been constructed” + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.print(); // 显示“Dog is Barkley and weighs 10 kg” + return 0; +} // 显示“Goodbye Barkley” + +// 继承: + +// 这个类继承了Dog类中的公有(public)和保护(protected)对象 +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // 重写OwnedDogs类的print方法。 + // 如果你不熟悉子类多态的话,可以参考这个页面中的概述: + // http://zh.wikipedia.org/wiki/%E5%AD%90%E7%B1%BB%E5%9E%8B + + // override关键字是可选的,它确保你所重写的是基类中的方法。 + void print() const override; + +private: + std::string owner; +}; + +// 与此同时,在对应的.cpp文件里: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // 调用基类Dog中的print方法 + // "Dog is and weights " + + std::cout << "Dog is owned by " << owner << "\n"; + // "Dog is owned by " +} + +///////////////////// +// 初始化与运算符重载 +///////////////////// + +// 在C++中,通过定义一些特殊名称的函数, +// 你可以重载+、-、*、/等运算符的行为。 +// 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。 + +#include +using namespace std; + +class Point { +public: + // 可以以这样的方式为成员变量设置默认值。 + double x = 0; + double y = 0; + + // 定义一个默认的构造器。 + // 除了将Point初始化为(0, 0)以外,这个函数什么都不做。 + Point() { }; + + // 下面使用的语法称为初始化列表, + // 这是初始化类中成员变量的正确方式。 + Point (double a, double b) : + x(a), + y(b) + { /* 除了初始化成员变量外,什么都不做 */ } + + // 重载 + 运算符 + Point operator+(const Point& rhs) const; + + // 重载 += 运算符 + Point& operator+=(const Point& rhs); + + // 增加 - 和 -= 运算符也是有意义的,但这里不再赘述。 +}; + +Point Point::operator+(const Point& rhs) const +{ + // 创建一个新的点, + // 其横纵坐标分别为这个点与另一点在对应方向上的坐标之和。 + return Point(x + rhs.x, y + rhs.y); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // 这里使用了Point类型的运算符“+” + // 调用up(Point类型)的“+”方法,并以right作为函数的参数 + Point result = up + right; + // 显示“Result is upright (1,1)” + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +/////////// +// 异常处理 +/////////// + +// 标准库中提供了一些基本的异常类型 +// (参见http://en.cppreference.com/w/cpp/error/exception) +// 但是,其他任何类型也可以作为一个异常被拋出 +#include + +// 在_try_代码块中拋出的异常可以被随后的_catch_捕获。 +try { + // 不要用 _new_关键字在堆上为异常分配空间。 + throw std::exception("A problem occurred"); +} +// 如果拋出的异常是一个对象,可以用常量引用来捕获它 +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// 捕获尚未被_catch_处理的所有错误 +} catch (...) +{ + std::cout << "Unknown exception caught"; + throw; // 重新拋出异常 +} + +/////// +// RAII +/////// + +// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization), +// 它被视作C++中最强大的编程范式之一。 +// 简单说来,它指的是,用构造函数来获取一个对象的资源, +// 相应的,借助析构函数来释放对象的资源。 + +// 为了理解这一范式的用处,让我们考虑某个函数使用文件句柄时的情况: +void doSomethingWithAFile(const char* filename) +{ + // 首先,让我们假设一切都会顺利进行。 + + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // 关闭文件句柄 +} + +// 不幸的是,随着错误处理机制的引入,事情会变得复杂。 +// 假设fopen函数有可能执行失败, +// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。 +// (虽然异常是C++中处理错误的推荐方式, +// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。 +// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。 +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 + if (fh == nullptr) // 当执行失败是,返回的指针是nullptr + return false; // 向调用者汇报错误 + + // 假设每个函数会在执行失败时返回false + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // 关闭文件句柄,避免造成内存泄漏。 + return false; // 反馈错误 + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // 关闭文件句柄 + return false; // 反馈错误 + } + + fclose(fh); // 关闭文件句柄 + return true; // 指示函数已成功执行 +} + +// C语言的程序员通常会借助goto语句简化上面的代码: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // 关闭文件 + return true; // 执行成功 + +failure: + fclose(fh); + return false; // 反馈错误 +} + +// 如果用异常捕获机制来指示错误的话, +// 代码会变得清晰一些,但是仍然有优化的余地。 +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 + if (fh == nullptr) + throw std::exception("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // 保证出错的时候文件被正确关闭 + throw; // 之后,重新抛出这个异常 + } + + fclose(fh); // 关闭文件 + // 所有工作顺利完成 +} + +// 相比之下,使用C++中的文件流类(fstream)时, +// fstream会利用自己的析构器来关闭文件句柄。 +// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。 +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream是输入文件流(input file stream)的简称 + std::ifstream fh(filename); // 打开一个文件 + + // 对文件进行一些操作 + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // 文件已经被析构器自动关闭 + +// 与上面几种方式相比,这种方式有着_明显_的优势: +// 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。 +// 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。 +// 2. 可以注意到,通过这种方式写出来的代码十分简洁。 +// 析构器会在后台关闭文件句柄,不再需要你来操心这些琐事。 +// 3. 这种方式的代码具有异常安全性。 +// 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。 + +// 地道的C++代码应当把RAII的使用扩展到各种类型的资源上,包括: +// - 用unique_ptr和shared_ptr管理的内存 +// - 各种数据容器,例如标准库中的链表、向量(容量自动扩展的数组)、散列表等; +// 当它们脱离作用域时,析构器会自动释放其中储存的内容。 +// - 用lock_guard和unique_lock实现的互斥 +``` +扩展阅读: + +* [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。 +* 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。 +* 可以在 [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)上找到涵盖语言基础和设置编码环境的教程。 diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown index 3f6ccbcf..a429fcbc 100644 --- a/zh-cn/elisp-cn.html.markdown +++ b/zh-cn/elisp-cn.html.markdown @@ -1,345 +1,345 @@ ---- -language: elisp -contributors: - - ["Bastien Guerry", "http://bzg.fr"] -translators: - - ["Chenbo Li", "http://binarythink.net"] -filename: learn-emacs-lisp-zh.el -lang: zh-cn ---- - -```scheme -;; 15分钟学会Emacs Lisp (v0.2a) -;;(作者:bzg,https://github.com/bzg -;; 译者:lichenbo,http://douban.com/people/lichenbo) -;; -;; 请先阅读Peter Norvig的一篇好文: -;; http://norvig.com/21-days.html -;; (译者注:中文版请见http://blog.youxu.info/21-days/) -;; -;; 之后安装GNU Emacs 24.3: -;; -;; Debian: apt-get install emacs (视具体发行版而定) -;; MacOSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg -;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip -;; -;; 更多信息可以在这里找到: -;; http://www.gnu.org/software/emacs/#Obtaining - -;; 很重要的警告: -;; -;; 按照这个教程来学习并不会对你的电脑有任何损坏 -;; 除非你自己在学习的过程中愤怒地把它砸了 -;; 如果出现了这种情况,我不会承担任何责任 -;; -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; 打开emacs -;; -;; 按'q'消除欢迎界面 -;; -;; 现在请注意窗口底部的那一个灰色长条 -;; -;; "*scratch*" 是你现在编辑界面的名字。 -;; 这个编辑界面叫做一个"buffer"。 -;; -;; 每当你打开Emacs时,都会默认打开这个scratch buffer -;; 此时你并没有在编辑任何文件,而是在编辑一个buffer -;; 之后你可以将这个buffer保存到一个文件中。 -;; -;; 之后的"Lisp interaction" 则是表明我们可以用的某组命令 -;; -;; Emacs在每个buffer中都有一组内置的命令 -;; 而当你激活某种特定的模式时,就可以使用相应的命令 -;; 这里我们使用`lisp-interaction-mode', -;; 这样我们就可以使用内置的Emacs Lisp(以下简称Elisp)命令了。 - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; 分号是注释开始的标志 -;; -;; Elisp 是由符号表达式构成的 (即"s-表达式"或"s式"): -(+ 2 2) - -;; 这个s式的意思是 "对2进行加2操作". - -;; s式周围有括号,而且也可以嵌套: -(+ 2 (+ 1 1)) - -;; 一个s式可以包含原子符号或者其他s式 -;; 在上面的例子中,1和2是原子符号 -;; (+ 2 (+ 1 1)) 和 (+ 1 1) 是s式. - -;; 在 `lisp-interaction-mode' 中你可以计算s式. -;; 把光标移到闭括号后,之后按下ctrl+j(以后简写为'C-j') - -(+ 3 (+ 1 2)) -;; ^ 光标放到这里 -;; 按下`C-j' 就会输出 6 - -;; `C-j' 会在buffer中插入当前运算的结果 - -;; 而`C-xC-e' 则会在emacs最底部显示结果,也就是被称作"minibuffer"的区域 -;; 为了避免把我们的buffer填满无用的结果,我们以后会一直用`C-xC-e' - -;; `setq' 可以将一个值赋给一个变量 -(setq my-name "Bastien") -;; `C-xC-e' 输出 "Bastien" (在 mini-buffer 中显示) - -;; `insert' 会在光标处插入字符串: -(insert "Hello!") -;; `C-xC-e' 输出 "Hello!" - -;; 在这里我们只传给了insert一个参数"Hello!", 但是 -;; 我们也可以传给它更多的参数,比如2个: - -(insert "Hello" " world!") -;; `C-xC-e' 输出 "Hello world!" - -;; 你也可以用变量名来代替字符串 -(insert "Hello, I am " my-name) -;; `C-xC-e' 输出 "Hello, I am Bastien" - -;; 你可以把s式嵌入函数中 -(defun hello () (insert "Hello, I am " my-name)) -;; `C-xC-e' 输出 hello - -;; 现在执行这个函数 -(hello) -;; `C-xC-e' 输出 Hello, I am Bastien - -;; 函数中空括号的意思是我们不需要接受任何参数 -;; 但是我们不能一直总是用my-name这个变量 -;; 所以我们现在使我们的函数接受一个叫做"name"的参数 - -(defun hello (name) (insert "Hello " name)) -;; `C-xC-e' 输出 hello - -;; 现在我们调用这个函数,并且将"you"作为参数传递 - -(hello "you") -;; `C-xC-e' 输出 "Hello you" - -;; 成功! - -;; 现在我们可以休息一下 - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; 下面我们在新的窗口中新建一个名为 "*test*" 的buffer: - -(switch-to-buffer-other-window "*test*") -;; `C-xC-e' 这时屏幕上会显示两个窗口,而光标此时位于*test* buffer内 - -;; 用鼠标单击上面的buffer就会使光标移回。 -;; 或者你可以使用 `C-xo' 使得光标跳到另一个窗口中 - -;; 你可以用 `progn'命令将s式结合起来: -(progn - (switch-to-buffer-other-window "*test*") - (hello "you")) -;; `C-xC-e' 此时屏幕分为两个窗口,并且在*test* buffer中显示"Hello you" - -;; 现在为了简洁,我们需要在每个s式后面都使用`C-xC-e'来执行,后面就不再说明了 - -;; 记得可以用过鼠标或者`C-xo'回到*scratch*这个buffer。 - -;; 清除当前buffer也是常用操作之一: -(progn - (switch-to-buffer-other-window "*test*") - (erase-buffer) - (hello "there")) - -;; 也可以回到其他的窗口中 -(progn - (switch-to-buffer-other-window "*test*") - (erase-buffer) - (hello "you") - (other-window 1)) - -;; 你可以用 `let' 将一个值和一个局部变量绑定: -(let ((local-name "you")) - (switch-to-buffer-other-window "*test*") - (erase-buffer) - (hello local-name) - (other-window 1)) - -;; 这里我们就不需要使用 `progn' 了, 因为 `let' 也可以将很多s式组合起来。 - -;; 格式化字符串的方法: -(format "Hello %s!\n" "visitor") - -;; %s 是字符串占位符,这里被"visitor"替代. -;; \n 是换行符。 - -;; 现在我们用格式化的方法再重写一下我们的函数: -(defun hello (name) - (insert (format "Hello %s!\n" name))) - -(hello "you") - -;; 我们再用`let'新建另一个函数: -(defun greeting (name) - (let ((your-name "Bastien")) - (insert (format "Hello %s!\n\nI am %s." - name ; the argument of the function - your-name ; the let-bound variable "Bastien" - )))) - -;; 之后执行: -(greeting "you") - -;; 有些函数可以和用户交互: -(read-from-minibuffer "Enter your name: ") - -;; 这个函数会返回在执行时用户输入的信息 - -;; 现在我们让`greeting'函数显示你的名字: -(defun greeting (from-name) - (let ((your-name (read-from-minibuffer "Enter your name: "))) - (insert (format "Hello!\n\nI am %s and you are %s." - from-name ; the argument of the function - your-name ; the let-bound var, entered at prompt - )))) - -(greeting "Bastien") - -;; 我们让结果在另一个窗口中显示: -(defun greeting (from-name) - (let ((your-name (read-from-minibuffer "Enter your name: "))) - (switch-to-buffer-other-window "*test*") - (erase-buffer) - (insert (format "Hello %s!\n\nI am %s." your-name from-name)) - (other-window 1))) - -;; 测试一下: -(greeting "Bastien") - -;; 第二节结束,休息一下吧。 - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; -;; 我们将一些名字存到列表中: -(setq list-of-names '("Sarah" "Chloe" "Mathilde")) - -;; 用 `car'来取得第一个名字: -(car list-of-names) - -;; 用 `cdr'取得剩下的名字: -(cdr list-of-names) - -;; 用 `push'把名字添加到列表的开头: -(push "Stephanie" list-of-names) - -;; 注意: `car' 和 `cdr' 并不修改列表本身, 但是 `push' 却会对列表本身进行操作. -;; 这个区别是很重要的: 有些函数没有任何副作用(比如`car') -;; 但还有一些却是有的 (比如 `push'). - -;; 我们来对`list-of-names'列表中的每一个元素都使用hello函数: -(mapcar 'hello list-of-names) - -;; 将 `greeting' 改进,使的我们能够对`list-of-names'中的所有名字执行: -(defun greeting () - (switch-to-buffer-other-window "*test*") - (erase-buffer) - (mapcar 'hello list-of-names) - (other-window 1)) - -(greeting) - -;; 记得我们之前定义的 `hello' 函数吗? 这个函数接受一个参数,名字。 -;; `mapcar' 调用 `hello', 并将`list-of-names'作为参数先后传给`hello' - -;; 现在我们对显示的buffer中的内容进行一些更改: - -(defun replace-hello-by-bonjour () - (switch-to-buffer-other-window "*test*") - (goto-char (point-min)) - (while (search-forward "Hello") - (replace-match "Bonjour")) - (other-window 1)) - -;; (goto-char (point-min)) 将光标移到buffer的开始 -;; (search-forward "Hello") 查找字符串"Hello" -;; (while x y) 当x返回某个值时执行y这个s式 -;; 当x返回`nil' (空), 退出循环 - -(replace-hello-by-bonjour) - -;; 你会看到所有在*test* buffer中出现的"Hello"字样都被换成了"Bonjour" - -;; 你也会得到以下错误提示: "Search failed: Hello". -;; -;; 如果要避免这个错误, 你需要告诉 `search-forward' 这个命令是否在 -;; buffer的某个地方停止查找, 并且在什么都没找到时是否应该不给出错误提示 - -;; (search-forward "Hello" nil t) 可以达到这个要求: - -;; `nil' 参数的意思是 : 查找并不限于某个范围内 -;; `t' 参数的意思是: 当什么都没找到时,不给出错误提示 - -;; 在下面的函数中,我们用到了s式,并且不给出任何错误提示: - -(defun hello-to-bonjour () - (switch-to-buffer-other-window "*test*") - (erase-buffer) - ;; 为`list-of-names'中的每个名字调用hello - (mapcar 'hello list-of-names) - (goto-char (point-min)) - ;; 将"Hello" 替换为"Bonjour" - (while (search-forward "Hello" nil t) - (replace-match "Bonjour")) - (other-window 1)) - -(hello-to-bonjour) - -;; 给这些名字加粗: - -(defun boldify-names () - (switch-to-buffer-other-window "*test*") - (goto-char (point-min)) - (while (re-search-forward "Bonjour \\(.+\\)!" nil t) - (add-text-properties (match-beginning 1) - (match-end 1) - (list 'face 'bold))) - (other-window 1)) - -;; 这个函数使用了 `re-search-forward': -;; 和查找一个字符串不同,你用这个命令可以查找一个模式,即正则表达式 - -;; 正则表达式 "Bonjour \\(.+\\)!" 的意思是: -;; 字符串 "Bonjour ", 之后跟着 -;; 一组 | \\( ... \\) 结构 -;; 任意字符 | . 的含义 -;; 有可能重复的 | + 的含义 -;; 之后跟着 "!" 这个字符串 - -;; 准备好了?试试看。 - -(boldify-names) - -;; `add-text-properties' 可以添加文字属性, 比如文字样式 - -;; 好的,我们成功了! - -;; 如果你想对一个变量或者函数有更多的了解: -;; -;; C-h v 变量 回车 -;; C-h f 函数 回车 -;; -;; 阅读Emacs Lisp官方文档: -;; -;; C-h i m elisp 回车 -;; -;; 在线阅读Emacs Lisp文档: -;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html - -;; 感谢以下同学的建议和反馈: -;; - Wes Hardaker -;; - notbob -;; - Kevin Montuori -;; - Arne Babenhauserheide -;; - Alan Schmitt -;; - spacegoing -``` - +--- +language: elisp +contributors: + - ["Bastien Guerry", "http://bzg.fr"] +translators: + - ["Chenbo Li", "http://binarythink.net"] +filename: learn-emacs-lisp-zh.el +lang: zh-cn +--- + +```scheme +;; 15分钟学会Emacs Lisp (v0.2a) +;;(作者:bzg,https://github.com/bzg +;; 译者:lichenbo,http://douban.com/people/lichenbo) +;; +;; 请先阅读Peter Norvig的一篇好文: +;; http://norvig.com/21-days.html +;; (译者注:中文版请见http://blog.youxu.info/21-days/) +;; +;; 之后安装GNU Emacs 24.3: +;; +;; Debian: apt-get install emacs (视具体发行版而定) +;; MacOSX: http://emacsformacosx.com/emacs-builds/Emacs-24.3-universal-10.6.8.dmg +;; Windows: http://ftp.gnu.org/gnu/windows/emacs/emacs-24.3-bin-i386.zip +;; +;; 更多信息可以在这里找到: +;; http://www.gnu.org/software/emacs/#Obtaining + +;; 很重要的警告: +;; +;; 按照这个教程来学习并不会对你的电脑有任何损坏 +;; 除非你自己在学习的过程中愤怒地把它砸了 +;; 如果出现了这种情况,我不会承担任何责任 +;; +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; 打开emacs +;; +;; 按'q'消除欢迎界面 +;; +;; 现在请注意窗口底部的那一个灰色长条 +;; +;; "*scratch*" 是你现在编辑界面的名字。 +;; 这个编辑界面叫做一个"buffer"。 +;; +;; 每当你打开Emacs时,都会默认打开这个scratch buffer +;; 此时你并没有在编辑任何文件,而是在编辑一个buffer +;; 之后你可以将这个buffer保存到一个文件中。 +;; +;; 之后的"Lisp interaction" 则是表明我们可以用的某组命令 +;; +;; Emacs在每个buffer中都有一组内置的命令 +;; 而当你激活某种特定的模式时,就可以使用相应的命令 +;; 这里我们使用`lisp-interaction-mode', +;; 这样我们就可以使用内置的Emacs Lisp(以下简称Elisp)命令了。 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; 分号是注释开始的标志 +;; +;; Elisp 是由符号表达式构成的 (即"s-表达式"或"s式"): +(+ 2 2) + +;; 这个s式的意思是 "对2进行加2操作". + +;; s式周围有括号,而且也可以嵌套: +(+ 2 (+ 1 1)) + +;; 一个s式可以包含原子符号或者其他s式 +;; 在上面的例子中,1和2是原子符号 +;; (+ 2 (+ 1 1)) 和 (+ 1 1) 是s式. + +;; 在 `lisp-interaction-mode' 中你可以计算s式. +;; 把光标移到闭括号后,之后按下ctrl+j(以后简写为'C-j') + +(+ 3 (+ 1 2)) +;; ^ 光标放到这里 +;; 按下`C-j' 就会输出 6 + +;; `C-j' 会在buffer中插入当前运算的结果 + +;; 而`C-xC-e' 则会在emacs最底部显示结果,也就是被称作"minibuffer"的区域 +;; 为了避免把我们的buffer填满无用的结果,我们以后会一直用`C-xC-e' + +;; `setq' 可以将一个值赋给一个变量 +(setq my-name "Bastien") +;; `C-xC-e' 输出 "Bastien" (在 mini-buffer 中显示) + +;; `insert' 会在光标处插入字符串: +(insert "Hello!") +;; `C-xC-e' 输出 "Hello!" + +;; 在这里我们只传给了insert一个参数"Hello!", 但是 +;; 我们也可以传给它更多的参数,比如2个: + +(insert "Hello" " world!") +;; `C-xC-e' 输出 "Hello world!" + +;; 你也可以用变量名来代替字符串 +(insert "Hello, I am " my-name) +;; `C-xC-e' 输出 "Hello, I am Bastien" + +;; 你可以把s式嵌入函数中 +(defun hello () (insert "Hello, I am " my-name)) +;; `C-xC-e' 输出 hello + +;; 现在执行这个函数 +(hello) +;; `C-xC-e' 输出 Hello, I am Bastien + +;; 函数中空括号的意思是我们不需要接受任何参数 +;; 但是我们不能一直总是用my-name这个变量 +;; 所以我们现在使我们的函数接受一个叫做"name"的参数 + +(defun hello (name) (insert "Hello " name)) +;; `C-xC-e' 输出 hello + +;; 现在我们调用这个函数,并且将"you"作为参数传递 + +(hello "you") +;; `C-xC-e' 输出 "Hello you" + +;; 成功! + +;; 现在我们可以休息一下 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; 下面我们在新的窗口中新建一个名为 "*test*" 的buffer: + +(switch-to-buffer-other-window "*test*") +;; `C-xC-e' 这时屏幕上会显示两个窗口,而光标此时位于*test* buffer内 + +;; 用鼠标单击上面的buffer就会使光标移回。 +;; 或者你可以使用 `C-xo' 使得光标跳到另一个窗口中 + +;; 你可以用 `progn'命令将s式结合起来: +(progn + (switch-to-buffer-other-window "*test*") + (hello "you")) +;; `C-xC-e' 此时屏幕分为两个窗口,并且在*test* buffer中显示"Hello you" + +;; 现在为了简洁,我们需要在每个s式后面都使用`C-xC-e'来执行,后面就不再说明了 + +;; 记得可以用过鼠标或者`C-xo'回到*scratch*这个buffer。 + +;; 清除当前buffer也是常用操作之一: +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "there")) + +;; 也可以回到其他的窗口中 +(progn + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello "you") + (other-window 1)) + +;; 你可以用 `let' 将一个值和一个局部变量绑定: +(let ((local-name "you")) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (hello local-name) + (other-window 1)) + +;; 这里我们就不需要使用 `progn' 了, 因为 `let' 也可以将很多s式组合起来。 + +;; 格式化字符串的方法: +(format "Hello %s!\n" "visitor") + +;; %s 是字符串占位符,这里被"visitor"替代. +;; \n 是换行符。 + +;; 现在我们用格式化的方法再重写一下我们的函数: +(defun hello (name) + (insert (format "Hello %s!\n" name))) + +(hello "you") + +;; 我们再用`let'新建另一个函数: +(defun greeting (name) + (let ((your-name "Bastien")) + (insert (format "Hello %s!\n\nI am %s." + name ; the argument of the function + your-name ; the let-bound variable "Bastien" + )))) + +;; 之后执行: +(greeting "you") + +;; 有些函数可以和用户交互: +(read-from-minibuffer "Enter your name: ") + +;; 这个函数会返回在执行时用户输入的信息 + +;; 现在我们让`greeting'函数显示你的名字: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (insert (format "Hello!\n\nI am %s and you are %s." + from-name ; the argument of the function + your-name ; the let-bound var, entered at prompt + )))) + +(greeting "Bastien") + +;; 我们让结果在另一个窗口中显示: +(defun greeting (from-name) + (let ((your-name (read-from-minibuffer "Enter your name: "))) + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (insert (format "Hello %s!\n\nI am %s." your-name from-name)) + (other-window 1))) + +;; 测试一下: +(greeting "Bastien") + +;; 第二节结束,休息一下吧。 + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; 我们将一些名字存到列表中: +(setq list-of-names '("Sarah" "Chloe" "Mathilde")) + +;; 用 `car'来取得第一个名字: +(car list-of-names) + +;; 用 `cdr'取得剩下的名字: +(cdr list-of-names) + +;; 用 `push'把名字添加到列表的开头: +(push "Stephanie" list-of-names) + +;; 注意: `car' 和 `cdr' 并不修改列表本身, 但是 `push' 却会对列表本身进行操作. +;; 这个区别是很重要的: 有些函数没有任何副作用(比如`car') +;; 但还有一些却是有的 (比如 `push'). + +;; 我们来对`list-of-names'列表中的每一个元素都使用hello函数: +(mapcar 'hello list-of-names) + +;; 将 `greeting' 改进,使的我们能够对`list-of-names'中的所有名字执行: +(defun greeting () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + (mapcar 'hello list-of-names) + (other-window 1)) + +(greeting) + +;; 记得我们之前定义的 `hello' 函数吗? 这个函数接受一个参数,名字。 +;; `mapcar' 调用 `hello', 并将`list-of-names'作为参数先后传给`hello' + +;; 现在我们对显示的buffer中的内容进行一些更改: + +(defun replace-hello-by-bonjour () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (search-forward "Hello") + (replace-match "Bonjour")) + (other-window 1)) + +;; (goto-char (point-min)) 将光标移到buffer的开始 +;; (search-forward "Hello") 查找字符串"Hello" +;; (while x y) 当x返回某个值时执行y这个s式 +;; 当x返回`nil' (空), 退出循环 + +(replace-hello-by-bonjour) + +;; 你会看到所有在*test* buffer中出现的"Hello"字样都被换成了"Bonjour" + +;; 你也会得到以下错误提示: "Search failed: Hello". +;; +;; 如果要避免这个错误, 你需要告诉 `search-forward' 这个命令是否在 +;; buffer的某个地方停止查找, 并且在什么都没找到时是否应该不给出错误提示 + +;; (search-forward "Hello" nil t) 可以达到这个要求: + +;; `nil' 参数的意思是 : 查找并不限于某个范围内 +;; `t' 参数的意思是: 当什么都没找到时,不给出错误提示 + +;; 在下面的函数中,我们用到了s式,并且不给出任何错误提示: + +(defun hello-to-bonjour () + (switch-to-buffer-other-window "*test*") + (erase-buffer) + ;; 为`list-of-names'中的每个名字调用hello + (mapcar 'hello list-of-names) + (goto-char (point-min)) + ;; 将"Hello" 替换为"Bonjour" + (while (search-forward "Hello" nil t) + (replace-match "Bonjour")) + (other-window 1)) + +(hello-to-bonjour) + +;; 给这些名字加粗: + +(defun boldify-names () + (switch-to-buffer-other-window "*test*") + (goto-char (point-min)) + (while (re-search-forward "Bonjour \\(.+\\)!" nil t) + (add-text-properties (match-beginning 1) + (match-end 1) + (list 'face 'bold))) + (other-window 1)) + +;; 这个函数使用了 `re-search-forward': +;; 和查找一个字符串不同,你用这个命令可以查找一个模式,即正则表达式 + +;; 正则表达式 "Bonjour \\(.+\\)!" 的意思是: +;; 字符串 "Bonjour ", 之后跟着 +;; 一组 | \\( ... \\) 结构 +;; 任意字符 | . 的含义 +;; 有可能重复的 | + 的含义 +;; 之后跟着 "!" 这个字符串 + +;; 准备好了?试试看。 + +(boldify-names) + +;; `add-text-properties' 可以添加文字属性, 比如文字样式 + +;; 好的,我们成功了! + +;; 如果你想对一个变量或者函数有更多的了解: +;; +;; C-h v 变量 回车 +;; C-h f 函数 回车 +;; +;; 阅读Emacs Lisp官方文档: +;; +;; C-h i m elisp 回车 +;; +;; 在线阅读Emacs Lisp文档: +;; https://www.gnu.org/software/emacs/manual/html_node/eintr/index.html + +;; 感谢以下同学的建议和反馈: +;; - Wes Hardaker +;; - notbob +;; - Kevin Montuori +;; - Arne Babenhauserheide +;; - Alan Schmitt +;; - spacegoing +``` + diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown index ca08b36b..bb1ab79a 100644 --- a/zh-cn/matlab-cn.html.markdown +++ b/zh-cn/matlab-cn.html.markdown @@ -1,504 +1,504 @@ ---- -language: MATLAB -filename: matlab-cn.m -contributors: - - ["mendozao", "http://github.com/mendozao"] - - ["jamesscottbrown", "http://jamesscottbrown.com"] -translators: - - ["sunxb10", "https://github.com/sunxb10"] -lang: zh-cn - ---- - -MATLAB 是 MATrix LABoratory(矩阵实验室)的缩写。 -它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。 - -如果您有任何需要反馈或交流的内容,请联系本教程作者: -[@the_ozzinator](https://twitter.com/the_ozzinator) -或 [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。 - -```matlab -% 以百分号作为注释符 - -%{ -多行注释 -可以 -这样 -表示 -%} - -% 指令可以随意跨行,但需要在跨行处用 '...' 标明: - a = 1 + 2 + ... - + 4 - -% 可以在MATLAB中直接向操作系统发出指令 -!ping google.com - -who % 显示内存中的所有变量 -whos % 显示内存中的所有变量以及它们的类型 -clear % 清除内存中的所有变量 -clear('A') % 清除指定的变量 -openvar('A') % 在变量编辑器中编辑指定变量 - -clc % 清除命令窗口中显示的所有指令 -diary % 将命令窗口中的内容写入本地文件 -ctrl-c % 终止当前计算 - -edit('myfunction.m') % 在编辑器中打开指定函数或脚本 -type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码 - -profile on % 打开 profile 代码分析工具 -profile off % 关闭 profile 代码分析工具 -profile viewer % 查看 profile 代码分析工具的分析结果 - -help command % 在命令窗口中显示指定命令的帮助文档 -doc command % 在帮助窗口中显示指定命令的帮助文档 -lookfor command % 在所有 MATLAB 内置函数的头部注释块的第一行中搜索指定命令 -lookfor command -all % 在所有 MATLAB 内置函数的整个头部注释块中搜索指定命令 - - -% 输出格式 -format short % 浮点数保留 4 位小数 -format long % 浮点数保留 15 位小数 -format bank % 金融格式,浮点数只保留 2 位小数 -fprintf('text') % 在命令窗口中显示 "text" -disp('text') % 在命令窗口中显示 "text" - - -% 变量与表达式 -myVariable = 4 % 命令窗口中将新创建的变量 -myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果 -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 -a = 2; b = 3; -c = exp(a)*sin(pi/2) % c = 7.3891 - - -% 调用函数有两种方式: -% 标准函数语法: -load('myFile.mat', 'y') % 参数放在括号内,以英文逗号分隔 -% 指令语法: -load myFile.mat y % 不加括号,以空格分隔参数 -% 注意在指令语法中参数不需要加引号:在这种语法下,所有输入参数都只能是文本文字, -% 不能是变量的具体值,同样也不能是输出变量 -[V,D] = eig(A); % 这条函数调用无法转换成等价的指令语法 -[~,D] = eig(A); % 如果结果中只需要 D 而不需要 V 则可以这样写 - - - -% 逻辑运算 -1 > 5 % 假,ans = 0 -10 >= 10 % 真,ans = 1 -3 ~= 4 % 不等于 -> ans = 1 -3 == 3 % 等于 -> ans = 1 -3 > 1 && 4 > 1 % 与 -> ans = 1 -3 > 1 || 4 > 1 % 或 -> ans = 1 -~1 % 非 -> ans = 0 - -% 逻辑运算可直接应用于矩阵,运算结果也是矩阵 -A > 5 -% 对矩阵中每个元素做逻辑运算,若为真,则在运算结果的矩阵中对应位置的元素就是 1 -A( A > 5 ) -% 如此返回的向量,其元素就是 A 矩阵中所有逻辑运算为真的元素 - -% 字符串 -a = 'MyString' -length(a) % ans = 8 -a(2) % ans = y -[a,a] % ans = MyStringMyString -b = '字符串' % MATLAB目前已经可以支持包括中文在内的多种文字 -length(b) % ans = 3 -b(2) % ans = 符 -[b,b] % ans = 字符串字符串 - - -% 元组(cell 数组) -a = {'one', 'two', 'three'} -a(1) % ans = 'one' - 返回一个元组 -a{1} % ans = one - 返回一个字符串 - - -% 结构体 -A.b = {'one','two'}; -A.c = [1 2]; -A.d.e = false; - - -% 向量 -x = [4 32 53 7 1] -x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0 -x(2:3) % ans = 32 53 -x(2:end) % ans = 32 53 7 1 - -x = [4; 32; 53; 7; 1] % 列向量 - -x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 - - -% 矩阵 -A = [1 2 3; 4 5 6; 7 8 9] -% 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素 -% A = - -% 1 2 3 -% 4 5 6 -% 7 8 9 - -A(2,3) % ans = 6,A(row, column) -A(6) % ans = 8 -% (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素) - - -A(2,3) = 42 % 将第 2 行第 3 列的元素设为 42 -% A = - -% 1 2 3 -% 4 5 42 -% 7 8 9 - -A(2:3,2:3) % 取原矩阵中的一块作为新矩阵 -%ans = - -% 5 42 -% 8 9 - -A(:,1) % 第 1 列的所有元素 -%ans = - -% 1 -% 4 -% 7 - -A(1,:) % 第 1 行的所有元素 -%ans = - -% 1 2 3 - -[A ; A] % 将两个矩阵上下相接构成新矩阵 -%ans = - -% 1 2 3 -% 4 5 42 -% 7 8 9 -% 1 2 3 -% 4 5 42 -% 7 8 9 - -% 等价于 -vertcat(A, A); - - -[A , A] % 将两个矩阵左右相接构成新矩阵 - -%ans = - -% 1 2 3 1 2 3 -% 4 5 42 4 5 42 -% 7 8 9 7 8 9 - -% 等价于 -horzcat(A, A); - - -A(:, [3 1 2]) % 重新排布原矩阵的各列 -%ans = - -% 3 1 2 -% 42 4 5 -% 9 7 8 - -size(A) % 返回矩阵的行数和列数,ans = 3 3 - -A(1, :) =[] % 删除矩阵的第 1 行 -A(:, 1) =[] % 删除矩阵的第 1 列 - -transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点) -ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数),等价于 A' - - -% 元素运算 vs. 矩阵运算 -% 单独运算符就是对矩阵整体进行矩阵运算 -% 在运算符加上英文句点就是对矩阵中的元素进行元素计算 -% 示例如下: -A * B % 矩阵乘法,要求 A 的列数等于 B 的行数 -A .* B % 元素乘法,要求 A 和 B 形状一致,即两矩阵行列数完全一致 - % 元素乘法的结果是与 A 和 B 形状一致的矩阵 - % 其每个元素等于 A 对应位置的元素乘 B 对应位置的元素 - -% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算: -exp(A) % 对矩阵中每个元素做指数运算 -expm(A) % 对矩阵整体做指数运算 -sqrt(A) % 对矩阵中每个元素做开方运算 -sqrtm(A) % 对矩阵整体做开方运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵) - - -% 绘图 -x = 0:0.1:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi - % 其中 pi 为圆周率 -y = sin(x); -plot(x,y) -xlabel('x axis') -ylabel('y axis') -title('Plot of y = sin(x)') -axis([0 2*pi -1 1]) % x 轴范围是从 0 到 2*pi,y 轴范围是从 -1 到 1 - -plot(x,y1,'-',x,y2,'--',x,y3,':') % 在同一张图中绘制多条曲线 -legend('Line 1 label', 'Line 2 label') % 为图片加注图例 -% 图例数量应当小于或等于实际绘制的曲线数目,从 plot 绘制的第一条曲线开始对应 - -% 在同一张图上绘制多条曲线的另一种方法: -% 使用 hold on,令系统保留前次绘图结果并在其上直接叠加新的曲线, -% 如果没有 hold on,则每个 plot 都会首先清除之前的绘图结果再进行绘制。 -% 在 hold on 和 hold off 中可以放置任意多的 plot 指令, -% 它们和 hold on 前最后一个 plot 指令的结果都将显示在同一张图中。 -plot(x, y1) -hold on -plot(x, y2) -plot(x, y3) -plot(x, y4) -hold off - -loglog(x, y) % 对数—对数绘图 -semilogx(x, y) % 半对数(x 轴对数)绘图 -semilogy(x, y) % 半对数(y 轴对数)绘图 - -fplot (@(x) x^2, [2,5]) % 绘制函数 x^2 在 [2, 5] 区间的曲线 - -grid on % 在绘制的图中显示网格,使用 grid off 可取消网格显示 -axis square % 将当前坐标系设定为正方形(保证在图形显示上各轴等长) -axis equal % 将当前坐标系设定为相等(保证在实际数值上各轴等长) - -scatter(x, y); % 散点图 -hist(x); % 直方图 - -z = sin(x); -plot3(x,y,z); % 绘制三维曲线 - -pcolor(A) % 伪彩色图(热图) -contour(A) % 等高线图 -mesh(A) % 网格曲面图 - -h = figure % 创建新的图片对象并返回其句柄 h -figure(h) % 将句柄 h 对应的图片作为当前图片 -close(h) % 关闭句柄 h 对应的图片 -close all % 关闭 MATLAB 中所用打开的图片 -close % 关闭当前图片 - -shg % 显示图形窗口 -clf clear % 清除图形窗口中的图像,并重置图像属性 - -% 图像属性可以通过图像句柄进行设定 -% 在创建图像时可以保存图像句柄以便于设置 -% 也可以用 gcf 函数返回当前图像的句柄 -h = plot(x, y); % 在创建图像时显式地保存图像句柄 -set(h, 'Color', 'r') -% 颜色代码: -% 'y' 黄色,'m' 洋红,'c' 青色 -% 'r' 红色,'g' 绿色,'b' 蓝色 -% 'w' 白色,'k' 黑色 -set(h, 'Color', [0.5, 0.5, 0.4]) -% 也可以使用 RGB 值指定颜色 -set(h, 'LineStyle', '--') -% 线型代码:'--' 实线,'---' 虚线,':' 点线,'-.' 点划线,'none' 不划线 -get(h, 'LineStyle') -% 获取当前句柄的线型 - - -% 用 gca 函数返回当前图像的坐标轴句柄 -set(gca, 'XDir', 'reverse'); % 令 x 轴反向 - -% 用 subplot 指令创建平铺排列的多张子图 -subplot(2,3,1); % 选择 2 x 3 排列的子图中的第 1 张图 -plot(x1); title('First Plot') % 在选中的图中绘图 -subplot(2,3,2); % 选择 2 x 3 排列的子图中的第 2 张图 -plot(x2); title('Second Plot') % 在选中的图中绘图 - - -% 要调用函数或脚本,必须保证它们在你的当前工作目录中 -path % 显示当前工作目录 -addpath /path/to/dir % 将指定路径加入到当前工作目录中 -rmpath /path/to/dir % 将指定路径从当前工作目录中删除 -cd /path/to/move/into % 以制定路径作为当前工作目录 - - -% 变量可保存到 .mat 格式的本地文件 -save('myFileName.mat') % 保存当前工作空间中的所有变量 -load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 - - -% .m 脚本文件 -% 脚本文件是一个包含多条 MATLAB 指令的外部文件,以 .m 为后缀名 -% 使用脚本文件可以避免在命令窗口中重复输入冗长的指令 - - -% .m 函数文件 -% 与脚本文件类似,同样以 .m 作为后缀名 -% 但函数文件可以接受用户输入的参数并返回运算结果 -% 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突 -% 函数文件的名称应当与其所定义的函数的名称一致 -% 比如下面例子中函数文件就应命名为 double_input.m -% 使用 'help double_input.m' 可返回函数定义中第一行注释信息 -function output = double_input(x) - % double_input(x) 返回 x 的 2 倍 - output = 2*x; -end -double_input(6) % ans = 12 - - -% 同样还可以定义子函数和内嵌函数 -% 子函数与主函数放在同一个函数文件中,且只能被这个主函数调用 -% 内嵌函数放在另一个函数体内,可以直接访问被嵌套函数的各个变量 - - -% 使用匿名函数可以不必创建 .m 函数文件 -% 匿名函数适用于快速定义某函数以便传递给另一指令或函数(如绘图、积分、求根、求极值等) -% 下面示例的匿名函数返回输入参数的平方根,可以使用句柄 sqr 进行调用: -sqr = @(x) x.^2; -sqr(10) % ans = 100 -doc function_handle % find out more - - -% 接受用户输入 -a = input('Enter the value: ') - - -% 从文件中读取数据 -fopen(filename) -% 类似函数还有 xlsread(excel 文件)、importdata(CSV 文件)、imread(图像文件) - - -% 输出 -disp(a) % 在命令窗口中打印变量 a 的值 -disp('Hello World') % 在命令窗口中打印字符串 -fprintf % 按照指定格式在命令窗口中打印内容 - -% 条件语句(if 和 elseif 语句中的括号并非必需,但推荐加括号避免混淆) -if (a > 15) - disp('Greater than 15') -elseif (a == 23) - disp('a is 23') -else - disp('neither condition met') -end - -% 循环语句 -% 注意:对向量或矩阵使用循环语句进行元素遍历的效率很低!! -% 注意:只要有可能,就尽量使用向量或矩阵的整体运算取代逐元素循环遍历!! -% MATLAB 在开发时对向量和矩阵运算做了专门优化,做向量和矩阵整体运算的效率高于循环语句 -for k = 1:5 - disp(k) -end - -k = 0; -while (k < 5) - k = k + 1; -end - - -% 程序运行计时:'tic' 是计时开始,'toc' 是计时结束并打印结果 -tic -A = rand(1000); -A*A*A*A*A*A*A; -toc - - -% 链接 MySQL 数据库 -dbname = 'database_name'; -username = 'root'; -password = 'root'; -driver = 'com.mysql.jdbc.Driver'; -dburl = ['jdbc:mysql://localhost:8889/' dbname]; -javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); % 此处 xx 代表具体版本号 -% 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载 -conn = database(dbname, username, password, driver, dburl); -sql = ['SELECT * from table_name where id = 22'] % SQL 语句 -a = fetch(conn, sql) % a 即包含所需数据 - - -% 常用数学函数 -sin(x) -cos(x) -tan(x) -asin(x) -acos(x) -atan(x) -exp(x) -sqrt(x) -log(x) -log10(x) -abs(x) -min(x) -max(x) -ceil(x) -floor(x) -round(x) -rem(x) -rand % 均匀分布的伪随机浮点数 -randi % 均匀分布的伪随机整数 -randn % 正态分布的伪随机浮点数 - -% 常用常数 -pi -NaN -inf - -% 求解矩阵方程(如果方程无解,则返回最小二乘近似解) -% \ 操作符等价于 mldivide 函数,/ 操作符等价于 mrdivide 函数 -x=A\b % 求解 Ax=b,比先求逆再左乘 inv(A)*b 更加高效、准确 -x=b/A % 求解 xA=b - -inv(A) % 逆矩阵 -pinv(A) % 伪逆矩阵 - - -% 常用矩阵函数 -zeros(m, n) % m x n 阶矩阵,元素全为 0 -ones(m, n) % m x n 阶矩阵,元素全为 1 -diag(A) % 返回矩阵 A 的对角线元素 -diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素 -eye(m, n) % m x n 阶单位矩阵 -linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点 -inv(A) % 矩阵 A 的逆矩阵 -det(A) % 矩阵 A 的行列式 -eig(A) % 矩阵 A 的特征值和特征向量 -trace(A) % 矩阵 A 的迹(即对角线元素之和),等价于 sum(diag(A)) -isempty(A) % 测试 A 是否为空 -all(A) % 测试 A 中所有元素是否都非 0 或都为真(逻辑值) -any(A) % 测试 A 中是否有元素非 0 或为真(逻辑值) -isequal(A, B) % 测试 A 和 B是否相等 -numel(A) % 矩阵 A 的元素个数 -triu(x) % 返回 x 的上三角这部分 -tril(x) % 返回 x 的下三角这部分 -cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积) -dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长 -transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点) -fliplr(A) % 将一个矩阵左右翻转 -flipud(A) % 将一个矩阵上下翻转 - -% 矩阵分解 -[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵 -[P, D] = eig(A) % 特征值分解:AP = PD - % D 是由特征值构成的对角阵,P 的各列就是对应的特征向量 -[U, S, V] = svd(X) % 奇异值分解:XV = US - % U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵 - -% 常用向量函数 -max % 最大值 -min % 最小值 -length % 元素个数 -sort % 按升序排列 -sum % 各元素之和 -prod % 各元素之积 -mode % 众数 -median % 中位数 -mean % 平均值 -std % 标准差 -perms(x) % x 元素的全排列 - -``` - -## 相关资料 - -* 官方网页:[MATLAB - 技术计算语言 - MATLAB & Simulink](https://ww2.mathworks.cn/products/matlab.html) -* 官方论坛:[MATLAB Answers - MATLAB Central](https://ww2.mathworks.cn/matlabcentral/answers/) +--- +language: MATLAB +filename: matlab-cn.m +contributors: + - ["mendozao", "http://github.com/mendozao"] + - ["jamesscottbrown", "http://jamesscottbrown.com"] +translators: + - ["sunxb10", "https://github.com/sunxb10"] +lang: zh-cn + +--- + +MATLAB 是 MATrix LABoratory(矩阵实验室)的缩写。 +它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。 + +如果您有任何需要反馈或交流的内容,请联系本教程作者: +[@the_ozzinator](https://twitter.com/the_ozzinator) +或 [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。 + +```matlab +% 以百分号作为注释符 + +%{ +多行注释 +可以 +这样 +表示 +%} + +% 指令可以随意跨行,但需要在跨行处用 '...' 标明: + a = 1 + 2 + ... + + 4 + +% 可以在MATLAB中直接向操作系统发出指令 +!ping google.com + +who % 显示内存中的所有变量 +whos % 显示内存中的所有变量以及它们的类型 +clear % 清除内存中的所有变量 +clear('A') % 清除指定的变量 +openvar('A') % 在变量编辑器中编辑指定变量 + +clc % 清除命令窗口中显示的所有指令 +diary % 将命令窗口中的内容写入本地文件 +ctrl-c % 终止当前计算 + +edit('myfunction.m') % 在编辑器中打开指定函数或脚本 +type('myfunction.m') % 在命令窗口中打印指定函数或脚本的源码 + +profile on % 打开 profile 代码分析工具 +profile off % 关闭 profile 代码分析工具 +profile viewer % 查看 profile 代码分析工具的分析结果 + +help command % 在命令窗口中显示指定命令的帮助文档 +doc command % 在帮助窗口中显示指定命令的帮助文档 +lookfor command % 在所有 MATLAB 内置函数的头部注释块的第一行中搜索指定命令 +lookfor command -all % 在所有 MATLAB 内置函数的整个头部注释块中搜索指定命令 + + +% 输出格式 +format short % 浮点数保留 4 位小数 +format long % 浮点数保留 15 位小数 +format bank % 金融格式,浮点数只保留 2 位小数 +fprintf('text') % 在命令窗口中显示 "text" +disp('text') % 在命令窗口中显示 "text" + + +% 变量与表达式 +myVariable = 4 % 命令窗口中将新创建的变量 +myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果 +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; +c = exp(a)*sin(pi/2) % c = 7.3891 + + +% 调用函数有两种方式: +% 标准函数语法: +load('myFile.mat', 'y') % 参数放在括号内,以英文逗号分隔 +% 指令语法: +load myFile.mat y % 不加括号,以空格分隔参数 +% 注意在指令语法中参数不需要加引号:在这种语法下,所有输入参数都只能是文本文字, +% 不能是变量的具体值,同样也不能是输出变量 +[V,D] = eig(A); % 这条函数调用无法转换成等价的指令语法 +[~,D] = eig(A); % 如果结果中只需要 D 而不需要 V 则可以这样写 + + + +% 逻辑运算 +1 > 5 % 假,ans = 0 +10 >= 10 % 真,ans = 1 +3 ~= 4 % 不等于 -> ans = 1 +3 == 3 % 等于 -> ans = 1 +3 > 1 && 4 > 1 % 与 -> ans = 1 +3 > 1 || 4 > 1 % 或 -> ans = 1 +~1 % 非 -> ans = 0 + +% 逻辑运算可直接应用于矩阵,运算结果也是矩阵 +A > 5 +% 对矩阵中每个元素做逻辑运算,若为真,则在运算结果的矩阵中对应位置的元素就是 1 +A( A > 5 ) +% 如此返回的向量,其元素就是 A 矩阵中所有逻辑运算为真的元素 + +% 字符串 +a = 'MyString' +length(a) % ans = 8 +a(2) % ans = y +[a,a] % ans = MyStringMyString +b = '字符串' % MATLAB目前已经可以支持包括中文在内的多种文字 +length(b) % ans = 3 +b(2) % ans = 符 +[b,b] % ans = 字符串字符串 + + +% 元组(cell 数组) +a = {'one', 'two', 'three'} +a(1) % ans = 'one' - 返回一个元组 +a{1} % ans = one - 返回一个字符串 + + +% 结构体 +A.b = {'one','two'}; +A.c = [1 2]; +A.d.e = false; + + +% 向量 +x = [4 32 53 7 1] +x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0 +x(2:3) % ans = 32 53 +x(2:end) % ans = 32 53 7 1 + +x = [4; 32; 53; 7; 1] % 列向量 + +x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 + + +% 矩阵 +A = [1 2 3; 4 5 6; 7 8 9] +% 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素 +% A = + +% 1 2 3 +% 4 5 6 +% 7 8 9 + +A(2,3) % ans = 6,A(row, column) +A(6) % ans = 8 +% (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素) + + +A(2,3) = 42 % 将第 2 行第 3 列的元素设为 42 +% A = + +% 1 2 3 +% 4 5 42 +% 7 8 9 + +A(2:3,2:3) % 取原矩阵中的一块作为新矩阵 +%ans = + +% 5 42 +% 8 9 + +A(:,1) % 第 1 列的所有元素 +%ans = + +% 1 +% 4 +% 7 + +A(1,:) % 第 1 行的所有元素 +%ans = + +% 1 2 3 + +[A ; A] % 将两个矩阵上下相接构成新矩阵 +%ans = + +% 1 2 3 +% 4 5 42 +% 7 8 9 +% 1 2 3 +% 4 5 42 +% 7 8 9 + +% 等价于 +vertcat(A, A); + + +[A , A] % 将两个矩阵左右相接构成新矩阵 + +%ans = + +% 1 2 3 1 2 3 +% 4 5 42 4 5 42 +% 7 8 9 7 8 9 + +% 等价于 +horzcat(A, A); + + +A(:, [3 1 2]) % 重新排布原矩阵的各列 +%ans = + +% 3 1 2 +% 42 4 5 +% 9 7 8 + +size(A) % 返回矩阵的行数和列数,ans = 3 3 + +A(1, :) =[] % 删除矩阵的第 1 行 +A(:, 1) =[] % 删除矩阵的第 1 列 + +transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点) +ctranspose(A) % 矩阵的共轭转置(对矩阵中的每个元素取共轭复数),等价于 A' + + +% 元素运算 vs. 矩阵运算 +% 单独运算符就是对矩阵整体进行矩阵运算 +% 在运算符加上英文句点就是对矩阵中的元素进行元素计算 +% 示例如下: +A * B % 矩阵乘法,要求 A 的列数等于 B 的行数 +A .* B % 元素乘法,要求 A 和 B 形状一致,即两矩阵行列数完全一致 + % 元素乘法的结果是与 A 和 B 形状一致的矩阵 + % 其每个元素等于 A 对应位置的元素乘 B 对应位置的元素 + +% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算: +exp(A) % 对矩阵中每个元素做指数运算 +expm(A) % 对矩阵整体做指数运算 +sqrt(A) % 对矩阵中每个元素做开方运算 +sqrtm(A) % 对矩阵整体做开方运算(即试图求出一个矩阵,该矩阵与自身的乘积等于 A 矩阵) + + +% 绘图 +x = 0:0.1:2*pi; % 生成一向量,其元素从 0 开始,以 0.1 的间隔一直递增到 2*pi + % 其中 pi 为圆周率 +y = sin(x); +plot(x,y) +xlabel('x axis') +ylabel('y axis') +title('Plot of y = sin(x)') +axis([0 2*pi -1 1]) % x 轴范围是从 0 到 2*pi,y 轴范围是从 -1 到 1 + +plot(x,y1,'-',x,y2,'--',x,y3,':') % 在同一张图中绘制多条曲线 +legend('Line 1 label', 'Line 2 label') % 为图片加注图例 +% 图例数量应当小于或等于实际绘制的曲线数目,从 plot 绘制的第一条曲线开始对应 + +% 在同一张图上绘制多条曲线的另一种方法: +% 使用 hold on,令系统保留前次绘图结果并在其上直接叠加新的曲线, +% 如果没有 hold on,则每个 plot 都会首先清除之前的绘图结果再进行绘制。 +% 在 hold on 和 hold off 中可以放置任意多的 plot 指令, +% 它们和 hold on 前最后一个 plot 指令的结果都将显示在同一张图中。 +plot(x, y1) +hold on +plot(x, y2) +plot(x, y3) +plot(x, y4) +hold off + +loglog(x, y) % 对数—对数绘图 +semilogx(x, y) % 半对数(x 轴对数)绘图 +semilogy(x, y) % 半对数(y 轴对数)绘图 + +fplot (@(x) x^2, [2,5]) % 绘制函数 x^2 在 [2, 5] 区间的曲线 + +grid on % 在绘制的图中显示网格,使用 grid off 可取消网格显示 +axis square % 将当前坐标系设定为正方形(保证在图形显示上各轴等长) +axis equal % 将当前坐标系设定为相等(保证在实际数值上各轴等长) + +scatter(x, y); % 散点图 +hist(x); % 直方图 + +z = sin(x); +plot3(x,y,z); % 绘制三维曲线 + +pcolor(A) % 伪彩色图(热图) +contour(A) % 等高线图 +mesh(A) % 网格曲面图 + +h = figure % 创建新的图片对象并返回其句柄 h +figure(h) % 将句柄 h 对应的图片作为当前图片 +close(h) % 关闭句柄 h 对应的图片 +close all % 关闭 MATLAB 中所用打开的图片 +close % 关闭当前图片 + +shg % 显示图形窗口 +clf clear % 清除图形窗口中的图像,并重置图像属性 + +% 图像属性可以通过图像句柄进行设定 +% 在创建图像时可以保存图像句柄以便于设置 +% 也可以用 gcf 函数返回当前图像的句柄 +h = plot(x, y); % 在创建图像时显式地保存图像句柄 +set(h, 'Color', 'r') +% 颜色代码: +% 'y' 黄色,'m' 洋红,'c' 青色 +% 'r' 红色,'g' 绿色,'b' 蓝色 +% 'w' 白色,'k' 黑色 +set(h, 'Color', [0.5, 0.5, 0.4]) +% 也可以使用 RGB 值指定颜色 +set(h, 'LineStyle', '--') +% 线型代码:'--' 实线,'---' 虚线,':' 点线,'-.' 点划线,'none' 不划线 +get(h, 'LineStyle') +% 获取当前句柄的线型 + + +% 用 gca 函数返回当前图像的坐标轴句柄 +set(gca, 'XDir', 'reverse'); % 令 x 轴反向 + +% 用 subplot 指令创建平铺排列的多张子图 +subplot(2,3,1); % 选择 2 x 3 排列的子图中的第 1 张图 +plot(x1); title('First Plot') % 在选中的图中绘图 +subplot(2,3,2); % 选择 2 x 3 排列的子图中的第 2 张图 +plot(x2); title('Second Plot') % 在选中的图中绘图 + + +% 要调用函数或脚本,必须保证它们在你的当前工作目录中 +path % 显示当前工作目录 +addpath /path/to/dir % 将指定路径加入到当前工作目录中 +rmpath /path/to/dir % 将指定路径从当前工作目录中删除 +cd /path/to/move/into % 以制定路径作为当前工作目录 + + +% 变量可保存到 .mat 格式的本地文件 +save('myFileName.mat') % 保存当前工作空间中的所有变量 +load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 + + +% .m 脚本文件 +% 脚本文件是一个包含多条 MATLAB 指令的外部文件,以 .m 为后缀名 +% 使用脚本文件可以避免在命令窗口中重复输入冗长的指令 + + +% .m 函数文件 +% 与脚本文件类似,同样以 .m 作为后缀名 +% 但函数文件可以接受用户输入的参数并返回运算结果 +% 并且函数拥有自己的工作空间(变量域),不必担心变量名称冲突 +% 函数文件的名称应当与其所定义的函数的名称一致 +% 比如下面例子中函数文件就应命名为 double_input.m +% 使用 'help double_input.m' 可返回函数定义中第一行注释信息 +function output = double_input(x) + % double_input(x) 返回 x 的 2 倍 + output = 2*x; +end +double_input(6) % ans = 12 + + +% 同样还可以定义子函数和内嵌函数 +% 子函数与主函数放在同一个函数文件中,且只能被这个主函数调用 +% 内嵌函数放在另一个函数体内,可以直接访问被嵌套函数的各个变量 + + +% 使用匿名函数可以不必创建 .m 函数文件 +% 匿名函数适用于快速定义某函数以便传递给另一指令或函数(如绘图、积分、求根、求极值等) +% 下面示例的匿名函数返回输入参数的平方根,可以使用句柄 sqr 进行调用: +sqr = @(x) x.^2; +sqr(10) % ans = 100 +doc function_handle % find out more + + +% 接受用户输入 +a = input('Enter the value: ') + + +% 从文件中读取数据 +fopen(filename) +% 类似函数还有 xlsread(excel 文件)、importdata(CSV 文件)、imread(图像文件) + + +% 输出 +disp(a) % 在命令窗口中打印变量 a 的值 +disp('Hello World') % 在命令窗口中打印字符串 +fprintf % 按照指定格式在命令窗口中打印内容 + +% 条件语句(if 和 elseif 语句中的括号并非必需,但推荐加括号避免混淆) +if (a > 15) + disp('Greater than 15') +elseif (a == 23) + disp('a is 23') +else + disp('neither condition met') +end + +% 循环语句 +% 注意:对向量或矩阵使用循环语句进行元素遍历的效率很低!! +% 注意:只要有可能,就尽量使用向量或矩阵的整体运算取代逐元素循环遍历!! +% MATLAB 在开发时对向量和矩阵运算做了专门优化,做向量和矩阵整体运算的效率高于循环语句 +for k = 1:5 + disp(k) +end + +k = 0; +while (k < 5) + k = k + 1; +end + + +% 程序运行计时:'tic' 是计时开始,'toc' 是计时结束并打印结果 +tic +A = rand(1000); +A*A*A*A*A*A*A; +toc + + +% 链接 MySQL 数据库 +dbname = 'database_name'; +username = 'root'; +password = 'root'; +driver = 'com.mysql.jdbc.Driver'; +dburl = ['jdbc:mysql://localhost:8889/' dbname]; +javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); % 此处 xx 代表具体版本号 +% 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载 +conn = database(dbname, username, password, driver, dburl); +sql = ['SELECT * from table_name where id = 22'] % SQL 语句 +a = fetch(conn, sql) % a 即包含所需数据 + + +% 常用数学函数 +sin(x) +cos(x) +tan(x) +asin(x) +acos(x) +atan(x) +exp(x) +sqrt(x) +log(x) +log10(x) +abs(x) +min(x) +max(x) +ceil(x) +floor(x) +round(x) +rem(x) +rand % 均匀分布的伪随机浮点数 +randi % 均匀分布的伪随机整数 +randn % 正态分布的伪随机浮点数 + +% 常用常数 +pi +NaN +inf + +% 求解矩阵方程(如果方程无解,则返回最小二乘近似解) +% \ 操作符等价于 mldivide 函数,/ 操作符等价于 mrdivide 函数 +x=A\b % 求解 Ax=b,比先求逆再左乘 inv(A)*b 更加高效、准确 +x=b/A % 求解 xA=b + +inv(A) % 逆矩阵 +pinv(A) % 伪逆矩阵 + + +% 常用矩阵函数 +zeros(m, n) % m x n 阶矩阵,元素全为 0 +ones(m, n) % m x n 阶矩阵,元素全为 1 +diag(A) % 返回矩阵 A 的对角线元素 +diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素 +eye(m, n) % m x n 阶单位矩阵 +linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点 +inv(A) % 矩阵 A 的逆矩阵 +det(A) % 矩阵 A 的行列式 +eig(A) % 矩阵 A 的特征值和特征向量 +trace(A) % 矩阵 A 的迹(即对角线元素之和),等价于 sum(diag(A)) +isempty(A) % 测试 A 是否为空 +all(A) % 测试 A 中所有元素是否都非 0 或都为真(逻辑值) +any(A) % 测试 A 中是否有元素非 0 或为真(逻辑值) +isequal(A, B) % 测试 A 和 B是否相等 +numel(A) % 矩阵 A 的元素个数 +triu(x) % 返回 x 的上三角这部分 +tril(x) % 返回 x 的下三角这部分 +cross(A, B) % 返回 A 和 B 的叉积(矢量积、外积) +dot(A, B) % 返回 A 和 B 的点积(数量积、内积),要求 A 和 B 必须等长 +transpose(A) % 矩阵(非共轭)转置,等价于 A.' (注意!有个点) +fliplr(A) % 将一个矩阵左右翻转 +flipud(A) % 将一个矩阵上下翻转 + +% 矩阵分解 +[L, U, P] = lu(A) % LU 分解:PA = LU,L 是下三角阵,U 是上三角阵,P 是置换阵 +[P, D] = eig(A) % 特征值分解:AP = PD + % D 是由特征值构成的对角阵,P 的各列就是对应的特征向量 +[U, S, V] = svd(X) % 奇异值分解:XV = US + % U 和 V 是酉矩阵,S 是由奇异值构成的半正定实数对角阵 + +% 常用向量函数 +max % 最大值 +min % 最小值 +length % 元素个数 +sort % 按升序排列 +sum % 各元素之和 +prod % 各元素之积 +mode % 众数 +median % 中位数 +mean % 平均值 +std % 标准差 +perms(x) % x 元素的全排列 + +``` + +## 相关资料 + +* 官方网页:[MATLAB - 技术计算语言 - MATLAB & Simulink](https://ww2.mathworks.cn/products/matlab.html) +* 官方论坛:[MATLAB Answers - MATLAB Central](https://ww2.mathworks.cn/matlabcentral/answers/) From 01bbd084f1908a6815d53a1bd42b02c042e44bdb Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 4 Apr 2024 04:02:42 -0700 Subject: [PATCH 060/392] Add empty lines before code blocks otherwise they don't render as blocks --- cs-cz/css.html.markdown | 2 ++ de-de/dynamic-programming-de.html.markdown | 1 + es-es/amd-es.html.markdown | 6 ++++++ es-es/self-es.html.markdown | 1 + fr-fr/git-fr.html.markdown | 2 ++ hd-hd/amd.html.markdown | 8 ++++++++ hd-hd/d.html.markdown | 14 ++++++-------- pt-br/amd-pt.html.markdown | 7 +++++++ pt-br/self-pt.html.markdown | 1 + sk-sk/git-sk.html.markdown | 3 +++ zh-cn/zfs-cn.html.markdown | 2 +- 11 files changed, 38 insertions(+), 9 deletions(-) diff --git a/cs-cz/css.html.markdown b/cs-cz/css.html.markdown index 54a0a08e..ed69c73a 100644 --- a/cs-cz/css.html.markdown +++ b/cs-cz/css.html.markdown @@ -220,9 +220,11 @@ p { vlastnost: hodnota !important; } ``` a tento element + ```xml

    ``` + Priorita stylu je následující. Pamatujte, priorita pro každou **vlastnost**, ne pro celý blok. * `E` má nejvyšší prioritu kvůli slůvku `!important`. Je doporučováno se úplně vyhnout jeho použití. diff --git a/de-de/dynamic-programming-de.html.markdown b/de-de/dynamic-programming-de.html.markdown index 58568b3b..9cf461d0 100644 --- a/de-de/dynamic-programming-de.html.markdown +++ b/de-de/dynamic-programming-de.html.markdown @@ -56,6 +56,7 @@ wie `largest_sequences_so_far` und dessen Index würde eine Menge Zeit sparen. Ein ähnliches Konzept könnte auch bei der Suche nach dem längsten Weg in gerichteten azyklischen Graphen angewandt werden. + ```python for i=0 to n-1 LS[i]=1 diff --git a/es-es/amd-es.html.markdown b/es-es/amd-es.html.markdown index 40aa6647..83c705c3 100644 --- a/es-es/amd-es.html.markdown +++ b/es-es/amd-es.html.markdown @@ -16,6 +16,7 @@ lang: es-es El API del **Módulo de Definición Asíncrono** especifica un mecanismo para definir módulos JavaScript de manera tal que tanto el módulo como sus dependencias puedan ser cargadas de manera asíncrona. Esto es particularmente adecuado para el entorno del navegador donde la carga sincronizada de los módulos genera problemas de rendimiento, usabilidad, depuración y acceso de multi-dominios. ### Conceptos básicos + ```javascript // El API básico de AMD consiste en tan solo dos métodos: `define` y `require` // y se basa en la definición y consumo de los módulos: @@ -137,6 +138,7 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL coolLib.doFancyStuffWith(helpers.transform($('#foo'))); }); ``` + Las aplicaciones basadas en `require.js` usualmente tendrán un solo punto de entrada (`main.js`) que se pasa a la etiqueta del script `require.js` como un atributo de datos. Será cargado y ejecutado automáticamente al cargar la página: ```html @@ -158,16 +160,19 @@ Muchas personas prefieren usar AMD para la organización del código durante el `require.js` incluye un script llamado `r.js` (el que probablemente correrás en node.js, aunque Rhino también es soportado) que puede analizar el gráfico de dependencias de tu proyecto, y armar un solo fichero que contenga todos tus módulos (adecuadamente nombrados), minificado y listo para consumo. Instálalo usando `npm`: + ```shell $ npm install requirejs -g ``` Ahora puedes alimentarlo con un fichero de configuración: + ```shell $ r.js -o app.build.js ``` Para nuestro ejemplo anterior el archivo de configuración luciría así: + ```javascript /* file : app.build.js */ ({ @@ -184,6 +189,7 @@ Para nuestro ejemplo anterior el archivo de configuración luciría así: ``` Para usar el fichero creado en producción, simplemente intercambia `data-main`: + ```html ``` diff --git a/es-es/self-es.html.markdown b/es-es/self-es.html.markdown index 11972214..1f985215 100644 --- a/es-es/self-es.html.markdown +++ b/es-es/self-es.html.markdown @@ -116,6 +116,7 @@ Las expresiones múltiples son separadas por un punto. ^ retorna inmediatamente. ``` Los bloques son ejecutados al enviales el mensaje 'value' y son inherentes (delegados a) sus contextos: + ``` "returns 0" [|x| diff --git a/fr-fr/git-fr.html.markdown b/fr-fr/git-fr.html.markdown index 00b6b6e1..a4d0c185 100644 --- a/fr-fr/git-fr.html.markdown +++ b/fr-fr/git-fr.html.markdown @@ -171,6 +171,7 @@ $ git init --help Ne plus suivre certains fichiers et dossiers de Git. Habituellement fait pour les fichiers privés et temporaires qui seraient, autrement, partagés dans le dépôt. + ```bash $ echo "temp/" >> .gitignore $ echo "cle_privee" >> .gitignore @@ -466,6 +467,7 @@ Vous pouvez maintenant pull ! ```bash git pull ``` + `...changes apply...` Vérifiez maintenant que tout est OK diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown index 0a6581d6..b85567c2 100644 --- a/hd-hd/amd.html.markdown +++ b/hd-hd/amd.html.markdown @@ -12,6 +12,7 @@ lang: hd जावास्क्रिप्ट मॉड्यूल ऐसे मॉड्यूल और इसकी अतुल्यकालिक निर्भरता से भरा हुआ है। यह ब्राउज़र पर्यावरण जहां के लिए विशेष रूप से अच्छी तरह से अनुकूल है, और प्रदर्शन , प्रयोज्य, डीबगिंग, और क्रॉस-डोमेन जैसे मॉड्यूल्स को जल्दी सिंक्रनाइज़ लोडिंग करता hai। ### मूल अवधारणा + ```javascript // बुनियादी एएमडी एपीआई दो तरीकों लेकिन कुछ भी नहीं होते : ` define` और` require` // और सभी मॉड्यूल परिभाषा और खपत के बारे में है : @@ -79,6 +80,7 @@ function require(deps, callback){ ### Require.js के साथ वास्तविक दुनिया के उपयोग परिचयात्मक उदाहरण के विपरीत, ` require.js` (सबसे लोकप्रिय एएमडी पुस्तकालय ) वास्तव में लागू करता है ** ** Amd ** में *A * **, आप XHR के माध्यम से मॉड्यूल और उनकी निर्भरता लोड करने के लिए सक्षम करने के लिए : + ```javascript /* file: app/main.js */ require(['modules/someClass'], function(SomeClass){ @@ -113,6 +115,7 @@ define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ return SomeClass; }); ``` + अपने ` main.js` में डिफ़ॉल्ट पथ मानचित्रण व्यवहार का उपयोग ` requirejs.config ( configObj ) ` में परिवर्तन करने के लिए: ```javascript @@ -131,6 +134,7 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL coolLib.doFancyStuffWith(helpers.transform($('#foo'))); }); ``` + ` require.js` आधारित क्षुधा आमतौर पर एक डाटा विशेषता के रूप में ` require.js` स्क्रिप्ट टैग को पारित कर दिया है कि एक एकल प्रवेश बिंदु (` main.js` ) होगा। यह स्वचालित रूप से भरी हुई है और pageload पर क्रियान्वित किया जाएगा : ```html @@ -151,16 +155,19 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL (राइनो भी समर्थन किया है, तो आप शायद Node.js में चलेगा ) ` require.js` ( अपनी परियोजना की निर्भरता ग्राफ का विश्लेषण , और अपने सभी मॉड्यूल युक्त एक एकल फाइल निर्माण कर सकते हैं कि ` r.js` नामक एक स्क्रिप्ट के साथ आता है ठीक से minified और उपभोग के लिए तैयार है, ) नाम दिया है। Install it using `npm`: + ```shell $ npm install requirejs -g ``` अब आप एक विन्यास फाइल के साथ फ़ीड कर सकते हैं: + ```shell $ r.js -o app.build.js ``` हमारे ऊपर के उदाहरण के लिए विन्यास की तरह लग सकता है: + ```javascript /* file : app.build.js */ ({ @@ -177,6 +184,7 @@ $ r.js -o app.build.js ``` उत्पादन में बनाया फ़ाइल का उपयोग करने के लिए, बस ` Data-main` स्वैप: + ```html ``` diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown index 96274e2b..f5e0858a 100644 --- a/hd-hd/d.html.markdown +++ b/hd-hd/d.html.markdown @@ -126,7 +126,6 @@ class Matrix(uint m, uint n, T = int) { } auto mat = new Matrix!(3, 3); - ``` Classes की बात हो रही है , एक दूसरे के लिए गुणों के बारे में बात करते हैं। एक संपत्ति @@ -176,8 +175,8 @@ class MyClass(T, U) { void main() { auto mc = new MyClass!(int, string)(7, "seven"); - करने के लिए लिखने के लिए मानक पुस्तकालय से - // आयात ' stdio ' मॉड्यूल + // करने के लिए लिखने के लिए मानक पुस्तकालय से + // आयात ' stdio ' मॉड्यूल // सांत्वना (आयात एक गुंजाइश के लिए स्थानीय हो सकता है) । import std.stdio; @@ -235,22 +234,21 @@ UFCS के साथ, हम एक विधि के रूप में ए एक विधि के रूप में ग्रुप ए की किसी भी अभिव्यक्ति पर कुछ प्रकार एक की है । मैं समानता चाहते । समानता की तरह कोई और? ज़रूर तुम करना। चलो कुछ करते हैं! + ```c import std.stdio; import std.parallelism : parallel; import std.math : sqrt; void main() { - // हम हमारे सरणी में वर्गमूल हर नंबर ले जाना चाहता हूँ , - // हम उपलब्ध है के रूप में और के रूप में कई कोर का लाभ ले। + // हम हमारे सरणी में वर्गमूल हर नंबर ले जाना चाहता हूँ , + // हम उपलब्ध है के रूप में और के रूप में कई कोर का लाभ ले। auto arr = new double[1_000_000]; - // संदर्भ के द्वारा एक सूचकांक , और एक सरणी तत्व का प्रयोग + // संदर्भ के द्वारा एक सूचकांक , और एक सरणी तत्व का प्रयोग // और सिर्फ सरणी पर समानांतर फोन! foreach(i, ref elem; parallel(arr)) { ref = sqrt(i + 1.0); } } - - ``` diff --git a/pt-br/amd-pt.html.markdown b/pt-br/amd-pt.html.markdown index 40c7cd09..886cb253 100644 --- a/pt-br/amd-pt.html.markdown +++ b/pt-br/amd-pt.html.markdown @@ -19,6 +19,7 @@ módulos de forma síncrona fica sujeito a problemas de performance, usabilidade debugging e problemas de acesso em requisições cross-domain. ### Conceito básico + ```javascript // O básico da API de AMD consiste de nada mais que dois métodos: `define` e `require` // e isso é tudo sobre a definição de módulo e consumo: @@ -122,6 +123,7 @@ define(['daos/coisas', 'modules/algunsHelpers'], function(coisasDao, helpers){ return AlgumaClasse; }); ``` + Para alterar o comportamento padrão de mapeamento de caminho de pastas utilize `requirejs.config(configObj)` em seu `main.js`: @@ -141,6 +143,7 @@ require(['jquery', 'coolLibFromBower', 'modules/algunsHelpers'], function($, coo coolLib.facaAlgoDoidoCom(helpers.transform($('#foo'))); }); ``` + Apps baseados em `require.js` geralmente terão um único ponto de acesso (`main.js`) que é passado à tag script do `require.js` como um data-attribute. Ele vai ser automaticamente carregado e executado com o carregamento da página: ```html @@ -162,16 +165,19 @@ Muitas pessoas preferem usar AMD para sanar a organização do código durante o `require.js` vem com um script chamado `r.js` (que você vai provavelmente rodar em node.js, embora Rhino suporte também) que você pode analisar o gráfico de dependências de seu projeto, e fazer em um único arquivo contendo todos os seus módulos (corretamente nomeados), minificados e prontos para serem consumidos. Instale-o utilizando `npm`: + ```shell $ npm install requirejs -g ``` Agora você pode alimentá-lo com um arquivo de configuração: + ```shell $ r.js -o app.build.js ``` Para o nosso exemplo acima a configuração pode ser essa: + ```javascript /* file : app.build.js */ ({ @@ -188,6 +194,7 @@ Para o nosso exemplo acima a configuração pode ser essa: ``` Para usar o arquivo gerado, em produção, simplesmente troque o `data-main`: + ```html ``` diff --git a/pt-br/self-pt.html.markdown b/pt-br/self-pt.html.markdown index eb821474..0fadf58d 100644 --- a/pt-br/self-pt.html.markdown +++ b/pt-br/self-pt.html.markdown @@ -117,6 +117,7 @@ Múltiplas expressões são separadas por ponto final. ^ retorna imediatamente. ``` Blocos são realizados (completados) ao enviá-los a mensagem 'value' e herdando (imcumbir a) seus contextos: + ``` "retorna 0" [|x| diff --git a/sk-sk/git-sk.html.markdown b/sk-sk/git-sk.html.markdown index ddcd9658..1187abc5 100644 --- a/sk-sk/git-sk.html.markdown +++ b/sk-sk/git-sk.html.markdown @@ -139,6 +139,7 @@ $ git init --help ### ignoruj súbory Zámerne prestaneš sledovať súbor(y) a zložky. Typicky sa používa pre súkromné a dočasné súbory, ktoré by boli inak zdieľané v repozitári. + ```bash $ echo "temp/" >> .gitignore $ echo "private_key" >> .gitignore @@ -172,6 +173,7 @@ $ git add /cesta/k/súboru/HelloWorld.c # Môžeš použiť regulárne výrazy! $ git add ./*.java ``` + Tento príkaz len pridáva súbory do staging indexu, necommituje ich do repozitára. ### branch @@ -476,6 +478,7 @@ $ git reset 31f2bb1 # a zosúladí ju s pracovným adresárom (vymaže nekomitnuté zmeny). $ git reset --hard 31f2bb1 ``` + ### revert Vezme naspäť ("od-urobí") commit. Nezamieňaj s resetom, ktorý obnoví stav diff --git a/zh-cn/zfs-cn.html.markdown b/zh-cn/zfs-cn.html.markdown index fdf5277e..80688fbe 100644 --- a/zh-cn/zfs-cn.html.markdown +++ b/zh-cn/zfs-cn.html.markdown @@ -288,6 +288,7 @@ tank/home/sarlalian@now 0 - 259M - tank/home/alice@now 0 - 156M - tank/home/bob@now 0 - 156M - ... +``` Destroy snapshots (删除快照) @@ -297,7 +298,6 @@ $ zfs destroy tank/home/sarlalian@now # 删除某一数据集及其子集的快照 $ zfs destroy -r tank/home/sarlalian@now - ``` Renaming Snapshots (重命名) From f8475ed139b68a258fcf7093d0b54d83b5a2963d Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 4 Apr 2024 04:06:33 -0700 Subject: [PATCH 061/392] Github -> GitHub --- de-de/elm-de.html.markdown | 2 +- de-de/pug-de.html.markdown | 2 +- de-de/rst-de.html.markdown | 6 +++--- es-es/git-es.html.markdown | 2 +- fr-fr/markdown-fr.html.markdown | 2 +- httpie.html.markdown | 2 +- id-id/markdown.html.markdown | 12 ++++++------ id-id/rst-id.html.markdown | 6 +++--- it-it/markdown.html.markdown | 10 +++++----- it-it/rst-it.html.markdown | 6 +++--- mercury.html.markdown | 2 +- montilang.html.markdown | 2 +- nl-nl/markdown-nl.html.markdown | 10 +++++----- osl.html.markdown | 2 +- pt-br/pug-pt.html.markdown | 2 +- pug.html.markdown | 2 +- rst.html.markdown | 6 +++--- ru-ru/markdown-ru.html.markdown | 8 ++++---- ru-ru/sql-ru.html.markdown | 2 +- tr-tr/git-tr.html.markdown | 2 +- vi-vn/markdown-vi.html.markdown | 2 +- zh-cn/crystal-cn.html.markdown | 2 +- 22 files changed, 46 insertions(+), 46 deletions(-) diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown index 08832327..a6a8cd88 100644 --- a/de-de/elm-de.html.markdown +++ b/de-de/elm-de.html.markdown @@ -343,7 +343,7 @@ $ elm reactor -- Starte das REPL (read-eval-print-loop). $ elm repl --- Bibliotheken werden durch den Github-Nutzernamen und ein Repository identifiziert. +-- Bibliotheken werden durch den GitHub-Nutzernamen und ein Repository identifiziert. -- Installieren einer neuen Bibliothek. $ elm package install elm-lang/html -- Diese wird der elm-package.json Datei hinzugefügt. diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown index 10172d6b..ce31c648 100644 --- a/de-de/pug-de.html.markdown +++ b/de-de/pug-de.html.markdown @@ -205,4 +205,4 @@ mixin comment(name, kommentar) ### Zusätzliche Ressourcen - [The Site](https://pugjs.org/) - [The Docs](https://pugjs.org/api/getting-started.html) -- [Github Repo](https://github.com/pugjs/pug) +- [GitHub Repo](https://github.com/pugjs/pug) diff --git a/de-de/rst-de.html.markdown b/de-de/rst-de.html.markdown index 072299f5..0eb2b6bf 100644 --- a/de-de/rst-de.html.markdown +++ b/de-de/rst-de.html.markdown @@ -86,14 +86,14 @@ erstellt werden, aber ich empfehle dir dafür die komplette Dokumentation zu les Es gibt mehrere Möglichkeiten um Links zu machen: -- Wenn man einen Unterstrich hinter einem Wort hinzufügt: Github_ Zusätzlich +- Wenn man einen Unterstrich hinter einem Wort hinzufügt: GitHub_ Zusätzlich muss man die Zielurl nach dem Text hinzufügen. (Dies hat den Vorteil, dass man keine unnötigen Urls in lesbaren Text einfügt. - Wenn man die vollständige Url eingibt : https://github.com/ (Dies wird automatisch in ein Link konvertiert.) -- Wenn man es mehr Markdown ähnlich eingibt: `Github `_ . +- Wenn man es mehr Markdown ähnlich eingibt: `GitHub `_ . -.. _Github https://github.com/ +.. _GitHub https://github.com/ ``` diff --git a/es-es/git-es.html.markdown b/es-es/git-es.html.markdown index dc0dda30..c93584d8 100644 --- a/es-es/git-es.html.markdown +++ b/es-es/git-es.html.markdown @@ -414,4 +414,4 @@ $ git rm /directorio/del/archivo/FooBar.c * [Pro Git](http://www.git-scm.com/book/en/v2) -* [Una introducción a Git y Github para principiantes (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) +* [Una introducción a Git y GitHub para principiantes (Tutorial)](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) diff --git a/fr-fr/markdown-fr.html.markdown b/fr-fr/markdown-fr.html.markdown index 91894787..f5d6aacc 100644 --- a/fr-fr/markdown-fr.html.markdown +++ b/fr-fr/markdown-fr.html.markdown @@ -335,7 +335,7 @@ Tapez \*ce texte\*. ### Touches de clavier -Avec le "Github Flavored Markdown", vous pouvez utiliser la balise `` +Avec le "GitHub Flavored Markdown", vous pouvez utiliser la balise `` pour représenter une touche du clavier. ```md diff --git a/httpie.html.markdown b/httpie.html.markdown index 390e7b35..40481dff 100644 --- a/httpie.html.markdown +++ b/httpie.html.markdown @@ -117,4 +117,4 @@ http --follow GET https://example.com # Follow Redirects ## Further Reading - [Official Documentation](https://httpie.io/docs/cli). -- [Github](https://github.com/httpie). +- [GitHub](https://github.com/httpie). diff --git a/id-id/markdown.html.markdown b/id-id/markdown.html.markdown index 1ff1963b..22fcb17f 100644 --- a/id-id/markdown.html.markdown +++ b/id-id/markdown.html.markdown @@ -54,8 +54,8 @@ __Dan juga teks ini.__ **_Dan juga ini!_** *__Dan ini!__* - + ~~Teks ini dirender dengan coretan.~~ @@ -155,7 +155,7 @@ di dalam kode Anda --> John bahkan tidak tahu apa fungsi dari `go_to()` ! - + \`\`\`ruby def foobar @@ -163,7 +163,7 @@ def foobar end \`\`\` - @@ -236,14 +236,14 @@ Saya ingin mengetik *teks ini dikelilingi tanda bintang* tapi saya tidak mau tek miring, jadi saya melakukan: \*teks ini dikelilingi tanda bintang\*. - Komputer Anda hang? Coba kirim sebuah Ctrl+Alt+Del - | Kol1 | Kol2 | Kol3 | diff --git a/id-id/rst-id.html.markdown b/id-id/rst-id.html.markdown index 06d80089..a5070d64 100644 --- a/id-id/rst-id.html.markdown +++ b/id-id/rst-id.html.markdown @@ -88,14 +88,14 @@ ini :) Ada berbagai macam cara untuk membuat tautan: -- Dengan menambahkan garis bawah setelah sebuah huruf : Github_ dan dengan +- Dengan menambahkan garis bawah setelah sebuah huruf : GitHub_ dan dengan menambahkan URL target setelah teks (cara ini mempunyai kelebihan dengan tidak memasukkan URL yang tidak penting ke dalam teks yang bisa dibaca). - Dengan mengetik URL lengkap yang dapat dipahami : https://github.com (akan otomatis diubah menjadi sebuah link) -- Dengan membuat link seperti di Markdown: `Github `_ . +- Dengan membuat link seperti di Markdown: `GitHub `_ . -.. _Github https://github.com/ +.. _GitHub https://github.com/ ``` diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index ff6f0aed..609d3bb7 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -72,7 +72,7 @@ __Come pure questo.__ *__E questo!__* ``` -In Github Flavored Markdown, che è utilizzato per renderizzare i file markdown su Github, è presente anche lo stile barrato: +In GitHub Flavored Markdown, che è utilizzato per renderizzare i file markdown su GitHub, è presente anche lo stile barrato: ```md ~~Questo testo è barrato.~~ @@ -193,7 +193,7 @@ Codice inline può essere inserito usando il carattere backtick ` Giovanni non sapeva neppure a cosa servisse la funzione `go_to()`! ``` -In Github Flavored Markdown, potete inoltre usare una sintassi speciale per il codice +In GitHub Flavored Markdown, potete inoltre usare una sintassi speciale per il codice ````md ```ruby @@ -203,7 +203,7 @@ end ``` ```` -Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre Github userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali +Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre GitHub userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali ## Linea orizzontale Le linee orizzontali (`


    `) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi. @@ -285,7 +285,7 @@ Voglio inserire *questo testo circondato da asterischi* ma non voglio che venga ``` ### Combinazioni di tasti -In Github Flavored Markdown, potete utilizzare il tag `` per raffigurare i tasti della tastiera. +In GitHub Flavored Markdown, potete utilizzare il tag `` per raffigurare i tasti della tastiera. ```md Il tuo computer è crashato? Prova a premere @@ -293,7 +293,7 @@ Il tuo computer è crashato? Prova a premere ``` ### Tabelle -Le tabelle sono disponibili solo in Github Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue: +Le tabelle sono disponibili solo in GitHub Flavored Markdown e sono leggeremente complesse, ma se proprio volete inserirle fate come segue: ```md | Col1 | Col2 | Col3 | diff --git a/it-it/rst-it.html.markdown b/it-it/rst-it.html.markdown index a834e899..3885cbd8 100644 --- a/it-it/rst-it.html.markdown +++ b/it-it/rst-it.html.markdown @@ -81,11 +81,11 @@ Anche le tabelle più complesse possono essere inserite facilmente (colonne e/o Esistono diversi modi per creare collegamenti: -- Aggiungendo un underscore dopo una parola: Github_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile). +- Aggiungendo un underscore dopo una parola: GitHub_ e aggiungendo l'URL di destinazione dopo il testo (questo metodo ha il vantaggio di non inserire URL non necessari all'interno del testo leggibile). - Digitando un URL completo: https://github.com/ (verrà automaticamente convertito in un collegamento) -- Utilizzando una sintassi simile a Markdown: `Github `_ . +- Utilizzando una sintassi simile a Markdown: `GitHub `_ . -.. _Github https://github.com/ +.. _GitHub https://github.com/ ``` diff --git a/mercury.html.markdown b/mercury.html.markdown index f749bac4..6d278ce0 100644 --- a/mercury.html.markdown +++ b/mercury.html.markdown @@ -254,7 +254,7 @@ received(crypto(Type, _Wallet, Amount)) = S :- % _Wallet is named throwaway * [Mercury Tutorial](https://mercurylang.org/documentation/papers/book.pdf) (pdf link) - a more traditional tutorial with a more relaxed pace * [Mercury Crash Course](https://mercury-in.space/crash.html) - a dense example-driven tutorial with Q&A format -* [Github Wiki Tutorial](https://github.com/Mercury-Language/mercury/wiki/Tutorial) +* [GitHub Wiki Tutorial](https://github.com/Mercury-Language/mercury/wiki/Tutorial) * [Getting Started with Mercury](https://bluishcoder.co.nz/2019/06/23/getting-started-with-mercury.html) - installation and your first steps ### Documentation diff --git a/montilang.html.markdown b/montilang.html.markdown index 483dc5a5..14b45d31 100644 --- a/montilang.html.markdown +++ b/montilang.html.markdown @@ -230,4 +230,4 @@ DEL 1 PRINT . /# [1, 3] #/ ## Extra information - [MontiLang.ml](http://montilang.ml/) -- [Github Page](https://github.com/lduck11007/MontiLang) +- [GitHub Page](https://github.com/lduck11007/MontiLang) diff --git a/nl-nl/markdown-nl.html.markdown b/nl-nl/markdown-nl.html.markdown index b5b4681c..0af78d88 100644 --- a/nl-nl/markdown-nl.html.markdown +++ b/nl-nl/markdown-nl.html.markdown @@ -52,7 +52,7 @@ __En deze tekst ook!__ *__En zelfs deze!__* +op GitHub, is er ook doorstrepen --> ~~Deze tekst wordt doorstreept.~~ @@ -142,7 +142,7 @@ Dit item zal aangevinkt zijn in de gerenderde html. John wist zelfs niet dat de `go_to()` functie bestond! - \`\`\`ruby @@ -151,7 +151,7 @@ def foobar end \`\`\` - @@ -215,13 +215,13 @@ worden. Dit kan je oplossen met backslashes: \*dit\* staat tussen sterretjes - + Loopt je computer vast? Probeer volgende toetsen combinatie: Ctrl+Alt+Del - | Col1 | Col2 | Col3 | diff --git a/osl.html.markdown b/osl.html.markdown index af5f83bc..1fe010ec 100644 --- a/osl.html.markdown +++ b/osl.html.markdown @@ -747,5 +747,5 @@ for (int i = 0; i < 5; i += 1) { * [Blender Docs for OSL](https://docs.blender.org/manual/en/latest/render/shader_nodes/osl.html) * [C4D Docs for OSL](https://docs.otoy.com/cinema4d//OpenShadingLanguageOSL.html) -* Open Shading Language on [Github](https://github.com/AcademySoftwareFoundation/OpenShadingLanguage) +* Open Shading Language on [GitHub](https://github.com/AcademySoftwareFoundation/OpenShadingLanguage) * [Official OSL Documentation](https://open-shading-language.readthedocs.io/en/main/) \ No newline at end of file diff --git a/pt-br/pug-pt.html.markdown b/pt-br/pug-pt.html.markdown index a74666fb..52eda86a 100644 --- a/pt-br/pug-pt.html.markdown +++ b/pt-br/pug-pt.html.markdown @@ -208,4 +208,4 @@ mixin comment(nome, comentario) ### Saiba Mais - [Site Oficial](https://pugjs.org/) - [Documentação](https://pugjs.org/api/getting-started.html) -- [Repositório no Github](https://github.com/pugjs/pug) +- [Repositório no GitHub](https://github.com/pugjs/pug) diff --git a/pug.html.markdown b/pug.html.markdown index 9badee92..21d8db9f 100644 --- a/pug.html.markdown +++ b/pug.html.markdown @@ -205,4 +205,4 @@ mixin comment(name, comment) ### Additional Resources - [The Site](https://pugjs.org/) - [The Docs](https://pugjs.org/api/getting-started.html) -- [Github Repo](https://github.com/pugjs/pug) +- [GitHub Repo](https://github.com/pugjs/pug) diff --git a/rst.html.markdown b/rst.html.markdown index 8a730c7a..c68c1d54 100644 --- a/rst.html.markdown +++ b/rst.html.markdown @@ -84,11 +84,11 @@ More complex tables can be done easily (merged columns and/or rows) but I sugges There are multiple ways to make links: -- By adding an underscore after a word : Github_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text). +- By adding an underscore after a word : GitHub_ and by adding the target URL after the text (this way has the advantage of not inserting unnecessary URLs in the visible text). - By typing a full comprehensible URL : https://github.com/ (will be automatically converted to a link). -- By making a more Markdown-like link: `Github `_ . +- By making a more Markdown-like link: `GitHub `_ . -.. _Github: https://github.com/ +.. _GitHub: https://github.com/ ``` diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index 4692e628..fc8614c4 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -85,7 +85,7 @@ __И этот тоже.__ *__И даже здесь!__* ``` -В Github Flavored Markdown, стандарте, который используется в Github, +В GitHub Flavored Markdown, стандарте, который используется в GitHub, текст также можно сделать зачёркнутым: ```md @@ -220,7 +220,7 @@ __И этот тоже.__ Ваня даже не знал, что делает функция `go_to()`! ``` -В Github Flavored Markdown для блоков кода можно использовать +В GitHub Flavored Markdown для блоков кода можно использовать специальный синтаксис: ```ruby @@ -230,7 +230,7 @@ end ``` Во фрагменте, приведённом выше, отступ не требуется. -Кроме того, Github подсветит синтаксис языка, указанного после \`\`\` +Кроме того, GitHub подсветит синтаксис языка, указанного после \`\`\` ## Горизонтальный разделитель @@ -330,7 +330,7 @@ Markdown также позволяет размечать ссылку в вид ``` ### Клавиши на клавиатуре -В Github Flavored Markdown для представления клавиш на клавиатуре +В GitHub Flavored Markdown для представления клавиш на клавиатуре вы можете использовать тег ``. ```md diff --git a/ru-ru/sql-ru.html.markdown b/ru-ru/sql-ru.html.markdown index c7ba0edb..702a8102 100644 --- a/ru-ru/sql-ru.html.markdown +++ b/ru-ru/sql-ru.html.markdown @@ -22,7 +22,7 @@ lang: ru-ru поддерживают ключевые слова QUIT, EXIT или оба). Некоторые команды ниже предполагают использование -[демонстрационного образца базы данных сотрудников от MySQL](https://dev.mysql.com/doc/employee/en/), доступного на [Github](https://github.com/datacharmer/test_db). +[демонстрационного образца базы данных сотрудников от MySQL](https://dev.mysql.com/doc/employee/en/), доступного на [GitHub](https://github.com/datacharmer/test_db). Следовательно, для повторения команд в локальном окружении он должен быть загружен. Файлы на github — это скрипты с командами, схожие с командами ниже, которые создают и манипулируют таблицами и данными о сотрудниках вымышленной diff --git a/tr-tr/git-tr.html.markdown b/tr-tr/git-tr.html.markdown index c6979468..ad2f2e95 100644 --- a/tr-tr/git-tr.html.markdown +++ b/tr-tr/git-tr.html.markdown @@ -591,4 +591,4 @@ $ git rm /pather/to/the/file/HelloWorld.c * [Pro Git](http://www.git-scm.com/book/en/v2) -* [Yeni başlayanlar için Git ve Github](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) +* [Yeni başlayanlar için Git ve GitHub](http://product.hubspot.com/blog/git-and-github-tutorial-for-beginners) diff --git a/vi-vn/markdown-vi.html.markdown b/vi-vn/markdown-vi.html.markdown index 52c2df42..696fe465 100644 --- a/vi-vn/markdown-vi.html.markdown +++ b/vi-vn/markdown-vi.html.markdown @@ -309,7 +309,7 @@ Khi ta muốn viết *đoạn văn bản này có dấu sao bao quanh* nhưng ta ### Phím bàn phím -Trong Markdown của Github, ta có thể sử dụng thẻ `` để thay cho phím trên bàn phím. +Trong Markdown của GitHub, ta có thể sử dụng thẻ `` để thay cho phím trên bàn phím. ```md Máy treo? Thử bấm tổ hợp diff --git a/zh-cn/crystal-cn.html.markdown b/zh-cn/crystal-cn.html.markdown index 14805114..b69ce688 100644 --- a/zh-cn/crystal-cn.html.markdown +++ b/zh-cn/crystal-cn.html.markdown @@ -564,4 +564,4 @@ ex #=> "ex2" - [官方网站](https://crystal-lang.org/) - [官方文档](https://crystal-lang.org/docs/overview/) - [在线运行代码](https://play.crystal-lang.org/#/cr) -- [Github仓库](https://github.com/crystal-lang/crystal) +- [GitHub仓库](https://github.com/crystal-lang/crystal) From 327001f58739489b41f6b1f7bbc8be900847b381 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 4 Apr 2024 04:20:22 -0700 Subject: [PATCH 062/392] Normalize file permissions these files do not need to be executable --- pt-br/stylus-pt.html.markdown | 0 toml.html.markdown | 0 vala.html.markdown | 0 3 files changed, 0 insertions(+), 0 deletions(-) mode change 100755 => 100644 pt-br/stylus-pt.html.markdown mode change 100755 => 100644 toml.html.markdown mode change 100755 => 100644 vala.html.markdown diff --git a/pt-br/stylus-pt.html.markdown b/pt-br/stylus-pt.html.markdown old mode 100755 new mode 100644 diff --git a/toml.html.markdown b/toml.html.markdown old mode 100755 new mode 100644 diff --git a/vala.html.markdown b/vala.html.markdown old mode 100755 new mode 100644 From e9a4d929c22557ed3653b870d18617f8297e5c9c Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 4 Apr 2024 04:27:36 -0700 Subject: [PATCH 063/392] Fix typos as requested --- de-de/sql-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/sql-de.html.markdown b/de-de/sql-de.html.markdown index fcf3a36e..9cb95666 100644 --- a/de-de/sql-de.html.markdown +++ b/de-de/sql-de.html.markdown @@ -18,7 +18,7 @@ Einige dieser Beispielbefehle gehen davon aus, dass sie die [MySQL employee samp -- Kommentare starten mit zwei Bindestrichen. Jeder Befehl endet mit einem Semikolon. -- SQL unterscheidet nicht zwischen Groß- und Kleinschreibung bei --- Schlüsselwörtern. Die Beispielbefehele folgen der Konvention der +-- Schlüsselwörtern. Die Beispielbefehle folgen der Konvention der -- Schreibweise in Großbuchstaben, damit sie leichter von Datebank-, -- Tabellen- und Spaltennamen zu unterscheiden sind. @@ -52,7 +52,7 @@ SELECT * FROM departments LIMIT 5; -- in der der Wert dept_name die Teilzeichenfolge 'en' hat. SELECT dept_name FROM departments WHERE dept_name LIKE '%en%'; --- Hole dir alle Spalten von der departments Tabele, in der die dept_name +-- Hole dir alle Spalten von der departments Tabelle, in der die dept_name -- Spalte mit einem 'S' beginnt und exakt 4 Zeichen danach besitzt. SELECT * FROM departments WHERE dept_name LIKE 'S____'; From 10304f3a7e0e6f22c4ec34f5209ec13dbcdf8637 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 4 Apr 2024 08:00:12 -0700 Subject: [PATCH 064/392] Update httpie-pt.html.markdown --- pt-br/httpie-pt.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pt-br/httpie-pt.html.markdown b/pt-br/httpie-pt.html.markdown index 9ef515bc..f81919fe 100644 --- a/pt-br/httpie-pt.html.markdown +++ b/pt-br/httpie-pt.html.markdown @@ -119,4 +119,4 @@ http --follow GET https://example.com # Segue redirecionamentos ## Leitura Adicional - [Documentação Oficial](https://httpie.io/docs/cli). -- [Github](https://github.com/httpie). +- [GitHub](https://github.com/httpie). From 742c6ba20055890f900fdc346decafaa3adc77bc Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Apr 2024 03:21:13 -0700 Subject: [PATCH 065/392] Update haskell-gr.html.markdown --- el-gr/haskell-gr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/el-gr/haskell-gr.html.markdown b/el-gr/haskell-gr.html.markdown index 1560e32e..d2fed85a 100644 --- a/el-gr/haskell-gr.html.markdown +++ b/el-gr/haskell-gr.html.markdown @@ -195,7 +195,7 @@ foldl1 (\acc x -> acc + x) [1..5] -- 15 -- Μερική κλήση: αν δεν περάσουμε όλες τις μεταβλητές σε μια συνάρτηση, -- τότε αυτή "καλείται μερικώς". Αυτό σημαίνει ότι μας επιστρέφει μια συνάρτηση --- η οποία παίρνει ως ορίσματα τις εναπομείναντες μεταβλητές +-- η οποία παίρνει ως ορίσματα τις εναπομείνασες μεταβλητές add a b = a + b foo = add 10 -- η foo είναι μια συνάρτηση που περιμένει 1 αριθμό και του προσθέτει 10 From 64b1e44842ff0b5403ae42a928f8ec4adaf68e3b Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Apr 2024 04:00:49 -0700 Subject: [PATCH 066/392] Normalize natural language tags --- hd-hd/amd.html.markdown | 2 +- hd-hd/d.html.markdown | 2 +- hjson.html.markdown | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/hd-hd/amd.html.markdown b/hd-hd/amd.html.markdown index b85567c2..7e335668 100644 --- a/hd-hd/amd.html.markdown +++ b/hd-hd/amd.html.markdown @@ -4,7 +4,7 @@ tool: amd contributors: - ["Frederik Ring", "https://github.com/m90"] filename: learnamd-hd.js -lang: hd +lang: hd-hd --- ## एएमडी के साथ प्रारंभ करना diff --git a/hd-hd/d.html.markdown b/hd-hd/d.html.markdown index f5e0858a..a08feb2e 100644 --- a/hd-hd/d.html.markdown +++ b/hd-hd/d.html.markdown @@ -3,7 +3,7 @@ language: D filename: learnd-hd.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] -lang: hd +lang: hd-hd --- ```c diff --git a/hjson.html.markdown b/hjson.html.markdown index 6b3cc3ed..e778dabb 100644 --- a/hjson.html.markdown +++ b/hjson.html.markdown @@ -3,7 +3,7 @@ language: Hjson filename: learnhjson.hjson contributors: - ["MrTeferi", "https://github.com/MrTeferi"] -lang: en +lang: en-us --- Hjson is an attempt to make [JSON](https://learnxinyminutes.com/docs/json/) more human readable. From 100fb0a74004cc1e7a9482f5c58a33839fe64aed Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Apr 2024 04:01:29 -0700 Subject: [PATCH 067/392] iBooks -> Apple Books --- de-de/swift-de.html.markdown | 2 +- pt-pt/swift-pt.html.markdown | 2 +- ru-ru/swift-ru.html.markdown | 2 +- swift.html.markdown | 2 +- tr-tr/swift-tr.html.markdown | 2 +- zh-cn/swift-cn.html.markdown | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown index 5828b5d3..c4da99f5 100644 --- a/de-de/swift-de.html.markdown +++ b/de-de/swift-de.html.markdown @@ -13,7 +13,7 @@ lang: de-de Swift ist eine Programmiersprache von Apple für die Entwicklung von iOS und macOS Applikationen. Swift wurde 2014 zu Apples WWDC Entwicklerkonferenz vorgestellt und wurde mit dem Ziel entwickelt, fehlerträchtigen Code zu vermeiden sowie mit Objective-C zu koexistieren. Es wird mit dem LLVM Compiler gebaut und ist ab Xcode 6+ verfügbar. -Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via iBooks verfügbar. +Das offizielle [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) Buch von Apple ist kostenlos via Apple Books verfügbar. Außerdem hilfreich ist Apples [Getting Started Guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), ein guter Einstiegspunkt mit komplettem Swift-Tutorial. diff --git a/pt-pt/swift-pt.html.markdown b/pt-pt/swift-pt.html.markdown index a8d3e1ab..aba1994a 100644 --- a/pt-pt/swift-pt.html.markdown +++ b/pt-pt/swift-pt.html.markdown @@ -16,7 +16,7 @@ Swift é uma linguagem de programação criada pela Apple para o desenvolvimento Desenhada de forma a coexistir com Objective-C e ser mais resiliente contra código errôneo, a linguagem Swift foi introduzida em 2014 na conferência para desenvolvedores WWDC da Apple. Swift usa o compilador LLVM incluido no XCode 6+. -O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via iBooks. +O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple está agora disponivel via Apple Books. Consulta também o [guia de iniciação](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) da Apple, que contêm um tutorial completo em Swift. diff --git a/ru-ru/swift-ru.html.markdown b/ru-ru/swift-ru.html.markdown index bd2d23a0..56471961 100644 --- a/ru-ru/swift-ru.html.markdown +++ b/ru-ru/swift-ru.html.markdown @@ -18,7 +18,7 @@ Swift - это язык программирования, созданный к конференции разработчиков Apple, WWDC. Приложения на Swift собираются с помощью LLVM-компилятора, включенного в Xcode 6+. -Официальная книга по [языку программирования Swift](https://itunes.apple.com/us/book/swift-programming-language/id881256329) от Apple доступна в iBooks. +Официальная книга по [языку программирования Swift](https://itunes.apple.com/us/book/swift-programming-language/id881256329) от Apple доступна в Apple Books. Смотрите еще [начальное руководство](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) Apple, которое содержит полное учебное пособие по Swift. diff --git a/swift.html.markdown b/swift.html.markdown index 36124e11..52015344 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -14,7 +14,7 @@ filename: learnswift.swift Swift is a programming language for iOS and macOS development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6+. -The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via iBooks. It goes into much more detail than this guide, and if you have the time and patience to read it, it's recommended. Some of these examples are from that book. +The official _[Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329)_ book from Apple is now available via Apple Books. It goes into much more detail than this guide, and if you have the time and patience to read it, it's recommended. Some of these examples are from that book. Another great reference is _About Swift_ on Swift's [website](https://docs.swift.org/swift-book/). diff --git a/tr-tr/swift-tr.html.markdown b/tr-tr/swift-tr.html.markdown index 4c2cf59b..29df93ef 100644 --- a/tr-tr/swift-tr.html.markdown +++ b/tr-tr/swift-tr.html.markdown @@ -9,7 +9,7 @@ lang: tr-tr Swift iOS ve OSX platformlarında geliştirme yapmak için Apple tarafından oluşturulan yeni bir programlama dilidir. Objective - C ile beraber kullanılabilecek ve de hatalı kodlara karşı daha esnek bir yapı sunacak bir şekilde tasarlanmıştır. Swift 2014 yılında Apple'ın geliştirici konferansı WWDC de tanıtıldı. Xcode 6+'a dahil edilen LLVM derleyici ile geliştirildi. -Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı iBooks'ta yerini aldı. +Apple'ın resmi [Swift Programlama Dili](https://itunes.apple.com/us/book/swift-programming-language/id881256329) kitabı Apple Books'ta yerini aldı. Ayrıca Swift ile gelen tüm özellikleri görmek için Apple'ın [başlangıç kılavuzu](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html)na bakmanızda yarar var. diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown index c56a0d33..7955cc2b 100644 --- a/zh-cn/swift-cn.html.markdown +++ b/zh-cn/swift-cn.html.markdown @@ -12,7 +12,7 @@ lang: zh-cn Swift 是 Apple 开发的用于 iOS 和 macOS 开发的编程语言。Swift 于2014年 Apple WWDC (全球开发者大会)中被引入,用以与 Objective-C 共存,同时对错误代码更具弹性。Swift 由 Xcode 6 beta 中包含的 LLVM 编译器编译。 -Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载. +Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 Apple Books 免费下载. 亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程 From f712321988dddc7972f36726866776f21dee1390 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Apr 2024 04:03:33 -0700 Subject: [PATCH 068/392] Remove Latino sine flexione --- lsf/lambda-calculus-lsf.html.markdown | 91 ---------------- lsf/latex-lsf.html.markdown | 146 -------------------------- 2 files changed, 237 deletions(-) delete mode 100644 lsf/lambda-calculus-lsf.html.markdown delete mode 100644 lsf/latex-lsf.html.markdown diff --git a/lsf/lambda-calculus-lsf.html.markdown b/lsf/lambda-calculus-lsf.html.markdown deleted file mode 100644 index 88bb638f..00000000 --- a/lsf/lambda-calculus-lsf.html.markdown +++ /dev/null @@ -1,91 +0,0 @@ ---- -category: Algorithms & Data Structures -name: Lambda Calculus -contributors: - - ["Max Sun", "http://github.com/maxsun"] -translators: - - ["Victore Leve", "https://github.com/AcProIL"] -lang: lsf ---- - -# Calculo λ - -Calculo lambda, creato principto per Alonzo Church, es lingua de programmatura -computatro maximo parvo. Quamquam non habe numero, serie de charactere vel ullo -typo de data non functionale, id pote repraesenta omne machina de Turing. - -Tres elemento compone calculo lambda: **quantitate variabile** (q.v.), -**functione** et **applicatione**. - -| Elemento | Syntaxe | Exemplo | -|----------------------|-----------------------------------|-----------| -| Quantitate variabile | `` | `x` | -| Functione | `λ.` | `λx.x` | -| Applicatione | `` | `(λx.x)a` | - -Functione fundamentale es identitate: `λx.x` cum argumento primo `x` et cum -corpore secundo `x`. In mathematica, nos scribe `id: x↦x`. - -## Quantitate variabile libero et ligato - -* In functione praecedente, `x` es q.v. ligato nam id es et in copore et - argumento. -* In `λx.y`, `y` es q.v. libero nam non es declarato ante. - -## Valutatione - -Valutatione es facto per reductione beta (reductione β) que es essentialiter -substitutione lexicale. - -Dum valutatione de formula `(λx.x)a`, nos substitue omne evento de `x` in -corpore de functione pro `a`. - -* `(λx.x)a` vale `a` -* `(λx.y)a` vale `y` - -Pote etiam crea functione de ordine supero: `(λx.(λy.x))a` vale `λy.a`. - -Etsi calculo lambda solo tracta functione de uno parametro, nos pote crea -functione cum plure argumento utente methodo de Curry: `λx.(λy.(λz.xyz))` -es scriptura informatica de formula mathematico `f: x, y, z ↦ x(y(z)))`. - -Ergo, interdum, nos ute `λxy.` pro `λx.λy.`. - -## Arithmetica - -### Logica de Boole - -Es nec numero nec booleano in calculo lambda. - -* «vero» es `v = λx.λy.x` -* «falso» es `f = λx.λy.y` - -Primo, nos pote defini functione «si t tunc a alio b» per `si = λtab.tab`. -Si `t` es vero, valutatione da `(λxy.x) a b` id es `a`. Similiter si `t` es -falso, nos obtine `b`. - -Secundo, nos pote defini operatore de logica: - -* «a et b» es `et = λa.λb.si a b f` -* «a vel b» es `vel = λa.λb.si a t b` -* «non a» es `non = λa.si a f t` - -### Numeros - -Nos pone: - -* `0 = λf.λx.x` (`0: f↦id`) -* `1 = λf.λx.f x` (`1: f↦f`) -* `2 = λf.λx.f(f x)` (`2: f↦f⚬f`) - -Cum mente generale, successore de numero `n` es `S n = λf.λx.f((n f) x)` -(`n+1: f↦f⚬fⁿ`). Id es **`n` est functione que da `fⁿ` ex functione `f`**. - -Postremo additione es `λab.(a S)b` - -## Ut progrede - -### In lingua anglo - -1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) per Raúl Roja -2. [The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html), CS 312 Recitation 26 diff --git a/lsf/latex-lsf.html.markdown b/lsf/latex-lsf.html.markdown deleted file mode 100644 index 18c2e62b..00000000 --- a/lsf/latex-lsf.html.markdown +++ /dev/null @@ -1,146 +0,0 @@ ---- -language: latex -lang: lsf -contributors: - - ["Chaitanya Krishna Ande", "http://icymist.github.io"] - - ["Colton Kohnke", "http://github.com/voltnor"] - - ["Sricharan Chiruvolu", "http://sricharan.xyz"] -translators: - - ["Victore Leve", "https://github.com/AcProIL"] -filename: learn-latex-lsf.tex ---- - -```tex -% Solo existe commentario monolinea, illo incipe cum charactere % - -% LaTeX non es sicut MS Word aut OpenOffice: que scribe non es que obtine. -% Primo, scribe imperio (que semper incipe cum \) et secundo programma crea -% lima. - -% Nos defini typo de document (id es articulo aut libro aut libello etc.). -% Optione muta quomodo programma age, per exemplo altore de littera. -\documentclass[12pt]{article} - -% Deinde nos lista paccettos que nos vol ute. Es classe de imperio que alio -% utatore e scribe. Pote muta funda, geometria de pagina, etc. vel adde -% functionnalitate. -\usepackage{euler} -\usepackage{graphicx} - -% Ultimo statione ante scribe documento es metadata id es titulo, auctore et -% tempore. Charactere ~ es spatio que non pote es secato. -\title{Disce LaTeX in~Y Minutos!} -\author{Chaitanya Krishna Ande, Colton Kohnke \& Sricharan Chiruvolu} -\date{\today} - -% Principio de documento -\begin{document} - \maketitle % Nos vol adfige metadata. - - % Saepe nos adde breviario us describe texto. - \begin{abstract} - Hic es exmplo de documento sibre cum lingua de LaTeX. - \end{abstract} - - % \section crea sectione cum titulo dato sicut sperato - \section{Introductione} - - Traductione de hic cursu es importante. - - \subsection{Methodo} - Iste parte non es utile. - - \subsubsection{Methodo peculiare} - % \label da nomine ad parte ut post ute imperio de referentia \ref. - \label{subsec:metpec} - - % Cum asteritco nos indice que nos non vol numero ante titulo de sectione. - \section*{Me non aestima numero…} - - …sed de Peano aut de Church. - - \section{Listas} - - Que me debe scribe: - - \begin{enumerate} % `enumerate` designa lista cum numeros contra `itemize`. - \item articulo, - \item libro, - \item cursu. - \end{enumerate} - - \section{Mathematica} - - Methematicas ute multo programma LaTeX ut communica suo decooperito. - Illo necessita symbolo multo instar de logica vel sagitta vel littera cum - accento. - - % Fornula es in linea si nos scribe inter \( et \) (aut duo $) sed magno si - % nos ute \[ et \]. - \(\forall n\in N_0\) % pro omne n in classe N₀ - \[^{3}/_{4} = \frac{3}{4} < 1\] % ¾ < 1 - - Alphabeta graeco contine littera $\alpha$. - - % Ut scribe equatione cum numero et nomine, existe circumiecto `equation`. - \begin{equation} - c^2 = a^2 + b^2 - \label{eq:pythagoras} - \end{equation} - - \begin{equation} - % Summa ab 1 ad n de numeros dimidio de n(n+1) - \sum_{i=1}^n i = \frac{n(n+1)}{2} - \end{equation} - - \section{Figura} - - % Nos adde imagine `right-triangle.png` cum latitudo de quinque centimetro, - % horizontaliter in centro et cum capite «Triangulo recto». - \begin{figure} - \centering - \includegraphics[width=5cm]{right-triangle.png} - \caption{Triangulo recto} - \label{fig:right-triangle} - \end{figure} - - \subsection{Tabula} - - \begin{table} - \caption{Título para la tabla.} - % Argumento de `tabular` es lineamente de columna. - % c: centro, l: sinistra, r: destra, | linea verticale - \begin{tabular}{c|cc} - Numero & B & C \\ - \hline % linea horizontale - 1 & et & aut \\ - 2 & atque & vel - \end{tabular} - \end{table} - - \section{Stylo} - - Texto pote es \textbf{crasso} et \textit{italico}! - - \section{Texto puro} - - % Circumiecto `verbatim` ignora imperio, nos saepe ute id pro monstra - % programma. - \begin{verbatim} -from math import tau, e -print(e ** tau) - \end{verbatim} - - \section{Et plus!} - LaTeX habe facultate crea bibliographia, paritura, scaccarip… cum paccetto - dedicato. -\end{document} -``` - -Imperio ut conge documento es `pdflatex documento` in terminale. - -## Ut progrede - -### In lingua anglo - -* [LaTeX tutorial](http://www.latex-tutorial.com/) per Claudio Vellage From 9fa4b5af80f1cd7fe2469c198d02a21e4f8884a1 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Apr 2024 06:59:13 -0700 Subject: [PATCH 069/392] Add missing natural language tags --- el-gr/haskell-gr.html.markdown | 3 ++- sk-sk/latex-sk.html.markdown | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/el-gr/haskell-gr.html.markdown b/el-gr/haskell-gr.html.markdown index d2fed85a..c202f3a4 100644 --- a/el-gr/haskell-gr.html.markdown +++ b/el-gr/haskell-gr.html.markdown @@ -1,8 +1,9 @@ --- language: Haskell -filename: haskell-gr.html.markdown contributors: - ["Miltiadis Stouras", "https://github.com/mstou"] +lang: el-gr +filename: learnhaskell-gr.hs --- Η Haskell σχεδιάστηκε για να είναι μια πρακτική, αγνή συναρτησιακή γλώσσα προγραμματισμού. diff --git a/sk-sk/latex-sk.html.markdown b/sk-sk/latex-sk.html.markdown index 5e2f9c7f..9c2b2a29 100644 --- a/sk-sk/latex-sk.html.markdown +++ b/sk-sk/latex-sk.html.markdown @@ -6,6 +6,7 @@ contributors: - ["Sricharan Chiruvolu", "http://sricharan.xyz"] translators: - ["Terka Slanináková", "http://github.com/TerkaSlan"] +lang: sk-sk filename: learn-latex-sk.tex --- From 3e687f1a8ccb1cd0d52a966005551d528ca141df Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Apr 2024 08:33:50 -0700 Subject: [PATCH 070/392] Remove leading and trailing empty lines in code blocks --- CHICKEN.html.markdown | 2 +- amd.html.markdown | 7 ++ ar-ar/html-ar.html.markdown | 1 - ar-ar/python-ar.html.markdown | 1 - ar-ar/sql-ar.html.markdown | 1 + asciidoc.html.markdown | 1 - assemblyscript.html.markdown | 1 - awk.html.markdown | 1 - bc.html.markdown | 1 + c++.html.markdown | 3 +- c.html.markdown | 1 - ca-es/groovy-ca.html.markdown | 3 - ca-es/html-ca.html.markdown | 1 - ca-es/kotlin-ca.html.markdown | 1 - cobol.html.markdown | 6 -- coldfusion.html.markdown | 1 + common-lisp.html.markdown | 1 - crystal.html.markdown | 2 - cs-cz/hack.html.markdown | 1 - cs-cz/python.html.markdown | 1 - cs-cz/sass.html.markdown | 4 -- csharp.html.markdown | 1 - cue.html.markdown | 2 + cypher.html.markdown | 21 +++++- d.html.markdown | 1 - dart.html.markdown | 1 - de-de/asciidoc-de.html.markdown | 1 - de-de/bc.html.markdown | 1 + de-de/c++-de.html.markdown | 3 +- de-de/c-de.html.markdown | 1 + de-de/crystal-de.html.markdown | 1 - de-de/css-de.html.markdown | 3 - de-de/d-de.html.markdown | 2 - de-de/edn-de.html.markdown | 1 - de-de/elixir-de.html.markdown | 2 - de-de/hack-de.html.markdown | 1 - de-de/haml-de.html.markdown | 1 - de-de/haskell-de.html.markdown | 1 - de-de/html-de.html.markdown | 1 - de-de/latex-de.html.markdown | 1 + de-de/lua-de.html.markdown | 2 +- de-de/make-de.html.markdown | 1 - de-de/processing-de.html.markdown | 1 - de-de/pug-de.html.markdown | 3 +- de-de/pyqt-de.html.markdown | 1 - de-de/python-de.html.markdown | 2 - de-de/pythonlegacy-de.html.markdown | 1 - de-de/rst-de.html.markdown | 1 - de-de/sass-de.html.markdown | 3 - de-de/scala-de.html.markdown | 1 - de-de/shutit-de.html.markdown | 1 - de-de/tcl-de.html.markdown | 2 - docker.html.markdown | 5 +- edn.html.markdown | 1 - el-gr/haskell-gr.html.markdown | 1 - el-gr/html-gr.html.markdown | 1 - el-gr/java-gr.html.markdown | 1 - el-gr/ocaml-gr.html.markdown | 1 + el-gr/python-gr.html.markdown | 1 - el-gr/scala-gr.html.markdown | 2 - erlang.html.markdown | 1 - es-es/asymptotic-notation-es.html.markdown | 1 + es-es/awk-es.html.markdown | 1 - es-es/bf-es.html.markdown | 2 +- es-es/binary-search-es.html.markdown | 5 +- es-es/c++-es.html.markdown | 2 +- es-es/c-es.html.markdown | 1 - es-es/coldfusion-es.html.markdown | 1 + es-es/common-lisp-es.html.markdown | 1 - es-es/csharp-es.html.markdown | 1 - es-es/dart-es.html.markdown | 1 - es-es/edn-es.html.markdown | 1 - es-es/elixir-es.html.markdown | 1 - es-es/factor-es.html.markdown | 2 - es-es/forth-es.html.markdown | 1 - es-es/groovy-es.html.markdown | 3 - es-es/hack-es.html.markdown | 1 - es-es/haml-es.html.markdown | 1 - es-es/haskell-es.html.markdown | 1 - es-es/html-es.html.markdown | 1 - es-es/java-es.html.markdown | 1 - es-es/jquery-es.html.markdown | 4 -- es-es/json-es.html.markdown | 1 - es-es/lambda-calculus-es.html.markdown | 5 ++ es-es/learnsmallbasic-es.html.markdown | 2 +- es-es/less-es.html.markdown | 4 -- es-es/matlab-es.html.markdown | 1 - es-es/objective-c-es.html.markdown | 2 +- es-es/pascal-es.html.markdown | 1 - es-es/perl-es.html.markdown | 1 - es-es/php-composer-es.html.markdown | 2 +- es-es/php-es.html.markdown | 1 - es-es/pyqt-es.html.markdown | 1 - es-es/python-es.html.markdown | 1 - es-es/pythonstatcomp-es.html.markdown | 1 - es-es/r-es.html.markdown | 4 -- es-es/raku-es.html.markdown | 2 +- es-es/sass-es.html.markdown | 3 - es-es/scala-es.html.markdown | 2 - es-es/tcl-es.html.markdown | 2 - es-es/tmux-es.html.markdown | 4 -- es-es/tmux.html.markdown | 4 -- es-es/typescript-es.html.markdown | 1 - es-es/visualbasic-es.html.markdown | 1 - es-es/xml-es.html.markdown | 3 - es-es/yaml-es.html.markdown | 1 - fa-ir/css-fa.html.markdown | 5 +- fa-ir/java-fa.html.markdown | 1 - fa-ir/javascript-fa.html.markdown | 82 ++++++++++++++++++++++ factor.html.markdown | 2 - fish.html.markdown | 1 - forth.html.markdown | 1 - fortran.html.markdown | 2 - fr-fr/HTML-fr.html.markdown | 1 - fr-fr/awk-fr.html.markdown | 1 - fr-fr/binary-search-fr.html.markdown | 5 +- fr-fr/c++-fr.html.markdown | 4 +- fr-fr/crystal-fr.html.markdown | 2 - fr-fr/css-fr.html.markdown | 3 - fr-fr/d-fr.html.markdown | 6 +- fr-fr/elixir-fr.html.markdown | 1 - fr-fr/erlang-fr.html.markdown | 1 - fr-fr/fsharp-fr.html.markdown | 2 - fr-fr/haml-fr.html.markdown | 1 - fr-fr/haskell-fr.html.markdown | 1 - fr-fr/java-fr.html.markdown | 1 - fr-fr/javascript-fr.html.markdown | 1 - fr-fr/jquery-fr.html.markdown | 4 -- fr-fr/lua-fr.html.markdown | 2 +- fr-fr/make-fr.html.markdown | 1 - fr-fr/objective-c-fr.html.markdown | 1 - fr-fr/php-fr.html.markdown | 1 - fr-fr/pyqt-fr.html.markdown | 1 - fr-fr/python-fr.html.markdown | 1 - fr-fr/pythonlegacy-fr.html.markdown | 2 - fr-fr/r-fr.html.markdown | 4 -- fr-fr/ruby-fr.html.markdown | 1 - fr-fr/scala-fr.html.markdown | 3 - fr-fr/tmux-fr.html.markdown | 4 -- fr-fr/typescript-fr.html.markdown | 1 - fr-fr/xml-fr.html.markdown | 3 - fr-fr/yaml-fr.html.markdown | 1 - fsharp.html.markdown | 2 - git.html.markdown | 3 + groovy.html.markdown | 3 - hack.html.markdown | 1 - haml.html.markdown | 1 - haskell.html.markdown | 1 - haxe.html.markdown | 1 - hdl.html.markdown | 2 - html.html.markdown | 1 - hu-hu/pythonlegacy-hu.html.markdown | 1 - hu-hu/typescript-hu.html.markdown | 1 - id-id/asciidoc-id.html.markdown | 1 - id-id/css-id.html.markdown | 4 -- id-id/java-id.html.markdown | 1 - id-id/php-id.html.markdown | 1 - id-id/rst-id.html.markdown | 1 - id-id/smallbasic-id.html.markdown | 1 - id-id/xml-id.html.markdown | 4 +- it-it/asciidoc-it.html.markdown | 1 - it-it/bf-it.html.markdown | 1 - it-it/c++-it.html.markdown | 2 +- it-it/elixir-it.html.markdown | 1 - it-it/html-it.html.markdown | 1 - it-it/java-it.html.markdown | 1 + it-it/jquery-it.html.markdown | 4 -- it-it/matlab-it.html.markdown | 1 - it-it/php-composer-it.html.markdown | 2 +- it-it/pyqt-it.html.markdown | 1 - it-it/python-it.html.markdown | 1 - it-it/pythonlegacy-it.html.markdown | 1 - it-it/rst-it.html.markdown | 1 - it-it/solidity.html.markdown | 1 - it-it/zfs-it.html.markdown | 2 - ja-jp/asciidoc.html.markdown | 1 - ja-jp/bash-jp.html.markdown | 1 - ja-jp/julia-jp.html.markdown | 1 - ja-jp/php-jp.html.markdown | 1 - ja-jp/r-jp.html.markdown | 6 -- jinja.html.markdown | 2 - jquery.html.markdown | 3 - jsonnet.html.markdown | 1 - ko-kr/erlang-kr.html.markdown | 1 - ko-kr/java-kr.html.markdown | 1 - ko-kr/kotlin-kr.html.markdown | 1 - ko-kr/lua-kr.html.markdown | 1 - ko-kr/php-kr.html.markdown | 1 - ko-kr/pythonlegacy-kr.html.markdown | 2 - less.html.markdown | 4 -- lfe.html.markdown | 1 - lt-lt/tmux-lt.html.markdown | 4 -- lua.html.markdown | 1 - m.html.markdown | 11 ++- make.html.markdown | 1 - matlab.html.markdown | 1 - messagepack.html.markdown | 2 - mips.html.markdown | 1 - ms-my/common-lisp-my.html.markdown | 1 - ms-my/javascript-my.html.markdown | 1 + ms-my/sass-my.html.markdown | 5 -- ms-my/xml-my.html.markdown | 3 - nl-nl/typescript-nl.html.markdown | 1 - nl-nl/xml-nl.html.markdown | 3 - objective-c.html.markdown | 2 +- osl.html.markdown | 4 +- pascal.html.markdown | 1 - pcre.html.markdown | 2 - php-composer.html.markdown | 2 +- php.html.markdown | 1 - pl-pl/haskell-pl.html.markdown | 1 - pl-pl/perl-pl.html.markdown | 2 - pl-pl/xml-pl.html.markdown | 4 -- powershell.html.markdown | 2 +- pt-br/asciidoc-pt.html.markdown | 1 - pt-br/asymptotic-notation-pt.html.markdown | 1 + pt-br/awk-pt.html.markdown | 1 - pt-br/bc-pt.html.markdown | 1 + pt-br/binary-search-pt.html.markdown | 5 +- pt-br/c++-pt.html.markdown | 1 + pt-br/c-pt.html.markdown | 1 - pt-br/clojure-macros-pt.html.markdown | 1 - pt-br/common-lisp-pt.html.markdown | 1 - pt-br/cypher-pt.html.markdown | 21 +++++- pt-br/d-pt.html.markdown | 1 - pt-br/dart-pt.html.markdown | 1 - pt-br/elixir-pt.html.markdown | 1 - pt-br/erlang-pt.html.markdown | 1 - pt-br/factor-pt.html.markdown | 2 - pt-br/fsharp-pt.html.markdown | 2 - pt-br/git-pt.html.markdown | 2 + pt-br/groovy-pt.html.markdown | 3 - pt-br/hack-pt.html.markdown | 1 - pt-br/haxe-pt.html.markdown | 2 +- pt-br/html-pt.html.markdown | 1 - pt-br/java-pt.html.markdown | 1 - pt-br/jquery-pt.html.markdown | 4 -- pt-br/kotlin-pt.html.markdown | 1 - pt-br/less-pt.html.markdown | 4 -- pt-br/lua-pt.html.markdown | 1 - pt-br/make-pt.html.markdown | 1 - pt-br/matlab-pt.html.markdown | 1 - pt-br/pascal-pt.html.markdown | 1 - pt-br/php-composer-pt.html.markdown | 2 +- pt-br/php-pt.html.markdown | 1 - pt-br/pug-pt.html.markdown | 3 +- pt-br/pyqt-pt.html.markdown | 1 - pt-br/python-pt.html.markdown | 1 - pt-br/pythonlegacy-pt.html.markdown | 2 - pt-br/pythonstatcomp-pt.html.markdown | 4 -- pt-br/r-pt.html.markdown | 4 -- pt-br/sass-pt.html.markdown | 4 -- pt-br/scala-pt.html.markdown | 1 - pt-br/set-theory-pt.html.markdown | 4 ++ pt-br/stylus-pt.html.markdown | 2 - pt-br/swift-pt.html.markdown | 1 - pt-br/tmux-pt.html.markdown | 4 -- pt-br/typescript-pt.html.markdown | 1 - pt-br/visualbasic-pt.html.markdown | 1 - pt-br/xml-pt.html.markdown | 3 - pt-br/yaml-pt.html.markdown | 1 + pt-pt/scala-pt.html.markdown | 2 - pug.html.markdown | 3 +- purescript.html.markdown | 2 - pyqt.html.markdown | 1 - python.html.markdown | 2 - pythonlegacy.html.markdown | 1 - pythonstatcomp.html.markdown | 4 -- r.html.markdown | 4 -- raku-pod.html.markdown | 1 + raylib.html.markdown | 1 - rdf.html.markdown | 1 - red.html.markdown | 2 +- ro-ro/bf-ro.html.markdown | 1 - ro-ro/elixir-ro.html.markdown | 1 - ro-ro/haskell-ro.html.markdown | 2 +- ro-ro/pythonlegacy-ro.html.markdown | 2 - ro-ro/xml-ro.html.markdown | 3 - rst.html.markdown | 1 - ru-ru/binary-search-ru.html.markdown | 4 +- ru-ru/c++-ru.html.markdown | 2 +- ru-ru/common-lisp-ru.html.markdown | 1 - ru-ru/crystal-ru.html.markdown | 1 - ru-ru/css-ru.html.markdown | 3 - ru-ru/d-ru.html.markdown | 1 + ru-ru/elixir-ru.html.markdown | 1 - ru-ru/erlang-ru.html.markdown | 1 - ru-ru/forth-ru.html.markdown | 1 - ru-ru/haml-ru.html.markdown | 1 - ru-ru/haskell-ru.html.markdown | 1 - ru-ru/html-ru.html.markdown | 1 - ru-ru/java-ru.html.markdown | 1 - ru-ru/jquery-ru.html.markdown | 4 -- ru-ru/julia-ru.html.markdown | 1 - ru-ru/kotlin-ru.html.markdown | 1 - ru-ru/learnvisualbasic-ru.html.markdown | 1 - ru-ru/lua-ru.html.markdown | 2 +- ru-ru/objective-c-ru.html.markdown | 2 +- ru-ru/pascal-ru.html.markdown | 1 - ru-ru/php-composer-ru.html.markdown | 1 + ru-ru/php-ru.html.markdown | 1 - ru-ru/pyqt-ru.html.markdown | 2 - ru-ru/python-ru.html.markdown | 2 - ru-ru/pythonlegacy-ru.html.markdown | 1 - ru-ru/qt-ru.html.markdown | 1 + ru-ru/rust-ru.html.markdown | 1 - ru-ru/tcl-ru.html.markdown | 3 - ru-ru/tmux-ru.html.markdown | 4 -- ru-ru/typescript-ru.html.markdown | 1 - ru-ru/xml-ru.html.markdown | 3 - ru-ru/zfs-ru.html.markdown | 2 - sass.html.markdown | 3 - scala.html.markdown | 2 - self.html.markdown | 1 + shutit.html.markdown | 1 - sk-sk/elixir-sk.html.markdown | 1 - sl-si/asciidoc-sl.html.markdown | 2 - smallbasic.html.markdown | 1 - solidity.html.markdown | 1 - stylus.html.markdown | 1 - sv-se/haskell-sv.html.markdown | 1 - ta_in/xml-ta.html.markdown | 3 - tact.html.markdown | 1 - tailspin.html.markdown | 1 - tcl.html.markdown | 2 - textile.html.markdown | 11 +-- th-th/pascal.th.html.markdown | 1 - th-th/typescript.th.html.markdown | 2 - tmux.html.markdown | 4 -- toml.html.markdown | 3 +- tr-tr/c++-tr.html.markdown | 3 +- tr-tr/c-tr.html.markdown | 1 - tr-tr/dynamic-programming-tr.html.markdown | 3 +- tr-tr/edn-tr.html.markdown | 1 - tr-tr/fsharp-tr.html.markdown | 2 - tr-tr/git-tr.html.markdown | 5 ++ tr-tr/html-tr.html.markdown | 1 - tr-tr/jquery-tr.html.markdown | 2 - tr-tr/kotlin-tr.html.markdown | 2 - tr-tr/objective-c-tr.html.markdown | 4 +- tr-tr/php-tr.html.markdown | 1 - tr-tr/python-tr.html.markdown | 1 - tr-tr/pythonlegacy-tr.html.markdown | 3 - tr-tr/typescript-tr.html.markdown | 1 - typescript.html.markdown | 1 - uk-ua/c-ua.html.markdown | 2 +- uk-ua/cypher-ua.html.markdown | 19 ++++- uk-ua/java-ua.html.markdown | 1 - uk-ua/json-ua.html.markdown | 2 - uk-ua/mips-ua.html.markdown | 1 - uk-ua/wasm-ua.html.markdown | 1 - v.html.markdown | 2 +- vala.html.markdown | 3 +- vi-vn/html-vi.html.markdown | 1 - vi-vn/less-vi.html.markdown | 4 -- vi-vn/objective-c-vi.html.markdown | 4 +- vi-vn/python-vi.html.markdown | 1 - vi-vn/sass-vi.html.markdown | 3 - vi-vn/typescript-vi.html.markdown | 1 - visualbasic.html.markdown | 1 - vyper.html.markdown | 1 - wasm.html.markdown | 1 - zfs.html.markdown | 2 - zh-cn/asciidoc-cn.html.markdown | 1 - zh-cn/awk-cn.html.markdown | 2 +- zh-cn/bf-cn.html.markdown | 1 + zh-cn/c++-cn.html.markdown | 1 + zh-cn/c-cn.html.markdown | 1 - zh-cn/cobol-cn.html.markdown | 6 -- zh-cn/crystal-cn.html.markdown | 2 - zh-cn/csharp-cn.html.markdown | 1 - zh-cn/css-cn.html.markdown | 3 - zh-cn/dart-cn.html.markdown | 1 - zh-cn/elixir-cn.html.markdown | 1 - zh-cn/erlang-cn.html.markdown | 1 - zh-cn/fortran-cn.html.markdown | 1 - zh-cn/groovy-cn.html.markdown | 3 - zh-cn/haskell-cn.html.markdown | 1 - zh-cn/html-cn.html.markdown | 1 - zh-cn/java-cn.html.markdown | 1 - zh-cn/jquery-cn.html.markdown | 4 -- zh-cn/kotlin-cn.html.markdown | 1 - zh-cn/less-cn.html.markdown | 4 -- zh-cn/matlab-cn.html.markdown | 1 - zh-cn/mips-cn.html.markdown | 1 - zh-cn/perl-cn.html.markdown | 2 - zh-cn/php-cn.html.markdown | 1 - zh-cn/pythonlegacy-cn.html.markdown | 3 - zh-cn/r-cn.html.markdown | 1 - zh-cn/raylib-cn.html.markdown | 1 - zh-cn/red-cn.html.markdown | 1 - zh-cn/sass-cn.html.markdown | 3 - zh-cn/scala-cn.html.markdown | 2 - zh-cn/sql-cn.html.markdown | 1 - zh-cn/swift-cn.html.markdown | 1 - zh-cn/tmux-cn.html.markdown | 4 -- zh-cn/typescript-cn.html.markdown | 1 - zh-cn/visualbasic-cn.html.markdown | 1 - zh-cn/xml-cn.html.markdown | 3 - zh-cn/zfs-cn.html.markdown | 1 - zh-tw/dart-tw.html.markdown | 1 - zh-tw/elixir-tw.html.markdown | 1 - zh-tw/pythonlegacy-tw.html.markdown | 1 - 403 files changed, 257 insertions(+), 618 deletions(-) diff --git a/CHICKEN.html.markdown b/CHICKEN.html.markdown index 4ae45cac..37f6c859 100644 --- a/CHICKEN.html.markdown +++ b/CHICKEN.html.markdown @@ -504,8 +504,8 @@ sqr ;; => # (import star-squarer) (square 3) ;; => ((* * *)(* * *)(* * *)) - ``` + ## Further Reading * [CHICKEN User's Manual](https://wiki.call-cc.org/manual). * [R5RS standards](http://www.schemers.org/Documents/Standards/R5RS) diff --git a/amd.html.markdown b/amd.html.markdown index fc8f20a4..82739780 100644 --- a/amd.html.markdown +++ b/amd.html.markdown @@ -15,6 +15,7 @@ synchronous loading of modules incurs performance, usability, debugging, and cross-domain access problems. ### Basic concept + ```javascript // The basic AMD API consists of nothing but two methods: `define` and `require` // and is all about module definition and consumption: @@ -117,6 +118,7 @@ define(['daos/things', 'modules/someHelpers'], function(thingsDao, helpers){ return SomeClass; }); ``` + To alter the default path mapping behavior use `requirejs.config(configObj)` in your `main.js`: ```javascript @@ -135,6 +137,7 @@ require(['jquery', 'coolLibFromBower', 'modules/someHelpers'], function($, coolL coolLib.doFancyStuffWith(helpers.transform($('#foo'))); }); ``` + `require.js`-based apps will usually have a single entry point (`main.js`) that is passed to the `require.js` script tag as a data-attribute. It will be automatically loaded and executed on pageload: ```html @@ -156,16 +159,19 @@ Many people prefer using AMD for sane code organization during development, but `require.js` comes with a script called `r.js` (that you will probably run in node.js, although Rhino is supported too) that can analyse your project's dependency graph, and build a single file containing all your modules (properly named), minified and ready for consumption. Install it using `npm`: + ```shell $ npm install requirejs -g ``` Now you can feed it with a configuration file: + ```shell $ r.js -o app.build.js ``` For our above example the configuration might look like: + ```javascript /* file : app.build.js */ ({ @@ -182,6 +188,7 @@ For our above example the configuration might look like: ``` To use the built file in production, simply swap `data-main`: + ```html ``` diff --git a/ar-ar/html-ar.html.markdown b/ar-ar/html-ar.html.markdown index f17164cf..b88df668 100644 --- a/ar-ar/html-ar.html.markdown +++ b/ar-ar/html-ar.html.markdown @@ -107,7 +107,6 @@ HTML اختصار ل HyperText Markup Language، أي "لغة ترميز الن الصف الثاني، العمود الأول - ``` ## الاستعمال diff --git a/ar-ar/python-ar.html.markdown b/ar-ar/python-ar.html.markdown index f89c2f25..76191387 100644 --- a/ar-ar/python-ar.html.markdown +++ b/ar-ar/python-ar.html.markdown @@ -22,7 +22,6 @@ filename: learnpython-ar.py ملحوظة: هذا المقال يُطبق على بايثون 3 فقط. راجع المقال [هنا](http://learnxinyminutes.com/docs/pythonlegacy/) إذا أردت تعلم لغة البايثون نسخة 2.7 الأقدم ```python - # تعليق من سطر واحد يبدأ برمز الرقم. """ يمكن كتابة تعليق يتكون من أكثر من سطر diff --git a/ar-ar/sql-ar.html.markdown b/ar-ar/sql-ar.html.markdown index dea20c1f..de1f16a2 100644 --- a/ar-ar/sql-ar.html.markdown +++ b/ar-ar/sql-ar.html.markdown @@ -125,6 +125,7 @@ DELETE FROM tablename1; -- تماما tablename1 إزالة جدول DROP TABLE tablename1; ``` +
    ## اقرأ أكثر diff --git a/asciidoc.html.markdown b/asciidoc.html.markdown index 557ed294..95c545ce 100644 --- a/asciidoc.html.markdown +++ b/asciidoc.html.markdown @@ -81,7 +81,6 @@ Section Titles ==== Level 3

    ===== Level 4

    - ``` Lists diff --git a/assemblyscript.html.markdown b/assemblyscript.html.markdown index 4433b41e..0bc4bf0d 100644 --- a/assemblyscript.html.markdown +++ b/assemblyscript.html.markdown @@ -193,7 +193,6 @@ let doubles = [0.0, 1.0, 2, 3, 4] // will infer as Array let bytes1 = [0 as u8, 1, 2, 3, 4] // will infer as Array let bytes2 = [0, 1, 2, 3, 4] as u8[] // will infer as Array let bytes3: u8[] = [0, 1, 2, 3, 4] // will infer as Array - ``` ## Further Reading diff --git a/awk.html.markdown b/awk.html.markdown index e1d4a0a3..ee4cfcac 100644 --- a/awk.html.markdown +++ b/awk.html.markdown @@ -375,7 +375,6 @@ END { if (nlines) print "The average age for " name " is " sum / nlines; } - ``` Further Reading: diff --git a/bc.html.markdown b/bc.html.markdown index 9d63acfb..1103d7bb 100644 --- a/bc.html.markdown +++ b/bc.html.markdown @@ -93,6 +93,7 @@ print a[0], " ", a[1], " ", a[2], " ", a[3], "\n" quit /*Add this line of code to make sure that your program exits. This line of code is optional.*/ ``` + Enjoy this simple calculator! (Or this programming language, to be exact.) This whole program is written in GNU bc. To run it, use ```bc learnbc.bc```. diff --git a/c++.html.markdown b/c++.html.markdown index 499eb669..6a3fdb5b 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1196,9 +1196,8 @@ compl 4 // Performs a bitwise not 4 bitor 3 // Performs bitwise or 4 bitand 3 // Performs bitwise and 4 xor 3 // Performs bitwise xor - - ``` + Further Reading: * An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp). diff --git a/c.html.markdown b/c.html.markdown index ef341abf..a737696f 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -905,7 +905,6 @@ Node createLinkedList(int *vals, int len); /* a header file but instead put into separate headers or a C file. */ #endif /* End of the if precompiler directive. */ - ``` ## Further Reading diff --git a/ca-es/groovy-ca.html.markdown b/ca-es/groovy-ca.html.markdown index f0a9adbe..9e3dabe1 100644 --- a/ca-es/groovy-ca.html.markdown +++ b/ca-es/groovy-ca.html.markdown @@ -13,7 +13,6 @@ translations: Groovy - Un llenguatge dinàmic per la plataforma Java [Llegir-ne més.](http://www.groovy-lang.org/) ```groovy - /* Posa'l en marxa tu mateix: @@ -413,8 +412,6 @@ int sum(int x, int y) { } assert sum(2,5) == 7 - - ``` ## Per aprendre'n més diff --git a/ca-es/html-ca.html.markdown b/ca-es/html-ca.html.markdown index 351eb722..206d9885 100644 --- a/ca-es/html-ca.html.markdown +++ b/ca-es/html-ca.html.markdown @@ -160,7 +160,6 @@ article tracta principalment la sintaxi de l'HTML i alguns consells útils. Segona fila, segona columna - ``` ## Ús diff --git a/ca-es/kotlin-ca.html.markdown b/ca-es/kotlin-ca.html.markdown index cd05a808..04681e11 100644 --- a/ca-es/kotlin-ca.html.markdown +++ b/ca-es/kotlin-ca.html.markdown @@ -379,7 +379,6 @@ fun useObject() { ObjectExample.hello() val someRef: Any = ObjectExample // podem fer servir el nom de l'objecte } - ``` ### Per llegir més diff --git a/cobol.html.markdown b/cobol.html.markdown index 1350c66f..208aec94 100644 --- a/cobol.html.markdown +++ b/cobol.html.markdown @@ -184,12 +184,6 @@ organizations. *and then re-run the program. This time the output is: THE FULL NAME IS: BOB GIBBERISH COBB - - - - - - ``` ##Ready For More? diff --git a/coldfusion.html.markdown b/coldfusion.html.markdown index 97259f56..01d44e98 100644 --- a/coldfusion.html.markdown +++ b/coldfusion.html.markdown @@ -233,6 +233,7 @@ ColdFusion started as a tag-based language. Almost all functionality is availabl Code for reference (Functions must return something to support IE) ``` + ```cfs diff --git a/common-lisp.html.markdown b/common-lisp.html.markdown index 1f2bb366..6fbb9a25 100644 --- a/common-lisp.html.markdown +++ b/common-lisp.html.markdown @@ -17,7 +17,6 @@ popular and recent book is [Land of Lisp](http://landoflisp.com/). A new book ab ```lisp - ;;;----------------------------------------------------------------------------- ;;; 0. Syntax ;;;----------------------------------------------------------------------------- diff --git a/crystal.html.markdown b/crystal.html.markdown index d32712ce..eed009cb 100644 --- a/crystal.html.markdown +++ b/crystal.html.markdown @@ -9,7 +9,6 @@ contributors: --- ```crystal - # This is a comment # Everything is an object @@ -556,7 +555,6 @@ rescue ex4 # catch any kind of exception end ex #=> "ex2" - ``` ## Additional resources diff --git a/cs-cz/hack.html.markdown b/cs-cz/hack.html.markdown index 736ad7e0..9004632a 100644 --- a/cs-cz/hack.html.markdown +++ b/cs-cz/hack.html.markdown @@ -295,7 +295,6 @@ class Samuel $cat = new Samuel(); $cat instanceof KittenInterface === true; // True - ``` ## Více informací diff --git a/cs-cz/python.html.markdown b/cs-cz/python.html.markdown index 71509460..b89408a0 100644 --- a/cs-cz/python.html.markdown +++ b/cs-cz/python.html.markdown @@ -20,7 +20,6 @@ autora českého překladu pak na [@tbedrich](http://twitter.com/tbedrich) nebo Poznámka: Tento článek je zaměřen na Python 3. Zde se můžete [naučit starší Python 2.7](http://learnxinyminutes.com/docs/pythonlegacy/). ```python - # Jednořádkový komentář začíná křížkem """ Víceřádkové komentáře používají tři uvozovky nebo apostrofy diff --git a/cs-cz/sass.html.markdown b/cs-cz/sass.html.markdown index 0d2fca64..c8c5a2ca 100644 --- a/cs-cz/sass.html.markdown +++ b/cs-cz/sass.html.markdown @@ -19,8 +19,6 @@ Tento tutoriál bude používat syntaxi CSS. Pokud jste již obeznámeni s CSS3, budete schopni používat Sass relativně rychle. Nezprostředkovává nějaké úplně nové stylové možnosti, spíše nátroje, jak psát Vás CSS kód více efektivně, udržitelně a jednoduše. ```scss - - //Jednořádkové komentáře jsou ze Sassu při kompilaci vymazány /*Víceřádkové komentáře jsou naopak zachovány */ @@ -411,8 +409,6 @@ body { .gutter { width: 6.25%; } - - ``` diff --git a/csharp.html.markdown b/csharp.html.markdown index 1d7d0881..cfc75d25 100644 --- a/csharp.html.markdown +++ b/csharp.html.markdown @@ -1311,7 +1311,6 @@ namespace Csharp7 } } } - ``` ## Topics Not Covered diff --git a/cue.html.markdown b/cue.html.markdown index a1ff0822..a1a21086 100644 --- a/cue.html.markdown +++ b/cue.html.markdown @@ -23,6 +23,7 @@ disposition: "oblivious" ``` Now we can unify and export to JSON: + ```bash % cue export name.cue disposition.cue { @@ -32,6 +33,7 @@ Now we can unify and export to JSON: ``` Or YAML: + ```bash % cue export --out yaml name.cue disposition.cue name: Daniel diff --git a/cypher.html.markdown b/cypher.html.markdown index 32868354..5fe113a2 100644 --- a/cypher.html.markdown +++ b/cypher.html.markdown @@ -93,7 +93,6 @@ path = shortestPath( (user)-[:KNOWS*..5]-(other) ) // Tree navigation (root)<-[:PARENT*]-(leaf:Category)-[:ITEM]->(data:Product) - ``` @@ -101,13 +100,16 @@ Create queries --- Create a new node + ``` CREATE (a:Person {name:"Théo Gauchoux"}) RETURN a ``` + *`RETURN` allows to have a result after the query. It can be multiple, as `RETURN a, b`.* Create a new relationship (with 2 new nodes) + ``` CREATE (a:Person)-[k:KNOWS]-(b:Person) RETURN a,k,b @@ -117,36 +119,42 @@ Match queries --- Match all nodes + ``` MATCH (n) RETURN n ``` Match nodes by label + ``` MATCH (a:Person) RETURN a ``` Match nodes by label and property + ``` MATCH (a:Person {name:"Théo Gauchoux"}) RETURN a ``` Match nodes according to relationships (undirected) + ``` MATCH (a)-[:KNOWS]-(b) RETURN a,b ``` Match nodes according to relationships (directed) + ``` MATCH (a)-[:MANAGES]->(b) RETURN a,b ``` Match nodes with a `WHERE` clause + ``` MATCH (p:Person {name:"Théo Gauchoux"})-[s:LIVES_IN]->(city:City) WHERE s.since = 2015 @@ -154,6 +162,7 @@ RETURN p,state ``` You can use `MATCH WHERE` clause with `CREATE` clause + ``` MATCH (a), (b) WHERE a.name = "Jacquie" AND b.name = "Michel" @@ -165,6 +174,7 @@ Update queries --- Update a specific property of a node + ``` MATCH (p:Person) WHERE p.name = "Théo Gauchoux" @@ -172,6 +182,7 @@ SET p.age = 23 ``` Replace all properties of a node + ``` MATCH (p:Person) WHERE p.name = "Théo Gauchoux" @@ -179,6 +190,7 @@ SET p = {name: "Michel", age: 23} ``` Add new property to a node + ``` MATCH (p:Person) WHERE p.name = "Théo Gauchoux" @@ -186,6 +198,7 @@ SET p + = {studies: "IT Engineering"} ``` Add a label to a node + ``` MATCH (p:Person) WHERE p.name = "Théo Gauchoux" @@ -197,6 +210,7 @@ Delete queries --- Delete a specific node (linked relationships must be deleted before) + ``` MATCH (p:Person)-[relationship]-() WHERE p.name = "Théo Gauchoux" @@ -204,14 +218,17 @@ DELETE relationship, p ``` Remove a property in a specific node + ``` MATCH (p:Person) WHERE p.name = "Théo Gauchoux" REMOVE p.age ``` + *Pay attention to the `REMOVE`keyword, it's not `DELETE` !* Remove a label from a specific node + ``` MATCH (p:Person) WHERE p.name = "Théo Gauchoux" @@ -219,11 +236,13 @@ DELETE p:Person ``` Delete entire database + ``` MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n, r ``` + *Seriously, it's the `rm -rf /` of Cypher !* diff --git a/d.html.markdown b/d.html.markdown index 93c08da2..e56661e7 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -128,7 +128,6 @@ class Matrix(uint m, uint n, T = int) { } auto mat = new Matrix!(3, 3); // We've defaulted type 'T' to 'int'. - ``` Speaking of classes, let's talk about properties for a second. A property diff --git a/dart.html.markdown b/dart.html.markdown index ab3c07d2..e6594fc5 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -710,7 +710,6 @@ main() { example30 // Adding this comment stops the dart formatter from putting all items on a new line ].forEach((ef) => ef()); } - ``` ## Further Reading diff --git a/de-de/asciidoc-de.html.markdown b/de-de/asciidoc-de.html.markdown index d0a62c66..c12c2479 100644 --- a/de-de/asciidoc-de.html.markdown +++ b/de-de/asciidoc-de.html.markdown @@ -87,7 +87,6 @@ Abteilungstitel ==== Level 3

    ===== Level 4

    - ``` Listen diff --git a/de-de/bc.html.markdown b/de-de/bc.html.markdown index 49a2878d..d2c6e9ae 100644 --- a/de-de/bc.html.markdown +++ b/de-de/bc.html.markdown @@ -96,6 +96,7 @@ print a[0], " ", a[1], " ", a[2], " ", a[3], "\n" quit /* Füge diese Codezeile hinzu, um sicherzustellen, dass das Programm beendet. Diese Codezeile ist optional.*/ ``` + Viel Spass mit diesem einfachen Rechner! (Oder dieser Programmiersprache, um exakt zu sein.) Das ganze Programm wurde in GNU bc geschrieben. Um es auszuführen, benutze ```bc learnbc.bc```. diff --git a/de-de/c++-de.html.markdown b/de-de/c++-de.html.markdown index cca54c30..6224d179 100644 --- a/de-de/c++-de.html.markdown +++ b/de-de/c++-de.html.markdown @@ -1148,9 +1148,8 @@ compl 4 // Führt bitweises nicht aus. 4 bitor 3 // Führt bitweises oder aus. 4 bitand 3 // Führt bitweises und aus. 4 xor 3 // Führt bitweises xor aus. - - ``` + Weiterführende Literatur: * Aktuelle Sprachen-Referenz [CPP Reference](http://cppreference.com/w/cpp). diff --git a/de-de/c-de.html.markdown b/de-de/c-de.html.markdown index 3a726b83..3eb1e4e6 100644 --- a/de-de/c-de.html.markdown +++ b/de-de/c-de.html.markdown @@ -844,6 +844,7 @@ Node create_linked_list(int *value, int length); #endif /* Ende der Präprozessordirektive */ ``` + ## Weiterführende Literatur Das Beste wird es sein, wenn man sich ein Exemplar des Buches diff --git a/de-de/crystal-de.html.markdown b/de-de/crystal-de.html.markdown index 535267ee..2c1dda72 100644 --- a/de-de/crystal-de.html.markdown +++ b/de-de/crystal-de.html.markdown @@ -10,7 +10,6 @@ lang: de-de --- ```crystal - # Das ist ein Kommentar # Alles ist ein Objekt diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index da706e91..02c7559f 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -144,7 +144,6 @@ selector { font-family: "Courier New", Trebuchet, Arial; /* wird die erste Schriftart nicht gefunden, wird die zweite benutzt, usw. */ } - ``` ## Benutzung @@ -164,7 +163,6 @@ empfohlen ist -->
    - ``` ## Spezifität @@ -190,7 +188,6 @@ p {} /*E*/ p { property: wert !important; } - ``` und das folgende Markup: diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 28ecc7ae..a4c8c372 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -128,7 +128,6 @@ class Matrix(uint m, uint n, T = int) { } auto mat = new Matrix!(3, 3); // Standardmäßig ist T vom Typ Integer - ``` Wo wir schon bei Klassen sind - Wie wäre es mit Properties! Eine Property @@ -248,5 +247,4 @@ void main() { ref = sqrt(i + 1.0); } } - ``` diff --git a/de-de/edn-de.html.markdown b/de-de/edn-de.html.markdown index 2434d1bd..2d194f3b 100644 --- a/de-de/edn-de.html.markdown +++ b/de-de/edn-de.html.markdown @@ -102,7 +102,6 @@ false (edn/read-string {:readers {'MyYelpClone/MenuItem map->menu-item}} "#MyYelpClone/MenuItem {:name \"eggs-benedict\" :rating 10}") ; -> #user.MenuItem{:name "eggs-benedict", :rating 10} - ``` # Referenzen diff --git a/de-de/elixir-de.html.markdown b/de-de/elixir-de.html.markdown index 4acb8e23..a91288c9 100644 --- a/de-de/elixir-de.html.markdown +++ b/de-de/elixir-de.html.markdown @@ -13,7 +13,6 @@ kompatibel mit Erlang, verfügt aber über eine freundlichere Syntax und bringt viele Features mit. ```ruby - # Einzeilige Kommentare werden mit der Raute gesetzt. # Es gibt keine mehrzeiligen Kommentare; @@ -412,7 +411,6 @@ pid <- {:circle, 2} # Die Shell selbst ist ein Prozess und mit dem Schlüsselwort 'self' kann man # die aktuelle pid herausfinden. self() #=> #PID<0.27.0> - ``` ## Referenzen und weitere Lektüre diff --git a/de-de/hack-de.html.markdown b/de-de/hack-de.html.markdown index 42428130..6e9b9da3 100644 --- a/de-de/hack-de.html.markdown +++ b/de-de/hack-de.html.markdown @@ -305,7 +305,6 @@ class Samuel $cat = new Samuel(); $cat instanceof KittenInterface === true; // True - ``` ## Weitere Informationen diff --git a/de-de/haml-de.html.markdown b/de-de/haml-de.html.markdown index 7272b365..9757ec2f 100644 --- a/de-de/haml-de.html.markdown +++ b/de-de/haml-de.html.markdown @@ -147,7 +147,6 @@ $ haml input_file.haml output_file.html :javascript console.log('Dies ist ein + + +``` + +### Een heel project optimaliseren met r.js + +Veel mensen geven er de voorkeur aan om AMD te gebruiken tijdens de + ontwikkelfase om code op een gezonde manier te organiseren maar + willen nog steeds een enkel scriptbestand gebruiken in productie in + plaats van honderderen XHR verzoeken uit te voeren als de pagina laadt. + +`require.js` wordt geleverd met een script genaamd `r.js` (die je waarschijnlijk +uitvoert in node.js, hoewel Rhino ook ondersteund wordt) welke de +dependency book van je project analyseert en een enkel bestand bouwt met daarin +al je module (juist genaamd), geminificeerd en klaar voor productie. + +Instaleren met `npm`: + +```shell +$ npm install requirejs -g +``` + +Nu kun je het een configuratiebestand voeden: + +```shell +$ r.js -o app.build.js +``` + +Voor ons bovenstaande voorbeeld zou de configuratie er zo uit kunnen zien: + +```javascript +/* file : app.build.js */ +({ + name : 'main', // naam van het beginpunt + out : 'main-built.js', // naam van het bestand waar de output naar geschreven wordt + baseUrl : 'app', + paths : { + // `empty:` verteld r.js dat dee nog steeds geladen moet worden van de CDN, + // gebruik makend van de locatie gespecificeert in `main.js` + jquery : 'empty:', + coolLibUitBower : '../bower_components/cool-lib/coollib' + } +}) +``` + +Verwissel simpelweg `data-main` om het gebouwde bestand te gebruiken in productie: + +```html + +``` + +Een erg gedetaileerd [overzicht van bouwopties](https://github.com/jrburke/r.js/blob/master/build/example.build.js) is +beschikbar in de GitHub repo (Engels). + +Hieronder vind je nog meer informatie over AMD (Engels). + +### Onderwerpen die niet aan bod zijn gekomen + +* [Loader plugins / transforms](http://requirejs.org/docs/plugins.html) +* [CommonJS style loading and exporting](http://requirejs.org/docs/commonjs.html) +* [Advanced configuration](http://requirejs.org/docs/api.html#config) +* [Shim configuration (loading non-AMD modules)](http://requirejs.org/docs/api.html#config-shim) +* [CSS loading and optimizing with require.js](http://requirejs.org/docs/optimization.html#onecss) +* [Using almond.js for builds](https://github.com/jrburke/almond) + +### Verder lezen: + +* [Official Spec](https://github.com/amdjs/amdjs-api/wiki/AMD) +* [Why AMD?](http://requirejs.org/docs/whyamd.html) +* [Universal Module Definition](https://github.com/umdjs/umd) + +### Implementaties: + +* [require.js](http://requirejs.org) +* [dojo toolkit](http://dojotoolkit.org/documentation/tutorials/1.9/modules/) +* [cujo.js](http://cujojs.com/) +* [curl.js](https://github.com/cujojs/curl) +* [lsjs](https://github.com/zazl/lsjs) +* [mmd](https://github.com/alexlawrence/mmd) From 4be8105b1f475842e77ca80bbe2de235b824c23a Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sun, 12 May 2024 05:55:20 -0600 Subject: [PATCH 160/392] [d/*] highlight as D --- d.html.markdown | 1 - de-de/d-de.html.markdown | 20 ++++++++++---------- fr-fr/d-fr.html.markdown | 40 ++++++++++++++++++++-------------------- hi-in/d.html.markdown | 12 ++++++------ ru-ru/d-ru.html.markdown | 2 +- 5 files changed, 37 insertions(+), 38 deletions(-) diff --git a/d.html.markdown b/d.html.markdown index e56661e7..5c850845 100644 --- a/d.html.markdown +++ b/d.html.markdown @@ -3,7 +3,6 @@ language: D filename: learnd.d contributors: - ["Nick Papanastasiou", "www.nickpapanastasiou.github.io"] - --- ```d diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 3250b625..65d2931b 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -39,7 +39,7 @@ void main() { } auto n = 1; // auto um den Typ vom Compiler bestimmen zu lassen - + // Zahlenliterale können _ verwenden für lesbarkeit while(n < 10_000) { n += n; @@ -82,7 +82,7 @@ struct LinkedList(T) { class BinTree(T) { T data = null; - + // Wenn es nur einen T Parameter gibt, können die Klammern um ihn weggelassen werden BinTree!T left; BinTree!T right; @@ -147,13 +147,13 @@ class MyClass(T, U) { class MyClass(T, U) { T _data; U _other; - + // Konstruktoren heißen immer `this` this(T t, U u) { data = t; other = u; } - + // getters @property T data() { return _data; @@ -163,8 +163,8 @@ class MyClass(T, U) { return _other; } - // setters - // @property kann genauso gut am ende der Methodensignatur stehen + // setters + // @property kann genauso gut am ende der Methodensignatur stehen void data(T t) @property { _data = t; } @@ -180,7 +180,7 @@ void main() { mc.data = 7; mc.other = "seven"; - + writeln(mc.data); writeln(mc.other); } @@ -208,10 +208,10 @@ import std.range : iota; // builds an end-exclusive range void main() { // Wir wollen die Summe aller Quadratzahlen zwischen // 1 und 100 ausgeben. Nichts leichter als das! - + // Einfach eine Lambda-Funktion als Template Parameter übergeben // Es ist genau so gut möglich eine normale Funktion hier zu übergeben - // Lambdas bieten sich hier aber an. + // Lambdas bieten sich hier aber an. auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) .reduce!((a, b) => a + b); @@ -225,7 +225,7 @@ um num zu berechnen? Das war möglich durch die Uniform Function Call Syntax. Mit UFCS können wir auswählen, ob wir eine Funktion als Methode oder als freie Funktion aufrufen. Walters artikel dazu findet ihr -[hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) +[hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) Kurzgesagt kann man Funktionen, deren erster Parameter vom typ A ist, als Methode auf A anwenden. diff --git a/fr-fr/d-fr.html.markdown b/fr-fr/d-fr.html.markdown index d0da8851..e593fdbd 100644 --- a/fr-fr/d-fr.html.markdown +++ b/fr-fr/d-fr.html.markdown @@ -8,7 +8,7 @@ translators: lang: fr-fr --- -```c +```d // Commençons par un classique module hello; @@ -30,7 +30,7 @@ D est activement développé par de nombreuses personnes très intelligents, gui [Andrei Alexandrescu](https://fr.wikipedia.org/wiki/Andrei_Alexandrescu). Après cette petite introduction, jetons un coup d'oeil à quelques exemples. -```c +```d import std.stdio; void main() { @@ -76,13 +76,13 @@ On peut définir de nouveaux types avec les mots-clés `struct`, `class`, `union` et `enum`. Ces types sont passés à la fonction par valeur (ils sont copiés) De plus, on peut utiliser les templates pour rendre toutes ces abstractions génériques. -```c +```d // Ici, 'T' est un paramètre de type. Il est similaire au de C++/C#/Java. struct LinkedList(T) { T data = null; - // Utilisez '!' pour instancier un type paramétré. - // Encore une fois semblable à '' + // Utilisez '!' pour instancier un type paramétré. + // Encore une fois semblable à '' LinkedList!(T)* next; } @@ -141,7 +141,7 @@ une méthode qui peut se comporter comme une lvalue. On peut donc utiliser la syntaxe des structures classiques (`struct.x = 7`) comme si il s'agissait de méthodes getter ou setter. -```c +```d // Considérons une classe paramétrée avec les types 'T' et 'U' class MyClass(T, U) { T _data; @@ -153,9 +153,9 @@ class MyClass(T, U) { T _data; U _other; - // Les constructeurs s'appellent toujours 'this'. + // Les constructeurs s'appellent toujours 'this'. this(T t, U u) { - // Ceci va appeller les setters ci-dessous. + // Ceci va appeller les setters ci-dessous. data = t; other = u; } @@ -183,18 +183,18 @@ class MyClass(T, U) { void main() { auto mc = new MyClass!(int, string)(7, "seven"); - // Importer le module 'stdio' de la bibliothèque standard permet - // d'écrire dans la console (les imports peuvent être locaux à une portée) + // Importer le module 'stdio' de la bibliothèque standard permet + // d'écrire dans la console (les imports peuvent être locaux à une portée) import std.stdio; - // On appelle les getters pour obtenir les valeurs. + // On appelle les getters pour obtenir les valeurs. writefln("Earlier: data = %d, str = %s", mc.data, mc.other); - // On appelle les setter pour assigner de nouvelles valeurs. + // On appelle les setter pour assigner de nouvelles valeurs. mc.data = 8; mc.other = "eight"; - // On appelle les setter pour obtenir les nouvelles valeurs. + // On appelle les setter pour obtenir les nouvelles valeurs. writefln("Later: data = %d, str = %s", mc.data, mc.other); } ``` @@ -214,17 +214,17 @@ de premier ordre, les fonctions `pures` et les données immuables. De plus, tout vos algorithmes fonctionels favoris (map, reduce, filter) sont disponibles dans le module `std.algorithm`. -```c +```d import std.algorithm : map, filter, reduce; import std.range : iota; // construit un intervalle excluant la dernière valeur. void main() { - // On veut un algorithme qui affiche la somme de la liste des carrés - // des entiers paires de 1 à 100. Un jeu d'enfant ! + // On veut un algorithme qui affiche la somme de la liste des carrés + // des entiers paires de 1 à 100. Un jeu d'enfant ! - // On se contente de passer des expressions lambda en paramètre à des templates. - // On peut fournir au template n'importe quelle fonction, mais dans notre - // cas, les lambdas sont pratiques. + // On se contente de passer des expressions lambda en paramètre à des templates. + // On peut fournir au template n'importe quelle fonction, mais dans notre + // cas, les lambdas sont pratiques. auto num = iota(1, 101).filter!(x => x % 2 == 0) .map!(y => y ^^ 2) .reduce!((a, b) => a + b); @@ -244,7 +244,7 @@ est de type A, comme si c'était une méthode de A. J'aime le parallélisme. Vous aimez le parallélisme ? Bien sûr que vous aimez ça. Voyons comment on le fait en D ! -```c +```d import std.stdio; import std.parallelism : parallel; import std.math : sqrt; diff --git a/hi-in/d.html.markdown b/hi-in/d.html.markdown index 8809c87e..b410b7fd 100644 --- a/hi-in/d.html.markdown +++ b/hi-in/d.html.markdown @@ -6,7 +6,7 @@ contributors: lang: hi-in --- -```c +```d //क्या आ रहा है पता है ... module hello; @@ -27,7 +27,7 @@ D सक्रिय रूप से सुपर स्मार्ट लो [आंद्रेई Alexandrescu](https://en.wikipedia.org/wiki/Andrei_Alexandrescu)। जिस तरह की है कि सभी के साथ बाहर, चलो कुछ उदाहरणों पर गौर करते हैं! -```c +```d import std.stdio; void main() { @@ -70,7 +70,7 @@ void main() { मूल्य से कार्य करने के लिए पारित कर रहे हैं (यानी नकल) और वर्गों के संदर्भ द्वारा पारित कर रहे हैं। इसके अलावा, हम प्रकारों और मानों दोनों पर करने के लिए टेम्पलेट का उपयोग कर सकते हैं! -```c +```d // इधर, 'T' एक प्रकार पैरामीटर है। लगता है कि '<+T>' C++ / C/ Java से। struct LinkedList(T) { T data = null; @@ -132,7 +132,7 @@ Classes की बात हो रही है , एक दूसरे के के शब्दों के साथ पॉड संरचनाओं की वाक्य रचना (`structure.x = 7`) है मनुष्य और सेटर तरीकों (`object.setX(7)`) ! -```c +```d // Consider a class parameterized on types 'T' & 'U'. class MyClass(T, U) { T _data; @@ -206,7 +206,7 @@ void main() { कार्यात्मक एल्गोरिदम ( नक्शा, फिल्टर , कम करने और मित्र हो सकते हैं) अद्भुत `std.algorithm` मॉड्यूल में पाया! -```c +```d import std.algorithm : map, filter, reduce; import std.range : iota; // builds an end-exclusive range @@ -234,7 +234,7 @@ UFCS के साथ, हम एक विधि के रूप में ए मैं समानता चाहते । समानता की तरह कोई और? ज़रूर तुम करना। चलो कुछ करते हैं! -```c +```d import std.stdio; import std.parallelism : parallel; import std.math : sqrt; diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 6896f67c..82a53b46 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -12,7 +12,7 @@ D - современный компилируемый язык общего на который сочетает удобство, продуманный дизайн и высокую производительность. D - это С++, сделанный правильно. -```c +```d // Welcome to D! Это однострочный комментарий /* многострочный From 652e6d9cb4b169fe0cd053e1447cbd9975932cbe Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sun, 12 May 2024 22:20:38 -0600 Subject: [PATCH 161/392] Remove .gitattributes (#4940) --- .gitattributes | 65 -------------------------------------------------- 1 file changed, 65 deletions(-) delete mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index da8c9d63..00000000 --- a/.gitattributes +++ /dev/null @@ -1,65 +0,0 @@ -asciidoc*.html.markdown linguist-language=AsciiDoc -angularjs*.html.markdown linguist-language=JavaScript -bash*.html.markdown linguist-language=bash -bf.html.markdown linguist-language=Brainfuck -bf-*.html.markdown linguist-language=Brainfuck -c-*.html.markdown linguist-language=C -c.html.markdown linguist-language=C -c++*.html.markdown linguist-language=C++ -chapel*.html.markdown linguist-language=Chapel -clojure*.html.markdown linguist-language=Clojure -cmake*.html.markdown linguist-language=CMake -coffeescript*.html.markdown linguist-language=CoffeeScript -coldfusion*.html.markdown linguist-language=ColdFusion -common-lisp*.html.markdown linguist-language=lisp -compojure*.html.markdown linguist-language=Clojure -csharp*.html.markdown linguist-language=C# -css*.html.markdown linguist-language=CSS -d.html.markdown linguist-language=D -d-*.html.markdown linguist-language=D -dart*.html.markdown linguist-language=Dart -edn*.html.markdown linguist-language=edn -elisp*.html.markdown linguist-language=elisp -elixir*.html.markdown linguist-language=Elixir -elm*.html.markdown linguist-language=Elm -erlang*.html.markdown linguist-language=Erlang -factor*.html.markdown linguist-language=Factor -forth*.html.markdown linguist-language=Forth -fortran*.html.markdown linguist-language=FORTRAN -fsharp*.html.markdown linguist-language=fsharp -go.html.markdown linguist-language=Go -go-*.html.markdown linguist-language=Go -groovy*.html.markdown linguist-language=Groovy -hack*.html.markdown linguist-language=Hack -haml*.html.markdown linguist-language=Haml -haskell*.html.markdown linguist-language=Haskell -haxe*.html.markdown linguist-language=Haxe -html*.html.markdown linguist-language=HTML -hy.html.markdown linguist-language=Hy -hy-*.html.markdown linguist-language=Hy -inform7*.html.markdown linguist-language=inform7 -java.html.markdown linguist-language=Java -java-*.html.markdown linguist-language=Java -javascript*.html.markdown linguist-language=JavaScript -jquery*.html.markdown linguist-language=JavaScript -json*.html.markdown linguist-language=JSON -julia*.html.markdown linguist-language=Julia -kotlin*.html.markdown linguist-language=Kotlin -latex*.html.markdown linguist-language=latex -less*.html.markdown linguist-language=Less -livescript*.html.markdown linguist-language=LiveScript -logtalk*.html.markdown linguist-language=Logtalk -lua*.html.markdown linguist-language=Lua -make*.html.markdown linguist-language=Makefile -markdown*.html.markdown linguist-language=Markdown -matlab*.html.markdown linguist-language=MATLAB -nim*.html.markdown linguist-language=Nimrod -nix*.html.markdown linguist-language=Nix -objective-c*.html.markdown linguist-language=Objective-C -ocaml*.html.markdown linguist-language=OCaml -paren*.html.markdown linguist-language=lisp -pcre*.html.markdown linguist-language=Perl -perl.html.markdown linguist-language=Perl -perl-*.html.markdown linguist-language=Perl -raku*.html.markdown linguist-language=Perl6 -ruby*.html.markdown linguist-language=Ruby From 519c9566fb4a14836ac7cd26820e10dc97925f10 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sun, 12 May 2024 22:33:54 -0600 Subject: [PATCH 162/392] Mark repo as Markdown --- .gitattributes | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .gitattributes diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..559d4c5f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.html.markdown linguist-language=Markdown linguist-detectable +file.html.erb linguist-vendored From 2c2e8650d9b7b3caba65fa9e3ca6bc55ea08c317 Mon Sep 17 00:00:00 2001 From: Antonio Ognio <30294002+aognio@users.noreply.github.com> Date: Mon, 13 May 2024 01:11:06 -0500 Subject: [PATCH 163/392] [gleam/en-us] Add initial version of Gleam (#4886) --- gleam.html.markdown | 888 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 888 insertions(+) create mode 100644 gleam.html.markdown diff --git a/gleam.html.markdown b/gleam.html.markdown new file mode 100644 index 00000000..df6cddfd --- /dev/null +++ b/gleam.html.markdown @@ -0,0 +1,888 @@ +--- +name: Gleam +category: language +language: Gleam +contributors: + - ["Antonio Ognio", "https://github.com/aognio/"] +filename: learngleam.gleam +--- + +Gleam is a new language for Erlang's BEAM virtual machine that relies on the +power of a robust type system, the expressiveness of functional programming, +and the highly concurrent fault-tolerant Erlang runtime using familiar and +modern syntax inspired by languages like OCaml, Rust and Elixir. + +Being a pretty modern development, Gleam comes with a compiler, a build tool, +a code formatter, several editor integrations, and package manager. + +Being part of the larger BEAM ecosystem, the programs created with Gleam can +also make use of thousands of published packages written in Erlang or Elixir. + +The design of the language is very concise so it feature no null values, +no exceptions, clear error messages, and a practical type system. + +JavaScript is additionally supported as a compile target, so you can run Gleam +code in browser or any other JS-enabled runtime. When using this feature, +TypeScript definitions get created, so you can interact with your Gleam code +confidently, even from the outside. + +```gleam +//// This comment with four slashes is a module-level. +//// This kind of comments are used to describe the whole module. + +import gleam/bool +import gleam/io +import gleam/int +import gleam/float +import gleam/list +import gleam/iterator +import gleam/option.{type Option, None, Some} +import gleam/result +import gleam/string +import gleam/string as text + +// A type's name always starts with a capital letter, contrasting to variables +// and functions, which start with a lowercase letter. + +// When the pub keyword is used the type alias is public and can be referred to +// by other modules. + +pub type UserId = + Int + +pub fn main() { + io.println("Hello from learnxinmyminutes.com!") + // io.println("This statement got commented out by a two slashes comment.!") + + // Modules are the units in which all Gleam code gets organized. + // In a module full will find a bunch of definitions of types, functions, etc. + // that seem to belong together. + // For example, the gleam/io module contains a variety of functions for + // printing, like println. + + // All gleam code is in some module or other, whose name comes from the name + // of the file it's in. + // For example, gleam/io is in a file called io.gleam in a directory called + // gleam. + + // Gleam has a robust static type system that helps you as you write and edit + // code, catching mistakes and showing you where to make changes. + // io.println(10) + // If you uncomment the previous line you'll get a compile time error reported + // as the io.println function only works with strings, not ints. + + // The compile will output an error that looks like this: + // error: Type mismatch + // ┌─ /home/contributor/learnxinmyminutes/src/learnxinmyminutes.gleam:21:14 + // │ + // 21 │ io.println(10) + // │ ^^ + // + // Expected type: + // + // String + // + // Found type: + // + // Int + + // Working with numbers + + // When running on the Erlang virtual machine ints have no maximum and minimum + // size. + // When running on JavaScript runtimes ints are represented using JavaScript's + // 64 bit floating point numbers. + + // Int arithmetic + io.debug(1 + 1) + io.debug(5 - 1) + io.debug(5 / 2) + io.debug(3 * 3) + io.debug(5 % 2) + + // Int comparisons + io.debug(2 > 1) + io.debug(2 < 1) + io.debug(2 >= 1) + io.debug(2 <= 1) + + // Equality works for any type and is checked structurally, meaning that two + // values are equal if they have the same structure rather than if they are at + // the same memory location. + io.debug(1 == 1) + // True + io.debug(2 != 2) + // False + + // Standard library int functions + io.debug(int.min(142, 137)) + // 137 + io.debug(int.clamp(-80, min: 0, max: 100)) + // 0 + io.debug(int.base_parse("10", 2)) + // Ok(2) + + // Binary, octal, and hex Int literals + io.debug(0b00001111) + io.debug(0o17) + io.debug(0xF) + + // Use underscores to enhance integer readibility + io.debug(1_000_000) + + // Gleam's numerical operators are not overloaded, so there are dedicated + // operators for working with floats. + + // Float arithmetic + io.debug(1.0 +. 1.5) + io.debug(5.0 -. 1.5) + io.debug(5.0 /. 2.5) + io.debug(3.0 *. 3.5) + + // Float comparisons + io.debug(2.2 >. 1.3) + io.debug(2.2 <. 1.3) + io.debug(2.2 >=. 1.3) + io.debug(2.2 <=. 1.3) + + // Floats are represented as 64 bit floating point numbers on both the Erlang + // and JavaScript runtimes. + // The floating point behaviour is native to their respective runtimes, so + // their exact behaviour will be slightly different on the two runtimes. + + // Under the JavaScript runtime, exceeding the maximum (or minimum) + // representable value for a floating point value will result in Infinity + // (or -Infinity). Should you try to divide two infinities you will get NaN + // as a result. + + // When running on the BEAM any overflow will raise an error. So there is no + // NaN or Infinity float value in the Erlang runtime. + + // Division by zero is not an error + io.debug(3.14 /. 0.0) + // 0.0 + + // Standard library float functions + io.debug(float.max(2.0, 9.5)) + // 9.5 + io.debug(float.ceiling(5.4)) + // 6.0 + + // Underscores for floats are also supported + io.debug(10_000.01) + + // Division by zero will not overflow, but is instead defined to be zero. + + // Working with strings + io.debug("⭐ Gleam ⭐ - 별") + io.debug( + "this + is + a + multi + line + string", + ) + io.debug("\u{1F600}") + // Outputs a smiley 😀 + + // Double quote can be escaped + io.println("\"X\" marks the spot") + + // String concatenation + io.debug("One " <> "Two") + + // String functions + io.debug(text.reverse("1 2 3 4 5")) + io.debug(text.append("abc", "def")) + + io.println(text.reverse("!desrever tog gnirts sihT")) + // Outputs "This string got reversed!" + + // Several escape sequences are supported: + + // \" - double quote + // \\ - backslash + // \f - form feed + // \n - newline + // \r - carriage return + // \t - tab + + // Bool operators + // The || and && operators work by short-circuiting + + io.debug(True && False) + // False + + io.debug(True && True) + // True + + io.debug(False || False) + // False + + io.debug(False || True) + // True + + // Bool functions + io.debug(bool.to_string(True)) + // "True" + + io.debug(bool.to_int(False)) + // 0 + + // Assignments + let x = "Original value" + io.debug(x) + + // Assign `y` to the value of `x` + let y = x + io.debug(y) + + // Assign `x` to a new value + let x = "New value" + io.debug(x) + + // The `y` still refers to the original value + io.debug(y) + + // In Gleam variable and function names are written in snake_case. + let answer_to_the_universe = 42 + io.debug(answer_to_the_universe) + + let and_everything = answer_to_the_universe + // Now using a variable produces a warning + + // warning: Unused variable + // ┌─ /home/contributor/learnxinmyminutes/src/learnxinmyminutes.gleam:199:7 + // │ + // 199 │ let and_everything = answer_to_the_universe + // │ ^^^^^^^^^^^^^^ This variable is never used + // Hint: You can ignore it with an underscore: `_and_everything`. + + // Type annotations + + let _name: String = "Gleam" + + let _is_cool: Bool = True + + let _version: Int = 1 + // Useful for documentation purposes but they do not change how the compiler + // type checks the code beyond making sure the annotation matches the type, + // otherwise you get an error. + + // let _has_wrong_type_annotation: Int = True + + // error: Type mismatch + // ┌─ /home/contributor/learnxinmyminutes/src/learnxinmyminutes.gleam:219:41 + // │ + // 219 │ let _has_wrong_type_annotation: Int = True + // │ ^^^^ + // + // Expected type: + // + // Int + // + // Found type: + // + // Bool + + // Type aliases + let one: UserId = 1 + // Refer to the beginning of the file for the definition of the UserId type + + let two: Int = 2 + + // Aliases are just for creating more readable code and more precise + // documentation. + // Under the hood they are still values of the same type so operations + // still work + io.debug(one + two) + // 3 + + // Blocks: scoping and value + let radius = { + let value = 100.0 + value + } + // io.debug(value) // <- This will not compile because "value" is out of scope + + let area = 3.14159 *. radius *. radius + io.debug(area) + + // Use blocks to group operations instead of parenthesis + let n1 = { 3 + 2 } * 5 + let n2 = 3 + { 2 * 5 } + io.debug(n1 != n2) + // True + + // Lists + + // Nephews of Scrooge McDuck + let nephews = ["Huey", "Dewey", "Louie"] + io.debug(nephews) + // ["Huey", "Dewey", "Louie"] + + // Immutably prepend so the original list is not changed + io.debug(["Donald", ..nephews]) + // ["Donald", "Huey", "Dewey", "Louie"] + + // Some standard library functions for lists + + list.each(nephews, io.println) + // Huey + // Dewey + // Louie + + io.debug(list.drop(nephews, 2)) + // ["Louie"] + + more_examples() + more_function_examples() + generic_typing_examples() + beloved_pipelines_demo() + labels_in_function_calls() + showcase_flow_control() + more_on_recursion() + more_on_pattern_matching() + showcase_types() + more_on_types() + more_on_callbacks() + showcase_externals() + showcase_panic() +} + +// The fn keyword is used to define new functions. +fn multiply(a: Int, b: Int) -> Int { + // No explicit return + // The last expression gets returned + a * b +} + +// The double and multiply functions are defined without the pub keyword. +// This makes them private functions, they can only be used within this module. +// If another module attempted to use them it would result in a compiler error. +fn double(a: Int) -> Int { + multiply(a, 2) +} + +// Only public functions are exported and can be called from outside the module. + +// Type annotations are optional for function arguments and return values +// but are considered good practice for clarity and in order to encourage +// intentional and thoughtful design. + +pub fn is_leap_year(year: Int) -> Bool { + { year % 4 == 0 } && { { year % 100 != 0 } || { year % 400 == 0 } } +} + +fn more_examples() { + // Debug also returns a value so its output is the return value of + // this function + io.debug(double(10)) + // 20 + io.debug(is_leap_year(2000)) + // True +} + +// Gleam supports higher order functions: +// They can be assigned to variables, passed as arguments to other functions +// or even be returned as values from blocks or other functions +fn call_func_on_int(func: fn(Int) -> Int, value: Int) -> Int { + func(value) +} + +fn more_function_examples() -> Int { + io.debug(call_func_on_int(double, 2)) + // 4 + + let square = fn(x: Int) -> Int { x * x } + io.debug(square(3)) + // 9 + + // Calling an anonymous function inmediately after defining it + io.debug(fn(x: Int) { x + 1 }(1)) + + // Closure example + let make_adder = fn(n: Int) -> fn(Int) -> Int { + fn(argument: Int) -> Int { argument + n } + } + + let adder_of_fives = make_adder(5) + io.debug(adder_of_fives(10)) + // 15 + + // Anonymous functions can be used interchangeably with named functions. + io.debug(call_func_on_int(fn(x: Int) -> Int { x + 100 }, 900)) + // 1000 + + // Let's create a function decorator + let twice = fn(wrapped_func: fn(Int) -> Int) -> fn(Int) -> Int { + fn(argument: Int) -> Int { wrapped_func(wrapped_func(argument)) } + } + let quadruple = twice(double) + io.debug(quadruple(1)) + + let quadruple_2 = fn(a: Int) -> Int { multiply(4, a) } + io.debug(quadruple_2(2)) + // 8 + + // A function capture is a shorthand syntax for creating anonymous functions + // that take one argument and immediately call another function with that + // argument + let quadruple_3 = multiply(4, _) + io.debug(quadruple_3(4)) + // 16 +} + +// Generic functions are supported using type variables. +fn generic_twice(func: fn(value) -> value, argument: value) -> value { + func(func(argument)) +} + +// In generic_twice value was the type variable. +// In generic_twice_decorator the_type is the type variable. +// As in any other variable you get to choose the name. +fn generic_twice_decorator( + func: fn(the_type) -> the_type, +) -> fn(the_type) -> the_type { + fn(argument: the_type) -> the_type { func(func(argument)) } +} + +fn generic_typing_examples() { + let double_integers = fn(a: Int) -> Int { a * 2 } + let double_floats = fn(a: Float) -> Float { a *. 2.0 } + io.debug(generic_twice(double_integers, 3)) + io.debug(generic_twice(double_floats, 3.0)) + + let quadruple_integers = generic_twice_decorator(double_integers) + let quadruple_floats = generic_twice_decorator(double_floats) + io.debug(quadruple_integers(1)) + // 4 + io.debug(quadruple_floats(1.0)) + // 4.0 +} + +// Gleam's pipe operator |> takes the result of the expression on its left +// and passes it as an argument to the function on its right. +fn beloved_pipelines_demo() { + // Let's be honest: you want to use Gleam just for this cool operator, right? + ["hello", "world"] + |> list.intersperse(" ") + |> list.append(["!"]) + |> string.concat + |> string.capitalise + |> io.debug + + // Match cleaner than this right? + io.debug( + string.capitalise( + string.concat( + list.append(list.intersperse(["hello", "world"], " "), ["!"]), + ), + ), + ) + + // Solution to the first problem of Project Euler: + // URL: https://projecteuler.net/problem=1 + // Description: Find the sum of all the multiples of 3 and 5 below 1000. + iterator.iterate(1, fn(n) { n + 1 }) + |> iterator.take(1000 - 1) + |> iterator.filter(fn(n) { { n % 3 == 0 } || { n % 5 == 0 } }) + |> iterator.fold(from: 0, with: fn(acc, element) { element + acc }) + |> int.to_string + |> fn(sum_as_text: String) { + "Solution to Project Euler's problem #1: " <> sum_as_text + } + |> io.debug + // Solution to Project Euler's problem #1: 233168 +} + +// Labels can be added before each argument +fn call_func_on_int_with_labels( + func passed_func: fn(Int) -> Int, + value n: Int, +) -> Int { + passed_func(n) +} + +// The label and the argument can have the same name +fn add_one(number number: Int) -> Int { + number + 1 +} + +fn add_two_integers(first n: Int, second m: Int) -> Int { + n + m +} + +fn labels_in_function_calls() -> Int { + // Since we are labelling the arguments we can switch the order + // if we want to + io.debug(call_func_on_int_with_labels(value: 8, func: double)) + io.debug(add_one(number: 1)) + // 2 + io.debug(string.contains(does: "theme", contain: "the")) + // True + // Unlabeled arguments must go first + io.debug(add_two_integers(2, second: 2)) + // 4 +} + +fn showcase_flow_control() { + // Use case if you want to use pattern-matching in order to + // select which code to execute. + // Gleam will make sure all possible values are covered + // by performing exhaustiveness checks. + // Otherwise you get compilation errors. + let puppies = ["Bear", "Frisco", "Ranger"] + let count = list.length(of: puppies) + { + "We have " + <> int.to_string(count) + <> " " + <> // The underscore matches with any other value + case count { + 1 -> "puppy" + _ -> "puppies" + } + } + |> io.debug + + // Gleam allows patterns in case expressions to also assign variables. + { + "Puppy count: " + <> case list.length(puppies) { + 0 -> "None." + 1 -> "Just one." + other -> "As many as " <> int.to_string(other) <> " puppies." + } + } + |> io.debug + + // Consider BEAM languages are functional in design and Gleam is no exception + // so there are no if, for or while constructs available. + + // Use pattern-matching for conditionals + let answer = 42 + case answer == 42 { + True -> { + io.debug("This is the answer to the universe.") + } + False -> { + io.debug("This is the answer to something else.") + } + } + + // Use recursion instead of looping + from_one_to_ten(1) +} + +// Recursive function +fn from_one_to_ten(n: Int) { + io.debug(n) + case n { + 10 -> Nil + _ -> from_one_to_ten(n + 1) + } +} + +// In order to avoid memory exhaustion due to creating excesive +// stack frames when calling functions recursively, Gleam supports +// "tail call optimisation" which means that the compiler can reuse +// the stack frame for the current function if a function call is +// the last thing the function does. + +pub fn fib(x: Int) -> Int { + // The public function calls the private tail recursive function + fib_loop(x, 1) +} + +fn fib_loop(x: Int, accumulator: Int) -> Int { + case x { + 1 -> accumulator + + // The last thing this function does is call itself + // In the previous lesson the last thing it did was multiply two ints + _ -> fib_loop(x - 1, accumulator + x) + } +} + +// Gleam supports pattern-matching the first element and the remainder +// of a list with the [x, ..y] pattern inside a case expression. +fn reverse_list(the_list: List(value)) -> List(value) { + case the_list { + [head, ..tail] -> list.concat([reverse_list(tail), [head]]) + [] -> [] + } +} + +fn more_on_recursion() { + io.debug(fib(10)) + // 55 + io.debug(reverse_list([1, 2, 3])) +} + +fn more_on_pattern_matching() { + // When pattern-matching on strings the <> operator match on strings + // with a specific prefix and assigns the reminder to a variable + io.debug(case "Hello, Lucy" { + "Hello, " <> name -> "Grettings for " <> name + _ -> "Potentially no greetings" + }) + + // Alternative patters are supported so the same clause is used + // for multiple values + let month = 2 + let year = 2024 + let number_of_days = case month { + 2 -> + case is_leap_year(year) { + False -> 28 + True -> 29 + } + 4 | 6 | 9 | 11 -> 30 + 1 | 3 | 5 | 7 | 8 | 10 | 12 -> 31 + _ -> 0 + } + io.debug("Number of days: " <> int.to_string(number_of_days)) + // 29 + + // Guards in pattern-matching: + // When using the if keyword an expression must evaluate to True + // for the pattern to match. + let list_starts_with = fn(the_list: List(value), the_value: value) -> Bool { + case the_list { + [head, ..] if head == the_value -> True + _ -> False + } + } + io.debug(list_starts_with([10, 20, 30], 10)) + // True +} + +pub type Gender { + Male + Female + Other +} + +// Records: +// - Support variants +// - Each variant is similar to a struct with fields +pub type Shape { + Rectangle(base: Float, height: Float) + Triangle(base: Float, height: Float) +} + +// Records with one variant resemble structs +pub type Point { + Point(x: Float, y: Float) +} + +fn showcase_types() { + // Tuples: + // - Can mix together elements of different types + // - Their type is implicit e.g. #{1, "Hello"} is of type #{Int, String} + // - Their elements can be accessed by numeric indexes + let tuple_01 = #(1, "Ferris", "rustacean", True) + let tuple_02 = #(1, "Lucy", "starfish", True) + io.debug(tuple_01) + io.debug(tuple_01.0) + // 1 + io.debug(tuple_02.1) + // Lucy + let #(_, name, species, _) = tuple_01 + io.debug(name <> " the " <> species) + + // Pattern-matching with tuples including variable assignment + case tuple_02 { + #(_, name, _, True) -> io.debug(name <> " is a mascot.") + #(_, name, _, False) -> io.debug(name <> " is not a mascot.") + } + + // Using a custom type with pattern-matching + let gender = Other + io.debug(case gender { + Male -> "Boy" + Female -> "Girl" + _ -> "Undetermined" + }) + + // Using records + let rectangle_1 = Rectangle(base: 10.0, height: 20.0) + io.debug(rectangle_1.height) + // 10.3 + + let point_1 = Point(x: 3.2, y: 4.3) + io.debug(point_1) + + // Updating a record + let point_2 = Point(..point_1, y: 5.7) + io.debug(point_2) + + // In Gleam, values ar not nullable. + // Nil is the only value of its type. + let some_var = Nil + let result = io.println("Hello!") + io.debug(some_var == result) + // True +} + +pub type Mineral { + Gold + Silver + Copper +} + +// Generic custom types with contained types as parameters +pub type Purity(inner_type) { + Pure(inner_type) + Impure(inner_type) +} + +pub type Beverage { + Water + Juice +} + +// Existing custom types from the gleam/option and gleam/result modules +// facilitate working with nullable values and handling potential errors +pub type Person { + Person(name: String, nickname: Option(String)) +} + +pub type DiceError { + DiceValueOutOfRange +} + +fn checked_dice_value(value: Int) -> Result(Int, DiceError) { + case value { + 1 | 2 | 3 | 4 | 5 | 6 -> Ok(value) + _ -> Error(DiceValueOutOfRange) + } +} + +fn double_dice_value(value: Int) -> Result(Int, DiceError) { + case value { + 1 | 2 | 3 -> Ok(value * 2) + _ -> Error(DiceValueOutOfRange) + } +} + +fn more_on_types() { + let mineral_sample_01: Purity(Mineral) = Pure(Gold) + let mineral_sample_02 = Impure(Silver) + io.debug(mineral_sample_01) + io.debug(mineral_sample_02) + + // A glass can be empty or not + let glass_01: Option(Beverage) = Some(Water) + let glass_02 = None + io.debug(glass_01) + io.debug(glass_02) + + // A person can have a nickname or not + let person_01 = Person(name: "John", nickname: Some("The Ripper")) + let person_02 = Person(name: "Martin", nickname: None) + io.debug(person_01) + io.debug(person_02) + + // Working with functions that return values of type Result + let dice_01 = 5 + case checked_dice_value(dice_01) { + Ok(checked_value) -> + io.debug("The value of " <> int.to_string(checked_value) <> " is OK.") + Error(DiceValueOutOfRange) -> + io.debug("The value of the dice is out of range") + } + + // Let's attempt to double the value if the resulting value is still + // a number in any of the sides of the dice. + // Otherwise, let's put the max value. + 2 + |> checked_dice_value + |> result.try(double_dice_value) + |> result.unwrap(or: 6) + |> io.debug +} + +pub fn throw_dice_as_result() { + Ok(int.random(6) + 1) +} + +pub fn sum_dice_values(a: Int, b: Int) { + Ok(a + b) +} + +// Betting on first-class functions and pattern-matching +// can easily lead to tons of indentation +fn roll_two_dices_without_use() { + result.try(throw_dice_as_result(), fn(first_dice) { + result.try(throw_dice_as_result(), fn(second_dice) { + result.map(sum_dice_values(first_dice, second_dice), fn(sum) { sum }) + }) + }) +} + +// The use expression still let us write code that uses callbacks +// but cleans up excessive indentation: +// - A call to higher order function go the right side of the <- operator +// - The argument names for the callback function go on the left hand side of +// the <- operator +// - All the remaining code in the enclosing {} block becomes the body of the +// callback function. +fn roll_two_dices_with_use() { + use first_dice <- result.try(throw_dice_as_result()) + use second_dice <- result.try(throw_dice_as_result()) + use sum <- result.map(sum_dice_values(first_dice, second_dice)) + // this is the remaing code in innermost callback function + sum +} + +fn more_on_callbacks() { + io.debug(roll_two_dices_without_use()) + io.debug(roll_two_dices_with_use()) +} + +pub type DateTime + +// External functions must annotate a return type +@external(erlang, "calendar", "local_time") +pub fn now() -> DateTime + +fn showcase_externals() { + io.debug(now()) + // #(#(2024, 4, 6), #(14, 4, 16)) +} + +fn showcase_panic() { + // We can deliberately abort execution by using the panic keyword + // in order to make our program crash immediately + case 3 == 2 { + True -> panic as "The equality operator is broken!" + False -> "Equality operator works for integers" + } + // Calling a function that uses the todo keyword also crashes + // homework() +} + +pub fn homework() { + todo +} +``` + +## Further reading + +* [Gleam's official website](https://gleam.run/) +* [Language tour](https://tour.gleam.run/) - Includes live code editor +* [Official documentation](https://gleam.run/documentation/) +* [Gleam's awesome list](https://github.com/gleam-lang/awesome-gleam) +* [Exercism track for Gleam](https://exercism.org/tracks/gleam) + +There official docs have cheatsheets for people familiar with: + +* [Elixir](https://gleam.run/cheatsheets/gleam-for-elixir-users) +* [Elm](https://gleam.run/cheatsheets/gleam-for-elm-users) +* [Erlang](https://gleam.run/cheatsheets/gleam-for-erlang-users) +* [PHP](https://gleam.run/cheatsheets/gleam-for-php-users) +* [Python](https://gleam.run/cheatsheets/gleam-for-python-users) +* [Rust](https://gleam.run/cheatsheets/gleam-for-python-users) From 7b4a50ac46346fb794c25ca9b4097ad7d39822b6 Mon Sep 17 00:00:00 2001 From: Balagopal Komarath Date: Mon, 13 May 2024 11:44:59 +0530 Subject: [PATCH 164/392] [lean4/en] Documentation for Lean 4 (#4893) --- lean4.html.markdown | 519 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 519 insertions(+) create mode 100644 lean4.html.markdown diff --git a/lean4.html.markdown b/lean4.html.markdown new file mode 100644 index 00000000..4d427cec --- /dev/null +++ b/lean4.html.markdown @@ -0,0 +1,519 @@ +--- +language: "Lean 4" +filename: learnlean4.lean +contributors: + - ["Balagopal Komarath", "https://bkomarath.rbgo.in/"] + - ["Ferinko", "https://github.com/Ferinko"] +--- + +[Lean 4](https://lean-lang.org/) is a dependently typed functional programming +language and an interactive theorem prover. + +```lean4 +/- +An enumerated data type. +-/ +inductive Grade where + | A : Grade + | B : Grade + | F : Grade +deriving Repr + +/- +Functions. +-/ +def grade (m : Nat) : Grade := + if 80 <= m then Grade.A + else if 60 <= m then Grade.B + else Grade.F + +def highMarks := 80 + 9 +def lowMarks := 25 + 25 +#eval grade highMarks +#eval grade lowMarks + +#check (0 : Nat) +/- #check (0 : Grade) -/ /- This is an error. -/ + +/- +Types themselves are values. +-/ +#check (Nat : Type) + +/- +Mathematical propositions are values in Lean. `Prop` is the type of +propositions. + +Here are some simple propositions. +-/ + +#check 0 = 1 +#check 1 = 1 +#check 2^9 - 2^8 = 2^8 + +/- +Notice Lean displays `0 = 1 : Prop` to say: + + The statement "0 = 1" is a proposition. + +We want to distinguish true propositions and false propositions. We do this via +proofs. + +Each proposition is a type. `0 = 1` is a type, `1 = 1` is another type. + +A proposition is true iff there is a value of that type. + +How do we construct a value of type `1 = 1`? We use a constructor that is +defined for that type. + + `Eq.refl a` constructs a value of type `a = a`. (reflexivity) + +Using this we can prove `1 = 1` as follows. +-/ + +theorem one_eq_one : 1 = 1 := Eq.refl 1 + +/- +But there is no way to prove (construct a value of type) `0 = 1`. + +The following will fail. As will `Eq.refl 1` +-/ + +/- theorem zero_eq_one : 0 = 1 := Eq.refl 0 -/ + +/- +Let us prove an inequality involving variables. + +The `calc` primitive allows us to prove equalities using stepwise +calculations. Each step has to be justified by a proof. +-/ +theorem plus_squared (a b : Nat) : (a+b)^2 = a^2 + 2*a*b + b^2 := + calc + (a+b)^2 = (a+b)*(a+b) := Nat.pow_two _ + _ = (a+b)*a + (a+b)*b := Nat.mul_add _ _ _ + _ = a*a + b*a + (a*b + b*b) := by repeat rw [Nat.add_mul] + _ = a*a + b*a + a*b + b*b := by rw [← Nat.add_assoc] + _ = a*a + a*b + a*b + b*b := by rw [Nat.mul_comm b _] + _ = a^2 + a*b + a*b + b*b := by rw [← Nat.pow_two _] + _ = a^2 + a*b + a*b + b^2 := by rw [← Nat.pow_two _] + _ = a^2 + (a*b + a*b) + b^2 := by rw [Nat.add_assoc (a^_)] + _ = a^2 + 2*(a*b) + b^2 := by rw [← Nat.two_mul _] + _ = a^2 + 2*a*b + b^2 := by rw [Nat.mul_assoc _ _ _] +/- +Underscores can be used when there is no ambiguity in what is to be matched. + +For example, in the first step, we want to apply `Nat.pow_two (a+b)`. But, +`(a+b)` is the only pattern here to apply `Nat.pow_two`. So we can omit it. +-/ + +/- +Let us now prove more "realistic" theorems. Those involving logical connectives. + +First, we define even and odd numbers. +-/ +def Even (n : Nat) := ∃ k, n = 2*k +def Odd (n : Nat) := ∃ k, n = 2*k + 1 + +/- +To prove an existential, we can provide specific values if we know them. +-/ +theorem zero_even : Even 0 := + have h : 0 = 2 * 0 := Eq.symm (Nat.mul_zero 2) + Exists.intro 0 h +/- +`Exists.intro v h` proves `∃ x, p x` by substituting `x` by `v` and using the +proof `h` for `p v`. +-/ + +/- +Now, we will see how to use hypothesis that are existentials to prove +conclusions that are existentials. + +The curly braces around parameters `n` and `m` indicate that they are +implicit. Here, Lean will infer them from `hn` and `hm`. +-/ +theorem even_mul_even_is_even' {n m : Nat} (hn : Even n) (hm : Even m) : Even (n*m) := + Exists.elim hn (fun k1 hk1 => + Exists.elim hm (fun k2 hk2 => + Exists.intro (k1 * ( 2 * k2)) ( + calc + n*m = (2 * k1) * (2 * k2) := by rw [hk1, hk2] + _ = 2 * (k1 * (2 * k2)) := by rw [Nat.mul_assoc] + ) + ) + ) + +/- +Most proofs are written using *tactics*. These are commands to Lean that guide +it to construct proofs by itself. + +The same theorem, proved using tactics. +-/ +theorem even_mul_even_is_even {n m : Nat} (hn : Even n) (hm : Even m) : Even (n*m) := by + have ⟨k1, hk1⟩ := hn + have ⟨k2, hk2⟩ := hm + apply Exists.intro $ k1 * (2 * k2) + calc + n*m = (2 * k1) * (2 * k2) := by rw [hk1, hk2] + _ = 2 * (k1 * (2 * k2)) := by rw [Nat.mul_assoc] + +/- +Let us work with implications. +-/ +theorem succ_of_even_is_odd' {n : Nat} : Even n → Odd (n+1) := + fun hn => + have ⟨k, hk⟩ := hn + Exists.intro k ( + calc + n + 1 = 2 * k + 1 := by rw [hk] + ) +/- +To prove an implication `p → q`, you have to write a function that takes a proof +of `p` and construct a proof of `q`. + +Here, `pn` is proof of `Even n := ∃ k, n = 2 *k`. Eliminating the existential +gets us `k` and a proof `hk` of `n = 2 * k`. + +Now, we have to introduce the existential `∃ k, n + 1 = 2 * k + 1`. This `k` is +the same as `k` for `n`. And, the equation is proved by a simple calculation +that substitutes `2 * k` for `n`, which is allowed by `hk`. +-/ + +/- +Same theorem, now using tactics. +-/ +theorem succ_of_even_is_odd {n : Nat} : Even n → Odd (n+1) := by + intro hn + have ⟨k, hk⟩ := hn + apply Exists.intro k + rw [hk] + +/- +The following theorem can be proved similarly. + +We will use this theorem later. + +A `sorry` proves any theorem. It should not be used in real proofs. +-/ +theorem succ_of_odd_is_even {n : Nat} : Odd n → Even (n+1) := sorry + +/- +We can use theorems by applying them. +-/ +example : Odd 1 := by + apply succ_of_even_is_odd + exact zero_even +/- +The two new tactics are: + + - `apply p` where `p` is an implication `q → r` and `r` is the goal rewrites + the goal to `q`. More generally, `apply t` will unify the current goal with + the conclusion of `t` and generate goals for each hypothesis of `t`. + - `exact h` solves the goal by stating that the goal is the same as `h`. +-/ + +/- +Let us see examples of disjunctions. +-/ +example : Even 0 ∨ Odd 0 := Or.inl zero_even +example : Even 0 ∨ Odd 1 := Or.inl zero_even +example : Odd 1 ∨ Even 0 := Or.inr zero_even +/- +Here, we always know from `p ∨ q` which of `p` and/or `q` is correct. So we can +introduce a proof of the correct side. +-/ + +/- +Let us see a more "standard" disjunction. + +Here, from the hypothesis that `n : Nat`, we cannot determine whether `n` is +even or odd. So we cannot construct `Or` directly. + +But, for any specific `n`, we will know which one to construct. + +This is exactly what induction allows us to do. We introduce the `induction` +tactic. + +The inductive hypothesis is a disjunction. When disjunctions appear at the +hypothesis, we use *proof by exhaustive cases*. This is done using the `cases` +tactic. +-/ +theorem even_or_odd {n : Nat} : Even n ∨ Odd n := by + induction n + case zero => left ; exact zero_even + case succ n ihn => + cases ihn with + | inl h => right ; apply (succ_of_even_is_odd h) + | inr h => left ; apply (succ_of_odd_is_even h) +/- +`induction` is not just for natural numbers. It is for any type, since all types +in Lean are inductive. +-/ + +/- +We now state Collatz conjecture. The proof is left as an exercise to the reader. +-/ +def collatz_next (n : Nat) : Nat := + if n % 2 = 0 then n / 2 else 3 * n + 1 + +def iter (k : Nat) (f: Nat → Nat) := + match k with + | Nat.zero => fun x => x + | Nat.succ k' => fun x => f (iter k' f x) + +theorem collatz : ∀ n, n > 0 → ∃ k, iter k collatz_next n = 1 := sorry + +/- +Now, some "corner cases" in logic. +-/ + +/- +The proposition `True` is something that can be trivially proved. + +`True.intro` is a constructor for proving `True`. Notice that it needs no +inputs. +-/ +theorem obvious : True := True.intro + +/- +On the other hand, there is no constructor for `False`. + +We have to use `sorry`. +-/ +theorem impossible : False := sorry + +/- +Any `False` in the hypothesis allows us to conclude anything. + +Written in term style, we use the eliminator `False.elim`. It takes a proof of +`False`, here `h`, and concludes whatever is the goal. +-/ +theorem nonsense (h : False) : 0 = 1 := False.elim h + +/- +The `contradiction` tactic uses any `False` in the hypothesis to conclude the +goal. +-/ +theorem more_nonsense (h : False) : 1 = 2 := by contradiction + +/- +To illustrate constructive vs classical logic, we now prove the contrapositive +theorem. + +The forward direction does not require classical logic. +-/ +theorem contrapositive_forward' (p q : Prop) : (p → q) → (¬q → ¬p) := + fun pq => fun hqf => fun hp => hqf (pq hp) +/- +Use the definition `¬q := q → False`. Notice that we have to construct `p → +False` given `p → q` and `q → False`. This is just function composition. +-/ + +/- +The above proof, using tactics. +-/ +theorem contrapositive_forward (p q : Prop) : (p → q) → (¬q → ¬p) := by + intro hpq + intro + intro hp + specialize hpq hp + contradiction + +/- +The reverse requires classical logic. + +Here, we are required to construct a `q` given values of following types: + + - `(q → False) → (p → False)`. + - `p`. + +This is impossible without using the law of excluded middle. +-/ +theorem contrapositive_reverse' (p q : Prop) : (¬q → ¬p) → (p → q) := + fun hnqnp => + Classical.byCases + (fun hq => fun _ => hq) + (fun hnq => fun hp => absurd hp (hnqnp hnq)) +/- +Law of excluded middle tells us that we will have a `q` or a `q → False`. In the +first case, it is trivial to construct a `q`, we already have it. In the second +case, we give the `q → False` to obtain a `p → False`. Then, we use the fact +(in constructive logic) that given `p` and `p → False`, we can construct +`False`. Once, we have `False`, we can construct anything, and specifically `q`. +-/ + +/- +Same proof, using tactics. +-/ +theorem contrapositive_reverse (p q : Prop) : (¬q → ¬p) → (p → q) := by + intro hnqnp + intro hp + have emq := Classical.em q + cases emq + case inl _ => assumption + case inr h => specialize hnqnp h ; contradiction + +/- +To illustrate how we can define an work with axiomatic systems. Here is a +definition of Groups and some proofs directly translated from "Topics in +Algebra" by Herstein, Second edition. +-/ + +/- +A `section` introduces a namespace. +-/ +section GroupTheory +/- +To define abstract objects like groups, we may use `class`. +-/ +class Group (G : Type u) where + op : G → G → G + assoc : ∀ a b c : G, op (op a b) c = op a (op b c) + e : G + identity: ∀ a : G, op a e = a ∧ op e a = a + inverse: ∀ a : G, ∃ b : G, op a b = e ∧ op b a = e + +/- +Let us introduce some notation to make this convenient. +-/ +open Group +infixl:70 " * " => op + +/- +`G` will always stand for a group and variables `a b c` will be elements of that +group in this `section`. +-/ +variable [Group G] {a b c : G} + +def is_identity (e' : G) := ∀ a : G, (a * e' = a ∧ e' * a = a) + +/- +We prove that the identity element is unique. +-/ +theorem identity_element_unique : ∀ e' : G, is_identity e' → e' = e := by + intro e' + intro h + specialize h e + have ⟨h1, _⟩ := h + have h' := identity e' + have ⟨_, h2⟩ := h' + exact Eq.trans (Eq.symm h2) h1 +/- +Note that we used the `identity` axiom. +-/ + +/- +Left cancellation. We have to use both `identity` and `inverse` axioms from +`Group`. +-/ +theorem left_cancellation : ∀ x y : G, a * x = a * y → x = y := by + have h1 := inverse a + have ⟨ai, a_inv⟩ := h1 + have ⟨_, h2⟩ := a_inv + intro x y + intro h3 + calc + x = (e : G) * x := Eq.symm (identity x).right + _ = ai * a * x := by rw [h2] + _ = ai * (a * x) := by rw [assoc] + _ = ai * (a * y) := by rw [h3] + _ = ai * a * y := by rw [← assoc] + _ = (e : G) * y := by rw [h2] + _ = y := (identity y).right + +end GroupTheory /- Variables `G`, `a`, `b`, `c` are now not in scope. -/ + +/- +Let us see a mutually recursive definition. + +The game of Nim with two heaps. +-/ +abbrev between (lower what upper : Nat) : Prop := lower ≤ what ∧ what ≤ upper + +mutual + def Alice : Nat → Nat → Prop + | n1, n2 => + ∃ k, (between 1 k n1 ∧ (between 1 k n1 → Bob (n1-k) n2)) + ∨ (between 1 k n2 ∧ (between 1 k n2 → Bob n1 (n2-k))) + + def Bob : Nat → Nat → Prop + | n1, n2 => + ∀ k, (between 1 k n1 → Alice (n1-k) n2) + ∧ (between 1 k n2 → Alice n1 (n2-k)) +end + +example : Bob 0 0 := by + intro k + induction k + case zero => + constructor + intro ; contradiction + intro ; contradiction + case succ => + constructor + intro a ; have := a.right ; contradiction + intro a ; have := a.right ; contradiction + +/- +We have to convince Lean of termination when a function is defined using just a +`def`. Here's a simple primality checking algorithm that tests all candidate +divisors. +-/ +def prime' (n : Nat) : Bool := + if h : n < 2 then + false + else + @go 2 n (by omega) +where + go (d : Nat) (n : Nat) {_ : n ≥ d} : Bool := + if h : n = d then /- `h` needed for `omega` below. -/ + true + else if n % d = 0 then + false + else + @go (Nat.succ d) n (by omega) + termination_by (n - d) +/- +We have to specify that the recursive function `go` terminates because `n-k` +decreases in each recursive call. This needs the hypothesis `n > k` at the +recursive call site. But the function itself can only assume that `n ≥ k`. We +label the test `n ≤ k` by `h` so that the falsification of this proposition can +be used by `omega` later to conclude that `n > k`. + +The tactic `omega` can solve simple equalities and inequalities. +-/ +/- +You can also instruct Lean to not check for totality by prefixing `partial` to +`def`. +-/ + +/- +Or, we can rewrite the function to test the divisors from largest to +smallest. In this case, Lean easily verifies that the function is total. +-/ +def prime (n : Nat) : Bool := + if n < 2 then + true + else + go (n-1) n +where + go d n := + if d < 2 then + true + else if n % d = 0 then + false + else + go (d-1) n +/- +Now, to Lean, it is obvious that `go` will terminate because `d` decreases in +each recursive call. +-/ +#eval prime 57 +#eval prime 97 +``` + +For further learning, see: + +* [Functional Programming in Lean](https://lean-lang.org/functional_programming_in_lean/) +* [Theorem Proving in Lean 4](https://lean-lang.org/theorem_proving_in_lean4/) +* [Lean 4 Manual](https://lean-lang.org/lean4/doc/) From cf670d3414e5b32eb1595bbb33f8ee4199d32f30 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Mon, 13 May 2024 07:19:23 +0100 Subject: [PATCH 165/392] [python/en] Clarify inheritance description (#4759) --- python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python.html.markdown b/python.html.markdown index a9b5f92c..0cdf256a 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -826,8 +826,8 @@ if __name__ == "__main__": # variables from their parent class. # Using the Human class defined above as the base or parent class, we can -# define a child class, Superhero, which inherits the class variables like -# "species", "name", and "age", as well as methods, like "sing" and "grunt" +# define a child class, Superhero, which inherits variables like "species", +# "name", and "age", as well as methods, like "sing" and "grunt" # from the Human class, but can also have its own unique properties. # To take advantage of modularization by file you could place the classes above From ebad04845e3d91c0e9a4a4470786a4986aa845dd Mon Sep 17 00:00:00 2001 From: Th3G33k <4394090+Th3G33k@users.noreply.github.com> Date: Sun, 12 May 2024 20:23:40 -1000 Subject: [PATCH 166/392] [javascript/fr] Add new js features (#4903) --- fr-fr/javascript-fr.html.markdown | 69 ++++++++++++++++++++++++++++--- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index 8f9f2c1b..d0ea1e33 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -133,6 +133,10 @@ undefined; // utilisé pour une valeur actuellement non présente (cependant, // est 'presque-vrai' (truthy) // Notez que 0 est falsy mais '0' est truthy, alors même que 0 == '0' (mais 0 !== '0') +// Les expressions régulières peuvent être utilisées +let re = /\d+/g // re = new RegExp("\\d+","g") +re.test("123") // vrai + // *ES6:* Introduction d'un nouveau type primitif : Symbol var symbol_one = Symbol(); var symbol_two = Symbol('This is optional description, for debugging'); @@ -355,6 +359,10 @@ if (!name){ name = 'default'; } +// Opérateur ternaire : +// Si la condition est vérifiée, retourne la valeur 1, sinon la valeur 2. +name = otherName === 'test' ? 'value1' : 'value2'; + // Le switch vérifie les égalités avec === // utilisez un "break" à la fin de chaque cas // ou les cas suivants seront eux aussi exécutés @@ -456,12 +464,16 @@ function sayHelloInFiveSeconds(name){ } sayHelloInFiveSeconds('Adam'); // ouvre un popup avec 'Hello, Adam!' dans 5sec -// *ES6:* Les paramètres des fonctions appelées avec un tableau en entré -// préfixé par `...` vont se peupler avec les éléments du tableau -function spread(x, y, z) { - return x + y + z; +// Gestion des erreurs +// Essaye d'exécuter les instructions du bloc try. En cas d'erreur, plutôt que d'arrêter l'éxécution, +// capture l'erreur et continue avec les instructions du bloc catch. +try { + let json = 'bad JSON'; + if (!json) throw 'empty string'; + json = JSON.parse(json); +} catch (e) { + console.log(e) } -spread(...[1,2,3]); // == 6 // *ES6:* Les fonctions peuvent recevoir les paramètres dans un tableau en utilisant l'opérateur `...` function spread(x, y, z) { @@ -469,6 +481,39 @@ function spread(x, y, z) { } spread(...[1,2,3]); // == 6 +// *ES6:* Paramètre du reste +// Permet d'avoir un nombre indéfini d'arguments. +function restParam(...z) { + return z; +} +restParam(1, 2, 3, 4); // [1, 2, 3, 4] + +// *ES6:* Promesse +function sleep(ms) { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve('sleep end'); + }, ms) + }) +} + +// *ES6:* Exécute entièrement fnThen. Une fois la Promesse résolue, exécute la fonction de rappel. +// Affiche "function end", puis "sleep end". +(function fnThen() { + sleep(1000).then(x => { + console.log(x) + }) + console.log('function end') +})() + +// *ES2017:* Fonction asynchrone. Attend la fin de la Promesse, puis continue l'exécution de fnAsync. +// Affiche "sleep end", puis "function end". +(async function fnAsync() { + console.log(await sleep(1000)) + console.log('function end') +})() + + /////////////////////////////////// // 5. Encore plus à propos des Objets; Constructeurs and Prototypes @@ -643,6 +688,18 @@ if (Object.create === undefined){ // pour ne pas reécrire si la fonction existe } } +// *ES2020:* Opérateur de chaînage optionnel ?. +// Permet d'accéder aux propriétés dans une chaine d'objets. +// Retourne undefined si un objet intermédiaire n'est pas défini. +let optChainObj = {} +let optChainVal +optChainVal = optChainObj.obj2?.obj3?.val + +// Equivalent à : +if (("obj2" in optChainObj) && ("obj3" in optChainObj.obj2)) { + optChainVal = optChainObj.obj2.obj3.val +} + // *ES6:* Les objets peuvent être équipés de proxies qui permettent d'intercepter // les actions sur leurs propriétés. Voici comment créer un proxy sur un objet : var proxyObject = new Proxy(object, handler); @@ -693,6 +750,8 @@ import {foo, baz} from "api"; // = importe les attributs `foo` et `baz` du modul import {foo as moo, baz} from "api"; // = importe les attributs `foo` (en le renommant `moo`) et `baz` du module import _, {map} from "api"; // = importe les exports par défaut ET `map` import * as coolapi from "api"; // = importe le namespace global du module + +let coolapi = await import("api") // = importe le module dans la variable `coolapi` ``` ## Pour aller plus loin (en anglais) From 9d1ddbea0407c2bd3ea49a364eb3fbb387c506e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ada=C3=ADas=20Magdiel?= Date: Mon, 13 May 2024 03:25:53 -0300 Subject: [PATCH 167/392] [p5.js/pt-br] Add p5.js tutorial in Brazilian Portuguese (#4850) --- pt-br/p5-pt.html.markdown | 167 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) create mode 100644 pt-br/p5-pt.html.markdown diff --git a/pt-br/p5-pt.html.markdown b/pt-br/p5-pt.html.markdown new file mode 100644 index 00000000..10da5869 --- /dev/null +++ b/pt-br/p5-pt.html.markdown @@ -0,0 +1,167 @@ +--- +category: tool +tool: p5 +filename: p5-pt.js +contributors: + - ['Amey Bhavsar', 'https://github.com/ameybhavsar24'] + - ['Claudio Busatto', 'https://github.com/cjcbusatto'] +translators: + - ["Adaías Magdiel", "https://adaiasmagdiel.com/"] +lang: pt-br +--- + +p5.js é biblioteca JavaScript que carrega o princípio original do [Processing](https://processing.org), tornar a programação acessível à artistas, designers, professores e alunos e traz esse lema para os dias atuais. +Como o p5.js é uma biblioteca JavaScript, você precisa aprender [Javascript](https://learnxinyminutes.com/docs/pt-br/javascript-pt/) primeiro. + +Para rodar códigos com p5.js online, você pode acessar o [editor online](https://editor.p5js.org/). + +```js +/////////////////////////////////// +// p5.js possui duas funções importantes para se trabalhar. + +function setup() { + // a função setup é carregada apenas uma vez, quando a janela é carregada +} +function draw() { + // a função draw é chamada a cada frame + // se o framerate é definido como 30, essa função vai ser chamada 30 vezes por segundo +} + +// o seguinte código explica todas as funcionalidades + +function setup() { + createCanvas(640, 480); // cria um novo elemento canvas com 640px de largura e 480px de altura + background(128); // muda a cor do background para rgb(128, 128, 128) + // background('#aaf') // Você pode usar hexadecimal como código de cor, também +} + +function draw() { + // normalmente, a função `background` é chamada na função `draw` para limpar a tela + background('#f2f2fc'); + + // cria uma elipse a partir de 10px do topo e 10px da esquerda, com uma largura e altura de 37 + ellipse(10, 10, 37, 37); + // no p5.js a origem é sempre no canto à esquerda e no topo do canvas + + if (mouseIsPressed) { + // mouseIsPressed é uma variável booleana que é verdadeira quando o mouse está pressionado e falso quando é liberado + + fill(0); // define a cor de preenchimento, que permanece até ser modificada novamente + } else { + fill(255, 255, 255, 240); // fill(a, b, c, d) define a cor de preenchimento para rgba(a, b, c, d) + } + + ellipse(mouseX, mouseY, 80, 80); + // mouseX e mouseY são as coordenadas da posição do mouse, x e y respectivamente + // o código acima cria uma elipse embaixo da posição do mouse e preenche com branco ou preto + + + // algumas outras formas primitivas em 2d que você pode utilizar: + rect(9, 3, 23, 26); // x, y, largura, altura + noFill(); // define a cor de preenchimento como transparente + triangle(100, 400, 130, 200, 200, 300); // x1, y1, x2, y2, x3, y3 + point(100, 300); // cria um ponto na posição x, y + // existem outras formas, mas elas são mais complexas. +} + +/** Animação de bolas quicando + * Você pode copiar e colar esse código no editor online, acessando: + * https://editor.p5js.org/ + */ +class Ball { + constructor(x, y, xvel, yvel, radius, col) { + this.position = createVector(x, y); // cria um objeto p5.Vector que armazena os valores de x e y + this.velocity = createVector(xvel, yvel); // criar um objeto p5.Vector armazenando a velocidade + this.radius = radius; + this.col = col; // p5.js já utiliza a palavra color, então usaremos "col" no nosso exemplo + } + + update() { + this.position.add(this.velocity); // você pode somar vetores usando a função p5.Vector.add(p5.Vector) + if (this.position.x + this.radius > width) { + // muda a direção da bola se ela bater nas paredes + this.velocity.x *= -1; + } + if (this.position.x - this.radius < 0) { + this.velocity.x *= -1; + } + if (this.position.y + this.radius > height) { + this.velocity.y *= -1; + } + if (this.position.y - this.radius < 0) { + this.velocity.y *= -1; + } + } + + render() { + // com base nesses exemplos, você já deve ser capaz de entender o que essa função está fazendo + fill(this.col); + ellipse(this.position.x, this.position.y, this.radius); + } +} + +let numBalls = 23; +let balls = []; + +function setup() { + createCanvas(400, 400); // largura, altura + for (let i = 0; i < numBalls; i++) { + let r = random(255); // um número aleatório entre 0 e 255 + let g = random(255); + let b = random(255); + + balls.push( + new Ball( + random(30, width), // posição x + random(height), // posição y + random(-4, 4), // velocidade x + random(-4, 4), // velocidade y + random(4, 10), // raio + color(r, g, b) // cor de preenchimento para a bola + ) + ); + } +} + +function draw() { + background(255); + for (let ball of balls) { + ball.update(); + ball.render(); + } +} + +// Até agora, só vimos o modo de renderização padrão. +// Dessa vez, usaremos o modo de renderização "webgl". + + +function setup() { + createCanvas(400, 400, WEBGL); // largura, altura, modo de renderização +} + +function draw() { + background(0); + + stroke('#000'); + fill('#aaf'); + + // rotaciona entorno dos eixos x, y e z com base na quantidade de frames dividido por 50 + rotateX(frameCount / 50); + rotateY(frameCount / 50); + rotateZ(frameCount / 50); + // frameCount é uma variável do p5.js que armazena a quantidade de frames que já ocorreu + + box(50, 50, 50); // largura, altura, profundidade +} +``` + +## Saiba Mais + +- [Começando com p5.js](http://p5js.org/get-started/) A documentação oficial +- [Code! Programming for Beginners with p5.js - YouTube](https://www.youtube.com/watch?v=yPWkPOfnGsw&vl=en) Introdução e desafios usando Processing e p5.js por Coding Train +- [The Coding Train](https://codingtra.in/) Um site com exemplos feito utilizando p5.js e Processing + +## Fonte + +- [p5.js - Código Fonte](https://github.com/processing/p5.js) +- [p5.sound.js](https://github.com/processing/p5.js-sound) From 5ffa5d8356cf1e99daea42a9d34c644b6ccb6a23 Mon Sep 17 00:00:00 2001 From: Luke Harold Miles <10591373+qpwo@users.noreply.github.com> Date: Sun, 12 May 2024 23:41:45 -0700 Subject: [PATCH 168/392] [toml/en] change toml from 0.4.0 to 1.0.0 (#4690) --- toml.html.markdown | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/toml.html.markdown b/toml.html.markdown index 13be23b8..1af38e4a 100644 --- a/toml.html.markdown +++ b/toml.html.markdown @@ -9,8 +9,7 @@ TOML stands for Tom's Obvious, Minimal Language. It is a data serialisation lang It is an alternative to YAML and JSON. It aims to be more human friendly than JSON and simpler that YAML. TOML is designed to map unambiguously to a hash table. TOML should be easy to parse into data structures in a wide variety of languages. -Be warned, TOML's spec is still changing a lot. Until it's marked as 1.0, you -should assume that it is unstable and act accordingly. This document follows TOML v0.4.0. +This document follows [TOML v1.0.0](https://toml.io/en/v1.0.0). Future [changes](https://github.com/toml-lang/toml/blob/main/CHANGELOG.md) are expected to be minor and backwards-compatible. ```toml # Comments in TOML look like this. @@ -32,7 +31,8 @@ boolean = true dateTime = 1979-05-27T07:32:00-08:00 scientificNotation = 1e+12 "key can be quoted" = true # Both " and ' are fine -"key may contain" = "letters, numbers, underscores, and dashes" +"unquoted key may contain" = "letters, numbers, underscores, and dashes" +other_kêys = "are permitted by spec but most implementations don't actually permit them" # A bare key must be non-empty, but an empty quoted key is allowed "" = "blank" # VALID but discouraged @@ -205,8 +205,12 @@ c = 2 # Inline table # ################ -inlineTables = { areEnclosedWith = "{ and }", mustBeInline = true } +inlineTables = { areEnclosedWith = "{ and }", a = { b = { c = { d = 1 } } } } point = { x = 1, y = 2 } +usingMultiple = { + lines = "discouraged!", + instead = "use normal TOML tables", +} ################### # Array of Tables # From bd36d7714bfa79b1dd1ea717dcbb5ebe6338dc50 Mon Sep 17 00:00:00 2001 From: Prayag Bhakar Date: Mon, 13 May 2024 02:46:20 -0400 Subject: [PATCH 169/392] [zfs/en] Update (#4817) --- zfs.html.markdown | 114 +++++++++++++++++++++++++++++++++++++--------- 1 file changed, 92 insertions(+), 22 deletions(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index 56a676a7..92d7aaa2 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -3,39 +3,38 @@ category: tool tool: zfs contributors: - ["sarlalian", "http://github.com/sarlalian"] + - ["81reap", "https://github.com/81reap"] - ["A1EF", "https://github.com/A1EF"] filename: LearnZfs.txt --- - [ZFS](http://open-zfs.org/wiki/Main_Page) is a rethinking of the storage stack, combining traditional file systems as well as volume managers into one cohesive tool. ZFS has some specific terminology that sets it apart from more traditional storage systems, however it has a great set of features with a focus on usability for systems administrators. - ## ZFS Concepts ### Virtual Devices -A VDEV is similar to a raid device presented by a RAID card, there are several different -types of VDEV's that offer various advantages, including redundancy and speed. In general -VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a -RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. +A VDEV (Virtual Device) in ZFS is analogous to a RAID device and simmilaly offers different +benefits in terms of redundancy and performance. In general VDEV's offer better reliability +and safety than a RAID card. It is discouraged to use a RAID setup with ZFS, as ZFS expects +to directly manage the underlying disks. -Types of VDEV's +| VDEV Type | Similar RAID | Notes | +|-----------|----------------|---------------------------------------| +| Mirror | RAID 1 | Supports n-way mirroring for redundancy. | +| raidz1 | RAID 5 | Single disk parity, offering fault tolerance of one disk failure. | +| raidz2 | RAID 6 | Two-disk parity, can tolerate two disk failures. | +| raidz3 | - | Three-disk parity, can tolerate three disk failures. | +| Disk | - | Represents a single physical disk in a VDEV. | +| File | - | File-based VDEV, not recommended for production as it adds complexity and reduces reliability. | -* mirror (n-way mirrors supported) -* raidz - * raidz1 (1-disk parity, similar to RAID 5) - * raidz2 (2-disk parity, similar to RAID 6) - * raidz3 (3-disk parity, no RAID analog) -* disk -* file (not recommended for production due to another filesystem adding unnecessary layering) - -Your data is striped across all the VDEV's present in your Storage Pool, so more VDEV's will -increase your IOPS. +Data in a ZFS storage pool is striped across all VDEVs. Adding more VDEVs, Logs, or Caches +can increase IOPS (Input/Output Operations Per Second), enhancing performance. It's crucial +to balance VDEVs for optimal performance and redundancy. ### Storage Pools @@ -48,14 +47,12 @@ ZFS datasets are analogous to traditional filesystems but with many more feature provide many of ZFS's advantages. Datasets support [Copy on Write](https://en.wikipedia.org/wiki/Copy-on-write) snapshots, quota's, compression and de-duplication. - ### Limits One directory may contain up to 2^48 files, up to 16 exabytes each. A single storage pool can contain up to 256 zettabytes (2^78) of space, and can be striped across 2^64 devices. A single host can have 2^64 storage pools. The limits are huge. - ## Commands ### Storage Pools @@ -144,7 +141,6 @@ Remove zpool $ zpool destroy test ``` - ### Datasets Actions: @@ -258,6 +254,82 @@ zroot/var none none ... ``` +### Write Log Pool + +The ZFS Intent Log (ZIL) is a write log designed to speed up syncronus writes. This is +typically a faster drive or drive partition than the larger storage pools. + +```bash +# Add a log pool +$ zpool add mypool/lamb log /dev/sdX + +# Check the configureation +$ zpool status mypool/lamb +``` + +### Read Cache Pool + +The Level 2 Adaptive Replacement Cache (L2ARC) extends the primary ARC (in-RAM cache) and is +used for read caching. This is typically a faster drive or drive partition than the larger +storage pools. + +```bash +# Add a cache pool +$ zpool add mypool/lamb cache /dev/sdY + +# Check the configureation +$ zpool status mypool/lamb +``` + +### Data Compression + +Data compression reduces the amount of space data occupies on disk in excange for some extra +CPU usage. When enabled, it can enhance performance by reducing the amount of disk I/O. It +especially beneficial on systems with more CPU resources than disk bandwidth. + +```bash +# Get compression options +$ zfs get -help +... +compression NO YES on | off | lzjb | gzip | gzip-[1-9] | zle | lz4 | zstd | zstd-[1-19] | zstd-fast | zstd-fast-[1-10,20,30,40,50,60,70,80,90,100,500,1000] +... + +# Set compression +$ zfs set compression=on mypool/lamb + +# Check the configureation +$ zpool get compression mypool/lamb +``` + +### Encryption at Rest + +Encryption allows data to be encrypted on the device at the cost of extra CPU cycles. This +propery can only be set when a dataset is being created. + +```bash +# Enable encryption on the pool +$ zpool set feature@encryption=enabled black_hole + +# Create an encrypted dataset with a prompt +$ zfs create -o encryption=on -o keyformat=passphrase black_hole/enc + +# Check the configureation +$ zfs get encryption black_hole/enc +``` + +It should be noted that there are parts of the system where the data is not encrypted. See +the table below for a breakdown. + +| Component | Encrypted | Notes | +|----------------------|-------------------------------------------|------------------------------------------------------| +| Main Data Storage | Yes | Data in datasets/volumes is encrypted. | +| ZFS Intent Log (ZIL) | Yes | Synchronous write requests are encrypted. | +| L2ARC (Cache) | Yes | Cached data is stored in an encrypted form. | +| RAM (ARC) | No | Data in the primary ARC, in RAM, is not encrypted. | +| Swap Area | Conditional | Encrypted if the ZFS swap dataset is encrypted. | +| ZFS Metadata | Yes | Metadata is encrypted for encrypted datasets. | +| Snapshot Data | Yes | Snapshots of encrypted datasets are also encrypted. | +| ZFS Send/Receive | Conditional | Encrypted during send/receive if datasets are encrypted and `-w` flag is used. | ### Snapshots @@ -277,7 +349,6 @@ Actions: * Send / Receive * Clone - Create snapshots ```bash @@ -392,7 +463,6 @@ echo "STOP SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging echo "RESET SLAVE;" | /usr/local/bin/mysql -u root -pmyrootpassword -h staging ``` - ### Additional Reading * [BSDNow's Crash Course on ZFS](http://www.bsdnow.tv/tutorials/zfs) From 21372617c0a47cbb622f1a93355b37d559f59efa Mon Sep 17 00:00:00 2001 From: Albina Gimaletdinova Date: Mon, 13 May 2024 07:56:14 +0100 Subject: [PATCH 170/392] [dynamic-programming/ru] Added translation (#4571) --- ru-ru/dynamic-programming-ru.html.markdown | 66 ++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 ru-ru/dynamic-programming-ru.html.markdown diff --git a/ru-ru/dynamic-programming-ru.html.markdown b/ru-ru/dynamic-programming-ru.html.markdown new file mode 100644 index 00000000..0b823b2d --- /dev/null +++ b/ru-ru/dynamic-programming-ru.html.markdown @@ -0,0 +1,66 @@ +--- +category: Algorithms & Data Structures +name: Dynamic Programming +contributors: + - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] + - ["Miltiadis Stouras", "https://github.com/mstou"] +translators: + - ["Albina Gimaletdinova", "https://github.com/albina-astr"] +lang: ru-ru +--- + +# Динамическое программирование + +## Введение + +Динамическое программирование (dynamic programming, DP) — мощный инструмент для решения определенного класса задач. Идея очень проста: если вы решили задачу для каких-то вводных данных, сохраните этот результат для будущих вычислений, чтобы снова не решать ту же самую задачу с теми же данными. + +Запомните! +«Кто не помнит своего прошлого, обречен на то, чтобы пережить его вновь» + +## Способы решения подобных задач + +1. *Сверху-вниз*: Начните с разбиения задачи на подзадачи. Если вы видите, что подзадача уже была решена, тогда используйте сохраненный ранее результат. Иначе решите подзадачу и сохраните её результат. Эта техника интуитивно понятна и называется мемоизацией. + +2. *Снизу-вверх*: Проанализируйте задачу и определите порядок, в котором решаются подзадачи, и начните решать от тривиальной подзадачи до изначальной задачи. Это гарантирует, что подзадачи будут решены, прежде чем решится вся задача. В этом и заключается динамическое программирование. + +## Пример задачи динамического программирования + +В задаче по определению самой длинной возрастающей подпоследовательности необходимо найти найти самую длинную возрастающую подпоследовательность для заданной последовательности. +Для последовательности `S={ a1, a2, a3, a4, ............., an-1, an }` мы должны найти самое длинное подмножество, такое, что для всех `j` и `i`, `j a[j] and LS[i] Date: Mon, 13 May 2024 03:00:26 -0400 Subject: [PATCH 171/392] [solidity/en] Correct typo (#4533) --- solidity.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/solidity.html.markdown b/solidity.html.markdown index cddaa6db..094baa13 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -657,7 +657,7 @@ reveal(100, "mySecret"); // in a decentralized manner, otherwise you run into the centralized risk that // smart contract design matter prevents. -// To easiest way get and use pre-boxed decentralized data is with Chainlink Data Feeds +// The easiest way to get and use pre-boxed decentralized data is with Chainlink Data Feeds // https://docs.chain.link/docs/get-the-latest-price // We can reference on-chain reference points that have already been aggregated by // multiple sources and delivered on-chain, and we can use it as a "data bank" From f6f88843aafe9a60569f7b93ae175cfd7281d260 Mon Sep 17 00:00:00 2001 From: Imran Khan <42691857+astr0n0mer@users.noreply.github.com> Date: Mon, 13 May 2024 12:32:44 +0530 Subject: [PATCH 172/392] [pug/en] Fix style attribute syntax error (#4653) --- de-de/pug-de.html.markdown | 4 ++-- pug.html.markdown | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown index ebc32622..e4229622 100644 --- a/de-de/pug-de.html.markdown +++ b/de-de/pug-de.html.markdown @@ -84,8 +84,8 @@ div(class=meineKlasse) //- JS Stil - const meineStile = {'color':'white', 'background-color':'blue'} -div(styles=meineStile) -//-
    +div(style=meineStile) +//-
    //- JS Attributte - const meineAttribute = {"src": "foto.png", "alt": "meine Bilder"} diff --git a/pug.html.markdown b/pug.html.markdown index 052c5dcc..64bf1d9a 100644 --- a/pug.html.markdown +++ b/pug.html.markdown @@ -80,8 +80,8 @@ div(class=myClass) //- JS Styles - const myStyles = {'color':'white', 'background-color':'blue'} -div(styles=myStyles) -//-
    +div(style=myStyles) +//-
    //- JS Attributes - const myAttributes = {"src": "photo.png", "alt": "My Photo"} From 9e75ad79c5d2a1b6a57b685e63df32efd8894c8f Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Mon, 13 May 2024 03:13:58 -0400 Subject: [PATCH 173/392] [nim/en] Clarify Nim zero value for uninitialized variables (#4573) --- nim.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index 81662630..e3c749dc 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -188,7 +188,7 @@ echo "I'm thinking of a number between 41 and 43. Guess which!" let number: int = 42 var raw_guess: string - guess: int + guess: int # Variables in Nim are always initialized with a zero value while guess != number: raw_guess = readLine(stdin) if raw_guess == "": continue # Skip this iteration From f3fc404374222d8d73758eae3429d366e145dd1b Mon Sep 17 00:00:00 2001 From: edgar-vincent <63352906+edgar-vincent@users.noreply.github.com> Date: Mon, 13 May 2024 09:22:09 +0200 Subject: [PATCH 174/392] [elisp/fr] minibuffer -> echo area (#4522) --- fr-fr/elisp-fr.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fr-fr/elisp-fr.html.markdown b/fr-fr/elisp-fr.html.markdown index f9bf589c..e866013e 100644 --- a/fr-fr/elisp-fr.html.markdown +++ b/fr-fr/elisp-fr.html.markdown @@ -86,12 +86,12 @@ lang: fr-fr ;; `C-j' insère le résultat de l'évaluation dans le buffer. ;; `C-x C-e' affiche le même résultat dans la ligne tout en bas -;; d'Emacs, appelée le "minibuffer". On utilise en général `C-x C-e', +;; d'Emacs, appelée l' "echo area". On utilise en général `C-x C-e', ;; pour ne pas encombrer le buffer avec du texte inutile. ;; `setq' assigne une valeur à une variable : (setq my-name "Bastien") -;; `C-x C-e' => "Bastien" (affiché dans le minibuffer) +;; `C-x C-e' => "Bastien" (affiché dans l'*echo area*) ;; `insert' va insérer "Hello!" là où se trouve le curseur : (insert "Hello!") From fadb281798a95bd87c8a3a1b443272af951103df Mon Sep 17 00:00:00 2001 From: Danny Yang Date: Mon, 13 May 2024 03:37:11 -0400 Subject: [PATCH 175/392] [rescript/en] add ReScript (#4394) --- rescript.html.markdown | 536 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 536 insertions(+) create mode 100644 rescript.html.markdown diff --git a/rescript.html.markdown b/rescript.html.markdown new file mode 100644 index 00000000..b633332c --- /dev/null +++ b/rescript.html.markdown @@ -0,0 +1,536 @@ +--- +language: ReScript +filename: rescript.res +contributors: + - ["Seth Corker", "https://sethcorker.com"] + - ["Danny Yang", "https://yangdanny97.github.io"] +--- + +ReScript is a robustly typed language that compiles to efficient and human-readable JavaScript. It comes with a lightning fast compiler toolchain that scales to any codebase size. ReScript is descended from OCaml and Reason, with nice features like type inference and pattern matching, along with beginner-friendly syntax and a focus on the JavaScript ecosystem. + +```javascript +/* Comments start with slash-star, and end with star-slash */ +// Single line comments start with double slash + +/*---------------------------------------------- + * Variable and function declaration + *---------------------------------------------- + * Variables and functions use the let keyword and end with a semi-colon + * `let` bindings are immutable + */ + +let x = 5 +/* - Notice we didn't add a type, ReScript will infer x is an int */ + +/* A function like this, take two arguments and add them together */ +let add = (a, b) => a + b +/* - This doesn't need a type annotation either! */ + +/*---------------------------------------------- + * Type annotation + *---------------------------------------------- + * Types don't need to be explicitly annotated in most cases but when you need + * to, you can add the type after the name + */ + +/* A type can be explicitly written like so */ +let x: int = 5 + +/* The add function from before could be explicitly annotated too */ +let add2 = (a: int, b: int): int => a + b + +/* A type can be aliased using the type keyword */ +type companyId = int +let myId: companyId = 101 + +/* Mutation is not encouraged in ReScript but it's there if you need it + If you need to mutate a let binding, the value must be wrapped in a `ref()`*/ +let myMutableNumber = ref(120) + +/* To access the value (and not the ref container), use `.contents` */ +let copyOfMyMutableNumber = myMutableNumber.contents + +/* To assign a new value, use the `:=` operator */ +myMutableNumber := 240 + +/*---------------------------------------------- + * Basic types and operators + *---------------------------------------------- + */ + +/* > String */ + +/* Use double quotes for strings */ +let greeting = "Hello world!" + +/* A string can span multiple lines */ +let aLongerGreeting = "Look at me, +I'm a multi-line string +" + +/* Use ` for unicode */ +let world = `🌍` + +/* The ` annotation is also used for string interpolation */ +let helloWorld = `hello, ${world}` +/* Bindings must be converted to strings */ +let age = 10 +let ageMsg = `I am ${Js.Int.toString(age)} years old` + +/* Using `j` annotation in interpolation will implicitly convert bindings to strings */ +let ageMsg = j`I am $age years old` + + +/* Concatenate strings with ++ */ +let name = "John " ++ "Wayne" +let emailSubject = "Hi " ++ name ++ ", you're a valued customer" + +/* > Char */ + +/* Use a single character for the char type */ +let lastLetter = 'z' +/* - Char doesn't support Unicode or UTF-8 */ + +/* > Boolean */ + +/* A boolean can be either true or false */ +let isLearning = true + +true && false /* - : bool = false Logical and */ +true || true /* - : bool = true Logical or */ +!true /* - : bool = false Logical not */ + +/* Greater than `>`, or greater than or equal to `>=` */ +'a' > 'b' /* - bool : false */ + +/* Less than `<`, or less than or equal to `<=` */ +1 < 5 /* - : bool = true */ + +/* Structural equal */ +"hello" == "hello" /* - : bool = true */ + +/* Referential equal */ +"hello" === "hello" /* - : bool = false */ +/* - This is false because they are two different "hello" string literals */ + +/* Structural unequal */ +lastLetter != 'a' /* -: bool = true */ + +/* Referential unequal */ +lastLetter !== lastLetter /* - : bool = false */ + +/* > Integer */ +/* Perform math operations on integers */ + +1 + 1 /* - : int = 2 */ +25 - 11 /* - : int = 11 */ +5 * 2 * 3 /* - : int = 30 */ +8 / 2 /* - : int = 4 */ + +/* > Float */ +/* Operators on floats have a dot after them */ + +1.1 +. 1.5 /* - : float = 2.6 */ +18.0 -. 24.5 /* - : float = -6.5 */ +2.5 *. 2.0 /* - : float = 5. */ +16.0 /. 4.0 /* - : float = 4. */ + +/* > Tuple + * Tuples have the following attributes + - immutable + - ordered + - fix-sized at creation time + - heterogeneous (can contain different types of values) + A tuple is 2 or more values */ + +let teamMember = ("John", 25) + +/* Type annotation matches the values */ +let position2d: (float, float) = (9.0, 12.0) + +/* Pattern matching is a great tool to retrieve just the values you care about + If we only want the y value, let's use `_` to ignore the value */ +let (_, y) = position2d +y +. 1.0 /* - : float = 13. */ + +/* > Record */ + +/* A record has to have an explicit type */ +type trainJourney = { + destination: string, + capacity: int, + averageSpeed: float, +} + +/* Once the type is declared, ReScript can infer it whenever it comes up */ +let firstTrip = {destination: "London", capacity: 45, averageSpeed: 120.0} + +/* Access a property using dot notation */ +let maxPassengers = firstTrip.capacity + +/* If you define the record type in a different file, you have to reference the + filename, if trainJourney was in a file called Trips.re */ +let secondTrip: Trips.trainJourney = { + destination: "Paris", + capacity: 50, + averageSpeed: 150.0, +} + +/* Records are immutable by default */ +/* But the contents of a record can be copied using the spread operator */ +let newTrip = {...secondTrip, averageSpeed: 120.0} + +/* A record property can be mutated explicitly with the `mutable` keyword */ +type breakfastCereal = { + name: string, + mutable amount: int, +} + +let tastyMuesli = {name: "Tasty Muesli TM", amount: 500} + +tastyMuesli.amount = 200 +/* - tastyMuesli now has an amount of 200 */ + +/* Punning is used to avoid redundant typing */ +let name = "Just As Good Muesli" +let justAsGoodMuesli = {name, amount: 500} +/* - justAsGoodMuesli.name is now "Just As Good Muesli", it's equivalent + to { name: name, amount: 500 } */ + +/* > Variant + Mutually exclusive states can be expressed with variants */ + +type authType = + | GitHub + | Facebook + | Google + | Password +/* - The constructors must be capitalized like so */ +/* - Like records, variants should be named if declared in a different file */ + +let userPreferredAuth = GitHub + +/* Variants work great with a switch statement */ +let loginMessage = + switch (userPreferredAuth) { + | GitHub => "Login with GitHub credentials." + | Facebook => "Login with your Facebook account." + | Google => "Login with your Google account" + | Password => "Login with email and password." + } + +/* > Option + An option can be None or Some('a) where 'a is the type */ + +let userId = Some(23) + +/* A switch handles the two cases */ +let alertMessage = + switch (userId) { + | Some(id) => "Welcome, your ID is" ++ string_of_int(id) + | None => "You don't have an account!" + } +/* - Missing a case, `None` or `Some`, would cause an error */ + +/* > List + * Lists have the following attributes + - immutable + - ordered + - fast at prepending items + - fast at splitting + + * Lists in ReScript are linked lists + */ + +/* A list is declared with the `list` keyword and initialized with values wrapped in curly braces */ +let userIds = list{1, 4, 8} + +/* The type can be explicitly set with list<'a> where 'a is the type */ +type idList = list +type attendanceList = list + +/* Lists are immutable */ +/* But you can create a new list with additional prepended elements by using the spread operator on an existing list */ +let newUserIds = list{101, 102, ...userIds} + +/* > Array + * Arrays have the following attributes + - mutable + - fast at random access & updates */ + +/* An array is declared with `[` and ends with `]` */ +let languages = ["ReScript", "JavaScript", "OCaml"] + +/*---------------------------------------------- + * Function + *---------------------------------------------- + */ + +/* ReScript functions use the arrow syntax, the expression is returned */ +let signUpToNewsletter = email => "Thanks for signing up " ++ email + +/* Call a function like this */ +signUpToNewsletter("hello@ReScript.org") + +/* For longer functions, use a block */ +let getEmailPrefs = email => { + let message = "Update settings for " ++ email + let prefs = ["Weekly News", "Daily Notifications"] + + (message, prefs) +} +/* - the final tuple is implicitly returned */ + +/* > Labeled Arguments */ + +/* Arguments can be labeled with the ~ symbol */ +let moveTo = (~x, ~y) => { + /* Move to x,y */ + () +} + +moveTo(~x=7.0, ~y=3.5) + +/* Labeled arguments can also have a name used within the function */ +let getMessage = (~message as msg) => "==" ++ msg ++ "==" + +getMessage(~message="You have a message!") +/* - The caller specifies ~message but internally the function can make use */ + +/* The following function also has explicit types declared */ +let showDialog = (~message: string): unit => { + () /* Show the dialog */ +} +/* - The return type is `unit`, this is a special type that is equivalent to + specifying that this function doesn't return a value + the `unit` type can also be represented as `()` */ + +/* > Currying + Functions can be curried and are partially called, allowing for easy reuse */ + +let div = (denom, numr) => numr / denom +let divBySix = div(6) +let divByTwo = div(2) + +div(3, 24) /* - : int = 8 */ +divBySix(128) /* - : int = 21 */ +divByTwo(10) /* - : int = 5 */ + +/* > Optional Labeled Arguments */ + +/* Use `=?` syntax for optional labeled arguments */ +let greetPerson = (~name, ~greeting=?, ()) => { + switch (greeting) { + | Some(greet) => greet ++ " " ++ name + | None => "Hi " ++ name + } +} +/* - The third argument, `unit` or `()` is required because if we omitted it, + the function would be curried so greetPerson(~name="Kate") would create + a partial function, to fix this we add `unit` when we declare and call it */ + +/* Call greetPerson without the optional labeled argument */ +greetPerson(~name="Kate", ()) + +/* Call greetPerson with all arguments */ +greetPerson(~name="Marco", ~greeting="How are you today,") + +/* > Pipe */ +/* Functions can be called with the pipeline operator */ + +/* Use `->` to pass in the first argument (pipe-first) */ +3->div(24) /* - : int = 8 */ +/* - This is equivalent to div(3, 24) */ + +36->divBySix /* - : int = 6 */ +/* - This is equivalent to divBySix(36) */ + +/* Pipes make it easier to chain code together */ +let addOne = a => a + 1 +let divByTwo = a => a / 2 +let multByThree = a => a * 3 + +let pipedValue = 3->addOne->divByTwo->multByThree /* - : int = 6 */ + +/*---------------------------------------------- + * Control Flow & Pattern Matching + *---------------------------------------------- + */ + +/* > If-else */ +/* In ReScript, `If` is an expression when evaluate will return the result */ + +/* greeting will be "Good morning!" */ +let greeting = if (true) {"Good morning!"} else {"Hello!"} + +/* Without an else branch the expression will return `unit` or `()` */ +if (false) { + showDialog(~message="Are you sure you want to leave?") +} +/* - Because the result will be of type `unit`, both return types should be of + the same type if you want to assign the result. */ + +/* > Destructuring */ +/* Extract properties from data structures easily */ + +let aTuple = ("Teacher", 101) + +/* We can extract the values of a tuple */ +let (name, classNum) = aTuple + +/* The properties of a record can be extracted too */ +type person = { + firstName: string, + age: int, +} +let bjorn = {firstName: "Bjorn", age: 28} + +/* The variable names have to match with the record property names */ +let {firstName, age} = bjorn + +/* But we can rename them like so */ +let {firstName: bName, age: bAge} = bjorn + +let {firstName: cName, age: _} = bjorn + +/* > Switch + Pattern matching with switches is an important tool in ReScript + It can be used in combination with destructuring for an expressive and + concise tool */ + +/* Lets take a simple list */ +let firstNames = ["James", "Jean", "Geoff"] + +/* We can pattern match on the names for each case we want to handle */ +switch (firstNames) { +| [] => "No names" +| [first] => "Only " ++ first +| [first, second] => "A couple of names " ++ first ++ "," ++ second +| [first, second, third] => + "Three names, " ++ first ++ ", " ++ second ++ ", " ++ third +| _ => "Lots of names" +} +/* - The `_` is a catch all at the end, it signifies that we don't care what + the value is so it will match every other case */ + +/* > When clause */ + +let isJohn = a => a == "John" +let maybeName = Some("John") + +/* When can add more complex logic to a simple switch */ +let aGreeting = + switch (maybeName) { + | Some(name) when isJohn(name) => "Hi John! How's it going?" + | Some(name) => "Hi " ++ name ++ ", welcome." + | None => "No one to greet." + } + +/* > Exception */ + +/* Define a custom exception */ +exception Under_Age + +/* Raise an exception within a function */ +let driveToTown = (driver: person) => + if (driver.age >= 15) { + "We're in town" + } else { + raise(Under_Age) + } + +let evan = {firstName: "Evan", age: 14} + +/* Pattern match on the exception Under_Age */ +switch (driveToTown(evan)) { +| status => print_endline(status) +| exception Under_Age => + print_endline(evan.firstName ++ " is too young to drive!") +} + +/* Alternatively, a try block can be used */ +/* - With ReScript exceptions can be avoided with optionals and are seldom used */ +let messageToEvan = + try { + driveToTown(evan) + } catch { + | Under_Age => evan.firstName ++ " is too young to drive!" + } + +/*---------------------------------------------- + * Object + *---------------------------------------------- + * Objects are similar to Record types, but are less rigid + */ + +/* An object may be typed like a record but the property names are quoted */ +type surfaceComputer = { + "color": string, + "capacity": int, +} +let surfaceBook: surfaceComputer = { "color": "blue", "capacity": 512 } + +/* Objects don't require types */ +let hamster = { "color": "brown", "age": 2 } + +/* Object typing is structural, so you can have functions that accept any object with the required fields */ +let getAge = animal => animal["age"] +getAge(hamster) +getAge({ "name": "Fido", "color": "silver", "age": 3 }) +getAge({ "age": 5 }) + +/*---------------------------------------------- + * Module + *---------------------------------------------- + * Modules are used to organize your code and provide namespacing. + * Each file is a module by default + */ + +/* Create a module */ +module Staff = { + type role = + | Delivery + | Sales + | Other + type member = { + name: string, + role, + } + + let getRoleDirectionMessage = staff => + switch (staff.role) { + | Delivery => "Deliver it like you mean it!" + | Sales => "Sell it like only you can!" + | Other => "You're an important part of the team!" + } +} + +/* A module can be accessed with dot notation */ +let newEmployee: Staff.member = {name: "Laura", role: Staff.Delivery} + +/* Using the module name can be tiresome so the module's contents can be opened + into the current scope with `open` */ +open Staff + +let otherNewEmployee: member = {name: "Fred", role: Other} + +/* A module can be extended using the `include` keyword, include copies + the contents of the module into the scope of the new module */ +module SpecializedStaff = { + include Staff + + /* `member` is included so there's no need to reference it explicitly */ + let ceo: member = {name: "Reggie", role: Other} + + let getMeetingTime = staff => + switch (staff) { + | Other => 11_15 /* - : int = 1115 Underscores are for formatting only */ + | _ => 9_30 + } +} +``` + +## Further Reading + +- [Official ReScript Docs](https://rescript-lang.org/) +- [Try ReScript - Online Playground](https://rescript-lang.org/try) From b5f8ea76bc45fda775f1e6efe887e79d91e8447f Mon Sep 17 00:00:00 2001 From: Marko M <81194128+mmilivoj@users.noreply.github.com> Date: Mon, 13 May 2024 09:38:52 +0200 Subject: [PATCH 176/392] [java/*] Update obsolete link to "Thinking in Java" (#4365) --- de-de/java-de.html.markdown | 2 +- el-gr/java-gr.html.markdown | 2 +- fa-ir/java-fa.html.markdown | 2 +- fr-fr/java-fr.html.markdown | 2 +- id-id/java-id.html.markdown | 2 +- java.html.markdown | 2 +- pl-pl/java-pl.html.markdown | 2 +- uk-ua/java-ua.html.markdown | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/de-de/java-de.html.markdown b/de-de/java-de.html.markdown index e52087ec..be96a7e8 100644 --- a/de-de/java-de.html.markdown +++ b/de-de/java-de.html.markdown @@ -490,7 +490,7 @@ Für tiefergreifende Fragen ist Google der beste Startpunkt. * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) diff --git a/el-gr/java-gr.html.markdown b/el-gr/java-gr.html.markdown index df66a2a9..745b9537 100644 --- a/el-gr/java-gr.html.markdown +++ b/el-gr/java-gr.html.markdown @@ -850,7 +850,7 @@ public class EnumTest { * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) diff --git a/fa-ir/java-fa.html.markdown b/fa-ir/java-fa.html.markdown index a834afcd..6bc3a420 100644 --- a/fa-ir/java-fa.html.markdown +++ b/fa-ir/java-fa.html.markdown @@ -894,7 +894,7 @@ public class EnumTest { * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) diff --git a/fr-fr/java-fr.html.markdown b/fr-fr/java-fr.html.markdown index 3acbb46b..8e3192b1 100644 --- a/fr-fr/java-fr.html.markdown +++ b/fr-fr/java-fr.html.markdown @@ -931,7 +931,7 @@ n'hésitez pas à consulter Google pour trouver des exemples spécifiques. * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) diff --git a/id-id/java-id.html.markdown b/id-id/java-id.html.markdown index 600c4c56..2c29a407 100644 --- a/id-id/java-id.html.markdown +++ b/id-id/java-id.html.markdown @@ -793,7 +793,7 @@ Tip, trik, dan contoh lainnya dapat melakukan pencarian melalui Google atau mesi * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) diff --git a/java.html.markdown b/java.html.markdown index 7bf3fa0a..14664625 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1049,7 +1049,7 @@ The links provided here below are just to get an understanding of the topic, fee * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) diff --git a/pl-pl/java-pl.html.markdown b/pl-pl/java-pl.html.markdown index 0da449c5..3f11fede 100644 --- a/pl-pl/java-pl.html.markdown +++ b/pl-pl/java-pl.html.markdown @@ -1019,7 +1019,7 @@ Linki zamieszczone poniżej służą pomocą w zrozumieniu wybranego tematu, w r * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) diff --git a/uk-ua/java-ua.html.markdown b/uk-ua/java-ua.html.markdown index b96d9a48..8c88b211 100644 --- a/uk-ua/java-ua.html.markdown +++ b/uk-ua/java-ua.html.markdown @@ -776,7 +776,7 @@ public class EnumTest { * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) -* [Thinking in Java](http://www.mindview.net/Books/TIJ/) +* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) * [Objects First with Java](http://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) From 0fc242b833f57d4391b26bef31d23f09a9fcfab5 Mon Sep 17 00:00:00 2001 From: Eric Ampire <32017617+eric-ampire@users.noreply.github.com> Date: Mon, 13 May 2024 03:57:24 -0400 Subject: [PATCH 177/392] [kotlin/fr-fr] Kotlin French translation (#3952) --- fr-fr/kotlin.html-fr.markdown | 457 ++++++++++++++++++++++++++++++++++ 1 file changed, 457 insertions(+) create mode 100644 fr-fr/kotlin.html-fr.markdown diff --git a/fr-fr/kotlin.html-fr.markdown b/fr-fr/kotlin.html-fr.markdown new file mode 100644 index 00000000..10f67fc4 --- /dev/null +++ b/fr-fr/kotlin.html-fr.markdown @@ -0,0 +1,457 @@ +--- +language: kotlin +filename: LearnKotlin-fr.kt +lang: fr-fr +contributors: + - ["S Webber", "https://github.com/s-webber"] +translators: + - ["Eric Ampire", "https://github.com/eric-ampire"] +--- + +Kotlin est un langage de programmation à typage statique pour la JVM, Android et le +navigateur. Il est 100% interopérable avec Java. +[Pour en savoir plus, cliquez ici](https://kotlinlang.org/) + +```kotlin +// Les commentaires d'une seule ligne commencent par // +/* +Les commentaires de plusieurs lignes ressemblent à ceci. +*/ + +// Le mot-clé "package" fonctionne de la même manière qu'en Java. + package com.learnxinyminutes.kotlin + +/* +Le point d'entrée d'un programme Kotlin est une fonction appelée "main". +La fonction reçoit un tableau contenant tous les arguments de la ligne de commande. +Depuis Kotlin 1.3, la fonction "main" peut également être définie sans +tout paramètre. +*/ +fun main(args: Array) { + /* + La déclaration des valeurs se fait en utilisant soit "var" soit "val". + Les déclarations "val" ne peuvent pas être réaffectées, alors que les déclarations "vars" le peuvent. + */ + val fooVal = 10 // nous ne pouvons pas plus tard réaffecter fooVal à autre chose + var fooVar = 10 + fooVar = 20 // fooVar peut être réaffecté + + /* + Dans la plupart des cas, Kotlin peut déterminer quel est le type de variable, + afin de ne pas avoir à le préciser explicitement à chaque fois. + Nous pouvons déclarer explicitement le type d'une variable de cette manière : + */ + val foo: Int = 7 + + /* + Les chaînes de caractères peuvent être représentées de la même manière qu'en Java. + L'échappement se fait avec une barre oblique inversée. + */ + val fooString = "Ma chaine est là !" + val barString = "Imprimer sur une nouvelle ligne ? \nPas de problème !" + val bazString = "Vous voulez ajouter une tabulation ? \tPas de problème !" + println(fooString) + println(barString) + println(bazString) + + /* + Une chaîne brute est délimitée par une triple citation ("""). + Les chaînes de caractères brutes peuvent contenir des nouvelles lignes et tout autre caractère. + */ + val fooRawString = """ +fun helloWorld(val name : String) { + println("Bonjour, le monde !") +} +""" + println(fooRawString) + + /* + Les chaînes de caractères peuvent contenir des expressions modèles. + Une expression modèle commence par le signe du dollar ($). + */ + val fooTemplateString = "$fooString as ${fooString.length} caractères" + println(fooTemplateString) // => Ma chaine est là ! comporte 18 caractères + + /* + Pour qu'une variable soit considérée comme nulle, elle doit être explicitement spécifiée comme nulable. + Une variable peut être spécifiée comme nulle en ajoutant un ? à son type. + On peut accéder à une variable nulable en utilisant l'opérateur ? + Nous pouvons utiliser l'opérateur ?: pour spécifier une valeur alternative à utiliser + si une variable est nulle. + */ + var fooNullable: String? = "abc" + println(fooNullable?.length) // => 3 + println(fooNullable?.length ?: -1) // => 3 + fooNullable = null + println(fooNullable?.length) // => null + println(fooNullable?.length ?: -1) // => -1 + + /* + Les fonctions peuvent être déclarées en utilisant le mot-clé "fun". + Les arguments des fonctions sont spécifiés entre parenthèses après le nom de la fonction. + Les arguments de fonction peuvent éventuellement avoir une valeur par défaut. + Le type de retour de la fonction, si nécessaire, est spécifié après les arguments. + */ + fun hello(name: String = "world"): String { + return "Bonjour, $name!" + } + println(hello("foo")) // => Bonjour, foo! + println(hello(name = "bar")) // => Bonjour, bar! + println(hello()) // => Bonjour, le monde! + + /* + Un paramètre de fonction peut être marqué avec le mot-clé "vararg + pour permettre de passer un nombre variable d'arguments à la fonction. + */ + fun varargExample(vararg names: Int) { + println("L'argument comporte ${names.size} éléments.") + } + varargExample() // => L'argument a 0 éléments + varargExample(1) // => L'argument a 1 éléments + varargExample(1, 2, 3) // => L'argument comporte 3 éléments + + /* + Lorsqu'une fonction est constituée d'une seule expression, les parenthèses bouclées peuvent + être omis. Le corps est spécifié après le symbole =. + */ + fun odd(x: Int): Boolean = x % 2 == 1 + println(odd(6)) // => false + println(odd(7)) // => true + + // Si le type de retour peut être déduit, alors nous n'avons pas besoin de le préciser. + fun even(x: Int) = x % 2 == 0 + println(even(6)) // => true + println(even(7)) // => false + + // Les fonctions peuvent prendre des fonctions d'arguments et des fonctions de retour. + fun not(f: (Int) -> Boolean): (Int) -> Boolean { + return {n -> !f.invoke(n)} + } + // Les fonctions nommées peuvent être spécifiées comme arguments en utilisant l'opérateur :: . + val notOdd = not(::odd) + val notEven = not(::even) + // Les expressions lambda peuvent être spécifiées en tant qu'arguments. + val notZero = not {n -> n == 0} + /* + Si un lambda n'a qu'un seul paramètre + alors sa déclaration peut être omise (ainsi que le ->). + Le nom du paramètre unique sera "it". + */ + val notPositive = not {it > 0} + for (i in 0..4) { + println("${notOdd(i)} ${notEven(i)} ${notZero(i)} ${notPositive(i)}") + } + + // Le mot-clé "class" est utilisé pour déclarer les classes. + class ExampleClass(val x: Int) { + fun memberFunction(y: Int): Int { + return x + y + } + + infix fun infixMemberFunction(y: Int): Int { + return x * y + } + } + /* + Pour créer une nouvelle instance, nous appelons le constructeur. + Notez que Kotlin n'a pas de mot-clé "new" . + */ + val fooExampleClass = ExampleClass(7) + // Les fonctions des membres peuvent être appelées en utilisant la notation par points. + println(fooExampleClass.memberFunction(4)) // => 11 + /* + Si une fonction a été marquée avec le mot-clé "infix", elle peut être + appelé en utilisant la notation infixe. + */ + println(fooExampleClass infixMemberFunction 4) // => 28 + + /* + Les classes de données sont une façon concise de créer des classes qui ne contiennent que des données. + Les méthodes "hashCode"/"equals" et "toString" sont générées automatiquement. + */ + data class DataClassExample (val x: Int, val y: Int, val z: Int) + val fooData = DataClassExample(1, 2, 4) + println(fooData) // => DataClassExample(x=1, y=2, z=4) + + // Les classes de données ont une methode "copy". + val fooCopy = fooData.copy(y = 100) + println(fooCopy) // => DataClassExample(x=1, y=100, z=4) + + // Les objets peuvent être déstructurés en plusieurs variables. + val (a, b, c) = fooCopy + println("$a $b $c") // => 1 100 4 + + // La déstructuration en boucle "for" + for ((a, b, c) in listOf(fooData)) { + println("$a $b $c") // => 1 100 4 + } + + val mapData = mapOf("a" to 1, "b" to 2) + // Map.Entry est également déstructurable + for ((key, value) in mapData) { + println("$key -> $value") + } + + // La fonction "with" est similaire à la déclaration "with" de JavaScript. + data class MutableDataClassExample (var x: Int, var y: Int, var z: Int) + val fooMutableData = MutableDataClassExample(7, 4, 9) + with (fooMutableData) { + x -= 2 + y += 2 + z-- + } + println(fooMutableData) // => MutableDataClassExample(x=5, y=6, z=8) + + /* + Nous pouvons créer une liste en utilisant la fonction "listOf". + La liste sera immuable - les éléments ne peuvent être ajoutés ou supprimés. + */ + val fooList = listOf("a", "b", "c") + println(fooList.size) // => 3 + println(fooList.first()) // => a + println(fooList.last()) // => c + // Les éléments d'une liste sont accessibles par leur index. + println(fooList[1]) // => b + + // Une liste mutable peut être créée en utilisant la fonction "mutableListOf". + val fooMutableList = mutableListOf("a", "b", "c") + fooMutableList.add("d") + println(fooMutableList.last()) // => d + println(fooMutableList.size) // => 4 + + // Nous pouvons créer un ensemble en utilisant la fonction "setOf". + val fooSet = setOf("a", "b", "c") + println(fooSet.contains("a")) // => true + println(fooSet.contains("z")) // => false + + // Nous pouvons créer un map en utilisant la fonction "mapOf". + val fooMap = mapOf("a" to 8, "b" to 7, "c" to 9) + // Map values can be accessed by their key. + println(fooMap["a"]) // => 8 + + /* + Les séquences représentent des collections évaluées paresseusement. + Nous pouvons créer une séquence en utilisant la fonction "generateSequence". + */ + val fooSequence = generateSequence(1, { it + 1 }) + val x = fooSequence.take(10).toList() + println(x) // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] + + // Un exemple d'utilisation d'une séquence pour générer des nombres de Fibonacci : + fun fibonacciSequence(): Sequence { + var a = 0L + var b = 1L + + fun next(): Long { + val result = a + b + a = b + b = result + return a + } + + return generateSequence(::next) + } + val y = fibonacciSequence().take(10).toList() + println(y) // => [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] + + // Kotlin offre des fonctions d'ordre supérieur pour le travail avec les collections. + val z = (1..9).map {it * 3} + .filter {it < 20} + .groupBy {it % 2 == 0} + .mapKeys {if (it.key) "even" else "odd"} + println(z) // => {odd=[3, 9, 15], even=[6, 12, 18]} + + // Une boucle "for" peut être utilisée avec tout ce qui fournit un itérateur. + for (c in "hello") { + println(c) + } + + // Les boucles "while" fonctionnent de la même manière que les autres langues. + var ctr = 0 + while (ctr < 5) { + println(ctr) + ctr++ + } + do { + println(ctr) + ctr++ + } while (ctr < 10) + + /* + "if" peut être utilisé comme une expression qui renvoie une valeur. + Pour cette raison, l'opérateur ternaire ?: n'est pas nécessaire dans Kotlin. + */ + val num = 5 + val message = if (num % 2 == 0) "even" else "odd" + println("$num is $message") // => 5 is odd + + // Le terme "when" peut être utilisé comme alternative aux chaînes "if-else if". + val i = 10 + when { + i < 7 -> println("first block") + fooString.startsWith("hello") -> println("second block") + else -> println("else block") + } + + // "when" peut être utilisé avec un argument. + when (i) { + 0, 21 -> println("0 or 21") + in 1..20 -> println("in the range 1 to 20") + else -> println("none of the above") + } + + // "when" peut être utilisé comme une fonction qui renvoie une valeur. + var result = when (i) { + 0, 21 -> "0 or 21" + in 1..20 -> "in the range 1 to 20" + else -> "none of the above" + } + println(result) + + /* + Nous pouvons vérifier si un objet est d'un type particulier en utilisant l'opérateur "is". + Si un objet passe avec succès une vérification de type, il peut être utilisé comme ce type sans + en le diffusant explicitement. + */ + fun smartCastExample(x: Any) : Boolean { + if (x is Boolean) { + // x est automatiquement converti en booléen + return x + } else if (x is Int) { + // x est automatiquement converti en Int + return x > 0 + } else if (x is String) { + // x est automatiquement converti en String + return x.isNotEmpty() + } else { + return false + } + } + println(smartCastExample("Bonjour, le monde !")) // => true + println(smartCastExample("")) // => false + println(smartCastExample(5)) // => true + println(smartCastExample(0)) // => false + println(smartCastExample(true)) // => true + + // Le Smartcast fonctionne également avec le bloc when + fun smartCastWhenExample(x: Any) = when (x) { + is Boolean -> x + is Int -> x > 0 + is String -> x.isNotEmpty() + else -> false + } + + /* + Les extensions sont un moyen d'ajouter de nouvelles fonctionnalités à une classe. + C'est similaire aux méthodes d'extension C#. + */ + fun String.remove(c: Char): String { + return this.filter {it != c} + } + println("Hello, world!".remove('l')) // => Heo, word! +} + +// Les classes Enum sont similaires aux types Java enum. +enum class EnumExample { + A, B, C // Les constantes Enum sont séparées par des virgules. +} +fun printEnum() = println(EnumExample.A) // => A + +// Puisque chaque enum est une instance de la classe enum, ils peuvent être initialisés comme : +enum class EnumExample(val value: Int) { + A(value = 1), + B(value = 2), + C(value = 3) +} +fun printProperty() = println(EnumExample.A.value) // => 1 + +// Chaque énum a des propriétés pour obtenir son nom et son ordinal (position) dans la déclaration de classe de l'énum : +fun printName() = println(EnumExample.A.name) // => A +fun printPosition() = println(EnumExample.A.ordinal) // => 0 + +/* +Le mot-clé "objet" peut être utilisé pour créer des objets singleton. +On ne peut pas l'instancier mais on peut se référer à son instance unique par son nom. +Cela est similaire aux objets singleton de Scala. +*/ +object ObjectExample { + fun hello(): String { + return "Bonjour" + } + + override fun toString(): String { + return "Bonjour, c'est moi, ${ObjectExample::class.simpleName}" + } +} + + +fun useSingletonObject() { + println(ObjectExample.hello()) // => hello + // Dans Kotlin, "Any" est la racine de la hiérarchie des classes, tout comme "Object" l'est dans Java + val someRef: Any = ObjectExample + println(someRef) // => Bonjour, c'est moi, ObjectExample +} + + +/* L'opérateur d'assertion non nulle ( !!) convertit toute valeur en un type non nul et + lance une exception si la valeur est nulle. +*/ +var b: String? = "abc" +val l = b!!.length + +data class Counter(var value: Int) { + // surcharge Counter += Int + operator fun plusAssign(increment: Int) { + this.value += increment + } + + // surcharge Counter++ et ++Counter + operator fun inc() = Counter(value + 1) + + // surcharge Counter + Counter + operator fun plus(other: Counter) = Counter(this.value + other.value) + + // surcharge Counter * Counter + operator fun times(other: Counter) = Counter(this.value * other.value) + + // surcharge Counter * Int + operator fun times(value: Int) = Counter(this.value * value) + + // surcharge Counter dans Counter + operator fun contains(other: Counter) = other.value == this.value + + // surcharge Counter[Int] = Int + operator fun set(index: Int, value: Int) { + this.value = index + value + } + + // surcharge Counter instance invocation + operator fun invoke() = println("The value of the counter is $value") + +} +/* Vous pouvez également surcharger les opérateurs par des méthodes d'extension */ +// surcharge -Counter +operator fun Counter.unaryMinus() = Counter(-this.value) + +fun operatorOverloadingDemo() { + var counter1 = Counter(0) + var counter2 = Counter(5) + counter1 += 7 + println(counter1) // => Counter(value=7) + println(counter1 + counter2) // => Counter(value=12) + println(counter1 * counter2) // => Counter(value=35) + println(counter2 * 2) // => Counter(value=10) + println(counter1 in Counter(5)) // => false + println(counter1 in Counter(7)) // => true + counter1[26] = 10 + println(counter1) // => Counter(value=36) + counter1() // => La valeur est 36 + println(-counter2) // => Counter(value=-5) +} +``` + +### Lectures complémentaires + +* [Kotlin tutorials](https://kotlinlang.org/docs/tutorials/) +* [Try Kotlin in your browser](https://play.kotlinlang.org/) +* [A list of Kotlin resources](http://kotlin.link/) From 0659b70da6289d190d46c7937768015bfca88b62 Mon Sep 17 00:00:00 2001 From: Javier Vivanco Date: Mon, 13 May 2024 05:04:38 -0300 Subject: [PATCH 178/392] [racket/es] Parameters (#4071) --- es-es/racket-es.html.markdown | 66 ++++++++++++++++++++++++++++++----- 1 file changed, 58 insertions(+), 8 deletions(-) diff --git a/es-es/racket-es.html.markdown b/es-es/racket-es.html.markdown index a49509c7..58084aa8 100644 --- a/es-es/racket-es.html.markdown +++ b/es-es/racket-es.html.markdown @@ -46,7 +46,7 @@ Racket es un lenguaje de propósito general, multiparadigma que hace parte de la 1+2i ; numeros complejos ;; La aplicación de funciones es escrita de la siguiente forma: (f x y z ...) -;; donde f es una función y “x, y, z” son sus operandos +;; donde f es una función y “x, y, z” son sus operandos ;; Si quieres crear una lista de literales debes agregar ' al inicio ;; para que no sean evaluados '(+ 1 2) ; => (+ 1 2) @@ -283,7 +283,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no 'd' (= 3 3.0) ; => #t (= 2 1) ; => #f -;; 'eq?' retorna #t si 2 argumentos refieren al mismo objeto en memoria +;; 'eq?' retorna #t si 2 argumentos refieren al mismo objeto en memoria ;; #f de lo contrario. ;; En otras palabras, es una simple comparación de punteros. (eq? '() '()) ; => #t, Debido a que existe solo una lista vacia en memoria @@ -318,7 +318,7 @@ m ; => '#hash((b . 2) (a . 1) (c . 3)) <-- no 'd' (eqv? (string-append "foo" "bar") (string-append "foo" "bar")) ; => #f ;; 'equal?' permite comparar los siguientes tipos de datos: -;; strings, byte strings, pairs, mutable pairs, vectors, boxes, +;; strings, byte strings, pairs, mutable pairs, vectors, boxes, ;; hash tables, and inspectable estructuras. ;; para otros tipos de datos, 'equal?' y 'eqv?' devuelven el mismo resultado. (equal? 3 3.0) ; => #f @@ -515,7 +515,7 @@ vec ; => #(1 2 3 4) (show " | ~a | " n #\space) (show "---~a---" n #\-)) - (define (show fmt n ch) ; función interna + (define (show fmt n ch) ; función interna (printf fmt (make-string n ch)) (newline))) @@ -672,12 +672,62 @@ vec ; => #(1 2 3 4) (call-with-input-file "/tmp/tmp.txt" (λ (in-port) (displayln (read-line in-port)))) + + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; 12. Parametros +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +;; Racket tiene el concepto de "parameter" +;; El cual es un tipo de funcion similar un variable global entre modulos + +;; Defino x y lo cambio localmente +(define x 42) +(set! x 43) +x ; 43 + +;; Ahora x es parte un modulo +(module mod racket + (provide x-mod) + (define x-mod 42)) +;; incluyo x e intento cambiarlo +(require 'mod) +x-mod ; 42 +(set! x-mod 43) ; error: cannot mutate x +;; Aca es donde tiene utilidad el uso de parametros +(module mod-param racket + (provide my-param) + (define my-param (make-parameter 42))) ;; creo un parametro con (make-parameter ) + +(require 'mod-param) +(my-param) ; 42 +(my-param 43) ;; ahora el valor x es cambiado para todo el ambiente del modulo donde se esta ejecutando +(my-param) ; 43 +;; Tambien puedo asignar un valor a un parametro en un ambiente local simil let +;; devuelve el ultimo valor del BODY (parameterize ([ID EXPR] BODY ... ) +(parameterize + ([ my-param "un valor de tipo distinto"]) + (displayln (my-param))) +"un valor de tipo distinto" ;; x cambio solo el ambiente local de parameterize +(my-param) ;; 43 +;; mi modulo tiene un funcion con parametros que cambia su comportamiento según el parametro +(module my-mod racket + (provide my-add verbose) + (define verbose (make-parameter #f)) ;; Parametro + (define (my-add a b ) ;; funcion + (define result (+ a b)) + (when (verbose) (display (format "verbose: (my-add ~a ~a) => ~a~n" a b result))) + result)) ;; creo un parametro con (make-parameter ) +(require 'my-mod) +(my-add 3 4) +;; 7 +(verbose #f) +(my-add 3 4) +;; 7 +(+ 1 (parameterize ([ verbose #t]) (my-add 3 4 ))) +;; 8 ``` ## Mas información ¿Quieres saber mas? Prueba en [Empezando con Racket](http://docs.racket-lang.org/getting-started/) - - - - From 05399fe6cc0c5bd0e882941bcf9fadfae752e14a Mon Sep 17 00:00:00 2001 From: Conor Flynn Date: Mon, 13 May 2024 10:08:49 +0200 Subject: [PATCH 179/392] [vim/en] Replace Command Mode with Normal Mode (#4563) --- vim.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/vim.html.markdown b/vim.html.markdown index b3509934..d120b944 100644 --- a/vim.html.markdown +++ b/vim.html.markdown @@ -98,17 +98,17 @@ that aims to make getting started with vim more approachable! Vim is based on the concept on **modes**. -- Command Mode - vim starts up in this mode, used to navigate and write commands -- Insert Mode - used to make changes in your file -- Visual Mode - used to highlight text and do operations to them -- Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands +- Normal Mode - vim starts up in this mode, used to navigate and write commands +- Insert Mode - used to make changes in your file +- Visual Mode - used to highlight text and do operations to them +- Ex Mode - used to drop down to the bottom with the ':' prompt to enter commands ``` i # Puts vim into insert mode, before the cursor position a # Puts vim into insert mode, after the cursor position v # Puts vim into visual mode : # Puts vim into ex mode - # 'Escapes' from whichever mode you're in, into Command mode + # 'Escapes' from whichever mode you're in, into Normal mode # Copying and pasting text # Operations use the vim register by default From 46a6e0be69fa97ba5837cdbadd5d3d9339660571 Mon Sep 17 00:00:00 2001 From: Cendy <57063107+CLOEI@users.noreply.github.com> Date: Mon, 13 May 2024 15:16:17 +0700 Subject: [PATCH 180/392] [php/id] Fixed typos and updated the translation (#4656) --- id-id/php-id.html.markdown | 51 +++++++++++++++++++++++++++----------- 1 file changed, 37 insertions(+), 14 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 48afebc4..45306475 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -6,6 +6,7 @@ contributors: filename: learnphp-id.php translators: - ["Ahmad Zafrullah", "https://github.com/23Pstars"] + - ["Cendy", "https://cendy.co"] lang: id-id --- @@ -24,7 +25,7 @@ Dokumen ini menjelaskan tentang PHP5 keatas. membuat komentar untuk banyak-baris sekaligus. */ -// Gunakan "echo" or "print" untuk menampilkan sesuatu +// Gunakan "echo" atau "print" untuk menampilkan sesuatu print('Halo '); // Menampilkan "Halo " tanpa baris baru // () boleh tidak digunakan dalam menggunakan "print" dan "echo" @@ -41,9 +42,9 @@ Halo Dunia, lagi! * Tipe Data & Variabel */ -// Variabel diawali dengan simnbol $. +// Variabel diawali dengan simbol $. // Nama variabel yang benar diawali dengan huruf atau garis-bawah, -// diikuti dengan beberapa huruf, angka, dan garis-bawah lainnya. +// diikuti dengan beberapa huruf, angka, ataupun garis bawah. // Nilai Boolean adalah case-insensitive $boolean = true; // atau TRUE atau True @@ -74,14 +75,14 @@ $pembagian = 2 / 1; // 2 // Aritmatika singkat $angka = 0; $angka += 1; // Menjumlahkan $angka dengan 1 -echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah ditampilkan) -echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum ditampilkan) +echo $angka++; // Menampilkan 1 (dijumlahkan dengan 1 setelah dievaluasi) +echo ++$angka; // Menampilkan 3 (dijumlahkan dengan 1 sebelum dievaluasi) $angka /= $float; // Membagi dan menyimpan hasil pembagian pada $angka; // String biasanya diawali dan ditutup dengan petik satu. $sgl_quotes = '$String'; // => '$String' -// Hindari menggunakan petik dua kecuali menyertakan variabel lain +// Hindari menggunakan petik dua kecuali untuk menyertakan variabel lain $dbl_quotes = "Ini adalah $sgl_quotes."; // => 'Ini adalah $String.' // Karakter khusus hanya berlaku pada petik dua @@ -103,10 +104,10 @@ Banyak baris $sgl_quotes END; -// Menyambung string dapat dilakukan menggunakan . +// Menyambungkan String dapat dilakukan dengan menggunakan . echo 'String ini ' . 'tersambung'; -// String dapat dijadikan parameter pada "echo" +// Beberapa String dapat dijadikan sebagai parameter untuk "echo" echo 'Banyak', 'Parameter', 'String'; // Menampilkan 'BanyakParameterString' @@ -118,7 +119,7 @@ echo 'Banyak', 'Parameter', 'String'; // Menampilkan 'BanyakParameterString' // dan tidak bisa diganti/rubah selama program berjalan! // Nama konstan yang benar diawali dengan huruf dan garis-bawah, -// diikuti dengan beberapa huruf, angka, atau garis-bawah. +// diikuti dengan beberapa huruf, angka, ataupun garis-bawah. define("FOO", "sesuatu"); // Mengakses konstan memungkinkan untuk dapat dipanggil tanpa menggunakan simbol $ @@ -207,7 +208,7 @@ $b = '0'; $c = '1'; $d = '1'; -// menegaskan lemparan sebuah peringatan jika pernyataan tidak benar +// assert akan melempar sebuah peringatan jika pernyataan tidak benar // Perbandingan berikut akan selalu benar, meskipun memiliki tipe yang berbeda. assert($a == $b); // kesamaan @@ -520,8 +521,8 @@ class KelasSaya // Properti harus mendeklarasikan hak aksesnya public $properti = 'publik'; public $PropertiInstansi; - protected $variabel = 'terlindungi'; // Dapat diakses dari kelas itu sendiri dan kelas turunannya - private $variabel = 'tersembunyi'; // Hanya dapat diakses dari kelas itu sendiri + protected $terlindungi = 'terlindungi'; // Dapat diakses dari kelas itu sendiri dan kelas turunannya + private $terprivat = 'tersembunyi'; // Hanya dapat diakses dari kelas itu sendiri // Membuat konstruktor dengan perintah __construct public function __construct($PropertiInstansi) { @@ -540,6 +541,21 @@ class KelasSaya { } + // Metode ajaib + + // apa yang dilakukan jika Objek diperlakukan sebagai String + public function __toString() + { + return $properti; + } + + // Berlawanan dari __construct() + // Dipanggil saat objek tidak lagi di referensi + public function __destruct() + { + print "Destroying"; + } + /* * Deklarasi properti atau method pada kelas sebagai statis membuat properti atau method tersebut * dapat diakses tanpa melakukan instansiasi kelas. Properti statis tidak dapat diakses melalui @@ -567,12 +583,19 @@ echo $kelas_saya->properti; // => "publik" echo $kelas_saya->propertiInstansi; // => "Sebuah properti instansi" $kelas_saya->methodSaya(); // => "KelasSaya" +// Operasi Nullsafe semenjak PHP 8 +// Kamu bisa menggunakan ini jika kamu tidak yakin apakah $kelas_saya memiliki sebuah properti/metode +// Ini bisa digunakan bersamaan dengan operator nullish coalesce untuk memastikan value +echo $kelas_saya->properti_invalid // Akan muncul sebuah error +echo $kelas_saya?->properti_invalid // => NULL +echo $kelas_saya?->properti_invalid ?? "publik" // => "publik" + // Menurunkan kelas menggunakan kata kunci "extends" class KelasSayaLainnya extends KelasSaya { function tampilkanPropertiTerlindungi() { - echo $this->properti; + echo $this->terlindungi; } // "override" terhadap sebuah method @@ -757,7 +780,7 @@ class KelasAnak extends KelasInduk { } } -KelasAnak::tes(); +KelasAnak::coba(); /* Ini adalah KelasInduk Tapi ini adalah KelasAnak From 00a1071fe45890840cdb7e989964ec2b9eefe6b2 Mon Sep 17 00:00:00 2001 From: Jarod Date: Mon, 13 May 2024 18:19:04 +1000 Subject: [PATCH 181/392] [rust/en] link to A half-hour to learn Rust (#4379) --- rust.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rust.html.markdown b/rust.html.markdown index be0b0bc9..421124be 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -344,6 +344,10 @@ fn main() { ## Further reading +For a deeper-yet-still-fast explanation into Rust and its symbols/keywords, the +[half-hour to learn Rust](https://fasterthanli.me/articles/a-half-hour-to-learn-rust) +article by Fasterthanlime explains (almost) everything in a clear and concise way! + There’s a lot more to Rust—this is just the basics of Rust so you can understand the most important things. To learn more about Rust, read [The Rust Programming Language](http://doc.rust-lang.org/book/index.html) and check out the From 094f083fbcb36c1281b4d7fae149dff1afc0685d Mon Sep 17 00:00:00 2001 From: Anuj Shah Date: Mon, 13 May 2024 13:55:24 +0530 Subject: [PATCH 182/392] [linker/en] translate from Russian (#3971) --- linker.html.markdown | 196 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 195 insertions(+), 1 deletion(-) diff --git a/linker.html.markdown b/linker.html.markdown index 42839e05..40ad7020 100644 --- a/linker.html.markdown +++ b/linker.html.markdown @@ -3,7 +3,201 @@ category: tool tool: linker contributors: - ["Alexander Kovalchuk", "https://github.com/Zamuhrishka"] +translators: + - ["Anuj Shah", "https://github.com/ShahAnuj2610"] --- -This article is available in [Russian](https://learnxinyminutes.com/docs/ru-ru/linker-ru/). +## Basic concepts and definitions +**Position counter** - the linker has a special variable +"." (dot) always contains the current output position. + +## Functions + +**ADDR (section)** - returns the absolute address of the specified section. However +this section must be defined before using the ADDR function. + +**ALIGN (exp)** - returns the value of the position counter aligned to the border +following the exp expression. + +**SIZEOF (section)** - returns the size of the section in bytes. + +**FILL (param)** - defines the fill pattern for the current section. All +other unspecified regions within the section are filled with the value indicated +in function argument. + +**KEEP (param)** - used to mark param as fatal. + +**ENTRY (func)** - defines the function that will be the entry point +into the program. + +```bash +# Determine the entry point to the program +ENTRY(Reset_Handler) + +# Define a variable that contains the address of the top of the stack +_estack = 0x20020000; +# Define a variable that contains a heap size value +_Min_Heap_Size = 0x200; +# Define a variable that contains the value of the stack size +_Min_Stack_Size = 0x400; + +# Description of the memory card available for this processor +# MEMORY +# { +#MEMORY_DOMAIN_NAME (access rights): ORIGIN = START_ADDRESS, LENGTH = SIZE +# } +# In our example, the controller contains three memory areas: +# RAM - starts with the address 0x20000000 and takes 128 KB; +# CCMRAM - starts with the address 0x10000000 and occupies 64 KB; +# FLASH - starts with the address 0x8000000; takes 1024 Kb; +# Moreover, RAM memory access for reading, writing and execution. +# CCMRAM memory is read-write only. +# FLASH memory is available for reading and execution. +MEMORY +{ + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 128K + CCMRAM (rw) : ORIGIN = 0x10000000, LENGTH = 64K + FLASH (rx) : ORIGIN = 0x8000000, LENGTH = 1024K +} + +# We describe output sections +SECTIONS +{ + # The first section contains a table of interrupt vectors + .isr_vector : + { + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # There is an option --gc-sections, which allows you to collect garbage from unused + # input sections. And if there are sections that the garbage collector should not touch, + # you need to specify them as an argument to the KEEP () function (analogue of the keyword + # volatile). + # The entry (* (. Isr_vector)) means the .isr_vector sections in all object files. Because + # appeal to the section in general terms looks like this: (FILE_NAME (SECTION_NAME)) + KEEP(*(.isr_vector)) + + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # The expression "> MEMORY AREA" indicates which area of ​​memory will be placed + # this section. In our section, the .isr_vector section will be located in FLASH memory. + } >FLASH + +# TOTAL: The .isr_vector section that contains the table of interrupt vectors is aligned +# on the border of 4 bytes, marked as inaccessible to the garbage collector and placed at the beginning +# FLASH microcontroller memory. + + # The second section contains the program code. + .text : + { + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # We indicate that in this section the .text areas of all + # object files + *(.text) + *(.text*) + + # Protect the .init and .fini sections from the garbage collector + KEEP (*(.init)) + KEEP (*(.fini)) + + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # The variable _etext is defined, which stores the address of the end of the .text section and which + # may be available in the source code of the program through the announcement + # volaile unsigned int extern _etext; + _etext = .; + } >FLASH + +# TOTAL: The .text section that contains the program code is aligned on the border of 4 bytes, +# includes: all sections with program code in all object files and protected +# from the garbage collector of the .init and .fini sections in all object files, located in FLASH +# microcontroller memory immediately after the table of vectors. +# The text, .init, and .fini sections. are located in memory in the order in which they +# declared in the script. + + # The third section contains constant data. + .rodata : + { + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # We indicate that in this section areas .rodata will be stored + # object files + *(.rodata) + *(.rodata*) + + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + } >FLASH + + # Save the absolute address of the .data section in the _sidata variable + _sidata = LOADADDR(.data); + + # The fourth section contains initialized variables. + .data : + { + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # Save the address of the current position (beginning of the section) in the variable _sdata + _sdata = .; + + # We indicate that in this section the .data areas of all + # объектных файлов + *(.data) + *(.data*) + + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # Save the address of the current position (end of section) in the variable _sdata + _edata = .; + + # AT function indicates that this sector is stored in one memory area + # (in our case, FLASH), and it will be executed from another area of ​​memory (in our case, RAM). + # There are two types of addresses: + # * VMA (Virtual memory address) - this is the run-time address at which the compiler expects + # see data. + # * LMA (Load memory address) is the address at which the linker stores data. + + #Startup must code to copy the .data section from the LMA addresses to the VMA addresses. + + } >RAM AT> FLASH + + # The fifth section contains zero-initialized variables. + .bss : + { + # Save the address of the current position (beginning of the section) in the variable _sbss and __bss_start__ + _sbss = .; + __bss_start__ = _sbss; + + # We indicate that in this section the .bss areas of all + # object files + *(.bss) + *(.bss*) + + # Align the current position to the border of 4 bytes. + . = ALIGN(4); + + # Save the address of the current position (beginning of the section) in the variable _ebss and __bss_end__ + _ebss = .; + __bss_end__ = _ebss; + } >RAM + + # The sixth section contains a bunch and a stack. It is located at the very end of RAM. + ._user_heap_stack : + { + . = ALIGN(4); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(4); + } >RAM +} +``` From ffe967e1ea8e916caf5a5bff810e3b7ae25ccb8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20H=C3=A4rtl?= Date: Mon, 13 May 2024 10:38:50 +0200 Subject: [PATCH 183/392] [kotlin/en] Parentheses can be omitted for single lambda args (#4708) --- kotlin.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index a6fac518..48abce3a 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -127,7 +127,10 @@ fun helloWorld(val name : String) { // Named functions can be specified as arguments using the :: operator. val notOdd = not(::odd) val notEven = not(::even) - // Lambda expressions can be specified as arguments. + /* + Lambda expressions can be specified as arguments. + If it's the only argument parentheses can be omitted. + */ val notZero = not {n -> n == 0} /* If a lambda has only one parameter From 5f0454566c11087f18b706fdd000bb7a760b94de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Adri=C3=A1n=20Arroyo=20Calle?= Date: Mon, 13 May 2024 10:50:09 +0200 Subject: [PATCH 184/392] [logtalk/es] Add Logtalk in Spanish (#4329) --- es-es/logtalk-es.html.markdown | 261 +++++++++++++++++++++++++++++++++ 1 file changed, 261 insertions(+) create mode 100644 es-es/logtalk-es.html.markdown diff --git a/es-es/logtalk-es.html.markdown b/es-es/logtalk-es.html.markdown new file mode 100644 index 00000000..0bf110ab --- /dev/null +++ b/es-es/logtalk-es.html.markdown @@ -0,0 +1,261 @@ +--- +language: Logtalk +filename: learnlogtalk.lgt +contributors: + - ["Paulo Moura", "http://github.com/pmoura"] + - ["Adrián Arroyo Calle", "https://adrianistan.eu"] +lang: es-es +--- + +Logtalk nació en 1998 debido a los problemas de Prolog al escribir aplicaciones grandes. Diseñado por Paulo Moura, se trata de acercar Smalltalk y Prolog. De este modo el elemento fundamental de Logtalk serán los objetos, no las clases. A través de objetos podremos hacer clases si es lo que deseamos, o podemos usarlos como prototipos. Logtalk se ejecuta por encima de un sistema Prolog, sobre todo aquellos que implementen el estándar ISO Prolog. Actualmente Logtalk soporta: B-Prolog, Ciao Prolog, CxProlog, ECLiPSe, GNU Prolog, JIProlog, LVM, Quintus Prolog, Scryer Prolog, SICStus Prolog, SWI Prolog, Tau Prolog, Trealla Prolog, XSB y YAP. El código 100% Logtalk debería ser portable entre estos sistemas. + +Podemos instalar Logtalk desde [logtalk.org](https://logtalk.org/). + +En Logtalk existen tres tipos de entidades: objetos, protocolos y categorías. + +# Objetos + +El elemento fundamental de Logtalk es el objeto. Veremos que casi todo en Logtalk son objetos. Estos objetos no tienen estado ya que son puramente declarativos. Con los objetos podemos construir jerarquías tipo prototipo (ideal para objetos únicos) y tipo clase (ideal para objetos de los que se harán muchos). + +```logtalk +:- object(python). + + :- public(say_creator/0). + say_creator :- + write('Created by: Guido van Rossum'),nl. + +:- end_object. +``` + +Este código crea un objeto llamado _python_ con un predicado o método público, llamado _say\_creator_ con aridad 0. El predicado en sí lo que hace es imprimir por pantalla un texto. Lo vamos a guardar en un fichero llamado langs.lgt (lgt es la extensión de Logtalk). + +Vamos a ejecutarlo. Para ello, lanzamos el comando de Logtalk de nuestro Prolog, por ejemplo, en Scryer Prolog, es _scryerlgt_. Si usas SWI Prolog, es _swilgt_. Si todo va bien, verás una terminal similar a la de Prolog. Una vez allí, cargamos el fichero con _logtalk\_load_. + +```logtalk +?- logtalk_load('langs.lgt'). +``` + +Si todo va bien, ahora podremos mandar un mensaje al objeto python. + +```logtalk +?- python::say_creator. +Creator: Guido van Rossum + true. +``` + +Si no existe predicado en el objeto o si la visibilidad del método no lo permite, el envío falla. Se podría decir mucho de los mensajes como que emiten eventos, se puede hacer broadcasting, etc pero esto es más avanzado. + +Los objetos pueden: _implementar_ protocolos, _importar_ categorías, _extender_ otros objetos, _instanciar_ un objeto (clase) y _especializar_ otro objeto (clase). Las jerarquías de objetos se pueden realizar mediante extensiones (prototipos) o mediante instancias y especializaciones (clases). + +Por ejemplo, un objeto que _extienda_ otro se haría así: + +```logtalk +:- object(animal). + + :- public(run/0). + run :- + write('Animal is running'),nl. + +:- end_object. + +:- object(dog, extends(animal)). + + :- public(sleep/0). + sleep :- + write('Dog is sleeping'),nl. +:- end_object. +``` + +Si cargamos el fichero, veremos que el objeto animal tiene solo el método run, mientras que dog tiene el método run y sleep. + +Aquí podemos introducir también las otras dos formas de mandar un mensaje. Con _::_ podemos mandar un mensaje al mismo objeto en el que estamos. Y con _^^_ podemos mandar un mensaje al superobjeto (es decir, del que estamos extendiendo). + +```logtalk +:- object(animal). + + :- public(run/0). + run :- + write('Animal is running'),nl. + +:- end_object. + +:- object(dog, extends(animal)). + + :- public(run/0). + run :- + write('Dog is running'),nl, + ^^run. + + :- public(sleep/0). + sleep :- + write('Dog is sleeping'),nl. + + :- public(run_and_sleep/0). + run_and_sleep :- + ::run, + ::sleep. +:- end_object. +``` + +Al ejecutar _dog::run_and_sleep/0_ obtendremos: + +``` +Dog is running +Animal is running +Dog is sleeping +``` + +Adicionalmente podemos usar _self/1_ para obtener una referencia al objeto actual. _run\_and\_sleep/0_ puede escribirse también así: + +```logtalk + run_and_sleep :- + self(Self), + Self::run, + Self::sleep. +``` + +## Crear objetos de forma dinámica + +Si has programado en otros lenguaje OOP quizá te esté extrañando que todos los objetos existan desde el principio en Logtalk. Afortunadamente, esto era porque no habíamos llegado todavía a la parte donde se crean de forma dinámica. Esto se hace mediante el predicado _create\_object/4_. + +El primer argumento será la variable o el nombre del objeto. Seguidamente irán las relaciones. En tercer lugar las directivas (ahora las vemos pero básicamente public, private, info,...) y en cuarto lugar las cláusulas. + +Por ejemplo, estos dos códigos son equivalentes: + +```logtalk +?- create_object(foo, [extends(bar)], [public(foo/1)], [foo(1), foo(2)]). + +%%%% + +:- object(foo, extends(bar)). + + :- dynamic. + + :- public(foo/1). + foo(1). + foo(2). + +:- end_object. +``` + +Lo normal es dejar la creación de objetos dinámicos en un objeto prototito o en una metaclase. + +Los objetos dinámicos se pueden borrar con _abolish\_object/1_. + +## Objetos paramétricos + +Existen unos objetos algo diferentes, los objetos paramétricos. Son objetos cuyo identificador no es un átomo sino un término compuesto de Prolog. De este modo los propios objetos cargan con información en su definición de nombre. + +```logtalk +:- object(ruby(_Creator)). + + :- public(say_creator/0). + say_creator :- + write('Created by: '), + parameter(1, Creator), + write(Creator),nl. + +:- end_object. +``` + +Y lo tendremos que ejecutar de esta forma: _ruby('Matz')::say\_creator._. Los objetos paramétricos también pueden usar _this/1_ y la sintaxis de doble underscore (\_Creator\_). Pero como siempre, para estas cosas extra, lo recomendable es mirar el Logtalk Handbook. + +# Protocolos + +Lo siguiente dentro de Logtalk son los protocolos. Los protocolos permiten separar la interfaz de la implementación. Los protocolos solo incluyen las declaraciones de los predicados, pero no su lógica. + +```logtalk +:- protocol(langp). + + :- public(say_creator/0). + +:- end_protocol. + +:- object(python, implements(langp)). + + say_creator :- + write('Created by: Guido van Rossum'),nl. + +:- end_object. +``` + +Ahora definimos un protocolo llamado langp, que el objeto python implementa. Ahora ya no necesitamos incluir la directiva de visibilidad en el objeto ya que esa forma parte de la interfaz al exterior del objeto. + +# Categorías + +Las categorías son unidades de código reutilizables. Podemos pensar en ellos como partes de un objeto que se pueden añadir a otros objetos. + +```logtalk +:- category(reverse_creator(_Creator_)). + + :- uses(list, [reverse/2]). + + :- public(reverse_creator/1). + reverse_creator(Reversed) :- + reverse(_Creator_, Reversed). + +:- end_category. + +:- object(ruby(CreatorParam), implements(langp), imports(reverse_creator(CreatorParam))). + + say_creator :- + write('Created by: '), + parameter(1, Creator), + write(Creator),nl. + +:- end_object. +``` + +En este ejemplo, vamos a tener una categoría (paramétrica) y vamos a importarlo desde nuestro objeto paramétrico. Así podemos ver como los objetos paramétricos se pueden pasar los parámetros entre sí. Además, en el ejemplo se usa la directiva use, que nos permite "importar" ciertos predicados de algunos objetos (en este caso del objeto list) para no tener que escribir la sintaxis larga de mandar mensaje. + +Para que esto funcione, vamos a tener que cargar la librería con el objeto list en Logtalk primero. + +```logtalk +?- logtalk_load(types(loader)). + .... +?- logtalk_load('langs.lgt'). + .... +?- ruby("Matz")::reverse_creator(X). + X = "ztaM". +``` + +Esto nos lleva a la pregunta de, ¿hay alguna forma de organizar los proyectos en Logtalk? + +# Estructura proyecto Logtalk + +Por norma general un proyecto Logtalk consta de archivos lgt. Hay dos especiales, loader.lgt y tester.lgt. + +loader.lgt deberá contener todo lo necesario para cargar la aplicación, normalmente cargar todos los ficheros y librerías en el orden correcto. + +```logtalk +:- initialization(( + logtalk_load(sets(loader)), + logtalk_load(meta(loader)), + logtalk_load(app) +)). +``` + +Este es un ejemplo de fichero loader, que carga las librerías sets, meta y el fichero app.lgt. + +El fichero tester.lgt es igual, pero deberá incluir una llamada a ejecutar los tests de lgtUnit. lgtUnit es el framework de testing de Logtalk, muy interesante pero del que hablaré en otro artículo. + +# Lambdas y más + +Logtalk incluye predicados lambda, es decir, predicados definidos sobre un metapredicado. + +```logtalk +?- meta::map([X, Y]>>(Y is 2*X), [1,2,3], Ys). + Ys = [2,4,6]. +``` + +En este caso, el predicado lambda es equivalente al predicado: + +```logtalk +times2(X, Y) :- Y is 2 * X. +``` + +Pero sin tener que haber definido un nombre ni ubicarlo en otro sitio. + +Logtalk incluye más funcionalidad aparte de objetos, protocolos y categorías. Eventos, multithreading, type checking, debugger, documentation, tests, etc. Definitivamente, escribir sobre todo ello llevaría un buen rato. + +Esto es solo una introducción a Logtalk. Aparte del [handbook](https://logtalk.org/manuals/index.html) también puedes ver los [ejemplos del repo de GitHub](https://github.com/LogtalkDotOrg/logtalk3/). From 14538c6fdd0afe70036421eedb534366e9d889bc Mon Sep 17 00:00:00 2001 From: Kaan Kacar Date: Mon, 13 May 2024 12:01:27 +0300 Subject: [PATCH 185/392] [javascript/tr-tr] Javascript Documentation Translated into Turkish (#4667) --- tr-tr/javascript-tr.html.markdown | 606 ++++++++++++++++++++++++++++++ 1 file changed, 606 insertions(+) create mode 100644 tr-tr/javascript-tr.html.markdown diff --git a/tr-tr/javascript-tr.html.markdown b/tr-tr/javascript-tr.html.markdown new file mode 100644 index 00000000..a20f1f4e --- /dev/null +++ b/tr-tr/javascript-tr.html.markdown @@ -0,0 +1,606 @@ +--- +language: javascript +contributors: + - ["Leigh Brenecki", "https://leigh.net.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + - ["Kaan Kaçar", "https://github.com/kaankacar"] +filename: learnjavascript-tr.js +lang: tr-tr +--- + +JavaScript, Brendan Eich tarafından 1995 yılında oluşturuldu. Başlangıçta, daha karmaşık web uygulamaları için Java'nın kullanıldığı siteler için daha basit bir betik dili olarak tasarlandı, ancak Web sayfalarıyla sıkı entegrasyonu ve tarayıcılardaki yerleşik desteği nedeniyle Java'dan daha yaygın hale geldi. + +Ancak, JavaScript yalnızca web tarayıcılarıyla sınırlı değildir: Google Chrome'un V8 JavaScript motoru için bağımsız bir çalışma ortamı sağlayan Node.js giderek daha popüler hale gelmektedir. + +JavaScript, C diline benzer bir sözdizimine sahiptir, bu nedenle C veya Java gibi dilleri kullandıysanız, temel sözdizimin büyük bir kısmını zaten biliyorsunuz. Bununla birlikte, isim benzerliğine rağmen, JavaScript'in nesne modeli Java'nınkinden önemli ölçüde farklıdır. + +```js +// Tek satırlık yorumlar iki eğik çizgi ile başlar. +/* Çok satırlı yorumlar eğik çizgi-yıldız ile başlar, + ve yıldız-eğik çizgi ile biter */ + +// İfadeler ; ile sonlandırılabilir +birSeyYap(); + +// ... ancak sonlandırma yapmak zorunda değilsiniz, çünkü noktalı virgüller +// otomatik olarak yeni satırlarda yer alır, ancak bazı durumlar hariç. +birSeyYap() + +// Bu durumlar beklenmeyen sonuçlara yol açabileceğinden, burada +// noktalı virgüller kullanmaya devam edeceğiz. + +/////////////////////////////////// +// 1. Sayılar, Dizeler ve Operatörler + +// JavaScript'in bir sayı türü vardır (64 bitlik IEEE 754 double). +// Double'lar 52 bitlik bir mantisaya sahiptir, bu da tam sayıları +// yaklaşık olarak 9✕10¹⁵'e kadar kesin olarak depolamak için yeterlidir. +3; // = 3 +1.5; // = 1.5 + +// Temel aritmetik işlemler beklediğiniz gibi çalışır. +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// Hatta düzensiz bölme işlemi de yapılabilir. +5 / 2; // = 2.5 + +// Ve modülo bölmesi de yapılabilir. +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + +// Bit işlemleri de çalışır; bir bit işlemi yaptığınızda float'ınız +// *en fazla* 32 bitlik bir işaretleme tamsayıya dönüştürülür. +1 << 2; // = 4 + +// Öncelik parantez ile sağlanır. +(1 + 3) * 2; // = 8 + +// Üç adet gerçek olmayan sayı değeri vardır: +Infinity; // örneğin 1/0'ın sonucu +-Infinity; // örneğin -1/0'ın sonucu +NaN; // örneğin 0/0'ın sonucu, 'Sayı Değil' anlamına gelir + +// Ayrıca boolean türü vardır. +true; +false; + +// Stringler ' veya " ile oluşturulur. +'abc'; +"Merhaba, dünya"; + +// Olumsuzluk işareti ! sembolü ile yapılır. +!true; // = false +!false; // = true + +// Eşitlik === ile kontrol edilir. +1 === 1; // = true +2 === 1; // = false + +// Eşitsizlik !== ile kontrol edilir. +1 !== 1; // = false +2 !== 1; // = true + +// Diğer karşılaştırmalar +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// Stringler + ile birleştirilir. +"Merhaba " + "dünya!"; // = "Merhaba dünya!" + +// ... ve sadece stringlerle sınırlı olmayan bir şekilde çalışır +"1, 2, " + 3; // = "1, 2, 3" +"Merhaba " + ["dünya", "!"]; // = "Merhaba dünya,!" + +// ve < ve > ile karşılaştırma yapılabilir. +"a" < "b"; // = true + +// Tip dönüşümü(type conversion), çift eşittir işaretiyle yapılan karşılaştırmalarda gerçekleştirilir. +"5" == 5; // = true +null == undefined; // = true + +// ...ancak === işaretini kullanırsanız... +"5" === 5; // = false +null === undefined; // = false + +// ...bu bazen garip davranışlara yol açabilir... +13 + !0; // 14 +"13" + !0; // '13true' + +// Bir stringteki karakterlere `charAt` kullanarak erişebilirsiniz. +"Bu bir string(dize)".charAt(0); // = 'B' + +// ...veya daha büyük parçaları almak için `substring` kullanabilirsiniz. +"Merhaba dünya".substring(0, 5); // = "Merhaba" + +// `length` bir özelliktir, bu yüzden () kullanmayın. +"Merhaba".length; // = 7 + +// Ayrıca `null` ve `undefined` değerleri de vardır. +null; // bilerek atanmamış bir değeri belirtmek için kullanılır. +undefined; // bir değerin şu anda mevcut olmadığını belirtmek için kullanılır (aslında + // `undefined` kendisi bir değerdir) + +// false, null, undefined, NaN, 0 ve "" yanıltıcıdır (falsy); diğer her şey doğrudur (truthy). +// 0 yanıltıcıdır ve "0" doğrudur, 0 == "0" olduğu halde. + +/////////////////////////////////// +// 2. Değişkenler(Variables), Diziler(Arrays) ve Nesneler(Objects) + +// Değişkenler `var` anahtar kelimesiyle tanımlanır. JavaScript dinamik olarak +// yazıldığından türü belirtmeniz gerekmez. Atama işlemi tek `=` karakteriyle yapılır. +var birDegisken = 5; + +// Eğer var anahtar kelimesini atlamışsanız, hata almayacaksınız... +ikinciDegisken = 10; + +// ...ancak değişkeniniz tanımladığınız kapsamda değil, global kapsamda oluşturulur. + +// Atanmadan tanımlanan değişkenler undefined olarak ayarlanır. +var ucuncuDegisken; // = undefined + +// Eğer tek satırda birkaç değişken tanımlamak istiyorsanız, virgül ayırıcısını kullanabilirsiniz. +var dorduncuDegisken = 2, besinciDegisken = 4; + +// Değişkenler üzerinde matematiksel işlemler için kısa yol bulunmaktadır: +birDegisken += 5; // birDegisken = birDegisken + 5; birDegisken şimdi 10 +birDegisken *= 10; // şimdi birDegisken 100 + +// Ve 1 eklemek veya çıkarmak için daha da kısa bir yol bulunmaktadır +birDegisken++; // şimdi birDegisken 101 +birDegisken--; // tekrar 100'e döndü + +// Diziler, herhangi bir türde değerlerin sıralı listeleridir. +var benimDizim = ["Merhaba", 45, true]; + +// Elemanlara, köşeli parantezlerle indeks(index) kullanarak erişilebilir. +// Dizi indeksleri sıfırdan başlar. +benimDizim[1]; // = 45 + +// Diziler değiştirilebilir ve değişken uzunluğa sahiptir. +benimDizim.push("Dünya"); +benimDizim.length; // = 4 + +// Belirli bir indekse ekleme/düzenleme yapma +benimDizim[3] = "Merhaba"; + +// Dizinin başından veya sonundan bir eleman ekleyip çıkarma +benimDizim.unshift(3); // İlk eleman olarak ekle +birDegisken = benimDizim.shift(); // İlk elemanı çıkar ve geri döndür +benimDizim.push(3); // Son eleman olarak ekle +birDegisken = benimDizim.pop(); // Son elemanı çıkar ve geri döndür + +// Dizinin tüm elemanlarını noktalı virgül ile birleştir +var benimDizim0 = [32,false,"js",12,56,90]; +benimDizim0.join(";"); // = "32;false;js;12;56;90" + +// İndeks 1'den (dahil) indeks 4'e (hariç) kadar olan elemanları içeren alt diziyi al +benimDizim0.slice(1,4); // = [false,"js",12] + +// İndeks 2'den başlayarak 4 elemanı kaldır ve yerine "hi", "wr" ve "ld" dizelerini ekle; kaldırılan alt diziyi döndür +benimDizim0.splice(2,4,"hi","wr","ld"); // = ["js",12,56,90] +// benimDizim0 === [32,false,"hi","wr","ld"] + +// JavaScript nesneleri, diğer dillerde "sözlük(dictionary)" veya "haritalar(maps)" ile eşdeğerdir: anahtar-değer çiftlerinin sırasız bir koleksiyonudur. +var benimNesnem = {anahtar1: "Merhaba", anahtar2: "Dünya"}; + +// Değerler herhangi bir tür olabilir. +var benimNesnem = {benimAnahtarim: "benimDegerim", "digerAnahtarim": 4}; + +// Nesne özelliklerine köşeli parantezlerle veya nokta sözdizimi kullanarak da erişilebilir, +benimNesnem["digerAnahtarim"]; // = 4 +benimNesnem.benimAnahtarim; // = "benimDegerim" + +// Nesneler değiştirilebilir; değerler değiştirilebilir ve yeni anahtarlar eklenir. +benimNesnem.benimUcuncuAnahtarim = true; + +// Henüz tanımlanmamış bir değeri erişmeye çalışırsanız, undefined alırsınız. +benimNesnem.benimDorduncuAnahtarim; // = undefined + +/////////////////////////////////// +// 3. Mantık ve Kontrol Yapıları + +// `if` yapısı beklediğiniz gibi çalışır. +var sayi = 1; +if (sayi == 3){ + // sayı 3 ise değerlendirilir +} else if (sayi == 4){ + // sayı 4 ise değerlendirilir +} else { + // ne 3 ne de 4 ise değerlendirilir +} + +// `while` da beklediğiniz gibi çalışır. +while (true){ + // Sonsuz döngü! +} + +// Do-while döngüleri, while döngülerine benzer, ancak her zaman en az bir kez çalışır. +var input; +do { + input = getInput(); +} while (!isValid(input)); + +// `for` döngüsü C ve Java ile aynıdır: +// başlatma; devam koşulu; iterasyon. +for (var i = 0; i < 5; i++){ + // 5 kez çalışır +} + +// Etiketli döngülerden çıkmak, Java'ya benzer. +dis: +for (var i = 0; i < 10; i++) { + for (var j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break dis; + // sadece iç içe olan yerine dış döngüden çıkar + } + } +} + +// for/in ifadesi bir nesnenin özellikleri üzerinde dolaşmaya olanak sağlar. +var aciklama = ""; +var kisi = {ad:"Kaan", soyad:"Kaçar", yas:26}; +for (var x in kisi){ + aciklama += kisi[x] + " "; +} // aciklama = 'Kaan Kaçar 26' + +// for/of ifadesi, yinelemeli nesneler üzerinde dolaşmayı sağlar +var evdekiHayvanlar = ""; +var hayvanlar = ["kedi", "köpek", "hamster", "kirpi"]; +for (var hayvan of hayvanlar){ + evdekiHayvanlar += hayvan + " "; +} // evdekiHayvanlar = 'kedi köpek hamster kirpi ' + +// && mantıksal ve, || mantıksal veya'dır. +if (ev.buyukluk == "büyük" && ev.renk == "mavi"){ + ev.icinde = "ayı"; +} +if (renk == "kırmızı" || renk == "mavi"){ + // renk ya kırmızı ya da mavidir +} + +// && ve || "kısa devre(short circuit)" yapar, bu varsayılan değerlerin atanmasında kullanışlıdır. +var isim = digerIsim || "varsayılan"; + +// `switch` ifadesi `===` ile eşitlik kontrolü yapar. +// case kodu çalıştıktan sonra çalışmasını istemiyorsanız "break" kullanın. +not = 'B'; +switch (not) { + case 'A': + console.log("Harika iş"); + break; + case 'B': + console.log("İyi iş"); + break; + case 'C': + console.log("Daha iyisini yapabilirsin"); + break; + default: + console.log("Eyvah"); + break; +} + + +/////////////////////////////////// +// 4. Fonksiyonlar, Kapsam(Scope) ve Kapanışlar(Closure) + +// JavaScript fonksiyonları `function` anahtar kelimesi ile tanımlanır. +function fonksiyonum(sey){ + return sey.toUpperCase(); +} +fonksiyonum("foo"); // = "FOO" + +// Dikkat edilmesi gereken bir nokta, döndürülecek değerin `return` anahtar kelimesiyle +// aynı satırda başlaması gerektiğidir. Aksi takdirde, otomatik noktalı virgül ekleme +// nedeniyle her zaman `undefined` döndürülür. +function fonksiyonum(){ + return // <- buraya otomatik olarak noktalı virgül eklenir + {buBir: 'nesne haritası'}; +} +fonksiyonum(); // = undefined + +// JavaScript fonksiyonları birinci sınıf nesnelerdir, bu nedenle farklı değişken adlarına +// yeniden atanabilir ve diğer fonksiyonlara argüman olarak geçilebilir - örneğin, +// bir olay işleyici sağlarken: +function fonksiyonum(){ + // bu kod 5 saniye sonra çağrılacak +} +setTimeout(fonksiyonum, 5000); +// Not: setTimeout, JS dilinin bir parçası değildir, ancak tarayıcılar ve Node.js tarafından sağlanır. + +// Tarayıcılar tarafından sağlanan başka bir fonksiyon da setInterval'dir +function fonksiyonum(){ + // bu kod her 5 saniyede bir çağrılacak +} +setInterval(fonksiyonum, 5000); + +// Fonksiyon nesnelerinin bile isimle tanımlanması gerekmez - başka bir argümana +// doğrudan anonim bir fonksiyon tanımı yazabilirsiniz. +setTimeout(function(){ + // bu kod 5 saniye sonra çağrılacak +}, 5000); + +// JavaScript, fonksiyon kapsamına sahiptir; fonksiyonlar kendi kapsamlarını alır, +// ancak diğer bloklar almaz. +if (true){ + var i = 5; +} +i; // = 5 - blok kapsamı olan bir dilde beklendiği gibi undefined değil + +// Bu, "hemen çalışan anonim fonksiyonlar"ın yaygın bir modeline yol açmıştır. +// Bu model, geçici değişkenlerin global kapsama sızmasını önler. +(function(){ + var gecici = 5; + // Global kapsama `window` olarak atanarak global kapsama erişebiliriz. + // Web tarayıcısında global nesne her zaman `window`'dur. Node.js gibi tarayıcı dışı + // ortamlarda global nesnenin farklı bir adı olabilir. + window.kalici = 10; +})(); +gecici; // Referans Hatası verir +kalici; // = 10 + +// JavaScript'in en güçlü özelliklerinden biri closure'lardır. Eğer bir fonksiyon başka bir fonksiyonun içinde tanımlanmışsa, iç fonksiyon dış fonksiyonun tüm değişkenlerine erişebilir, hatta dış fonksiyon sonlandıktan sonra bile. +function beşSaniyedeMerhabaDe(isim){ + var mesaj = "Merhaba, " + isim + "!"; + // İç fonksiyonlar varsayılan olarak yerel kapsama yerleştirilir, sanki `var` ile tanımlanmış gibi. + function içFonksiyon(){ + alert(mesaj); + } + setTimeout(içFonksiyon, 5000); + // setTimeout asenkron bir işlem olduğu için beşSaniyedeMerhabaDe fonksiyonu hemen sonlanacak ve setTimeout daha sonra içFonksiyon'u çağıracak. Ancak içFonksiyon, beşSaniyedeMerhabaDe fonksiyonunun kapsamında olduğu için içFonksiyon sonunda çağrıldığında hala `mesaj` değişkenine erişebilecektir. +} +beşSaniyedeMerhabaDe("Kaan"); // 5 saniye sonra "Merhaba, Kaan!" içeren bir pencere açacak + +/////////////////////////////////// +// 5. Nesneler Hakkında Daha Fazla: Kurucular(Constructors) ve Prototipler(Prototypes) + +// Nesneler fonksiyonlar içerebilir. +var myObj = { + myFunc: function(){ + return "Merhaba dünya!"; + } +}; +myObj.myFunc(); // = "Merhaba dünya!" + +// Nesneye bağlı olarak çağrılan fonksiyonlar, `this` anahtar kelimesini kullanarak kendilerine bağlı olan nesneye erişebilir. +myObj = { + myString: "Merhaba dünya!", + myFunc: function(){ + return this.myString; + } +}; +myObj.myFunc(); // = "Merhaba dünya!" + +// `this` hangi bağlamda fonksiyonun çağrıldığıyla ilgilidir, tanımlandığı yerle değil. Bu nedenle, fonksiyonumuz nesnenin bağlamında çağrılmazsa çalışmaz. +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// Tersine, bir fonksiyon, tanımlandığı sırada bağlı olmasa bile nesneye atanabilir ve `this` aracılığıyla nesneye erişebilir. +var myOtherFunc = function(){ + return this.myString.toUpperCase(); +}; +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // = "MERHABA DÜNYA!" + +// Ayrıca, bir fonksiyonu çağırırken onu hangi bağlamda çalıştıracağımızı `call` veya `apply` kullanarak belirtebiliriz. + +var anotherFunc = function(s){ + return this.myString + s; +}; +anotherFunc.call(myObj, " Ve Merhaba Ay!"); // = "Merhaba Dünya! Ve Merhaba Ay!" + +// `apply` işlevi neredeyse aynıdır, ancak bir argüman listesi için bir dizi alır. + +anotherFunc.apply(myObj, [" Ve Merhaba Güneş!"]); // = "Merhaba Dünya! Ve Merhaba Güneş!" + +// Bu, bir dizi geçirmek istediğinizde bir argüman dizisini kabul eden bir işlevle çalışırken faydalıdır. + +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN (Haydaaa) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// Ancak, `call` ve `apply` geçicidir. Kalıcı olmasını istediğimizde `bind` kullanabiliriz. + +var birlestir = anotherFunc.bind(myObj); +birlestir(" Ve Merhaba Satürn!"); // = "Merhaba Dünya! Ve Merhaba Satürn!" + +// `bind` ayrıca bir işlevi kısmen uygulamak (curry) için de kullanılabilir. + +var product = function(a, b){ return a * b; }; +var ikiylecarp = product.bind(this, 2); +ikiylecarp(8); // = 16 + +// `new` anahtar kelimesiyle bir işlevi çağırdığınızda, yeni bir nesne oluşturulur ve bu nesne `this` anahtar kelimesi aracılığıyla işleve ulaşır. Böyle çağrılmak üzere tasarlanmış işlevlere kurucular denir. + +var MyConstructor = function(){ + this.myNumber = 5; +}; +myNewObj = new MyConstructor(); // = {myNumber: 5} +myNewObj.myNumber; // = 5 + +// JavaScript, diğer popüler nesne tabanlı dillerin aksine, 'sınıf' taslaklarından oluşturulan 'örnekler' kavramına sahip değildir; bunun yerine, JavaScript, örnekleme ve kalıtımı tek bir kavramda birleştirir: 'prototype' (prototip). + +// Her JavaScript nesnesinin bir 'prototype'u vardır. Bir nesnenin üzerinde mevcut olmayan bir özelliğe erişmeye çalıştığınızda, yorumlayıcı prototipine bakar. + +// Bazı JS uygulamaları, nesnenin prototipine `__proto__` sihirli özelliği üzerinden erişmenizi sağlar. Bu, prototipleri açıklamak için faydalı olsa da, bunun standart bir parçası değildir; prototipleri kullanmanın standart yollarına daha sonra geleceğiz. +var myObj = { + myString: "Merhaba dünya!" +}; +var prototipim = { + hayatinAnlami: 42, + myFunc: function(){ + return this.myString.toLowerCase(); + } +}; + +myObj.__proto__ = prototipim; +myObj.hayatinAnlami; // = 42 + +// Bu, işlevler için de çalışır. +myObj.myFunc(); // = "merhaba dünya!" + +// Elbette, özelliğiniz prototipte değilse, prototipin prototipi aranır ve böyle devam eder. +prototipim.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// Burada herhangi bir kopyalama işlemi yoktur; her nesne, prototipine bir referans tutar. Bu, prototipi değiştirebileceğimiz ve değişikliklerimizin her yerde yansıyacağı anlamına gelir. +prototipim.hayatinAnlami = 43; +myObj.hayatinAnlami; // = 43 + +// for/in ifadesi bir nesnenin özellikleri üzerinde yinelemeye izin verir, +// bir null prototipi görünceye kadar prototip zinciri üzerinde yürür. +for (var x in myObj){ + console.log(myObj[x]); +} +///çıktı: +// Merhaba dünya! +// 43 +// [Fonksiyon: myFunc] +// true + +// Yalnızca nesneye kendisi tarafından eklenen özellikleri düşünmek için +// ve prototiplerini değil, `hasOwnProperty()` kontrolünü kullanın. +for (var x in myObj){ + if (myObj.hasOwnProperty(x)){ + console.log(myObj[x]); + } +} +///çıktı: +// Merhaba dünya! + +// `__proto__`'nun standart olmadığını ve mevcut bir nesnenin prototipini +// değiştirmenin standart bir yolunun olmadığını belirttik. Bununla birlikte, verilen bir prototiple +// yeni bir nesne oluşturmanın iki yolu vardır. + +// İlk yöntem: +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// İkinci yol, yapıcılarla(constructors) ilgilidir. +// Yapıcıların prototype adında bir özelliği vardır. Bu, yapıcı işlevinin kendisinin prototipi değildir; +// bunun yerine, yeni nesnelerin, o yapıcı ve new anahtar kelimesiyle oluşturulduklarında verilen +// prototiptir. +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6; +myNewObj2.getMyNumber(); // = 6 + +// Dize ve sayı gibi yerleşik tiplerin ayrıca denk gelen sarma nesnelerini oluşturan yapıcıları vardır. +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// Ancak, tam olarak eşdeğer değiller. +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // Bu kod çalışmayacak, çünkü 0 yanlış değerlidir. +} +if (new Number(0)){ + // Bu kod çalışacak, çünkü sarmalanan sayılar nesnelerdir ve nesneler + // her zaman doğru değerlidir. +} + +// Bununla birlikte, sarma nesneleri ve düzenli yerleşik tipler bir prototipi paylaşırlar, bu yüzden +// aslında bir dizeye işlevsellik ekleyebilirsiniz, örneğin. +String.prototype.firstCharacter = function(){ + return this.charAt(0); +}; +"abc".firstCharacter(); // = "a" + +// Bu genellikle "polyfilling" olarak adlandırılan bir yöntemde kullanılır. + +// Örneğin, Object.create bazı uygulamalarda mevcut değil, +// ancak aşağıdaki polyfill ile yine de kullanabiliriz: +if (Object.create === undefined){ // mevcut ise üzerine yazma + Object.create = function(proto){ + // doğru prototipe sahip geçici bir yapıcı oluştur + var Constructor = function(){}; + Constructor.prototype = proto; + // ardından onu kullanarak yeni, uygun prototipli bir nesne oluştur + return new Constructor(); + }; +} + +// ES6 + +// "let" anahtar kelimesi, değişkenleri bir fonksiyon kapsamı yerine +// bir leksikal kapsamda tanımlamanıza olanak tanır, var anahtar kelimesi gibi. +let name = "Billy"; + +// let ile tanımlanan değişkenlere yeni değerler atanabilir. +name = "William"; + +// "const" anahtar kelimesi, let ile aynı şekilde bir leksikal kapsamda bir değişken tanımlamanıza olanak tanır, +// ancak bir değer atandıktan sonra tekrar değer atanamaz. + +const pi = 3.14; + +pi = 4.13; // Bunu yapamazsınız. + +// ES6'da "lambda sözdizimi" olarak bilinen bir fonksiyon için farklı bir sözdizimi vardır. +// Bu, sabit ve let ile tanımlanan değişkenler gibi bir leksikal kapsamda fonksiyonların tanımlanmasına olanak tanır. + +const isEven = (number) => { + return number % 2 === 0; +}; + +isEven(7); // false + +// Geleneksel sözdizimde bu fonksiyonun "eşdeğeri" şu şekilde görünür: + +function isEven(number) { + return number % 2 === 0; +}; + +// "eşdeğer" kelimesini çift tırnak içine koydum çünkü lambda sözdizisi kullanılarak tanımlanan bir fonksiyon, tanımdan önce çağrılamaz. +// Aşağıdaki, geçersiz bir kullanım örneğidir: + +add(1, 8); + +const add = (firstNumber, secondNumber) => { + return firstNumber + secondNumber; +}; +``` + +## Daha Fazlası İçin + +[Mozilla Developer Network][1] tarayıcılarda kullanılan JavaScript için mükemmel bir dokümantasyon sunar. Ayrıca, bir wiki olduğu için daha fazla bilgi edindikçe kendi bilginizi paylaşarak diğer insanlara yardımcı olabilirsiniz. + +MDN'nin [A re-introduction to JavaScript(JavaScript'e Yeniden Giriş)][2] başlıklı kaynağı, burada ele alınan kavramların daha detaylı bir şekilde ele alınmış halini içerir. Bu rehber, bilinçli bir şekilde sadece JavaScript dilini ele almıştır. Eğer JavaScript'i web sayfalarında nasıl kullanacağınız hakkında daha fazla bilgi edinmek isterseniz, [Belge Nesne Modeli (Document Object Model)][3] hakkında öğrenmeye başlayabilirsiniz. + +[Patika - Javascript][4]Hakan Yalçınkaya'nın eğitmen olduğu bu kaynak, Javascript'i baştan sonra öğrenmenizi ve öğrendiklerinizi çeşitli test, proje ve coding challenge'lar ile pekiştirmenizi sağlar. + +[Learn Javascript by Example and with Challenges][5] Bu da öğrendiklerinizi çeşitli challenge'lar ile pekiştirmenize olanak sağlar. + +[JavaScript Garden][6] tüm detaylarının derinlemesine incelendiği bir rehberdir. + +[Yusuf Sezer][7] Hem Türkçe hem yazılı olsun diyenler için kapsamlı bir kaynak. + +[BTK Akademi][8] BTK Akademi Javascript kursu + +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript +[3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core +[4]: https://academy.patika.dev/courses/javascript +[5]: http://www.learneroo.com/modules/64/nodes/350 +[6]: http://bonsaiden.github.io/JavaScript-Garden/ +[7]: https://www.yusufsezer.com.tr/javascript-dersleri/ +[8]: https://www.btkakademi.gov.tr/portal/course/javascript-8099 From 53d6334848ff592bb2758cfe2b0afb80517a84c4 Mon Sep 17 00:00:00 2001 From: andres7293 Date: Mon, 13 May 2024 11:08:26 +0200 Subject: [PATCH 186/392] [make/es] Translate make (#4648) --- es-es/make-es.html.markdown | 260 ++++++++++++++++++++++++++++++++++++ 1 file changed, 260 insertions(+) create mode 100644 es-es/make-es.html.markdown diff --git a/es-es/make-es.html.markdown b/es-es/make-es.html.markdown new file mode 100644 index 00000000..0e07ec13 --- /dev/null +++ b/es-es/make-es.html.markdown @@ -0,0 +1,260 @@ +--- +category: tool +tool: make +filename: Makefile +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] +translators: + - ["Andrés Perdomo", "https://github.com/andres7293"] +lang: es-es +--- + +Un archivo Makefile define un conjunto de reglas para crear un objetivo (o +varios objetivos). Su propósito es hacer la mínima cantidad de trabajo necesaria +para actualizar un objetivo a la versión más reciente de la fuente. Escrito +famosamente en un fin de semana por Stuart Feldman en 1976, todavía se utiliza +ampliamente (especialmente en Unix y Linux) a pesar de muchos competidores y +críticas. + +Existen muchas variedades de Make en existencia, no obstante, este artículo +asume que estamos utilizando GNU Make, que es el estándar en Linux. + +```make +# Los comentarios se pueden escribir de esta forma. + +# El fichero debe tener el nombre de Makefile y luego puede ser ejecutado +# como `make `. +# De lo contrario, se utiliza `make -f "nombre_archivo" ` + +# Advertencia: ¡solo use TABULACIONES para la identación en Makefiles, nunca +# espacios! + +#----------------------------------------------------------------------- +# Fundamentos +#----------------------------------------------------------------------- + +# Las reglas tienen el formato +# objetivo: +# donde prerrequisito es opcional. + +# Una regla - esta regla solamente se ejecutará si file0.txt no existe. +file0.txt: + echo "foo" > file0.txt + # Incluso los comandos en esta sección de 'receta' se pasan a la shell. + # Prueba `make file0.txt` o simplemente 'make' - La primera regla es la + # predeterminada. + +# Esta regla se ejecutará solo si file0.txt es más reciente que file1.txt. +file1.txt: file0.txt + cat file0.txt > file1.txt + # Use las mismas reglas de comillas que en la shell. + @cat file0.txt >> file1.txt + # @ evita que el comando se muestre en stdout. + -@echo 'hello' + # - Quiere decir que make continuará en caso de error. + # Pruebe 'make file1.txt` en la línea de comandos. + +# Una regla puede tener múltiples objetivos y múltiples prerrequisitos +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make se quejará de múltiples recetas para la misma regla. Sin embargo, +# las reglas vacías no cuentan y se pueden utilizar para agregar nuevas +# dependencias + +#----------------------------------------------------------------------- +# Objetivos ficticios (Phony Targets) +#----------------------------------------------------------------------- + +# Un objetivo ficticio (phony target). Cualquier objetivo que no sea un archivo. +# Nunca estará actualizado, por lo que make siempre tratará de ejecutarlo. +all: make process + +# Podemos declarar cosas sin orden. +maker: + touch ex0.txt ex1.txt + +# Se puede evitar que las reglas ficticias (phony) se rompan cuando un archivo +# real tiene el mismo nombre usando: +.PHONY: all maker process +# Esto es un objetivo especial. Hay varios otros. + +# Una regla con una dependencia en un objetivo ficticio (phony target) +# se ejecutara siempre: +ex0.txt ex1.txt: maker + +# Los objetivos ficticios (phony target) más comunes son: +# all make clean install... + +#----------------------------------------------------------------------- +# Variables automáticas y Wildcards +#----------------------------------------------------------------------- + +process: file*.txt # usa un wildcard para coincidir con los nombres de archivos. + @echo $^ # $^ es una variable que contiene una lista de todos los prerrequisitos + @echo $@ # imprime el nombre del objetivo + #(para reglas con múltiples objetivos, $@ es el que hizo que se ejecutara la regla) + @echo $< # el primer prerrequisito listado + @echo $? # solo las dependencias que están desactualizadas + @echo $+ # todas las dependencias incluyendo las duplicadas (a diferencia de lo normal) + #@echo $| # solo los 'prerrequisitos solicitados' + +# Incluso si dividimos las definiciones de las dependencias, de las reglas, $^ +# las encontrará +process: ex1.txt file0.txt +# ext1.xt se encontrará pero file0.txt se duplicará. + +#----------------------------------------------------------------------- +# Patrones +#----------------------------------------------------------------------- + +# Se puede instruir a make sobre como convertir ciertos tipos de archivos en +# otros archivos. + +%.png: %.svg + inkscape --export-png $^ + +# Las reglas de patrones solo harán algo si make decide crear el objetivo. + +# Los directorios no suelen tenerse en cuenta al coincidir con reglas de +# patrones. +# Pero make intentará usar la regla más apropiada disponible. + +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# make usará la última versión de una regla de patrón que encuentre. +%.png: %.svg + @echo esta regla es elegida + +# Sin embargo make usará la primera regla de patrón que pueda construir el +# objetivo. +%.png: %.ps + @echo esta regla no es elegida si *.svg y *.ps están ambas presentes + +# Make ya tiene algunas reglas de patrón integradas. +# Por ejemplo, sabe cómo convertir archivos *.c en archivos *.o. + +# En makefiles antiguos se solían utilizar las reglas de sufijo en lugar de las +# reglas de patrón +.png.ps: + @echo esta regla es similar a una regla de patrón. + +# Instruye a make sobre una regla de sufijo +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables +#----------------------------------------------------------------------- +# también conocidas como macros. + +# Las variables son básicamente de tipo cadena (string) + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Esto no funcionará, se tratará como $(n)name. + @echo $(name3) # Variables desconocidas se tratarán como cadenas vacías. + +# Hay 4 lugares donde se pueden definir variables. +# En orden de prioridad de mayor a menor: +# 1: argumentos de línea de comando. +# 2: Makefile. +# 3: variables de entorno de la shell - make las importa automáticamente. +# 4: make tiene algunas variables predefinidas. + +name4 ?= Jean +# Solo establece la variable si la variable de entorno no está aún definida. + +override name5 = David +# Detiene que los argumentos de línea de comandos modifiquen esta variable. + +name4 +=grey +# Añade valores a la variable (incluye un espacio). + +# Valores de variables específicos de patrones (Extension de GNU). +echo: name2 = Sara # Verdadero dentro de la regla coincidente + # y también dentro de sus dependencias recursivas rehechas + # (¡excepto que puede romperse cuando el grafo se complica demasiado!) + +# Algunas variables son definidas automáticamente por make. +echo_inbuilt: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables 2 +#----------------------------------------------------------------------- + +# El primer tipo de variables se evalúan cada vez que se usan. +# Esto puede ser costoso, por lo que existe un segundo tipo de variable que se +# evalúa solo una vez. (Esta es una extensión de GNU make) + +var := hello +var2 ::= $(var) hello +#:= y ::= son equivalentes + +# Estas variables se evalúan de manera procedimental (en el orden en que +# aparecen), ¡rompiendo así con el resto del lenguaje! + +# Esto no funciona +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funciones +#----------------------------------------------------------------------- + +# make tiene muchas funciones disponibles. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# El formato es $(func arg0,arg1,arg2...) + +# Algunos ejemplos +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directrices (Directives) +#----------------------------------------------------------------------- + +# Incluye otros makefiles, útil para código de plataformas específicas +include foo.mk + +sport = tennis +# Compilación condicional +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# También existe ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + +### Más recursos (en inglés) + ++ [GNU Make documentation](https://www.gnu.org/software/make/manual/) ++ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/) From 401b64eafa3de7ea8a2656b783de2b32532e74a4 Mon Sep 17 00:00:00 2001 From: Gustavo Tramontin Pedro <62556451+gustatramontin@users.noreply.github.com> Date: Mon, 13 May 2024 06:09:29 -0300 Subject: [PATCH 187/392] [lambda-calculus/pt-br] Lambda Calculus portuguese translation (#4755) --- pt-br/lambda-calculus-pt.html.markdown | 210 +++++++++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 pt-br/lambda-calculus-pt.html.markdown diff --git a/pt-br/lambda-calculus-pt.html.markdown b/pt-br/lambda-calculus-pt.html.markdown new file mode 100644 index 00000000..8e727eda --- /dev/null +++ b/pt-br/lambda-calculus-pt.html.markdown @@ -0,0 +1,210 @@ +--- +category: Algorithms & Data Structures +name: Lambda Calculus +contributors: + - ["Max Sun", "http://github.com/maxsun"] + - ["Yan Hui Hang", "http://github.com/yanhh0"] +translators: + - ["Gustavo Tramontin", "https://github.com/gustatramontin"] +lang: pt-br +--- + +# Cálculo Lambda + +Cálculo Lambda (cálculo-λ), originalmente criada por +[Alonzo Church](https://en.wikipedia.org/wiki/Alonzo_Church), +é a menor linguagem de programação do mundo. +Composta apenas por funções, sem números, texto, booleans, ou qualquer outro tipo, +apesar dessa limitação, cálculo lambda é capaz de representar qualquer Máquina de Turing! + +Cálculo lambda é composto por 3 elementos: **variáveis**, **funções** e **aplicações**. + + +| Nome | Sintaxe | Exemplo | Explicação | +|-----------|--------------------------------|-----------|--------------------------------------------| +| Variável | `` | `x` | uma variável chamada "x" | +| Função | `λ.` | `λx.x` | uma função com parâmetro "x" e corpo "x" | +| Aplicação | `` | `(λx.x)a` | aplicando a função "λx.x" ao argumento "a" | + +A função mais simples é a função indentidade: `λx.x` equivalente a `f(x) = x`. +O primeiro "x" é o argumento da função, e o segundo o corpo da função. + +## Variáveis Livres e Ligadas: + +- Na função `λx.x`, "x" é uma variável ligada porque ela está +no corpo e em um dos parâmetros da função. +- Na função `λx.y`, "y" é uma variável livre porque ela não foi definida anteriormente. + +## Avaliação: + +Avaliação é realizada por +[Redução-β](https://en.wikipedia.org/wiki/Lambda_calculus#Beta_reduction), +que é essencialmente substituição léxica + +Ao avaliar `(λx.x)a`, todo "x" no corpo da função é substituído por "a". + +- `(λx.x)a` avalia para: `a` +- `(λx.y)a` avalia para: `y` + +Você ainda pode criar funções de ordem superior + +- `(λx.(λy.x))a` avalia para: `λy.a` + +Tradicionalmente funções no cálculo lambda possuem um único parâmetro, +porém usando a técnina de [currying](https://en.wikipedia.org/wiki/Currying) +podes criar funções com múltiplos argumentos. + +- `(λx.λy.λz.xyz)` equivale a `f(x, y, z) = ((x y) z)` + +Às vezes `λxy.` é usado como notação para: `λx.λy.` + +---- + +É importante ressaltar que **cálculo lambda não tem números, carácteres, +ou qualquer tipo que não seja uma função!** + +## Lógica Booleana: + +Cálculo lambda não tem booleans, valores lógicos de "verdade" e "falso". + +No lugar temos: + +`T` representado por: `λx.λy.x` + +`F` representado por: `λx.λy.y` + +* `T` e `F` para Verdade e Falso respectivamente. + +Assim representamos os operadores lógicos: + +`Não a` como: `λa.a F T` + +`a E b` como: `λa.λb.a b F` + +`a OU b` como: `λa.λb.a T b` + +## Números: + +Apesar do cálculo lambda não ter números, podemos representa-los usando [numerais Church](https://en.wikipedia.org/wiki/Church_encoding). + +Para todo número n: n = λf.fn assim: + +`0 = λf.λx.x` + +`1 = λf.λx.f x` + +`2 = λf.λx.f(f x)` + +`3 = λf.λx.f(f(f x))` + +Para incrementar um numeral Church, +usamos a função sucessora `S(n) = n + 1` definida como: + +`S = λn.λf.λx.f((n f) x)` + +Usando-a definimos a função soma: + +`SOMA = λab.(a S)b` + +**Desafio:** defina sua própria função de multiplicação! + +## Ainda Menor: SKI, SK E Iota + +### Cálculo Combinador SKI + +Seja, S, K, I as funções seguintes: + +`I x = x` + +`k x y = x` + +`S x y z = x z (y z)` + +Podemos converter uma expressão no cálculo lambda para uma no cálculo combinador SKI: + +1. `λx.x = I` +2. `λx.c = Kc` desde que `x` não ocorra livre em `c` +3. `λx.(y z) = S (λx.y) (λx.z)` + +Exemplo com numeral church 2: + +`2 = λf.λx.f(f x)` + +Para a parte interna `λx.f(f x)`: + +``` + λx.f(f x) += S (λx.f) (λx.(f x)) (caso 3) += S (K f) (S (λx.f) (λx.x)) (caso 2, 3) += S (K f) (S (K f) I) (caso 2, 1) +``` + +Então: + +``` + 2 += λf.λx.f(f x) += λf.(S (K f) (S (K f) I)) += λf.((S (K f)) (S (K f) I)) += S (λf.(S (K f))) (λf.(S (K f) I)) (caso 3) +``` + +Para o primeiro argumento `λf.(S (K f))`: + +``` + λf.(S (K f)) += S (λf.S) (λf.(K f)) (caso 3) += S (K S) (S (λf.K) (λf.f)) (caso 2, 3) += S (K S) (S (K K) I) (caso 2, 3) +``` + +Para o segundo argumento `λf.(S (K f) I)`: + +``` + λf.(S (K f) I) += λf.((S (K f)) I) += S (λf.(S (K f))) (λf.I) (caso 3) += S (S (λf.S) (λf.(K f))) (K I) (caso 2, 3) += S (S (K S) (S (λf.K) (λf.f))) (K I) (caso 1, 3) += S (S (K S) (S (K K) I)) (K I) (caso 1, 2) +``` + +Juntando-os: + +``` + 2 += S (λf.(S (K f))) (λf.(S (K f) I)) += S (S (K S) (S (K K) I)) (S (S (K S) (S (K K) I)) (K I)) +``` + +Expandindo isso, finalizamos com a mesma expressão para o numeral Church 2. + +### Cálculo Combinador SK + +O cálculo combinador SKI pode ser reduzido ainda mais. +Ao notar que `I = SKK`, podemos remover o combinador I +substituindo-o por `SKK`. + +### Combinador Iota + +Cálculo combinador SK ainda não é mínimo. Definindo: + +``` +ι = λf.((f S) K) +``` + +Temos: + +``` +I = ιι +K = ι(ιI) = ι(ι(ιι)) +S = ι(K) = ι(ι(ι(ιι))) +``` + +## Para leituras mais avançadas: + +1. [A Tutorial Introduction to the Lambda Calculus](http://www.inf.fu-berlin.de/lehre/WS03/alpi/lambda.pdf) +2. [Cornell CS 312 Recitation 26: The Lambda Calculus](http://www.cs.cornell.edu/courses/cs3110/2008fa/recitations/rec26.html) +3. [Wikipedia - Lambda Calculus](https://en.wikipedia.org/wiki/Lambda_calculus) +4. [Wikipedia - SKI combinator calculus](https://en.wikipedia.org/wiki/SKI_combinator_calculus) +5. [Wikipedia - Iota and Jot](https://en.wikipedia.org/wiki/Iota_and_Jot) From 6a1234ad7adeccbcf5725d160961ab3e3a363f50 Mon Sep 17 00:00:00 2001 From: MenahcemZeivald <108309381+MenachemZeivald@users.noreply.github.com> Date: Mon, 13 May 2024 12:33:11 +0300 Subject: [PATCH 188/392] [html/he] Hebrew translation (#4669) --- he-he/html-he.html.markdown | 166 ++++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100644 he-he/html-he.html.markdown diff --git a/he-he/html-he.html.markdown b/he-he/html-he.html.markdown new file mode 100644 index 00000000..6e4421f7 --- /dev/null +++ b/he-he/html-he.html.markdown @@ -0,0 +1,166 @@ +--- +language: html +filename: learnhtml-he.html +contributors: + - ['Christophe THOMAS', 'https://github.com/WinChris'] +translators: + - ['Menachem Zeivald', 'https://github.com/MenachemZeivald'] +lang: he-he +--- + +HTML קיצור של Hypertext Markup Language כלומר זוהי שפה שמשתמשת בתגיות. + +זוהי שפה המאפשרת לנו לכתוב אתרי אינטרנט. +זוהי שפת תגיות והיא מאפשרת לנו לכתוב דפי אינטרנט באמצעות קוד +כדי לתת הוראות לדפדפן כיצד יש להציג טקסט ונתונים. +למעשה, קובצי HTML הם קבצי טקסט פשוטים. + +מהם התגיות? +זוהי שיטה לארגון מידע על ידי הקפתו בתגיות פתיחה וסגירה. +התגית משמשת כדי לתת משמעות לטקסט שהיא מקיפה. +ל-HTML יש גרסאות רבות. כאן נדבר על HTML5. + +**הערה:** אתה יכול לבדוק את התגים והאלמנטים השונים תוך כדי קריאת המדריך +באתר כמו [codepen](http://codepen.io/pen/) כדי לראות את ההשפעות שלהם, +להבין איך הם עובדים ולהכיר את השפה. +מאמר זה עוסק בעיקר בתחביר של HTML וכמה עצות שימושיות. + +```html + + + + + + + + + + + + האתר שלי + + +

    שלום עולם!

    + + בואו נבדוק את הקישור הזה + +

    זוהי פסקה.

    +

    זו עוד פסקה.

    +
      +
    • זה פריט ברשימה לא ממוספרת
    • +
    • זהו פריט נוסף
    • +
    • וזה הפריט האחרון ברשימה
    • +
    + + + + + + + + + + + + + + + + + + + + + האתר שלי + + + + + + + + +

    שלום עולם

    + + + + בואו נבדוק את הקישור הזה + + +

    זוהי פסקה.

    +

    זו עוד פסקה.

    + + + +
      +
    • זה פריט ברשימה לא ממוספרת
    • +
    • זהו פריט נוסף
    • +
    • וזה הפריט האחרון ברשימה
    • +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    כותרת ראשונהכותרת שנייה
    שורה ראשונה, עמודה ראשונהשורה ראשונה, עמודה שנייה
    שורה שנייה, עמודה ראשונהשורה שנייה, עמודה שנייה
    +``` + +## שימוש + +HTML נכתב בקבצים המסתיימים ב-`.html` או `.htm`. + +**HTML אינה שפת תכנות** + +## לקריאה נוספת + +- [Wikipedia](https://he.wikipedia.org/wiki/HTML) +- [HTML Tutorial (EN)](https://developer.mozilla.org/en-US/docs/Web/HTML) +- [W3Schools (EN)](http://www.w3schools.com/html/html_intro.asp) From 6754700132834f4eb923899cb749a5c4f264d32e Mon Sep 17 00:00:00 2001 From: Cillian Smith <72135306+smithc36-tcd@users.noreply.github.com> Date: Mon, 13 May 2024 10:34:24 +0100 Subject: [PATCH 189/392] [OpenMP/en] Added documentation for OpenMP (#4645) --- openmp.html.markdown | 346 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 346 insertions(+) create mode 100644 openmp.html.markdown diff --git a/openmp.html.markdown b/openmp.html.markdown new file mode 100644 index 00000000..ac810eda --- /dev/null +++ b/openmp.html.markdown @@ -0,0 +1,346 @@ +--- +category: tool +tool: OpenMP +filename: learnopenMP.cpp +contributors: + - ["Cillian Smith", "https://github.com/smithc36-tcd"] +--- + +**OpenMP** is a library used for parallel programming on shared-memory machines. +OpenMP allows you to use simple high-level constructs for parallelism, +while hiding the details, keeping it easy to use and quick to write. +OpenMP is supported by C, C++, and Fortran. + +## Structure + +Generally an OpenMP program will use the following structure. + +- **Master**: Start a Master thread, which will be used to set up the environment and +initialize variables + +- **Slave**: Slave threads are created for sections of code which are marked by a special +directive, these are the threads which will run the parallel sections. + +Each thread will have its own ID which can be obtained using the function +`omp_get_thread_num()`, but more on that later. + +``` + __________ Slave + /__________ Slave + / +Master ------------- Master + \___________ Slave + \__________ Slave + +``` + +## Compiling and running OpenMP + +A simple "hello world" program can be parallelized using the `#pragma omp parallel` directive + +```cpp +#include + +int main() { + #pragma omp parallel + { + printf("Hello, World!\n"); + } + return 0; +} +``` + +Compile it like this + +```bash +# The OpenMP flat depends on the compiler +# intel : -openmp +# gcc : -fopenmp +# pgcc : -mp +gcc -fopenmp hello.c -o Hello +``` + +Running it should output + +``` +Hello, World! +... +Hello, World! +``` + +The exact number of "`Hello, Worlds`" depends on the number of cores of your machine, +for example I got 12 my laptop. + +## Threads and processes + +You can change the default number of threads using `export OMP_NUM_THREADS=8` + +Here are some useful library functions in the `omp.h` library + +```cpp +// Check the number of threads +printf("Max Threads: %d\n", omp_get_max_threads()); +printf("Current number of threads: %d\n", omp_get_num_threads()); +printf("Current Thread ID: %d\n", omp_get_thread_num()); + +// Modify the number of threads +omp_set_num_threads(int); + +// Check if we are in a parallel region +omp_in_parallel(); + +// Dynamically vary the number of threads +omp_set_dynamic(int); +omp_get_dynamic(); + +// Check the number of processors +printf("Number of processors: %d\n", omp_num_procs()); +``` + +## Private and shared variables + +```cpp +// Variables in parallel sections can be either private or shared. + +/* Private variables are private to each thread, as each thread has its own +* private copy. These variables are not initialized or maintained outside +* the thread. +*/ +#pragma omp parallel private(x, y) + +/* Shared variables are visible and accessible by all threads. By default, +* all variables in the work sharing region are shared except the loop +* iteration counter. +* +* Shared variables should be used with care as they can cause race conditions. +*/ +#pragma omp parallel shared(a, b, c) + +// They can be declared together as follows +#pragma omp parallel private(x, y) shared(a,b,c) +``` + +## Synchronization + +OpenMP provides a number of directives to control the synchronization of threads + +```cpp +#pragma omp parallel { + + /* `critical`: the enclosed code block will be executed by only one thread + * at a time, and not simultaneously executed by multiple threads. It is + * often used to protect shared data from race conditions. + */ + #pragma omp critical + data += data + computed; + + + /* `single`: used when a block of code needs to be run by only a single + * thread in a parallel section. Good for managing control variables. + */ + #pragma omp single + printf("Current number of threads: %d\n", omp_get_num_threads()); + + /* `atomic`: Ensures that a specific memory location is updated atomically + * to avoid race conditions. */ + #pragma omp atomic + counter += 1; + + + /* `ordered`: the structured block is executed in the order in which + * iterations would be executed in a sequential loop */ + #pragma omp for ordered + for (int i = 0; i < N; ++i) { + #pragma omp ordered + process(data[i]); + } + + + /* `barrier`: Forces all threads to wait until all threads reach this point + * before proceeding. */ + #pragma omp barrier + + /* `nowait`: Allows threads to proceed with their next task without waiting + * for other threads to complete the current one. */ + #pragma omp for nowait + for (int i = 0; i < N; ++i) { + process(data[i]); + } + + /* `reduction` : Combines the results of each thread's computation into a + * single result. */ + #pragma omp parallel for reduction(+:sum) + for (int i = 0; i < N; ++i) { + sum += a[i] * b[i]; + } + +} +``` + +Example of the use of `barrier` + +```c +#include +#include + +int main() { + + // Current number of active threads + printf("Num of threads is %d\n", omp_get_num_threads()); + +#pragma omp parallel + { + // Current thread ID + printf("Thread ID: %d\n", omp_get_thread_num()); + +#pragma omp barrier <--- Wait here until other threads have returned + if(omp_get_thread_num() == 0) + { + printf("\nNumber of active threads: %d\n", omp_get_num_threads()); + } + } + return 0; +} +``` + +## Parallelizing Loops + +It is simple to parallelise loops using OpenMP. Using a work-sharing directive we can do the following + +```c +#pragma omp parallel +{ + #pragma omp for + // for loop to be parallelized + for() ... +} +``` + +A loop must be easily parallelisable for OpenMP to unroll and facilitate the assignment amoungst threads. +If there are any data dependancies between one iteration to the next, OpenMP can't parallelise it. + +## Speed Comparison + +The following is a C++ program which compares parallelised code with serial code + +```cpp + +#include +#include +#include +#include +#include + +int main() { + const int num_elements = 100000000; + + std::vector a(num_elements, 1.0); + std::vector b(num_elements, 2.0); + std::vector c(num_elements, 0.0); + + // Serial version + auto start_time = std::chrono::high_resolution_clock::now(); + for (int i = 0; i < num_elements; i++) { + c[i] = a[i] * b[i]; + } + auto end_time = std::chrono::high_resolution_clock::now(); + auto duration_serial = std::chrono::duration_cast(end_time - start_time).count(); + + // Parallel version with OpenMP + start_time = std::chrono::high_resolution_clock::now(); + #pragma omp parallel for + for (int i = 0; i < num_elements; i++) { + c[i] = a[i] * b[i]; + } + end_time = std::chrono::high_resolution_clock::now(); + auto duration_parallel = std::chrono::duration_cast(end_time - start_time).count(); + + std::cout << "Serial execution time: " << duration_serial << " ms" << std::endl; + std::cout << "Parallel execution time: " << duration_parallel << " ms" << std::endl; + std::cout << "Speedup: " << static_cast(duration_serial) / duration_parallel << std::endl; + + return 0; +} +``` + +This results in + +``` +Serial execution time: 488 ms +Parallel execution time: 148 ms +Speedup: 3.2973 +``` + +It should be noted that this example is fairly contrived and the actual speedup +depends on implementation and it should also be noted that serial code may run +faster than parallel code due to cache preformace. + +## Example + +The following example uses OpenMP to calculate the Mandlebrot set + +```cpp +#include +#include +#include +#include +#include + +const int width = 2000; +const int height = 2000; +const int max_iterations = 1000; + +int mandelbrot(const std::complex &c) { + std::complex z = c; + int n = 0; + while (abs(z) <= 2 && n < max_iterations) { + z = z * z + c; + n++; + } + return n; +} + +int main() { + std::vector> values(height, std::vector(width)); + + // Calculate the Mandelbrot set using OpenMP + #pragma omp parallel for schedule(dynamic) + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + double real = (x - width / 2.0) * 4.0 / width; + double imag = (y - height / 2.0) * 4.0 / height; + std::complex c(real, imag); + + values[y][x] = mandelbrot(c); + } + } + + // Prepare the output image + std::ofstream image("mandelbrot_set.ppm"); + image << "P3\n" << width << " " << height << " 255\n"; + + // Write the output image in serial + for (int y = 0; y < height; y++) { + for (int x = 0; x < width; x++) { + int value = values[y][x]; + int r = (value % 8) * 32; + int g = (value % 16) * 16; + int b = (value % 32) * 8; + + image << r << " " << g << " " << b << " "; + } + image << "\n"; + } + + image.close(); + std::cout << "Mandelbrot set image generated as mandelbrot_set.ppm." << std::endl; + + return 0; +} +``` + +## Resources + +- [Intro to parallel programming](https://tildesites.bowdoin.edu/~ltoma/teaching/cs3225-GIS/fall17/Lectures/openmp.html) +- [Tutorials currated by OpenMP](https://www.openmp.org/resources/tutorials-articles/) +- [OpenMP cheatsheet](https://www.openmp.org/wp-content/uploads/OpenMPRefCard-5-2-web.pdf) From ef6f8dd275dadbc6ebd2d4cb07bec79a6b7b7808 Mon Sep 17 00:00:00 2001 From: hlischt <50388907+hlischt@users.noreply.github.com> Date: Mon, 13 May 2024 04:03:47 -0600 Subject: [PATCH 190/392] [go/es] Add Go Mobile mention and fix whitespace inconsistencies (#4411) --- es-es/go-es.html.markdown | 51 ++++++++++++++++++++++----------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/es-es/go-es.html.markdown b/es-es/go-es.html.markdown index 17bf4a22..3472a4ba 100644 --- a/es-es/go-es.html.markdown +++ b/es-es/go-es.html.markdown @@ -41,11 +41,11 @@ package main // La instrucción `import` declara los paquetes de bibliotecas referidos // en este fichero. import ( - "fmt" // Un paquete en la biblioteca estándar de Go. + "fmt" // Un paquete en la biblioteca estándar de Go. "io/ioutil" // Implementa algunas útiles funciones de E/S. - m "math" // Biblioteca de matemáticas con alias local m. - "net/http" // Sí, ¡un servidor web! - "strconv" // Conversiones de cadenas. + m "math" // Biblioteca de matemáticas con alias local m. + "net/http" // Sí, ¡un servidor web! + "strconv" // Conversiones de cadenas. ) // Definición de una función. `main` es especial. Es el punto de entrada @@ -63,7 +63,7 @@ func main() { // Si no hay parámetros, los paréntesis siguen siendo obligatorios. func másAlláDelHola() { var x int // Declaración de una variable. - // Las variables se deben declarar antes de utilizarlas. + // Las variables se deben declarar antes de utilizarlas. x = 3 // Asignación de variable. // Declaración "corta" con := para inferir el tipo, declarar y asignar. y := 4 @@ -76,7 +76,7 @@ func másAlláDelHola() { // Las funciones pueden tener parámetros y (¡múltiples!) valores de // retorno. func aprendeMúltiple(x, y int) (suma, producto int) { - return x + y, x * y // Devuelve dos valores. + return x + y, x * y // Devuelve dos valores. } // Algunos tipos incorporados y literales. @@ -113,7 +113,7 @@ saltos de línea.` // mismo tipo cadena // Para añadir elementos a un sector, se utiliza la función incorporada // append(). // El primer argumento es el sector al que se está anexando. Comúnmente, - // la variable del arreglo se actualiza en su lugar, como en el + // la variable del arreglo se actualiza en su lugar, como en el // siguiente ejemplo. sec := []int{1, 2 , 3} // El resultado es un sector de longitud 3. sec = append(sec, 4, 5, 6) // Añade 3 elementos. El sector ahora tiene una @@ -222,7 +222,7 @@ func aprendeControlDeFlujo() { // primero, luego comprobar y > x. if y := cálculoCaro(); y > x { x = y - } + } // Las funciones literales son "cierres". granX := func() bool { return x > 100 // Referencia a x declarada encima de la instrucción @@ -398,7 +398,7 @@ func aprendeConcurrencia() { // Una simple función del paquete http inicia un servidor web. func aprendeProgramaciónWeb() { -// El primer parámetro es la direccinón TCP a la que escuchar. + // El primer parámetro es la direccinón TCP a la que escuchar. // El segundo parámetro es una interfaz, concretamente http.Handler. go func() { err := http.ListenAndServe(":8080", par{}) @@ -427,24 +427,31 @@ func consultaAlServidor() { La raíz de todas las cosas sobre Go es el [sitio web oficial de Go](https://go.dev/). Allí puedes seguir el tutorial, jugar interactivamente y leer mucho más. +Aparte del recorrido, [la documentación](https://golang.org/doc/) tiene +información sobre cómo escribir código efectivo y limpio en Go, documentación de +paquetes y comandos, y el historial de versiones. -La definición del lenguaje es altamente recomendada. Es fácil de leer y -sorprendentemente corta (como la definición del lenguaje Go en estos -días). +La [definición del lenguaje](https://golang.org/ref/spec) es altamente recomendada. +Es fácil de leer y sorprendentemente corta +(relativo a las definiciones de lenguajes en estos días). Puedes jugar con el código en el -[parque de diversiones Go](https://go.dev/play/p/ncRC2Zevag). ¡Trata -de cambiarlo y ejecutarlo desde tu navegador! Ten en cuenta que puedes -utilizar [https://go.dev/play/]( https://go.dev/play/) como un -[REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) para probar -cosas y el código en el navegador, sin ni siquiera instalar Go. +[parque de diversiones Go](https://go.dev/play/p/ncRC2Zevag). ¡Trata +de cambiarlo y ejecutarlo desde tu navegador! Ten en cuenta que puedes +utilizar [https://go.dev/play/](https://go.dev/play/) como un +[REPL](https://es.wikipedia.org/wiki/REPL) para probar +cosas y el código en el navegador, sin tener que instalar Go. En la lista de lecturas para estudiantes de Go está el [código fuente de la biblioteca estándar](https://go.dev/src/). -Ampliamente documentado, que demuestra lo mejor del legible y comprensible -Go, con su característico estilo y modismos. ¡O puedes hacer clic en un -nombre de función en [la documentación](https://go.dev/pkg/) y +Ampliamente documentado, demuestra lo mejor del legible y comprensible +Go, con su característico estilo y modismos. ¡O puedes hacer clic en un +nombre de función en [la documentación](https://pkg.go.dev/std) y aparecerá el código fuente! -Otro gran recurso para aprender Go está en -[Go con ejemplos](http://goconejemplos.com/). +Go Mobile provee soporte para plataformas móbiles (Android y iOS). +Puedes escribir aplicaciones móbiles completamente en Go +o escribir una biblioteca con bindings de un paquete de Go, +que pueden invocarse en Java (en Android) y Objective-C (en iOS). +Visita la [página de Go Mobile](https://go.dev/wiki/Mobile) +para más información. From 5d9be7080dab9789f7b9485f6563c27dc2b7751f Mon Sep 17 00:00:00 2001 From: Dennis Keller Date: Mon, 13 May 2024 12:12:12 +0200 Subject: [PATCH 191/392] [clojure/de] Translate clojure (#3711) --- de-de/clojure-de.html.markdown | 422 +++++++++++++++++++++++++++++++++ 1 file changed, 422 insertions(+) create mode 100644 de-de/clojure-de.html.markdown diff --git a/de-de/clojure-de.html.markdown b/de-de/clojure-de.html.markdown new file mode 100644 index 00000000..1257b099 --- /dev/null +++ b/de-de/clojure-de.html.markdown @@ -0,0 +1,422 @@ +--- +language: clojure +filename: learnclojure-de.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Dennis Keller", "https://github.com/denniskeller"] +lang: de-de +--- + +Clojure ist ein Lispdialekt, der für die Java Virtual Maschine entwickelt worden ist. Sie hat eine stärkere Betonung auf reine [funktionale Programmierung](https://en.wikipedia.org/wiki/Functional_programming) als Common Lisp. Jedoch besitzt sie je nach Bedarf mehrere [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) Werkzeuge zur Handhabung von Zustand. + +Diese Verknüpfung erlaubt es parallele Verarbeitung sehr einfach und häufig automatisch zu verarbeiten. + +(Du brauchst die Clojure Version 1.2 oder neuer) + +```clojure +; Kommentare starten mit einem Semikolon. + +; Clojure wird in "Forms" geschrieben, was nur Listen von Dingen +; in Klammern sind, getrennt durch Leerzeichen. +; +; Der Clojure Leser nimmt an, dass das Erste, was aufgerufen wird +; eine Funktion oder ein Makro ist, der Rest sind Argumente. + +; Der erste Aufruf in einer Datei sollte ns sein, um den Namespacezu setzen. +(ns learnclojure) + +; Weitere einfache Beispiele: + +; str erstellt einen String aus allen Argumenten +(str "Hallo" " " "Welt") ; => "Hallo Welt" + +; Mathe ist einfach +(+ 1 1) ; => 2 +(- 2 1) ; => 1 +(* 1 2) ; => 2 +(/ 2 1) ; => 2 + +; Gleichheit ist = +(= 1 1) ; => true +(= 2 1) ; => false + +; Du brauchst auch not für Logik +(not true) ; => false + +; Verschachtelte Forms funktionieren, wie erwartet +(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2 + +; Typen +;;;;;;;;;;;;; + +; Clojure verwendet Javas Objekt Typen für Booleans, Strings und Zahlen. +; Verwende `class` um sie zu inszipieren. +(class 1) ; Integer Literalte sind standardmäßig java.lang.Long +(class 1.); Float Literale sind java.lang.Double +(class ""); Strings sind immer in doppelten Anführungszeichen notiert und sind java.lang.String +(class false) ; Booleans sind java.lang.Boolean +(class nil); Der "null" Wert heißt nil + +; Wenn du ein literale Liste aus Daten erzeugen willst, verwendest du ' um +; zu verhindern dass es evaluiert wird +'(+ 1 2) ; => (+ 1 2) +; (Kurzform für (quote (+ 1 2))) + +; Du kannst eine zitierte Liste evaluieren +(eval '(+ 1 2)) ; => 3 + +; Kollektioenn & Sequenzen +;;;;;;;;;;;;;;;;;;; + +; Listen sind Linked-Lists Datenstrukturen, während Vektoren arraybasierend sind. +; Vektoren und Listen sind auch Java Klassen! +(class [1 2 3]); => clojure.lang.PersistentVector +(class '(1 2 3)); => clojure.lang.PersistentList + +; Eine Liste würde nur als (1 2 3) geschrieben, aber wir müssen es zitieren +; damit der Leser aufhört zu denken, es sei eine Funktion. +; Außerdem ist (list 1 2 3) das Selbe, wie '(1 2 3) + +; "Kollektioen" sind nur Gruppen von Daten +; Listen und Vektoren sind Kolllektionen: +(coll? '(1 2 3)) ; => true +(coll? [1 2 3]) ; => true + +; "Sequenzen" (seqs) sind abstrakte Beschreibungen von Listen von Daten. +; Nur Listen sind seqs. +(seq? '(1 2 3)) ; => true +(seq? [1 2 3]) ; => false + +; Ein seq muss nur einen Eintrittspunkt bereitstellen, wenn auf ihm zugegriffen wird. +; Das heißt, dass seqs faul sein können -- Mit ihnen kann man unendliche Serien beschreiben. +(range 4) ; => (0 1 2 3) +(range) ; => (0 1 2 3 4 ...) (eine unendliche Serie) +(take 4 (range)) ; (0 1 2 3) + +; Verwende cons um ein Item zum Anfang einer Liste oder eines Vektors hinzuzufügen. +(cons 4 [1 2 3]) ; => (4 1 2 3) +(cons 4 '(1 2 3)) ; => (4 1 2 3) + +; Conj fügt ein Item auf die effizienteste Weise zu einer Kollektion hinzu. +; Für Listen fügt er sie an den Anfang hinzu. Für Vektoren fügt er sie an das Ende hinzu. +(conj [1 2 3] 4) ; => [1 2 3 4] +(conj '(1 2 3) 4) ; => (4 1 2 3) + +; Verwende concat um Listen und Vektoren miteinander zu verbinden +(concat [1 2] '(3 4)) ; => (1 2 3 4) + +; Verwende filter, map um mit Kollektionen zu interagieren +(map inc [1 2 3]) ; => (2 3 4) +(filter even? [1 2 3]) ; => (2) + +; Verwende reduce um sie zu reduzieren +(reduce + [1 2 3 4]) +; = (+ (+ (+ 1 2) 3) 4) +; => 10 + +; Reduce kann auch einen Initalwert als Argument verwenden +(reduce conj [] '(3 2 1)) +; = (conj (conj (conj [] 3) 2) 1) +; => [3 2 1] + +; Funktionen +;;;;;;;;;;;;;;;;;;;;; + +; Verwende fn um neue Funktionen zu erstellen. Eine Funktion gibt immer ihr +; letztes Statement zurück. +(fn [] "Hallo Welt") ; => fn + +; (Du brauchst exta Klammern um sie aufzurufen) +((fn [] "Hallo Welt")) ; => "Hallo Welt" + +; Du kannst eine Variable mit def erstellen +(def x 1) +x ; => 1 + +; Weise eine Funktion einer Variable zu +(def hello-world (fn [] "Hallo Welt")) +(hello-world) ; => "Hallo Welt" + +; Du kannst den Prozess verkürzen indem du defn verwendest +(defn hello-world [] "Hallo Welt") + +; [] ist die Liste der Argumente für die Funktion +; The [] is the list of arguments for the function. +(defn hello [name] + (str "Hallo " name)) +(hello "Steve") ; => "Hallo Steve" + +; Du kannst diese Kurzschreibweise verwenden um Funktionen zu erstellen: +(def hello2 #(str "Hallo " %1)) +(hello2 "Julie") ; => "Hallo Julie" + +; Du kannst auch multi-variadische Funktionen haben +(defn hello3 + ([] "Hallo Welt") + ([name] (str "Hallo " name))) +(hello3 "Jake") ; => "Hallo Jake" +(hello3) ; => "Hallo Welt" + +; Funktionen können auch extra Argumente in einem seq für dich speichern +(defn count-args [& args] + (str "Du hast " (count args) " Argumente übergeben: " args)) +(count-args 1 2 3) ; => "Du hast 3 Argumente übergeben: (1 2 3)" + +; Du kannst reguläre und gepackte Argumente mischen +(defn hello-count [name & args] + (str "Hallo " name ", Du hast " (count args) " extra Argumente übergeben")) +(hello-count "Finn" 1 2 3) +; => "Hallo Finn, Du hast 3 extra Argumente übergeben" + + +; Maps +;;;;;;;;;; + +; Hash maps und Array maps teilen sich ein Interface. Hash maps haben eine schnellere Zugriffszeit, +; aber behalten keine Schlüsselreihenfolge. +(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap +(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap + +; Arraymaps werden durch die meisten Operatioen automatisch zu Hashmaps, +; sobald sie groß genug werden. Das heißt du musst dich nicht darum sorgen. + +; Maps können einen beliebigen Hash-Typ als Schlüssel verwenden, in der Regel +; sind jedoch Keywords am besten. Keywords sind wie Strings, jedoch besitzen sie +; Performancevorteile +(class :a) ; => clojure.lang.Keyword + +(def stringmap {"a" 1, "b" 2, "c" 3}) +stringmap ; => {"a" 1, "b" 2, "c" 3} + +(def keymap {:a 1, :b 2, :c 3}) +keymap ; => {:a 1, :c 3, :b 2} + +; Übrigens werden Kommas als Leerzeichen behandelt und machen nichts. + +; Rufe einen Wert von einer Map ab, indem du sie als Funktion aufrufst +(stringmap "a") ; => 1 +(keymap :a) ; => 1 + +; Keywords können auch verwendet werden um ihren Wert aus der Map zu bekommen! +(:b keymap) ; => 2 + +; Versuche es nicht mit Strings. +;("a" stringmap) +; => Exception: java.lang.String cannot be cast to clojure.lang.IFn + +; Das Abrufen eines nicht vorhandenen Keys gibt nil zurück +(stringmap "d") ; => nil + +; Verwende assoc um einen neuen Key zu einer Hash-map hinzuzufügen +(def newkeymap (assoc keymap :d 4)) +newkeymap ; => {:a 1, :b 2, :c 3, :d 4} + +; Aber denk daran, Clojure Typen sind unveränderlich! +keymap ; => {:a 1, :b 2, :c 3} + +; Verwende dissoc um Keys zu entfernen +(dissoc keymap :a :b) ; => {:c 3} + +; Sets +;;;;;; + +(class #{1 2 3}) ; => clojure.lang.PersistentHashSet +(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3} + +; Füge ein Element mit conj hinzu +(conj #{1 2 3} 4) ; => #{1 2 3 4} + +; Entferne ein Element mit disj +(disj #{1 2 3} 1) ; => #{2 3} + +; Teste auf Existenz, indem du das Set als Funktion verwendest: +(#{1 2 3} 1) ; => 1 +(#{1 2 3} 4) ; => nil + +; Es gibt mehr Funktionen in dem clojure.sets Namespace. + +; Nützliche Forms +;;;;;;;;;;;;;;;;; + +; Logische Konstrukte in Clojure sind nur Makros und sie sehen, wie alles +; andere aus +(if false "a" "b") ; => "b" +(if false "a") ; => nil + +; Verwende let um temporäre Bindungen aufzubauen +(let [a 1 b 2] + (> a b)) ; => false + +; Gruppiere Statements mit do zusammen +; Group statements together with do +(do + (print "Hallo") + "Welt") ; => "Welt" (prints "Hallo") + +; Funktionen haben ein implizites do +(defn print-and-say-hello [name] + (print "Sage Hallo zu " name) + (str "Hallo " name)) +(print-and-say-hello "Jeff") ;=> "Hallo Jeff" (prints "Sage Hallo zu Jeff") + +; let macht das auch +(let [name "Urkel"] + (print "Sage Hallo zu " name) + (str "Hallo " name)) ; => "Hallo Urkel" (prints "Sage Hallo zu Urkel") + + +; Verwende die Threading Makros (-> and ->>) um Transformationen von +; Daten deutlicher auszudrücken. + +; Das "Thread-zuerst" Makro (->) fügt in jede Form das Ergebnis des +; Vorherigen als erstes Argument (zweites Element) ein. +(-> + {:a 1 :b 2} + (assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3) + (dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b) + +; Dieser Ausdruck kann auch als so geschrieben werden: +; (dissoc (assoc {:a 1 :b 2} :c 3) :b) +; and evaluates to {:a 1 :c 3} + +; Der Doppelpfeil macht das Selbe, aber er fügt das Ergebnis von jeder +; Zeile an das Ende der Form, Das ist vor allem für Operationen auf +; Kollektionen nützlich: +(->> + (range 10) + (map inc) ;=> (map inc (range 10) + (filter odd?) ;=> (filter odd? (map inc (range 10)) + (into [])) ;=> (into [] (filter odd? (map inc (range 10))) + ; Result: [1 3 5 7 9] + +; Wenn du in einer Situation bist, in der du mehr Freiheit willst, +; wohin du das Ergebnis vorheriger Datentransformationen in einem Ausruck +; platzieren möchtest, kannst du das as-> Macro verwenden. Mit diesem Macro +; kannst du einen speziellen Namen auf die Ausgabe einer Transformationen geben. +; Du kannst es als Platzhalter in verketteten Ausdrücken verwenden: + +(as-> [1 2 3] input + (map inc input);=> Du kannst die letzte Ausgabe der Transformation in der letzten Position verwenden + (nth input 2) ;=> und auch in der zweiten Position, im selben Ausdruck verwenden + (conj [4 5 6] input [8 9 10])) ;=> oder auch in der Mitte! + + + +; Module +;;;;;;;;;;;;;;; + +; Verwende "use" um alle Funktionen aus einem Modul zu bekommen +(use 'clojure.set) + +; Nun können wir set Operationen verwenden +(intersection #{1 2 3} #{2 3 4}) ; => #{2 3} +(difference #{1 2 3} #{2 3 4}) ; => #{1} + +; Du kannst auch auswählen nur ein Subset von Funktionen zu importieren +(use '[clojure.set :only [intersection]]) + +; Verwende require um ein Modul zu importieren +(require 'clojure.string) + +; Verwende / um eine Funktion aus einem Modul aufzurufen +; Hier verwenden wir das Modul clojure.string und die Funktion blank? +(clojure.string/blank? "") ; => true + +; Du kannst auch einem Modul einem kürzerern Namen beim Import geben +(require '[clojure.string :as str]) +(str/replace "Das ist ein Test." #"[a-o]" str/upper-case) ; => "DAs IsT EIN TEsT." +; (#"" bezeichnet einen regulären literalen Ausdruck) + +; Du kannst require aus einem Namespace verwenden (auch use ist möglich, aber nicht zu empfehlen) +; indem du :require verwendest. +; Du brauchst keine Zitierzeichen für deine Module verwenden, wenn du +; es auf diese Weise machst. +(ns test + (:require + [clojure.string :as str] + [clojure.set :as set])) + +; Java +;;;;;;;;;;;;;;;;; + +; Java hat eine riesige und nützliche Standardbibliothek, +; du möchtest lernen wie man sie verwendet. + +; Verwende import um ein Java modul zu laden. +(import java.util.Date) + +; Du kannst auch von einem ns importieren. +(ns test + (:import java.util.Date + java.util.Calendar)) + +; Verwende den Klassennamen mit einem "." am Ende, um eine neue Instanz zu erstellen +(Date.) ; + +; Verwende . um Methoden aufzurufen oder verwende die ".method" Abkürzung +(. (Date.) getTime) ; +(.getTime (Date.)) ; Genau das Selbe + +; Verwende / um statische Methoden aufzurufen +(System/currentTimeMillis) ; (system ist immer da) + +; Verwende doto um mit veränderliche Klassen besser umzugehen +(import java.util.Calendar) +(doto (Calendar/getInstance) + (.set 2000 1 1 0 0 0) + .getTime) ; => A Date. set to 2000-01-01 00:00:00 + +; STM +;;;;;;;;;;;;;;;;; + +; Software Transactional Memory ist der Mechanismus, den Clojure verwendet +; um mit persistenten Zuständen umzugehen. Es gibt ein Paar Konstrukte in +; Clojure die es verwenden. + +; Ein Atom ist das Einfachste. Gebe es einen Initalwert +(def my-atom (atom {})) + +; Update ein Atom mit swap!. +; swap! nimmt eine Funktion und ruft sie mit dem aktuellen Zustand des +; Atoms auf und alle nachfolgenden Argumente als das Zweite +(swap! my-atom assoc :a 1) ; Setzt my-atom zu dem Ergebnis von (assoc {} :a 1) +(swap! my-atom assoc :b 2) ; Setzt my-atom zu dem Ergebnis von (assoc {:a 1} :b 2) + +; Verwende '@' um das Atom zu dereferenzieren und den Wert zu bekommen +my-atom ;=> Atom<#...> (Gibt das Atom Objekt zurück +@my-atom ; => {:a 1 :b 2} + +; Hier ist ein einfacher Zähler mit einem Atom +(def counter (atom 0)) +(defn inc-counter [] + (swap! counter inc)) + +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) +(inc-counter) + +@counter ; => 5 + +; Andere STM Konstrukte sind refs und agents. +; Refs: http://clojure.org/refs +; Agents: http://clojure.org/agents +``` + +### Weiterführende Literatur + +Das ist alles andere als erschöpfend, aber hoffentlich ist es genug, um dich auf die Beine zu stellen. + +Clojure.org hat eine Menge von Artikeln: +[http://clojure.org/](http://clojure.org/) + +Clojuredocs.org hat eine Dokumentation mit Beispielen für die meisten Kernfunktionen +[http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) + +4Clojure ist eine gute Möglichkeit um deine clojure/FP zu verbessern: +[http://www.4clojure.com/](http://www.4clojure.com/) + +Clojure-doc.org (ja, wirklich) hat eine Reihe von Artikeln zum Starten: +[http://clojure-doc.org/](http://clojure-doc.org/) From 711d3ba152dc576e56aaadef1718b5de185ccb94 Mon Sep 17 00:00:00 2001 From: Krasov Ilia Date: Mon, 13 May 2024 16:26:13 +0600 Subject: [PATCH 192/392] [javascript/ru] Update links in docs (#4943) --- ru-ru/javascript-ru.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ru-ru/javascript-ru.html.markdown b/ru-ru/javascript-ru.html.markdown index 4c4fa503..cf925406 100644 --- a/ru-ru/javascript-ru.html.markdown +++ b/ru-ru/javascript-ru.html.markdown @@ -507,8 +507,8 @@ if (Object.create === undefined) { // не перезаписываем мето Кроме того, это вики. Поэтому, если вы знаете больше, вы можете помочь другим, делясь своими знаниями. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/ru/) — это +[JavaScript Garden](https://shamansir.github.io/JavaScript-Garden/ru/) — это подробное руководство по всем неинтуитивным особенностей языка. -[Stack Overflow](http://stackoverflow.com/questions/tagged/javascript) — можно +[Stack Overflow](https://stackoverflow.com/questions/tagged/javascript) — можно найти ответ почти на любой ваш вопрос, а если его нет, то задать вопрос самому. From e7271a9e1c215bf690652dd79ce1b814ecc1e308 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 13 May 2024 04:29:03 -0600 Subject: [PATCH 193/392] [elisp/*] minibuffer -> echo area (#4941) --- es-es/elisp-es.html.markdown | 4 ++-- ms-my/elisp-my.html.markdown | 4 ++-- pt-br/elisp-pt.html.markdown | 4 ++-- zh-cn/elisp-cn.html.markdown | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/es-es/elisp-es.html.markdown b/es-es/elisp-es.html.markdown index a6cd3934..6c10c939 100644 --- a/es-es/elisp-es.html.markdown +++ b/es-es/elisp-es.html.markdown @@ -96,12 +96,12 @@ filename: learn-emacs-lisp-es.el ;; `C-j' añade el resultado de la evaluación al buffer. ;; `C-xC-e' muestra el mismo resultado pero en la linea inferior -;; la cual se llama "minibuffer". Este será el metodo que usaremos +;; la cual se llama "echo area". Este será el metodo que usaremos ;; normalmente para no llenar el buffer con texto inútil. ;; `setq' guarda un valor en una variable: (setq my-name "Bastien") -;; `C-xC-e' => "Bastien" (aparece en el mini-buffer) +;; `C-xC-e' => "Bastien" (aparece en el echo area) ;; `insert' añade "Hello!" en el punto donde esté tu cursor: (insert "Hello!") diff --git a/ms-my/elisp-my.html.markdown b/ms-my/elisp-my.html.markdown index 73dff0f4..d5c519f7 100644 --- a/ms-my/elisp-my.html.markdown +++ b/ms-my/elisp-my.html.markdown @@ -80,12 +80,12 @@ filename: learn-emacs-lisp-ms.el ;; `C-j' memasukkan jawapan pengiraan ke dalam buffer. ;; `C-xC-e' memaparkan jawapan yang sama di bahagian bawah Emacs, -;; yang dipanggil "minibuffer". Secara umumnya kita akan menggunakan `C-xC-e', +;; yang dipanggil "echo area". Secara umumnya kita akan menggunakan `C-xC-e', ;; sebab kita tidak mahu memenuhi buffer dengan teks yang tidak penting. ;; `setq' menyimpan value ke dalam variable: (setq my-name "Bastien") -;; `C-xC-e' => "Bastien" (terpapar di mini-buffer) +;; `C-xC-e' => "Bastien" (terpapar di echo area) ;; `insert' akan memasukkan "Hello!" di tempat di mana cursor berada: (insert "Hello!") diff --git a/pt-br/elisp-pt.html.markdown b/pt-br/elisp-pt.html.markdown index aa611097..8378003e 100644 --- a/pt-br/elisp-pt.html.markdown +++ b/pt-br/elisp-pt.html.markdown @@ -82,12 +82,12 @@ filename: learn-emacs-lisp-pt.el ;; `C-j' insere o resultado da interpretação da expressão no buffer. ;; `C-xC-e' exibe o mesmo resultado na linha inferior do Emacs, -;; chamada de "mini-buffer". Nós geralmente utilizaremos `C-xC-e', +;; chamada de "echo area". Nós geralmente utilizaremos `C-xC-e', ;; já que não queremos poluir o buffer com texto desnecessário. ;; `setq' armazena um valor em uma variável: (setq my-name "Bastien") -;; `C-xC-e' => "Bastien" (texto exibido no mini-buffer) +;; `C-xC-e' => "Bastien" (texto exibido no echo area) ;; `insert' insere "Hello!" na posição em que se encontra seu cursor: (insert "Hello!") diff --git a/zh-cn/elisp-cn.html.markdown b/zh-cn/elisp-cn.html.markdown index a429fcbc..11dc304b 100644 --- a/zh-cn/elisp-cn.html.markdown +++ b/zh-cn/elisp-cn.html.markdown @@ -79,12 +79,12 @@ lang: zh-cn ;; `C-j' 会在buffer中插入当前运算的结果 -;; 而`C-xC-e' 则会在emacs最底部显示结果,也就是被称作"minibuffer"的区域 +;; 而`C-xC-e' 则会在emacs最底部显示结果,也就是被称作"echo area"的区域 ;; 为了避免把我们的buffer填满无用的结果,我们以后会一直用`C-xC-e' ;; `setq' 可以将一个值赋给一个变量 (setq my-name "Bastien") -;; `C-xC-e' 输出 "Bastien" (在 mini-buffer 中显示) +;; `C-xC-e' 输出 "Bastien" (在 echo area 中显示) ;; `insert' 会在光标处插入字符串: (insert "Hello!") From e50493e4d327f8921093f6ae61deabcecdb3b18b Mon Sep 17 00:00:00 2001 From: Romans Malinovskis Date: Mon, 13 May 2024 13:02:59 +0100 Subject: [PATCH 194/392] [hcl/en] Add guide for Terraform/HCL (#3949) * add hcl * wip * Proofread --------- Co-authored-by: Boris Verkhovskiy --- hcl.html.markdown | 368 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 368 insertions(+) create mode 100644 hcl.html.markdown diff --git a/hcl.html.markdown b/hcl.html.markdown new file mode 100644 index 00000000..4ab26842 --- /dev/null +++ b/hcl.html.markdown @@ -0,0 +1,368 @@ +--- +category: tool +tool: HCL +contributors: + - ["Romans Malinovskis" , "http://github.com/romaninsh"] +filename: terraform.txt +--- +## Introduction + +HCL (Hashicorp Configuration Language) is a high-level configuration language used in tools from +Hashicorp (such as Terraform). HCL/Terraform is widely used in provisioning cloud infastructure and +configuring platforms/services through APIs. This document focuses on HCL 0.13 syntax. + +HCL is a declarative language and Terraform will consume all `*.tf` files in the current folder, so code +placement and sequence has no significance. Sub-folders can be consumed through modules. + +This guide is focused on HCL specifics, you should already be familiar with what Terraform is. + +```terraform +// Top-level HCL file will interactively ask user values for the variables +// which do not have a default value +variable "ready" { + description = "Ready to learn?" + type = bool + // default = true +} + +// Module block consults a specified folder for *.tf files, would +// effectively prefix all resources IDs with "module.learn-basics." +module "learn-basics" { + source = "./learn-basics" + ready_to_learn = var.ready +} + +output "knowledge" { + value = module.learn-basics.knowledge +} +``` + +## learn-basics + +```terraform +// Variables are not automatically passed into modules +// and can be typeless. +variable "ready" { +} + +// It is good practice to define a type though. There are 3 primitive types - +// 3 collection types and 2 structural types. Structural types define +// types recursively +variable "structural-types" { + type = object({ + object: object({ + can-be-nested: bool + }), + tuple: tuple([int, string]) + }) + + default = { + object = { can-be-nested: true } + tuple = [3, "cm"] + } +} + +// Collection types may specify a type, but can also be "any". +variable "list" { + type: list(string) + default = ["red", "green", "blue"] +} + +variable "map" { + type: map(any) + default = { + red = "#FF0000" + "green" = "#00FF00" + } +} + +variable "favourites" { + type: set + default = ["red", "blue"] +} + +// When the type is not specified or is a mix of scalars +// they will be converted to strings. + +// Use modern IDEs for type completion features. It does not matter +// in which file and in which order you define a variable, it becomes +// accessible from anywhere. + +// Default values for variables may not use expressions, but you can +// use locals for that. You don't specify types for locals. With locals +// you can create intermediate products from other variables, modules, +// and functions. + +locals { + ready = var.ready ? "yes": "no" + + yaml = yamldecode(file("${path.module}/file-in-current-folder.yaml")) +} + +// 'locals' blocks can be defined multiple times, but all variables, +// resources and local names should be unique + +locals { + set = toset(var.map) +} + +module "more-resources" { + source = "../more-learning" + yaml-data = local.yaml +} + +// Modules can declare outputs, that can be optionally referenced +// (see above), typically outputs appear at the bottom of the file or +// in "outputs.tf". +output "knowledge" { + value = "types so far, more to come" +} +``` + +Terraform exists for managing cloud "resources". A resource could be anything as long as it +can be created and destroyed through an API call. (compute instance, distribution, +DNS record, S3 bucket, SSL certificate or permission grant). Terraform relies on "providers" +for implementing specific vendor APIs. For example the "aws" provider enables use of resources +for managing AWS cloud resources. + +When `terraform` is invoked (`terraform apply`) it will validate code, create all resources +in memory, load their existing state from a file (state file), refresh against the current +cloud APIs and then calculate the differences. Based on the differences, Terraform proposes +a "plan" - series of create, modify or delete actions to bring your infrastructrue in +alignment with an HCL definition. + +Terraform will also automatically calculate dependencies between resources and will maintain +the correct create / destroy order. Failure during execution allows you to retry the entire +process, which will usually pick off where things finished. + +## more-learning + +Time to introduce resources. + +```terraform +variable "yaml-data" { + + // config is sourced from a .yaml file, so technically it is a + // map(any), but we can narrow down type like this: + type = map(string) +} + +// You do not need to explicitly define providers, they all have reasonable +// defaults with environment variables. Using a resource that relies on a +// provider will also transparently initialize it (when you invoke terraform init) +resource "aws_s3_bucket" "bucket" { + bucket = "abc" +} + +// You can also create provider aliases +provider "aws" { + alias = "as-role" + assume_role { + role_arn = ".." + } +} + +// then use them to create resources +resource "aws_s3_bucket_object" "test-file" { + + // all resources have attributes that can be referenced. Some of those + // will be available right away (like bucket) and others may only + // become available after the plan begins executing. The test-file resource + // will be created only after aws_s3_bucket.bucket finishes being created + + // depends_on = aws_s3_bucket.bucket + bucket = aws_s3_bucket.bucket.bucket + key = "index.html" + content = file("${path.module}/index.html") + + // you can also manually specify provider alias + provider = aws.as-role +} + +// Each resource will receive an ID in state, like "aws_s3_bucket.bucket". +// When resources are created inside a module, their state ID is prepended +// with module. + +module "learn-each" { + source = "../learn-each" +} + +// Nesting modules like this may not be the best practice, and it's only +// used here for illustration purposes +``` + +## learn-each + +Terraform offers some great features for creating series of objects: + +```terraform +locals { + list = ["red", "green", "blue"] +} +resource "aws_s3_bucket" "badly-coloured-bucket" { + count = count(local.list) + bucket_prefix = "${local.list[count.index]}-" +} +// will create 3 buckets, prefixed with "red-", etc. and followed by +// a unique identifier. Some resources will automatically generate +// a random name if not specified. The actual name of the resource +// (or bucket in this example) can be referenced as attributes + +output "red-bucket-name" { + value = aws_s3_bucket.badly-coloured-bucket[0].bucket +} + +// note that bucket resource ID will be "aws_s3_bucket.badly-coloured-bucket[0]" +// through to 2, because they are list index elements. If you remove "red" from +// the list, however, it will re-create all the buckets as they would now +// have new IDs. A better way is to use for_each + +resource "aws_s3_bucket" "coloured-bucket" { + // for_each only supports maps and sets + for_each = toset(local.list) + bucket_prefix = "${each.value}-" +} + +// the name for this resource would be aws_s3_bucket.coloured-bucket[red] + +output "red-bucket-name2" { + value = aws_s3_bucket.badly-coloured-bucket["red"].bucket +} + +output "all-bucket-names" { + + // returns a list containing bucket names - using a "splat expression" + value = aws_s3_bucket.coloured-bucket[*].bucket +} + +// there are other splat expressions: +output "all-bucket-names2" { + value = [for b in aws_s3_bucket.coloured-bucket: b.bucket] +} +// can also include a filter +output "filtered-bucket-names" { + value = [for b in aws_s3_bucket.coloured-bucket: + b.bucket if length(b.bucket) < 10 ] +} + +// here are some ways to generate maps {red: "red-123123.."} +output "bucket-map" { + value = { + for b in aws_s3_bucket.coloured-bucket: + trimsuffix(b.bucket_prefix, '-') + => b.bucket + } +} + +// as of Terraform 0.13 it is now also possible to use count/each for modules + +variable "learn-functions" { + type = bool + default = true +} + +module "learn-functions" { + count = var.learn-functions ? 1: 0 + source = "../learn-functions" +} +``` + +This is now popular syntax that works in Terraform 0.13 that allows including modules conditionally. + +## learn-functions + +Terraform does not allow you to define your own functions, but there's an extensive list of built-in functions + +```terraform +locals { + list = ["one", "two", "three"] + + upper_list = [for x in local.list : upper(x) ] // "ONE", "TWO", "THREE" + + map = {for x in local.list : x => upper(x) } // "one":"ONE", "two":"TWO", "three":"THREE" + + filtered_list = [for k, v in local.map : substr(v, 0, 2) if k != "two" } // "ON", "TH" + + prefixed_list = [for v in local.filtered_list : "pre-${k}" } // "pre-ON", "pre-TH" + + joined_list = join(local.upper_list,local. filtered_list) // "ONE", "TWO", "THREE", "pre-ON", "pre-TH" + + // Set is very similar to List, but element order is irrelevant + joined_set = toset(local.joined_list) // "ONE", "TWO", "THREE", "pre-ON", "pre-TH" + + map_again = map(slice(local.joined_list, 0, 4)) // "ONE":"TWO", "THREE":"pre-ON" +} + +// Usually list manipulation can be useful either for a resource with for_each or +// to specify a dynamic block for a resource. This creates a bucket with some tags: + +resource "aws_s3_bucket" "bucket" { + name = "test-bucket" + tags = local.map_again +} + +// this is identical to: +// resource "aws_s3_bucket" "bucket" { +// name = "test-bucket" +// tags = { +// ONE = "TWO" +// THREE = "pre-ON" +// } +// } + +// Some resources also contain dynamic blocks. The next example uses a "data" block +// to look up 3 buckets (red, green and blue), then creates a policy that contains +// read-only access to the red and green buckets and full access to the blue bucket. + +locals { + buckets = { + red = "read-only" + green = "read-only" + blue = "full" + } + // we could load buckets from a file: + // bucket = file('bucket.json') + + actions = { + "read-only" = ["s3:GetObject", "s3:GetObjectVersion"], + "full" = ["s3:GetObject", "s3:GetObjectVersion", "s3:PutObject", "s3:PutObjectVersion"] + } + // we will look up actions, so that we don't have to repeat actions +} + +// use a function to convert map keys into set +data "aws_s3_bucket" "bucket" { + for_each = toset(keys(local.buckets)) + bucket = each.value +} + +// create json for our policy +data "aws_iam_policy_document" "role_policy" { + statement { + effect = "Allow" + actions = [ + "ec2:*", + ] + resources = ["*"] + } + + dynamic "statement" { + for_each = local.buckets + content { + effect = "Allow" + actions = lookup(local.actions, statement.value, null) + resources = [data.aws_s3_bucket.bucket[statement.key]] + } + } +} + +// and this actually creates the AWS policy with permissions to all buckets +resource "aws_iam_policy" "policy" { + policy = data.aws_iam_policy_document.role_policy.json +} +``` + +## Additional Resources + +- [Terraform tips & tricks](https://blog.gruntwork.io/terraform-tips-tricks-loops-if-statements-and-gotchas-f739bbae55f9) +- [Building Dynamic Outputs with Terraform Expressions and Functions](https://www.thegreatcodeadventure.com/building-dynamic-outputs-with-terraform-for_each-for-and-zipmap/) From bd5b3fb3924684fbc80ba95520ea8fd1b0e0b76b Mon Sep 17 00:00:00 2001 From: Paulo Moura Date: Mon, 13 May 2024 13:11:24 +0100 Subject: [PATCH 195/392] [logtalk/en] [logtalk/it] Update for the current major version of the language (#4526) --- it-it/logtalk-it.html.markdown | 12 +++++++++--- logtalk.html.markdown | 14 ++++++++++---- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/it-it/logtalk-it.html.markdown b/it-it/logtalk-it.html.markdown index dfb9cd27..4fbf2d10 100644 --- a/it-it/logtalk-it.html.markdown +++ b/it-it/logtalk-it.html.markdown @@ -379,6 +379,9 @@ Se il codice sorgente dell'oggetto non è disponibile e bisogna correggere l'app Dopo la compilazione e il caricamento della categoria nell'applicazione in esecuzione si ottiene: ```logtalk +?- set_logtalk_flag(complements, allow). +yes + ?- {patch}. yes @@ -387,7 +390,7 @@ bar yes ``` -Poiché l'hot-patching pregiudica forzatamente l'incapsulamento, un apposito flag di compilazione `complementary` può essere impostato (a livello globale o per un singolo oggetto) per consentire, limitare o prevenire l'hot-patching. +Poiché l'hot-patching interrompe forzatamente l'incapsulamento, è possibile impostare il flag del compilatore `complementary` può essere impostato (a livello globale o per un singolo oggetto) per consentire, limitare o prevenire l'hot-patching. # Oggetti Parametrici e Categorie @@ -463,6 +466,9 @@ Logtalk supporta l'_event-driven programming_ mediante la definizione di eventi Supponendo che l'oggetto `tracer` e l'oggetto `list` definito in precedenza siano stati già compilati e caricati, si possono osservare i gestori di eventi in azione durante l'invio di un messaggio: ```logtalk +?- set_logtalk_flag(events, allow). +yes + ?- list::member(X, [1,2,3]). call: list <-- member(X, [1,2,3]) from user @@ -481,11 +487,11 @@ La programmazione event-driven può essere vista come una forma di _computationa # Espressioni lambda -Logtalk supporta anche le espressioni lambda. I parametri della espressioni lambda sono rappresentati mediante una lista con l'operatore infisso `(>>)/2` che collega i parametri alla relativa lambda espressione. Ecco alcuni semplici esempi di che usano i meta-predicati. +Logtalk supporta anche le espressioni lambda. I parametri della espressioni lambda sono rappresentati mediante una lista con l'operatore infisso `(>>)/2` che collega i parametri alla relativa lambda espressione. Ecco alcuni semplici esempi che utilizzano la libreria `meta`. ```logtalk -?- {library(metapredicates_loader)}. +?- {meta(loader)}. yes ?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys). diff --git a/logtalk.html.markdown b/logtalk.html.markdown index ce907ee3..8c6b87dd 100644 --- a/logtalk.html.markdown +++ b/logtalk.html.markdown @@ -1,8 +1,8 @@ --- language: Logtalk +filename: learnlogtalk.lgt contributors: - ["Paulo Moura", "http://github.com/pmoura"] -filename: learnlogtalk.lgt --- Logtalk is an object-oriented logic programming language that extends and leverages Prolog with modern code encapsulation and code reuse mechanisms without compromising its declarative programming features. Logtalk is implemented in highly portable code and can use most modern and standards compliant Prolog implementations as a back-end compiler. @@ -376,6 +376,9 @@ If the object source code is not available and we need to fix an application run After compiling and loading the category into the running application we will now get: ```logtalk +?- set_logtalk_flag(complements, allow). +yes + ?- {patch}. yes @@ -384,7 +387,7 @@ bar yes ``` -As hot-patching forcefully breaks encapsulation, there is a `complements` compiler flag that can be set (globally or on a per-object basis) to allow, restrict, or prevent it. +As hot-patching forcefully breaks encapsulation, the `complements` compiler flag can be set (globally or on a per-object basis) to allow, restrict, or prevent it. # Parametric objects and categories @@ -460,6 +463,9 @@ Logtalk supports _event-driven programming_ by allowing defining events and moni Assuming that the `tracer` object and the `list` object defined earlier are compiled and loaded, we can observe the event handlers in action by sending a message: ```logtalk +?- set_logtalk_flag(events, allow). +yes + ?- list::member(X, [1,2,3]). call: list <-- member(X, [1,2,3]) from user @@ -478,10 +484,10 @@ Event-driven programming can be seen as a form of _computational reflection_. Bu # Lambda expressions -Logtalk supports lambda expressions. Lambda parameters are represented using a list with the `(>>)/2` infix operator connecting them to the lambda. Some simple examples using library meta-predicates: +Logtalk supports lambda expressions. Lambda parameters are represented using a list with the `(>>)/2` infix operator connecting them to the lambda. Some simple examples using library `meta`: ```logtalk -?- {library(metapredicates_loader)}. +?- {meta(loader)}. yes ?- meta::map([X,Y]>>(Y is 2*X), [1,2,3], Ys). From 4bf3759c17cc03e8588309d93dc0fea1571dc668 Mon Sep 17 00:00:00 2001 From: Luke Holmes <36161628+lukeholmescodes@users.noreply.github.com> Date: Mon, 13 May 2024 13:18:05 +0100 Subject: [PATCH 196/392] [kdb+/en] Update KX links (#4569) --- kdb+.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/kdb+.html.markdown b/kdb+.html.markdown index 0573067d..2c8c83fa 100644 --- a/kdb+.html.markdown +++ b/kdb+.html.markdown @@ -74,7 +74,7 @@ floor 3.14159 / => 3 / ...getting the absolute value... abs -3.14159 / => 3.14159 / ...and many other things -/ see http://code.kx.com/q/ref/card/ for more +/ see http://code.kx.com/q/ref/ for more / q has no operator precedence, everything is evaluated right to left / so results like this might take some getting used to @@ -713,8 +713,8 @@ first each (1 2 3;4 5 6;7 8 9) {x + y}\[1 2 3 4 5] / => 1 3 6 10 15 (i.e. the running sum) {x + y}/[1 2 3 4 5] / => 15 (only the final result) -/ There are other adverbs and uses, this is only intended as quick overview -/ http://code.kx.com/q4m3/6_Functions/#67-adverbs +/ There are other iterators and uses, this is only intended as quick overview +/ http://code.kx.com/q4m3/6_Functions/#67-iterators ////// Scripts ////// / q scripts can be loaded from a q session using the "\l" command From 872840d680b51290ff22941cef721b984154919d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Reynier?= <88983487+loicreynier@users.noreply.github.com> Date: Mon, 13 May 2024 14:28:20 +0200 Subject: [PATCH 197/392] [nix/fr]: Add French translation (#4518) --- fr-fr/nix-fr.html.markdown | 395 +++++++++++++++++++++++++++++++++++++ 1 file changed, 395 insertions(+) create mode 100644 fr-fr/nix-fr.html.markdown diff --git a/fr-fr/nix-fr.html.markdown b/fr-fr/nix-fr.html.markdown new file mode 100644 index 00000000..53fb87a8 --- /dev/null +++ b/fr-fr/nix-fr.html.markdown @@ -0,0 +1,395 @@ +--- +language: nix +filename: learn.nix +contributors: + - ["Chris Martin", "http://chris-martin.org/"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Javier Candeira", "https://candeira.com/"] +translators: + - ["Loïc Reynier", "https://github.com/loicreynier"] +lang: fr-fr +--- + +Nix est un langage fonctionnel développé pour +le gestionnaire de paquet [Nix](https://nixos.org/nix/) et +[NixOS](https://nixos.org/). + +Les expressions Nix peuvent être évaluées avec +[nix-instantiate](https://nixos.org/nix/manual/#sec-nix-instantiate) +ou [`nix repl`](https://nixos.org/nix/manual/#ssec-relnotes-2.0). + +```nix +with builtins; [ + + # Commentaires + #========================================= + + # Ceci est un commentaire en ligne. + + /* Ceci est un commentaire + écrit sur plusieurs lignes. */ + + + # Booléens + #========================================= + + (true && false) # Et + #=> false + + (true || false) # Ou + #=> true + + (if 3 < 4 then "a" else "b") # Test logique + #=> "a" + + + # Entiers et nombres flottants + #========================================= + + # Il y a deux types de nombres : les entiers et les flottants. + + 1 0 42 (-3) # Quelques exemples d'entiers + + 123.43 .27e13 # Quelques exemples de nombre flottants + + # Les opérations conservent le type du nombre + + (4 + 6 + 12 - 2) # Addition + #=> 20 + (4 - 2.5) + #=> 1.5 + + (7 / 2) # Division + #=> 3 + (7 / 2.0) + #=> 3.5 + + + # Chaînes de caractères + #========================================= + + "Les chaînes de caractères littérales sont écrites entre guillements." + + " + Les chaînes de caractères littérales + peuvent s'étendre sur + plusieurs lignes + " + + '' + Ceci est ce qu'on appelle une + "chaîne de caractères littérale indentée". + Les espaces de début de lignes sont intelligemment supprimées. + '' + + '' + a + b + '' + #=> "a\n b" + + ("ab" + "cd") # Concaténation de chaînes de caractères + #=> "abcd" + + # L'antiquotation vous permet d'intégrer des valeurs + # dans des chaînes de caracères. + ("Votre répertoire personnel est ${getEnv "HOME"}") + #=> "Votre répertoire personnel est /home/alice" + + + # Chemins + #========================================= + + # Nix a un type de variable primitif pour les chemins. + /tmp/tutorials/learn.nix + + # Un chemin relatif est résolu en un chemin absolu + # au moment de l'évaluation. + tutorials/learn.nix + #=> /the-base-path/tutorials/learn.nix + + # Un chemin doit toujours contenir au moins une barre oblique (slash). + # Un chemin relatif d'un fichier dans le répertoire courant + # a donc besoin du préfixe `./` + ./learn.nix + #=> /the-base-path/learn.nix + + # L'opérateur `/` doit être entouré d'espaces afin d'être + # traité comme une division + 7/2 # Ceci est un chemin + (7 / 2) # Ceci est une division entière + + + # Importations + #========================================= + + # Un fichier nix contient une seule expression principale sans + # variable libre. + # Une expression importée s'évalue à la valeur du fichier importé. + (import /tmp/foo.nix) + + # Les importations peuvent également être spécifiées par des chaînes + # de caractères. + (import "/tmp/foo.nix") + + # Les chemins doivent être absolus. Cependant comme les chemins + # relatifs sont automatiquement résolus, ils peuvent être utilisés + # pour l'importation. + (import ./foo.nix) + + # Attention, cela ne se produit pas avec les chaînes de caractères. + (import "./foo.nix") + #=> error: string ‘foo.nix’ doesn't represent an absolute path + + + # Let + #========================================= + + # Les blocs `let` permettent d'affecter des valeurs avec des variables. + (let x = "a"; in + x + x + x) + #=> "aaa" + + # Les affectations peuvent se référer les unes aux autres, et leur ordre + # n'a pas d'importance. + (let y = x + "b"; + x = "a"; in + y + "c") + #=> "abc" + + + # Les affectations d'un bloc fille écrasent les affections du bloc mère. + (let a = 1; in + let a = 2; in + a) + #=> 2 + + + # Fonctions + #========================================= + + (n: n + 1) # Fonction qui ajoute 1 + + ((n: n + 1) 5) # Fonction précédente appliquée à 5 + #=> 6 + + # Il n'y a pas de syntaxe pour nommer les fonctions, + # mais elles peuvent affectée à une variable par un bloc `let` + # comme toutes les autres valeurs. + (let succ = (n: n + 1); in succ 5) + #=> 6 + + # Une fonction a exactement un seul argument. + # Des fonctions à plusieurs arguments peuvent être construites + # par imbrificication de fonctions. + ((x: y: x + "-" + y) "a" "b") + #=> "a-b" + + # Il est également possible d'avoir des arguments de fonction nommés. + # Nous verrons comment après avoir introduit les ensembles. + + + # Listes + #========================================= + + # Les listes sont indiquées par des crochets. + + (length [1 2 3 "x"]) + #=> 4 + + ([1 2 3] ++ [4 5]) + #=> [1 2 3 4 5] + + (concatLists [[1 2] [3 4] [5]]) + #=> [1 2 3 4 5] + + (head [1 2 3]) + #=> 1 + (tail [1 2 3]) + #=> [2 3] + + (elemAt ["a" "b" "c" "d"] 2) + #=> "c" + + (elem 2 [1 2 3]) + #=> true + (elem 5 [1 2 3]) + #=> false + + (filter (n: n < 3) [1 2 3 4]) + #=> [ 1 2 ] + + + # Ensembles + #========================================= + + # Un ensemble, ou "set", est un dictionnaire non ordonné avec des clés + # en chaîne de caractères. + { foo = [1 2]; bar = "x"; } + + # L'opérateur `.` extrait une valeur d'un ensemble. + { a = 1; b = 2; }.a + #=> 1 + + # L'opérateur `?` teste si la clé est présente dans l'ensemble. + ({ a = 1; b = 2; } ? a) + #=> true + ({ a = 1; b = 2; } ? c) + #=> false + + # L'opérateur `//` fusionne deux ensembles. + ({ a = 1; } // { b = 2; }) + #=> { a = 1; b = 2; } + + # Les valeurs de droite écrasent les valeurs de gauche. + ({ a = 1; b = 2; } // { a = 3; c = 4; }) + #=> { a = 3; b = 2; c = 4; } + + # Le mot clé `rec` indique un ensemble récursif, ou "recursive set", + # dans lequel les attributs peuvent se référer les uns aux autres. + (let a = 1; in { a = 2; b = a; }.b) + #=> 1 + (let a = 1; in rec { a = 2; b = a; }.b) + #=> 2 + + # Les ensembles imbriqués peuvent être définis par morceaux. + { + a.b = 1; + a.c.d = 2; + a.c.e = 3; + }.a.c + #=> { d = 2; e = 3; } + + # Les ensembles sont immuables, il est donc impossible de rédéfinir + # un attribut : + { + a = { b = 1; }; + a.b = 2; + } + #=> attribute 'a.b' at (string):3:5 already defined at (string):2:11 + + # Cependant un attribut d'un attribut de l'ensemble peut également + # être défini par morceaux même si l'attribut père a été directement + # défini. + { + a = { b = 1; }; + a.c = 2; + } + #=> { a = { b = 1; c = 2; }; } + + + # With + #========================================= + + # Le corps d'un bloc `with` est évalué avec + # les mappings d'un ensemble liés à des variables. + (with { a = 1; b = 2; }; + a + b) + # => 3 + + # Les affectations d'un bloc fille écrasent les affections du bloc mère. + (with { a = 1; b = 2; }; + (with { a = 5; }; + a + b)) + #=> 7 + + # La première ligne du tutoriel commence par `with builtins;` + # car `builtins` est un ensmble qui contient toutes les fonctions + # de base (`length`, `head`, `tail`, `filter`, etc.). Cela permet + # de ne pas avoir à écrire `builtins.length` au lieu de simplement + # `length` par exemple. + + + # Modèles d'ensemble + #========================================= + + # Les ensembles sont utiles pour passer plusieurs valeurs + # à une fonction. + (args: args.x + "-" + args.y) { x = "a"; y = "b"; } + #=> "a-b" + + # On peut l'écrire plus clairement en utilisant des modèles d'ensemble, + # ou "set patterns". + ({x, y}: x + "-" + y) { x = "a"; y = "b"; } + #=> "a-b" + + # Par défaut, le modèle échoue si l'ensemble contient des clés + # supplémentaires. + ({x, y}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> error: anonymous function called with unexpected argument ‘z’ + + # L'ajout de `, ...` permet d'ignorer les clés supplémentaires. + ({x, y, ...}: x + "-" + y) { x = "a"; y = "b"; z = "c"; } + #=> "a-b" + + + # Erreurs + #========================================= + + # `throw` provoque l'abandon de l'évaluation avec un message d'erreur. + (2 + (throw "foo")) + #=> error: foo + + # `tryEval` permet de capturer les erreurs. + (tryEval 42) + #=> { success = true; value = 42; } + (tryEval (2 + (throw "foo"))) + #=> { success = false; value = false; } + + # `abort` est comme `throw`, mais l'erreur est alors fatale : + # elle ne peut pas être capturée. + (tryEval (abort "foo")) + #=> error: evaluation aborted with the following error message: ‘foo’ + + # `assert` s'évalue à la valeur donnée si le test est vrai; + # sinon il lève une exception capturable. + (assert 1 < 2; 42) + #=> 42 + (assert 1 > 2; 42) + #=> error: assertion failed at (string):1:1 + (tryEval (assert 1 > 2; 42)) + #=> { success = false; value = false; } + + + # Impureté + #========================================= + + + # La répétabilité des constructions étant critique pour le + # gestionnaire de paquets Nix, la pureté fonctionnelle est + # mise en avant dans le langage Nix. Cependant, il existe des + # impuretés. + + # Vous pouvez vous référer aux variables d'environnement. + (getEnv "HOME") + #=> "/home/alice" + + + # La fonction `trace` est utilisée pour le débogage. + # Elle affiche le premier argument dans `stderr` et + # évalue le second argument. + (trace 1 2) + #=> trace: 1 + #=> 2 + + # Vous pouvez écrire des fichiers dans le magasin Nix (Nix store). + # Bien qu'impur, c'est assez sûr car le nom du fichier est dérivé + # du hachage de son contenu. On peut lire des fichiers depuis n'importe où. + # Dans cet exemple, on écrit un fichier dans le magasin, puis on le relit. + (let filename = toFile "foo.txt" "hello!"; in + [filename (builtins.readFile filename)]) + #=> [ "/nix/store/ayh05aay2anx135prqp0cy34h891247x-foo.txt" "hello!" ] + + # Il est également possible de télécharger des fichiers dans le magasin Nix. + (fetchurl "https://example.com/package-1.2.3.tgz") + #=> "/nix/store/2drvlh8r57f19s9il42zg89rdr33m2rm-package-1.2.3.tgz" + +] +``` + +### Pour en savoir plus (anglais) + +- [Nix Manual - Nix expression language](https://nixos.org/nix/manual/#ch-expression-language) +- [James Fisher - Nix by example - Part 1: The Nix expression language](https://medium.com/@MrJamesFisher/nix-by-example-a0063a1a4c55) +- [Susan Potter - Nix Cookbook - Nix By Example](https://ops.functionalalgebra.com/nix-by-example/) +- [Rommel Martinez - A Gentle Introduction to the Nix Family](https://web.archive.org/web/20210121042658/https://ebzzry.io/en/nix/#nix) From 0dbdc6dd286065bbc21dc24b7ad83107c877a400 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 13 May 2024 10:15:31 -0600 Subject: [PATCH 198/392] [php/id] rename function (#4942) --- id-id/php-id.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/id-id/php-id.html.markdown b/id-id/php-id.html.markdown index 45306475..331b78a8 100644 --- a/id-id/php-id.html.markdown +++ b/id-id/php-id.html.markdown @@ -762,9 +762,9 @@ class KelasInduk { } public static function coba() { // kata kunci "self" merujuk pada method yang berada dalam satu kelas - self::who(); + self::siapa(); // kata kunci "static" merujuk pada method yang berada di kelas dimana method itu dijalankan - static::who(); + static::siapa(); } } From fb452907a35cd6e603190a6a3af40bfb85684381 Mon Sep 17 00:00:00 2001 From: Mario Ledinscak Date: Mon, 13 May 2024 18:33:43 +0200 Subject: [PATCH 199/392] [raylib/en] Updated example (#4775) --- raylib.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/raylib.html.markdown b/raylib.html.markdown index 7057e525..74a2443b 100644 --- a/raylib.html.markdown +++ b/raylib.html.markdown @@ -36,11 +36,11 @@ int main(void) // raylib defines two types of cameras: Camera3D and Camera2D // Camera is a typedef for Camera3D Camera camera = { - .position = {0.0f, 0.0f, 0.0f}, - .target = {0.0f, 0.0f, 1.0f}, - .up = {0.0f, 1.0f, 0.0f}, - .fovy = 70.0f, - .type = CAMERA_PERSPECTIVE + .position = {0.0f, 0.0f, 0.0f}, + .target = {0.0f, 0.0f, 1.0f}, + .up = {0.0f, 1.0f, 0.0f}, + .fovy = 70.0f, + .projection = CAMERA_PERSPECTIVE }; // raylib supports loading of models, animations, images and sounds From bb2e6c755c56aae4455545aeda93d992b692e17d Mon Sep 17 00:00:00 2001 From: Eunpyoung Kim Date: Tue, 14 May 2024 01:54:38 +0900 Subject: [PATCH 200/392] [clojure-macros/ko-kr] Translate (#4806) --- ko-kr/clojure-macros-kr.html.markdown | 147 ++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 ko-kr/clojure-macros-kr.html.markdown diff --git a/ko-kr/clojure-macros-kr.html.markdown b/ko-kr/clojure-macros-kr.html.markdown new file mode 100644 index 00000000..314aae2b --- /dev/null +++ b/ko-kr/clojure-macros-kr.html.markdown @@ -0,0 +1,147 @@ +--- +language: "clojure macros" +filename: learnclojuremacros-kr.clj +contributors: + - ["Adam Bard", "http://adambard.com/"] +translators: + - ["Eunpyoung Kim", "https://github.com/netpyoung"] +lang: ko-kr +--- + +다른 모든 Lisp와 마찬가지로, Clojure가 가진 [동형성(homoiconicity)](https://en.wikipedia.org/wiki/Homoiconic)은 + "매크로"라고 불리는 코드 생성 루틴을 작성할 수 있도록 언어의 전체적인 범위에 접근할 수 있게 해줍니다. + 매크로는 필요에 맞게 언어를 바꿀 수 있는 강력한 방법을 제공합니다. + +주의하시기 바랍니다. 함수로도 충분히 해결할 수 있는 문제를 매크로로 작성하게 된다면, 좋은 코드라고 할 수 없습니다. +인자가 평가되는 시점을 제어해야 할 때만 매크로를 사용하는게 좋습니다. + +Clojure랑 친해지면 쉽게 따라갈 수 있습니다. [Clojure in Y Minutes](/docs/ko-kr/clojure-kr/)를 한번 읽어보세요. + +```clojure +;; defmacro로 매크로를 정의합니다. +;; 매크로는 clojure 코드로 평가될 수 있는 리스트를 반환해야 합니다. +;; +;; 다음 매크로는 (reverse "Hello World") 라고 쓴 것과 같습니다. +(defmacro my-first-macro [] + (list reverse "Hello World")) + +;; macroexpand나 macroexpand-1을 사용해서 매크로의 결과를 확인할 수 있습니다. +;; +;; 호출하는 부분이 '(quote)된 것을 주목합니다. +(macroexpand '(my-first-macro)) +;; -> (# "Hello World") + +;; macroexpand의 결과를 바로 평가할 수 있습니다. +(eval (macroexpand '(my-first-macro))) +; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; 하지만, 함수와 같이 좀 더 간결한 구문을 이용하는게 좋습니다: +(my-first-macro) ; -> (\d \l \o \r \W \space \o \l \l \e \H) + +;; 더 간결한 quote 구문 ( ' )을 이용하여, 보다 편리하게 매크로 안에서 리스트를 만들 수 있습니다: +(defmacro my-first-quoted-macro [] + '(reverse "Hello World")) + +(macroexpand '(my-first-quoted-macro)) +;; -> (reverse "Hello World") +;; reverse는 더 이상 함수 객체가 아니라 심볼이라는 것에 주목하세요. + +;; 매크로는 인자를 받을 수 있습니다. +(defmacro inc2 [arg] + (list + 2 arg)) + +(inc2 2) ; -> 4 + +;; 하지만, quote된 리스트를 사용하면 에러가 발생합니다. +;; 인자도 quote되기 때문입니다. +;; 이를 해결하기 위해, clojure는 매크로를 quote할 수 있는 방법을 제공합니다: `. +;; ` 안에서 ~를 사용하면 외부 스코프에 접근할 수 있습니다. +(defmacro inc2-quoted [arg] + `(+ 2 ~arg)) + +(inc2-quoted 2) + +;; destructuring args도 사용할 수 있습니다. ~@를 사용하여 리스트 변수를 확장할 수 있습니다. +(defmacro unless [arg & body] + `(if (not ~arg) + (do ~@body))) ; do를 빼먹지 마세요! + +(macroexpand '(unless true (reverse "Hello World"))) +;; -> +;; (if (clojure.core/not true) (do (reverse "Hello World"))) + +;; (unless)는 첫 번째 인자가 false일 때, body를 평가하고 반환합니다. +;; 그렇지않으면, nil을 반환합니다. +(unless true "Hello") ; -> nil +(unless false "Hello") ; -> "Hello" + +;; 주의하지 않으면, 매크로는 변수를 덮어쓰는 등 큰 문제를 일으킬 수 있습니다. +(defmacro define-x [] + '(do + (def x 2) + (list x))) + +(def x 4) +(define-x) ; -> (2) +(list x) ; -> (2) + +;; 이를 피하기 위해, gensym을 이용하여 고유한 식별자를 얻을 수 있습니다. +(gensym 'x) ; -> x1281 (혹은 다른 식별자) + +(defmacro define-x-safely [] + (let [sym (gensym 'x)] + `(do + (def ~sym 2) + (list ~sym)))) + +(def x 4) +(define-x-safely) ; -> (2) +(list x) ; -> (4) + +;; ` 안에서 #를 사용하면 자동으로 각 심볼에 대한 gensym을 생성할 수 있습니다. +(defmacro define-x-hygienically [] + `(do + (def x# 2) + (list x#))) + +(def x 4) +(define-x-hygienically) ; -> (2) +(list x) ; -> (4) + +;; 매크로를 만들 때는 보통 헬퍼 함수를 많이 이용합니다. +;; 인라인 산술 문법을 지원하는 몇 개의 헬퍼 함수를 만들어 봅시다. +(declare inline-2-helper) +(defn clean-arg [arg] + (if (seq? arg) + (inline-2-helper arg) + arg)) + +(defn apply-arg + "Given args [x (+ y)], return (+ x y)" + [val [op arg]] + (list op val (clean-arg arg))) + +(defn inline-2-helper + [[arg1 & ops-and-args]] + (let [ops (partition 2 ops-and-args)] + (reduce apply-arg (clean-arg arg1) ops))) + +;; 매크로를 만들지 않고, 바로 테스트해볼 수 있습니다. +(inline-2-helper '(a + (b - 2) - (c * 5))) ; -> (- (+ a (- b 2)) (* c 5)) + +; 하지만, 이 함수를 컴파일 타임에 실행하려면 매크로로 만들어야 합니다. +(defmacro inline-2 [form] + (inline-2-helper form)) + +(macroexpand '(inline-2 (1 + (3 / 2) - (1 / 2) + 1))) +; -> (+ (- (+ 1 (/ 3 2)) (/ 1 2)) 1) + +(inline-2 (1 + (3 / 2) - (1 / 2) + 1)) +; -> 3 (실제로는 3N이라는 결과가 나옵니다. / 연산자를 사용하면 숫자가 유리수로 캐스팅되기 때문입니다.) +``` + +### 더 읽어볼거리 + +- [Writing Macros](http://www.braveclojure.com/writing-macros/) +- [Official docs](http://clojure.org/macros) +- [When to use macros?](https://lispcast.com/when-to-use-a-macro/) From 01ef2df20bac3c4cf8259075a86f2b38f5c7434c Mon Sep 17 00:00:00 2001 From: Eunpyoung Kim Date: Tue, 14 May 2024 01:57:47 +0900 Subject: [PATCH 201/392] [common-lisp/ko-kr] Translate (#4805) --- ko-kr/common-lisp-kr.html.markdown | 684 +++++++++++++++++++++++++++++ 1 file changed, 684 insertions(+) create mode 100644 ko-kr/common-lisp-kr.html.markdown diff --git a/ko-kr/common-lisp-kr.html.markdown b/ko-kr/common-lisp-kr.html.markdown new file mode 100644 index 00000000..eb651277 --- /dev/null +++ b/ko-kr/common-lisp-kr.html.markdown @@ -0,0 +1,684 @@ +--- +language: "Common Lisp" +category: language +filename: commonlisp-kr.lisp +contributors: + - ["Paul Nathan", "https://github.com/pnathan"] + - ["Rommel Martinez", "https://ebzzry.io"] +translators: + - ["Eunpyoung Kim", "https://github.com/netpyoung"] +lang: ko-kr +--- + +커먼 리스프(Common Lisp, CL)는 다양한 산업 어플리케이션에 적합한 범용적인 멀티페러다임 언어입니다. + 프로그래밍할 수 있는 프로그래밍 언어로서 자주 언급되곤 합니다. + +처음 접하기 좋은책은 [Practical Common Lisp](http://www.gigamonkeys.com/book/)입니다. + 또 다른 유명한 책으로는 최근에 나온 [Land of Lisp](http://landoflisp.com/)입니다. + 베스트 프렉틱스에 관한 [Common Lisp Recipes](http://weitz.de/cl-recipes/) 책도 최근에 출판되었습니다. + +```lisp +;;;----------------------------------------------------------------------------- +;;; 0. 구문 (Syntax, 신택스) +;;;----------------------------------------------------------------------------- + +;;; 일반적인 폼(form) + +;;; CL은 2개의 근본이 되는 구문 요소를 가집니다: ATOM 과 S-EXPRESSION. +;;; 일반적으로, 괄호로 묶인 S-expressions를 `폼(form)`이라고 부릅니다. + +10 ; atom; 그 자체로 평가됩니다 +:thing ; atom; 심볼 :thing로 평가됩니다 +t ; atom, 참을 나타냅니다 +(+ 1 2 3 4) ; s-expression +'(4 :foo t) ; s-expression + + +;;; 주석 + +;;; 한줄주석은 세미콜론으로 시작합니다( ; ) +;;; 파일 단위로는 4개, 구획(section) 설명으로는 3개, 정의(definition) 안에서는 2개, +;;; 한 라인에 대해서는 1개를 사용합니다. 예를들면, + +;;;; life.lisp + +;;; Foo bar baz, because quu quux. Optimized for maximum krakaboom and umph. +;;; Needed by the function LINULUKO. + +(defun meaning (life) + "LIFE의 의미를 계산하여 반환합니다." + (let ((meh "abc")) + ;; Invoke krakaboom + (loop :for x :across meh + :collect x))) ; 값을 x에 저장한 다음, 이를 반환합니다. + + +;;; 반면, 블록주석은 자유롭게 쓸 수 있습니다. +;;; #| 와 |# 로 구역을 나눌 수 있습니다. + +#| 이것은 블록 주석이며, + 여러 줄로 쓸 수 있으며 + #| + 중첩하여 사용할 수 있습니다! + |# +|# + + +;;; 환경 + +;;; 여러 종류의 구현체들이 있습니다; +;;; 대부분 표준을 따르지만, SBCL이 처음 시작하기에 좋습니다. +;;; Quicklisp를 이용하여 서드파티 라이브러리들을 쉽게 설치할 수 있습니다. + +;;; CL을 개발할때 텍스트 편집기와 +;;; 읽고(Read) 평가하고(Eval) 출력(Print)을 반복(Loop)하는 REPL을 동시에 활용하여 개발합니다. +;;; REPL은 프로그램이 "실행되고 있는 중(live)"에 프로그램과 상호작용을 할 수 있도록 만들어 줍니다. + + + +;;;----------------------------------------------------------------------------- +;;; 1. 주요 데이터 타입 및 연산자 +;;;----------------------------------------------------------------------------- + +;;; 심볼 + +'foo ; => FOO 자동으로 심볼이 대문자로 된 것을 주목하시기 바랍니다. + +;;; INTERN은 문자열을 심볼로 만들어 줍니다. + +(intern "AAAA") ; => AAAA +(intern "aaa") ; => |aaa| + +;;; 숫자 + +9999999999999999999999 ; 정수 +#b111 ; 2진수 => 7 +#o111 ; 8진수 => 73 +#x111 ; 16진수 => 273 +3.14159s0 ; single +3.14159d0 ; double +1/2 ; 분수 +#C(1 2) ; 복소수 + +;;; 함수 적용 +;;; (f x y z ...)에서 f는 함수이며, x, y, z, ... 인자입니다. + +(+ 1 2) ; => 3 + +;;; 데이터 그 자체를 만들기 원한다면, +;;; QUOTE를 이용하여 평가를 막을 수 있습니다. + +(quote (+ 1 2)) ; => (+ 1 2) +(quote a) ; => A + +;;; QUOTE을 짧게 쓰면 ( ' )입니다. + +'(+ 1 2) ; => (+ 1 2) +'a ; => A + +;;; 기본 산술 연산자 + +(+ 1 1) ; => 2 +(- 8 1) ; => 7 +(* 10 2) ; => 20 +(expt 2 3) ; => 8 ;; exponentiation: 제곱 +(mod 5 2) ; => 1 ;; modulo: 나머지 연산 +(/ 35 5) ; => 7 +(/ 1 3) ; => 1/3 +(+ #C(1 2) #C(6 -4)) ; => #C(7 -2) + +;;; 불리언(Boolean) + +t ; 참 ; NIL이 아니면 참. +nil ; 거짓; 빈 리스트: () 역시 거짓. +(not nil) ; => T +(and 0 t) ; => T +(or 0 nil) ; => 0 + +;;; 문자 + +#\A ; => #\A +#\λ ; => #\GREEK_SMALL_LETTER_LAMDA +#\u03BB ; => #\GREEK_SMALL_LETTER_LAMDA + +;;; 문자열은 고정된 길이의 배열속에 문자들이 들어있는 것입니다. + +"Hello, world!" +"Benjamin \"Bugsy\" Siegel" ; 역슬래쉬(\)는 이스케이프 문자입니다. + +;;; 문자열을 연결(concatenate)시킬 수 도 있습니다. + +(concatenate 'string "Hello, " "world!") ; => "Hello, world!" + +;;; 문자열을 마치 문자들이 나열된것처럼 취급할 수도 있습니다. + +(elt "Apple" 0) ; => #\A + +;;; FORMAT은 형식화된 출력을 만들기 위해 사용됩니다. +;;; 간단한 스트링 인터폴레이션(string interpolation)부터 반복문이나 조건문까지 다양한 기능을 제공합니다. +;;; FORMAT의 첫번째 인자는 포맷팅된 문자열이 어디로 갈지 결정합니다 +;;; 만약 NIL이라면, FORMAT은 포맷팅된 문자열을 반환합니다; +;;; 만약 T라면, FORMAT은 표준 출력, 일반적으로 스크린에 출력한 다음 NIL을 반환합니다. + +(format nil "~A, ~A!" "Hello" "world") ; => "Hello, world!" +(format t "~A, ~A!" "Hello" "world") ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 2. 변수 +;;;----------------------------------------------------------------------------- + +;;; DEFVAR와 DEFPARAMETER를 이용하여 전역 (동적 스코프) 변수를 만들 수 있습니다. +;;; 변수 이름은 다음을 제외한 모든 문자를 사용할 수 있습니다: ()",'`;#|\ + +;;; DEFVAR와 DEFPARAMETER의 차이점으로는, DEFVAR 표현식을 다시 평가하더라도 변수의 값이 변경되지 않는다는 것입니다. +;;; 반면 DEFPARAMETER는 변경됩니다. + +;;; 관례상, 동적 스코프 변수는 이름에는 귀마개(earmuffs)를 씌워줍니다. + +(defparameter *some-var* 5) +*some-var* ; => 5 + +;;; 유니코드 문자 역시 사용할 수 있습니다. +(defparameter *AΛB* nil) + +;;; 이전에 바인딩되지 않은 변수에 접근하면 UNBOUND-VARIABLE 에러가 발생하지만, 이것은 정의된 동작입니다. +;;; 바인딩되지 않은 변수에는 접근하지 마세요. + +;;; LET 으로 지역 바인딩을 만들 수 있습니다. +;;; 다음 코드에서 (let ...) 안에서 "dance with you"는 `me`로 바인딩됩니다. +;;; LET은 항상 LET 폼의 마지막 `form`의 값을 반환합니다. + +(let ((me "dance with you")) me) ; => "dance with you" + + +;;;-----------------------------------------------------------------------------; +;;; 3. 구조체와 컬렉션 +;;;-----------------------------------------------------------------------------; + + +;;; 구조체 + +(defstruct dog name breed age) +(defparameter *rover* + (make-dog :name "rover" + :breed "collie" + :age 5)) +*rover* ; => #S(DOG :NAME "rover" :BREED "collie" :AGE 5) +(dog-p *rover*) ; => T +(dog-name *rover*) ; => "rover" + +;;; DOG-P, MAKE-DOG, DOG-NAME은 모두 DEFSTRUCT에 의해 자동으로 생성됩니다. + + +;;; 페어(쌍, Pair) + +;;; CONS는 페어를 만듭니다. CAR와 CDR은 페어의 head와 tail을 반환합니다. + +(cons 'SUBJECT 'VERB) ; => '(SUBJECT . VERB) +(car (cons 'SUBJECT 'VERB)) ; => SUBJECT +(cdr (cons 'SUBJECT 'VERB)) ; => VERB + + +;;; 리스트 + +;;; 리스트는 CONS 페어로 만들어진 링크드 리스트 데이터 구조입니다. +;;; 리스트의 끝은 NIL (또는 '())로 표시됩니다. + +(cons 1 (cons 2 (cons 3 nil))) ; => '(1 2 3) + +;;; LIST는 리스트를 위한 가변인자 생성자입니다. + +(list 1 2 3) ; => '(1 2 3) + +;;; CONS에 첫번째 인자가 원자이고 두번째 인자는 리스트일때, +;;; CONS는 새로운 CONS-페어를 반환하게 되는데, +;;; 첫번째 인자를 첫번째 아이템으로, 두번째 인자를 CONS-페어의 나머지로 하게됩니다. + +(cons 4 '(1 2 3)) ; => '(4 1 2 3) + +;;; APPEND를 사용하여 리스트를 연결할 수 있습니다. + +(append '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; 또는 CONCATENATE + +(concatenate 'list '(1 2) '(3 4)) ; => '(1 2 3 4) + +;;; 리스트는 매우 중요한 타입이며, 다양한 기능들이 있습니다. +;;; 몇 가지 예를 들어보겠습니다: + +(mapcar #'1+ '(1 2 3)) ; => '(2 3 4) +(mapcar #'+ '(1 2 3) '(10 20 30)) ; => '(11 22 33) +(remove-if-not #'evenp '(1 2 3 4)) ; => '(2 4) +(every #'evenp '(1 2 3 4)) ; => NIL +(some #'oddp '(1 2 3 4)) ; => T +(butlast '(subject verb object)) ; => (SUBJECT VERB) + + +;;; 벡터 + +;;; 벡터는 고정길이 배열입니다. + +#(1 2 3) ; => #(1 2 3) + +;;; CONCATENATE를 사용하여 벡터를 연결할 수 있습니다. + +(concatenate 'vector #(1 2 3) #(4 5 6)) ; => #(1 2 3 4 5 6) + + +;;; 배열 + +;;; 벡터와 스트링은 배열의 특이 케이스입니다. + +;;; 2차원 배열 + +(make-array (list 2 2)) ; => #2A((0 0) (0 0)) +(make-array '(2 2)) ; => #2A((0 0) (0 0)) +(make-array (list 2 2 2)) ; => #3A(((0 0) (0 0)) ((0 0) (0 0))) + +;;; 주의: MAKE-ARRAY의 기본 초기값은 구현체에 따라 다릅니다. +;;; 명시적으로 지정하려면 다음과 같이하면 됩니다: + +(make-array '(2) :initial-element 'unset) ; => #(UNSET UNSET) + +;;; 1, 1, 1에 있는 요소에 접근하기: + +(aref (make-array (list 2 2 2)) 1 1 1) ; => 0 +;;; 반환되는 값은 구현체에 따라 다릅니다: +;;; SBCL과 CCL에서는 0, ECL에서는 NIL + +;;; 조절 가능한 벡터(adjustable vector) + +;;; 조절 가능한 벡터는 고정길이 벡터와 동일한 출력 결과를 갖습니다. + +(defparameter *adjvec* (make-array '(3) :initial-contents '(1 2 3) + :adjustable t :fill-pointer t)) +*adjvec* ; => #(1 2 3) + +;;; 새로운 요소 추가하기 + +(vector-push-extend 4 *adjvec*) ; => 3 +*adjvec* ; => #(1 2 3 4) + + +;;; 셋(Set)은 단순히 리스트입니다: + +(set-difference '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1) +(intersection '(1 2 3 4) '(4 5 6 7)) ; => 4 +(union '(1 2 3 4) '(4 5 6 7)) ; => (3 2 1 4 5 6 7) +(adjoin 4 '(1 2 3 4)) ; => (1 2 3 4) + +;;; 하지만, 많은 데이터 셋을 다룰 경우, +;;; 링크드리스트 보다 더 나은 데이터 구조를 필요로 할 것입니다. + +;;; 딕션어리는 해쉬태이블로 만들어졌습니다. + +;;; 해쉬 테이블 만들기 + +(defparameter *m* (make-hash-table)) + +;;; 값 설정 + +(setf (gethash 'a *m*) 1) + +;;; 값 받아오기 + +(gethash 'a *m*) ; => 1, T + +;;; CL의 표현식은 여러개의 값을 반환 할 수 있습니다. + +(values 1 2) ; => 1, 2 + +;;; MULTIPLE-VALUE-BIND로 연결(bind)지을 수 있습니다. + +(multiple-value-bind (x y) + (values 1 2) + (list y x)) + +; => '(2 1) + +;;; GETHASH는 여러 값을 반환하는 함수의 예입니다. +;;; 첫번째 반환값은 해쉬 테이블의 키의 값입니다; +;;; 만약 키가 발견되지 않으면 NIL을 반환합니다. + +;;; 두번째 반환값은 키가 해쉬 테이블에 존재하는지 여부를 결정합니다. +;;; 테이블에서 키를 찾지 못하면 NIL을 반환합니다. +;;; 이러한 동작은 키의 값이 실제로 NIL인지 확인할 수 있도록 해줍니다. + +(gethash 'd *m*) ;=> NIL, NIL + +;;; 키가 없을때를 대비한 기본값을 설정할 수 있습니다; + +(gethash 'd *m* :not-found) ; => :NOT-FOUND + +;;; 반환된 값들을 처리해보겠습니다. + +(multiple-value-bind (a b) + (gethash 'd *m*) + (list a b)) +; => (NIL NIL) + +(multiple-value-bind (a b) + (gethash 'a *m*) + (list a b)) +; => (1 T) + + +;;;----------------------------------------------------------------------------- +;;; 3. 함수 +;;;----------------------------------------------------------------------------- + +;;; 익명 함수를 만들기 위해 LAMBDA를 사용합니다. +;;; 함수는 항상 마지막 표현식의 값을 반환합니다. +;;; 함수의 출력방식은 구현체마다 다릅니다. + +(lambda () "Hello World") ; => # + +;;; 익명 함수를 호출하기 위해 FUNCALL을 사용합니다. + +(funcall (lambda () "Hello World")) ; => "Hello World" +(funcall #'+ 1 2 3) ; => 6 + +;;; 리스트의 앞에 lambda표현식을 넣으면, 암시적으로 FUNCALL을 호출합니다. + +((lambda () "Hello World")) ; => "Hello World" +((lambda (val) val) "Hello World") ; => "Hello World" + +;;; 인자가 미리 주어져 있으면 FUNCALL을 사용하고, 그렇지 않으면 APPLY를 사용합니다. + +(apply #'+ '(1 2 3)) ; => 6 +(apply (lambda () "Hello World") nil) ; => "Hello World" + +;;; 함수에 이름을 붙이려면 DEFUN을 사용합니다. + +(defun hello-world () "Hello World") +(hello-world) ; => "Hello World" + +;;; 위 정의에서 ()는 인자 리스트입니다. + +(defun hello (name) (format nil "Hello, ~A" name)) +(hello "Steve") ; => "Hello, Steve" + +;;; 함수는 선택적(optional) 인자를 가질 수 있습니다; 기본값은 NIL입니다. + +(defun hello (name &optional from) + (if from + (format t "Hello, ~A, from ~A" name from) + (format t "Hello, ~A" name))) + +(hello "Jim" "Alpacas") ; => Hello, Jim, from Alpacas + +;;; 기본값을 다음과 같이 지정할 수도 있습니다. + +(defun hello (name &optional (from "The world")) + (format nil "Hello, ~A, from ~A" name from)) + +(hello "Steve") ; => Hello, Steve, from The world +(hello "Steve" "the alpacas") ; => Hello, Steve, from the alpacas + +;;; 함수는 키워드 인자를 이용하여 위치와 상관없는 인자를 가질 수도 있습니다. + +(defun generalized-greeter (name &key (from "the world") (honorific "Mx")) + (format t "Hello, ~A ~A, from ~A" honorific name from)) + +(generalized-greeter "Jim") +; => Hello, Mx Jim, from the world + +(generalized-greeter "Jim" :from "the alpacas you met last summer" :honorific "Mr") +; => Hello, Mr Jim, from the alpacas you met last summer + + +;;;----------------------------------------------------------------------------- +;;; 4. 동등성(Equality) +;;;----------------------------------------------------------------------------- + +;;; CL은 정교한 동등성 시스템을 가지고 있습니다. +;;; 그 중 일부를 여기서 다뤄보도록 하겠습니다. + +;;; 숫자에 대해서는 ( = )를 사용합니다. +(= 3 3.0) ; => T +(= 2 1) ; => NIL + +;;; 객체 식별에 대해서는 EQL을 사용합니다. +(eql 3 3) ; => T +(eql 3 3.0) ; => NIL +(eql (list 3) (list 3)) ; => NIL + +;;; 리스트, 스트링, 비트-벡터에 대해서는 EQUAL을 사용합니다. +(equal (list 'a 'b) (list 'a 'b)) ; => T +(equal (list 'a 'b) (list 'b 'a)) ; => NIL + + +;;;----------------------------------------------------------------------------- +;;; 5. 제어 흐름(Control Flow) +;;;----------------------------------------------------------------------------- + +;;; 조건문 + +(if t ; 구문: 조건 + "참입니다" ; 구문: 그러면 + "거짓입니다") ; 구문: 그렇지 않으면 +; => "참입니다" + +;;; 조건문에서, NIL이 아닌 모든 값은 참으로 취급됩니다. + +(member 'Groucho '(Harpo Groucho Zeppo)) ; => '(GROUCHO ZEPPO) +(if (member 'Groucho '(Harpo Groucho Zeppo)) + 'yep + 'nope) +; => 'YEP + +;;; COND는 일련의 테스트를 실행하며, 결과를 선택합니다. +(cond ((> 2 2) (error "wrong!")) + ((< 2 2) (error "wrong again!")) + (t 'ok)) ; => 'OK + +;;; TYPECASE는 값의 타입에 따라 분기합니다. +(typecase 1 + (string :string) + (integer :int)) +; => :int + + +;;; 루프(loop) + +;;; 재귀(recursion) + +(defun fact (n) + (if (< n 2) + 1 + (* n (fact(- n 1))))) + +(fact 5) ; => 120 + +;;; 반복(iteration) + +(defun fact (n) + (loop :for result = 1 :then (* result i) + :for i :from 2 :to n + :finally (return result))) + +(fact 5) ; => 120 + +(loop :for x :across "abcd" :collect x) +; => (#\a #\b #\c #\d) + +(dolist (i '(1 2 3 4)) + (format t "~A" i)) +; => 1234 + + +;;;----------------------------------------------------------------------------- +;;; 6. 변경(Mutation) +;;;----------------------------------------------------------------------------- + +;;; 기존 변수에 새 값을 할당하기 위해선 SETF를 사용합니다. +;;; 해쉬 테이블 예제에서도 한번 나왔었습니다. + +(let ((variable 10)) + (setf variable 2)) +; => 2 + +;;; 좋은 리스프 스타일은 파괴적인 함수의 사용을 최소화하고, +;;; 변경을 되도록 피하는 것입니다. + +;;;----------------------------------------------------------------------------- +;;; 7. 클래스와 객체 +;;;----------------------------------------------------------------------------- + +;;; 더 이상 animal 클래스는 없습니다. +;;; 인간을 동력수단으로 삼는 운송기계 +;;; (Human-Powered Mechanical Conveyances)를 만들어보겠습니다. + +(defclass human-powered-conveyance () + ((velocity + :accessor velocity + :initarg :velocity) + (average-efficiency + :accessor average-efficiency + :initarg :average-efficiency)) + (:documentation "A human powered conveyance")) + +;;; DEFCLASS의 인자의 순서는 다음과 같습니다: +;;; 1. 클래스 이름 +;;; 2. 슈퍼클래스 목록 +;;; 3. 슬롯 목록 +;;; 4. 선택적 지정자 + +;;; 이 때 슈퍼클래스 목록이 설정되지 않으면, 빈 목록이 표준 객체 클래스로 기본 설정됩니다. +;;; 이것은 변경할 수도 있지만, 어떻게 돌아가는지 알기전에는 변경하지 않습니다. +;;; 그러면, 메타오브젝트 프로토콜의 예술(Art of the Metaobject Protocol)에 대해 좀 더 살펴보도록 하겠습니다. + +(defclass bicycle (human-powered-conveyance) + ((wheel-size + :accessor wheel-size + :initarg :wheel-size + :documentation "Diameter of the wheel.") + (height + :accessor height + :initarg :height))) + +(defclass recumbent (bicycle) + ((chain-type + :accessor chain-type + :initarg :chain-type))) + +(defclass unicycle (human-powered-conveyance) nil) + +(defclass canoe (human-powered-conveyance) + ((number-of-rowers + :accessor number-of-rowers + :initarg :number-of-rowers))) + +;;; REPL에서 HUMAN-POWERED-CONVEYANCE 클래스에 대해 DESCRIBE를 호출하면 다음과 같은 결과를 얻게됩니다: + +(describe 'human-powered-conveyance) + +; COMMON-LISP-USER::HUMAN-POWERED-CONVEYANCE +; [symbol] +; +; HUMAN-POWERED-CONVEYANCE names the standard-class #: +; Documentation: +; A human powered conveyance +; Direct superclasses: STANDARD-OBJECT +; Direct subclasses: UNICYCLE, BICYCLE, CANOE +; Not yet finalized. +; Direct slots: +; VELOCITY +; Readers: VELOCITY +; Writers: (SETF VELOCITY) +; AVERAGE-EFFICIENCY +; Readers: AVERAGE-EFFICIENCY +; Writers: (SETF AVERAGE-EFFICIENCY) + +;;; 주목할 점은 리플렉션이 가능하다는 것입니다. +;;; CL은 대화형 시스템으로 설계되었습니다. + +;;; 메서드를 정의하기 앞서, 자전거 바퀴의 둘레가 얼마나 되는 공식을 살펴봅시다: +;;; C = d * pi + +(defmethod circumference ((object bicycle)) + (* pi (wheel-size object))) + +;;; PI는 CL에 미리 정의되어 있습니다. + + + +;;; 카누에 있는 노 젓는 사람들의 수의 효율성 값이 대략 로그함수적이라는 것을 안다고 가정해봅시다. +;;; 이와 같은 정보는 생성자/초기화자에서 설정하는 것이 좋습니다. + +;;; CL이 인스턴스를 생성한 다음에(after), 인스턴스를 초기화하기 위해선: + +(defmethod initialize-instance :after ((object canoe) &rest args) + (setf (average-efficiency object) (log (1+ (number-of-rowers object))))) + +;;; 그런 다음 인스턴스를 생성하고, 평균 효율을 확인합니다... + +(average-efficiency (make-instance 'canoe :number-of-rowers 15)) +; => 2.7725887 + + +;;;----------------------------------------------------------------------------- +;;; 8. 매크로 +;;;----------------------------------------------------------------------------- + +;;; 매크로는 언어의 구문을 확장할 수 있게 해줍니다. +;;; CL에는 WHILE 루프가 없지만, 새로 작성하는 것은 간단합니다. +;;; 어셈블러의 명령어를 따라가자면, 다음과 같이 될 것입니다: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. +`condition` is tested prior to each execution of `body`" + (let ((block-name (gensym)) (done (gensym))) + `(tagbody + ,block-name + (unless ,condition + (go ,done)) + (progn + ,@body) + (go ,block-name) + ,done))) + +;;; 좀 더 고수준 버전을 살펴보겠습니다: + +(defmacro while (condition &body body) + "While `condition` is true, `body` is executed. +`condition` is tested prior to each execution of `body`" + `(loop while ,condition + do + (progn + ,@body))) + +;;; 하지만, 현대의 컴파일러에서는 이것이 필요하지 않습니다; +;;; LOOP 폼은 동일하게 잘 컴파일되며 읽기 쉽습니다. + +;;; Note that ``` is used, as well as `,` and `@`. ``` is a quote-type operator +;;; known as quasiquote; it allows the use of `,` . `,` allows "unquoting" +;;; variables. @ interpolates lists. + +;;; GEMSYM은 다른 곳에서 사용되지 않는 것이 보장된 시스템에서 유일한 심볼을 생성합니다. +;;; 컴파일 타임에 매크로가 확장되는데, 매크로에서 선언된 변수가 +;;; 일반 코드에서 사용되는 변수와 충돌할 가능성이 있기 때문입니다. + +;;; 매크로에 대해 더 자세한 정보를 얻고 싶으시다면, Practical Common Lisp와 On Lisp를 살펴보시기 바랍니다. +``` + +## 더 읽어볼거리 + +- [Practical Common Lisp](http://www.gigamonkeys.com/book/) +- [Common Lisp: A Gentle Introduction to Symbolic Computation](https://www.cs.cmu.edu/~dst/LispBook/book.pdf) + +## 추가 정보 + +- [CLiki](http://www.cliki.net/) +- [common-lisp.net](https://common-lisp.net/) +- [Awesome Common Lisp](https://github.com/CodyReichert/awesome-cl) +- [Lisp Lang](http://lisp-lang.org/) + +## 크레딧 + +Scheme 사용자들의 노고에 큰 감사를 드립니다. 좋은 시작점을 만들어 주신 덕분에 쉽게 Common Lisp로 옮길 수 있었습니다. + +- 훌륭한 리뷰를 해주신 [Paul Khuong](https://github.com/pkhuong) From 5aa44434a22771a03e7143470f51979ca7c54e32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9C=89=E8=B3=80=20=E6=B8=85=E4=B8=80=20Seiichi=20Ariga?= Date: Tue, 14 May 2024 02:01:57 +0900 Subject: [PATCH 202/392] [nim/ja-jp] New Japanese translation (#4766) --- ja-jp/nim-jp.html.markdown | 289 +++++++++++++++++++++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 ja-jp/nim-jp.html.markdown diff --git a/ja-jp/nim-jp.html.markdown b/ja-jp/nim-jp.html.markdown new file mode 100644 index 00000000..9a4ee004 --- /dev/null +++ b/ja-jp/nim-jp.html.markdown @@ -0,0 +1,289 @@ +--- +language: Nim +filename: learnNim-jp.nim +contributors: + - ["Jason J. Ayala P.", "http://JasonAyala.com"] + - ["Dennis Felsing", "https://dennis.felsing.org"] +translators: + - ["Seiichi Ariga", "https://github.com/s-ariga"] +lang: ja-jp +--- + +Nim (元 Nimrod)は、静的型付けの命令型言語です。ランタイムの効率を損なうこと +なく、プログラマーに恩恵を与えてくれます。 + +Nimは、効率的で、表現力があり、エレガントです。 + +```nim +# 単一行コメントは # で開始 + +#[ + 複数行コメントです。 + Nimでは、複数行コメントはネスト可能で、#[で始まり、 + ... そして終了は ]# +]# + +discard """ +これも複数行コメントとして機能します。 +あるいは、解析不能のコードです。 +""" + + + +var # 変数宣言 (そして割当て) + letter: char = 'n' # 型注釈ありとなし + lang = "N" & "im" + nLength: int = len(lang) + boat: float + truth: bool = false + +let # letで変数を*1回(イミュータブル)*束縛します + legs = 400 # legsはイミュータブル + arms = 2_000 # _ は無視され、長い数値を読みやすくします + aboutPi = 3.15 + +const # 定数はコンパイル時に評価されます。 + debug = true # これにより実行速度を高めます。 + compileBadCode = false + +when compileBadCode: # `when`はコンパイル時の`if`です。 + legs = legs + 1 # この部分はコンパイルされません。ed. + const input = readline(stdin) # 定数値はコンパイル時に決まっていなければ + # なりません。 + +discard 1 > 2 # Note: コンパイラーはある式の結果が使われていないと警告を + # 表示します。`discard`により、これを回避できます。 + + +# +# データ構造 +# + +# タプル + +var + child: tuple[name: string, age: int] # タプルにはフィールド名 + today: tuple[sun: string, temp: float] # *そして*順序の*両方*があります + +child = (name: "Rudiger", age: 2) # ()リテラルで両方同時に割当て +today.sun = "Overcast" # あるいは、個別のフィールドに割当て +today.temp = 70.1 + +# シーケンス + +var + drinks: seq[string] + +drinks = @["Water", "Juice", "Chocolate"] # シーケンスリテラルは@[V1,..,Vn] + +drinks.add("Milk") + +if "Milk" in drinks: + echo "We have Milk and ", drinks.len - 1, " other drinks" + +let myDrink = drinks[2] + +# +# 型の定義 +# + +# あなた自身の型を定義することで、コンパイラーにより多くの仕事をさせられます。 +# それにより静的型付けがパワフルで便利なものになります。 + +type + Name = string # 型エイリアスは、既存の型と置き換え可能でありながら、 + Age = int # より記述的な型を提供します。 + Person = tuple[name: Name, age: Age] # データ構造も定義できます。 + AnotherSyntax = tuple + fieldOne: string + secondField: int + +var + john: Person = (name: "John B.", age: 17) + newage: int = 18 # ここはint型よりもAge型を使ったほうが良いでしょう。 + +john.age = newage # intとAgeは同じ型なので、これで動作します。 + +type + Cash = distinct int # `distinct`を使うと、新しい型と + Desc = distinct string # 元の型の互換性がなくなります。 + +var + money: Cash = 100.Cash # `.Cash`がint型をわれわれ独自の型に + #変換しています。 + description: Desc = "Interesting".Desc + +when compileBadCode: + john.age = money # エラー! ageはint型でmoneyはCash型です。 + john.name = description # コンパイル時のエラーになります。 + +# +# さらに型とデータ構造 +# + +# 列挙は型にいくつかの値の中から1つの値をとることを許します。 + +type + Color = enum cRed, cBlue, cGreen + Direction = enum # 別の書き方 + dNorth + dWest + dEast + dSouth +var + orient = dNorth # `orient`はDirection型で値は`dNorth` + pixel = cGreen # `pixel`はColor型で値は`cGreen` + +discard dNorth > dEast # 列挙には通常、順序があります。 + +# サブレンジは有効な値の範囲を限定します。 + +type + DieFaces = range[1..20] # 1から20のintだけが有効な値です。 +var + my_roll: DieFaces = 13 + +when compileBadCode: + my_roll = 23 # エラー! + +# 配列 + +type + RollCounter = array[DieFaces, int] # 配列の長さは固定で、順序のある型の + DirNames = array[Direction, string] # どれかをインデックスとします。 + Truths = array[42..44, bool] +var + counter: RollCounter + directions: DirNames + possible: Truths + +possible = [false, false, false] # [V1,..,Vn]で配列を作れます。 +possible[42] = true + +directions[dNorth] = "Ahh. The Great White North!" +directions[dWest] = "No, don't go there." + +my_roll = 13 +counter[my_roll] += 1 +counter[my_roll] += 1 + +var anotherArray = ["Default index", "starts at", "0"] + +# 他にも表、集合、リスト、キュー、Crit-bit treeなどのデータ構造があります。 +# http://nim-lang.org/docs/lib.html#collections-and-algorithms + +# +# IOと制御 +# + +# `case`, `readLine()` + +echo "Read any good books lately?" +case readLine(stdin) +of "no", "No": + echo "Go to your local library." +of "yes", "Yes": + echo "Carry on, then." +else: + echo "That's great; I assume." + +# `while`, `if`, `continue`, `break` + +import strutils as str # http://nim-lang.org/docs/strutils.html +echo "I'm thinking of a number between 41 and 43. Guess which!" +let number: int = 42 +var + raw_guess: string + guess: int +while guess != number: + raw_guess = readLine(stdin) + if raw_guess == "": continue # この繰り返しを飛ばす。 + guess = str.parseInt(raw_guess) + if guess == 1001: + echo("AAAAAAGGG!") + break + elif guess > number: + echo("Nope. Too high.") + elif guess < number: + echo(guess, " is too low") + else: + echo("Yeeeeeehaw!") + +# +# 繰返し +# + +for i, elem in ["Yes", "No", "Maybe so"]: # または単に`for elem in` + echo(elem, " is at index: ", i) + +for k, v in items(@[(person: "You", power: 100), (person: "Me", power: 9000)]): + echo v + +let myString = """ +an +`string` to +play with +""" # 複数行の生文字列 + +for line in splitLines(myString): + echo(line) + +for i, c in myString: # インデックスと文字。 + # あるいは`for j in`で文字だけ。 + if i mod 2 == 0: continue # `if`構文の簡易版 + elif c == 'X': break + else: echo(c) + +# +# プロシージャ +# + +type Answer = enum aYes, aNo + +proc ask(question: string): Answer = + echo(question, " (y/n)") + while true: + case readLine(stdin) + of "y", "Y", "yes", "Yes": + return Answer.aYes # 列挙に限定することができます。 + of "n", "N", "no", "No": + return Answer.aNo + else: echo("Please be clear: yes or no") + +proc addSugar(amount: int = 2) = # amountのデフォルトは2、戻り値はなし + assert(amount > 0 and amount < 9000, "Crazy Sugar") + for a in 1..amount: + echo(a, " sugar...") + +case ask("Would you like sugar in your tea?") +of aYes: + addSugar(3) +of aNo: + echo "Oh do take a little!" + addSugar() +# ここで可能な値は`yes`か`no`だけなので、`else`は必要ない + +# +# FFI +# + +# NimはCへとコンパイルされるので、容易にFFIができる: + +proc strcmp(a, b: cstring): cint {.importc: "strcmp", nodecl.} + +let cmp = strcmp("C?", "Easy!") +``` + +これらの他に、Nimはほかの言語と比較してメタプログラミング、 +実行時パフォーマンス、コンパイル時の機能で特長があります。 + +## 参考 + +* [Home Page](http://nim-lang.org) +* [Download](http://nim-lang.org/download.html) +* [Community](http://nim-lang.org/community.html) +* [FAQ](http://nim-lang.org/question.html) +* [Documentation](http://nim-lang.org/documentation.html) +* [Manual](http://nim-lang.org/docs/manual.html) +* [Standard Library](http://nim-lang.org/docs/lib.html) +* [Rosetta Code](http://rosettacode.org/wiki/Category:Nim) From e8d07adad1ce214f89ddfaf623115050ecd45c2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Mon, 13 May 2024 19:03:23 +0200 Subject: [PATCH 203/392] [elixir/en] Give more context around comparison operators (#4792) --- elixir.html.markdown | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index 2748a983..c4da22e8 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -146,13 +146,15 @@ nil && 20 #=> nil 1 == 1.0 #=> true 1 === 1.0 #=> false -# We can also compare two different data types: +# Elixir operators are strict in theiar arguments, with the exception +# of comparison operators that work across different data types: 1 < :hello #=> true -# The overall sorting order is defined below: -# number < atom < reference < functions < port < pid < tuple < list < bit string +# This enables building collections of mixed types: +["string", 123, :atom] -# To quote Joe Armstrong on this: "The actual order is not important, +# While there is an overall order of all data types, +# to quote Joe Armstrong on this: "The actual order is not important, # but that a total ordering is well defined is important." ## --------------------------- From 90a16a6d5e317fc58030625945ded8b83f1055b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Furkan=20=C3=9Cz=C3=BCmc=C3=BC?= Date: Mon, 13 May 2024 13:14:45 -0400 Subject: [PATCH 204/392] [qml/en] Add QML tutorial (#4582) --- qml.html.markdown | 368 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 368 insertions(+) create mode 100644 qml.html.markdown diff --git a/qml.html.markdown b/qml.html.markdown new file mode 100644 index 00000000..78e94d66 --- /dev/null +++ b/qml.html.markdown @@ -0,0 +1,368 @@ +--- +language: QML +contributors: + - ["Furkan Uzumcu", "https://zmc.space/"] +filename: learnqml.qml +lang: en-us +--- + +```qml +// This is a completely valid QML file that you can run using `qmlscene` if you copy the contents +// into a *.qml file. +// Comments start with double forward slashes. +/* Or you + can have + multi line + comments + */ + +// Import statement syntax is +// import ${MODULE_NAME} [${VERSION_NUMBER}] [as ${QUALIFIER}] +import QtQuick 2.15 +import QtQuick.Window 2.15 +import QtQuick.Controls 2.15 as QQC +import QtQuick.Layouts 1.15 +import Qt.labs.platform 1.1 + +// Each QML document can contain only one top level type +Window { + // Each object has a special and optional `id` attribute that can be used to refer to the + // declared objects. An `id` has to be unique in the same document. + id: root + width: 400 + height: 600 + title: "Learn QML in Y Minutes" + + Item { + // Every object that can be declared inherits from QObject and contains at + // least one property, which is `objectName`. All the other properties are + // added by extending `QObject` type. This is an `Item` type and it contains + // the additional `width` and `height` properties and more. + objectName: "My Item" + // `id`s in the same document can be used anywhere in the same file. + // You cannot access an `id` from a different file. + width: root.width + } + + // Signals are used to communicate that a certain event happened. + // Some types have built-in signals + Timer { + id: timer + interval: 500 + onTriggered: { + console.log("Timer triggered!") + } + } + + QtObject { + id: objSignals + // You can also declare your own signals. + signal clicked() + // Signals can also have arguments. + signal mousePositionChanged(int x, int y) + // The way to react to a signal emission is by adding signal handlers to + // the immediate object that the signal belongs to. + onClicked: () => { + // Do stuff here. + console.log("objSignals.clicked() signal is emitted.") + } + // Signal handlers must explicitly declare the arguments. + onMousePositionChanged: (x, y) => { + // Do stuff here. + console.log("objSignals.mousePositionChanged() signal is emitted. x=", x, "y=", y) + } + } + + // If you want to declare signal handlers for other objects, you can use + // `Connections`. + Connections { + target: objSignals + + // You can then declare functions with the same name as the signal + // handler. + function onClicked() { + console.log("objSignals.clicked() signal is handled from Connections.") + } + } + + Item { + visible: false + + // An object can support having child objects. You can add child objects + // by declaring types as follows: + Rectangle { + width: 16 + height: 16 + color: "red" + } + } + + Item { + id: objProperties + // You can also declare your own properties. + // Syntax for declaring is + // [default] [required] [readonly] property ${TYPE} ${NAME} + property color nextColor + // Read only properties have to be initialized when declared. + readonly property color defaultColor: "red" + // Required properties have to be initialized where the reusable type is + // used. + required property color initialColor + + // NOTE: Although the initial assignment can be done in the same file, + // it is not often the use case. + initialColor: "green" + + // Properties are type safe and a property can only be assigned a value + // that matches the property type. + // property int volume: "four" // ERROR! + + Item { + // You can create alias properties that hold a reference to another + // property. + + property alias parentNextColor: objProperties.nextColor + + // Assignments to alias properties alter the property that it holds + // a reference to. + parentNextColor: "blue" // Changes objProperties.nextColor + // Since `parentNextColor` is an alias to `nextColor`, any changes + // to `nextColor` will also be reflected to `parentNextColor`. + } + } + + Item { + // Property assignment values can either be static or binding + // expressions. + // Static value + property int radius: 32 + // Binding expressions describe a property's relationship to other + // properties. When the value of `radius` changes, the expression here + // will be re-evaluated. + property int diameter: radius * 2 + + onDiameterChanged: { + console.log("onDiameterChanged:", diameter) + } + } + + ListView { + // Attached properties and signal handlers provide a way to extend an + // existing object and provide more information that is otherwise not + // immediately available. + width: 100 + height: 30 + model: 3 + delegate: Rectangle { + // ListView provides an attached property for its children that can + // be used to access more information. + color: ListView.isCurrentItem ? "green" : "red" + } + // Attached types can also have signal handlers. + // `Component` is attached to every type that's available in QML. + Component.onCompleted: { + console.log("This signal handler is called after object is created.") + } + } + + Rectangle { + // Since this rectangle is not created by the ListView, the attached + // type is not avaiable. + color: ListView.isCurrentItem ? "green" : "red" + } + + QtObject { + id: calculator + + // Objects can also declare methods. Function declarations can annotate + // the arguments, or have no arguments at all. + function add(a: int, b: int): int { + // Semicolon at the end of a line is optional. + return a + b + } + + function multiply(a: real, b: real): real { + return a * b; + } + } + + MouseArea { + anchors.fill: parent + onClicked: (mouse) => { + console.log("2 + 2 =", calculator.add(2, 2)) + } + } + + Item { + width: 100 + // Methods can also be used as binding expressions. When `width` + // changes, the binding expression will evaluate and call `multiply`. + height: calculator.multiply(width, 0.5) + opacity: calculateOpacity() + + function calculateOpacity() { + // If the function declaration contains references to other + // properties, changes to those properties also trigger a binding + // evaluation. + return height < 50 ? 0.5 : 1 + } + } + + // Each QML file that starts with an upper case name declares a re-usable + // component, e.g "RedRectangle.qml". + // In addition, reusable components can be declared in-line. + component RedRectangle: Rectangle { + color: "red" + } + + // This inline component can then be used in the same file, or in other + // files by prefixing the type name with the file name that it belongs to. + // + // ${FILE_NAME}.RedRectangle { } + // or + RedRectangle { + } + + // QML also supports enumeration declarations. + component MyText: Text { + enum TextType { + Normal, + Heading + } + + // Enum types are assigned to integer properties. + property int textType: MyText.TextType.Normal + + font.bold: textType == MyText.TextType.Heading + font.pixelSize: textType == MyText.TextType.Heading ? 24 : 12 + } + + // ----- Interactive Area + + QQC.ScrollView { + anchors.fill: parent + contentWidth: container.implicitWidth + contentHeight: container.implicitHeight + + Column { + id: container + spacing: 6 + + Row { + spacing: 2 + + QQC.Label { + width: 200 + anchors.verticalCenter: parent.verticalCenter + text: "Click to start the timer.\nCheck the logs!" + wrapMode: QQC.Label.WordWrap + } + + QQC.Button { + text: timer.running ? "Timer Running" : "Start Timer" + onClicked: { + timer.start() + } + } + } + + Row { + spacing: 2 + + QQC.Label { + width: 200 + anchors.verticalCenter: parent.verticalCenter + text: "Click to emit objSignals.clicked() signal" + wrapMode: QQC.Label.WordWrap + } + + QQC.Button { + property int emissionCount: 0 + + text: "Emitted " + emissionCount + " times." + onClicked: { + objSignals.clicked() + emissionCount++ + } + } + } + + Row { + spacing: 2 + + QQC.Label { + width: 200 + anchors.verticalCenter: parent.verticalCenter + text: "Click to emit objSignals.mousePositionChanged() signal" + wrapMode: QQC.Label.WordWrap + } + + QQC.Button { + property int emissionCount: 0 + + text: "Emitted " + emissionCount + " times." + onClicked: { + objSignals.mousePositionChanged(32, 32) + emissionCount++ + } + } + } + + Rectangle { + width: 200 + height: 80 + color: objProperties.nextColor + + QQC.Label { + width: 200 + anchors.verticalCenter: parent.verticalCenter + text: "Click to change nextColor property." + wrapMode: QQC.Label.WordWrap + } + + TapHandler { + onTapped: { + colorDialog.open() + } + } + + ColorDialog { + id: colorDialog + currentColor: objProperties.initialColor + onColorChanged: { + objProperties.nextColor = color + + } + } + } + + Row { + spacing: 2 + + Rectangle { + width: 200 + height: 80 + color: "red" + radius: radiusSlider.value + + QQC.Label { + width: parent.width + anchors.centerIn: parent + text: "Use slider to change radius" + wrapMode: QQC.Label.WordWrap + horizontalAlignment: Qt.AlignHCenter + } + } + + QQC.Slider { + id: radiusSlider + width: 100 + anchors.verticalCenter: parent.verticalCenter + from: 0 + to: 80 + } + } + } + } +} +``` From c3f67d32c8dfd16a08662b8301686f7335a83823 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 13 May 2024 11:32:40 -0600 Subject: [PATCH 205/392] [python/en] "rounds down" -> "rounds towards zero" (#4944) --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index 0cdf256a..a045e784 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -39,7 +39,7 @@ syntactic clarity. It's basically executable pseudocode. 10 * 2 # => 20 35 / 5 # => 7.0 -# Integer division rounds down for both positive and negative numbers. +# Integer division rounds towards zero for both positive and negative numbers. 5 // 3 # => 1 -5 // 3 # => -2 5.0 // 3.0 # => 1.0 # works on floats too From 154d5272a01e68ec1e0871d75d94fc7bf8a871e0 Mon Sep 17 00:00:00 2001 From: Nicholas Georgescu <36280690+NGeorgescu@users.noreply.github.com> Date: Mon, 13 May 2024 15:10:46 -0400 Subject: [PATCH 206/392] [GolfScript/en] (#4626) --- golfscript.html.markdown | 619 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 619 insertions(+) create mode 100644 golfscript.html.markdown diff --git a/golfscript.html.markdown b/golfscript.html.markdown new file mode 100644 index 00000000..8ea985e8 --- /dev/null +++ b/golfscript.html.markdown @@ -0,0 +1,619 @@ +--- +language: GolfScript +filename: golfscript.gs +contributors: + - ["Nicholas S Georgescu", "http://github.com/ngeorgescu"] +--- + +GolfScript is an esoteric language that was developed in 2007 by Darren +Smith. It is a scripting language with an interpreter written in Ruby. It lets +you write very dense code in very few characters. The main goal of the language +is, as the name suggests, to solve problems in as few keystrokes as possible. +The examples page on the GolfScript website even has an entire Sudoku solver +written in just 77 characters. + +If you get really good at GolfScript you can easily find yourself using it as a +go-to language for solving some (even somewhat hard) coding problems. It's never +going to be faster than Ruby, but it can be very fast to write, since a single +character of GolfScript can replace an entire line of code in some other languages. + +GolfScript is based on the use of the stack. This tutorial therefore will +read as a sequence of stack operations on an actual stack, as opposed to some +standalone code and individual results. The stack starts as an empty list, and +everything either adds to the stack, or it pops some items off, transforms them, +and puts them back onto the stack. + +To get started running GolfScript, you can get the golfscript.rb file from the +[GitHub repo](https://github.com/darrenks/golfscript). Copy it into your `$PATH`, +(dropping the .rb and chmodding as necessary). You can run GolfScript from either +the interactive interpreter (which mirrors the tutorial below). Once you get the hang +of GolfScript, you can start running from "stdin". If you see a script starting with `~`, +it was probably designed to be dropped in a file and run with `golfscript file.gs`. You +can pipe in or enter in your input at runtime. + +```golfscript +> anything undefined technically evaluates to nothing and so is also a comment +# but commenting it out explicitly anyway is probably a good idea because if +# you use a reserved keyword or any punctuation you'll run into trouble. +[] +> ###################################################################### +# datatypes +######################################################################## +> 1 # Here we add 1 to the stack. Any object entry adds things to the stack +[1] +> 'abc' # here we are adding a string. The only difference between single and +# double quotes is that double lets you escape more things other than \' and \n +# it won't matter for the sake of this tutorial. +[1 "abc"] +> {+} # the third type of object you can put on the stack is a block +[1 "abc" {+}] +> ] # this takes everything prior and puts it into an array, the fourth type +# of object. (besides bug exploits like [2-1?] those are the only four types) +[[1 "abc" {+}]] +> ; # let's clear the stack by executing the discard function on this array. +# if you type the characters ]; it always clears the stack. +[] +> 1"abc"{+}]; # newlines are whitespaces. Everything we did up to this point +# can be put into one line and it all works the exact same. +######################################################################## +# operators and math +######################################################################## +[] +> 1 1 # we add two 1s to the stack. We could also duplicate the first with . +[1 1] +> + # math is done by executing an operation on the top of the stack. This +# can be a standalone character. The way to read this is that we put a 1 on +# the stack, another one one the stack, and then executed a + operation which +# takes the top two elements off of the stack, sums them up, and returns them +# to the stack. This is typically referred to as postfix notation. It can be +# a bit jarring, but this is the way to think about things. You're adding to +# the stack with objects and modifying the top of the stack with operators. +[2] +> 8 1- # minus works the same way. N.B. that we still have that 2 on the stack +# from earlier +[2 7] +> 10 2* # multiplication works the same way. The product is added to the stack +[2 7 20] +> 35 4/ # all division is integer division +[2 7 20 8] +> 35 4% # modulo operation +[2 7 20 8 3] +> 2 3? # exponentiation +[2 7 20 8 3 8] +> 8~ # bitwise "not" function on signed integers +[2 7 20 8 3 8 -9] +> -1~ # this yields 0, which is useful to know for the ? operator +[2 7 20 8 3 8 -9 0] +> 5 3| # or: yields 7, since [1 0 1] | [0 1 1] => [1 1 1] +[2 7 20 8 3 8 -9 0 7] +> 5 3^ # xor: yields 6, since the parity differs at [1 1 0] +[2 7 20 8 3 8 -9 0 7 6] +> 5 3& # and: yields 1, since it's the only bit active in both: [0 0 1] +[2 7 20 8 3 8 -9 0 7 6 1] +> ]; ################################################################### +# booleans +######################################################################## +[] +> 5 3 +[5 3] +> < #add two numbers to the stack, and then perform a lessthan operation +# booleans are False if 0, [], {}, '', and true if anything else. +[0] +> 5 3> # greater than operation. +[0 1] +> 5 3= #single equal is the operator. Again, before the equals is executed, +# the stack reads [0 1 5 3], and then the equals operator checks the top 2 +# values and yields: +[0 1 0] +> ! #not, returns 1 if 0 else 0. +[0 1 1] +> ) #increments the last number +[0 1 2] +> ( #decrements the last number +[0 1 1] +> ]; ################################################################### +# stack control +######################################################################## +[] +> 1 # put a number on the stack +[1] +> . # duplicate the number +[1 1] +> ) # increment +[1 2] +> \ # flip the top two items +[2 1] +> 1$ # $ copies the nth-to-last item on the stack at the index preceding. +# Here we get the 1-indexed item. +[2 1 2] +> 0$ # to copy the 0-indexed item we use the appropriate index. +# This is identical to . operation +[2 1 2 2] +> ) # increment +[2 1 2 3] +> @ # pulls the third item up to the top +[2 2 3 1] +> [@] # use this trick to flip the top 3 items and put them into an array +# if you wrap any operation in brackets it flips the results into an array. +# even math operations like, [+] and [-] +[2 [3 1 2]] +> ]; # also, using at most two strokes you can orient the top three items +# in any permutation. Below are shown the results on 3,~ + # => 0 1 2 (i.e. doing nothing) + # \ => 0 2 1 + # @\ => 1 0 2 + # @ => 1 2 0 + # @@ => 2 0 1 + # \@ => 2 1 0 +[] +> ###################################################################### +# using arrays +######################################################################## +[] +> 2, # comma is the range() function +[[0 1]] +> , # and also the length() function +[2] +> ;4, # let's get an array of four items together +[[0 1 2 3]] +> ) # we can pop off the last value +[[0 1 2] 3] +> + # and put it back +[[0 1 2 3]] +> ( # we can pop off the first value +[[1 2 3] 0] +> \+ # and put it back +[[0 1 2 3]] +> 2- # we can subtract a particular value +[[0 1 3]] +> [1 3] # or a list of values +[[0 1 3] [1 3]] +> - +[[0]] +> ! # boolean operations also work on lists, strings, and blocks. If it's +# empty it's a 1, otherwise 0. Here, the list has a zero, but it's not zero- +# length, so the array as a whole is still True... and hence "not" is False +[0] +> ;4,(+ # let's make a range, pop the first value, and tack it on the end +[[1 2 3 0]] +> $ # we can also restore order by sorting the array +[[0 1 2 3]] +> 1 > # we can also use < > and = to get the indeces that match. Note this +# is not a filter! This is an index match. Filtering items greater than one +# is done with {1>}, +[[1 2 3]] +> 2 < # remember it's zero-indexed, so everything in this array is at an index +# less than 2, the indeces are 0 and 1. +[[1 2]] +> 1= # < and > return an array, even if it's one item. Equals always drops +# it out of the array +[2] +> ;6,2% # the modulo operator works on lists as the step. +[[0 2 4]] +> ;4,2,-:a 3,2+:b # booleans also work on lists. lets define two lists +[[2 3] [0 1 2 2]] +> | # "or" - returns set of items that appear in either list i.e. "union set" +[[2 3 0 1]] +> ;a b& # returns set of items that appear in 1 AND 2, e.g. "intersection set" +[[2]] +> ;a b^ # returns the symmetric difference set between two lists, +[[3 0 1]] +> ~ # tilde unpacks the items from a list +[3 0 1] +> ]; a +[2 3] +> 2? # finds the index of an item +[0] +> ;3a? +[1] +> 4a? # returns -1 if the item doesn't exist. Note: Order of element and array +# doesn't matter for searching. it can be [item list?] or [list item?]. +[1 -1] +> ]; # clear +[] +> 3,[4]* # join or intersperse: puts items in between the items +[[0 4 1 4 2]] +> ; 3,4* # multiplication of lists +[[0 1 2 0 1 2 0 1 2 0 1 2]] +> ;[1 2 3 2 3 5][2 3]/ # "split at" +[[[1] [] [5]]] +> ;[1 2 3 2 3 5][2 3]% # modulo is "split at... and drop empty" +[[[1] [5]]] +> ];#################################################################### +# strings +######################################################################## +# strings work just like arrays +[] +> "use arch, am vegan, drive a stick" ', '/ # split +[["use arch" "am vegan" "drive a stick"]] +> {'I '\+', BTW.'+}% # map +[["I use arch, BTW." "I am vegan, BTW." "I drive a stick, BTW."]] +> n* # join. Note the variable n is defined as a newline char by default +["I use arch, BTW.\nI am vegan, BTW.\nI drive a stick, BTW."] +> n/ # to replace, use split, and join with the replacement string. +[n "Also, not sure if I mentioned this, but" n]{+}* # fold sum 3-item array +* # and use join to get the result +n+ print # and then pop/print the results prettily +I use arch, BTW. +Also, not sure if I mentioned this, but +I am vegan, BTW. +Also, not sure if I mentioned this, but +I drive a stick, BTW. +[] +> '22222'{+}* # note that if you fold-sum a string not in an array, you'll +# get the sum of the ascii values. '2' is 50, so five times that is: +250 +> ]; ################################################################### +# blocks +######################################################################## +[] +> 3,~ # start with an unpacked array +[0 1 2] +> {+-} # brackets define a block which can comprise multiple functions +[0 1 2 {+-}] +> ~ # blocks are functions waiting for execution. tilde does a single +# execution of the block in this case, we added the top two values, 1 and 2, +# and subtracted from 0 +[-3] +> ;10,~{+}5* # multiplication works on executing blocks multiple times +# in this case we added the last 6 values together by running "add" 5 times +[0 1 2 3 39] +> ];10,4> # we can achieve the same result by just grabbing the last 6 items +[[4 5 6 7 8 9]] +> {+}* # and using the "fold" function for addition. +[39] +> # "fold" sequentially applies the operation pairwise from the left +# and then dumps the results. Watch what happens when we use the duplicate +# operator to fold. it's clear what happens when we duplicate and then negate +# the duplicated item: +> ;4,{.-1*}* +[0 1 -1 2 -2 3 -3] +> ]{3%}, # we can filter a list based on applying the block to each element +# in this case we get the numbers that do NOT give 0 mod 3 +[[1 -1 2 -2]] +> ;10,{3%0}, # note that only the last element matters for retaining in the +# array. Here we take 0..9, calculate x mod 3, and then return a 0. The +# intermediate generated values are dumped out sequentially. +[0 1 2 0 1 2 0 1 2 0 []] +> ]; # clear +[] +> 5,{5*}% # map performs each operation on the array and returns the result +# to an array +[[0 5 10 15 20]] +> {.}% # watch what happens when you map duplicate on each item +[[0 0 5 5 10 10 15 15 20 20]] +> ]; ################################################################### +# Control Flow! +######################################################################## +# This is the most important part of scripting. Most languages have +# two main types of loops, for loops and while loops. Even though golfscript +# has many possible loops, only a few are generally useful and terse. For loops +# are implemented using mapping, filtering, folding, and sorting over lists. +# For instance, we can take the factorial of 6 by: +6, # get 0..5 +{)}% # increment the list, i.e. "i++ for i in list" to get 1..6 +{*}* # fold by multiplication , 9 characters for the operator itself. +[720] +> 6),(;{*}* # but can we get shorter? We can save some space by incrementing +# the 6, dropping the zero, and folding. 8 characters. +> # we can also use fold to do the same thing with unfold +1 6 # accumlator and multiplicand, we'll call A and M +{}{ # while M + . # copy M, so now the stack is A M M + @ # bring A to the top, so now M M A + * # apply M to the accumulator, so M A + \( # flip the order, so it's A M, and M-- +}/; # "end", drop the list of multiplicands +# this is effectively a while-loop factorial +[720 720] +> 1.{6>!}{.@*\)}/; # we can also do the same thing with M++ while M not > 6 +> 1 6{.@*\(.}do; # works the same way as the decrementing fold. +[720 720 720] +> ]; #obviously a for loop is ideal for factorials, since it naturally lends +# itself to running over a finite set of items. +######################################################################## +# Writing code +######################################################################## +# Let's go through the process for writing a script. There are some tricks and +# ways to think about things. Let's take a simple example: a prime sieve. +# There are a few strategies for sieving. First, there's a strategy that +# uses two lists, candidates and primes. We pop a value from candidates, +# remove all the candidates divisible by it, and then add it to the primes. +# Second, there's just a filtering operation on numbers. I think it's +# probably shorter to write a program that just checks if a number has no +# numbers mod zero besides 0, 1, and itself. Slower, but shorter is king. +# Let's try this second strategy first. +[] +> 10 # we're probably going to filter a list using this strategy. It's easiest +# to start working with one element of the list. So let's take some example +# where we know the answer that we want to get. +[10] +> .,2> # let's duplicate it and take a list of values, and drop the first two +[10 [2 3 4 5 6 7 8 9]] +> {1$\%!}, # duplicate the ten, and scoot it behind the element, and then run +# 10 element %, and then ! the answer, so we are left with even multiples +[10 [2 5]] +> \; # we want to get rid of the intermediate so it doesn't show up in our +# solution. +[[2 5]] +> 10.,2,-{1$\%!},\; # Okay, let's put our little function together on one line +[[2 5] [2 5]] +> ;; # now we just filter the list using this strategy. We need to negate the +# result with ! so when we get a number with a factor, ! evaluates to 0, and +# the number is filtered out. +[] +> 10,{.,2,-{1$\%!},\;!}, # let's try filtering on the first 10 numbers +[[0 1 2 3 5 7]] +> 2> # now we can just drop 0 and 1. +[[2 3 5 7]] +> 4.?,{.,2,-{1$\%!},\;!},2> # trick: an easy way to generate large numbers in +# a few bytes is duplicate and exponentiate. 4.? is 256, and 9.? is 387420489 +[[2 3 5 7] [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 +97 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 +197 199 211 223 227 229 233 239 241 251]] +> ];'4.?,{.,2,-{1$\%!},\;!},2>', # how long is our code for p<256 ? +[25] +> ; # this is 25 characters. Can we do better?! +[] +> []99,2> # let's go with the first strategy. We'll start with an empty list +# of primes and a list of candidates +[[] [2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 +29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 +55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 +81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98]] +> (\ # pop left and leave left, we're going to copy this value with the filter +[[] 2 [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 +29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 +55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 +81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98]] +> {1$%}, # filter out anything that is 0 mod by the popped item one back on the +# stack +[[] 2 [3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 +53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97]] +> @@+ # great, all the 2-divisible values are off the list! now we need to add +# it to the running list of primes +[[3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 +57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97] [2]] +> \ # swap back. Now it seems pretty clear when our candidates list is empty +# we're done. So let's try it with a do loop. Remember we need to duplicate +# the final value for the pop check. So we add a dot +[[2] [3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 +55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97]] +> {(\{1$%},@@+\.}do; +[[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]] +> ; # ok that worked. So let's start with our initialization as well. +[]4.?,2>{(\{1$%},@@+\.}do; # and let's check our work +[[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 +103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 +211 223 227 229 233 239 241 251]] +> ,'[]99,2>{(\{1$%},@@+\.}do;', # how long is this? +[26] +> ]; # wow this solution is only 26 long, and much more effective. I don't see +# a way to get any smaller here. I wonder if with unfold we can do better? The +# strategy here is to use unfold and then at the end grab the first value from +# each table. +[] +> 99,2> # start with the candidates list +[[2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 +30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 +56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 +82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98]] +> (\{1$%}, # pop left and filter +[2 [3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 +55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97]] +> (\{1$%}, # again +[2 3 [5 7 11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 +79 83 85 89 91 95 97]] +89 91 95 97]] +> {}{(\{1$%},}/ # ok I think it'll work. let's try to put it into an unfold. +[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 [[5 7 +11 13 17 19 23 25 29 31 35 37 41 43 47 49 53 55 59 61 65 67 71 73 77 79 83 85 +89 91 95 97] [7 11 13 17 19 23 29 31 37 41 43 47 49 53 59 61 67 71 73 77 79 83 +89 91 97] [11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97] [13 +17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97] [17 19 23 29 31 37 41 +43 47 53 59 61 67 71 73 79 83 89 97] [19 23 29 31 37 41 43 47 53 59 61 67 71 73 +79 83 89 97] [23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97] [29 31 37 41 +43 47 53 59 61 67 71 73 79 83 89 97] [31 37 41 43 47 53 59 61 67 71 73 79 83 89 +97] [37 41 43 47 53 59 61 67 71 73 79 83 89 97] [41 43 47 53 59 61 67 71 73 79 +83 89 97] [43 47 53 59 61 67 71 73 79 83 89 97] [47 53 59 61 67 71 73 79 83 89 +97] [53 59 61 67 71 73 79 83 89 97] [59 61 67 71 73 79 83 89 97] [61 67 71 73 +79 83 89 97] [67 71 73 79 83 89 97] [71 73 79 83 89 97] [73 79 83 89 97] [79 83 +89 97] [83 89 97] [89 97] [97]]] +> ;] # drop that list of candidates generated at each step and put the items +# left behind by the unfold at each step (which is the primes) into a list +[[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]] +> ]; # clear and let's try with larger numbers +[] +> 4.?,2>{}{(\{1$%},}/;] +[[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 +103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 +211 223 227 229 233 239 241 251]] +>;'4.?,2>{}{(\{1$%},}/;]', # find the length of our solution. +[21] +> ]; # only 21 characters for the primes! Let's see if we actually can use this +# strategy of leaving items behind, now using the do loop to get even shorter! +> 3.?,2> # candidates +[[2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26]] +> (\{1$%}, # pop and filter +[2 [3 5 7 9 11 13 15 17 19 21 23 25]] +> (\{1$%}, # again! +[2 3 [5 7 11 13 17 19 23 25]] +> {(\{1$%},.}do;] # try in a do loop and drop the empty list of candidates at +# the end of the do loop. Don't forget the dot before the closing brace! +[[2 3 5 7 11 13 17 19 23]] +> ;4.?,2>{(\{1$%},.}do;] # check our work +[[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 +103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 +211 223 227 229 233 239 241 251]] +> ;'4.?,2>{(\{1$%},.}do;]', +[21] +>]; # Still 21 characters. there's one other thing to try, which is the prime +# test known as Wilson's theorem. We can try filtering the items down using +# this test. +[] +> '4.?,2>{.,(;{*}*.*\%},'.~\, # let's run it and take the length +[[2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 101 +103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193 197 199 +211 223 227 229 233 239 241 251] 21] +> ; # Still 21 characters! I think this number is quite good and it's not +# obvious how to beat it. The problem with GolfScript is there's always someone +# out there who thinks of some trick you didn't. For instance, you might think +# you're doing well with a Collatz seq generator of {(}{.2%{3*)}{2/}if}/ until +# you find that someone figured out {(}{3*).2%6\?/}/ which is so much shorter +# and cleaner - the unfold operation is nearly half the length! +######################################################################## +# How to read GolfScript +######################################################################## +# let's take the gcd from the GolfScript banner. It starts with: +[] +> '2706 410'~ # so that's pretty straightforward, that it just evals the list +# and dumps the results on the stack. It's common to read from stdin which +# necessitates unpacking with ~ +[2706 410] +> . # we want to know what that do loop does. the best way to do that is to +# drop the braces and run the loop one command at a time. We duplicate +[2706 410 410] +> @\ # We rearrange +[410 2706 410] +> % # we take the modulo +[410 246] +> .@\% # repeat. Note we don't need to run the final dot before the closing +# brace since this is just a value that is popped to check the loop condition +# you can also replicate the loop end with a semicolon to pop it yourself. +[246 164] +> .@\% # again! +[164 82] +> .@\% # and finally we hit zero. The loop would exit and ; would pop the zero, +# leaving you with the gcd of 82. +[82 0] +> ;; 2706 410{1$1$%.}do # Clearly this involves knowing about Euclid's method. +# you can also try a more obvious method like this one here which shows the +# numbers in sequence. +[2706 410 246 164 82 0] +>]; # so sometimes it pays dividends to know the math and you can write short +# algorithms that rely on easy tricks that aren't immediately obvious. +[] +> # let's try looking at the sudoku solver that is on the examples page. I'll +# skip the unpack step. +[2 8 4 3 7 5 1 6 9 0 0 9 2 0 0 0 0 7 0 0 1 0 0 4 0 0 2 0 5 0 0 0 0 8 0 0 0 0 8 +0 0 0 9 0 0 0 0 6 0 0 0 0 4 0 9 0 0 1 0 0 5 0 0 8 0 0 0 0 7 6 0 4 4 2 5 6 8 9 7 +3 1]:a 0?:b # again the grid is put into an array. Now, the next step +# is to define the "@" symbol as the working grid. This is because "@9" is +# interpreted as two symbols, whereas if you used something like "a" as the +# variable "a9" is interpreted as a single symbol, and this is not defined, +# so it will not get run at execution time. You would need a space which is an +# additional char. On the other hand, redefining built-ins is confusing so I +# will use "a" and "b" for the "@" and "^" definitions respectively. So the +# grid is "a" and the zero-index location of the first zero is "b", at index 9. +[9] +> ~! # this makes sure that the value is not -1 for find, i.e. -1~ evaluates to +# 0 so a ! makes it nonzero. ?~! is a great trick for "isn't in the list" +[0] +> {@p}* # this prints out the grid the number of times as the previous value, +# which is how this thing "finishes". So if 0 isn't in the grid, it prints. +> 10, # let's get the digits 0-9. Zero will be eliminated because our original +# value is zero so when we look in any row or column, zero is guaranteed to be +# there. +[[0 1 2 3 4 5 6 7 8 9]] +> a 9/ # split the original grid row-wise +b 9/ # get the row of our checked value, in this case the second row += # and we get that row and +- # take those numbers off the candidates +[[1 3 4 5 6 8]] +> a # put the grid on the stack +b 9% # get the column of the zero +> # drop the first x values of the grid +9% # take every ninth digit. We now have the column the zero is in +> - # pull those items off the candidates list +[[1 3 5 6]] +> a 3/ # split the grid into three-long arrays +b 9% # get the column of the zero +3/ # is the column in the left (0), middle (1), or right (2) triad? + > # pull that many three-groups off +3% # get every third. Now we have 9 groups - the left side of the grid +3/ # divide those 9 groups it into thirds +b 27/ # was the zero on top (0), middle (1), or bottom (2) third of the grid? += # since it's the top, grab the top group of triads. You now have the + # 1/9th of The sudoku grid where the zero sits +[[1 3 5 6] [[2 8 4] [0 0 9] [0 0 1]]] +> {+}*- # flatten those lists and remove those items from the candidates +# We now have the possible values for the position in question that work given +# the current state of the grid! if this list is empty then we've hit a +# contradiction given our previous values. +[[3 5 6]] +> 0= # {a b<\+a 1 b+>+}/ # now we've hit this unfold operation. If you run it +# you'll find we get the grids back. How does that work?! Let's take the first +# value in the "each" []{}/ operation. This is the best way to figure out what +# is happening in a mapping situation. +[3] +> a # get the grid +b< # get the grid up to the zero +\+ # and tack on our value of 3. +[[2 8 4 3 7 5 1 6 9 3]] +> a 1b+>+ # and we add on the rest of the grid. Note: we could do 1 char better +# because 1b+ is equivalent to but, longer than, just b) +[[2 8 4 3 7 5 1 6 9 3 0 9 2 0 0 0 0 7 0 0 1 0 0 4 0 0 2 0 5 0 0 0 0 8 0 0 0 0 8 +0 0 0 9 0 0 0 0 6 0 0 0 0 4 0 9 0 0 1 0 0 5 0 0 8 0 0 0 0 7 6 0 4 4 2 5 6 8 9 7 +3 1]] +> 1;; # and the do block runs again no matter what. So it's now clear why this +# thing exists with an error: if you solve the last digit, then this loop just +# keeps on rolling! You could add some bytes for some control flow but if it +# works it works and short is king. +[] + +# Closing Tips for getting to the next level: +# 0. using lookback might be more effective than swapping around the values. +# for instance, 1$1$ and \.@.@.\ do the same thing: duplicate last two items +# but the former is more obvious and shorter. +# 1. golfscript can be fun to use for messing around with integer sequences or +# do other cool math. So, don't be afraid to define your own functions to +# make your life easier, like +> {$0=}:min; {$-1=}:max; {.,(;{*}*.*\%}:isprime; {.|}:set; # etc. +# 2. write pseudocode in another language or port a script over to figure out +# what's going on. Especially useful when you combine this strategy with +# algebra engines. For instance, you can port the examples-page 1000 digits +# of pi to python and get: +# import sympy as sp +# a, k = sp.var('a'), list(range(20))[1::2] +# for _ in range(len(k)-1): +# m = k.pop() +# l = k.pop() +# k.append(((l+1)//2*m)//(l+2)+2*a) +# print(str(k[0])) +# which gives "2*a + floor(2*a/3 + floor(4*a/5 + 2*floor(6*a/7 + 3*floor( +# 8*a/9 + 4*floor(10*a/11 + 5*floor(12*a/13 + 6*floor(14*a/15 + 7*floor(16* +# a/17 + 72/17)/15)/13)/11)/9)/7)/5)/3)"... which makes it much more obvious +# what's going on than 10.3??:a;20,-2%{2+.2/@*\/a 2*+}* especially when +# you're new to the language +# 3. a little math goes a long way. The above prime test uses Wilson's theorem +# a comparable program testing for factors {:i,(;{i\%!},(;!}:isprime is +# longer and slower. Also, as discussed above, Collatz is much shorter if +# you recognize that you can do (3x+1) and then divide by 6 to the power +# ((3x+1) mod 2). (If x was even, (3x+1) is now odd, so 3x+1 div 6 is x/2.) +# avoiding conditionals and redundancy can sometimes require such insight. +# And of course, unless you know this continued fraction of pi it's hard to +# calculate it in a terse block of code. +# 4. don't be afraid to define variables and use arrays! particularly if you +# have 4 or more items to shuffle. +# 5. don't be afraid to use [some_long_script] to pack a bunch of items in an +# array after the fact, rather than gathering or adding them later or +# forcing yourself to use a datastructure that keeps the items in an array +# 6. sometimes you might get in a jam with - followed by an int that can be +# solved with ^ to do a symmetric set difference without adding a space +# 7. "#{require 'net/http';Net::HTTP.get_response(URI.parse(address)).body}" +# can get any page source from the internet, substituting 'address' for your +# URL. Try it with an OEIS b-file or wordlists, etc. You can also use the +# shorter "#{File.open('filename.txt').read}" to read in a file. GolfScript +# can run "#{any_ruby_code_here}" and add the results to the stack. +# 8. you can set anything to mean anything, which can be useful for golf: +# 3:^;^2? => 9 because this set ^ to 3, and 3 2 ? => 9 +# 3:a;a2? => Warning: pop on empty stack - because a2 doesn't exist +# 3:a;a 2? => 9 - it works again, but takes an extra character over ^2 +# usually you will only want to do this once you're trying to squeeze the +# last few chars out of your code because it ruins your environment. +``` + +* [Run GolfScript online](https://tio.run/#golfscript) +* [GolfScript's documentation](http://www.golfscript.com/golfscript/builtin.html) +* [Useful StackExchange thread](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript) +* [GolfScript on GitHub](https://github.com/darrenks/golfscript) From 781ebf270b3001883847a28237b57d93dff1269a Mon Sep 17 00:00:00 2001 From: Dmytro Sytnik Date: Mon, 13 May 2024 15:21:49 -0400 Subject: [PATCH 207/392] [smalltalk/en] add mixed type array (#4109) --- smalltalk.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index 9c2e870e..e1ae832c 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -441,8 +441,9 @@ Fixed length collection - WordArray: Array limited to word elements (0-2^32) ```smalltalk -| b x y sum max | +| b x y z sum max | x := #(4 3 2 1). "constant array" +z := #(1 2 3 'hi'). "mixed type array" x := Array with: 5 with: 4 with: 3 with: 2. "create array with up to 4 elements" x := Array new: 4. "allocate an array with specified size" x "set array elements" From 950adf2cc3a358d08848da8c2346cbb74ce33311 Mon Sep 17 00:00:00 2001 From: Yujia Qiao Date: Tue, 14 May 2024 03:28:48 +0800 Subject: [PATCH 208/392] [Chapel/en] Update chapel.html.markdown (#3877) --- chapel.html.markdown | 388 +++++++++++++++++++++++++------------------ 1 file changed, 224 insertions(+), 164 deletions(-) diff --git a/chapel.html.markdown b/chapel.html.markdown index 4f6c3df2..fe00da0f 100644 --- a/chapel.html.markdown +++ b/chapel.html.markdown @@ -13,42 +13,60 @@ as well as multi-kilocore supercomputers. More information and support can be found at the bottom of this document. +You can refer to the official site for [latest version](https://chapel-lang.org/docs/master/primers/learnChapelInYMinutes.html) of this document. + ```chapel +/* + Learn Chapel in Y Minutes + + This primer will go over basic syntax and concepts in Chapel. + Last sync with official page: Sun, 08 Mar 2020 08:05:53 +0000 +*/ + // Comments are C-family style // one line comment /* - multi-line comment + multi-line comment */ -// Basic printing +/* +Basic printing +*/ write("Hello, "); writeln("World!"); -// write and writeln can take a list of things to print. +// ``write`` and ``writeln`` can take a list of things to print. // Each thing is printed right next to the others, so include your spacing! writeln("There are ", 3, " commas (\",\") in this line of code"); // Different output channels: +use IO; // Required for accessing the alternative output channels + stdout.writeln("This goes to standard output, just like plain writeln() does"); stderr.writeln("This goes to standard error"); +/* +Variables +*/ // Variables don't have to be explicitly typed as long as // the compiler can figure out the type that it will hold. -// 10 is an int, so myVar is implicitly an int +// 10 is an ``int``, so ``myVar`` is implicitly an ``int`` var myVar = 10; myVar = -10; var mySecondVar = myVar; -// var anError; would be a compile-time error. +// ``var anError;`` would be a compile-time error. // We can (and should) explicitly type things. var myThirdVar: real; var myFourthVar: real = -1.234; myThirdVar = myFourthVar; -// Types +/* +Types +*/ // There are a number of basic types. var myInt: int = -1000; // Signed ints @@ -75,39 +93,45 @@ type RGBColor = 3*chroma; // Type representing a full color var black: RGBColor = (0,0,0); var white: RGBColor = (255, 255, 255); -// Constants and Parameters +/* +Constants and Parameters +*/ -// A const is a constant, and cannot be changed after set in runtime. +// A ``const`` is a constant, and cannot be changed after set in runtime. const almostPi: real = 22.0/7.0; -// A param is a constant whose value must be known statically at +// A ``param`` is a constant whose value must be known statically at // compile-time. param compileTimeConst: int = 16; -// The config modifier allows values to be set at the command line. -// Set with --varCmdLineArg=Value or --varCmdLineArg Value at runtime. +// The ``config`` modifier allows values to be set at the command line. +// Set with ``--varCmdLineArg=Value`` or ``--varCmdLineArg Value`` at runtime. config var varCmdLineArg: int = -123; config const constCmdLineArg: int = 777; -// config param can be set at compile-time. -// Set with --set paramCmdLineArg=value at compile-time. +// ``config param`` can be set at compile-time. +// Set with ``--set paramCmdLineArg=value`` at compile-time. config param paramCmdLineArg: bool = false; writeln(varCmdLineArg, ", ", constCmdLineArg, ", ", paramCmdLineArg); -// References +/* +References +*/ -// ref operates much like a reference in C++. In Chapel, a ref cannot +// ``ref`` operates much like a reference in C++. In Chapel, a ``ref`` cannot // be made to alias a variable other than the variable it is initialized with. -// Here, refToActual refers to actual. +// Here, ``refToActual`` refers to ``actual``. var actual = 10; -ref refToActual = actual; +ref refToActual = actual; writeln(actual, " == ", refToActual); // prints the same value actual = -123; // modify actual (which refToActual refers to) writeln(actual, " == ", refToActual); // prints the same value refToActual = 99999999; // modify what refToActual refers to (which is actual) writeln(actual, " == ", refToActual); // prints the same value -// Operators +/* +Operators +*/ // Math operators: var a: int, thisInt = 1234, thatInt = 5678; @@ -146,7 +170,7 @@ a <<= 3; // Left-bit-shift-equals (a = a << 10;) // Unlike other C family languages, there are no // pre/post-increment/decrement operators, such as: // -// ++j, --j, j++, j-- +// ``++j``, ``--j``, ``j++``, ``j--`` // Swap operator: var old_this = thisInt; @@ -156,7 +180,9 @@ writeln((old_this == thatInt) && (old_that == thisInt)); // Operator overloads can also be defined, as we'll see with procedures. -// Tuples +/* +Tuples +*/ // Tuples can be of the same type or different types. var sameTup: 2*int = (10, -1); @@ -179,16 +205,18 @@ writeln(diffTup == (tupInt, tupReal, tupCplx)); // They are also useful for writing a list of variables, as is common in debugging. writeln((a,b,thisInt,thatInt,thisBool,thatBool)); -// Control Flow +/* +Control Flow +*/ -// if - then - else works just like any other C-family language. +// ``if`` - ``then`` - ``else`` works just like any other C-family language. if 10 < 100 then writeln("All is well"); if -1 < 1 then writeln("Continuing to believe reality"); else - writeln("Send mathematician, something is wrong"); + writeln("Send mathematician, something's wrong"); // You can use parentheses if you prefer. if (10 > 100) { @@ -209,11 +237,11 @@ if a % 3 == 0 { writeln(b, " is divided by 3 with a remainder of 2."); } -// Ternary: if - then - else in a statement. +// Ternary: ``if`` - ``then`` - ``else`` in a statement. var maximum = if thisInt < thatInt then thatInt else thisInt; -// select statements are much like switch statements in other languages. -// However, select statements do not cascade like in C or Java. +// ``select`` statements are much like switch statements in other languages. +// However, ``select`` statements don't cascade like in C or Java. var inputOption = "anOption"; select inputOption { when "anOption" do writeln("Chose 'anOption'"); @@ -223,11 +251,11 @@ select inputOption { } otherwise { writeln("Any other Input"); - writeln("the otherwise case does not need a do if the body is one line"); + writeln("the otherwise case doesn't need a do if the body is one line"); } } -// while and do-while loops also behave like their C counterparts. +// ``while`` and ``do``-``while`` loops also behave like their C counterparts. var j: int = 1; var jSum: int = 0; while (j <= 1000) { @@ -242,8 +270,8 @@ do { } while (j <= 10000); writeln(jSum); -// for loops are much like those in Python in that they iterate over a -// range. Ranges (like the 1..10 expression below) are a first-class object +// ``for`` loops are much like those in python in that they iterate over a +// range. Ranges (like the ``1..10`` expression below) are a first-class object // in Chapel, and as such can be stored in variables. for i in 1..10 do write(i, ", "); writeln(); @@ -261,7 +289,9 @@ for x in 1..10 { writeln(); } -// Ranges and Domains +/* +Ranges and Domains +*/ // For-loops and arrays both use ranges and domains to define an index set that // can be iterated over. Ranges are single dimensional integer indices, while @@ -277,17 +307,18 @@ var rangeEmpty: range = 100..-100; // this is valid but contains no indices var range1toInf: range(boundedType=BoundedRangeType.boundedLow) = 1.. ; // 1, 2, 3, 4, 5, ... var rangeNegInfTo1 = ..1; // ..., -4, -3, -2, -1, 0, 1 -// Ranges can be strided (and reversed) using the by operator. +// Ranges can be strided (and reversed) using the ``by`` operator. var range2to10by2: range(stridable=true) = 2..10 by 2; // 2, 4, 6, 8, 10 var reverse2to10by2 = 2..10 by -2; // 10, 8, 6, 4, 2 var trapRange = 10..1 by -1; // Do not be fooled, this is still an empty range -writeln("Size of range ", trapRange, " = ", trapRange.length); +writeln("Size of range '", trapRange, "' = ", trapRange.size); -// Note: range(boundedType= ...) and range(stridable= ...) are only +// Note: ``range(boundedType= ...)`` and ``range(stridable= ...)`` are only // necessary if we explicitly type the variable. -// The end point of a range can be determined using the count (#) operator. +// The end point of a range can be computed by specifying the total size +// of the range using the count (``#``) operator. var rangeCount: range = -5..#12; // range from -5 to 6 // Operators can be mixed. @@ -297,8 +328,8 @@ writeln(rangeCountBy); // Properties of the range can be queried. // In this example, printing the first index, last index, number of indices, // stride, and if 2 is include in the range. -writeln((rangeCountBy.first, rangeCountBy.last, rangeCountBy.length, - rangeCountBy.stride, rangeCountBy.member(2))); +writeln((rangeCountBy.first, rangeCountBy.last, rangeCountBy.size, + rangeCountBy.stride, rangeCountBy.contains(2))); for i in rangeCountBy { write(i, if i == rangeCountBy.last then "\n" else ", "); @@ -322,7 +353,7 @@ for idx in twoDimensions do write(idx, ", "); writeln(); -// These tuples can also be deconstructed. +// These tuples can also be destructured. for (x,y) in twoDimensions { write("(", x, ", ", y, ")", ", "); } @@ -352,7 +383,9 @@ var domainB = {-5..5, 1..10}; var domainC = domainA[domainB]; writeln((domainA, domainB, domainC)); -// Arrays +/* +Arrays +*/ // Arrays are similar to those of other languages. // Their sizes are defined using domains that represent their indices. @@ -364,9 +397,9 @@ for i in 1..10 do intArray[i] = -i; writeln(intArray); -// We cannot access intArray[0] because it exists outside -// of the index set, {1..10}, we defined it to have. -// intArray[11] is illegal for the same reason. +// We cannot access ``intArray[0]`` because it exists outside +// of the index set, ``{1..10}``, we defined it to have. +// ``intArray[11]`` is illegal for the same reason. var realDomain: domain(2) = {1..5,1..7}; var realArray: [realDomain] real; var realArray2: [1..5,1..7] real; // equivalent @@ -396,9 +429,9 @@ for value in realArray { writeln(rSum, "\n", realArray); // Associative arrays (dictionaries) can be created using associative domains. -var dictDomain: domain(string) = { "one", "two" }; -var dict: [dictDomain] int = ["one" => 1, "two" => 2]; -dict["three"] = 3; // Adds 'three' to 'dictDomain' implicitly +var dictDomain: domain(string) = { "one", "two", "three"}; +var dict: [dictDomain] int = ["one" => 1, "two" => 2, "three" => 3]; + for key in dictDomain.sorted() do writeln(dict[key]); @@ -407,9 +440,9 @@ for key in dictDomain.sorted() do var thisArray : [0..5] int = [0,1,2,3,4,5]; var thatArray : [0..5] int; -// First, simply assign one to the other. This copies thisArray into -// thatArray, instead of just creating a reference. Therefore, modifying -// thisArray does not also modify thatArray. +// First, simply assign one to the other. This copies ``thisArray`` into +// ``thatArray``, instead of just creating a reference. Therefore, modifying +// ``thisArray`` does not also modify ``thatArray``. thatArray = thisArray; thatArray[1] = -1; @@ -425,7 +458,7 @@ var thisPlusThat = thisArray + thatArray; writeln(thisPlusThat); // Moving on, arrays and loops can also be expressions, where the loop -// body expression is the result of each iteration. +// body's expression is the result of each iteration. var arrayFromLoop = for i in 1..10 do i; writeln(arrayFromLoop); @@ -435,16 +468,18 @@ var evensOrFives = for i in 1..10 do if (i % 2 == 0 || i % 5 == 0) then i; writeln(arrayFromLoop); // Array expressions can also be written with a bracket notation. -// Note: this syntax uses the forall parallel concept discussed later. +// Note: this syntax uses the ``forall`` parallel concept discussed later. var evensOrFivesAgain = [i in 1..10] if (i % 2 == 0 || i % 5 == 0) then i; // They can also be written over the values of the array. arrayFromLoop = [value in arrayFromLoop] value + 1; -// Procedures +/* +Procedures +*/ -// Chapel procedures have similar syntax functions in other languages. +// Chapel procedures have similar syntax functions in other languages. proc fibonacci(n : int) : int { if n <= 1 then return n; return fibonacci(n-1) + fibonacci(n-2); @@ -482,10 +517,10 @@ writeln(defaultsProc(x=11)); writeln(defaultsProc(x=12, y=5.432)); writeln(defaultsProc(y=9.876, x=13)); -// The ? operator is called the query operator, and is used to take +// The ``?`` operator is called the query operator, and is used to take // undetermined values like tuple or array sizes and generic types. // For example, taking arrays as parameters. The query operator is used to -// determine the domain of A. This is uesful for defining the return type, +// determine the domain of ``A``. This is useful for defining the return type, // though it's not required. proc invertArray(A: [?D] int): [D] int{ for a in A do a = -a; @@ -509,7 +544,7 @@ genericProc(1, 2); genericProc(1.2, 2.3); genericProc(1.0+2.0i, 3.0+4.0i); -// We can also enforce a form of polymorphism with the where clause +// We can also enforce a form of polymorphism with the ``where`` clause // This allows the compiler to decide which function to use. // Note: That means that all information needs to be known at compile-time. // The param modifier on the arg is used to enforce this constraint. @@ -526,13 +561,13 @@ proc whereProc(param N : int): void whereProc(10); whereProc(-1); -// whereProc(0) would result in a compiler error because there -// are no functions that satisfy the where clause's condition. -// We could have defined a whereProc without a where clause +// ``whereProc(0)`` would result in a compiler error because there +// are no functions that satisfy the ``where`` clause's condition. +// We could have defined a ``whereProc`` without a ``where`` clause // that would then have served as a catch all for all the other cases // (of which there is only one). -// where clauses can also be used to constrain based on argument type. +// ``where`` clauses can also be used to constrain based on argument type. proc whereType(x: ?t) where t == int { writeln("Inside 'int' version of 'whereType': ", x); } @@ -544,7 +579,9 @@ proc whereType(x: ?t) { whereType(42); whereType("hello"); -// Intents +/* +Intents +*/ /* Intent modifiers on the arguments convey how those arguments are passed to the procedure. @@ -571,7 +608,7 @@ intentsProc(inVar, outVar, inoutVar, refVar); writeln("Outside After: ", (inVar, outVar, inoutVar, refVar)); // Similarly, we can define intents on the return type. -// refElement returns a reference to an element of array. +// ``refElement`` returns a reference to an element of array. // This makes more practical sense for class methods where references to // elements in a data-structure are returned via a method or iterator. proc refElement(array : [?D] ?T, idx) ref : T { @@ -586,14 +623,16 @@ refToElem = -2; // modify reference which modifies actual value in array writeln(refToElem); writeln(myChangingArray); -// Operator Definitions +/* +Operator Definitions +*/ // Chapel allows for operators to be overloaded. // We can define the unary operators: -// + - ! ~ +// ``+ - ! ~`` // and the binary operators: -// + - * / % ** == <= >= < > << >> & | ˆ by -// += -= *= /= %= **= &= |= ˆ= <<= >>= <=> +// ``+ - * / % ** == <= >= < > << >> & | ˆ by`` +// ``+= -= *= /= %= **= &= |= ˆ= <<= >>= <=>`` // Boolean exclusive or operator. proc ^(left : bool, right : bool): bool { @@ -605,25 +644,28 @@ writeln(false ^ true); writeln(true ^ false); writeln(false ^ false); -// Define a * operator on any two types that returns a tuple of those types. +// Define a ``*`` operator on any two types that returns a tuple of those types. proc *(left : ?ltype, right : ?rtype): (ltype, rtype) { writeln("\tIn our '*' overload!"); return (left, right); } -writeln(1 * "a"); // Uses our * operator. -writeln(1 * 2); // Uses the default * operator. +writeln(1 * "a"); // Uses our ``*`` operator. +writeln(1 * 2); // Uses the default ``*`` operator. // Note: You could break everything if you get careless with your overloads. // This here will break everything. Don't do it. -/* - proc +(left: int, right: int): int { - return left - right; - } +/* + + proc +(left: int, right: int): int { + return left - right; + } */ -// Iterators +/* +Iterators +*/ // Iterators are sisters to the procedure, and almost everything about // procedures also applies to iterators. However, instead of returning a single @@ -656,7 +698,7 @@ for i in absolutelyNothing(10) { } // We can zipper together two or more iterators (who have the same number -// of iterations) using zip() to create a single zipped iterator, where each +// of iterations) using ``zip()`` to create a single zipped iterator, where each // iteration of the zipped iterator yields a tuple of one value yielded // from each iterator. for (positive, negative) in zip(1..5, -5..-1) do @@ -683,11 +725,10 @@ for (i, j) in zip(toThisArray.domain, -100..#5) { } writeln(toThisArray); -// This is very important in understanding why this statement exhibits a -// runtime error. +// This is very important in understanding why this statement exhibits a runtime error. -/* - var iterArray : [1..10] int = [i in 1..10] if (i % 2 == 1) then i; +/* + var iterArray : [1..10] int = [i in 1..10] if (i % 2 == 1) then i; */ // Even though the domain of the array and the loop-expression are @@ -695,8 +736,9 @@ writeln(toThisArray); // Because iterators can yield nothing, that iterator yields a different number // of things than the domain of the array or loop, which is not allowed. -// Classes - +/* +Classes +*/ // Classes are similar to those in C++ and Java, allocated on the heap. class MyClass { @@ -704,13 +746,16 @@ class MyClass { var memberInt : int; var memberBool : bool = true; -// Explicitly defined initializer. -// We also get the compiler-generated initializer, with one argument per field. -// Note that soon there will be no compiler-generated initializer when we -// define any initializer(s) explicitly. - proc init(val : real) { - this.memberInt = ceil(val): int; - } +// By default, any class that doesn't define an initializer gets a +// compiler-generated initializer, with one argument per field and +// the field's initial value as the argument's default value. +// Alternatively, the user can define initializers manually as shown +// in the following commented-out routine: +// +/* // proc init(val : real) { + // this.memberInt = ceil(val): int; + // } +*/ // Explicitly defined deinitializer. // If we did not write one, we would get the compiler-generated deinitializer, @@ -738,37 +783,45 @@ class MyClass { } // end MyClass // Call compiler-generated initializer, using default value for memberBool. -var myObject = new MyClass(10); - myObject = new MyClass(memberInt = 10); // Equivalent -writeln(myObject.getMemberInt()); +{ + var myObject = new owned MyClass(10); + myObject = new owned MyClass(memberInt = 10); // Equivalent + writeln(myObject.getMemberInt()); -// Same, but provide a memberBool value explicitly. -var myDiffObject = new MyClass(-1, true); - myDiffObject = new MyClass(memberInt = -1, - memberBool = true); // Equivalent -writeln(myDiffObject); + // Same, but provide a memberBool value explicitly. + var myDiffObject = new owned MyClass(-1, true); + myDiffObject = new owned MyClass(memberInt = -1, + memberBool = true); // Equivalent + writeln(myDiffObject); -// Call the initializer we wrote. -var myOtherObject = new MyClass(1.95); - myOtherObject = new MyClass(val = 1.95); // Equivalent -writeln(myOtherObject.getMemberInt()); + // Similar, but rely on the default value of memberInt, passing in memberBool. + var myThirdObject = new owned MyClass(memberBool = true); + writeln(myThirdObject); -// We can define an operator on our class as well, but -// the definition has to be outside the class definition. -proc +(A : MyClass, B : MyClass) : MyClass { - return new MyClass(memberInt = A.getMemberInt() + B.getMemberInt(), - memberBool = A.getMemberBool() || B.getMemberBool()); + // If the user-defined initializer above had been uncommented, we could + // make the following calls: + // + /* // var myOtherObject = new MyClass(1.95); + // myOtherObject = new MyClass(val = 1.95); + // writeln(myOtherObject.getMemberInt()); + */ + + // We can define an operator on our class as well, but + // the definition has to be outside the class definition. + proc +(A : MyClass, B : MyClass) : owned MyClass { + return + new owned MyClass(memberInt = A.getMemberInt() + B.getMemberInt(), + memberBool = A.getMemberBool() || B.getMemberBool()); + } + + var plusObject = myObject + myDiffObject; + writeln(plusObject); + + // Destruction of an object: calls the deinit() routine and frees its memory. + // ``unmanaged`` variables should have ``delete`` called on them. + // ``owned`` variables are destroyed when they go out of scope. } -var plusObject = myObject + myDiffObject; -writeln(plusObject); - -// Destruction. -delete myObject; -delete myDiffObject; -delete myOtherObject; -delete plusObject; - // Classes can inherit from one or more parent classes class MyChildClass : MyClass { var memberComplex: complex; @@ -780,42 +833,46 @@ class GenericClass { var classDomain: domain(1); var classArray: [classDomain] classType; -// Explicit constructor. - proc GenericClass(type classType, elements : int) { - this.classDomain = {1..#elements}; +// Explicit initializer. + proc init(type classType, elements : int) { + this.classType = classType; + this.classDomain = {1..elements}; + // all generic and const fields must be initialized in "phase 1" prior + // to a call to the superclass initializer. } -// Copy constructor. -// Note: We still have to put the type as an argument, but we can -// default to the type of the other object using the query (?) operator. -// Further, we can take advantage of this to allow our copy constructor -// to copy classes of different types and cast on the fly. - proc GenericClass(other : GenericClass(?otherType), - type classType = otherType) { +// Copy-style initializer. +// Note: We include a type argument whose default is the type of the first +// argument. This lets our initializer copy classes of different +// types and cast on the fly. + proc init(other : GenericClass(?), + type classType = other.classType) { + this.classType = classType; this.classDomain = other.classDomain; - // Copy and cast - for idx in this.classDomain do this[idx] = other[idx] : classType; + this.classArray = for o in other do o: classType; // copy and cast } // Define bracket notation on a GenericClass // object so it can behave like a normal array -// i.e. objVar[i] or objVar(i) +// i.e. ``objVar[i]`` or ``objVar(i)`` proc this(i : int) ref : classType { return this.classArray[i]; } // Define an implicit iterator for the class // to yield values from the array to a loop -// i.e. for i in objVar do ... +// i.e. ``for i in objVar do ...`` iter these() ref : classType { for i in this.classDomain do yield this[i]; } } // end GenericClass +// Allocate an owned instance of our class +var realList = new owned GenericClass(real, 10); + // We can assign to the member array of the object using the bracket // notation that we defined. -var realList = new GenericClass(real, 10); for i in realList.classDomain do realList[i] = i + 1.0; // We can iterate over the values in our list with the iterator @@ -823,23 +880,25 @@ for i in realList.classDomain do realList[i] = i + 1.0; for value in realList do write(value, ", "); writeln(); -// Make a copy of realList using the copy constructor. -var copyList = new GenericClass(realList); +// Make a copy of realList using the copy initializer. +var copyList = new owned GenericClass(realList); for value in copyList do write(value, ", "); writeln(); -// Make a copy of realList and change the type, also using the copy constructor. -var copyNewTypeList = new GenericClass(realList, int); +// Make a copy of realList and change the type, also using the copy initializer. +var copyNewTypeList = new owned GenericClass(realList, int); for value in copyNewTypeList do write(value, ", "); writeln(); -// Modules +/* +Modules +*/ // Modules are Chapel's way of managing name spaces. // The files containing these modules do not need to be named after the modules // (as in Java), but files implicitly name modules. -// For example, this file implicitly names the learnChapelInYMinutes module +// For example, this file implicitly names the ``learnChapelInYMinutes`` module module OurModule { @@ -870,21 +929,23 @@ module OurModule { } } // end OurModule -// Using OurModule also uses all the modules it uses. -// Since OurModule uses Time, we also use Time. +// Using ``OurModule`` also uses all the modules it uses. +// Since ``OurModule`` uses ``Time``, we also use ``Time``. use OurModule; -// At this point we have not used ChildModule or SiblingModule so -// their symbols (i.e. foo) are not available to us. However, the module -// names are available, and we can explicitly call foo() through them. +// At this point we have not used ``ChildModule`` or ``SiblingModule`` so +// their symbols (i.e. ``foo``) are not available to us. However, the module +// names are available, and we can explicitly call ``foo()`` through them. SiblingModule.foo(); OurModule.ChildModule.foo(); -// Now we use ChildModule, enabling unqualified calls. +// Now we use ``ChildModule``, enabling unqualified calls. use ChildModule; foo(); -// Parallelism +/* +Parallelism +*/ // In other languages, parallelism is typically done with // complicated libraries and strange class structure hierarchies. @@ -894,9 +955,9 @@ foo(); // executed. proc main() { -// A begin statement will spin the body of that statement off +// A ``begin`` statement will spin the body of that statement off // into one new task. -// A sync statement will ensure that the progress of the main +// A ``sync`` statement will ensure that the progress of the main // task will not progress until the children have synced back up. sync { @@ -913,7 +974,7 @@ proc main() { writeln("fibonacci(",n,") = ", fibonacci(n)); } -// A cobegin statement will spin each statement of the body into one new +// A ``cobegin`` statement will spin each statement of the body into one new // task. Notice here that the prints from each statement may happen in any // order. cobegin { @@ -929,17 +990,17 @@ proc main() { } } -// A coforall loop will create a new task for EACH iteration. +// A ``coforall`` loop will create a new task for EACH iteration. // Again we see that prints happen in any order. -// NOTE: coforall should be used only for creating tasks! +// NOTE: ``coforall`` should be used only for creating tasks! // Using it to iterating over a structure is very a bad idea! var num_tasks = 10; // Number of tasks we want - coforall taskID in 1..#num_tasks { + coforall taskID in 1..num_tasks { writeln("Hello from task# ", taskID); } -// forall loops are another parallel loop, but only create a smaller number -// of tasks, specifically --dataParTasksPerLocale= number of tasks. +// ``forall`` loops are another parallel loop, but only create a smaller number +// of tasks, specifically ``--dataParTasksPerLocale=`` number of tasks. forall i in 1..100 { write(i, ", "); } @@ -951,10 +1012,10 @@ proc main() { // (1..3, 4..6, or 7..9) doing that chunk serially, but each task happens // in parallel. Your results may depend on your machine and configuration -// For both the forall and coforall loops, the execution of the +// For both the ``forall`` and ``coforall`` loops, the execution of the // parent task will not continue until all the children sync up. -// forall loops are particularly useful for parallel iteration over arrays. +// ``forall`` loops are particularly useful for parallel iteration over arrays. // Lets run an experiment to see how much faster a parallel loop is use Time; // Import the Time module to use Timer objects var timer: Timer; @@ -982,14 +1043,14 @@ proc main() { // the parallel loop went faster than the serial loop. // The bracket style loop-expression described -// much earlier implicitly uses a forall loop. +// much earlier implicitly uses a ``forall`` loop. [val in myBigArray] val = 1 / val; // Parallel operation // Atomic variables, common to many languages, are ones whose operations // occur uninterrupted. Multiple threads can therefore modify atomic // variables and can know that their values are safe. -// Chapel atomic variables can be of type bool, int, -// uint, and real. +// Chapel atomic variables can be of type ``bool``, ``int``, +// ``uint``, and ``real``. var uranium: atomic int; uranium.write(238); // atomically write a variable writeln(uranium.read()); // atomically read a variable @@ -1003,7 +1064,7 @@ proc main() { writeln("uranium was ", was, " but is now ", replaceWith); var isEqualTo = 235; - if uranium.compareExchange(isEqualTo, replaceWith) { + if uranium.compareAndSwap(isEqualTo, replaceWith) { writeln("uranium was equal to ", isEqualTo, " so replaced value with ", replaceWith); } else { @@ -1025,7 +1086,7 @@ proc main() { } } -// sync variables have two states: empty and full. +// ``sync`` variables have two states: empty and full. // If you read an empty variable or write a full variable, you are waited // until the variable is full or empty again. var someSyncVar$: sync int; // varName$ is a convention not a law. @@ -1043,9 +1104,8 @@ proc main() { } } -// single vars can only be written once. A read on an unwritten single -// results in a wait, but when the variable has a value it can be read -// indefinitely. +// ``single`` vars can only be written once. A read on an unwritten ``single`` +// results in a wait, but when the variable has a value it can be read indefinitely. var someSingleVar$: single int; // varName$ is a convention not a law. sync { begin { // Reader task @@ -1063,7 +1123,7 @@ proc main() { } } -// Here's an example using atomics and a sync variable to create a +// Here's an example using atomics and a ``sync`` variable to create a // count-down mutex (also known as a multiplexer). var count: atomic int; // our counter var lock$: sync bool; // the mutex lock @@ -1074,7 +1134,7 @@ proc main() { // (full:unlocked / empty:locked) // Also, writeXF() fills (F) the sync var regardless of its state (X) - coforall task in 1..#5 { // Generate tasks + coforall task in 1..5 { // Generate tasks // Create a barrier do { lock$; // Read lock$ (wait) @@ -1091,7 +1151,7 @@ proc main() { lock$.writeXF(true); // Set lock$ to full (signal) } -// We can define the operations + * & | ^ && || min max minloc maxloc +// We can define the operations ``+ * & | ^ && || min max minloc maxloc`` // over an entire array using scans and reductions. // Reductions apply the operation over the entire array and // result in a scalar value. @@ -1099,7 +1159,7 @@ proc main() { var sumOfValues = + reduce listOfValues; var maxValue = max reduce listOfValues; // 'max' give just max value -// maxloc gives max value and index of the max value. +// ``maxloc`` gives max value and index of the max value. // Note: We have to zip the array and domain together with the zip iterator. var (theMaxValue, idxOfMax) = maxloc reduce zip(listOfValues, listOfValues.domain); @@ -1108,7 +1168,7 @@ proc main() { // Scans apply the operation incrementally and return an array with the // values of the operation at that index as it progressed through the -// array from array.domain.low to array.domain.high. +// array from ``array.domain.low`` to ``array.domain.high``. var runningSumOfValues = + scan listOfValues; var maxScan = max scan listOfValues; writeln(runningSumOfValues); From d935b164e43ca32c8670d6d5482ff8e330478c78 Mon Sep 17 00:00:00 2001 From: Eli Orzitzer Date: Mon, 13 May 2024 22:32:33 +0300 Subject: [PATCH 209/392] [yaml/en] Fix an example in YAML (#4562) --- yaml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index 6901695c..6e2545c4 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -177,7 +177,7 @@ bar: <<: *base # base anchor will be merged age: 20 -# foo and bar would also have name: Everyone has same name +# foo name won't be changed and it will be: John. On the other hand, bar's name will be changed to the base one: Everyone has same name # YAML also has tags, which you can use to explicitly declare types. # Syntax: !![typeName] [value] From bb91dc603bbe2c24adda27933a22b1f850003778 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 14 May 2024 05:23:32 -0600 Subject: [PATCH 210/392] [set-theory/zh-cn] list original author --- zh-cn/set-theory-cn.html.markdown | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/zh-cn/set-theory-cn.html.markdown b/zh-cn/set-theory-cn.html.markdown index 13ba2c80..2fdc6ea5 100644 --- a/zh-cn/set-theory-cn.html.markdown +++ b/zh-cn/set-theory-cn.html.markdown @@ -2,10 +2,12 @@ category: Algorithms & Data Structures name: Set theory contributors: + - ["Andrew Ryan Davis", "https://github.com/AndrewDavis1191"] translators: - ["Tianchen Xu", "https://github.com/lo0b0o"] lang: zh-cn --- + 集合论是数学的一个分支,研究集合、它们的运算和它们的性质。 * 集合由不重复的项组成。 @@ -13,6 +15,7 @@ lang: zh-cn ## 基本符号 ### 运算符 + * 并运算符,`∪`,表示“或”; * 交运算符,`∩`,表示“且”; * 差运算符,`\`,表示“不包括”; @@ -20,12 +23,14 @@ lang: zh-cn * 叉积运算符,`×`,表示笛卡尔积。 ### 限定词 + * 冒号限定词,`:`,表示“使得”; * 从属限定词,`∈`,表示“属于”; * 子集限定词,`⊆`,表示“是……的子集”; * 真子集限定词,`⊂`,表示“是……的真子集”。 -### 重要的集合 +### 重要的集合 + * `∅`,空集,即不包含任何元素的集合; * `ℕ`,自然数集; * `ℤ`,整数集; @@ -33,6 +38,7 @@ lang: zh-cn * `ℝ`,实数集。 关于以上集合,有如下几点需要注意: + 1. 空集是其本身的子集(并且也是任何其他集合的子集),即便空集不包含任何项; 2. 数学家们对于零是否为自然数的看法通常并不统一,教科书一般会明确说明作者是否认为零是自然数。 @@ -43,7 +49,7 @@ lang: zh-cn 例如,若 `S = { 1, 2, 4 }`,则 `|S| = 3`。 ### 空集 - + * 可以在集合符号中使用不成立的条件来构造空集,例如,`∅ = { x : x ≠ x }`,或 `∅ = { x : x ∈ N, x < 0 }`; * 空集总是唯一的(即,有且只有一个空集); * 空集是所有集合的子集; @@ -98,6 +104,7 @@ P(A) = { x : x ⊆ A } ``` ## 两个集合的运算 + ### 并 给定集合 `A` 和 `B`,两个集合的并由出现在 `A` 或 `B` 中的项构成,记作 `A ∪ B`。 @@ -115,6 +122,7 @@ A ∩ B = { x : x ∈ A, x ∈ B } ``` ### 差 + 给定集合 `A` 和 `B`,`A` 对于 `B` 的集合差指的是属于 `A` 但不属于 `B` 的每一项。 ``` @@ -122,6 +130,7 @@ A \ B = { x : x ∈ A, x ∉ B } ``` ### 对称差 + 给定集合 `A` 和 `B`,对称差指的是属于 `A` 或 `B` 但不属于它们交集的所有项。 ``` @@ -131,6 +140,7 @@ A △ B = (A \ B) ∪ (B \ A) ``` ### 笛卡尔积 + 给定集合 `A` 和 `B`,`A` 和 `B` 的笛卡尔积由 `A` 和 `B` 的项的所有组合构成。 ``` From 8ceeec19fdcf662f3ac02593944308cce33a15ac Mon Sep 17 00:00:00 2001 From: Nicholas Georgescu <36280690+NGeorgescu@users.noreply.github.com> Date: Tue, 14 May 2024 18:47:58 -0400 Subject: [PATCH 211/392] [golfscript/en-en] Add some nifty string tricks (#4945) --- golfscript.html.markdown | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/golfscript.html.markdown b/golfscript.html.markdown index 8ea985e8..f4b88a9f 100644 --- a/golfscript.html.markdown +++ b/golfscript.html.markdown @@ -242,7 +242,18 @@ I drive a stick, BTW. [] > '22222'{+}* # note that if you fold-sum a string not in an array, you'll # get the sum of the ascii values. '2' is 50, so five times that is: -250 +[250] +> ]; # this actually is a clever trick to get ascii values into an array. +[] +> "aabc" [{""+~}*] # if you fold over addition and drop it into a string: +[[97 97 98 99]] +> {[.]""^}%""+ # which can be returned to a string as such using a ""^ map. +# and an empty string join. +["aabc"] +> {32-}% # note that most mapping operations work on the ascii values as +# you would expect, for instance with the difference between A and a being +# 32, you can just subtract that from the ascii value to get: +["AABC"] > ]; ################################################################### # blocks ######################################################################## From e543ca4e52e2fc65b0ada75eded4af775a1c3bb2 Mon Sep 17 00:00:00 2001 From: hivazarei <82463110+hivazarei@users.noreply.github.com> Date: Tue, 14 May 2024 18:52:19 -0400 Subject: [PATCH 212/392] [html/fa-ir] Persian translation added for HTML (#4167) --- fa-ir/html-fa.html.markdown | 147 ++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 fa-ir/html-fa.html.markdown diff --git a/fa-ir/html-fa.html.markdown b/fa-ir/html-fa.html.markdown new file mode 100644 index 00000000..cac945f0 --- /dev/null +++ b/fa-ir/html-fa.html.markdown @@ -0,0 +1,147 @@ +--- +language: html +filename: learnhtml-fa.txt +contributors: + - ["Christophe THOMAS", "https://github.com/WinChris"] +translators: + - ["Hiva Zarei", "https://github.com/hivazarei"] +--- +

    HTML مخفف كلمه ی Hyper Text Markup Language می باشد.

    + +

    یك زبان نشانه گیری است كه با استفاده از كد نویسی می توانیم متن و داده های مختلف را با استفاده از آن نمایش دهیم.

    + +

    Markup چیست؟ روشی است یرای مرتب كردن داده های صفحه كه با تگ ها ی باز و بسته احاطه شده است. همانند زبان ها ی برنامه نویسی دیگر نسخه های متفاوتی دارد . در اینجا درباره ی HTML5 توضیح داده شده است.

    + +

    توجه: شما می توانید تگ ها و عناصر مختلفی را تست كنید، هرچه پیش می روید می توانید effect هارو در سایتی مانند codepen مشاهده كنید و روش عملكردشان را بیاموزید تا آشنایی بیشتری با این زبان پیدا كنید. این مقاله پر از syntax HTML و نكات پر كاربرد می باشد.

    + +```html + + + + + + + + + + + + وب سایت من + + +

    !سلام دنیا

    +
    + به این لینک مراجعه فرمایید + +

    این یک پاراگراف است

    +

    این هم یک پاراگراف دیگر است

    +
      +
    • این یک گزینه در لیست غیرترتیبی می‌باشد
    • +
    • این یک گزینه دیگر می‌باشد
    • +
    • و این هم آخرین گزینه در لیست می باشد
    • +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + +

    سلام، دنيا!

    + + + + + + به این لینک مراجعه فرمایید + + + +

    اين يك پاراگراف است

    +

    اين يك پاراگراف ديگر است

    + + + + + +
      +
    • ین یک گزینه در لیست غیرترتیبی می‌باشد
    • +
    • اين يك آيتم ديگر است
    • +
    • اين آخرين آيتم داخل ليست هست
    • +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    اولين هدردومين هدر
    اولين رديف، اولين ستوناولين رديف دومين ستون
    دومين رديف اولين ستوندومين رديف دومين ستون
    +``` + +

    استفاده

    +

    +فایل های HTML با پسوند .html یا .htm نمایش داده می شوند و با مایم تایپ text/html شناخته می شوند. +

    + +

    HTML زبان برنامه‌نویسی محسوب نمی‌شود.

    +

    برای یادگیری بیشتر

    + +* [Wikipedia](https://en.wikipedia.org/wiki/HTML) +* [HTML tutorial](https://developer.mozilla.org/en-US/docs/Web/HTML) From 901d3924220b0ec9a02a5ce1041d3f99ce0c1daa Mon Sep 17 00:00:00 2001 From: Raghu R Date: Wed, 15 May 2024 06:56:14 +0800 Subject: [PATCH 213/392] [bqn/en] Add BQN tutorial (#4523) --- bqn.html.markdown | 289 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 bqn.html.markdown diff --git a/bqn.html.markdown b/bqn.html.markdown new file mode 100644 index 00000000..58c2f787 --- /dev/null +++ b/bqn.html.markdown @@ -0,0 +1,289 @@ +--- +language: bqn +filename: learnbqn.bqn +contributors: + - ["Raghu Ranganathan", "https://github.com/razetime"] +translators: +--- + +BQN is a modern array language (similar to APL) that aims to eliminate burdensome aspects of the APL tradition. + +It is recommended to try these code examples out in a REPL. The [online REPL](https://mlochbaum.github.io/BQN/try.html) is +recommended for quick start, since it comes with keyboard and easy to access help. You can try building +[CBQN](https://github.com/dzaima/CBQN) for a local install, but it will need keyboard setup. + +```bqn +# This is a comment. +# The characters ',' and `⋄` are statement separators. + +################## +# Main datatypes # +################## + +# Numbers +1,2,3,4 +¯1,¯2,¯3 # Negative numbers are written with a high minus +π,∞,¯π,¯∞ # Pi and Infinity are defined constants +1_234_456 # You can add underscores in between numbers + # This does not change their value +1.3E4 # Scientific notation is supported + +# Characters +'a','⥊' +' +' # Yes, you can put *any* character in a character literal +@ # Null character ('\0' in C) +# Arrays +1‿2‿3 # Stranding, good for simple lists +⟨1,2,3⟩ # General list notation +⟨1‿2,2‿3⟩ # Both can be mixed +[1‿2,2‿3] # Array notation + # An array is multidimensional, as opposed to containing sublists. + # It must be rectangular in shape (a grid structure rather than a tree structure) +[1‿2‿3,4‿5] # This is hence invalid + # May be familiar coming from Numpy, MATLAB and similar languages. +"asdf" # Character array (String) +"newline +separated" # Allows newlines +"quo""tes" # Escape a double quote by typing it twice +# Functions +1{𝕨+𝕩}3 # All functions are infix + # 𝕨 is left argument, 𝕩 is right argument +{-𝕩}5 # 𝕨 can be omitted +1+3 # Same as the above +{𝕊𝕩} # 𝕊 is a recursive call + # (this function will loop forever) +{𝕨 𝕊 𝕩: 𝕨+𝕩} # Functions can have headers (too many cases to discuss here) + # Headers can define arity +{𝕊 a‿b: a}1‿2 # and also do basic pattern matching + # (returns 1) + +# Modifiers (higher order functions) +{𝕗,𝔽,𝕘,𝔾} # 𝔽 and 𝔾 are the operands as callable functions + # 𝕗 and 𝕘 are the operands as values +{𝔽𝕩} # 1-modifiers use 𝔽/𝕗 ONLY +˜,˘,¨,⁼,⌜ # primitive 1-modifiers are superscripts +{𝕨𝔽𝔾𝕩} # 2-modifiers MUST use both 𝔽/𝕗 and 𝔾/𝕘 in body or header +⊸,∘,○,⟜ # primitive 2-modifiers all have circles ++{⟨𝕗⟩} # returns ⟨ + ⟩ +1-{𝔽 𝕨 𝔾 𝕩 }×2 # returns ¯2 (operators are *also* infix) + # (same as 1 -○× 2) + +# Trains (Special form of function composition) +(+´÷≠) # Average (but how?) +# The above train is an F G H train, where +# (F G H) 𝕩 → (F 𝕩) G (H 𝕩) +# F ← +´, G ← ÷, H ← ≠ +# In explicit form, this is +{(+´𝕩)÷≠𝕩} +# The second pattern is (f g) 𝕩 → f g 𝕩. +# longer trains are complex arrangements of these patterns, involving constants and Nothing (·). +# Read more about trains at https://mlochbaum.github.io/BQN/doc/train.html + +# Evaluation order: +# BQN evaluates functions right to left with no precedence rules governing *functions*. Functions are what +# one would call operators in a mainstream language. +1÷2+3 # 1÷(2+3) = 0.2 +(1÷2)+3 # ((1÷2)+3) = 1.5 + +# Modifiers: +# Modifiers are higher order functions, and bind tighter than functions. Modifiers execute left to right. +# Modifiers can take non-function arguments e.g. Constant (`˙`) ++ +1+˜2+○-∘×3 # 1(+˜)(2((+○-)∘×)3) + +# Variables +# Since the case of a variable matters to determine what it means, BQN variables are *case insensitive* +# The case that a variable is written in can change the way it is interpreted by BQN. +# Eg. `F` refers to a value as a callable function, whereas `f` refers to the same variable as just a value. +# Variable assignment is done with `←`. Variables have naming conventions based on their value: +subject ← 1‿2‿3 # Arrays, single values, namespaces come under this + # name must start with with a lowercase letter +Function ← {𝕨+𝕩} # Primitive and user defined functions come under this, both monadic and dyadic + # Starts with an uppercase letter +_1modifier ← {𝕨𝔽𝕩} # Starts with an underscore +_2modifier_ ← {𝔽𝕨𝔾𝕩} # Starts and ends with an underscore +# Variable modification is done with `↩`. An existing name cannot be reassigned with `←`. +Func ↩ {"Hello"∾𝕩} +array_or_atom +↩ 2 # You can use a dyadic function for modification + #≡ 3‿4‿5 +array_or_atom -↩ # Or a monadic function. + #≡ ¯3‿¯4‿¯5 +# Due to all functions being infix, you can use your own functions for modification as well: +array_or_atom {2⋆𝕩}↩ #≡ ⟨ 0.125, 0.0625, 0.03125 ⟩ + +################## +# BQN Primitives # +################## +# All of BQN's base primitives are a single character long. Refer to https://mlochbaum.github.io/BQN/help/index.html for +# examples. +# Here we will look at a few primitives from each section. You will want to consult the docs for detailed explanations. + +# Primitive Functions +# All BQN functions are variadic, and can take one or two arguments. The base functions have both monadic and dyadic overloads. +# Usually the two overloads for a function are related. + +## Arithmetic Functions ++, -, ×, ÷ # Add, Subtract, Signum/Multiply, Reciprocal/Divide , '*' does NOT do multiplication + # ⌊∘÷ does floor division +√, ⋆ # Square root/Nth root, e^x/Power +# All Arithmetic functions vectorize: +1 + 2‿3‿4 #≡ 3‿4‿5 +1‿2‿3 + 2‿3‿4 #≡ 3‿5‿7 +# Character arithmetic(+ and - only): +"abc"+3 #≡ "def" +'a'-'d' #≡ ¯3 + +## Logic Functions +∧, ∨, ¬ # For Booleans, retrun 1 or 0 +≤, <, >, ≥, = # Vectorizing comparisons +≡, ≢ # Nonvectorizing comparisons + +## Array manipulation Functions +↕ # Make a range +∾, ≍, ⋈ # Joining arrays together +a←1‿2‿3,b←4‿5 # Let us take a and b. +a∾b #≡ 1‿2‿3‿4‿5 +a≍b # Same as previous, since a and b are not multidimensional + # Adds an extra dimension, similar to a ⋈ for multidimensional arrays. +a⋈b #≡ ⟨1‿2‿3, 4‿5⟩ +⊑, ⊏ # Indexing +1⊑1‿2‿3 #≡ 2 (BQN is 0-indexed) +1‿2⊏1‿2‿3 #≡ 2‿3 (for multiple indices) +↑, ↓ # Getting a prefix, suffix of an array. + # together they can be used for slicing +⥊ # Reshape/repeat items to create a new array + +# Primitive 1-Modifiers +## Looping combinators +¨, ˘, ⌜ # Mapping/Zipping +´, ˝ # Fold from right +` # Scan from left + +## General combinators +˜ # duplicate argument/swap args - Very useful! +˙ # Create constant function +1 -˜ 2 #≡ 2 - 1 ++˜ 2 #≡ 2 + 2 + +# Primitive 2-modifiers +## Control Flow +◶ # Choose from a list of funcs +⍟ # Repeat n times + +## General Combinators +⊸, ⟜ # hook, hookf +∘, ○ # simple function composition + +########## +# Blocks # +########## +# Code delimited by {} +# Lexically scoped +# For more info: https://mlochbaum.github.io/BQN/doc/block.html +# Can have headers, which are ways to explicitly define what a block should be. +# A block without headers is automatically inferred from its special variables (𝕨, 𝕩, ...). + +# Function blocks +# Implicit variables(Capitals are functions): +# - 𝕨, 𝕎 left argument +# - 𝕩, 𝕏 right argument +# - 𝕤, 𝕊 represent the block itself +# Optional: one or more headers that trigger based on +# - pattern match (':') o +# - condition ('?') (similar to if-then-else) + +{ # A factorial using headers: + 𝕊 0: 1; + 𝕊 𝕩: 𝕩×𝕊 𝕩-1 +} +{ # Factorial with predicates + 𝕩<2 ? 1; # Similar to an if-else pattern. + 𝕩×𝕊 𝕩-1 +} + +# Modifier blocks +# create 1-modifiers and 2-modifiers, which have separate types +# Implicit variables(Capitals are functions): +# - has 𝕨 and 𝕩 if needed +# - 𝕗, 𝔽 left operand +# - 𝕘, 𝔾 right operand (only in 2-modifiers) +# - 𝕣 represents the block itself* (requires underscores as per convention) +# Same header rules as functions. +{ 𝕨=0 ? 𝔽 𝕩; 𝔾 𝕩 } # execute 𝔽 or 𝔾 based on whether left argument is 0. + +# Namespace blocks +# Create immutable namespaces with fields +# Require exports (`⇐`) for accessible fields. +# Use '.' for field access +n←{ + A←+ + b⇐4 +} +n.b #≡ 4 +n.a # ERROR + +# Immediate Blocks +# No arguments taken +# Run the code inside and return the last statement +# Often responsible for strange errors. +# Can be mistaken for other blocks easily +# Good for avoiding scoping issues +{ + 1‿2‿3 +} +{+} # Trick for returning a function as a value +#################### +# Basic constructs # +#################### +# Functional programming +# `¨` is used for mapping, as discussed before: +{𝕩∾2}¨1‿2‿3 #≡ ⟨1‿2,2‿2,3‿2⟩ +# ⋈¨ is a plain zip, which produces pairs. +# `¨` acts as a zipWith when used with two arguments: +1‿2‿3 {⟨𝕩+2,2⥊𝕨⟩} 4‿5‿6 #≡ ⟨⟨6,1‿1⟩,⟨7,2‿2⟩,⟨8,3‿3⟩⟩ +# `/` is replicate, which serves several purposes *including* filtering. +# elements in 𝕩 are repeated by the corresponding number in 𝕨. +1‿2‿3‿0/4‿5‿6‿7 #≡ 4‿5‿5‿6‿6‿6 +# a simple filter idiom is F⊸/: +{2|𝕩}⊸/67‿42‿83 # keep the odd elements + #≡ 67‿83 + +# Conditionals +# There are two main ways to define a conditional. +## Predicate headers +{ + 𝕩 > 2: "greater than 2"; + 𝕩 < 2: "lesser than 2"; + "equal to 2" +} + +## Choose (function-based) +# - 2-modifier +# - 𝔾: list of functions that serve as bodies +# - 𝔽: condition function that specifies which function from 𝔾 to select +# The same conditional as above would be: +{⊑/⟨𝕩>2, 𝕩<2, 𝕩=2⟩}◶⟨ + {𝕊: "greater than 2"} + {𝕊: "lesser than 2"} + {𝕊: "equal to 2"} +⟩ + +## Some helpers for conditionals +If ← {𝕏⍟𝕎@}´ # Used as If ⟨Condition, Block⟩ +IfElse ← {c‿T‿F: c◶F‿T@} # Used as IfElse ⟨Condition, Block, ElseBlock⟩ + +# Looping +# The primary form of unbounded looping is recursion (performed with 𝕊). +# BQN does not eliminate tail calls, but the while idiom can be used to work around this: +While ← {𝕩{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩}𝕨@}´ # While 1‿{... to run forever +DoWhile ← {𝕏@ ⋄ While 𝕨‿𝕩}´ +# A For loop can be done with ¨, functions need not be pure. +``` + +## Ready for more? + +- [Quickstart guide](https://mlochbaum.github.io/BQN/doc/quick.html) +- [Full length, explained documentation](https://mlochbaum.github.io/BQN/doc/index.html) +- [Short docs](https://mlochbaum.github.io/BQN/help/index.html) +- [BQN community!](https://mlochbaum.github.io/BQN/community/index.html) From 8cc5c997c6aa19b89894d9ec0e93903dbf7a2801 Mon Sep 17 00:00:00 2001 From: JoeStrout Date: Tue, 14 May 2024 16:08:26 -0700 Subject: [PATCH 214/392] [miniscript/en] Add MiniScript (#4343) --- miniscript.html.markdown | 422 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 422 insertions(+) create mode 100644 miniscript.html.markdown diff --git a/miniscript.html.markdown b/miniscript.html.markdown new file mode 100644 index 00000000..8a2a4f87 --- /dev/null +++ b/miniscript.html.markdown @@ -0,0 +1,422 @@ +--- +language: MiniScript +contributors: + - ["Joe Strout", "https://github.com/JoeStrout"] +filename: miniscript.ms +--- + +**MiniScript** is a simple scripting language designed to be easily embedded in games and other software. It can also be used on the command line, or as a cross-platform game development environment via [Soda](https://github.com/JoeStrout/soda) or [Mini Micro](https://miniscript.org/MiniMicro). + +An easy way to get started with MiniScript is on the [Try-It! page](https://miniscript.org/tryit/), which runs MiniScript code on the server. Note however that the code on this page is limited to 2000 characters. (The tutorial scripts below are broken up into blocks 2048 characters or less so they will run on the Try-It! page.) + +Once you are ready to go beyond the Try-It! page, your next stop should probably be to download [Mini Micro](https://miniscript.org/MiniMicro), a free virtual computer that uses MiniScript both on the command line and in programs. In that environment, enter **edit** at the prompt to edit code, then click the Run button in the editor to run it. + +``` +print "Hello world" + +// MiniScript is very syntax-light. Notice that no parentheses are +// needed on the print statement above. Comments begin with //, and +// extend to the end of the line. MiniScript is case-sensitive. + +// CONTROL FLOW +// Use if blocks to do different things depending on some condition. +// Include zero or more else if blocks, and one optional else block. +if 2+2 == 4 then + print "math works!" +else if pi > 3 then + print "pi is tasty" +else if "a" < "b" then + print "I can sort" +else + print "last chance" +end if + +// LOOPING +// MiniScript has only two loop constructs: while loops and for loops. +// Use a while block to loop as long as a condition is true. +s = "Spam" +while s.len < 50 + s = s + ", spam" +end while +print s + " and spam!" + +// A for loop can loop over any list, including ones easily created +// with the range function. +for i in range(10, 1) + print i + "..." +end for +print "Liftoff!" + +// Two additional keywords are useful inside loops. The break statement +// jumps out of the nearest while or for loop. The continue statement +// jumps to the top of the loop, skipping the rest of the current iteration. +for i in range(1,100) + if i % 3 == 0 then continue // skip multiples of 3 + if i^2 > 200 then break // stop when i^2 is over 200 + print i + " squared is " + i^2 +end for +``` + +### Numbers + +``` +// All numbers are stored in full-precision format. Numbers also +// represent true (1) and false (0), and there are built-in keywords +// (true and false) for those. +a = 7 +b = 3 +ultimateAnswer = 42 +pi = 3.14159 +n = true +m = false +print ultimateAnswer + ", " + pi + ", " + n + ", " + m + +// Numbers support the following operators: +print "Basic math:" +print a + b // addition +print a - b // subtraction +print a * b // multiplication +print a / b // division +print a % b // modulo (remainder) +print a ^ b // power + +print "Logic:" +print n and m // logical "and" +print n or m // logical "or" +print not n // logical negation + +print "Comparisons:" +print a == b // equality test (note == rather than = here!) +print a != b // inequality +print a > b // greater than +print a >= b // greater than or equal +print a < b // less than +print a <= b // less than or equal +``` + +### Strings + +``` +// Text is stored in strings of Unicode characters. Write strings +// by surrounding them with quotes. If you need to include a +// quotation mark in a string, type it twice. +print "Hello, ""Bob""." +a = "Hello" +b = "Spam" + +// Strings support the following operators: +print "String ""math"":" +print a + b // string concatenation +print b - "m" // string subtraction (chop) +print b * 4 // string replication +print a / 2 // string division + +print "Comparisons:" +print a == b // equality test (note == rather than = here!) +print a != b // inequality +print a > b // greater than +print a >= b // greater than or equal +print a < b // less than +print a <= b // less than or equal + +// Indexing and slicing in a string is done with an index (or two) +// in square brackets. Use a 0-based index to count from the front, +// or a negative index to count from the end. Get a slice (substring) +// with two indices, separated by a colon. Either one may be omitted +// to extend the slice to the beginning or end of the string. +print "Indexing and slicing:" +print a[0] // get a character, starting with 0 ("H") +print a[1] // get second character ("e") +print a[-1] // negative numbers count from the end ("o") +print a[1:4] // get slice from 1 up to (but not including) 4 ("ell") +print a[1:-1] // same as above, but using a negative index +print a[1:] // get slice from 1 to the end ("ello") +print a[:2] // get slice from beginning up to 2 ("He") + +// Note that strings in MiniScript are immutable. You can't reache +// into a string and change what characters it contains (but you can +// always create a new string with different characters). +``` + +### Lists + +``` +// A list is an ordered sequence of values of any type. You can +// iterate over a list with a for loop, or iterate over the indexes +// using .indexes. +x = ["alpha", "beta", "gamma", "delta"] +for item in x + print item +end for +for i in x.indexes + print "x[" + i + "] is " + x[i] +end for + +// Indexing and slicing in a list is exactly like a string: use a +// 0-based index to count from the front, or a negative number to +// count from the end. Get a slice (subset) of a list with two +// indices, separated by a colon. Either one may be omitted +// to extend the slice to the beginning or end of the list. +print x[0] // alpha +print x[-1] // delta +print x[1:3] // [beta, gamma] +print x[2:] // [gamma, delta] +print x[:-1] // [alpha, beta, gamma] + +// Lists support the following operators: +y = ["a", "be", "ce", "de"] +print "List ""math"":" +print x + y // list concatenation +print y * 3 // list replication +print x / 2 // list division + +print "Comparisons:" +print x == y // equality test (note == rather than = here!) +print x != y // inequality +``` + +### Maps + +``` +// A map is a set of values associated with unique keys. Maps +// are an extremely powerful and versatile data type, used to +// represent data records, objects, sparse arrays, and much more. +// Create a map with curly braces; get or set a single value +// with square brackets. Keys and values may be any type. +// ("Key" and "index" mean the same thing in the context of a map.) +m = {1:"one", 2:"two"} +print m[1] // one +m[2] = "dos" // change the value associated with index 2 +print m[2] // dos + +// In the special case where the key (index) is a string that +// would be a valid variable name, there is an alternate to the +// square-bracket syntax called dot syntax. Just put the key, +// without quotes, after the map and a dot (period). +m.pi = 3.14 // equivalent to: m["pi"] = 3.14 +print m["pi"] // 3.14 +m["e"] = 2.72 // equivalent to: m.e = 2.72 +print m.e // 2.72 + +// Maps support only the + operator, which combines all the key/value +// pairs from two maps into one. +m1 = {1:"one", 2:"two"} +m2 = {2:"dos", 3:"tres"} +print m1 + m2 // map concatenation + +// You can iterate over the key/value pairs in a map with a for loop. +// On each iteration, the variable will be itself a little map with +// "key" and "value" indexes. +for kv in m1+m2 + print kv.key + " -> " + kv.value +end for + +// Note that the order of key/value pairs in a map is undefined. +// You should never rely on them appearing in a particular order +// when you print or iterate over a map. +``` + +### Functions + +``` +// Create a function in miniscript with a function...end function +// block. In most cases you will assign the result to a variable +// so you can call it later. If a function needs to return a +// a result, do that with the return keyword. +rollDie = function + return ceil(rnd * 6) // return a random number from 1-6 +end function +print rollDie +print rollDie + +// If it needs parameters, put them after function keyword inside +// parentheses. Parameters may have default values. +roll = function(numberOfDice, sides=6) + sum = 0 + for i in range(1, numberOfDice) + sum = sum + ceil(rnd * sides) + end for + return sum +end function +print roll(2) // roll two 6-sided dice +print roll(2,20) // roll two 20-sided dice + +// Variables are always local by default in MiniScript. The +// variables i and sum in the function above are not accessible +// outside the function, and disappear as soon as the function +// returns. (We'll talk more about variable scope later.) + +// Parentheses are needed only if (1) you're passing arguments +// (parameter values) to the function, and (2) you're using the +// result as part of some larger statement. Notice how the first +// example above, rollDie did not need any parentheses because we +// weren't passing an arguments. Here's an example of a function +// that, like the built-in print function, is used as a statement +// by itself, and so does not need parentheses. +doRoll = function(numberOfDice, sides=6) + print "Rolling " + numberOfDice + "d" + sides + "..." + sum = 0 + for i in range(1, numberOfDice) + roll = ceil(rnd * sides) + print "You rolled a " + roll + "." + sum = sum + roll + end for + print "Your total is: " + sum +end function +doRoll 3 // roll 3d6 -- note no parentheses needed +doRoll 3, 8 // same here, but rolling 3d6 + +// If you ever need to refer to a function without invoking it, +// you can do so with the @ operator. +f = @doRoll // makes f refer to the same function as doRoll +f 2,4 // rolls 2d4 +``` + +### Classes and Objects + +``` +// MiniScript uses prototype-based inheritance. A class or object +// is just a map with a special __isa entry that points to the +// parent class. This is set automatically when you use the new +// operator. +Shape = {} // make a base class +Shape.sides = 0 // give it 0 sides by default + +Square = new Shape // make a subclass of Shape called Square +Square.sides = 4 // override the number of sides + +x = new Square // create an instance of the Square class +print x.sides // 4, because x is a Square and Square.sides is 4 + +// A method is just a function stored in a class (map). These +// are inherited through the __isa chain, just like other values. +// Within a method, the keyword self refers to the object on which +// the method was invoked (using dot syntax). This is how you +// refer to data or methods on the object. +Shape.describe = function + print + print "This is a " + self.sides + "-sided shape." +end function +x.describe // This is a 4-sided shape. + +// Methods may be overridden (again just like values). In a +// subclass/instance method, you may use super to invoke the next +// version of the method up the inheritance chain, while still +// keeping self bound to the object this method was called on. +Square.describe = function + super.describe // first, do the standard description + print "It looks very squarish." // then add this +end function +x.describe +``` + +### More on Variable Scope + +``` +// Variables assignments in MiniScript always create or update +// a local variable, i.e., one that exists only within the function +// containing the assignment, unless dot syntax is used to specify +// some other scope. +x = 42 // here's a global variable called x +f = function + x = 1234 // make a local variable, also called x + print "Inside the function, x is now " + x +end function +f +print "Outside the function, x is " + x + +// In the example above, the assignment to x inside the function +// has no effect on the global value of x, even though they happen +// to have the same name. (This is a Good Thing because it helps +// you avoid unintended side-effects in your code.) Global variables +// are generally discouraged, but if you must update one inside +// a function, you can use a "globals." prefix to do so. +f = function + print "Using the globals prefix..." + globals.x = 1234 // update the global variable x + print "Inside the function, x is now " + x +end function +f +print "Outside the function, x is " + x + +// This is very similar to the "self." prefix used with +// class methods; in both cases, you are giving a more specific +// scope to a variable (which is really just specifying a map +// to index into with dot syntax). + +// However there is an important difference: when READING (not +// assigning to) a variable, if the variable name is not found +// among the local variables, MiniScript will automatically look +// for a global variable of that name. Thus no "globals." prefix +// is needed when reading a variable, but only when assigning it. +count = 0 +addToCount = function(amount=1) + globals.count = count + amount +end function +addToCount +addToCount +print "count is now: " + count + +// In the addToCount function above, note how we need the globals +// prefix on the left-hand side of the assignment, since otherwise +// it would create a local variable. But we don't need it on the +// right-hand side, where we are merely reading the global value. +``` + +### Handy Intrinsic Methods + +``` +// Intrinsic methods are ones that are built into MiniScript or its +// environment. Particular MiniScript environments (e.g. Mini Micro, +// Soda, command-line MiniScript, some game using MiniScript as an +// embedded language, etc.) will probably add additional intrinsics. +// But there is a core of about 50 intrinsics that should always be +// available. + +// Here's a quick demo of some of the most commonly used ones. +print abs(-42) // absolute value +print pi // get value of pi (yep, this is built in!) +print cos(pi) // cosine +print sqrt(100) // square root +print round(pi, 2) // round (to 2 decimal places) +print char(65) // get Unicode character 65 + +print +s = "Hello world!" +print s.upper // convert to upper case +print s.len // get length (number of characters) +print s.replace("Hello", "Heya") // string substitution +print s.split(" ") // split on spaces to make a list +print s.remove("l") // remove first occurrence of "l" + +print +a = range(2,15,3) // make a list: 2 through 10, in steps of 3 +print "a: " + a +print "a.len:" + a.len // get length (number of values) +print "a.sum:" + a.sum // get sum of adding all values together +print a.pop // pop off the last value +print a.pull // pull off the first value +print "popped and pulled: " + a +a.push 99 // push a new item onto the end +a.insert 0, 101 // insert a new item at index 0 +print "after push and insert: " + a +a.remove 2 // remove index 2 from the list +print "after remove 2: " + a +s = a.join("#") // make a string by joining values with # +print s + +print +m = {"one": "uno", "two": "dos", "three": "tres"} +print m.hasIndex("one") // check whether a key exists +print m.indexes // get all the indexes +print m.values // get all the values +m.remove "two" // remove an index (and its value) +print m +``` + +## Further Reading + +* [MiniScript.org website](https://miniscript.org/) — center of the MiniScript universe +* [MiniScript Quick Reference](https://miniscript.org/files/MiniScript-QuickRef.pdf) — this tutorial, in one page +* [MiniScript User's Manual](https://miniscript.org/files/MiniScript-Manual.pdf) — more in-depth documentation +* [MiniScript Wiki](https://miniscript.org/wiki/) — community-driven documentation From 8c3acb8fb2957ffec7b976c5c80ed9c711c6505c Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 14 May 2024 17:26:52 -0600 Subject: [PATCH 215/392] [janet/en] [reason/en] use correct highlight lang --- janet.html.markdown | 2 +- reason.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/janet.html.markdown b/janet.html.markdown index 62ed7331..1fc3a991 100644 --- a/janet.html.markdown +++ b/janet.html.markdown @@ -18,7 +18,7 @@ As we only have a scant *y* minutes, we'll survey the basics here and leave the remaining details for the manual. So please, keep your arms and legs inside the vehicle at all times, and on with the scenic tour! -```python +```janet # A comment. # Some literal values. diff --git a/reason.html.markdown b/reason.html.markdown index b8a2215d..065dd33b 100644 --- a/reason.html.markdown +++ b/reason.html.markdown @@ -7,7 +7,7 @@ contributors: Reason is a syntax over OCaml that is easier to get started for programmers who are familiar with C-style syntax like JavaScript. BuckleScript is part of the toolchain which compiles Reason to JavaScript so you can write statically typed code for anywhere that JavaScript runs. -```javascript +```reason /* Comments start with slash-star, and end with star-slash */ /*---------------------------------------------- From 717d099842a4b133c12cfa32636634766f6bc197 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 14 May 2024 17:51:24 -0600 Subject: [PATCH 216/392] Fix newlines --- es-es/make-es.html.markdown | 520 ++++++++++++++++++------------------ hre.csv | 47 +++- 2 files changed, 306 insertions(+), 261 deletions(-) diff --git a/es-es/make-es.html.markdown b/es-es/make-es.html.markdown index 0e07ec13..7ee47814 100644 --- a/es-es/make-es.html.markdown +++ b/es-es/make-es.html.markdown @@ -1,260 +1,260 @@ ---- -category: tool -tool: make -filename: Makefile -contributors: - - ["Robert Steed", "https://github.com/robochat"] - - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] -translators: - - ["Andrés Perdomo", "https://github.com/andres7293"] -lang: es-es ---- - -Un archivo Makefile define un conjunto de reglas para crear un objetivo (o -varios objetivos). Su propósito es hacer la mínima cantidad de trabajo necesaria -para actualizar un objetivo a la versión más reciente de la fuente. Escrito -famosamente en un fin de semana por Stuart Feldman en 1976, todavía se utiliza -ampliamente (especialmente en Unix y Linux) a pesar de muchos competidores y -críticas. - -Existen muchas variedades de Make en existencia, no obstante, este artículo -asume que estamos utilizando GNU Make, que es el estándar en Linux. - -```make -# Los comentarios se pueden escribir de esta forma. - -# El fichero debe tener el nombre de Makefile y luego puede ser ejecutado -# como `make `. -# De lo contrario, se utiliza `make -f "nombre_archivo" ` - -# Advertencia: ¡solo use TABULACIONES para la identación en Makefiles, nunca -# espacios! - -#----------------------------------------------------------------------- -# Fundamentos -#----------------------------------------------------------------------- - -# Las reglas tienen el formato -# objetivo: -# donde prerrequisito es opcional. - -# Una regla - esta regla solamente se ejecutará si file0.txt no existe. -file0.txt: - echo "foo" > file0.txt - # Incluso los comandos en esta sección de 'receta' se pasan a la shell. - # Prueba `make file0.txt` o simplemente 'make' - La primera regla es la - # predeterminada. - -# Esta regla se ejecutará solo si file0.txt es más reciente que file1.txt. -file1.txt: file0.txt - cat file0.txt > file1.txt - # Use las mismas reglas de comillas que en la shell. - @cat file0.txt >> file1.txt - # @ evita que el comando se muestre en stdout. - -@echo 'hello' - # - Quiere decir que make continuará en caso de error. - # Pruebe 'make file1.txt` en la línea de comandos. - -# Una regla puede tener múltiples objetivos y múltiples prerrequisitos -file2.txt file3.txt: file0.txt file1.txt - touch file2.txt - touch file3.txt - -# Make se quejará de múltiples recetas para la misma regla. Sin embargo, -# las reglas vacías no cuentan y se pueden utilizar para agregar nuevas -# dependencias - -#----------------------------------------------------------------------- -# Objetivos ficticios (Phony Targets) -#----------------------------------------------------------------------- - -# Un objetivo ficticio (phony target). Cualquier objetivo que no sea un archivo. -# Nunca estará actualizado, por lo que make siempre tratará de ejecutarlo. -all: make process - -# Podemos declarar cosas sin orden. -maker: - touch ex0.txt ex1.txt - -# Se puede evitar que las reglas ficticias (phony) se rompan cuando un archivo -# real tiene el mismo nombre usando: -.PHONY: all maker process -# Esto es un objetivo especial. Hay varios otros. - -# Una regla con una dependencia en un objetivo ficticio (phony target) -# se ejecutara siempre: -ex0.txt ex1.txt: maker - -# Los objetivos ficticios (phony target) más comunes son: -# all make clean install... - -#----------------------------------------------------------------------- -# Variables automáticas y Wildcards -#----------------------------------------------------------------------- - -process: file*.txt # usa un wildcard para coincidir con los nombres de archivos. - @echo $^ # $^ es una variable que contiene una lista de todos los prerrequisitos - @echo $@ # imprime el nombre del objetivo - #(para reglas con múltiples objetivos, $@ es el que hizo que se ejecutara la regla) - @echo $< # el primer prerrequisito listado - @echo $? # solo las dependencias que están desactualizadas - @echo $+ # todas las dependencias incluyendo las duplicadas (a diferencia de lo normal) - #@echo $| # solo los 'prerrequisitos solicitados' - -# Incluso si dividimos las definiciones de las dependencias, de las reglas, $^ -# las encontrará -process: ex1.txt file0.txt -# ext1.xt se encontrará pero file0.txt se duplicará. - -#----------------------------------------------------------------------- -# Patrones -#----------------------------------------------------------------------- - -# Se puede instruir a make sobre como convertir ciertos tipos de archivos en -# otros archivos. - -%.png: %.svg - inkscape --export-png $^ - -# Las reglas de patrones solo harán algo si make decide crear el objetivo. - -# Los directorios no suelen tenerse en cuenta al coincidir con reglas de -# patrones. -# Pero make intentará usar la regla más apropiada disponible. - -small/%.png: %.svg - inkscape --export-png --export-dpi 30 $^ - -# make usará la última versión de una regla de patrón que encuentre. -%.png: %.svg - @echo esta regla es elegida - -# Sin embargo make usará la primera regla de patrón que pueda construir el -# objetivo. -%.png: %.ps - @echo esta regla no es elegida si *.svg y *.ps están ambas presentes - -# Make ya tiene algunas reglas de patrón integradas. -# Por ejemplo, sabe cómo convertir archivos *.c en archivos *.o. - -# En makefiles antiguos se solían utilizar las reglas de sufijo en lugar de las -# reglas de patrón -.png.ps: - @echo esta regla es similar a una regla de patrón. - -# Instruye a make sobre una regla de sufijo -.SUFFIXES: .png - -#----------------------------------------------------------------------- -# Variables -#----------------------------------------------------------------------- -# también conocidas como macros. - -# Las variables son básicamente de tipo cadena (string) - -name = Ted -name2="Sarah" - -echo: - @echo $(name) - @echo ${name2} - @echo $name # Esto no funcionará, se tratará como $(n)name. - @echo $(name3) # Variables desconocidas se tratarán como cadenas vacías. - -# Hay 4 lugares donde se pueden definir variables. -# En orden de prioridad de mayor a menor: -# 1: argumentos de línea de comando. -# 2: Makefile. -# 3: variables de entorno de la shell - make las importa automáticamente. -# 4: make tiene algunas variables predefinidas. - -name4 ?= Jean -# Solo establece la variable si la variable de entorno no está aún definida. - -override name5 = David -# Detiene que los argumentos de línea de comandos modifiquen esta variable. - -name4 +=grey -# Añade valores a la variable (incluye un espacio). - -# Valores de variables específicos de patrones (Extension de GNU). -echo: name2 = Sara # Verdadero dentro de la regla coincidente - # y también dentro de sus dependencias recursivas rehechas - # (¡excepto que puede romperse cuando el grafo se complica demasiado!) - -# Algunas variables son definidas automáticamente por make. -echo_inbuilt: - echo $(CC) - echo ${CXX} - echo $(FC) - echo ${CFLAGS} - echo $(CPPFLAGS) - echo ${CXXFLAGS} - echo $(LDFLAGS) - echo ${LDLIBS} - -#----------------------------------------------------------------------- -# Variables 2 -#----------------------------------------------------------------------- - -# El primer tipo de variables se evalúan cada vez que se usan. -# Esto puede ser costoso, por lo que existe un segundo tipo de variable que se -# evalúa solo una vez. (Esta es una extensión de GNU make) - -var := hello -var2 ::= $(var) hello -#:= y ::= son equivalentes - -# Estas variables se evalúan de manera procedimental (en el orden en que -# aparecen), ¡rompiendo así con el resto del lenguaje! - -# Esto no funciona -var3 ::= $(var4) and good luck -var4 ::= good night - -#----------------------------------------------------------------------- -# Funciones -#----------------------------------------------------------------------- - -# make tiene muchas funciones disponibles. - -sourcefiles = $(wildcard *.c */*.c) -objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) - -# El formato es $(func arg0,arg1,arg2...) - -# Algunos ejemplos -ls: * src/* - @echo $(filter %.txt, $^) - @echo $(notdir $^) - @echo $(join $(dir $^),$(notdir $^)) - -#----------------------------------------------------------------------- -# Directrices (Directives) -#----------------------------------------------------------------------- - -# Incluye otros makefiles, útil para código de plataformas específicas -include foo.mk - -sport = tennis -# Compilación condicional -report: -ifeq ($(sport),tennis) - @echo 'game, set, match' -else - @echo "They think it's all over; it is now" -endif - -# También existe ifneq, ifdef, ifndef - -foo = true - -ifdef $(foo) -bar = 'hello' -endif -``` - -### Más recursos (en inglés) - -+ [GNU Make documentation](https://www.gnu.org/software/make/manual/) -+ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/) +--- +category: tool +tool: make +filename: Makefile +contributors: + - ["Robert Steed", "https://github.com/robochat"] + - ["Stephan Fuhrmann", "https://github.com/sfuhrm"] +translators: + - ["Andrés Perdomo", "https://github.com/andres7293"] +lang: es-es +--- + +Un archivo Makefile define un conjunto de reglas para crear un objetivo (o +varios objetivos). Su propósito es hacer la mínima cantidad de trabajo necesaria +para actualizar un objetivo a la versión más reciente de la fuente. Escrito +famosamente en un fin de semana por Stuart Feldman en 1976, todavía se utiliza +ampliamente (especialmente en Unix y Linux) a pesar de muchos competidores y +críticas. + +Existen muchas variedades de Make en existencia, no obstante, este artículo +asume que estamos utilizando GNU Make, que es el estándar en Linux. + +```make +# Los comentarios se pueden escribir de esta forma. + +# El fichero debe tener el nombre de Makefile y luego puede ser ejecutado +# como `make `. +# De lo contrario, se utiliza `make -f "nombre_archivo" ` + +# Advertencia: ¡solo use TABULACIONES para la identación en Makefiles, nunca +# espacios! + +#----------------------------------------------------------------------- +# Fundamentos +#----------------------------------------------------------------------- + +# Las reglas tienen el formato +# objetivo: +# donde prerrequisito es opcional. + +# Una regla - esta regla solamente se ejecutará si file0.txt no existe. +file0.txt: + echo "foo" > file0.txt + # Incluso los comandos en esta sección de 'receta' se pasan a la shell. + # Prueba `make file0.txt` o simplemente 'make' - La primera regla es la + # predeterminada. + +# Esta regla se ejecutará solo si file0.txt es más reciente que file1.txt. +file1.txt: file0.txt + cat file0.txt > file1.txt + # Use las mismas reglas de comillas que en la shell. + @cat file0.txt >> file1.txt + # @ evita que el comando se muestre en stdout. + -@echo 'hello' + # - Quiere decir que make continuará en caso de error. + # Pruebe 'make file1.txt` en la línea de comandos. + +# Una regla puede tener múltiples objetivos y múltiples prerrequisitos +file2.txt file3.txt: file0.txt file1.txt + touch file2.txt + touch file3.txt + +# Make se quejará de múltiples recetas para la misma regla. Sin embargo, +# las reglas vacías no cuentan y se pueden utilizar para agregar nuevas +# dependencias + +#----------------------------------------------------------------------- +# Objetivos ficticios (Phony Targets) +#----------------------------------------------------------------------- + +# Un objetivo ficticio (phony target). Cualquier objetivo que no sea un archivo. +# Nunca estará actualizado, por lo que make siempre tratará de ejecutarlo. +all: make process + +# Podemos declarar cosas sin orden. +maker: + touch ex0.txt ex1.txt + +# Se puede evitar que las reglas ficticias (phony) se rompan cuando un archivo +# real tiene el mismo nombre usando: +.PHONY: all maker process +# Esto es un objetivo especial. Hay varios otros. + +# Una regla con una dependencia en un objetivo ficticio (phony target) +# se ejecutara siempre: +ex0.txt ex1.txt: maker + +# Los objetivos ficticios (phony target) más comunes son: +# all make clean install... + +#----------------------------------------------------------------------- +# Variables automáticas y Wildcards +#----------------------------------------------------------------------- + +process: file*.txt # usa un wildcard para coincidir con los nombres de archivos. + @echo $^ # $^ es una variable que contiene una lista de todos los prerrequisitos + @echo $@ # imprime el nombre del objetivo + #(para reglas con múltiples objetivos, $@ es el que hizo que se ejecutara la regla) + @echo $< # el primer prerrequisito listado + @echo $? # solo las dependencias que están desactualizadas + @echo $+ # todas las dependencias incluyendo las duplicadas (a diferencia de lo normal) + #@echo $| # solo los 'prerrequisitos solicitados' + +# Incluso si dividimos las definiciones de las dependencias, de las reglas, $^ +# las encontrará +process: ex1.txt file0.txt +# ext1.xt se encontrará pero file0.txt se duplicará. + +#----------------------------------------------------------------------- +# Patrones +#----------------------------------------------------------------------- + +# Se puede instruir a make sobre como convertir ciertos tipos de archivos en +# otros archivos. + +%.png: %.svg + inkscape --export-png $^ + +# Las reglas de patrones solo harán algo si make decide crear el objetivo. + +# Los directorios no suelen tenerse en cuenta al coincidir con reglas de +# patrones. +# Pero make intentará usar la regla más apropiada disponible. + +small/%.png: %.svg + inkscape --export-png --export-dpi 30 $^ + +# make usará la última versión de una regla de patrón que encuentre. +%.png: %.svg + @echo esta regla es elegida + +# Sin embargo make usará la primera regla de patrón que pueda construir el +# objetivo. +%.png: %.ps + @echo esta regla no es elegida si *.svg y *.ps están ambas presentes + +# Make ya tiene algunas reglas de patrón integradas. +# Por ejemplo, sabe cómo convertir archivos *.c en archivos *.o. + +# En makefiles antiguos se solían utilizar las reglas de sufijo en lugar de las +# reglas de patrón +.png.ps: + @echo esta regla es similar a una regla de patrón. + +# Instruye a make sobre una regla de sufijo +.SUFFIXES: .png + +#----------------------------------------------------------------------- +# Variables +#----------------------------------------------------------------------- +# también conocidas como macros. + +# Las variables son básicamente de tipo cadena (string) + +name = Ted +name2="Sarah" + +echo: + @echo $(name) + @echo ${name2} + @echo $name # Esto no funcionará, se tratará como $(n)name. + @echo $(name3) # Variables desconocidas se tratarán como cadenas vacías. + +# Hay 4 lugares donde se pueden definir variables. +# En orden de prioridad de mayor a menor: +# 1: argumentos de línea de comando. +# 2: Makefile. +# 3: variables de entorno de la shell - make las importa automáticamente. +# 4: make tiene algunas variables predefinidas. + +name4 ?= Jean +# Solo establece la variable si la variable de entorno no está aún definida. + +override name5 = David +# Detiene que los argumentos de línea de comandos modifiquen esta variable. + +name4 +=grey +# Añade valores a la variable (incluye un espacio). + +# Valores de variables específicos de patrones (Extension de GNU). +echo: name2 = Sara # Verdadero dentro de la regla coincidente + # y también dentro de sus dependencias recursivas rehechas + # (¡excepto que puede romperse cuando el grafo se complica demasiado!) + +# Algunas variables son definidas automáticamente por make. +echo_inbuilt: + echo $(CC) + echo ${CXX} + echo $(FC) + echo ${CFLAGS} + echo $(CPPFLAGS) + echo ${CXXFLAGS} + echo $(LDFLAGS) + echo ${LDLIBS} + +#----------------------------------------------------------------------- +# Variables 2 +#----------------------------------------------------------------------- + +# El primer tipo de variables se evalúan cada vez que se usan. +# Esto puede ser costoso, por lo que existe un segundo tipo de variable que se +# evalúa solo una vez. (Esta es una extensión de GNU make) + +var := hello +var2 ::= $(var) hello +#:= y ::= son equivalentes + +# Estas variables se evalúan de manera procedimental (en el orden en que +# aparecen), ¡rompiendo así con el resto del lenguaje! + +# Esto no funciona +var3 ::= $(var4) and good luck +var4 ::= good night + +#----------------------------------------------------------------------- +# Funciones +#----------------------------------------------------------------------- + +# make tiene muchas funciones disponibles. + +sourcefiles = $(wildcard *.c */*.c) +objectfiles = $(patsubst %.c,%.o,$(sourcefiles)) + +# El formato es $(func arg0,arg1,arg2...) + +# Algunos ejemplos +ls: * src/* + @echo $(filter %.txt, $^) + @echo $(notdir $^) + @echo $(join $(dir $^),$(notdir $^)) + +#----------------------------------------------------------------------- +# Directrices (Directives) +#----------------------------------------------------------------------- + +# Incluye otros makefiles, útil para código de plataformas específicas +include foo.mk + +sport = tennis +# Compilación condicional +report: +ifeq ($(sport),tennis) + @echo 'game, set, match' +else + @echo "They think it's all over; it is now" +endif + +# También existe ifneq, ifdef, ifndef + +foo = true + +ifdef $(foo) +bar = 'hello' +endif +``` + +### Más recursos (en inglés) + ++ [GNU Make documentation](https://www.gnu.org/software/make/manual/) ++ [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/) diff --git a/hre.csv b/hre.csv index eab43cc4..cec7c4a8 100644 --- a/hre.csv +++ b/hre.csv @@ -1 +1,46 @@ -Ix,Dynasty,Name,Birth,Death,Coronation 1,Coronation 2,Ceased to be Emperor N/A,Carolingian,Charles I,2 April 742,28 January 814,25 December 800,N/A,28 January 814 N/A,Carolingian,Louis I,778,20 June 840,11 September 813,5 October 816,20 June 840 N/A,Carolingian,Lothair I,795,29 September 855,5 April 823,N/A,29 September 855 N/A,Carolingian,Louis II,825,12 August 875,15 June 844,18 May 872,12 August 875 N/A,Carolingian,Charles II,13 June 823,6 October 877,29 December 875,N/A,6 October 877 N/A,Carolingian,Charles III,13 June 839,13 January 888,12 February 881,N/A,11 November 887 N/A,Widonid,Guy III,835,12 December 894,21 February 891,N/A,12 December 894 N/A,Widonid,Lambert I,880,15 October 898,30 April 892,N/A,15 October 898 N/A,Carolingian,Arnulph,850,8 December 899,22 February 896,N/A,8 December 899 N/A,Bosonid,Louis III,880,5 June 928,22 February 901,N/A,21 July 905 N/A,Unruoching,Berengar I,845,7 April 924,December 915,N/A,7 April 924 1,Ottonian,Otto I,23 November 912,7 May 973,2 February 962,N/A,7 May 973 2,Ottonian,Otto II,955,7 December 983,25 December 967,N/A,7 December 983 3,Ottonian,Otto III,980,23 January 1002,21 May 996,N/A,23 January 1002 4,Ottonian,Henry II,6 May 973,13 July 1024,14 February 1014,N/A,13 July 1024 5,Salian,Conrad II,990,4 June 1039,26 March 1027,N/A,4 June 1039 6,Salian,Henry III,29 October 1017,5 October 1056,25 December 1046,N/A,5 October 1056 7,Salian,Henry IV,11 November 1050,7 August 1106,31 March 1084,N/A,December 1105 8,Salian,Henry V,8 November 1086,23 May 1125,13 April 1111,N/A,23 May 1125 9,Supplinburg,Lothair III,9 June 1075,4 December 1137,4 June 1133,N/A,4 December 1137 10,Staufen,Frederick I,1122,10 June 1190,18 June 1155,N/A,10 June 1190 11,Staufen,Henry VI,November 1165,28 September 1197,14 April 1191,N/A,28 September 1197 12,Welf,Otto IV,1175,19 May 1218,4 October 1209,N/A,1215 13,Staufen,Frederick II,26 December 1194,13 December 1250,22 November 1220,N/A,13 December 1250 14,Luxembourg,Henry VII,1275,24 August 1313,29 June 1312,N/A,24 August 1313 15,Wittelsbach,Louis IV,1 April 1282,11 October 1347,17 January 1328,N/A,11 October 1347 16,Luxembourg,Charles IV,14 May 1316,29 November 1378,5 April 1355,N/A,29 November 1378 17,Luxembourg,Sigismund,14 February 1368,9 December 1437,31 May 1433,N/A,9 December 1437 18,Habsburg,Frederick III,21 September 1415,19 August 1493,19 March 1452,N/A,19 August 1493 19,Habsburg,Maximilian I,22 March 1459,12 January 1519,N/A,N/A,12 January 1519 20,Habsburg,Charles V,24 February 1500,21 September 1558,February 1530,N/A,16 January 1556 21,Habsburg,Ferdinand I,10 March 1503,25 July 1564,N/A,N/A,25 July 1564 22,Habsburg,Maximilian II,31 July 1527,12 October 1576,N/A,N/A,12 October 1576 23,Habsburg,Rudolph II,18 July 1552,20 January 1612,30 June 1575,N/A,20 January 1612 24,Habsburg,Matthias,24 February 1557,20 March 1619,23 January 1612,N/A,20 March 1619 25,Habsburg,Ferdinand II,9 July 1578,15 February 1637,10 March 1619,N/A,15 February 1637 26,Habsburg,Ferdinand III,13 July 1608,2 April 1657,18 November 1637,N/A,2 April 1657 27,Habsburg,Leopold I,9 June 1640,5 May 1705,6 March 1657,N/A,5 May 1705 28,Habsburg,Joseph I,26 July 1678,17 April 1711,1 May 1705,N/A,17 April 1711 29,Habsburg,Charles VI,1 October 1685,20 October 1740,22 December 1711,N/A,20 October 1740 30,Wittelsbach,Charles VII,6 August 1697,20 January 1745,12 February 1742,N/A,20 January 1745 31,Lorraine,Francis I,8 December 1708,18 August 1765,N/A,N/A,18 August 1765 32,Habsburg-Lorraine,Joseph II,13 March 1741,20 February 1790,19 August 1765,N/A,20 February 1790 33,Habsburg-Lorraine,Leopold II,5 May 1747,1 March 1792,N/A,N/A,1 March 1792 34,Habsburg-Lorraine,Francis II,12 February 1768,2 March 1835,4 March 1792,N/A,6 August 1806 \ No newline at end of file +Ix,Dynasty,Name,Birth,Death,Coronation 1,Coronation 2,Ceased to be Emperor +N/A,Carolingian,Charles I,2 April 742,28 January 814,25 December 800,N/A,28 January 814 +N/A,Carolingian,Louis I,778,20 June 840,11 September 813,5 October 816,20 June 840 +N/A,Carolingian,Lothair I,795,29 September 855,5 April 823,N/A,29 September 855 +N/A,Carolingian,Louis II,825,12 August 875,15 June 844,18 May 872,12 August 875 +N/A,Carolingian,Charles II,13 June 823,6 October 877,29 December 875,N/A,6 October 877 +N/A,Carolingian,Charles III,13 June 839,13 January 888,12 February 881,N/A,11 November 887 +N/A,Widonid,Guy III,835,12 December 894,21 February 891,N/A,12 December 894 +N/A,Widonid,Lambert I,880,15 October 898,30 April 892,N/A,15 October 898 +N/A,Carolingian,Arnulph,850,8 December 899,22 February 896,N/A,8 December 899 +N/A,Bosonid,Louis III,880,5 June 928,22 February 901,N/A,21 July 905 +N/A,Unruoching,Berengar I,845,7 April 924,December 915,N/A,7 April 924 +1,Ottonian,Otto I,23 November 912,7 May 973,2 February 962,N/A,7 May 973 +2,Ottonian,Otto II,955,7 December 983,25 December 967,N/A,7 December 983 +3,Ottonian,Otto III,980,23 January 1002,21 May 996,N/A,23 January 1002 +4,Ottonian,Henry II,6 May 973,13 July 1024,14 February 1014,N/A,13 July 1024 +5,Salian,Conrad II,990,4 June 1039,26 March 1027,N/A,4 June 1039 +6,Salian,Henry III,29 October 1017,5 October 1056,25 December 1046,N/A,5 October 1056 +7,Salian,Henry IV,11 November 1050,7 August 1106,31 March 1084,N/A,December 1105 +8,Salian,Henry V,8 November 1086,23 May 1125,13 April 1111,N/A,23 May 1125 +9,Supplinburg,Lothair III,9 June 1075,4 December 1137,4 June 1133,N/A,4 December 1137 +10,Staufen,Frederick I,1122,10 June 1190,18 June 1155,N/A,10 June 1190 +11,Staufen,Henry VI,November 1165,28 September 1197,14 April 1191,N/A,28 September 1197 +12,Welf,Otto IV,1175,19 May 1218,4 October 1209,N/A,1215 +13,Staufen,Frederick II,26 December 1194,13 December 1250,22 November 1220,N/A,13 December 1250 +14,Luxembourg,Henry VII,1275,24 August 1313,29 June 1312,N/A,24 August 1313 +15,Wittelsbach,Louis IV,1 April 1282,11 October 1347,17 January 1328,N/A,11 October 1347 +16,Luxembourg,Charles IV,14 May 1316,29 November 1378,5 April 1355,N/A,29 November 1378 +17,Luxembourg,Sigismund,14 February 1368,9 December 1437,31 May 1433,N/A,9 December 1437 +18,Habsburg,Frederick III,21 September 1415,19 August 1493,19 March 1452,N/A,19 August 1493 +19,Habsburg,Maximilian I,22 March 1459,12 January 1519,N/A,N/A,12 January 1519 +20,Habsburg,Charles V,24 February 1500,21 September 1558,February 1530,N/A,16 January 1556 +21,Habsburg,Ferdinand I,10 March 1503,25 July 1564,N/A,N/A,25 July 1564 +22,Habsburg,Maximilian II,31 July 1527,12 October 1576,N/A,N/A,12 October 1576 +23,Habsburg,Rudolph II,18 July 1552,20 January 1612,30 June 1575,N/A,20 January 1612 +24,Habsburg,Matthias,24 February 1557,20 March 1619,23 January 1612,N/A,20 March 1619 +25,Habsburg,Ferdinand II,9 July 1578,15 February 1637,10 March 1619,N/A,15 February 1637 +26,Habsburg,Ferdinand III,13 July 1608,2 April 1657,18 November 1637,N/A,2 April 1657 +27,Habsburg,Leopold I,9 June 1640,5 May 1705,6 March 1657,N/A,5 May 1705 +28,Habsburg,Joseph I,26 July 1678,17 April 1711,1 May 1705,N/A,17 April 1711 +29,Habsburg,Charles VI,1 October 1685,20 October 1740,22 December 1711,N/A,20 October 1740 +30,Wittelsbach,Charles VII,6 August 1697,20 January 1745,12 February 1742,N/A,20 January 1745 +31,Lorraine,Francis I,8 December 1708,18 August 1765,N/A,N/A,18 August 1765 +32,Habsburg-Lorraine,Joseph II,13 March 1741,20 February 1790,19 August 1765,N/A,20 February 1790 +33,Habsburg-Lorraine,Leopold II,5 May 1747,1 March 1792,N/A,N/A,1 March 1792 +34,Habsburg-Lorraine,Francis II,12 February 1768,2 March 1835,4 March 1792,N/A,6 August 1806 From 23c81e3b65e01a73d677bd10a01b6781700b43f9 Mon Sep 17 00:00:00 2001 From: Pratyaksh Gautam Date: Wed, 15 May 2024 05:27:09 +0530 Subject: [PATCH 217/392] [kotlin/en] Add small section for lambda functions (#4798) --- kotlin.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index 48abce3a..c16b5db1 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -120,6 +120,13 @@ fun helloWorld(val name : String) { println(even(6)) // => true println(even(7)) // => false + /* + You can also use lambda functions, with the '->' operator seperating + the parameters from the function body. + */ + fun fooLambda: (Int) -> Int = {n -> n + 1} + println(fooLambda(1)) // => 2 + // Functions can take functions as arguments and return functions. fun not(f: (Int) -> Boolean): (Int) -> Boolean { return {n -> !f.invoke(n)} From d6244e00c1f812802ec1da2052ee1419d916bccb Mon Sep 17 00:00:00 2001 From: Jishan Shaikh <30091032+jishanshaikh4@users.noreply.github.com> Date: Wed, 15 May 2024 06:41:38 +0530 Subject: [PATCH 218/392] [c++/hi]: Translate C++ to Hindi (#4195) --- hi-in/c++-hd.html.markdown | 1195 ++++++++++++++++++++++++++++++++++++ 1 file changed, 1195 insertions(+) create mode 100644 hi-in/c++-hd.html.markdown diff --git a/hi-in/c++-hd.html.markdown b/hi-in/c++-hd.html.markdown new file mode 100644 index 00000000..36abf2c2 --- /dev/null +++ b/hi-in/c++-hd.html.markdown @@ -0,0 +1,1195 @@ +--- +language: c++ +filename: learncpp-hi.cpp +contributors: + - ["Steven Basart", "https://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] + - ["Geoff Liu", "http://geoffliu.me"] + - ["Connor Waters", "https://github.com/connorwaters"] + - ["Ankush Goyal", "https://github.com/ankushg07"] + - ["Jatin Dhankhar", "https://github.com/jatindhankhar"] +translators: + - ["Jishan Shaikh", "https://github.com/jishanshaikh4"] +--- + +C++ एक सिस्टम प्रोग्रामिंग लैंग्वेज है जो, +[इसके आविष्कारक बजेर्न स्ट्राउस्ट्रप के अनुसार](https://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote), +के लिए डिजाइन किया गया था + +* एक "बेहतर सी" बनें +* डेटा एब्स्ट्रैक्शन का समर्थन करें +* ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग का समर्थन करें +* सामान्य प्रोग्रामिंग का समर्थन करें + +हालांकि इसका सिंटैक्स नई भाषाओं की तुलना में अधिक कठिन या जटिल हो सकता है, इसका व्यापक रूप से उपयोग किया जाता है क्योंकि यह मूल निर्देशों को संकलित करता है जो हो सकते हैं सीधे प्रोसेसर द्वारा चलाया जाता है और हार्डवेयर पर कड़ा नियंत्रण प्रदान करता है (जैसे सी) जेनेरिक, अपवाद और कक्षाओं जैसी उच्च-स्तरीय सुविधाओं की पेशकश करते हुए। गति और कार्यक्षमता का यह संयोजन C++ बनाता है | सबसे व्यापक रूप से उपयोग की जाने वाली प्रोग्रामिंग भाषाओं में से एक। + +```c++ +////////////////// +// सी . से तुलना +////////////////// + +// C++ _लगभग_C का सुपरसेट है और इसके लिए अपना मूल सिंटैक्स साझा करता है +// परिवर्तनीय घोषणाएं, आदिम प्रकार, और कार्य। + +// सी की तरह ही, आपके प्रोग्राम का एंट्री पॉइंट एक फंक्शन है, जिसे कहा जाता है +// मुख्य एक पूर्णांक वापसी प्रकार के साथ। +// यह मान प्रोग्राम की निकास स्थिति के रूप में कार्य करता है। +// अधिक जानकारी के लिए https://en.wikipedia.org/wiki/Exit_status देखें। +int main(int argc, char** argv) +{ + // कमांड लाइन तर्क उसी तरह argc और argv द्वारा पारित किए जाते हैं + // वे सी में हैं। + // argc तर्कों की संख्या को इंगित करता है, + // और argv सी-स्टाइल स्ट्रिंग्स (चार *) की एक सरणी है + // तर्कों का प्रतिनिधित्व करते हैं। + // पहला तर्क वह नाम है जिसके द्वारा प्रोग्राम को बुलाया गया था। + // यदि आप तर्कों की परवाह नहीं करते हैं तो argc और argv को छोड़ा जा सकता है, + // int main का फंक्शन सिग्नेचर देना () + + // 0 की निकास स्थिति सफलता को इंगित करती है। + return 0; +} + +// हालाँकि, C++ निम्नलिखित में से कुछ तरीकों से भिन्न होता है: + +// सी ++ में, वर्ण अक्षर वर्ण हैं +sizeof('c') == sizeof(char) == 1 + +// सी में, चरित्र अक्षर ints . हैं +sizeof('c') == sizeof(int) + + +// सी ++ में सख्त प्रोटोटाइप है +void func(); // फ़ंक्शन जो कोई तर्क स्वीकार नहीं करता है + +// सी में +void func(); // फ़ंक्शन जो किसी भी संख्या में तर्कों को स्वीकार कर सकता है + +// C++ में NULL के बजाय nullptr का प्रयोग करें +int* ip = nullptr; + +// सी मानक हेडर सी ++ में उपलब्ध हैं। +// सी हेडर .h में समाप्त होते हैं, जबकि +// सी ++ हेडर "सी" के साथ उपसर्ग कर रहे हैं और कोई ".एच" प्रत्यय नहीं है। + +// सी ++ मानक संस्करण: +#include + +// सी मानक संस्करण: +#include + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////////////////// +// फंक्शन ओवरलोडिंग +/////////////////////// + +// सी ++ फ़ंक्शन ओवरलोडिंग का समर्थन करता है +// बशर्ते प्रत्येक फ़ंक्शन अलग-अलग पैरामीटर लेता है। + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // Resolves to void print(const char*) + print(15); // Resolves to void print(int) +} + +///////////////////////////// +// डिफ़ॉल्ट फ़ंक्शन तर्क +///////////////////////////// + +// आप किसी फ़ंक्शन के लिए डिफ़ॉल्ट तर्क प्रदान कर सकते हैं +// अगर वे कॉलर द्वारा प्रदान नहीं किए जाते हैं। + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // यहां इनट्स के साथ कुछ करें +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// डिफ़ॉल्ट तर्क तर्क सूची के अंत में होना चाहिए। + +void invalidDeclaration(int a = 1, int b) // Error! +{ +} + + +///////////// +// नेमस्पेस +///////////// + +// नेमस्पेस वैरिएबल, फंक्शन के लिए अलग-अलग स्कोप प्रदान करते हैं, +// और अन्य घोषणाएं। +// नेमस्पेस को नेस्ट किया जा सकता है। + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // अंत नामस्थान नेस्टेड +} // अंतिम नाम स्थान पहले + +namespace Second { + void foo() + { + printf("This is Second::foo\n"); + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // नेमस्पेस सेकेंड से वर्तमान दायरे में सभी प्रतीकों को शामिल करता है। ध्यान दें + // वह बस foo() अब काम नहीं करता है, क्योंकि यह अब अस्पष्ट है कि क्या + // हम फू को नेमस्पेस सेकेंड या टॉप लेवल में कॉल कर रहे हैं। + using namespace Second; + + Second::foo(); // प्रिंट "यह दूसरा है :: फू" + First::Nested::foo(); // प्रिंट "यह पहला है :: नेस्टेड :: फू" + ::foo(); // प्रिंट करता है "यह वैश्विक फू है" +} + +/////////////// +// इनपुट आउटपुट +/////////////// + +// सी ++ इनपुट और आउटपुट स्ट्रीम का उपयोग करता है +// cin, cout, और cerr stdin, stdout और stderr का प्रतिनिधित्व करते हैं। +// << इंसर्शन ऑपरेटर है और >> एक्सट्रैक्शन ऑपरेटर है। + +#include // I/O स्ट्रीम के लिए शामिल करें + +using namespace std; // स्ट्रीम एसटीडी नेमस्पेस (मानक पुस्तकालय) में हैं + +int main() +{ + int myInt; + + // स्टडआउट (या टर्मिनल / स्क्रीन) पर प्रिंट करता है + cout << "Enter your favorite number:\n"; + // इनपुट लेता है + cin >> myInt; + + // cout को भी स्वरूपित किया जा सकता है + cout << "Your favorite number is " << myInt << '\n'; + // प्रिंट करता है "आपका पसंदीदा नंबर " है + + cerr << "Used for error messages"; +} + +////////// +// स्ट्रिंग्स +////////// + +// सी ++ में स्ट्रिंग्स ऑब्जेक्ट हैं और इसमें कई सदस्य कार्य हैं +#include + +using namespace std; // स्ट्रिंग्स नेमस्पेस एसटीडी (मानक पुस्तकालय) में भी हैं + +string myString = "Hello"; +string myOtherString = " World"; + +// + का उपयोग संयोजन के लिए किया जाता है। +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// सी ++ स्ट्रिंग्स म्यूटेबल हैं। +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// संदर्भ +///////////// + +// सी में वाले जैसे पॉइंटर्स के अलावा, +// सी ++ में _references_ हैं। +// ये पॉइंटर प्रकार हैं जिन्हें एक बार सेट करने के बाद पुन: असाइन नहीं किया जा सकता है +// और शून्य नहीं हो सकता। +// उनके पास वैरिएबल के समान सिंटैक्स भी है: +// नहीं * dereferencing के लिए आवश्यक है और +// और (का पता) असाइनमेंट के लिए उपयोग नहीं किया जाता है। + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // यह foo का संदर्भ बनाता है। +fooRef += ". Hi!"; // संदर्भ के माध्यम से फू को संशोधित करें +cout << fooRef; // प्रिंट "I am foo. Hi!" + +// "fooRef" को पुन: असाइन नहीं करता है। यह "फू = बार" जैसा ही है, और +// फू == "मैं बार हूँ" +// इस लाइन के बाद। +cout << &fooRef << endl; // फू का पता प्रिंट करता है +fooRef = bar; +cout << &fooRef << endl; // अभी भी फू का पता प्रिंट करता है +cout << fooRef; // प्रिंट "I am bar" + +// fooRef का पता वही रहता है, यानी यह अभी भी foo की बात कर रहा है। + + +const string& barRef = bar; // बार के लिए एक कॉन्स्टेबल संदर्भ बनाएं। +// सी की तरह, कॉन्स्ट वैल्यू (और पॉइंटर्स और रेफरेंस) को संशोधित नहीं किया जा सकता है। +barRef += ". Hi!"; // त्रुटि, कॉन्स्ट संदर्भों को संशोधित नहीं किया जा सकता है। + +// साइडट्रैक: इससे पहले कि हम संदर्भों के बारे में अधिक बात करें, हमें एक अवधारणा पेश करनी चाहिए +// एक अस्थायी वस्तु कहा जाता है। मान लीजिए हमारे पास निम्नलिखित कोड है: +string tempObjectFun() { ... } +string retVal = tempObjectFun(); + +// दूसरी पंक्ति में वास्तव में क्या होता है: +// - एक स्ट्रिंग ऑब्जेक्ट tempObjectFun से लौटाया जाता है +// - तर्क के रूप में लौटाई गई वस्तु के साथ एक नई स्ट्रिंग का निर्माण किया जाता है +// कंस्ट्रक्टर +// - लौटाई गई वस्तु नष्ट हो जाती है +// लौटाई गई वस्तु को अस्थायी वस्तु कहा जाता है। अस्थायी वस्तुएं हैं +// जब भी कोई फ़ंक्शन किसी ऑब्जेक्ट को लौटाता है, तब बनाया जाता है, और वे नष्ट हो जाते हैं +// संलग्न अभिव्यक्ति के मूल्यांकन का अंत (ठीक है, यह वही है +// मानक कहता है, लेकिन संकलक को इस व्यवहार को बदलने की अनुमति है। ऊपर देखो +// "वापसी मूल्य अनुकूलन" यदि आप इस तरह के विवरण में हैं)। तो इसमें +// कोड: +foo(bar(tempObjectFun())) + +// यह मानते हुए कि फू और बार मौजूद हैं, tempObjectFun से लौटाई गई वस्तु है +// बार को पास किया गया, और फू को कॉल करने से पहले इसे नष्ट कर दिया गया। + +// अब वापस संदर्भों पर। "संलग्नक के अंत में" का अपवाद +// अभिव्यक्ति" नियम यह है कि यदि एक अस्थायी वस्तु एक कॉन्स्ट संदर्भ के लिए बाध्य है, तो +// किस मामले में इसका जीवन वर्तमान दायरे तक बढ़ जाता है: + +void constReferenceTempObjectFun() { + // constRef अस्थायी वस्तु प्राप्त करता है, और यह इस के अंत तक मान्य है + // समारोह। + const string& constRef = tempObjectFun(); + ... +} + +// सी ++ 11 में पेश किया गया एक अन्य प्रकार का संदर्भ विशेष रूप से अस्थायी के लिए है +// ऑब्जेक्ट्स। आपके पास इसके प्रकार का एक चर नहीं हो सकता है, लेकिन इसमें पूर्वता होती है +// अधिभार संकल्प: + +void someFun(string& s) { ... } // नियमित संदर्भ +void someFun(string&& s) { ... } // अस्थायी वस्तु का संदर्भ + +string foo; +someFun(foo); // नियमित संदर्भ के साथ संस्करण को कॉल करें +someFun(tempObjectFun()); // अस्थायी संदर्भ के साथ संस्करण को कॉल करें + +// उदाहरण के लिए, आप कंस्ट्रक्टर के इन दो संस्करणों को देखेंगे +// std::basic_string: +basic_string(const basic_string& other); +basic_string(basic_string&& other); + +// विचार यह है कि अगर हम एक अस्थायी वस्तु से एक नई स्ट्रिंग का निर्माण कर रहे हैं (जो +// वैसे भी जल्द ही नष्ट होने जा रहा है), हम अधिक कुशल हो सकते हैं +// कंस्ट्रक्टर जो उस अस्थायी स्ट्रिंग के कुछ हिस्सों को "बचाता" है। आप इसे देखेंगे +// अवधारणा को "मूव सेमेन्टिक्स" के रूप में जाना जाता है। + +///////////////////// +// Enums +///////////////////// + +// Enums सबसे अधिक उपयोग किए जाने वाले स्थिरांक को मान निर्दिष्ट करने का एक तरीका है +// आसान विज़ुअलाइज़ेशन और कोड को पढ़ना +enum ECarTypes +{ + Sedan, + Hatchback, + SUV, + Wagon +}; + +ECarTypes GetPreferredCarType() +{ + return ECarTypes::Hatchback; +} + +// सी ++ 11 के रूप में एनम को एक प्रकार असाइन करने का एक आसान तरीका है जो हो सकता है +// डेटा के क्रमांकन में उपयोगी और एनम को आगे-पीछे परिवर्तित करना +// वांछित प्रकार और उनके संबंधित स्थिरांक +enum ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // किसी फ़ाइल में इनपुटवैल्यू को क्रमबद्ध करें +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // एनम को इसके घोषित एनम प्रकार के कारण uint8_t में परिवर्तित कर दिया गया है + WriteByteToFile(InputCarType); +} + +// दूसरी ओर, हो सकता है कि आप नहीं चाहते कि गलती से एनम को एक पूर्णांक में डाला जाए +// टाइप करें या अन्य एनम के लिए ताकि इसके बजाय एक एनम क्लास बनाना संभव हो जो +// परोक्ष रूप से परिवर्तित नहीं किया जाएगा +enum class ECarTypes : uint8_t +{ + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 +}; + +void WriteByteToFile(uint8_t InputValue) +{ + // किसी फ़ाइल में इनपुटवैल्यू को क्रमबद्ध करें +} + +void WritePreferredCarTypeToFile(ECarTypes InputCarType) +{ + // संकलित नहीं होगा, भले ही ECarTypes एक uint8_t एनम के कारण है + // "एनम क्लास" के रूप में घोषित किया जा रहा है! + WriteByteToFile(InputCarType); +} + +////////////////////////////////////////// +// कक्षाएं और वस्तु-उन्मुख प्रोग्रामिंग +////////////////////////////////////////// + +// कक्षाओं का पहला उदाहरण +#include + +// एक वर्ग घोषित करें। +// कक्षाएं आमतौर पर हेडर (.h या .hpp) फाइलों में घोषित की जाती हैं। +class Dog { + // सदस्य चर और कार्य डिफ़ॉल्ट रूप से निजी हैं। + std::string name; + int weight; + +// इसका अनुसरण करने वाले सभी सदस्य सार्वजनिक हैं +// जब तक "निजी:" या "संरक्षित:" नहीं मिलता है। +public: + + // Default constructor + Dog(); + + // सदस्य फ़ंक्शन घोषणाएं (कार्यान्वयन का पालन करें) + // ध्यान दें कि हम यहां रखने के बजाय std::string का उपयोग करते हैं + // नेमस्पेस एसटीडी का उपयोग करना; + // ऊपर। + // हेडर में कभी भी "नेमस्पेस का उपयोग करके" स्टेटमेंट न डालें। + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // ऐसे कार्य जो वस्तु की स्थिति को संशोधित नहीं करते हैं + // को कॉन्स्ट के रूप में चिह्नित किया जाना चाहिए। + // यह आपको ऑब्जेक्ट के संदर्भ में दिए जाने पर उन्हें कॉल करने की अनुमति देता है। + // यह भी ध्यान दें कि कार्यों को स्पष्ट रूप से _virtual_ के रूप में घोषित किया जाना चाहिए + // व्युत्पन्न कक्षाओं में ओवरराइड करने के लिए। + // कार्य प्रदर्शन कारणों से डिफ़ॉल्ट रूप से आभासी नहीं हैं। + virtual void print() const; + + // फंक्शन को क्लास बॉडी के अंदर भी परिभाषित किया जा सकता है। + // इस तरह परिभाषित कार्य स्वचालित रूप से रेखांकित होते हैं। + void bark() const { std::cout << name << " barks!\n"; } + + // कंस्ट्रक्टर्स के साथ, C++ डिस्ट्रक्टर्स प्रदान करता है। + // इन्हें तब कहा जाता है जब कोई वस्तु हटा दी जाती है या दायरे से बाहर हो जाती है। + // यह RAII जैसे शक्तिशाली प्रतिमानों को सक्षम बनाता है + // (निचे देखो) + // विध्वंसक आभासी होना चाहिए यदि एक वर्ग से प्राप्त किया जाना है; + // यदि यह आभासी नहीं है, तो व्युत्पन्न वर्ग 'विनाशक होगा' + // यदि ऑब्जेक्ट बेस-क्लास संदर्भ के माध्यम से नष्ट हो जाता है तो कॉल नहीं किया जाएगा + // या सूचक। + virtual ~Dog(); + +}; // अर्धविराम को वर्ग परिभाषा का पालन करना चाहिए। + +// क्लास सदस्य फ़ंक्शन आमतौर पर .cpp फ़ाइलों में कार्यान्वित किए जाते हैं। +Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// वस्तुओं (जैसे तार) को संदर्भ द्वारा पारित किया जाना चाहिए +// यदि आप उन्हें संशोधित कर रहे हैं या यदि आप नहीं हैं तो संदर्भ संदर्भ। +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// ध्यान दें कि "आभासी" केवल घोषणा में आवश्यक है, परिभाषा नहीं। +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +Dog::~Dog() +{ + std::cout << "Goodbye " << name << '\n'; +} + +int main() { + Dog myDog; // prints "A dog has been constructed" + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.print(); // prints "Dog is Barkley and weighs 10 kg" + return 0; +} // prints "Goodbye Barkley" + +// विरासत: + +// इस वर्ग को सब कुछ विरासत में मिला है और डॉग क्लास से संरक्षित है +// साथ ही निजी लेकिन सीधे निजी सदस्यों / विधियों तक नहीं पहुंच सकता है +// ऐसा करने के लिए सार्वजनिक या संरक्षित विधि के बिना +class OwnedDog : public Dog { + +public: + void setOwner(const std::string& dogsOwner); + + // सभी स्वामित्व वाले कुत्तों के लिए प्रिंट फ़ंक्शन के व्यवहार को ओवरराइड करें। ले देख + // https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // अधिक सामान्य परिचय के लिए यदि आप अपरिचित हैं + // उपप्रकार बहुरूपता। + // ओवरराइड कीवर्ड वैकल्पिक है लेकिन सुनिश्चित करता है कि आप वास्तव में हैं + // बेस क्लास में विधि को ओवरराइड करना। + +private: + std::string owner; +}; + +// इस बीच, संबंधित .cpp फ़ाइल में: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // बेस डॉग क्लास में प्रिंट फ़ंक्शन को कॉल करें class + std::cout << "Dog is owned by " << owner << '\n'; + // प्रिंट करता है "कुत्ता <नाम> है और वजन <वजन>" है + // "कुत्ता <मालिक> के स्वामित्व में है" +} + +////////////////////////////////////////// +// आरंभीकरण और ऑपरेटर ओवरलोडिंग +////////////////////////////////////////// + +// सी ++ में आप ऑपरेटरों के व्यवहार को ओवरलोड कर सकते हैं जैसे +, -, *, /, आदि। +// यह एक फ़ंक्शन को परिभाषित करके किया जाता है जिसे कहा जाता है +// जब भी ऑपरेटर का उपयोग किया जाता है। + +#include +using namespace std; + +class Point { +public: + // सदस्य चर को इस तरह से डिफ़ॉल्ट मान दिया जा सकता है। + double x = 0; + double y = 0; + + // एक डिफ़ॉल्ट कंस्ट्रक्टर को परिभाषित करें जो कुछ भी नहीं करता है + // लेकिन बिंदु को डिफ़ॉल्ट मान (0, 0) पर प्रारंभ करें + Point() { }; + + // The following syntax is known as an initialization list + // and is the proper way to initialize class member values + Point (double a, double b) : + x(a), + y(b) + { /* मानों को इनिशियलाइज़ करने के अलावा कुछ न करें */ } + + // + ऑपरेटर को ओवरलोड करें। + Point operator+(const Point& rhs) const; + + // + = ऑपरेटर को अधिभारित करें + Point& operator+=(const Point& rhs); + + // - और - = ऑपरेटरों को जोड़ना भी समझ में आता है, + // लेकिन हम उन्हें संक्षिप्तता के लिए छोड़ देंगे। +}; + +Point Point::operator+(const Point& rhs) const +{ + // एक नया बिंदु बनाएं जो इस एक और rhs का योग हो।. + return Point(x + rhs.x, y + rhs.y); +} + +// के सबसे बाएं चर के संदर्भ को वापस करने के लिए यह अच्छा अभ्यास है +// सौंपा गया कार्य। `(a += b) == c` इस तरह से काम करेगा। +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + + // `this` उस वस्तु का सूचक है, जिस पर एक विधि कहलाती है। + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // यह प्वाइंट + ऑपरेटर को कॉल करता है + // पॉइंट अप + (फ़ंक्शन) को इसके पैरामीटर के रूप में दाईं ओर कॉल करता है + Point result = up + right; + // Prints "Result is upright (1,1)" + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +///////////////////// +// टेम्पलेट्स +///////////////////// + +// C++ में टेम्प्लेट ज्यादातर सामान्य प्रोग्रामिंग के लिए उपयोग किए जाते हैं, हालांकि वे हैं +// अन्य भाषाओं में सामान्य निर्माणों की तुलना में बहुत अधिक शक्तिशाली। वे भी +// स्पष्ट और आंशिक विशेषज्ञता और कार्यात्मक-शैली प्रकार का समर्थन करें +// कक्षाएं; वास्तव में, वे एक ट्यूरिंग-पूर्ण कार्यात्मक भाषा एम्बेडेड हैं +// सी ++ में! + +// हम उस तरह की सामान्य प्रोग्रामिंग से शुरू करते हैं जिससे आप परिचित हो सकते हैं। सेवा +// एक वर्ग या फ़ंक्शन को परिभाषित करें जो एक प्रकार का पैरामीटर लेता है: +template +class Box { +public: + // इस वर्ग में, टी का उपयोग किसी अन्य प्रकार के रूप में किया जा सकता है। + void insert(const T&) { ... } +}; + +// संकलन के दौरान, कंपाइलर वास्तव में प्रत्येक टेम्पलेट की प्रतियां बनाता है +// प्रतिस्थापित मापदंडों के साथ, इसलिए वर्ग की पूरी परिभाषा होनी चाहिए +// प्रत्येक आह्वान पर उपस्थित। यही कारण है कि आप टेम्पलेट वर्ग परिभाषित देखेंगे +// पूरी तरह से हेडर फाइलों में। + +// स्टैक पर टेम्प्लेट क्लास को इंस्टेंट करने के लिए: +Box intBox; + +// और आप इसका उपयोग कर सकते हैं जैसा कि आप उम्मीद करेंगे: +intBox.insert(123); + +// आप निश्चित रूप से, नेस्ट टेम्प्लेट कर सकते हैं: +Box > boxOfBox; +boxOfBox.insert(intBox); + +// C++11 तक, आपको दो '>' के बीच एक जगह रखनी थी, अन्यथा '>>' +// सही शिफ्ट ऑपरेटर के रूप में पार्स किया जाएगा। + +// आप कभी-कभी देखेंगे +// टेम्पलेट<टाइपनाम टी> +// बजाय। 'वर्ग' कीवर्ड और 'टाइपनाम' कीवर्ड _अधिकतर_ हैं +// इस मामले में विनिमेय। पूरी व्याख्या के लिए देखें +// https://en.wikipedia.org/wiki/Typename +// (हाँ, उस कीवर्ड का अपना विकिपीडिया पेज है)। + +// इसी तरह, एक टेम्पलेट फ़ंक्शन: +template +void barkThreeTimes(const T& input) +{ + input.bark(); + input.bark(); + input.bark(); +} + +// ध्यान दें कि यहां प्रकार के मापदंडों के बारे में कुछ भी निर्दिष्ट नहीं है। संकलक +// उत्पन्न करेगा और फिर टेम्पलेट के प्रत्येक आमंत्रण को टाइप-चेक करेगा, इसलिए +// उपरोक्त फ़ंक्शन किसी भी प्रकार 'T' के साथ काम करता है जिसमें एक कॉन्स 'bark' विधि होती है! + +Dog fluffy; +fluffy.setName("Fluffy") +barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. + +// टेम्प्लेट मापदंडों का वर्ग होना जरूरी नहीं है: +template +void printMessage() { + cout << "Learn C++ in " << Y << " minutes!" << endl; +} + +// और आप स्पष्ट रूप से अधिक कुशल कोड के लिए टेम्पलेट्स को विशेषज्ञ बना सकते हैं। का +// बेशक, विशेषज्ञता के अधिकांश वास्तविक दुनिया के उपयोग इस तरह के रूप में तुच्छ नहीं हैं। +// ध्यान दें कि आपको अभी भी फ़ंक्शन (या वर्ग) को टेम्पलेट के रूप में घोषित करने की आवश्यकता है +// भले ही आपने सभी मापदंडों को स्पष्ट रूप से निर्दिष्ट किया हो। +template<> +void printMessage<10>() { + cout << "Learn C++ faster in only 10 minutes!" << endl; +} + +printMessage<20>(); // Prints "Learn C++ in 20 minutes!" +printMessage<10>(); // Prints "Learn C++ faster in only 10 minutes!" + + +///////////////////// +// संचालन अपवाद +///////////////////// + +// मानक पुस्तकालय कुछ अपवाद प्रकार प्रदान करता है +// (देखें https://en.cppreference.com/w/cpp/error/exception) +// लेकिन किसी भी प्रकार को अपवाद के रूप में फेंका जा सकता है +#include +#include + +// _try_ ब्लॉक के अंदर फेंके गए सभी अपवादों को बाद में पकड़ा जा सकता है +// _कैच_ हैंडलर। +try { + // _new_ का उपयोग करके ढेर पर अपवाद आवंटित न करें। + throw std::runtime_error("A problem occurred"); +} + +// कॉन्स्ट संदर्भ द्वारा अपवादों को पकड़ें यदि वे ऑब्जेक्ट हैं +catch (const std::exception& ex) +{ + std::cout << ex.what(); +} + +// पिछले _catch_ ब्लॉक द्वारा नहीं पकड़े गए किसी भी अपवाद को पकड़ता है +catch (...) +{ + std::cout << "Unknown exception caught"; + throw; // Re-throws the exception +} + +/////// +// आरएआईआई +/////// + +// RAII का अर्थ "संसाधन अधिग्रहण आरंभीकरण है"। +// इसे अक्सर C++ में सबसे शक्तिशाली प्रतिमान माना जाता है +// और सरल अवधारणा है कि एक वस्तु के लिए एक निर्माता +// उस वस्तु के संसाधनों को प्राप्त करता है और विनाशक उन्हें जारी करता है। + +// यह समझने के लिए कि यह कैसे उपयोगी है, +// एक फ़ंक्शन पर विचार करें जो C फ़ाइल हैंडल का उपयोग करता है: +void doSomethingWithAFile(const char* filename) +{ + // शुरू करने के लिए, मान लें कि कुछ भी विफल नहीं हो सकता है। + + FILE* fh = fopen(filename, "r"); // Open the file in read mode. + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // Close the file handle. +} + +// दुर्भाग्य से, त्रुटि प्रबंधन से चीजें जल्दी जटिल हो जाती हैं। +// मान लीजिए कि fopen विफल हो सकता है, और वह doSomethingWithTheFile और +// doSomethingElseWithIt विफल होने पर त्रुटि कोड लौटाता है। +// (अपवाद विफलता से निपटने का पसंदीदा तरीका है, +// लेकिन कुछ प्रोग्रामर, विशेष रूप से C बैकग्राउंड वाले, +// अपवादों की उपयोगिता पर असहमत)। +// अब हमें विफलता के लिए प्रत्येक कॉल की जांच करनी होगी और फ़ाइल हैंडल को बंद करना होगा +// यदि कोई समस्या हुई। +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // फ़ाइल को रीड मोड में खोलें + if (fh == nullptr) // लौटाया गया सूचक विफलता पर शून्य है। + return false; // Report that failure to the caller. + + // मान लें कि प्रत्येक फ़ंक्शन विफल होने पर गलत लौटाता है + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // फ़ाइल हैंडल को बंद करें ताकि यह लीक न हो। + return false; // त्रुटि का प्रचार करें। + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // फ़ाइल हैंडल को बंद करें ताकि यह लीक न हो। + return false; // त्रुटि का प्रचार करें। + } + + fclose(fh); // फ़ाइल हैंडल को बंद करें ताकि यह लीक न हो। + return true; // सफलता का संकेत दें +} + +// सी प्रोग्रामर अक्सर गोटो का उपयोग करके इसे थोड़ा साफ करते हैं: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // Close the file + return true; // Indicate success + +failure: + fclose(fh); + return false; // Propagate the error +} + +// यदि फ़ंक्शन अपवादों का उपयोग करके त्रुटियों को इंगित करता है, +// चीजें थोड़ी साफ हैं, लेकिन फिर भी उप-इष्टतम हैं। +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // Open the file in shared_ptrread mode + if (fh == nullptr) + throw std::runtime_error("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // Be sure to close the file if an error occurs. + throw; // Then re-throw the exception. + } + + fclose(fh); // Close the file + // Everything succeeded +} + +// इसकी तुलना C++ के फाइल स्ट्रीम क्लास (fstream) के उपयोग से करें +// fstream फ़ाइल को बंद करने के लिए अपने विनाशक का उपयोग करता है। +// ऊपर से याद करें कि विध्वंसक स्वचालित रूप से कहलाते हैं +// जब भी कोई वस्तु दायरे से बाहर हो जाती है। +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream इनपुट फ़ाइल स्ट्रीम के लिए छोटा है + std::ifstream fh(filename); // Open the file + + // Do things with the file + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} //फ़ाइल स्वचालित रूप से यहाँ विध्वंसक द्वारा बंद कर दी गई है + +// इसके _massive_ फायदे हैं: +// 1. चाहे कुछ भी हो जाए, +// संसाधन (इस मामले में फ़ाइल हैंडल) को साफ किया जाएगा। +// एक बार जब आप विध्वंसक को सही ढंग से लिख लेते हैं, +// हैंडल को बंद करना और रिसोर्स को लीक करना भूल जाना _असंभव_ है। +// 2. ध्यान दें कि कोड ज्यादा साफ है। +// विनाशक पर्दे के पीछे फ़ाइल को बंद करने का प्रबंधन करता है +// आपको इसके बारे में चिंता किए बिना। +// 3. कोड अपवाद सुरक्षित है। +// फंक्शन और क्लीनअप में कहीं भी एक अपवाद फेंका जा सकता है +// अभी भी होगा। + +// सभी मुहावरेदार सी ++ कोड सभी संसाधनों के लिए बड़े पैमाने पर आरएआईआई का उपयोग करता है। +// अतिरिक्त उदाहरणों में शामिल हैं +// - unique_ptr और shared_ptr . का उपयोग करके मेमोरी +// - कंटेनर - मानक पुस्तकालय लिंक्ड सूची, +// वेक्टर (यानी स्व-आकार देने वाला सरणी), हैश मैप, और इसी तरह +// जब वे दायरे से बाहर हो जाते हैं तो सभी स्वचालित रूप से अपनी सामग्री को नष्ट कर देते हैं। +// - लॉक_गार्ड और यूनिक_लॉक का उपयोग करने वाले म्यूटेक्स + + +///////////////////// +// स्मार्ट पॉइंटर +///////////////////// + +// आम तौर पर एक स्मार्ट पॉइंटर एक ऐसा वर्ग होता है जो "रॉ पॉइंटर" ("नया" का उपयोग) को लपेटता है +// क्रमशः सी में मॉलोक / कॉलोक)। लक्ष्य सक्षम होना है +// स्पष्ट रूप से हटाने की आवश्यकता के बिना इंगित की जा रही वस्तु के जीवनकाल का प्रबंधन करें +// वस्तु। यह शब्द केवल पॉइंटर्स के एक सेट का वर्णन करता है जिसमें +// अमूर्त का उल्लेख किया। +// स्मार्ट पॉइंटर्स को रोकने के लिए कच्चे पॉइंटर्स पर प्राथमिकता दी जानी चाहिए +// जोखिम भरा मेमोरी लीक, जो तब होता है जब आप किसी ऑब्जेक्ट को हटाना भूल जाते हैं। + +// कच्चे सूचक का उपयोग: +Dog* ptr = new Dog(); +ptr->bark(); +delete ptr; + +// स्मार्ट पॉइंटर का उपयोग करके, आपको हटाने के बारे में चिंता करने की ज़रूरत नहीं है +// अब वस्तु का। +// एक स्मार्ट पॉइंटर एक नीति का वर्णन करता है, जिसमें संदर्भों की गणना की जाती है +// सूचक। वस्तु नष्ट हो जाती है जब अंतिम +// वस्तु का संदर्भ नष्ट हो जाता है। + +// "std::shared_ptr" का उपयोग: +void foo() +{ + // It's no longer necessary to delete the Dog. + std::shared_ptr doggo(new Dog()); + doggo->bark(); +} + +// संभावित परिपत्र संदर्भों से सावधान रहें !!! +// हमेशा एक संदर्भ होगा, इसलिए इसे कभी नष्ट नहीं किया जाएगा! +std::shared_ptr doggo_one(new Dog()); +std::shared_ptr doggo_two(new Dog()); +doggo_one = doggo_two; // p1 references p2 +doggo_two = doggo_one; // p2 references p1 + +// कई प्रकार के स्मार्ट पॉइंटर्स हैं। +// उनका उपयोग करने का तरीका हमेशा एक जैसा होता है। +// यह हमें इस प्रश्न की ओर ले जाता है: हमें प्रत्येक प्रकार के स्मार्ट पॉइंटर का उपयोग कब करना चाहिए? +// std::unique_ptr - इसका उपयोग तब करें जब आप केवल एक संदर्भ रखना चाहते हैं +// वस्तु। +// std::shared_ptr - इसका उपयोग तब करें जब आप इसके लिए कई संदर्भ रखना चाहते हैं +// एक ही वस्तु और यह सुनिश्चित करना चाहते हैं कि इसे हटा दिया गया है +// जब सभी संदर्भ चले गए हैं। +// std::weak_ptr - जब आप एक्सेस करना चाहते हैं तो इसका इस्तेमाल करें +// एक std::shared_ptr की अंतर्निहित वस्तु उस वस्तु को आवंटित किए बिना। +// कमजोर पॉइंटर्स का उपयोग सर्कुलर रेफरेंसिंग को रोकने के लिए किया जाता है। + + +///////////////////// +// कंटेनर +///////////////////// + +// कंटेनर या मानक टेम्पलेट लाइब्रेरी कुछ पूर्वनिर्धारित टेम्पलेट हैं। +// वे इसके तत्वों के लिए भंडारण स्थान का प्रबंधन करते हैं और प्रदान करते हैं +// सदस्य उन्हें एक्सेस और हेरफेर करने के लिए कार्य करता है। + +// कुछ कंटेनर इस प्रकार हैं: + +// वेक्टर (गतिशील सरणी) +// हमें रन टाइम पर ऐरे या ऑब्जेक्ट्स की सूची को परिभाषित करने की अनुमति दें +#include +string val; +vector my_vector; // initialize the vector +cin >> val; +my_vector.push_back(val); // will push the value of 'val' into vector ("array") my_vector +my_vector.push_back(val); // will push the value into the vector again (now having two elements) + +// एक वेक्टर के माध्यम से पुनरावृति करने के लिए हमारे पास 2 विकल्प हैं: +// या तो क्लासिक लूपिंग (वेक्टर के माध्यम से इंडेक्स 0 से उसके अंतिम इंडेक्स तक पुनरावृति): +for (int i = 0; i < my_vector.size(); i++) { + cout << my_vector[i] << endl; // वेक्टर के तत्व तक पहुँचने के लिए हम ऑपरेटर का उपयोग कर सकते हैं [] +} + +// या एक पुनरावर्तक का उपयोग करना: +vector::iterator it; // initialize the iterator for vector +for (it = my_vector.begin(); it != my_vector.end(); ++it) { + cout << *it << endl; +} + +// सेट +// सेट कंटेनर हैं जो एक विशिष्ट क्रम के बाद अद्वितीय तत्वों को संग्रहीत करते हैं। +// सेट अद्वितीय मूल्यों को क्रमबद्ध क्रम में संग्रहीत करने के लिए एक बहुत ही उपयोगी कंटेनर है +// बिना किसी अन्य फ़ंक्शन या कोड के। + +#include +set ST; // Will initialize the set of int data type +ST.insert(30); // Will insert the value 30 in set ST +ST.insert(10); // Will insert the value 10 in set ST +ST.insert(20); // Will insert the value 20 in set ST +ST.insert(30); // Will insert the value 30 in set ST +// अब सेट के तत्व इस प्रकार हैं +// 10 20 30 + +// किसी तत्व को मिटाने के लिए +ST.erase(20); // मान 20 . के साथ तत्व मिटा देगा +// एसटी सेट करें: 10 30 +// सेट के माध्यम से पुनरावृति करने के लिए हम पुनरावृत्तियों का उपयोग करते हैं +set::iterator it; +for(it=ST.begin();it!=ST.end();it++) { + cout << *it << endl; +} +// Output: +// 10 +// 30 + +// पूरे कंटेनर को साफ करने के लिए हम कंटेनर_नाम.क्लियर () का उपयोग करते हैं +ST.clear(); +cout << ST.size(); // will print the size of set ST +// आउटपुट: 0 + +// नोट: डुप्लिकेट तत्वों के लिए हम मल्टीसेट का उपयोग कर सकते हैं +// नोट: हैश सेट के लिए, unordered_set का उपयोग करें। वे अधिक कुशल हैं लेकिन +// आदेश को संरक्षित न करें। unordered_set C++11 के बाद से उपलब्ध है + +// नक्शा +// मैप्स एक प्रमुख मूल्य के संयोजन द्वारा गठित तत्वों को संग्रहीत करता है +// और एक विशिष्ट क्रम के बाद एक मैप किया गया मान। + +#include +map mymap; // Will initialize the map with key as char and value as int + +mymap.insert(pair('A',1)); +// Will insert value 1 for key A +mymap.insert(pair('Z',26)); +// Will insert value 26 for key Z + +// To iterate +map::iterator it; +for (it=mymap.begin(); it!=mymap.end(); ++it) + std::cout << it->first << "->" << it->second << std::cout; +// आउटपुट: +// ए-> 1 +// जेड-> 26 + +// कुंजी के अनुरूप मान ज्ञात करने के लिए +it = mymap.find('Z'); +cout << it->second; + +// आउटपुट: 26 + +// नोट: हैश मैप के लिए, unordered_map का उपयोग करें। वे अधिक कुशल हैं लेकिन करते हैं +// आदेश को संरक्षित नहीं करें। unordered_map C++11 के बाद से उपलब्ध है। + +// गैर-आदिम मूल्यों (कस्टम वर्ग) की ऑब्जेक्ट कुंजियों वाले कंटेनरों की आवश्यकता होती है +// ऑब्जेक्ट में या फ़ंक्शन पॉइंटर के रूप में फ़ंक्शन की तुलना करें। पुरातन +// डिफ़ॉल्ट तुलनित्र हैं, लेकिन आप इसे ओवरराइड कर सकते हैं। +class Foo { +public: + int j; + Foo(int a) : j(a) {} +}; +struct compareFunction { + bool operator()(const Foo& a, const Foo& b) const { + return a.j < b.j; + } +}; +// इसकी अनुमति नहीं है (हालांकि यह कंपाइलर के आधार पर भिन्न हो सकता है) +// एसटीडी :: नक्शा <फू, इंट> फूमैप; +std::map fooMap; +fooMap[Foo(1)] = 1; +fooMap.find(Foo(1)); //true + + +//////////////////////////////////// +// लैम्ब्डा एक्सप्रेशन (सी ++ 11 और ऊपर) +//////////////////////////////////// + +// लैम्ब्डा एक अनाम फ़ंक्शन को परिभाषित करने का एक सुविधाजनक तरीका है +// वस्तु उस स्थान पर ठीक है जहां इसे लागू किया गया है या पारित किया गया है +// किसी फ़ंक्शन के लिए एक तर्क। + +// उदाहरण के लिए, दूसरे का उपयोग करके जोड़े के वेक्टर को सॉर्ट करने पर विचार करें +// जोड़ी का मूल्य + +vector > tester; +tester.push_back(make_pair(3, 6)); +tester.push_back(make_pair(1, 9)); +tester.push_back(make_pair(5, 0)); + +// लैम्ब्डा एक्सप्रेशन को सॉर्ट फ़ंक्शन के तीसरे तर्क के रूप में पास करें +// सॉर्ट <एल्गोरिदम> हेडर से है + +sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { + return lhs.second < rhs.second; + }); + +// लैम्ब्डा एक्सप्रेशन के सिंटैक्स पर ध्यान दें, +// [] लैम्ब्डा में चर को "कैप्चर" करने के लिए प्रयोग किया जाता है +// "कैप्चर लिस्ट" परिभाषित करती है कि लैम्ब्डा के बाहर से फंक्शन बॉडी के अंदर क्या उपलब्ध होना चाहिए और कैसे। +// यह या तो हो सकता है: +// 1. एक मान: [x] +// 2. एक संदर्भ: [&x] +// 3. संदर्भ के अनुसार वर्तमान में कोई भी चर [&] +// 4. ३ के समान, लेकिन मूल्य से [=] +// उदाहरण: + +vector dog_ids; +// number_of_dogs = 3; +for(int i = 0; i < 3; i++) { + dog_ids.push_back(i); +} + +int weight[3] = {30, 50, 10}; + +// मान लें कि आप कुत्तों के वजन के अनुसार dog_ids को सॉर्ट करना चाहते हैं +// तो dog_ids अंत में बन जाना चाहिए: [२, ०, १] + +// यहाँ वह जगह है जहाँ लैम्ब्डा के भाव काम आते हैं + +sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { + return weight[lhs] < weight[rhs]; + }); +// ध्यान दें कि हमने उपरोक्त उदाहरण में संदर्भ द्वारा "वजन" पर कब्जा कर लिया है। +// सी ++ में लैम्ब्डा पर अधिक: https://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11 + +///////////////////////////// +// रेंज के लिए (सी ++ 11 और ऊपर) +///////////////////////////// + +// आप एक कंटेनर पर लूप को पुनरावृत्त करने के लिए एक श्रेणी का उपयोग कर सकते हैं +int arr[] = {1, 10, 3}; + +for(int elem: arr){ + cout << elem << endl; +} + +// आप "ऑटो" का उपयोग कर सकते हैं और कंटेनर के तत्वों के प्रकार के बारे में चिंता न करें +// उदाहरण के लिए: + +for(auto elem: arr) { + // Do something +} + +///////////////////// +// मजेदार चीजें +///////////////////// + +// सी ++ के पहलू जो नवागंतुकों (और यहां तक ​​​​कि कुछ दिग्गजों) के लिए आश्चर्यजनक हो सकते हैं। +// यह खंड, दुर्भाग्य से, बेतहाशा अधूरा है; सी ++ सबसे आसान में से एक है +// भाषाएं जिनके साथ अपने आप को पैर में गोली मारनी है। + +// आप निजी तरीकों को ओवरराइड कर सकते हैं! +class Foo { + virtual void bar(); +}; +class FooSub : public Foo { + virtual void bar(); // Overrides Foo::bar! +}; + + +// 0 == false == NULL (most of the time)! +bool* pt = new bool; +*pt = 0; // मान बिंदुओं को 'पीटी' द्वारा गलत पर सेट करता है। +pt = 0; // 'पीटी' को अशक्त सूचक पर सेट करता है। दोनों पंक्तियाँ बिना किसी चेतावनी के संकलित हैं। + +// nullptr उस समस्या में से कुछ को ठीक करने वाला है: +int* pt2 = new int; +*pt2 = nullptr; // Doesn't compile +pt2 = nullptr; // Sets pt2 to null. + +// बूल के लिए एक अपवाद बनाया गया है। +// यह आपको if(!ptr) के साथ नल पॉइंटर्स के लिए परीक्षण करने की अनुमति देता है, +// लेकिन परिणामस्वरूप आप सीधे बूल को नलप्टर असाइन कर सकते हैं! +*pt = nullptr; // This still compiles, even though '*pt' is a bool! + + +// '=' != '=' != '='! +// कॉल फू :: फू (कॉन्स्ट फू एंड) या कुछ प्रकार (मूव शब्दार्थ देखें) कॉपी +// कंस्ट्रक्टर। +Foo f2; +Foo f1 = f2; + +// कॉल फू :: फू (कॉन्स्ट फू एंड) या संस्करण, लेकिन केवल 'फू' भाग की प्रतिलिपि बनाता है +// 'फूसब'। 'fooSub' के किसी भी अतिरिक्त सदस्य को छोड़ दिया जाता है। यह कभी कभी +// भयानक व्यवहार को "ऑब्जेक्ट स्लाइसिंग" कहा जाता है। +FooSub fooSub; +Foo f1 = fooSub; + +// Calls Foo::operator=(Foo&) or variant. +Foo f1; +f1 = f2; + + +//////////////////////////////////// +// टुपल्स (सी ++ 11 और ऊपर) +//////////////////////////////////// + +#include + +// वैचारिक रूप से, टुपल्स पुराने डेटा संरचनाओं (सी-जैसी संरचना) के समान हैं +// लेकिन डेटा सदस्यों को नामित करने के बजाय, +// इसके तत्वों को टपल में उनके क्रम द्वारा एक्सेस किया जाता है। + +// हम एक टपल के निर्माण के साथ शुरू करते हैं। +// मूल्यों को टपल में पैक करें +auto first = make_tuple(10, 'A'); +const int maxN = 1e9; +const int maxL = 15; +auto second = make_tuple(maxN, maxL); + +// Printing elements of 'first' tuple +cout << get<0>(first) << " " << get<1>(first) << '\n'; //prints : 10 A + +// Printing elements of 'second' tuple +cout << get<0>(second) << " " << get<1>(second) << '\n'; // prints: 1000000000 15 + +// टपल को वेरिएबल में अनपैक करना + +int first_int; +char first_char; +tie(first_int, first_char) = first; +cout << first_int << " " << first_char << '\n'; // prints : 10 A + +// हम इस तरह टपल भी बना सकते हैं। + +tuple third(11, 'A', 3.14141); +// tuple_size टपल में तत्वों की संख्या लौटाता है (एक कॉन्स्टेक्स के रूप में) + +cout << tuple_size::value << '\n'; // prints: 3 + +// tuple_cat सभी टुपल्स के तत्वों को एक ही क्रम में संयोजित करता है। + +auto concatenated_tuple = tuple_cat(first, second, third); +// concatenated_tuple बन जाता है = (10, 'ए', 1e9, 15, 11, 'ए', 3.14141) + +cout << get<0>(concatenated_tuple) << '\n'; // prints: 10 +cout << get<3>(concatenated_tuple) << '\n'; // prints: 15 +cout << get<5>(concatenated_tuple) << '\n'; // prints: 'A' + + +///////////////////////////////// +// लॉजिकल और बिटवाइज ऑपरेटर्स +//////////////////////////////// + +// सी ++ में अधिकांश ऑपरेटर अन्य भाषाओं की तरह ही हैं + +// लॉजिकल ऑपरेटर्स + +// सी ++ बूलियन अभिव्यक्तियों के लिए शॉर्ट-सर्किट मूल्यांकन का उपयोग करता है, यानी, दूसरा तर्क निष्पादित किया जाता है या +// केवल तभी मूल्यांकन किया जाता है जब पहला तर्क अभिव्यक्ति के मूल्य को निर्धारित करने के लिए पर्याप्त नहीं है + +true && false // निष्पादित करता है **तार्किक और** असत्य उत्पन्न करने के लिए +true || false // सत्य उत्पन्न करने के लिए **तार्किक या** करता है +! true // प्रदर्शन करता है **तार्किक नहीं** झूठा उत्पन्न करने के लिए + +// प्रतीकों का उपयोग करने के बजाय समकक्ष कीवर्ड का उपयोग किया जा सकता है +true and false // प्रदर्शन करता है **तार्किक और ** गलत उत्पन्न करने के लिए +true or false // सत्य उत्पन्न करने के लिए **तार्किक या ** करता है +not true // निष्पादित करता है **तार्किक नहीं ** असत्य उत्पन्न करने के लिए + +// बिटवाइज ऑपरेटर्स + +// **<<** लेफ्ट शिफ्ट ऑपरेटर +// << बिट्स को बाईं ओर शिफ्ट करता है +4 << 1 // 8 देने के लिए 4 के बिट्स को 1 से बायीं ओर शिफ्ट करता है +// x << n को x * 2^n . के रूप में माना जा सकता है + + +// **>>** राइट शिफ्ट ऑपरेटर +// >> बिट्स को दाईं ओर शिफ्ट करता है +4 >> 1 // २ देने के लिए ४ के बिट्स को १ से दायीं ओर शिफ्ट करता है +// x >> n को x / 2^n . के रूप में माना जा सकता है + +~4 // Performs a bitwise not +4 | 3 // Performs bitwise or +4 & 3 // Performs bitwise and +4 ^ 3 // Performs bitwise xor + +// समतुल्य कीवर्ड हैं +compl 4 // Performs a bitwise not +4 bitor 3 // Performs bitwise or +4 bitand 3 // Performs bitwise and +4 xor 3 // Performs bitwise xor +``` + +अग्रिम पठन: + +* एक अप-टू-डेट भाषा संदर्भ [सीपीपी संदर्भ](http://cppreference.com/w/cpp) पर पाया जा सकता है। +* अतिरिक्त संसाधन [CPlusPlus](http://cplusplus.com) पर मिल सकते हैं। +* [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb) पर भाषा की बुनियादी बातों और कोडिंग परिवेश को सेट करने वाला एक ट्यूटोरियल उपलब्ध है। From 7dce0227a74f71ac8126b7f5c193433cc68f4c71 Mon Sep 17 00:00:00 2001 From: Ily <90933947+Ily83@users.noreply.github.com> Date: Wed, 15 May 2024 03:18:59 +0200 Subject: [PATCH 219/392] [fortran/en] do concurrent (#4531) --- fortran.html.markdown | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/fortran.html.markdown b/fortran.html.markdown index c0d90367..83074073 100644 --- a/fortran.html.markdown +++ b/fortran.html.markdown @@ -438,6 +438,35 @@ contains end function complex_abs end module fruity + +! ISO Standard Fortran 2008 introduced the DO CONCURRENT construct to allow you +! to express loop-level parallelism + +integer :: i +real :: array(100) + +DO CONCURRENT (i = 1:size(array)) + array(i) = sqrt(i**i) +END DO + + +! Only calls to pure functions are allowed inside the loop and we can declare +! multiple indices: + +integer :: x, y +real :: array(8, 16) + +do concurrent (x = 1:size(array, 1), y = 1:size(array, 2)) + array(x, y) = real(x) +end do + +! loop indices can also declared inside the contruct: + +real :: array(8, 16) + +do concurrent (integer :: x = 1:size(array, 1), y = 1:size(array, 2)) + array(x, y) = real(x) +end do ``` ### More Resources From d3b496230e4dd2e90f5334964126a6ffe9382556 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 14 May 2024 19:23:01 -0600 Subject: [PATCH 220/392] [c++/hi] fix language name --- hi-in/{c++-hd.html.markdown => c++-hi.html.markdown} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename hi-in/{c++-hd.html.markdown => c++-hi.html.markdown} (99%) diff --git a/hi-in/c++-hd.html.markdown b/hi-in/c++-hi.html.markdown similarity index 99% rename from hi-in/c++-hd.html.markdown rename to hi-in/c++-hi.html.markdown index 36abf2c2..7fd90878 100644 --- a/hi-in/c++-hd.html.markdown +++ b/hi-in/c++-hi.html.markdown @@ -1,5 +1,5 @@ --- -language: c++ +language: C++ filename: learncpp-hi.cpp contributors: - ["Steven Basart", "https://github.com/xksteven"] From 6c72a9c2b76df4cb80533df87f30566cc543c749 Mon Sep 17 00:00:00 2001 From: "Ihor P. Sokorchuk" <98028882+IhorSokorchuk@users.noreply.github.com> Date: Wed, 15 May 2024 04:59:10 +0300 Subject: [PATCH 221/392] [awk/uk] translate AWK (#4306) --- uk-ua/awk-uk.html.markdown | 397 +++++++++++++++++++++++++++++++++++++ 1 file changed, 397 insertions(+) create mode 100644 uk-ua/awk-uk.html.markdown diff --git a/uk-ua/awk-uk.html.markdown b/uk-ua/awk-uk.html.markdown new file mode 100644 index 00000000..a99dca17 --- /dev/null +++ b/uk-ua/awk-uk.html.markdown @@ -0,0 +1,397 @@ +--- +category: tool +tool: awk +filename: learnawk-ua.awk +contributors: + - ["Marshall Mason", "http://github.com/marshallmason"] +translators: + - ["Ihor Sokorchuk", "https://github.com/IhorSokorchuk"] +lang: uk-ua +--- + +AWK є стандартним інструментом у кожній POSIX-сумісній системі UNIX. +Він схожий на flex/lex із командного рядка й чудово підходить для завдань +обробки тексту та інших скриптових задач. Він має подібний до C синтаксис, +але без обов’язкових крапок з комою (хоча їх все одно потрібно використовувати, +якщо ви пишете однорядковий код, для якого AWK відмінно підходить), +у ньому немає ручного керування пам’яттю та статичної типізації. +Він відмінно обробляє текст. Ви можете викликати його зі сценарію оболонки або +використовувати як окрему мову сценаріїв. + +Навіщо використовувати AWK замість Perl? Це читабельність коду. +Адже AWK легше читати, ніж Perl. Для простих сценаріїв обробки тексту, +особливо тих, які читають файли рядок за рядком і розбивають їх +за роздільниками, AWK є чи не найкращим інструментом. + +```awk +#!/usr/bin/awk -f + +# Коментарі у AWK схожі на цей коментар. + +# Програми AWK складаються з набору шаблонів і дій. +pattern1 { action; } # зовсім як lex +pattern2 { action; } + +# Скрипт виконує неявний цикл, у якому AWK автоматично читає та аналізує кожен +# запис із кожного наданого йому файла. Кожен такий запис розділяється на поля +# роздільником FS, який за замовчуванням має значення пробіл (кілька пробілів +# або символів табуляції вважаються одним роздільником). +# Можна встановити значення FS в командному рядку (-FC) або у шаблоні BEGIN. + +# Одним із спеціальних шаблонів є шаблон BEGIN. Цей шаблон є дійсним +# ДО прочитання будь-якого з вхідних файлів. +# Ще один спеціальний шаблон END є дійсним після кінця останнього з вказаних +# вхідних файлів, або після стандартного введення, якщо вхідні файли не вказано. +# Також використовується роздільник між полями виводу (OFS), значення якого +# ви також можете призначити, і для якого за замовчуванням встановлено +# значення один пробіл. + + +BEGIN { + + # BEGIN запускатиметься на початку програми. Тут розміщують весь код + # попереднього налаштування перед обробкою будь-яких текстових файлів. + # Якщо ваш скрипт не читає текстові файли, розглядайте BEGIN як + # головну точку входу. + + # Змінні є глобальними. Просто встановіть їх і використовуйте. + # Оголошувати змінні не потрібно. + count = 0; + + # Оператори є такими ж як у мові C та схожих на неї мовах програмування. + a = count + 1; + b = count - 1; + c = count * 1; + d = count / 1; # цілочислене ділення + e = count % 1; # модуль + f = count ^ 1; # піднесення до степеня + + a += 1; + b -= 1; + c *= 1; + d /= 1; + e %= 1; + f ^= 1; + + # Постфіксний оператор збільшення та зменшення на одиницю + a++; + b--; + + # Префіксний оператор, який повертає збільшене на одиницю значення + ++a; + --b; + + # Зверніть також увагу, що в кінці рядка не обов'язково вказувати + # розділовий знак крапка з комою. + + # Оператор галудження + if (count == 0) + print "Starting with count of 0"; + else + print "Huh?"; + + # Можна використовувати тернарний оператор + print (count == 0) ? "Starting with count of 0" : "Huh?"; + + # Для блоків, що складаються з кількох рядків, використовують дужки + while (a < 10) { + print "String concatenation is done" " with a series" " of" + " space-separated strings"; + print a; + + a++; + } + + for (i = 0; i < 10; i++) + print "Good ol' for loop"; + + # Порівняння є стандартними: + # a < b # менше ніж + # a <= b # менше або дорівнює + # a != b # не дорівнює + # a == b # дорівнює + # a > b # більше ніж + # a >= b # більше або дорівнює + + # Логічні оператори також стандартні: + # a && b # AND - І + # a || b # OR - АБО + + # Крім того, є перевірка на збіг із регулярним виразом: + if ("foo" ~ "^fo+$") + print "Fooey!"; + if ("boo" !~ "^fo+$") + print "Boo!"; + + # Масиви: + arr[0] = "foo"; + arr[1] = "bar"; + + # Також можна ініціалізувати масив за допомогою вбудованої функції split(): + n = split("foo:bar:baz", arr, ":"); + + # Підтримуються асоціативні масиви (насправді, всі масиви асоціативні): + assoc["foo"] = "bar"; + assoc["bar"] = "baz"; + + # Та багатовимірні масиви (з деякими обмеженнями, які описуються далі): + multidim[0,0] = "foo"; + multidim[0,1] = "bar"; + multidim[1,0] = "baz"; + multidim[1,1] = "boo"; + + # Можна перевірити членство в масиві: + if ("foo" in assoc) + print "Fooey!"; + + # Оператор 'in' також можна використовувати для обходу ключів масиву: + for (key in assoc) + print assoc[key]; + + # Командний рядок знаходиться у спеціальному масиві з ім'ям ARGV + for (argnum in ARGV) + print ARGV[argnum]; + + # Можна видаляти елементи масиву. Це особливо корисно для того, щоб AWK + # не розглядав аргументи як імена файлів для обробки + delete ARGV[1]; + + # Кількість аргументів командного рядка міститься у змінній з іменем ARGC + print ARGC; + + # AWK має багато вбудованих функцій. Вони діляться на три категорії, які + # буде розглянуто далі. + + return_value = arithmetic_functions(a, b, c); + string_functions(); + io_functions(); +} + +# Функції декларуються так: +function arithmetic_functions(a, b, c, d) { + + # Однією з дратівливих особливостей AWK є те, що в цій мові немає + # локальних змінних. Усе є глобальним. + # Для коротких сценаріїв це добре, навіть корисно, але для довших + # сценаріїв це може бути проблемою. + + # Проте, є обхідний шлях (huk). Вказані у функції аргументи є локальними + # у функції. Крім того, AWK дозволяє вказувати більше аргументів функції, + # ніж потрібно. Тому, просто вставте локальну змінну в оголошення + # функції, як це зроблено вище. Можна додати також додаткові пробіли, + # щоб відрізнити фактичні параметри функції від створених у такий спосіб + # локальних змінних. + # У наведеному вище прикладі, змінні a, b, c є фактичними параметрами, + # тоді як d є лише локальною змінною. + + # Тепер, розглянемо математичні функції + + # Більшість реалізацій AWK підтримують стандартні тригонометричні функції: + localvar = sin(a); + localvar = cos(a); + localvar = atan2(b, a); # арктангенс b / a + + # та логаритмічні обчислення: + localvar = exp(a); + localvar = log(a); + + # квадратний корінь: + localvar = sqrt(a); + + # округлення до цілого числа: + localvar = int(5.34); # localvar => 5 + + # випадкові числа: + srand(); # встановити т.зв. "сіль" (без аргумента використовується час) + localvar = rand(); # випадкове число від 0 до 1. + + # Повернути значення можна так: + return localvar; +} + +# Функції для обробки рядків тексту +function string_functions( localvar, arr) { + + # AWK, як мова обробки тексту, підтримує функції для обробки рядків. + # У багатьох з цих функцій використовуються регулярні вирази. + + # Пошук і заміна, першої (sub) або всіх відповідностей (gsub). + # Обидві вони повертають кількість замінених відповідностей. + localvar = "fooooobar"; + sub("fo+", "Meet me at the ", localvar); # localvar => "Meet me at the bar" + gsub("e", ".", localvar); # localvar => "m..t m. at th. bar" + + # Пошук підрядка, який збігається з регулярним виразом: + # index() робить те ж саме, але не використовує регулярний вираз. + match(localvar, "t"); # => 4, оскільки 't' є четвертим символом + + # Розбити рядок за роздільником + n = split("foo-bar-baz", arr, "-"); # a[1] = "foo"; a[2] = "bar"; a[3] = "baz"; n = 3 + + # Інші корисні речі + sprintf("%s %d %d %d", "Testing", 1, 2, 3); # => "Testing 1 2 3" + substr("foobar", 2, 3); # => "oob" + substr("foobar", 4); # => "bar" + length("foo"); # => 3 + tolower("FOO"); # => "foo" + toupper("foo"); # => "FOO" +} + +# Функції введення-виведення +function io_functions( localvar) { + + # Ви вже бачили print + print "Hello world"; + + # Є також printf + printf("%s %d %d %d\n", "Testing", 1, 2, 3); + + # AWK сам по собі не має дескрипторів файлів. Він автоматично відкриває + # дескриптор файлу, коли виконується дія, яка потребує дискриптора. + # Рядок, який використано для цього, можна розглядати як дескриптор файлу + # для введення-виводу. Це схоже на сценарії оболонки. + # Рядок, при цьому, повинен точно збігатися. Тому використовуйте змінну: + outfile = "/tmp/foobar.txt"; + print "foobar" > outfile; + + # Тепер, рядок вихідного файлу є дескриптором файлу. + # Ви можете закрити його: + close(outfile); + + # Ось як запустити команду в оболонці + system("echo foobar"); # => друкує foobar + + # Читає рядок із потоку стандартного введення та зберігає в localvar + getline localvar; + + # Читає рядок з каналу (використовуйте рядок, щоб правильно його закрити) + cmd = "echo foobar"; + cmd | getline localvar; # localvar => "foobar" + close(cmd); + + # Читає рядок з файлу та зберігає в localvar + infile = "/tmp/foobar.txt"; + getline localvar < infile; + close(infile); +} + +# Як вже вказувалося, програми AWK складаються з набору шаблонів та дій. +# Було розглянуто шаблони BEGIN та END . Інші шаблони використовуються тоді, +# коли скрипт обробляє рядки з файлів або стандартного потоку введення. +# + +# Вказані у командному рядку аргументи розглядаються як імена файлів для +# обробки. Усі ці файли обробляються послідовно один за одним. +# Виконується неявний цикл, в якому обробляються усі рядки з цих файлів. +# Шаблони та дії AWK схожі на оператор switch всередині циклу. + +/^fo+bar$/ { + # Ця дія буде виконуватися для кожного рядка, який збігається з регулярним + # виразом: /^fo+bar$/, і буде пропущена для усіх рядків, + # які не збігаються з ним. Давайте просто надрукуємо рядок: + + print; + + # Без аргументів! Це тому, що print має аргумент за замовчуванням: $0. + # $0 - ім'я змінної, яка містить увесь поточний рядок. Ця змінна + # створюється автоматично. + + # Також існують інші змінні зі знаком $. Кожен рядок неявно розбивається + # перед викликом кожної дії так, як це робить оболонка. І так само, як і + # в оболонці, до кожного поля можна отримати доступ із відповідної змінної + # зі знаком долара. + + # Тут буде виведене друге та четверте поля з рядка + print $2, $4; + + # AWK автоматично визначає багато інших змінних, щоб допомогти перевірити + # та обробити кожен рядок. Однією з них є NF. + + # Друкує кількість полів у цьому рядку + print NF; + + # Друк останнього поля у цьому рядку + print $NF; +} + +# Кожен шаблон є логічним виразом. Регулярний вираз у наведеному шаблоні +# також є перевіркою на істине/хибне, але частина виразу прихована. +# Шаблон обробляє кожен вхідний рядок і його повна версія є такою: +$0 ~ /^fo+bar$/ { + print "Equivalent to the last pattern"; +} + +a > 0 { + # цей блок виконуватиметься для кожного рядка, допоки змінна a буде + # більшою від 0 +} + +# Ідея AWK зрозуміла. Обробка текстових файлів, порядкове зчитування і +# обробка, зокрема розбиття за роздільником, настільки поширені в UNIX, +# що AWK — це мова сценаріїв, яка виконує все це сама, без ваших вказівок. +# Все, що вам потрібно зробити, це написати шаблони та дії на основі того, +# що ви очікуєте від введення, і що ви хочете з ним зробити. + +# Ось короткий приклад простого сценарію, для якого чудово підходить AWK. +# Цей сценарій прочитає ім’я зі стандартного потоку введення, а потім надрукує +# середній вік для людей з цим іменем. +# Нехай, як аргумент скрипта вказано ім’я файла з такими даними: +# +# Bob Jones 32 +# Jane Doe 22 +# Steve Stevens 83 +# Bob Smith 29 +# Bob Barker 72 +# + +# Ось сценарій: + +BEGIN { + + # Спершу попросимо користувача ввести ім'я + print "What name would you like the average age for?"; + + # Отримати рядок зі стандартного потоку введення, а не з файлів + # командного рядка + getline name < "/dev/stdin"; +} + +# Тепер обробимо кожен рядок, першим полем якого є вказане ім'я +$1 == name { + + # Тут усередині ми маємо доступ до низки корисних змінних, які вже + # встановлені для нас попередньо: + # $0 - це весь рядок + # $3 - це третє поле, вік, який нас тут цікавить + # NF - це кількість полів, яка має бути 3 + # NR - це кількість записів (рядків), переглянутих на поточний момент + # FILENAME - ім'я файла, який обробляється + # FS - це роздільник полів, який використовується. Тут це - " " + # ... є багато інших задокументованих на сторінці керівництва змінних + + # Обчислимо поточну суму та кількість рядків, які відповідають шаблону + sum += $3; + nlines++; +} + +# Ще один спеціальний шаблон називається END. Він виконується після обробки +# всіх текстових файлів. На відміну від BEGIN, він запуститься, якщо були +# дані для обробки. Він виконуватиметься після того, як будуть прочитані та +# оброблені, відповідно до вказаних правил та дій, усі файли з вхідними даними. +# Його мета зазвичай полягає в тому, щоб вивести якийсь остаточний звіт або +# зробити щось із накопиченою протягом сценарію сукупністю даних + +END { + if (nlines) + print "The average age for " name " is " sum / nlines; +} +``` + +Детальніше дивіться: + +* [Awk tutorial](http://www.grymoire.com/Unix/Awk.html) +* [Awk man page](https://linux.die.net/man/1/awk) +* [The GNU Awk User's Guide](https://www.gnu.org/software/gawk/manual/gawk.html) GNU Awk is found on most Linux systems. +* [AWK one-liner collection](http://tuxgraphics.org/~guido/scripts/awk-one-liner.html) +* [Awk alpinelinux wiki](https://wiki.alpinelinux.org/wiki/Awk) a technical summary and list of "gotchas" (places where different implementations may behave in different or unexpected ways). +* [basic libraries for awk](https://github.com/dubiousjim/awkenough) From 07b055e8f104ff83e26f426f75ee6dbfba3260cd Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 14 May 2024 20:05:35 -0600 Subject: [PATCH 222/392] [cypher/en] It use -> It uses --- cypher.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cypher.html.markdown b/cypher.html.markdown index f6febb4c..389e1d11 100644 --- a/cypher.html.markdown +++ b/cypher.html.markdown @@ -34,7 +34,7 @@ The types allowed in properties: ## Relationships (or Edges) connect two nodes -`[:KNOWS]` is a *relationship* with the *label* `KNOWS`. It's a *label* as the node's label. It begins with uppercase and use UPPER\_SNAKE\_CASE. +`[:KNOWS]` is a *relationship* with the *label* `KNOWS`. It's a *label* as the node's label. It uses UPPER\_SNAKE\_CASE. `[k:KNOWS]` - the same *relationship*, referred by the variable `k`, reusable in the query, but it's not necessary. From 69f7f5d856a1073be6d5adbad811483c4d0ba4f7 Mon Sep 17 00:00:00 2001 From: Albert <87888006+MustCodeAl@users.noreply.github.com> Date: Tue, 14 May 2024 21:34:54 -0500 Subject: [PATCH 223/392] [typescript/en] multiple types (#4803) --- typescript.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/typescript.html.markdown b/typescript.html.markdown index f8e78d44..24d1db10 100644 --- a/typescript.html.markdown +++ b/typescript.html.markdown @@ -72,6 +72,11 @@ let f4 = (i: number) => { return i * i; } // keyword needed let f5 = (i: number) => i * i; +// Functions can accept more than one type +function f6(i: string | number): void { + console.log("The value was " + i); +} + // Interfaces are structural, anything that has the properties is compliant with // the interface interface Person { From 250a508cbf5cf17404d1b010c508333c417b708f Mon Sep 17 00:00:00 2001 From: Sean Liao Date: Wed, 15 May 2024 03:52:23 +0100 Subject: [PATCH 224/392] [go/en] update for modern go (#4678) --- go.html.markdown | 65 ++++++++++++++++++++++++++---------------------- 1 file changed, 35 insertions(+), 30 deletions(-) diff --git a/go.html.markdown b/go.html.markdown index 59ba2e4f..b93cbc61 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -32,11 +32,11 @@ Go comes with a good standard library and a sizeable community. /* Multi- line comment */ - /* A build tag is a line comment starting with // +build + /* A build tag is a line comment starting with //go:build and can be executed by go build -tags="foo bar" command. Build tags are placed before the package clause near or at the top of the file followed by a blank line or other line comments. */ -// +build prod, dev, test +//go:build prod || dev || test // A package clause starts every source file. // main is a special name declaring an executable rather than a library. @@ -44,12 +44,13 @@ package main // Import declaration declares library packages referenced in this file. import ( - "fmt" // A package in the Go standard library. - "io/ioutil" // Implements some I/O utility functions. - m "math" // Math library with local alias m. - "net/http" // Yes, a web server! - "os" // OS functions like working with the file system - "strconv" // String conversions. + "fmt" // A package in the Go standard library. + "io" // Implements some I/O utility functions. + m "math" // Math library with local alias m. + "net/http" // Yes, a web server! + _ "net/http/pprof" // Profiling library imported only for side effects + "os" // OS functions like working with the file system + "strconv" // String conversions. ) // A function definition. Main is special. It is the entry point for the @@ -106,13 +107,13 @@ can include line breaks.` // Same string type. n := byte('\n') // byte is an alias for uint8. // Arrays have size fixed at compile time. - var a4 [4]int // An array of 4 ints, initialized to all 0. + var a4 [4]int // An array of 4 ints, initialized to all 0. a5 := [...]int{3, 1, 5, 10, 100} // An array initialized with a fixed size of five // elements, with values 3, 1, 5, 10, and 100. // Arrays have value semantics. - a4_cpy := a4 // a4_cpy is a copy of a4, two separate instances. - a4_cpy[0] = 25 // Only a4_cpy is changed, a4 stays the same. + a4_cpy := a4 // a4_cpy is a copy of a4, two separate instances. + a4_cpy[0] = 25 // Only a4_cpy is changed, a4 stays the same. fmt.Println(a4_cpy[0] == a4[0]) // false // Slices have dynamic size. Arrays and slices each have advantages @@ -123,24 +124,24 @@ can include line breaks.` // Same string type. bs := []byte("a slice") // Type conversion syntax. // Slices (as well as maps and channels) have reference semantics. - s3_cpy := s3 // Both variables point to the same instance. - s3_cpy[0] = 0 // Which means both are updated. - fmt.Println(s3_cpy[0] == s3[0]) // true + s3_cpy := s3 // Both variables point to the same instance. + s3_cpy[0] = 0 // Which means both are updated. + fmt.Println(s3_cpy[0] == s3[0]) // true // Because they are dynamic, slices can be appended to on-demand. // To append elements to a slice, the built-in append() function is used. // First argument is a slice to which we are appending. Commonly, // the slice variable is updated in place, as in example below. - s := []int{1, 2, 3} // Result is a slice of length 3. - s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] + s := []int{1, 2, 3} // Result is a slice of length 3. + s = append(s, 4, 5, 6) // Added 3 elements. Slice now has length of 6. + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6] // To append another slice, instead of list of atomic elements we can // pass a reference to a slice or a slice literal like this, with a // trailing ellipsis, meaning take a slice and unpack its elements, // appending them to slice s. s = append(s, []int{7, 8, 9}...) // Second argument is a slice literal. - fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] + fmt.Println(s) // Updated slice is now [1 2 3 4 5 6 7 8 9] p, q := learnMemory() // Declares p, q to be type pointer to int. fmt.Println(*p, *q) // * follows a pointer. This prints two ints. @@ -160,7 +161,7 @@ can include line breaks.` // Same string type. file, _ := os.Create("output.txt") fmt.Fprint(file, "This is how you write to a file, by the way") file.Close() - + // Output of course counts as using a variable. fmt.Println(s, c, a4, s3, d2, m) @@ -179,7 +180,7 @@ func learnNamedReturns(x, y int) (z int) { // Go is fully garbage collected. It has pointers but no pointer arithmetic. // You can make a mistake with a nil pointer, but not by incrementing a pointer. -// Unlike in C/Cpp taking and returning an address of a local variable is also safe. +// Unlike in C/Cpp taking and returning an address of a local variable is also safe. func learnMemory() (p, q *int) { // Named return values p and q have type pointer to int. p = new(int) // Built-in function new allocates memory. @@ -190,7 +191,7 @@ func learnMemory() (p, q *int) { return &s[3], &r // & takes the address of an object. } -// Use the aliased math library (see imports, above) +// Use the aliased math library (see imports, above) func expensiveComputation() float64 { return m.Exp(10) } @@ -214,8 +215,8 @@ func learnFlowControl() { case 42: // Cases don't "fall through". /* - There is a `fallthrough` keyword however, see: - https://github.com/golang/go/wiki/Switch#fall-through + There is a `fallthrough` keyword however, see: + https://github.com/golang/go/wiki/Switch#fall-through */ case 43: // Unreached. @@ -355,7 +356,7 @@ func learnInterfaces() { } // Functions can have variadic parameters. -func learnVariadicParams(myStrings ...interface{}) { +func learnVariadicParams(myStrings ...any) { // any is an alias for interface{} // Iterate each value of the variadic. // The underscore here is ignoring the index argument of the array. for _, param := range myStrings { @@ -428,7 +429,6 @@ func learnConcurrency() { // A single function from package http starts a web server. func learnWebProgramming() { - // First parameter of ListenAndServe is TCP address to listen to. // Second parameter is an interface, specifically http.Handler. go func() { @@ -449,7 +449,7 @@ func requestServer() { resp, err := http.Get("http://localhost:8080") fmt.Println(err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) fmt.Printf("\nWebserver said: `%s`", string(body)) } ``` @@ -457,20 +457,23 @@ func requestServer() { ## Further Reading The root of all things Go is the [official Go web site](https://go.dev/). -There you can follow the tutorial, play interactively, and read lots. +There you can follow the [tutorial](https://go.dev/tour/), play interactively, and read lots. Aside from a tour, [the docs](https://go.dev/doc/) contain information on how to write clean and effective Go code, package and command docs, and release history. The [Go language specification](https://go.dev/ref/spec) itself is highly recommended. It's easy to read and amazingly short (as language definitions go these days.) -You can play around with the code on [Go playground](https://go.dev/play/p/tnWMjr16Mm). Try to change it and run it from your browser! Note that you can use [https://go.dev/play/](https://go.dev/play/) as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. +You can play around with the code on [Go playground](https://go.dev/play/p/Y96bRpJWzjr). +Try to change it and run it from your browser! +Note that you can use [https://go.dev/play/](https://go.dev/play/) +as a [REPL](https://en.wikipedia.org/wiki/Read-eval-print_loop) to test things and code in your browser, without even installing Go. On the reading list for students of Go is the [source code to the standard library](https://go.dev/src/). Comprehensively documented, it demonstrates the best of readable and understandable Go, Go style, and Go idioms. Or you can click on a function name in [the -documentation](https://go.dev/pkg/) and the source code comes up! +documentation](https://pkg.go.dev/std) and the source code comes up! Another great resource to learn Go is [Go by example](https://gobyexample.com/). @@ -480,4 +483,6 @@ There are many excellent conference talks and video tutorials on Go available on - [Golang University 201](https://www.youtube.com/playlist?list=PLEcwzBXTPUE_5m_JaMXmGEFgduH8EsuTs) steps it up a notch, explaining important techniques like testing, web services, and APIs - [Golang University 301](https://www.youtube.com/playlist?list=PLEcwzBXTPUE8KvXRFmmfPEUmKoy9LfmAf) dives into more advanced topics like the Go scheduler, implementation of maps and channels, and optimisation techniques -Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information. +Go Mobile adds support for mobile platforms (Android and iOS). +You can write all-Go native mobile apps or write a library that contains bindings from a Go package, +which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information. From 5c518f4a316215d49c3efb1bed7846d44bf21b5b Mon Sep 17 00:00:00 2001 From: Kir Malev Date: Thu, 16 May 2024 07:25:02 +0400 Subject: [PATCH 225/392] [dart/en] Updated exercise 11 (#3880) --- dart.html.markdown | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/dart.html.markdown b/dart.html.markdown index e6594fc5..69b1925b 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -254,25 +254,29 @@ example10() { /// `int` and `double` are children of type `num` example11() { var i = 1 + 320, d = 3.2 + 0.01; + final num myFinalNumDouble = 2.2; + final num myFinalNumInt = 2; + final int myFinalInt = 1; + final double myFinalDouble = 0.1; num myNumDouble = 2.2; num myNumInt = 2; int myInt = 1; double myDouble = 0; // Dart will add decimal prefix, becomes 0.0; - myNumDouble = myInt; // valid - myNumDouble = myDouble; //valid - myNumDouble = myNumInt; //valid + myNumDouble = myFinalInt; // valid + myNumDouble = myFinalDouble; // valid + myNumDouble = myFinalNumInt; // valid - myNumInt = myInt; // valid - myNumInt = myDouble; // valid - myNumInt = myNumDouble; // valid + myNumInt = myFinalInt; // valid + myNumInt = myFinalDouble; // valid + myNumInt = myFinalNumDouble; // valid - myInt = myNumDouble; //Error - myInt = myDouble; //Error - myInt = myNumInt; //valid + myInt = myNumDouble; // error + myInt = myFinalDouble; // error + myInt = myFinalNumInt; // valid - myDouble = myInt; //error - myDouble = myNumInt; //valid - myDouble = myNumDouble; //valid + myDouble = myFinalInt; // error + myDouble = myFinalNumInt; // error + myDouble = myFinalNumDouble; // valid print("Example11 int ${i}"); print("Example11 double ${d}"); From ef5bdf1c52c601aa32ec0b1ba3175171876ef6ab Mon Sep 17 00:00:00 2001 From: Kir Malev Date: Thu, 16 May 2024 07:25:14 +0400 Subject: [PATCH 226/392] [dart/en] Updated example14 (#3881) --- dart.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/dart.html.markdown b/dart.html.markdown index 69b1925b..4d2bf5ac 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -312,15 +312,15 @@ example14() { if (a) { print("true, a is $a"); } - a = null; + a = false; if (a) { - print("true, a is $a"); + print("true, a is $a"); } else { print("false, a is $a"); /// runs here } - /// dynamic typed null can be convert to bool - var b;/// b is dynamic type + /// dynamic typed null can not be convert to bool + var b; /// b is dynamic type b = "abc"; try { if (b) { @@ -331,17 +331,17 @@ example14() { } catch (e) { print("error, b is $b"); /// this could be run but got error } - b = null; - if (b) { + b = null; + if (b) { /// Failed assertion: boolean expression must not be null) print("true, b is $b"); } else { - print("false, b is $b"); /// runs here + print("false, b is $b"); } /// statically typed null can not be convert to bool var c = "abc"; c = null; - /// complie failed + /// compilation failed /// if (c) { /// print("true, c is $c"); /// } else { From 9842c8859b03e34f0ba09a3e6885218d67a3862d Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 16 May 2024 03:23:02 -0600 Subject: [PATCH 227/392] Correct URLs --- ...arnsmallbasic-es.html.markdown => smallbasic-es.html.markdown} | 0 ...nvisualbasic-ru.html.markdown => visualbasic-ru.html.markdown} | 0 ...ure-macro-cn.html.markdown => clojure-macros-cn.html.markdown} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename es-es/{learnsmallbasic-es.html.markdown => smallbasic-es.html.markdown} (100%) rename ru-ru/{learnvisualbasic-ru.html.markdown => visualbasic-ru.html.markdown} (100%) rename zh-cn/{clojure-macro-cn.html.markdown => clojure-macros-cn.html.markdown} (100%) diff --git a/es-es/learnsmallbasic-es.html.markdown b/es-es/smallbasic-es.html.markdown similarity index 100% rename from es-es/learnsmallbasic-es.html.markdown rename to es-es/smallbasic-es.html.markdown diff --git a/ru-ru/learnvisualbasic-ru.html.markdown b/ru-ru/visualbasic-ru.html.markdown similarity index 100% rename from ru-ru/learnvisualbasic-ru.html.markdown rename to ru-ru/visualbasic-ru.html.markdown diff --git a/zh-cn/clojure-macro-cn.html.markdown b/zh-cn/clojure-macros-cn.html.markdown similarity index 100% rename from zh-cn/clojure-macro-cn.html.markdown rename to zh-cn/clojure-macros-cn.html.markdown From c0d28ff31bb334202edf1e30fd9d1fbaf0dfb3f8 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 16 May 2024 03:27:45 -0600 Subject: [PATCH 228/392] [c++/hi-in] add language code --- hi-in/c++-hi.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/hi-in/c++-hi.html.markdown b/hi-in/c++-hi.html.markdown index 7fd90878..504f3fd4 100644 --- a/hi-in/c++-hi.html.markdown +++ b/hi-in/c++-hi.html.markdown @@ -10,6 +10,7 @@ contributors: - ["Jatin Dhankhar", "https://github.com/jatindhankhar"] translators: - ["Jishan Shaikh", "https://github.com/jishanshaikh4"] +lang: hi-in --- C++ एक सिस्टम प्रोग्रामिंग लैंग्वेज है जो, From 6c9d2170cf9d39eb2393951482307d7d6b8be70c Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 16 May 2024 03:30:39 -0600 Subject: [PATCH 229/392] [html/fa-ir] add lang code --- fa-ir/html-fa.html.markdown | 2 ++ 1 file changed, 2 insertions(+) diff --git a/fa-ir/html-fa.html.markdown b/fa-ir/html-fa.html.markdown index cac945f0..1ac49444 100644 --- a/fa-ir/html-fa.html.markdown +++ b/fa-ir/html-fa.html.markdown @@ -5,7 +5,9 @@ contributors: - ["Christophe THOMAS", "https://github.com/WinChris"] translators: - ["Hiva Zarei", "https://github.com/hivazarei"] +lang: fa-ir --- +

    HTML مخفف كلمه ی Hyper Text Markup Language می باشد.

    یك زبان نشانه گیری است كه با استفاده از كد نویسی می توانیم متن و داده های مختلف را با استفاده از آن نمایش دهیم.

    From ac928285e1158d6ecd07f15fd7d7203cc5efc25a Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Thu, 16 May 2024 07:08:35 -0600 Subject: [PATCH 230/392] [bqn/en] fix frontmatter --- bqn.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/bqn.html.markdown b/bqn.html.markdown index 58c2f787..928b3a54 100644 --- a/bqn.html.markdown +++ b/bqn.html.markdown @@ -1,9 +1,8 @@ --- -language: bqn +language: BQN filename: learnbqn.bqn contributors: - ["Raghu Ranganathan", "https://github.com/razetime"] -translators: --- BQN is a modern array language (similar to APL) that aims to eliminate burdensome aspects of the APL tradition. From 6cb3dc06a91ff7bf5d8e22c3baee4a92c0ea7790 Mon Sep 17 00:00:00 2001 From: Mario Stabile <66466058+mariostabile1@users.noreply.github.com> Date: Thu, 16 May 2024 22:06:15 +0200 Subject: [PATCH 231/392] [fish/it] Translate (#4916) --- it-it/fish-it.html.markdown | 343 ++++++++++++++++++++++++++++++++++++ 1 file changed, 343 insertions(+) create mode 100644 it-it/fish-it.html.markdown diff --git a/it-it/fish-it.html.markdown b/it-it/fish-it.html.markdown new file mode 100644 index 00000000..edf35b4b --- /dev/null +++ b/it-it/fish-it.html.markdown @@ -0,0 +1,343 @@ +--- +category: tool +tool: fish +contributors: + - ["MySurmise", "https://github.com/MySurmise"] + - ["Geo Maciolek", "https://github.com/GeoffMaciolek"] +translators: + - ["Mario Stabile", "https://github.com/mariostabile1"] +filename: learnfish-it.fish +lang: it-it +--- + +Fish (**f**riendly **i**nteractive **sh**ell) è il nome di una shell esotica. Si tratta di una shell la cui sintassi non deriva né dalla Bourne-Shell né dalla C-Shell. + +Il vantaggio di fish è che molte caratteristiche che si desiderano in una shell moderna sono implementate out-of-the-box (già pronte), quindi non è necessario installare software aggiuntivi come zsh e oh-my-zsh. + +Esempi di queste caratteristiche sono i suggerimenti automatici, i colori a 24 bit, il completamento delle pagine man (cioè fish analizza automaticamente le pagine man e suggerisce opzioni aggiuntive per i comandi) o la possibilità di modificare le impostazioni attraverso una pagina web (quando è installata un'interfaccia grafica). + +È stato rilasciato nel Febbraio 2005. + +- [Leggi di più](https://fishshell.com/docs/current/language.html) +- [Guida all'installazione](https://github.com/fish-shell/fish-shell#getting-fish) + +## Guida + +Verifica di avere l'ultima versione di fish shell, Questa guida è stata fatta con la 3.3.0. Per farlo, scrivi: + +``` +> fish -v +``` + +Per avviare la shell di fish, scrivi: + +``` +> fish +``` + +per uscire, scrivi: + +``` +> exit +``` + +o premi Ctrl + D + +Ora, sin dall'inizio, c'è una cosa fastidiosa in fish. Il messaggio di benvenuto. A chi importa, giusto? Quando si avvia la shell, basta scrivere: + +``` +> set -U fish_greeting "" +``` + +Se volessi eseguire un singolo comando in bash, senza passare a quella shell, puoi scrivere: + +``` +> bash -c 'echo "Questo testo sarà stampato sul terminale"' +``` + +Su fish, si possono usare sia le singole che le doppie virgolette. +Il carattere di escape è uno `\` (slash) + +Puoi cambiare le configurazioni di fish modificando il file di config + +``` +> vim ~/.config/fish/config.fish +``` + +o aprendo l'interfaccia web: + +``` +> fish_config +``` + +Aggiungere qualcosa alla variabile PATH di fish è semplice: + +``` +> fish_path_add ~/cowsay +``` + +Questo puoi farlo con bash, eh? No, devi sempre cercarlo... Così è facile! + +Ma c'è di più. La maggior parte dei comandi specifici per fish iniziano, hai indovinato, con 'fish'. Basta scrivere `fish` e premere TAB. Ed ecco una delle tante funzioni interessanti di fish: L'autocompletamento che **funziona.** +Ora puoi navigare con TAB, Shift + TAB e le frecce . + +Per avere aiuto, chiama il tuo psichiatra di fiducia oppure scrivi `man`. Ti mostrerà il manuale per quel comando, per esempio: + +``` +> man set +``` + +Se finalmente hai provato fish, potrai vedere in questa shell qualcosa di diverso, il che è molto figo. Ogni cosa ha colori fantastici, se scrivi qualcosa di sbagliato viene segnato in rosso, senza nemmeno eseguirlo, se si mette qualcosa tra virgolette, si vede dove finisce e perchè quella citazione non funziona, perchè c'è un'altro segno di citazione nella citazione in posizione 26. + +fish ha ancora altre cose interessanti, come le wildcards (o carattere jolly). +Per esempio, scrivi: + +``` +> ls *.fish +``` + +Questo elencherà ogni file .fish nella directory corrente. + +Puoi avere multiple wildcards per comando o anche una wildcard ricorsiva, `**`, il che significa che includerà tutti i sotto-file e le sotto-directory presenti nella directory corrente. +Per esempio, il seguente comando restituirà (in questo caso): + +``` +> ls ~/images/**.jpg + +~/images/nudini/pewdiepie.jpg +~/images/nudini/peppa.jpg +~/images/screenshots/2020-42-69.jpg +~/images/omegalul.jpg +``` + +Ovviamente, puoi anche inviare l'output di un comando ad un'altro con una pipe + +``` +>echo . Qui ci sarà un testo | grep [udense] +``` + +scrivere su un file: + +``` +>echo Questo\ é\ un\ testo > file.txt +``` + +(notato il carattere di escape?) +Aggiungere a un file: + +``` +>echo Questa\ è\ una\ riga >> file.txt +>echo Questa\ è\ un'altra\ riga >> file.txt +``` + +Per l'autompletamento, basta premere sempre TAB. Ti sorprenderà quante cose conosce fish + +Per usare le variabili, basta scrivere `$VAR`, come in bash. + +``` +> echo "La mia home è $HOME" +La mia home è /home/mioutente +``` + +Qui arriva la differenza tra le virgolette singole e doppie. Se usi una variabile dentro singole virgolette, non verrà sostituita. + +``` +> echo 'La mia home è $HOME' +La mia home è $HOME +``` + +Più info sulle variabili successivamente. + +Per eseguire due comandi, separali con `;` + +``` +> echo Lol; echo questo è divertente +``` + +Lo status dell'ultimo comando eseguito è contenuto in `$status` + +Puoi usare && per due comandi che dipendolo l'uno dall'altro. + +``` +> set var lol && echo $var +``` + +Puoi anche usare `and` che esegue solo se il comando precedente ha avuto successo, `or` che esegue solo se il comando precedente fallisce, e `not` +che inverte lo stato di output del comando. + +Per esempio: + +``` +> if not echo Testo testo, bla bla bla + echo Altro testo, bla bla + end +``` + +(Ovviamente tutto questo lo puoi fare nella shell) + +--- + +Adesso cominciamo con la parte di scripting di fish. + +Come per ogni shell, puoi non solo eseguire comandi nella shell, ma anche da file, salvati come file `.fish`. +(Puoi anche eseguire file `.sh` con la sintassi di fish, ma io uso sempre l'estensione `.fish` per la sintassi di fish per distinguerla dai file in bash) + +```fish +# Questo è un commento in fish. +# +# Se esegui un file senza specificare un interprete, +# cioè il programma che fa girare il tuo script, è necessario per dire alla shell, +# dove l'interprete è posizionato. +# In fish basta aggiungere questo commento nella prima linea del tuo script: + +#!/bin/fish + +# Quando esegui lo script tramite, per esempio, fish /path/to/script.fish +# non è necessario, perchè hai specificato fish come interprete + +# Cominciamo con le variabili. +# per l'uso interno a un programma, puoi usare la sintassi +set nome = 'La mia variabile' + +# Utilizzo... +set -x nome valore +# per esportare, o +set -e nome +# per Eliminare + +# una variabile settata con uno spazio non viene inviata come due argomenti, ma come uno solo, come ci si aspetterebbe. +set directoryBella 'Directory Bella' +mkdir $directoryBella + +# Questo creerà una sola directory, come ci si aspetterebbe, non due come in bash... +# chi vorrebbe una roba del genere? è UnA FeAtUrE n0n Un BuG... + +# puoi anche avere liste in forma di variabili. Questo ha senso, perchè se volessi una variabile che crei due directory, basta dare a mkdir un elenco di nomi di directory. + +# puoi anche contare le istanze nella lista con: +count $PATH + +# Non solo è tutto fantastico, ma in fish, tutto è anche una lista. +# $PWD per esempio è una lista di lunghezza 1. +# Per fare una lista, basta dare al comando set più argomenti: +set list argomento1 argomento2 argomento3 + +# in questo modo puoi anche inserire qualcosa in una variabile pre-esistente:: +set PATH $PATH ~/cowsay/ + +# Ma, come precedentemente menzionato, abbiamo anche un'altro modo più semplice per farlo specialmente in fish. +# Come per ogni Array/Lista, puoi anche accedergli con +$listavar[2] + +# ci sono anche gli intervalli +$listavar[1..5] + +# puoi anche usare numeri negativi +$listavar[-1] +# accesso all'ultimo elemento. + +# Quando combini due liste di variabili puoi anche usare un bel prodotto cartesiano:: +set a 1 2 3 +set 1 a b c +echo $a$1 +# Restituirà : 1a 2a 3a 1b 2b 3b 1c 2c 3c + +# Naturalmente, se li si separa, saranno visti come due argomenti separati e li stamperà uno dopo l'altro. QUESTO è il comportamento che ci si aspetta da @bash. + +# Ci sono anche altre cose utili, come la sotituzione di comandi. Per esempio, quando vuoi che ti sia restituito l'output di due comandi in una sola riga. In bash lo faresti in questo modo +echo "`ls` è in $PWD" +# oppure +echo "$(ls) è in $PWD" + +# secondo me, non è necessario. Scrivo sempre l'apostrogo sbagliato. Perchè non usare semplicemente le parentesi, come in fish? +echo (ls) è in $PWD + +# Yep, è facile. E grazie all'highlighting di fish lo puoi vedere istantaneamente, se lo scrivi correttamente. + +# E, come ci si aspetterebbe, a mio avviso, i comandi non funzionano tra virgolette. Voglio dire, perchè bash? Ok adesso la smetto. Ma in fish, basta fare: +echo (ls)" è in $PWD" +# oppure +set miavar "Il file"(ls -a)" è nella directory $PWD" +# creerà una lista con la stringa e tutti i file. Prova. Non è una figata? + +# E per semparare le variabili in diversi argomenti, basta mettere uno spazio: + +set miavar "I file" (ls -a) " sono nella directory $PWD" + +# Ci sono anche if, else if, else +if grep fish /etc/shells + echo Trovato fish +else if grep bash /etc/shells + echo Trovato bash +else + echo Non ho trovato niente +end + +# Risulta un pò strano confrontare due cose con un solo segno =, ovviamente perchè non en abbiamo bisogno per settare le variabili, ma comunque... e la parola chiave "test": +if test $var = "test" + echo si +else + echo no +end + +# Naturalmente, ci sono anche gli switch case +switch $OS +case Linux + echo "Sei un grande" +case Windows + echo "Potresti provare fish su WSL" +case MacOS + echo "Su MacOS c'è fish!" +case '*' + echo "quale OS è $OS, per favore?" +end + + +# le funzioni in fish prendono gli argomenti attraverso la variabile $argv. La sintassi è la seguente: + +function stampa + echo $argv +end + +# Ci sono anche gli eventi, come l'evento "fish_exit" (Cosa farà mai, hmm?). + +# Puoi usarli aggiungendoli alle definizioni di funzione: + +function in_uscita --on-event fish_exit + echo fish si sta chiuendo +end + +# trova gli eventi con il comando +functions --handlers + + +# Puoi usare il comando functions per approfondire, beh, le funzioni. +# Per esempio puoi far stampare il codice sorgente di ogni funzione: +functions cd +functions print +# oppure ottenere il nome di ogni funzione: +functions + +# Ci sono i cicli while, ovviamente +while test $var = lol + echo lol +end + +# Cicli for (con le wildcards, sono ancora meglio): +for immagine in *.jpg + echo $immagine +end + +# c'è un equivalente di range(0, 5) in Python, quindi puoi anche fare il classico ciclo for con i numeri: + +set files (ls) +for numeri in (seq 10) + echo "$files[$numeri] è il file numero $numeri" +end + +# Bello! + +# L'equivalente di bashrc non è fishrc, ma il già citato file config.fish in ~/.config/fish/ +# Per aggiungere una funzione a fish, però, occorre creare un semplice file .fish in quell directory. Non incollare la funzione nel file config.fish. È brutto. +# Se avete altro da dire, aggiugete pure, ma queste sono le basi più importanti. +``` From 4f18651cb217909ec6cfa674b3be54e7d220735e Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 17 May 2024 00:07:49 -0600 Subject: [PATCH 232/392] Remove unnecessary filenames --- tr-tr/dynamic-programming-tr.html.markdown | 1 - zh-cn/dynamic-programming-cn.html.markdown | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/tr-tr/dynamic-programming-tr.html.markdown b/tr-tr/dynamic-programming-tr.html.markdown index 07ee46bf..573d9e0f 100644 --- a/tr-tr/dynamic-programming-tr.html.markdown +++ b/tr-tr/dynamic-programming-tr.html.markdown @@ -1,6 +1,5 @@ --- language: Dynamic Programming -filename: dynamic-tr.txt contributors: - ["Akashdeep Goel", "https://github.com/akashdeepgoel"] translators: diff --git a/zh-cn/dynamic-programming-cn.html.markdown b/zh-cn/dynamic-programming-cn.html.markdown index 7864c22a..6671b556 100644 --- a/zh-cn/dynamic-programming-cn.html.markdown +++ b/zh-cn/dynamic-programming-cn.html.markdown @@ -3,10 +3,9 @@ category: Algorithms & Data Structures name: Dynamic Programming contributors: - ["Akashdeep Goel", "http://github.com/akashdeepgoel"] -filename: dynamic-programming-cn.html.markdown -lang: zh-cn translators: - ["EtaoinWu", "https://github.com/EtaoinWu"] +lang: zh-cn --- # 动态规划 From 72d4fadaf0b625172ee3d4954b4d891262bc1ce0 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 17 May 2024 00:10:34 -0600 Subject: [PATCH 233/392] [inform7/en] syntax highlighting --- inform7.html.markdown | 51 +++++++++++++++++++++---------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/inform7.html.markdown b/inform7.html.markdown index 7f1da0e0..53880d4c 100644 --- a/inform7.html.markdown +++ b/inform7.html.markdown @@ -4,20 +4,19 @@ contributors: - ["Hyphz", "http://github.com/hyphz/"] filename: LearnInform.Inform --- + Inform 7 is a natural language based language created by Graham Nelson and Emily Short for writing text adventures, but also potentially usable for other text based applications, especially data backed ones. -``` -"LearnInform" by Hyphz - +```inform7 [This is a comment.] [Inform 7 is a language designed for building text adventures. -It can be used for other purposes too, although the default +It can be used for other purposes too, although the default library builds a text adventure. Inform 7 is object oriented.] [This creates a class by subclassing. "Value" is the universal subclass, but "object" is the most basic that behaves like an OO object.] -A datablock is a kind of object. +A datablock is a kind of object. [Classes can have properties.] A datablock can be broken. [This creates a boolean property.] @@ -36,18 +35,18 @@ The name of Block1 is "Block One." [Functions and procedures are defined as "phrases".] To do the thing everyone does with their first program: say "Hello World.". [Full stop indicates the end, indent indicates the scope.] - + To dump (the block - a datablock): [That's how we create a parameter.] say the sequence number of the block; say the name of the block; if the block is broken, say "(Broken)". - + To toggle (the block - a datablock): if the block is broken: [Conditional.] now the block is not broken; [Updating a property.] else: now the block is broken. - + [Multiple parameters.] To fix (the broken block - a datablock) using (the repair block - a datablock): if the broken block is not broken, stop; [Comma for a non indented single command.] @@ -56,8 +55,8 @@ To fix (the broken block - a datablock) using (the repair block - a datablock): now the broken block is not broken. [Because of its text adventure origins, Inform 7 doesn't generally allow objects -to be created dynamically, although there's a language extension that enables it.] -Block2 is a datablock. +to be created dynamically, although there's a language extension that enables it.] +Block2 is a datablock. Block2 is broken. The sequence number of Block2 is 2. The name of Block2 is "Block two." @@ -66,8 +65,8 @@ To demonstrate calling a phrase with two parameters: Let the second block be block2; [Local pointer variable.] fix the second block using Block1; say the sequence number of the second block. [1.] - -[Lists.] + +[Lists.] To show how to use list types: let the list be a list of datablocks; add Block1 to the list; @@ -84,7 +83,7 @@ To show how to use list types: dump X; ["1 Block two."] remove X from the list; say the list. [Block1] - + [Here's how we define a function and do arithmetic.] To decide which number is the sum of all numbers up to (X - a number) (this is summing up): @@ -92,7 +91,7 @@ To decide which number is the sum of all numbers up to (X - a number) (this is s repeat with the current number running from 1 to X: now the total so far is the total so far + the current number; decide on the total so far. [This is the return statement.] - + [ We have higher order functions too. ] To demonstrate a higher order function: @@ -102,7 +101,7 @@ To decide which number is the result of applying (phrase - phrase A -> A) twice let b1 be phrase applied to B; let b2 be phrase applied to b1; decide on b2. - + To demonstrate defining a higher order function: let X be 5; say the result of applying summing up twice to X. @@ -112,14 +111,14 @@ To demonstrate defining a higher order function: Datablock validation rules is a datablock based rulebook. A datablock validation rule for a broken datablock: rule fails. -A datablock validation rule for a datablock (called the block): +A datablock validation rule for a datablock (called the block): dump the block; rule succeeds. - + To demonstrate invoking a rulebook: follow datablock validation rules for Block1; follow datablock validation rules for Block2. - + [ Objects can also have relations, which resemble those in a relational database. ] A dog is a kind of thing. Rover is a dog. @@ -136,7 +135,7 @@ Friendship relates various people to various people. [Many-to-many.] The verb to own means the property ownership relation. The verb to be the guide dog of means the guide dog ownership relation. -The verb to be guided by means the reversed guide dog ownership relation. +The verb to be guided by means the reversed guide dog ownership relation. The verb to be friends with means the friendship relation. Edward is a person. A person can be blind. Edward is blind. @@ -156,18 +155,18 @@ The verb to be helpful to means the helpfulness relation. To demonstrate using a procedural relation: repeat with the helper running through people that are helpful to Edward: say the helper. - + [ Interface to the text adventure harness to allow the above code to be run. ] -Tutorial room is a room. +Tutorial room is a room. "A rather strange room full of buttons. Push them to run the exercises, or turn on the robot to run them all." -A button is a kind of thing. A button is fixed in place. +A button is a kind of thing. A button is fixed in place. -The red button is a button in tutorial room. +The red button is a button in tutorial room. Instead of pushing the red button, do the thing everyone does with their first program. -The green button is a button in tutorial room. +The green button is a button in tutorial room. Instead of pushing the green button, demonstrate calling a phrase with two parameters. -The blue button is a button in tutorial room. +The blue button is a button in tutorial room. Instead of pushing the blue button, show how to use list types. The cyan button is a button in tutorial room. Instead of pushing the cyan button, say the sum of all numbers up to 5. @@ -190,6 +189,6 @@ Instead of switching on the robot: try pushing button. ``` -##Ready For More? +## Ready For More? * [Inform 7](http://www.inform7.com/) From 04b39f5f4902acc4871938cc978d64d83d104d72 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 17 May 2024 00:10:51 -0600 Subject: [PATCH 234/392] [jquery/tr] fix filename --- tr-tr/jquery-tr.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tr-tr/jquery-tr.html.markdown b/tr-tr/jquery-tr.html.markdown index 4a9729e9..80fc552a 100644 --- a/tr-tr/jquery-tr.html.markdown +++ b/tr-tr/jquery-tr.html.markdown @@ -3,7 +3,7 @@ category: framework framework: jquery contributors: - ["Seçkin KÜKRER", "https://github.com/leavenha"] -filename: jquery-tr-tr.js +filename: jquery-tr.js lang: tr-tr --- From c268b08f13a9265581a6be3224af0792a587d48d Mon Sep 17 00:00:00 2001 From: JorgeLDB <28984877+JorgeLDB@users.noreply.github.com> Date: Fri, 17 May 2024 08:17:21 -0500 Subject: [PATCH 235/392] [lua/es] translate lua to spanish (#4946) --- es-es/lua.html.markdown | 442 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 442 insertions(+) create mode 100644 es-es/lua.html.markdown diff --git a/es-es/lua.html.markdown b/es-es/lua.html.markdown new file mode 100644 index 00000000..6fc997f7 --- /dev/null +++ b/es-es/lua.html.markdown @@ -0,0 +1,442 @@ +--- +language: Lua +filename: learnlua-es.lua +contributors: + - ["Tyler Neylon", "http://tylerneylon.com/"] +translators: + - ["Jorge Diaz", "https://github.com/jorgeldb"] +lang: es-es +--- + +```lua +-- Dos guiones inician un comentario de una única línea. + +--[[ + Añadir dos corchetes [ y ] lo convierten + en un comentario multi-línea +--]] + +---------------------------------------------------- +-- 1. Variables y control de flujo. +---------------------------------------------------- + +num = 42 -- Todos los números son flotantes + -- de precisión doble (64 bits). + -- Los dobles de 64 bits pueden tienen + -- 52 bits para representación de valores + -- enteros, así que no representa un + -- problema para valores menores a 52 bits. + +s = 'alternados' -- Los string son imnutables, como en Python +t = "Las comillas dobles también son válidas" +u = [[ Los corchetes dobles inician + y terminan strings de + múltiples líneas. ]] +t = nil -- Vuelve a t indefinido. Lua hace uso de Garbage Collector. + +-- Los bloques se denotan con palabras claves como "do" o "end" + +-- Ciclo while (do/end) +while num < 50 do + num = num + 1 -- No existen operadores como ++ o += +end + +-- Sentencia if (then/end) +if num > 40 then + print('mayor a 40') +elseif s ~= 'alternados' then -- ~= significa "diferente de" + -- == significa "igual a". Puede usarse en strings, igual que en Python + + io.write('no mayor a 40\n') -- Por defecto, escribe + -- a la salida estándar stdout +else + -- Las variables son globales por defecto + estoEsGlobal = 5 -- Es común utilizar Camel Case. + + -- Se usa la palabra clave 'local' para declarar variables locales + local line = io.read() -- Lee la próxima línea de la entrada + -- estándar stdin + + -- Para concatenar strings se usa el operador ".." + print('Viene el invierno, ' .. line) +end + +-- Las variables indefinidas retornan nil +-- Esto no es un error +foo = unaVariableDesconocida -- Ahora foo = nil. + +unValorBooleano = false + +-- Sólo 'nil' y 'false' son valores falsos. ¡0 y "" son verdaderos! +if not unValorBooleano then print('era falso') end + +-- 'or' y 'and' son operadores corto-circuito +-- Esto es similar al operador ternario en C/JavaScript +ans = unValorBooleano and 'sí' or 'no' --> 'no' + +karlSum = 0 +-- El rango es inclusivo, esto empieza en 1 y termina en 100 +for i = 1, 100 do karlSum = karlSum + i +end + +-- Se puede usar "100, 1, -1" con paso negativo como rango decremental +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end + +-- En general, los rangos son: inicio, fin[, paso]. + +-- Otra manera de hacer bucle, similar a una sentencia do/while en C/Java +repeat + print('el camino del futuro') + num = num - 1 +until num == 0 + + +---------------------------------------------------- +-- 2. Funciones. +---------------------------------------------------- + +-- Las funciones se declaran con "function" +function fib(n) + if n < 2 then return 1 end + return fib(n - 2) + fib(n - 1) -- ¡Pueden ser recursivas! +end + +-- Las clausuras y funciones anónimas están permitidas: +function adder(x) + -- La función retornada es creada al invocar "caller" + -- y recuerda el valor de x. + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 + +-- Los retornos, llamados de función y asignaciones +-- admiten listas que pueden ser diferentes en +-- tamaño. +-- Los receptores sin valor asociado son nil. +-- Los valores sin receptores son descartados. + +x, y, z = 1, 2, 3, 4 +-- Ahora, x = 1, y = 2, z = 3. El 4 es descartado. + +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end + +x, y = bar('zaphod') --> Esto imprime "zaphod nil nil" +-- Ahora x = 4, y = 8, y los valores 15, 16, 23 y 42 son descartados. + +-- Las funciones son de primera clase, pueden ser globales o locales: +-- Estas 2 líneas hacen lo mismo: +function f(x) return x * x end +f = function (x) return x * x end + +-- Al igual que estas 2 líneas: +local function g(x) return math.sin(x) end +local g; g = function (x) return math.sin(x) end +-- La declaración 'local g' hace que las autorreferencias de g sean válidas + +-- Por cierto, las funciones trigonométricas trabajan en radianes. + +-- Los llamados de funciones con un único string no requieren paréntesis. +-- Estas 2 líneas de código hacen lo mismo: +print 'hello' +print('hello') + + +---------------------------------------------------- +-- 3. Tablas. +---------------------------------------------------- + +-- Las tablas son la única estructura de datos compuesta: +-- Son arreglos asociativos. +-- De manera similar a los arreglos de PHP u objetos de JS, +-- son diccionarios de búsqueda de hash que también pueden +-- ser usados como listas. + +-- Usando tablas como diccionarios / mapas: + +-- Los literales de diccionarios usan strings como llaves por defecto: +t = {key1 = 'value1', key2 = false} + +-- Se puede acceder a 'key1' usando corchetes '[' y ']': +print(t['key1']) -- => 'value1' + +-- Las llaves tipo string pueden usar notación de punto como JS: +print(t.key1) -- Imprime 'value1'. +t.newKey = {} -- Añade un nuevo par llave/valor +t.key2 = nil -- Elimina key2 de la tabla + +-- Cualquier literal no nulo puede ser una llave: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- imprime "tau" + +-- La correspondencia de llave es por valor para números +-- y strings, pero es por identidad para tablas. +a = u['@!#'] -- 'a' tiene el valor 'qbert' +b = u[{}] -- 'b' tiene valor nil +-- 'b' es nil debido a que la búsqueda falló. Esta +-- búsqueda falla porque la llave que usamos es un +-- objeto diferente al que usamos para crear la llave +-- original. Los números y strings son llaves más portables +-- para este propósito. + +-- Una llamada de función con un único parámetro tipo tabla no +-- requiere paréntesis. +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- Imprime 'Sonmi~451'. + +for key, val in pairs(u) do -- Iteración llave/valor sobre una tabla + print(key, val) +end + +-- _G es una tabla especial para todos los globales +print(_G['_G'] == _G) -- Imprime 'true'. + +-- En este caso, la variable global t se puede consultar de esta manera +t = 6 +print(_G['t']) -- Imprime '6' + +-- Usando tablas como listas / arreglos: + +-- Las listas de literales usan implícitamente enteros como llaves +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v es el tamaño de la lista v + print(v[i]) -- Los índices inician en 1. ¡Qué locura! +end +-- No existe un tipo de dato "Lista". v es sólo una +-- tabla con llaves enteras consecutivas. + +---------------------------------------------------- +-- 3.1 Metatablas y Metamétodos. +---------------------------------------------------- + +-- Una tabla puede tener una metatabla que otorga a la tabla +-- comportamientos similares a sobrecarga de operadores. Más +-- tarde veremos cómo las metatablas soportan el comportamiento +-- de prototipos de JavaScript. + +f1 = {a = 1, b = 2} -- Representa la fracción a / b +f2 = {a = 2, b = 3} + +-- Esto puede fallar: +-- s = f1 + f2 + +metafraction = {} +function metafraction.__add(f1, f2) + sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b + return sum +end + +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) + +s = f1 + f2 -- Esto llama la función __add(f1, f2) de la metatabla + +-- f1 y f2 no tienen llave para su metatabla, a diferencia +-- de los prototipos de JS, así que se debe recuperar usando +-- getmetatable(f1). La metatabla es sólo una tabla normal con +-- llave que Lua reconoce, como "__add". + +-- Pero la siguiente línea falla ya que s no tiene metatabla. +-- t = s + s +-- Los patrones tipo clase a continuación solucionan ese problema. + +-- Una llave __index en una metatabla sobrecarga las consultas de punto: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- ¡Funciona! Gracias, metatabla. + +-- Las consultas a la tabla que fallen serán reintentadas +-- en el valor __index de la metatabla, de manera recursiva. + +-- Un valor __index también puede ser una function(tbl, key) +-- para consultas más avanzadas. + +-- Los valores de __index, __add... son llamados metamétodos. +-- Acá hay una lista completa con los metamétodos: + +-- __add(a, b) para a + b +-- __sub(a, b) para a - b +-- __mul(a, b) para a * b +-- __div(a, b) para a / b +-- __mod(a, b) para a % b +-- __pow(a, b) para a ^ b +-- __unm(a) para -a +-- __concat(a, b) para a .. b +-- __len(a) para #a +-- __eq(a, b) para a == b +-- __lt(a, b) para a < b +-- __le(a, b) para a <= b +-- __index(a, b) para a.b +-- __newindex(a, b, c) para a.b = c +-- __call(a, ...) para a(...) + +---------------------------------------------------- +-- 3.2 Tablas como clases y herencia. +---------------------------------------------------- + +-- Aunque las clases no están incorporadas, existen maneras +-- diferentes de hacerlas usando tablas y metatablas. + +-- La explicación de este ejemplo está justo debajo: + +Dog = {} -- 1. + +function Dog:new() -- 2. + newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end + +function Dog:makeSound() -- 6. + print('I say ' .. self.sound) +end + +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'I say woof' -- 8. + +-- 1. Dog actúa como una clase, aunque es sólo una tabla +-- 2. function table:fn(...) es lo mismo que +-- function table.fn(self, ...) +-- El operador ':' añade un primer argumento llamado self. +-- Lea 7 y 8 para entender cómo self obtiene su valor. +-- 3. newObj será una instancia de clase Dog +-- 4. self = la clase siendo instanciada. Usualmente, +-- self sería Dog, pero la herencia puede cambiar eso. +-- newObj obtiene las funciones de self cuando establecemos +-- la metatabla e __index de newObj a self. +-- 5. Recordatorio: setmetatable retorna su primer argumento. +-- 6. El operador ':' funciona igual que en 2, pero esta vez +-- esperamos que self sea una instancia de la clase. +-- 7. Lo mismo que Dog.new(Dog), por lo tanto self = Dog en new(). +-- 8. Lo mismo que mrDog.makeSound(mrDog), self = mrDog. + +---------------------------------------------------- + +-- Ejemplo de herencia: + +LoudDog = Dog:new() -- 1. + +function LoudDog:makeSound() + s = self.sound .. ' ' -- 2. + print(s .. s .. s) +end + +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof' -- 4. + +-- 1. Loud dog obtiene los métodos y variables de Dog +-- 2. self tiene una llave 'sound' obtenido de new(), ver 3. +-- 3. Lo mismo que LoudDog.new(LoudDog), y convertido a +-- Dog.new(LoudDog) ya que LoudDog no tiene llave 'new', +-- pero tiene __index = Dog en su metatabla. +-- Resultado: La metatabla de seymour es LoudDog, y +-- LoudDog.__index = LoudDog. Así que seymour.key +-- = seymour.key, LoudDog.key o Dog.key, dependiendo de +-- cuál tabla sea la primera con la llave dada. +-- 4. La llave 'makeSound' se encuentra en LoudDog: +-- Es lo mismo que LoudDog.makeSound(seymour). + +-- Si es requerido, el 'new()' de una subclase es igual +-- al de la clase base. +function LoudDog:new() + newObj = {} + -- set up newObj + self.__index = self + return setmetatable(newObj, self) +end + +---------------------------------------------------- +-- 4. Módulos. +---------------------------------------------------- + + +--[[ Comento esta sección del código para que el resto + del script siga siendo ejecutable +``` + +```lua +-- Supongamos que el archivo mod.lua se ve así: +local M = {} + +local function sayMyName() + print('Hrunkner') +end + +function M.sayHello() + print('Why hello there') + sayMyName() +end + +return M + +-- Otro archivo puede usar las funcionalidades de mod.lua +local mod = require('mod') -- Corre el archivo mod.lua + +-- 'require' es la función estándar para incluir módulos +-- 'require' funciona así (si no ha sido almacenado en caché, ver abajo) +local mod = (function () + +end)() +-- Es como si mod.lua fuese el cuerpo de una función, de tal manera +-- que los locales de mod.lua son invisibles fuera de él. + +-- Esto funciona porque mod es igual a M dentro de mod.lua +mod.sayHello() -- Imprime: Why hello there Hrunkner + +-- Esto es erróneo. sayMyName sólo existe dentro de mod.lua: +mod.sayMyName() -- error +-- El valor de 'require' es guardado en caché, así que cada archivo +-- se ejecuta máximo una vez, incluso si se usa 'require' varias veces. + +-- Suponga que mod2.lua contiene "print('Hi!')" +local a = require('mod2') -- Imprime 'Hi!' +local b = require('mod2') -- No imprime. También, a = b + +-- 'dofile' es similar a require pero no usa caché. +dofile('mod2.lua') --> Hi! +dofile('mod2.lua') --> Hi! (lo ejecuta nuevamente) + +-- 'loadfile' carga un archivo lua, pero no lo ejecuta +f = loadfile('mod2.lua') -- Se puede llamar f() para ejecutarlo. + +-- 'load' es como 'loadfile' para strings que contengan código lua +-- ('loadstring' es obsoleto, se prefiere el uso de 'load') +g = load('print(343)') -- Retorna una función +g() -- Imprime '343', nada es impreso antes de esto. + +--]] +``` + +## Referencias + +Estaba emocionado por aprender lua para poder crear juegos +con el motor de juegos [Love 2D](http://love2d.org/). Ese es el por qué. + +Empecé con [BlackBulletIV para programadores Lua](https://ebens.me/posts/lua-for-programmers-part-1/). +Luego, leí el libro oficial de [Programación en Lua](http://www.lua.org/pil/contents.html). +Ese es el cómo. + +Podría serle útil darle un vistazo a +[Lua Short Reference](http://lua-users.org/wiki/LuaShortReference) en lua-users.org. + +Los principales temas no cubiertos son las librerías estándar: + +* [Librería de strings](http://lua-users.org/wiki/StringLibraryTutorial) +* [Librería de tablas](http://lua-users.org/wiki/TableLibraryTutorial) +* [Librería de matemáticas](http://lua-users.org/wiki/MathLibraryTutorial) +* [Librería de Entrada/Salida (io)](http://lua-users.org/wiki/IoLibraryTutorial) +* [Libreria de Sistema Operativo (os)](http://lua-users.org/wiki/OsLibraryTutorial) + +Por cierto, el archivo entero es código Lua válido. ¡Guárdelo como +aprendiendo.lua y ejecútelo con el comando "lua aprendiendo.lua" ! + +¡Que se divierta con lua! From 21c588354c88b309408b81e738efc6829c9b9c5b Mon Sep 17 00:00:00 2001 From: Mi-Br <43519102+Mi-Br@users.noreply.github.com> Date: Fri, 17 May 2024 15:28:58 +0200 Subject: [PATCH 236/392] [go/en] missing map keys (#4413) --- go.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/go.html.markdown b/go.html.markdown index b93cbc61..81d45b98 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -150,6 +150,13 @@ can include line breaks.` // Same string type. // hash or dictionary types of some other languages. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 + // Looking up a missing key returns the zero value, + // which is 0 in this case, since it's a map[string]int + m["key not present"] // 0 + // Check if a key is present in the map like this: + if val, ok := m["one"]; ok { + // Do something + } // Unused variables are an error in Go. // The underscore lets you "use" a variable but discard its value. From 89857f5e24eda256f978dc44df04ffa729f69273 Mon Sep 17 00:00:00 2001 From: nbehrnd Date: Fri, 17 May 2024 15:36:55 +0200 Subject: [PATCH 237/392] [rst/de] light extension of export formats docutils offers (#4654) --- de-de/rst-de.html.markdown | 50 ++++++++++++++++++++------------------ 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/de-de/rst-de.html.markdown b/de-de/rst-de.html.markdown index 2c5e63a7..40c5791f 100644 --- a/de-de/rst-de.html.markdown +++ b/de-de/rst-de.html.markdown @@ -10,39 +10,36 @@ lang: de-de --- RST ist ein Dateiformat, das von der Python Community entwickelt wurde, - -um Dokumentation zu schreiben (und ist somit Teil von Docutils). - -RST-Dateien sind simple Textdateien mit einer leichtgewichtigen Syntax (im Vergleich zu HTML). - +um Dokumentation zu schreiben (und ist somit Teil von Docutils). +RST-Dateien sind simple Textdateien mit einer leichtgewichtigen Syntax (im +Vergleich zu HTML). ## Installation Um Restructured Text zu verwenden, musst du [Python](http://www.python.org) - -installieren und das `docutils` Paket installieren. `docutils` kann mit dem folgenden - -Befehl auf der Kommandozeile installiert werden: +installieren und das `docutils` Paket installieren. `docutils` kann mit dem +folgenden Befehl auf der Kommandozeile installiert werden: ```bash -$ easy_install docutils +easy_install docutils ``` -Wenn auf deinem System `pip` installiert kannst du es stattdessen auch verwenden: +Ebenso kann die Installation mit `pip` ```bash -$ pip install docutils +pip install docutils ``` +initiiert werden. ## Dateisyntax Ein einfaches Beispiel für die Dateisyntax: ``` -.. Zeilen, die mit zwei Punkten starten sind spezielle Befehle. +.. Zeilen, die mit zwei Punkten starten sind spezielle Befehle. -.. Wenn kein Befehl gefunden wird, wird die Zeile als Kommentar gewertet. +.. Wenn kein Befehl gefunden wird, wird die Zeile als Kommentar gewertet. ============================================================================ Haupttitel werden mit Gleichheitszeichen darüber und darunter gekennzeichnet @@ -75,19 +72,20 @@ oder Tabellen sind einfach zu schreiben: =========== ========== -Land Hauptstadt +Land Hauptstadt =========== ========== Frankreich Paris Japan Tokyo =========== ======== -Komplexere Tabellen (zusammengeführte Spalten und Zeilen) können einfach -erstellt werden, aber ich empfehle dir dafür die komplette Dokumentation zu lesen :) +Komplexere Tabellen (zusammengeführte Spalten und Zeilen) können einfach +erstellt werden, aber ich empfehle dir dafür die komplette Dokumentation zu +lesen :) Es gibt mehrere Möglichkeiten um Links zu machen: -- Wenn man einen Unterstrich hinter einem Wort hinzufügt: GitHub_ Zusätzlich -muss man die Zielurl nach dem Text hinzufügen. +- Wenn man einen Unterstrich hinter einem Wort hinzufügt: GitHub_ Zusätzlich +muss man die Zielurl nach dem Text hinzufügen. (Dies hat den Vorteil, dass man keine unnötigen Urls in lesbaren Text einfügt. - Wenn man die vollständige Url eingibt: https://github.com/ (Dies wird automatisch in ein Link konvertiert.) @@ -96,18 +94,22 @@ muss man die Zielurl nach dem Text hinzufügen. .. _GitHub https://github.com/ ``` - ## Wie man es verwendet -RST kommt mit docutils, dort hast du den Befehl `rst2html`, zum Beispiel: +Mit der Installation von [docutils](https://docutils.sourceforge.io/) bietet +sich beispielsweise die Umwandlung zu html (mehrere Standards stehen zur +Auswahl) an: ```bash -$ rst2html myfile.rst output.html +rst2html myfile.rst output.html ``` -*Anmerkung : Auf manchen Systemen könnte es rst2html.py sein* +*Anmerkung: Auf manchen Systemen könnte es `rst2html.py` sein.* -Es gibt komplexere Anwendungen, die das RST Format verwenden: +Weitere Exporte bieten beispielsweise `rst2latex`, `rst2man`, `rst2odt`, +`rst2pdf` und `rst2xml`. + +Es gibt komplexere Anwendungen, die das RST Format verwenden: - [Pelican](http://blog.getpelican.com/), ein statischer Webseitengenerator - [Sphinx](http://sphinx-doc.org/), ein Dokumentationsgenerator From 825a2b0875c6739b65379f20765313afad885255 Mon Sep 17 00:00:00 2001 From: rilysh Date: Fri, 17 May 2024 23:16:56 +0530 Subject: [PATCH 238/392] [c++/en] remove using namespace std (#4738) --- c++.html.markdown | 145 +++++++++++++++++++++++----------------------- 1 file changed, 74 insertions(+), 71 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index dd4ba055..99e2feea 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -31,7 +31,7 @@ one of the most widely-used programming languages. // Comparison to C ////////////////// -// C++ is _almost_ a superset of C and shares its basic syntax for +// C++ is almost a superset of C and shares its basic syntax for // variable declarations, primitive types, and functions. // Just like in C, your program's entry point is a function called @@ -55,24 +55,26 @@ int main(int argc, char** argv) // However, C++ varies in some of the following ways: -// In C++, character literals are chars -sizeof('c') == sizeof(char) == 1 +// In C++, character literals are chars, therefore the size is 1 +sizeof('c') == sizeof(char) -// In C, character literals are ints +// In C, character literals are ints, therefore the size is 4 sizeof('c') == sizeof(int) // C++ has strict prototyping void func(); // function which accepts no arguments +void func(void); // same as earlier // In C -void func(); // function which may accept any number of arguments +void func(); // function which may accept any number of arguments with unknown type +void func(void); // function which accepts no arguments // Use nullptr instead of NULL in C++ int* ip = nullptr; -// C standard headers are available in C++. -// C headers end in .h, while +// Most C standard headers are available in C++. +// C headers generally end with .h, while // C++ headers are prefixed with "c" and have no ".h" suffix. // The C++ standard version: @@ -101,7 +103,7 @@ void print(char const* myString) void print(int myInt) { - printf("My int is %d", myInt); + printf("My int is %d\n", myInt); } int main() @@ -193,22 +195,24 @@ int main() #include // Include for I/O streams -using namespace std; // Streams are in the std namespace (standard library) - int main() { int myInt; // Prints to stdout (or terminal/screen) - cout << "Enter your favorite number:\n"; + // std::cout referring the access to the std namespace + std::cout << "Enter your favorite number:\n"; // Takes in input - cin >> myInt; + std::cin >> myInt; // cout can also be formatted - cout << "Your favorite number is " << myInt << '\n'; + std::cout << "Your favorite number is " << myInt << '\n'; // prints "Your favorite number is " - cerr << "Used for error messages"; + std::cerr << "Used for error messages"; + + // flush string stream buffer with new line + std::cout << "I flushed it away" << std::endl; } ////////// @@ -218,22 +222,20 @@ int main() // Strings in C++ are objects and have many member functions #include -using namespace std; // Strings are also in the namespace std (standard library) - -string myString = "Hello"; -string myOtherString = " World"; +std::string myString = "Hello"; +std::string myOtherString = " World"; // + is used for concatenation. -cout << myString + myOtherString; // "Hello World" +std::cout << myString + myOtherString; // "Hello World" -cout << myString + " You"; // "Hello You" +std::cout << myString + " You"; // "Hello You" // C++ string length can be found from either string::length() or string::size() cout << myString.length() + myOtherString.size(); // Outputs 11 (= 5 + 6). // C++ strings are mutable. myString.append(" Dog"); -cout << myString; // "Hello Dog" +std::cout << myString; // "Hello Dog" // C++ can handle C-style strings with related functions using cstrings #include @@ -254,35 +256,32 @@ cout << "Length = " << strlen(myOldString); // Length = 9 // No * is needed for dereferencing and // & (address of) is not used for assignment. -using namespace std; +std::string foo = "I am foo"; +std::string bar = "I am bar"; -string foo = "I am foo"; -string bar = "I am bar"; - - -string& fooRef = foo; // This creates a reference to foo. +std::string& fooRef = foo; // This creates a reference to foo. fooRef += ". Hi!"; // Modifies foo through the reference -cout << fooRef; // Prints "I am foo. Hi!" +std::cout << fooRef; // Prints "I am foo. Hi!" // Doesn't reassign "fooRef". This is the same as "foo = bar", and // foo == "I am bar" // after this line. -cout << &fooRef << endl; //Prints the address of foo +std::cout << &fooRef << '\n'; // Prints the address of foo fooRef = bar; -cout << &fooRef << endl; //Still prints the address of foo -cout << fooRef; // Prints "I am bar" +std::cout << &fooRef << '\n'; // Still prints the address of foo +std::cout << fooRef << '\n'; // Prints "I am bar" // The address of fooRef remains the same, i.e. it is still referring to foo. -const string& barRef = bar; // Create a const reference to bar. +const std::string& barRef = bar; // Create a const reference to bar. // Like C, const values (and pointers and references) cannot be modified. barRef += ". Hi!"; // Error, const references cannot be modified. // Sidetrack: Before we talk more about references, we must introduce a concept // called a temporary object. Suppose we have the following code: -string tempObjectFun() { ... } -string retVal = tempObjectFun(); +std::string tempObjectFun() { ... } +std::string retVal = tempObjectFun(); // What happens in the second line is actually: // - a string object is returned from tempObjectFun @@ -307,7 +306,7 @@ foo(bar(tempObjectFun())) void constReferenceTempObjectFun() { // constRef gets the temporary object, and it is valid until the end of this // function. - const string& constRef = tempObjectFun(); + const std::string& constRef = tempObjectFun(); ... } @@ -315,17 +314,17 @@ void constReferenceTempObjectFun() { // objects. You cannot have a variable of its type, but it takes precedence in // overload resolution: -void someFun(string& s) { ... } // Regular reference -void someFun(string&& s) { ... } // Reference to temporary object +void someFun(std::string& s) { ... } // Regular reference +void someFun(std::string&& s) { ... } // Reference to temporary object -string foo; +std::string foo; someFun(foo); // Calls the version with regular reference someFun(tempObjectFun()); // Calls the version with temporary reference // For example, you will see these two versions of constructors for // std::basic_string: -basic_string(const basic_string& other); -basic_string(basic_string&& other); +std::basic_string(const basic_string& other); +std::basic_string(basic_string&& other); // Idea being if we are constructing a new string from a temporary object (which // is going to be destroyed soon anyway), we can have a more efficient @@ -586,7 +585,7 @@ int main () { // Point up calls the + (function) with right as its parameter Point result = up + right; // Prints "Result is upright (1,1)" - cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + std::cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; return 0; } @@ -654,7 +653,7 @@ barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. // Template parameters don't have to be classes: template void printMessage() { - cout << "Learn C++ in " << Y << " minutes!" << endl; + std::cout << "Learn C++ in " << Y << " minutes!\n"; } // And you can explicitly specialize templates for more efficient code. Of @@ -663,7 +662,7 @@ void printMessage() { // even if you explicitly specified all parameters. template<> void printMessage<10>() { - cout << "Learn C++ faster in only 10 minutes!" << endl; + std::cout << "Learn C++ faster in only 10 minutes!\n"; } printMessage<20>(); // Prints "Learn C++ in 20 minutes!" @@ -716,6 +715,9 @@ void doSomethingWithAFile(const char* filename) // To begin with, assume nothing can fail. FILE* fh = fopen(filename, "r"); // Open the file in read mode. + if (fh == NULL) { + // Handle possible error + } doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); @@ -855,9 +857,9 @@ delete ptr; // Usage of "std::shared_ptr": void foo() { -// It's no longer necessary to delete the Dog. -std::shared_ptr doggo(new Dog()); -doggo->bark(); + // It's no longer necessary to delete the Dog. + std::shared_ptr doggo(new Dog()); + doggo->bark(); } // Beware of possible circular references!!! @@ -893,22 +895,23 @@ doggo_two = doggo_one; // p2 references p1 // Vector (Dynamic array) // Allow us to Define the Array or list of objects at run time #include -string val; -vector my_vector; // initialize the vector -cin >> val; +std::string val; +std::vector my_vector; // initialize the vector +std::cin >> val; + my_vector.push_back(val); // will push the value of 'val' into vector ("array") my_vector my_vector.push_back(val); // will push the value into the vector again (now having two elements) // To iterate through a vector we have 2 choices: // Either classic looping (iterating through the vector from index 0 to its last index): for (int i = 0; i < my_vector.size(); i++) { - cout << my_vector[i] << endl; // for accessing a vector's element we can use the operator [] + std::cout << my_vector[i] << '\n'; // for accessing a vector's element we can use the operator [] } // or using an iterator: vector::iterator it; // initialize the iterator for vector for (it = my_vector.begin(); it != my_vector.end(); ++it) { - cout << *it << endl; + std::cout << *it << '\n'; } // Set @@ -917,7 +920,7 @@ for (it = my_vector.begin(); it != my_vector.end(); ++it) { // without any other functions or code. #include -set ST; // Will initialize the set of int data type +std::set ST; // Will initialize the set of int data type ST.insert(30); // Will insert the value 30 in set ST ST.insert(10); // Will insert the value 10 in set ST ST.insert(20); // Will insert the value 20 in set ST @@ -929,9 +932,9 @@ ST.insert(30); // Will insert the value 30 in set ST ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 // To iterate through Set we use iterators -set::iterator it; -for(it=ST.begin();it!=ST.end();it++) { - cout << *it << endl; +std::set::iterator it; +for(it = ST.begin(); it != ST.end(); it++) { + std::cout << *it << '\n'; } // Output: // 10 @@ -939,7 +942,7 @@ for(it=ST.begin();it!=ST.end();it++) { // To clear the complete container we use Container_name.clear() ST.clear(); -cout << ST.size(); // will print the size of set ST +std::cout << ST.size(); // will print the size of set ST // Output: 0 // NOTE: for duplicate elements we can use multiset @@ -951,7 +954,7 @@ cout << ST.size(); // will print the size of set ST // and a mapped value, following a specific order. #include -map mymap; // Will initialize the map with key as char and value as int +std::map mymap; // Will initialize the map with key as char and value as int mymap.insert(pair('A',1)); // Will insert value 1 for key A @@ -959,16 +962,16 @@ mymap.insert(pair('Z',26)); // Will insert value 26 for key Z // To iterate -map::iterator it; +std::map::iterator it; for (it=mymap.begin(); it!=mymap.end(); ++it) - std::cout << it->first << "->" << it->second << std::endl; + std::cout << it->first << "->" << it->second << '\n'; // Output: // A->1 // Z->26 // To find the value corresponding to a key it = mymap.find('Z'); -cout << it->second; +std::cout << it->second; // Output: 26 @@ -1006,7 +1009,7 @@ fooMap.find(Foo(1)); //true // For example, consider sorting a vector of pairs using the second // value of the pair -vector > tester; +std::vector > tester; tester.push_back(make_pair(3, 6)); tester.push_back(make_pair(1, 9)); tester.push_back(make_pair(5, 0)); @@ -1014,7 +1017,7 @@ tester.push_back(make_pair(5, 0)); // Pass a lambda expression as third argument to the sort function // sort is from the header -sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { +std::sort(tester.begin(), tester.end(), [](const pair& lhs, const pair& rhs) { return lhs.second < rhs.second; }); @@ -1028,7 +1031,7 @@ sort(tester.begin(), tester.end(), [](const pair& lhs, const pair dog_ids; +std::vector dog_ids; // number_of_dogs = 3; for(int i = 0; i < 3; i++) { dog_ids.push_back(i); @@ -1133,33 +1136,33 @@ const int maxL = 15; auto second = make_tuple(maxN, maxL); // Printing elements of 'first' tuple -cout << get<0>(first) << " " << get<1>(first) << '\n'; //prints : 10 A +std::cout << get<0>(first) << " " << get<1>(first) << '\n'; //prints : 10 A // Printing elements of 'second' tuple -cout << get<0>(second) << " " << get<1>(second) << '\n'; // prints: 1000000000 15 +std::cout << get<0>(second) << " " << get<1>(second) << '\n'; // prints: 1000000000 15 // Unpacking tuple into variables int first_int; char first_char; tie(first_int, first_char) = first; -cout << first_int << " " << first_char << '\n'; // prints : 10 A +std::cout << first_int << " " << first_char << '\n'; // prints : 10 A // We can also create tuple like this. tuple third(11, 'A', 3.14141); // tuple_size returns number of elements in a tuple (as a constexpr) -cout << tuple_size::value << '\n'; // prints: 3 +std::cout << tuple_size::value << '\n'; // prints: 3 // tuple_cat concatenates the elements of all the tuples in the same order. auto concatenated_tuple = tuple_cat(first, second, third); // concatenated_tuple becomes = (10, 'A', 1e9, 15, 11, 'A', 3.14141) -cout << get<0>(concatenated_tuple) << '\n'; // prints: 10 -cout << get<3>(concatenated_tuple) << '\n'; // prints: 15 -cout << get<5>(concatenated_tuple) << '\n'; // prints: 'A' +std::cout << get<0>(concatenated_tuple) << '\n'; // prints: 10 +std::cout << get<3>(concatenated_tuple) << '\n'; // prints: 15 +std::cout << get<5>(concatenated_tuple) << '\n'; // prints: 'A' /////////////////////////////////// @@ -1207,7 +1210,7 @@ compl 4 // Performs a bitwise not 4 xor 3 // Performs bitwise xor ``` -Further Reading: +## Further Reading: * An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp). * A tutorial for beginners or experts, covering many modern features and good practices: [LearnCpp.com](https://www.learncpp.com/) From 389f2c29565038ded1e8e336d8b6923f1cdd053e Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 17 May 2024 11:52:08 -0600 Subject: [PATCH 239/392] [c++/en] consistent indentation --- c++.html.markdown | 130 +++++++++++++++++++++++----------------------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 99e2feea..6d039c33 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -162,7 +162,7 @@ namespace Second { } void bar() { - printf("This is Second::bar\n"); + printf("This is Second::bar\n"); } } @@ -197,22 +197,22 @@ int main() int main() { - int myInt; + int myInt; - // Prints to stdout (or terminal/screen) - // std::cout referring the access to the std namespace - std::cout << "Enter your favorite number:\n"; - // Takes in input - std::cin >> myInt; + // Prints to stdout (or terminal/screen) + // std::cout referring the access to the std namespace + std::cout << "Enter your favorite number:\n"; + // Takes in input + std::cin >> myInt; - // cout can also be formatted - std::cout << "Your favorite number is " << myInt << '\n'; - // prints "Your favorite number is " + // cout can also be formatted + std::cout << "Your favorite number is " << myInt << '\n'; + // prints "Your favorite number is " - std::cerr << "Used for error messages"; + std::cerr << "Used for error messages"; - // flush string stream buffer with new line - std::cout << "I flushed it away" << std::endl; + // flush string stream buffer with new line + std::cout << "I flushed it away" << std::endl; } ////////// @@ -304,10 +304,10 @@ foo(bar(tempObjectFun())) // which case its life gets extended to the current scope: void constReferenceTempObjectFun() { - // constRef gets the temporary object, and it is valid until the end of this - // function. - const std::string& constRef = tempObjectFun(); - ... + // constRef gets the temporary object, and it is valid until the end of this + // function. + const std::string& constRef = tempObjectFun(); + ... } // Another kind of reference introduced in C++11 is specifically for temporary @@ -339,15 +339,15 @@ std::basic_string(basic_string&& other); // easier visualization and reading of code enum ECarTypes { - Sedan, - Hatchback, - SUV, - Wagon + Sedan, + Hatchback, + SUV, + Wagon }; ECarTypes GetPreferredCarType() { - return ECarTypes::Hatchback; + return ECarTypes::Hatchback; } // As of C++11 there is an easy way to assign a type to the enum which can be @@ -355,21 +355,21 @@ ECarTypes GetPreferredCarType() // the desired type and their respective constants enum ECarTypes : uint8_t { - Sedan, // 0 - Hatchback, // 1 - SUV = 254, // 254 - Hybrid // 255 + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 }; void WriteByteToFile(uint8_t InputValue) { - // Serialize the InputValue to a file + // Serialize the InputValue to a file } void WritePreferredCarTypeToFile(ECarTypes InputCarType) { - // The enum is implicitly converted to a uint8_t due to its declared enum type - WriteByteToFile(InputCarType); + // The enum is implicitly converted to a uint8_t due to its declared enum type + WriteByteToFile(InputCarType); } // On the other hand you may not want enums to be accidentally cast to an integer @@ -377,22 +377,22 @@ void WritePreferredCarTypeToFile(ECarTypes InputCarType) // won't be implicitly converted enum class ECarTypes : uint8_t { - Sedan, // 0 - Hatchback, // 1 - SUV = 254, // 254 - Hybrid // 255 + Sedan, // 0 + Hatchback, // 1 + SUV = 254, // 254 + Hybrid // 255 }; void WriteByteToFile(uint8_t InputValue) { - // Serialize the InputValue to a file + // Serialize the InputValue to a file } void WritePreferredCarTypeToFile(ECarTypes InputCarType) { - // Won't compile even though ECarTypes is a uint8_t due to the enum - // being declared as an "enum class"! - WriteByteToFile(InputCarType); + // Won't compile even though ECarTypes is a uint8_t due to the enum + // being declared as an "enum class"! + WriteByteToFile(InputCarType); } ////////////////////////////////////////// @@ -573,7 +573,7 @@ Point& Point::operator+=(const Point& rhs) { x += rhs.x; y += rhs.y; - + // `this` is a pointer to the object, on which a method is called. return *this; } @@ -653,7 +653,7 @@ barkThreeTimes(fluffy); // Prints "Fluffy barks" three times. // Template parameters don't have to be classes: template void printMessage() { - std::cout << "Learn C++ in " << Y << " minutes!\n"; + std::cout << "Learn C++ in " << Y << " minutes!\n"; } // And you can explicitly specialize templates for more efficient code. Of @@ -662,7 +662,7 @@ void printMessage() { // even if you explicitly specified all parameters. template<> void printMessage<10>() { - std::cout << "Learn C++ faster in only 10 minutes!\n"; + std::cout << "Learn C++ faster in only 10 minutes!\n"; } printMessage<20>(); // Prints "Learn C++ in 20 minutes!" @@ -715,9 +715,9 @@ void doSomethingWithAFile(const char* filename) // To begin with, assume nothing can fail. FILE* fh = fopen(filename, "r"); // Open the file in read mode. - if (fh == NULL) { - // Handle possible error - } + if (fh == NULL) { + // Handle possible error + } doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); @@ -837,7 +837,7 @@ void doSomethingWithAFile(const std::string& filename) // Generally a smart pointer is a class which wraps a "raw pointer" (usage of "new" // respectively malloc/calloc in C). The goal is to be able to -// manage the lifetime of the object being pointed to without ever needing to explicitly delete +// manage the lifetime of the object being pointed to without ever needing to explicitly delete // the object. The term itself simply describes a set of pointers with the // mentioned abstraction. // Smart pointers should preferred over raw pointers, to prevent @@ -857,9 +857,9 @@ delete ptr; // Usage of "std::shared_ptr": void foo() { - // It's no longer necessary to delete the Dog. - std::shared_ptr doggo(new Dog()); - doggo->bark(); + // It's no longer necessary to delete the Dog. + std::shared_ptr doggo(new Dog()); + doggo->bark(); } // Beware of possible circular references!!! @@ -869,7 +869,7 @@ std::shared_ptr doggo_two(new Dog()); doggo_one = doggo_two; // p1 references p2 doggo_two = doggo_one; // p2 references p1 -// There are several kinds of smart pointers. +// There are several kinds of smart pointers. // The way you have to use them is always the same. // This leads us to the question: when should we use each kind of smart pointer? // std::unique_ptr - use it when you just want to hold one reference to @@ -905,13 +905,13 @@ my_vector.push_back(val); // will push the value into the vector again (now havi // To iterate through a vector we have 2 choices: // Either classic looping (iterating through the vector from index 0 to its last index): for (int i = 0; i < my_vector.size(); i++) { - std::cout << my_vector[i] << '\n'; // for accessing a vector's element we can use the operator [] + std::cout << my_vector[i] << '\n'; // for accessing a vector's element we can use the operator [] } // or using an iterator: vector::iterator it; // initialize the iterator for vector for (it = my_vector.begin(); it != my_vector.end(); ++it) { - std::cout << *it << '\n'; + std::cout << *it << '\n'; } // Set @@ -933,8 +933,8 @@ ST.erase(20); // Will erase element with value 20 // Set ST: 10 30 // To iterate through Set we use iterators std::set::iterator it; -for(it = ST.begin(); it != ST.end(); it++) { - std::cout << *it << '\n'; +for (it = ST.begin(); it != ST.end(); it++) { + std::cout << *it << '\n'; } // Output: // 10 @@ -963,7 +963,7 @@ mymap.insert(pair('Z',26)); // To iterate std::map::iterator it; -for (it=mymap.begin(); it!=mymap.end(); ++it) +for (it = mymap.begin(); it != mymap.end(); ++it) std::cout << it->first << "->" << it->second << '\n'; // Output: // A->1 @@ -1033,8 +1033,8 @@ std::sort(tester.begin(), tester.end(), [](const pair& lhs, const pair std::vector dog_ids; // number_of_dogs = 3; -for(int i = 0; i < 3; i++) { - dog_ids.push_back(i); +for (int i = 0; i < 3; i++) { + dog_ids.push_back(i); } int weight[3] = {30, 50, 10}; @@ -1057,15 +1057,15 @@ sort(dog_ids.begin(), dog_ids.end(), [&weight](const int &lhs, const int &rhs) { // You can use a range for loop to iterate over a container int arr[] = {1, 10, 3}; -for(int elem: arr){ - cout << elem << endl; +for (int elem: arr) { + cout << elem << endl; } // You can use "auto" and not worry about the type of the elements of the container // For example: -for(auto elem: arr) { - // Do something with each element of arr +for (auto elem: arr) { + // Do something with each element of arr } ///////////////////// @@ -1078,10 +1078,10 @@ for(auto elem: arr) { // You can override private methods! class Foo { - virtual void bar(); + virtual void bar(); }; class FooSub : public Foo { - virtual void bar(); // Overrides Foo::bar! + virtual void bar(); // Overrides Foo::bar! }; @@ -1212,7 +1212,7 @@ compl 4 // Performs a bitwise not ## Further Reading: -* An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp). -* A tutorial for beginners or experts, covering many modern features and good practices: [LearnCpp.com](https://www.learncpp.com/) -* A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). -* Additional resources may be found at [CPlusPlus](http://cplusplus.com). +- An up-to-date language reference can be found at [CPP Reference](http://cppreference.com/w/cpp). +- A tutorial for beginners or experts, covering many modern features and good practices: [LearnCpp.com](https://www.learncpp.com/) +- A tutorial covering basics of language and setting up coding environment is available at [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb). +- Additional resources may be found at [CPlusPlus](http://cplusplus.com). From ab75eeff40a9c73a87c94212a558de870f67535f Mon Sep 17 00:00:00 2001 From: pxtom <79592123+pxtom@users.noreply.github.com> Date: Fri, 17 May 2024 16:08:57 -0400 Subject: [PATCH 240/392] [phix/en] create (#4131) --- phix.html.markdown | 451 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 451 insertions(+) create mode 100644 phix.html.markdown diff --git a/phix.html.markdown b/phix.html.markdown new file mode 100644 index 00000000..2a199edd --- /dev/null +++ b/phix.html.markdown @@ -0,0 +1,451 @@ +--- +language: Phix +contributors: + - ["pxtom", "https://gitgub.com/pxtom"] +filename: learnphix.exw +--- + +``` + -- single line comment + + // single line comment + + /* multi- + line comment */ + +// Start programming immediately + + -- write using UTF8; save as: hello.ex + -- use ? for output + + ? "😍 hello , 😎 world!" + ? sqrt(2+2) + +// Interpret your program + /* + p hello */ + +// Compile your program + /* + p -c hello */ + +// Coding mistakes receive gentle help messages + /* + string line + line = 5 + ^ type error (storing atom in string) */ + +// Every literal value, constant, and variable is an ''object'' + + -- a literal object + ? "hello" + ? PI + ? { "hello", PI } + + -- a named variable object + object X + X = "hello" + X = PI + X = { "hello", PI } + + -- a named constant object + constant myPI = 22/7 + +// Everything is an ''object'', just two fundemental kinds + /* + ┌────────────────────▄ + ┌─┤ object █─┐ + │ └─▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█ │ + │ │ + "atom" "container" */ + + number x = 3.14159 sequence s = { "hello", PI } + integer y = 3 string txt = "hello" + + -- simplify, + -- and use only two primitives + number x1=3.14156, y1=3 + sequence s1={"hello",PI}, txt1="hello" + + -- simplify even more, + -- and use just one primitive + object x2=3.14156, y2=3, s2={"hello",PI}, txt2="hello" + +// Elegant data-type design + + -- invent your own "type" + -- organize with "struct" or "class" + /* + ╔═══════════════════════════════╗ + ║ ┌─────────────────────────┐ ║ + ║ │ ┌───────────▄ │ ║ + ║ │ ┌─┤ object █─┐ │ ║ + ║ │ │ └─▄▄▄▄▄▄▄▄▄▄█ │ │ ║ + ║ │ │ │ │ ║ + ║ │ number sequence │ ║ + ║ │ │ │ │ ║ + ║ │ integer string │ ║ + ║ └──────── type ───────────┘ ║ + ║ ║ + ╚════════ struct ║ + class ════════════════╝ + */ + +// Syntax is consistant: "keyword...end keyword" + + -- no invisible syntax or extra rules needed. + + // loop + -- while ... end while + + integer index = 1 + while index <= 5 do + ? index + index += 1 + end while + + // loop + -- for ... end for + + for i=5 to 1 by -1 do + ? i + end for + + // conditional + -- if ... end if + + number p = 4 + if p < 1 then + ? "p is a small number" + elsif p > 10 then + ? "p is a large number" + else + ? "p is inbetween" + end if + + // conditional + -- switch ... end switch + + object ch = prompt_string("enter one character: " ) + switch ch + case "a": ? "ch is a" + case "b": ? "ch is b" + case "c": ? "ch is c" + default: ? "ch is something else" + end switch + +// Operators are always consistant; never overloaded. + + -- the + operator ''always adds'' + ? 2+7 + ? 'A' + 32 + + -- the & operator ''always concatenates'' + ? 2 & 7 --> {2,7} + ? "cat" & " " & "dog" --> "cat dog" + ? {1,2,3} & "fish" --> {1,2,3} & "fish" + pp( {1,2,3} & "fish" ) --> {1,2,3,102'f',105'i',115's',104'h'} + +// Use ''sq_'' functions to span entire containers. + + ? sq_add( {1,2,3}, 10 ) --> {11,12,13} + ? sq_sqrt( {4,9,16} ) --> {2,3,4} + +// Functions must return a value + + function add2( number x, number y ) + number sum = x + y + return sum + end function + ? add2( 4, 9 ) + +// Procedures do not return a value + + procedure sum_all( sequence lst ) + number sum = 0 + for i=1 to length(lst) do + sum += lst[i] + end for + ? sum + end procedure + sum_all( {1,3,9,11} ) + +// Recursion and mutal recursion are permitted + + function factorial(number n) + if n == 0 then + return 1 + end if + if n<0 then + return "error, no negative numbers for factorials" + end if + return n * factorial(n - 1) + end function + ? factorial(5) + +// User defined data-types + + -- defined like a function: type ... end type + -- they are fully programmable; add your own features + + type positive( number x ) + if not integer(x) then + ? "use integers for factorials" + return False + end if + if x < 0 then + ? "error, no negative numbers for factorials" + return False + end if + return True + end type + + -- use them to declare variables and parameters + + function factorial2( positive n ) + if n == 0 then return 1 end if + return n * factorial2(n-1) + end function + ? factorial(5) + + -- to catch errors, and recover, use: try ... end try + + try + ? factorial2( -5 ) + catch e + ? "that was a mistake" + end try + +// Sequences are versatile + + -- multiple assignment + number a, b, c + {a,b,c} = { -100, -200/-2, -300*3 } + ? a --> -100 + ? b --> 100 + ? c --> -900 + + -- swapping values + ? a --> -100 + ? c --> -900 + {a,c} = {c,a} + ? a --> -900 + ? c --> -100 + + +// Symmetrical one-based indexing does it all + + -- both sequence and string are mutable and work alike + + -- 1 2 3 4 5 -- index head to tail + s = { 10, 20, 30, 40, 50 } + -- -5 -4 -3 -2 -1 -- index tail to head + + // one item + ? s[ 2] + ? s[-4] + -- output for both is: + -----> 20 + + // slice with one item + ? s[ 2.. 2] + ? s[-4..-4] + -- output for both is: + -----> {20} + + // inclusive slice + ? s[ 2.. 4] + ? s[-4..-2] + -- output for both is: + -----> {20,30,40} + + // empty sequence + ? s[3 .. 2] + ? s[-3..-4] + -- output for both is: + -----> {} + + // insert + s[3..2] = {99} + ? s + -----> {10,20,99,30,40,50} + + // prepend and append + s = { 10,20,30,40,50 } + + s[ 1..0] = {0} -- prepend + s[$+1..$] = {6} -- append + + ? s + -----> {0,10,20,99,30,40,50,6} + + s[0..-1] = {9999} -- append + + ? s + -----> {0,10,20,99,30,40,50,6,9999} + + // delete + s = { 10,20,30,40,50 } + + s[2..2] = {} -- item deleted + ? s + -----> {10,30,40,50} + + s[2..3] = {} -- slice deleted + ? s + -----> {10,50} + +// Learn and reuse; you keep what you learn. + + s = { 1,3,5,7 } + txt = "jello" + + -- "find" locates one item in either a sequence or a string + ? find( 3, s ) --> 2 + ? find( 'e', txt ) --> 2 + + -- "match" locates a slice in either a sequence or a string + ? match( {5,7}, s ) -- > 3 + ? match( "ll", txt ) --> 3 + +// Look back at the examples, Phix is generic! + +// Batteries are installed + + ? sort( {2, 54,6,4, 0} ) + ? upper( "cat" ) + ? log( 10.4 ) + ? trunc(1.4) -- 1 + ? floor(1.4) -- 1 + ? trunc(-1.4) -- -1 + ? floor(-1.4) -- -2 + +// Batteries are included + + include builtins/regex.e + + string str = "say hello and smile" + str = gsub( `s...e`, str, "😍" ) + ? str --> "say hello and 😍" + +// Yes, sequences are "powerful" + + function odd(integer a) return remainder(a,2)=1 end function + function even(integer a) return remainder(a,2)=0 end function + + ? tagset(10) --> {1,2,3,4,5,6,7,8,9,10} + ? filter(tagset(10),odd) --> {1,3,5,7,9} + ? filter(tagset(10),even) --> {2,4,6,8,10} + +// A ''struct'' provides named fields, type-checking, and dot notation + + struct point + number x = 0 + number y = 0 + end struct + + procedure show( point q ) + printf(1, "(%g,%g)", { q.x, q.y } ) + end procedure + + point p1 = new() + show(p1) + --> (0,0) + + p1.x = 3 + p1.y = 5 + show( p1 ) + --> (3,5) + +// A ''class'' adds methods and scope control + + class pair + public number x = 0 + public number y = 0 + + procedure show( ) + printf(1, "(%g,%g)", { this.x, this.y } ) + end procedure + end class + + pair p2 = new() + p2.show() + --> (0,0) + + p2.x = 3 + p2.y = 5 + p2.show() + --> (3,5) + +// Inherit and compose + + class Pair -- any 2 objects + public sequence xy + public integer x,y + function get_x() + return xy[1] + end function + + function get_y() + return xy[2] + end function + end class + + type pos_seq(sequence x) + return min(x) >= 0 + end type + + class Point extends Pair + public pos_seq loc -- any two numbers >= 0 + + procedure set_loc(object x) + this.xy = {x[1],x[2]} + end procedure + end class + + class Rectangle extends Point + public Point tlc,brc --top_left, bottom_right corners; + public sequence size + + function get_size() + this.size = {brc.x-tlc.x , brc.y-tlc.y} + return this.size + end function + end class + + Point p1a = new() p1a.loc = {50,10} + Point p2a = new() p2a.loc = {300,200} + + Rectangle r = new() + r.tlc = p1a + r.brc = p2a + ? r -- {"struct","Rectangle",4,1} + ? r.tlc -- {"struct","Point",3,3} + + ? r.size --> {250,190} + ? r.get_size() --> {250,190} +``` + +Phix does not (although most can be emulated) directly support +operator|builtin|function overloading, lambda expressions, closures, +currying, eval, partial function application, function composition, +function prototyping, monads, generators, anonymous recursion, +the Y combinator, aspect oriented programming, interfaces, delegates, +first class environments, implicit type conversion +(of the destructive kind), interactive programming, inverted syntax, +list comprehensions, metaprogramming, pointers +(other than to raw allocated memory), topic variables, +enforced singletons, safe mode, s-expressions, +or formal proof construction. + +The author wryly comments: + +''That should both scare off and attract the right people''. + + +## References + +* [http://phix.x10.mx](http://phix.x10.mx) +* [Source code](https://github.com/petelomax/Phix) +* [Forum](https://openeuphoria.org/forum/index.wc) +* [Rosetta Code](https://rosettacode.org/wiki/Category:Phix) From 08c1c2e5d87b87a2425fed74790f9ca1eccda360 Mon Sep 17 00:00:00 2001 From: Th3G33k <4394090+Th3G33k@users.noreply.github.com> Date: Fri, 17 May 2024 10:10:02 -1000 Subject: [PATCH 241/392] [css/en] add more css3 features (#4907) --- css.html.markdown | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/css.html.markdown b/css.html.markdown index 948b70ac..2d9add84 100644 --- a/css.html.markdown +++ b/css.html.markdown @@ -69,6 +69,9 @@ div { } /* or ends with a value (CSS 3) */ [attr$='ue'] { font-size:smaller; } +/* or contains a value (CSS 3) */ +[attr*='foo'] { } + /* or contains a value in a space-separated list */ [otherAttr~='foo'] { } [otherAttr~='bar'] { } @@ -125,6 +128,9 @@ selector:first-child {} /* any element that is the last child of its parent */ selector:last-child {} +/* Select the nth child of selector parent (CSS 3) */ +selector:nth-child(n) { } + /* Just like pseudo classes, pseudo elements allow you to style certain parts of a document */ @@ -144,6 +150,12 @@ selector::after {} in the group */ selector1, selector2 { } +/* Select elements that do not have a certain state (CSS 3) */ +/* Here, we select div with no id attribute. */ +div:not([id]) { + background-color: red; +} + /* #################### ## PROPERTIES #################### */ @@ -196,6 +208,41 @@ selector { /* if the first one is not found, the browser uses the next, and so on */ font-family: "Courier New", Trebuchet, Arial, sans-serif; } + +/* Custom CSS properties using variables (CSS 3) */ +:root { + --main-bg-color: whitesmoke; +} +body { + background-color: var(--main-bg-color) +} + +/* Perfom a calculation (CSS 3) */ +body { + width: calc(100vw - 100px) +} + +/* Nest style rule inside another (CSS 3) */ +.main { + .bgred { /* same as: .main .bgred { } */ + background: red; + } + & .bggreen { /* same as: .main .bggreen { } */ + background: green; + } + &.bgblue { /* (without space) same as: .main.bgblue { } */ + background: blue; + } +} + +/* Design responsive layout using flexbox (CSS 3) */ +.container { + display: flex; + flex-direction: row; /* in which direction stack the flex items */ + flex-wrap: wrap; /* whether or not flex items should wrap */ + justify-content: center; /* how to align flex items horizontally */ + align-items: center; /* how to align flex items vertically */ +} ``` ## Usage From 1638727b7b1a72e357f4046fd8903de6eec4cfcf Mon Sep 17 00:00:00 2001 From: Archar Gelod <60652075+Archargelod@users.noreply.github.com> Date: Sat, 18 May 2024 08:26:21 +0000 Subject: [PATCH 242/392] [nim/en] add objects and ref objects (#4762) --- nim.html.markdown | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/nim.html.markdown b/nim.html.markdown index e3c749dc..0259dd45 100644 --- a/nim.html.markdown +++ b/nim.html.markdown @@ -61,7 +61,10 @@ var child = (name: "Rudiger", age: 2) # Assign all at once with literal () today.sun = "Overcast" # or individual fields. -today.temp = 70.1 +today[1] = 70.1 # or by index. + +let impostor = ("Rudiger", 2) # Two tuples are the same as long as they have +assert child == impostor # the same type and the same contents # Sequences @@ -114,6 +117,21 @@ when compileBadCode: # More Types and Data Structures # +# Objects are similar to tuples, but they *require* names of the fields + +type + Room = ref object # reference to an object, useful for big objects or + windows: int # objects inside objects + doors: int = 1 # Change the default value of a field (since Nim 2.0) + House = object + address: string + rooms: seq[Room] + +var + defaultHouse = House() # initialize with default values + defaultRoom = new Room() # create new instance of ref object + sesameHouse = House(address: "123 Sesame St.", rooms: @[defaultRoom]) + # Enumerations allow a type to have one of a limited number of values type From 36fdc4019569358b0039c86029336b14ad9e9769 Mon Sep 17 00:00:00 2001 From: Danny Yang Date: Sat, 18 May 2024 11:20:04 -0400 Subject: [PATCH 243/392] [rescript/en] update (#4947) --- rescript.html.markdown | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/rescript.html.markdown b/rescript.html.markdown index b633332c..4839631a 100644 --- a/rescript.html.markdown +++ b/rescript.html.markdown @@ -75,10 +75,7 @@ let world = `🌍` let helloWorld = `hello, ${world}` /* Bindings must be converted to strings */ let age = 10 -let ageMsg = `I am ${Js.Int.toString(age)} years old` - -/* Using `j` annotation in interpolation will implicitly convert bindings to strings */ -let ageMsg = j`I am $age years old` +let ageMsg = `I am ${Int.toString(age)} years old` /* Concatenate strings with ++ */ @@ -169,7 +166,7 @@ let firstTrip = {destination: "London", capacity: 45, averageSpeed: 120.0} let maxPassengers = firstTrip.capacity /* If you define the record type in a different file, you have to reference the - filename, if trainJourney was in a file called Trips.re */ + filename, if trainJourney was in a file called Trips.res */ let secondTrip: Trips.trainJourney = { destination: "Paris", capacity: 50, @@ -306,11 +303,12 @@ let showDialog = (~message: string): unit => { the `unit` type can also be represented as `()` */ /* > Currying - Functions can be curried and are partially called, allowing for easy reuse */ + Functions can be curried and are partially called, allowing for easy reuse + The remaining arguments are represented with ... */ let div = (denom, numr) => numr / denom -let divBySix = div(6) -let divByTwo = div(2) +let divBySix = div(6, ...) +let divByTwo = div(2, ...) div(3, 24) /* - : int = 8 */ divBySix(128) /* - : int = 21 */ @@ -319,7 +317,7 @@ divByTwo(10) /* - : int = 5 */ /* > Optional Labeled Arguments */ /* Use `=?` syntax for optional labeled arguments */ -let greetPerson = (~name, ~greeting=?, ()) => { +let greetPerson = (~name, ~greeting=?) => { switch (greeting) { | Some(greet) => greet ++ " " ++ name | None => "Hi " ++ name @@ -330,7 +328,7 @@ let greetPerson = (~name, ~greeting=?, ()) => { a partial function, to fix this we add `unit` when we declare and call it */ /* Call greetPerson without the optional labeled argument */ -greetPerson(~name="Kate", ()) +greetPerson(~name="Kate") /* Call greetPerson with all arguments */ greetPerson(~name="Marco", ~greeting="How are you today,") From c36fc10ef56e945b59c30a067e3437244e3e9c4e Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 18 May 2024 10:48:18 -0600 Subject: [PATCH 244/392] [kotlin/fr] fix filename --- fr-fr/{kotlin.html-fr.markdown => kotlin-fr.html.markdown} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename fr-fr/{kotlin.html-fr.markdown => kotlin-fr.html.markdown} (100%) diff --git a/fr-fr/kotlin.html-fr.markdown b/fr-fr/kotlin-fr.html.markdown similarity index 100% rename from fr-fr/kotlin.html-fr.markdown rename to fr-fr/kotlin-fr.html.markdown From 406d3f041fe5dd55d5b3842a64cfe5b67e3eb8e1 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 18 May 2024 12:03:35 -0600 Subject: [PATCH 245/392] [make/en] typo and change link --- make.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/make.html.markdown b/make.html.markdown index 5269e436..6738cd05 100644 --- a/make.html.markdown +++ b/make.html.markdown @@ -186,7 +186,7 @@ echo_inbuilt: # only evaluated once. (This is a GNU make extension) var := hello -var2 ::= $(var) hello +var2 ::= $(var) hello #:= and ::= are equivalent. # These variables are evaluated procedurally (in the order that they @@ -240,6 +240,6 @@ endif ### More Resources -+ [gnu make documentation](https://www.gnu.org/software/make/manual/) -+ [software carpentry tutorial](http://swcarpentry.github.io/make-novice/) -+ learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html) +- [GNU Make documentation](https://www.gnu.org/software/make/manual/make.html) +- [Software Carpentry tutorial](https://swcarpentry.github.io/make-novice/) +- [Makefile Tutorial By Example](https://makefiletutorial.com/#makefile-cookbook) From 781b19ef41571a5cbe82d4aaae0aa87f1daa42ca Mon Sep 17 00:00:00 2001 From: rilysh Date: Sun, 19 May 2024 10:18:40 +0530 Subject: [PATCH 246/392] [apl/en]: Add Further Reading section (#4948) --- apl.html.markdown | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/apl.html.markdown b/apl.html.markdown index f72da2c5..2fd6ec34 100644 --- a/apl.html.markdown +++ b/apl.html.markdown @@ -61,3 +61,9 @@ A ← 10 60 55 23 mean ← {(+/⍵)÷⍴⍵} mean A ⍝ 37 ``` + +## Further Reading + +- [APL Wiki](https://aplwiki.com/) +- An older version of APL book by the creator: [Kenneth Iverson - A Programming Language](https://www.softwarepreservation.org/projects/apl/Books/APROGRAMMING%20LANGUAGE/view) +- Additional Books: [APL Books](https://aplwiki.com/wiki/Books) From 34c5f5ad9a5388609c8cc9d49fb68caaf0e2051d Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sun, 19 May 2024 03:24:27 -0600 Subject: [PATCH 247/392] [opencv/*] fix empty links and format code --- de-de/opencv-de.html.markdown | 93 ++++++++++++++++++----------------- opencv.html.markdown | 69 +++++++++++++------------- zh-cn/opencv-cn.html.markdown | 88 ++++++++++++++++----------------- 3 files changed, 126 insertions(+), 124 deletions(-) diff --git a/de-de/opencv-de.html.markdown b/de-de/opencv-de.html.markdown index a2b55439..c39e5a65 100644 --- a/de-de/opencv-de.html.markdown +++ b/de-de/opencv-de.html.markdown @@ -8,11 +8,10 @@ translators: - ["Dennis Keller", "https://github.com/denniskeller"] lang: de-de --- -### OpenCV -OpenCV (Open Source Computer Vision) ist eine Bibliothek von Programmierfunktionen, +OpenCV (Open Source Computer Vision) ist eine Bibliothek von Programmierfunktionen, die hauptsächlich auf maschinelles Sehen in Echtzeit ausgerichtet ist. -Ursprünglich wurde OpenCV von Intel entwickelt. Später wurde es von +Ursprünglich wurde OpenCV von Intel entwickelt. Später wurde es von Willow Garage und dann Itseez (das später von Intel übernommen wurde) unterstützt. OpenCV unterstützt derzeit eine Vielzahl von Sprachen, wie C++, Python, Java uvm. @@ -20,9 +19,9 @@ OpenCV unterstützt derzeit eine Vielzahl von Sprachen, wie C++, Python, Java uv Bitte lies diesen Artikel für die Installation von OpenCV auf deinem Computer. -* Windows Installationsanleitung: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]() -* Mac Installationsanleitung (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]() -* Linux Installationsanleitung (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]() +* [Windows Installationsanleitung](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows) +* [Mac Installationsanleitung](https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a) (High Sierra) +* [Linux Installationsanleitung](https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv) (Ubuntu 18.04) ### Hier werden wir uns auf die Pythonimplementierung von OpenCV konzentrieren. @@ -33,16 +32,16 @@ img = cv2.imread('Katze.jpg') # Bild darstellen # Die imshow() Funktion wird verwendet um das Display darzustellen. -cv2.imshow('Image',img) +cv2.imshow('Image', img) # Das erste Argument ist der Titel des Fensters und der zweite Parameter ist das Bild # Wenn du den Fehler Object Type None bekommst, ist eventuell dein Bildpfad falsch. # Bitte überprüfe dann den Pfad des Bildes erneut. cv2.waitKey(0) -# waitKey() ist eine Tastaturbindungsfunktion, sie nimmt Argumente in +# waitKey() ist eine Tastaturbindungsfunktion, sie nimmt Argumente in # Millisekunden an. Für GUI Ereignisse MUSST du die waitKey() Funktion verwenden. # Ein Bild schreiben -cv2.imwrite('graueKatze.png',img) +cv2.imwrite('graueKatze.png', img) # Das erste Argument ist der Dateiname und das zweite ist das Bild # Konvertiert das Bild zu Graustufen @@ -51,10 +50,10 @@ gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Videoaufnahme von der Webcam cap = cv2.VideoCapture(0) # 0 ist deine Kamera, wenn du mehrere Kameras hast musst du deren Id eingeben -while(True): +while True: # Erfassen von Einzelbildern _, frame = cap.read() - cv2.imshow('Frame',frame) + cv2.imshow('Frame', frame) # Wenn der Benutzer q drückt -> beenden if cv2.waitKey(1) & 0xFF == ord('q'): break @@ -63,59 +62,60 @@ cap.release() # Wiedergabe von Videos aus einer Datei cap = cv2.VideoCapture('film.mp4') -while(cap.isOpened()): +while cap.isOpened(): _, frame = cap.read() # Das Video in Graustufen abspielen gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - cv2.imshow('frame',gray) + cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() # Zeichne eine Linie in OpenCV -# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) -cv2.line(img,(0,0),(511,511),(255,0,0),5) +# cv2.line(img, (x,y), (x1,y1), (color->r,g,b->0 to 255), thickness) +cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5) # Zeichne ein Rechteck -# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +# cv2.rectangle(img, (x,y), (x1,y1), (color->r,g,b->0 to 255), thickness) # thickness = -1 wird zum Füllen des Rechtecks verwendet -cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) +cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3) # Zeichne ein Kreis -cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) -cv2.circle(img,(200,90), 100, (0,0,255), -1) +# cv2.circle(img, (xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) +cv2.circle(img, (200, 90), 100, (0, 0, 255), -1) # Zeichne eine Ellipse -cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) +cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, 255, -1) # Text auf Bildern hinzufügen -cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) +cv2.putText(img, "Hello World!!!", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) # Bilder zusammenfügen img1 = cv2.imread('Katze.png') img2 = cv2.imread('openCV.jpg') -dst = cv2.addWeighted(img1,0.5,img2,0.5,0) +dst = cv2.addWeighted(img1, 0.5, img2, 0.5, 0) # Schwellwertbild # Binäre Schwellenwerte -_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY) -# Anpassbare Schwellenwerte -adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) +_, thresImg = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) +# Anpassbare Schwellenwerte +adapThres = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # Weichzeichnung von einem Bild # Gaußscher Weichzeichner -blur = cv2.GaussianBlur(img,(5,5),0) +blur = cv2.GaussianBlur(img, (5, 5), 0) # Rangordnungsfilter -medianBlur = cv2.medianBlur(img,5) +medianBlur = cv2.medianBlur(img, 5) # Canny-Algorithmus -img = cv2.imread('Katze.jpg',0) -edges = cv2.Canny(img,100,200) +img = cv2.imread('Katze.jpg', 0) +edges = cv2.Canny(img, 100, 200) # Gesichtserkennung mit Haarkaskaden # Lade die Haarkaskaden von https://github.com/opencv/opencv/blob/master/data/haarcascades/ herunter import cv2 import numpy as np + face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') @@ -123,31 +123,32 @@ img = cv2.imread('Mensch.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) aces = face_cascade.detectMultiScale(gray, 1.3, 5) -for (x,y,w,h) in faces: - cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) - roi_gray = gray[y:y+h, x:x+w] - roi_color = img[y:y+h, x:x+w] +for x, y, w, h in faces: + cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) + roi_gray = gray[y : y + h, x : x + w] + roi_color = img[y : y + h, x : x + w] eyes = eye_cascade.detectMultiScale(roi_gray) - for (ex,ey,ew,eh) in eyes: - cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) + for ex, ey, ew, eh in eyes: + cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2) -cv2.imshow('img',img) +cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() # destroyAllWindows() zerstört alle Fenster -# Wenn du ein bestimmtes Fenster zerstören möchtest, musst du den genauen Namen des +# Wenn du ein bestimmtes Fenster zerstören möchtest, musst du den genauen Namen des # von dir erstellten Fensters übergeben. ``` ### Weiterführende Literatur: -* Lade Kaskade hier herunter [https://github.com/opencv/opencv/blob/master/data/haarcascades]() -* OpenCV Zeichenfunktionen [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]() -* Eine aktuelle Sprachenreferenz kann hier gefunden werden [https://opencv.org]() -* Zusätzliche Ressourcen können hier gefunden werden [https://en.wikipedia.org/wiki/OpenCV]() + +* Lade Kaskade hier herunter [https://github.com/opencv/opencv/blob/master/data/haarcascades](https://github.com/opencv/opencv/blob/master/data/haarcascades) +* OpenCV Zeichenfunktionen [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html](https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html) +* Eine aktuelle Sprachenreferenz kann hier gefunden werden [https://opencv.org](https://opencv.org) +* Zusätzliche Ressourcen können hier gefunden werden [https://en.wikipedia.org/wiki/OpenCV](https://en.wikipedia.org/wiki/OpenCV) * Gute OpenCV Tutorials - * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]() - * [https://realpython.com/python-opencv-color-spaces]() - * [https://pyimagesearch.com]() - * [https://www.learnopencv.com]() - * [https://docs.opencv.org/master/]() + * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html) + * [https://realpython.com/python-opencv-color-spaces](https://realpython.com/python-opencv-color-spaces) + * [https://pyimagesearch.com](https://pyimagesearch.com) + * [https://www.learnopencv.com](https://www.learnopencv.com) + * [https://docs.opencv.org/master/](https://docs.opencv.org/master/) diff --git a/opencv.html.markdown b/opencv.html.markdown index ff91d2a5..9a931bcb 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -7,9 +7,9 @@ contributors: --- ### Opencv -OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. -Originally developed by Intel, it was later supported by Willow Garage then Itseez (which was later acquired by Intel). -Opencv currently supports wide variety of languages like, C++, Python, Java etc +OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. +Originally developed by Intel, it was later supported by Willow Garage then Itseez (which was later acquired by Intel). +OpenCV currently supports wide variety of languages like, C++, Python, Java etc #### Installation Please refer to these articles for installation of OpenCV on your computer. @@ -27,14 +27,14 @@ img = cv2.imread('cat.jpg') # Displaying the image # imshow() function is used to display the image -cv2.imshow('Image',img) +cv2.imshow('Image', img) # Your first arguement is the title of the window and second parameter is image # If you are getting error, Object Type None, your image path may be wrong. Please recheck the pack to the image cv2.waitKey(0) # waitKey() is a keyboard binding function and takes arguement in milliseconds. For GUI events you MUST use waitKey() function. # Writing an image -cv2.imwrite('catgray.png',img) +cv2.imwrite('catgray.png', img) # first arguement is the file name and second is the image # Convert image to grayscale @@ -42,11 +42,11 @@ gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Capturing Video from Webcam cap = cv2.VideoCapture(0) -#0 is your camera, if you have multiple camera, you need to enter their id -while(True): +# 0 is your camera, if you have multiple camera, you need to enter their id +while True: # Capturing frame-by-frame _, frame = cap.read() - cv2.imshow('Frame',frame) + cv2.imshow('Frame', frame) # When user presses q -> quit if cv2.waitKey(1) & 0xFF == ord('q'): break @@ -55,59 +55,60 @@ cap.release() # Playing Video from file cap = cv2.VideoCapture('movie.mp4') -while(cap.isOpened()): +while cap.isOpened(): _, frame = cap.read() # Play the video in grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - cv2.imshow('frame',gray) + cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() # Drawing The Line in OpenCV -# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) -cv2.line(img,(0,0),(511,511),(255,0,0),5) +# cv2.line(img, (x,y), (x1,y1), (color->r,g,b->0 to 255), thickness) +cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5) # Drawing Rectangle -# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +# cv2.rectangle(img, (x,y), (x1,y1), (color->r,g,b->0 to 255), thickness) # thickness = -1 used for filling the rectangle -cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) +cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3) # Drawing Circle -cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) -cv2.circle(img,(200,90), 100, (0,0,255), -1) +# cv2.circle(img, (xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) +cv2.circle(img, (200, 90), 100, (0, 0, 255), -1) # Drawing Ellipse -cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) +cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, 255, -1) # Adding Text On Images -cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) +cv2.putText(img, "Hello World!!!", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) # Blending Images img1 = cv2.imread('cat.png') img2 = cv2.imread('openCV.jpg') -dst = cv2.addWeighted(img1,0.5,img2,0.5,0) +dst = cv2.addWeighted(img1, 0.5, img2, 0.5, 0) # Thresholding image # Binary Thresholding -_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY) +_, thresImg = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # Adaptive Thresholding -adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) +adapThres = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # Blur Image # Gaussian Blur -blur = cv2.GaussianBlur(img,(5,5),0) +blur = cv2.GaussianBlur(img, (5, 5), 0) # Median Blur -medianBlur = cv2.medianBlur(img,5) +medianBlur = cv2.medianBlur(img, 5) # Canny Edge Detection -img = cv2.imread('cat.jpg',0) -edges = cv2.Canny(img,100,200) +img = cv2.imread('cat.jpg', 0) +edges = cv2.Canny(img, 100, 200) # Face Detection using Haar Cascades # Download Haar Cascades from https://github.com/opencv/opencv/blob/master/data/haarcascades/ import cv2 import numpy as np + face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml') @@ -115,21 +116,21 @@ img = cv2.imread('human.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, 1.3, 5) -for (x,y,w,h) in faces: +for x, y, w, h in faces: # Draw a rectangle around detected face - cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) - roi_gray = gray[y:y+h, x:x+w] - roi_color = img[y:y+h, x:x+w] + cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) + roi_gray = gray[y : y + h, x : x + w] + roi_color = img[y : y + h, x : x + w] eyes = eye_cascade.detectMultiScale(roi_gray) - for (ex,ey,ew,eh) in eyes: + for ex, ey, ew, eh in eyes: # Draw a rectangle around detected eyes - cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) + cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2) -cv2.imshow('img',img) +cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() -# destroyAllWindows() destroys all windows. +# destroyAllWindows() destroys all windows. # If you wish to destroy specific window pass the exact name of window you created. ``` @@ -139,7 +140,7 @@ cv2.destroyAllWindows() * OpenCV drawing Functions [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html](https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html) * An up-to-date language reference can be found at [https://opencv.org](https://opencv.org) * Additional resources may be found at [https://en.wikipedia.org/wiki/OpenCV](https://en.wikipedia.org/wiki/OpenCV) -* Good OpenCv Tutorials +* Good OpenCV Tutorials * [https://realpython.com/python-opencv-color-spaces](https://realpython.com/python-opencv-color-spaces) * [https://pyimagesearch.com](https://pyimagesearch.com) * [https://www.learnopencv.com](https://www.learnopencv.com) diff --git a/zh-cn/opencv-cn.html.markdown b/zh-cn/opencv-cn.html.markdown index 2932e586..596430f6 100644 --- a/zh-cn/opencv-cn.html.markdown +++ b/zh-cn/opencv-cn.html.markdown @@ -8,18 +8,18 @@ translators: - ["GengchenXU", "https://github.com/GengchenXU"] lang: zh-cn --- -### Opencv -Opencv(开源计算机视觉)是一个编程功能库,主要面向实时计算机视觉。最初由英特尔开发,后来由Willow Garage,然后Itseez(后来被英特尔收购)支持。Opencv 目前支持多种语言,如C++、Python、Java 等 +OpenCV(开源计算机视觉)是一个编程功能库,主要面向实时计算机视觉。最初由英特尔开发,后来由Willow Garage,然后Itseez(后来被英特尔收购)支持。OpenCV 目前支持多种语言,如C++、Python、Java 等 #### 安装 + 有关在计算机上安装 OpenCV,请参阅这些文章。 -* Windows 安装说明: [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows]() -* Mac 安装说明 (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a]() -* Linux 安装说明 (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv]() +* [Windows 安装说明](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_setup/py_setup_in_windows/py_setup_in_windows.html#install-opencv-python-in-windows) +* [Mac 安装说明](https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a) (High Sierra) +* [Linux 安装说明](https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv) (Ubuntu 18.04) -### 在这里,我们将专注于 OpenCV 的 python 实现 +### 在这里,我们将专注于 OpenCV 的 Python 实现 ```python # OpenCV读取图片 @@ -28,14 +28,14 @@ img = cv2.imread('cat.jpg') # 显示图片 # imshow() 函数被用来显示图片 -cv2.imshow('Image',img) +cv2.imshow('Image', img) # 第一个参数是窗口的标题,第二个参数是image # 如果你得到错误,对象类型为None,你的图像路径可能是错误的。请重新检查图像包 cv2.waitKey(0) # waitKey() 是一个键盘绑定函数,参数以毫秒为单位。对于GUI事件,必须使用waitKey()函数。 # 保存图片 -cv2.imwrite('catgray.png',img) +cv2.imwrite('catgray.png', img) # 第一个参数是文件名,第二个参数是图像 # 转换图像灰度 @@ -43,11 +43,11 @@ gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 从摄像头捕捉视频 cap = cv2.VideoCapture(0) -#0 是你的相机,如果你有多台相机,你需要输入他们的id -while(True): +# 0 是你的相机,如果你有多台相机,你需要输入他们的id +while True: # 一帧一帧地获取 _, frame = cap.read() - cv2.imshow('Frame',frame) + cv2.imshow('Frame', frame) # 当用户按下q ->退出 if cv2.waitKey(1) & 0xFF == ord('q'): break @@ -56,54 +56,54 @@ cap.release() # 在文件中播放视频 cap = cv2.VideoCapture('movie.mp4') -while(cap.isOpened()): +while cap.isOpened(): _, frame = cap.read() # 灰度播放视频 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) - cv2.imshow('frame',gray) + cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() # 在OpenCV中画线 -# cv2.line(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness)(注 color颜色rgb参数 thickness粗细) -cv2.line(img,(0,0),(511,511),(255,0,0),5) +# cv2.line(img, (x,y), (x1,y1), (color->r,g,b->0 to 255), thickness)(注 color颜色rgb参数 thickness粗细) +cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5) # 画矩形 -# cv2.rectangle(img,(x,y),(x1,y1),(color->r,g,b->0 to 255),thickness) +# cv2.rectangle(img, (x,y), (x1,y1), (color->r,g,b->0 to 255), thickness) # 粗细= -1用于填充矩形 -cv2.rectangle(img,(384,0),(510,128),(0,255,0),3) +cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3) # 画圆 -cv2.circle(img,(xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) -cv2.circle(img,(200,90), 100, (0,0,255), -1) +# cv2.circle(img, (xCenter,yCenter), radius, (color->r,g,b->0 to 255), thickness) +cv2.circle(img, (200, 90), 100, (0, 0, 255), -1) # 画椭圆 -cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1) +cv2.ellipse(img, (256, 256), (100, 50), 0, 0, 180, 255, -1) # 在图像上增加文字 -cv2.putText(img,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) +cv2.putText(img, "Hello World!!!", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255) # 合成图像 img1 = cv2.imread('cat.png') img2 = cv2.imread('openCV.jpg') -dst = cv2.addWeighted(img1,0.5,img2,0.5,0) +dst = cv2.addWeighted(img1, 0.5, img2, 0.5, 0) # 阈值图像 # 二进制阈值 -_,thresImg = cv2.threshold(img,127,255,cv2.THRESH_BINARY) +_, thresImg = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY) # Adaptive Thresholding -adapThres = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2) +adapThres = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # 模糊的形象 # 高斯模糊 -blur = cv2.GaussianBlur(img,(5,5),0) +blur = cv2.GaussianBlur(img, (5, 5), 0) # 模糊中值 -medianBlur = cv2.medianBlur(img,5) +medianBlur = cv2.medianBlur(img, 5) # Canny 边缘检测 -img = cv2.imread('cat.jpg',0) -edges = cv2.Canny(img,100,200) +img = cv2.imread('cat.jpg', 0) +edges = cv2.Canny(img, 100, 200) # 用Haar Cascades进行人脸检测 # 下载 Haar Cascades 在 https://github.com/opencv/opencv/blob/master/data/haarcascades/ @@ -116,30 +116,30 @@ img = cv2.imread('human.jpg') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) aces = face_cascade.detectMultiScale(gray, 1.3, 5) -for (x,y,w,h) in faces: - cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) - roi_gray = gray[y:y+h, x:x+w] - roi_color = img[y:y+h, x:x+w] +for x, y, w, h in faces: + cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) + roi_gray = gray[y : y + h, x : x + w] + roi_color = img[y : y + h, x : x + w] eyes = eye_cascade.detectMultiScale(roi_gray) - for (ex,ey,ew,eh) in eyes: - cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2) + for ex, ey, ew, eh in eyes: + cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2) -cv2.imshow('img',img) +cv2.imshow('img', img) cv2.waitKey(0) cv2.destroyAllWindows() -# destroyAllWindows() destroys all windows. +# destroyAllWindows() destroys all windows. # 如果您希望销毁特定窗口,请传递您创建的窗口的确切名称。 ``` ### 进一步阅读: -* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades]() -* OpenCV 绘图函数 [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html]() -* 最新的语言参考 [https://opencv.org]() -* 更多的资源 [https://en.wikipedia.org/wiki/OpenCV]() +* Download Cascade from [https://github.com/opencv/opencv/blob/master/data/haarcascades](https://github.com/opencv/opencv/blob/master/data/haarcascades) +* OpenCV 绘图函数 [https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html](https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html) +* 最新的语言参考 [https://opencv.org](https://opencv.org) +* 更多的资源 [https://en.wikipedia.org/wiki/OpenCV](https://en.wikipedia.org/wiki/OpenCV) * 优秀的的 OpenCV 教程 - * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html]() - * [https://realpython.com/python-opencv-color-spaces]() - * [https://pyimagesearch.com]() - * [https://www.learnopencv.com]() + * [https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html](https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_tutorials.html) + * [https://realpython.com/python-opencv-color-spaces](https://realpython.com/python-opencv-color-spaces) + * [https://pyimagesearch.com](https://pyimagesearch.com) + * [https://www.learnopencv.com](https://www.learnopencv.com) From 797b965edd18cbdf68d2d6fc9e2e7ddd5b069ff8 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sun, 19 May 2024 03:27:05 -0600 Subject: [PATCH 248/392] Fix empty links --- it-it/dynamic-programming-it.html.markdown | 9 ++-- tr-tr/dynamic-programming-tr.html.markdown | 13 ++--- tr-tr/ruby-tr.html.markdown | 56 ++++++++++------------ 3 files changed, 33 insertions(+), 45 deletions(-) diff --git a/it-it/dynamic-programming-it.html.markdown b/it-it/dynamic-programming-it.html.markdown index 9c7bd9b6..eb35192e 100644 --- a/it-it/dynamic-programming-it.html.markdown +++ b/it-it/dynamic-programming-it.html.markdown @@ -45,11 +45,10 @@ for i=0 to n-1 ### Alcuni famosi problemi DP -- Floyd Warshall Algorithm - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() -- Integer Knapsack Problem - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() -- Longest Common Subsequence - Tutorial e Codice sorgente in C del programma: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() - +- [Floyd Warshall Algorithm](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) - Tutorial e Codice sorgente in C del programma +- [Integer Knapsack Problem](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) - Tutorial e Codice sorgente in C del programma +- [Longest Common Subsequence](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) - Tutorial e Codice sorgente in C del programma ## Risorse online -* [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) +- [codechef](https://www.codechef.com/wiki/tutorial-dynamic-programming) diff --git a/tr-tr/dynamic-programming-tr.html.markdown b/tr-tr/dynamic-programming-tr.html.markdown index 573d9e0f..1d47531a 100644 --- a/tr-tr/dynamic-programming-tr.html.markdown +++ b/tr-tr/dynamic-programming-tr.html.markdown @@ -17,11 +17,8 @@ Her zaman hatırla! "Geçmiş hatırlayamayanlar, aynı şeyleri tekrar yaşamay ## Bu tür sorunların çözüm yolları -1. Yukarıdan aşağıya: -Verilen problemi çözerek çözmeye başlayın. Sorunun zaten çözüldüğünü görürseniz, kaydedilen cevabı döndürmeniz yeterlidir. Çözülmemişse, çözünüz ve cevabı saklayınız. Bu genellikle düşünmek kolaydır ve çok sezgiseldir. Buna Ezberleştirme denir. - -2. Aşağıdan yukarıya: -Sorunu analiz edin ve alt problemlerin çözülme sırasını görün ve önemsiz alt sorundan verilen soruna doğru başlayın. Bu süreçte, problemi çözmeden önce alt problemlerin çözülmesi gerekmektedir. Buna Dinamik Programlama denir. +1. Yukarıdan aşağıya: Verilen problemi çözerek çözmeye başlayın. Sorunun zaten çözüldüğünü görürseniz, kaydedilen cevabı döndürmeniz yeterlidir. Çözülmemişse, çözünüz ve cevabı saklayınız. Bu genellikle düşünmek kolaydır ve çok sezgiseldir. Buna Ezberleştirme denir. +2. Aşağıdan yukarıya: Sorunu analiz edin ve alt problemlerin çözülme sırasını görün ve önemsiz alt sorundan verilen soruna doğru başlayın. Bu süreçte, problemi çözmeden önce alt problemlerin çözülmesi gerekmektedir. Buna Dinamik Programlama denir. ## Örnek @@ -44,9 +41,9 @@ for i=0 to n-1 ### Bazı Ünlü Dinamik Programlama Problemleri -- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code]() -- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem]() -- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence]() +- Floyd Warshall Algorithm - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code](http://www.thelearningpoint.net/computer-science/algorithms-all-to-all-shortest-paths-in-graphs---floyd-warshall-algorithm-with-c-program-source-code) +- Integer Knapsack Problem - Tutorial and C Program source code: [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---the-integer-knapsack-problem) +- Longest Common Subsequence - Tutorial and C Program source code : [http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence](http://www.thelearningpoint.net/computer-science/algorithms-dynamic-programming---longest-common-subsequence) ## Online Kaynaklar diff --git a/tr-tr/ruby-tr.html.markdown b/tr-tr/ruby-tr.html.markdown index 7bc21c83..b6ada7f7 100644 --- a/tr-tr/ruby-tr.html.markdown +++ b/tr-tr/ruby-tr.html.markdown @@ -7,14 +7,9 @@ contributors: lang: tr-tr --- -# Dile nazik bir giriş. - -## Ruby Nedir ? - Ruby, doğrudan bir Google aramasıyla aklınızdakini bulmanız zor olabilir. İngilizce bu kelime, `Ruby` (IPA: ˈruːbi) "kırmızı taş" anlamına gelen Fransızca kökenli bir kelime olan `rubi`'den gelmektedir. -Yaratıcısı tarafından, yine esinlenilen bir dil olarak ortaya çıkan `Ruby`, Perl, Smalltalk, Eiffel, Ada, Lisp programlama dillerinin en iyi özelliklerini almıştır. ! [İmperativ]() programlama mentalitesi üzerine kurmayı seçtiği bu teknoloji, günümüzde sektöründe öncü. - +Yaratıcısı tarafından, yine esinlenilen bir dil olarak ortaya çıkan `Ruby`, Perl, Smalltalk, Eiffel, Ada, Lisp programlama dillerinin en iyi özelliklerini almıştır. ! İmperativ programlama mentalitesi üzerine kurmayı seçtiği bu teknoloji, günümüzde sektöründe öncü. ## Tarihçe @@ -22,8 +17,6 @@ Ruby 1995’te halka duyurulduğundan beri, dünya çapında programcıların di Daha sonraları `Ruby`, dünya çapında programlama dillerinin büyümesini ve popülaritesini ölçen dizinlerin (TIOBE dizini gibi) çoğunda ilk 10 içinde yer almıştır. Büyümenin çoğu, Ruby ile yazılmış yazılımların popülaritesiyle ilgilidir, özellikle de Ruby on Rails web çatısıyla. -! [kaynak]() - ## Sektördeki Konumu ve Geleceği ? Çoğu uzmana göre, şu anda sadece `Rails` teknolojisi için bir betik dili olarak sıkışmış durumda. @@ -69,7 +62,7 @@ Diğer gerçeklemeler için, lütfen ileri okumaya danışınız. ### bu veri yapısıdır. # Tam sayı örneği. -1453 #=> 1453 +1453 #=> 1453 ## Okunabilirlik için, binlik ya da ondalık kısmını `_` ile ## ayırmak mümkündür ve bu karakter tümüyle görmezden gelinir. @@ -119,7 +112,7 @@ false #=> false ## Metin sabitleri 'Bu, bir metin ifadesi.' -## Kaçışlar için +## Kaçışlar için 'Kaçışlar için "\\"' #=> "Kaçışlar için \"\\\"" ## Alternatif ise çift tırnaklı ifadeler. @@ -138,7 +131,7 @@ false #=> false "\s" #=> "\s" ## -- -# Karakterler +# Karakterler ## -- ## Basitçe önlerine soru işareti getirilmiş @@ -149,7 +142,7 @@ false #=> false ## -- # Semboller ## -- -## Ruby'de semboller, temsilleri bakımından +## Ruby'de semboller, temsilleri bakımından ## Clojure'daki semboller ile benzerlerdir. :sembol #=> :sembol @@ -452,7 +445,7 @@ Range.new(0, 10) #=> 0..10 #=> [1, 2, 3, 4] ## | operatörü bizi, nihai sonuçtaki tekrarlı veriden koruyor. -## Peki ya bir diziyi, eleman bazında diğeriyle +## Peki ya bir diziyi, eleman bazında diğeriyle ## süzmek istersek ? [1,2] - [2,3,4] #=> [1] @@ -481,7 +474,7 @@ Range.new(0, 10) #=> 0..10 ## eğer vermeseydik, dizinin ilk elemanı olacaktı. ## Tabi, daha kolay bir yolu var; -["", +["", ""].reduce(:+) #=> "" ## reduce metodu, ikili bir operasyonu (akümülatör için metot!) @@ -504,7 +497,7 @@ Range.new(0, 10) #=> 0..10 # -------------------------------- ## -- -# Rakamlar +# Rakamlar ## -- ## Sayısal değerlerin diğer tiplere dönüşümü; @@ -541,7 +534,7 @@ Range.new(0, 10) #=> 0..10 ## -- -# Mantıksal +# Mantıksal ## -- ## Mantıksal -> Metinsel @@ -573,7 +566,7 @@ false.to_s #=> "false" ## -- -# Metinsel +# Metinsel ## -- ## Metinsel -> Sayısal @@ -626,7 +619,7 @@ false.to_s #=> "false" ## -- -# Sembol +# Sembol ## -- ## Sembol -> Metinsel @@ -634,7 +627,7 @@ false.to_s #=> "false" ## Başka bir dönüşüm için dilin bir teşviki yoktur. ## -- -# Diziler +# Diziler ## -- ## Dizi -> Metinsel @@ -642,7 +635,7 @@ false.to_s #=> "false" ## -- -# Eşlemeler +# Eşlemeler ## -- ## Eşleme -> Dizi @@ -703,7 +696,7 @@ class Varlık def initialize() @varlık_değişkeni = 101 end - + def göster() puts "Varlık değişkeni: #@varlık_değişkeni" end @@ -739,7 +732,7 @@ class Sınıf def initialize() @@sınıf_nesne_sayısı += 1 end - + def göster() puts "Sınıf sayısı: #@@sınıf_nesne_sayısı" end @@ -929,7 +922,7 @@ end ## Şimdi tanımı çağıralım selamla_sonra_çağır {puts 'Çağrı, gerçekleşti!'} #= Selamlar! -#= Çağrı, gerçekleşti! +#= Çağrı, gerçekleşti! #=> nil ## Çağırım, kendini çağıran kaynağa nil döndürmekte. ## Değerlendirmenin sonucunda, Ruby yorumlayıcısı, @@ -1084,7 +1077,7 @@ end ## -- ## Sonlandırıcı ( break ) kontrol ifadesi: -## Bu kontrol ifadesi yürütüldüğünde, çalışma zamanını +## Bu kontrol ifadesi yürütüldüğünde, çalışma zamanını ## en iç tekrarlı bloktan çıkarır. ## Örnek: @@ -1112,7 +1105,7 @@ end # -------------------------------- ## -- -## __ENCODING__: +## __ENCODING__: ## Bu anahtar kelime size yorumlayıcı kodlama türünü verecektir. __ENCODING__ @@ -1299,13 +1292,13 @@ b = B.new 1, 2 - Klavyeden bastığınız herhangi bir tuş. - Fare hareketleriniz ya da tıklamalarınız. - Mikrofonunuzun aldığı sesler. - + Çıktı örnekleri: - Herhangi bir dil ifadesinin sonucu. - Dijital bir ses dosyasının sese dönüşmesi. - Ekranda gördükleriniz. - - Fakat endişelenmeyin, G/Ç derken, şu anda + + Fakat endişelenmeyin, G/Ç derken, şu anda biz sadece Ruby'de, - Dosya okuma/yazma. - Ekrana metin yazdırma / Bilgi okuma. @@ -1441,7 +1434,7 @@ soket.recv 80 ## tekerlekleri, direksiyonu, kasası, ve diğer parçalarıyla. ## Ama bu, tam tanım değildir. NYP'de, Nesneler, ## Bilgilere ( evet, varlık olarak başka nesneler de sayılabilir ) -## ve bu bilgileri yönetecek ( hesaplamalar gerçekleştirecek +## ve bu bilgileri yönetecek ( hesaplamalar gerçekleştirecek ## ya da aksiyonlar alacak -- G/Ç -- gibi ) metotlara sahiptir. ## Bir nesnenin en net tanımı böyle yapılabilirken, @@ -1495,7 +1488,7 @@ class Araba def initialize(hız) @hız = hız end - + def git! puts 'Hınn, hınn!' end @@ -1583,7 +1576,7 @@ araba = Araba.new 100 ## Lütfen detaylı bilgi için ileri okumaya başvurunuz. ``` -# İleri okumalar. +## İleri okumalar. Tümüyle İngilizce olan bu ileri okumalara inat, bu detaylı özgün Türkçe içeriği üretmek istedim. Dilerim, benden sonra katkıda bulunanlar olur. @@ -1595,4 +1588,3 @@ Dilerim, benden sonra katkıda bulunanlar olur. - [Ruby Gerçeklemeleri Listesi](https://github.com/codicoscepticos/ruby-implementations) Ruby'nin farklı platformlardaki gerçeklemeleri. Opal ve Topaz dikkat çekenleridir. - [The Object-Oriented Thought Process](https://www.amazon.com/Object-Oriented-Thought-Process-Developers-Library/dp/0321861272) kitap, bir paradigma olarak NYP ve düşünce yapısından bahsediyor. Bir paradigma olarak, NYP, türetildiği temel paradigmadan ne almış, başka paradigmalara ne kadar imkan sağlıyor ve paralel paradigma uyumu konusunda tüm sorularınıza cevap bulabilirsiniz. Yazar, belli etmese de, pragmatik bir yaklaşımda. - [Block Argument](https://docs.ruby-lang.org/en/2.4.0/syntax/methods_rdoc.html#label-Block+Argument) Ruby Blokları ve yield hakkındaki Ruby resmi döküman sayfası ve alt başlığı. -- [A Theory of Objects]() Class-Based Languages başlığında inceleniyorlar. From 036500080b4f2dbbe67d7af0224bc2f7c420c0a6 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sun, 19 May 2024 06:39:54 -0600 Subject: [PATCH 249/392] [whip/*] delete (#4949) --- es-es/whip-es.html.markdown | 255 ------------------------------------ pt-br/whip-pt.html.markdown | 247 ---------------------------------- whip.html.markdown | 241 ---------------------------------- 3 files changed, 743 deletions(-) delete mode 100644 es-es/whip-es.html.markdown delete mode 100644 pt-br/whip-pt.html.markdown delete mode 100644 whip.html.markdown diff --git a/es-es/whip-es.html.markdown b/es-es/whip-es.html.markdown deleted file mode 100644 index 7c2f4bd2..00000000 --- a/es-es/whip-es.html.markdown +++ /dev/null @@ -1,255 +0,0 @@ ---- -language: whip -contributors: - - ["Tenor Biel", "http://github.com/L8D"] -translators: - - ["Daniel Zendejas", "https://github.com/DanielZendejas"] -author: Tenor Biel -author_url: http://github.com/L8D -filename: whip-es.lisp -lang: es-es ---- -Tutorial de Whip en español. - -Whip es un dialecto de LISP hecho para escribir código y conceptos -simples. Ha tomado prestado bastante de la sintaxis de Haskell -(un lenguaje no relacionado). - -Esta documentación fue escrita por el creador del lenguaje - -```scheme -; Los comentarios son como en LISP, con punto y coma... - -; La mayoría de las sentencias de primer nivel están dentro de -; "formas". Una forma no es más que cosas dentro de paréntesis -no_en_la_forma -(en_la_form) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 1. Números, Strings y Operadores - -;Whip tiene un tipo para números (es el estándar 64-bit IEEE 754 double, de JS) -3 ; => 3 -1.5 ; => 1.5 - -; Las funciones son llamadas si son el primer elemento de una forma -(funcion_llamada argumentos) - -; La mayoría de los operadores se hacen con funciones -; Toda la aritmética básica es bastante estándar -(+ 1 1) ; => 2 -(- 2 1) ; => 1 -(* 1 2) ; => 2 -(/ 2 1) ; => 2 -; incluso el módulo -(% 9 4) ; => 1 -; división impar al estilo de JavaScript. -(/ 5 2) ; => 2.5 - -; Las formas anidadas funcionan como se espera. -(* 2 (+ 1 3)) ; => 8 - -; Hay un tipo booleano. -true -false - -; Los Strings son creados con comillas dobles ". -"Hola mundo" - -; Los caracteres solos se declaran con comillas simples '. -'a' - -; La negación usa la función 'not'. -(not true) ; => false -(not false) ; => true - -; La mayoría de las funcions que no vienen de Haskell tienen -; atajos. La función 'not' también se puede declarar con '!'. -(! (! true)) ; => true - -; La igualdad es `equal` o `=`. -(= 1 1) ; => true -(equal 2 1) ; => false - -; Por ejemplo, la desigualdad sería combinar la función 'not' con -; la función de igualdad -(! (= 2 1)) ; => true - -; Más comparaciones -(< 1 10) ; => true -(> 1 10) ; => false -; y su contraparte textual. -(lesser 1 10) ; => true -(greater 1 10) ; => false - -; Los Strings pueden concatenarse con la función +. -(+ "Hola " "mundo!") ; => "Hello world!" - -; También puedes usar las comparativas de JavaScript -(< 'a' 'b') ; => true -; ...y la coerción de tipos -(= '5' 5) - -; La función 'at' o @ accesa a los caracteres dentro de los strings, -; empezando en 0. -(at 0 'a') ; => 'a' -(@ 3 "foobar") ; => 'b' - -; También están las variables `null` and `undefined`. -null; usado para indicar una falta de valor deliberada. -undefined; usado para indicar un valor que aún no está definido. - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 2. Variables, Listas y Diccionarios - -; Las variables son declaradas con las funciones `def` o `let`. -; Las variables que aún no son asignadas tendrán el valor `undefined`. -(def mi_variable 5) -; `def` asignará la variable al contexto global. -; `let` asignará la variable al contexto local, -; y tiene una sintaxis distinta. -(let ((mi_variable 5)) (+ mi_variable 5)) ; => 10 -(+ mi_variable 5) ; = undefined + 5 => undefined - -; Las listas son arreglos de valores de cualquier tipo. -; Básicamente, son formas sin funciones al inicio. -(1 2 3) ; => [1, 2, 3] (sintaxis JavaScript) - -; Los diccionarios son el equivalente en Whip de los 'objetos' de JavaScript, -; los 'dicts' de Python o los 'hashes' de Ruby: una colección desordenada -; de pares llave-valor -{"llave1" "valor1" "llave2" 2 3 3} - -; Las llaves son sólo valores, identificadores, números o strings. -(def mi_diccionario {mi_llave "mi_valor" "mi otra llave" 4}) -; Pero con Whip, los diccionarios son leidos así: -; "llave" "espacio en blanco" "valor" "espacio en blanco" -{"llave" "valor" -"otra llave" -1234 -} - -; Las definiciones de los diccionarios pueden accesarse con la función @ -; (como los strings y las listas) -(@ "mi otra llave" mi_diccionario) ; => 4 - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 3. Logica y secuencias de control - -; La funcion `if` es bastante simple, aunque distinta que en otros lenguajes. -(if true "regresa esto si es true" "regresa esto si es false") -; => "regresa esto si es true" - -; Y para el operador ternario `?` -(? false true false) ; => false - -? `both` es un 'y' lógico, mientras que la función `either` es un 'o'. -(both true true) ; => true -(both true false) ; => false -(either true false) ; => true -(either false false) ; => false -; Y sus atajos son '&' y '^' respectivamente -; & => both -; ^ => either -(& true true) ; => true -(^ false true) ; => true - -;;;;;;;;; -; Lambdas - -; Las Lambdas en Whip son declaradas con las funciones `lambda` o `->`. -; Las funciones regulares en realidad sólo son lambdas con nombre. -(def mi_funcion (-> (x y) (+ (+ x y) 10))) -; | | | | -; | | | valor regresado(estas son las variables argumentos) -; | | argumentos -; | declaración de lambda -; | -; nombre de la lambda - -(mi_funcion 10 10) ; = (+ (+ 10 10) 10) => 30 - -; Obviamente, todas las lambdas por definición son anónimas y -; técnicamente siempre usadas anónimamente. Redundancia. -((lambda (x) x) 10) ; => 10 - -;;;;;;;;;;;;;;;; -; Comprensiones - -; `range` o `..` genera una lista de números que comprende -; cada entero dentro de los argumentos. -(range 1 5) ; => (1 2 3 4 5) -(.. 0 2) ; => (0 1 2) - -; `map` aplica su primer argumento (que debe ser una función) -; al siguiente argumento (que es una lista). -(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) - -; Reducir -(reduce + (.. 1 5)) -; equivale a -((+ (+ (+ 1 2) 3) 4) 5) - -; Nota: map y reduce no tienen atajos. - -; `slice` o `\` es idéntico a la función .slice() de JavaScript -; Pero toma la lista del primer argumento, no del último. -(slice (.. 1 5) 2) ; => (3 4 5) -(\ (.. 0 100) -5) ; => (96 97 98 99 100) - -; `append` o `<<` se explica solo. -(append 4 (1 2 3)) ; => (1 2 3 4) -(<< "bar" ("foo")) ; => ("foo" "bar") - -; Length se explica solo. -(length (1 2 3)) ; => 3 -(_ "foobar") ; => 6 - -;;;;;;;;;;;;;;; -; Elementos de Haskell - -; Primer elemento en una lista -(head (1 2 3)) ; => 1 - -; Lista del segundo elemento al último en una lista -(tail (1 2 3)) ; => (2 3) - -; Último elemento en una lista -(last (1 2 3)) ; => 3 - -; Contrario a `tail` -(init (1 2 3)) ; => (1 2) - -; Lista del primer elemento al argumento -(take 1 (1 2 3 4)) ; (1 2) - -; Contrario a `take` -(drop 1 (1 2 3 4)) ; (3 4) - -; Valor más pequeño de una lista -(min (1 2 3 4)) ; 1 - -; Valor más grande de una lista -(max (1 2 3 4)) ; 4 - -; Comprobar que el elemento está en la lista -(elem 1 (1 2 3)) ; true -(elem "foo" {"foo" "bar"}) ; true -(elem "bar" {"foo" "bar"}) ; false - -; Invertir el orden de la lista -(reverse (1 2 3 4)) ; => (4 3 2 1) - -; Comprobar si un elemento es par o impar -(even 1) ; => false -(odd 1) ; => true - -; Separar string en una lista de strings, separados por espacios -(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") -; Juntar lista de strings. -(unwords ("foo" "bar")) ; => "foobar" -(pred 21) ; => 20 -(succ 20) ; => 21 -``` - -Para más información, revisa el [repositorio](http://github.com/L8D/whip) diff --git a/pt-br/whip-pt.html.markdown b/pt-br/whip-pt.html.markdown deleted file mode 100644 index b11faf28..00000000 --- a/pt-br/whip-pt.html.markdown +++ /dev/null @@ -1,247 +0,0 @@ ---- -language: whip -contributors: - - ["Tenor Biel", "http://github.com/L8D"] - - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] -author: Tenor Biel -author_url: http://github.com/L8D -translators: - - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] -lang: pt-br -filename: whip-pt.lisp ---- - -Whip é um dialeto de Lisp feito para construir scripts e trabalhar com -conceitos mais simples. -Ele também copia muitas funções e sintaxe de Haskell (uma linguagem não correlata) - -Esse documento foi escrito pelo próprio autor da linguagem. Então é isso. - -```scheme -; Comentário são como em Lisp. Pontos-e-vírgulas... - -; A maioria das declarações de primeiro nível estão dentro de "listas" -; que nada mais são que coisas entre parênteses separadas por espaços em branco -nao_é_uma_lista -(uma lista) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 1. Números, texto e operadores - -; Whip tem um tipo numérico (que é um double de 64 bits IEE 754, do JavaScript) -3 ; => 3 -1.5 ; => 1.5 - -; Funções são chamadas se elas são o primeiro elemento em uma lista -(funcao_chamada argumentos) - -; A maioria das operações são feitas com funções -; Todas as funções aritméticas básicas são bem diretas -(+ 1 1) ; => 2 -(- 2 1) ; => 1 -(* 1 2) ; => 2 -(/ 2 1) ; => 2 -; até mesmo o módulo -(% 9 4) ; => 1 -; Divisão não inteira ao estilo JavaScript. -(/ 5 2) ; => 2.5 - -; Aninhamento de listas funciona como esperado. -(* 2 (+ 1 3)) ; => 8 - -; Há um tipo boleano. -true -false - -; Textos são criados com ". -"Hello, world" - -; Caracteres são criados com '. -'a' - -; Para negação usa-se a função 'not'. -(not true) ; => false -(not false) ; => true - -; Mas a maioria das funções não-haskell tem atalhos -; o atalho para "não" é um '!'. -(! (! true)) ; => true - -; Igualdade é `equal` ou `=`. -(= 1 1) ; => true -(equal 2 1) ; => false - -; Por exemplo, desigualdade pode ser verificada combinando as funções -;`not` e `equal`. -(! (= 2 1)) ; => true - -; Mais comparações -(< 1 10) ; => true -(> 1 10) ; => false -; e suas contra partes para texto. -(lesser 1 10) ; => true -(greater 1 10) ; => false - -; Texto pode ser concatenado com +. -(+ "Hello " "world!") ; => "Hello world!" - -; Você pode usar as características comparativas do JavaScript. -(< 'a' 'b') ; => true -; ... e coerção de tipos -(= '5' 5) - -; As funções `at` ou `@` acessarão caracteres de um texto, começando em 0. -(at 0 'a') ; => 'a' -(@ 3 "foobar") ; => 'b' - -; Também existem as variáveis `null` e `undefined`. -null ; usada para indicar a ausência de algum valor -undefined ; usada para indicar que um valor não foi informado - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 2. Variáveis, matrizes e dicionários - -; Variáveis são declaradas com as funções `def` ou `let`. -; Variáveis que não tiveram valor atribuído serão `undefined`. -(def some_var 5) -; `def` deixará a variável no contexto global. -; `let` deixará a variável no contexto local, e tem uma sintaxe estranha. -(let ((a_var 5)) (+ a_var 5)) ; => 10 -(+ a_var 5) ; = undefined + 5 => undefined - -; Matrizes são listas de valores de qualquer tipo. -; Elas basicamente são listas sem funções no início -(1 2 3) ; => [1, 2, 3] (sintaxe JavaScript) - -; Dicionários em Whip são o equivalente a 'object' em JavaScript ou -; 'dict' em python ou 'hash' em Ruby: eles são uma coleção desordenada -de pares chave-valor. -{"key1" "value1" "key2" 2 3 3} - -; Chaves podem ser apenas identificadores, números ou texto. -(def my_dict {my_key "my_value" "my other key" 4}) -; Mas em Whip, dicionários são parceados como: valor, espaço, valor; -; com mais espaço entre cada. Então isso significa que -{"key" "value" -"another key" -1234 -} -é avaliado da mesma forma que -{"key" "value" "another key" 1234} - -; Dicionários podem ser acessados usando a função `at` -; (como em texto e listas) -(@ "my other key" my_dict) ; => 4 - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 3. Lógica e controle de fluxo - -; A função `if` é muito simples, ainda que muito diferente do que em muitas -linguagens imperativas. -(if true "returned if first arg is true" "returned if first arg is false") -; => "returned if first arg is true" - -; E por conta do legado operador ternário -; `?` é o atalho não utilizado para `if`. -(? false true false) ; => false - -; `both` é uma declaração lógica `and`, e `either` é o `or` lógico. -(both true true) ; => true -(both true false) ; => false -(either true false) ; => true -(either false false) ; => false -; E seus atalhos são -; & => both -; ^ => either -(& true true) ; => true -(^ false true) ; => true - -;;;;;;;;; -; Lambdas - -; Lambdas em Whip são declaradas com as funções `lambda` ou `->`. -; E funções são na verdade lambdas com nomes. -(def my_function (-> (x y) (+ (+ x y) 10))) -; | | | | -; | | | valor retornado (com escopo contento argumentos) -; | | argumentos -; | declaração de funções lambda -; | -; nome do lambda a ser declarado - -(my_function 10 10) ; = (+ (+ 10 10) 10) => 30 - -; Obviamente, todos os lambdas por definição são anônimos e -; tecnicamente sempre usados anonimamente. Redundância. -((lambda (x) x) 10) ; => 10 - -;;;;;;;;;;;;;;;; -; Comprehensions - -; `range` or `..` geram uma lista dos números para -; cada número entre seus dois argumentos. -(range 1 5) ; => (1 2 3 4 5) -(.. 0 2) ; => (0 1 2) - -; `map` aplica seu primeiro argumento (que deve ser um lambda/função) -; a cada item dos argumentos seguintes (que precisa ser uma lista) -(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) - -; Reduce -(reduce + (.. 1 5)) -; equivalente a -((+ (+ (+ 1 2) 3) 4) 5) - -; Nota: map e reduce não possuem atalhos - -; `slice` ou `\` é similar ao .slice() do JavaScript -; mas veja que ele pega uma lista como primeiro argumento, não o último. -(slice (.. 1 5) 2) ; => (3 4 5) -(\ (.. 0 100) -5) ; => (96 97 98 99 100) - -; `append` ou `<<` são auto explicativos -(append 4 (1 2 3)) ; => (1 2 3 4) -(<< "bar" ("foo")) ; => ("foo" "bar") - -; Length é auto explicativo. -(length (1 2 3)) ; => 3 -(_ "foobar") ; => 6 - -;;;;;;;;;;;;;;; -; Delicadezas Haskell - -; Primeiro item de uma lista -(head (1 2 3)) ; => 1 -; Pega do segundo ao último elemento de uma lista -(tail (1 2 3)) ; => (2 3) -; Último item de uma lista -(last (1 2 3)) ; => 3 -; Contrário de `tail` -(init (1 2 3)) ; => (1 2) -; Pega do primeiro até o elemento especificado da lista -(take 1 (1 2 3 4)) ; (1 2) -; Contrário de `take` -(drop 1 (1 2 3 4)) ; (3 4) -; Menor valor em uma lista -(min (1 2 3 4)) ; 1 -; Maior valor em uma lista -(max (1 2 3 4)) ; 4 -; Verifica se o valor está em uma lista ou objeto -(elem 1 (1 2 3)) ; true -(elem "foo" {"foo" "bar"}) ; true -(elem "bar" {"foo" "bar"}) ; false -; Inverte a ordem de uma lista -(reverse (1 2 3 4)) ; => (4 3 2 1) -; Verifica se o valor é par ou ímpar -(even 1) ; => false -(odd 1) ; => true -; Separa um texto cortando por espaço em branco -(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") -; Junta lista de textos -(unwords ("foo" "bar")) ; => "foobar" -; Sucessor e predecessor -(pred 21) ; => 20 -(succ 20) ; => 21 -``` - -Para mais informação, verifique o [repositório](http://github.com/L8D/whip) diff --git a/whip.html.markdown b/whip.html.markdown deleted file mode 100644 index c692714a..00000000 --- a/whip.html.markdown +++ /dev/null @@ -1,241 +0,0 @@ ---- -language: whip -contributors: - - ["Tenor Biel", "http://github.com/L8D"] - - ["Saurabh Sandav", "http://github.com/SaurabhSandav"] - - ["Paulo Henrique Rodrigues Pinheiro", "https://github.com/paulohrpinheiro"] -author: Tenor Biel -author_url: http://github.com/L8D -filename: whip.lisp ---- - -Whip is a LISP-dialect made for scripting and simplified concepts. -It has also borrowed a lot of functions and syntax from Haskell (a non-related language). - -These docs were written by the creator of the language himself. So is this line. - -```scheme -; Comments are like LISP. Semi-colons... - -; Majority of first-level statements are inside "forms" -; which are just things inside parens separated by whitespace -not_in_form -(in_form) - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 1. Numbers, Strings, and Operators - -; Whip has one number type (which is a 64-bit IEEE 754 double, from JavaScript). -3 ; => 3 -1.5 ; => 1.5 - -; Functions are called if they are the first element in a form -(called_function args) - -; Majority of operations are done with functions -; All the basic arithmetic is pretty straight forward -(+ 1 1) ; => 2 -(- 2 1) ; => 1 -(* 1 2) ; => 2 -(/ 2 1) ; => 2 -; even modulo -(% 9 4) ; => 1 -; JavaScript-style uneven division. -(/ 5 2) ; => 2.5 - -; Nesting forms works as you expect. -(* 2 (+ 1 3)) ; => 8 - -; There's a boolean type. -true -false - -; Strings are created with ". -"Hello, world" - -; Single chars are created with '. -'a' - -; Negation uses the 'not' function. -(not true) ; => false -(not false) ; => true - -; But the majority of non-haskell functions have shortcuts -; not's shortcut is a '!'. -(! (! true)) ; => true - -; Equality is `equal` or `=`. -(= 1 1) ; => true -(equal 2 1) ; => false - -; For example, inequality would be combining the not and equal functions. -(! (= 2 1)) ; => true - -; More comparisons -(< 1 10) ; => true -(> 1 10) ; => false -; and their word counterpart. -(lesser 1 10) ; => true -(greater 1 10) ; => false - -; Strings can be concatenated with +. -(+ "Hello " "world!") ; => "Hello world!" - -; You can use JavaScript's comparative abilities. -(< 'a' 'b') ; => true -; ...and type coercion -(= '5' 5) - -; The `at` or @ function will access characters in strings, starting at 0. -(at 0 'a') ; => 'a' -(@ 3 "foobar") ; => 'b' - -; There is also the `null` and `undefined` variables. -null ; used to indicate a deliberate non-value -undefined ; user to indicate a value that hasn't been set - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 2. Variables, Lists, and Dicts - -; Variables are declared with the `def` or `let` functions. -; Variables that haven't been set will be `undefined`. -(def some_var 5) -; `def` will keep the variable in the global context. -; `let` will only have the variable inside its context, and has a weirder syntax. -(let ((a_var 5)) (+ a_var 5)) ; => 10 -(+ a_var 5) ; = undefined + 5 => undefined - -; Lists are arrays of values of any type. -; They basically are just forms without functions at the beginning. -(1 2 3) ; => [1, 2, 3] (JavaScript syntax) - -; Dictionaries are Whip's equivalent to JavaScript 'objects' or Python 'dicts' -; or Ruby 'hashes': an unordered collection of key-value pairs. -{"key1" "value1" "key2" 2 3 3} - -; Keys are just values, either identifier, number, or string. -(def my_dict {my_key "my_value" "my other key" 4}) -; But in Whip, dictionaries get parsed like: value, whitespace, value; -; with more whitespace between each. So that means -{"key" "value" -"another key" -1234 -} -; is evaluated to the same as -{"key" "value" "another key" 1234} - -; Dictionary definitions can be accessed used the `at` function -; (like strings and lists.) -(@ "my other key" my_dict) ; => 4 - -;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -; 3. Logic and Control sequences - -; The `if` function is pretty simple, though different than most imperative langs. -(if true "returned if first arg is true" "returned if first arg is false") -; => "returned if first arg is true" - -; And for the sake of ternary operator legacy -; `?` is if's unused shortcut. -(? false true false) ; => false - -; `both` is a logical 'and' statement, and `either` is a logical 'or'. -(both true true) ; => true -(both true false) ; => false -(either true false) ; => true -(either false false) ; => false -; And their shortcuts are -; & => both -; ^ => either -(& true true) ; => true -(^ false true) ; => true - -;;;;;;;;; -; Lambdas - -; Lambdas in Whip are declared with the `lambda` or `->` function. -; And functions are really just lambdas with names. -(def my_function (-> (x y) (+ (+ x y) 10))) -; | | | | -; | | | returned value(with scope containing argument vars) -; | | arguments -; | lambda declaration function -; | -; name of the to-be-declared lambda - -(my_function 10 10) ; = (+ (+ 10 10) 10) => 30 - -; Obviously, all lambdas by definition are anonymous and -; technically always used anonymously. Redundancy. -((lambda (x) x) 10) ; => 10 - -;;;;;;;;;;;;;;;; -; Comprehensions - -; `range` or `..` generates a list of numbers for -; each number between its two args. -(range 1 5) ; => (1 2 3 4 5) -(.. 0 2) ; => (0 1 2) - -; `map` applies its first arg (which should be a lambda/function) -; to each item in the following arg (which should be a list) -(map (-> (x) (+ x 1)) (1 2 3)) ; => (2 3 4) - -; Reduce -(reduce + (.. 1 5)) -; equivalent to -((+ (+ (+ 1 2) 3) 4) 5) - -; Note: map and reduce don't have shortcuts - -; `slice` or `\` is just like JavaScript's .slice() -; But do note, it takes the list as the first argument, not the last. -(slice (.. 1 5) 2) ; => (3 4 5) -(\ (.. 0 100) -5) ; => (96 97 98 99 100) - -; `append` or `<<` is self explanatory -(append 4 (1 2 3)) ; => (1 2 3 4) -(<< "bar" ("foo")) ; => ("foo" "bar") - -; Length is self explanatory. -(length (1 2 3)) ; => 3 -(_ "foobar") ; => 6 - -;;;;;;;;;;;;;;; -; Haskell fluff - -; First item in list -(head (1 2 3)) ; => 1 -; List from second to last elements in list -(tail (1 2 3)) ; => (2 3) -; Last item in list -(last (1 2 3)) ; => 3 -; Reverse of `tail` -(init (1 2 3)) ; => (1 2) -; List from first to specified elements in list -(take 1 (1 2 3 4)) ; (1 2) -; Reverse of `take` -(drop 1 (1 2 3 4)) ; (3 4) -; Lowest value in list -(min (1 2 3 4)) ; 1 -; Highest value in list -(max (1 2 3 4)) ; 4 -; If value is in list or object -(elem 1 (1 2 3)) ; true -(elem "foo" {"foo" "bar"}) ; true -(elem "bar" {"foo" "bar"}) ; false -; Reverse list order -(reverse (1 2 3 4)) ; => (4 3 2 1) -; If value is even or odd -(even 1) ; => false -(odd 1) ; => true -; Split string into list of strings by whitespace -(words "foobar nachos cheese") ; => ("foobar" "nachos" "cheese") -; Join list of strings together. -(unwords ("foo" "bar")) ; => "foobar" -; Successor and Predecessor -(pred 21) ; => 20 -(succ 20) ; => 21 -``` - -For more info, check out the [repo](http://github.com/L8D/whip) From 54f75e008b6cb8d00d52346882dfdbaf2366e88a Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 19 May 2024 18:08:55 +0200 Subject: [PATCH 250/392] [d/de] Fix typo, spelling (#4953) --- de-de/d-de.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 65d2931b..9eb5ef46 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -22,11 +22,11 @@ void main(string[] args) { Wenn du so wie ich bist und viel Zeit im Internet verbringst, stehen die Chancen gut, dass du schonmal über [D](http://dlang.org/) gehört hast. -Die D-Sprache ist eine moderne, überall einsetzbare programmiersprache die von +Die D-Sprache ist eine moderne, überall einsetzbare Programmiersprache die von Low bis High Level verwendet werden kann und dabei viele Stile anbietet. D wird aktiv von Walter Bright und Andrei Alexandrescu entwickelt, zwei super schlaue, -richtig coole leute. Da das jetzt alles aus dem Weg ist - auf zu den Beispielen! +richtig coole Leute. Da das jetzt alles aus dem Weg ist - auf zu den Beispielen! ```d import std.stdio; @@ -40,7 +40,7 @@ void main() { auto n = 1; // auto um den Typ vom Compiler bestimmen zu lassen - // Zahlenliterale können _ verwenden für lesbarkeit + // Zahlenliterale können _ verwenden für Lesbarkeit while(n < 10_000) { n += n; } @@ -69,9 +69,9 @@ void main() { ``` Neue Typen können mit `struct`, `class`, `union`, und `enum` definiert werden. -Structs und unions werden as-value (koppiert) an Methoden übergeben wogegen +Structs und unions werden as-value (kopiert) an Methoden übergeben wogegen Klassen als Referenz übergeben werden. Templates können verwendet werden um -alle Typen zu parameterisieren. +alle Typen zu parametrisieren. ```d // Hier, T ist ein Type-Parameter, Er funktioniert wie Generics in C#/Java/C++ @@ -121,7 +121,7 @@ void swap(T)(ref T a, ref T b) { b = temp; } -// Templates können ebenso Werte parameterisieren. +// Templates können ebenso Werte parametrisieren. class Matrix(uint m, uint n, T = int) { T[m] rows; T[n] columns; From f930b9e6d0c6a9c5fad9b3db21c088d05b3b45c5 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 19 May 2024 18:09:17 +0200 Subject: [PATCH 251/392] [crystal/de] Fix typo (#4952) --- de-de/crystal-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/crystal-de.html.markdown b/de-de/crystal-de.html.markdown index b45b673c..423de5fb 100644 --- a/de-de/crystal-de.html.markdown +++ b/de-de/crystal-de.html.markdown @@ -170,7 +170,7 @@ set << 3 {1 => 2, 3 => 4}.class # => Hash(Int32, Int32) {1 => 2, 'a' => 3}.class # => Hash (Int32 | Char, Int32) -# Leere Hashes sollten einen Typen spezifieren +# Leere Hashes sollten einen Typen spezifizieren {} # Syntaxfehler {} of Int32 => Int32 # {} Hash(Int32, Int32).new # {} From 5b18843e8fad6379f201cdd88d3c4d0c2ec96727 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 19 May 2024 18:09:37 +0200 Subject: [PATCH 252/392] [haml/de] Fix typo (#4954) --- de-de/haml-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/haml-de.html.markdown b/de-de/haml-de.html.markdown index 9757ec2f..0f12eebf 100644 --- a/de-de/haml-de.html.markdown +++ b/de-de/haml-de.html.markdown @@ -141,7 +141,7 @@ $ haml input_file.haml output_file.html / ------------------------------------------- / - Mit dem Doppelpinkt können Haml Filter benutzt werden. + Mit dem Doppelpunkt können Haml Filter benutzt werden. Zum Beispiel gibt es den :javascript Filter, mit dem inline JS geschrieben werden kann: From 206e1dd76a2e549870afd94561fd0429937e8f41 Mon Sep 17 00:00:00 2001 From: Mario Stabile <66466058+mariostabile1@users.noreply.github.com> Date: Sun, 19 May 2024 23:19:43 +0200 Subject: [PATCH 253/392] [fish/it] minor adjustments (#4955) --- it-it/fish-it.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/it-it/fish-it.html.markdown b/it-it/fish-it.html.markdown index edf35b4b..551b3339 100644 --- a/it-it/fish-it.html.markdown +++ b/it-it/fish-it.html.markdown @@ -76,7 +76,7 @@ Aggiungere qualcosa alla variabile PATH di fish è semplice: > fish_path_add ~/cowsay ``` -Questo puoi farlo con bash, eh? No, devi sempre cercarlo... Così è facile! +Questo puoi farlo con bash, eh? No, devi sempre cercarlo... Così è facile! Ma c'è di più. La maggior parte dei comandi specifici per fish iniziano, hai indovinato, con 'fish'. Basta scrivere `fish` e premere TAB. Ed ecco una delle tante funzioni interessanti di fish: L'autocompletamento che **funziona.** Ora puoi navigare con TAB, Shift + TAB e le frecce . @@ -87,9 +87,9 @@ Per avere aiuto, chiama il tuo psichiatra di fiducia oppure scrivi `man`. Ti mos > man set ``` -Se finalmente hai provato fish, potrai vedere in questa shell qualcosa di diverso, il che è molto figo. Ogni cosa ha colori fantastici, se scrivi qualcosa di sbagliato viene segnato in rosso, senza nemmeno eseguirlo, se si mette qualcosa tra virgolette, si vede dove finisce e perchè quella citazione non funziona, perchè c'è un'altro segno di citazione nella citazione in posizione 26. +Se finalmente hai provato fish, potrai vedere in questa shell qualcosa di diverso, il che è molto figo. Ogni cosa ha colori fantastici, se scrivi qualcosa di sbagliato viene segnato in rosso, senza nemmeno eseguirlo!, se si mette qualcosa tra virgolette, si vede dove finisce e perchè quella citazione non funziona. -fish ha ancora altre cose interessanti, come le wildcards (o carattere jolly). +fish ha varie altre cose interessanti, come le wildcards (o carattere jolly). Per esempio, scrivi: ``` @@ -222,10 +222,10 @@ count $PATH # Per fare una lista, basta dare al comando set più argomenti: set list argomento1 argomento2 argomento3 -# in questo modo puoi anche inserire qualcosa in una variabile pre-esistente:: +# in questo modo puoi anche inserire qualcosa in una variabile pre-esistente: set PATH $PATH ~/cowsay/ -# Ma, come precedentemente menzionato, abbiamo anche un'altro modo più semplice per farlo specialmente in fish. +# Ma, come precedentemente menzionato, abbiamo anche un'altro modo più semplice per farlo, specialmente in fish. # Come per ogni Array/Lista, puoi anche accedergli con $listavar[2] @@ -244,12 +244,12 @@ echo $a$1 # Naturalmente, se li si separa, saranno visti come due argomenti separati e li stamperà uno dopo l'altro. QUESTO è il comportamento che ci si aspetta da @bash. -# Ci sono anche altre cose utili, come la sotituzione di comandi. Per esempio, quando vuoi che ti sia restituito l'output di due comandi in una sola riga. In bash lo faresti in questo modo +# Ci sono anche altre cose utili, come la sostituzione di comandi. Per esempio, quando vuoi che ti sia restituito l'output di due comandi in una sola riga. In bash lo faresti in questo modo echo "`ls` è in $PWD" # oppure echo "$(ls) è in $PWD" -# secondo me, non è necessario. Scrivo sempre l'apostrogo sbagliato. Perchè non usare semplicemente le parentesi, come in fish? +# secondo me, non è necessario. Scrivo sempre l'apostrofo sbagliato. Perchè non usare semplicemente le parentesi, come in fish? echo (ls) è in $PWD # Yep, è facile. E grazie all'highlighting di fish lo puoi vedere istantaneamente, se lo scrivi correttamente. @@ -338,6 +338,6 @@ end # Bello! # L'equivalente di bashrc non è fishrc, ma il già citato file config.fish in ~/.config/fish/ -# Per aggiungere una funzione a fish, però, occorre creare un semplice file .fish in quell directory. Non incollare la funzione nel file config.fish. È brutto. +# Per aggiungere una funzione a fish, però, occorre creare un semplice file .fish in quella directory. Non incollare la funzione nel file config.fish. È brutto. # Se avete altro da dire, aggiugete pure, ma queste sono le basi più importanti. ``` From 856d36e4e3e15df6cb748527e53da4a823ede357 Mon Sep 17 00:00:00 2001 From: Mario Stabile <66466058+mariostabile1@users.noreply.github.com> Date: Mon, 20 May 2024 01:23:53 +0200 Subject: [PATCH 254/392] [cmake/it] Translate (#4956) --- it-it/cmake-it.html.markdown | 172 +++++++++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 it-it/cmake-it.html.markdown diff --git a/it-it/cmake-it.html.markdown b/it-it/cmake-it.html.markdown new file mode 100644 index 00000000..a4febf4d --- /dev/null +++ b/it-it/cmake-it.html.markdown @@ -0,0 +1,172 @@ +--- +category: tool +tool: cmake +contributors: + - ["Bruno Alano", "https://github.com/brunoalano"] +translators: + - ["Mario Stabile", "https://github.com/mariostabile1"] +lang: it-it +--- + +CMake è un build tool multi-piattaforma e open-source. Questo tool ti permette di testare, compilare e creare pacchetti del tuo codice sorgente. + +I problemi che CMake provara a risolvere sono quelli dei Makefile, +dell'Autoconfigurazione multi-piattaforma (diversi interpreti di Make hanno comandi diversi) e la facilità d'uso nel collegamento di librerie di terze parti. + +CMake è un sistema estensibile e open-source che gestisce il processo di compilazione in maniera simile a come farebbero i sistemi operativi, indipendentemente dal formato usato. A differenza di altri sistemi multi-piattaforma, CMake è progettato per essere usato insieme all'ambiente di compilazione nativo. Semplici file di configurazione collocati in ogni cartella dei sorgenti (chiamati CMakeLists.txt) sono usati per generare i file di compilazione standard (ad esempio, makefile su Unix e project/workspace in Windows MSVC) che sono utilizzati nel classico modo. + +```cmake +# In CMake, questo è un commento + +# Per eseguire il nostro codice, usa questi comandi: +# - mkdir build && cd build +# - cmake .. +# - make +# +# Con questi passaggi, seguiremo la pratica migliore per compilare in una sotto-cartella. +# La seconda riga chiderà a CMake di generare un nuovo Makefile dipendente dal sistema operativo. +# Infine, eseguiremo il comando nativo Make. + +#------------------------------------------------------------------------------ +# Le basi +#------------------------------------------------------------------------------ +# +# Il file CMake DEVE essere chiamato "CMakeLists.txt". + +# Configuriamo la versione minima di CMake per generare il Makefile +cmake_minimum_required (VERSION 2.8) + +# Lancerà un errore FATAL_ERROR se la versione < 2.8 +cmake_minimum_required (VERSION 2.8 FATAL_ERROR) + +# Definiamo il nome del nostro progetto, questo modificherà +# le convenzioni di denominazione generate da CMake per alcune cartelle. +# Possiamo passare il LANG del codice come secondo parametro +project (learncmake C) + +# Settiamo la cartella del sorgente (è solo una convenzione) +set( LEARN_CMAKE_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} ) +set( LEARN_CMAKE_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} ) + +# Risulta utile settare l'attuale versione del nostro codice nel sistema di compilazione +# usando uno stile `semver` +set (LEARN_CMAKE_VERSION_MAJOR 1) +set (LEARN_CMAKE_VERSION_MINOR 0) +set (LEARN_CMAKE_VERSION_PATCH 0) + +# Passiamo le variabili (numero di versione) all'header del sorgente +configure_file ( + "${PROJECT_SOURCE_DIR}/TutorialConfig.h.in" + "${PROJECT_BINARY_DIR}/TutorialConfig.h" +) + +# Includiamo le Librerie +# In GCC, questo invocherà il comando "-I" +include_directories( include ) + +# Dove sono installate le librerie aggiuntive? Nota: includi i percorsi +# delle librerie qui, i controlli successivi risolveranno il resto +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Condizioni +if ( CONDITION ) + # Output! + + # Informazioni accessorie + message(STATUS "My message") + + # Warning di CMake, continua a elaborare + message(WARNING "My message") + + # Warning di CMake (dev), continua a elaborare + message(AUTHOR_WARNING "My message") + + # Errore di CMake, continua a elaborare, ma salta la generazione + message(SEND_ERROR "My message") + + # Errore di CMake, ferma l'elaborazione e la generazione + message(FATAL_ERROR "My message") +endif() + +if( CONDITION ) + +elseif( CONDITION ) + +else( CONDITION ) + +endif( CONDITION ) + +# Cicli +foreach(loop_var arg1 arg2 ...) + COMMAND1(ARGS ...) + COMMAND2(ARGS ...) + ... +endforeach(loop_var) + +foreach(loop_var RANGE total) +foreach(loop_var RANGE start stop [step]) + +foreach(loop_var IN [LISTS [list1 [...]]] + [ITEMS [item1 [...]]]) + +while(condition) + COMMAND1(ARGS ...) + COMMAND2(ARGS ...) + ... +endwhile(condition) + + +# Operazioni logiche +if(FALSE AND (FALSE OR TRUE)) + message("Don't display!") +endif() + +# Impostiamo una variabile regolare, di cache o di ambiente a un determinato valore. +# Se viene fornita l'opzione PARENT_SCOPE, la variabile verrà settata nello scope +# sopra lo scope corrente. +# `set( ... [PARENT_SCOPE])` + +# Come fare riferimento a variabili all'interno di argomenti tra virgolette e non? +# Un riferimento a una variabile è sostituito sia dal valore della variabile, sia da +# una stringa vuota se la variabile non è settata. +${variable_name} + +# Liste +# Prepariamo la lista dei file sorgente +set( LEARN_CMAKE_SOURCES + src/main.c + src/imagem.c + src/pather.c +) + +# Chiamate al compilatore +# +# ${PROJECT_NAME} fa riferimento a Learn_CMake +add_executable( ${PROJECT_NAME} ${LEARN_CMAKE_SOURCES} ) + +# Link alle librerie +target_link_libraries( ${PROJECT_NAME} ${LIBS} m ) + +# Dove sono installate le librerie aggiuntive? Nota: includi i percorsi +# delle librerie qui, i controlli successivi risolveranno il resto +set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/CMake/modules/" ) + +# Condizioni del compilatore (gcc ; g++) +if ( "${CMAKE_C_COMPILER_ID}" STREQUAL "GNU" ) + message( STATUS "Setting the flags for ${CMAKE_C_COMPILER_ID} compiler" ) + add_definitions( --std=c99 ) +endif() + +# Controllo del sistema operativo +if( UNIX ) + set( LEARN_CMAKE_DEFINITIONS + "${LEARN_CMAKE_DEFINITIONS} -Wall -Wextra -Werror -Wno-deprecated-declarations -Wno-unused-parameter -Wno-comment" ) +endif() +``` + +### Maggiori risorse + ++ [Tutorial CMake](https://cmake.org/cmake-tutorial/) ++ [Documentazione CMake](https://cmake.org/documentation/) ++ [Mastera CMake](http://amzn.com/1930934319/) ++ [Un'introduzione al CMake moderno](https://cliutils.gitlab.io/modern-cmake/) From 64dcb689dfd24314b685d65042a5d5b78dbe7ecb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20P?= Date: Mon, 20 May 2024 06:35:43 +0200 Subject: [PATCH 255/392] [bash/fr] update based on [bash/en] (#4520) --- fr-fr/bash-fr.html.markdown | 116 ++++++++++++++++++++++++++++++++---- 1 file changed, 103 insertions(+), 13 deletions(-) diff --git a/fr-fr/bash-fr.html.markdown b/fr-fr/bash-fr.html.markdown index 58d01e6a..1bd78817 100644 --- a/fr-fr/bash-fr.html.markdown +++ b/fr-fr/bash-fr.html.markdown @@ -26,10 +26,10 @@ ou exécutés directement dans le terminal. ```bash #!/bin/bash -# La première ligne du script s’appelle le « shebang, » qui indique au système +# La première ligne du script s’appelle le « shebang », elle indique au système # comment exécuter le script : http://fr.wikipedia.org/wiki/Shebang -# Comme vous pouvez le remarquer, les commentaires commencent par #. Le shebang -# est aussi un commentaire +# Comme vous pouvez le remarquer, les commentaires commencent par un « # ». +# Le shebang est donc aussi un commentaire # Un exemple simple qui affiche « Hello world! » : echo Hello world! @@ -41,32 +41,96 @@ echo 'Ceci est la première ligne'; echo 'Ceci est la seconde ligne' VARIABLE="Du texte" # Mais pas comme ça : -VARIABLE = "Du texte" +VARIABLE = "Du texte" # => renvoie une erreur : "Variable: command not found" # Bash va penser que VARIABLE est une commande qu’il doit exécuter et va # afficher une erreur parce qu’elle est introuvable. +# Ni comme ça : +VARIABLE= 'Some string' # => renvoie une erreur : "Du texte: command not found" +# Bash va penser que 'Di texte' est une commande qu’il doit exécuter et va +# afficher une erreur parce qu’elle est introuvable. (Dans ce cas, la partie +# 'VARIABLE=' est considérée comme une affectation de variable valable uniquement +# pour la portée de la commande 'Du texte'). + # Utiliser une variable : -echo $VARIABLE -echo "$VARIABLE" -echo '$VARIABLE' +echo $VARIABLE # => Du texte +echo "$VARIABLE" # => Du texte +echo '$VARIABLE' # => $VARIABLE # Quand vous utilisez la variable en elle-même – en lui assignant une valeur, # en l’exportant ou autre – vous écrivez son nom sans $. Si vous voulez # utiliser sa valeur, vous devez utiliser $. # Notez qu’entourer une variable de deux guillemets simples (') empêche # l’expansion des variables ! +# Expansion des paramètres (Parameter expansion) ${ } : +echo ${VARIABLE} # => Du texte +# Ceci est une utilisation simple de l'expansion de paramètre. +# L'expansion de paramètre récupère la valeur d'une variable. +# Elle « déploie » ou imprime la valeur. +# Lors de l'expansion, la valeur ou le paramètre peut être modifié. +# Voici d'autres modifications qui s'ajoutent à cette expansion. + # Substitution de chaîne de caractères dans une variable echo ${VARIABLE/Some/A} # Ceci va remplacer la première occurrence de « Some » par « A » # Sous-chaîne d’une variable -echo ${VARIABLE:0:7} -# Ceci va retourner seulement les 7 premiers caractères de la valeur +LONGUEUR=5 +echo ${VARIABLE:0:LONGUEUR} # => Du te +# Ceci va retourner les 5 premiers caractères de la valeur +echo ${VARIABLE:LONGUEUR} # => xte +# Ceci va retourner la valeur sans les 5 premiers caractères +echo ${VARIABLE: -4} # => exte +# Ceci va retourner les 4 derniers caractères de la valeur +# (l'espace avant -4 est nécessaire) + +# Longueur d'une chaîne +echo ${#VARIABLE} # => 8 + +# Expansion indirecte +AUTRE_VARIABLE="VARIABLE" +echo ${!AUTRE_VARIABLE} # => Du texte +# Cela va utiliser la valeur comme un nom de variable # Valeur par défaut d’une variable -echo ${FOO:-"ValeurParDefautSiFOOestVideOuInexistant"} -# Ceci marche pour null (FOO=), la chaîne de caractères vide (FOO=""). Zéro -# (FOO=0) retourne 0 +echo ${FOO:-"ValeurParDefaut"} +# Retourne 'ValeurParDefaut' si FOO n'a pas été déclarée, si +# FOO est null (FOO=) ou si FOO est une chaîne vide (FOO=""). +# En revanche Zéro (FOO=0) retourne 0 + +# Les tableaux (array) + +array0=(un deux trois quatre cinq six) +# Déclarer un tableau de 6 éléments + +echo $array0 # => "un" +# Affiche le premier élément + +echo ${array0[0]} # => "un" +# Affiche le premier élément + +echo ${array0[@]} # => "un deux trois quatre cinq six" +# Affiche tous les éléments + +echo ${#array0[@]} # => "6" +# Attiche le nombre d'éléments + +echo ${#array0[2]} # => "5" +# Affiche le nombre de caractères du troisième élément + +echo ${array0[@]:3:2} # => "quatre cinq" +# Affiche 2 element en à partir du quatrième + +for i in "${array0[@]}"; do + echo "$i" +done +# Affiche tous éléments, chacun sur un nouvelle ligne + +# Brace Expansion { } +# Permet de générer des tableau +echo {1..12} # => 1 2 3 4 5 6 7 8 9 10 11 12 +echo {100..95} # => 100 99 98 97 96 95 +echo {a..z} # => a b c d e f g h i j k l m n o p q r s t u v w x y z # Variables pré-remplies : # Il y a quelques variables pré-remplies utiles, comme : @@ -76,6 +140,21 @@ echo "Nombre d’arguments : $#" echo "Arguments du script : $@" echo "Arguments du script séparés en plusieurs variables : $1 $2..." +# Maintenant que nous savons comment utiliser et afficher des variables, +# apprenons d'autres fonctionnalités basiques de bash ! + +# Notre répertoire courant est accessible par la commande `pwd`. +# `pwd` signifie « imprimer le répertoire de travail ». +# On peut aussi utiliser la variable intégrée `$PWD`. +# Observez que les commandes suivantes sont équivalentes : +echo "Je suis dans $(pwd)" # exécute `pwd` et interpole la sortie +echo "Je suis dans $PWD" # interprète la variable + +# Si vous avez trop de données dans votre terminal, la commande +# `clear` efface votre écran +clear +# Ctrl-L fonctionne aussi pour effacer la sortie. + # Lire une valeur depuis l’entrée standard : echo "Quel est votre nom ?" read NAME # Notez que l’on n’a pas eu à déclarer une nouvelle variable @@ -83,16 +162,27 @@ echo Bonjour, $NAME! # Nous avons l’habituelle structure « if » : # Utilisez 'man test' pour plus d’informations à propos des conditions -if [ $NAME -ne $USER ] +if [ $NAME != $USER ] # remarque : $USER est le nom l'utilisateur en cours. then echo "Votre nom n’est pas votre pseudo" else echo "Votre nom est votre pseudo" fi +# Remarque : si $NAME est vide, bash verra la condition précédente comme : +if [ != $USER ] +# ce qui est syntaxiquement invalide +# la bonne façon d'utiliser une variable potentiellement vide en bash est : +if [ "$NAME" != $USER ] +# ce qui sera interprété par bash si $NAME est vide comme : +if [ "" != $USER ] + # Il y a aussi l’exécution conditionnelle echo "Toujours exécuté" || echo "Exécuté si la première commande ne réussit pas" +# Toujours exécuté echo "Toujours exécuté" && echo "Exécuté si la première commande réussit" +# Toujours exécuté +# Exécuté si la première commande réussit # Pour utiliser && et || avec des commandes « if, » vous devez utiliser # plusieurs paires de crochets : From 5c7cfb75754867e22ab7e080ceafea569b3cffc1 Mon Sep 17 00:00:00 2001 From: Bryan McKnight Date: Mon, 20 May 2024 11:16:40 -0500 Subject: [PATCH 256/392] Typo fix (#4957) --- elixir.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elixir.html.markdown b/elixir.html.markdown index c4da22e8..fcff8a69 100644 --- a/elixir.html.markdown +++ b/elixir.html.markdown @@ -146,7 +146,7 @@ nil && 20 #=> nil 1 == 1.0 #=> true 1 === 1.0 #=> false -# Elixir operators are strict in theiar arguments, with the exception +# Elixir operators are strict in their arguments, with the exception # of comparison operators that work across different data types: 1 < :hello #=> true From b506816adb8cca907a7c5ab4f6e888510270ffda Mon Sep 17 00:00:00 2001 From: zacryol <60046681+zacryol@users.noreply.github.com> Date: Tue, 21 May 2024 09:31:08 -0600 Subject: [PATCH 257/392] [gdscript/en] Update for Godot 4 (#4607) --- gdscript.html.markdown | 123 ++++++++++++++++++++++++++++------------- 1 file changed, 84 insertions(+), 39 deletions(-) diff --git a/gdscript.html.markdown b/gdscript.html.markdown index 3312e2e3..ffc08b14 100644 --- a/gdscript.html.markdown +++ b/gdscript.html.markdown @@ -2,13 +2,14 @@ language: GDScript contributors: - ["Wichamir", "https://github.com/Wichamir/"] + - ["zacryol", "https://github.com/zacryol"] filename: learngdscript.gd --- -GDScript is a dynamically typed scripting language made specifically for -free and open source game engine Godot. GDScript's syntax is similar to -Python's. Its main advantages are ease of use and tight integration with -the engine. It's a perfect fit for game development. +GDScript is a dynamically and statically typed scripting language +for the free and open source game engine Godot. Its syntax is vaguely +similar to Python's. Its main advantages are ease of use and tight +integration with the engine. It's a perfect fit for game development. ## Basics @@ -20,9 +21,16 @@ the engine. It's a perfect fit for game development. are written using - docstrings. + triple + quoted + strings """ +# Doc Comments can add a decription to classes and fields +# which can be viewed in the in-engine docs. + +## This class is a demonstration of GDScript + # Script file is a class in itself and you can optionally define a name for it. class_name MyClass @@ -41,8 +49,13 @@ var d = { "key" : "value", 42 : true } # Dictionary holds key-value pairs. -var p_arr = PoolStringArray(["Hi", "there", "!"]) # Pool arrays can - # only hold a certain type. +var p_arr = PackedStringArray(["Hi", "there", "!"]) # Packed Arrays can + # only hold a certain type. + +# Doc comments can apply to properties + +## How many times this object has jumped +var jump_count = 0 # Built-in vector types: var v2 = Vector2(1, 2) @@ -57,10 +70,15 @@ enum { ZERO, ONE , TWO, THREE } enum NamedEnum { ONE = 1, TWO, THREE } # Exported variables are visible in the inspector. -export(int) var age -export(float) var height -export var person_name = "Bob" # Export type hints are unnecessary - # if you set a default value. +# +# Either a type hint (explained later) or a default value are needed in order +# for the editor to know what options to give +@export var age: int +@export var height: float +@export var person_name = "Bob" +# But both is also acceptable +@export var favorite_color: String = "Green" +@export var favorite_food := "Pizza" # Functions func foo(): @@ -69,6 +87,12 @@ func foo(): func add(first, second): return first + second +# Doc Comments on functions + +## Increases the Jump Count +func jump(): + jump_count += 1 + # Printing values func printing(): print("GDScript ", "is ", " awesome.") @@ -76,6 +100,11 @@ func printing(): printt("These", "words", "are", "divided", "by", "tabs.") printraw("This gets printed to system console.") + # Lambdas + var my_lambda = func(): print("hello from lambda!") + + my_lambda.call() + # Math func doing_math(): var first = 8 @@ -97,14 +126,14 @@ func control_flow(): y = 2 # y was originally a float, # but we can change its type to int # using the power of dynamic typing! - + if x < y: print("x is smaller than y") elif x > y: print("x is bigger than y") else: print("x and y are equal") - + var a = true var b = false var c = false @@ -119,7 +148,7 @@ func control_flow(): for i in ["two", 3, 1.0]: # iterating over an array print(i) - + while x > y: printt(x, y) y += 1 @@ -147,7 +176,7 @@ func control_flow(): continue _: print("Underscore is a default case.") - + # ternary operator (one line if-else statement) prints("x is", "positive" if x >= 0 else "negative") @@ -191,7 +220,7 @@ func _physics_process(delta): # like here: func get_children(): # Do some additional things here. - var r = .get_children() # call parent's implementation + var r = super() # call parent's implementation return r # Inner class @@ -220,19 +249,19 @@ func _ready() -> void: # Create NodePath by passing String to its constructor: var path1 = NodePath("path/to/something") # Or by using NodePath literal: - var path2 = @"path/to/something" + var path2 = ^"path/to/something" # NodePath examples: - var path3 = @"Sprite" # relative path, immediate child of the current node - var path4 = @"Timers/Firerate" # relative path, child of the child - var path5 = @".." # current node's parent - var path6 = @"../Enemy" # current node's sibling - var path7 = @"/root" # absolute path, equivalent to get_tree().get_root() - var path8 = @"/root/Main/Player/Sprite" # absolute path to Player's Sprite - var path9 = @"Timers/Firerate:wait_time" # accessing properties - var path10 = @"Player:position:x" # accessing subproperties + var path3 = ^"Sprite" # relative path, immediate child of the current node + var path4 = ^"Timers/Firerate" # relative path, child of the child + var path5 = ^".." # current node's parent + var path6 = ^"../Enemy" # current node's sibling + var path7 = ^"/root" # absolute path, equivalent to get_tree().get_root() + var path8 = ^"/root/Main/Player/Sprite" # absolute path to Player's Sprite + var path9 = ^"Timers/Firerate:wait_time" # accessing properties + var path10 = ^"Player:position:x" # accessing subproperties # Finally, to get a reference use one of these: - sprite = get_node(@"Sprite") as Sprite # always cast to the type you expect + sprite = get_node(^"Sprite") as Sprite # always cast to the type you expect sprite = get_node("Sprite") as Sprite # here String gets # implicitly casted to NodePath sprite = get_node(path3) as Sprite @@ -243,14 +272,17 @@ func _process(delta): # Now we can reuse the reference in other places. prints("Sprite has global_position of", sprite.global_position) -# Use onready keyword to assign a value to +# Use @onready annotation to assign a value to # a variable just before _ready executes. # This is a commonly used syntax sugar. -onready var tween = $Tween as Tween +@onready var other_sprite = $Sprite as Sprite # You can export NodePath, so you can assign it within the inspector. -export var nodepath = @"" -onready var reference = get_node(nodepath) as Node +@export var nodepath = ^"" +@onready var reference = get_node(nodepath) as Node + +# Or export Node directly +@export var other_reference: Node ``` ## Signals @@ -263,27 +295,34 @@ class_name Player extends Node2D var hp = 10 +# Doc comments can go on signals too + +## Emitted when the player dies signal died() # define signal signal hurt(hp_old, hp_new) # signals can take arguments func apply_damage(dmg): var hp_old = hp hp -= dmg - emit_signal("hurt", hp_old, hp) # emit signal and pass arguments + hurt.emit(hp_old, hp) # emit signal and pass arguments if hp <= 0: - emit_signal("died") + died.emit() func _ready(): # connect signal "died" to function "_on_death" defined in self - self.connect("died", self, "_on_death") + died.connect(_on_death) + # Alternate way + # needed if the target object is not self + # died.connect(Callable(self, &"_on_death")) func _on_death(): - self.queue_free() # destroy Player on death + queue_free() # destroy Player on death ``` ## Type hints -GDScript can optionally use static typing. +GDScript can optionally use static typing, for both code clarity and +performance benefits. ```gdscript extends Node @@ -292,15 +331,23 @@ var x: int # define typed variable var y: float = 4.2 var z := 1.0 # infer type based on default value using := operator -onready var node_ref_typed := $Child as Node +var a: Array[int] = [1, 2, 3] # Array can also have its type content specified -export var speed := 50.0 +enum NamedEnum { ONE = 1, TWO, THREE } +var n: NamedEnum = NamedEnum.ONE # Enums can be used as types as well + +@onready var node_ref_typed := $Child as Node + +@export var speed := 50.0 const CONSTANT := "Typed constant." +signal example(arg: int) + func _ready() -> void: # function returns nothing x = "string" # ERROR! Type can't be changed! + a.append("q") # ERROR! Array[int] can't hold strings! return func join(arg1: String, arg2: String) -> String: @@ -310,8 +357,6 @@ func join(arg1: String, arg2: String) -> String: func get_child_at(index: int) -> Node: # function takes an int and returns a Node return get_children()[index] - -signal example(arg: int) # ERROR! Signals can't take typed arguments! ``` ## Further Reading From 3121a72981978d8ebbdd55795d5f31b85db15e20 Mon Sep 17 00:00:00 2001 From: ven Date: Fri, 24 May 2024 14:54:23 +0200 Subject: [PATCH 258/392] Update dart.html.markdown fixes #4958 --- dart.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dart.html.markdown b/dart.html.markdown index 4d2bf5ac..48fb1367 100644 --- a/dart.html.markdown +++ b/dart.html.markdown @@ -32,7 +32,7 @@ import "dart:math" as math; // Single line comment /** * Multi-line comment -* Can comment more than 2 lines +* Can comment several lines */ /// Code doc comment /// It uses markdown syntax to generate code docs when making an API. From 693d4415c884d476053dfbf0e85e3de8e0bda81f Mon Sep 17 00:00:00 2001 From: dingyanhe Date: Mon, 27 May 2024 01:18:29 +0800 Subject: [PATCH 259/392] [lua/zh-cn] Mention LUA_PATH (#4564) --- zh-cn/lua-cn.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index b31a98c1..81883850 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -361,6 +361,7 @@ return M -- 另一个文件可以使用mod.lua的功能: local mod = require('mod') -- 运行文件mod.lua. +-- 注意:require 需要配合 LUA_PATH 一起使用 例如:export LUA_PATH="$HOME/workspace/projectName/?.lua;;" -- require是包含模块的标准做法。 -- require等价于: (针对没有被缓存的情况;参见后面的内容) From de3ddb18c139e3cccd332e265ecbf726cd4b6d33 Mon Sep 17 00:00:00 2001 From: qadzek <84473512+qadzek@users.noreply.github.com> Date: Mon, 27 May 2024 19:27:36 +0200 Subject: [PATCH 260/392] [json/nl] Remove duplicate tutorial (#4959) --- nl-nl/json.html.markdown | 61 ---------------------------------------- 1 file changed, 61 deletions(-) delete mode 100644 nl-nl/json.html.markdown diff --git a/nl-nl/json.html.markdown b/nl-nl/json.html.markdown deleted file mode 100644 index bedfb70a..00000000 --- a/nl-nl/json.html.markdown +++ /dev/null @@ -1,61 +0,0 @@ ---- -language: json -filename: learnjson-nl.json -contributors: - - ["Anna Harren", "https://github.com/iirelu"] - - ["Marco Scannadinari", "https://github.com/marcoms"] -translators: - - ["Mathieu De Coster", "https://github.com/m-decoster"] -lang: nl-nl ---- - -Aangezien JSON een extreem eenvoudig datauitwisselingsformaat is, zal dit waarschijnlijk -de meest eenvoudige Learn X in Y Minutes ooit zijn. - -Puur JSON heeft geen commentaar, maar de meeste parsers zullen commentaar in de stijl -van C (`//`, `/* */`) aanvaarden. In dit voorbeeld zal alles 100% correcte JSON zijn. -Gelukkig spreekt het meeste voor zichzelf. - -```json -{ - "key": "value", - - "keys": "moeten altijd tussen dubbele aanhalingstekens staan", - "getallen": 0, - "strings": "Hellø, world. Alle Unicode-karakters zijn toegelaten, zo ook \"escaping\".", - "heeft json booleans?": true, - "niets": null, - - "groot getal": 1.2e+100, - - "objecten": { - "commentaar": "De meeste structuur wordt gemaakt met objecten.", - - "array": [0, 1, 2, 3, "Arrays kunnen eender wat bevatten.", 5], - - "nog een object": { - "commentaar": "Hoe handig, we kunnen objecten nesten." - } - }, - - "dwaasheid": [ - { - "bronnen van kalium": ["bananen"] - }, - [ - [1, 0, 0, 0], - [0, 1, 0, 0], - [0, 0, 1, "neo"], - [0, 0, 0, 1] - ] - ], - - "alternatieve stijl": { - "commentaar": "kijk hier eens naar!" - , "komma locatie": "maakt niet uit - zo lang het voor de value komt, is alles in orde" - , "nog commentaar": "hoe leuk" - }, - - "dat was kort": "Je bent klaar. Je kent nu alles dat JSON kan aanbieden." -} -``` From e1bc8441e80800278f4276906b0c9f6c14b28eee Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 27 May 2024 12:11:49 -0600 Subject: [PATCH 261/392] [julia/*] highlight as julia --- es-es/julia-es.html.markdown | 8 +-- ja-jp/julia-jp.html.markdown | 2 +- pt-br/julia-pt.html.markdown | 28 ++++---- ru-ru/julia-ru.html.markdown | 122 +++++++++++++++++------------------ zh-cn/julia-cn.html.markdown | 60 ++++++++--------- 5 files changed, 108 insertions(+), 112 deletions(-) diff --git a/es-es/julia-es.html.markdown b/es-es/julia-es.html.markdown index 355c7f29..a2572003 100644 --- a/es-es/julia-es.html.markdown +++ b/es-es/julia-es.html.markdown @@ -9,9 +9,7 @@ filename: learnjulia-es.jl lang: es-es --- -![JuliaLang](http://s13.postimg.org/z89djuwyf/julia_small.png) - -[Julia](http://julialanges.github.io) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org). +[Julia](https://julialang.org/) es un [lenguaje de programación](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n) [multiplataforma](http://es.wikipedia.org/wiki/Multiplataforma) y [multiparadigma](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_multiparadigma) de [tipado dinámico](http://es.wikipedia.org/wiki/Tipado_din%C3%A1mico), [alto nivel](http://es.wikipedia.org/wiki/Lenguaje_de_alto_nivel) y [alto desempeño](http://es.wikipedia.org/wiki/Computaci%C3%B3n_de_alto_rendimiento) para la computación [genérica](http://es.wikipedia.org/wiki/Lenguaje_de_programaci%C3%B3n_de_prop%C3%B3sito_general), [técnica y científica](http://es.wikipedia.org/wiki/Computaci%C3%B3n_cient%C3%ADfica), con una sintaxis que es familiar para los usuarios de otros entornos de computación técnica y científica. Provee de un [sofisticado compilador JIT](http://es.wikipedia.org/wiki/Compilaci%C3%B3n_en_tiempo_de_ejecuci%C3%B3n), [ejecución distribuida y paralela](http://docs.julialang.org/en/release-0.3/manual/parallel-computing), [precisión numérica](http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers) y de una [extensa librería con funciones matemáticas](http://docs.julialang.org/en/release-0.3/stdlib). La librería estándar, escrita casi completamente en Julia, también integra las mejores y más maduras librerías de C y Fortran para el [álgebra lineal](http://docs.julialang.org/en/release-0.3/stdlib/linalg), [generación de números aleatorios](http://docs.julialang.org/en/release-0.3/stdlib/numbers/?highlight=random#random-numbers), [procesamiento de señales](http://docs.julialang.org/en/release-0.3/stdlib/math/?highlight=signal#signal-processing), y [procesamiento de cadenas](http://docs.julialang.org/en/release-0.3/stdlib/strings). Adicionalmente, la comunidad de [desarrolladores de Julia](https://github.com/JuliaLang/julia/graphs/contributors) contribuye un número de [paquetes externos](http://pkg.julialang.org) a través del gestor de paquetes integrado de Julia a un paso acelerado. [IJulia](https://github.com/JuliaLang/IJulia.jl), una colaboración entre las comunidades de [IPython](http://ipython.org) y Julia, provee de una poderosa interfaz gráfica basada en el [navegador para Julia](https://juliabox.org). En Julia los programas están organizados entorno al [despacho múltiple](http://docs.julialang.org/en/release-0.3/manual/methods/#man-methods); definiendo funciones y sobrecargándolas para diferentes combinaciones de tipos de argumentos, los cuales también pueden ser definidos por el usuario. @@ -41,7 +39,7 @@ En Julia los programas están organizados entorno al [despacho múltiple](http:/ Esto se basa en la versión `0.3.11`. -```ruby +```julia # Los comentarios de una línea comienzan con una almohadilla (o signo de gato). #= @@ -931,8 +929,6 @@ code_native(area_circulo, (Float64,)) =# ``` -![Julia-tan](http://s27.postimg.org/x37ndhz0j/julia_tan_small.png) - ## ¿Listo para más? Para más detalles, lee el [manual de Julia](http://docs.julialang.org/en/release-0.3). diff --git a/ja-jp/julia-jp.html.markdown b/ja-jp/julia-jp.html.markdown index 209e4a87..0d009216 100644 --- a/ja-jp/julia-jp.html.markdown +++ b/ja-jp/julia-jp.html.markdown @@ -14,7 +14,7 @@ Julia は科学技術計算向けに作られた、同図像性を持った(homo この文章は、Julia の2013年10月18日現在の開発バージョンを元にしています。 -```ruby +```julia # ハッシュ(シャープ)記号から改行までは単一行コメントとなります。 #= 複数行コメントは、 '#=' と '=#' とで囲むことで行えます。 diff --git a/pt-br/julia-pt.html.markdown b/pt-br/julia-pt.html.markdown index 52675bf5..70c13551 100644 --- a/pt-br/julia-pt.html.markdown +++ b/pt-br/julia-pt.html.markdown @@ -12,7 +12,7 @@ Julia é uma linguagem homoicônica funcional focada na computação técnica. A Este tutorial é baseado no Julia 0.3. -```ruby +```julia # Linhas únicas de comentários começam com o simbolo hash(jogo da velha). #= Comentários de multiplas linhas podem ser escritos colocando '#=' antes do texto e '=#' @@ -88,7 +88,7 @@ false # Uma string pode ser indexada como um vetor de caracteres "Isso é uma string"[1] # => 'I' # Julia começa a indexar a partir do 1 # Porém isso não funcionará direito com strings em UTF8, -# portanto é recomendado usar iterações sobre uma string (map, loops com for, etc). +# portanto é recomendado usar iterações sobre uma string (map, loops com for, etc). # $ pode ser usado para interpolação de string: "2 + 2 = $(2 + 2)" # => "2 + 2 = 4" @@ -110,7 +110,7 @@ some_var # => 5 # Acessando a variável anterior não iniciada é um erro try - some_other_var # => ERROR: some_other_var não definida + some_other_var # => ERROR: some_other_var não definida catch e println(e) end @@ -130,7 +130,7 @@ SomeOtherVar123! = 6 # => 6 # de underscore é desencorajado a menos que o nome da variável seja dificil # de ler. # -# * Os nomes de tipos começam com letra maiúscula e a separação de letras é +# * Os nomes de tipos começam com letra maiúscula e a separação de letras é # feita a partir de CamelCase no lugar de underscores. # # * Nomes de funções e macros são em minúsculo, sem underscore. @@ -186,8 +186,8 @@ catch e println(e) end -# Erros listam a linha e o nome do arquivo que ele está, mesmo se for uma -# biblioteca padrão. Se você construiu Julia pelo source, você pode olhar na +# Erros listam a linha e o nome do arquivo que ele está, mesmo se for uma +# biblioteca padrão. Se você construiu Julia pelo source, você pode olhar na # pasta base dentro da pasta do Julia para encontrar esses arquivos. # Você pode inicializar vetores com limites @@ -315,7 +315,7 @@ end # Tipos iterativos incluem Range, Array, set Dict e String. for animal=["dog", "cat", "mouse"] println("$animal is a mammal") - # Você pode interpolar variáveis usando $ ou expressões em strings + # Você pode interpolar variáveis usando $ ou expressões em strings end # exibe: # dog is a mammal @@ -379,14 +379,14 @@ end function add(x, y) println("x is $x and y is $y") - # Funções retornam o valor da sua ultima declaração + # Funções retornam o valor da sua ultima declaração t x + y end add(5, 6) # => 11 after printing out "x is 5 and y is 6" # Você pode definir funções que tomam um numero incerto de -# argumentos +# argumentos function varargs(args...) return args # use a palavra chave return para retornar um valor em qualquer parte da função @@ -471,7 +471,7 @@ add_10 = create_adder(10) add_10(3) # => 13 -# Há +# Há # There are built-in higher order functions map(add_10, [1,2,3]) # => [11, 12, 13] filter(x -> x > 5, [3, 4, 5, 6, 7]) # => [6, 7] @@ -672,7 +672,7 @@ square_area(5) #25 # O que acontece quando alimentamos square_area com um inteiro? # What happens when we feed square_area an integer? -code_native(square_area, (Int32,)) +code_native(square_area, (Int32,)) # .section __TEXT,__text,regular,pure_instructions # Filename: none # Source line: 1 # Prólogo @@ -705,7 +705,7 @@ code_native(square_area, (Float64,)) # vmulsd XMM0, XMM0, XMM0 # Duplicação ecalar de precisão multipla(AVX) # pop RBP # ret - # + # # Note que Julia usará instruções de ponto flutuante se quaser um dos # argumentos forem float # Vamos calcular a área de um circulo @@ -739,10 +739,10 @@ code_native(circle_area, (Float64,)) # vmulsd XMM0, XMM1, XMM0 # pop RBP # ret - # + # ``` ## Extras -Você pode ver mais um monte de detalhes no [manual de Julia] (http://docs.julialang.org/en/latest/manual/) +Você pode ver mais um monte de detalhes no [manual de Julia](http://docs.julialang.org/en/latest/manual/) O melhor lugar pra pedir ajuda em Julia é a (muito amigável) [mailing list](https://groups.google.com/forum/#!forum/julia-users). diff --git a/ru-ru/julia-ru.html.markdown b/ru-ru/julia-ru.html.markdown index 964a9eb9..ac5cc3df 100644 --- a/ru-ru/julia-ru.html.markdown +++ b/ru-ru/julia-ru.html.markdown @@ -13,7 +13,7 @@ Julia — гомоиконный функциональный язык прог Документ описывает текущую dev-версию Julia от 18-о октября 2013 года. -```ruby +```julia # Однострочные комментарии начинаются со знака решётки. #################################################### @@ -113,7 +113,7 @@ catch e end # Имена переменных начинаются с букв. -# После первого символа можно использовать буквы, цифры, +# После первого символа можно использовать буквы, цифры, # символы подчёркивания и восклицательные знаки. SomeOtherVar123! = 6 # => 6 @@ -123,7 +123,7 @@ SomeOtherVar123! = 6 # => 6 2 * π # => 6.283185307179586 # Рекомендации по именованию: -# * имена переменных в нижнем регистре, слова разделяются символом +# * имена переменных в нижнем регистре, слова разделяются символом # подчёркивания ('\_'); # # * для имён типов используется CamelCase; @@ -184,7 +184,7 @@ end # Вывод ошибок содержит строку и файл, где произошла ошибка, # даже если это случилось в стандартной библиотеке. -# Если вы собрали Julia из исходных кодов, +# Если вы собрали Julia из исходных кодов, # то найти эти файлы можно в директории base. # Создавать массивы можно из последовательности @@ -445,7 +445,7 @@ all_the_args(1, 3, keyword_arg=4) # optional arg: 3 # keyword arg: 4 -# Функции в Julia первого класса +# Функции в Julia первого класса function create_adder(x) adder = function (y) return x + y @@ -526,7 +526,7 @@ sherekhan = typeof(tigger)(5.6,"fire") # => Tiger(5.6,"fire") # abstract Name abstract Cat # просто имя и точка в иерархии типов -# Объекты абстрактных типов создавать нельзя, +# Объекты абстрактных типов создавать нельзя, # но зато от них можно наследовать подтипы. # Например, Number — это абстрактный тип. subtypes(Number) # => 6 элементов в массиве Array{Any,1}: @@ -672,40 +672,40 @@ square_area(l) = l * l # square_area (generic function with 1 method) square_area(5) #25 # Что происходит, когда мы передаём функции square_area целое число? -code_native(square_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 # Вводная часть - # push RBP - # mov RBP, RSP - # Source line: 1 - # movsxd RAX, EDI # - # imul RAX, RAX # - # pop RBP # - # ret # +code_native(square_area, (Int32,)) + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 # Вводная часть + # push RBP + # mov RBP, RSP + # Source line: 1 + # movsxd RAX, EDI # + # imul RAX, RAX # + # pop RBP # + # ret # code_native(square_area, (Float32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulss XMM0, XMM0, XMM0 # Произведение чисел одинарной точности (AVX) - # pop RBP - # ret + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulss XMM0, XMM0, XMM0 # Произведение чисел одинарной точности (AVX) + # pop RBP + # ret code_native(square_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vmulsd XMM0, XMM0, XMM0 # Произведение чисел двойной точности (AVX) - # pop RBP - # ret - # + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vmulsd XMM0, XMM0, XMM0 # Произведение чисел двойной точности (AVX) + # pop RBP + # ret + # # Если хотя бы один из аргументов является числом с плавающей запятой, # то Julia будет использовать соответствующие инструкции. # Вычислим площать круга @@ -713,33 +713,33 @@ circle_area(r) = pi * r * r # circle_area (generic function with 1 method) circle_area(5) # 78.53981633974483 code_native(circle_area, (Int32,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # Source line: 1 - # vcvtsi2sd XMM0, XMM0, EDI # Загрузить целое число (r) - # movabs RAX, 4593140240 # Загрузить pi - # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r - # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r - # pop RBP - # ret - # + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # Source line: 1 + # vcvtsi2sd XMM0, XMM0, EDI # Загрузить целое число (r) + # movabs RAX, 4593140240 # Загрузить pi + # vmulsd XMM1, XMM0, QWORD PTR [RAX] # pi * r + # vmulsd XMM0, XMM0, XMM1 # (pi * r) * r + # pop RBP + # ret + # code_native(circle_area, (Float64,)) - # .section __TEXT,__text,regular,pure_instructions - # Filename: none - # Source line: 1 - # push RBP - # mov RBP, RSP - # movabs RAX, 4593140496 - # Source line: 1 - # vmulsd XMM1, XMM0, QWORD PTR [RAX] - # vmulsd XMM0, XMM1, XMM0 - # pop RBP - # ret - # + # .section __TEXT,__text,regular,pure_instructions + # Filename: none + # Source line: 1 + # push RBP + # mov RBP, RSP + # movabs RAX, 4593140496 + # Source line: 1 + # vmulsd XMM1, XMM0, QWORD PTR [RAX] + # vmulsd XMM0, XMM1, XMM0 + # pop RBP + # ret + # ``` ## Что дальше? diff --git a/zh-cn/julia-cn.html.markdown b/zh-cn/julia-cn.html.markdown index b350b6dc..3b53160a 100644 --- a/zh-cn/julia-cn.html.markdown +++ b/zh-cn/julia-cn.html.markdown @@ -93,7 +93,7 @@ false # 字符串使用 UTF-8 编码 # 可以像取数组取值一样用 index 取出对应字符 ascii("This is a string")[1] -# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase) +# => 'T': ASCII/Unicode U+0054 (category Lu: Letter, uppercase) # Julia 的 index 从 1 开始 :( # 但只有在字符串仅由 ASCII 字符构成时,字符串才能够被安全的引索 # 因此建议使用遍历器 (map, for loops, 等) @@ -186,7 +186,7 @@ a[1] # => 1 # 永远记住 Julia 的引索从 1 开始!而不是 0! a[end] # => 6 # 数组还支持 popfirst! 和 pushfirst! -popfirst!(a) # => 1 +popfirst!(a) # => 1 a # => [2,4,3,4,5,6] pushfirst!(a, 7) # => [7,2,4,3,4,5,6] a # => [7,2,4,3,4,5,6] @@ -200,16 +200,16 @@ arr # => [4,5,6] # 数组越界会抛出 BoundsError try - a[0] - # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + a[0] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at # index [0] # => Stacktrace: # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 # => [2] top-level scope at none:0 # => [3] ... # => in expression starting at ...\LearnJulia.jl:203 - a[end + 1] - # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at + a[end + 1] + # => ERROR: BoundsError: attempt to access 7-element Array{Int64,1} at # index [8] # => Stacktrace: # => [1] getindex(::Array{Int64,1}, ::Int64) at .\array.jl:731 @@ -234,7 +234,7 @@ a[2:end] # => [2, 3, 4, 5] # 用 splice! 切割原数组 arr = [3,4,5] -splice!(arr, 2) # => 4 +splice!(arr, 2) # => 4 arr # => [3,5] # 用 append! 连接数组 @@ -253,8 +253,8 @@ tup = (1, 2, 3) # => (1,2,3) typeof(tup) # => Tuple{Int64,Int64,Int64} tup[1] # => 1 try - tup[1] = 3 - # => ERROR: MethodError: no method matching + tup[1] = 3 + # => ERROR: MethodError: no method matching # setindex!(::Tuple{Int64,Int64,Int64}, ::Int64, ::Int64) catch e println(e) @@ -266,7 +266,7 @@ tup[1:2] # => (1,2) in(2, tup) # => true # 可以将元组的元素解包赋给变量 -a, b, c = (1, 2, 3) # => (1,2,3) +a, b, c = (1, 2, 3) # => (1,2,3) a # => 1 b # => 2 c # => 3 @@ -282,7 +282,7 @@ f # => 6 (1) == 1 # => true # 交换值 -e, d = d, e # => (5,4) +e, d = d, e # => (5,4) d # => 5 e # => 4 @@ -306,7 +306,7 @@ keys(filled_dict) # 获得所有值 values(filled_dict) -# => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: +# => Base.ValueIterator for a Dict{String,Int64} with 3 entries. Values: # => 2, 1, 3 # 注意,值的顺序也一样 @@ -368,7 +368,7 @@ end # 可迭代的类型包括:Range, Array, Set, Dict 和 AbstractString for animal = ["dog", "cat", "mouse"] println("$animal is a mammal") - # 你可以用 $ 将变量或表达式插入字符串中 + # 你可以用 $ 将变量或表达式插入字符串中 end # => dog is a mammal # => cat is a mammal @@ -528,7 +528,7 @@ function create_adder(x) end # => create_adder (generic function with 1 method) -add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) +add_10 = create_adder(10) # => (::getfield(Main, Symbol("#adder#11")){Int64}) # (generic function with 1 method) add_10(3) # => 13 @@ -707,7 +707,7 @@ fight(l::Lion, c::Cat) = println("The victorious cat says $(meow(c))") fight(Lion("balooga!"), Panther()) # => The victorious cat says grrr try - fight(Panther(), Lion("RAWR")) + fight(Panther(), Lion("RAWR")) # => ERROR: MethodError: no method matching fight(::Panther, ::Lion) # => Closest candidates are: # => fight(::Tiger, ::Lion) at ... @@ -736,7 +736,7 @@ catch e end # 在不同版本的 Julia 中错误信息可能有所不同 -fight(l::Lion, l2::Lion) = println("The lions come to a tie") +fight(l::Lion, l2::Lion) = println("The lions come to a tie") # => fight (generic function with 5 methods) fight(Lion("RAR"), Lion("brown", "rarrr")) # => The lions come to a tie @@ -749,20 +749,20 @@ square_area(5) # => 25 # 当我们喂给 square_area 一个整数时会发生什么? code_native(square_area, (Int32,), syntax = :intel) - # .text - # ; Function square_area { - # ; Location: REPL[116]:1 # 函数序言 (Prologue) - # push rbp - # mov rbp, rsp - # ; Function *; { - # ; Location: int.jl:54 - # imul ecx, ecx # 求 l 的平方,并把结果放在 ECX 中 - # ;} - # mov eax, ecx - # pop rbp # 还原旧的基址指针(base pointer) - # ret # 返回值放在 EAX 中 - # nop dword ptr [rax + rax] - # ;} + # .text + # ; Function square_area { + # ; Location: REPL[116]:1 # 函数序言 (Prologue) + # push rbp + # mov rbp, rsp + # ; Function *; { + # ; Location: int.jl:54 + # imul ecx, ecx # 求 l 的平方,并把结果放在 ECX 中 + # ;} + # mov eax, ecx + # pop rbp # 还原旧的基址指针(base pointer) + # ret # 返回值放在 EAX 中 + # nop dword ptr [rax + rax] + # ;} # 使用 syntax 参数指定输出语法。默认为 AT&T 格式,这里指定为 Intel 格式 code_native(square_area, (Float32,), syntax = :intel) From 12ecedd4f51ec9f61b45058755c161d773e1be40 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 27 May 2024 12:15:14 -0600 Subject: [PATCH 262/392] Correct highlighted lanugages --- bc.html.markdown | 6 ++-- de-de/bc.html.markdown | 22 ++++++------ elisp.html.markdown | 2 +- fsharp.html.markdown | 2 +- it-it/solidity.html.markdown | 6 ++-- pt-br/bc-pt.html.markdown | 6 ++-- pt-br/solidity-pt.html.markdown | 2 +- sed.html.markdown | 2 +- solidity.html.markdown | 6 ++-- tr-tr/fsharp-tr.html.markdown | 2 +- uk-ua/wasm-ua.html.markdown | 2 +- wasm.html.markdown | 2 +- wikitext.html.markdown | 59 ++++++++++++++++++--------------- zh-cn/solidity-cn.html.markdown | 2 +- 14 files changed, 63 insertions(+), 58 deletions(-) diff --git a/bc.html.markdown b/bc.html.markdown index 3420f766..d4825739 100644 --- a/bc.html.markdown +++ b/bc.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Btup"] filename: learnbc.bc --- -```c +```bc /*This is a multi- line comment.*/ # This is also a (one-line) comment! (in GNU bc). @@ -29,12 +29,12 @@ hour = read() /*Input a number*/ if(hour < 12) { /*Operators are exactly like C.*/ print "Good morning\n" /*"print" outputs strings or variables - separated by commas.*/ + separated by commas.*/ } else if(hour == 12) { print "Hello\n" /*Escaping sequences start with a \ in a string. In order to make the escaping sequences clearer, here - is a simplified list of them that will work in bc: + is a simplified list of them that will work in bc: \b: backspace \c: carriage return \n: newline diff --git a/de-de/bc.html.markdown b/de-de/bc.html.markdown index a73d6e87..5b169f34 100644 --- a/de-de/bc.html.markdown +++ b/de-de/bc.html.markdown @@ -5,7 +5,8 @@ contributors: filename: learnbc-de.bc lang: de-de --- -```c + +```bc /* Das ist ein mehr- zeiliger Kommentar */ # Das ist ein (einzeiliger) Kommentar (in GNU bc). @@ -14,11 +15,11 @@ zeiliger Kommentar */ num = 45 /* Alle Variablen speichern nur Doubles und es ist nicht möglich String-Konstanten direkt zu speichern */ num = 45; /* Es kann nach jedem Statement ein optionales Semikolon - hinzugefügt werden */ + hinzugefügt werden */ /* Blöcke werden mit den Operatoren {} (ähnlich wie in C) bezeichnet */ while(num < 50) { - num += 1 /* äquivalent zu num=num+1. - a = a Op b ist äquivalent zu a Op= b*/ + num += 1 /* äquivalent zu num=num+1. + a = a Op b ist äquivalent zu a Op= b*/ } /* Ausserdem gibt es ++ (Inkrement) und -- (Dekrement) Operatoren */ /* Es gibt 3 spezielle Variablen: @@ -30,21 +31,21 @@ hour = read() /*Eingabe einer Zahl*/ if(hour < 12) { /*Operatoren sind genau wie in C*/ print "Guten Morgen\n" /*"print" Gibt Strings oder Variablen - mit einem Komma separiert aus.*/ + mit einem Komma separiert aus.*/ } else if(hour == 12) { print "Hallo\n" - /* Escape-Sequenzen starten mit einem \ in einem String. - Um Escape-Sequenzen klarer zu machen, ist hier eine vereinfachte - Liste, welche in bc funktioneren: + /* Escape-Sequenzen starten mit einem \ in einem String. + Um Escape-Sequenzen klarer zu machen, ist hier eine vereinfachte + Liste, welche in bc funktioneren: \b: Backspace \c: carriage return \n: Zeilenumbruch \t: Tab \\: Backslash*/ } else { - /* Standardmässig sind Variablen global. */ + /* Standardmässig sind Variablen global. */ thisIsGlobal = 5 - /*Variablen können lokal gemacht werden. Benutze das Schlüsselwort "auto" + /*Variablen können lokal gemacht werden. Benutze das Schlüsselwort "auto" in einer Funktion.*/ } @@ -100,4 +101,3 @@ das Programm beendet. Diese Codezeile ist optional.*/ Viel Spass mit diesem einfachen Rechner! (Oder dieser Programmiersprache, um exakt zu sein.) Das ganze Programm wurde in GNU bc geschrieben. Um es auszuführen, benutze ```bc learnbc.bc```. - diff --git a/elisp.html.markdown b/elisp.html.markdown index 5d98ceff..1355e6c3 100644 --- a/elisp.html.markdown +++ b/elisp.html.markdown @@ -7,7 +7,7 @@ contributors: filename: learn-emacs-lisp.el --- -```scheme +```elisp ;; This gives an introduction to Emacs Lisp in 15 minutes (v0.2d) ;; ;; First make sure you read this text by Peter Norvig: diff --git a/fsharp.html.markdown b/fsharp.html.markdown index aa2a2751..10859b34 100644 --- a/fsharp.html.markdown +++ b/fsharp.html.markdown @@ -16,7 +16,7 @@ The syntax of F# is different from C-style languages: If you want to try out the code below, you can go to [https://try.fsharp.org](https://try.fsharp.org) and paste it into an interactive REPL. -```csharp +```fsharp // single line comments use a double slash (* multi line comments use (* . . . *) pair diff --git a/it-it/solidity.html.markdown b/it-it/solidity.html.markdown index 77cb2ad3..a50f08e5 100644 --- a/it-it/solidity.html.markdown +++ b/it-it/solidity.html.markdown @@ -118,7 +118,7 @@ di tempo, ti apparirà la stessa interfaccia per il contratto nella parte inferiore dello schermo. -```javascript +```solidity // Iniziamo con un semplice contratto su una Banca // Permette di depositare, prelevare e fare l'estratto conto @@ -800,7 +800,7 @@ contract SomeOracle { Prova l'esempio completo qui sotto [usando remix e la `Javascript VM`](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=3d12cd503dcedfcdd715ef61f786be0b&runs=200) -```javascript +```solidity // *** ESEMPIO: Un esempio di crowdfunding (molto simile a Kickstarter) *** // ** START EXAMPLE ** @@ -944,7 +944,7 @@ contract CrowdFunder { Qualche altra funzionalità. -```javascript +```solidity // 10. ATRE FUNZIONALITA' NATIVE // Unità di valuta diff --git a/pt-br/bc-pt.html.markdown b/pt-br/bc-pt.html.markdown index f3f25601..90908127 100644 --- a/pt-br/bc-pt.html.markdown +++ b/pt-br/bc-pt.html.markdown @@ -7,7 +7,7 @@ translators: lang: pt-br filename: learnbc-pt.bc --- -```c +```bc /*Este é um comentário multi-linhas*/ # Este é um comentário de uma única linha! (em bc GNU). @@ -33,7 +33,7 @@ hora = read() /*Lê a entrada de um número*/ if(hora < 12) { /*Os operadores são idênticos ao C.*/ print "Bom dia\n" /*"print" imprime strings ou variáveis - separados por vírgula (,).*/ + separados por vírgula (,).*/ } else if(hora == 12) { print "Olá\n" /*Para escapar strings, inicie a string com \. @@ -97,7 +97,7 @@ for(i = 0; i <= 3; i++) { /*Para acessar um array, faça assim:*/ print a[0], " ", a[1], " ", a[2], " ", a[3], "\n" quit /*Adicione essa linha no final do código -para garantir que o programa encerre. Essa linha é opcional.*/ +para garantir que o programa encerre. Essa linha é opcional.*/ ``` Aproveite bem essa simples calculadora! (Ou essa linguagem de programação, para ser exato.) diff --git a/pt-br/solidity-pt.html.markdown b/pt-br/solidity-pt.html.markdown index c77ff298..4d30d62a 100644 --- a/pt-br/solidity-pt.html.markdown +++ b/pt-br/solidity-pt.html.markdown @@ -38,7 +38,7 @@ Como Solidity e Ethereum ainda estão sob desenvolvimento, funcionalidades beta e experimentais são tipicamente marcadas e sujeitas à mudanças. Pull requests são bem-vindos. -```javascript +```solidity // Primeiramente, um contrato de um Banco simples // Permite depósitos, retiradas e checagens de saldo diff --git a/sed.html.markdown b/sed.html.markdown index 3e6d8fc8..b544af5f 100644 --- a/sed.html.markdown +++ b/sed.html.markdown @@ -26,7 +26,7 @@ on its standard output. You can suppress the default output by specifying the `-n` command-line argument. -```perl +```sed #!/usr/bin/sed -f # Files that begin with the above line and are given execute permission # can be run as regular scripts. diff --git a/solidity.html.markdown b/solidity.html.markdown index 094baa13..be0d34e8 100644 --- a/solidity.html.markdown +++ b/solidity.html.markdown @@ -93,7 +93,7 @@ This will use whatever network is currently selected in your metamask as the net For now, please continue to use the `Javascript VM` unless instructed otherwise. When you deploy to a testnet, metamask will pop up to ask you to "confirm" the transaction. Hit yes, and after a delay, you'll get the same contract interface at the bottom of your screen. -```javascript +```solidity // First, a simple Bank contract // Allows deposits, withdrawals, and balance checks @@ -720,7 +720,7 @@ contract SomeOracle { Work with the full example below using the [`Javascript VM` in remix here.](https://remix.ethereum.org/#version=soljson-v0.6.6+commit.6c089d02.js&optimize=false&evmVersion=null&gist=3d12cd503dcedfcdd715ef61f786be0b&runs=200) -```javascript +```solidity // *** EXAMPLE: A crowdfunding example (broadly similar to Kickstarter) *** // ** START EXAMPLE ** @@ -860,7 +860,7 @@ contract CrowdFunder { Some more functions. -```javascript +```solidity // 10. OTHER NATIVE FUNCTIONS // Currency units diff --git a/tr-tr/fsharp-tr.html.markdown b/tr-tr/fsharp-tr.html.markdown index 816c12b3..3315cfad 100644 --- a/tr-tr/fsharp-tr.html.markdown +++ b/tr-tr/fsharp-tr.html.markdown @@ -19,7 +19,7 @@ F#'ın söz dizimi C-stili dillerden farklıdır: Aşağıdaki kodu denemek istiyorsanız, [tryfsharp.org](http://www.tryfsharp.org/Create)'a gidin be interaktif REPL'e kodu yapıştırın. -```csharp +```fsharp // tek satır yorumlar ikili bölme işareti ile başlar (* çok satırlı yorumlar ( * . . . * ) ikilisini kullanır diff --git a/uk-ua/wasm-ua.html.markdown b/uk-ua/wasm-ua.html.markdown index 28c54941..e514a9b9 100644 --- a/uk-ua/wasm-ua.html.markdown +++ b/uk-ua/wasm-ua.html.markdown @@ -8,7 +8,7 @@ translators: - ["Oleh Hromiak", "https://github.com/ogroleg"] --- -``` +```wast ;; learnwasm-ua.wast (module diff --git a/wasm.html.markdown b/wasm.html.markdown index abb3a6a0..b12c3531 100644 --- a/wasm.html.markdown +++ b/wasm.html.markdown @@ -5,7 +5,7 @@ contributors: - ["Dean Shaff", "http://dean-shaff.github.io"] --- -``` +```wast ;; learn-wasm.wast (module diff --git a/wikitext.html.markdown b/wikitext.html.markdown index 65a85a1e..568b44b8 100644 --- a/wikitext.html.markdown +++ b/wikitext.html.markdown @@ -26,9 +26,9 @@ Section headings are bracketed by `=`. They go from `= One equal sign =` to `=== Note that the `= One equal sign =` heading actually corresponds to the title of the page, and so cannot actually be used within a page. Consequently, the least number of equal signs is `== Two equal signs ==`. -Subscripts and superscripts can be written as `x1` and `x1`. Alternatively they can be written by the `` tag (see below). `Small` and `big` texts are rarely used. +Subscripts and superscripts can be written as `x1` and `x1`. Alternatively they can be written by the `` tag (see below). `Small` and `big` texts are rarely used. -``` +```wikitext Colons allow indentation :Each colon creates an indentation three characters wide. ::and they can be nested. @@ -42,21 +42,22 @@ The syntax for tables is [very complicated](https://en.wikipedia.org/wiki/Help:T ```wikitext {| class="wikitable" -|+ -! column title A -! column title B +|+ +! column title A +! column title B |- -| cell A1 -| cell B1 +| cell A1 +| cell B1 |- -| cell A2 -| cell B2 +| cell A2 +| cell B2 |- -| ... -| ... +| ... +| ... |} ``` -which renders to + +which renders to | **column title A** | **column title B** | |---|---| | cell A1 | cell B1 | @@ -67,13 +68,16 @@ Be warned that the newlines in a wikitext table are meaningful. Deleting a singl You can insert images, audios, videos, or other forms of media by `[[File:Image.png|thumb|right|Image caption]]`. All media files must be hosted on [Wikimedia Commons](https://commons.wikimedia.org/wiki/Main_Page). You can insert quotations either by HTML-like tag + ```wikitext

    Quotation text.

    Name, source, reference

    ``` + or [template](#templates) + ```wikitext {{Quote|text=Quotation text.|title=Title|author=Author|source=Location in the publication}} ``` @@ -82,7 +86,8 @@ A "[non-breaking space](https://en.wikipedia.org/wiki/Non-breaking_space)" is a Extra whitespaces can be specified by `pad` tag. For example, `{{pad|4.0em}}` is a white space with length 4.0 [em-dashes](https://en.wikipedia.org/wiki/Dash#Em_dash). -Longer code blocks can be done by +Longer code blocks can be done by + ```wikitext #include @@ -91,7 +96,9 @@ int m2 (int ax, char *p_ax) { return 0; } ``` -which renders to + +which renders to + ```cpp #include int m2 (int ax, char *p_ax) { @@ -102,13 +109,13 @@ int m2 (int ax, char *p_ax) { ## Linking -Basic `[[linking]]` is done by double brackets. +Basic `[[linking]]` is done by double brackets. -The `|` symbol allows displaying a `[[Actual page title|different text]]`. +The `|` symbol allows displaying a `[[Actual page title|different text]]`. The `#` symbol allows linking to sections within a text, like `[[Frog#Locomotion]]` or `[[Frog#Locomotion|locomotion in frogs]]`. -If a word is interrupted by a link, it is "blended" into the link. For example, `[[copy edit]]ors` renders to [copy editors](https://en.wikipedia.org/wiki/copy_edit). +If a word is interrupted by a link, it is "blended" into the link. For example, `[[copy edit]]ors` renders to [copy editors](https://en.wikipedia.org/wiki/copy_edit). To suppress this behavior, use ``. For example, `[[micro-]]second` renders to [micro-](https://en.wikipedia.org/wiki/micro-)second. @@ -130,6 +137,7 @@ The most (in)famous one is the \[citation needed\]`{{cn}}` template. Note that ` An `infobox` template is, as it says, a template for a box containing information. Usually, each page contains at most two infoboxes, one on top and one on bottom. For particularly detailed pages, there can be more than two. The infobox on the top is usually used to compactly display tabular information. They are common for biographies, geographical locations, and such. For example, the top infobox for [Euler](https://en.wikipedia.org/wiki/Leonhard_Euler) is: + ```wikitext {{Infobox scientist | name = Leonhard Euler @@ -144,12 +152,11 @@ The infobox on the top is usually used to compactly display tabular information. The infobox at the bottom is usually used to display a curated table of related links. For example, the bottom infobox for [Euler–Lagrange equation](https://en.wikipedia.org/wiki/Euler%E2%80%93Lagrange_equation) is just `{{Leonhard Euler}}`, which displays a box containing links to many of the things named after Euler. - `~~~~` is used to sign on talk pages, and expands to something like `Username (talk) 10:50, 12 June 2023 (UTC)`. ### Mathematics -`` tag renders $\LaTeX$ inline like `$`, while `` renders it on a separate line like `$$`. +`` tag renders $\LaTeX$ inline like `$`, while `` renders it on a separate line like `$$`. `E = mc^2` renders to $E = mc^2$. @@ -157,9 +164,9 @@ The infobox at the bottom is usually used to display a curated table of related One can also include math using [HTML renders](https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Mathematics#Using_HTML) or even by [plain Unicode](https://en.wikipedia.org/wiki/Mathematical_operators_and_symbols_in_Unicode). These are less flexible but more compatible with older browsers. Further, parts of Wikipedia syntax themselves are incompatible with ``, such as in section titles or some templates, forcing the use of HTML or Unicode in such cases. -Theorems and proofs can be boxed and named: +Theorems and proofs can be boxed and named: -``` +```wikitext {{Math theorem |name=Pythagorean theorem |note=Pythagoras, 500s BC @@ -171,12 +178,11 @@ Theorems and proofs can be boxed and named: |title=Proof by similar triangles |proof=Drop a perpendicular from point C to side AB. Now argue by proportionality. \blacksquare }} - ``` ## References -References are the backbone of Wikipedia `{{citation needed}}`. There are in general two ways to do citations. +References are the backbone of Wikipedia `{{citation needed}}`. There are in general two ways to do citations. | type | inline citation | expanded citation | | ---- | ---- | ---- | @@ -187,11 +193,10 @@ References are the backbone of Wikipedia `{{citation needed}}`. There are in gen As expanded citations are just inline citations without the `` tag, we will describe just inline citations. -The most basic form is a plaintext citation, like `Author, Title, date, [url](https://example.com/), etc`. +The most basic form is a plaintext citation, like `Author, Title, date, [url](https://example.com/), etc`. One should generally use a templated citation, like `{{cite web|url=https://example.com/|title=Example|date=2001|access-date=2023}}`. There are three forms of citation templates: [`cite web`](https://en.wikipedia.org/wiki/Template:Cite_web), [`cite journal`](https://en.wikipedia.org/wiki/Template:Cite_journal), [`cite book`](https://en.wikipedia.org/wiki/Template:Cite_book). - A citation can be named as `...`. It can then be invoked as ``. The instance `...` can go before or after ``. Any ordering would render to the same page. ## Typical Wikipedia page @@ -234,7 +239,7 @@ Something about the relation between X and Y. == References == -{{Reflist|30em}} +{{Reflist|30em}} {{Refbegin|30em}} @@ -255,6 +260,6 @@ Something about the relation between X and Y. ## Further reading * [Wikipedia's manual of style](https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style) -* [Wikitext cheatsheet](https://en.wikipedia.org/wiki/Help:Cheatsheet) +* [Wikitext cheatsheet](https://en.wikipedia.org/wiki/Help:Cheatsheet) * [Wikitext, full reference](https://en.wikipedia.org/wiki/Help:Wikitext). * [Tables, full reference](https://en.wikipedia.org/wiki/Help:Table#Simple_straightforward_tables) diff --git a/zh-cn/solidity-cn.html.markdown b/zh-cn/solidity-cn.html.markdown index 12a532bc..95110ea8 100644 --- a/zh-cn/solidity-cn.html.markdown +++ b/zh-cn/solidity-cn.html.markdown @@ -30,7 +30,7 @@ Solidity 代码中存在高风险和高成本的错误,因此你必须非常 由于 Solidity 和以太坊正在积极开发,通常会标记为实验或 beta 特性,并很可能会更改。因此欢迎 提交更改请求。 -```javascript +```solidity // 首先,一个简单的银行合约 // 允许存款、取款、以及检查余额 From 36db268e388238cdae927c9c220f9faae8c8d6ed Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 27 May 2024 12:17:10 -0600 Subject: [PATCH 263/392] Remove unsupported highlight languages (#4962) --- gleam.html.markdown | 2 +- golfscript.html.markdown | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/gleam.html.markdown b/gleam.html.markdown index df6cddfd..01d65e99 100644 --- a/gleam.html.markdown +++ b/gleam.html.markdown @@ -26,7 +26,7 @@ code in browser or any other JS-enabled runtime. When using this feature, TypeScript definitions get created, so you can interact with your Gleam code confidently, even from the outside. -```gleam +``` //// This comment with four slashes is a module-level. //// This kind of comments are used to describe the whole module. diff --git a/golfscript.html.markdown b/golfscript.html.markdown index f4b88a9f..b2cb60c9 100644 --- a/golfscript.html.markdown +++ b/golfscript.html.markdown @@ -31,7 +31,7 @@ of GolfScript, you can start running from "stdin". If you see a script starting it was probably designed to be dropped in a file and run with `golfscript file.gs`. You can pipe in or enter in your input at runtime. -```golfscript +``` > anything undefined technically evaluates to nothing and so is also a comment # but commenting it out explicitly anyway is probably a good idea because if # you use a reserved keyword or any punctuation you'll run into trouble. From 16d4cb721f2201a37673c72bf0aa2e0728adc7c2 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 27 May 2024 12:31:50 -0600 Subject: [PATCH 264/392] [gleam/en] fix metadata --- gleam.html.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/gleam.html.markdown b/gleam.html.markdown index 01d65e99..751beac0 100644 --- a/gleam.html.markdown +++ b/gleam.html.markdown @@ -1,6 +1,4 @@ --- -name: Gleam -category: language language: Gleam contributors: - ["Antonio Ognio", "https://github.com/aognio/"] From f56734356dbcd66f0c70b913bc2617a88d75329a Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 27 May 2024 21:26:51 -0600 Subject: [PATCH 265/392] [tmux/es] fix link and delete duplicate --- es-es/tmux-es.html.markdown | 13 +- es-es/tmux.html.markdown | 238 ------------------------------------ 2 files changed, 2 insertions(+), 249 deletions(-) delete mode 100644 es-es/tmux.html.markdown diff --git a/es-es/tmux-es.html.markdown b/es-es/tmux-es.html.markdown index 45800c72..f8baee6a 100644 --- a/es-es/tmux-es.html.markdown +++ b/es-es/tmux-es.html.markdown @@ -9,14 +9,12 @@ translators: lang: es-es --- - -[tmux](http://tmux.sourceforge.net) +[tmux](https://github.com/tmux/tmux) es un terminal multiplexor: habilita la creación, acceso y control de múltiples terminales controlados desde una sola pantalla. tmux puede ser separado de una pantalla y continuar corriendo en el fondo y luego ser insertado nuevamente. - ``` tmux [command] # Corre un comando # 'tmux' sin comandos creará una nueva sesión @@ -24,7 +22,7 @@ y luego ser insertado nuevamente. new # Crea una nueva sesión -s "Session" # Crea sesión con nombre -n "Window" # Crea ventana con nombre - -c "/dir" # Comienza en el directorio destino + -c "/dir" # Comienza en el directorio destino attach # Adjunta sesión última/disponible -t "#" # Adjunta sesión destino @@ -53,7 +51,6 @@ y luego ser insertado nuevamente. -a -t "#" # Cierra todas las sesiones menos el destino ``` - ### Atajos de Teclado El método para controlar una sesión adjunta tmux es mediante @@ -108,7 +105,6 @@ combinaciones de teclas llamadas teclas 'Prefijo'. M-Left, M-Right ``` - ### Configurando ~/.tmux.conf tmux.conf puede usarse para establecer opciones automáticas al arrancar, parecido a como .vimrc o init.el hacen. @@ -235,15 +231,10 @@ set -g status-interval 4 set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" ``` - ### Referencias [Tmux | Inicio](http://tmux.sourceforge.net) - [Tmux Manual](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) - [Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) - [Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) - [Mostrar CPU/MEM % en barra de estado](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) diff --git a/es-es/tmux.html.markdown b/es-es/tmux.html.markdown deleted file mode 100644 index cd29a972..00000000 --- a/es-es/tmux.html.markdown +++ /dev/null @@ -1,238 +0,0 @@ ---- -category: tool -tool: tmux -contributors: - - ["mdln", "https://github.com/mdln"] -translators: - - ["Ferran Pelayo", "https://github.com/ferranpm"] -filename: LearnTmux-es.txt -lang: es-es ---- - -[tmux](http://tmux.sourceforge.net) permite crear, controlar y acceder a -multiples terminales desde una sola ventana. Puede desconectarse una sesión de -la ventana, seguir corriendo en segundo plano y volver a conectar otra ventana -más tarde. - - -``` - tmux [command] # Correr un comando de tmux - # 'tmux' sin comando crea una nueva sesión. - - new # Crear una nueva sesión - -s "Session" # Crear una sesión con nombre - -n "Window" # Crear una ventana con nombre - -c "/dir" # Empezar en el directorio "/dir" - - attach # Atar la ventana a la ultima sesión iniciada - -t "#" # Atar la ventana a la sesión "#" - -d # Desatar la ventana de la sesión - - ls # Listar las sesiones abiertas - -a # Listar todas las sesiones abiertas - - lsw # Listar ventanas - -a # Listar todas las ventanas - -s # Listar todas las ventanas de la sesión - - lsp # Listar paneles - -a # Listar todos los paneles - -s # Listar todos los paneles de la sesión - -t # Listar paneles de la aplicación en el target - - kill-window # Eliminar la ventana actual - -t "#" # Eliminar la ventana "#" - -a # Eliminar todas las ventanas - -a -t "#" # Eliminar todas las ventanas menos la "#" - - kill-session # Eliminar la sesión actual - -t "#" # Eliminar la sesión "#" - -a # Eliminar todas las sessiones - -a -t "#" # Eliminar todas las sessiones menos la "#" -``` - - -### Atajos de teclado - -Para controlar una sesión atada se usa la combinación llamada 'Prefijo' + atajo. - -``` ----------------------------------------------------------------------- - (C-b) = Ctrl + b # 'Prefijo' por defecto requerido para usar los atajos - - (M-1) = Meta + 1 -o- Alt + 1 ----------------------------------------------------------------------- - - ? # Listar todos los atajos de teclado - : # Insertar un comando de tmux - r # Forzar refresco gráfico del cliente - c # Crear una nueva ventana - - ! # Quitar el panel actual de la ventana - % # Dividir el panel actual en dos (derecha e izquierda) - " # Dividir el panel actual en dos (arriba y abajo) - - n # Cambiar a la siguiente ventana - p # Cambiar a la ventana anterior - { # Cambiar el panel por el panel anterior - } # Cambiar el panel por el siguiente panel - - s # Seleccionar y atar el cliente a una sesión distinta - de forma interactiva - w # Seleccionar una ventana de forma interactiva - 0 to 9 # Seleccionar una ventana (del 0 al 9) - - d # Desatar el cliente actual de la sesión - D # Escojer un cliente a desatar - - & # Eliminar la ventana actual - x # Eliminar el panel actual - - Up, Down # Cambiar al panel de arriba, debajo, izquierda o derecha - Left, Right - - M-1 to M-5 # Ordenar los paneles - - C-Up, C-Down # Dimensionar el panel actual en pasos de una celda - C-Left, C-Right - - M-Up, M-Down # Dimensionar el panel actual en pasos de cinco celdas - M-Left, M-Right -``` - - -### Configurar ~/.tmux.conf - -El fichero tmux.conf se puede configurar para establecer unas opciones por -defecto, igual que .vimrc o init.el para vim o emacs. - -``` -# Ejemplo tmux.conf -# 2014.10 - - -### General -########################################################################### - -# Activar UTF-8 -setw -g utf8 on -set-option -g status-utf8 on - -# Limite del historico de comandos -set -g history-limit 2048 - -# Index Start -set -g base-index 1 - -# Ratón -set-option -g mouse-select-pane on - -# Forzar volver a cargar el fichero de configuración -unbind r -bind r source-file ~/.tmux.conf - - -### Atajos de teclado -########################################################################### - -# Quitar C-b como prefijo por defecto -unbind C-b - -# Establecer ` como nuevo prefijo -set-option -g prefix ` - -# Volver a la ventana anterior cuando el prefijo se pulsa dos veces -bind C-a last-window -bind ` last-window - -# Intercambiar entre C-a y ` como prefijo pulsando F11/F12 -bind F11 set-option -g prefix C-a -bind F12 set-option -g prefix ` - -# Preferencias de los atajos -setw -g mode-keys vi -set-option -g status-keys vi - -# Mover entre paneles con atajos de vim -bind h select-pane -L -bind j select-pane -D -bind k select-pane -U -bind l select-pane -R - -# Cambiar/Saltar de ventana -bind e previous-window -bind f next-window -bind E swap-window -t -1 -bind F swap-window -t +1 - -# Divisiones de paneles -bind = split-window -h -bind - split-window -v -unbind '"' -unbind % - -### Tema de colores -########################################################################### - -# Barra de estado -set-option -g status-justify left -set-option -g status-bg black -set-option -g status-fg white -set-option -g status-left-length 40 -set-option -g status-right-length 80 - -# Bordes de paneles -set-option -g pane-active-border-fg green -set-option -g pane-active-border-bg black -set-option -g pane-border-fg white -set-option -g pane-border-bg black - -# Color de los mensajes -set-option -g message-fg black -set-option -g message-bg green - -# Colores del estado de las ventanas -setw -g window-status-bg black -setw -g window-status-current-fg green -setw -g window-status-bell-attr default -setw -g window-status-bell-fg red -setw -g window-status-content-attr default -setw -g window-status-content-fg yellow -setw -g window-status-activity-attr default -setw -g window-status-activity-fg yellow - - -### UI -########################################################################### - -# Notificaciones -setw -g monitor-activity on -set -g visual-activity on -set-option -g bell-action any -set-option -g visual-bell off - -# Titulos de las ventanas -set-option -g set-titles on -set-option -g set-titles-string '#H:#S.#I.#P #W #T' # window number,program name,active (or not) - -# Formato de la barra de estado -set -g status-left "#[fg=red] #H#[fg=green]:#[fg=white]#S#[fg=green] |#[default]" - -# Mostrar estadisticas de rendimiento en la barra de estado -# Requiere https://github.com/thewtex/tmux-mem-cpu-load/ -set -g status-interval 4 -set -g status-right "#[fg=green] | #[fg=white]#(tmux-mem-cpu-load)#[fg=green] | #[fg=cyan]%H:%M #[default]" -``` - - -### Referencias - -[Tmux | Home](http://tmux.sourceforge.net) - -[Tmux Manual page](http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man1/tmux.1?query=tmux) - -[Gentoo Wiki](http://wiki.gentoo.org/wiki/Tmux) - -[Archlinux Wiki](https://wiki.archlinux.org/index.php/Tmux) - -[Display CPU/MEM % in statusbar](https://stackoverflow.com/questions/11558907/is-there-a-better-way-to-display-cpu-usage-in-tmux) From 779208e017ffda39b5a23482bd12a5c5519dc0b1 Mon Sep 17 00:00:00 2001 From: lucii7vel <33035261+lucii7vel@users.noreply.github.com> Date: Wed, 29 May 2024 07:29:56 -0700 Subject: [PATCH 266/392] [python/be] translate (#4963) --- be-by/python-by.html.markdown | 1136 +++++++++++++++++++++++++++++++++ 1 file changed, 1136 insertions(+) create mode 100644 be-by/python-by.html.markdown diff --git a/be-by/python-by.html.markdown b/be-by/python-by.html.markdown new file mode 100644 index 00000000..f16443b6 --- /dev/null +++ b/be-by/python-by.html.markdown @@ -0,0 +1,1136 @@ +--- +language: Python +contributors: + - ["Louie Dinh", "http://pythonpracticeprojects.com"] + - ["Steven Basart", "http://github.com/xksteven"] + - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] + - ["Rommel Martinez", "https://ebzzry.io"] + - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] + - ["caminsha", "https://github.com/caminsha"] + - ["Stanislav Modrak", "https://stanislav.gq"] + - ["John Paul Wohlscheid", "https://gitpi.us"] +translators: + - ["lucii7vel", "https://https://github.com/lucii7vel"] +filename: learnpython-by.py +lang: be-by +--- +Python быў створаны Гвіда ван Росумам у пачатку 90-х. Цяпер гэта адна з +самыя папулярных моў праграмавання. Я закахаўся ў Python за яго +сінтаксічную празрыстасць. Гэта літаральна выканальны псеўдакод. + +```python +# Аднарадковыя каментарыі пачынаюцца знакам рашоткі. + +""" Шматрадковыя каментарыі можна + рабіць выкарыстоўваючы тры ", яны часта + выкарыстоўваюцца ў якасці дакументацыі. +""" + +#################################################### +## 1. Прымітыўныя тыпы даных і аператары. +#################################################### + +# Лічбы +3 # => 3 + +# Відавочныя матэматычныя аперацыі +1 + 1 # => 2 +8 - 1 # => 7 +10 * 2 # => 20 +35 / 5 # => 7.0 + +# Вынік цэлалікавага дзялення акругляецца як для пазітыўных, +# так і для негатыўных значэнняў. +5 // 3 # => 1 +-5 // 3 # => -2 + +# Працуе таксама на лічбах з плаваючай кропкай. +5.0 // 3.0 # => 1.0 +-5.0 // 3.0 # => -2.0 + +# Вынік дзялення — заўсёды лічба з плаваючай кропкай. +10.0 / 3 # => 3.3333333333333335 + +# Дзяленне па модулю +7 % 3 # => 1 +# У выніку i % j атрымаецца значэнне са знакам j +-7 % 3 # => 2 + +# Узвядзенне ў ступень +2**3 # => 8 + +# Прыярытэт аперацый праз дужкі +1 + 3 * 2 # => 7 +(1 + 3) * 2 # => 8 + +# Лагічныя значэнні з'яўляюцца прымітывамі +# (Звярніце ўвагу на рэгістр) +True # => True +False # => False + +# Адмаўленне праз not +not True # => False +not False # => True + +# Лагічныя аператары +# Звярніце ўвагу, "and" і "or" чуллівыя да рэгістра +True and False # => False +False or True # => True + +# True і False на самай справе 1 і 0, толькі з іншымі ключавымі словамі. +True + True # => 2 +True * 8 # => 8 +False - 5 # => -5 + +# Параўнальныя аператары звяртаюцца да лічбавых значэнняў True і False. +0 == False # => True +2 > True # => True +2 == True # => False +-5 != False # => True + +# None, 0 і пустыя радкі/спісы/слоўнікі/картэжы/мноства адпавядаюць False. +# Усе іншыя значэнні адпавядаюць True. +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False +bool(set()) # => False +bool(4) # => True +bool(-6) # => True + +# Выкарыстоўванне лагічных аператараў на цэлалікавых значэннях ператварае +# іх у boolean для вылічэнняў, але вяртае значэнне іх зыходнага тыпу. +# Не блытайце з bool(int) і пабітавымі and/or (&, |). +bool(0) # => False +bool(2) # => True +0 and 2 # => 0 +bool(-5) # => True +bool(2) # => True +-5 or 0 # => -5 + +# Роўнасць == +1 == 1 # => True +2 == 1 # => False + +# Няроўнасць != +1 != 1 # => False +2 != 1 # => True + +# Больш параўнанняў +1 < 10 # => True +1 > 10 # => False +2 <= 2 # => True +2 >= 2 # => True + +# Праверка значэння на ўваход у дыяпазон +1 < 2 and 2 < 3 # => True +2 < 3 and 3 < 2 # => False +# Звязванне выглядае прыгажэй +1 < 2 < 3 # => True +2 < 3 < 2 # => False + +# (is супраць ==) is правярае, ці спасылаюцца дзве пераменныя на адзін і той жа +# аб'ект, а == правярае, ці маюць дзве пераменныя аднолькавыя значэнні. +a = [1, 2, 3, 4] # a спасылаецца на новы спіс [1, 2, 3, 4] +b = a # b спасылаецца туды ж, куды і a +b is a # => True, a і b спасылаюцца на адзін і той жа аб'ект +b == a # => True, аб'екты a і b аднолькавыя +b = [1, 2, 3, 4] # b спасылаецца на новы спіс [1, 2, 3, 4] +b is a # => False, a і b спасылаюцца на розныя аб'екты +b == a # => True, аб'екты a і b аднолькавыя + +# Радкі ствараюцца праз " ці ' +"Гэта радок." +'Гэта таксама радок.' + +# Радкі можна складваць +"Вітаю, " + "свет!" # => "Вітаю, свет!" +# Радковыя літаралы (але не пераменныя) магчыма злучаць без выкарыстоўвання '+' +"Вітаю, " "свет!" # => "Вітаю, свет!" + +# Радок можна успрымаць як спіс сімвалаў +"Вітаю, свет"[0] # => 'В' + +# Ёсць магчымасць знайсці даўжыню радка +len("Гэта радок") # => 10 + +# З версіі Python 3.6 магчыма выкарыстоўваць f-радкі +# або фарматаваныя радковыя літаралы. +name = "Рэйко" +f"Яна сказала, што яе завуць {name}." # => "Яна сказала, што яе завуць Рэйко" +# Любы дзейны Python-выраз унутры гэтых дужак вяртаецца ў радок. +f"Даўжыня {name} — {len(name)} сімвалаў." # => "Даўжыня Рэйко — 5 сімвалаў." + +# None — гэта аб'ект +None # => None + +# Не выкарыстоўвайце знак роўнасці '==' для параўнання аб'ектаў з None. +# Замест гэтага карыстайцеся 'is'. Ён правярае аб'екты на ідэнтычнасць. +"etc" is None # => False +None is None # => True + +#################################################### +## 2. Пераменныя і калекцыі +#################################################### + +# У Python ёсць функцыя print +print("Я Python. Рады бачыць!") # => Я Python. Рады бачыць! + +# Па змаўчанні print таксама пераводзіць на новы радок у канцы. +# Выкарыстоўвайце апцыянальны аргумент end каб змяніць канцоўку радка. +print("Вітаю, свет", end="!") # => Вітаю, свет! + +# Просты спосаб атрымаць уваходныя даныя з кансолі +input_string_var = input("Увядзіце даныя: ") # Вяртае даныя ў якасці радка + +# Ніякіх аб'яўленняў, толькі прызначэнні пераменных. +# Пераменныя заведзена называць у стылі snake_case. +some_var = 5 +some_var # => 5 + +# Звяртанне да непрызначаннай пераменнай прыводзіць да выключэння. +# Падрабязнасці пра апрацоўку выключэнняў у раздзеле "Паток кіравання". +some_unknown_var # Выкідвае NameError + +# if можа быць выкарыстаны ў якасці выражэння +# Эквівалент цернарнага аператара '?:' з C +"Так!" if 0 > 1 else "Не!" # => "Не!" + +# Спісы захоўваюць паслядоўнасці +li = [] +# Вы можаце стварыць запоўнены спіс +other_li = [4, 5, 6] + +# Дадаць нешта ў канец спіса праз append +li.append(1) # li цяпер [1] +li.append(2) # li цяпер [1, 2] +li.append(4) # li цяпер [1, 2, 4] +li.append(3) # li цяпер [1, 2, 4, 3] +# Выдаліць з канца праз pop +li.pop() # => 3 li цяпер [1, 2, 4] +# Пакладзём назад +li.append(3) # li цяпер зноў [1, 2, 4, 3] + +# Звяртайцеся да спіса як да звычайнага масіву +li[0] # => 1 +# Зварот да апошняга элемента +li[-1] # => 3 + +# Зварот за межы спіса выкідвае IndexError +li[4] # выклідвае IndexError + +# Магчыма звяртацца да дыяпазонаў праз адсячэнні. +# Пачатковы індэкс уключаецца ў дыяпазон, а канчатковы не +# (матэматыкі сярод вас ведаюць гэта як напаўадкрыты адцінак). +li[1:3] # Вярнуць спіс з індэкса 1 па 3 => [2, 4] +li[2:] # Вярнуць спіс з індэкса 2 => [4, 3] +li[:3] # Вярнуць спіс да індэкса 3 => [1, 2, 4] +li[::2] # Вярнуць спіс, абіраючы элементы з крокам 2 => [1, 4] +li[::-1] # Вярнуць спіс у адваротным парадку => [3, 4, 2, 1] +# Выкарыстоўвайце іх у рознай камбінацыі, каб ствараць лепшыя адсячэнні +# li[пачатак:канец:крок] + +# Зрабіць копію глыбінёй у адзін слой выкарыстоўваючы адсячэнні +li2 = li[:] # => li2 = [1, 2, 4, 3] але (li2 is li) верне false. + +# Выдаліць элемент са спіса па пазіцыі праз "del" +del li[2] # li цяпер [1, 2, 3] + +# Выдаліць першае знойдзенае значэнне +li.remove(2) # li цяпер [1, 3] +li.remove(2) # Выкідвае ValueError, бо ў спісе няма элемента са значэннем 2 + +# Уставіць элемент па дадзенаму індэксу +li.insert(1, 2) # li цяпер зноў [1, 2, 3] + +# Атрымаць індэкс першага элемента з дадзеным значэннем +li.index(2) # => 1 +li.index(4) # Выкідвае ValueError, бо ў спісе няма элемента са значэннем 4 + +# Магчыма складваць спісы. +# Заўвага: значэнні li і other_li не змяняюцца. +li + other_li # => [1, 2, 3, 4, 5, 6] + +# Аб'яднанне спісаў праз "extend()" +li.extend(other_li) # li цяпер [1, 2, 3, 4, 5, 6] + +# Праверка на наяўнасць элемента ў спісе праз "in" +1 in li # => True + +# Атрымаць даўжыню спіса праз "len()" +len(li) # => 6 + + +# Картэжы падобныя на спісы, але не змяняюцца +tup = (1, 2, 3) +tup[0] # => 1 +tup[0] = 3 # Выкідвае TypeError + +# Звярніце ўвагу, што картэжы даўжыні 1 павінны мець коску пасля +# апошняга элемента, але картэжы іншай даўжыні, нават 0, не. +type((1)) # => +type((1,)) # => +type(()) # => + +# Большасць аперацый для спісаў працуюць таксама на картэжах +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True + +# Вы можаце распакоўваць картэжы (або спісы) у пераменныя +a, b, c = (1, 2, 3) # a цяпер 1, b цяпер 2 і c цяпер 3 +# Таксама ёсць пашыраная распакоўка +a, *b, c = (1, 2, 3, 4) # a цяпер 1, b цяпер [2, 3] і c цяпер 4 +# Картэжы ствараюцца па змаўчанні, калі апусціць дужкі +d, e, f = 4, 5, 6 # картэж 4, 5, 6 распакоўваецца ў d, e, f, +# адпаведна, d = 4, e = 5 і f = 6. +# Цяпер паглядзіце, як лёгка абмяняць значэнні дзвюх пераменных +e, d = d, e # d цяпер 5, e цяпер 4 + + +# Слоўнікі змяшчаюць пары ключ/значэнне +empty_dict = {} +# Так выглядае папярэдне запоўнены слоўнік +filled_dict = {"адзін": 1, "два": 2, "тры": 3} + +# Звярніце ўвагу, што ключы ў слоўніках павінны быць нязменных тыпаў. Гэта для +# таго, каб пераканацца, што ключ заўсёды створыць аднолькавы хэш для пошуку. +# У нязменныя тыпы ўваходзяць цэлалікавыя значэнні, +# значэнні з плаваючай кропкай, радкі і картэжы. +invalid_dict = {[1,2,3]: "123"} # => Вікідвае TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Значэнні, аднак, могуць быць любых тыпаў. + +# Пошук значэнняў праз [] +filled_dict["адзін"] # => 1 + +# Атрымаць усе ключы ў якасці itterable-аб'екта праз "keys()". Нам трэба +# абгарнуць вызаў у list(), каб ператварыць вынік у спіс. Паразмаўляем аб +# гэтым пазней. Заўвага, для версій Python, ніжэйшых за 3.7, парадак ключоў +# слоўніка не гарантуецца, вашыя вынікі могуць не адпавядаць прыкладам ніжэй. +# Аднак, з версіі Python 3.7, элементы слоўніка захоўваюць парадак, у якім яны +# былі ўстаўлены. +list(filled_dict.keys()) # => ["тры", "два", "адзін"] для Python <3.7> +list(filled_dict.keys()) # => ["адзін", "два", "тры"] для Python 3.7+ + + +# Атрымаць усе значэнні ў якасці itterable-аб'екта праз "values()". Зноў жа, +# нам трэба абгарнуць вызаў у list(), каб атрымаць спіс. Тая ж заўвага пра +# парадак, што і вышэй. +list(filled_dict.values()) # => [3, 2, 1] для Python <3.7 +list(filled_dict.values()) # => [1, 2, 3] для Python 3.7+ + +# Праверка на наяўнасць ключа ў слоўніку праз "in" +"адзін" in filled_dict # => True +1 in filled_dict # => False + +# Пошук неіснуючага ключа выкідвае KeyError +filled_dict["чатыры"] # KeyError + +# Выкарыстоўвайце метад "get()", каб пазбегнуць KeyError +filled_dict.get("адзін") # => 1 +filled_dict.get("чатыры") # => None +# get() падтрымлівае прадвызначаны аргумент, калі значэнне адсутнічае ў слоўніку +filled_dict.get("адзін", 4) # => 1 +filled_dict.get("чатыры", 4) # => 4 + +# "setdefault()" устаўляе ў слоўнік толькі калі дадзенага ключа не існуе +filled_dict.setdefault("пяць", 5) # filled_dict["пяць"] цяпер 5 +filled_dict.setdefault("пяць", 6) # filled_dict["пяць"] усё яшчэ 5 + +# Дадаванне ў слоўнік +filled_dict.update({"чатыры":4}) +# => {"адзін": 1, "два": 2, "тры": 3, "чатыры": 4} +filled_dict["чатыры"] = 4 # іншы спосаб дадаць у слоўнік + +# Выдаленне ключоў са слоўніка праз del +del filled_dict["адзін"] # выдаляе ключ "адзін" з запоўненага слоўніка + +# З версіі Python 3.5 таксама існуюць дадатковыя спосабы распакоўкі +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + + +# Мноства змяшчаюць... Ну, мноства +empty_set = set() +# Ініцыялізваць мноства з кучы значэнняў +some_set = {1, 1, 2, 2, 3, 4} # some_set цяпер {1, 2, 3, 4} + +# Адпаведна ключам слоўніка, элементы мноства павінны быць нязменнымі +invalid_set = {[1], 1} # => Выкідвае TypeError: unhashable type: 'list' +valid_set = {(1,), 1} + +# Дадаць яшчэ адзін элемент у мноства +filled_set = some_set +filled_set.add(5) # filled_set цяпер {1, 2, 3, 4, 5} +# Мноства не змяшчаюць паўторных элементаў +filled_set.add(5) # застаецца ранейшым {1, 2, 3, 4, 5} + +# Перасячэнне мностваў праз & +other_set = {3, 4, 5, 6} +filled_set & other_set # => {3, 4, 5} + +# Аб'яднанне мностваў праз | +filled_set | other_set # => {1, 2, 3, 4, 5, 6} + +# Рознасць мностваў праз - +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Сіметрычная рознасць мностваў праз ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Праверыць, ці з'яўляецца мноства злева надмноствам мноства справа +{1, 2} >= {1, 2, 3} # => False + +# Праверыць, ці з'яўляецца мноства злева падмноствам мноства справа +{1, 2} <= {1, 2, 3} # => True + +# Праверка на наяўнасць у мностве праз in +2 in filled_set # => True +10 in filled_set # => False + +# Зрабіць копію глыбінёй у адзін слой +filled_set = some_set.copy() # filled_set цяпер {1, 2, 3, 4, 5} +filled_set is some_set # => False + + +#################################################### +## 3. Паток кіравання і ітэрабельныя аб'екты +#################################################### + +# Давайце зробім пераменную +some_var = 5 + +# Так выглядае інструкцыя if. Водступы маюць значэнне ў Python! +# Заведзена выкарыстоўваць чатыры прабелы, не табуляцыю. +# Гэта выводзіць "some_var меньшая за 10" +if some_var > 10: + print("some_var цалкам большая за 10.") +elif some_var < 10: # гэты elif неабавязковы. + print("some_var меньшая за 10.") +else: # гэта таксама неабавязкова. + print("some_var насамрэч 10.") + + +""" +Ітэраванне спісаў праз цыкл for +выводзіць: + сабакі — млекакормячыя + каты — млекакормячыя + мышы — млекакормячыя +""" +for animal in ["сабакі", "каты", "мышы"]: + # Вы можаце выкарыстоўваць format() для ўводу фарматаваных радкоў + print("{} — млекакормячыя".format(animal)) + +""" +"range(number)" вяртае ітэрабельны аб'ект з лічбаў +ад 0 да дадзенай лічбы (не ўключна) +выводзіць: + 0 + 1 + 2 + 3 +""" +for i in range(4): + print(i) + +""" +"range(lower, upper)" вяртае ітэрабельны аб'ект з лічбаў +ад ніжэйшай(lower) да вышэйшай(upper) лічбы +выводзіць: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + +""" +"range(lower, upper, step)" вяртае ітэрабельны аб'ект з лічбаў +ад ніжэйшай да вышэйшай лічбы з дадзеным крокам. Калі крок не +вызначаны, прадвызначаным значэннем з'яўляецца 1 +выводзіць: + 4 + 6 +""" +for i in range(4, 8, 2): + print(i) + +""" +Прайсці цыклам праз спіс, каб атрымаць індэкс і значэнне кожнага элемента: + 0 сабака + 1 кот + 2 мыш +""" +animals = ["сабака", "кот", "мыш"] +for i, value in enumerate(animals): + print(i, value) + +""" +Цыклы while працуюць пакуль умова не парушана +prints: + 0 + 1 + 2 + 3 +""" +x = 0 +while x < 4: + print(x) + x += 1 # Скарачэнне x = x + 1 + +# Апрацоўка выключэнняў праз блок try/except +try: + # Выкарыстоўвайце "raise" каб выкінуць памылку + raise IndexError("Гэта памылка індэкса") +except IndexError as e: + pass # Не рабіце так, забяспечце аднаўленне. +except (TypeError, NameError): + pass # Некалькі выключэнняў можна апрацоўваць сумесна. +else: # Неабавязковая частка блока try/except. Павінна быць + # пасля ўсіх блокаў except. + print("Усё добра!") # Выконваецца толькі калі код унутры try не выкідвае + # выключэнняў +finally: # Выконваецца пры ўсіх абставінах. + print("Тут можна пачысціць рэсурсы") + +# Замест try/finally для ачысткі рэсурсаў магчыма выкарыстоўваць with +with open("myfile.txt") as f: + for line in f: + print(line) + +# Запіс у файл +contents = {"aa": 12, "bb": 21} +with open("myfile1.txt", "w") as file: + file.write(str(contents)) # запісвае радок у файл + +import json +with open("myfile2.txt", "w") as file: + file.write(json.dumps(contents)) # запісвае аб'ект у файл + +# Reading from a file +with open('myfile1.txt', "r") as file: + contents = file.read() # чытае радок з файла +print(contents) +# выводзіць: {"aa": 12, "bb": 21} + +with open('myfile2.txt', "r") as file: + contents = json.load(file) # чытае json аб'ект з файла +print(contents) +# выводзіць: {"aa": 12, "bb": 21} + + +# Python прапануе фундаментальную абстракцыю +# пад назвай Iterable ("ітэрабельны аб'ект" далей). +# Ітэрабельны аб'ект — гэта аб'ект, які можна разглядаць як паслядоўнасць. +# Аб'ект, які вяртаецца функцыяй range, з'яўляецца ітэрабельным. + +filled_dict = {"адзін": 1, "два": 2, "тры": 3} +our_iterable = filled_dict.keys() +print(our_iterable) # => dict_keys(['адзін', 'два', 'тры']). Гэта аб'ект, + # які рэалізуе інтэрфейс Iterable. + +# Мы можам прайсці па яму цыклам +for i in our_iterable: + print(i) # Выводзіць адзін, два, тры + +# Аднак, да элементаў нельга звяртацца па індэксу +our_iterable[1] # Выкідвае TypeError + +# Ітэрабельны аб'ект ведае, як стварыць ітэратар +our_iterator = iter(our_iterable) + +# Наш ітэратар з'яўляецца аб'ектам, які можа запамінаць +# стан падчас нашага праходу праз яго. +# Мы можам атрымаць наступны аб'ект з дапамогаю "next()" +next(our_iterator) # => "адзін" + +# Ён утрымлівае стан, пакуль мы ітэруем +next(our_iterator) # => "два" +next(our_iterator) # => "тры" + +# Калі ітэратар вярнуў усе дадзеныя, ён выкідвае выключэнне StopIteration +next(our_iterator) # Выкідвае StopIteration + +# Мы таксама можам прайсці па яму цыклам, +# насамрэч, "for" ускосна гэта і робіць +our_iterator = iter(our_iterable) +for i in our_iterator: + print(i) # Выводзіць адзін, два, тры + +# Вы можаце захапіць усе элементы ітэрабельнага аб'екта або ітэратара +# праз вызаў list() +list(our_iterable) # => Вяртае ["адзін", "два", "тры"] +list(our_iterator) # => Вяртае [], бо стан захоўваецца + + +#################################################### +## 4. Функцыі +#################################################### + +# Выкарыстоўвайце "def" для стварэння новых функцый +def add(x, y): + print("x = {}, а y - {}".format(x, y)) + return x + y # Вяртайце значэнні праз return + +# Вызаў функцый з параметрамі +add(5, 6) # => выводзіць "x = 5, а y = 6" і вяртае 11 + +# Таксама магчыма вызываць функцыі з найменнымі аргументамі +add(y=6, x=5) # Найменныя аргументы можна выкарыстоўваць у любым парадку + +# Вы можаце вызначыць функцыю, якая прымае зменлівую колькасць +# пазіцыйных аргументаў +def varargs(*args): + return args + +varargs(1, 2, 3) # => (1, 2, 3) + +# Таксама, вы можаце вызначаць функцыі, якія прымаюць зменлівую колькасць +# найменных аргументаў +def keyword_args(**kwargs): + return kwargs + +# Давайце вызавем яе і паглядзім, што будзе +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} + + +# Вы можаце выкарыстоўваць два спосабы адначасова, калі хочаце +def all_the_args(*args, **kwargs): + print(args) + print(kwargs) +""" +all_the_args(1, 2, a=3, b=4) выводзіць: + (1, 2) + {"a": 3, "b": 4} +""" + +# Вызываючы функцыі, вы можаце зрабіць адваротнае args/kwargs! +# Выкарыстоўвайце * для разгортвання пазіцыйных аргументаў (картэжаў) +# і ** для разгортвання найменных аргументаў (слоўнікаў) +args = (1, 2, 3, 4) +kwargs = {"a": 3, "b": 4} +all_the_args(*args) # адпавядае: all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # адпавядае: all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # адпавядае: all_the_args(1, 2, 3, 4, a=3, b=4) + +# Вяртанне некалькіх значэнняў (з прызначэннем картэжаў) +def swap(x, y): + return y, x # Вяртае некалькі значэнняў у выглядзе картэжу без дужак. + # (Заўвага: дужкі апускаюцца, але могуць выкарыстоўвацца) + +x = 1 +y = 2 +x, y = swap(x, y) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Зноў жа, выкарыстоўваць дужкі неабавязкова + +# глабальная вобласць +x = 5 + +def set_x(num): + # лакальная вобласць пачынаецца тут + # лакальная пераменная x адрозніваецца ад глабальнай + x = num # => 43 + print(x) # => 43 + +def set_global_x(num): + # global пазначае, што пераменная знаходзіцца ў глабальнай вобласці + global x + print(x) # => 5 + x = num # глабальная пераменная x цяпер 6 + print(x) # => 6 + +set_x(43) +set_global_x(6) +""" +выводзіць: + 43 + 5 + 6 +""" + + +# Python падтрымлівае функцыі першага класа +def create_adder(x): + def adder(y): + return x + y + return adder + +add_10 = create_adder(10) +add_10(3) # => 13 + +# Замыканні ва ўкладзеных функцыях: +# Мы можам выкарыстоўваць ключавое слова nonlocal для працы з пераменнымі +# ўнутры ўкладзенай вобласці, якія не павінны быць аб'яўлены ва ўнутраных +# функцыях. +def create_avg(): + total = 0 + count = 0 + def avg(n): + nonlocal total, count + total += n + count += 1 + return total/count + return avg +avg = create_avg() +avg(3) # => 3.0 +avg(5) # (3+5)/2 => 4.0 +avg(7) # (8+7)/3 => 5.0 + +# Таксама існуюць ананімныя функцыі +(lambda x: x > 2)(3) # => True +(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 + +# Існуюць убудаваныя функцыі вышэйшага парадку +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] + +list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] + +# Для прыгажосці, замест map і filter мы можам выкарыстоўваць спісачныя выразы +# Спісачныя выразы захоўваюць вынік у выглядзе спіса (які сам па сабе можа +# быць укладзеным). +[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] +[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] + +# Таксама вы можаце стварыць адпаведныя выразы для мностваў і слоўнікаў +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + + +#################################################### +## 5. Модулі +#################################################### + +# Вы можаце імпартаваць модулі +import math +print(math.sqrt(16)) # => 4.0 + +# Вы можаце ўзяць дакладныя функцыі з модуля +from math import ceil, floor +print(ceil(3.7)) # => 4 +print(floor(3.7)) # => 3 + +# Вы можаце імпартаваць усе функцыі з модуля. +# Заўвага: не рэкамендуецца так рабіць. +from math import * + +# Вы можаце скарачаць імёны модуляў +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Модулі ў Python з'яўляюцца звычайнымі Python файламі. Вы можаце напісаць +# свае і імпартаваць іх. Імя модуля адпавядае імені файла. + +# Вы можаце даведацца, якія функцыі і атрыбуты вызначаны ў модулі +import math +dir(math) + +# Калі ў вас ёсць Python-скрыпт з назвай math.py у той жа папцы, +# што і бягучы скрыпт, файл math.py будзе загружаны замест убудаванага +# Python-модуля. Гэта адбываецца таму, што лакальная папка мае большы +# прыярытэт, чым убудаваныя Python-бібліятэкі. + + +#################################################### +## 6. Класы +#################################################### + +# Мы выкарыстоўваем інструкцыю "class" для стварэння класаў +class Human: + + # Атрыбут класа. Яго першапачатковае значэнне пашыраецца + # паміж усімі экзэмплярамі класа. + species = "H. sapiens" + + # Базавы канструктар, вызываецца пры стварэнні экзэмпляраў класа. + # Звярніце ўвагу, што двайное падкрэсліванне абазначае аб'екты або + # атрыбуты, якія выкарыстоўвае Python, але яны існуюць у прасторах назваў, + # якія кантралюе карыстальнік. Метады(або аб'екты ці атрыбуты), такія як + # __init__, __str__, __repr__ і г.д., называюцца спецыяльнымі метадамі, + # або магічнымі метадамі. Вам не варта ствараць такія імёны самастойна. + def __init__(self, name): + # Прызначэнне аргумента атрыбуту name экзэмпляра класа + self.name = name + + # Ініцыялізацыя ўласцівасці + self._age = 0 # папярэдняе падкрэсліванне абазначае, што ўласцівасць + # "age" створана для ўнутранага выкарыстання, + # але гэта ніяк не кантралюецца, а з'яўляецца + # звычайнай падказкай для іншых распрацоўшчыкаў. + + # Метад экзэмпляра. Усе метады прымаюць "self" у якасці першага аргумента. + def say(self, msg): + print("{name}: {message}".format(name=self.name, message=msg)) + + # Іншы метад экзэмпляра + def sing(self): + return 'ёў... ёў... праверка мікрафона... раз два... раз два...' + + # Метад класа пашыраецца паміж усімі экзэмплярамі. + # Яны вызываюцца з указаннем вызываючага класа ў якасці першага аргумента. + @classmethod + def get_species(cls): + return cls.species + + # Статычны метад вызываецца без спасылкі на клас або экзэмпляр + @staticmethod + def grunt(): + return "*рохкае*" + + # property зусім як гетэр + # гэты дэкаратар ператварае метад age() у аднайменны атрыбут, + # даступны толькі для чытання. + # У Python не трэба пісаць трывіяльныя гетэры і сэтэры, дарэчы. + @property + def age(self): + return self._age + + # Гэта дазваляе ўстанавіць уласцівасць + @age.setter + def age(self, age): + self._age = age + + # Гэта дазваляе выдаліць уласцівасць + @age.deleter + def age(self): + del self._age + + +# Калі інтэрпрэтатар Python чытае зыходны файл, ён выконвае ўвесь код. +# З дапамогай гэтай праверкі, блок кода выконваецца толькі калі модуль +# з'яўляецца асноўнай праграмай. +if __name__ == '__main__': + # Стварэнне экзэмпляра класа + i = Human(name="Ігар") + i.say("вітан") # "Ігар: вітан" + j = Human("Янка") + j.say("вітаю") # "Янка: вітаю" + # i з j з'яўляюцца экзэмплярамі тыпу Human, г.з., яны аб'екты Human + + # Вызаў метаду класа + i.say(i.get_species()) # "Ігар: H. sapiens" + # Змена агульнага атрыбута + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ігар: H. neanderthalensis" + j.say(j.get_species()) # => "Янка: H. neanderthalensis" + + # Вызаў статычнага метаду + print(Human.grunt()) # => "*рохкае*" + + # Статычны метад магчыма вызваць таксама з экзэмпляра + print(i.grunt()) # => "*рохкае*" + + # Абнавіць уласцівасць для гэтага экзэмпляра + i.age = 42 + # Атрымаць уласцівасць + i.say(i.age) # => "Ігар: 42" + j.say(j.age) # => "Янка: 0" + # Выдаліць уласцівасць + del i.age + # i.age # => гэта выкіне AttributeError + + +#################################################### +## 6.1 Наследаванне +#################################################### + +# Наследаванне дазваляе вызначаць новыя вытворныя класы, якія наследуюць +# метады і пераменныя сваіх базавых класаў. + +# Выкарыстоўваючы клас Human, вызначаны раней, у якасці базавага або +# класа-папярэдніка, мы можам вызначыць вытворны клас Superhero, які наследуе +# пераменныя класа(species, name, age) і метады(sing, grunt) з класа Human, +# але таксама мае свае ўнікальныя ўласцівасці. + +# Каб выкарыстаць перавагі файлавай модульнасці, вы можаце змясціць класы +# ў асобныя файлы, напрыклад, human.py + +# Каб імпартаваць функцыі з іншых файлаў, выкарыстоўвайце наступны фармат +# from "імя-файла-без-пашырэння" import "функцыя-або-клас" + +from human import Human + + +# Пазначце клас-папярэднік ў якасці параметра ў вызначэнні вытворнага класа +class Superhero(Human): + + # Калі вытворнаму класу трэба толькі ўнаследаваць усе вызначэнні + # класа-папярэдніка без мадыфікацый, вы можаце выкарыстаць ключавое + # слова "pass" (і нічога больш), але ў гэтым выпадку яно закаментавана, + # каб мець магчымасць стварыць унікальны клас + # pass + + # Вытворныя класы могуць перавызначыць атрыбуты папярэднікаў + species = 'Суперчалавек' + + # Вытворныя класы аўтаматычна наследуюць канструктары папярэднікаў разам + # з аргументамі, але таксама могуць вызначаць дадатковыя аргументы або + # вызначэнні, і перавызначаць метады, такія як канструктар класа. + # Гэты канструктар наследуе аргумент name з Human + # і дадае superpowers і movie: + def __init__(self, name, movie=False, + superpowers=["суперсіла", "куленепрабівальнасць"]): + + # дадаць дадатковыя атрыбуты класа: + self.fictional = True + self.movie = movie + # сцеражыцеся прадвызначаных значэнняў зменных тыпаў, + # паколькі яны абагульняюцца + self.superpowers = superpowers + + # Функцыя "super" дазваляе атрымаць доступ да метадаў папярэдніка, + # якія былі перавызначаны ў вытворным класе, у гэтым выпадку + # да метаду __init__. + # Вызаў канструктара класа-папярэдніка: + super().__init__(name) + + # перавызначыць метад sing + def sing(self): + return 'Шчучыншчына!' + + # дадаць дадатковы метад экзэмпляра + def boast(self): + for power in self.superpowers: + print("Я маю такую моц, як {pow}!".format(pow=power)) + + +if __name__ == '__main__': + sup = Superhero(name="Клешч") + + # Праверка тыпу экзэмпляра + if isinstance(sup, Human): + print('Я — чалавек') + if type(sup) is Superhero: + print('Я — супергерой') + + # Атрымаць "Парадак Вырашэння Метаду"(Method Resolution Order), які + # выкарыстоўваюць getattr() і super() + # (парадак, у якім адбываецца пошук атрыбутаў або метадаў у класе). + # Гэты атрыбут дынамічны і можа абнаўляцца. + print(Superhero.__mro__) # => (, + # => , ) + + # Вызывае метад папярэдніка, але выкарыстоўвае ўласны атрыбут класа + print(sup.get_species()) # => Суперчалавек + + # Вызывае перавызначаны метад + print(sup.sing()) # => Шчучыншчына! + + # Вызывае метад з Human + sup.say('Лыжка') # => Клешч: Лыжка + + # Вызывае метад, які існуе толькі ўнутры Superhero + sup.boast() # => Я маю такую моц, як суперсіла! + # => Я маю такую моц, як куленепрабівальнасць! + + # Унаследаваны атрыбут класа + sup.age = 31 + print(sup.age) # => 31 + + # Атрыбут, які існуе толькі ўнутры Superhero + print('Я магу атрымаць Оскар? ' + str(sup.movie)) + +#################################################### +## 6.2 Множнае наследаванне +#################################################### + +# Вызначэнне іншага класа +# bat.py +class Bat: + + species = 'рукакрылачка' + + def __init__(self, can_fly=True): + self.fly = can_fly + + # У гэтым класе таксама ёсць метад say + def say(self, msg): + msg = '... ... ...' + return msg + + # І свой уласны метад таксама + def sonar(self): + return '))) ... (((' + +if __name__ == '__main__': + b = Bat() + print(b.say('вітаю')) + print(b.fly) + + +# І вызначэнне яшчэ аднаго класа, які наследуецца ад Superhero і Bat +# superhero.py +from superhero import Superhero +from bat import Bat + +# Вызначыць Batman у якасці вытворнага класа, +# які наследуецца ад Superhero і Bat. +class Batman(Superhero, Bat): + + def __init__(self, *args, **kwargs): + # Звычайна, каб унаследаваць атрыбуты, вам трэба вызваць super: + # super(Batman, self).__init__(*args, **kwargs) + # Аднак, мы маем справу з множным наследаваннем, а super() працуе + # толькі з наступным базавым класам у спісе MRO. + # Таму, замест гэтага мы напрамую вызываем __init__ + # для кожнага з папярэднікаў. + # Выкарыстанне *args і **kwargs дазваляе ахайна перадаць аргументы, + # якія папярэднікі будуць разбіраць слой за слоем. + Superhero.__init__(self, 'ананім', movie=True, + superpowers=['Багаты'], *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # перавызначэнне значэння атрыбута name + self.name = 'Сум Афлек' + + def sing(self): + return 'шчу шчу шчу шчу Шчучыншчына!' + + +if __name__ == '__main__': + sup = Batman() + + # Парадак Вырашэння Метаду(MRO) + print(Batman.__mro__) # => (, + # => , + # => , + # => , ) + + # Вызывае метад папярэдніка, але выкарыстоўвае ўласныя атрыбуты + print(sup.get_species()) # => Суперчалавек + + # Вызывае перавызначаны метад + print(sup.sing()) # => шчу шчу шчу шчу Шчучыншчына! + + # Вызывае метад з Human, бо парадак наследавання мае значэнне + sup.say('згодны') # => Сум Афлек: згодны + + # Вызывае метад, які існуе толькі ў другім папярэдніку + print(sup.sonar()) # => ))) ... ((( + + # Унаследаваны атрыбут класа + sup.age = 100 + print(sup.age) # => 100 + + # Унаследаваны атрыбут другога папярэдніка, прадвызначаныя значэнні + # якога былі пераназначаны + print('Я ўмею лятаць? ' + str(sup.fly)) # => Я ўмею лятаць? False + + + +#################################################### +## 7. Дадаткова +#################################################### + +# Генератары дапамагаюць пісаць лянівы код +def double_numbers(iterable): + for i in iterable: + yield i + i + +# Генератары эфектыўна выкарыстоўваюць памяць, таму што загружаюць толькі +# даныя, патрэбныя для апрацоўкі наступнага кроку ітэрацыі. Гэта дазваляе +# ім выконваць аперацыі з вялікімі дыяпазонамі даных, якія ў іншых выпадках +# былі б недапушчальнымі. +# Заўвага: `range` замяняе `xrange` у Python 3. +for i in double_numbers(range(1, 900000000)): # `range` гэта генератар. + print(i) + if i >= 30: + break + +# Адпаведна спісачным выразам, магчыма таксама ствараць генератарныя выразы. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # выводзіць -1 -2 -3 -4 -5 у кансоль/тэрмінал + +# Таксама вы можаце ператварыць генератарны выраз прама ў спісак. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + + +# Дэкаратары з'яўляюцца формай сінтаксічнага цукру. +# Нягледзячы на дзіўны сінтаксіс, яны робяць код лягчэйшым для прачытання. + +# Абгорткі — адзін з відаў дэкаратараў. +# З іх дапамогай вельмі зручна дадаваць лагіраванне ў існуючыя функцыі без +# неабходнасці іх мадыфікаваць. + +def log_function(func): + def wrapper(*args, **kwargs): + print("Уваход у функцыю", func.__name__) + result = func(*args, **kwargs) + print("Выхад з функцыі", func.__name__) + return result + return wrapper + +@log_function # адпаведнік: +def my_function(x,y): # def my_function(x,y): + return x+y # return x+y + # my_function = log_function(my_function) +# Дэкаратар @log_function кажа, што падчас прачытання вызначэння функцыі +# my_function, яна будзе абгорнута ў log_function. +# Калі вызначэнні функцый доўгія, можа быць цяжка апрацаваць неабгорнутыя +# прызначэнні ў канцы вызначэнняў. + +my_function(1,2) # => "Уваход у функцыю my_function" + # => "3" + # => "Выхад з функцыі my_function" + +# Але ёсць праблема. +# Што калі мы паспрабуем атрымаць якую-небудзь інфармацыю пра my_function? + +print(my_function.__name__) # => 'wrapper' +print(my_function.__code__.co_argcount) # => 0. argcount у выніку 0 таму, што абодва аргументы ў сігнатуры wrapper() з'яўляюцца апцыянальнымі. + +# Таму, што наш дэкаратар адпавядае my_function = log_function(my_function), +# мы замянілі інфармацыю аб my_function інфармацыяй з абгорткі. + +# Выправіць гэта праз functools + +from functools import wraps + +def log_function(func): + @wraps(func) # Гэта гарантуе, што дакументацыйны радок (docstring), імя + # функцыі, спіс аргументаў і інш., капіруюцца ў выніковую + # функцыю замест іх замены інфармацыяй з абгорткі. + def wrapper(*args, **kwargs): + print("Уваход у функцыю ", func.__name__) + result = func(*args, **kwargs) + print("Выхад з функцыі ", func.__name__) + return result + return wrapper + +@log_function +def my_function(x,y): + return x+y + +my_function(1,2) # => "Уваход у функцыю my_function" + # => "3" + # => "Выхад з функцыі my_function" + +print(my_function.__name__) # => 'my_function' +print(my_function.__code__.co_argcount) # => 2 +``` + +### Бясплатныя анлайн-рэсурсы + +* [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) +* [The Official Docs](https://docs.python.org/3/) +* [Hitchhiker's Guide to Python](https://docs.python-guide.org/en/latest/) +* [Python Course](https://www.python-course.eu) +* [Free Interactive Python Course](http://www.Kikodo.io) +* [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) +* [30 Python Language Features and Tricks You May Not Know About](https://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) +* [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) +* [Python 3 Computer Science Circles](https://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](https://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](https://nbviewer.jupyter.org/gist/anonymous/5924718) +* [Python Tutorial for Intermediates](https://pythonbasics.org/) +* [Build a Desktop App with Python](https://pythonpyqt.com/) From ae280b79ec741b0244c593b1b6fb04ee00b50797 Mon Sep 17 00:00:00 2001 From: lucii7vel <33035261+lucii7vel@users.noreply.github.com> Date: Fri, 31 May 2024 04:43:17 -0700 Subject: [PATCH 267/392] [python/be] fix translator link (#4965) --- be-by/python-by.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/be-by/python-by.html.markdown b/be-by/python-by.html.markdown index f16443b6..c5476a08 100644 --- a/be-by/python-by.html.markdown +++ b/be-by/python-by.html.markdown @@ -12,7 +12,7 @@ contributors: - ["Stanislav Modrak", "https://stanislav.gq"] - ["John Paul Wohlscheid", "https://gitpi.us"] translators: - - ["lucii7vel", "https://https://github.com/lucii7vel"] + - ["lucii7vel", "https://github.com/lucii7vel"] filename: learnpython-by.py lang: be-by --- From 842937f79fa3b269dec65e286d6189e21d20b12b Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 31 May 2024 08:55:46 -0600 Subject: [PATCH 268/392] [lfe/en] proofread --- lfe.html.markdown | 107 ++++++++++++++++++++-------------------------- 1 file changed, 47 insertions(+), 60 deletions(-) diff --git a/lfe.html.markdown b/lfe.html.markdown index 4baa5b2b..07118182 100644 --- a/lfe.html.markdown +++ b/lfe.html.markdown @@ -1,21 +1,15 @@ --- - -language: "Lisp Flavoured Erlang(LFE)" +language: "Lisp Flavoured Erlang (LFE)" filename: lispflavourederlang.lfe contributors: - ["Pratik Karki", "https://github.com/prertik"] --- -Lisp Flavoured Erlang(LFE) is a functional, concurrent, general-purpose programming -language and Lisp dialect(Lisp-2) built on top of Core Erlang and the Erlang Virtual Machine(BEAM). - -LFE can be obtained from [LFE](https://github.com/rvirding/lfe) - -The classic starting point is [LFE DOCS.](http://docs.lfe.io) - -Another new site is being built to replace it.[LFE DEV.](http://docs.lfe.io/dev) - +Lisp Flavoured Erlang (LFE) is a functional, concurrent, general-purpose programming +language and Lisp dialect (Lisp-2) built on top of Core Erlang and the Erlang Virtual Machine (BEAM). +LFE can be obtained from [LFE](https://github.com/rvirding/lfe). +The classic starting point is the [LFE docs](http://docs.lfe.io). ```lisp ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -24,7 +18,7 @@ Another new site is being built to replace it.[LFE DEV.](http://docs.lfe.io/dev) ;;; General form. -;; Lisp comprises of two syntax called: the ATOM and the S-expression. +;; Lisp is comprised of two syntaxes, the ATOM and the S-expression. ;; `forms` are known as grouped S-expressions. 8 ; an atom; it evaluates to itself @@ -55,7 +49,7 @@ t ; another atom which denotes true. ;; Libraries can be used directly from the Erlang ecosystem. Rebar3 is the build tool. ;; LFE is usually developed with a text editor(preferably Emacs) and a REPL -;; (Read Evaluate Print Loop) running at the same time. The REPL +;; (Read Evaluate Print Loop) running at the same time. The REPL ;; allows for interactive exploration of the program as it is "live" ;; in the system. @@ -65,18 +59,18 @@ t ; another atom which denotes true. ;;; Integers -1234 -123 ; Regular decimal notation -#b0 #b10101 ; Binary notation -#0 #10101 ; Binary notation (alternative form) -#o377 #o-111 ; Octal notation -#d123456789 #d+123 ; Explicitly decimal notation -#xc0ffe 0x-01 ; Hexadecimal notation -#2r1010 #8r377 ;Notation with explicit base (up to 36) +1234 -123 ; Regular decimal notation +#b0 #b10101 ; Binary notation +#0 #10101 ; Binary notation (alternative form) +#o377 #o-111 ; Octal notation +#d123456789 #d+123 ; Explicitly decimal notation +#xc0ffe 0x-01 ; Hexadecimal notation +#2r1010 #8r377 ;Notation with explicit base (up to 36) #\a #$ #\ä #\🐭 ;Character notation (the value is the Unicode code point of the character) -#\x1f42d; ;Character notation with the value in hexadecimal +#\x1f42d; ;Character notation with the value in hexadecimal ;;; Floating point numbers -1.0 +2.0 -1.5 1.0e10 1.111e-10 +1.0 +2.0 -1.5 1.0e10 1.111e-10 ;;; Strings @@ -85,25 +79,25 @@ t ; another atom which denotes true. "Cat: \x1f639;" ; writing unicode in string for regular font ending with semicolon. #"This is a binary string \n with some \"escaped\" and quoted (\x1f639;) characters" -; Binary strings are just strings but function different in the VM. +; Binary strings are just strings but function different in the VM. ; Other ways of writing it are: #B("a"), #"a", and #B(97). ;;; Character escaping -\b ; => Backspace -\t ; => Tab -\n ; => Newline -\v ; => Vertical tab -\f ; => Form Feed -\r ; => Carriage Return -\e ; => Escape -\s ; => Space -\d ; => Delete +\b ; => Backspace +\t ; => Tab +\n ; => Newline +\v ; => Vertical tab +\f ; => Form Feed +\r ; => Carriage Return +\e ; => Escape +\s ; => Space +\d ; => Delete ;;; Binaries ;; It is used to create binaries with any contents. -#B((#"a" binary) (#"b" binary)) ; #"ab" (Evaluated form) +#B((#"a" binary) (#"b" binary)) ; #"ab" (Evaluated form) ;;; Lists are: () or (foo bar baz) @@ -114,7 +108,7 @@ t ; another atom which denotes true. ;;; Symbols: Things that cannot be parsed. Eg: foo, Foo, foo-bar, :foo | foo | ; explicit construction of symbol by wrapping vertical bars. -;;; Evaluation +;;; Evaluation ;; #.(... some expression ...). E.g. '#.(+ 1 1) will evaluate the (+ 1 1) while it ;; reads the expression and then be effectively '2. @@ -130,7 +124,7 @@ lfe> (list-comp ;; 2. Core forms ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; These forms are same as those found at Common Lisp and Scheme. +;; These forms are the same as those found in Common Lisp and Scheme. (quote e) (cons head tail) @@ -189,8 +183,8 @@ lfe> (list-comp ;; 3. Macros ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Macros are part of the language to allow you to create abstractions -;; on top of the core language and standard library that move you closer +;; Macros are part of the language and allow you to create abstractions +;; on top of the core language and standard library that move you closer ;; toward being able to directly express the things you want to express. ;; Top-level function @@ -215,7 +209,7 @@ lfe> (list-comp ((argpat ...) ...) ...) -;; Top-level macro using Scheme inspired syntax-rules format +;; Top-level macro using Scheme inspired syntax-rules format (defsyntax name (pat exp) @@ -226,7 +220,7 @@ lfe> (list-comp (macrolet ((name (arg ... ) ... ) ... ) ... ) - + (syntaxlet ((name (pat exp) ...) ...) ...) @@ -258,12 +252,12 @@ lfe> (list-comp ;; [P|Ps]=All (= (cons p ps) all) _ ; => is don't care while pattern matching - + (= pattern1 pattern2) ; => easier, better version of pattern matching - + ;; Guards -;; Whenever pattern occurs(let, case, receive, lc, etc) it can be followed by an optional +;; Whenever pattern occurs (let, case, receive, lc, etc) it can be followed by an optional ;; guard which has the form (when test ...). (progn gtest ...) ;; => Sequence of guard tests @@ -316,19 +310,19 @@ lfe>msg ;; Functions are bound by top-level defun, flet and fletrec. ;; Macros are bound by top-level defmacro/defsyntax and by macrolet/syntaxlet. -;; (funcall func arg ...) like CL to call lambdas/match-lambdas +;; (funcall func arg ...) like CL to call lambdas/match-lambdas ;; (funs) bound to variables are used. ;; separate bindings and special for apply. -apply _F (...), +apply _F (...), apply _F/3 ( a1, a2, a3 ) - + ;; Cons'ing in function heads (defun sum (l) (sum l 0)) (defun sum (('() total) total) (((cons h t) total) (sum t (+ h total)))) - + ;; ``cons`` literal instead of constructor form (defun sum (l) (sum l 0)) (defun sum @@ -349,7 +343,7 @@ apply _F/3 ( a1, a2, a3 ) (receive ((tuple 'become func) (funcall func)))) - + ;; another way for receiving messages (defun universal-server () @@ -392,7 +386,7 @@ apply _F/3 ( a1, a2, a3 ) (defun send-message (calling-pid msg) (let ((spawned-pid (spawn 'messenger-back 'print-result ()))) (! spawned-pid (tuple calling-pid msg)))) - + ;; Multiple simultaneous HTTP Requests: (defun parse-args (flag) @@ -437,22 +431,15 @@ apply _F/3 ( a1, a2, a3 ) (io:format "Error: ~p~n" `(,reason))) (`#(http #(,request-id ,result)) (io:format "Result: ~p~n" `(,result)))))) - - -;; Check out Erlang's documentation for more concurrency and OTP docs. ``` ## Further Reading -* [LFE DOCS](http://docs.lfe.io) -* [LFE GitBook](https://lfe.gitbooks.io/reference-guide/index.html) -* [LFE Wiki](https://en.wikipedia.org/wiki/LFE_(programming_language)) +* [LFE DOCS](http://docs.lfe.io) +* [LFE GitBook](https://lfe.gitbooks.io/reference-guide/index.html) +* [LFE Wiki](https://en.wikipedia.org/wiki/LFE_(programming_language)) ## Extra Info -* [LFE PDF](http://www.erlang-factory.com/upload/presentations/61/Robertvirding-LispFlavouredErlang.pdf) -* [LFE mail](https://groups.google.com/d/msg/lisp-flavoured-erlang/XA5HeLbQQDk/TUHabZCHXB0J) - -## Credits - -Lots of thanks to Robert Virding for creating LFE, Duncan McGreggor for documenting it and other LFE contributors who made LFE awesome. +* [LFE PDF](http://www.erlang-factory.com/upload/presentations/61/Robertvirding-LispFlavouredErlang.pdf) +* [LFE mail](https://groups.google.com/d/msg/lisp-flavoured-erlang/XA5HeLbQQDk/TUHabZCHXB0J) From 37f0b264505813fe6de08b74584f74e81c9b3665 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 31 May 2024 08:57:42 -0600 Subject: [PATCH 269/392] Remove readme badge --- README.markdown | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.markdown b/README.markdown index 9a8a3752..a71e85bd 100644 --- a/README.markdown +++ b/README.markdown @@ -1,7 +1,5 @@ # [Learn X in Y minutes][1] -[![Build Status](https://travis-ci.org/adambard/learnxinyminutes-docs.svg?branch=master)](https://travis-ci.org/adambard/learnxinyminutes-docs) - Whirlwind tours of (several, hopefully many someday) popular and ought-to-be-more-popular programming languages, presented as valid, commented code and explained as they go. From 3ea2b0b29ff004bfd4151dede0c1b55e52ea922d Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 31 May 2024 12:18:45 -0600 Subject: [PATCH 270/392] Remove email addresses --- de-de/javascript-de.html.markdown | 133 ++++++++--------- es-es/javascript-es.html.markdown | 57 ++++---- es-es/matlab-es.html.markdown | 23 ++- fa-ir/javascript-fa.html.markdown | 7 - ko-kr/javascript-kr.html.markdown | 69 +++++---- matlab.html.markdown | 85 +++++------ pt-br/javascript-pt.html.markdown | 65 ++++---- pt-br/matlab-pt.html.markdown | 12 +- ta-in/javascript-ta.html.markdown | 236 +++++++++++++++--------------- tr-tr/csharp-tr.html.markdown | 54 +++---- zh-cn/javascript-cn.html.markdown | 20 +-- zh-cn/matlab-cn.html.markdown | 55 ++++--- zh-cn/red-cn.html.markdown | 2 +- 13 files changed, 381 insertions(+), 437 deletions(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index a71d4316..3dc5b532 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -8,27 +8,24 @@ filename: learnjavascript-de.js lang: de-de --- -(Anmerkungen des Original-Autors:) JavaScript wurde im Jahr 1995 von Brendan Eich bei Netscape entwickelt. Ursprünglich war es als einfachere Skriptsprache für Websites gedacht, ergänzend zu Java, das für komplexere Webanwendungen verwendet wird. Die enge Integration in Websites und der in Browser eingebaute Support der Sprache haben dafür gesorgt, dass JavaScript weit häufiger für Web-Frontends verwendet wird als Java. Dabei ist JavaScript inzwischen nicht mehr auf Browser beschränkt: Node.js, ein Projekt, das eine eigene Laufzeitumgebung auf Grundlage von Google Chromes V8 mitbringt, wird derzeit immer populärer. -Feedback ist herzlich Willkommen! Der ursprüngliche Autor ist unter [@excitedleigh](https://twitter.com/excitedleigh) oder [l@leigh.net.au](mailto:l@leigh.net.au) zu erreichen. Der Übersetzer unter [gregorbg@web.de](mailto:gregorbg@web.de). - ```js -// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei +// Kommentare werden wie in C gesetzt: Einzeilige Kommentare starten mit zwei // Slashes -/* während mehrzeilige Kommentare mit einem +/* während mehrzeilige Kommentare mit einem Slash und einem Stern anfangen und enden */ // Statements können mit einem Semikolon beendet werden machWas(); -// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn +// ...müssen sie aber nicht, weil Semikola automatisch eingefügt werden, wenn // eine neue Zeile beginnt, abgesehen von einigen Ausnahmen. machWas() -// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist +// Obwohl wir uns für den Anfang nicht um diese Ausnahmen kümmern müssen ist // es besser die Semikola immer zu setzen. /////////////////////////////////// @@ -47,8 +44,8 @@ machWas() // Division funktioniert auch mit einem Ergebnis nach dem Komma. 5 / 2; // = 2.5 -// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation -// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit +// Bit-weise Operationen sind auch möglich; wenn eine Bit-weise Operation +// ausgeführt wird, wird die Fließkomma-Zahl in einen 32-bit Integer (mit // Vorzeichen) umgewandelt. 1 << 2; // = 4 @@ -86,7 +83,7 @@ false; 2 <= 2; // = true 2 >= 2; // = true -// Strings können mit + verbunden +// Strings können mit + verbunden "Hello " + "world!"; // = "Hello world!" // und mit < und > verglichen werden. @@ -98,7 +95,7 @@ false; // ...solange man nicht === verwendet. "5" === 5; // = false -// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode +// Auf einzelne Buchstaben innerhalb eines Strings kann mit der Methode // 'charAt' zugegriffen werden "This is a string".charAt(0); // = "T" @@ -110,17 +107,17 @@ false; // Es gibt außerdem die Werte 'null' und 'undefined' null; // wird verwendet um einen vorsätzlich gewählten 'Nicht'-Wert anzuzeigen -undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht - // verfügbar ist (obwohl genau genommen undefined selbst einen Wert +undefined; // wird verwendet um anzuzeigen, dass der Wert (aktuell) nicht + // verfügbar ist (obwohl genau genommen undefined selbst einen Wert // darstellt) -// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist +// false, null, undefined, NaN, 0 und "" sind 'falsy', d. h. alles andere ist // wahr. Man beachte, dass 0 falsch und "0" wahr ist, obwohl 0 == "0". /////////////////////////////////// // 2. Variablen, Arrays und Objekte -// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren +// Variablen werden mit dem Schlüsselwort 'var' und einem frei wählbaren // Bezeichner deklariert. JavaScript ist dynamisch typisiert, so dass man einer // Variable keinen Typ zuweisen muss. Die Zuweisung verwendet ein einfaches =. var einWert = 5; @@ -135,12 +132,12 @@ einAndererWert = 10; // Wert 'undefined'. var einDritterWert; // = undefined -// Es existiert eine Kurzform, um mathematische Operationen mit Variablen +// Es existiert eine Kurzform, um mathematische Operationen mit Variablen // auszuführen: einWert += 5; // äquivalent zu einWert = einWert + 5; einWert ist nun also 10 einWert *= 10; // einWert ist nach dieser Operation 100 -// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren +// Und es existiert eine weitere, sogar noch kürzere Form, um 1 zu addieren // oder zu subtrahieren einWert++; // nun ist einWert 101 einWert--; // wieder 100 @@ -149,7 +146,7 @@ einWert--; // wieder 100 var myArray = ["Hello", 45, true]; // Auf einzelne Elemente eines Arrays kann zugegriffen werden, in dem der Index -// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung +// in eckigen Klammern hinter das Array geschrieben werden. Die Indexierung // beginnt bei 0. myArray[1]; // = 45 @@ -160,11 +157,11 @@ myArray.length; // = 4 // und sind veränderlich myArray[3] = "Hello"; -// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen +// Die Objekte in JavaScript entsprechen 'dictionaries' oder 'maps' in anderen // Sprachen: es handelt sich um ungeordnete Schlüssel-Wert-Paare. var myObj = { key1: "Hello", key2: "World" }; -// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt, +// Schlüssel sind Strings, aber es werden keine Anführungszeichen benötigt, // sofern es sich um reguläre JavaScript-Bezeichner handelt. Werte können von // jedem Typ sein. var myObj = { myKey: "myValue", "my other key": 4 }; @@ -173,15 +170,15 @@ var myObj = { myKey: "myValue", "my other key": 4 }; // werden, myObj["my other key"]; // = 4 -// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt +// ... oder in dem man die Punkt-Notation verwendet, vorausgesetzt es handelt // sich bei dem Schlüssel um einen validen Bezeichner. myObj.myKey; // = "myValue" -// Objekte sind veränderlich, Werte können verändert und neue Schlüssel +// Objekte sind veränderlich, Werte können verändert und neue Schlüssel // hinzugefügt werden. myObj.myThirdKey = true; -// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein +// Der Zugriff auf einen noch nicht definierten Schlüssel, liefert ein // undefined. myObj.myFourthKey; // = undefined @@ -203,7 +200,7 @@ while (true) { // Eine unendliche Schleife! } -// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie +// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie // immer mindestens einmal ausgeführt werden. var input; do { @@ -211,7 +208,7 @@ do { } while ( !isValid( input ) ) // Die for-Schleife arbeitet genau wie in C und Java: -// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird; +// Initialisierung; Bedingung, unter der die Ausführung fortgesetzt wird; // Iteration. for ( var i = 0; i < 5; i++ ) { // wird 5-mal ausgeführt @@ -227,7 +224,7 @@ if (colour == "red" || colour == "blue"){ } // Die Auswertung von '&&' und '||' erfolgt so, dass abgebrochen wird, wenn die -// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist +// Bedingung erfüllt ist (bei oder) oder nicht-erfüllt ist (bei und). Das ist // nützlich, um einen Default-Wert zu setzen. var name = otherName || "default"; @@ -272,8 +269,8 @@ function myFunction() } myFunction(); // = undefined -// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie -// Variablen verwendet und als Parameter anderen Funktionen übergeben werden +// In JavaScript sind Funktionen 'Bürger erster Klasse', also können sie wie +// Variablen verwendet und als Parameter anderen Funktionen übergeben werden // - zum Beispiel, um einen 'event handler' zu 'beliefern'. function myFunction() { // wird ausgeführt, nachdem 5 Sekunden vergangen sind @@ -281,36 +278,36 @@ function myFunction() { setTimeout(myFunction, 5000); // Funktionen können auch deklariert werden, ohne ihnen einen Namen zuzuweisen. -// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument +// Es ist möglich diese anonymen Funktionen direkt als (oder im) Argument // einer anderen Funktion zu definieren. setTimeout(function(){ // wird ausgeführt, nachdem 5 Sekunden vergangen sind }, 5000); -// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt: +// JavaScript hat einen Geltungsbereich, der sich auf Funktionen erstreckt: // Funktionen haben ihren eigenen Geltungsbereich, andere Blöcke nicht. if(true) { var i = 5; } -i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die +i; // = 5 - nicht undefined, wie man es von einer Sprache erwarten würde, die // ihren Geltungsbereich nach Blöcken richtet -// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme +// Daraus ergibt sich ein bestimmtes Muster für sofort-ausführbare, anonyme // Funktionen, die es vermeiden, dass der globale Geltungsbereich von Variablen // 'verschmutzt' wird. (function(){ var temporary = 5; - // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden, - // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist - // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js, - // kann das anders aussehen). + // Auf eine Variable im globalen Geltungsbereich kann zugegriffen werden, + // sofern sie im globalen Objekt definiert ist (in einem Webbrowser ist + // dies immer das 'window'-Objekt, in anderen Umgebungen, bspw. Node.js, + // kann das anders aussehen). window.permanent = 10; })(); temporary; // wirft einen ReferenceError permanent; // = 10 -// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird -// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die +// Eines der mächtigsten Charakteristika von JavaScript sind Closures. Wird +// eine Funktion innerhalb einer anderen Funktion definiert, dann hat die // innere Funktion Zugriff auf alle Variablen der äußeren Funktion, sogar dann, // wenn die äußere Funktion beendet wurde. function sayHelloInFiveSeconds(name){ @@ -319,13 +316,13 @@ function sayHelloInFiveSeconds(name){ alert(prompt); } setTimeout(inner, 5000); - // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds - // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' - // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere - // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die + // setTimeout wird asynchron ausgeführt. Also wird sayHelloInFiveSeconds + // sofort verlassen und setTimeout wird die innere Funktion 'im nachhinein' + // aufrufen. Dennoch: Weil sayHelloInFiveSeconds eine Hülle um die innere + // Funktion bildet, hat die innere Funktion immer noch Zugriff auf die // Variable prompt. } -sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der +sayHelloInFiveSeconds("Adam"); // wird nach 5 Sekunden ein Popup mit der // Nachricht "Hello, Adam!" öffnen. /////////////////////////////////// @@ -339,7 +336,7 @@ var myObj = { }; myObj.myFunc(); // = "Hello world!" -// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie +// Wenn Funktionen aufgerufen werden, die zu einem Objekt gehören, können sie // auf das eigene Objekt mit dem Schlüsselwort 'this' zugreifen. myObj = { myString: "Hello world!", @@ -349,14 +346,14 @@ myObj = { }; myObj.myFunc(); // = "Hello world!" -// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen -// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht -// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen +// Worauf 'this' gesetzt wird, ist davon abhängig, wie die Funktion aufgerufen +// wird, nicht wo sie definiert wurde. Unsere Funktion wird daher nicht +// funktionieren, sofern sie außerhalb des Kontextes des Objekts aufgerufen // wird. var myFunc = myObj.myFunc; myFunc(); // = undefined -// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch +// Umgekehrt ist es möglich eine Funktion einem Objekt zuzuweisen und dadurch // Zugriff auf den this-Kontext zu erhalten, sogar dann, wenn die Funktion dem // Objekt nach dessen Definition zugewiesen wird. var myOtherFunc = function(){ @@ -396,8 +393,8 @@ var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird -// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser +// Wenn eine Funktion mit dem Schlüsselwort 'new' aufgerufen wird, dann wird +// ein neues Objekt erzeugt. Funktionen, die darauf ausgelegt sind in dieser // Art aufgerufen zu werden, werden Konstruktoren genannt. var MyConstructor = function(){ this.myNumber = 5; @@ -405,14 +402,14 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine +// Jedes JavaScript-Objekt hat einen Prototyp. Wenn man versucht auf eine // Eigenschaft des Objekts zuzugreifen, das nicht im Objekt selbst existiert, // schaut der Interpreter in dessen Prototyp nach. -// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den +// Einige JavaScript-Implementierungen erlauben den direkten Zugriff auf den // Prototyp eines Objekts durch die magische Eigenschaft __proto__. Obwohl das // nützlich ist, um Prototypen im Allgemeinen zu erklären, ist das nicht Teil -// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir +// des Standards; zum Standard-Weg der Nutzung von Prototypen kommen wir // später. var myObj = { myString: "Hello world!", @@ -437,26 +434,26 @@ myPrototype.__proto__ = { myObj.myBoolean; // = true // Dafür wird nichts hin und her kopiert; jedes Objekt speichert eine Referenz -// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann +// auf seinen Prototypen. Das heißt wenn der Prototyp geändert wird, dann // werden die Änderungen überall sichtbar. myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es +// Es wurde bereits erwähnt, dass __proto__ nicht zum Standard gehört und es // gibt ebenso keinen Standard-Weg, um den Prototyp eines existierenden Objekts -// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem +// zu ändern. Es gibt dennoch zwei Wege, wie man ein neues Objekt mit einem // gegebenen Prototypen erzeugt. // Der erste Weg ist die Methode Object.create, die eine jüngere Ergänzung des -// JavaScript-Standards ist und daher noch nicht in allen Implementierungen +// JavaScript-Standards ist und daher noch nicht in allen Implementierungen // verfügbar. var myObj = Object.create(myPrototype); myObj.meaningOfLife; // = 43 -// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun. +// Der zweite Weg, der immer funktioniert, hat mit den Konstruktoren zu tun. // Konstruktoren haben eine Eigenschaft, die Prototyp heißt. Dabei handelt es // sich *nicht* um den Prototypen der Konstruktor-Funktion; stattdessen handelt -// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es +// es sich um den Prototypen, der einem neuen Objekt mitgegeben wird, wenn es // mit dem Konstruktor und dem Schlüsselwort 'new' erzeugt wird. MyConstructor.prototype = { getMyNumber: function(){ @@ -466,8 +463,8 @@ MyConstructor.prototype = { var myNewObj2 = new MyConstructor(); myNewObj2.getMyNumber(); // = 5 -// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren, -// die zu dem Typ äquivalente Wrapper-Objekte erzeugen. +// Alle primitiven Typen, also strings und numbers, haben auch Konstruktoren, +// die zu dem Typ äquivalente Wrapper-Objekte erzeugen. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true @@ -480,8 +477,8 @@ if (0){ // Dieser Teil wird nicht ausgeführt, weil 0 'falsy' ist. } -// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen -// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen +// Das Wrapper-Objekt und die regulären, eingebauten Typen, teilen sich einen +// Prototyp; so ist es möglich zum Beispiel einem String weitere Funktionen // hinzuzufügen. String.prototype.firstCharacter = function(){ return this.charAt(0); @@ -489,11 +486,11 @@ String.prototype.firstCharacter = function(){ "abc".firstCharacter(); // = "a" // Diese Tatsache wird häufig bei einer Methode mit dem Namen 'polyfilling' -// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren -// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in +// verwendet: Dabei wird ein neues Feature von JavaScript in einer älteren +// Untermenge der Sprache integriert, so dass bestimmte Funktionen auch in // älteren Umgebungen und Browsern verwendet werden können. -// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in +// Ein Beispiel: Es wurde erwähnt, dass die Methode Object.create nicht in // allen Umgebungen verfügbar ist - wir können sie dennoch verwenden, mit einem // 'polyfill': if (Object.create === undefined){ // überschreib nichts, was eventuell bereits @@ -503,7 +500,7 @@ if (Object.create === undefined){ // überschreib nichts, was eventuell bereits // Prototypen var Constructor = function(){}; Constructor.prototype = proto; - // verwende es dann, um ein neues Objekt mit einem passenden + // verwende es dann, um ein neues Objekt mit einem passenden // Prototypen zurückzugeben return new Constructor(); } @@ -514,7 +511,7 @@ if (Object.create === undefined){ // überschreib nichts, was eventuell bereits Das [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) bietet eine ausgezeichnete Dokumentation für die Verwendung von JavaScript im Browser. Es ist außerdem ein Wiki und ermöglicht es damit anderen zu helfen, wenn man selbst ein wenig Wissen angesammelt hat. -MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus. +MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) führt sehr viele der hier vorgestellten Konzepte im Detail aus. Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen. diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index 050154c7..a70c5160 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -8,22 +8,19 @@ translators: filename: javascript-es.js lang: es-es --- + Tutorial de JavaScript en español. -JavaScript fue creado por Brendan Eich en 1995 mientras trabajaba en Netscape. +JavaScript fue creado por Brendan Eich en 1995 mientras trabajaba en Netscape. Su intención original era crear un lenguaje simple para sitios web, complementándolo con Java para aplicaciones más complejas. Debido a su integracion estrecha con sitios -web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común +web y soporte por defecto de los navegadores modernos se ha vuelto mucho más común para front-end que Java. Sin embargo, JavaScript no sólo se limita a los navegadores web: Node.js, un proyecto que proporciona un entorno de ejecución independiente para el motor V8 de Google Chrome, se está volviendo más y más popular. -¡La retroalimentación es bienvenida! Puedes encontrarme en: -[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), o -[l@leigh.net.au](mailto:l@leigh.net.au). - ```js -// Los comentarios en JavaScript son los mismos como comentarios en C. +// Los comentarios en JavaScript son los mismos como comentarios en C. //Los comentarios de una sola línea comienzan con //, /* y los comentarios multilínea comienzan @@ -78,7 +75,7 @@ false; 'abc'; "Hola, mundo"; -// La negación se aplica con la expresión ! +// La negación se aplica con la expresión ! !true; // = false !false; // = true @@ -147,7 +144,7 @@ var miTerceraVariable; // = undefined // Existen atajos para realizar operaciones aritméticas: miPrimeraVariable += 5; // equivalente a miPrimeraVariable = miPrimeraVariable + 5; - // miPrimeraVariable ahora es 10 + // miPrimeraVariable ahora es 10 miPrimeraVariable *= 10; // ahora miPrimeraVariable es 100 // Y atajos aún más cortos para sumar y restar 1 @@ -157,7 +154,7 @@ miPrimeraVariable--; // de vuelta a 100 // Los arreglos son listas ordenadas de valores, de cualquier tipo. var miArreglo = ["Hola", 45, true]; -// Los miembros de un arreglo pueden ser accesados con la sintaxis +// Los miembros de un arreglo pueden ser accesados con la sintaxis // de indices dentro de corchetes []. // Los índices empiezan en cero. miArreglo[1]; // = 45 @@ -194,7 +191,7 @@ miObjeto.miCuartaLlave; // = undefined /////////////////////////////////// // 3. Lógica y estructura de control -// La sintaxis de esta sección es casi idéntica a la de Java. +// La sintaxis de esta sección es casi idéntica a la de Java. // La estructura if funciona de la misma forma. var contador = 1; @@ -236,8 +233,8 @@ var nombre = otroNombre || "default"; // la estructura switch usa === para sus comparaciones -// usa 'break' para terminar cada caso -// o los casos después del caso correcto serán ejecutados también. +// usa 'break' para terminar cada caso +// o los casos después del caso correcto serán ejecutados también. calificacion = 'B'; switch (calificacion) { case 'A': @@ -266,7 +263,7 @@ function miFuncion(miArgumentoString){ miFuncion("foo"); // = "FOO" // Note que el valor a ser regresado debe estar en la misma línea que la -// palabra clave 'return', de otra forma la función siempre regresará 'undefined' +// palabra clave 'return', de otra forma la función siempre regresará 'undefined' // debido a la inserción automática de punto y coma. function miFuncion() { @@ -299,7 +296,7 @@ if (true){ } i; // = 5 - en un lenguaje que da ámbitos por bloque esto sería undefined, pero no aquí. -// Este conlleva a un patrón de diseño común llamado "ejecutar funciones anónimas +// Este conlleva a un patrón de diseño común llamado "ejecutar funciones anónimas //inmediatamente", que preveé variables temporales de fugarse al ámbito global (function(){ var temporal = 5; @@ -313,7 +310,7 @@ permanente; // = 10 // Una de las características más útiles de JavaScript son los closures. // Si una función es definida dentro de otra función, la función interna tiene acceso -// a todas las variables de la función externa, incluso aunque la función +// a todas las variables de la función externa, incluso aunque la función // externa ya haya terminado. function decirHolaCadaCincoSegundos(nombre){ var texto = "¡Hola, " + nombre + "!"; @@ -323,7 +320,7 @@ function decirHolaCadaCincoSegundos(nombre){ alert(texto); } setTimeout(interna, 5000); - // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos + // setTimeout es asíncrono, así que la función decirHolaCadaCincoSegundos // terminará inmediatamente, y setTimeout llamará a interna() a los cinco segundos // Como interna está "cerrada dentro de" decirHolaCadaCindoSegundos, interna todavía tiene // acceso a la variable 'texto' cuando es llamada. @@ -341,7 +338,7 @@ var miObjeto = { }; miObjeto.miFuncion(); // = "¡Hola Mundo!" -// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables +// Cuando las funciones de un objeto son llamadas, pueden acceder a las variables // del objeto con la palabra clave 'this'. miObjeto = { miString: "¡Hola Mundo!", @@ -375,7 +372,7 @@ otraFuncion.call(miObjeto, " y hola Luna!"); // = "¡Hola Mundo! y hola Luna!" otraFuncion.apply(miObjeto, [" y hola Sol!"]); // = "¡Hola Mundo! y hola Sol!" -// Esto es útil cuando estás trabajando con una función que acepta una secuencia de +// Esto es útil cuando estás trabajando con una función que acepta una secuencia de // argumentos y quieres pasar un arreglo. Math.min(42, 6, 27); // = 6 @@ -407,7 +404,7 @@ miNuevoObjeto.miNumero; // = 5 // propiedad en un objeto que no existe en el objeto el intérprete buscará en // el prototipo. -// Algunas implementaciones de JavaScript te permiten acceder al prototipo de +// Algunas implementaciones de JavaScript te permiten acceder al prototipo de // un objeto con la propiedad __proto__. Mientras que esto es útil para explicar // prototipos, no es parte del estándar; veremos formas estándar de usar prototipos // más adelante. @@ -428,20 +425,20 @@ miObjeto.sentidoDeLaVida; // = 42 // Esto funcionan también para funciones. miObjeto.miFuncion(); // = "hello world!" -// Por supuesto, si la propiedad que buscas no está en el prototipo, +// Por supuesto, si la propiedad que buscas no está en el prototipo, // se buscará en el prototipo del prototipo. miPrototipo.__proto__ = { miBoolean: true }; miObjeto.miBoolean; // = true -// Esto no involucra ningún copiado, cada objeto guarda una referencia a su +// Esto no involucra ningún copiado, cada objeto guarda una referencia a su // prototipo. Esto significa que podemos alterar el prototipo y nuestros // cambios serán reflejados en todos lados. miPrototipo.sentidoDeLaVida = 43; miObjeto.sentidoDeLaVida; // = 43 -// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no +// Mencionabamos anteriormente que __proto__ no está estandarizado, y que no // existe una forma estándar de acceder al prototipo de un objeto. De todas formas. // hay dos formas de crear un nuevo objeto con un prototipo dado. @@ -450,7 +447,7 @@ miObjeto.sentidoDeLaVida; // = 43 var miObjeto = Object.create(miPrototipo); miObjeto.sentidoDeLaVida; // = 43 -// El segundo método, el cual trabaja en todos lados, tiene que ver con los +// El segundo método, el cual trabaja en todos lados, tiene que ver con los // constructores. Los constructores tienen una propiedad llamada prototype. // Este NO ES el prototipo de la función constructor; es el prototipo que // se le da a los nuevos objetos cuando son creados con la palabra clave @@ -482,7 +479,7 @@ if (0){ } // Aún así, los objetos que envuelven y los prototipos por defecto comparten -// un prototipo. así que puedes agregar funcionalidades a un string de la +// un prototipo. así que puedes agregar funcionalidades a un string de la // siguiente forma: String.prototype.primerCaracter = function(){ return this.charAt(0); @@ -497,7 +494,7 @@ String.prototype.primerCaracter = function(){ // las implementaciones, pero podemos hacerlo con polyfill: if (Object.create === undefined){ // esta validación sirve para no sobreescribir Object.create = function(proto){ - // hace un constructor temporal con el prototipo correcto + // hace un constructor temporal con el prototipo correcto var Constructor = function(){}; Constructor.prototype = proto; // y luego lo usamos para hacer un objeto con el prototipo @@ -509,22 +506,22 @@ if (Object.create === undefined){ // esta validación sirve para no sobreescribi ## Fuentes y Referencias -La [Red para Desarroladores de Mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript) +La [Red para Desarroladores de Mozilla](https://developer.mozilla.org/en-US/docs/Web/JavaScript) proveé excelente documentación para JavaScript para navegadores. Además, está en formato de wiki, por lo que mientras vayas aprendiendo podrás ayudar a los demás con tu experiencia. MDN [Una re-introducción a JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) -cubre muchos de los conceptos que vimos aquí pero a mayor detalle. Esta guía cubre, más que nada, +cubre muchos de los conceptos que vimos aquí pero a mayor detalle. Esta guía cubre, más que nada, el lenguaje JavaScript solo. Si quieres aprender a cómo usarlo en un ambiente web empieza aprendiendo sobre el [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) -[Aprende JavaScript con ejemplos y retos](http://www.learneroo.com/modules/64/nodes/350) es una +[Aprende JavaScript con ejemplos y retos](http://www.learneroo.com/modules/64/nodes/350) es una variante de esta guía pero con retos. [Jardín JavaScript](http://bonsaiden.github.io/JavaScript-Garden/) es una guía para todas las funciones y características contra-intuitivas del lenguaje. -[JavaScript: La guía definitiva](http://www.amazon.com/gp/product/0596805527/) es una guía clásica / libro de referencia. +[JavaScript: La guía definitiva](http://www.amazon.com/gp/product/0596805527/) es una guía clásica / libro de referencia. Aparte de las contribuciones directas para este artículo, algo del contenido se adaptó del tutorial de Python por Louie Dinh en este sitio. y el [Tutorial JS](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript) en la Red de Desarrolladores de Mozilla. diff --git a/es-es/matlab-es.html.markdown b/es-es/matlab-es.html.markdown index 6c9800c2..2d1a1809 100644 --- a/es-es/matlab-es.html.markdown +++ b/es-es/matlab-es.html.markdown @@ -13,10 +13,6 @@ lang: es-es MATLAB significa 'MATrix LABoratory'. Es un poderoso lenguaje de computación numérica comúnmente usado en ingeniería y matemáticas. -Si tiene algún comentario, no dude en ponerse en contacto el autor en -[@the_ozzinator](https://twitter.com/the_ozzinator), o -[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). - ```matlab %% Una sección de código comienza con dos símbolos de porcentaje. Los títulos de la sección van en la misma líneas. % Los comentarios comienzan con un símbolo de porcentaje. @@ -24,7 +20,7 @@ Si tiene algún comentario, no dude en ponerse en contacto el autor en %{ Los Comentarios de multiples líneas se ven -como +como esto %} @@ -38,7 +34,7 @@ esto load learnmatlab.mat y %% Esta es otra sección de código -% Esta sección puede ser editada y ejecutada de manera repetida por sí misma, +% Esta sección puede ser editada y ejecutada de manera repetida por sí misma, % y es útil para la programación exploratoria y demostraciones. A = A * 2; plot(A); @@ -97,7 +93,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891 load('myFile.mat', 'y') % argumentos entre paréntesis, separados por comas % Sintaxis del comando: load myFile.mat y % sin paréntesis, y espacios en lugar de comas -% Tenga en cuenta la falta de comillas en el formulario de comandos: +% Tenga en cuenta la falta de comillas en el formulario de comandos: % las entradas siempre se pasan como texto literal; no pueden pasar valores de variables. % Además, no puede recibir salida: [V,D] = eig(A); % esto no tiene equivalente en forma de comando @@ -241,7 +237,7 @@ A.' % Versión concisa de transposición (sin tomar complejo conjugado) A * B % Multiplicación de matrices A .* B % Multiplica cada elemento en A por su elemento correspondiente en B -% Hay varios pares de funciones, donde una actúa sobre cada elemento y +% Hay varios pares de funciones, donde una actúa sobre cada elemento y % la otra (cuyo nombre termina en m) actúa sobre la matriz completa. exp(A) % exponencializar cada elemento expm(A) % calcular la matriz exponencial @@ -443,7 +439,7 @@ abs(x) % Magnitud de la variable compleja x phase(x) % Fase (o ángulo) de la variable compleja x real(x) % Retorna la parte real de x (es decir, devuelve a si x = a + jb) imag(x) % Retorna la parte imaginaria de x (es decir, devuelve b si x = a + jb) -conj(x) % Retorna el complejo conjugado +conj(x) % Retorna el complejo conjugado % Constantes comunes @@ -507,15 +503,15 @@ find(x) % Encuentra todos los elementos distintos de cero de x y devuelve sus í % Clases % MATLAB puede soportar programación orientada a objetos. -% Las clases deben colocarse en un archivo del nombre de la clase con la extensión .m. +% Las clases deben colocarse en un archivo del nombre de la clase con la extensión .m. % Para comenzar, creamos una clase simple para almacenar puntos de referencia de GPS. % Comience WaypointClass.m classdef WaypointClass % El nombre de la clase. properties % Las propiedades de la clase se comportan como Estructuras - latitude - longitude + latitude + longitude end - methods + methods % Este método que tiene el mismo nombre de la clase es el constructor. function obj = WaypointClass(lat, lon) obj.latitude = lat; @@ -564,4 +560,3 @@ c = a + b * [The official MATLAB Answers forum (EN)](http://www.mathworks.com/matlabcentral/answers/) * [Loren on the Art of MATLAB (EN)](http://blogs.mathworks.com/loren/) * [Cleve's Corner (EN)](http://blogs.mathworks.com/cleve/) - diff --git a/fa-ir/javascript-fa.html.markdown b/fa-ir/javascript-fa.html.markdown index 16b18a7c..0aa8079a 100644 --- a/fa-ir/javascript-fa.html.markdown +++ b/fa-ir/javascript-fa.html.markdown @@ -13,13 +13,6 @@ lang: fa-ir با این حال جاوااسکریپت فقط محدود به مرورگر های وب نمیشود. Node.js پروژه ایست که یک نسخه ی مستقل از اجراکننده ی موتور جاوااسکریپت V8 از گوگل کروم را در اختیار قرار میده که هر روزه درحال محبوب تر شدن نیز هست.

    -

    -قدر دان نظرات سازنده شما هستم! شما میتوانید از طریق زیر با من تماس بگیرید: -

    - -[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), or -[l@leigh.net.au](mailto:l@leigh.net.au). -

    // توضیحات همانند C هستند. توضیحات یک خطی با دو خط مورب شروع میشوند.,

    diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index 619d8104..267b5b2f 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -9,18 +9,15 @@ filename: javascript-kr.js lang: ko-kr --- -자바스크립트는 넷스케이프의 브렌던 아이크(Brendan Eich)가 1995년에 만들었습니다. -원래 자바스크립트는 웹사이트를 위한 단순한 스크립트 언어를 목표로 만들어졌는데, -좀 더 복잡한 웹 애플리케이션을 만들기 위해 자바를 보완하는 역할이었지만 -웹 페이지와의 긴밀한 상호작용과 브라우저에 대한 지원 기능 덕분에 웹 프론트엔드에서 -자바보다 훨씬 더 보편적으로 쓰이게 됐습니다. +자바스크립트는 넷스케이프의 브렌던 아이크(Brendan Eich)가 1995년에 만들었습니다. +원래 자바스크립트는 웹사이트를 위한 단순한 스크립트 언어를 목표로 만들어졌는데, +좀 더 복잡한 웹 애플리케이션을 만들기 위해 자바를 보완하는 역할이었지만 +웹 페이지와의 긴밀한 상호작용과 브라우저에 대한 지원 기능 덕분에 웹 프론트엔드에서 +자바보다 훨씬 더 보편적으로 쓰이게 됐습니다. -그렇지만 자바스크립트는 웹 브라우저에만 국한되지 않습니다. 구글 크롬의 V8 자바스크립트 +그렇지만 자바스크립트는 웹 브라우저에만 국한되지 않습니다. 구글 크롬의 V8 자바스크립트 엔진을 위한 독립형 런타임을 제공하는 Node.js는 점점 인기를 얻고 있습니다. -피드백 주시면 대단히 감사하겠습니다! [@ExcitedLeigh](https://twitter.com/ExcitedLeigh)나 -[l@leigh.net.au](mailto:l@leigh.net.au)를 통해 저와 만나실 수 있습니다. - ```js // 주석은 C와 비슷합니다. 한 줄짜리 주석은 두 개의 슬래시로 시작하고, /* 여러 줄 주석은 슬래시 별표로 시작해서 @@ -30,7 +27,7 @@ lang: ko-kr doStuff(); // 하지만 꼭 그럴 필요는 없는데, 특정 경우를 제외하고 -// 새 줄이 시작할 때마다 세미콜론이 자동으로 삽입되기 때문입니다. +// 새 줄이 시작할 때마다 세미콜론이 자동으로 삽입되기 때문입니다. doStuff() // 여기서는 세미콜론을 생략하겠습니다. 세미콜론을 생략할지 여부는 @@ -57,7 +54,7 @@ doStuff() // 32비트까지 부호가 있는 int로 변환됩니다. 1 << 2 // = 4 -// 괄호를 이용하면 우선순위를 지정할 수 있습니다. +// 괄호를 이용하면 우선순위를 지정할 수 있습니다. (1 + 3) * 2 // = 8 // 실제 숫자가 아닌 특별한 세 가지 값이 있습니다. @@ -97,7 +94,7 @@ false // 그리고 <와 >로 비교할 수 있습니다. "a" < "b" // = true -// 비교 시 타입 강제변환이 수행됩니다. +// 비교 시 타입 강제변환이 수행됩니다. "5" == 5 // = true // ===를 쓰지 않는다면 말이죠. @@ -123,14 +120,14 @@ var someVar = 5 // var 키워드를 지정하지 않아도 오류는 발생하지 않습니다. someOtherVar = 10 -// 그렇지만 변수가 여러분이 정의한 유효범위가 아니라 +// 그렇지만 변수가 여러분이 정의한 유효범위가 아니라 // 전역 유효범위에 생성됩니다. -// 값을 할당하지 않은 채로 선언한 변수는 undefined로 설정됩니다. +// 값을 할당하지 않은 채로 선언한 변수는 undefined로 설정됩니다. var someThirdVar // = undefined // 변수에 수학 연산을 수행하는 축약형 표현은 다음과 같습니다. -someVar += 5 // someVar = someVar + 5;와 같음. 이제 someVar는 10. +someVar += 5 // someVar = someVar + 5;와 같음. 이제 someVar는 10. someVar *= 10 // somVar는 100 // 1을 더하거나 빼는 훨씬 더 짧은 표현도 있습니다. @@ -234,7 +231,7 @@ setTimeout(function myFunction(){ // 이 코드는 5초 내에 호출됨 }, 5000) -// 자바스크립트에는 함수 유효범위가 있습니다. +// 자바스크립트에는 함수 유효범위가 있습니다. // 함수는 자체적인 유효범위를 가지지만 다른 블록은 유효범위를 가지지 않습니다. if (true){ var i = 5 @@ -246,7 +243,7 @@ i // = 5 - 블록 유효범위를 지원하는 언어에서는 undefined가 아 (function(){ var temporary = 5 // '전역 객체'에 할당하는 식으로 전역 유효범위에 접근할 수 있는데, - // 브라우저에서 전역 객체는 항상 'window'입니다. 전역 객체는 + // 브라우저에서 전역 객체는 항상 'window'입니다. 전역 객체는 // Node.js와 같은 브라우저가 아닌 환경에서는 다른 이름일 수도 있습니다. window.permanent = 10 // 또는 앞에서 언급했다시피 var 키워드를 뺄 수도 있습니다. @@ -292,8 +289,8 @@ myObj = { } myObj.myFunc() // = "Hello world!" -// 여기서 설정한 것은 함수가 정의된 곳이 아닌 함수가 호출되는 -// 방식과 관련이 있습니다. 그래서 아래 함수는 객체 컨텍스트에서 +// 여기서 설정한 것은 함수가 정의된 곳이 아닌 함수가 호출되는 +// 방식과 관련이 있습니다. 그래서 아래 함수는 객체 컨텍스트에서 // 호출되지 않으면 동작하지 않습니다. var myFunc = myObj.myFunc myFunc() // = undefined @@ -320,8 +317,8 @@ myNewObj.myNumber // = 5 // 해당 프로퍼티를 찾습니다. // 일부 자바스크립트 구현체에서는 __proto__라는 마법의 프로퍼티로 -// 객체의 프로토타입에 접근하는 것을 허용하기도 합니다. 프로토타입을 -// 설명하기에는 이런 내용도 도움되겠지만 __proto__는 표준에 포함돼 +// 객체의 프로토타입에 접근하는 것을 허용하기도 합니다. 프로토타입을 +// 설명하기에는 이런 내용도 도움되겠지만 __proto__는 표준에 포함돼 // 있지 않습니다. 나중에 프로토타입을 사용하는 표준 방법을 살펴보겠습니다. var myObj = { myString: "Hello world!", @@ -346,18 +343,18 @@ myPrototype.__proto__ = { myObj.myBoolean // = true // 여기서 복사는 일어나지 않습니다. 각 객체에는 프로토타입에 대한 -// 참조가 보관돼 있습니다. 이는 프로토타입을 변경하면 변경사항이 +// 참조가 보관돼 있습니다. 이는 프로토타입을 변경하면 변경사항이 // 모든 곳에 반영된다는 의미입니다. myPrototype.meaningOfLife = 43 myObj.meaningOfLife // = 43 -// 앞에서 __proto__가 표준에 포함돼 있지 않다고 이야기했는데, -// 기존 객체의 프로토타입을 변경하는 표준 방법은 없습니다. +// 앞에서 __proto__가 표준에 포함돼 있지 않다고 이야기했는데, +// 기존 객체의 프로토타입을 변경하는 표준 방법은 없습니다. // 하지만 특정 프로토타입을 가지고 새로운 객체를 생성하는 두 가지 // 방법이 있습니다. -// 첫 번째 방법은 Object.create를 이용하는 것인데, -// Object.create는 최근에 자바스크립트에 추가된 것이라서 아직까지 +// 첫 번째 방법은 Object.create를 이용하는 것인데, +// Object.create는 최근에 자바스크립트에 추가된 것이라서 아직까지 // 모든 구현체에서 이용할 수 있는 것은 아닙니다. var myObj = Object.create(myPrototype) myObj.meaningOfLife // = 43 @@ -388,7 +385,7 @@ if (0){ // 0은 거짓이라서 이 코드는 실행되지 않습니다. } -// 하지만 래퍼 객체와 일반 내장 함수는 프로토타입을 공유하기 때문에 +// 하지만 래퍼 객체와 일반 내장 함수는 프로토타입을 공유하기 때문에 // 가령 문자열에 실제로 기능을 추가할 수 있습니다. String.prototype.firstCharacter = function(){ return this.charAt(0) @@ -399,7 +396,7 @@ String.prototype.firstCharacter = function(){ // 새로운 기능을 구현하는 "폴리필(polyfilling)"에 자주 이용되므로 // 오래된 버전의 브라우저와 같이 기존 환경에서 사용될 수 있습니다. -// 예를 들어, Object.create가 모든 구현체에서 사용 가능한 것은 아니라고 +// 예를 들어, Object.create가 모든 구현체에서 사용 가능한 것은 아니라고 // 했지만 아래의 폴리필을 이용해 Object.create를 여전히 사용할 수 있습니다. if (Object.create === undefined){ // 이미 존재하면 덮어쓰지 않음 Object.create = function(proto){ @@ -415,19 +412,19 @@ if (Object.create === undefined){ // 이미 존재하면 덮어쓰지 않음 ## 기타 참고 자료 -[모질라 개발자 네트워크](https://developer.mozilla.org/en-US/docs/Web/JavaScript)에서는 -자바스크립트에 대한 훌륭한 문서를 제공합니다. 더불어 위키 형식이라서 좀 더 많은 사항을 +[모질라 개발자 네트워크](https://developer.mozilla.org/en-US/docs/Web/JavaScript)에서는 +자바스크립트에 대한 훌륭한 문서를 제공합니다. 더불어 위키 형식이라서 좀 더 많은 사항을 배우게 되면 여러분만의 지식을 공유함으로써 다른 사람들에게 도움을 줄 수도 있습니다. -MDN의 ['자바스크립트 재입문'](https://developer.mozilla.org/ko/docs/A_re-introduction_to_JavaScript)에서는 -여기서 다룬 개념의 상당수를 더욱 자세히 다루고 있습니다. 이 자료에서는 자바스크립트 언어 자체에 -대해서만 상당히 신중하게 다뤘습니다. 웹 페이지에서 자바스크립트를 사용하는 방법을 배우고 싶다면 -[문서 객체 모델(Document Object Model)](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)에 +MDN의 ['자바스크립트 재입문'](https://developer.mozilla.org/ko/docs/A_re-introduction_to_JavaScript)에서는 +여기서 다룬 개념의 상당수를 더욱 자세히 다루고 있습니다. 이 자료에서는 자바스크립트 언어 자체에 +대해서만 상당히 신중하게 다뤘습니다. 웹 페이지에서 자바스크립트를 사용하는 방법을 배우고 싶다면 +[문서 객체 모델(Document Object Model)](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)에 관해 배우는 것으로 시작하길 바랍니다. [자바스크립트 가든](http://bonsaiden.github.io/JavaScript-Garden/)에서는 자바스크립트 언어에서 직관에 어긋나는 모든 부분들을 심도 있게 다룹니다. -더불어 이 글에 직접적으로 기여한 분들로, 내용 중 일부는 이 사이트에 있는 -루이 딘(Louie Dihn)의 파이썬 튜토리얼과 모질라 개발자 네트워크에 있는 +더불어 이 글에 직접적으로 기여한 분들로, 내용 중 일부는 이 사이트에 있는 +루이 딘(Louie Dihn)의 파이썬 튜토리얼과 모질라 개발자 네트워크에 있는 [자바스크립트 튜토리얼](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript)을 참고했습니다. diff --git a/matlab.html.markdown b/matlab.html.markdown index 07f73cfb..ddf79f05 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -10,10 +10,6 @@ contributors: MATLAB stands for MATrix LABoratory. It is a powerful numerical computing language commonly used in engineering and mathematics. -If you have any feedback please feel free to reach me at -[@the_ozzinator](https://twitter.com/the_ozzinator), or -[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). - ```matlab %% Code sections start with two percent signs. Section titles go on the same line. % Comments start with a percent sign. @@ -49,42 +45,42 @@ plot(A); % commands can be passed to the operating system !ping google.com -who % Displays all variables in memory -whos % Displays all variables in memory, with their types -clear % Erases all your variables from memory -clear('A') % Erases a particular variable +who % Displays all variables in memory +whos % Displays all variables in memory, with their types +clear % Erases all your variables from memory +clear('A') % Erases a particular variable openvar('A') % Open variable in variable editor -clc % Erases the writing on your Command Window -diary % Toggle writing Command Window text to file +clc % Erases the writing on your Command Window +diary % Toggle writing Command Window text to file ctrl-c % Abort current computation edit('myfunction.m') % Open function/script in editor type('myfunction.m') % Print the source of function/script to Command Window -profile on % turns on the code profiler -profile off % turns off the code profiler -profile viewer % Open profiler +profile on % turns on the code profiler +profile off % turns off the code profiler +profile viewer % Open profiler -help command % Displays documentation for command in Command Window -doc command % Displays documentation for command in Help Window -lookfor command % Searches for command in the first commented line of all functions +help command % Displays documentation for command in Command Window +doc command % Displays documentation for command in Help Window +lookfor command % Searches for command in the first commented line of all functions lookfor command -all % searches for command in all functions % Output formatting -format short % 4 decimals in a floating number -format long % 15 decimals -format bank % only two digits after decimal point - for financial calculations +format short % 4 decimals in a floating number +format long % 15 decimals +format bank % only two digits after decimal point - for financial calculations fprintf('text') % print "text" to the screen -disp('text') % print "text" to the screen +disp('text') % print "text" to the screen % Variables & Expressions -myVariable = 4 % Notice Workspace pane shows newly created variable +myVariable = 4 % Notice Workspace pane shows newly created variable myVariable = 4; % Semi colon suppresses output to the Command Window -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 @@ -92,7 +88,7 @@ c = exp(a)*sin(pi/2) % c = 7.3891 % Standard function syntax: load('myFile.mat', 'y') % arguments within parentheses, separated by commas % Command syntax: -load myFile.mat y % no parentheses, and spaces instead of commas +load myFile.mat y % no parentheses, and spaces instead of commas % Note the lack of quote marks in command form: inputs are always passed as % literal text - cannot pass variable values. Also, can't receive output: [V,D] = eig(A); % this has no equivalent in command form @@ -338,8 +334,8 @@ load('myFileName.mat') % Load saved variables into Workspace % Function name should match file name (so save this example as double_input.m). % 'help double_input.m' returns the comments under line beginning function function output = double_input(x) - %double_input(x) returns twice the value of x - output = 2*x; + %double_input(x) returns twice the value of x + output = 2*x; end double_input(6) % ans = 12 @@ -375,23 +371,23 @@ fprintf % Print to Command Window with more control % Conditional statements (the parentheses are optional, but good style) if (a > 23) - disp('Greater than 23') + disp('Greater than 23') elseif (a == 23) - disp('a is 23') + disp('a is 23') else - disp('neither condition met') + disp('neither condition met') end % Looping % NB. looping over elements of a vector/matrix is slow! % Where possible, use functions that act on whole vector/matrix at once for k = 1:5 - disp(k) + disp(k) end k = 0; while (k < 5) - k = k + 1; + k = k + 1; end % Timing code execution: 'toc' prints the time since 'tic' was called @@ -435,11 +431,11 @@ randi % Uniformly distributed pseudorandom integers randn % Normally distributed pseudorandom numbers %Complex math operations -abs(x) % Magnitude of complex variable x +abs(x) % Magnitude of complex variable x phase(x) % Phase (or angle) of complex variable x real(x) % Returns the real part of x (i.e returns a if x = a +jb) imag(x) % Returns the imaginary part of x (i.e returns b if x = a+jb) -conj(x) % Returns the complex conjugate +conj(x) % Returns the complex conjugate % Common constants @@ -496,23 +492,23 @@ median % median value mean % mean value std % standard deviation perms(x) % list all permutations of elements of x -find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators, +find(x) % Finds all non-zero elements of x and returns their indexes, can use comparison operators, % i.e. find( x == 3 ) returns indexes of elements that are equal to 3 % i.e. find( x >= 3 ) returns indexes of elements greater than or equal to 3 % Classes -% MATLAB can support object-oriented programming. -% Classes must be put in a file of the class name with a .m extension. +% MATLAB can support object-oriented programming. +% Classes must be put in a file of the class name with a .m extension. % To begin, we create a simple class to store GPS waypoints. % Begin WaypointClass.m classdef WaypointClass % The class name. properties % The properties of the class behave like Structures - latitude - longitude + latitude + longitude end - methods - % This method that has the same name of the class is the constructor. + methods + % This method that has the same name of the class is the constructor. function obj = WaypointClass(lat, lon) obj.latitude = lat; obj.longitude = lon; @@ -543,12 +539,12 @@ a.longitude = 25.0 % Methods can be called in the same way as functions ans = multiplyLatBy(a,3) -% The method can also be called using dot notation. In this case, the object +% The method can also be called using dot notation. In this case, the object % does not need to be passed to the method. ans = a.multiplyLatBy(1/3) -% MATLAB functions can be overloaded to handle objects. -% In the method above, we have overloaded how MATLAB handles +% MATLAB functions can be overloaded to handle objects. +% In the method above, we have overloaded how MATLAB handles % the addition of two Waypoint objects. b = WaypointClass(15.0, 32.0) c = a + b @@ -560,4 +556,3 @@ c = a + b * [The official MATLAB Answers forum](http://www.mathworks.com/matlabcentral/answers/) * [Loren on the Art of MATLAB](http://blogs.mathworks.com/loren/) * [Cleve's Corner](http://blogs.mathworks.com/cleve/) - diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index e38804f3..c5be649d 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -16,13 +16,9 @@ integração com páginas web e seu suporte nativo nos browsers fez com que ela se tornasse mais comum que Java no frontend web. Javascript não é somente limitada a browsers web, existindo o Node.js, -que é um projeto que fornece um interpretador baseado no motor V8 do Google +que é um projeto que fornece um interpretador baseado no motor V8 do Google Chrome e está se tornando cada vez mais famoso. -Feedback são muito apreciados! Você me encontrar em -[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), ou -[l@leigh.net.au](mailto:l@leigh.net.au). - ```js // Comentários são como em C. Comentários de uma linha começam com duas barras, /* e comentários de múltiplas linhas começam com barra-asterisco @@ -35,7 +31,7 @@ facaAlgo(); // inserido quando há uma nova linha, exceto alguns casos. facaAlgo() -// Como esses casos podem causar resultados inesperados, vamos continuar +// Como esses casos podem causar resultados inesperados, vamos continuar // a usar ponto-e-vírgula neste guia. /////////////////////////////////// @@ -107,7 +103,7 @@ null == undefined; // = true // ...a menos que use === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false // ...isso pode resultar em comportamentos estranhos... 13 + !0; // 14 @@ -134,7 +130,7 @@ undefined; // usado para indicar um valor que não é a atualmente definido /////////////////////////////////// // 2. Variáveis, Arrays e Objetos -// Variáveis são declaradas com a palavra-chave `var`. O Javascript é +// Variáveis são declaradas com a palavra-chave `var`. O Javascript é // dinâmicamente tipado, portanto você não precisa especificar o tipo. // Atribuições usam um simples caracter de `=`. var someVar = 5; @@ -185,7 +181,7 @@ myObj["my other key"]; // = 4 // válido. myObj.myKey; // = "myValue" -// Objetos são mutáveis, valores podem ser modificados e novas chaves +// Objetos são mutáveis, valores podem ser modificados e novas chaves // adicionadas. myObj.myThirdKey = true; @@ -265,8 +261,8 @@ function myFunction(thing){ myFunction("foo"); // = "FOO" // Repare que o valor a ser retornado deve começar na mesma linha que -// a palavra-chave `return`, senão você sempre irá retornar `undefined` -// visto que o ponto-e-vírgula é inserido automáticamente nas quebras de +// a palavra-chave `return`, senão você sempre irá retornar `undefined` +// visto que o ponto-e-vírgula é inserido automáticamente nas quebras de // linha. Preste atenção quando usar o estilo Allman. function myFunction() { @@ -287,21 +283,21 @@ setTimeout(myFunction, 5000); // Nota: `setTimeout` não é parte da linguagem Javascript, mas é provido pelos // browsers e o Node.js. -// Objetos de funções não precisam nem serem declarados com nome - você pode -// escrever a definição de uma função anônima diretamente nos argumentos de +// Objetos de funções não precisam nem serem declarados com nome - você pode +// escrever a definição de uma função anônima diretamente nos argumentos de // outra função. setTimeout(function(){ // este código será chamado em 5 segundos }, 5000); -// O Javascript tem escopo de função; as funções tem seu próprio escopo, +// O Javascript tem escopo de função; as funções tem seu próprio escopo, // mas outros blocos não. if (true){ var i = 5; } i; // = 5 - não `undefined` como você esperaria numa linguagem de blogo-escopo -// Isso levou a padrão comum chamado de IIFE (Imediately Invoked Function +// Isso levou a padrão comum chamado de IIFE (Imediately Invoked Function // Expression) ou (Expressão de Função Invocada Imediatamente), que previne // que variáveis temporárias vazem para o escopo global. (function(){ @@ -322,7 +318,7 @@ function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; // Funções internas são colocadas no escopo local por padrão, assim como - // se fossem declaradas com `var`. + // se fossem declaradas com `var`. function inner(){ alert(prompt); } @@ -347,7 +343,7 @@ var myObj = { myObj.myFunc(); // = "Olá mundo!" // Quando uma função ligada a um objeto é chamada, ela pode acessar o objeto -// da qual foi ligada usando a palavra-chave `this`. +// da qual foi ligada usando a palavra-chave `this`. myObj = { myString: "Olá mundo!", myFunc: function(){ @@ -356,7 +352,7 @@ myObj = { }; myObj.myFunc(); // = "Olá mundo!" -// O `this` só funciona para dentro do escopo do objeto, portanto, se chamarmos +// O `this` só funciona para dentro do escopo do objeto, portanto, se chamarmos // um método do objeto fora de seu escopo, este não irá funcionar. var myFunc = myObj.myFunc; myFunc(); // = undefined @@ -369,7 +365,7 @@ var myOtherFunc = function(){ myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "OLÁ MUNDO!" -// Nós podemos também especificar um contexto onde a função irá executar, +// Nós podemos também especificar um contexto onde a função irá executar, // usando o `call` ou `apply`. var anotherFunc = function(s){ @@ -389,7 +385,7 @@ Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -// Mas, o `call` e `apply` são somente temporários. Quando você quiser que +// Mas, o `call` e `apply` são somente temporários. Quando você quiser que // permaneça sempre no escopo, use `bind`. var boundFunc = anotherFunc.bind(myObj); @@ -402,7 +398,7 @@ var doubler = product.bind(this, 2); doubler(8); // = 16 // Quando você invoca uma função com a palavra-chave `new`, um novo objeto -// é criado, e fica disponível para a função pela palavra-chave `this`. +// é criado, e fica disponível para a função pela palavra-chave `this`. // Funções são desenhadas para serem invocadas como se invocam os construtores. var MyConstructor = function(){ @@ -411,13 +407,13 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -// Todo objeto JavaScript possui um `prototype`. Quando você tenta acessar +// Todo objeto JavaScript possui um `prototype`. Quando você tenta acessar // uma propriedade de um objeto que não existe no objeto atual, o interpretador // vai olhar imediatamente para o seu prototype. -// Algumas implementações em JS deixam você acessar o objeto prototype com a -// propriedade mágica `__proto__`. Enquanto isso é útil para explicar -// prototypes, não é parte de um padrão; nós vamos falar de algumas formas de +// Algumas implementações em JS deixam você acessar o objeto prototype com a +// propriedade mágica `__proto__`. Enquanto isso é útil para explicar +// prototypes, não é parte de um padrão; nós vamos falar de algumas formas de // usar prototypes depois. var myObj = { @@ -436,7 +432,7 @@ myObj.meaningOfLife; // = 42 // Isto funciona para funções, também. myObj.myFunc(); // = "olá mundo!" -// É claro, se sua propriedade não está em seu prototype, +// É claro, se sua propriedade não está em seu prototype, // o prototype do prototype será procurado e por aí vai. myPrototype.__proto__ = { myBoolean: true @@ -450,8 +446,8 @@ myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 -// Nós mencionamos que o `__proto__` não é uma forma padrão, e não há uma -// forma padrão de mudar o prototype de um objeto já existente. Entretanto, +// Nós mencionamos que o `__proto__` não é uma forma padrão, e não há uma +// forma padrão de mudar o prototype de um objeto já existente. Entretanto, // existem duas formas de se criar um objeto com um dado prototype. // A primeira forma é `Object.create`, que é uma adição recente do JS, @@ -475,7 +471,7 @@ myNewObj2.myNumber = 6 myNewObj2.getMyNumber(); // = 6 // Tipos originais da linguagem como strings e números também possuem -// construtores equivalentes. +// construtores equivalentes. var myNumber = 12; var myNumberObj = new Number(12); myNumber == myNumberObj; // = true @@ -500,7 +496,7 @@ String.prototype.firstCharacter = function(){ // uma nova característica do Javascript em uma versão mais velha, para que // assim funcionem em ambientes mais velhos como browsers ultrapassados. -// Havíamos mencionado que `Object.create` não estava ainda disponível em +// Havíamos mencionado que `Object.create` não estava ainda disponível em // todos as implementações, mas nós podemos usá-lo com esse polyfill: if (Object.create === undefined){ // Não o sobrescreve se já existir Object.create = function(proto){ @@ -517,12 +513,11 @@ if (Object.create === undefined){ // Não o sobrescreve se já existir O [Mozilla Developer Network](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript) dispõe de uma -excelente documentação sobre Javascript e seu uso nos browsers. E mais, +excelente documentação sobre Javascript e seu uso nos browsers. E mais, é uma wiki, portanto conforme você vai aprendendo, mais você pode ir ajudando os outros compartilhando do seu conhecimento. -[Uma re-introdução do JavaScript pela MDN] -(https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) +[Uma re-introdução do JavaScript pela MDN](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) cobre muito dos conceitos abordados aqui em mais detalhes. Este guia fala somente sobre a linguagem JavaScript em si; se você quiser aprender mais sobre e como usar o JavaScript em páginas na web, comece aprendendo sobre @@ -532,11 +527,11 @@ Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) [Aprenda Javascript por Exemplos e com Desafios](http://www.learneroo.com/modules/64/nodes/350) é uma variação desse guia com desafios. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) é um guia +[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) é um guia profundo de todas as partes do JavaScript. [JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) é o guia clássico -/ livro de referência. +/ livro de referência. Parte desse artigo foi adaptado do tutorial de Python do Louie Dinh que está nesse site e do [Tutorial de JS](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/A_re-introduction_to_JavaScript) diff --git a/pt-br/matlab-pt.html.markdown b/pt-br/matlab-pt.html.markdown index cd300f39..7da4aea4 100644 --- a/pt-br/matlab-pt.html.markdown +++ b/pt-br/matlab-pt.html.markdown @@ -8,15 +8,10 @@ translators: - ["Claudson Martins", "https://github.com/claudsonm"] lang: pt-br filename: learnmatlab-pt.mat - --- MATLAB significa MATrix LABoratory. É uma poderosa linguagem de computação numérica geralmente utilizada em engenharia e matemática. -Se você tem algum feedback, por favor fique a vontade para me contactar via -[@the_ozzinator](https://twitter.com/the_ozzinator), ou -[osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com). - ```matlab % Comentários iniciam com um sinal de porcentagem @@ -485,10 +480,10 @@ perms(x) % Lista todas as permutações de elementos de x % Início ClassePosicoesGPS.m classdef ClassePosicoesGPS % O nome da classe. properties % As propriedades da classe comportam-se como estruturas - latitude - longitude + latitude + longitude end - methods + methods % Este método que tem o mesmo nome da classe é o construtor. function obj = ClassePosicoesGPS(lat, lon) obj.latitude = lat; @@ -535,4 +530,3 @@ c = a + b * O site oficial [http://http://www.mathworks.com/products/matlab/](http://www.mathworks.com/products/matlab/) * O fórum oficial de respostas: [http://www.mathworks.com/matlabcentral/answers/](http://www.mathworks.com/matlabcentral/answers/) - diff --git a/ta-in/javascript-ta.html.markdown b/ta-in/javascript-ta.html.markdown index 539218a6..f7fd282e 100644 --- a/ta-in/javascript-ta.html.markdown +++ b/ta-in/javascript-ta.html.markdown @@ -4,7 +4,7 @@ contributors: - ['Leigh Brenecki', 'https://leigh.net.au'] - ['Ariel Krakowski', 'http://www.learneroo.com'] translators: - - ["Rasendran Kirushan", "https://github.com/kirushanr"] + - ["Rasendran Kirushan", "https://github.com/kirushanr"] filename: javascript-ta.js lang: ta-in --- @@ -12,37 +12,33 @@ lang: ta-in javascript 1995 ஆம் ஆண்டு Netscape இல் பணிபுரிந்த Brendan Eich என்பவரால் உருவாக்கபட்டது.ஆரம்பத்தில் மிகவும் எளிமையான ஸ்க்ரிப்டிங் மொழியாக இணையதளங்களில் பயன்படுத்தபட்டது. -இது ஜாவா (java ) வில் உருவாக்கபட்ட மிகவும் சிக்கலான இணைய செயலிகளுக்கு -உதவும் முகமாக உருவாக்கபட்டது. எனினும் இணையதள பக்கங்களில் இதன் முழுதான பயன்பாடு -மற்றும் உலாவிகளில் பயன்படுத்த கூடிய வகையில் இருந்தமையாலும் Java வை விட +இது ஜாவா (java ) வில் உருவாக்கபட்ட மிகவும் சிக்கலான இணைய செயலிகளுக்கு +உதவும் முகமாக உருவாக்கபட்டது. எனினும் இணையதள பக்கங்களில் இதன் முழுதான பயன்பாடு +மற்றும் உலாவிகளில் பயன்படுத்த கூடிய வகையில் இருந்தமையாலும் Java வை விட இணையதளகளின் முகப்பு உருவாக்கத்தில் இன்றளவில் முன்னிலை பெற்றுள்ளது. -உலாவிகளுக்கு மட்டும் மட்டுபடுத்தபடவில்லை , Node.js மூலமாக -மிகவும் பிரபல்யமடைந்து வருகின்றது , உதாரணமாக கூகிள்க்ரோம் உலாவியின் +உலாவிகளுக்கு மட்டும் மட்டுபடுத்தபடவில்லை , Node.js மூலமாக +மிகவும் பிரபல்யமடைந்து வருகின்றது , உதாரணமாக கூகிள்க்ரோம் உலாவியின் V8 JavaScript engine Node .js உதவியுடன் இயங்குகிறது . -உங்கள் கருத்துக்கள் மிகவும் வரவேற்கபடுகின்றன , என்னுடன் தொடர்புகொள்ள -[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), or -[l@leigh.net.au](mailto:l@leigh.net.au). - ```js -// குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும் +// குறிப்புக்கள் C நிரலாக்கத்தை ஒத்தது .ஒரு வரி குறிப்புக்கள் "//" குறியீடுடன் ஆரம்பமாகும் /* பலவரி குறிப்புக்கள் "/*" ஆரம்பமாகி "/*" இல் முடிவடையும் */ // ஒரு கூற்று முற்றுபெற செய்ய ; இடல் வேண்டும் . doStuff(); -// ...ஆனால் அரைபுள்ளி இட வேண்டும் என்று அவசியம் இல்லை ஏன் எனில் +// ...ஆனால் அரைபுள்ளி இட வேண்டும் என்று அவசியம் இல்லை ஏன் எனில் // ஒரு வரி புதிதாக இடப்படும் போது அரைபுள்ளிகள் தானாகவே இடப்படும் ஆனால் சில தருணங்களை தவிர . doStuff() -// ஆனால் அவ்வாறான தருணங்கள் எதிர்பாராத முடிவுகளை தரலாம் +// ஆனால் அவ்வாறான தருணங்கள் எதிர்பாராத முடிவுகளை தரலாம் // எனவே நாம் தொடர்ந்து ஒரு கூற்று நிறைவடையும் போது அரைபுள்ளி ஒன்றை இடுவோம் . /////////////////////////////////// -// 1. எண்கள்(Number) ,சரம் (String),செயற்குறிகள்(Operators) +// 1. எண்கள்(Number) ,சரம் (String),செயற்குறிகள்(Operators) // JavaScript ஒரே ஒரு எண்வகை காணப்படுகிறது தசமி (which is a 64-bit IEEE 754 double). // தசமி எண்வகை (Doubles) 2^ 52 வரை சேமிக்க கூடியது @@ -50,7 +46,7 @@ doStuff() 3; // = 3 1.5; // = 1.5 -// அடிப்படை கணித பொறிமுறைகள் +// அடிப்படை கணித பொறிமுறைகள் 1 + 1; // = 2 0.1 + 0.2; // = 0.30000000000000004 8 - 1; // = 7 @@ -61,29 +57,29 @@ doStuff() 5 / 2; // = 2.5 -//bitwise பொறிமுறையை உபயோகிக்கும் போது -//உங்கள் தசம எண்ணின் பெறுமானமானது ஒரு நேர் அல்லது மறை அல்லது பூசியமாகவுள்ள முழு எண்ணாக -//மாற்றம் பெறுகிறது இது 32 இருமம்(bit) வரை செல்லலாம் +//bitwise பொறிமுறையை உபயோகிக்கும் போது +//உங்கள் தசம எண்ணின் பெறுமானமானது ஒரு நேர் அல்லது மறை அல்லது பூசியமாகவுள்ள முழு எண்ணாக +//மாற்றம் பெறுகிறது இது 32 இருமம்(bit) வரை செல்லலாம் 1 << 2; // = 4 -// நிரலாக்கத்தில் செயலியை அமுல்படுத்தும் வரிசைமுறையில் அடைப்பு குறிக்கு முன்னிலை வழங்கபடுகிறது +// நிரலாக்கத்தில் செயலியை அமுல்படுத்தும் வரிசைமுறையில் அடைப்பு குறிக்கு முன்னிலை வழங்கபடுகிறது (1 + 3) * 2; // = 8 // மெய் எண் அல்லாத மூன்றுபெறுமானங்கள் உள்ளன : Infinity; // result of e.g. 1/0 -Infinity; // result of e.g. -1/0 -NaN; // result of e.g. 0/0, இது எண் அல்ல என்பதை குறிக்கும் +NaN; // result of e.g. 0/0, இது எண் அல்ல என்பதை குறிக்கும் // தர்க ரீதியில் ஆன கட்டமைப்பு காணப்படுகிறது . true; false; -// சரம் (string) ' அல்லது " குறியீட்டினால் உருவாக்கபடுகிறது +// சரம் (string) ' அல்லது " குறியீட்டினால் உருவாக்கபடுகிறது 'abc'; "Hello, world"; -// ஒரு boolean பெறுமானத்தின் எதிர்மறை பெறுமானத்தை பெற ! குறியீடு பயன்படுத்தபடுகிறது +// ஒரு boolean பெறுமானத்தின் எதிர்மறை பெறுமானத்தை பெற ! குறியீடு பயன்படுத்தபடுகிறது !true; // = false !false; // = true @@ -95,7 +91,7 @@ false; 1 !== 1; // = false 2 !== 1; // = true -// மேலும் சில ஒப்பீடுகள் +// மேலும் சில ஒப்பீடுகள் 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true @@ -107,15 +103,15 @@ false; // இரண்டு மாறிகளை/பெறுமானங்களை ஒப்பிட < and > "a" < "b"; // = true -// இரண்டு பெறுமானங்கள் / மாறிகள் ஒரேவகையை சேர்ந்தவையா என பார்க்க +// இரண்டு பெறுமானங்கள் / மாறிகள் ஒரேவகையை சேர்ந்தவையா என பார்க்க "5" == 5; // = true null == undefined; // = true // ...இல்லாவிடின் === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false -// ...கிழே உள்ள கூற்றுகள் எதிர்பாராத +// ...கிழே உள்ள கூற்றுகள் எதிர்பாராத வெளியீடுகளை தரலாம் ... 13 + !0; // 14 "13" + !0; // '13true' @@ -127,11 +123,11 @@ null === undefined; // = false //... ஒரு சரத்தை(string ) சொற்களாக பிரிக்க (substring) `substring "Hello world".substring(0, 5); // = "Hello" -// `length` ஒரு சரத்தில்(string) உள்ள சொற்களின் எண்ணிக்கை அல்லது நீளத்தை(length)அறிய +// `length` ஒரு சரத்தில்(string) உள்ள சொற்களின் எண்ணிக்கை அல்லது நீளத்தை(length)அறிய "Hello".length; // = 5 // `null` மற்றும் `undefined` இரு பெறுமானங்கள் உள்ளன . -null; // மதிப்பு அற்ற ஒரு பெறுமானத்தை குறிக்கும் +null; // மதிப்பு அற்ற ஒரு பெறுமானத்தை குறிக்கும் undefined; // பெறுமானம் இன்னும் நிர்ணயிக்க படவில்லை என்பதை குறிக்கும் ( // `undefined` இருப்பினும் இதுவும் ஒரு பெறுமானமாக கருதபடுகிறது ) @@ -142,35 +138,35 @@ undefined; // பெறுமானம் இன்னும் நிர்ண // 2. மாறிகள் (Variables),அணிகள் (Arrays) மற்றும் பொருட்கள் (Objects) // மாறிகளை உருவாக்க `var ` என்னும் குறியீட்டு சொல் (keyword ) பயன்படுகிறது . -//உருவாக்கப்படும் மாறிகள் எந்த வகையை சார்ந்தன என்பதை JavaScript -//தானாகவே நிர்ணயிக்கும் . மாறிக்கு ஒரு பெறுமானத்தை வழங்க `=` பாவிக்க +//உருவாக்கப்படும் மாறிகள் எந்த வகையை சார்ந்தன என்பதை JavaScript +//தானாகவே நிர்ணயிக்கும் . மாறிக்கு ஒரு பெறுமானத்தை வழங்க `=` பாவிக்க var someVar = 5; -// //நீங்கள் மாறிகளை நிறுவ 'var' குறியீட்டு சொல்லை பயன்படுத்தா விடினும் +// //நீங்கள் மாறிகளை நிறுவ 'var' குறியீட்டு சொல்லை பயன்படுத்தா விடினும் //அது தவறில்லை ... someOtherVar = 10; -// ...ஆனால் நீங்கள் நிறுவிய மாறி(variable) எல்லா உங்கள் ப்ரோக்ராம் இன் சகல இடங்களிலும் -//அணுக கூடியதாய் அமையும் , இல்லாவிடின் அது ஒரு குறிபிட்ட இடத்திற்கு மட்டும் +// ...ஆனால் நீங்கள் நிறுவிய மாறி(variable) எல்லா உங்கள் ப்ரோக்ராம் இன் சகல இடங்களிலும் +//அணுக கூடியதாய் அமையும் , இல்லாவிடின் அது ஒரு குறிபிட்ட இடத்திற்கு மட்டும் //மட்டுபடுத்தபடும் . -//பெறுமானம் வழங்கபடாத மாறிகளுக்கு ,இயல்பாக/தானாக undefined என்ற பெறுமானம் -//வழங்கப்படும் +//பெறுமானம் வழங்கபடாத மாறிகளுக்கு ,இயல்பாக/தானாக undefined என்ற பெறுமானம் +//வழங்கப்படும் var someThirdVar; // = undefined // மாறிகளில் கணித செயல்பாடுகளை நடத்த சுருக்கெழுத்து முறைகள் காணப்படுகின்றன : someVar += 5; // இது someVar = someVar + 5; ஐ ஒத்தது someVar இன் பெறுமானம் இப்போது 10 someVar *= 10; // someVar இன் பெறுமானம் இப்போது 100 -//மிகவும் சுருக்கமான சுருகேழுத்து முறை கூட்டல் அல்லது கழித்தல் செயன்முறையை -//மேற்கொள்ள +//மிகவும் சுருக்கமான சுருகேழுத்து முறை கூட்டல் அல்லது கழித்தல் செயன்முறையை +//மேற்கொள்ள someVar++; // someVar இன் பெறுமானம் இப்போது is 101 someVar--; // someVar இன் பெறுமானம் இப்போது 100 -// அணிகள்(Arrays) எல்லாவகையான பெறுமானங்களையும் உள்ளடக்க கூடியது +// அணிகள்(Arrays) எல்லாவகையான பெறுமானங்களையும் உள்ளடக்க கூடியது var myArray = ["Hello", 45, true]; -// அணிகள்(Arrays) உறுப்பினர்கள் சதுர அடைப்புக்குறிக்குள் அதன் தான இலக்கத்தை கொண்டு +// அணிகள்(Arrays) உறுப்பினர்கள் சதுர அடைப்புக்குறிக்குள் அதன் தான இலக்கத்தை கொண்டு //அணுகமுடியும் . // அணிகளில் உள்ள உறுப்புகள் 0 இருந்து ஆரம்பமாகும் . myArray[1]; // = 45 @@ -182,47 +178,47 @@ myArray.length; // = 4 // அணியில்(Array) ஒரு குறிப்பிட்ட இடத்தில உள்ள பெறுமானத்தை மாற்ற . myArray[3] = "Hello"; -// JavaScript's பொருள் (objects) அகராதியை ஒத்தன -// ஒழுங்கு படுத்த படாத சேகரிப்பு (collection) ஆகும் இதில் ஒரு சாவியும்(key) +// JavaScript's பொருள் (objects) அகராதியை ஒத்தன +// ஒழுங்கு படுத்த படாத சேகரிப்பு (collection) ஆகும் இதில் ஒரு சாவியும்(key) //அதுக்குரிய பெறுமானமும்(value) காணப்படும் . var myObj = {key1: "Hello", key2: "World"}; // விசைகள் சரங்களை, ஆனால் அவர்கள் சரியான என்றால் மேற்கோள் அவசியம் இல்லை //சாவிகளை உ.ம் : "key" என நிறுவலாம் ஆனால் , மேற்கோள் ஆனது சாவி முன்பே நிறுவபட்டிருப்பின் -//அவசியம் இல்லை -// சாவிகளுக்குரிய பெறுமானங்கள் எந்த வகையாகவும் இருக்கலாம் +//அவசியம் இல்லை +// சாவிகளுக்குரிய பெறுமானங்கள் எந்த வகையாகவும் இருக்கலாம் var myObj = {myKey: "myValue", "my other key": 4}; -//பொருள் பண்புகளை சதுர அடைப்புக்குறிக்குள் அதன் சாவியின் பெயரை (key) கொண்டு +//பொருள் பண்புகளை சதுர அடைப்புக்குறிக்குள் அதன் சாவியின் பெயரை (key) கொண்டு //அணுகமுடியும் , myObj["my other key"]; // = 4 // ... அல்லது புள்ளி குறியீட்டை பயன்படுத்தி ,சாவியின் (key is a valid identifier) -//பெயர் மூலம் அணுக முடியும் +//பெயர் மூலம் அணுக முடியும் myObj.myKey; // = "myValue" -// பொருட்கள்(ஒப்ஜெக்ட்ஸ்) மாற்றபடகூடியான சாவிகளின் பெறுமதிகளை மாற்ற முடியும் அத்துடன் புதிய -//சாவிகளை(keys) இடவும் முடியும் +// பொருட்கள்(ஒப்ஜெக்ட்ஸ்) மாற்றபடகூடியான சாவிகளின் பெறுமதிகளை மாற்ற முடியும் அத்துடன் புதிய +//சாவிகளை(keys) இடவும் முடியும் myObj.myThirdKey = true; -//பெறுமதி வரையறுக்கபடாத ஒரு சாவியினை அணுகும் போது +//பெறுமதி வரையறுக்கபடாத ஒரு சாவியினை அணுகும் போது //அது வெளியிடும் பெறுமதி `undefined`. myObj.myFourthKey; // = undefined /////////////////////////////////// // 3. தர்க்கம் மற்றும் கட்டுப்பாட்டு கட்டமைப்பு -// கீழே காட்டப்பட்டுள்ள தொடரியல் ஜாவா வை ஒத்தது +// கீழே காட்டப்பட்டுள்ள தொடரியல் ஜாவா வை ஒத்தது -// The `if` ஒரு குறித்த தர்க்கம் சரியாயின் -//அல்லது என்ற வடிவமைப்பை +// The `if` ஒரு குறித்த தர்க்கம் சரியாயின் +//அல்லது என்ற வடிவமைப்பை var count = 1; if (count == 3){ - // count இன் பெறுமானம் 3 சமமா என பார்க்கபடுகிறது + // count இன் பெறுமானம் 3 சமமா என பார்க்கபடுகிறது } else if (count == 4){ - // count இன் பெறுமானம் 4க்கு சமமா என பார்க்கபடுகிறது + // count இன் பெறுமானம் 4க்கு சமமா என பார்க்கபடுகிறது } else { - // count ஆனது 3 அல்ல 4 அல்ல எனின் + // count ஆனது 3 அல்ல 4 அல்ல எனின் } // ஒரு குறிப்பிட்ட ஒப்பீடு உண்மையாக இருக்கும் வரை `while`. @@ -230,40 +226,40 @@ while (true){ // இந்த இருக்கும் கூற்றுகள் முடிவிலி தடவை மறுபடி செயற்படுத்தப்படும் ! } -// while போல் அல்லாது do-while ,அவை ஒரு தடவையேனும் அதனுள் உள்ள கூற்றுகள் செயற்படுத்தபடும் +// while போல் அல்லாது do-while ,அவை ஒரு தடவையேனும் அதனுள் உள்ள கூற்றுகள் செயற்படுத்தபடும் var input; do { input = getInput(); } while (!isValid(input)) -// for (loop /சுற்று ) C , ஜாவாவை ஒத்தது +// for (loop /சுற்று ) C , ஜாவாவை ஒத்தது //மாறிக்கு பெறுமானத்தை வழங்கல் , மாறியானது தர்க்கத்தை பூர்த்தி செய்கிறதா என பார்த்தல் , -//சுற்றுக்குள் இருக்கும் கூற்றை செயற்படுதல் +//சுற்றுக்குள் இருக்கும் கூற்றை செயற்படுதல் for (var i = 0; i < 5; i++){ - // இந்த சுற்று 5 தடவைகள் தொடர்ந்து செயற்படுத்தபடும் + // இந்த சுற்று 5 தடவைகள் தொடர்ந்து செயற்படுத்தபடும் } -//for /In சுற்றுகள் prototype சங்கிலியில் உள்ள சகல காரணிகள் ஊடகவும் செல்லும் +//for /In சுற்றுகள் prototype சங்கிலியில் உள்ள சகல காரணிகள் ஊடகவும் செல்லும் var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ description += person[x] + " "; } //ஒரு பொருளில் (Object) இடப்பட்ட பண்புகளை (properties) கருத்தில் கொள்ளும் போது -//குறிப்பிட்ட பண்புகளை அந்த Object கொண்டுள்ளதா என பார்க்க +//குறிப்பிட்ட பண்புகளை அந்த Object கொண்டுள்ளதா என பார்க்க var description = ""; -var person = {fname:"Paul", lname:"Ken", age:18}; +var person = {fname:"Paul", lname:"Ken", age:18}; for (var x in person){ if (person.hasOwnProperty(x)){ description += person[x] + " "; } } -//for /in ஆனது அணியில் உள்ள பண்புகள் ஒழுங்குபடுத்தப்பட்டவிதம் முக்கியம் -//ஆயின் பாவிப்பதை தவிர்க்கவும் ஏனெனில் அது சரியான ஒழுங்கில் -//வெளியீட்டை தரும் என்பது ஐயம் ஆகும் +//for /in ஆனது அணியில் உள்ள பண்புகள் ஒழுங்குபடுத்தப்பட்டவிதம் முக்கியம் +//ஆயின் பாவிப்பதை தவிர்க்கவும் ஏனெனில் அது சரியான ஒழுங்கில் +//வெளியீட்டை தரும் என்பது ஐயம் ஆகும் // && is logical and, || is logical or if (house.size == "big" && house.colour == "blue"){ @@ -298,16 +294,16 @@ switch (grade) { /////////////////////////////////// // 4. Functions, Scope and Closures -// JavaScript இல் functions நிறுவ `function` keyword.பயன்படும் +// JavaScript இல் functions நிறுவ `function` keyword.பயன்படும் function myFunction(thing){ return thing.toUpperCase(); } myFunction("foo"); // = "FOO" -//ஒரு பெறுமானத்தை return செய்ய வேண்டும் எனின் இரண்டும் ஒரே வரியில் -//இருக்க வேண்டும் இல்லாவிடின் return ஆனது `undefined ` return செய்யும் -//காற் புள்ளி தானாகவே இடப்படும் , நீங்கள் Allman style உபயோகிக்கும் போது -//அவதானமாக இருக்கவும் +//ஒரு பெறுமானத்தை return செய்ய வேண்டும் எனின் இரண்டும் ஒரே வரியில் +//இருக்க வேண்டும் இல்லாவிடின் return ஆனது `undefined ` return செய்யும் +//காற் புள்ளி தானாகவே இடப்படும் , நீங்கள் Allman style உபயோகிக்கும் போது +//அவதானமாக இருக்கவும் function myFunction() { return // <- semicolon automatically inserted here @@ -317,20 +313,20 @@ function myFunction() } myFunction(); // = undefined -// JavaScript functions ஆனது first class objects ஆகும் ,எனவே அவற்றை மாறிகளுக்கு -//assign செய்ய முடியும் அதுமட்டும் அல்லது functions களில் arguments ஆக அனுப்பமுடியும் +// JavaScript functions ஆனது first class objects ஆகும் ,எனவே அவற்றை மாறிகளுக்கு +//assign செய்ய முடியும் அதுமட்டும் அல்லது functions களில் arguments ஆக அனுப்பமுடியும் // உதாரணமாக ஒரு event handler: function myFunction(){ - //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் } setTimeout(myFunction, 5000); -// Note: setTimeout ஆனது ஜாவஸ்க்ரிப்ட் சேர்ந்தது அன்று , ஆனால் அந்த வசதி -//உலாவிகளிலும் ,Node .js காணப்படுகிறது +// Note: setTimeout ஆனது ஜாவஸ்க்ரிப்ட் சேர்ந்தது அன்று , ஆனால் அந்த வசதி +//உலாவிகளிலும் ,Node .js காணப்படுகிறது -// Function objects கட்டாயம் பெயரிடப்பட வீண்டும் என்று அவசியம் இல்லை -// அவை anonymous(பெயரிடப்படாமல்) உருவாக்கபடலாம் +// Function objects கட்டாயம் பெயரிடப்பட வீண்டும் என்று அவசியம் இல்லை +// அவை anonymous(பெயரிடப்படாமல்) உருவாக்கபடலாம் setTimeout(function(){ - //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் + //இந்த code 5 செக்கன்களில் செயற்படுத்தப்படும் }, 5000); // JavaScript function ஒரு குறிப்பிட்ட scope(எல்லை) கொண்டுள்ளது ; @@ -339,42 +335,42 @@ setTimeout(function(){ if (true){ var i = 5; } -i; // = 5 - //இது undefined அல்ல +i; // = 5 - //இது undefined அல்ல -// இதன் காரணமாக anonymous functions உடனடியாக செயற்படுத்தபடுகின்றன +// இதன் காரணமாக anonymous functions உடனடியாக செயற்படுத்தபடுகின்றன //இதன் மூலம் தற்காலிக மாறிகள்(variable) குளோபல் scope //இற்கு மாறுவதை தவிர்க்கலாம் . (function(){ var temporary = 5; - //நாங்கள் ஒரு மாறியை எங்கிருந்தும் அணுக (access) அதை "global object" - //ஒன்றுக்கு வழங்க வேண்டும் உலாவியில் அது எப்போதும் `window` ஆகும் . - //உலாவி அல்லாத சூழலில் (Node.js) வேறு பெயருடன் இருக்கும் + //நாங்கள் ஒரு மாறியை எங்கிருந்தும் அணுக (access) அதை "global object" + //ஒன்றுக்கு வழங்க வேண்டும் உலாவியில் அது எப்போதும் `window` ஆகும் . + //உலாவி அல்லாத சூழலில் (Node.js) வேறு பெயருடன் இருக்கும் window.permanent = 10; })(); temporary; // raises ReferenceError permanent; // = 10 -//JavaScript's மிகவும் சக்தி வாய்ந்த ஒரு வசதி closures ஆகும் +//JavaScript's மிகவும் சக்தி வாய்ந்த ஒரு வசதி closures ஆகும் //ஒரு function இன்னொரு function உள் உருவாக்கபடின் -//அது உருவாகப்பட்ட function இன் மாறிகளை அணுக முடியும் +//அது உருவாகப்பட்ட function இன் மாறிகளை அணுக முடியும் function sayHelloInFiveSeconds(name){ var prompt = "Hello, " + name + "!"; - // Inner functions ஆனது local scope இல் காணப்படும் - //அது `var ` என்ற குறியீட்டு சொல்லால் நிறுவப்படும் + // Inner functions ஆனது local scope இல் காணப்படும் + //அது `var ` என்ற குறியீட்டு சொல்லால் நிறுவப்படும் function inner(){ alert(prompt); } setTimeout(inner, 5000); //setTimeout ஆனது background இல் இயங்கும் , எனவே sayHelloInFiveSeconds function, - //செயற்பாடு முடிவடைய ,setTimeout ஆனது inner function call செய்யும். + //செயற்பாடு முடிவடைய ,setTimeout ஆனது inner function call செய்யும். } -sayHelloInFiveSeconds("Adam"); // //இது ஒரு popup ஐ ஐந்து செக்கன்களில் காட்டும் +sayHelloInFiveSeconds("Adam"); // //இது ஒரு popup ஐ ஐந்து செக்கன்களில் காட்டும் /////////////////////////////////// -// 5. Objects; Constructors and Prototypes பற்றி மேலும் +// 5. Objects; Constructors and Prototypes பற்றி மேலும் -// Objects functions ஐ கொண்டிருக்கலாம் +// Objects functions ஐ கொண்டிருக்கலாம் var myObj = { myFunc: function(){ return "Hello world!"; @@ -382,8 +378,8 @@ var myObj = { }; myObj.myFunc(); // = "Hello world!" -//functions ஆனது objects உடன் இணைக்கப்பட்டுள போது அவை object ஐ அணுக முடியும் -//அவை this என்ற குறியீட்டு சொல்லை பயன்படுத்தி இணைக்கபடுகின்றன +//functions ஆனது objects உடன் இணைக்கப்பட்டுள போது அவை object ஐ அணுக முடியும் +//அவை this என்ற குறியீட்டு சொல்லை பயன்படுத்தி இணைக்கபடுகின்றன myObj = { myString: "Hello world!", myFunc: function(){ @@ -392,20 +388,20 @@ myObj = { }; myObj.myFunc(); // = "Hello world!" -//எங்கள் function ஆனது தொழிற் படாமல் போகலாம் அது context(அமைப்பு ) of the object call செய்யபடவிடின் +//எங்கள் function ஆனது தொழிற் படாமல் போகலாம் அது context(அமைப்பு ) of the object call செய்யபடவிடின் var myFunc = myObj.myFunc; myFunc(); // = undefined -//function ஆனது ஒரு object உக்கு assign செய்யலாம் பிறகு அதை நாம் அணுகமுடியும் -//`this` மூலம் +//function ஆனது ஒரு object உக்கு assign செய்யலாம் பிறகு அதை நாம் அணுகமுடியும் +//`this` மூலம் var myOtherFunc = function(){ return this.myString.toUpperCase(); } myObj.myOtherFunc = myOtherFunc; myObj.myOtherFunc(); // = "HELLO WORLD!" -//ஒரு function ஒரு அமைப்பை நாம் உருவாக்க முடியும் +//ஒரு function ஒரு அமைப்பை நாம் உருவாக்க முடியும் //அதை நாம் `call` அல்லது `apply` மூலம் செயல்படுத்த முடியும் var anotherFunc = function(s){ @@ -413,34 +409,34 @@ var anotherFunc = function(s){ } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -//apply செயற்பாட்டளவில் ஒத்தன ,ஆனால் அது array (அணி) argument +//apply செயற்பாட்டளவில் ஒத்தன ,ஆனால் அது array (அணி) argument //ஆக எடுக்கிறது. anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" -//இது தொடர்ச்சியான arguments ஐ நாம் function ஒன்றுக்குள் pass பண்ண -//வேண்டும் எனில் மிகவும் உபயோகமானது +//இது தொடர்ச்சியான arguments ஐ நாம் function ஒன்றுக்குள் pass பண்ண +//வேண்டும் எனில் மிகவும் உபயோகமானது Math.min(42, 6, 27); // = 6 Math.min([42, 6, 27]); // = NaN (uh-oh!) Math.min.apply(Math, [42, 6, 27]); // = 6 -//ஆனால் `call ` ,`apply ` இரண்டும் தற்காலிகமானவை -//அவற்றை நிரந்தரமாக்க bind function ஐ பயன்படுத்தவும் +//ஆனால் `call ` ,`apply ` இரண்டும் தற்காலிகமானவை +//அவற்றை நிரந்தரமாக்க bind function ஐ பயன்படுத்தவும் var boundFunc = anotherFunc.bind(myObj); boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" -//`bind ` ஐ உபயோகித்து ஒரு function ஐ பகுதியாக apply செய்ய முடியும் +//`bind ` ஐ உபயோகித்து ஒரு function ஐ பகுதியாக apply செய்ய முடியும் var product = function(a, b){ return a * b; } var doubler = product.bind(this, 2); doubler(8); // = 16 -//ஒரு function ஐ நாம் new என்ற குறியீட்டு சொல்லை பயன்படுத்தி -//அழைக்கும் போது புதிய object உருவாக்கப்படும் .இவ்வாறான functions -//constructors என அழைக்கப்படும் +//ஒரு function ஐ நாம் new என்ற குறியீட்டு சொல்லை பயன்படுத்தி +//அழைக்கும் போது புதிய object உருவாக்கப்படும் .இவ்வாறான functions +//constructors என அழைக்கப்படும் var MyConstructor = function(){ this.myNumber = 5; @@ -448,15 +444,15 @@ var MyConstructor = function(){ myNewObj = new MyConstructor(); // = {myNumber: 5} myNewObj.myNumber; // = 5 -//ஒவ்வொரு JavaScript object உம் ஒரு `prototype ` கொண்டுள்ளது -//நீங்கள் object ஒன்றின் ஒரு property ஐ அணுகும் போது -//அந்த property இல்லாவிடின் interpreter ஆனது -//அதன் prototype உள்ளதா என பார்க்கும் +//ஒவ்வொரு JavaScript object உம் ஒரு `prototype ` கொண்டுள்ளது +//நீங்கள் object ஒன்றின் ஒரு property ஐ அணுகும் போது +//அந்த property இல்லாவிடின் interpreter ஆனது +//அதன் prototype உள்ளதா என பார்க்கும் -//JS இன் சில செயலாக்கங்கள் ஒரு object இன் protoype ஐ +//JS இன் சில செயலாக்கங்கள் ஒரு object இன் protoype ஐ //இலகுவாக `__proto__` மூலம் access செய்ய முடியும் . -//இது prototype பாவணை யை இலகுவாக்கினாலும் -//இது சரியான ஒரு முறை அல்ல +//இது prototype பாவணை யை இலகுவாக்கினாலும் +//இது சரியான ஒரு முறை அல்ல var myObj = { myString: "Hello world!" }; @@ -473,21 +469,21 @@ myObj.meaningOfLife; // = 42 // This works for functions, too. myObj.myFunc(); // = "hello world!" -//உங்கள் property prototype இல் இல்லது இருப்பின் , protype இன் -//prototype search செய்யப்படும் +//உங்கள் property prototype இல் இல்லது இருப்பின் , protype இன் +//prototype search செய்யப்படும் myPrototype.__proto__ = { myBoolean: true }; myObj.myBoolean; // = true -//ஒவ்வொரு object உம் அதன் protype க்கும் reference (மேற்கோள் ) ஒன்றை வைத்திருக்கும் +//ஒவ்வொரு object உம் அதன் protype க்கும் reference (மேற்கோள் ) ஒன்றை வைத்திருக்கும் //நாம் ஒரு protype இணை மாற்றினால் அதன் மாற்றங்கள் எல்லா இடத்திலும் (program இல் ) -//பிரதிபலிக்கும் +//பிரதிபலிக்கும் myPrototype.meaningOfLife = 43; myObj.meaningOfLife; // = 43 - -//நாம் முன்பு கூறியது போல் `__proto__` பயன்படுத்துவது சரியான முறை அல்ல + +//நாம் முன்பு கூறியது போல் `__proto__` பயன்படுத்துவது சரியான முறை அல்ல //எனவே நாம் ஒரு protype ஐ object இல் உருவாக்க இரண்டு வழிமுறைகள் //உள்ளன @@ -550,7 +546,7 @@ String.prototype.firstCharacter = function(){ //இது பழைய சூழல்களில் உபயோகிகப்படும். -//நாங்கள் முன்பு கூறி இருந்தோம் Object.create சில இடங்களில் இந்த முறை இன்னும் +//நாங்கள் முன்பு கூறி இருந்தோம் Object.create சில இடங்களில் இந்த முறை இன்னும் //அறிமுகம் ஆகவில்லை என்று ஆனால் இதை polyfill ஐ பயன்படுத்தி உருவாக்க //முடியும் diff --git a/tr-tr/csharp-tr.html.markdown b/tr-tr/csharp-tr.html.markdown index 9834be20..e9dae611 100644 --- a/tr-tr/csharp-tr.html.markdown +++ b/tr-tr/csharp-tr.html.markdown @@ -9,17 +9,14 @@ translators: - ["Melih Mucuk", "http://melihmucuk.com"] lang: tr-tr filename: LearnCSharp-tr.cs - --- C# zarif ve tip güvenli nesne yönelimli bir dil olup geliştiricilerin .NET framework üzerinde çalışan güçlü ve güvenli uygulamalar geliştirmesini sağlar. -[Yazım yanlışları ve öneriler için bana ulaşabilirsiniz](mailto:melihmucuk@gmail.com) - [Daha fazlasını okuyun.](http://msdn.microsoft.com/en-us/library/vstudio/z1zx9t92.aspx) ```c# -// Tek satırlık yorumlar // ile başlar +// Tek satırlık yorumlar // ile başlar /* Birden fazla satırlı yorumlar buna benzer */ @@ -46,7 +43,7 @@ namespace Learning public class LearnCSharp { // TEMEL SÖZ DİZİMİ - daha önce Java ya da C++ kullandıysanız İLGİNÇ ÖZELLİKLER'e geçin - public static void Syntax() + public static void Syntax() { // Satırları yazdırmak için Console.WriteLine kullanın Console.WriteLine("Merhaba Dünya"); @@ -111,7 +108,7 @@ namespace Learning string fooString = "\"escape\" quotes and add \n (new lines) and \t (tabs)"; Console.WriteLine(fooString); - // İndeks numarası kullanarak bir string'in bütün karakterlerine erişilebilirsiniz: + // İndeks numarası kullanarak bir string'in bütün karakterlerine erişilebilirsiniz: char charFromString = fooString[1]; // => 'e' // String'ler değiştirilemez: fooString[1] = 'X' işlemini yapamazsınız; @@ -129,7 +126,7 @@ namespace Learning string bazString = @"Here's some stuff on a new line! ""Wow!"", the masses cried"; - // Bir değişkeni değiştirilemez yapmak için const ya da read-only kullanın. + // Bir değişkeni değiştirilemez yapmak için const ya da read-only kullanın. // const değerleri derleme sırasında hesaplanır const int HOURS_I_WORK_PER_WEEK = 9001; @@ -357,7 +354,7 @@ on a new line! ""Wow!"", the masses cried"; // // İLGİNÇ ÖZELLİKLER // - + // VARSAYILAN METOD TANIMLAMALARI public // Görünebilir @@ -369,7 +366,7 @@ on a new line! ""Wow!"", the masses cried"; int another = 3, params string[] otherParams // Metoda gönderilen diğer bütün parametreleri alır ) - { + { return -1; } @@ -382,8 +379,8 @@ on a new line! ""Wow!"", the masses cried"; // TKey ve TValue değerleri kullanıcı tarafından bu fonksiyon çağırılırken belirtilir. // Bu metod Python'daki SetDefault'a benzer public static TValue SetDefault( - IDictionary dictionary, - TKey key, + IDictionary dictionary, + TKey key, TValue defaultItem) { TValue result; @@ -428,7 +425,7 @@ on a new line! ""Wow!"", the masses cried"; // GENERIC'LER // - var phonebook = new Dictionary() { + var phonebook = new Dictionary() { {"Sarah", "212 555 5555"} // Telefon rehberine bir kaç numara ekleyelim. }; @@ -449,19 +446,19 @@ on a new line! ""Wow!"", the masses cried"; writer.WriteLine("Nothing suspicious here"); // Bu bölümün sonunda kaynaklar temilenir. // Hata fırlatılmış olsa bile. - } + } // PARALEL FRAMEWORK // http://blogs.msdn.com/b/csharpfaq/archive/2010/06/01/parallel-programming-in-net-framework-4-getting-started.aspx - var websites = new string[] { - "http://www.google.com", "http://www.reddit.com", + var websites = new string[] { + "http://www.google.com", "http://www.reddit.com", "http://www.shaunmccarthy.com" }; var responses = new Dictionary(); - - // Her istek farklı bir thread de işlem görecek + + // Her istek farklı bir thread de işlem görecek // bir sonraki işleme geçmeden birleştirilecek. - Parallel.ForEach(websites, + Parallel.ForEach(websites, new ParallelOptions() {MaxDegreeOfParallelism = 3}, // en fazla 3 thread kullanmak için website => { @@ -506,7 +503,7 @@ on a new line! ""Wow!"", the masses cried"; // ASPARALLEL // Linq ve paralel işlemlerini birleştirme var threeWheelers = bikes.AsParallel().Where(b => b.Wheels == 3).Select(b => b.Name); - // bu paralel bir şekilde gerçekleşecek! Threadler otomatik ve sihirli bir şekilde işleri paylaşacak! + // bu paralel bir şekilde gerçekleşecek! Threadler otomatik ve sihirli bir şekilde işleri paylaşacak! // Birden fazla çekirdeğiniz varsa büyük veri setleri ile kullanmak için oldukça uygun bir yapı. // LINQ - IQueryable objelerini mapler ve saklar, gecikmeli bir işlemdir @@ -524,9 +521,9 @@ on a new line! ""Wow!"", the masses cried"; .Select(b => b.Name); // hala sorgu çalışmadı // Şimdi sorgu çalışıyor, reader'ı açar ama sadece sizin sorgunuza uyanlar foreach döngüsüne girer. - foreach (string bike in query) + foreach (string bike in query) Console.WriteLine(result); - + } @@ -609,7 +606,7 @@ on a new line! ""Wow!"", the masses cried"; // Kurucular sınıf oluşturmanın bir yoludur // Bu bir varsayılan kurucudur. - public Bicycle() + public Bicycle() { this.Gear = 1; // bu objenin üyelerine this anahtar kelimesi ile ulaşılır Cadence = 50; // ama her zaman buna ihtiyaç duyulmaz @@ -621,13 +618,13 @@ on a new line! ""Wow!"", the masses cried"; // Bu belirlenmiş bir kurucudur. (argümanlar içerir) public Bicycle(int startCadence, int startSpeed, int startGear, - string name, bool hasCardsInSpokes, BikeBrand brand) + string name, bool hasCardsInSpokes, BikeBrand brand) : base() // önce base'i çağırın { - Gear = startGear; + Gear = startGear; Cadence = startCadence; _speed = startSpeed; - Name = name; + Name = name; _hasCardsInSpokes = hasCardsInSpokes; Brand = brand; } @@ -666,7 +663,7 @@ on a new line! ""Wow!"", the masses cried"; set { _hasTassles = value; } } - // Ayrıca tek bir satırda otomatik property tanımlayabilirsiniz. + // Ayrıca tek bir satırda otomatik property tanımlayabilirsiniz. // bu söz dizimi otomatik olarak alan oluşturacaktır. // Erişimi kısıtlamak için nitelik belirleyiciler getter veya setter'a ya da ikisine birden atanabilir: public bool IsBroken { get; private set; } @@ -819,7 +816,4 @@ on a new line! ""Wow!"", the masses cried"; * [ASP.NET Web Matrix Tutorials](http://www.asp.net/web-pages/tutorials) * [ASP.NET Web Forms Tutorials](http://www.asp.net/web-forms/tutorials) * [Windows Forms Programming in C#](http://www.amazon.com/Windows-Forms-Programming-Chris-Sells/dp/0321116208) - - - -[C# Kodlama Adetleri](http://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx) + * [C# Kodlama Adetleri](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions) diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index 45e30932..d637c21c 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -16,10 +16,6 @@ Javascript 于 1995 年由网景公司的 Brendan Eich 发明。最初它作为 不过,Javascript 不仅用于网页浏览器,一个名为 Node.js 的项目提供了面向 Google Chrome V8 引擎的独立运行时环境,它正在变得越来越流行。 -很欢迎来自您的反馈,您可以通过下列方式联系到我: -[@ExcitedLeigh](https://twitter.com/ExcitedLeigh), 或者 -[l@leigh.net.au](mailto:l@leigh.net.au). - ```js // 注释方式和C很像,这是单行注释 /* 这是多行 @@ -83,7 +79,7 @@ false; 1 !== 1; // = false 2 !== 1; // = true -// 更多的比较操作符 +// 更多的比较操作符 1 < 10; // = true 1 > 10; // = false 2 <= 2; // = true @@ -101,7 +97,7 @@ null == undefined; // = true // ...除非你是用 === "5" === 5; // = false -null === undefined; // = false +null === undefined; // = false // ...但会导致奇怪的行为 13 + !0; // 14 @@ -127,7 +123,7 @@ undefined; // 用来表示还没有设置的值(尽管`undefined`自身实际是 // 2. 变量、数组和对象 // 变量需要用`var`关键字声明。Javascript是动态类型语言, -// 所以你无需指定类型。 赋值需要用 `=` +// 所以你无需指定类型。 赋值需要用 `=` var someVar = 5; // 如果你在声明时没有加var关键字,你也不会得到错误... @@ -139,7 +135,7 @@ someOtherVar = 10; var someThirdVar; // = undefined // 对变量进行数学运算有一些简写法: -someVar += 5; // 等价于 someVar = someVar + 5; someVar 现在是 10 +someVar += 5; // 等价于 someVar = someVar + 5; someVar 现在是 10 someVar *= 10; // 现在 someVar 是 100 // 自增和自减也有简写 @@ -191,7 +187,7 @@ if (count == 3){ } else if (count == 4){ // count 是 4 时执行 } else { - // 其他情况下执行 + // 其他情况下执行 } // while循环 @@ -219,12 +215,12 @@ if (colour == "red" || colour == "blue"){ // colour是red或者blue时执行 } -// && 和 || 是“短路”语句,它在设定初始化值时特别有用 +// && 和 || 是“短路”语句,它在设定初始化值时特别有用 var name = otherName || "default"; // `switch`语句使用`===`检查相等性。 // 在每一个case结束时使用 'break' -// 否则其后的case语句也将被执行。 +// 否则其后的case语句也将被执行。 grade = 'B'; switch (grade) { case 'A': @@ -286,7 +282,7 @@ i; // = 5 - 并非我们在其他语言中所期望得到的undefined (function(){ var temporary = 5; // 我们可以访问修改全局对象("global object")来访问全局作用域, - // 在web浏览器中是`window`这个对象。 + // 在web浏览器中是`window`这个对象。 // 在其他环境如Node.js中这个对象的名字可能会不同。 window.permanent = 10; })(); diff --git a/zh-cn/matlab-cn.html.markdown b/zh-cn/matlab-cn.html.markdown index b74b153f..009020ff 100644 --- a/zh-cn/matlab-cn.html.markdown +++ b/zh-cn/matlab-cn.html.markdown @@ -7,16 +7,11 @@ contributors: translators: - ["sunxb10", "https://github.com/sunxb10"] lang: zh-cn - --- MATLAB 是 MATrix LABoratory(矩阵实验室)的缩写。 它是一种功能强大的数值计算语言,在工程和数学领域中应用广泛。 -如果您有任何需要反馈或交流的内容,请联系本教程作者: -[@the_ozzinator](https://twitter.com/the_ozzinator) -或 [osvaldo.t.mendoza@gmail.com](mailto:osvaldo.t.mendoza@gmail.com)。 - ```matlab % 以百分号作为注释符 @@ -68,10 +63,10 @@ disp('text') % 在命令窗口中显示 "text" % 变量与表达式 myVariable = 4 % 命令窗口中将新创建的变量 myVariable = 4; % 加上分号可使命令窗口中不显示当前语句执行结果 -4 + 6 % ans = 10 -8 * myVariable % ans = 32 -2 ^ 3 % ans = 8 -a = 2; b = 3; +4 + 6 % ans = 10 +8 * myVariable % ans = 32 +2 ^ 3 % ans = 8 +a = 2; b = 3; c = exp(a)*sin(pi/2) % c = 7.3891 @@ -114,7 +109,7 @@ b(2) % ans = 符 % 元组(cell 数组) -a = {'one', 'two', 'three'} +a = {'one', 'two', 'three'} a(1) % ans = 'one' - 返回一个元组 a{1} % ans = one - 返回一个字符串 @@ -126,7 +121,7 @@ A.d.e = false; % 向量 -x = [4 32 53 7 1] +x = [4 32 53 7 1] x(2) % ans = 32,MATLAB中向量的下标索引从1开始,不是0 x(2:3) % ans = 32 53 x(2:end) % ans = 32 53 7 1 @@ -137,7 +132,7 @@ x = [1:10] % x = 1 2 3 4 5 6 7 8 9 10 % 矩阵 -A = [1 2 3; 4 5 6; 7 8 9] +A = [1 2 3; 4 5 6; 7 8 9] % 以分号分隔不同的行,以空格或逗号分隔同一行中的不同元素 % A = @@ -146,7 +141,7 @@ A = [1 2 3; 4 5 6; 7 8 9] % 7 8 9 A(2,3) % ans = 6,A(row, column) -A(6) % ans = 8 +A(6) % ans = 8 % (隐式地将 A 的三列首尾相接组成一个列向量,然后取其下标为 6 的元素) @@ -185,7 +180,7 @@ A(1,:) % 第 1 行的所有元素 % 4 5 42 % 7 8 9 -% 等价于 +% 等价于 vertcat(A, A); @@ -226,7 +221,7 @@ A .* B % 元素乘法,要求 A 和 B 形状一致,即两矩阵行列数完 % 元素乘法的结果是与 A 和 B 形状一致的矩阵 % 其每个元素等于 A 对应位置的元素乘 B 对应位置的元素 -% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算: +% 以下函数中,函数名以 m 结尾的执行矩阵运算,其余执行元素运算: exp(A) % 对矩阵中每个元素做指数运算 expm(A) % 对矩阵整体做指数运算 sqrt(A) % 对矩阵中每个元素做开方运算 @@ -290,7 +285,7 @@ clf clear % 清除图形窗口中的图像,并重置图像属性 % 图像属性可以通过图像句柄进行设定 % 在创建图像时可以保存图像句柄以便于设置 -% 也可以用 gcf 函数返回当前图像的句柄 +% 也可以用 gcf 函数返回当前图像的句柄 h = plot(x, y); % 在创建图像时显式地保存图像句柄 set(h, 'Color', 'r') % 颜色代码: @@ -323,8 +318,8 @@ cd /path/to/move/into % 以制定路径作为当前工作目录 % 变量可保存到 .mat 格式的本地文件 -save('myFileName.mat') % 保存当前工作空间中的所有变量 -load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 +save('myFileName.mat') % 保存当前工作空间中的所有变量 +load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 % .m 脚本文件 @@ -339,11 +334,11 @@ load('myFileName.mat') % 将指定文件中的变量载入到当前工作空间 % 函数文件的名称应当与其所定义的函数的名称一致 % 比如下面例子中函数文件就应命名为 double_input.m % 使用 'help double_input.m' 可返回函数定义中第一行注释信息 -function output = double_input(x) +function output = double_input(x) % double_input(x) 返回 x 的 2 倍 output = 2*x; end -double_input(6) % ans = 12 +double_input(6) % ans = 12 % 同样还可以定义子函数和内嵌函数 @@ -389,8 +384,8 @@ end for k = 1:5 disp(k) end - -k = 0; + +k = 0; while (k < 5) k = k + 1; end @@ -411,7 +406,7 @@ driver = 'com.mysql.jdbc.Driver'; dburl = ['jdbc:mysql://localhost:8889/' dbname]; javaclasspath('mysql-connector-java-5.1.xx-bin.jar'); % 此处 xx 代表具体版本号 % 这里的 mysql-connector-java-5.1.xx-bin.jar 可从 http://dev.mysql.com/downloads/connector/j/ 下载 -conn = database(dbname, username, password, driver, dburl); +conn = database(dbname, username, password, driver, dburl); sql = ['SELECT * from table_name where id = 22'] % SQL 语句 a = fetch(conn, sql) % a 即包含所需数据 @@ -423,7 +418,7 @@ tan(x) asin(x) acos(x) atan(x) -exp(x) +exp(x) sqrt(x) log(x) log10(x) @@ -456,7 +451,7 @@ pinv(A) % 伪逆矩阵 zeros(m, n) % m x n 阶矩阵,元素全为 0 ones(m, n) % m x n 阶矩阵,元素全为 1 diag(A) % 返回矩阵 A 的对角线元素 -diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素 +diag(x) % 构造一个对角阵,对角线元素就是向量 x 的各元素 eye(m, n) % m x n 阶单位矩阵 linspace(x1, x2, n) % 返回介于 x1 和 x2 之间的 n 个等距节点 inv(A) % 矩阵 A 的逆矩阵 @@ -485,14 +480,14 @@ flipud(A) % 将一个矩阵上下翻转 % 常用向量函数 max % 最大值 -min % 最小值 +min % 最小值 length % 元素个数 -sort % 按升序排列 -sum % 各元素之和 +sort % 按升序排列 +sum % 各元素之和 prod % 各元素之积 mode % 众数 -median % 中位数 -mean % 平均值 +median % 中位数 +mean % 平均值 std % 标准差 perms(x) % x 元素的全排列 ``` diff --git a/zh-cn/red-cn.html.markdown b/zh-cn/red-cn.html.markdown index a0abce6e..96ab117b 100644 --- a/zh-cn/red-cn.html.markdown +++ b/zh-cn/red-cn.html.markdown @@ -198,7 +198,7 @@ Red 相关的源码信息在 [Red 语言主页](https://www.red-lang.org)。 Red/System 特性在 [这里](https://static.red-lang.org/red-system-specs-light.html)。 -想要了解更多关于 Rebol 和 Red 的信息,加入 [Gitter 聊天室](https://gitter.im/red/red)。如果你无法加入,也可以给我们发[邮件](mailto:red-langNO_SPAM@googlegroups.com)。 +想要了解更多关于 Rebol 和 Red 的信息,加入 [Gitter 聊天室](https://gitter.im/red/red)。 也可以在 [Stack Overflow](https://stackoverflow.com/questions/tagged/red) 上查阅、提交问题。 From f18b36c3bff0082f08524718481f21e36a244ac1 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 3 Jun 2024 05:37:35 -0600 Subject: [PATCH 271/392] [lua/*] remove HTML tags --- de-de/lua-de.html.markdown | 25 +- es-es/lua.html.markdown | 8 +- fr-fr/lua-fr.html.markdown | 44 +-- ko-kr/lua-kr.html.markdown | 46 ++-- lua.html.markdown | 26 +- pt-br/lua-pt.html.markdown | 22 +- ru-ru/lua-ru.html.markdown | 22 +- zh-cn/lua-cn.html.markdown | 534 ++++++++++++++++++------------------- 8 files changed, 361 insertions(+), 366 deletions(-) diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown index 161b0493..b4b5f2c1 100644 --- a/de-de/lua-de.html.markdown +++ b/de-de/lua-de.html.markdown @@ -21,7 +21,7 @@ lang: de-de num = 42 -- Alle Nummern sind vom Typ: Double. -- Werd nicht nervös, 64-Bit Double haben 52 Bits zum Speichern von exakten --- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als +-- Ganzzahlen; Maschinen-Genauigkeit ist kein Problem für Ganzzahlen kleiner als -- 52 Bit. s = 'walternate' -- Zeichenketten sind unveränderlich, wie bei Python. @@ -404,23 +404,22 @@ g() -- Ausgabe 343; Vorher kam keine Ausgabe. ## Referenzen -Ich war so begeistert Lua zu lernen, damit ich Spiele mit Love 2D game engine programmieren konnte. +Ich war so begeistert Lua zu lernen, damit ich Spiele mit [LÖVE game engine](http://love2d.org/) programmieren konnte. -Ich habe angefangen mit BlackBulletIV's Lua for programmers. -Danach habe ich das offizielle Lua Buch gelesen: Programming in Lua +Ich habe angefangen mit [BlackBulletIV's Lua for programmers](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/). +Danach habe ich das offizielle Lua Buch gelesen: [Programming in Lua](http://www.lua.org/pil/contents.html) -Es kann auch hilfreich sein hier vorbeizuschauen: Lua short -reference +Es kann auch hilfreich sein hier vorbeizuschauen: [Lua short reference](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf) Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken: -* string library -* table library -* math library -* io library -* os library +* [`string` library](http://lua-users.org/wiki/StringLibraryTutorial) +* [`table` library](http://lua-users.org/wiki/TableLibraryTutorial) +* [`math` library](http://lua-users.org/wiki/MathLibraryTutorial) +* [`io` library](http://lua-users.org/wiki/IoLibraryTutorial) +* [`os` library](http://lua-users.org/wiki/OsLibraryTutorial) Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und -starte sie als "lua learn.lua" ! +starte sie als "`lua learn.lua`" ! -Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: GitHub gist. Viel Spaß mit Lua! +Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: [GitHub gist](https://gist.github.com/tylerneylon/5853042). Viel Spaß mit Lua! diff --git a/es-es/lua.html.markdown b/es-es/lua.html.markdown index 6fc997f7..05266d27 100644 --- a/es-es/lua.html.markdown +++ b/es-es/lua.html.markdown @@ -419,7 +419,7 @@ g() -- Imprime '343', nada es impreso antes de esto. ## Referencias Estaba emocionado por aprender lua para poder crear juegos -con el motor de juegos [Love 2D](http://love2d.org/). Ese es el por qué. +con el motor de juegos [LÖVE](http://love2d.org/). Ese es el por qué. Empecé con [BlackBulletIV para programadores Lua](https://ebens.me/posts/lua-for-programmers-part-1/). Luego, leí el libro oficial de [Programación en Lua](http://www.lua.org/pil/contents.html). @@ -433,10 +433,10 @@ Los principales temas no cubiertos son las librerías estándar: * [Librería de strings](http://lua-users.org/wiki/StringLibraryTutorial) * [Librería de tablas](http://lua-users.org/wiki/TableLibraryTutorial) * [Librería de matemáticas](http://lua-users.org/wiki/MathLibraryTutorial) -* [Librería de Entrada/Salida (io)](http://lua-users.org/wiki/IoLibraryTutorial) -* [Libreria de Sistema Operativo (os)](http://lua-users.org/wiki/OsLibraryTutorial) +* [Librería de Entrada/Salida (`io`)](http://lua-users.org/wiki/IoLibraryTutorial) +* [Libreria de Sistema Operativo (`os`)](http://lua-users.org/wiki/OsLibraryTutorial) Por cierto, el archivo entero es código Lua válido. ¡Guárdelo como -aprendiendo.lua y ejecútelo con el comando "lua aprendiendo.lua" ! +aprendiendo.lua y ejecútelo con el comando "`lua aprendiendo.lua`" ! ¡Que se divierta con lua! diff --git a/fr-fr/lua-fr.html.markdown b/fr-fr/lua-fr.html.markdown index 4191ec74..b6d1c8ea 100644 --- a/fr-fr/lua-fr.html.markdown +++ b/fr-fr/lua-fr.html.markdown @@ -12,7 +12,7 @@ lang: fr-fr -- Les commentaires unilignes commencent par un double tiret. --[[ - Les doubles crochets à la suite du double tiret + Les doubles crochets à la suite du double tiret permettent d'insérer des commentaires multilignes. --]] @@ -123,7 +123,7 @@ end x, y = bar('zaphod') --> affiche "zaphod nil nil" -- x = 4, y = 8, les valeurs 15 à 42 sont ignorées. --- Les fonctions sont des valeurs de première classe +-- Les fonctions sont des valeurs de première classe -- et peuvent être locales/globales. -- Les déclarations suivantes sont identiques: function f(x) return x * x end @@ -139,7 +139,7 @@ local g = function(x) return math.sin(x) end -- À moins de déclarer la fonction auparavant: local g; g = function (x) return math.sin(x) end --- À propos, les fonctions trigonométriques interprètent +-- À propos, les fonctions trigonométriques interprètent -- leurs arguments en radians. print(math.cos(math.pi)) -- affiche "-1" print(math.sin(math.pi)) -- affiche "0" @@ -250,7 +250,7 @@ myFavs = {food = 'pizza'} setmetatable(myFavs, {__index = defaultFavs}) eatenBy = myFavs.animal -- Affiche "gru"! merci à la métatable! --- Ainsi donc, un accès direct à une valeur dans une table via une clé +-- Ainsi donc, un accès direct à une valeur dans une table via une clé -- inexistante (ce qui normalement retourne "nil") conduira à exploiter -- le champ __index de la métatable. Cela peut être récursif. @@ -281,7 +281,7 @@ eatenBy = myFavs.animal -- Affiche "gru"! merci à la métatable! ---------------------------------------------------- -- Lua n'implémente pas d'orienté objet par défaut. --- Mais il reste possible d'imiter de plusieurs manières +-- Mais il reste possible d'imiter de plusieurs manières -- le concept de "classe" grâce aux tables et aux métatables. -- L'explication pour l'exemple qui suit vient juste après. @@ -302,9 +302,9 @@ mrDog = Dog:new() -- 7. mrDog:makeSound() -- 'Je dis: woof! -- 8. -- 1. Dog agit comme une classe; c'est une simple table. --- 2. L'expression tbl:fn(...) est identique à +-- 2. L'expression tbl:fn(...) est identique à -- tbl.fn(self, ...) --- La notation : permet de passer par défaut un premier +-- La notation : permet de passer par défaut un premier -- argument appelé "self" à la fonction tbl.fn -- Voir 7 & 8 ci-après pour comprendre comment self prend -- sa valeur. @@ -388,7 +388,7 @@ local mod = (function () end)() -- Comme si le contenu de mod.lua était enveloppé dans le corps d'une fonction, --- si bien que les variables locales contenues dans mod.lua sont +-- si bien que les variables locales contenues dans mod.lua sont -- inaccessibles en dehors de ce module. -- Le code suivant fonctionne car mod = M (dans mod.lua): @@ -423,27 +423,27 @@ g() -- Affiche 343; Rien n'est affiché avant cet appel. *Les références qui suivent sont en Anglais.* -Les sujets non abordés dans ce tutoriel sont couverts en intégralité par +Les sujets non abordés dans ce tutoriel sont couverts en intégralité par les librairies standard: -* La librairie string -* La librairie table -* La librairie math -* La librairie io -* La librairie os +* La librairie [`string`](http://lua-users.org/wiki/StringLibraryTutorial) +* La librairie [`table`](http://lua-users.org/wiki/TableLibraryTutorial) +* La librairie [`math`](http://lua-users.org/wiki/MathLibraryTutorial) +* La librairie [`io`](http://lua-users.org/wiki/IoLibraryTutorial) +* La librairie [`os`](http://lua-users.org/wiki/OsLibraryTutorial) Autres références complémentaires: -* Lua pour programmeurs -* Référence condensée de Lua -* Programmer en Lua -* Les manuels de référence Lua +* [Lua pour programmeurs](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/) +* [Référence condensée de Lua](lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf) +* [Programmer en Lua](http://www.lua.org/pil/contents.html) +* [Les manuels de référence Lua](http://www.lua.org/manual/) A propos, ce fichier est exécutable. Sauvegardez-le sous le nom *learn.lua* et -exécutez-le avec la commande `lua learn.lua` ! +exécutez-le avec la commande "`lua learn.lua`" ! -Ce tutoriel a été originalement écrit pour tylerneylon.com et est aussi -disponible en tant que gist. -Il a été traduit en français par Roland Yonaba (voir son GitHub). +Ce tutoriel a été originalement écrit pour [tylerneylon.com](tylerneylon.com) et est aussi +disponible en tant que [gist](https://gist.github.com/tylerneylon/5853042). +Il a été traduit en français par Roland Yonaba (voir son [GitHub](http://github.com/Yonaba)). Amusez-vous bien avec Lua! diff --git a/ko-kr/lua-kr.html.markdown b/ko-kr/lua-kr.html.markdown index 2fa73789..24acc442 100644 --- a/ko-kr/lua-kr.html.markdown +++ b/ko-kr/lua-kr.html.markdown @@ -21,9 +21,9 @@ filename: learnlua-kr.lua ---------------------------------------------------- num = 42 -- 모든 숫자는 double입니다. --- 놀랄 필요는 없습니다. 64비트 double은 --- 정확한 int 값을 저장하기 위해 52비트로 구성돼 --- 있습니다. 52비트 이하의 int 값에 대해서는 +-- 놀랄 필요는 없습니다. 64비트 double은 +-- 정확한 int 값을 저장하기 위해 52비트로 구성돼 +-- 있습니다. 52비트 이하의 int 값에 대해서는 -- 장비 정밀도와 관련된 문제가 생기지 않습니다. s = 'walternate' -- 파이썬과 같은 불변 문자열 @@ -42,7 +42,7 @@ end if num > 40 then print('40 이상') elseif s ~= 'walternate' then -- ~=은 '같지 않다'입니다. - -- 동일성 검사는 파이썬과 마찬가지로 ==입니다. + -- 동일성 검사는 파이썬과 마찬가지로 ==입니다. -- 문자열에도 쓸 수 있습니다. io.write('not over 40\n') -- 기본적으로 stdout에 씁니다. else @@ -198,7 +198,7 @@ end ---------------------------------------------------- -- 테이블은 테이블에 연산자 오버로딩을 가능하게 하는 메타테이블을 --- 가질 수 있습니다. 나중에 메타테이블이 어떻게 자바스크립트 +-- 가질 수 있습니다. 나중에 메타테이블이 어떻게 자바스크립트 -- 프로토타입과 같은 행위를 지원하는지 살펴보겠습니다. f1 = {a = 1, b = 2} -- 분수 a/b를 표현 @@ -220,7 +220,7 @@ setmetatable(f2, metafraction) s = f1 + f2 -- f1의 메타테이블을 대상으로 __add(f1, f2)를 호출 --- f1과 f2는 자바스크립트의 프로토타입과 달리 각 메타테이블에 대한 +-- f1과 f2는 자바스크립트의 프로토타입과 달리 각 메타테이블에 대한 -- 키가 없어서 getmetatable(f1)과 같이 받아와야 합니다. -- 메타테이블은 __add 같은 루아가 알고 있는 키가 지정된 일반 테이블입니다. @@ -290,11 +290,11 @@ mrDog:makeSound() -- 'I say woof' -- 8. -- self가 값을 어떻게 얻는지 궁금하다면 아래의 7과 8을 읽어보세요. -- 3. newObj는 Dog 클래스의 인스턴스가 됩니다. -- 4. self = 인스턴스화되는 클래스. --- 주로 self = Dog이지만 상속을 이용하면 이것을 바꿀 수 있습니다. +-- 주로 self = Dog이지만 상속을 이용하면 이것을 바꿀 수 있습니다. -- newObj의 메타테이블과 self의 __index를 모두 self에 설정하면 -- newObj가 self의 함수를 갖게 됩니다. -- 5. 참고: setmetatable은 첫 번째 인자를 반환합니다. --- 6. :는 2에서 설명한 것과 같이 동작하지만 이번에는 self가 +-- 6. :는 2에서 설명한 것과 같이 동작하지만 이번에는 self가 -- 클래스가 아닌 인스턴스라고 예상할 수 있습니다. -- 7. Dog.new(Dog)과 같으므로 new()에서는 self = Dog입니다. -- 8. mrDog.makeSound(mrDog)과 같으므로 self = mrDog입니다. @@ -319,10 +319,10 @@ seymour:makeSound() -- 'woof woof woof' -- 4. -- 메타테이블에서 __index = Dog이기 때문에 Dog.new(LoudDog)으로 -- 변환됩니다. -- 결과: seymour의 메타테이블은 LoudDog이고 LoudDog.__index는 --- LoudDog입니다. 따라서 seymour.key는 seymour.key, +-- LoudDog입니다. 따라서 seymour.key는 seymour.key, -- LoudDog.key, Dog.key와 같을 것이며, 지정한 키에 어떤 테이블이 -- 오든 상관없을 것입니다. --- 4. 'makeSound' 키는 LoudDog에서 발견할 수 있습니다. +-- 4. 'makeSound' 키는 LoudDog에서 발견할 수 있습니다. -- 이것은 LoudDog.makeSound(seymour)와 같습니다. -- 필요할 경우, 하위 클래스의 new()는 기반 클래스의 new()와 유사합니다. @@ -338,7 +338,7 @@ end ---------------------------------------------------- ---[[ 여기서 주석을 제거하면 이 스크립트의 나머지 부분은 +--[[ 여기서 주석을 제거하면 이 스크립트의 나머지 부분은 -- 실행 가능한 상태가 됩니다. ``` @@ -395,27 +395,27 @@ g() -- 343이 출력됩니다. 그전까지는 아무것도 출력되지 않습 ## 참고자료 -루아를 배우는 일이 흥미진진했던 이유는 Love 2D 게임 엔진을 이용해 +루아를 배우는 일이 흥미진진했던 이유는 [LÖVE 게임 엔진](http://love2d.org/)을 이용해 게임을 만들 수 있었기 때문입니다. 이것이 제가 루아를 배운 이유입니다. -저는 BlackBulletIV의 "프로그래머를 위한 루아"로 -시작했습니다. 그다음으로 공식 "프로그래밍 루아" 책을 읽었습니다. +저는 [BlackBulletIV의 "프로그래머를 위한 루아"](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/)로 +시작했습니다. 그다음으로 공식 ["프로그래밍 루아"](http://www.lua.org/pil/contents.html) 책을 읽었습니다. 그렇게 루아를 배웠습니다. -lua-users.org에 있는 짧은 루아 레퍼런스를 +lua-users.org에 있는 [짧은 루아 레퍼런스](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)를 읽어두면 도움될지도 모르겠습니다. 여기서는 표준 라이브러리에 관해서는 다루지 않았습니다. -* string 라이브러리 -* table 라이브러리 -* math 라이브러리 -* io 라이브러리 -* os 라이브러리 +* [`string` 라이브러리](http://lua-users.org/wiki/StringLibraryTutorial) +* [`table` 라이브러리](http://lua-users.org/wiki/TableLibraryTutorial) +* [`math` 라이브러리](http://lua-users.org/wiki/MathLibraryTutorial) +* [`io` 라이브러리](http://lua-users.org/wiki/IoLibraryTutorial) +* [`os` 라이브러리](http://lua-users.org/wiki/OsLibraryTutorial) 그나저나 이 파일 전체는 유효한 루아 프로그램입니다. 이 파일을 -learn.lua로 저장한 후 "lua learn.lua"를 실행해 보세요! +learn.lua로 저장한 후 "`lua learn.lua`"를 실행해 보세요! -이 글은 tylerneylon.com에 처음으로 써본 글이며, -GitHub의 Gist에서도 확인할 수 있습니다. +이 글은 tylerneylon.com에 처음으로 써본 글이며, +[GitHub의 Gist](https://gist.github.com/tylerneylon/5853042)에서도 확인할 수 있습니다. 루아로 즐거운 시간을 보내세요! diff --git a/lua.html.markdown b/lua.html.markdown index 460295ff..a755e6e1 100644 --- a/lua.html.markdown +++ b/lua.html.markdown @@ -390,31 +390,29 @@ g() -- Prints out 343; nothing printed before now. ## Community -If you need support join the official Lua [mailing list](https://www.lua.org/lua-l.html), [irc channel](http://lua-users.org/wiki/IrcChannel), or [forum](https://luaforum.com). - +If you need support join the official Lua [mailing list](https://www.lua.org/lua-l.html), [IRC channel](http://lua-users.org/wiki/IrcChannel), or [forum](https://luaforum.com). ## References I was excited to learn Lua so I could make games -with the Love 2D game engine. That's the why. +with the [LÖVE game engine](http://love2d.org/). That's the why. -I started with BlackBulletIV's Lua for programmers. -Next I read the official Programming in Lua book. +I started with [BlackBulletIV's Lua for programmers](https://ebens.me/posts/lua-for-programmers-part-1/). +Next I read the official [Programming in Lua](http://www.lua.org/pil/contents.html) book. That's the how. -It might be helpful to check out the Lua short -reference on lua-users.org. +It might be helpful to check out the [Lua short reference](http://lua-users.org/wiki/LuaShortReference) on lua-users.org. The main topics not covered are standard libraries: -* string library -* table library -* math library -* io library -* os library +* [`string` library](http://lua-users.org/wiki/StringLibraryTutorial) +* [`table` library](http://lua-users.org/wiki/TableLibraryTutorial) +* [`math` library](http://lua-users.org/wiki/MathLibraryTutorial) +* [`io` library](http://lua-users.org/wiki/IoLibraryTutorial) +* [`os` library](http://lua-users.org/wiki/OsLibraryTutorial) By the way, the entire file is valid Lua; save it -as learn.lua and run it with "lua learn.lua" ! +as learn.lua and run it with "`lua learn.lua`" ! This was first written for tylerneylon.com, and is -also available as a GitHub gist. Have fun with Lua! +also available as a [GitHub gist](https://gist.github.com/tylerneylon/5853042). Have fun with Lua! diff --git a/pt-br/lua-pt.html.markdown b/pt-br/lua-pt.html.markdown index d272150d..2b69ecdf 100644 --- a/pt-br/lua-pt.html.markdown +++ b/pt-br/lua-pt.html.markdown @@ -397,26 +397,26 @@ g() -- Imprime 343; nada foi impresso antes disso. ## Referências Fiquei bastante animado para aprender Lua pois consegui fazer jogos -com a Love 2D engine de jogos. +com a [LÖVE engine de jogos](http://love2d.org/). -Eu comecei com BlackBulletIV's para programadores LUA. -Em seguida, eu li a documentação oficial Programando em Lua. +Eu comecei com [BlackBulletIV's para programadores LUA](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/). +Em seguida, eu li a documentação oficial [Programando em Lua](https://www.lua.org/manual/5.1/pt/index.html#contents). É assim que se começa. -Pode ser útil conferir Uma pequena referencia sobre LUA em lua-users.org. +Pode ser útil conferir [Uma pequena referencia sobre LUA](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf) em lua-users.org. Os principais tópicos não cobertos, são as bibliotecas padrões: -- Biblioteca de strings -- Biblioteca de tabelas -- Biblioteca de matemática -- Biblioteca de entrada/saída -- Biblioteca do sistema operacional +- [Biblioteca de strings](http://lua-users.org/wiki/StringLibraryTutorial) +- [Biblioteca de tabelas](http://lua-users.org/wiki/TableLibraryTutorial) +- [Biblioteca de matemática](http://lua-users.org/wiki/MathLibraryTutorial) +- [Biblioteca de entrada/saída](http://lua-users.org/wiki/IoLibraryTutorial) +- [Biblioteca do sistema operacional](http://lua-users.org/wiki/OsLibraryTutorial) A propósito, todo este arquivo é um código LUA válido, salve-o como -aprenda.lua e rode-o com "lua aprenda.lua" ! +aprenda.lua e rode-o com "`lua aprenda.lua`" ! Este guia foi escrito pela primeira vez por tylerneylon.com, e agora -também disponível em GitHub gist. E também em português. +também disponível em [GitHub gist](https://gist.github.com/tylerneylon/5853042). E também em português. Se divirta com lua diff --git a/ru-ru/lua-ru.html.markdown b/ru-ru/lua-ru.html.markdown index fdbde45e..ff1dc77a 100644 --- a/ru-ru/lua-ru.html.markdown +++ b/ru-ru/lua-ru.html.markdown @@ -404,22 +404,22 @@ g() -- Напишет 343. ## Примечание (от автора) -Мне было интересно изучить Lua, чтобы делать игры при помощи игрового движка LÖVE. +Мне было интересно изучить Lua, чтобы делать игры при помощи [игрового движка LÖVE](http://love2d.org/). -Я начинал с BlackBulletIV's Lua for programmers. -Затем я прочитал официальную Документацию по Lua. +Я начинал с [BlackBulletIV's Lua for programmers](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/). +Затем я прочитал официальную [Документацию по Lua](http://www.lua.org/pil/contents.html). -Также может быть полезной Краткая справка по Lua на lua-users.org. +Также может быть полезной [Краткая справка по Lua](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf) на lua-users.org. Ещё из основных тем не охвачены стандартные библиотеки: -* библиотека string -* библиотека table -* библиотека math -* библиотека io -* библиотека os +* [библиотека `string`](http://lua-users.org/wiki/StringLibraryTutorial) +* [библиотека `table`](http://lua-users.org/wiki/TableLibraryTutorial) +* [библиотека `math`](http://lua-users.org/wiki/MathLibraryTutorial) +* [библиотека `io`](http://lua-users.org/wiki/IoLibraryTutorial) +* [библиотека `os`](http://lua-users.org/wiki/OsLibraryTutorial) -Кстати, весь файл написан на Lua; сохраните его как learn.lua и запустите при помощи "lua learn.lua" ! +Кстати, весь файл написан на Lua; сохраните его как learn.lua и запустите при помощи `lua learn.lua` Изначально эта статья была написана для tylerneylon.com. -Также она доступна как GitHub gist. Удачи с Lua! +Также она доступна как [GitHub gist](https://gist.github.com/tylerneylon/5853042). Удачи с Lua! diff --git a/zh-cn/lua-cn.html.markdown b/zh-cn/lua-cn.html.markdown index 81883850..920725e8 100644 --- a/zh-cn/lua-cn.html.markdown +++ b/zh-cn/lua-cn.html.markdown @@ -1,7 +1,7 @@ --- language: Lua lang: zh-cn -contributors: +contributors: - ["Tyler Neylon", "http://tylerneylon.com/"] - ["Rob Hoelz", "http://hoelz.ro"] - ["Jakukyo Friel", "http://weakish.github.io"] @@ -13,411 +13,409 @@ filename: lua-cn.lua --- ```lua --- 单行注释以两个连字符开头 +-- 单行注释以两个连字符开头 ---[[ +--[[ 多行注释 --]] ----------------------------------------------------- +---------------------------------------------------- -- 1. 变量和流程控制 ----------------------------------------------------- +---------------------------------------------------- num = 42 -- 所有的数字都是双精度浮点型。 --- 别害怕,64位的双精度浮点型数字中有52位用于 --- 保存精确的整型值; 对于52位以内的整型值, +-- 别害怕,64位的双精度浮点型数字中有52位用于 +-- 保存精确的整型值; 对于52位以内的整型值, -- 不用担心精度问题。 -s = 'walternate' -- 和Python一样,字符串不可变。 -t = "也可以用双引号" +s = 'walternate' -- 和Python一样,字符串不可变。 +t = "也可以用双引号" u = [[ 多行的字符串 以两个方括号 - 开始和结尾。]] -t = nil -- 撤销t的定义; Lua 支持垃圾回收。 + 开始和结尾。]] +t = nil -- 撤销t的定义; Lua 支持垃圾回收。 --- 块使用do/end之类的关键字标识: -while num < 50 do - num = num + 1 -- 不支持 ++ 或 += 运算符。 -end +-- 块使用do/end之类的关键字标识: +while num < 50 do + num = num + 1 -- 不支持 ++ 或 += 运算符。 +end --- If语句: -if num > 40 then - print('over 40') -elseif s ~= 'walternate' then -- ~= 表示不等于。 - -- 像Python一样,用 == 检查是否相等 ;字符串同样适用。 +-- If语句: +if num > 40 then + print('over 40') +elseif s ~= 'walternate' then -- ~= 表示不等于。 + -- 像Python一样,用 == 检查是否相等 ;字符串同样适用。 io.write('not over 40\n') -- 默认标准输出。 -else - -- 默认全局变量。 +else + -- 默认全局变量。 thisIsGlobal = 5 -- 通常使用驼峰。 - -- 如何定义局部变量: - local line = io.read() -- 读取标准输入的下一行。 + -- 如何定义局部变量: + local line = io.read() -- 读取标准输入的下一行。 - -- ..操作符用于连接字符串: - print('Winter is coming, ' .. line) -end + -- ..操作符用于连接字符串: + print('Winter is coming, ' .. line) +end --- 未定义的变量返回nil。 --- 这不是错误: -foo = anUnknownVariable -- 现在 foo = nil. +-- 未定义的变量返回nil。 +-- 这不是错误: +foo = anUnknownVariable -- 现在 foo = nil. -aBoolValue = false +aBoolValue = false ---只有nil和false为假; 0和 ''均为真! -if not aBoolValue then print('false') end +--只有nil和false为假; 0和 ''均为真! +if not aBoolValue then print('false') end --- 'or'和 'and'短路 --- 类似于C/js里的 a?b:c 操作符: -ans = aBoolValue and 'yes' or 'no' --> 'no' +-- 'or'和 'and'短路 +-- 类似于C/js里的 a?b:c 操作符: +ans = aBoolValue and 'yes' or 'no' --> 'no' -karlSum = 0 -for i = 1, 100 do -- 范围包含两端 - karlSum = karlSum + i -end +karlSum = 0 +for i = 1, 100 do -- 范围包含两端 + karlSum = karlSum + i +end --- 使用 "100, 1, -1" 表示递减的范围: -fredSum = 0 -for j = 100, 1, -1 do fredSum = fredSum + j end +-- 使用 "100, 1, -1" 表示递减的范围: +fredSum = 0 +for j = 100, 1, -1 do fredSum = fredSum + j end --- 通常,范围表达式为begin, end[, step]. +-- 通常,范围表达式为begin, end[, step]. --- 循环的另一种结构: -repeat - print('the way of the future') - num = num - 1 -until num == 0 +-- 循环的另一种结构: +repeat + print('the way of the future') + num = num - 1 +until num == 0 ----------------------------------------------------- --- 2. 函数。 ----------------------------------------------------- +---------------------------------------------------- +-- 2. 函数。 +---------------------------------------------------- function fib(n) if n < 2 then return n end return fib(n - 2) + fib(n - 1) end --- 支持闭包及匿名函数: -function adder(x) +-- 支持闭包及匿名函数: +function adder(x) -- 调用adder时,会创建返回的函数, - -- 并且会记住x的值: - return function (y) return x + y end -end -a1 = adder(9) -a2 = adder(36) -print(a1(16)) --> 25 -print(a2(64)) --> 100 + -- 并且会记住x的值: + return function (y) return x + y end +end +a1 = adder(9) +a2 = adder(36) +print(a1(16)) --> 25 +print(a2(64)) --> 100 -- 返回值、函数调用和赋值都可以 --- 使用长度不匹配的list。 --- 不匹配的接收方会被赋值nil; --- 不匹配的发送方会被丢弃。 +-- 使用长度不匹配的list。 +-- 不匹配的接收方会被赋值nil; +-- 不匹配的发送方会被丢弃。 -x, y, z = 1, 2, 3, 4 --- x = 1、y = 2、z = 3, 而 4 会被丢弃。 +x, y, z = 1, 2, 3, 4 +-- x = 1、y = 2、z = 3, 而 4 会被丢弃。 -function bar(a, b, c) - print(a, b, c) - return 4, 8, 15, 16, 23, 42 -end +function bar(a, b, c) + print(a, b, c) + return 4, 8, 15, 16, 23, 42 +end -x, y = bar('zaphod') --> 打印 "zaphod nil nil" --- 现在 x = 4, y = 8, 而值15..42被丢弃。 +x, y = bar('zaphod') --> 打印 "zaphod nil nil" +-- 现在 x = 4, y = 8, 而值15..42被丢弃。 --- 函数是一等公民,可以是局部的,也可以是全局的。 --- 以下表达式等价: -function f(x) return x * x end -f = function (x) return x * x end +-- 函数是一等公民,可以是局部的,也可以是全局的。 +-- 以下表达式等价: +function f(x) return x * x end +f = function (x) return x * x end --- 这些也是等价的: +-- 这些也是等价的: local function g(x) return math.sin(x) end local g; g = function (x) return math.sin(x) end -- 以上均因'local g',使得g可以自引用。 local g = function(x) return math.sin(x) end -- 等价于 local function g(x)..., 但函数体中g不可自引用 --- 顺便提下,三角函数以弧度为单位。 +-- 顺便提下,三角函数以弧度为单位。 --- 用一个字符串参数调用函数,可以省略括号: -print 'hello' --可以工作。 +-- 用一个字符串参数调用函数,可以省略括号: +print 'hello' --可以工作。 -- 调用函数时,如果只有一个table参数, -- 同样可以省略括号(table详情见下): print {} -- 一样可以工作。 ----------------------------------------------------- --- 3. Table。 ----------------------------------------------------- +---------------------------------------------------- +-- 3. Table。 +---------------------------------------------------- --- Table = Lua唯一的组合数据结构; --- 它们是关联数组。 --- 类似于PHP的数组或者js的对象, --- 它们是哈希表或者字典,也可以当列表使用。 +-- Table = Lua唯一的组合数据结构; +-- 它们是关联数组。 +-- 类似于PHP的数组或者js的对象, +-- 它们是哈希表或者字典,也可以当列表使用。 --- 按字典/map的方式使用Table: +-- 按字典/map的方式使用Table: --- Dict字面量默认使用字符串类型的key: -t = {key1 = 'value1', key2 = false} +-- Dict字面量默认使用字符串类型的key: +t = {key1 = 'value1', key2 = false} --- 字符串key可以使用类似js的点标记: -print(t.key1) -- 打印 'value1'. -t.newKey = {} -- 添加新的键值对。 -t.key2 = nil -- 从table删除 key2。 +-- 字符串key可以使用类似js的点标记: +print(t.key1) -- 打印 'value1'. +t.newKey = {} -- 添加新的键值对。 +t.key2 = nil -- 从table删除 key2。 --- 使用任何非nil的值作为key: -u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} -print(u[6.28]) -- 打印 "tau" +-- 使用任何非nil的值作为key: +u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} +print(u[6.28]) -- 打印 "tau" -- 数字和字符串的key按值匹配的 --- table按id匹配。 -a = u['@!#'] -- 现在 a = 'qbert'. -b = u[{}] -- 我们或许期待的是 1729, 但是得到的是nil: --- b = nil ,因为没有找到。 +-- table按id匹配。 +a = u['@!#'] -- 现在 a = 'qbert'. +b = u[{}] -- 我们或许期待的是 1729, 但是得到的是nil: +-- b = nil ,因为没有找到。 -- 之所以没找到,是因为我们用的key与保存数据时用的不是同 --- 一个对象。 --- 所以字符串和数字是移植性更好的key。 +-- 一个对象。 +-- 所以字符串和数字是移植性更好的key。 --- 只需要一个table参数的函数调用不需要括号: -function h(x) print(x.key1) end -h{key1 = 'Sonmi~451'} -- 打印'Sonmi~451'. +-- 只需要一个table参数的函数调用不需要括号: +function h(x) print(x.key1) end +h{key1 = 'Sonmi~451'} -- 打印'Sonmi~451'. for key, val in pairs(u) do -- 遍历Table - print(key, val) -end - --- _G 是一个特殊的table,用于保存所有的全局变量 -print(_G['_G'] == _G) -- 打印'true'. - --- 按列表/数组的方式使用: - --- 列表字面量隐式添加整数键: -v = {'value1', 'value2', 1.21, 'gigawatts'} -for i = 1, #v do -- #v 是列表的大小 - print(v[i]) -- 索引从 1 开始!! 太疯狂了! + print(key, val) end --- 'list'并非真正的类型,v 其实是一个table, --- 只不过它用连续的整数作为key,可以像list那样去使用。 ----------------------------------------------------- --- 3.1 元表(metatable) 和元方法(metamethod)。 ----------------------------------------------------- +-- _G 是一个特殊的table,用于保存所有的全局变量 +print(_G['_G'] == _G) -- 打印'true'. + +-- 按列表/数组的方式使用: + +-- 列表字面量隐式添加整数键: +v = {'value1', 'value2', 1.21, 'gigawatts'} +for i = 1, #v do -- #v 是列表的大小 + print(v[i]) -- 索引从 1 开始!! 太疯狂了! +end +-- 'list'并非真正的类型,v 其实是一个table, +-- 只不过它用连续的整数作为key,可以像list那样去使用。 + +---------------------------------------------------- +-- 3.1 元表(metatable) 和元方法(metamethod)。 +---------------------------------------------------- -- table的元表提供了一种机制,支持类似操作符重载的行为。 --- 稍后我们会看到元表如何支持类似js prototype的行为。 +-- 稍后我们会看到元表如何支持类似js prototype的行为。 -f1 = {a = 1, b = 2} -- 表示一个分数 a/b. -f2 = {a = 2, b = 3} +f1 = {a = 1, b = 2} -- 表示一个分数 a/b. +f2 = {a = 2, b = 3} -- 这会失败: --- s = f1 + f2 +-- s = f1 + f2 -metafraction = {} -function metafraction.__add(f1, f2) - local sum = {} - sum.b = f1.b * f2.b - sum.a = f1.a * f2.b + f2.a * f1.b +metafraction = {} +function metafraction.__add(f1, f2) + local sum = {} + sum.b = f1.b * f2.b + sum.a = f1.a * f2.b + f2.a * f1.b return sum end -setmetatable(f1, metafraction) -setmetatable(f2, metafraction) +setmetatable(f1, metafraction) +setmetatable(f2, metafraction) -s = f1 + f2 -- 调用在f1的元表上的__add(f1, f2) 方法 +s = f1 + f2 -- 调用在f1的元表上的__add(f1, f2) 方法 --- f1, f2 没有关于元表的key,这点和js的prototype不一样。 +-- f1, f2 没有关于元表的key,这点和js的prototype不一样。 -- 因此你必须用getmetatable(f1)获取元表。 --- 元表是一个普通的table, --- 元表的key是普通的Lua中的key,例如__add。 +-- 元表是一个普通的table, +-- 元表的key是普通的Lua中的key,例如__add。 --- 但是下面一行代码会失败,因为s没有元表: --- t = s + s --- 下面提供的与类相似的模式可以解决这个问题: +-- 但是下面一行代码会失败,因为s没有元表: +-- t = s + s +-- 下面提供的与类相似的模式可以解决这个问题: --- 元表的__index 可以重载用于查找的点操作符: -defaultFavs = {animal = 'gru', food = 'donuts'} -myFavs = {food = 'pizza'} -setmetatable(myFavs, {__index = defaultFavs}) -eatenBy = myFavs.animal -- 可以工作!感谢元表 +-- 元表的__index 可以重载用于查找的点操作符: +defaultFavs = {animal = 'gru', food = 'donuts'} +myFavs = {food = 'pizza'} +setmetatable(myFavs, {__index = defaultFavs}) +eatenBy = myFavs.animal -- 可以工作!感谢元表 -- 如果在table中直接查找key失败,会使用 -- 元表的__index 递归地重试。 -- __index的值也可以是function(tbl, key) --- 这样可以支持自定义查找。 +-- 这样可以支持自定义查找。 --- __index、__add等的值,被称为元方法。 --- 这里是一个table元方法的清单: +-- __index、__add等的值,被称为元方法。 +-- 这里是一个table元方法的清单: --- __add(a, b) for a + b --- __sub(a, b) for a - b --- __mul(a, b) for a * b --- __div(a, b) for a / b --- __mod(a, b) for a % b --- __pow(a, b) for a ^ b --- __unm(a) for -a --- __concat(a, b) for a .. b --- __len(a) for #a --- __eq(a, b) for a == b --- __lt(a, b) for a < b --- __le(a, b) for a <= b --- __index(a, b) for a.b --- __newindex(a, b, c) for a.b = c --- __call(a, ...) for a(...) +-- __add(a, b) for a + b +-- __sub(a, b) for a - b +-- __mul(a, b) for a * b +-- __div(a, b) for a / b +-- __mod(a, b) for a % b +-- __pow(a, b) for a ^ b +-- __unm(a) for -a +-- __concat(a, b) for a .. b +-- __len(a) for #a +-- __eq(a, b) for a == b +-- __lt(a, b) for a < b +-- __le(a, b) for a <= b +-- __index(a, b) for a.b +-- __newindex(a, b, c) for a.b = c +-- __call(a, ...) for a(...) ----------------------------------------------------- --- 3.2 与类相似的table和继承。 ----------------------------------------------------- +---------------------------------------------------- +-- 3.2 与类相似的table和继承。 +---------------------------------------------------- -- Lua没有内建的类;可以通过不同的方法,利用表和元表 --- 来实现类。 +-- 来实现类。 --- 下面是一个例子,解释在后面: +-- 下面是一个例子,解释在后面: -Dog = {} -- 1. +Dog = {} -- 1. -function Dog:new() -- 2. - local newObj = {sound = 'woof'} -- 3. - self.__index = self -- 4. - return setmetatable(newObj, self) -- 5. -end +function Dog:new() -- 2. + local newObj = {sound = 'woof'} -- 3. + self.__index = self -- 4. + return setmetatable(newObj, self) -- 5. +end -function Dog:makeSound() -- 6. - print('I say ' .. self.sound) -end +function Dog:makeSound() -- 6. + print('I say ' .. self.sound) +end -mrDog = Dog:new() -- 7. -mrDog:makeSound() -- 'I say woof' -- 8. +mrDog = Dog:new() -- 7. +mrDog:makeSound() -- 'I say woof' -- 8. --- 1. Dog看上去像一个类;其实它是一个table。 +-- 1. Dog看上去像一个类;其实它是一个table。 -- 2. 函数tablename:fn(...) 等价于 -- 函数tablename.fn(self, ...) --- 冒号(:)只是添加了self作为第一个参数。 --- 阅读7 & 8条 了解self变量是如何得到其值的。 --- 3. newObj是类Dog的一个实例。 --- 4. self = 被继承的类。通常self = Dog,不过继承可以改变它。 --- 如果把newObj的元表和__index都设置为self, --- newObj就可以得到self的函数。 --- 5. 备忘:setmetatable返回其第一个参数。 --- 6. 冒号(:)的作用和第2条一样,不过这里 --- self是一个实例,而不是类 --- 7. 等价于Dog.new(Dog),所以在new()中,self = Dog。 --- 8. 等价于mrDog.makeSound(mrDog); self = mrDog。 +-- 冒号(:)只是添加了self作为第一个参数。 +-- 阅读7 & 8条 了解self变量是如何得到其值的。 +-- 3. newObj是类Dog的一个实例。 +-- 4. self = 被继承的类。通常self = Dog,不过继承可以改变它。 +-- 如果把newObj的元表和__index都设置为self, +-- newObj就可以得到self的函数。 +-- 5. 备忘:setmetatable返回其第一个参数。 +-- 6. 冒号(:)的作用和第2条一样,不过这里 +-- self是一个实例,而不是类 +-- 7. 等价于Dog.new(Dog),所以在new()中,self = Dog。 +-- 8. 等价于mrDog.makeSound(mrDog); self = mrDog。 ----------------------------------------------------- +---------------------------------------------------- --- 继承的例子: +-- 继承的例子: -LoudDog = Dog:new() -- 1. +LoudDog = Dog:new() -- 1. -function LoudDog:makeSound() - local s = self.sound .. ' ' -- 2. - print(s .. s .. s) -end +function LoudDog:makeSound() + local s = self.sound .. ' ' -- 2. + print(s .. s .. s) +end -seymour = LoudDog:new() -- 3. -seymour:makeSound() -- 'woof woof woof' -- 4. +seymour = LoudDog:new() -- 3. +seymour:makeSound() -- 'woof woof woof' -- 4. --- 1. LoudDog获得Dog的方法和变量列表。 --- 2. 因为new()的缘故,self拥有了一个'sound' key,参见第3条。 --- 3. 等价于LoudDog.new(LoudDog),转换一下就是 --- Dog.new(LoudDog),这是因为LoudDog没有'new' key, --- 但是它的元表中有 __index = Dog。 --- 结果: seymour的元表是LoudDog,并且 --- LoudDog.__index = Dog。所以有seymour.key --- = seymour.key, LoudDog.key, Dog.key --- 从其中第一个有指定key的table获取。 --- 4. 在LoudDog可以找到'makeSound'的key; --- 等价于LoudDog.makeSound(seymour)。 +-- 1. LoudDog获得Dog的方法和变量列表。 +-- 2. 因为new()的缘故,self拥有了一个'sound' key,参见第3条。 +-- 3. 等价于LoudDog.new(LoudDog),转换一下就是 +-- Dog.new(LoudDog),这是因为LoudDog没有'new' key, +-- 但是它的元表中有 __index = Dog。 +-- 结果: seymour的元表是LoudDog,并且 +-- LoudDog.__index = Dog。所以有seymour.key +-- = seymour.key, LoudDog.key, Dog.key +-- 从其中第一个有指定key的table获取。 +-- 4. 在LoudDog可以找到'makeSound'的key; +-- 等价于LoudDog.makeSound(seymour)。 --- 如果有必要,子类也可以有new(),与基类相似: -function LoudDog:new() - local newObj = {} - -- 初始化newObj - self.__index = self - return setmetatable(newObj, self) -end +-- 如果有必要,子类也可以有new(),与基类相似: +function LoudDog:new() + local newObj = {} + -- 初始化newObj + self.__index = self + return setmetatable(newObj, self) +end ----------------------------------------------------- --- 4. 模块 ----------------------------------------------------- +---------------------------------------------------- +-- 4. 模块 +---------------------------------------------------- ---[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 +--[[ 我把这部分给注释了,这样脚本剩下的部分可以运行 ``` ```lua --- 假设文件mod.lua的内容类似这样: -local M = {} +-- 假设文件mod.lua的内容类似这样: +local M = {} -local function sayMyName() - print('Hrunkner') -end +local function sayMyName() + print('Hrunkner') +end -function M.sayHello() - print('Why hello there') - sayMyName() -end +function M.sayHello() + print('Why hello there') + sayMyName() +end -return M +return M --- 另一个文件可以使用mod.lua的功能: -local mod = require('mod') -- 运行文件mod.lua. +-- 另一个文件可以使用mod.lua的功能: +local mod = require('mod') -- 运行文件mod.lua. -- 注意:require 需要配合 LUA_PATH 一起使用 例如:export LUA_PATH="$HOME/workspace/projectName/?.lua;;" --- require是包含模块的标准做法。 --- require等价于: (针对没有被缓存的情况;参见后面的内容) -local mod = (function () - -end)() +-- require是包含模块的标准做法。 +-- require等价于: (针对没有被缓存的情况;参见后面的内容) +local mod = (function () + +end)() -- mod.lua被包在一个函数体中,因此mod.lua的局部变量 --- 对外不可见。 +-- 对外不可见。 --- 下面的代码可以工作,因为在这里mod = mod.lua 中的 M: -mod.sayHello() -- Says hello to Hrunkner. +-- 下面的代码可以工作,因为在这里mod = mod.lua 中的 M: +mod.sayHello() -- Says hello to Hrunkner. --- 这是错误的;sayMyName只在mod.lua中存在: -mod.sayMyName() -- 错误 +-- 这是错误的;sayMyName只在mod.lua中存在: +mod.sayMyName() -- 错误 --- require返回的值会被缓存,所以一个文件只会被运行一次, --- 即使它被require了多次。 +-- require返回的值会被缓存,所以一个文件只会被运行一次, +-- 即使它被require了多次。 --- 假设mod2.lua包含代码"print('Hi!')"。 -local a = require('mod2') -- 打印Hi! -local b = require('mod2') -- 不再打印; a=b. +-- 假设mod2.lua包含代码"print('Hi!')"。 +local a = require('mod2') -- 打印Hi! +local b = require('mod2') -- 不再打印; a=b. --- dofile与require类似,但是不缓存: -dofile('mod2') --> Hi! -dofile('mod2') --> Hi! (再次运行,与require不同) +-- dofile与require类似,但是不缓存: +dofile('mod2') --> Hi! +dofile('mod2') --> Hi! (再次运行,与require不同) --- loadfile加载一个lua文件,但是并不运行它。 -f = loadfile('mod2') -- Calling f() runs mod2.lua. +-- loadfile加载一个lua文件,但是并不运行它。 +f = loadfile('mod2') -- Calling f() runs mod2.lua. --- loadstring是loadfile的字符串版本。 +-- loadstring是loadfile的字符串版本。 -- (loadstring已弃用, 使用load代替) g = load('print(343)') --返回一个函数。 -g() -- 打印343; 在此之前什么也不打印。 +g() -- 打印343; 在此之前什么也不打印。 ---]] +--]] ``` ## 参考 - - -为什么?我非常兴奋地学习lua, 这样我就可以使用[Löve 2D游戏引擎](http://love2d.org/)来编游戏。 +为什么?我非常兴奋地学习lua, 这样我就可以使用[LÖVE 2D游戏引擎](http://love2d.org/)来编游戏。 怎么做?我从[BlackBulletIV的面向程序员的Lua指南](http://nova-fusion.com/2012/08/27/lua-for-programmers-part-1/)入门。接着我阅读了官方的[Lua编程](http://www.lua.org/pil/contents.html)一书。 lua-users.org上的[Lua简明参考](http://lua-users.org/files/wiki_insecure/users/thomasl/luarefv51.pdf)应该值得一看。 本文没有涉及标准库的内容: - -* string library -* table library -* math library -* io library -* os library -顺便说一下,整个文件是可运行的Lua; +* [`string` library](http://lua-users.org/wiki/StringLibraryTutorial) +* [`table` library](http://lua-users.org/wiki/TableLibraryTutorial) +* [`math` library](http://lua-users.org/wiki/MathLibraryTutorial) +* [`io` library](http://lua-users.org/wiki/IoLibraryTutorial) +* [`os` library](http://lua-users.org/wiki/OsLibraryTutorial) + +顺便说一下,整个文件是可运行的Lua; 保存为 learn-cn.lua 用命令 `lua learn-cn.lua` 启动吧! 本文首次撰写于 [tylerneylon.com](http://tylerneylon.com) 同时也有 [GitHub gist](https://gist.github.com/tylerneylon/5853042) 版. From 29bf4c1b9f353fa3321f663dc52c1b227a1ed9e5 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 3 Jun 2024 06:02:10 -0600 Subject: [PATCH 272/392] [java/fa] delete (#4967) --- fa-ir/java-fa.html.markdown | 901 ------------------------------------ 1 file changed, 901 deletions(-) delete mode 100644 fa-ir/java-fa.html.markdown diff --git a/fa-ir/java-fa.html.markdown b/fa-ir/java-fa.html.markdown deleted file mode 100644 index 6bc3a420..00000000 --- a/fa-ir/java-fa.html.markdown +++ /dev/null @@ -1,901 +0,0 @@ ---- -language: java -lang: fa-ir -contributors: - - ["Jake Prather", "https://github.com/JakeHP"] - - ["Jakukyo Friel", "https://weakish.github.io"] - - ["Madison Dickson", "https://github.com/mix3d"] - - ["Simon Morgan", "https://sjm.io/"] - - ["Zachary Ferguson", "https://github.com/zfergus2"] - - ["Cameron Schermerhorn", "https://github.com/cschermerhorn"] - - ["Rachel Stiyer", "https://github.com/rstiyer"] - - ["Michael Dähnert", "https://github.com/JaXt0r"] - - ["Rob Rose", "https://github.com/RobRoseKnows"] - - ["Sean Nam", "https://github.com/seannam"] -translators: - - ["ghaseminya", "https://github.com/ghaseminya"] -filename: LearnJava-fa.java ---- - -جاوا یک زبان برنامه نویسی کامپیوتری چند منظوره، با قابلیت همزمانی، برپایه کلاس و شی گرایی می باشد. -[مطالعه بیشتر.](https://docs.oracle.com/javase/tutorial/java/) - -```java -// Single-line comments start with // - -/* -Multi-line comments look like this. -*/ - -/** - * JavaDoc comments look like this. Used to describe the Class or various - * attributes of a Class. - * Main attributes: - * - * @author @ghaseminya - * @version v1.0 -*/ - -// Import ArrayList class inside of the java.util package -import java.util.ArrayList; -// Import all classes inside of java.security package -import java.security.*; - -// Each .java file contains one outer-level public class, with the same name -// as the file. -public class LearnJava { - - // In order to run a java program, it must have a main method as an entry - // point. - public static void main (String[] args) { - - /////////////////////////////////////// - // Input/Output - /////////////////////////////////////// - - /* - * Output - */ - - // Use System.out.println() to print lines. - System.out.println("Hello World!"); - System.out.println( - "Integer: " + 10 + - " Double: " + 3.14 + - " Boolean: " + true); - - // To print without a newline, use System.out.print(). - System.out.print("Hello "); - System.out.print("World"); - - // Use System.out.printf() for easy formatted printing. - System.out.printf("pi = %.5f", Math.PI); // => pi = 3.14159 - - /* - * Input - */ - - // use Scanner to read input - // must import java.util.Scanner; - Scanner scanner = new Scanner(System.in); - - // read string input - String name = scanner.next(); - - // read byte input - byte numByte = scanner.nextByte(); - - // read int input - int numInt = scanner.nextInt(); - - // read long input - float numFloat - scanner.nextFloat(); - - // read double input - double numDouble = scanner.nextDouble(); - - // read boolean input - boolean bool = scanner.nextBoolean(); - - /////////////////////////////////////// - // Variables - /////////////////////////////////////// - - /* - * Variable Declaration - */ - // Declare a variable using - int fooInt; - // Declare multiple variables of the same - // type , , - int fooInt1, fooInt2, fooInt3; - - /* - * Variable Initialization - */ - - // Initialize a variable using = - int barInt = 1; - // Initialize multiple variables of same type with same - // value , , = - int barInt1, barInt2, barInt3; - barInt1 = barInt2 = barInt3 = 1; - - /* - * Variable types - */ - // Byte - 8-bit signed two's complement integer - // (-128 <= byte <= 127) - byte fooByte = 100; - - // If you would like to interpret a byte as an unsigned integer - // then this simple operation can help - int unsignedIntLessThan256 = 0xff & fooByte; - // this contrasts a cast which can be negative. - int signedInt = (int) fooByte; - - // Short - 16-bit signed two's complement integer - // (-32,768 <= short <= 32,767) - short fooShort = 10000; - - // Integer - 32-bit signed two's complement integer - // (-2,147,483,648 <= int <= 2,147,483,647) - int bazInt = 1; - - // Long - 64-bit signed two's complement integer - // (-9,223,372,036,854,775,808 <= long <= 9,223,372,036,854,775,807) - long fooLong = 100000L; - // L is used to denote that this variable value is of type Long; - // anything without is treated as integer by default. - - // Note: byte, short, int and long are signed. They can have positive and negative values. - // There are no unsigned variants. - // char, however, is 16-bit unsigned. - - // Float - Single-precision 32-bit IEEE 754 Floating Point - // 2^-149 <= float <= (2-2^-23) * 2^127 - float fooFloat = 234.5f; - // f or F is used to denote that this variable value is of type float; - // otherwise it is treated as double. - - // Double - Double-precision 64-bit IEEE 754 Floating Point - // 2^-1074 <= x <= (2-2^-52) * 2^1023 - double fooDouble = 123.4; - - // Boolean - true & false - boolean fooBoolean = true; - boolean barBoolean = false; - - // Char - A single 16-bit Unicode character - char fooChar = 'A'; - - // final variables can't be reassigned to another object, - final int HOURS_I_WORK_PER_WEEK = 9001; - // but they can be initialized later. - final double E; - E = 2.71828; - - // BigInteger - Immutable arbitrary-precision integers - // - // BigInteger is a data type that allows programmers to manipulate - // integers longer than 64-bits. Integers are stored as an array of - // of bytes and are manipulated using functions built into BigInteger - // - // BigInteger can be initialized using an array of bytes or a string. - BigInteger fooBigInteger = new BigInteger(fooByteArray); - - // BigDecimal - Immutable, arbitrary-precision signed decimal number - // - // A BigDecimal takes two parts: an arbitrary precision integer - // unscaled value and a 32-bit integer scale - // - // BigDecimal allows the programmer complete control over decimal - // rounding. It is recommended to use BigDecimal with currency values - // and where exact decimal precision is required. - // - // BigDecimal can be initialized with an int, long, double or String - // or by initializing the unscaled value (BigInteger) and scale (int). - BigDecimal fooBigDecimal = new BigDecimal(fooBigInteger, fooInt); - - // Be wary of the constructor that takes a float or double as - // the inaccuracy of the float/double will be copied in BigDecimal. - // Prefer the String constructor when you need an exact value. - BigDecimal tenCents = new BigDecimal("0.1"); - - // Strings - String fooString = "My String Is Here!"; - - // \n is an escaped character that starts a new line - String barString = "Printing on a new line?\nNo Problem!"; - // \t is an escaped character that adds a tab character - String bazString = "Do you want to add a tab?\tNo Problem!"; - System.out.println(fooString); - System.out.println(barString); - System.out.println(bazString); - - // String Building - // #1 - with plus operator - // That's the basic way to do it (optimized under the hood) - String plusConcatenated = "Strings can " + "be concatenated " + "via + operator."; - System.out.println(plusConcatenated); - // Output: Strings can be concatenated via + operator. - - // #2 - with StringBuilder - // This way doesn't create any intermediate strings. It just stores the string pieces, and ties them together - // when toString() is called. - // Hint: This class is not thread safe. A thread-safe alternative (with some impact on performance) is StringBuffer. - StringBuilder builderConcatenated = new StringBuilder(); - builderConcatenated.append("You "); - builderConcatenated.append("can use "); - builderConcatenated.append("the StringBuilder class."); - System.out.println(builderConcatenated.toString()); // only now is the string built - // Output: You can use the StringBuilder class. - - // StringBuilder is efficient when the fully constructed String is not required until the end of some processing. - StringBuilder stringBuilder = new StringBuilder(); - String inefficientString = ""; - for(int i = 0 ; i < 10; i++){ - stringBuilder.append(i).append(" "); - inefficientString += i + " "; - } - System.out.println(inefficientString); - System.out.println(stringBuilder.toString()); - // inefficientString requires a lot more work to produce, as it generates a String on every loop iteration. - // Simple concatenation with + is compiled to a StringBuilder and toString() - // Avoid string concatenation in loops. - - // #3 - with String formatter - // Another alternative way to create strings. Fast and readable. - String.format("%s may prefer %s.", "Or you", "String.format()"); - // Output: Or you may prefer String.format(). - - // Arrays - // The array size must be decided upon instantiation - // The following formats work for declaring an array - // [] = new []; - // [] = new []; - int[] intArray = new int[10]; - String[] stringArray = new String[1]; - boolean boolArray[] = new boolean[100]; - - // Another way to declare & initialize an array - int[] y = {9000, 1000, 1337}; - String names[] = {"Bob", "John", "Fred", "Juan Pedro"}; - boolean bools[] = {true, false, false}; - - // Indexing an array - Accessing an element - System.out.println("intArray @ 0: " + intArray[0]); - - // Arrays are zero-indexed and mutable. - intArray[1] = 1; - System.out.println("intArray @ 1: " + intArray[1]); // => 1 - - // Other data types worth checking out - // ArrayLists - Like arrays except more functionality is offered, and - // the size is mutable. - // LinkedLists - Implementation of doubly-linked list. All of the - // operations perform as could be expected for a - // doubly-linked list. - // Maps - A set of objects that map keys to values. Map is - // an interface and therefore cannot be instantiated. - // The type of keys and values contained in a Map must - // be specified upon instantiation of the implementing - // class. Each key may map to only one corresponding value, - // and each key may appear only once (no duplicates). - // HashMaps - This class uses a hashtable to implement the Map - // interface. This allows the execution time of basic - // operations, such as get and insert element, to remain - // constant even for large sets. - // TreeMap - This class is a sorted tree structure. It implements a red - // black tree and sorts the entries based on the key value or - // the comparator provided while creating the object - - /////////////////////////////////////// - // Operators - /////////////////////////////////////// - System.out.println("\n->Operators"); - - int i1 = 1, i2 = 2; // Shorthand for multiple declarations - - // Arithmetic is straightforward - System.out.println("1+2 = " + (i1 + i2)); // => 3 - System.out.println("2-1 = " + (i2 - i1)); // => 1 - System.out.println("2*1 = " + (i2 * i1)); // => 2 - System.out.println("1/2 = " + (i1 / i2)); // => 0 (int/int returns int) - System.out.println("1/2 = " + (i1 / (double)i2)); // => 0.5 - - // Modulo - System.out.println("11%3 = "+(11 % 3)); // => 2 - - // Comparison operators - System.out.println("3 == 2? " + (3 == 2)); // => false - System.out.println("3 != 2? " + (3 != 2)); // => true - System.out.println("3 > 2? " + (3 > 2)); // => true - System.out.println("3 < 2? " + (3 < 2)); // => false - System.out.println("2 <= 2? " + (2 <= 2)); // => true - System.out.println("2 >= 2? " + (2 >= 2)); // => true - - // Boolean operators - System.out.println("3 > 2 && 2 > 3? " + ((3 > 2) && (2 > 3))); // => false - System.out.println("3 > 2 || 2 > 3? " + ((3 > 2) || (2 > 3))); // => true - System.out.println("!(3 == 2)? " + (!(3 == 2))); // => true - - // Bitwise operators! - /* - ~ Unary bitwise complement - << Signed left shift - >> Signed/Arithmetic right shift - >>> Unsigned/Logical right shift - & Bitwise AND - ^ Bitwise exclusive OR - | Bitwise inclusive OR - */ - - // Increment operators - int i = 0; - System.out.println("\n->Inc/Dec-rementation"); - // The ++ and -- operators increment and decrement by 1 respectively. - // If they are placed before the variable, they increment then return; - // after the variable they return then increment. - System.out.println(i++); // i = 1, prints 0 (post-increment) - System.out.println(++i); // i = 2, prints 2 (pre-increment) - System.out.println(i--); // i = 1, prints 2 (post-decrement) - System.out.println(--i); // i = 0, prints 0 (pre-decrement) - - /////////////////////////////////////// - // Control Structures - /////////////////////////////////////// - System.out.println("\n->Control Structures"); - - // If statements are c-like - int j = 10; - if (j == 10) { - System.out.println("I get printed"); - } else if (j > 10) { - System.out.println("I don't"); - } else { - System.out.println("I also don't"); - } - - // While loop - int fooWhile = 0; - while(fooWhile < 100) { - System.out.println(fooWhile); - // Increment the counter - // Iterated 100 times, fooWhile 0,1,2...99 - fooWhile++; - } - System.out.println("fooWhile Value: " + fooWhile); - - // Do While Loop - int fooDoWhile = 0; - do { - System.out.println(fooDoWhile); - // Increment the counter - // Iterated 99 times, fooDoWhile 0->99 - fooDoWhile++; - } while(fooDoWhile < 100); - System.out.println("fooDoWhile Value: " + fooDoWhile); - - // For Loop - // for loop structure => for(; ; ) - for (int fooFor = 0; fooFor < 10; fooFor++) { - System.out.println(fooFor); - // Iterated 10 times, fooFor 0->9 - } - System.out.println("fooFor Value: " + fooFor); - - // Nested For Loop Exit with Label - outer: - for (int i = 0; i < 10; i++) { - for (int j = 0; j < 10; j++) { - if (i == 5 && j ==5) { - break outer; - // breaks out of outer loop instead of only the inner one - } - } - } - - // For Each Loop - // The for loop is also able to iterate over arrays as well as objects - // that implement the Iterable interface. - int[] fooList = {1, 2, 3, 4, 5, 6, 7, 8, 9}; - // for each loop structure => for ( : ) - // reads as: for each element in the iterable - // note: the object type must match the element type of the iterable. - for (int bar : fooList) { - System.out.println(bar); - //Iterates 9 times and prints 1-9 on new lines - } - - // Switch Case - // A switch works with the byte, short, char, and int data types. - // It also works with enumerated types (discussed in Enum Types), the - // String class, and a few special classes that wrap primitive types: - // Character, Byte, Short, and Integer. - int month = 3; - String monthString; - switch (month) { - case 1: monthString = "January"; - break; - case 2: monthString = "February"; - break; - case 3: monthString = "March"; - break; - default: monthString = "Some other month"; - break; - } - System.out.println("Switch Case Result: " + monthString); - - // Starting in Java 7 and above, switching Strings works like this: - String myAnswer = "maybe"; - switch(myAnswer) { - case "yes": - System.out.println("You answered yes."); - break; - case "no": - System.out.println("You answered no."); - break; - case "maybe": - System.out.println("You answered maybe."); - break; - default: - System.out.println("You answered " + myAnswer); - break; - } - - - // Try-with-resources (Java 7+) - // Try-catch-finally statements work as expected in Java but in Java 7+ - // the try-with-resources statement is also available. Try-with-resources - // simplifies try-catch-finally statements be closing resources - // automatically. - - // In order to use a try-with-resources, include a an instance of a class - // in the try statement. The class must implement java.lang.AutoCloseable. - try(BufferedReader br = new BufferedReader(new FileReader("foo.txt"))) { - // You can attempt to do something that could throw an exception. - System.out.println(br.readLine()); - // In Java 7, the resource will always be closed, even if it throws - // an Exception. - } catch (Exception ex) { - //The resource will be closed before the catch statement executes. - System.out.println("readLine() failed."); - } - // No need for a finally statement in this case, the BufferedReader is - // already closed. This can be used to avoid certain edge cases where - // a finally statement might not be called. - // To learn more: - // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html - - - // Conditional Shorthand - // You can use the '?' operator for quick assignments or logic forks. - // Reads as "If (statement) is true, use , otherwise, use - // " - int foo = 5; - String bar = (foo < 10) ? "A" : "B"; - System.out.println(bar); // Prints A, because the statement is true - - //////////////////////////////////////// - // Converting Data Types And Typecasting - //////////////////////////////////////// - - // Converting data - - // Convert String To Integer - Integer.parseInt("123");//returns an integer version of "123" - - // Convert Integer To String - Integer.toString(123);//returns a string version of 123 - - // For other conversions check out the following classes: - // Double - // Long - // String - - // Typecasting - // You can also cast Java objects, there's a lot of details and deals - // with some more intermediate concepts. Feel free to check it out here: - // https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html - - /////////////////////////////////////// - // Classes And Functions - /////////////////////////////////////// - - System.out.println("\n->Classes & Functions"); - - // (definition of the Bicycle class follows) - - // Use new to instantiate a class - Bicycle trek = new Bicycle(); - - // Call object methods - trek.speedUp(3); // You should always use setter and getter methods - trek.setCadence(100); - - // toString returns this Object's string representation. - System.out.println("trek info: " + trek.toString()); - - // Double Brace Initialization - // The Java Language has no syntax for how to create static Collections - // in an easy way. Usually you end up in the following way: - private static final Set COUNTRIES = new HashSet(); - static { - COUNTRIES.add("DENMARK"); - COUNTRIES.add("SWEDEN"); - COUNTRIES.add("FINLAND"); - } - - // But there's a nifty way to achieve the same thing in an - // easier way, by using something that is called Double Brace - // Initialization. - private static final Set COUNTRIES = new HashSet() {{ - add("DENMARK"); - add("SWEDEN"); - add("FINLAND"); - }} - - // The first brace is creating a new AnonymousInnerClass and the - // second one declares an instance initializer block. This block - // is called when the anonymous inner class is created. - // This does not only work for Collections, it works for all - // non-final classes. - - } // End main method -} // End LearnJava class - -// You can include other, non-public outer-level classes in a .java file, -// but it is not good practice. Instead split classes into separate files. - -// Class Declaration Syntax: -// class { -// // data fields, constructors, functions all inside. -// // functions are called as methods in Java. -// } - -class Bicycle { - - // Bicycle's Fields/Variables - public int cadence; // Public: Can be accessed from anywhere - private int speed; // Private: Only accessible from within the class - protected int gear; // Protected: Accessible from the class and subclasses - String name; // default: Only accessible from within this package - static String className; // Static class variable - - // Static block - // Java has no implementation of static constructors, but - // has a static block that can be used to initialize class variables - // (static variables). - // This block will be called when the class is loaded. - static { - className = "Bicycle"; - } - - // Constructors are a way of creating classes - // This is a constructor - public Bicycle() { - // You can also call another constructor: - // this(1, 50, 5, "Bontrager"); - gear = 1; - cadence = 50; - speed = 5; - name = "Bontrager"; - } - // This is a constructor that takes arguments - public Bicycle(int startCadence, int startSpeed, int startGear, - String name) { - this.gear = startGear; - this.cadence = startCadence; - this.speed = startSpeed; - this.name = name; - } - - // Method Syntax: - // () - - // Java classes often implement getters and setters for their fields - - // Method declaration syntax: - // () - public int getCadence() { - return cadence; - } - - // void methods require no return statement - public void setCadence(int newValue) { - cadence = newValue; - } - public void setGear(int newValue) { - gear = newValue; - } - public void speedUp(int increment) { - speed += increment; - } - public void slowDown(int decrement) { - speed -= decrement; - } - public void setName(String newName) { - name = newName; - } - public String getName() { - return name; - } - - //Method to display the attribute values of this Object. - @Override // Inherited from the Object class. - public String toString() { - return "gear: " + gear + " cadence: " + cadence + " speed: " + speed + - " name: " + name; - } -} // end class Bicycle - -// PennyFarthing is a subclass of Bicycle -class PennyFarthing extends Bicycle { - // (Penny Farthings are those bicycles with the big front wheel. - // They have no gears.) - - public PennyFarthing(int startCadence, int startSpeed) { - // Call the parent constructor with super - super(startCadence, startSpeed, 0, "PennyFarthing"); - } - - // You should mark a method you're overriding with an @annotation. - // To learn more about what annotations are and their purpose check this - // out: http://docs.oracle.com/javase/tutorial/java/annotations/ - @Override - public void setGear(int gear) { - this.gear = 0; - } -} - -// Interfaces -// Interface declaration syntax -// interface extends { -// // Constants -// // Method declarations -// } - -// Example - Food: -public interface Edible { - public void eat(); // Any class that implements this interface, must - // implement this method. -} - -public interface Digestible { - public void digest(); - // In Java 8, interfaces can have default method. - // public void digest() { - // System.out.println("digesting ..."); - // } -} - -// We can now create a class that implements both of these interfaces. -public class Fruit implements Edible, Digestible { - @Override - public void eat() { - // ... - } - - @Override - public void digest() { - // ... - } -} - -// In Java, you can extend only one class, but you can implement many -// interfaces. For example: -public class ExampleClass extends ExampleClassParent implements InterfaceOne, - InterfaceTwo { - @Override - public void InterfaceOneMethod() { - } - - @Override - public void InterfaceTwoMethod() { - } - -} - -// Abstract Classes - -// Abstract Class declaration syntax -// abstract extends { -// // Constants and variables -// // Method declarations -// } - -// Marking a class as abstract means that it contains abstract methods that -// must be defined in a child class. Similar to interfaces, abstract classes -// cannot be instantiated, but instead must be extended and the abstract -// methods defined. Different from interfaces, abstract classes can contain a -// concrete and abstract methods. Methods in an interface cannot have a body, -// mixture of unless the method is static, and variables are final by default, -// unlike an abstract class. Also abstract classes CAN have the "main" method. -public abstract class Animal -{ - public abstract void makeSound(); - - // Method can have a body - public void eat() - { - System.out.println("I am an animal and I am Eating."); - // Note: We can access private variable here. - age = 30; - } - - // No need to initialize, however in an interface - // a variable is implicitly final and hence has - // to be initialized. - protected int age; - - public void printAge() - { - System.out.println(age); - } - - // Abstract classes can have main function. - public static void main(String[] args) - { - System.out.println("I am abstract"); - } -} - -class Dog extends Animal -{ - // Note still have to override the abstract methods in the - // abstract class. - @Override - public void makeSound() - { - System.out.println("Bark"); - // age = 30; ==> ERROR! age is private to Animal - } - - // NOTE: You will get an error if you used the - // @Override annotation here, since java doesn't allow - // overriding of static methods. - // What is happening here is called METHOD HIDING. - // Check out this SO post: http://stackoverflow.com/questions/16313649/ - public static void main(String[] args) - { - Dog pluto = new Dog(); - pluto.makeSound(); - pluto.eat(); - pluto.printAge(); - } -} - -// Final Classes - -// Final Class declaration syntax -// final { -// // Constants and variables -// // Method declarations -// } - -// Final classes are classes that cannot be inherited from and are therefore a -// final child. In a way, final classes are the opposite of abstract classes -// because abstract classes must be extended, but final classes cannot be -// extended. -public final class SaberToothedCat extends Animal -{ - // Note still have to override the abstract methods in the - // abstract class. - @Override - public void makeSound() - { - System.out.println("Roar"); - } -} - -// Final Methods -public abstract class Mammal() -{ - // Final Method Syntax: - // final () - - // Final methods, like, final classes cannot be overridden by a child - // class, and are therefore the final implementation of the method. - public final boolean isWarmBlooded() - { - return true; - } -} - -// Enum Type -// -// An enum type is a special data type that enables for a variable to be a set -// of predefined constants. The variable must be equal to one of the values -// that have been predefined for it. Because they are constants, the names of -// an enum type's fields are in uppercase letters. In the Java programming -// language, you define an enum type by using the enum keyword. For example, -// you would specify a days-of-the-week enum type as: -public enum Day { - SUNDAY, MONDAY, TUESDAY, WEDNESDAY, - THURSDAY, FRIDAY, SATURDAY -} - -// We can use our enum Day like that: -public class EnumTest { - // Variable Enum - Day day; - - public EnumTest(Day day) { - this.day = day; - } - - public void tellItLikeItIs() { - switch (day) { - case MONDAY: - System.out.println("Mondays are bad."); - break; - case FRIDAY: - System.out.println("Fridays are better."); - break; - case SATURDAY: - case SUNDAY: - System.out.println("Weekends are best."); - break; - default: - System.out.println("Midweek days are so-so."); - break; - } - } - - public static void main(String[] args) { - EnumTest firstDay = new EnumTest(Day.MONDAY); - firstDay.tellItLikeItIs(); // => Mondays are bad. - EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); - thirdDay.tellItLikeItIs(); // => Midweek days are so-so. - } -} - -// Enum types are much more powerful than we show above. -// The enum body can include methods and other fields. -// You can see more at https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html -``` - -## مطالب بیشتر - -لینکهای زیر را می توانید برای پیگیرهای بیشتر استفاده کنید. -البته همیشه گوگل را در کنار دستتان داشته باشید! - -**سایت های راهنمای اصلی**: - -* [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html) - -* [Java Access level modifiers](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - -* [Object-Oriented Programming Concepts](https://docs.oracle.com/javase/tutorial/java/concepts/index.html): - * [Inheritance](https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) - * [Polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) - * [Abstraction](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - -* [Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - -* [Interfaces](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - -* [Generics](https://docs.oracle.com/javase/tutorial/java/generics/index.html) - -* [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html) - -* New features in Java 8: - * [Lambda expressions (functional programming)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) - * [Date and time API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) - -**راهنما و سایت های آموزشی** - -* [Learneroo.com - Learn Java](http://www.learneroo.com) - -* [Codingbat.com](http://codingbat.com/java) - -**کتاب‌ها**: - -* [Head First Java](http://www.headfirstlabs.com/books/hfjava/) - -* [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) - -* [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) - -* [Java The Complete Reference](https://www.amazon.com/gp/product/0071606300) From 790a78e3cf1ec8610699ed34255d459f84a92a18 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Mon, 3 Jun 2024 13:31:20 -0600 Subject: [PATCH 273/392] Remove bare links --- ca-es/go-ca.html.markdown | 4 +- ca-es/groovy-ca.html.markdown | 19 ++--- cs-cz/python.html.markdown | 11 +-- cue.html.markdown | 24 +++--- de-de/perl-de.html.markdown | 2 +- docker.html.markdown | 16 ++-- es-es/c-es.html.markdown | 42 +++++----- es-es/coldfusion-es.html.markdown | 2 +- es-es/css-es.html.markdown | 8 +- es-es/groovy-es.html.markdown | 16 ++-- es-es/perl-es.html.markdown | 2 +- es-es/pythonstatcomp-es.html.markdown | 7 +- es-es/visualbasic-es.html.markdown | 12 +-- fa-ir/vim-fa.html.markdown | 1 + fr-fr/make-fr.html.markdown | 9 +-- fr-fr/perl-fr.html.markdown | 9 ++- fr-fr/wolfram-fr.html.markdown | 7 +- groovy.html.markdown | 16 ++-- hi-in/amd.html.markdown | 4 +- httpie.html.markdown | 9 +-- id-id/coffeescript-id.html.markdown | 6 +- it-it/pyqt-it.html.markdown | 26 +++---- it-it/rust-it.html.markdown | 4 +- java.html.markdown | 19 +---- jq.html.markdown | 10 +-- lt-lt/json-lt.html.markdown | 3 +- m.html.markdown | 67 ++++++++-------- ms-my/json-my.html.markdown | 3 +- no-nb/json-no.html.markdown | 6 +- openscad.html.markdown | 7 +- pl-pl/java-pl.html.markdown | 26 ++----- pt-br/c-pt.html.markdown | 4 +- pt-br/clojure-pt.html.markdown | 17 ++-- pt-br/emacs-pt.html.markdown | 12 +-- pt-br/go-pt.html.markdown | 28 +++---- pt-br/groovy-pt.html.markdown | 21 ++--- pt-br/httpie-pt.html.markdown | 8 +- pt-br/java-pt.html.markdown | 13 +--- pt-br/json-pt.html.markdown | 6 +- pt-br/perl-pt.html.markdown | 2 +- pt-br/php-composer-pt.html.markdown | 3 +- pt-br/pythonstatcomp-pt.html.markdown | 17 ++-- pt-br/rust-pt.html.markdown | 24 +++--- pt-br/solidity-pt.html.markdown | 22 ++---- pt-br/stylus-pt.html.markdown | 45 ++++++----- pt-br/swift-pt.html.markdown | 2 +- pt-br/visualbasic-pt.html.markdown | 8 +- pythonstatcomp.html.markdown | 9 ++- ru-ru/c-ru.html.markdown | 40 +++++----- ru-ru/perl-ru.html.markdown | 4 +- smalltalk.html.markdown | 1 - stylus.html.markdown | 36 ++++----- ta-in/xml-ta.html.markdown | 44 +++++------ tr-tr/c-tr.html.markdown | 107 +++++++++++++------------- zh-cn/angularjs-cn.html.markdown | 21 ++--- zh-cn/c++-cn.html.markdown | 6 +- zh-cn/c-cn.html.markdown | 17 ++-- zh-cn/groovy-cn.html.markdown | 19 ++--- zh-cn/perl-cn.html.markdown | 2 +- zh-cn/visualbasic-cn.html.markdown | 20 ++--- zh-tw/pcre-tw.html.markdown | 9 +-- 61 files changed, 418 insertions(+), 546 deletions(-) diff --git a/ca-es/go-ca.html.markdown b/ca-es/go-ca.html.markdown index 7bec4ba4..dc6a6748 100644 --- a/ca-es/go-ca.html.markdown +++ b/ca-es/go-ca.html.markdown @@ -432,8 +432,8 @@ func requestServer() { ## Més informació -L'arrel de tot en Go és la web oficial [official Go web site] -(https://go.dev/). Allà es pot seguir el tutorial, jugar interactivament +L'arrel de tot en Go és la web oficial [official Go web site](https://go.dev/). +Allà es pot seguir el tutorial, jugar interactivament i llegir molt més del que hem vist aquí.En el "tour", [the docs](https://go.dev/doc/) conté informació sobre com escriure codi net i efectiu en Go, comandes per empaquetar i generar documentació, i diff --git a/ca-es/groovy-ca.html.markdown b/ca-es/groovy-ca.html.markdown index 9e3dabe1..341cadae 100644 --- a/ca-es/groovy-ca.html.markdown +++ b/ca-es/groovy-ca.html.markdown @@ -10,7 +10,7 @@ translations: - ["Xavier Sala Pujolar", "http://github.com/utrescu"] --- -Groovy - Un llenguatge dinàmic per la plataforma Java [Llegir-ne més.](http://www.groovy-lang.org/) +Groovy - Un llenguatge dinàmic per la plataforma Java [Llegir-ne més](http://www.groovy-lang.org/). ```groovy /* @@ -285,7 +285,7 @@ def clos = { print it } clos( "hi" ) /* - Groovy pot recordar els resultats dels Closures [1][2][3] + Groovy pot recordar els resultats dels Closures */ def cl = {a, b -> sleep(3000) // simula un procés llarg @@ -420,17 +420,10 @@ assert sum(2,5) == 7 [Cònsola de Groovy](http://groovyconsole.appspot.com/) -Uneix-te a un [grup d'usuaris Groovy] -(http://www.groovy-lang.org/usergroups.html) +Uneix-te a un [grup d'usuaris Groovy](http://www.groovy-lang.org/usergroups.html) ## Llibres -* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) - -* [Groovy in Action] (http://manning.com/koenig2/) - -* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) - -[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ -[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize -[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html +* [Groovy Goodness](https://leanpub.com/groovy-goodness-notebook) +* [Groovy in Action](http://manning.com/koenig2/) +* [Programming Groovy 2: Dynamic Productivity for the Java Developer](http://shop.oreilly.com/product/9781937785307.do) diff --git a/cs-cz/python.html.markdown b/cs-cz/python.html.markdown index 0681c69d..3682ce3e 100644 --- a/cs-cz/python.html.markdown +++ b/cs-cz/python.html.markdown @@ -74,9 +74,9 @@ False or True # => True 0 and 2 # => 0 -5 or 0 # => -5 -# Při porovnání s boolean hodnotou nepoužívejte operátor rovnosti "==". +# Při porovnání s boolean hodnotou nepoužívejte operátor rovnosti "==". # Stejně jako u hodnoty None. -# Viz PEP8: https://www.python.org/dev/peps/pep-0008/ +# Viz PEP8: https://www.python.org/dev/peps/pep-0008/ 0 is False # => True 2 is True # => False 1 is True # => True @@ -156,7 +156,7 @@ print("Jsem 3. Python 3.") nazev_promenne = 5 nazev_promenne # => 5 # Názvy proměnných mohou obsahovat i unicode znaky, ale nedělejte to. -# Viz PEP 3131 -- Supporting Non-ASCII Identifiers: +# Viz PEP 3131 -- Supporting Non-ASCII Identifiers: # https://www.python.org/dev/peps/pep-3131/ název_proměnné = 5 @@ -640,5 +640,6 @@ pozdrav("Pepo") # Vypíše 3x: "Měj se Pepo!" ## Co dál? -Spoustu odkazů na české i anglické materiály najdete na [webu české Python komunity] -(http://python.cz/). Můžete také přijít na Pyvo, kde to společně probereme. +Spoustu odkazů na české i anglické materiály najdete na +[webu české Python komunity](http://python.cz/). Můžete +také přijít na Pyvo, kde to společně probereme. diff --git a/cue.html.markdown b/cue.html.markdown index a1a21086..1a6f0cc9 100644 --- a/cue.html.markdown +++ b/cue.html.markdown @@ -35,7 +35,7 @@ Now we can unify and export to JSON: Or YAML: ```bash -% cue export --out yaml name.cue disposition.cue +% cue export --out yaml name.cue disposition.cue name: Daniel disposition: oblivious ``` @@ -60,7 +60,7 @@ foo: 100 ``` ```bash -% cue export string_value.cue integer_value.cue +% cue export string_value.cue integer_value.cue foo: conflicting values "baz" and 100 (mismatched types string and int): integer_value.cue:1:6 string_value.cue:1:6 @@ -222,7 +222,7 @@ vatican_city: #Country & { } ``` -CUE may save you quite a bit of time with all the sugar it provides on top of mere JSON. Here we're defining, "modifying", and validating a nested structure in three lines: (Notice the `[]` syntax used around `string` to signal to the engine that `string` is a constraint, not a string in this case.) +CUE may save you quite a bit of time with all the sugar it provides on top of mere JSON. Here we're defining, "modifying", and validating a nested structure in three lines: (Notice the `[]` syntax used around `string` to signal to the engine that `string` is a constraint, not a string in this case.) ```yaml //paths.cue @@ -388,7 +388,7 @@ j: 8 < 10 // and supports boolean ops price: number // Require a justification if price is too high if price > 100 { - justification: string + justification: string } price: 200 justification: "impulse buy" @@ -400,11 +400,11 @@ comp: [ for x in #items if x rem 2 == 0 {x*x}] // and... well you can do this too #a: [ "Apple", "Google", "SpaceX"] for k, v in #a { - "\( strings.ToLower(v) )": { - pos: k + 1 - name: v - nameLen: len(v) - } + "\( strings.ToLower(v) )": { + pos: k + 1 + name: v + nameLen: len(v) + } } ``` @@ -481,7 +481,7 @@ This creates a `cue.mod/` subdirectory within that `mymodule` directory, and `cu - gen/ - usr/ -For a different perspective on this and details about what's in there, see https://cuelang.org/docs/concepts/packages/. For my purposes here, I'll say you don't need to think about the contents of this directory *at all*, except that your module name will be the prefix for all imports within your module. +For a different perspective on this and details about what's in there, see [cuelang.org/docs/concepts/packages/](https://cuelang.org/docs/concepts/packages/). For my purposes here, I'll say you don't need to think about the contents of this directory *at all*, except that your module name will be the prefix for all imports within your module. Where will your module file hierarchy go? All files and directories for your module are rooted in `mymodule/`, the directory that also contains `cue.mod/`. If you want to import a package, you'll prefix it with `example.com/mymodule`, followed by a relative path rooted in `mymodule/`. @@ -548,6 +548,6 @@ configuredBar: conflicting values string and 200 (mismatched types string and in That's it for now. I understand there are more package management features coming in the future and the design decisions around `cue.mod` are looking ahead to that. -Finally, CUE has built-in modules with powerful functionality. We saw one of these earlier, when we imported "strings" and used `strings.ToLower`. Imports without fully-qualified module names are assumed to be built-ins. The full list and documentation for each is here: https://pkg.go.dev/cuelang.org/go/pkg +Finally, CUE has built-in modules with powerful functionality. We saw one of these earlier, when we imported "strings" and used `strings.ToLower`. Imports without fully-qualified module names are assumed to be built-ins. The full list and documentation for each is here: [pkg.go.dev/cuelang.org/go/pkg](https://pkg.go.dev/cuelang.org/go/pkg) -This has been a condensation of the official docs and tutorials, so go give the source material some love: https://cuelang.org/docs/tutorials/ +This has been a condensation of the official docs and tutorials, so go give the source material some love: [cuelang.org/docs/tutorials/](https://cuelang.org/docs/tutorials/) diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown index 13c00b01..71e775d7 100644 --- a/de-de/perl-de.html.markdown +++ b/de-de/perl-de.html.markdown @@ -157,7 +157,7 @@ logger("We have a logger subroutine!"); #### Verwenden von Perl Modulen -Perl Module liefern eine Menge an Funktionen die dabei Helfen das Rad nicht neu erfinden zu müssen. Perl Module können von CPAN (http://www.cpan.org/) heruntergeladen werden. Einige populäre Module sind in der Perl Distribution selbst bereits enthalten. +Perl Module liefern eine Menge an Funktionen die dabei Helfen das Rad nicht neu erfinden zu müssen. Perl Module können von [CPAN](http://www.cpan.org/) heruntergeladen werden. Einige populäre Module sind in der Perl Distribution selbst bereits enthalten. Perlfaq enthält Fragen und Antworten zu häufig vorkommenden Aufgaben. Sehr oft sind auch Vorschläge enthalten welches CPAN module am besten geeignet ist. diff --git a/docker.html.markdown b/docker.html.markdown index 6853451f..dd8fc0a6 100644 --- a/docker.html.markdown +++ b/docker.html.markdown @@ -12,7 +12,7 @@ contributors: Docker is a tool that helps you build, test, ship and run applications seamlessly across various machines. It replicates the environment our software needs on any machine. You can get Docker for your machine from -https://docs.docker.com/get-docker/ +[docs.docker.com/get-docker/](https://docs.docker.com/get-docker/) It has grown in popularity over the last decade due to being lightweight and fast as compared to virtual-machines that are bulky and slow. Unlike VMs, docker @@ -65,7 +65,6 @@ in a limited capacity architecture. │ Hardware Infrastructure │ └──────────────────────────────────────────────────┘ (Docker based architecture) - Couple of terms we will encounter frequently are Docker Images and Docker @@ -148,7 +147,7 @@ $ docker ps -a $ docker stop hello-world # or -$ docker start hello-world +$ docker start hello-world # The stop command simply stops one or more containers, and the start command # starts the container(s) up again! `docker start -a ubuntu` will attach our # detached container back to the terminal i.e. runs in the foreground @@ -174,7 +173,7 @@ $ docker images # alpine latest 9c6f07244728 3 months ago 5.54MB # hello-world latest feb5d9fea6a5 13 months ago 13.3kB -$ docker rmi +$ docker rmi # Removes one or more images from your system which do not have their instances # (or containers as we know them) running. If the image has an attached # container, either delete the container first or use the -f (or --force) flag @@ -204,12 +203,13 @@ $ docker logs ## The Dockerfile The Dockerfile is a blueprint of a Docker image. We can mention the artifacts -from our application along with their configurations into this file in the +from our application along with their configurations into this file in the specific syntax to let anyone create a Docker image of our application. ### A few things to keep in mind: + * It is always strictly named `Dockerfile` without any extensions -* We have to build our custom image on top of some already available Docker base +* We have to build our custom image on top of some already available Docker base image. (there is an empty image called `scratch` which literally lets you build an image from scratch) * All capitalised commands are part of the syntax, they are not case-sensitive @@ -236,7 +236,7 @@ ENTRYPOINT ["some-script.sh"] # executes an entire script as an entrypoint CMD [,...] -# always part of dockerfile, introduces entry point linux command e.g. +# always part of dockerfile, introduces entry point linux command e.g. # `CMD node server.js` # This executes after image creation only when the container from the image # is running. @@ -263,7 +263,7 @@ password on Docker Hub. When pushing an image to Docker Hub, we must specify our Docker Hub username as part of the source image name. We need to create the target image with the -tag name of username/image-name much like GitHub repositories. +tag name of username/image-name much like GitHub repositories. ```bash $ docker login diff --git a/es-es/c-es.html.markdown b/es-es/c-es.html.markdown index 8adeda87..6f9968e6 100644 --- a/es-es/c-es.html.markdown +++ b/es-es/c-es.html.markdown @@ -9,7 +9,7 @@ translators: lang: es-es --- -¡Ah!, C. Aun hoy en día sigue siendo el lenguaje por excelencia de la +¡Ah!, C. Aun hoy en día sigue siendo el lenguaje por excelencia de la computación moderna de alto rendimiento. C es el lenguaje de más bajo nivel que la mayoría de los programadores @@ -64,7 +64,7 @@ char y_char = 'y'; // Los caracteres literales se entrecomillan con '' // 'longs' son a menudo de 4 a 8 bytes; 'long longs' son fijo de por lo // menos 64 bits long x_long = 0; -long long x_long_long = 0; +long long x_long_long = 0; // 'floats' son normalmente números de coma flotante de 32 bits float x_float = 0.0; @@ -80,7 +80,7 @@ unsigned short ux_short; unsigned int ux_int; unsigned long long ux_long_long; -// Todos menos 'char', que es siempre de 1 byte, varían el tamaño +// Todos menos 'char', que es siempre de 1 byte, varían el tamaño // dependiendo de tu máquina. sizeof(T) te dice el tamaño de una variable // de tipo T en bytes por lo que podemos expresar el tamaño de estos tipos // portatilmente. @@ -114,7 +114,7 @@ printf("%s\n", a_string); // %s se sutituye por una cadena. /* Te habrás dado cuenta de que a_string es solo de 18 caracteres. -El 'char' #19 es el byte nulo. +El 'char' #19 es el byte nulo. El 'char' #20 es de valor indefinido. */ @@ -139,7 +139,7 @@ f1 / f2; // => 0.5, más o menos épsilon // Los operadores de comparación te resultaran familiares, pero no hay // booleanos en C. Usamos enteros (ints) en su lugar. 0 es falso, -// cualquier otra cosa es verdadero. (Los operadores de comparación +// cualquier otra cosa es verdadero. (Los operadores de comparación // siempre devuelven 0 o 1) 3 == 2; // => 0 (Falso) 3 != 2; // => 1 (Verdadero) @@ -226,8 +226,8 @@ printf("%d\n", (char)100.0); // Punteros /////////////////////////////////////// -// Un puntero es una variable declarada para almacenar una dirección de -// memoria. Su declaración además nos dirá el tipo de dato al que apunta. +// Un puntero es una variable declarada para almacenar una dirección de +// memoria. Su declaración además nos dirá el tipo de dato al que apunta. // Puedes obtener la dirección de memoria de tus variables, y después // enlazarlas con ellos. @@ -242,7 +242,7 @@ px = &x; // Almacena la dirección de x en px printf("%p\n", px); // => Muestra alguna dirección de memoria // Para obtener el valor de la dirección a la que apunta un puntero, pon -// * delante para desreferenciarle. +// * delante para desreferenciarle. printf("%d\n", *px); // => Muestra 0, el valor de x y de la dirección a la // que apunta px @@ -285,7 +285,7 @@ for (xx=0; xx<20; xx++) { // impredecibles printf("%d\n", *(my_ptr + 21)); // => Prints who-knows-what? -// Cuando hayas acabado con el bloque de memoría malloc, necesitas +// Cuando hayas acabado con el bloque de memoría malloc, necesitas // liberarlo o sino nadie más podrá usarlo hasta que tu programa se cierre free(my_ptr); @@ -310,8 +310,8 @@ int add_two_ints(int x1, int x2){ } /* -Las funciones son de paso por valor, pero puedes hacer tus propias -referencias con punteros de manera que las funciones puedan cambiar sus +Las funciones son de paso por valor, pero puedes hacer tus propias +referencias con punteros de manera que las funciones puedan cambiar sus valores. Ejemplo: invertidor de cadenas in-situ @@ -320,7 +320,7 @@ Ejemplo: invertidor de cadenas in-situ // Una función 'void' no retorna valor void str_reverse(char* str_in){ char tmp; - int ii=0, len = strlen(str_in); // Strlen es parte de la librería + int ii=0, len = strlen(str_in); // Strlen es parte de la librería for(ii=0; ii sleep(3000) // simula algún proceso que consume tiempo @@ -422,12 +422,6 @@ assert sum(2,5) == 7 ## Libros -* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) - -* [Groovy in Action] (http://manning.com/koenig2/) - -* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) - -[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ -[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize -[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html +* [Groovy Goodness](https://leanpub.com/groovy-goodness-notebook) +* [Groovy in Action](http://manning.com/koenig2/) +* [Programming Groovy 2: Dynamic Productivity for the Java Developer](http://shop.oreilly.com/product/9781937785307.do) diff --git a/es-es/perl-es.html.markdown b/es-es/perl-es.html.markdown index 6d1507a0..ffcaad9b 100644 --- a/es-es/perl-es.html.markdown +++ b/es-es/perl-es.html.markdown @@ -143,7 +143,7 @@ logger("Tenemos una subrutina logger!"); #### Utilizando módulos Perl -Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde CPAN ( http://www.cpan.org/ ). Algunos de los módulos más populares ya están incluidos con la misma distribución de Perl. +Los módulos en Perl proveen de una gama de funciones que le pueden ayudar a evitar reinventar la rueda. Éstas se pueden descargar desde [CPAN](http://www.cpan.org/). Algunos de los módulos más populares ya están incluidos con la misma distribución de Perl. perlfaq contiene preguntas y respuestas relacionadas con muchas tareas comunes, y algunas veces provee sugerencias sobre buenos módulos de CPAN que puede usar. diff --git a/es-es/pythonstatcomp-es.html.markdown b/es-es/pythonstatcomp-es.html.markdown index 96ce2c1c..2efdfe14 100644 --- a/es-es/pythonstatcomp-es.html.markdown +++ b/es-es/pythonstatcomp-es.html.markdown @@ -231,8 +231,9 @@ sns.lmplot("BirthY", "EstAge", data=hre); Si quieres aprender más, obtén _Python for Data Analysis_ por Wes McKinney. Es un extraordinario recurso usado como referencia para escribir este tutorial. -También puedes encontrar gran cantidad de tutoriales interactivos de IPython en temas específicos a tus intereses, como Pilon de Cam Davidson Probabilistic Programming and Bayesian Methods for Hackers. +También puedes encontrar gran cantidad de tutoriales interactivos de IPython en temas específicos a tus intereses, como Pilon de Cam Davidson [Probabilistic Programming and Bayesian Methods for Hackers](http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). Ver más módulos para investigar: - - análisis de texto y procesamiento natural del lenguaje: nltk, http://www.nltk.org - - análisis de redes sociales: igraph, http://igraph.org/python/ + + - análisis de texto y procesamiento natural del lenguaje: [nltk](http://www.nltk.org) + - análisis de redes sociales: [igraph](http://igraph.org/python/) diff --git a/es-es/visualbasic-es.html.markdown b/es-es/visualbasic-es.html.markdown index 6f42b430..eead182c 100644 --- a/es-es/visualbasic-es.html.markdown +++ b/es-es/visualbasic-es.html.markdown @@ -20,7 +20,7 @@ Module Module1 ' Dicho sistema se explicará a medida que avancemos en este ' tutorial; gradualmente entenderás lo que significa todo. Console.Title = ("Aprende X en Y minutos") - Console.WriteLine("NAVEGACIÓN") 'Mostrar + Console.WriteLine("NAVEGACIÓN") 'Mostrar Console.WriteLine("") Console.ForegroundColor = ConsoleColor.Green Console.WriteLine("1. Salida «Hola, mundo»") @@ -42,7 +42,7 @@ Module Module1 Case "2" 'Entrada «hola, mundo» Console.Clear() EntradaHolaMundo() - Case "3" 'Calcular números enteros + Case "3" 'Calcular números enteros Console.Clear() CalcularNumerosEnteros() Case "4" 'Calcular números decimales @@ -77,7 +77,7 @@ Module Module1 'Uno - He usado números para guiarme por el sistema de navegación anterior 'cuando regrese posteriormente a implementarlo. - 'Usamos subrutinas privadas para separar distintas secciones del programa. + 'Usamos subrutinas privadas para separar distintas secciones del programa. Private Sub SalidaHolaMundo() 'Título de la aplicación de consola Console.Title = "Salida «Hola, mundo» | Aprende X en Y minutos" @@ -212,7 +212,7 @@ Module Module1 Console.Title = "Uso de bucles «For» | Aprende X en Y minutos" 'Declarar Variable y desde qué número debe contar en Step -1, 'Step -2, Step -3, etc. - For i As Integer = 10 To 0 Step -1 + For i As Integer = 10 To 0 Step -1 Console.WriteLine(i.ToString) 'Muestra el valor del contador Next i 'Calcular el valor nuevo Console.WriteLine("Iniciar") '¡¡Comencemos el programa, nene!! @@ -278,6 +278,6 @@ End Module Aprendí Visual Basic en la aplicación de consola. Esta me permitió entender los principios de la programación para, posteriormente, aprender otros lenguajes con facilidad. -He creado un tutorial de Visual Basic más exhaustivo para quienes quieran saber más. +He creado un [tutorial de Visual Basic](http://www.vbbootcamp.co.uk/) más exhaustivo para quienes quieran saber más. -Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa. +Toda la sintaxis es válida. Copia el código y pégalo en el compilador de Visual Basic y ejecuta (F5) el programa. diff --git a/fa-ir/vim-fa.html.markdown b/fa-ir/vim-fa.html.markdown index 4510e383..fb281299 100644 --- a/fa-ir/vim-fa.html.markdown +++ b/fa-ir/vim-fa.html.markdown @@ -29,6 +29,7 @@ filename: LearnVim-fa.txt ``` vim # Open in vim ``` +

    باز کردن help docs های `` اگر وجود داشته باشد

    diff --git a/fr-fr/make-fr.html.markdown b/fr-fr/make-fr.html.markdown index 5d8b9404..66f820f3 100644 --- a/fr-fr/make-fr.html.markdown +++ b/fr-fr/make-fr.html.markdown @@ -255,14 +255,11 @@ endif ### En français -+ [Introduction à Makefile (developpez.com)] -(http://gl.developpez.com/tutoriel/outil/makefile/), -+ [Compilez sous GNU/Linux ! (openclassrooms)] -(https://openclassrooms.com/courses/compilez-sous-gnu-linux). ++ [Introduction à Makefile (developpez.com)](http://gl.developpez.com/tutoriel/outil/makefile/), ++ [Compilez sous GNU/Linux ! (openclassrooms)](https://openclassrooms.com/courses/compilez-sous-gnu-linux). ### En anglais + [Documentation de GNU make](https://www.gnu.org/software/make/manual/), + [Software carpentry tutorial](http://swcarpentry.github.io/make-novice/), -+ Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) -[ex28](http://c.learncodethehardway.org/book/ex28.html). ++ Learn C the hard way [ex2](http://c.learncodethehardway.org/book/ex2.html) [ex28](http://c.learncodethehardway.org/book/ex28.html). diff --git a/fr-fr/perl-fr.html.markdown b/fr-fr/perl-fr.html.markdown index e073bcf5..5b795cdf 100644 --- a/fr-fr/perl-fr.html.markdown +++ b/fr-fr/perl-fr.html.markdown @@ -48,8 +48,8 @@ my %fruit_couleur = ("pomme", "rouge", "banane", "jaune"); # Vous pouvez utiliser des espaces et l'opérateur "=>" pour les disposer plus joliment : my %fruit_couleur = ( - pomme => "rouge", - banane => "jaune" + pomme => "rouge", + banane => "jaune" ); # Les scalaires, tableaux et hashes sont plus amplement documentés dans le perldata @@ -105,7 +105,7 @@ for my $element (@elements) { # de la plupart des fonctions pour en simplifier l'écriture. # Dans l'exemple suivant, $_ prends successivement la valeur de -# chaque élément de la liste. +# chaque élément de la liste. for (@elements) { print; # affiche le contenu de $_ @@ -163,11 +163,12 @@ logger("On a une fonction de logging!!"); #### Utiliser des modules Perl -Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis CPAN (http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl. +Les modules Perl fournissent une palette de fonctionnalités vous évitant de réinventer la roue et peuvent être téléchargés depuis [CPAN](http://www.cpan.org/). Un certain nombre de modules populaires sont inclus dans la distribution même de Perl. Perlfaq contiens des questions et réponses liées aux tâches habituelles et propose souvent des suggestions quant aux bons modules à utiliser. #### Pour en savoir plus + - [perl-tutorial](http://perl-tutorial.org/) - [Learn at www.perl.com](http://www.perl.org/learn.html) - [perldoc](http://perldoc.perl.org/) diff --git a/fr-fr/wolfram-fr.html.markdown b/fr-fr/wolfram-fr.html.markdown index 10a37994..4cc9045e 100644 --- a/fr-fr/wolfram-fr.html.markdown +++ b/fr-fr/wolfram-fr.html.markdown @@ -12,7 +12,7 @@ Le langage Wolfram est utilisé dans les programmes suivants : * La ligne de commandes interactive noyau du Raspberry Pi, mais elle ne peut pas gérer des éléments graphiques. * _Mathematica_, un éditeur de texte riche spécialisé pour les mathématiques : -appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule +appuyer sur `Shift + Entrée` dans une cellule de code crée un nouvelle cellule contenant le résultat. * _Wolfram Wokbench_, une variante d'Eclipse spécialisée pour le langage Wolfram. @@ -138,7 +138,7 @@ FoldList[Plus, 0, liste] (* {0, 1, 3, 6, 10}, variante de la fonction précédente qui donne aussi les résultats intermédiaires *) Append[liste, 5] (* {1, 2, 3, 4, 5}, liste n'est pas modifiée... *) -Prepend[liste, 5] (* {5, 1, 2, 3, 4}, ... mais elle peut l'être en +Prepend[liste, 5] (* {5, 1, 2, 3, 4}, ... mais elle peut l'être en écrivant "liste = " *) Join[liste, {3, 4}] (* {1, 2, 3, 4, 3, 4} *) liste[[2]] = 5 (* {1, 5, 3, 4}, ceci modifie bien la liste *) @@ -163,5 +163,4 @@ Manipulate[y^2, {y, 0, 20}] (* Crée une interface graphique interactive qui ## Envie d'aller plus loin ? -* [Documentation du langage Wolfram (en anglais)] -(http://reference.wolfram.com/language/) +* [Documentation du langage Wolfram (en anglais)](http://reference.wolfram.com/language/) diff --git a/groovy.html.markdown b/groovy.html.markdown index 1dc6abb0..a9ca6836 100644 --- a/groovy.html.markdown +++ b/groovy.html.markdown @@ -6,7 +6,7 @@ contributors: filename: learngroovy.groovy --- -Groovy - A dynamic language for the Java platform [Read more here.](http://www.groovy-lang.org/) +[Groovy](http://www.groovy-lang.org/) is a dynamic language for the Java platform ```groovy /* @@ -299,7 +299,7 @@ def clos = { print it } clos( "hi" ) /* - Groovy can memoize closure results [1][2][3] + Groovy can memoize closure results */ def cl = {a, b -> sleep(3000) // simulate some time consuming processing @@ -438,12 +438,6 @@ Join a [Groovy user group](http://www.groovy-lang.org/usergroups.html) ## Books -* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) - -* [Groovy in Action] (http://manning.com/koenig2/) - -* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) - -[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ -[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize -[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html +* [Groovy Goodness](https://leanpub.com/groovy-goodness-notebook) +* [Groovy in Action](http://manning.com/koenig2/) +* [Programming Groovy 2: Dynamic Productivity for the Java Developer](http://shop.oreilly.com/product/9781937785307.do) diff --git a/hi-in/amd.html.markdown b/hi-in/amd.html.markdown index 3604efb5..437c98c2 100644 --- a/hi-in/amd.html.markdown +++ b/hi-in/amd.html.markdown @@ -198,12 +198,12 @@ $ r.js -o app.build.js * [उन्नत विन्यास](http://requirejs.org/docs/api.html#config) * [शिम विन्यास (गैर एएमडी मॉड्यूल लोडिंग)](http://requirejs.org/docs/api.html#config-shim) * [सीएसएस लदान और require.js साथ अनुकूलन](http://requirejs.org/docs/optimization.html#onecss) -* [बनाता है के लिए almond.js का प्रयोग](Https://github.com/jrburke/almond) +* [बनाता है के लिए almond.js का प्रयोग](https://github.com/jrburke/almond) ### अग्रिम पठन: * [सरकारी कल्पना](https://github.com/amdjs/amdjs-api/wiki/AMD) -* [क्यों एएमडी?](Http://requirejs.org/docs/whyamd.html) +* [क्यों एएमडी?](http://requirejs.org/docs/whyamd.html) * [यूनिवर्सल मॉड्यूल परिभाषा](https://github.com/umdjs/umd) ### कार्यान्वयन: diff --git a/httpie.html.markdown b/httpie.html.markdown index 40481dff..2b68f287 100644 --- a/httpie.html.markdown +++ b/httpie.html.markdown @@ -26,8 +26,8 @@ http --offline https://api.example.com/posts ### URL shortcuts for `localhost` -HTTPie supports a curl-like shorthand for localhost. For instance, ":3000" -expands to "http://localhost:3000". If the port is omitted, it assumes port 80. +HTTPie supports a curl-like shorthand for localhost. For instance, `:3000` +expands to `http://localhost:3000`. If the port is omitted, it assumes port 80. ```bash http :/users # http://localhost/users @@ -48,7 +48,6 @@ http https://api.example.com/tags title="Tutorial" slug="tutorial" # POST a new ## Querystring Parameters - If you're manually adding query string parameters in the terminal, try the `param==value` syntax. It avoids shell escaping for & separators and automatically URL-escapes special characters in parameter names and values. @@ -116,5 +115,5 @@ http --follow GET https://example.com # Follow Redirects ## Further Reading -- [Official Documentation](https://httpie.io/docs/cli). -- [GitHub](https://github.com/httpie). +- [Official Documentation](https://httpie.io/docs/cli) +- [GitHub](https://github.com/httpie) diff --git a/id-id/coffeescript-id.html.markdown b/id-id/coffeescript-id.html.markdown index fc876184..b1450b87 100644 --- a/id-id/coffeescript-id.html.markdown +++ b/id-id/coffeescript-id.html.markdown @@ -10,7 +10,7 @@ lang: id-id --- CoffeeScript adalah bahasa sederhana yang diterjemahkan saat kompilasi ke dalam JavaScript, -dan bukan diterjemahkan pada saat *runtime*. +dan bukan diterjemahkan pada saat *runtime*. CoffeeScript mencoba agar kode JavaScript yang dihasilkan tetap mudah dibaca dan kompatibel dengan semua *runtime* JavaScript. @@ -102,5 +102,5 @@ makan sayuran for sayuran in sayur_sayuran when sayuran isnt 'kemangi' ## Referensi Tambahan -- [Smooth CoffeeScript (EN)] (http://autotelicum.github.io/Smooth-CoffeeScript/) -- [CoffeeScript Ristretto (EN)] (https://leanpub.com/coffeescript-ristretto/read) +- [Smooth CoffeeScript (EN)](http://autotelicum.github.io/Smooth-CoffeeScript/) +- [CoffeeScript Ristretto (EN)](https://leanpub.com/coffeescript-ristretto/read) diff --git a/it-it/pyqt-it.html.markdown b/it-it/pyqt-it.html.markdown index 8daba022..3ebd8759 100644 --- a/it-it/pyqt-it.html.markdown +++ b/it-it/pyqt-it.html.markdown @@ -11,32 +11,32 @@ lang: it-it **Qt** è un framework ampiamente conosciuto per lo sviluppo di software multipiattaforma che può essere eseguito su varie piattaforme software e hardware con modifiche minime o nulle nel codice, pur avendo la potenza e la velocità delle applicazioni native. Sebbene **Qt** sia stato originariamente scritto in *C++*. - -Questo è un adattamento sull'introduzione di C ++ a QT di [Aleksey Kholovchuk] (https://github.com/vortexxx192 -), alcuni degli esempi di codice dovrebbero avere la stessa funzionalità -che avrebbero se fossero fatte usando pyqt! +Questo è un adattamento sull'introduzione di C ++ a QT di +[Aleksey Kholovchuk](https://github.com/vortexxx192), alcuni +degli esempi di codice dovrebbero avere la stessa +funzionalità che avrebbero se fossero fatte usando pyqt! ```python import sys from PyQt4 import QtGui def window(): - # Crea un oggetto applicazione + # Crea un oggetto applicazione app = QtGui.QApplication(sys.argv) - # Crea un widget in cui verrà inserita la nostra etichetta + # Crea un widget in cui verrà inserita la nostra etichetta w = QtGui.QWidget() - # Aggiungi un'etichetta al widget + # Aggiungi un'etichetta al widget b = QtGui.QLabel(w) - # Imposta del testo per l'etichetta + # Imposta del testo per l'etichetta b.setText("Ciao Mondo!") - # Fornisce informazioni su dimensioni e posizionamento + # Fornisce informazioni su dimensioni e posizionamento w.setGeometry(100, 100, 200, 50) b.move(50, 20) - # Dai alla nostra finestra un bel titolo + # Dai alla nostra finestra un bel titolo w.setWindowTitle("PyQt") - # Visualizza tutto + # Visualizza tutto w.show() - # Esegui ciò che abbiamo chiesto, una volta che tutto è stato configurato + # Esegui ciò che abbiamo chiesto, una volta che tutto è stato configurato sys.exit(app.exec_()) if __name__ == '__main__': @@ -60,7 +60,7 @@ def window(): b.setText("Premimi") b.move(50, 50) # Indica a b di chiamare questa funzione quando si fa clic -    # notare la mancanza di "()" sulla chiamata di funzione + # notare la mancanza di "()" sulla chiamata di funzione b.clicked.connect(showdialog) w.setWindowTitle("PyQt Dialog") w.show() diff --git a/it-it/rust-it.html.markdown b/it-it/rust-it.html.markdown index ff42df8d..c26fa599 100644 --- a/it-it/rust-it.html.markdown +++ b/it-it/rust-it.html.markdown @@ -300,7 +300,7 @@ fn main() { *ref_var2 += 2; // '*' serve a puntare al binding var2, preso in presto mutevolmente println!("{}", *ref_var2); // 6 - // var2 non compilerebbe. ref_var2 è di tipo &mut i32, e quindi + // var2 non compilerebbe. ref_var2 è di tipo &mut i32, e quindi // immagazzina un riferimento a un i32, e non il valore stesso. // var2 = 2; // questo non compilerebbe, perché `var2` è stato preso in prestito } @@ -312,7 +312,7 @@ C'è molto di più in Rust — questi sono solo i fondamenti di Rust, che servon le cose più importanti. Purtroppo c'è pochissima documentazione in italiano, tra cui: -(https://www.mozillaitalia.org/home/2015/05/30/primi-passi-con-rust/) +[mozillaitalia.org/home/2015/05/30/primi-passi-con-rust/](https://www.mozillaitalia.org/home/2015/05/30/primi-passi-con-rust/) Però ce n'è parecchia in inglese. Per saperne di più, leggi [The Rust Programming Language](http://doc.rust-lang.org/book/index.html) e tieni d'occhio l'area di interesse di Reddit (subreddit) diff --git a/java.html.markdown b/java.html.markdown index 14664625..20156365 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -1012,45 +1012,32 @@ public class Lambdas { The links provided here below are just to get an understanding of the topic, feel free to Google and find specific examples. -**Official Oracle Guides**: +### Official Oracle Guides * [Java Tutorial Trail from Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html) - * [Java Access level modifiers](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - * [Object-Oriented Programming Concepts](https://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Inheritance](https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstraction](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - * [Exceptions](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - * [Interfaces](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - * [Generics](https://docs.oracle.com/javase/tutorial/java/generics/index.html) - * [Java Code Conventions](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html) - * New features in Java 8: * [Lambda expressions (functional programming)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) * [Date and time API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) -**Online Practice and Tutorials** +### Online Practice and Tutorials * [Learneroo.com - Learn Java](http://www.learneroo.com) - * [Codingbat.com](http://codingbat.com/java) - * [Codewars - Java Katas](https://www.codewars.com/?language=java) - * [University of Helsinki - Object-Oriented programming with Java](http://moocfi.github.io/courses/2013/programming-part-1/) -**Books**: +### Books * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) - * [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) - * [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) - * [Java The Complete Reference](https://www.amazon.com/gp/product/0071606300) diff --git a/jq.html.markdown b/jq.html.markdown index dded34cb..bfcc9ecc 100644 --- a/jq.html.markdown +++ b/jq.html.markdown @@ -902,9 +902,9 @@ jq -n ' # - `def f($a; $b): ...;` is a shorthand for: `def f(a; b): a as $a | b as $b | ...` ``` - ## Further Reading -- https://stedolan.github.io/jq/manual/ -- https://github.com/stedolan/jq/wiki/jq-Language-Description -- https://github.com/stedolan/jq/wiki/Cookbook -- https://github.com/stedolan/jq/blob/master/src/builtin.jq + +- [jq Manual](https://jqlang.github.io/jq/manual/) +- [Language Description](https://github.com/jqlang/jq/wiki/jq-Language-Description) +- [Cookbook](https://github.com/jqlang/jq/wiki/Cookbook) +- [builtin.jq](https://github.com/jqlang/jq/blob/master/src/builtin.jq) diff --git a/lt-lt/json-lt.html.markdown b/lt-lt/json-lt.html.markdown index 50e52a7a..a0a0a82e 100644 --- a/lt-lt/json-lt.html.markdown +++ b/lt-lt/json-lt.html.markdown @@ -18,9 +18,10 @@ Failo plėtinys JSON failams yra „.json“, o MIME tipas yra „application/js Dauguma programavimo kalbų palaiko JSON duomenų serializaciją (kodavimą) ir deserializaciją (dekodavimą) į natyviasias duomenų struktūras. Javascript turi visišką JSON teksto kaip duomenų manipuliavimo palaikymą. -Daugiau informacijos galima rasti http://www.json.org/ +Daugiau informacijos galima rasti [json.org](http://www.json.org/) JSON yra pastatytas iš dviejų struktūrų: + * Vardų/reikšmių porų rinkinys. Daugomoje kalbų, tai yra realizuojama kaip objektas, įrašas, struktūra, žodynas, hash lentelė, sąrašas su raktais arba asociatyvusis masyvas. * Rūšiuotas reikšmių sąrašas. Daugumoje kalbų, toks sąrašas yra realizuojama kaip masyvas, vektorius, sąrašas arba seka. diff --git a/m.html.markdown b/m.html.markdown index 3ea422c4..a3885d6d 100644 --- a/m.html.markdown +++ b/m.html.markdown @@ -1,8 +1,8 @@ ---- +--- language: M (MUMPS) -contributors: - - ["Fred Turkington", "http://z3ugma.github.io"] -filename: LEARNM.m +contributors: + - ["Fred Turkington", "http://z3ugma.github.io"] +filename: LEARNM.m --- M, or MUMPS (Massachusetts General Hospital Utility Multi-Programming System) is @@ -22,7 +22,7 @@ to modern formats like JSON. Originally designed in 1966 for the healthcare applications, M continues to be used widely by healthcare systems and financial institutions for high-throughput -real-time applications. +real-time applications. ### Example @@ -72,12 +72,12 @@ Commands are case insensitive, and have full form, and a shortened abbreviation, #### Common Commands from all National and International Standards of M -#### Write (abbreviated as W) +#### Write (abbreviated as W) Print data to the current device. -``` -WRITE !,"hello world" +``` +WRITE !,"hello world" ``` Output Formatting characters: @@ -89,7 +89,7 @@ Output Formatting characters: Multiple statements can be provided as additional arguments before the space separators to the next command: ``` -w !,"foo bar"," ","baz" +w !,"foo bar"," ","baz" ``` #### Read (abbreviated as R) @@ -124,7 +124,7 @@ w !,centi,!,micro Remove a variable from memory or remove a database entry from disk. A database node (global variable) is killed depending on the variable name being prefixed by the caret character (^). -If it is not, then the local variable is removed from memory. +If it is not, then the local variable is removed from memory. If KILLed, automatic garbage collection occurs. ``` @@ -134,9 +134,9 @@ k micro ### Globals and Arrays -In addition to local variables, M has persistent, shared variables that are the built-in database of M. They are stored to disk and called _globals_. Global names must start with a __caret__ (__^__). +In addition to local variables, M has persistent, shared variables that are the built-in database of M. They are stored to disk and called _globals_. Global names must start with a __caret__ (__^__). -Any variable (local or global) can be an array with the assignment of a _subscript_. Arrays are sparse and do not have a predefined size. Only if data is stored will a value use memory. Arrays should be visualized like trees, where subscripts are branches and assigned values are leaves. Not all nodes in an array need to have a value. +Any variable (local or global) can be an array with the assignment of a _subscript_. Arrays are sparse and do not have a predefined size. Only if data is stored will a value use memory. Arrays should be visualized like trees, where subscripts are branches and assigned values are leaves. Not all nodes in an array need to have a value. ``` s ^cars=20 @@ -144,7 +144,7 @@ s ^cars("Tesla",1,"Name")="Model 3" s ^cars("Tesla",2,"Name")="Model X" s ^cars("Tesla",2,"Doors")=5 -w !,^cars +w !,^cars ; 20 w !,^cars("Tesla") ; null value - there's no value assigned to this node but it has children @@ -164,23 +164,23 @@ s ^TEMPS("11/12","1700",43)="" ### Operators -```jinja +``` ; Assignment: = ; Unary: + Convert a string value into a numeric value. ; Arthmetic: ; + addition -­; - subtraction +; - subtraction ; * multiplication ; / floating-point division ; \ integer division ; # modulo ; ** exponentiation -; Logical: +; Logical: ; & and ; ! or ; ' not ; Comparison: -; = equal +; = equal ; '= not equal ; > greater than ; < less than @@ -188,7 +188,7 @@ s ^TEMPS("11/12","1700",43)="" ; '< not less / greater than or equal to ; String operators: ; _ concatenate -; [ contains ­ a contains b +; [ contains ­ a contains b ; ]] sorts after ­ a comes after b ; '[ does not contain ; ']] does not sort after @@ -204,7 +204,7 @@ To change this order, just use parentheses to group expressions to be evaluated w 5+3*20 ;160 ;You probably wanted 65 -write 5+(3*20) +write 5+(3*20) ``` ### Flow Control, Blocks, & Code Structure @@ -215,17 +215,17 @@ A tag can accept parameters and return a value, this is a function. A function i ``` ; Execute the 'tag' function, which has two parameters, and write the result. -w !,$$tag^routine(a,b) +w !,$$tag^routine(a,b) ``` M has an execution stack. When all levels of the stack have returned, the program ends. Levels are added to the stack with _do_ commands and removed with _quit_ commands. #### Do (abbreviated as D) -With an argument: execute a block of code & add a level to the stack. +With an argument: execute a block of code & add a level to the stack. ``` -d ^routine ;run a routine from the beginning. +d ^routine ;run a routine from the beginning. ; ;routines are identified by a caret. d tag ;run a tag in the current routine d tag^routine ;run a tag in different routine @@ -235,11 +235,11 @@ Argumentless do: used to create blocks of code. The block is indented with a per ``` set a=1 -if a=1 do +if a=1 do . write !,a . read b . if b > 10 d -. . w !, b +. . w !, b w "hello" ``` @@ -258,7 +258,7 @@ Putting all this together, we can create a full example of an M routine: ; RECTANGLE - a routine to deal with rectangle math q ; quit if a specific tag is not called -main +main n length,width ; New length and width so any previous value doesn't persist w !,"Welcome to RECTANGLE. Enter the dimensions of your rectangle." r !,"Length? ",length,!,"Width? ",width @@ -267,7 +267,7 @@ main w !,"Perimeter: ",per quit -area(length,width) ; This is a tag that accepts parameters. +area(length,width) ; This is a tag that accepts parameters. ; It's not a function since it quits with no value. w !, "Area: ",length*width q ; Quit: return to the previous level of the stack. @@ -287,11 +287,11 @@ F(or) loops can follow a few different patterns: ;f var=start:increment:stop f i=0:5:25 w i," " -;0 5 10 15 20 25 +;0 5 10 15 20 25 ; Infinite loop with counter ; The counter will keep incrementing forever. Use a conditional with Quit to get out of the loop. -;f var=start:increment +;f var=start:increment f j=1:1 w j," " i j>1E3 q ; Print 1-1000 separated by a space @@ -299,7 +299,7 @@ f j=1:1 w j," " i j>1E3 q ;Argumentless for - infinite loop. Use a conditional with Quit. ; Also read as "forever" - f or for followed by two spaces. s var="" -f s var=var_"%" w !,var i var="%%%%%%%%%%" q +f s var=var_"%" w !,var i var="%%%%%%%%%%" q ; % ; %% ; %%% @@ -371,7 +371,7 @@ f s date=$ORDER(^TEMPS(date)) q:date="" d . f s time=$O(^TEMPS(date,time)) q:time="" d . . w !,"Time: ",time -; Build an index that sorts first by temperature - +; Build an index that sorts first by temperature - ; what dates and times had a given temperature? n date,time,temp f s date=$ORDER(^TEMPS(date)) q:date="" d @@ -387,20 +387,21 @@ f s date=$ORDER(^TEMPS(date)) q:date="" d ## Further Reading -There's lots more to learn about M. A great short tutorial comes from the University of Northern Iowa and Professor Kevin O'Kane's [Introduction to the MUMPS Language][1] presentation. More about M using VistA is at +There's lots more to learn about M. A great short tutorial comes from the University of Northern Iowa and Professor Kevin O'Kane's [Introduction to the MUMPS Language][1] presentation. More about M using VistA is at Intersystems has some products which are a super-set of the M programming language. + * [Iris Description Page][5] * [Cache Description Page][6] -To install an M interpreter / database on your computer, try a [YottaDB Docker image][2]. +To install an M interpreter / database on your computer, try a [YottaDB Docker image][2]. YottaDB and its precursor, GT.M, have thorough documentation on all the language features including database transactions, locking, and replication: * [YottaDB Programmer's Guide][3] * [GT.M Programmer's Guide][4] -[1]: https://www.cs.uni.edu/~okane/source/MUMPS-MDH/MumpsTutorial.pdf +[1]: https://www.cs.uni.edu/~okane/source/MUMPS-MDH/MumpsTutorial.pdf [2]: https://yottadb.com/product/get-started/ [3]: https://docs.yottadb.com/ProgrammersGuide/langfeat.html [4]: http://tinco.pair.com/bhaskar/gtm/doc/books/pg/UNIX_manual/index.html diff --git a/ms-my/json-my.html.markdown b/ms-my/json-my.html.markdown index 2d2da519..41c12b03 100644 --- a/ms-my/json-my.html.markdown +++ b/ms-my/json-my.html.markdown @@ -36,9 +36,10 @@ Banyak bahasa aturcara mempunyai fungsi untuk menyirikan (mengekod) dan menyah-sirikan (men-dekod) data JSON kepada struktur data asal. Javascript mempunyai sokongon tersirat untuk memanipulasi teks JSON sebagai data. -Maklumat lebih lanjut boleh dijumpai di http://www.json.org/ +Maklumat lebih lanjut boleh dijumpai di [json.org](http://www.json.org/) JSON dibina pada dua struktur: + * Sebuah koleksi pasangan nama/nilai. Di dalam pelbagai bahasa aturcara, ini direalisasikan sebagai objek, rekod, "struct", "dictionary", "hash table", senarai berkunci, atau "associative array". diff --git a/no-nb/json-no.html.markdown b/no-nb/json-no.html.markdown index 6c8c3c79..82e1f994 100644 --- a/no-nb/json-no.html.markdown +++ b/no-nb/json-no.html.markdown @@ -1,4 +1,4 @@ ---- +--- language: json filename: learnjson-no.json lang: no-nb @@ -18,7 +18,7 @@ C-stil (`//`, `/* */`) kommentarer. ```json { "nøkkel": "verdi", - + "nøkler": "må alltid være i doble anførselstegn", "tall": 0, "strings": "Hellø, wørld. Alt unicode er godkjent, også \"escaping\".", @@ -48,7 +48,7 @@ C-stil (`//`, `/* */`) kommentarer. [0, 0, 0, 1] ] ], - + "Alternativ": { "Kommentar": "Sjekk ut ditta!" , "plassering av komma": "Sålenge den er før verdien er det gyldig" diff --git a/openscad.html.markdown b/openscad.html.markdown index 63570cbe..2cd44bc5 100644 --- a/openscad.html.markdown +++ b/openscad.html.markdown @@ -112,6 +112,7 @@ use // Import modules and functions, but do not execute any comma ``` ## Further Reading -* Official docs https://openscad.org/documentation.html -* Cheat sheet https://openscad.org/cheatsheet/index.html -* Vim bindings https://github.com/sirtaj/vim-openscad + +* Official docs [openscad.org/documentation.html](https://openscad.org/documentation.html) +* Cheat sheet [openscad.org/cheatsheet/index.html](https://openscad.org/cheatsheet/index.html) +* Vim bindings [github.com/sirtaj/vim-openscad](https://github.com/sirtaj/vim-openscad) diff --git a/pl-pl/java-pl.html.markdown b/pl-pl/java-pl.html.markdown index 3f11fede..3aadd3b4 100644 --- a/pl-pl/java-pl.html.markdown +++ b/pl-pl/java-pl.html.markdown @@ -21,8 +21,7 @@ lang: pl-pl Java jest współbieżnym, opartym na klasach, obiektowym językiem programowania ogólnego zastosowania. -[Tu znajdziesz więcej informacji po angielsku.] -(https://docs.oracle.com/javase/tutorial/java/) +[Tu znajdziesz więcej informacji po angielsku](https://docs.oracle.com/javase/tutorial/java/). ```java // Pojedyncze komentarze oznaczamy // @@ -893,7 +892,7 @@ import java.security.SecureRandom; public class Lambdas { public static void main(String[] args) { // Składnia deklaracji lambdy: - // -> + // -> // Poniżej w przykładzie użyjemy tablicy z hashowaniem. Map planety = new HashMap<>(); @@ -978,49 +977,36 @@ public class Lambdas { Linki zamieszczone poniżej służą pomocą w zrozumieniu wybranego tematu, w razie braku rozwiązania wyszukanie w Google zwykle służy pomocą -**Oficjalne poradniki Oracle po angielsku**: +### Oficjalne poradniki Oracle po angielsku * [Tutorial w Javie od Sun / Oracle](https://docs.oracle.com/javase/tutorial/index.html) - * [Modyfikacje poziomu dostępu w Java](https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - * [Koncepty programowania obiektowego](https://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Dziedziczenie](https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polimorfizm](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstrakcja](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - * [Wyjątki](https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - * [Interfejsy](https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - * [Uogólnianie](https://docs.oracle.com/javase/tutorial/java/generics/index.html) - * [Konwencja kodu Java](https://www.oracle.com/technetwork/java/codeconvtoc-136057.html) - * Nowości z Java 8: * [Funkcje Lambda (programowanie funkcyjne)](https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html) * [Data y czas API (java.time package)](http://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html) -**Kursy po polsku** +### Kursy po polsku * [PJWSTK - Podstawy programowania w języku Java](http://edu.pjwstk.edu.pl/wyklady/ppj/scb/) - * [PJWSTK - Programowanie obiektowe w języku Java](http://edu.pjwstk.edu.pl/wyklady/poj/scb/) -**Tutoriale i ćwiczenia online po angielsku** +### Tutoriale i ćwiczenia online po angielsku * [Learneroo.com - Learn Java](http://www.learneroo.com) - * [Codingbat.com](http://codingbat.com/java) - * [Codewars - Java Katas](https://www.codewars.com/?language=java) -**Książki po angielsku**: +### Książki po angielsku * [Head First Java](http://www.headfirstlabs.com/books/hfjava/) - * [Thinking in Java](https://www.amazon.com/Thinking-Java-4th-Bruce-Eckel/dp/0131872486/) - * [Objects First with Java](https://www.amazon.com/Objects-First-Java-Practical-Introduction/dp/0132492660) - * [Java The Complete Reference](https://www.amazon.com/gp/product/0071606300) diff --git a/pt-br/c-pt.html.markdown b/pt-br/c-pt.html.markdown index 1daee632..9575007a 100644 --- a/pt-br/c-pt.html.markdown +++ b/pt-br/c-pt.html.markdown @@ -639,12 +639,10 @@ typedef void (*minha_função_type)(char *); Este é *o* livro sobre C, escrito pelos criadores da linguagem. Mas cuidado - ele é antigo e contém alguns erros (bem, ideias que não são mais consideradas boas) ou práticas ultrapassadas. -Outra boa referência é [Learn C the hard way](http://learncodethehardway.org/c/). - Se você tem uma pergunta, leia [compl.lang.c Frequently Asked Questions](http://c-faq.com). É importante usar espaços e indentação adequadamente e ser consistente com seu estilo de código em geral. Código legível é melhor que código 'esperto' e rápido. Para adotar um estilo de código bom e sensato, veja [Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle). -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +[1] [stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) diff --git a/pt-br/clojure-pt.html.markdown b/pt-br/clojure-pt.html.markdown index 15ad930a..2228584c 100644 --- a/pt-br/clojure-pt.html.markdown +++ b/pt-br/clojure-pt.html.markdown @@ -9,13 +9,12 @@ translators: lang: pt-br --- -Clojure é uma linguagem da família do Lisp desenvolvida para a JVM (máquina virtual Java). Possui uma ênfase muito mais forte em [programação funcional] (https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional) pura do que Common Lisp, mas inclui diversos recursos [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) para lidar com estado e mutabilidade, caso isso seja necessário. +Clojure é uma linguagem da família do Lisp desenvolvida para a JVM (máquina virtual Java). Possui uma ênfase muito mais forte em [programação funcional](https://pt.wikipedia.org/wiki/Programa%C3%A7%C3%A3o_funcional) pura do que Common Lisp, mas inclui diversos recursos [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) para lidar com estado e mutabilidade, caso isso seja necessário. Essa combinação permite gerenciar processamento concorrente de maneira muito simples - frequentemente, de modo automático. (Sua versão de clojure precisa ser pelo menos 1.2) - ```clojure ; Comentários começam por ponto e vírgula @@ -239,7 +238,7 @@ xis ; => :x ; É possível, inclusive, criar apelidos a nomes que já existem: (def somar! soma) -(somar! 41 1) ; => 42 +(somar! 41 1) ; => 42 ; Uma forma rápida de criar funções é por meio de funções anônimas. Elas são ótimas ; para manipulação de coleções e seqs, já que podem ser passadas para map, filter @@ -280,7 +279,7 @@ mapa-keywords ; => {:a 1, :c 3, :b 2} (mapa-strings "a") ; => 1 (mapa-keywords :a) ; => 1 -; Se a chave buscada for uma keyword, ela também pode ser usada como função para recuperar +; Se a chave buscada for uma keyword, ela também pode ser usada como função para recuperar ; valores. Note que isso não funciona com strings. (:b mapa-keywords) ; => 2 ("b" mapa-strings) ; => java.lang.String cannot be cast to clojure.lang.IFn @@ -357,7 +356,7 @@ meu-conjunto ; => #{1 3 2} (if false "a" "b") ; => "b" ; Opcionalmente você pode não passar o último argumento, mas se a condição for falsa -; o if vai retornar nil. +; o if vai retornar nil. (if false "a") ; => nil ; A forma if somente aceita um comando para ser executado em cada caso. Se você @@ -506,13 +505,13 @@ meu-conjunto ; => #{1 3 2} ; e ele criará um objeto que é seguro de atualizar: (def atom-mapa (atom {})) -; Para acessar o valor de um atom, você pode usar a função deref ou o operador @: +; Para acessar o valor de um atom, você pode usar a função deref ou o operador @: @atom-mapa ; => {} (deref atom-mapa) ; => {} ; Para mudar o valor de um atom, você deve usar a função swap! ; O que ela faz é chamar a função passada usando o atom como seu primeiro argumento. Com -; isso, ela altera o valor do atom de maneira segura. +; isso, ela altera o valor do atom de maneira segura. (swap! atom-mapa assoc :a 1) ; Atribui a atom-mapa o resultado de (assoc {} :a 1) (swap! atom-mapa assoc :b 2) ; Atribui a atom-mapa o resultado de (assoc {:a 1} :b 2) @@ -553,16 +552,12 @@ Caso queira aprender mais: * clojure.org tem vários artigos: [http://clojure.org/](http://clojure.org/) - * Brave Clojure possui um e-book que explora em profundidade diversos recursos de clojure, incluindo ótimos exemplos: [https://www.braveclojure.com/](https://www.braveclojure.com/) - * clojuredocs.org tem documentação com exemplos para quase todas as funções principais (pertecentes ao core): [http://clojuredocs.org/quickref/Clojure%20Core](http://clojuredocs.org/quickref/Clojure%20Core) - * 4clojure possui alguns problemas e desafios interessantes para quem quiser treinar clojure ou programação funcional: [https://4clojure.oxal.org/](https://4clojure.oxal.org/) - * clojure-doc.org tem um bom número de artigos para iniciantes: [http://clojure-doc.org/](http://clojure-doc.org/) diff --git a/pt-br/emacs-pt.html.markdown b/pt-br/emacs-pt.html.markdown index 7a86a119..baa7d769 100644 --- a/pt-br/emacs-pt.html.markdown +++ b/pt-br/emacs-pt.html.markdown @@ -9,7 +9,7 @@ translators: lang: pt-br --- -O Emacs começou sua vida como (https://www.gnu.org/software/emacs/emacs-paper.html) e cresceu +O Emacs começou sua vida como [gnu.org/software/emacs/emacs-paper.html](https://www.gnu.org/software/emacs/emacs-paper.html) e cresceu ao longo dos anos em um ecossistema completo. Muitas tarefas, geralmente relegado a um conjunto diversificado de ferramentas pode ser realizado de dentro Emacs em uma interface consistente e familiar. Exemplos incluem @@ -32,25 +32,15 @@ Aqui, discuto alguns conceitos e terminologia básicos do Emacs que podem ser confusos para os recém-chegados (especialmente para as pessoas acostumadas à terminologia do Vim): - O texto que o Emacs está editando é conhecido como **buffer** - - Um buffer não corresponde necessariamente a um arquivo real no disco. Pode ser apenas texto na memória. - - Quando um buffer corresponde a um arquivo no disco, dizemos que o buffer está **visitando** esse arquivo. - - O Emacs normalmente possui muitos buffers abertos ao mesmo tempo. - - A exibição do Emacs pode ser dividida em diferentes **windows**. - - Uma janela do sistema operacional para o Emacs é chamada de **frame**. Assim, quando o manual do Emacs fala sobre a abertura de um novo frame, esse essencialmente significa abrir uma nova janela do SO contendo uma (outra) instância do Emacs. -   - Os conceitos convencionalmente conhecidos como recortar e colar são referido como **killing** e **yanking**, respectivamente no Emacs. -   - A posição atual do cursor é chamada de **point** no Emacs. Tecnicamente, **point** é definido como a posição imediatamente antes do caractere onde o cursor está atualmente. -   - Finalmente, cada buffer pode ter vários **modes** associados: o **major mode** e possivelmente vários **minor modes**. -   - O **major mode** define o principal comportamento do Emacs no buffer atualmente selecionado. Isso pode ser pensado como o tipo de arquivo. Por exemplo, se você estiver editando um arquivo Python, os principais modes é (por padrão) `python-mode`, que faz com que o Emacs destaque a sintaxe Python e idente automaticamente seus blocos de código conforme exigido sintaticamente pelo seu código Python. -   - **Minor modes** definem mudanças sutis no comportamento e várias alterações menores Os modos podem estar ativos ao mesmo tempo no mesmo buffer. Um exemplo menor modo é o modo flyspell, que destaca automaticamente os erros de ortografia no seu buffer. # Recursos adicionais diff --git a/pt-br/go-pt.html.markdown b/pt-br/go-pt.html.markdown index ce10e079..159167bd 100644 --- a/pt-br/go-pt.html.markdown +++ b/pt-br/go-pt.html.markdown @@ -11,11 +11,11 @@ translators: - ["Nuno Antunes", "https://github.com/ntns"] --- -A linguagem Go foi criada a partir da necessidade de ver trabalho feito. Não +A linguagem Go foi criada a partir da necessidade de ver trabalho feito. Não é a última moda em ciências da computação, mas é a mais recente e mais rápida forma de resolver os problemas do mundo real. -Tem conceitos familiares de linguagens imperativas com tipagem estática. É +Tem conceitos familiares de linguagens imperativas com tipagem estática. É rápida para compilar e rápida para executar, acrescentando mecanismos de concorrência fáceis de entender para tirar partido dos CPUs multi-core de hoje em dia, e tem recursos para ajudar com a programação em larga escala. @@ -57,7 +57,7 @@ func beyondHello() { // Declarações "curtas" usam := para inferir o tipo, declarar e atribuir. y := 4 sum, prod := learnMultiple(x, y) // a função retorna dois valores - fmt.Println("soma:", sum, "produto:", prod) + fmt.Println("soma:", sum, "produto:", prod) learnTypes() // continuar a aprender! } @@ -69,9 +69,9 @@ func learnMultiple(x, y int) (sum, prod int) { // Alguns tipos e literais básicos. func learnTypes() { // Declarações "curtas" geralmente servem para o que pretendemos. - s := "Aprender Go!" // tipo string + s := "Aprender Go!" // tipo string - s2 := `Uma string em "bruto" + s2 := `Uma string em "bruto" pode incluir quebras de linha.` // mesmo tipo string // literal não-ASCII. A linguagem Go utiliza de raiz a codificação UTF-8. @@ -87,7 +87,7 @@ pode incluir quebras de linha.` // mesmo tipo string // Sintaxe de conversão de tipo, com declaração "curta". n := byte('\n') // byte é um alias para uint8 - // Os arrays têm tamanho fixo e definido antes da compilação. + // Os arrays têm tamanho fixo e definido antes da compilação. var a4 [4]int // um array de 4 ints, inicializado com ZEROS a3 := [...]int{3, 1, 5} // um array de 3 ints, inicializado como mostrado @@ -112,10 +112,10 @@ pode incluir quebras de linha.` // mesmo tipo string // Enviar para o stdout conta como utilização de uma variável. fmt.Println(s, c, a4, s3, d2, m) - learnFlowControl() + learnFlowControl() } -// A linguagem Go é totalmente garbage collected. Tem apontadores mas não +// A linguagem Go é totalmente garbage collected. Tem apontadores mas não // permite que os apontadores sejam manipulados com aritmética. Pode-se cometer // um erro com um apontador nulo, mas não por incrementar um apontador. func learnMemory() (p, q *int) { @@ -174,7 +174,7 @@ func learnFlowControl() { return x > 100 // referencia x, declarado acima da instrução switch. } fmt.Println("xBig:", xBig()) // true (1e6 é o último valor de x) - x /= 1e5 // agora temos x == 10 + x /= 1e5 // agora temos x == 10 fmt.Println("xBig:", xBig()) // false // Quando for mesmo necessário, pode usar o velho goto. @@ -194,7 +194,7 @@ type pair struct { x, y int } -// Define um método para o tipo pair. O tipo pair implementa agora a +// Define um método para o tipo pair. O tipo pair implementa agora a // interface Stringer. func (p pair) String() string { // p é chamado de "receptor" // Sprintf é outra função pública no pacote fmt. @@ -262,7 +262,7 @@ func learnConcurrency() { go func() { c <- 84 }() // inicia uma goroutine para enviar um valor go func() { cs <- "palavroso" }() // outra vez, para o channel cs desta vez // A instrução select tem uma sintaxe semelhante à instrução switch mas - // cada caso envolve uma operação com channels. Esta instrução seleciona, + // cada caso envolve uma operação com channels. Esta instrução seleciona, // de forma aleatória, um caso que esteja pronto para comunicar. select { case i := <-c: // o valor recebido pode ser atribuído a uma variável @@ -301,11 +301,11 @@ Lá é possível seguir o tutorial, experimentar de forma iterativa, e ler muito A própria especificação da linguagem é altamente recomendada. É fácil de ler e incrivelmente curta (em relação ao que é habitual hoje em dia). -Na lista de leitura para os aprendizes de Go deve constar o [código fonte da +Na lista de leitura para os aprendizes de Go deve constar o [código fonte da biblioteca padrão](https://go.dev/src/). Exaustivamente documentado, é a melhor demonstração de código fácil de ler e de perceber, do estilo Go, e da -sua escrita idiomática. Ou então clique no nome de uma função na [documentação] -(https://go.dev/pkg/) e veja o código fonte aparecer! +sua escrita idiomática. Ou então clique no nome de uma função na +[documentação](https://go.dev/pkg/) e veja o código fonte aparecer! Outra ótima fonte para aprender Go é o [Go by example](https://gobyexample.com/). Apesar de ser em inglês, é possível recodificar os exemplos para aprender sobre diff --git a/pt-br/groovy-pt.html.markdown b/pt-br/groovy-pt.html.markdown index ebde76d8..cb096a71 100644 --- a/pt-br/groovy-pt.html.markdown +++ b/pt-br/groovy-pt.html.markdown @@ -10,7 +10,7 @@ translators: lang: pt-br --- -Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui.](http://www.groovy-lang.org/) +Groovy - Uma linguagem dinâmica para a plataforma Java. [Leia mais aqui](http://www.groovy-lang.org/). ```groovy /* @@ -289,7 +289,7 @@ def clos = { print it } clos( "oi" ) /* - Groovy pode memorizar resultados de closures [1][2][3] + Groovy pode memorizar resultados de closures */ def cl = {a, b -> sleep(3000) // simula processamento @@ -317,7 +317,7 @@ chamaClosure(3, 4) /* Expando - A classe Expando é um bean dinâmico que permite adicionar propriedades e + A classe Expando é um bean dinâmico que permite adicionar propriedades e closures como métodos a uma instância desta classe http://mrhaki.blogspot.mx/2009/10/groovy-goodness-expando-as-dynamic-bean.html @@ -429,15 +429,6 @@ Junte-se a um [grupo de usuários Groovy](http://www.groovy-lang.org/usergroups. ## Livro -* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) - -* [Groovy in Action] (http://manning.com/koenig2/) - -* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) - -[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ -[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize -[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html - - - +* [Groovy Goodness](https://leanpub.com/groovy-goodness-notebook) +* [Groovy in Action](http://manning.com/koenig2/) +* [Programming Groovy 2: Dynamic Productivity for the Java Developer](http://shop.oreilly.com/product/9781937785307.do) diff --git a/pt-br/httpie-pt.html.markdown b/pt-br/httpie-pt.html.markdown index f81919fe..df15aa7d 100644 --- a/pt-br/httpie-pt.html.markdown +++ b/pt-br/httpie-pt.html.markdown @@ -29,8 +29,8 @@ http --offline https://api.example.com/posts ### Encurtando URLs `localhost` -HTTPie fornece suporte a atalhos para o localhost, similares aos do `curl`. Por exemplo, ":3000" -expande para "http://localhost:3000". Se a porta for omitida, o padrão será a porta 80. +HTTPie fornece suporte a atalhos para o localhost, similares aos do `curl`. Por exemplo, `:3000` +expande para `http://localhost:3000`. Se a porta for omitida, o padrão será a porta 80. ```bash http :/users # http://localhost/users @@ -118,5 +118,5 @@ http --follow GET https://example.com # Segue redirecionamentos ## Leitura Adicional -- [Documentação Oficial](https://httpie.io/docs/cli). -- [GitHub](https://github.com/httpie). +- [Documentação Oficial](https://httpie.io/docs/cli) +- [GitHub](https://github.com/httpie) diff --git a/pt-br/java-pt.html.markdown b/pt-br/java-pt.html.markdown index 6069974b..48a54917 100644 --- a/pt-br/java-pt.html.markdown +++ b/pt-br/java-pt.html.markdown @@ -630,28 +630,21 @@ Os links fornecidos aqui abaixo são apenas para ter uma compreensão do tema, u Outros tópicos para pesquisar: * [Tutorial Java para Sun Trail / Oracle](http://docs.oracle.com/javase/tutorial/index.html) - * [Modificadores de acesso do Java](http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html) - * [Coceitos de Programação Orientada à Objetos](http://docs.oracle.com/javase/tutorial/java/concepts/index.html): * [Herança](http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html) * [Polimorfismo](http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) * [Abstração](http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) - * [Exceções](http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html) - * [Interfaces](http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html) - * [Tipos Genéricos](http://docs.oracle.com/javase/tutorial/java/generics/index.html) - * [Conversões de código Java](http://www.oracle.com/technetwork/java/codeconv-138413.html) Livros: -* [Use a cabeça, Java] (http://www.headfirstlabs.com/books/hfjava/) +* [Use a cabeça, Java](http://www.headfirstlabs.com/books/hfjava/) Apostila: -* [Java e Orientação a Objetos] (http://www.caelum.com.br/apostila-java-orientacao-objetos/) - -* [Java para Desenvolvimento Web] (https://www.caelum.com.br/apostila-java-web/) +* [Java e Orientação a Objetos](http://www.caelum.com.br/apostila-java-orientacao-objetos/) +* [Java para Desenvolvimento Web](https://www.caelum.com.br/apostila-java-web/) diff --git a/pt-br/json-pt.html.markdown b/pt-br/json-pt.html.markdown index 62d9ccad..922a9b13 100644 --- a/pt-br/json-pt.html.markdown +++ b/pt-br/json-pt.html.markdown @@ -13,7 +13,7 @@ filename: learnjson-pt.json Como JSON é um formato de intercâmbio de dados, este será, muito provavelmente, o "Learn X in Y minutes" mais simples existente. -JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores +JSON na sua forma mais pura não tem comentários, mas a maioria dos analisadores aceitarão comentários no estilo C (//, /\* \*/). No entanto estes devem ser evitados para otimizar a compatibilidade. Um valor JSON pode ser um número, uma string, um array, um objeto, um booleano (true, false) ou null. @@ -22,12 +22,12 @@ Os browsers suportados são: Firefox 3.5+, Internet Explorer 8.0+, Chrome 1.0+, A extensão dos ficheiros JSON é “.json” e o tipo de mídia de Internet (MIME) é “application/json”. -Mais informação em: http://www.json.org/ +Mais informação em: [json.org](http://www.json.org/) ```json { "chave": "valor", - + "chaves": "deve ser sempre entre aspas (junto ou separado)", "números": 0, "strings": "Olá, mundo. Todo o padrão UNICODE é permitido, junto com \"escapando\".", diff --git a/pt-br/perl-pt.html.markdown b/pt-br/perl-pt.html.markdown index 55a10626..5430e89f 100644 --- a/pt-br/perl-pt.html.markdown +++ b/pt-br/perl-pt.html.markdown @@ -153,7 +153,7 @@ logger("Nós temos uma subrotina de log!"); #### Usando módulos Perl Módulos Perl provê uma lista de recursos para lhe ajudar a evitar redesenhar -a roda, e tudo isso pode ser baixado do CPAN (http://www.cpan.org/). Um número +a roda, e tudo isso pode ser baixado do [CPAN](http://www.cpan.org/). Um número de módulos populares podem ser incluídos com a própria distribuição do Perl. perlfaq contém questões e respostas relacionadas a muitas tarefas comuns, e frequentemente provê sugestões para um bom números de módulos CPAN. diff --git a/pt-br/php-composer-pt.html.markdown b/pt-br/php-composer-pt.html.markdown index 0ae83cf9..87cffe5c 100644 --- a/pt-br/php-composer-pt.html.markdown +++ b/pt-br/php-composer-pt.html.markdown @@ -24,8 +24,7 @@ php composer.phar about curl -sS https://getcomposer.org/installer | php -- --install-dir=~/bin --filename=composer ``` -Usuários Windows devem seguir as Instruções de instalação para Windows: -https://getcomposer.org/doc/00-intro.md#installation-windows (EN) +Usuários Windows devem seguir as [Instruções de instalação para Windows](https://getcomposer.org/doc/00-intro.md#installation-windows) (EN) ## Confirmando a instalação diff --git a/pt-br/pythonstatcomp-pt.html.markdown b/pt-br/pythonstatcomp-pt.html.markdown index 7b1a3bf4..08c73da3 100644 --- a/pt-br/pythonstatcomp-pt.html.markdown +++ b/pt-br/pythonstatcomp-pt.html.markdown @@ -16,10 +16,10 @@ Stata, SAS, SPSS ou MATLAB. ```python # 0. Preparando-se ==== -""" Para começar, instale o seguinte : jupyther, numpy, scipy, pandas, +""" Para começar, instale o seguinte : jupyther, numpy, scipy, pandas, matplotlib, seaborn, requests. Certifique-se de executar este tutorial utilizando o Jupyther notebook para - que você utilize os gráficos embarcados e ter uma fácil consulta à + que você utilize os gráficos embarcados e ter uma fácil consulta à documentação. O comando para abrir é simplesmente '`jupyter notebook`, quando abrir então clique em 'New -> Python'. @@ -29,7 +29,7 @@ Stata, SAS, SPSS ou MATLAB. """ A única razão das pessoas optarem por Python no lugar de R é que pretendem interagir com o ambiente web, copiando páginas diretamente ou solicitando - dados utilizando uma API. Você pode fazer estas coisas em R, mas no + dados utilizando uma API. Você pode fazer estas coisas em R, mas no contexto de um projeto já usando Python, há uma vantagem em se ater uma linguágem única. """ @@ -75,7 +75,7 @@ pets # 1 vesuvius 6 23 fish # 2 rex 5 34 dog -""" Usuários R: observe que o Python, como a maioria das linguagens de programação +""" Usuários R: observe que o Python, como a maioria das linguagens de programação influenciada pelo C, a indexação começa de 0. Em R, começa a indexar em 1 devido à influência do Fortran. """ @@ -99,7 +99,7 @@ pets.age[0:2] sum(pets.age) * 2 # 28 max(pets.weight) - min(pets.weight) # 20 -""" Se você está fazendo alguma álgebra linear séria e processamento de +""" Se você está fazendo alguma álgebra linear séria e processamento de números você pode desejar apenas arrays, não DataFrames. DataFrames são ideais para combinar colunas de diferentes tipos de dados. """ @@ -238,8 +238,9 @@ sns.lmplot("BirthY", "EstAge", data=hre) Se você quiser saber mais, obtenha o Python para análise de dados de Wes McKinney. É um excelente recurso e usei-o como referência ao escrever este tutorial. -Você também pode encontrar muitos tutoriais interativos de IPython sobre assuntos específicos de seus interesses, como Cam Davidson-Pilon's Programação Probabilística e Métodos Bayesianos para Hackers. +Você também pode encontrar muitos tutoriais interativos de IPython sobre assuntos específicos de seus interesses, como Cam Davidson-Pilon's [Programação Probabilística e Métodos Bayesianos para Hackers](http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). Mais alguns módulos para pesquisar: - - análise de texto e processamento de linguagem natural: nltk, http://www.nltk.org - - análise de rede social: igraph, http://igraph.org/python/ + + - análise de texto e processamento de linguagem natural: [nltk](http://www.nltk.org) + - análise de rede social: [igraph](http://igraph.org/python/) diff --git a/pt-br/rust-pt.html.markdown b/pt-br/rust-pt.html.markdown index 1dff7748..246450e9 100644 --- a/pt-br/rust-pt.html.markdown +++ b/pt-br/rust-pt.html.markdown @@ -12,7 +12,7 @@ combina controle de baixo nível sobre o desempenho com facilidades de alto nível e garantias de segurança. Ele atinge esse objetivo sem necessitar de um coletor de lixo ou um processo -*runtime*, permitindo que se use bibliotecas Rust em substituição a bibliotecas +*runtime*, permitindo que se use bibliotecas Rust em substituição a bibliotecas em C. A primeira versão de Rust, 0.1, apareceu em janeiro de 2012, e por três anos o @@ -65,10 +65,10 @@ fn main() { let f: f64 = 1.3f64; // Inferência de tipos - // Em geral, o compilador Rust consegue inferir qual o tipo de uma + // Em geral, o compilador Rust consegue inferir qual o tipo de uma // variável, então você não tem que escrever uma anotação explícita de tipo. - // Ao longo desse tutorial, os tipos serão explicitamente anotados em - // muitos lugares, mas apenas com propósito demonstrativo. A inferência de + // Ao longo desse tutorial, os tipos serão explicitamente anotados em + // muitos lugares, mas apenas com propósito demonstrativo. A inferência de // tipos pode gerenciar isso na maioria das vezes. let implicit_x = 1; let implicit_f = 1.3; @@ -94,7 +94,7 @@ fn main() { // Uma String slice - uma visão imutável em outra string. // Basicamente, isso é um par imutável de ponteiros para uma string - ele - // não contém o conteúdo de uma strinf, apenas um ponteiro para o começo e + // não contém o conteúdo de uma strinf, apenas um ponteiro para o começo e // um ponteiro para o fim da área de memória para a string, estaticamente // alocada ou contida em outro objeto (nesse caso, `s`) let s_slice: &str = &s; @@ -279,7 +279,7 @@ fn main() { // automaticamente desalocado com segurança. let mut mine: Box = Box::new(3); *mine = 5; // dereference - // Aqui, `now_its_mine` possui o controle exclusivo de `mine`. Em outras + // Aqui, `now_its_mine` possui o controle exclusivo de `mine`. Em outras // palavras, `mine` tem o controle transferido. let mut now_its_mine = mine; *now_its_mine += 2; @@ -317,15 +317,15 @@ fn main() { ## Outras leituras -Existe muita coisa sobre Rust - isto aqui é apenas o básico para que você possa -entender as coisas mais importantes. Para aprender mais sobre Rust, leia [The -Rust Programming Language](http://doc.rust-lang.org/book/index.html) e +Existe muita coisa sobre Rust - isto aqui é apenas o básico para que você possa +entender as coisas mais importantes. Para aprender mais sobre Rust, leia [The +Rust Programming Language](http://doc.rust-lang.org/book/index.html) e acompanhe [/r/rust](http://reddit.com/r/rust). A galera no canal #rust do irc.mozilla.org também estão sempre dispostos a ajudar os novatos. Você pode brincar com outras característica de Rust com um compilador online -no portal oficial do projeto [Rust Playground](https://play.rust-lang.org), or ler +no portal oficial do projeto [Rust Playground](https://play.rust-lang.org), or ler mais na página oficial [Rust website](http://rust-lang.org). -No Brasil acompanhe os encontros do [Meetup Rust São Paulo] -(http://www.meetup.com/pt-BR/Rust-Sao-Paulo-Meetup/). +No Brasil acompanhe os encontros do +[Meetup Rust São Paulo](http://www.meetup.com/pt-BR/Rust-Sao-Paulo-Meetup/). diff --git a/pt-br/solidity-pt.html.markdown b/pt-br/solidity-pt.html.markdown index 4d30d62a..76c27bb6 100644 --- a/pt-br/solidity-pt.html.markdown +++ b/pt-br/solidity-pt.html.markdown @@ -9,8 +9,8 @@ translators: lang: pt-br --- -Solidity permite você programar para a [Ethereum] -(https://www.ethereum.org/), uma máquina virtual baseada na tecnologia blockhain +Solidity permite você programar para a [Ethereum](https://www.ethereum.org/), +uma máquina virtual baseada na tecnologia blockhain para criação e execução de contratos inteligentes, sem necessidade de partes centralizadas ou de confiança. @@ -20,7 +20,6 @@ possue variáveis de estado, funções e tipos de dados comuns. Funcionalidades particulares de contratados incluem cláusuras modificadoras (guarda), notifica dores de eventos para listerners e variáveis globais customizadas. - Exemplos de contratos Ethereum incluem crowdfunding, votações e audições cegas. Erros em código Solidity causam grandes riscos e custos; portanto, você @@ -875,6 +874,7 @@ algumEnderecoDeContrato.callcode('nome_da_funcao'); ``` ## Recursos adicionais + - [Documetanção Solidity](https://solidity.readthedocs.org/en/latest/) - [Guia de Estilo do Solidity](https://ethereum.github.io/solidity//docs/style-guide/): O guia de estilo Ethereum é derivado do guia de estilo do Python [pep8](https://www.python.org/dev/peps/pep-0008/). @@ -883,32 +883,24 @@ algumEnderecoDeContrato.callcode('nome_da_funcao'); - [Estratégias de projeto modular para contratos Ethereum](https://docs.erisindustries.com/tutorials/solidity/) ## Contratos de Exemplo + - [Dapp Bin](https://github.com/ethereum/dapp-bin) - [Solidity Baby Step Contracts](https://github.com/fivedogit/solidity-baby-steps/tree/master/contracts) - [ConsenSys Contracts](https://github.com/ConsenSys/dapp-store-contracts) - [State of Dapps](http://dapps.ethercasts.com/) ## Segurança + - [Thinking About Smart Contract Security](https://blog.ethereum.org/2016/06/19/thinking-smart-contract-security/) - [Smart Contract Security](https://blog.ethereum.org/2016/06/10/smart-contract-security/) - [Hacking Distributed Blog](http://hackingdistributed.com/) -## Informação excluída intencionalmente -- Libraries - ## Estilo + - [PEP8](https://www.python.org/dev/peps/pep-0008/) é usado como guia de estilo, incluindo sua filosofia geral ## Editores + - [Vim Solidity](https://github.com/tomlion/vim-solidity) - Snippets de Editores ([Ultisnips format](https://gist.github.com/nemild/98343ce6b16b747788bc)) - -## Trabalhos Futuros -- Novas palavras-chave: protected, inheritable -- Lista de padrões de design comuns (throttling, RNG, atualização de versão) -- Padrões anti-segurança comuns - - -Sinta-se a vontade para enviar um pull request com quaisquer edições - ou email -para nemild - / at- / gmail diff --git a/pt-br/stylus-pt.html.markdown b/pt-br/stylus-pt.html.markdown index 7ea43d83..caa97cb0 100644 --- a/pt-br/stylus-pt.html.markdown +++ b/pt-br/stylus-pt.html.markdown @@ -14,7 +14,6 @@ A sintaxe do Stylus é muito flexivel podendo utilizar a sintaxe padrão do CSS Stylus não fornece novas opções de estilos, mas dá funcionalidades que permitem deixar seu CSS muito mais dinâmico. - ```sass /* Estilo de código ==============================*/ @@ -80,9 +79,9 @@ a { ==============================*/ -/* +/* É possível armazenar um valor CSS (tais como a cor) de uma variável. - Embora seja opcional, é recomendado adicionar $ antes de um nome de variável + Embora seja opcional, é recomendado adicionar $ antes de um nome de variável para que você possa distinguir uma variável de outro valor CSS. */ @@ -94,20 +93,20 @@ $body-font = 'Roboto', sans-serif Agora, se você quer mudar a cor, você só tem que fazer a mudança uma vez. */ body - background-color $primary-color - color $secondary-color - font-family $body-font + background-color $primary-color + color $secondary-color + font-family $body-font /* Quando compilar ficaria assim: */ body { - background-color: #A3A4FF; - color: #51527F; - font-family: 'Roboto', sans-serif; + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; } -/ * +/ * Este é muito mais fácil de manter do que ter de mudar a cor -cada vez que aparece em toda a sua folha de estilo. +cada vez que aparece em toda a sua folha de estilo. * / @@ -120,10 +119,10 @@ elemento, você pode querer armazenar esse código em um mixin. center() display block - margin-left auto - margin-right auto - left 0 - right 0 + margin-left auto + margin-right auto + left 0 + right 0 /* Utilizando um mixin */ body { @@ -133,12 +132,12 @@ body { /* Após compilar ficaria assim: */ div { - display: block; - margin-left: auto; - margin-right: auto; - left: 0; - right: 0; - background-color: #A3A4FF; + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; } /* Você pode usar mixins para criar uma propriedade estenográfica. */ @@ -151,7 +150,7 @@ size($width, $height) size(100px, 60px) .square - size(40px, 40px) + size(40px, 40px) /* Você pode usar um mixin como uma propriedade CSS. */ circle($ratio) @@ -223,4 +222,4 @@ for $item in (1..2) /* Repete o bloco 12 vezes */ width ($item / 12) * 100% /* Calcula a largura pelo número da coluna* ``` -Agora que você conhece um pouco sobre esse poderoso pré-processador de CSS, você está pronto para criar folhas de estilos mais dinâmicas. Para aprofundar seus conhecimentos visite a documentação oficial do stylus em http://stylus-lang.com. +Agora que você conhece um pouco sobre esse poderoso pré-processador de CSS, você está pronto para criar folhas de estilos mais dinâmicas. Para aprofundar seus conhecimentos visite a documentação oficial do stylus em [stylus-lang.com](http://stylus-lang.com). diff --git a/pt-br/swift-pt.html.markdown b/pt-br/swift-pt.html.markdown index 7f03c8a1..03aa0ab6 100644 --- a/pt-br/swift-pt.html.markdown +++ b/pt-br/swift-pt.html.markdown @@ -14,7 +14,7 @@ Swift é uma linguagem de programação para desenvolvimento de aplicações no coexistir com Objective-C e para ser mais resiliente a código com erros, Swift foi apresentada em 2014 na Apple's developer conference WWDC. Foi construída com o compilador LLVM já incluído no Xcode 6 beta. -O livro oficial [Swift Programming Language] (https://itunes.apple.com/us/book/swift-programming-language/id881256329) da +O livro oficial [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) da Apple já está disponível via IBooks (apenas em inglês). Confira também o tutorial completo de Swift da Apple [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html), também disponível apenas em inglês. diff --git a/pt-br/visualbasic-pt.html.markdown b/pt-br/visualbasic-pt.html.markdown index 29fef9c9..9b8dcf87 100644 --- a/pt-br/visualbasic-pt.html.markdown +++ b/pt-br/visualbasic-pt.html.markdown @@ -14,10 +14,10 @@ Module Module1 module Module1 Sub Main () - ' Uma visão geral de console de aplicativos do Visual Basic antes de + ' Uma visão geral de console de aplicativos do Visual Basic antes de ' mergulharmos mais profundamente na linguagem. ' Aspas simples começam comentários. - ' Para navegar neste tutorial dentro do compilador do Visual Basic, + ' Para navegar neste tutorial dentro do compilador do Visual Basic, ' eu criei um sistema de navegação. ' Este sistema de navegação vai ser explicado conforme avançarmos no ' tutorial, e você vai entender o que isso significa. @@ -275,10 +275,10 @@ module Module1 End Module ``` -##Referências +## Referências Aprendi Visual Basic no aplicativo de console. Isso me permitiu entender os princípios da programação de computador para continuar a aprender outras linguagens de programação facilmente. -Eu criei um tutorial mais aprofundado do Visual Basic para aqueles que gostariam de saber mais. +Eu criei um tutorial mais aprofundado do [Visual Basic](http://www.vbbootcamp.co.uk/) para aqueles que gostariam de saber mais. Toda a sintaxe deste tutorial é válida. Copie e cole o código no compilador do Visual Basic e execute (com o F5) o programa. diff --git a/pythonstatcomp.html.markdown b/pythonstatcomp.html.markdown index 38bffd88..1e8a12b8 100644 --- a/pythonstatcomp.html.markdown +++ b/pythonstatcomp.html.markdown @@ -13,7 +13,7 @@ This is a tutorial on how to do some typical statistical programming tasks using """ To get started, pip install the following: jupyter, numpy, scipy, pandas, matplotlib, seaborn, requests. Make sure to do this tutorial in a Jupyter notebook so that you get - the inline plots and easy documentation lookup. The shell command to open + the inline plots and easy documentation lookup. The shell command to open one is simply `jupyter notebook`, then click New -> Python. """ @@ -227,8 +227,9 @@ sns.lmplot("BirthY", "EstAge", data=hre) If you want to learn more, get _Python for Data Analysis_ by Wes McKinney. It's a superb resource and I used it as a reference when writing this tutorial. -You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's Probabilistic Programming and Bayesian Methods for Hackers. +You can also find plenty of interactive IPython tutorials on subjects specific to your interests, like Cam Davidson-Pilon's [Probabilistic Programming and Bayesian Methods for Hackers](http://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). Some more modules to research: - - text analysis and natural language processing: nltk, http://www.nltk.org - - social network analysis: igraph, http://igraph.org/python/ + + - text analysis and natural language processing: [nltk](http://www.nltk.org) + - social network analysis: [igraph](http://igraph.org/python/) diff --git a/ru-ru/c-ru.html.markdown b/ru-ru/c-ru.html.markdown index f7b1477b..f376054d 100644 --- a/ru-ru/c-ru.html.markdown +++ b/ru-ru/c-ru.html.markdown @@ -60,7 +60,7 @@ int main() { // long как правило занимает от 4 до 8 байт // long long занимает как минимум 64 бита long x_long = 0; - long long x_long_long = 0; + long long x_long_long = 0; // float это 32-битное число с плавающей точкой float x_float = 0.0; @@ -124,7 +124,7 @@ int main() { // Если между одинарными кавычками есть символ – это символьный литерал, // но это тип int, а не char (по историческим причинам). - + int cha = 'a'; // хорошо char chb = 'a'; // тоже хорошо (подразумевается преобразование int в char) @@ -165,7 +165,7 @@ int main() { // Правильно: int between_0_and_2 = 0 < a && a < 2; - // Логика + // Логика !3; // => 0 (логическое НЕ) !0; // => 1 1 && 1; // => 1 (логическое И) @@ -206,8 +206,8 @@ int main() { } // => prints "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, " printf("\n"); - - //Цикл с постусловием + + // Цикл с постусловием int kk = 0; do { printf("%d, ", kk); @@ -239,12 +239,12 @@ int main() { exit(-1); break; } - + /////////////////////////////////////// // Форматирование вывода /////////////////////////////////////// - // Каждое выражение в Си имеет тип, но вы можете привести один тип к другому, + // Каждое выражение в Си имеет тип, но вы можете привести один тип к другому, // если хотите (с некоторыми искажениями). int x_hex = 0x01; // Вы можете назначать переменные с помощью шестнадцатеричного кода. @@ -259,7 +259,7 @@ int main() { // Для определения максимального значения типов `char`, `signed char` и `unisigned char`, // соответственно используйте CHAR_MAX, SCHAR_MAX и UCHAR_MAX макросы из - + // Целые типы могут быть приведены к вещественным и наоборот. printf("%f\n", (float)100); // %f formats a float printf("%lf\n", (double)100); // %lf formats a double @@ -304,8 +304,8 @@ int main() { // Объявление указателя на int с адресом массива. int* x_ptr = x_array; - // x_ptr сейчас указывает на первый элемент массива (со значением 20). - // Это работает, потому что при обращении к имени массива возвращается + // x_ptr сейчас указывает на первый элемент массива (со значением 20). + // Это работает, потому что при обращении к имени массива возвращается // указатель на первый элемент. // Например, когда массив передаётся в функцию или присваивается указателю, он // неявно преобразуется в указатель. @@ -326,7 +326,7 @@ int main() { printf("%d\n", x_array[1]); // => Напечатает 19 // Вы также можете динамически выделять несколько блоков памяти с помощью - // функции malloc из стандартной библиотеки, которая принимает один + // функции malloc из стандартной библиотеки, которая принимает один // аргумент типа size_t – количество байт необходимых для выделения. int *my_ptr = malloc(sizeof(*my_ptr) * 20); for (xx = 0; xx < 20; xx++) { @@ -335,16 +335,16 @@ int main() { // Работа с памятью с помощью указателей может давать неожиданные и // непредсказуемые результаты. - printf("%d\n", *(my_ptr + 21)); // => Напечатает кто-нибудь знает, что? + printf("%d\n", *(my_ptr + 21)); // => Напечатает кто-нибудь знает, что? // Скорей всего программа вылетит. - // Когда вы закончили работать с памятью, которую ранее выделили, вам необходимо + // Когда вы закончили работать с памятью, которую ранее выделили, вам необходимо // освободить её, иначе это может вызвать утечку памяти или ошибки. free(my_ptr); - // Строки это массивы символов, но обычно они представляются как + // Строки это массивы символов, но обычно они представляются как // указатели на символ (как указатели на первый элемент массива). - // Хорошей практикой считается использование `const char *' при объявлении + // Хорошей практикой считается использование `const char *' при объявлении // строчного литерала. При таком подходе литерал не может быть изменён. // (например "foo"[0] = 'a' вызовет ошибку!) @@ -460,7 +460,7 @@ void str_reverse_through_pointer(char *str_in) { void (*f)(char *); // Сигнатура должна полностью совпадать с целевой функцией. f = &str_reverse; // Присвоить фактический адрес (во время исполнения) // "f = str_reverse;" тоже будет работать. - //Имя функции (как и массива) возвращает указатель на начало. + // Имя функции (как и массива) возвращает указатель на начало. (*f)(str_in); // Просто вызываем функцию через указатель. // "f(str_in);" или вот так } @@ -468,10 +468,8 @@ void str_reverse_through_pointer(char *str_in) { ## На почитать -Лучше всего найдите копию [K&R, aka "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language) -Это **книга** написанная создателями Си. Но будьте осторожны, она содержит идеи которые больше не считаются хорошими. - -Другой хороший ресурс: [Learn C the hard way](http://learncodethehardway.org/c/). +Лучше всего найдите копию [K&R, она же "The C Programming Language"](https://en.wikipedia.org/wiki/The_C_Programming_Language), +это книга написанная создателями Си. Но будьте осторожны, она содержит идеи которые больше не считаются хорошими. Если у вас появился вопрос, почитайте [compl.lang.c Frequently Asked Questions](http://c-faq.com). @@ -479,4 +477,4 @@ void str_reverse_through_pointer(char *str_in) { Читаемый код лучше, чем красивый или быстрый код. Чтобы научиться писать хороший код, почитайте [Linux kernel coding style](https://www.kernel.org/doc/Documentation/CodingStyle). -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +[1] [http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) diff --git a/ru-ru/perl-ru.html.markdown b/ru-ru/perl-ru.html.markdown index a9bb683b..417cd801 100644 --- a/ru-ru/perl-ru.html.markdown +++ b/ru-ru/perl-ru.html.markdown @@ -128,7 +128,7 @@ open(my $in, "<", "input.txt") or die "Can't open input.txt: $!"; open(my $out, ">", "output.txt") or die "Can't open output.txt: $!"; open(my $log, ">>", "my.log") or die "Can't open my.log: $!"; -# Читать из файлового дескриптора можно с помощью оператора "<>". +# Читать из файлового дескриптора можно с помощью оператора "<>". # В скалярном контексте он читает одну строку из файла, в списковом -- # читает сразу весь файл, сохраняя по одной строке в элементе массива: @@ -154,7 +154,7 @@ logger("We have a logger subroutine!"); Perl-овые модули предоставляют широкий набор функциональности, так что вы можете не изобретать заново велосипеды, а просто скачать -нужный модуль с CPAN (http://www.cpan.org/). +нужный модуль с [CPAN](http://www.cpan.org/). Некоторое количество самых полезных модулей включено в стандартную поставку Perl. diff --git a/smalltalk.html.markdown b/smalltalk.html.markdown index e1ae832c..208437be 100644 --- a/smalltalk.html.markdown +++ b/smalltalk.html.markdown @@ -5,7 +5,6 @@ contributors: - ["Jigyasa Grover", "https://jigyasa-grover.github.io"] - ["tim Rowledge", "tim@rowledge.org"] --- -
    Every effort has been made in the preparation of this material to ensure the accuracy and completeness of the information presented. However, no guarantee is given nor responsibility taken for errors or omissions. In case of any error, questions or suggestions on reach out to me at jigyasa-grover.github.io or drop me an e-mail at grover[dot]jigyasa1[at]gmail.com.
    - Smalltalk is a fully object-oriented, dynamically typed, reflective programming language with no 'non-object' types. - Smalltalk was created as the language to underpin the "new world" of computing exemplified by "human–computer symbiosis." diff --git a/stylus.html.markdown b/stylus.html.markdown index 7300dabf..9cf71466 100644 --- a/stylus.html.markdown +++ b/stylus.html.markdown @@ -93,15 +93,15 @@ $body-font = 'Roboto', sans-serif Now, if you want to change the color, you only have to make the change once. */ body - background-color $primary-color - color $secondary-color - font-family $body-font + background-color $primary-color + color $secondary-color + font-family $body-font /* After compilation: */ body { - background-color: #A3A4FF; - color: #51527F; - font-family: 'Roboto', sans-serif; + background-color: #A3A4FF; + color: #51527F; + font-family: 'Roboto', sans-serif; } / * @@ -118,10 +118,10 @@ element, you may want to store that code in a mixin. center() display block - margin-left auto - margin-right auto - left 0 - right 0 + margin-left auto + margin-right auto + left 0 + right 0 /* Using the mixin */ body { @@ -131,12 +131,12 @@ body { /* After compilation: */ div { - display: block; - margin-left: auto; - margin-right: auto; - left: 0; - right: 0; - background-color: #A3A4FF; + display: block; + margin-left: auto; + margin-right: auto; + left: 0; + right: 0; + background-color: #A3A4FF; } /* You can use mixins to create a shorthand property. */ @@ -149,7 +149,7 @@ size($width, $height) size(100px, 60px) .square - size(40px, 40px) + size(40px, 40px) /* You can use a mixin as a CSS property. */ circle($ratio) @@ -224,4 +224,4 @@ for $item in (1..2) /* Repeat block 12 times */ width ($item / 12) * 100% /* Calculate row by column number */ ``` -Now that you know a little about this powerful CSS preprocessor, you're ready to create more dynamic style sheets. To learn more, visit the official stylus documentation at http://stylus-lang.com. +Now that you know a little about this powerful CSS preprocessor, you're ready to create more dynamic style sheets. To learn more, visit the official stylus documentation at [stylus-lang.com](https://stylus-lang.com). diff --git a/ta-in/xml-ta.html.markdown b/ta-in/xml-ta.html.markdown index f9ebe854..e360ee39 100644 --- a/ta-in/xml-ta.html.markdown +++ b/ta-in/xml-ta.html.markdown @@ -13,19 +13,17 @@ lang: ta-in XML ஆனது ஒரு கட்டமைப்பு மொழி ஆகும் இது தகவலை சேமிக்கவும் தகவலை பரிமாறவும் உருவாக்கபட்டுள்ளது +HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது -HTML போல் அன்றி , XML ஆனது தகவலை மட்டும் கொண்டு செல்ல்கிறது - -## சில வரையறை மற்றும் முன்னுரை +## சில வரையறை மற்றும் முன்னுரை பல கூறுகளால் அமைக்கப்பட்டது. ஒவொரு கூறுகளிலும் அட்ட்ரிபூட்க்கள் இருக்கும், அவை அந்தந்த கூறுகளை வரையறுக்க பயன்படும். மேலும் அந்த கூறுகளை தகவல் அல்லது கிளை கூறுகள் இருக்கலாம். அணைத்து கோப்புகளிலும் ரூட்/ஆரம்ப கூறு இருக்கும், அது தனக்குள் கிளை கூறுகளை கொண்டுருக்கும். -XML பாகுபடுத்தி மிகவும் கண்டிப்பான வீதிகளைக்கொண்டது. [XML தொடரியல் விதிகளை அறிய] (http://www.w3schools.com/xml/xml_syntax.asp). - +XML பாகுபடுத்தி மிகவும் கண்டிப்பான வீதிகளைக்கொண்டது. [XML தொடரியல் விதிகளை அறிய](http://www.w3schools.com/xml/xml_syntax.asp). ```xml - @@ -68,7 +66,6 @@ XML பாகுபடுத்தி மிகவும் கண்டிப * XML வாக்கிய அமைப்பு - ```xml @@ -96,20 +93,19 @@ XML பாகுபடுத்தி மிகவும் கண்டிப @@ -166,11 +158,11 @@ With this tool, you can check the XML data outside the application logic. ]> - +--> diff --git a/tr-tr/c-tr.html.markdown b/tr-tr/c-tr.html.markdown index 18674cc6..898c732c 100644 --- a/tr-tr/c-tr.html.markdown +++ b/tr-tr/c-tr.html.markdown @@ -8,9 +8,8 @@ contributors: translators: - ["Haydar KULEKCI", "http://scanf.info/"] lang: tr-tr - --- -/* + C halen modern yüksek performans bilgisayarların dili. C bir çok programcının kullandığı en düşük seviye dillerdendir, ama @@ -24,23 +23,23 @@ anlarsanız sizi isteğiniz yere götürecektir. Çoklu satırlı yorumlar bu şekilde görünür. */ -// C Standart kütüphanelerini uygulamanıza #include ile +// C Standart kütüphanelerini uygulamanıza #include ile // dahil edebilirsiniz. #include #include #include -// Kendi başlık(header) dosyalarınız dahil etmek için "çift tırnak" +// Kendi başlık(header) dosyalarınız dahil etmek için "çift tırnak" // kullanmalısınız. #include "my_header.h" -// Fonksiyonlarınızı bir .h dosyasında ya da c dosyanızın üst tarafta +// Fonksiyonlarınızı bir .h dosyasında ya da c dosyanızın üst tarafta // tanımlayın. void function_1(); void function_2(); -// Programınızın giriş noktası main isimli bir fonksiyondur ve +// Programınızın giriş noktası main isimli bir fonksiyondur ve // integer değer döner int main() { @@ -62,31 +61,31 @@ int main() { // short değişken tipi genellikle 2 byte boyutundadır. short x_short = 0; - // char tipi 1 byte boyutunu garanti eder. + // char tipi 1 byte boyutunu garanti eder. char x_char = 0; char y_char = 'y'; // Karakterler '' işaretleri arasına yazılır. // long tipi 4-8 byte olur; long long tipi en azından 64 bit garantiler. long x_long = 0; - long long x_long_long = 0; + long long x_long_long = 0; // float tipi 32-bit kayan noktalı sayı boyutundadır. float x_float = 0.0; - // double değişken tipi 64-bit kayan noktalı yazı tipindedir. + // double değişken tipi 64-bit kayan noktalı yazı tipindedir. double x_double = 0.0; - // Integral türleri işaretsiz olabilir. Bunun anlamı, onlar eksi değer - // olamaz demektir, ama aynı boyuttaki işaretsiz bir sayının maksimum + // Integral türleri işaretsiz olabilir. Bunun anlamı, onlar eksi değer + // olamaz demektir, ama aynı boyuttaki işaretsiz bir sayının maksimum // değeri işaretli bir sayının maksimum değeriden büyük olur. unsigned char ux_char; unsigned short ux_short; unsigned int ux_int; unsigned long long ux_long_long; - // Diğer taraftan char, ki her zaman bir byte boyutundadır, bu tipler - // makinenize göre boyut değiştirir. sizeof(T) size bir değişkenin byte - // cinsinden boyutunu verir öyle ki bu tipin boyutunu taşınabilir bir + // Diğer taraftan char, ki her zaman bir byte boyutundadır, bu tipler + // makinenize göre boyut değiştirir. sizeof(T) size bir değişkenin byte + // cinsinden boyutunu verir öyle ki bu tipin boyutunu taşınabilir bir // şekilde ifade edilebilir // Örneğin, printf("%lu\n", sizeof(int)); // => 4 (bir çok makinede 4-byte words) @@ -96,7 +95,7 @@ int main() { // Bu durumda verimliligin degeri derleme-zamani sabitidir. int a = 1; - // size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir + // size_t bir objeyi temsil etmek için kullanılan 2 byte uzunluğundaki bir // işaretsiz tam sayı tipidir size_t size = sizeof(a++); // a++ is not evaluated @@ -111,7 +110,7 @@ int main() { // Şu şekilde bir diziyi 0 ile oluşturabilirsiniz: char my_array[20] = {0}; - // Dizinin elemanlarını indexlemek diğer diller gibidir, veya + // Dizinin elemanlarını indexlemek diğer diller gibidir, veya // diğer diller C gibi. my_array[0]; // => 0 @@ -137,13 +136,13 @@ int main() { // String'ler bir NUL (0x00) byte ile sonlandırılmış karakter dizileridir, // bu string içerisinde özel bir karakter olan '\0' ile gösterilir. - // (Biz Nul byte'i string karakterleri arasında bulundurmamıza gerek + // (Biz Nul byte'i string karakterleri arasında bulundurmamıza gerek // yoktur; derleyici onu bizim için dizinin sonuna ekler.) char a_string[20] = "This is a string"; printf("%s\n", a_string); // %s bir string formatıdır. /* - a_string 16 karakter uzunluğundadır. + a_string 16 karakter uzunluğundadır. 17. karakter NUL karakteridir. 18., 19. ve 20. karakterler tanımsızdır.(undefined) */ @@ -176,7 +175,7 @@ int main() { // Karşılaştırma operatörleri muhtemelen tanıdıktır, ama // C'de boolean tipi yoktur. Bunun yerine sayı(int) kullanırız. - // 0 false yerine ve diğer herşey true yerine geçmektedir. + // 0 false yerine ve diğer herşey true yerine geçmektedir. // (Karşılaştırma operatörleri her zaman 0 veya 1 dönmektedir.) 3 == 2; // => 0 (false) 3 != 2; // => 1 (true) @@ -247,7 +246,7 @@ int main() { // Tip Dönüşümleri /////////////////////////////////////// - // C'de her değer bir tipe sahiptir, ama siz bir değeri bir başka tipe + // C'de her değer bir tipe sahiptir, ama siz bir değeri bir başka tipe // dönüştürebilirsiniz. int x_hex = 0x01; // Hex literatüründe değer atayabilirsiniz. @@ -260,11 +259,11 @@ int main() { // Tip hiçbir hata vermeden taşacaktır(overflow). printf("%d\n", (unsigned char) 257); // => 1 (Max char = 255 eğer karakter 8 bit uzunluğunda ise) - // `char`, `signed char` ve `unsigned char` karakter tiplerinin maksimum uzunluğunu - // belirlemek için kütüphanesindeki CHAR_MAX, SCHAR_MAX ve UCHAR_MAX + // `char`, `signed char` ve `unsigned char` karakter tiplerinin maksimum uzunluğunu + // belirlemek için kütüphanesindeki CHAR_MAX, SCHAR_MAX ve UCHAR_MAX // macrolarını kullanınız. - // Integral tipi kayan noktalı yazı tipine dönüştürülecektir ve tam tersi. + // Integral tipi kayan noktalı yazı tipine dönüştürülecektir ve tam tersi. printf("%f\n", (float)100); // %f formats a float printf("%lf\n", (double)100); // %lf formats a double printf("%d\n", (char)100.0); @@ -273,36 +272,36 @@ int main() { // İşaretçiler (Pointers) /////////////////////////////////////// - // Bir işaretci bellek adresini barındıran bir değişkendir. Tanımlaması ile işaret - // edeceği verinin tipi de belirtilecektir. Değişkenlerininzi bellek adreslerini - // getirerek bellek ile ilgili karışıklığı ortadan kaldırabilirsiniz. + // Bir işaretci bellek adresini barındıran bir değişkendir. Tanımlaması ile işaret + // edeceği verinin tipi de belirtilecektir. Değişkenlerininzi bellek adreslerini + // getirerek bellek ile ilgili karışıklığı ortadan kaldırabilirsiniz. int x = 0; - printf("%p\n", &x); // & işareti bir değişkenin bellek adresini getirmek için kullanılır. + printf("%p\n", &x); // & işareti bir değişkenin bellek adresini getirmek için kullanılır. // (%p işaretçilerin formatıdır) // => Bazı bellek adresleri yazdırılacaktır. // İşaretçiler tanımlanırken * ile başlar - int *px, not_a_pointer; // px sayı tipinde bir işaretçidir. + int *px, not_a_pointer; // px sayı tipinde bir işaretçidir. px = &x; // X değişkeninin bellek adresi px değişkeninde tutulmaktadır. - printf("%p\n", px); // => x değişkeninin bellek adresi yazdırılacaktır. + printf("%p\n", px); // => x değişkeninin bellek adresi yazdırılacaktır. printf("%d, %d\n", (int)sizeof(px), (int)sizeof(not_a_pointer)); // => 64-bit sistemde "8, 4" yazdırılacaktır. - // İşaretçinin adres olarak gösterdiği yerdeki değeri almak için + // İşaretçinin adres olarak gösterdiği yerdeki değeri almak için // değişkenin önüne * işareti ekleyiniz. - printf("%d\n", *px); // => 0 bastıracaktır, x in değeridir, + printf("%d\n", *px); // => 0 bastıracaktır, x in değeridir, // çünkü px değişkeni x in adresini göstermektedir. - // Ayrıca siz işaretçinin gösterdiği yerin değerini - // değiştirebilirsiniz. Burada referansı parantez içerisinde göstereceğiz + // Ayrıca siz işaretçinin gösterdiği yerin değerini + // değiştirebilirsiniz. Burada referansı parantez içerisinde göstereceğiz // çünkü ++ işleminin önceliği * işleminden yüksektir. - (*px)++; // px'in işaret ettiği değeri 1 artır. + (*px)++; // px'in işaret ettiği değeri 1 artır. printf("%d\n", *px); // => 1 yazdırılır. printf("%d\n", x); // => 1 yazdırılır. - int x_array[20]; // Diziler(arrays) bellekten yan yana bellek bloklarını + int x_array[20]; // Diziler(arrays) bellekten yan yana bellek bloklarını // tahsis etmek için iyi bir yöntemdir. int xx; for (xx=0; xx<20; xx++) { @@ -312,7 +311,7 @@ int main() { // Bir sayı tipinde işaretçi tanımlanıyor ve x_array'i işaret ediyor. int* x_ptr = x_array; // x_ptr artık dizinin ilk elemanını işaret etmektedir (the integer 20). - // Bu çalışacaktır çünkü diziler(arrays) aslında sadece onların ilk + // Bu çalışacaktır çünkü diziler(arrays) aslında sadece onların ilk // elemanlarını gösteren birer işaretçidir. // For example, when an array is passed to a function or is assigned to a pointer, // it decays into (implicitly converted to) a pointer. @@ -331,25 +330,25 @@ int main() { printf("%d\n", *(x_ptr)); // => 20 yazılacaktır. printf("%d\n", x_array[0]); // => 20 yazılacaktır. - // İşaretçiler kendi tiplerinde artırılır ve azaltılır. + // İşaretçiler kendi tiplerinde artırılır ve azaltılır. printf("%d\n", *(x_ptr + 1)); // => 19 yazılacaktır. printf("%d\n", x_array[1]); // => 19 yazılacaktır. - // Ayrıca dinamik olarak bir bellek bloğunu standart kütüphanede bulunan - // malloc fonksiyonu ile uygulamanız için ayırabilirsiniz. Bu fonksiyon - // byte türünden ayırmak istediğiniz bloğun boyutunu parametre olarak alır. + // Ayrıca dinamik olarak bir bellek bloğunu standart kütüphanede bulunan + // malloc fonksiyonu ile uygulamanız için ayırabilirsiniz. Bu fonksiyon + // byte türünden ayırmak istediğiniz bloğun boyutunu parametre olarak alır. int* my_ptr = (int*) malloc(sizeof(int) * 20); for (xx=0; xx<20; xx++) { *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx 'de aynı zamanda çalışabilir } // Bellekte 20, 19, 18, 17... 2, 1 (as ints) şeklinde oluşturulmuş olacaktır. // Eğer ayrımadığınız bir bellek adresini çağırırsanız - // öngörülmeyen bir değer dönecektir. + // öngörülmeyen bir değer dönecektir. printf("%d\n", *(my_ptr + 21)); // => kim-bilir-ne-yazacak? - // Malloc fonksiyonu ile ayrıdığınız bellek kısmı ile işiniz bittiğinde - // onu free fonksiyonu ile boşaltmalısınız, aksi durumda uygulamanız - // kapatılana kadar belleğin o kısmını kimse kullanamaz. + // Malloc fonksiyonu ile ayrıdığınız bellek kısmı ile işiniz bittiğinde + // onu free fonksiyonu ile boşaltmalısınız, aksi durumda uygulamanız + // kapatılana kadar belleğin o kısmını kimse kullanamaz. free(my_ptr); // Metin Dizileri(String) birer karakter dizisidir(char array), ama @@ -373,8 +372,8 @@ int add_two_ints(int x1, int x2){ } /* -Fonksiyonlar pass-by-value'dür, ama isterseniz işaretçi referanslarını -kullanarak fonksiyona gönderilen parametrenin değerini değiştirebilirsiniz. +Fonksiyonlar pass-by-value'dür, ama isterseniz işaretçi referanslarını +kullanarak fonksiyona gönderilen parametrenin değerini değiştirebilirsiniz. Example: Bir metni tersine çevirme */ @@ -404,7 +403,7 @@ printf("%s\n", c); // => ".tset a si sihT" typedef int my_type; my_type my_type_var = 0; -// Struct'lar bir veri koleksiyonudur. +// Struct'lar bir veri koleksiyonudur. struct rectangle { int width; int height; @@ -426,14 +425,14 @@ void function_1(){ // Bir yapının adresini işaretçiye atayabilirsiniz. struct rectangle* my_rec_ptr = &my_rec; - // İşaretçi üzerinden bir yapıya ulaşabilirsiniz. + // İşaretçi üzerinden bir yapıya ulaşabilirsiniz. (*my_rec_ptr).width = 30; - // ya da -> işareti ile yapının elemanlarına ulaşabilirsiniz. + // ya da -> işareti ile yapının elemanlarına ulaşabilirsiniz. my_rec_ptr->height = 10; // (*my_rec_ptr).height = 10; ile aynıdır. } -// Kolaylık sağlamak için bir yapıya typedef tanımlayabilirsiniz. +// Kolaylık sağlamak için bir yapıya typedef tanımlayabilirsiniz. typedef struct rectangle rect; int area(rect r){ @@ -447,8 +446,8 @@ int area(rect r){ /* Çalışma zamanında, fonksiyonların bilinen bir bellek adresleri vardır. Fonksiyon işaretçileri fonksiyonları direk olarak çağırmayı sağlayan veya geri bildirim(callback) -için parametre gönderirken kullanılan başka birer işaretçidirler. Ama, syntax tanımı -başlangıçta biraz karışık gelebilir. +için parametre gönderirken kullanılan başka birer işaretçidirler. Ama, syntax tanımı +başlangıçta biraz karışık gelebilir. Örnek: bir işaretçiden str_reverse kullanımı */ @@ -469,7 +468,7 @@ typedef void (*my_fnp_type)(char *); // Gerçek bir işaretçi tanımlandığı zaman ki kullanımı: // ... -// my_fnp_type f; +// my_fnp_type f; ``` ## Daha Fazla Okuma Listesi @@ -484,4 +483,4 @@ Readable code is better than clever code and fast code. For a good, sane coding Diğer taraftan google sizin için bir arkadaş olabilir. -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +[1] [stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member](https://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) diff --git a/zh-cn/angularjs-cn.html.markdown b/zh-cn/angularjs-cn.html.markdown index b0e39269..a3eca38e 100644 --- a/zh-cn/angularjs-cn.html.markdown +++ b/zh-cn/angularjs-cn.html.markdown @@ -313,7 +313,7 @@ angular.module('myApp', []).controller('namesCtrl', function($scope) {

    Total = {{ (quantity * price) | currency }}

    - + //一个过滤器可以通过一个管道符 (|) 及一个过滤器表达式添加到一个指令上。 //orderBy 过滤器根据一个表达式排序一个数组: @@ -327,7 +327,7 @@ angular.module('myApp', []).controller('namesCtrl', function($scope) {
    -//一个输入框过滤器可以通过一个管道符 (|) +//一个输入框过滤器可以通过一个管道符 (|) //以及后跟一个冒号和模式名的 filter 添加到一个指令上。 //该过滤器从一个数组中选择一个子集: @@ -354,7 +354,7 @@ angular.module('myApp', []).controller('namesCtrl', function($scope) { // AngularJS $http 是一个从 web 服务器上读取数据的核心服务。 // $http.get(url) 这个函数用来读取服务器数据。 -
    +
    • @@ -395,7 +395,7 @@ header("Access-Control-Allow-Origin: *"); // AngularJS 表格 // 使用 angular 显示表格非常简单: -
      +
      @@ -626,7 +626,7 @@ app.controller("myCtrl", function($scope) { //myApp.js -var app = angular.module("myApp", []); +var app = angular.module("myApp", []); // 模块定义中的 [] 参数可用来定义依赖的模块。 @@ -697,14 +697,3 @@ app.controller('myCtrl', function($scope) { $scope.lastName= "Doe"; }); ``` - -## 来源 & 参考 - -**例子** - -- http://www.w3schools.com/angular/angular_examples.asp - -**参考** - -- http://www.w3schools.com/angular/angular_ref_directives.asp -- http://www.w3schools.com/angular/default.asp diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 816335c2..aec060ed 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -568,6 +568,6 @@ void doSomethingWithAFile(const std::string& filename) 扩展阅读: -* [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。 -* 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。 -* 可以在 [TheChernoProject - C ++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)上找到涵盖语言基础和设置编码环境的教程。 +- [CPP Reference](http://cppreference.com/w/cpp) 提供了最新的语法参考。 +- 可以在 [CPlusPlus](http://cplusplus.com) 找到一些补充资料。 +- 可以在 [TheChernoProject - C++](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb) 上找到涵盖语言基础和设置编码环境的教程。 diff --git a/zh-cn/c-cn.html.markdown b/zh-cn/c-cn.html.markdown index 3bdc8479..da59489d 100644 --- a/zh-cn/c-cn.html.markdown +++ b/zh-cn/c-cn.html.markdown @@ -73,7 +73,7 @@ char y_char = 'y'; // 字符变量的字面值需要用单引号包住 // long型(长整型)一般需要4个字节到8个字节; 而long long型则至少需要8个字节(64位) long x_long = 0; -long long x_long_long = 0; +long long x_long_long = 0; // float一般是用32位表示的浮点数字 float x_float = 0.0; @@ -93,7 +93,7 @@ unsigned long long ux_long_long; 'A' // => 在ASCII字符集中是65 // char类型一定会占用1个字节,但是其他的类型却会因具体机器的不同而各异 -// sizeof(T) 可以返回T类型在运行的机器上占用多少个字节 +// sizeof(T) 可以返回T类型在运行的机器上占用多少个字节 // 这样你的代码就可以在各处正确运行了 // sizeof(obj)返回表达式(变量、字面量等)的尺寸 printf("%zu\n", sizeof(int)); // => 4 (大多数的机器字长为4) @@ -144,7 +144,7 @@ char a_string[20] = "This is a string"; printf("%s\n", a_string); // %s 可以对字符串进行格式化 /* 也许你会注意到 a_string 实际上只有16个字节长. -第17个字节是一个空字符(NUL) +第17个字节是一个空字符(NUL) 而第18, 19 和 20 个字符的值是未定义。 */ @@ -365,7 +365,7 @@ for (xx=0; xx<20; xx++) { // 声明一个整型的指针,并初始化为指向x_array int* x_ptr = x_array; -// x_ptr现在指向了数组的第一个元素(即整数20). +// x_ptr现在指向了数组的第一个元素(即整数20). // 这是因为数组通常衰减为指向它们的第一个元素的指针。 // 例如,当一个数组被传递给一个函数或者绑定到一个指针时, //它衰减为(隐式转化为)一个指针。 @@ -533,7 +533,7 @@ int area(const rect *r) 例子:通过指针调用str_reverse */ void str_reverse_through_pointer(char *str_in) { - // 定义一个函数指针 f. + // 定义一个函数指针 f. void (*f)(char *); // 签名一定要与目标函数相同 f = &str_reverse; // 将函数的地址在运行时赋给指针 (*f)(str_in); // 通过指针调用函数 @@ -549,7 +549,7 @@ typedef void (*my_fnp_type)(char *); // 实际声明函数指针会这么用: // ... -// my_fnp_type f; +// my_fnp_type f; // 特殊字符 '\a' // bell @@ -610,13 +610,10 @@ typedef void (*my_fnp_type)(char *); 最好找一本 [K&R, aka "The C Programming Language", “C程序设计语言”](https://en.wikipedia.org/wiki/The_C_Programming_Language)。它是关于C最重要的一本书,由C的创作者撰写。不过需要留意的是它比较古老了,因此有些不准确的地方。 - -另一个比较好的资源是 [Learn C the hard way](http://learncodethehardway.org/c/) - 如果你有问题,请阅读[compl.lang.c Frequently Asked Questions](http://c-faq.com/)。 使用合适的空格、缩进,保持一致的代码风格非常重要。可读性强的代码比聪明的代码、高速的代码更重要。可以参考下[Linux内核编码风格](https://www.kernel.org/doc/Documentation/process/coding-style.rst) 。 除了这些,多多Google吧 -[1] http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member +[1] [stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member](http://stackoverflow.com/questions/119123/why-isnt-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member) diff --git a/zh-cn/groovy-cn.html.markdown b/zh-cn/groovy-cn.html.markdown index f83dff02..b1c1ed8e 100644 --- a/zh-cn/groovy-cn.html.markdown +++ b/zh-cn/groovy-cn.html.markdown @@ -8,7 +8,7 @@ translators: lang: zh-cn --- -Groovy - Java平台的动态语言。[了解更多。](http://www.groovy-lang.org/) +Groovy - Java平台的动态语言。[了解更多](http://www.groovy-lang.org/)。 ```groovy /* @@ -268,7 +268,7 @@ def clos = { print it } clos( "hi" ) /* - Groovy可以记忆闭包结果 [1][2][3] + Groovy可以记忆闭包结果 */ def cl = {a, b -> sleep(3000) // 模拟费时操作 @@ -405,15 +405,6 @@ assert sum(2,5) == 7 ## 图书 -* [Groovy Goodness] (https://leanpub.com/groovy-goodness-notebook) - -* [Groovy in Action] (http://manning.com/koenig2/) - -* [Programming Groovy 2: Dynamic Productivity for the Java Developer] (http://shop.oreilly.com/product/9781937785307.do) - -[1] http://roshandawrani.wordpress.com/2010/10/18/groovy-new-feature-closures-can-now-memorize-their-results/ -[2] http://www.solutionsiq.com/resources/agileiq-blog/bid/72880/Programming-with-Groovy-Trampoline-and-Memoize -[3] http://mrhaki.blogspot.mx/2011/05/groovy-goodness-cache-closure-results.html - - - +* [Groovy Goodness](https://leanpub.com/groovy-goodness-notebook) +* [Groovy in Action](http://manning.com/koenig2/) +* [Programming Groovy 2: Dynamic Productivity for the Java Developer](http://shop.oreilly.com/product/9781937785307.do) diff --git a/zh-cn/perl-cn.html.markdown b/zh-cn/perl-cn.html.markdown index 432866df..a9dd6fb3 100644 --- a/zh-cn/perl-cn.html.markdown +++ b/zh-cn/perl-cn.html.markdown @@ -138,7 +138,7 @@ logger("We have a logger subroutine!"); #### 使用Perl模块 -Perl模块提供一系列特性来帮助你避免重新发明轮子,CPAN是下载模块的好地方( http://www.cpan.org/ )。Perl发行版本身也包含很多流行的模块。 +Perl模块提供一系列特性来帮助你避免重新发明轮子,[CPAN](http://www.cpan.org/)是下载模块的好地方。Perl发行版本身也包含很多流行的模块。 perlfaq有很多常见问题和相应回答,也经常有对优秀CPAN模块的推荐介绍。 diff --git a/zh-cn/visualbasic-cn.html.markdown b/zh-cn/visualbasic-cn.html.markdown index 6bcb4364..236c10b5 100644 --- a/zh-cn/visualbasic-cn.html.markdown +++ b/zh-cn/visualbasic-cn.html.markdown @@ -74,14 +74,14 @@ Module Module1 ' 一、对应程序目录1,下同 - ' 使用 private subs 声明函数。 + ' 使用 private subs 声明函数。 Private Sub HelloWorldOutput() ' 程序名 Console.Title = "Hello World Output | Learn X in Y Minutes" ' 使用 Console.Write("") 或者 Console.WriteLine("") 来输出文本到屏幕上 ' 对应的 Console.Read() 或 Console.Readline() 用来读取键盘输入 Console.WriteLine("Hello World") - Console.ReadLine() + Console.ReadLine() ' Console.WriteLine()后加Console.ReadLine()是为了防止屏幕输出信息一闪而过 ' 类似平时常见的“单击任意键继续”的意思。 End Sub @@ -188,7 +188,7 @@ Module Module1 Console.Write(a.ToString() + " / " + b.ToString()) Console.WriteLine(" = " + e.ToString.PadLeft(3)) Console.ReadLine() - ' 询问用户是否继续,注意大小写。 + ' 询问用户是否继续,注意大小写。 Console.Write("Would you like to continue? (yes / no)") ' 程序读入用户输入 answer = Console.ReadLine() ' added a bracket here @@ -203,12 +203,12 @@ Module Module1 ' 这个程序我们将实现从10倒数计数. Console.Title = "Using For Loops | Learn X in Y Minutes" - ' 声明变量和Step (步长,即递减的速度,如-1,-2,-3等)。 - For i As Integer = 10 To 0 Step -1 + ' 声明变量和Step (步长,即递减的速度,如-1,-2,-3等)。 + For i As Integer = 10 To 0 Step -1 Console.WriteLine(i.ToString) ' 将计数结果输出的屏幕 Next i ' 计算新的i值 - Console.WriteLine("Start") - Console.ReadLine() + Console.WriteLine("Start") + Console.ReadLine() End Sub ' 八 @@ -266,8 +266,8 @@ End Module ## 参考 -我(译注:原作者)在命令行下学习的VB。命令行编程使我能够更好的了解程序编译运行机制,并使学习其它语言变得容易。 +我(译注:原作者)在命令行下学习的VB。命令行编程使我能够更好的了解程序编译运行机制,并使学习其它语言变得容易。 -如果希望进一步学习VB,这里还有更深层次的 VB教学(英文)。 +如果希望进一步学习VB,这里还有更深层次的 [VB教学(英文)](http://www.vbbootcamp.co.uk/)。 -所有代码均通过测试。只需复制粘帖到Visual Basic中,并按F5运行即可。 +所有代码均通过测试。只需复制粘帖到Visual Basic中,并按F5运行即可。 diff --git a/zh-tw/pcre-tw.html.markdown b/zh-tw/pcre-tw.html.markdown index 5f681d46..3b2ff3f7 100644 --- a/zh-tw/pcre-tw.html.markdown +++ b/zh-tw/pcre-tw.html.markdown @@ -72,13 +72,8 @@ PCRE提供了一些通用的字元類型,可被當作字元集合使用 | ^\S+ | 66.249.64.13 | `^` 為行首, `\S+` 抓取至少一個非空白字元 | | \+[0-9]+ | +1000 | `\+` 抓取 `+` 字元。 `[0-9]` 字元集表示剛好一個數字字元。 可以用 `\+\d+` 達到相同效果。 | -以上範例皆可在 https://regex101.com/ 測試,步驟如下: +以上範例皆可在 [regex101.com](https://regex101.com/) 測試,步驟如下: 1. 複製範例字串到 `TEST STRING` 區域 -2. 複製正規表達式字串到 `Regular Expression` 區域 +2. 複製正規表達式字串到 `Regular Expression` 區域 3. 網頁會顯示自動表達式抓取結果 - - -## 更多資料 - - From 8aab7be12b6e9011fc2796f0b5c67488819fb98b Mon Sep 17 00:00:00 2001 From: Gideon Date: Tue, 4 Jun 2024 21:34:29 -0400 Subject: [PATCH 274/392] [zfs/en] fixed typos (#4970) --- zfs.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/zfs.html.markdown b/zfs.html.markdown index 92d7aaa2..8058211d 100644 --- a/zfs.html.markdown +++ b/zfs.html.markdown @@ -18,7 +18,7 @@ usability for systems administrators. ### Virtual Devices -A VDEV (Virtual Device) in ZFS is analogous to a RAID device and simmilaly offers different +A VDEV (Virtual Device) in ZFS is analogous to a RAID device and similarly offers different benefits in terms of redundancy and performance. In general VDEV's offer better reliability and safety than a RAID card. It is discouraged to use a RAID setup with ZFS, as ZFS expects to directly manage the underlying disks. @@ -256,14 +256,14 @@ zroot/var none none ### Write Log Pool -The ZFS Intent Log (ZIL) is a write log designed to speed up syncronus writes. This is +The ZFS Intent Log (ZIL) is a write log designed to speed up synchronous writes. This is typically a faster drive or drive partition than the larger storage pools. ```bash # Add a log pool $ zpool add mypool/lamb log /dev/sdX -# Check the configureation +# Check the configuration $ zpool status mypool/lamb ``` @@ -277,13 +277,13 @@ storage pools. # Add a cache pool $ zpool add mypool/lamb cache /dev/sdY -# Check the configureation +# Check the configuration $ zpool status mypool/lamb ``` ### Data Compression -Data compression reduces the amount of space data occupies on disk in excange for some extra +Data compression reduces the amount of space data occupies on disk in exchange for some extra CPU usage. When enabled, it can enhance performance by reducing the amount of disk I/O. It especially beneficial on systems with more CPU resources than disk bandwidth. @@ -297,14 +297,14 @@ compression NO YES on | off | lzjb | gzip | gzip-[1-9] | zle | lz4 | # Set compression $ zfs set compression=on mypool/lamb -# Check the configureation +# Check the configuration $ zpool get compression mypool/lamb ``` ### Encryption at Rest Encryption allows data to be encrypted on the device at the cost of extra CPU cycles. This -propery can only be set when a dataset is being created. +property can only be set when a dataset is being created. ```bash # Enable encryption on the pool @@ -313,7 +313,7 @@ $ zpool set feature@encryption=enabled black_hole # Create an encrypted dataset with a prompt $ zfs create -o encryption=on -o keyformat=passphrase black_hole/enc -# Check the configureation +# Check the configuration $ zfs get encryption black_hole/enc ``` @@ -422,7 +422,7 @@ $ zfs promote zroot/home/sarlalian_new ### Putting it all together This following a script utilizing FreeBSD, jails and ZFS to automate -provisioning a clean copy of a mysql staging database from a live replication +provisioning a clean copy of a MySQL staging database from a live replication slave. ```bash From 0c411594bc385a3dcbf72b331eaa0e0da5264312 Mon Sep 17 00:00:00 2001 From: Mohammed Zohil PK <44064613+zoypk@users.noreply.github.com> Date: Wed, 5 Jun 2024 14:55:46 +0530 Subject: [PATCH 275/392] Update go.html.markdown (#4971) The Go wiki on GitHub has moved to go.dev The old link was broken, Updating the link ensures doc remains accurate and helpful. --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index 81d45b98..d3f2572e 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -492,4 +492,4 @@ There are many excellent conference talks and video tutorials on Go available on Go Mobile adds support for mobile platforms (Android and iOS). You can write all-Go native mobile apps or write a library that contains bindings from a Go package, -which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://github.com/golang/go/wiki/Mobile) for more information. +which can be invoked via Java (Android) and Objective-C (iOS). Check out the [Go Mobile page](https://go.dev/wiki/Mobile) for more information. From 8f09bf246e3bd7f49221e73aba36a0476a360e50 Mon Sep 17 00:00:00 2001 From: Mohammed Zohil PK <44064613+zoypk@users.noreply.github.com> Date: Wed, 5 Jun 2024 16:13:58 +0530 Subject: [PATCH 276/392] [go/cs-cz] Update Go Mobile link (#4974) --- cs-cz/go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cs-cz/go.html.markdown b/cs-cz/go.html.markdown index 18880a3b..b2fec30f 100644 --- a/cs-cz/go.html.markdown +++ b/cs-cz/go.html.markdown @@ -427,5 +427,5 @@ tak se podíváte na dokumentaci. Dalším dobrým zdrojem informací je [Go v ukázkách](https://gobyexample.com/). Go mobile přidává podporu pro Android a iOS. Můžete s ním psát nativní mobilní aplikace nebo knihovny, které půjdou -spustit přes Javu (pro Android), nebo Objective-C (pro iOS). Navštivte [web Go Mobile](https://github.com/golang/go/wiki/Mobile) +spustit přes Javu (pro Android), nebo Objective-C (pro iOS). Navštivte [web Go Mobile](https://go.dev/wiki/Mobile) pro více informací. From e61493af81c1df35c77546011e09755ef6833549 Mon Sep 17 00:00:00 2001 From: Mohammed Zohil PK <44064613+zoypk@users.noreply.github.com> Date: Thu, 6 Jun 2024 09:27:53 +0530 Subject: [PATCH 277/392] [go/ca-es] Update Go Mobile link (#4972) --- ca-es/go-ca.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ca-es/go-ca.html.markdown b/ca-es/go-ca.html.markdown index 7bec4ba4..82801ce1 100644 --- a/ca-es/go-ca.html.markdown +++ b/ca-es/go-ca.html.markdown @@ -460,5 +460,5 @@ Un altre gran recurs per aprendre Go és Go Mobile afegeix suport per plataformes mòbils (Android i iOS). Es poden escriure aplicacions mòbils o escriure llibreries de paquets de Go, que es poden cridar des de Java (android) i Objective-C (iOS). -Comproveu la [Go Mobile page](https://github.com/golang/go/wiki/Mobile) per +Comproveu la [Go Mobile page](https://go.dev/wiki/Mobile) per més informació. From 6b34d1f0838da0cd4d9899709c464b41c3878b26 Mon Sep 17 00:00:00 2001 From: Mohammed Zohil PK <44064613+zoypk@users.noreply.github.com> Date: Thu, 6 Jun 2024 09:28:08 +0530 Subject: [PATCH 278/392] [go/fr-fr] Update Go Mobile link (#4975) --- fi-fi/go-fi.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index c0b92d2f..6a966e46 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -438,4 +438,4 @@ lähdekoodi tulee esille! Toinen loistava paikka oppia on [Go by example](https://gobyexample.com/). Go Mobile lisää tuen mobiilialustoille (Android ja iOS). Voit kirjoittaa pelkällä Go:lla natiiveja applikaatioita tai tehdä kirjaston joka sisältää sidoksia -Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://github.com/golang/go/wiki/Mobile). +Go-paketista, jotka puolestaan voidaan kutsua Javasta (Android) ja Objective-C:stä (iOS). Katso [lisätietoja](https://go.dev/wiki/Mobile). From 06383371ef3eb376989a37fb6994b1624be5627d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A4=8D=E4=BA=88?= Date: Tue, 11 Jun 2024 11:58:24 +0800 Subject: [PATCH 279/392] [bc/zh-cn] Add Simplified Chinese Translation of `bc` (#4977) * [bc/zh-cn] Add Simplified Chinese Translation of bc Signed-off-by: CloneWith * Apply suggestions from review (7) --------- Signed-off-by: CloneWith --- zh-cn/bc-cn.html.markdown | 96 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 zh-cn/bc-cn.html.markdown diff --git a/zh-cn/bc-cn.html.markdown b/zh-cn/bc-cn.html.markdown new file mode 100644 index 00000000..e2cc3680 --- /dev/null +++ b/zh-cn/bc-cn.html.markdown @@ -0,0 +1,96 @@ +--- +language: bc +contributors: + - ["Btup"] +translators: + - ["CloneWith", "https://github.com/CloneWith"] +filename: learnbc.bc +lang: zh-cn +--- +```bc +/*这是一条 +多行注释。*/ +# 这(在 GNU bc 中)也是一条(单行)注释! + + /*1. 变量与指令结构*/ +num = 45 /*所有变量都只以双精度浮点数形式存储, + 并且 bc 不支持直接存储字符串常量。*/ +num = 45; /*每个语句后可以添加 + 一个英文分号,也可以不加。*/ +/*语句块使用 {} 运算符表示(与 C 语言相似):*/ +while(num < 50) { + num += 1 /*等价于 num=num+1。 + a = a op b 等价于 a op= b。*/ +} +/*也有 ++(自加)与 --(自减)运算符。*/ +/*有三个特殊变量: +scale: 定义双精度浮点数字的比例。 +ibase: 定义输入数值的基数。 +obase: 定义输出数值的基数。*/ +/*If 语句:*/ +hour = read() /*输入一个数字*/ + +if(hour < 12) { /*运算符的用法与 C 语言类似。*/ + print "Good morning\n" /*“print”输出字符串或变量,用英文逗号分隔。*/ +} else if(hour == 12) { + print "Hello\n" + /*字符串中的转义序列以反斜杠 \ 开头。 + 为了讲述清楚,以下为 bc 中常用转义序列表: + \b: 退格 + \c: 硬回车 + \n: 换行符 + \t: 制表符 + \\: 反斜杠*/ +} else { + print "Good afternoon\n" +} + +/*像 C 语言一样,只有 0 定义为假(false)。*/ +num = 0 +if(!num) {print "false\n"} + +/*与 C 语言不同,bc 没有 ?: 运算符。例如, + 这个代码块会导致出错: +a = (num) ? 1 : 0 +但是你可以模拟一个:*/ +a = (num) && (1) || (0) /*&& 代表“与”,|| 代表“或”*/ + +/*循环语句*/ +num = 0 +for(i = 1; i <= 100; i++) {/*与 C 语言中的循环类似。*/ + num += i +} + + /*2.函数与数组*/ +define fac(n) { /*使用“define”定义函数。*/ + if(n == 1 || n == 0) { + return 1 /*返回一个数值*/ + } + return n * fac(n - 1) /*可以使用递归*/ +} + +/*不可使用闭包与匿名函数。*/ + +num = fac(4) /*24*/ + +/*这是局部变量的示例:*/ +define x(n) { + auto x + x = 1 + return n + x +} +x(3) /*4*/ +print x /*看起来无法在函数外访问 x。*/ +/*数组与 C 语言中的等同。*/ +for(i = 0; i <= 3; i++) { + a[i] = 1 +} +/*这样访问它:*/ +print a[0], " ", a[1], " ", a[2], " ", a[3], "\n" +quit /*添加这行代码,确保程序退出。 +这行代码可写可不写。*/ +``` + +请享用这个简单的计算器吧!(或者确切地讲,这个编程语言。) + +本程序全部使用 GNU bc 语言编写。要运行程序,请使用 ```bc learnbc.bc```。 From 887d6e0653ddbec5f24179ac640509484f94d49d Mon Sep 17 00:00:00 2001 From: Mark Keller <8452750+keller00@users.noreply.github.com> Date: Tue, 18 Jun 2024 03:35:08 -0400 Subject: [PATCH 280/392] Move comment in c++.html.markdown (#4979) --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 6d039c33..7adb5244 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -263,10 +263,10 @@ std::string& fooRef = foo; // This creates a reference to foo. fooRef += ". Hi!"; // Modifies foo through the reference std::cout << fooRef; // Prints "I am foo. Hi!" +std::cout << &fooRef << '\n'; // Prints the address of foo // Doesn't reassign "fooRef". This is the same as "foo = bar", and // foo == "I am bar" // after this line. -std::cout << &fooRef << '\n'; // Prints the address of foo fooRef = bar; std::cout << &fooRef << '\n'; // Still prints the address of foo std::cout << fooRef << '\n'; // Prints "I am bar" From 7611e1f1904619b58333a8c564500d9cb2b584d9 Mon Sep 17 00:00:00 2001 From: Mark Keller <8452750+keller00@users.noreply.github.com> Date: Tue, 18 Jun 2024 03:35:45 -0400 Subject: [PATCH 281/392] Update c++.html.markdown (#4980) --- c++.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c++.html.markdown b/c++.html.markdown index 7adb5244..663fa45e 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -840,7 +840,7 @@ void doSomethingWithAFile(const std::string& filename) // manage the lifetime of the object being pointed to without ever needing to explicitly delete // the object. The term itself simply describes a set of pointers with the // mentioned abstraction. -// Smart pointers should preferred over raw pointers, to prevent +// Smart pointers should be preferred over raw pointers, to prevent // risky memory leaks, which happen if you forget to delete an object. // Usage of a raw pointer: From 0cdd791b9fe95a9fd3435a8af37dc20d6f5216df Mon Sep 17 00:00:00 2001 From: ary <75646364+arynnette@users.noreply.github.com> Date: Tue, 25 Jun 2024 04:03:23 -0400 Subject: [PATCH 282/392] fix typo/grammatical error in rust.html.markdown (#4985) --- rust.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust.html.markdown b/rust.html.markdown index 421124be..11483eef 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -99,7 +99,7 @@ fn main() { // A string slice – an immutable view into another string // This is basically an immutable pair of pointers to a string – it doesn’t // actually contain the contents of a string, just a pointer to - // the begin and a pointer to the end of a string buffer, + // the beginning and a pointer to the end of a string buffer, // statically allocated or contained in another object (in this case, `s`). // The string slice is like a view `&[u8]` into `Vec`. let s_slice: &str = &s; From 6a47e1605084dee71270a51b31671677e30cdb76 Mon Sep 17 00:00:00 2001 From: Coldle Date: Sat, 29 Jun 2024 20:52:58 +0800 Subject: [PATCH 283/392] [markdown/zh-cn] Update the translation (#4987) --- zh-cn/markdown-cn.html.markdown | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index da2e9ef2..c4635e84 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -6,6 +6,7 @@ translators: - ["Fangzhou Chen","https://github.com/FZSS"] - ["Luffy Zhong", "https://github.com/mengzhongshi"] - ["Yuchen Liu", "https://github.com/smallg0at"] + - ["Coldle", "https://github.com/yocoldle"] filename: learnmarkdown-cn.md lang: zh-cn --- @@ -273,7 +274,22 @@ Markdown同样支持引用形式的链接 [This]: http://thisisalink.com/ ``` -但这并不常用 +但这种用法并不常用。 + +### 目录 + +部分 Markdown 方言样式通过列表、链接以及标题的组合来创建文章的目录。 +在这种情况下,可使用填充了 hash(`#`) 的小写标题名称作为链接 id。 +如果标题由多个单词组成的,可通过连字符(`-`)连接在一起。(原标题中的部分特殊字符可能被省略) + +```md +- [Heading](#heading) +- [Another heading](#another-heading) +- [Chapter](#chapter) + - [Subchapter

      ](#subchapter-h3-) +``` + +注意,这一特性未必在所有的 Markdown 解析器中以相同的方式实现。 ## 图片 @@ -352,6 +368,16 @@ Markdown同样支持引用形式的链接 这真的太丑了 | 药不能 | 停!!!! ``` -真的是*看着令人头晕* +## Markdownlint(Markdown 的静态分析工具) + +`Markdownlint` 被创建用于简化 Markdown 的工作流程并统一编码样式。 +其作为[独立工具](https://github.com/markdownlint/markdownlint)以及某些 IDE 的插件使用,可确保 Markdown 文档的有效性和可读性。 + +--- 更多信息, 请于[此处](http://daringfireball.net/projects/Markdown/syntax)参见 John Gruber 关于语法的官方帖子,及于[此处](https://github.com/adam-p/Markdown-here/wiki/Markdown-Cheatsheet) 参见 Adam Pritchard 的摘要笔记。 + +如果您想了解更多主流 Markdown 方言样式的特性,请参阅: + +- [GitHub Flavored Markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) +- [GitLab Flavored Markdown](https://docs.gitlab.com/ee/user/markdown.html) \ No newline at end of file From 94c8d06049f5052a37e81edc8fbe04d4eda8f8bb Mon Sep 17 00:00:00 2001 From: Kenryu Shibata Date: Sun, 30 Jun 2024 04:46:00 +0900 Subject: [PATCH 284/392] [C/ja-jp] Added Japanese Translation (#4978) --- ja-jp/c-jp.html.markdown | 916 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 916 insertions(+) create mode 100644 ja-jp/c-jp.html.markdown diff --git a/ja-jp/c-jp.html.markdown b/ja-jp/c-jp.html.markdown new file mode 100644 index 00000000..9dbe0569 --- /dev/null +++ b/ja-jp/c-jp.html.markdown @@ -0,0 +1,916 @@ +--- +language: C +filename: learnc-jp.c +lang: ja-jp +contributors: + - ["Adam Bard", "http://adambard.com/"] + - ["Árpád Goretity", "http://twitter.com/H2CO3_iOS"] + - ["Jakub Trzebiatowski", "http://cbs.stgn.pl"] + - ["Marco Scannadinari", "https://marcoms.github.io"] + - ["Zachary Ferguson", "https://github.io/zfergus2"] + - ["himanshu", "https://github.com/himanshu81494"] + - ["Joshua Li", "https://github.com/JoshuaRLi"] + - ["Dragos B. Chirila", "https://github.com/dchirila"] + - ["Heitor P. de Bittencourt", "https://github.com/heitorPB/"] +translators: + - ["Kenryu Shibata", "https://github.com/kenryuS"] +--- + +え、C? あぁ、**未だに**モダンで高パフォーマンスを実現できるあの言語のことだな。 + +Cはほとんどのプログラマが最低水準言語として使われているが、その特徴は実行速度の速さだけ +ではないのだ。CはPythonなどの高水準言語とは異なり、メモリの自動管理機能がなく、 +プログラマーの手で管理する必要があり、これが初学者を苦しめる要素となるが、うまく使えば、 +ロボットなどで実行速度やメモリの使用率などを大幅に最適化できる。 + +> **コンパイラフラグについて** +> +> gccやclangなどのコンパイラではデフォルトでデバッグに有益なエラーや警告を表示しない +> 設定になっています。なので、それらのエラーを詳細に、厳しく表示させるフラグと共に +> 実行することをおすすめします。下記はそのフラグの例です: +> +> `-Wall -Wextra -Werror -O2 -std=c99 -pedantic` +> +> このようなフラグの詳細については、オンライン検索にかけるか、 +> コンパイラのドキュメンテーションを読んでください。(Linuxなら`man 1 gcc`等) + +```c +// 行コメントは//で始まる (C99より前のC標準では使えない) + +// Cに限ったことではないが、ソースコードで日本語コメントを書くときにはファイルを +// UTF-8で保存することをおすすめします。なぜならgccなど特定のコンパイラでは +// 文字コード変換の影響で意図しないコメントアウトが引き起こされる可能性があります。 + +// 例: +// forループで似たコードの繰り返しを解消することが可能 +// このコメントを消すと何故か動かない +for (int i = 0; i < 100; i++) { + printf("%d\n", i); +} +// 解説:shift-jisで「能」は 94 5c で、標準ASCIIでは 5c は"\"でLinux gccでは +// 次の行もコメントアウトされる仕様で、この例ではforループの最初の定義が +// コメントアウトされエラーとなります。 + +/* +複数行コメント、C89標準でも使える。 +*/ + +/* +複数行コメントはネストできないので/*注意*/ // コメントはここで終わり、 +*/ // ここのコメント終了は扱われない。 + +// 定数・マクロ:#define <定数名(英数字のみ)> +// 定数はすべて大文字で定義することをおすすめします。 +#define DAYS_IN_YEAR 365 + +// 列挙体も定数を定義する方法の一つです。 +// すべてのコード行は半角英数字で書き、セミコロン「;」で終わる必要があります。 +enum days {SUN, MON, TUE, WED, THU, FRI, SAT}; +// SUNは0、MONは1、TUEは2、などと続く。 + +// 列挙体の値は別の値にできますが、数字が大きくなるようにする必要があります。 +enum days {SUN = 1, MON, TUE, WED = 99, THU, FRI, SAT}; +// MONは自動的に2、TUEは3、と続き、WEDで99、THUは100、FRIは101、などと続く。 + +// #include でヘッダーファイルをインポートできる。 +#include +#include +#include + +// <アングルブラケット>で囲まれたファイル名はヘッダーファイルをシステムライブラリから +// 探すことをコンパイラに伝え、自分で書いたヘッダーファイルを使うときには ”引用符” で +//そのファイルのパスを囲みます。 +#include "my_header.h" // ローカルファイル +#include "../my_lib/my_lib_header.h" // 相対パス + +// 予め関数を .h (ヘッダー)ファイルで宣言するか、 +// .c (ソースコード)ファイルの上方に書いて宣言してください。 +void function_1(); +int function_2(void); + +// 関数を使用する前に、最低でも、関数プロトタイプを宣言しなければなりません。 +// プロトタイプは関数定義の前に書くのが一般的です。 +int add_two_ints(int x1, int x2); // 関数プロトタイプ +// 上記の書き方でも問題ありませんが(引数の連番)、引数にはコード保守を +// 容易にするためになるべくちゃんとした名前をつけてあげましょう。 + +// 関数プロトタイプはその関数を使う前に定義を書いておけば必要ありません。 +// しかし、関数プロトタイプをヘッダーファイルに記述し、ソースコードの上方に#includeを +// 使ってインポートすれば、コンパイラにまだ定義されていない関数を呼び出すことを防ぎ、 +// ヘッダーファイルにどんな関数が定義されるのかが分かるのでプログラムの保守性も上がります。 + +// プログラムが最初に実行する関数はエントリーポイントといい、Cではmain()関数となります。 +// 返り値はどんな型でも良いですが、Windowsなどの大抵のOSはエラーコードを検知・処理するために +// 関数はint型(整数型)を返すことが定められています。 +int main(void) { + // プログラムはここへ +} + +// コマンドライン引数はプログラムの挙動やオプションを実行時に設定することができます。 +// argcは引数の数を表し、プログラム名もカウントされるので常に1以上の値が入ります。 +// argvは引数文字列の配列を表し、プログラム名含むすべての引数が入るます。 +// argv[0]はプログラム名を、argv[1]は最初の引数などです。 +int main (int argc, char** argv) +{ + // コンソールに文字などを表示するときにはprintf関数を使います。 + // printfは”print format”のことで、書式に沿って値を表示させます。 + // %dには整数が入り、\nは新しい行("n"ew line)へ移動します。 + printf("%d\n", 0); // => 0が表示される + + // scanf関数はコンソールからユーザの入力を受け付けます。 + // 変数の前の'&'記号はメモリ上の変数の住所(address)を求める一種の演算子です。 + // この例では整数型の値をinput変数の住所に値を代入します。 + int input; + scanf("%d", &input); + + /////////////////////////////////////// + // 型 + /////////////////////////////////////// + + // C99標準の互換性がないコンパイラでは、そのスコープで使用するすべての変数は + // スコープの一番上に宣言する必要があります。C99標準互換のコンパイラは、使用する前なら + // スコープ内のどこでも宣言可能です。このチュートリアルでは、C99標準に統一して書いていきます。 + + // int型は大抵の場合整数を4バイトのメモリで格納しますが、古いCPUでは2バイトで格納します。 + // sizeof演算子を使えば、その型が何バイト使うか確認できます。 + int x_int = 0; + + // short型は2バイトで整数を格納。 + short x_short = 0; + + // char型は大抵のプロセッサーでは、最小のサイズで、 + // 1バイトのサイズで整数またはASCII文字一つを格納できます。 + // この型のサイズはプロセッサーによって異なり、2バイト以上の物もあります。 + // (例:TIからリリースされたTMS320は2バイトで格納される。) + char x_char = 0; + char y_char = 'y'; // ASCII文字リテラルは''で囲まれる。 + + // long型は4~8バイトで整数を格納します。long long型は常に8バイトであることが保証されます。 + long x_long = 0; + long long x_long_long = 0; + + // float型は32ビットの単精度浮遊少数を格納します。 + float x_float = 0.0f; // 'f'はその数字リテラルが単精度浮遊少数であることを示します。 + + // double型は64ビットの倍精度浮遊少数を格納します。 + double x_double = 0.0; // 実数のあとに何もつかない数字リテラルは倍精度浮遊少数として扱います。 + + // 整数型はunsignedをつけることで0以上の正の数のみを格納させることができます。 + unsigned short ux_short; + unsigned int ux_int; + unsigned long long ux_long_long; + + // char型に格納されている文字はASCIIなどの文字コードに対応する整数でもあります。 + '0'; // => ASCIIで48を表す。 + 'A'; // => ASCIIで65を表す。 + + // sizeof(T)でその型のサイズをバイトで返す(Tには型名が入る。) + // sizeof(obj)はその値の型のサイズを返す。(objには定数、変数、生の値が入る。) + printf("%zu\n", sizeof(int)); // => 4 (on most machines with 4-byte words) + + // もしsizeof演算子の引数が式だった場合、VLA(可変長配列、Variable Length Array)でない限り、 + // その式は評価されません。この場合の引数の値はコンパイル時定数である。 + int a = 1; + // size_t型は変数などの型サイズを表す2バイト以上の非負の整数を格納します。 + size_t size = sizeof(a++); // a++ は評価されない。 + printf("sizeof(a++) = %zu where a = %d\n", size, a); + // prints "sizeof(a++) = 4 where a = 1" (32ビット環境での場合) + + // 配列は定義時にサイズを決める必要があります。 + char my_char_array[20]; // この配列は 1 * 20 = 20 バイト使います + int my_int_array[20]; // この配列は 4 * 20 = 80 バイト使います + // (4バイト整数環境であると仮定した場合) + + // 次の定義では整数配列を20個の0で埋めた状態で初期値が与えられます。 + int my_array[20] = {0}; + // "{0}"は配列初期化子です。 + // 初期化子に含まれる要素以外の要素は、(もしあれば)すべて0に初期化されます: + int my_array[5] = {1, 2}; + // 上記の定義ではmy_arrayは5つの要素があり、最初の2つ以外は0に初期化されています: + // [1, 2, 0, 0, 0] + // 配列定義のときに明示的に初期化を行えば、要素数を決める必要がなくなります: + int my_array[] = {0}; + // サイズを指定しないで定義すると配列初期化子の要素数がそのまま自動的に決めまれます。 + // よって"{0}"で初期化した場合、配列のサイズは1となり、"[0]"が代入されます。 + // 実行時に配列の要素数を調べるには、配列のサイズを1つの要素のサイズで割れば良いのです。 + size_t my_array_size = sizeof(my_array) / sizeof(my_array[0]); + // 注意;この操作は配列ごとに、かつ関数に渡す前に実行することを勧めします。なぜなら + // 関数に配列を渡すと、ポインター(メモリ上の場所を表す単なる整数)に変換され、 + // 関数内で同じ操作を行うと、間違った結果につながる恐れがあるからです。 + + // 要素へアクセスするときは他の言語と同じようにできます。 + // 正しく言えば、Cに似た言語です。 + my_array[0]; // => 0 + + // 配列は変更可能です。 + my_array[1] = 2; + printf("%d\n", my_array[1]); // => 2 + + // C99標準以降(C11では任意選択)では、可変長配列(VLA)が使用可能で、コンパイル時に + // 定数による要素数指定をしなくても、変数などによる指定ができるようになります。 + printf("Enter the array size: "); // ユーザーに要素数を入力してもらう。 + int array_size; + fscanf(stdin, "%d", &array_size); + int var_length_array[array_size]; // VLAを宣言する。 + printf("sizeof array = %zu\n", sizeof var_length_array); + + // 例: + // > Enter the array size: 10 + // > sizeof array = 40 + + // 文字列はヌル文字(0x00, '\0')で終わる配列でもあります。 + // 文字列リテラルを使用する場合はコンパイラが末尾に塗る文字を追加するので明示的に + // 入れなくても良いです。 + char a_string[20] = "This is a string"; + printf("%s\n", a_string); // %s フォーマットで文字列を表示 + + printf("%d\n", a_string[16]); // => 0 + // 例, 17番目のバイトは0 (18, 19, 20番目も同様) + + // シングルクォーテーションで囲まれた文字は文字リテラルです。これはchar型*ではなく*、 + // int型です。(これには歴史的背景があります。) + int cha = 'a'; // OK + char chb = 'a'; // これもOK (intからcharへの暗黙的型変換) + + // 多次元配列: + int multi_array[2][5] = { + {1, 2, 3, 4, 5}, + {6, 7, 8, 9, 0} + }; + // 要素の取得: + int array_int = multi_array[0][2]; // => 3 + + /////////////////////////////////////// + // 演算子 + /////////////////////////////////////// + + // 複数の同一型変数の略記法: + int i1 = 1, i2 = 2; + float f1 = 1.0, f2 = 2.0; + + int b, c; + b = c = 0; + + // 四則演算は直感的にかけます: + i1 + i2; // => 3 + i2 - i1; // => 1 + i2 * i1; // => 2 + i1 / i2; // => 0 (0.5だが、0に繰り下げられている) + + // 結果を少数にするにはどちらか一方の変数をfloat型へキャスティングする必要がある。 + (float)i1 / i2; // => 0.5f + i1 / (double)i2; // => 0.5 // double型でも同様の操作ができる + f1 / f2; // => 0.5, プラスマイナス計算機イプシロン(その型が表せる最小の少数) + + // 浮動小数点数はIEEE 754の仕様で定義されているので、コンピューターは正確な + // 数をメモリ上で保存できない。よって意図しない数になることがある。例えば、0.1は + // 0.099999999999、0.3は0.300000000001として保存されているかもしれません。 + (0.1 + 0.1 + 0.1) != 0.3; // => 1 (真) + // なのでこれは上記の理由でこの真偽式は真になりません。 + 1 + (1e123 - 1e123) != (1 + 1e123) - 1e123; // => 1 (真) + // こちらは科学的表記法です : 1e123 = 1*10^123 + + // ほとんどのシステムはIEEE 754に基づいて浮動小数点数を定義していることを + // 知っておくことが重要になってきます。科学演算で多用されるPythonでも最終的に + // IEEE 754を使うCを呼び出すことになります。この注意書きはCの浮動小数点数の + // 仕様が悪く使うべきではないということをほのめかすのではなく、こういった誤差 + // (イプシロン)を考慮した上で比較するというのを頭に入れておくために書かれました。 + + // 剰余演算もありますが、負の値を計算するときには注意してください: + 11 % 3; // => 2 (11 = 2 + 3*x (x=3)) + (-11) % 3; // => -2 (-11 = -2 + 3*x (x=-3)) + 11 % (-3); // => 直感に反し被除数と同じ符号になる、2 (11 = 2 + (-3)*x (x=-3)) + + // 比較演算は親しみがあるかもしれませんが、Cには真偽型がなく、 + // 代わりに整数型が使われます。(C99以降は _Bool型がstdbool.hで + // 提供されました。) 0は偽を表し、それ以外はすべて真として扱います。 + // 比較演算を使用する際は必ず0か1を返します。 + 3 == 2; // => 0 (偽) 等しい + 3 != 2; // => 1 (真) 等しくない + 3 > 2; // => 1 より大きい + 3 < 2; // => 0 より小さい + 2 <= 2; // => 1 以下 + 2 >= 2; // => 1 以上 + + // CはPythonではないので、演算子の連鎖はできません。 + // 下記の例では問題なくコンパイルしますが、`0 < a < 2`は`(0 < a) < 2`になり、 + // `(0 < a)`の結果が真でも偽でも結局`0 < 2`または`1 < 2`となるので常に真となります。 + int between_0_and_2 = 0 < a < 2; + // 代わりにこう書きます: + int between_0_and_2 = 0 < a && a < 2; + + // 整数に対する論理演算子: + !3; // => 0 (否定) + !0; // => 1 + 1 && 1; // => 1 (論理積) + 0 && 1; // => 0 + 0 || 1; // => 1 (論理和) + 0 || 0; // => 0 + + // 条件付き三元式 ( ? : ) + int e = 5; + int f = 10; + int z; + z = (e > f) ? e : f; // => 10 "もし(e > f)が真ならばeを、偽ならばfを返す。" + + // 加算・減算演算子: + int j = 0; + int s = j++; // jを返してからjを1増やす (s = 0, j = 1) + s = ++j; // jを1増やしてからjを返す (s = 2, j = 2) + // 減算演算子 j-- と --j でも同様 + + // ビット演算子 + // 整数などのデータは0と1の2進数で表されておりそれぞれをビットといいます。 + // これらの演算子は各ビットに論理演算を適用します。 + ~0x0F; // => 0xFFFFFFF0 (ビット単位NOT、補数、32ビット16進数整数での例) + 0x0F & 0xF0; // => 0x00 (ビット単位AND) + 0x0F | 0xF0; // => 0xFF (ビット単位OR) + 0x04 ^ 0x0F; // => 0x0B (ビット単位XOR) + 0x01 << 1; // => 0x02 (算術左シフト (1ビット幅)) + 0x02 >> 1; // => 0x01 (算術右シフト (1ビット幅)) + + // 正負のついた整数に対するビットシフトには注意してください - これらの操作は未定義です: + // - 符号ビットへのビットシフト (int a = 1 << 31) + // - 負の整数を左シフトする (int a = -1 << 2) + // - 型のビットサイズ以上の幅でシフト: + // int a = 1 << 32; // 32ビット幅の整数の場合では未定義の動作 + + /////////////////////////////////////// + // 制御構造 + /////////////////////////////////////// + + // 条件文 + if (0) { + printf("I am never run\n"); + } else if (0) { + printf("I am also never run\n"); + } else { + printf("I print\n"); + } + + // whileループ文 + int ii = 0; + while (ii < 10) { // 10以下の整数がこの条件を満たす + printf("%d, ", ii++); // ii++ が値を使用してから1加算される。 + } // => "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "が出力される + + printf("\n"); + + // do-whileループ文 + int kk = 0; + do { + printf("%d, ", kk); + } while (++kk < 10); // ++kk が値を使用する*前*に1加算される. + // => "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "が出力される + + printf("\n"); + + // forループ文 + int jj; + for (jj=0; jj < 10; jj++) { + printf("%d, ", jj); + } // => "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "が出力される + + printf("\n"); + + // *****注*****: + // ループ文、関数には最低でも一つの命令・文が必要になります: + int i; + for (i = 0; i <= 5; i++) { + ; // セミコロン単体で何もしないという命令を作れる(ヌル命令) + } + // 別の表記法: + for (i = 0; i <= 5; i++); + + // switch文(if文より高速) + switch (a) { + case 0: // caseレーベルにはint型や列挙型やchar型等の整数で表せるものに限定されます。 + printf("Hey, 'a' equals 0!\n"); + break; // ブレイク文がなければ後続のcaseレーベルも実行されてしまいます。 + case 1: + printf("Huh, 'a' equals 1!\n"); + break; + // break文がそのcaseレーベルになければ、break文があるレーベルまですべて実行されます。 + case 3: + case 4: + printf("Look at that.. 'a' is either 3, or 4\n"); + break; + default: + // 上記の条件がすべて合致しなければdefaultレーベル下の命令が実行されます。 + fputs("Error!\n", stderr); + exit(-1); + break; + } + + // goto文 + typedef enum { false, true } bool; + // C99より前のC標準ではブール値が標準で定義されていません。 + bool disaster = false; + int i, j; + for(i=0; i<100; ++i) + for(j=0; j<100; ++j) + { + if((i + j) >= 150) + disaster = true; + if(disaster) + goto error; // 両方のforループから抜ける + } + error: // goto error;"で"error"レーベルまで「ジャンプ」します。 + printf("Error occurred at i = %d & j = %d.\n", i, j); + /* + この例の出所: https://ideone.com/GuPhd6 + "Error occurred at i = 51 & j = 99."が出力されます。 + */ + /* + ほとんどの場合、goto文を使うのは、そのコードが何をするかわかっていない限り、 + 良くないとされています。詳細は + https://ja.wikipedia.org/wiki/スパゲッティプログラム#goto文の濫用 + を読んでください。 + */ + + /////////////////////////////////////// + // 型キャスティング(型変換) + /////////////////////////////////////// + + // すべての値には型がありますが、これらは、互換性がある別の型にキャスティングすることができます。 + + int x_hex = 0x01; // 16進数リテラルで変数を定義できます。 + // 2進数リテラルにはコンパイラごとに差があります。 + // (GCCではx_bin = 0b0010010110) + + // 型キャスティングを行うとその値を保持しようとします。 + printf("%d\n", x_hex); // => 1 + printf("%d\n", (short) x_hex); // => 1 + printf("%d\n", (char) x_hex); // => 1 + + // キャスティング先の型のサイズより大きい値をキャストすると警告なしに値が丸められます。 + printf("%d\n", (unsigned char) 257); // => 1 (8ビット長のunsigned char型が保持できる最大値は255) + + // char, signed char, unsigned char型の最大値はそれぞれ、で提供される + // CHAR_MAX, SCHAR_MAX, UCHAR_MAXマクロを使用できます。 + + // 整数型と浮動小数点数型は双方向にキャスティング可能です。 + printf("%f\n", (double) 100); // %f はdouble型と + printf("%f\n", (float) 100); // float型をフォーマットします。 + printf("%d\n", (char)100.0); + + /////////////////////////////////////// + // ポインター + /////////////////////////////////////// + + // ポインターはメモリ上のアドレスを保持する整数の変数であり、型と共に宣言・定義されます。 + // 変数から直接アドレスを取得できることができます。 + + int x = 0; + printf("%p\n", (void *)&x); // &を用いて変数のアドレスを取得します。 + // (%p は void *型の値をフォーマットします。) + // => 結果: 変数が保持されているメモリーアドレスが表示される + + // ポインターは型名の直後にまたは変数名の直前に * を書いて宣言・定義します。 + int *px, not_a_pointer; // px はint型の値を指すポインター + px = &x; // pxにxのアドレスを代入する。 + printf("%p\n", (void *)px); // => &xと同様の結果が出力されるはずです。 + printf("%zu, %zu\n", sizeof(px), sizeof(not_a_pointer)); + // => 64ビット環境では"8, 4"が出力されます。 + + // ポインターから指示しているメモリー領域の値を取得(ディレファレンス)するには + // ポインター宣言と同じようにポインター名の前に * を書きます。 + printf("%d\n", *px); // => xの値である0を出力 + + // この機能を用いて、ポインターが指示している値を変更することができます。 + // 加算演算子はディレファレンス演算子より優先順位が高いので数学同様ディレファレンス操作を + // 丸括弧で括ります。 + (*px)++; // pxが指しているxの値を1加算する + printf("%d\n", *px); // => 1 + printf("%d\n", x); // => 1 + + // 配列は連続したメモリー領域を確保するのに有効です。 + int x_array[20]; // 長さ20の不可変長配列を宣言 + int xx; + for (xx = 0; xx < 20; xx++) { + x_array[xx] = 20 - xx; + } // x_arrayの値を 20, 19, 18,... 2, 1 と一括初期化する。 + + // int型の値を指し示すポインターを宣言し、x_arrayのアドレスで初期化する + int* x_ptr = x_array; + // x_ptrは整数20個の配列の最初の要素を指しています。 + // この場合配列は代入時に最初の要素へのポインターへ変換されます。 + // 関数に配列を渡す際にも暗黙的にポインターに変換されます。 + // 例外:`&`を配列に適用した場合、その配列のアドレスが返り、要素の型ではなく、 + // 配列型のポインターが使用されます: + int arr[10]; + int (*ptr_to_arr)[10] = &arr; // &arr は `int *`型ではない! + // これは「(10個の整数の)配列へのポインター」型です。 + // もう一つの例外には文字列リテラルをchar型配列に代入する場合: + char otherarr[] = "foobarbazquirk"; + // または、`sizeof`, `alignof`演算子を使用した場合: + int arraythethird[10]; + int *ptr = arraythethird; // equivalent with int *ptr = &arr[0]; + printf("%zu, %zu\n", sizeof(arraythethird), sizeof(ptr)); + // "40, 4" または "40, 8" が出力されます。 + + // ポインター型の値を加算・減算するとその方に応じて操作できます。 + // この操作のことをポインター演算といいます。 + printf("%d\n", *(x_ptr + 1)); // => 19 + printf("%d\n", x_array[1]); // => 19 + + // 標準ライブラリ関数の一つであるmallocを使えば連続したメモリ領域を動的に確保できます。 + // malloc関数は確保するバイト数を設定するsize_t型の引数が一つあります。 + // (確保するのは大抵の場合ヒープ領域に確保されますが、組み込みデバイスなどでは + // 挙動が異なる場合があります。このことはC標準では説明されていません。) + int *my_ptr = malloc(sizeof(*my_ptr) * 20); + for (xx = 0; xx < 20; xx++) { + *(my_ptr + xx) = 20 - xx; // my_ptr[xx] = 20-xx + } // メモリー領域を整数型配列として初期化する [20, 19, 18 ... 1] + + // mallocで確保されたメモリー領域へのデータの書き込みには注意してください。 + // 安全性を保証するには、確保すると同時にそのメモリー領域をすべて0で埋め尽くすcalloc関数を使用してください。 + int* my_other_ptr = calloc(20, sizeof(int)); + + // Cには動的配列のサイズをその場で求める方法はほとんどなく、関数などに渡すときに要素数を記録する別の変数が + // 必要になることがよくあります。詳細は次の関数についてのセクションを読んでください。 + size_t size = 10; + int *my_arr = calloc(size, sizeof(int)); + // 要素を追加する + size++; + my_arr = realloc(my_arr, sizeof(int) * size); // realloc関数で配列のサイズを更新する。 + if (my_arr == NULL) { + // mallocやreallocなどを使う際には領域確保に異常がない確認するために + // ヌルチェックをすることをおすすめします。 + return + } + my_arr[10] = 5; + + // 確保されていないメモリー領域へアクセスは予測不可能な結果を招く可能性があります。 + printf("%d\n", *(my_ptr + 21)); // => who-knows-what? が出力される**かも**、クラッシュするかもしれない。 + + // メモリー領域の使用を終えたら必ずfree関数を使ってその領域を解放しなければなりません。 + // 解放しなければ、プログラムが終了しても他のプログラムからそのメモリー領域を再利用できず、 + // システム全体で使用できる容量が減ってしまいます。このことをメモリーリークと呼びます。 + free(my_ptr); // my_ptrでポイントされてるメモリー領域を解放する。 + + // 文字列はchar型の配列で表せますが、よく使用されるのは文字列の最初の文字を指すcharポインターです。 + // もし、単に文字列リテラルを使用するだけならば"const char*"を使い、変更不能にしておくことが推奨されています。 + // なぜならば、本来文字列リテラルのデータは変更すべきではないからです。 + // なので、" foo[0] = 'a' "といった操作はできません。 + const char *my_str = "This is my very own string literal"; + printf("%c\n", *my_str); // => 'T' + + // char型の配列で定義されている場合は別で、文字列リテラルで初期化できますが、 + // 各要素は変更可能です。例に: + char foo[] = "foo"; + foo[0] = 'a'; // この操作は許されており、"aoo" に変更される。 + + function_1(); +} // main 関数の終わり + +/////////////////////////////////////// +// 関数 +/////////////////////////////////////// + +// 関数定義の構文: +// <戻り値の型> <関数名>(<引数>) + +int add_two_ints(int x1, int x2) +{ + return x1 + x2; // returnで値を返す。 +} + +/* +関数は値によって呼び出されます。関数が呼ばれると、引数として渡した値はコピーされ、 +関数内で値を変更したとしても、渡した引数の値は変わりません。(配列はこれに従わない。) + +関数内で引数の値を変更したい場合はポインターとして渡す必要があり、配列も渡すときに自動的にポインターになります。 + +例:即興文字列反転 +*/ + +// void型関数は値を返さない +void str_reverse(char *str_in) +{ + char tmp; + size_t ii = 0; + size_t len = strlen(str_in); // `strlen()` はC標準ライブラリ関数です。 + // NOTE: `strlen` で返される文字列の長さは終端文字の + // ヌルバイト('\0')を含んでいない状態です。 + // C99標準以降では、ループ定義の中にループ制御変数が定義できます。 + // 例:`for (size_t ii = 0; ...` + for (ii = 0; ii < len / 2; ii++) { + tmp = str_in[ii]; + str_in[ii] = str_in[len - ii - 1]; // 後ろから ii 番目の要素 を 前から ii 番目の要素にする + str_in[len - ii - 1] = tmp; + } +} +//NOTE: string.h のヘッダーファイルを#includeしないとstrlen()関数が使用できません。 + +/* +char c[] = "This is a test."; +str_reverse(c); +printf("%s\n", c); // => ".tset a si sihT" +*/ +/* +一つの変数を変更することができるように、 +ポインター渡しで複数の変数を変更できます。 +*/ +void swapTwoNumbers(int *a, int *b) +{ + int temp = *a; + *a = *b; + *b = temp; +} +/* +int first = 10; +int second = 20; +printf("first: %d\nsecond: %d\n", first, second); +swapTwoNumbers(&first, &second); +printf("first: %d\nsecond: %d\n", first, second); +// 変数の値が交換される +*/ + +// 一度に複数の値を返す +// Cではreturn文を使って複数の値を返すことができません。一度に複数の値を返すには、 +// 引数にそれぞれの戻り値を格納する変数へのポインターを設定しなければなりません。 +int return_multiple( int *array_of_3, int *ret1, int *ret2, int *ret3) +{ + if(array_of_3 == NULL) + return 0; //エラーコードを返す (偽) + + //値を変更するためにポインターをディレファレンスする。 + *ret1 = array_of_3[0]; + *ret2 = array_of_3[1]; + *ret3 = array_of_3[2]; + + return 1; //エラーコードを返す (真) +} + +/* +引数に配列型を使用するときは、配列は必ずポインターに変換されることに注意してください。これは +malloc関数で動的に確保したものでも、静的に定義した配列でも同じことが起きます。繰り返しになるが、 +Cでは引数として渡された動的配列の長さを標準仕様で知ることができません。 +*/ +// 引数として配列のサイズを渡してください。 +// でなければ、渡された配列の長さを知る術がありません。 +void printIntArray(int *arr, size_t size) { + int i; + for (i = 0; i < size; i++) { + printf("arr[%d] is: %d\n", i, arr[i]); + } +} +/* +int my_arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; +int size = 10; +printIntArray(my_arr, size); +// "arr[0] is: 1" などが出力される。 +*/ + +// 関数外で定義されている変数へアクセスするにはexternキーワードを使用します。 +int i = 0; +void testFunc() { + extern int i; //この変数iは外部変数iとして使用できる +} + +// 外部変数を他のソースファイルから見えないようにする: +static int j = 0; // testFunc2()を使用する他のファイルは変数jに直接アクセスできない。 +void testFunc2() { + extern int j; +} + +// staticキーワードはコンパイルユニット外での変数のアクセスを禁じ、プライベートにします。 +// (大抵のシステムでのコンパイルユニットとは .c ソースコードのことを指す。) +// このstaticキーワードは(コンパイルユニットの)グローバルスコープと関数スコープどちらでも使用できますが、 +// 関数スコープで使用すると挙動が変わり、アクセス制限をするのではなく、変数の寿命がプログラム終了まで延長されます。 +// これはその変数が関数の実行が終了したあともメモリーにとどまり、グローバル変数と同じように +// 値を保持し続けることができるようになります。グローバル変数とは違って、変数は定義された関数のスコープ内のみで使用できます。 +// 更に、staticで宣言された変数は初期値が与えられてなくても必ず0で初期化されます。 +// **関数をstatic宣言することで変数と同じようにプライベートにすることができます。** + +/////////////////////////////////////// +// ユーザー定義の型と構造体 +/////////////////////////////////////// + +// typedefキーワードを使えば型の別名をつけることができます +typedef int my_type; // my_type は int型の別名になった。 +my_type my_type_var = 0; // int my_type_var = 0; と等しい + +// 構造体は複数のデータを一つにまとめたものであり、上から下の順で定義されたメンバーがメモリーに割り当てられる: +struct rectangle { + int width; + int height; +}; + +// この構造体のサイズは必ずしも +// sizeof(struct rectangle) == sizeof(int) + sizeof(int) +// にならない、なぜならコンパイル時にシステムがメモリーを割り当てやすい位置にパッディングするからである。[1] + +void function_1() +{ + struct rectangle my_rec = { 1, 2 }; // メンバーは定義時に初期化できる + + // "." で個別のメンバーへアクセスできる + my_rec.width = 10; + my_rec.height = 20; + + // 構造体へのポインターも定義できる: + struct rectangle *my_rec_ptr = &my_rec; + + // ディレファレンスしてからメンバーの値をセットするのも良いが... + (*my_rec_ptr).width = 30; + + // 可読性を高めるために"->"を使ってポインターから直接メンバーへアクセスすることもできる。 + my_rec_ptr->height = 10; // (*my_rec_ptr).height = 10; と同じ +} + +// 毎回structを打たなくてもいいように構造体に別名をつけることができます +typedef struct rectangle rect; // rect = struct rectangle + +int area(rect r) +{ + return r.width * r.height; +} + +// typedefは構造体定義と同時に使えます: +typedef struct { + int width; + int height; +} rect; // 無名構造体にrectと名付けている。 +// これで +struct rectangle r; +// を打たなくても +rect r; +// と楽に宣言・定義できる + +// サイズが大きい構造体は値渡しの代わりにポインター渡しでコピー作成の時間・メモリー使用量増大を避けることができます: +int areaptr(const rect *r) +{ + return r->width * r->height; +} + +/////////////////////////////////////// +// 関数ポインター +/////////////////////////////////////// +/* +実行時には、関数はプログラムに決められたメモリーアドレスにあります。関数ポインターは他のポインターとほとんど変わりません。 +違うところは、ポインターを使って関数を呼び出せることです。これにより、関数の引数として他の関数をコールバックとしてわすことができます。 +難しいところは、他の変数へのポインターとは表記法が違ってくることです。 + +例:str_reverse関数をポインターとして使う +*/ +void str_reverse_through_pointer(char *str_in) { + // 戻り値がvoid型fの名前がついた関数ポインターを宣言する。 + void (*f)(char *); // 引数も一緒に書きますが、指している関数と同じ戻り値と引数の型でなければなりません(引数名は入れずにただ型を列挙する)。 + f = &str_reverse; // 関数のアドレスを代入する(アドレスは実行時に決定される)。 + // f = str_reverse; これも正しくコンパイルできる - 配列同様ポインターに変換される + (*f)(str_in); // 関数ポインターから実行する + // f(str_in); // この表記法でも正しく実行できる +} + +/* +同じ戻り値型と引数である限り、どの関数でも使えます。 +可読性と単純性を実現するために、typedefが使われます。 +*/ + +typedef void (*my_fnp_type)(char *); + +// 下記で直背ポインター変数を宣言できます: +// ... +// my_fnp_type f; + + +///////////////////////////////////// +// printf()を用いて文字などを出力する +///////////////////////////////////// + +//特殊文字: +/* +'\a'; // 警告 (ベル) 文字 +'\n'; // 改行文字 +'\t'; // タブ文字 (左揃えテキスト) +'\v'; // 垂直タブ文字 +'\f'; // (フォームフィードの)新規ページ +'\r'; // 復帰文字 +'\b'; // バックスペース文字 +'\0'; // ヌル文字 - Cでは文字列終端文字として使用される。 +// hello\n\0. \0が明示的に文字列の終わりを表している。 +'\\'; // バックスラッシュ +'\?'; // 疑問符 +'\''; // シングルクォーテーションマーク +'\"'; // ダブルクォーテーションマーク +'\xhh'; // 文字コード(16進数) 例: '\xb' = 垂直タブ文字 +'\0oo'; // 文字コード(8進数) 例: '\013' = 垂直タブ文字 + +// printf等で使われるフォーマティング: +"%d"; // 整数 +"%3d"; // 整数最低3桁表示 (右揃え) +"%s"; // 文字列 +"%f"; // 浮動小数点 +"%ld"; // 長整数 +"%3.2f"; // 小数点以下2桁、小数点以上最低3桁で表示される浮動小数点 +"%7.4s"; // (文字列としての浮動小数点でも同じことができる) +"%c"; // 文字(単一) +"%p"; // ポインター 注:ポインターを渡すときには (void*) 型へ + // 変換しなければならない。 +"%x"; // 整数16進数表示 +"%o"; // 整数8進数表示 +"%%"; // "%" を挿入する +*/ + +/////////////////////////////////////// +// 評価順序 +/////////////////////////////////////// + +// 順位は上から下へ、一番上は優先順位が最も高い +//------------------------------------------------------// +// 演算子 | 優先順位 // +//------------------------------------------------------// +// () [] -> . | 左から右 // +// ! ~ ++ -- + = *(型) sizeof | 右から左 // +// * % | 左から右 // +// + - | 左から右 // +// << >> | 左から右 // +// < <= > >= | 左から右 // +// == != | 左から右 // +// & | 左から右 // +// ^ | 左から右 // +// | | 左から右 // +// && | 左から右 // +// || | 左から右 // +// ? : | 右から左 // +// = += -= *= /= %= &= ^= |= <<= >>= | 右から左 // +// , | 左から右 // +//------------------------------------------------------// + +/******************************* ヘッダーファイル ********************************** + +ヘッダーファイルはC言語の重要な役割で、ソースファイル間の依存関係の管理を +容易にすることや関数などの宣言を他のファイルに分けることができます。 + +ヘッダーファイル内は通常のC言語と変わりませんが、ファイル拡張子が ".h" になっており、 +同じディレクトリー(フォルダー)に存在するなら` #include "ファイル名.h" `で +ヘッダーファイルで宣言した関数、定数などをソースファイルで使用できます。 +*/ + +/* +セーフガードは#includeマクロを使用する際に、複数回宣言されるのを防ぎます。 +特に互いを参照しあってしまう相互依存の場合に有効です。 +*/ +#ifndef EXAMPLE_H /* もし EXAMPLE_H が定義されていないならば、*/ +#define EXAMPLE_H /* マクロ EXAMPLE_H を定義する。*/ + +// ヘッダーファイル内で他のヘッダーファイルを #include することができます。 +#include + +/* 通常と同じように、マクロを用いて定数を定義できます。これは +ヘッダーファイルとそれを#includeしたソースファイルで使用できます。 */ +#define EXAMPLE_NAME "Dennis Ritchie" + +// 関数マクロも定義できます +#define ADD(a, b) ((a) + (b)) + +/* +引数である変数の周りに丸括弧がありますが、これはマクロの展開時に評価順序が +意図しないものにならないようにするためです。(例:関数 MUL(x, y) (x * y); +があるとします。MUL(1 + 2, 3) は(1 + 2 * 3)と展開され、間違った答えが帰ってきます。) +*/ +// struct, typedefも同じように定義できます。 +typedef struct Node +{ + int val; + struct Node *next; +} Node; + +// 列挙体も同じく、 +enum traffic_light_state {GREEN, YELLOW, RED}; + +/* +関数プロトタイプもヘッダーファイルで宣言できます。ヘッダーファイルで定義を +書くのはよろしくないとされており、定義はソースファイルで記述することを +強く勧めます。 +*/ +Node createLinkedList(int *vals, int len); + +/* +これ以外の要素はソースファイルに残します。過剰な#includeや定義は1つの +ヘッダーファイルには入れず、別の複数のヘッダーファイルかソースファイルに +分けてください。 +*/ + +#endif // if系列マクロの終わり +``` + +## 関連記事、教材(一部英語) + +[CS50 日本語版](https://cs50.jp/) はハーバード大学が無料で公開しているコンピューターサイエンスコースで +字幕付きの動画と一緒にC, Python, SQL, HTML, CSS, Javascriptなどの言語を使った素晴らしいコースです。 +C言語を学ぶ者は第1-5週目を受けることをおすすめします。 + +[Learn C The Hard Way](http://learncodethehardway.org/c/) は有料だが、良い英語での教材です。 + +質問があるならば、[compl.lang.c Frequently Asked Questions](http://c-faq.com) を見るのが良い。 + +インデンテーションや空白の使い方はどこでも一定であることが望まれています。たとえそのコードが画期的で実行速度が速くとも、 +可読性が確保できなければ保守性に欠けます。良いコーディングスタイルの一つには[Linuxカーネル](https://www.kernel.org/doc/Documentation/process/coding-style.rst)のものがあります。 + +それでも分からんことがあったら、GPTにかける前にググってこい。 +Googleは友達だからな。 + +[1] [【C言語】構造体を作る上でのアライメントのお話。そもそもアライメントとは...](https://creepfablic.site/2019/09/16/clangu-alignment-padding/) From aed24ef78860c9ff4592dfbb2c4fcc4fdf630f1f Mon Sep 17 00:00:00 2001 From: Alexander Brevig Date: Wed, 3 Jul 2024 09:50:54 +0200 Subject: [PATCH 285/392] chore(typo): duplicate are in abbreviation section (#4991) --- latex.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/latex.html.markdown b/latex.html.markdown index 9edc057e..28dfec67 100644 --- a/latex.html.markdown +++ b/latex.html.markdown @@ -97,7 +97,7 @@ Separate paragraphs by empty lines. You need to add a tilde after abbreviations (if not followed by a comma) for a non-breaking space, because otherwise the spacing after the dot is too large: -E.g., i.e., etc.~are are such abbreviations. +E.g., i.e., etc.~are such abbreviations. \section{Lists} Lists are one of the easiest things to create in \LaTeX! I need to go shopping From 4825b6039d379668ce3e6595ea79dcb94b1fb4e5 Mon Sep 17 00:00:00 2001 From: tomaszn Date: Thu, 4 Jul 2024 21:29:51 +0200 Subject: [PATCH 286/392] [python/en] Correct floor division examples (#4993) --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python.html.markdown b/python.html.markdown index a045e784..4f1c1cdb 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -39,7 +39,7 @@ syntactic clarity. It's basically executable pseudocode. 10 * 2 # => 20 35 / 5 # => 7.0 -# Integer division rounds towards zero for both positive and negative numbers. +# Floor division rounds towards negative infinity 5 // 3 # => 1 -5 // 3 # => -2 5.0 // 3.0 # => 1.0 # works on floats too From 93c0c95789e9f23171f42f650ca2a55ba3136d48 Mon Sep 17 00:00:00 2001 From: Sugarbell <67601252+TaprisSugarbell@users.noreply.github.com> Date: Fri, 5 Jul 2024 00:52:36 -0600 Subject: [PATCH 287/392] remove unnecessary parentheses (#4994) --- es-es/python-es.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/es-es/python-es.html.markdown b/es-es/python-es.html.markdown index cc53f944..f9786b39 100644 --- a/es-es/python-es.html.markdown +++ b/es-es/python-es.html.markdown @@ -551,7 +551,7 @@ def decir(decir_por_favor=False): print(decir()) # ¿Puedes comprarme una cerveza? -print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :() +print(decir(decir_por_favor=True)) # ¿Puedes comprarme una cerveza? ¡Por favor! Soy pobre :( ``` ## ¿Listo para más? From 6414d9d76738133a3f0aa1403aefdd0fe6383a90 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Fri, 5 Jul 2024 10:53:33 -0600 Subject: [PATCH 288/392] [markdown/zh-cn] Fix missing newline --- zh-cn/markdown-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index c4635e84..7b68c9b8 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -380,4 +380,4 @@ Markdown同样支持引用形式的链接 如果您想了解更多主流 Markdown 方言样式的特性,请参阅: - [GitHub Flavored Markdown](https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax) -- [GitLab Flavored Markdown](https://docs.gitlab.com/ee/user/markdown.html) \ No newline at end of file +- [GitLab Flavored Markdown](https://docs.gitlab.com/ee/user/markdown.html) From c21f0c4a2410894dc67350f1e1e94126d62185bc Mon Sep 17 00:00:00 2001 From: Coldle Date: Sat, 6 Jul 2024 18:55:17 +0800 Subject: [PATCH 289/392] [markdown/it-it,vi-vn,zh-cn,ko-kr,ru-ru] Fixed displaying of three backticks (#4986) --- it-it/markdown.html.markdown | 2 +- ko-kr/markdown-kr.html.markdown | 2 +- ru-ru/markdown-ru.html.markdown | 2 +- vi-vn/markdown-vi.html.markdown | 4 +--- zh-cn/markdown-cn.html.markdown | 2 +- 5 files changed, 5 insertions(+), 7 deletions(-) diff --git a/it-it/markdown.html.markdown b/it-it/markdown.html.markdown index d200827f..a622a830 100644 --- a/it-it/markdown.html.markdown +++ b/it-it/markdown.html.markdown @@ -195,7 +195,7 @@ end ``` ```` -Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre GitHub userà l'evidenziazione della sintassi del linguaggio specificato dopo i \`\`\` iniziali +Se usate questa sintassi, il testo non richiederà di essere indentato, inoltre GitHub userà l'evidenziazione della sintassi del linguaggio specificato dopo i ``` iniziali ## Linea orizzontale Le linee orizzontali (`
      `) sono inserite facilmente usanto tre o più asterischi o trattini, con o senza spazi. diff --git a/ko-kr/markdown-kr.html.markdown b/ko-kr/markdown-kr.html.markdown index a74b78f4..f1edd661 100644 --- a/ko-kr/markdown-kr.html.markdown +++ b/ko-kr/markdown-kr.html.markdown @@ -198,7 +198,7 @@ end ``` ```` -위의 경우에 들여쓰기가 필요없을 뿐 아니라 \`\`\` 뒤에 특정해 준 언어의 문법에 따라 +위의 경우에 들여쓰기가 필요없을 뿐 아니라 ``` 뒤에 특정해 준 언어의 문법에 따라 색을 입혀줄 것입니다. ## 수평선 diff --git a/ru-ru/markdown-ru.html.markdown b/ru-ru/markdown-ru.html.markdown index 7e5adba2..3b1293f9 100644 --- a/ru-ru/markdown-ru.html.markdown +++ b/ru-ru/markdown-ru.html.markdown @@ -226,7 +226,7 @@ end ```` Во фрагменте, приведённом выше, отступ не требуется. -Кроме того, GitHub подсветит синтаксис языка, указанного после \`\`\` +Кроме того, GitHub подсветит синтаксис языка, указанного после ``` ## Горизонтальный разделитель diff --git a/vi-vn/markdown-vi.html.markdown b/vi-vn/markdown-vi.html.markdown index 0e12e5fe..20c8c6c9 100644 --- a/vi-vn/markdown-vi.html.markdown +++ b/vi-vn/markdown-vi.html.markdown @@ -201,9 +201,7 @@ end ``` ```` -The above text doesn't require indenting, plus GitHub will use syntax -highlighting of the language you specify after the \`\`\` -Đoạn trên không cần sử dụng thụt đầu dòng, và GitHub sẽ tô sáng cú pháp sử dụng ngôn ngữ mà ta cung cấp sau đoạn kí tự \`\`\` +Đoạn trên không cần sử dụng thụt đầu dòng, và GitHub sẽ tô sáng cú pháp sử dụng ngôn ngữ mà ta cung cấp sau đoạn kí tự ``` ## Kẻ ngang diff --git a/zh-cn/markdown-cn.html.markdown b/zh-cn/markdown-cn.html.markdown index 7b68c9b8..169e6c1a 100644 --- a/zh-cn/markdown-cn.html.markdown +++ b/zh-cn/markdown-cn.html.markdown @@ -218,7 +218,7 @@ end ``` ```` -以上代码不需要缩进,而且 GitHub 会根据\`\`\`后指定的语言来进行语法高亮显示 +以上代码不需要缩进,而且 GitHub 会根据```后指定的语言来进行语法高亮显示 ## 水平线分隔 From da7872160f827066667d8f010b3988ad0377f65a Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Jul 2024 05:04:23 -0600 Subject: [PATCH 290/392] [clojure macros/pt-br] fix URL and generated filename --- pt-br/clojure-macros-pt.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pt-br/clojure-macros-pt.html.markdown b/pt-br/clojure-macros-pt.html.markdown index 1db3fdea..ca01eb92 100644 --- a/pt-br/clojure-macros-pt.html.markdown +++ b/pt-br/clojure-macros-pt.html.markdown @@ -1,6 +1,6 @@ --- -language: clojure -filename: learnclojure-pt.clj +language: "clojure macros" +filename: learnclojuremacros-pt.clj contributors: - ["Adam Bard", "http://adambard.com/"] translators: From 3c01f30087372cf3093f561db52264f7ef7095e6 Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 6 Jul 2024 05:12:47 -0600 Subject: [PATCH 291/392] [*/th-th] fix filenames --- ....html.markdown => pascal-th.html.markdown} | 30 +++++++++---------- ...l.markdown => typescript-th.html.markdown} | 0 2 files changed, 15 insertions(+), 15 deletions(-) rename th-th/{pascal.th.html.markdown => pascal-th.html.markdown} (97%) rename th-th/{typescript.th.html.markdown => typescript-th.html.markdown} (100%) diff --git a/th-th/pascal.th.html.markdown b/th-th/pascal-th.html.markdown similarity index 97% rename from th-th/pascal.th.html.markdown rename to th-th/pascal-th.html.markdown index e4e06102..5c2284b6 100644 --- a/th-th/pascal.th.html.markdown +++ b/th-th/pascal-th.html.markdown @@ -1,6 +1,6 @@ --- language: Pascal -filename: learnpascal.pas +filename: learnpascal-th.pas contributors: - ["Ganesha Danu", "http://github.com/blinfoldking"] - ["Keith Miyake", "https://github.com/kaymmm"] @@ -34,11 +34,11 @@ const type { ประกาศชนิดข้อมูลของเราเองที่นี่ ไม่ว่าจะเป็น ชนิดข้อมูลทั่วไป - หรือจะเป็นคลาส + หรือจะเป็นคลาส } var { - ตัวแปร ในภาษาปาสกาล ไม่เหมือนกับภาษาอื่น ๆ + ตัวแปร ในภาษาปาสกาล ไม่เหมือนกับภาษาอื่น ๆ เพราะต้องประกาศในบล็อค var ก่อนใช้งานเสมอ } @@ -59,7 +59,7 @@ var a:integer; var b:integer; //หรือแบบที่นิยมมากกว่า คือเอามาเก็บในบล็อค var ทั้งหมด -var +var a : integer; b : integer; @@ -85,7 +85,7 @@ type ch_array : array [0..255] of char; // อะเรย์ เป็นชนิดข้อมูลที่มี ความยาว/ช่องเก็บข้อมูล และ ชนิดข้อมูล // โค้ดด้านบน เป็นการประกาศอะเรย์ของตัวอักษา 255 ตัวอักษา - // ซึ่งได้ ความยาว/ช่องเก็บข้อมูลในตัวแปรตัวนี้ 256 ช่องที่เป็นข้อความ + // ซึ่งได้ ความยาว/ช่องเก็บข้อมูลในตัวแปรตัวนี้ 256 ช่องที่เป็นข้อความ md_array : array of array of integer; // ด้านบนนี้ เป็นตัวอย่าง อะเรย์สองมิติของเลขจำนวนเต็ม // อะเรย์ ยังซ้อนกับอะเรย์ได้อีกด้วย ทำให้สร้าง อะเรย์หลายมิติได้ @@ -95,22 +95,22 @@ type // การประกาศตัวแปร : ชื่อตัวแปรเหล่านี้จะนำไปใช้ด้านล่างต่อไป var int, c, d : integer; - // ประกาศในบล็อค var มีตัวแปรสามตัวเป็นอินทีเจอร์ + // ประกาศในบล็อค var มีตัวแปรสามตัวเป็นอินทีเจอร์ // ชนิดจำนวนเต็ม แบบ 16 bit มีช่วงข้อมูล [-32,768.. 32,767] // »int« ในที่นี้เป็น "ชื่อตัวแปร" ที่ต้นฉบับตั้งให้สอดคล้องกับชนิดข้อมูล // อย่าสับสนกับบางภาษาที่มีชนิด int ประกาศหน้าชื่อตัวแปร r : real; - // ตัวแปร r เป็นชนิดเรียล (real) หรือเลขทศนิยม + // ตัวแปร r เป็นชนิดเรียล (real) หรือเลขทศนิยม // real มีช่วงข้อมูล [3.4E-38..3.4E38] bool : boolean; // ข้อมูลชนิดบูเลียน (boolean) มีค่าได้สองแบบ คือ True/False ch : char; // ตัวแปร ch เป็นชนิดตัวอักษร (ชาร์? คาร์?) หรือคาแรกเตอร์ - // ตัวอักษรเป็นแบบ ASCII 8 bit ดังนั้นจะไม่ใช่ UTF, Unicode + // ตัวอักษรเป็นแบบ ASCII 8 bit ดังนั้นจะไม่ใช่ UTF, Unicode str : string; // ตัวแปรสตริงจะเก็บข้อความ หรือ char หลาย ๆ ตัว // ชนิดข้อมูลนี้ไม่เป็นมาตรฐานภาษาแต่คอมไพเลอร์ปาสกาลก็มักจะมีให้ - // ทั่ว ๆ ไปแล้ว จะเป็นอะเรย์ของ char ความยาวตั้งต้น 255 + // ทั่ว ๆ ไปแล้ว จะเป็นอะเรย์ของ char ความยาวตั้งต้น 255 s : string[50]; // แบบนี้คือ กำหนดความยาว string เอง ให้เก็บ char 50 ตัว // แบบนี้ก็ทำให้ประหยัดหน่วยความจำมากขึ้นนั่นเอง @@ -129,12 +129,12 @@ var li : longint; // มีช่วงข้อมูล [-2,147,483,648..2,147,483,647] lw : longword; // มีช่วงข้อมูล [0..4,294,967,295] c : cardinal; // ก็คือ longword - i64 : int64; // มีช่วงข้อมูล + i64 : int64; // มีช่วงข้อมูล // [-9223372036854775808..9223372036854775807] qw : qword; // มีช่วงข้อมูล [0..18,446,744,073,709,551,615] // ชนิดข้อมูลแบบ real เพิ่มเติม - rr : real; // มีช่วงข้อมูลที่ขึ้นกับระบบปฏิบัติการ + rr : real; // มีช่วงข้อมูลที่ขึ้นกับระบบปฏิบัติการ // (เช่นเป็นแบบ 8-bit, 16-bit, ฯลฯ) rs : single; // มีช่วงข้อมูล [1.5E-45..3.4E38] rd : double; // มีช่วงข้อมูล [5.0E-324 .. 1.7E308] @@ -146,7 +146,7 @@ Begin int := 1; r := 3.14; ch := 'a'; // ใช้ single quote เหมือนกันทั้ง char และ string - str := 'apple'; + str := 'apple'; bool := true; // ภาษาปาสกาล มอง "ชื่อเฉพาะ" แบบไม่สนพิมพ์ใหญ่พิมพ์เล็ก // (case-insensitive language) @@ -166,7 +166,7 @@ Begin // แต่ทำกลับกัน โดยกำหนด real ให้ integer ไม่ได้ c := str[1]; // กำหนดค่าแรกใน array str ให้ตัวแปร c ที่เป็น char - str := 'hello' + 'world'; // เรารวม string เข้าด้วยกันด้วย + + str := 'hello' + 'world'; // เรารวม string เข้าด้วยกันด้วย + my_str[0] := 'a'; // กำหนดค่าให้ string เฉพาะตำแหน่งแบบอะเรย์ทั่วไป @@ -219,12 +219,12 @@ End; //--------------------// // main program block //--------------------// -Begin +Begin dummy := 3; get_integer(i, dummy); writeln(i, '! = ', factorial_recursion(i)); // พิมพ์ค่า i! - writeln('dummy = ', dummy); // จะให้ค่าเป็น '3' เสมอ + writeln('dummy = ', dummy); // จะให้ค่าเป็น '3' เสมอ // เพราะจะไม่เปลี่ยนเนื่องด้วย // การประกาศพารามิเตอร์ใน // โพรซีเยอร์ get_integer ด้านบน diff --git a/th-th/typescript.th.html.markdown b/th-th/typescript-th.html.markdown similarity index 100% rename from th-th/typescript.th.html.markdown rename to th-th/typescript-th.html.markdown From cc9f50c3d8fa5d0995f607fe48d98c1cfb91fcb9 Mon Sep 17 00:00:00 2001 From: lucii7vel <33035261+lucii7vel@users.noreply.github.com> Date: Sat, 6 Jul 2024 07:21:28 -0400 Subject: [PATCH 292/392] [python/be] update floor division (#4996) --- be-by/python-by.html.markdown | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/be-by/python-by.html.markdown b/be-by/python-by.html.markdown index c5476a08..15460aa7 100644 --- a/be-by/python-by.html.markdown +++ b/be-by/python-by.html.markdown @@ -41,8 +41,7 @@ Python быў створаны Гвіда ван Росумам у пачатк 10 * 2 # => 20 35 / 5 # => 7.0 -# Вынік цэлалікавага дзялення акругляецца як для пазітыўных, -# так і для негатыўных значэнняў. +# Вынік цэлалікавага дзялення акругляецца ў напрамку мінус бесканечнасці 5 // 3 # => 1 -5 // 3 # => -2 From 08b303dab76f725f671ca3149f697961e0006d30 Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 18 Jul 2024 11:45:11 +0200 Subject: [PATCH 293/392] Update haskell.html.markdown #5000 --- haskell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/haskell.html.markdown b/haskell.html.markdown index 0c8055d1..1e1eb65a 100644 --- a/haskell.html.markdown +++ b/haskell.html.markdown @@ -444,7 +444,7 @@ canProceedThrough t = t /= Red -- rather than types, assuming that the function only relies on -- features of the typeclass -isEqual (Eq a) => a -> a -> Bool +isEqual :: (Eq a) => a -> a -> Bool isEqual x y = x == y -- Note that x and y MUST be the same type, as they are both defined From be1e100e38945418dfa1656741bccf9dc7674de9 Mon Sep 17 00:00:00 2001 From: zabackary <137591653+zabackary@users.noreply.github.com> Date: Mon, 22 Jul 2024 04:14:17 +0900 Subject: [PATCH 294/392] [rust/en] fix a typo and make some explanations clearer (#4998) --- rust.html.markdown | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/rust.html.markdown b/rust.html.markdown index 11483eef..61754378 100644 --- a/rust.html.markdown +++ b/rust.html.markdown @@ -92,14 +92,14 @@ fn main() { println!("{} {}", f, x); // 1.3 hello world // A `String` – a heap-allocated string - // Stored as a `Vec` and always hold a valid UTF-8 sequence, + // Stored as a `Vec` and always holds a valid UTF-8 sequence, // which is not null terminated. let s: String = "hello world".to_string(); // A string slice – an immutable view into another string - // This is basically an immutable pair of pointers to a string – it doesn’t - // actually contain the contents of a string, just a pointer to - // the beginning and a pointer to the end of a string buffer, + // This is basically an immutable pointer and length of a string – it + // doesn’t actually contain the contents of a string, just a pointer to + // the beginning and a length of a string buffer, // statically allocated or contained in another object (in this case, `s`). // The string slice is like a view `&[u8]` into `Vec`. let s_slice: &str = &s; @@ -162,6 +162,8 @@ fn main() { let up = Direction::Up; // Enum with fields + // If you want to make something optional, the standard + // library has `Option` enum OptionalI32 { AnI32(i32), Nothing, @@ -175,6 +177,8 @@ fn main() { struct Foo { bar: T } // This is defined in the standard library as `Option` + // `Option` is used in place of where a null pointer + // would normally be used. enum Optional { SomeVal(T), NoVal, @@ -304,7 +308,7 @@ fn main() { ///////////////////////////////// // Owned pointer – only one thing can ‘own’ this pointer at a time - // This means that when the `Box` leaves its scope, it can be automatically deallocated safely. + // This means that when the `Box` leaves its scope, it will be automatically deallocated safely. let mut mine: Box = Box::new(3); *mine = 5; // dereference // Here, `now_its_mine` takes ownership of `mine`. In other words, `mine` is moved. From ad6e1f09bcb1aae8272bc296742c63d40eb9ff64 Mon Sep 17 00:00:00 2001 From: Risun <79560036+Risuntsy@users.noreply.github.com> Date: Tue, 23 Jul 2024 15:55:15 +0800 Subject: [PATCH 295/392] [kotlin/en] lambda functions wrong defined (#5007) lambda functions can not defined by `fun` directly, use `val` (or `var` if mutability is required) instead --- kotlin.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kotlin.html.markdown b/kotlin.html.markdown index c16b5db1..45decb1e 100644 --- a/kotlin.html.markdown +++ b/kotlin.html.markdown @@ -124,7 +124,7 @@ fun helloWorld(val name : String) { You can also use lambda functions, with the '->' operator seperating the parameters from the function body. */ - fun fooLambda: (Int) -> Int = {n -> n + 1} + val fooLambda: (Int) -> Int = {n -> n + 1} println(fooLambda(1)) // => 2 // Functions can take functions as arguments and return functions. From 6a7cfde3f73347a81f7375e7612a62fbe2d7a66f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20M=C3=BCller?= Date: Wed, 7 Aug 2024 18:30:31 +0200 Subject: [PATCH 296/392] Update yaml.html.markdown (#5017) Two value description texts contain the wrong key name. This commit corrects both key names in the description texts. --- yaml.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/yaml.html.markdown b/yaml.html.markdown index 6e2545c4..ad3e2310 100644 --- a/yaml.html.markdown +++ b/yaml.html.markdown @@ -84,20 +84,20 @@ folded_style: > # |- and >- removes the trailing blank lines (also called literal/block "strip") literal_strip: |- - This entire block of text will be the value of the 'literal_block' key, + This entire block of text will be the value of the 'literal_strip' key, with trailing blank line being stripped. block_strip: >- - This entire block of text will be the value of 'folded_style', but this + This entire block of text will be the value of 'block_strip', but this time, all newlines will be replaced with a single space and trailing blank line being stripped. # |+ and >+ keeps trailing blank lines (also called literal/block "keep") literal_keep: |+ - This entire block of text will be the value of the 'literal_block' key, + This entire block of text will be the value of the 'literal_keep' key, with trailing blank line being kept. block_keep: >+ - This entire block of text will be the value of 'folded_style', but this + This entire block of text will be the value of 'block_keep', but this time, all newlines will be replaced with a single space and trailing blank line being kept. From 8dd93f14df51828033fae627d7b49a26f84d150a Mon Sep 17 00:00:00 2001 From: homersimpsons Date: Tue, 13 Aug 2024 00:51:55 +0200 Subject: [PATCH 297/392] :memo: Add "+" output (#5020) --- phix.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/phix.html.markdown b/phix.html.markdown index 2a199edd..08919a62 100644 --- a/phix.html.markdown +++ b/phix.html.markdown @@ -137,8 +137,8 @@ filename: learnphix.exw // Operators are always consistant; never overloaded. -- the + operator ''always adds'' - ? 2+7 - ? 'A' + 32 + ? 2+7 --> 9 + ? 'A' + 32 --> 97 -- the & operator ''always concatenates'' ? 2 & 7 --> {2,7} From 9228a93217ec3f5309231a964f5aa65bd4be14e4 Mon Sep 17 00:00:00 2001 From: Adrian Sieber <36796532+ad-si@users.noreply.github.com> Date: Tue, 13 Aug 2024 15:21:56 +0000 Subject: [PATCH 298/392] [wolfram/en] Fix formatting of list (#5021) --- wolfram.html.markdown | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/wolfram.html.markdown b/wolfram.html.markdown index fa8ee078..c35f9218 100644 --- a/wolfram.html.markdown +++ b/wolfram.html.markdown @@ -5,14 +5,21 @@ contributors: filename: learnwolfram.nb --- -The Wolfram Language is the underlying language originally used in Mathematica, but now available for use in multiple contexts. +The Wolfram Language is the underlying language originally used in Mathematica, +but now available for use in multiple contexts. Wolfram Language has several interfaces: -* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) which runs interactively and can't produce graphical input. -* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: pressing shift+Return on a "code cell" creates an output cell with the result, which is not dynamic -* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend -The code in this example can be typed in to any interface and edited with Wolfram Workbench. Loading directly into Mathematica may be awkward because the file contains no cell formatting information (which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. +* The command line kernel interface on Raspberry Pi (just called _The Wolfram Language_) + which runs interactively and can't produce graphical input. +* _Mathematica_ which is a rich text/maths editor with interactive Wolfram built in: + Pressing shift + Return on a "code cell" + creates an output cell with the result, which is not dynamic. +* _Wolfram Workbench_ which is Eclipse interfaced to the Wolfram Language backend. + +The code in this example can be typed in to any interface and edited with Wolfram Workbench. +Loading directly into Mathematica may be awkward because the file contains no cell formatting information +(which would make the file a huge mess to read as text) - it can be viewed/edited but may require some setting up. ```mathematica (* This is a comment *) From 6acd121c960ab97a27299b52f87f7b552649298b Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Tue, 13 Aug 2024 23:11:59 -0700 Subject: [PATCH 299/392] [ruby-ecosystem] fix Ruby Spec link --- de-de/ruby-ecosystem-de.html.markdown | 6 +++--- es-es/ruby-ecosystem-es.html.markdown | 6 +++--- fr-fr/ruby-ecosystem-fr.html.markdown | 6 +++--- it-it/ruby-ecosystem-it.html.markdown | 6 +++--- pt-br/ruby-ecosystem-pt.html.markdown | 6 +++--- ruby-ecosystem.html.markdown | 6 +++--- vi-vn/ruby-ecosystem-vi.html.markdown | 6 +++--- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown index a7e1f75f..64d0dfac 100644 --- a/de-de/ruby-ecosystem-de.html.markdown +++ b/de-de/ruby-ecosystem-de.html.markdown @@ -72,7 +72,7 @@ Am ausgereiftesten und stabilsten: * [MRI](https://github.com/ruby/ruby) - Geschrieben in C, das ist die Referenz Implementierung. Sie ist 100% kompatibel (mit sich selbst ;-). Alle anderen rubies - bleiben kompatibel mit MRI (siehe [RubySpec](#rubyspec) weiter unten). + bleiben kompatibel mit MRI (siehe [Ruby Spec](#ruby-spec) weiter unten). * [JRuby](http://jruby.org/) - Geschrieben in Java and Ruby, Robust und ziemlich schnell. Der größte Vorteil von JRuby ist die Interoperabilität mit JVM/Java und damit die Benutzung von Ruby im Java Ecosystem. @@ -98,9 +98,9 @@ Die Ruby Implementierungen haben ihre eigenen Versionsnummern, sind aber trotzdem immer zu einer MRI Version kompatibel. Viele können sogar zwischen verschiedenen Modi wechseln (1.8 mode -> 1.9 mode) -## RubySpec +## Ruby Spec -Die meisten Ruby Implementierungen vertrauen der [RubySpec](http://rubyspec.org/). +Die meisten Ruby Implementierungen vertrauen der [Ruby Spec](https://github.com/ruby/spec). sehr stark. Da Ruby keine offizielle Spezifikation hat, hat die Community ausführbare Specs (in Ruby) geschrieben, um so die Kompatibilität zur MRI testen zu können. diff --git a/es-es/ruby-ecosystem-es.html.markdown b/es-es/ruby-ecosystem-es.html.markdown index 9ce62ef5..44f25fd9 100644 --- a/es-es/ruby-ecosystem-es.html.markdown +++ b/es-es/ruby-ecosystem-es.html.markdown @@ -74,7 +74,7 @@ Muy maduras/compatibles: * [MRI](https://github.com/ruby/ruby) - Escrita en C, es la implementación de referencia de Ruby. Por definición es 100% compatible (consigo misma). Las otras implementaciones de Ruby mantienen compatibilidad con MRI (ver - [RubySpec](#rubyspec) más abajo). + [Ruby Spec](#ruby-spec) más abajo). * [JRuby](http://jruby.org/) - Escrita en Java y Ruby, esta implementación es robusta y bastante veloz. Más importante, la fortaleza de JRuby reside en la interoperabilidad con JVM/Java, pudiendo utilizar herramientas, proyectos y @@ -106,10 +106,10 @@ compatibilidad. Muchas implementaciones tienen la habilidad de trabajar en diferentes modos (por ejemplo, modo 1.8 o 1.9) para especificar a qué versión de MRI están apuntando. -## RubySpec +## Ruby Spec Muchas implementaciones de Ruby dependen en gran medida de -[RubySpec](http://rubyspec.org/). Ruby no tiene una especificación oficial, por +[Ruby Spec](https://github.com/ruby/spec). Ruby no tiene una especificación oficial, por lo que la comunidad ha escrito especificaciones ejecutables en Ruby para poder testear la compatibilidad de sus implementaciones con MRI. diff --git a/fr-fr/ruby-ecosystem-fr.html.markdown b/fr-fr/ruby-ecosystem-fr.html.markdown index edc69068..1066022f 100644 --- a/fr-fr/ruby-ecosystem-fr.html.markdown +++ b/fr-fr/ruby-ecosystem-fr.html.markdown @@ -75,7 +75,7 @@ Très mature/compatible: * [MRI](https://github.com/ruby/ruby) - Ecrite en C, c'est l'implémentation de référence de Ruby. Elle est par définition 100% compatible (avec elle-même). Tous les autres rubies maintiennent la compatibilité avec MRI - (voir [RubySpec](#rubyspec) à la suite). + (voir [Ruby Spec](#ruby-spec) à la suite). * [JRuby](http://jruby.org/) - Écrite en Java et Ruby, cette robuste implémentation est assez rapide. La force de JRuby réside surtout sur l'interopérabilité JVM/Java, faisant @@ -102,9 +102,9 @@ cibler. Une liste non exhaustive d'implémentations peut être trouvée [ici (EN)](https://github.com/cogitator/ruby-implementations/wiki/List-of-Ruby-implementations). -## RubySpec +## Ruby Spec -La plupart des implémentations Ruby s'appuient fortement sur [RubySpec](http://rubyspec.org/). +La plupart des implémentations Ruby s'appuient fortement sur [Ruby Spec](https://github.com/ruby/spec). Ruby n'a pas de spécification officielle, c'est pourquoi la commaunité a écrit des spécifications exécutables en Ruby pour tester la compatibilité de leur implémentation avec MRI. diff --git a/it-it/ruby-ecosystem-it.html.markdown b/it-it/ruby-ecosystem-it.html.markdown index d745399b..b0ea1ecf 100644 --- a/it-it/ruby-ecosystem-it.html.markdown +++ b/it-it/ruby-ecosystem-it.html.markdown @@ -68,7 +68,7 @@ Implementazioni mature e compatibili: * [MRI](https://github.com/ruby/ruby) - Scritto in C, Questa è l'implementazione standard di Ruby, per definizione è 100% compatibile (con se stessa). Tutte le altre implemetazioni mantengono la compatibilità con MRI - (vedere [RubySpec](#rubyspec) sotto). + (vedere [Ruby Spec](#ruby-spec) sotto). * [JRuby](http://jruby.org/) - Scritto in Java e Ruby, Questa implementazione è molto veloce e robusta, la forza di JRuby consiste nell'interoperabilità tra JVM/Java, permettendo l'utilizzo di struemnti Java già esistenti, progetti @@ -96,10 +96,10 @@ Le implementazioni Ruby possono avere una propria versione, ma hanno sempre come target una specifica versione di MRI. Molte implementazioni hanno l'abilità di selezionare una versione specifica di MRI. -##RubySpec +##Ruby Spec La maggior parte delle implementazioni Ruby dipendono pesantemente su -[RubySpec](http://rubyspec.org/). Ruby non ha una specifica ufficiale, quindi la +[Ruby Spec](https://github.com/ruby/spec). Ruby non ha una specifica ufficiale, quindi la community ha scritto una specifica eseguibile in Ruby per testare la compatibilità con MRI. diff --git a/pt-br/ruby-ecosystem-pt.html.markdown b/pt-br/ruby-ecosystem-pt.html.markdown index da4f6f37..bd599e5f 100644 --- a/pt-br/ruby-ecosystem-pt.html.markdown +++ b/pt-br/ruby-ecosystem-pt.html.markdown @@ -69,7 +69,7 @@ Muito maduras/compatíveis: * [MRI](https://github.com/ruby/ruby) - Escrita em C, esta é a implementação de referência do Ruby. Por definição, é 100% compatível (consigo mesma). Todos os - outros rubies mantêm compatibilidade com a MRI (veja [RubySpec](#rubyspec) abaixo). + outros rubies mantêm compatibilidade com a MRI (veja [Ruby Spec](#ruby-spec) abaixo). * [JRuby](http://jruby.org/) - Escrita em Java e Ruby, esta implementação robusta é um tanto rápida. Mais importante ainda, o ponto forte do JRuby é a interoperabilidade com JVM/Java, aproveitando ferramentas JVM, projetos, e @@ -98,9 +98,9 @@ sempre focam em uma versão específica da MRI para compatibilidade. Diversas implementações têm a capacidade de entrar em diferentes modos (1.8 ou 1.9, por exemplo) para especificar qual versão da MRI focar. -## RubySpec +## Ruby Spec -A maioria das implementações Ruby dependem fortemente da [RubySpec](http://rubyspec.org/). +A maioria das implementações Ruby dependem fortemente da [Ruby Spec](https://github.com/ruby/spec). Ruby não tem uma especificação oficial, então a comunidade tem escrito especificações executáveis em Ruby para testar a compatibilidade de suas implementações com a MRI. diff --git a/ruby-ecosystem.html.markdown b/ruby-ecosystem.html.markdown index 3c80075b..7e77695d 100644 --- a/ruby-ecosystem.html.markdown +++ b/ruby-ecosystem.html.markdown @@ -52,7 +52,7 @@ Very mature/compatible: * [MRI](https://github.com/ruby/ruby) - Written in C, this is the reference implementation of Ruby. By definition it is 100% compatible (with itself). All other rubies -maintain compatibility with MRI (see [RubySpec](#rubyspec) below). +maintain compatibility with MRI (see [Ruby Spec](#ruby-spec) below). * [JRuby](http://jruby.org/) - Written in Java and Ruby, this robust implementation is quite fast. Most importantly, JRuby's strength is JVM/Java interop, leveraging existing JVM tools, projects, and languages. @@ -80,9 +80,9 @@ target a specific version of MRI for compatibility. Many implementations have the ability to enter different modes (for example, 1.8 or 1.9 mode) to specify which MRI version to target. -## RubySpec +## Ruby Spec -Most Ruby implementations rely heavily on [RubySpec](http://rubyspec.org/). Ruby +Most Ruby implementations rely heavily on [Ruby Spec](https://github.com/ruby/spec). Ruby has no official specification, so the community has written executable specs in Ruby to test their implementations' compatibility with MRI. diff --git a/vi-vn/ruby-ecosystem-vi.html.markdown b/vi-vn/ruby-ecosystem-vi.html.markdown index 518cf072..5fb855b9 100644 --- a/vi-vn/ruby-ecosystem-vi.html.markdown +++ b/vi-vn/ruby-ecosystem-vi.html.markdown @@ -70,7 +70,7 @@ Một số ứng dụng nổi tiếng/tương thích cao: * [MRI](https://github.com/ruby/ruby) - Được viết bằng C, đây là ứng dụng tham chiếu của Ruby. Nó tương thích 100%. Tất cả các phiên bản Ruby có khả - năng duy trì với MRI(xem [RubySpec](#rubyspec) bên dưới). + năng duy trì với MRI(xem [Ruby Spec](#ruby-spec) bên dưới). * [JRuby](http://jruby.org/) - Được viết bằng Java và Ruby, ứng dụng này khá nhanh. Điểm mạnh quan trọng nhất của JRuby là JVM/Java interop, tận dụng các công cụ, dự án và ngôn ngữ hiện có của JVM. @@ -97,9 +97,9 @@ hướng đến sự một phiên bản đặc biệt của MRI cho sự tương dụng có khả năng đến các chế độ khác nhau (ví dụ, 1.8 hoặc 1.9) để hướng đến phiên bản MRI. -## RubySpec +## Ruby Spec -Hầu hết các ứng dụng Ruby dựa vào [RubySpec](http://rubyspec.org/). Ruby không +Hầu hết các ứng dụng Ruby dựa vào [Ruby Spec](https://github.com/ruby/spec). Ruby không có thông báo chính thức, nhưng cộng đồng đã viết những specs thực thi trong Ruby để kiểm tra sự tương thích với MRI. From 810ab009d5ba85fdd604094d3f282217f215cad8 Mon Sep 17 00:00:00 2001 From: AN Long Date: Thu, 15 Aug 2024 02:01:34 +0800 Subject: [PATCH 300/392] [java/en] Fix mix usage of spaces and tabs as indents (#5024) --- java.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/java.html.markdown b/java.html.markdown index 20156365..fc7383d8 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -126,8 +126,8 @@ public class LearnJava { // = = = int barInt1, barInt2, barInt3; barInt1 = barInt2 = barInt3 = 1; - // Shorthand for multiple declarations - int barInt4 = 1, barInt5 = 2; + // Shorthand for multiple declarations + int barInt4 = 1, barInt5 = 2; /* @@ -310,8 +310,8 @@ public class LearnJava { /////////////////////////////////////// System.out.println("\n->Operators"); - int i1 = 1, i2 = 2; - + int i1 = 1, i2 = 2; + // Arithmetic is straightforward System.out.println("1+2 = " + (i1 + i2)); // => 3 System.out.println("2-1 = " + (i2 - i1)); // => 1 @@ -543,7 +543,7 @@ public class LearnJava { // is called when the anonymous inner class is created. // This does not only work for Collections, it works for all // non-final classes. - + // Another option was to initialize the Collection from an array, // using Arrays.asList() method: @@ -926,7 +926,7 @@ import java.security.SecureRandom; public class Lambdas { public static void main(String[] args) { // Lambda declaration syntax: - // -> + // -> // We will use this hashmap in our examples below. Map planets = new HashMap<>(); From 2c0ab0067381176d6e4b22324e9202e57d006697 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 18 Aug 2024 22:33:57 +0200 Subject: [PATCH 301/392] Fix typos (#5030) --- de-de/paren-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/paren-de.html.markdown b/de-de/paren-de.html.markdown index 641e226e..9ac75598 100644 --- a/de-de/paren-de.html.markdown +++ b/de-de/paren-de.html.markdown @@ -34,7 +34,7 @@ Manche Beispiele sind von . ;; Funktionsapplikationen werden so geschrieben: (f x y z ...) ;; Dabei ist f eine Funktion und x, y, z sind die Operatoren. -;; Wenn du eine Literalliste von Daten erstelllen möchtest, +;; Wenn du eine Literalliste von Daten erstellen möchtest, ;; verwende (quote) um zu verhindern, dass sie ausgewertet zu werden. (quote (+ 1 2)) ; => (+ 1 2) ;; Nun einige arithmetische Operationen @@ -92,7 +92,7 @@ some-var ; => 5 ;;; Listen -;; Listen sind Vektrorartige Datenstrukturen. (Zufälliger Zugriff ist O(1). +;; Listen sind Vektorartige Datenstrukturen. (Zufälliger Zugriff ist O(1). (cons 1 (cons 2 (cons 3 (list)))) ; => (1 2 3) ;; 'list' ist ein komfortabler variadischer Konstruktor für Listen (list 1 2 3) ; => (1 2 3) @@ -196,5 +196,5 @@ a ; => (3 2) (infix 1 + 2 (infix 3 * 4)) ; => 15 ;; Makros sind nicht hygenisch, Du kannst bestehende Variablen überschreiben! -;; Sie sind Codetransformationenen. +;; Sie sind Codetransformationen. ``` From 3653c1efccb13cd1722850239c1289e4a5785807 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 18 Aug 2024 22:34:12 +0200 Subject: [PATCH 302/392] [edn/de-de] Fix typo (#5029) --- de-de/edn-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/edn-de.html.markdown b/de-de/edn-de.html.markdown index 2d194f3b..1ba5ffce 100644 --- a/de-de/edn-de.html.markdown +++ b/de-de/edn-de.html.markdown @@ -82,7 +82,7 @@ false ;;; markierte Elemente ;;; ;;;;;;;;;;;;;;;;;;;;;;;;; -; EDN kann erweitert werden, indem Elemente mit # Symbolen makiert werden. +; EDN kann erweitert werden, indem Elemente mit # Symbolen markiert werden. #MyYelpClone/MenuItem {:name "eggs-benedict" :rating 10} @@ -108,4 +108,4 @@ false - [EDN spec](https://github.com/edn-format/edn) - [Implementationen](https://github.com/edn-format/edn/wiki/Implementations) -- [makierte Elemente](http://www.compoundtheory.com/clojure-edn-walkthrough/) +- [markierte Elemente](http://www.compoundtheory.com/clojure-edn-walkthrough/) From daa86a4e9b1401052adb54a69698bea786ff41a3 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 19 Aug 2024 14:02:19 +0200 Subject: [PATCH 303/392] [opencv/en] Fix some typos, grammar and spelling (#5032) --- opencv.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/opencv.html.markdown b/opencv.html.markdown index 9a931bcb..390c36c3 100644 --- a/opencv.html.markdown +++ b/opencv.html.markdown @@ -5,11 +5,11 @@ filename: learnopencv.py contributors: - ["Yogesh Ojha", "http://github.com/yogeshojha"] --- -### Opencv +### OpenCV OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. Originally developed by Intel, it was later supported by Willow Garage then Itseez (which was later acquired by Intel). -OpenCV currently supports wide variety of languages like, C++, Python, Java etc +OpenCV currently supports wide variety of languages like, C++, Python, Java, etc. #### Installation Please refer to these articles for installation of OpenCV on your computer. @@ -18,7 +18,7 @@ Please refer to these articles for installation of OpenCV on your computer. * Mac Installation Instructions (High Sierra): [https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a](https://medium.com/@nuwanprabhath/installing-opencv-in-macos-high-sierra-for-python-3-89c79f0a246a) * Linux Installation Instructions (Ubuntu 18.04): [https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv](https://www.pyimagesearch.com/2018/05/28/ubuntu-18-04-how-to-install-opencv) -### Here we will be focusing on python implementation of OpenCV +### Here we will be focusing on Python implementation of OpenCV ```python # Reading image in OpenCV @@ -28,21 +28,21 @@ img = cv2.imread('cat.jpg') # Displaying the image # imshow() function is used to display the image cv2.imshow('Image', img) -# Your first arguement is the title of the window and second parameter is image -# If you are getting error, Object Type None, your image path may be wrong. Please recheck the pack to the image +# Your first argument is the title of the window and second parameter is image +# If you are getting an error, Object Type None, your image path may be wrong. Please recheck the path to the image cv2.waitKey(0) -# waitKey() is a keyboard binding function and takes arguement in milliseconds. For GUI events you MUST use waitKey() function. +# waitKey() is a keyboard binding function and takes an argument in milliseconds. For GUI events you MUST use waitKey() function. # Writing an image cv2.imwrite('catgray.png', img) -# first arguement is the file name and second is the image +# The first argument is the file name and second is the image # Convert image to grayscale gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Capturing Video from Webcam cap = cv2.VideoCapture(0) -# 0 is your camera, if you have multiple camera, you need to enter their id +# 0 is your camera, if you have multiple cameras, you need to enter their id while True: # Capturing frame-by-frame _, frame = cap.read() From 36370c5a5247403e9c80848321df1d8ebc56f74e Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 19 Aug 2024 14:02:58 +0200 Subject: [PATCH 304/392] [miniscript/en] Fix typos (#5031) --- miniscript.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/miniscript.html.markdown b/miniscript.html.markdown index 8a2a4f87..21abc57c 100644 --- a/miniscript.html.markdown +++ b/miniscript.html.markdown @@ -133,7 +133,7 @@ print a[1:-1] // same as above, but using a negative index print a[1:] // get slice from 1 to the end ("ello") print a[:2] // get slice from beginning up to 2 ("He") -// Note that strings in MiniScript are immutable. You can't reache +// Note that strings in MiniScript are immutable. You can't reach // into a string and change what characters it contains (but you can // always create a new string with different characters). ``` @@ -250,7 +250,7 @@ print roll(2,20) // roll two 20-sided dice // (parameter values) to the function, and (2) you're using the // result as part of some larger statement. Notice how the first // example above, rollDie did not need any parentheses because we -// weren't passing an arguments. Here's an example of a function +// weren't passing any arguments. Here's an example of a function // that, like the built-in print function, is used as a statement // by itself, and so does not need parentheses. doRoll = function(numberOfDice, sides=6) From 53738440a70a300416e0760ba4b9816ca77406ec Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 19 Aug 2024 21:35:05 +0200 Subject: [PATCH 305/392] [bc/de-de] Fix typos (#5033) --- de-de/bc.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/bc.html.markdown b/de-de/bc.html.markdown index 5b169f34..4491efc1 100644 --- a/de-de/bc.html.markdown +++ b/de-de/bc.html.markdown @@ -36,7 +36,7 @@ if(hour < 12) { /*Operatoren sind genau wie in C*/ print "Hallo\n" /* Escape-Sequenzen starten mit einem \ in einem String. Um Escape-Sequenzen klarer zu machen, ist hier eine vereinfachte - Liste, welche in bc funktioneren: + Liste, welche in bc funktionieren: \b: Backspace \c: carriage return \n: Zeilenumbruch @@ -79,7 +79,7 @@ define fac(n) { /*Definiere eine Funktion mit define*/ num = fac(4) /*24*/ -/*Dies ist ein Beispiel von lokalen Variabeln.*/ +/*Dies ist ein Beispiel von lokalen Variablen.*/ define x(n) { auto x x = 1 From e295a1621918fabbf4fd82418ea11f3aae5ab38d Mon Sep 17 00:00:00 2001 From: TehBrian <32250137+TehBrian@users.noreply.github.com> Date: Mon, 19 Aug 2024 18:06:05 -0400 Subject: [PATCH 306/392] [hocon/en] clean up document (#5035) --- hocon.html.markdown | 209 ++++++++++++++++++++++---------------------- 1 file changed, 106 insertions(+), 103 deletions(-) diff --git a/hocon.html.markdown b/hocon.html.markdown index b09e20f0..bd101a9d 100644 --- a/hocon.html.markdown +++ b/hocon.html.markdown @@ -9,17 +9,15 @@ Human-Optimized Configuration Object Notation, or HOCON, is a configuration and data serialization format designed to be easily editable by humans. It's a superset of JSON, meaning that any valid JSON is valid HOCON, but it -differs in being much less pedantic and opinionated. With its flexible yet -easily determinable syntax, resulting configuration files are often much less -noisy than some other formats. +differs in being less opinionated. With its flexible yet determinable syntax, +resulting configuration files are often less noisy than with other formats. -Additionally, its support for comments makes it much better suited for -user-facing configurations than JSON. +Additionally, its support for comments makes it better-suited for user-facing +configuration than JSON. ``` -// Comments can either look like this, -# or they can look like this. -// Anything after // or # is a comment. +// Anything after // or # is a comment. This is a comment. +# This is also a comment. ################## ### THE BASICS ### @@ -37,24 +35,29 @@ colon3 : value equals1=value equals2= value equals3 = value -# As you'll see, HOCON is very nonrestrictive regarding its syntax style. +# As you'll see, HOCON has a very nonrestrictive syntax. -# HOCON also isn't opinionated on how keys look. +# HOCON isn't opinionated on how keys look. THIS_IS_A_VALID_KEY: value this-is-also-a-valid-key: value -keys can have spaces too: value +keys can have spaces: value or even numbers like 12345: value "you can even quote keys if you'd like!": value -# A key, followed by any separator, and then finally a value, is called a field. +# Keys are case sensitive. +unique: value 1 +UnIqUe: value 3 +UNIQUE: value 2 + +# A key, followed by any separator, followed by a value, is called a field. this_entire_line_is: a field ################### ### VALUE TYPES ### ################### -# The types that a value can be are string, number, object, array, boolean, and -# null. Every value type except for array and object are called simple values. +# A value can be of type: string, number, object, array, boolean, null. +# Simple values are values of any type except array and object. ## SIMPLE VALUES ## @@ -62,18 +65,16 @@ quoted_string: "I like quoting my strings." unquoted_string: I don't like quoting my strings. # Special characters that cannot be used in unquoted strings are: # $ " { } [ ] : = , + # ` ^ ? ! @ * & -# Unquoted strings do not support any kind of escaping. If using one of those -# special characters is desired, use a quoted string. -multi-line_string: """ - This entire thing is a string! - One giant, multi-line string. - You can put 'single' and "double" quotes without it being invalid. -""" +# Unquoted strings do not support any kind of escaping. +# To use one of those special characters in a string, use a quoted string. +multiline_string: """This entire thing is a string! +One giant, multiline string. +You can put 'single' and "double" quotes without it being invalid.""" number: 123 negative: -123 fraction: 3.1415926536 -scientific_notation: 1.2e6 // same as 1.2 * (10^6) +scientific_notation: 1.2e6 // 1.2 * 10^6 boolean: true # or false empty: null @@ -81,10 +82,11 @@ empty: null ## ARRAYS ## # Arrays hold lists of values. + # Values in arrays can be separated with commas.. array: [ 1, 2, 3, 4, 5 ] fibonacci: [1,1,2,3,5,8,13] -multiples_of_5: [5, 10, 15, 20,] # Notice the trailing comma. That's okay here. +multiples_of_5: [5, 10, 15, 20,] # Notice the trailing comma. That's allowed. # or newlines.. friends: [ "Brian" @@ -97,25 +99,27 @@ ingredients: [ "Egg", "Sugar", "Oil", - "Flour", # Notice the trailing comma. That's okay here too. + "Flour", # Trailing comma. That's allowed here too. ] -# Once again, HOCON has a very loose syntax. Use whichever style you prefer. +# Once again, HOCON has a very liberal syntax. Use whichever style you prefer. + no newline before or after bracket: ["This" "is" "an" "array!"] -# Just like any other value, arrays can hold other arrays. +# Arrays can hold other arrays. array in array: [ [1, 2, 3], ["a", "b", "c"] ] array in array in array: [ [ [1, 2], [8, 9] ], [ ["a", "b" ], ["y", "z"] ] ] ## OBJECTS ## # Objects hold fields. + # Just like arrays, fields in objects can be separated with commas.. object: { key: value, another_key: another_value } server_connection: {ip: "127.0.0.1", port: 80} -first: {letter: a, number: 1,} # Notice the trailing comma. +first: {letter: a, number: 1,} # Trailing comma. # or newlines.. power_grid: { max_capacity: 15000 @@ -127,10 +131,10 @@ food_colors: { pear: green, apple: red, plum: purple, - banana: yellow, # Trailing commas are okay here too! + banana: yellow, # Trailing comma. These pesky things show up everywhere! } -# Arrays can hold objects just like any other value type. +# Arrays can hold objects. coworkers: [ { name: Jeff @@ -152,7 +156,7 @@ no_separator { speed_of_light: very fast ten: 10 - # Objects can go inside other objects just like any other value. + # Objects can hold other objects. another_object { twenty: 20 speed_of_sound: also pretty fast @@ -224,10 +228,10 @@ my_car: { # and then back to an object value, the new object will completely override any # previous value. -// Null, a non-object value, completely overrides the object value. +// Null, a non-object value, overrides the object. my_car: null -// Then, this object completely overrides null. +// Then, this object overrides null. my_car: { nickname: "My New Car" type: 4-door minivan @@ -242,49 +246,49 @@ my_car: { ## SIMPLE VALUE CONCATENATION ## -# Simple values (all value types except objects and arrays) separated by +# Simple values (all value types except array and object) separated by # whitespace are concatenated into a single string. The whitespace between # values is preserved. -number_concatenation: 1 2 3 12.5 -3 2e5 // same as: "1 2 3 12.5 -3 2e5" +number_concat: 1 2 3 12.5 -3 2e5 // "1 2 3 12.5 -3 2e5" boolean_concat: true false true // "true false true" null_concat: null null null // "null null null" mixed_concat: 1 true null // "1 true null" # String value concatenation can appear anywhere that a quoted string can. -number_concat_in_array: [1 2, 3 4, 5 6] // same as: ["1 2", "3 4", "5 6"] +number_concat_in_array: [1 2, 3 4, 5 6] // ["1 2", "3 4", "5 6"] # In fact, unquoted strings are actually just string value concatenations. -unquoted_string_concat: his name is jeff // same as: "his name is jeff" +unquoted_string_concat: his name is jeff // "his name is jeff" # Going further, even keys that are unquoted strings are actually just string # value concatenations. -this is a key: value // the KEY is the same as: "this is a key" +this is a key: value // the KEY is: "this is a key" # The following field is identical to the field above. "this is a key": value -# Quoted strings can also be concatenated. This will be useful later, -# when we cover substitutions. -quoted_string_concat: "her"" name" "is ""jenna" // same as: "her name is jenna" +# Quoted strings can also be concatenated. +# This will be useful later, when we cover substitutions. +quoted_string_concat: "her"" name" "is ""jenna" // "her name is jenna" # Notice that the whitespace (or lack thereof) between values is preserved. ## ARRAY CONCATENATION ## # Arrays separated by whitespace are merged into a single array. -array_concat: [1, 2, 3] [4, 5, 6] // same as: [1, 2, 3, 4, 5, 6] +array_concat: [1, 2, 3] [4, 5, 6] // [1, 2, 3, 4, 5, 6] # Arrays cannot be concatenated with a non-array value. -//array_concat: true [false] results in an error -//array_concat: 1 [2] results in an error +//array_concat: true [false] // error! +//array_concat: 1 [2] // error! ## OBJECT CONCATENATION ## # Objects separated by whitespace are merged into a single object. # The merge functionality is identical to that of duplicate key object merging. -lamp: {on: true} {color: tan} // same as: {on: true, color: tan} +lamp: {on: true} {color: tan} // {on: true, color: tan} # Similarly to arrays, objects cannot be concatenated with a non-object value. -//object_concat: true {on: false} results in an error -//object_concat: 1 {number: 2} results in an error +//object_concat: true {on: false} // error! +//object_concat: 1 {number: 2} // error! ######################## ### PATH EXPRESSIONS ### @@ -305,13 +309,12 @@ country: { } } } -# For example, the path to the address of the house could be written as: +# The path to the address could be written as: # country.city.neighborhood.house.address # Country, city, neighborhood, house, and address are all elements. -# Path expressions are used in two places: substitutions (which will be -# covered in a moment), and as keys. -# That's right: keys themselves can also be path expressions. +# Path expressions are used in two places: substitutions (which we'll get to +# in just a moment), and as keys. That's right: keys can be path expressions. foo: { bar: { baz: { @@ -319,8 +322,8 @@ foo: { } } } -# Rather than tediously specifying each object, a path expression can be used. -# The following field represents the same object found above. +# Rather than tediously specifying each object, a path expression could be used. +# The following field represents the same object. foo.bar.baz.number: 12 # Fields and objects specified with path expressions are merged in the same way @@ -333,41 +336,42 @@ foo.bar.baz.bool: true ##################### # Substitutions refer to a specific value from some path expression. -# They're only allowed in values, not keys or nested inside other substitutions. +# They're only allowed in values, not in keys or nested in other substitutions. me: { favorite_animal: parrots favorite_food: cookies } -# The syntax for a substitution is either ${path_expression} or -# ${?path_expression}. The latter syntax will be discussed in a moment. +# There are two syntaxes for substitutions: +# ${path_expression} and ${?path_expression}. +# The latter syntax will be covered in a moment. my_fav_animal: ${me.favorite_animal} my_fav_food: ${me.favorite_food} # Substitutions are not parsed inside quoted strings. To get around this, # either use an unquoted string or value concatenation. animal_announcement: My favorite animal is ${my_fav_animal} -// the value is: My favorite animal is parrots +// "My favorite animal is parrots" food_announcement: "My favorite food is "${my_fav_food}"!" -// the value is: "My favorite food is cookies!" +// "My favorite food is cookies!" # Substitutions are parsed last in the document. Because of this, you can # reference a key that hasn't been defined yet. color_announcement: "My favorite color is" ${my_fav_color}"!" -// the value is: "My favorite color is blue!" +// "My favorite color is blue!" my_fav_color: blue # Another effect of substitutions being parsed last is that substitutions will -# always use the latest, as in last, value assigned in the entire document, -# which includes merged objects. +# always use the latest, as in last, value assigned in the entire document. color: green -their_favorite_color: ${color} // the value is: orange +their_favorite_color: ${color} // orange color: orange +# This includes merged objects. random_object: { number: 12 } -the_number: ${random_object.number} // the value is: 15 +the_number: ${random_object.number} // 15 random_object: { number: 15 } @@ -379,13 +383,13 @@ random_object: { # A substitution using the ${path_expression} syntax with an undefined path # expression, meaning a path expression that does not point to a defined value, # is invalid and will therefore generate an error. -//${does.not.exist} will throw an error +//${does.not.exist} // error! # However, an undefined substitution using the ${?path_expression} syntax # has different behavior depending on what it is the value of. request: { - # If it is the value of a field, then the field will not be created. - response: ${?does.not.exist} // this field won't be created and does not exist + # If it is the value of a field, then the field won't be created. + response: ${?does.not.exist} // this field does not exist type: HTTP } @@ -397,19 +401,19 @@ request: { # If it is a value in an array, then it is simply not added. values: [ 172, "Brian", ${?does.not.exist}, null, true, ] -// the value is: [ 172, "Brian", null, true ] +// [ 172, "Brian", null, true ] # If it is part of simple value concatenation, it acts as an empty string. final_string: "String One"${?does.not.exist}"String Two" -// the value is: "String OneString Two" +// "String OneString Two" # If it is part of array concatenation, it acts as an empty array. final_array: [ 1, 2, 3 ] ${?does.not.exist} [ 7, 8, 9 ] -// the value is: [ 1, 2, 3, 7, 8, 9 ] +// [ 1, 2, 3, 7, 8, 9 ] # If it is part of object concatenation, it acts as an empty object. -final_array: { a: 1 } ${?does.not.exist} { c: 3 } -// the value is: { a: 1, c: 3 } +final_object: { a: 1 } ${?does.not.exist} { c: 3 } +// { a: 1, c: 3 } ###################################### ### SELF-REFERENTIAL SUBSTITUTIONS ### @@ -419,18 +423,18 @@ final_array: { a: 1 } ${?does.not.exist} { c: 3 } # document. However, in cases when this would create a cycle, the substitution # looks only backwards. -# A field which contains a substitution that points to itself or points to +# A field that contains a substitution that points to itself or points to # other fields that eventually point back to itself is called a # self-referential field. -letters: "a b c" // the value is: "a b c" +letters: "a b c" // "a b c" letters: ${letters}" d" // "a b c d" letters: ${letters}" e" // "a b c d e" -PATH: [/bin] // the value is: [/bin] +PATH: [/bin] // [/bin] PATH: ${PATH} [/usr/bin] // [/bin, /usr/bin] PATH: ${PATH} [/usr/local/bin] // [/bin, /usr/bin, /usr/local/bin] -x: "x" // the value is: "x" +x: "x" // "x" y: ${x}"y" // "xy" x: ${y}"z" // "xyz" @@ -439,34 +443,33 @@ x: ${y}"z" // "xyz" ########################## # In addition to : and =, there actually exists another separator: += -# A field separated with += acts as a self-referential array concatenation. -# In short, it appends an element to a previously defined array. +# A field separated with += implies self-referential array concatenation. +# Essentially, it appends an element to a previously defined array. a: [1] b: [1] -# This field: -a += 2 // the value is: [1, 2] -# functions the same as: -b: ${?b} [2] // the value is: [1, 2] +# These two fields are equivalent. +a += 2 // [1, 2] +b: ${?b} [2] // [1, 2] -USERS: [/usr/luke] // the value is: [/usr/luke] +USERS: [/usr/luke] // [/usr/luke] USERS += /usr/devon // [/usr/luke, /usr/devon] USERS += /usr/michael // [/usr/luke, /usr/devon, /usr/michael] # Since += only appends elements to a previously existing array, if the previous # value was not an array, an error will be generated. OTHER_USERS: /usr/luke -//OTHER_USERS += /usr/devon results in an error +//OTHER_USERS += /usr/devon // error! -# Notice that the underlying substitution syntax used is ${?path}, not ${path}. +# The underlying substitution syntax used is ${?path}, not ${path}. # Recall that, using the ${?} syntax, an undefined substitution in array # concatenation acts as an empty array. Because of this, it is perfectly # acceptable if the field that is being set is initially undefined. -//z: [] not necessary -z += 3 // the value is: [3] -z += 4 // the value is: [3, 4] +//z: [] // not necessary +z += 3 // [3] +z += 4 // [3, 4] -NEW_USERS += /usr/sandra // the value is: [/usr/sandra] +NEW_USERS += /usr/sandra // [/usr/sandra] NEW_USERS += /usr/kennedy // [/usr/sandra, /usr/kennedy] NEW_USERS += /usr/robin // [/usr/sandra, /usr/kennedy, /usr/robin] @@ -494,13 +497,13 @@ include classpath("config.conf") # If the included file does not exist, it will be silently ignored and act as if # it were an empty object. However, if it is wrapped around required(), then # parsing will explicitly error if the file cannot be resolved. -//include required("doesnt_exist.conf") will error -//include required(url("https://example.com/doesnt_exist.conf")) will error -//include required(file("doesnt_exist.conf")) will error -//include required(classpath("doesnt_exist.conf")) will error +//include required("doesnt_exist.conf") // error! +//include required(url("https://example.com/doesnt_exist.conf")) // error! +//include required(file("doesnt_exist.conf")) // error! +//include required(classpath("doesnt_exist.conf")) // error! -# The file specified by the include statement is called the included file, and -# the file which contains the include statement is called the including file. +# The file specified by the include statement is called the included file. +# The file containing the include statement is called the including file. # Including a file functions as if you directly replaced the include statement, # wherever it may be, with the contents of the included file's root object. @@ -518,19 +521,19 @@ screensaver: { turn_on_after: 1m } -# And then we include that file. +# Then, we include that file. include file("user_config.conf") # We can now reference values from that file! -path_to_user_screensaver: ${screensaver.image} // -greeting: "Welcome, "${username}"!" // the value is: "Welcome, RandomUser1337!" +path_to_user_screensaver: ${screensaver.image} // "usr/images/screensaver.jpg" +greeting: "Welcome, "${username}"!" // "Welcome, RandomUser1337!" # Duplicate keys override as they normally do. -status: "Auto Login: "${auto_login} // the value is: "Auto Login: true" +status: "Auto Login: "${auto_login} // "Auto Login: true" auto_login: false -status: "Auto Login: "${auto_login} // the value is: "Auto Login: false" +status: "Auto Login: "${auto_login} // "Auto Login: false" -# Object merging is also the same as usual. +# Object merging is the same as usual. screensaver: { // This gets added to the screensaver object. enable_during_day: false @@ -550,7 +553,7 @@ admin_page: { password: pass12345 } -# And then we include that file nested inside another object. +# Then, we include that file nested inside an object. websites: { my_epic_website: { include file("server_settings.conf") @@ -562,13 +565,13 @@ websites: { server_port: ${websites.my_epic_website.port} the_password: "The password is: "${websites.my_epic_website.admin_page.password} -// the value is: The password is: pass12345 +// "The password is: pass12345" max_conn: "Max Connections: "${websites.my_epic_website.max_connections} -// the value is: Max Connections: 10 +// "Max Connections: 10" ``` ### More Resources + [Official HOCON Specification](https://github.com/lightbend/config/blob/master/HOCON.md) -+ [HOCON Playground](https://hocon-playground.herokuapp.com) ++ [HOCON Playground](https://hocon-playground.tehbrian.dev) From 93d902380d6086b719d11b044381a4d744dc54e2 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Tue, 20 Aug 2024 00:06:27 +0200 Subject: [PATCH 307/392] [clojure/de-de] Fix typos, grammar and spelling (#5034) --- de-de/clojure-de.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/de-de/clojure-de.html.markdown b/de-de/clojure-de.html.markdown index 1257b099..6e8a50b8 100644 --- a/de-de/clojure-de.html.markdown +++ b/de-de/clojure-de.html.markdown @@ -10,7 +10,7 @@ lang: de-de Clojure ist ein Lispdialekt, der für die Java Virtual Maschine entwickelt worden ist. Sie hat eine stärkere Betonung auf reine [funktionale Programmierung](https://en.wikipedia.org/wiki/Functional_programming) als Common Lisp. Jedoch besitzt sie je nach Bedarf mehrere [STM](https://en.wikipedia.org/wiki/Software_transactional_memory) Werkzeuge zur Handhabung von Zustand. -Diese Verknüpfung erlaubt es parallele Verarbeitung sehr einfach und häufig automatisch zu verarbeiten. +Diese Verknüpfung erlaubt es, parallele Verarbeitung sehr einfach und häufig automatisch zu verarbeiten. (Du brauchst die Clojure Version 1.2 oder neuer) @@ -23,7 +23,7 @@ Diese Verknüpfung erlaubt es parallele Verarbeitung sehr einfach und häufig au ; Der Clojure Leser nimmt an, dass das Erste, was aufgerufen wird ; eine Funktion oder ein Makro ist, der Rest sind Argumente. -; Der erste Aufruf in einer Datei sollte ns sein, um den Namespacezu setzen. +; Der erste Aufruf in einer Datei sollte ns sein, um den Namespace zu setzen. (ns learnclojure) ; Weitere einfache Beispiele: @@ -52,8 +52,8 @@ Diese Verknüpfung erlaubt es parallele Verarbeitung sehr einfach und häufig au ; Clojure verwendet Javas Objekt Typen für Booleans, Strings und Zahlen. ; Verwende `class` um sie zu inszipieren. -(class 1) ; Integer Literalte sind standardmäßig java.lang.Long -(class 1.); Float Literale sind java.lang.Double +(class 1) ; Integer-Literale sind standardmäßig java.lang.Long +(class 1.); Float-Literale sind java.lang.Double (class ""); Strings sind immer in doppelten Anführungszeichen notiert und sind java.lang.String (class false) ; Booleans sind java.lang.Boolean (class nil); Der "null" Wert heißt nil @@ -66,7 +66,7 @@ Diese Verknüpfung erlaubt es parallele Verarbeitung sehr einfach und häufig au ; Du kannst eine zitierte Liste evaluieren (eval '(+ 1 2)) ; => 3 -; Kollektioenn & Sequenzen +; Kollektionen & Sequenzen ;;;;;;;;;;;;;;;;;;; ; Listen sind Linked-Lists Datenstrukturen, während Vektoren arraybasierend sind. @@ -76,7 +76,7 @@ Diese Verknüpfung erlaubt es parallele Verarbeitung sehr einfach und häufig au ; Eine Liste würde nur als (1 2 3) geschrieben, aber wir müssen es zitieren ; damit der Leser aufhört zu denken, es sei eine Funktion. -; Außerdem ist (list 1 2 3) das Selbe, wie '(1 2 3) +; Außerdem ist (list 1 2 3) dasselbe, wie '(1 2 3) ; "Kollektioen" sind nur Gruppen von Daten ; Listen und Vektoren sind Kolllektionen: @@ -178,12 +178,12 @@ x ; => 1 (class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap (class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap -; Arraymaps werden durch die meisten Operatioen automatisch zu Hashmaps, +; Arraymaps werden durch die meisten Operationen automatisch zu Hashmaps, ; sobald sie groß genug werden. Das heißt du musst dich nicht darum sorgen. ; Maps können einen beliebigen Hash-Typ als Schlüssel verwenden, in der Regel ; sind jedoch Keywords am besten. Keywords sind wie Strings, jedoch besitzen sie -; Performancevorteile +; Performance-Vorteile (class :a) ; => clojure.lang.Keyword (def stringmap {"a" 1, "b" 2, "c" 3}) From b4f23c3db686fcd8b0b6cf43ba113522caedc1f2 Mon Sep 17 00:00:00 2001 From: pseudoparenchymatous <105337186+pseudoparenchymatous@users.noreply.github.com> Date: Tue, 20 Aug 2024 21:33:44 +0800 Subject: [PATCH 308/392] [java/pl-pl] Remove duplicate `filename` header field (#5037) The duplicate `filename` field clashes with the English version --- pl-pl/java-pl.html.markdown | 1 - 1 file changed, 1 deletion(-) diff --git a/pl-pl/java-pl.html.markdown b/pl-pl/java-pl.html.markdown index 3aadd3b4..8839ddbf 100644 --- a/pl-pl/java-pl.html.markdown +++ b/pl-pl/java-pl.html.markdown @@ -13,7 +13,6 @@ contributors: - ["Rob Rose", "https://github.com/RobRoseKnows"] - ["Sean Nam", "https://github.com/seannam"] - ["Shawn M. Hanes", "https://github.com/smhanes15"] -filename: LearnJava.java translators: - ["Jacek Wachowiak", "https://github.com/jacekwachowiak"] lang: pl-pl From 43fd63cd1166e154a8a88eb2bd34395406d9f6e1 Mon Sep 17 00:00:00 2001 From: Sergii Tkachenko Date: Wed, 21 Aug 2024 08:08:48 -0400 Subject: [PATCH 309/392] [go/en] disambiguate "close" in learnDefer() (#5038) --- go.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.html.markdown b/go.html.markdown index d3f2572e..20f3adda 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -323,7 +323,7 @@ func learnDefer() (ok bool) { defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // Defer is commonly used to close a file, so the function closing the - // file stays close to the function opening the file. + // file stays near the function opening the file. return true } From 877dc56ed5a60da6756c33195686985c94c15667 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 21 Aug 2024 14:39:15 +0200 Subject: [PATCH 310/392] [elm/de-de] Fix typos and spelling (#5039) --- de-de/elm-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown index a6a8cd88..50cdbcc4 100644 --- a/de-de/elm-de.html.markdown +++ b/de-de/elm-de.html.markdown @@ -238,7 +238,7 @@ append [1,1,2] [3,5,8] -- [1,1,2,3,5,8] {-- Eigene Datentypen erstellen --} --- Ein "Record" ist ähnlich wie ein Tupel, nur das jedes Feld einen Namne hat. +-- Ein "Record" ist ähnlich wie ein Tupel, nur das jedes Feld einen Namen hat. -- Dabei spielt die Reihenfolge keine Rolle. { x = 3, y = 7 } @@ -253,7 +253,7 @@ append [1,1,2] [3,5,8] -- [1,1,2,3,5,8] { person | name = "George" } --- Mehrere Felder aufeinmal ändern unter Verwendung des alten Wertes. +-- Mehrere Felder auf einmal ändern unter Verwendung des alten Wertes. { particle | position = particle.position + particle.velocity, velocity = particle.velocity + particle.acceleration } @@ -309,7 +309,7 @@ leftmostElement tree = -- Die Kernbibliotheken und andere Bibliotheken sind in Module aufgeteilt. -- Für große Projekte können auch eigene Module erstellt werden. --- Eine Modul beginnt mit ganz oben. Ohne diese Angabe befindet man sich +-- Eine Modul beginnt ganz oben. Ohne diese Angabe befindet man sich -- automatisch im Modul "Main". module Name where @@ -337,7 +337,7 @@ $ elm make MyFile.elm -- "elm-package.json"-Datei anlegen, die alle Informationen des Projektes -- speichert. --- Der Reactor ist ein Server, welche alle Dateinen kompiliert und ausführt. +-- Der Reactor ist ein Server, welcher alle Dateien kompiliert und ausführt. $ elm reactor -- Starte das REPL (read-eval-print-loop). @@ -360,7 +360,7 @@ Noch ein paar weitere hilfreiche Ressourcen (in Englisch): - Die [Elm Homepage](http://elm-lang.org/). Dort findest du: - - [Anleitung zur Installierung von Elm](http://elm-lang.org/install) + - [Anleitung zur Installation von Elm](http://elm-lang.org/install) - [Dokumentation](http://elm-lang.org/docs), sowie eine [Referenz zur Syntax](http://elm-lang.org/docs/syntax) - Viele hilfreiche [Beispiele](http://elm-lang.org/examples) From 71cb7df1d6e031bc80f858e4e668642a8f64c5eb Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 21 Aug 2024 14:39:58 +0200 Subject: [PATCH 311/392] [montilang/en] Fix typos (#5041) --- montilang.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/montilang.html.markdown b/montilang.html.markdown index 14b45d31..c5bf617a 100644 --- a/montilang.html.markdown +++ b/montilang.html.markdown @@ -93,7 +93,7 @@ the string is used as an input prompt #/ /# FOR loops have the syntax 'FOR [condition] [commands] ENDFOR' At the moment, [condition] can only have the value of an integer. Either by using an integer, or a variable call to an integer. -[commands] will be interpereted the amount of time specified in [condition] #/ +[commands] will be interpreted the amount of time specified in [condition] #/ /# E.G: this prints out 1 to 10 #/ 1 VAR a . @@ -153,7 +153,7 @@ DEF printseven ENDFOR ENDDEF -/# to run the defined statement, simply type it and it will be run by the interpereter #/ +/# to run the defined statement, simply type it and it will be run by the interpreter #/ printseven From 29240ce53d48818f4a3e94488856745dfaee1611 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 24 Aug 2024 22:09:57 +0200 Subject: [PATCH 312/392] [bf/de-de] Fix typos, spelling and grammar (#5045) --- de-de/bf-de.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/bf-de.html.markdown b/de-de/bf-de.html.markdown index 11d12a23..ae7d7007 100644 --- a/de-de/bf-de.html.markdown +++ b/de-de/bf-de.html.markdown @@ -29,10 +29,10 @@ Es gibt acht Befehle: < : Bewegt den Zeiger um eine Stelle zurück. . : Gibt den Wert der aktuellen Zelle als ASCII Wert aus (z.B. 65 = 'A'). , : Liest ein einzelnes Zeichen von der Standardeingabe und speichert dessen ASCII Wert in der aktuellen Zelle. -[ : Wenn der Wert des aktuellen Elements Null ist, bewege des Zeiger hinter den +[ : Wenn der Wert des aktuellen Elements Null ist, bewege den Zeiger hinter den zugehörigen ]-Befehl. Ansonsten, bewege den Zeiger ein Element weiter. -] : Wenn der Wert des aktuellen Elements Null ist, bewege des Zeiger um eine Stelle +] : Wenn der Wert des aktuellen Elements Null ist, bewege den Zeiger um eine Stelle weiter. Ansonsten, bewege den Zeiger hinter den zugehörigen [-Befehl. @@ -51,7 +51,7 @@ und das Programm hinter dem korrespondierenden ] fortgesetzt). An dieser Stelle befinden wir uns an Zelle #1, die jetzt den Wert 0 hat, während Zelle #2 den Wert 60 hat. Wir gehen vor zu Zelle #2, inkrementieren 5 Mal, bis zum Wert 65, -und geben dann den Wert der Zelle #2 aus. 65 ist ein 'A' im ASCII Zeichensatz, +und geben dann den Wert der Zelle #2 aus. 65 ist ein 'A' im ASCII-Zeichensatz, daher wird 'A' am Terminal ausgegeben.. @@ -61,7 +61,7 @@ Dieses Programm liest ein Zeichen von der Benutzereingabe und schreibt dessen We in Zelle #1. Danach beginnt eine Schleife. Rücke vor auf Zelle #2, erhöhe den Wert der Zelle #2, gehe zurück auf Zelle #1, verringere den Wert der Zelle #1. Dies geht so lange bis Zelle #1 den Wert 0 und Zelle #2 den alten Wert aus #1 hat. Da wir am Ende der Schleife -bie Zelle #1 sind, gehe vor zu Zelle #2 und gibt den Wert als ASCII Zeichen aus. +bei Zelle #1 sind, gehe vor zu Zelle #2 und gibt den Wert als ASCII Zeichen aus. Beachte bitte, dass die Leerzeichen nur aus Gründen der Lesbarkeit geschrieben werden. Man könnte genauso schreiben: From 555e65574954a5e284e99c6c962afb17c24c654b Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 24 Aug 2024 22:10:31 +0200 Subject: [PATCH 313/392] [sql/de-de] Fix typos, spelling and grammar (#5046) --- de-de/sql-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/sql-de.html.markdown b/de-de/sql-de.html.markdown index 4d0ddf49..2d7d11d3 100644 --- a/de-de/sql-de.html.markdown +++ b/de-de/sql-de.html.markdown @@ -8,10 +8,10 @@ translators: lang: de-de --- -Die Structured Query Language (SQL) ist eine ISO Standardsprache zum Erstellen und Arbeiten mit Datenbanken, die in einem Set von Tabellen gespeichert sind. Implementiereungen fügen in der Regel eigene Erweiterungen zur Sprache hinzu; [Der Vergleich von verschiedenen SQL Implementierungen](http://troels.arvin.dk/db/rdbms/) ist eine gute Referenz für Produktunterschiede. +Die Structured Query Language (SQL) ist eine ISO Standardsprache zum Erstellen und Arbeiten mit Datenbanken, die in einem Set von Tabellen gespeichert sind. Implementierungen fügen in der Regel eigene Erweiterungen zur Sprache hinzu; [Der Vergleich von verschiedenen SQL Implementierungen](http://troels.arvin.dk/db/rdbms/) ist eine gute Referenz für Produktunterschiede. Implementierungen bieten typischerweise eine Eingabeaufforderung, in den du die hier gezeigten Befehle interaktiv eingeben kannst. Sie bieten auch einen Weg, um Serien von Befehlen in einer Skript auszuführen. (Die Anzeige, dass du fertig mit der interaktiven Eingabeaufforderung bist, ist ein gutes Beispiel für etwas, was nicht standardisiert ist. Die meisten SQL Implementierungen unterstützen die Schlüsselwörter QUIT, EXIT oder beides. -Einige dieser Beispielbefehle gehen davon aus, dass sie die [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/), verfügbar auf [GitHub](https://github.com/datacharmer/test_db), schon geladen wurde. Die GitHub Dateien sind Skripte von Befehlen, ähnlich wie die entsprechenden Befehle unten, die Tabellen mit Daten über die Mitarbeiter einer fiktionale Firma erstellen und füllen. Die Syntax für die Ausführung dieser Skripte hängt von der verwendeten SQL-Implementierung ab. Ein Dienstprogramm, das man über die Betriebssystemeingabeaufforderung ausführen kann, ist typisch. +Einige dieser Beispielbefehle gehen davon aus, dass sie die [MySQL employee sample database](https://dev.mysql.com/doc/employee/en/), verfügbar auf [GitHub](https://github.com/datacharmer/test_db), schon geladen wurde. Die GitHub Dateien sind Skripte von Befehlen, ähnlich wie die entsprechenden Befehle unten, die Tabellen mit Daten über die Mitarbeiter einer fiktiven Firma erstellen und füllen. Die Syntax für die Ausführung dieser Skripte hängt von der verwendeten SQL-Implementierung ab. Ein Dienstprogramm, das man über die Betriebssystemeingabeaufforderung ausführen kann, ist typisch. ```sql @@ -19,7 +19,7 @@ Einige dieser Beispielbefehle gehen davon aus, dass sie die [MySQL employee samp -- SQL unterscheidet nicht zwischen Groß- und Kleinschreibung bei -- Schlüsselwörtern. Die Beispielbefehle folgen der Konvention der --- Schreibweise in Großbuchstaben, damit sie leichter von Datebank-, +-- Schreibweise in Großbuchstaben, damit sie leichter von Datenbank-, -- Tabellen- und Spaltennamen zu unterscheiden sind. -- Erstellen und Löschen einer Datenbank. Bei Datenbank- und Tabellennamen @@ -70,11 +70,11 @@ SELECT COUNT(*) FROM departments; -- Teilezeichenkette des Wertes dept_name haben. SELECT COUNT(*) FROM departments WHERE dept_name LIKE '%en%'; --- Eine Vereinigung von Informatione von mehreren Tabellen: +-- Eine Vereinigung von Informationen von mehreren Tabellen: -- Die titles Tabelle zeigt, wer welche Jobtitel hatte, wer welche Mitarbeiter- -- nummer hat, von welchen Startdatum und zu welchen Enddatum -- Wir rufen diese Information ab, aber anstelle der Mitarbeiternummer, --- verwenden wir die Mitarbeiternummer als Querverweis auf die empoyees Tabelle +-- verwenden wir die Mitarbeiternummer als Querverweis auf die employees Tabelle -- um die die Vor- und Nachnamen jedes Mitarbeiters zu erhalten. -- (und nur 10 Reihen) SELECT employees.first_name, employees.last_name, From f1c0815916170c8d5cbf21cfabc7264ff5517b88 Mon Sep 17 00:00:00 2001 From: Mukund Kukreja <103610317+mk3-20@users.noreply.github.com> Date: Sun, 25 Aug 2024 01:43:09 +0530 Subject: [PATCH 314/392] [powershell/en] Fixed typo variable name (#5044) --- powershell.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/powershell.html.markdown b/powershell.html.markdown index 5116fac8..775c17e0 100644 --- a/powershell.html.markdown +++ b/powershell.html.markdown @@ -126,7 +126,7 @@ $a = (1,2,3,4) $b = $a # => Point b at what a is pointing to $b -is $a.GetType() # => True, a and b equal same type $b -eq $a # => None! See below -[System.Collections.Hashtable]$b = @{} # => Point a at a new hash table +[System.Collections.Hashtable]$b = @{} # => Point b at a new hash table $b = @{'one' = 1 'two' = 2} $b -is $a.GetType() # => False, a and b types not equal From 238ddc43e11f10e19190c65de1cf0efab4b1a697 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 25 Aug 2024 18:45:47 +0200 Subject: [PATCH 315/392] [tcl/de-de] Fix typos (#5049) --- de-de/tcl-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/tcl-de.html.markdown b/de-de/tcl-de.html.markdown index 0adcb07c..e75ce0aa 100644 --- a/de-de/tcl-de.html.markdown +++ b/de-de/tcl-de.html.markdown @@ -40,7 +40,7 @@ Verschiedenste herausragende Fähigkeiten von Tcl: Wenn Lisp ein Listen-Prozessor ist, dann ist TCl ein Zeichenketten-Prozessor. Alle Werte sind Zeichenketten. Eine Liste ist ein Zeichenketten-Format. Eine Prozedur-Definition ist ein Zeichenketten-Format. Um leistungsfähig zu sein, -werden Tcl-intern diese Zeichenketten in Strukutierter-Form gepuffert. Ein +werden Tcl-intern diese Zeichenketten in Strukturierter-Form gepuffert. Ein Beispiel: Der "list" Befehl arbeitet mit diesen internen gepufferten Repräsentationen. Tcl kümmert sich selbständig darum die String-Repräsentationen zu aktualisieren, falls dies im Skript benötigt werden sollten. Das Kopieren- @@ -318,7 +318,7 @@ set amount [lindex $amounts 1] # Werte in einer Liste zu formatieren. Eine Liste sieht aus wie ein Skript, # allerdings verlieren verlieren Zeilenumbrüche und Doppelüunkte ihre # besondere Bedeutung. Diese Funktionalität macht Tcl homoikonisch. Die -# folgende Liste enhtält drei Elemente. +# folgende Liste enthält drei Elemente. set values { one\ two From a47199942a902d7a3293da4c75399c93bd05213b Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 25 Aug 2024 18:46:09 +0200 Subject: [PATCH 316/392] [shutit/de-de] Fix typo (#5048) --- de-de/shutit-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/shutit-de.html.markdown b/de-de/shutit-de.html.markdown index 611aac43..f71f2d68 100644 --- a/de-de/shutit-de.html.markdown +++ b/de-de/shutit-de.html.markdown @@ -322,7 +322,7 @@ Um mehr zu erfahren, siehe: [ShutIt](https://ianmiell.github.io/shutit/) [GitHub](https://github.com/ianmiell/shutit/blob/master/README.md) -Es handelt sich um ein breiteres Automatiesierungsframework, und das oben +Es handelt sich um ein breiteres Automatisierungsframework, und das oben sogenannte ist der sogennante 'standalone Modus'. Feedback, feature requests, 'Wie mache ich es' sind herzlich willkommen! Erreiche mit unter From cb5aabe5cfc0ea288dc06a556d49157c7ccfb305 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 25 Aug 2024 18:50:53 +0200 Subject: [PATCH 317/392] [yaml/de-de] Fix typo (#5047) --- de-de/yaml-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index 94fb4ea8..bdbfee23 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -20,7 +20,7 @@ YAML ist eine Erweiterung von JSON mit der Erweiterung um syntaktisch wichtige Z ################# # Unser Kernobjekt (für das ganze Dokument) wird das Assoziative Datenfeld (Map) sein, -# welches equivalent zu einem Hash oder einem Objekt einer anderen Sprache ist. +# welches äquivalent zu einem Hash oder einem Objekt einer anderen Sprache ist. Schlüssel: Wert nochn_Schlüssel: Hier kommt noch ein Wert hin. eine_Zahl: 100 From 7052adf4cbbf353711b375d1b26516809238678e Mon Sep 17 00:00:00 2001 From: rainmodred Date: Sun, 25 Aug 2024 19:56:30 +0300 Subject: [PATCH 318/392] [go] Fix docs link (#5043) --- fi-fi/go-fi.html.markdown | 2 +- go.html.markdown | 2 +- it-it/go-it.html.markdown | 2 +- uk-ua/go-ua.html.markdown | 4 ++-- zh-cn/go-cn.html.markdown | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/fi-fi/go-fi.html.markdown b/fi-fi/go-fi.html.markdown index 6a966e46..192a7fce 100644 --- a/fi-fi/go-fi.html.markdown +++ b/fi-fi/go-fi.html.markdown @@ -189,7 +189,7 @@ func learnFlowControl() { // Tapaukset eivät "tipu läpi". /* Kuitenkin meillä on erikseen `fallthrough` -avainsana. Katso: - https://github.com/golang/go/wiki/Switch#fall-through + https://go.dev/wiki/Switch#fall-through */ case 43: // Saavuttamaton. diff --git a/go.html.markdown b/go.html.markdown index 20f3adda..731ccba8 100644 --- a/go.html.markdown +++ b/go.html.markdown @@ -223,7 +223,7 @@ func learnFlowControl() { // Cases don't "fall through". /* There is a `fallthrough` keyword however, see: - https://github.com/golang/go/wiki/Switch#fall-through + https://go.dev/wiki/Switch#fall-through */ case 43: // Unreached. diff --git a/it-it/go-it.html.markdown b/it-it/go-it.html.markdown index 6f974c91..63dc748e 100644 --- a/it-it/go-it.html.markdown +++ b/it-it/go-it.html.markdown @@ -451,4 +451,4 @@ Go Mobile aggiunge il supporto per lo sviluppo mobile (Android e iOS). In questo modo è possibile scrivere un'app mobile nativa in Go, oppure una libreria che contiene binding da un package scritto in Go, e che può essere richiamata da Java(Android) e Objective-C(iOS). Visita la pagina di -[Go Mobile](https://github.com/golang/go/wiki/Mobile) per maggiori informazioni. +[Go Mobile](https://go.dev/wiki/Mobile) per maggiori informazioni. diff --git a/uk-ua/go-ua.html.markdown b/uk-ua/go-ua.html.markdown index 6f294b1f..15e6662f 100644 --- a/uk-ua/go-ua.html.markdown +++ b/uk-ua/go-ua.html.markdown @@ -193,7 +193,7 @@ func learnFlowControl() { case 1: case 42: // Кейси не "провалюються". Натомість, є ключове слово `fallthrough`: - // https://github.com/golang/go/wiki/Switch#fall-through (англ) + // https://go.dev/wiki/Switch#fall-through (англ) case 43: // Недоступний. default: @@ -446,4 +446,4 @@ func requestServer() { Іншим прекрасним посиланням для вивчення Go є [Go by example](https://gobyexample.com/). -Go Mobile додає підтримку мобільних платформ (Android та iOS). Можна написати нативний код на Go для мобільних застосунків або написати бібліотеку, що міститиме прив'язки (bindings) з пакету Go, які можуть бути викликані з Java (Android) та Objective-C (iOS). Деталі можна дізнатись на [веб-сторінці Go Mobile](https://github.com/golang/go/wiki/Mobile). +Go Mobile додає підтримку мобільних платформ (Android та iOS). Можна написати нативний код на Go для мобільних застосунків або написати бібліотеку, що міститиме прив'язки (bindings) з пакету Go, які можуть бути викликані з Java (Android) та Objective-C (iOS). Деталі можна дізнатись на [веб-сторінці Go Mobile](https://go.dev/wiki/Mobile). diff --git a/zh-cn/go-cn.html.markdown b/zh-cn/go-cn.html.markdown index a2b71761..2d378860 100644 --- a/zh-cn/go-cn.html.markdown +++ b/zh-cn/go-cn.html.markdown @@ -406,4 +406,4 @@ func requestServer() { -Go Mobile添加了对移动平台的支持(Android and iOS)。你可以完全用go语言来创造一个app或编写一个可以从Java或Obj-C调用的函数库,敬请参考[Go Mobile page](https://github.com/golang/go/wiki/Mobile)。 +Go Mobile添加了对移动平台的支持(Android and iOS)。你可以完全用go语言来创造一个app或编写一个可以从Java或Obj-C调用的函数库,敬请参考[Go Mobile page](https://go.dev/wiki/Mobile)。 From 2b3dfab1465aba0e73a376dde54be70b887828c6 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 25 Aug 2024 22:19:56 +0200 Subject: [PATCH 319/392] Fix typo --- de-de/nix-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/nix-de.html.markdown b/de-de/nix-de.html.markdown index e79c1cc3..b75cac8f 100644 --- a/de-de/nix-de.html.markdown +++ b/de-de/nix-de.html.markdown @@ -222,7 +222,7 @@ with builtins; [ ({ a = 1; b = 2; } // { a = 3; c = 4; }) #=> { a = 3; b = 2; c = 4; } - # Das Schlüsselwort rec bezeichenet ein "rekursives Set", in dem sich Attribute + # Das Schlüsselwort rec bezeichnet ein "rekursives Set", in dem sich Attribute # aufeinander beziehen können. (let a = 1; in { a = 2; b = a; }.b) #=> 1 From c0f47f89cd845bb4178a955d7906e69930c8f573 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 26 Aug 2024 22:10:32 +0200 Subject: [PATCH 320/392] [lua/de-de] Fix typos (#5051) --- de-de/lua-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown index b4b5f2c1..f22f225a 100644 --- a/de-de/lua-de.html.markdown +++ b/de-de/lua-de.html.markdown @@ -29,11 +29,11 @@ t = "Doppelte Anführungszeichen sind auch OK" u = [[ Doppelte eckige Klammern beginnen und beenden mehrzeilige Zeichenketten.]] -t = nil -- Undefineren von t; Lua hat einen Garbage Collection. +t = nil -- Undefinieren von t; Lua hat einen Garbage Collection. -- Blöcke werden durch Schlüsselwörter wie do/end markiert: while num < 50 do - num = num + 1 -- Es gibt Keine Operatoren wie ++ oder += + num = num + 1 -- Es gibt keine Operatoren wie ++ oder += end -- If Bedingungen: @@ -72,7 +72,7 @@ for i = 1, 100 do -- Ein Bereich inkludiert beide Enden. karlSum = karlSum + i end --- Verwende "100, 1, -1" als Breich für Countdowns: +-- Verwende "100, 1, -1" als Bereich für Countdowns: fredSum = 0 for j = 100, 1, -1 do fredSum = fredSum + j end @@ -161,7 +161,7 @@ print(t.key1) -- Ausgabe 'value1'. t.newKey = {} -- Neues Schlüssel/Wert-Paar hinzufügen. t.key2 = nil -- key2 aus der Tabelle entfernen. --- Literale notation für jeden (nicht-nil) Wert als Schlüssel: +-- Literale Notation für jeden (nicht-nil) Wert als Schlüssel: u = {['@!#'] = 'qbert', [{}] = 1729, [6.28] = 'tau'} print(u[6.28]) -- Ausgabe "tau" @@ -171,7 +171,7 @@ a = u['@!#'] -- Nun ist a = 'qbert'. b = u[{}] -- Wir würden 1729 erwarten, aber es ist nil: -- b = nil weil der Lookup fehlschlägt. Er schlägt Fehl, weil der Schlüssel -- den wir verwendet haben nicht das gleiche Objekt ist das wir verwendet --- haben um den original Wert zu speichern. Zahlen und Zeichnkette sind daher +-- haben um den original Wert zu speichern. Zahlen und Zeichenkette sind daher -- die praktischeren Schlüssel. -- Eine Funktion mit nur einem Tabellen-Parameter benötigt keine Klammern. From 7fd1d03feff0929921942e652197c840059d49c1 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Tue, 27 Aug 2024 20:45:15 +0200 Subject: [PATCH 321/392] [lua/de-de] Fix typos (#5055) --- de-de/lua-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown index f22f225a..5564cd79 100644 --- a/de-de/lua-de.html.markdown +++ b/de-de/lua-de.html.markdown @@ -269,10 +269,10 @@ eatenBy = myFavs.animal -- Funktioniert dank Metatabelle! -- 3.2 Klassen-Artige Tabellen und Vererbung. -------------------------------------------------------------------------------- --- Klassen sind in Lua nicht eingebaut. Es gibt verschieden Wege sie mithilfe +-- Klassen sind in Lua nicht eingebaut. Es gibt verschiedene Wege sie mithilfe -- von Tabellen und Metatabellen zu erzeugen. --- Die Erklärund des Beispiels erfolgt unterhalb. +-- Die Erklärung des Beispiels erfolgt unterhalb. Dog = {} -- 1. @@ -419,7 +419,7 @@ Wichtige Themen die hier nicht angesprochen wurden; die Standard-Bibliotheken: * [`io` library](http://lua-users.org/wiki/IoLibraryTutorial) * [`os` library](http://lua-users.org/wiki/OsLibraryTutorial) -Übrigends, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und +Übrigens, die gesamte Datei ist gültiges Lua. Speichere sie als learn.lua und starte sie als "`lua learn.lua`" ! Die Erstfassung ist von tylerneylon.com, und ist auch hier verfügbar: [GitHub gist](https://gist.github.com/tylerneylon/5853042). Viel Spaß mit Lua! From f0eb9dbebd27020b3b9b0a6af7c7ddf092324429 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 28 Aug 2024 15:51:50 +0200 Subject: [PATCH 322/392] Fix typo (#5056) --- sorbet.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sorbet.html.markdown b/sorbet.html.markdown index 9c2e809b..5c93b356 100644 --- a/sorbet.html.markdown +++ b/sorbet.html.markdown @@ -913,7 +913,7 @@ module ValueSet # options. Especially when starting out with Sorbet, it may not be practical # to refactor the code to use `T::Enum`. In this case, you can use `T.enum`. # - # Note: Sorbet can't check this statically becuase it doesn't track the + # Note: Sorbet can't check this statically because it doesn't track the # values themselves. sig do params( From 546b5a9e5ce7504889ce406f1f03e5bbf414566c Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 28 Aug 2024 15:57:24 +0200 Subject: [PATCH 323/392] Fix typo (#5057) --- sing.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sing.html.markdown b/sing.html.markdown index 50b52390..b455c0fe 100644 --- a/sing.html.markdown +++ b/sing.html.markdown @@ -243,8 +243,8 @@ private: // How to declare a member function fn AClass.is_ready() bool { - // inside a member function, members can be accessed thrugh the - // this keyword and the field selector '.' + // inside a member function, members can be accessed through the + // 'this' keyword and the field selector '.' return(this.public_var > 10); } From 4e4f47cd8ec5266f60741670b217c880c2deefab Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 28 Aug 2024 16:17:05 +0200 Subject: [PATCH 324/392] [elm/de-de] Fix typo (#5059) --- de-de/elm-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown index 50cdbcc4..a7fe20a9 100644 --- a/de-de/elm-de.html.markdown +++ b/de-de/elm-de.html.markdown @@ -189,7 +189,7 @@ listLength aList = -- Klammern bietet die Möglichkeit der Bevorrangung. cos (degrees 30) ^ 2 + sin (degrees 30) ^ 2 -- 1 -- Als erstes wird die Funktion "degrees" mit dem Wert 30 aufgerufen. --- Danach wird das Ergenis davon den Funktionen "cos", bzw. "sin" übergeben. +-- Danach wird das Ergebnis davon den Funktionen "cos", bzw. "sin" übergeben. -- Dann wird das Ergebnis davon mit 2 quadriert und als letztes werden diese -- beiden Werte dann addiert. From 65d8f4221bce23d2a87c7779085f2df4687cdd18 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 28 Aug 2024 16:17:15 +0200 Subject: [PATCH 325/392] [qml/en] Fix typo (#5058) --- qml.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qml.html.markdown b/qml.html.markdown index 78e94d66..63b49d61 100644 --- a/qml.html.markdown +++ b/qml.html.markdown @@ -167,7 +167,7 @@ Window { Rectangle { // Since this rectangle is not created by the ListView, the attached - // type is not avaiable. + // type is not available. color: ListView.isCurrentItem ? "green" : "red" } From 27c5e6bae0007d4c8a36db0947194a96698a5943 Mon Sep 17 00:00:00 2001 From: chupson Date: Thu, 29 Aug 2024 13:17:40 +0200 Subject: [PATCH 326/392] [zig/en] Remove incorrect comment in enum section (#5061) * [zig/en] Remove incorrect comment in enum section Remove a comment in the enum section since it incorrectly says a code snippet won't compile * [zig/en] Add comment to enum section --- zig.html.markdown | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/zig.html.markdown b/zig.html.markdown index 4046ae43..68bff9ac 100644 --- a/zig.html.markdown +++ b/zig.html.markdown @@ -588,9 +588,7 @@ const x = switch (direction) { .South => true, }; - -// Switch statements need exhaustiveness. -// Won't compile: East and West are missing. +// This compiles without errors, since it exhaustively lists all possible values const x = switch (direction) { .North => true, .South => true, From 1e2f2e716cd50661e5a19caee634fd37e478cfb7 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 05:12:38 +0200 Subject: [PATCH 327/392] [sql/de-de] Fix typo (#5067) --- de-de/sql-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/sql-de.html.markdown b/de-de/sql-de.html.markdown index 2d7d11d3..b9705269 100644 --- a/de-de/sql-de.html.markdown +++ b/de-de/sql-de.html.markdown @@ -88,7 +88,7 @@ FROM titles INNER JOIN employees ON SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE'; --- Erstelle eine Tabelle in der aktuell verwedeten Datenbank +-- Erstelle eine Tabelle in der aktuell verwendeten Datenbank -- mit dem Namen tablename1, in der die beiden Spalten angezeigt werden -- Es gibt viele weiteren Optionen, wie man die Spalten spezifizieren kann, -- wie z.B. deren Datentyp. From 683d9f848b419fb94251c632d7c97d3aca5c44db Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 05:12:46 +0200 Subject: [PATCH 328/392] [processing/de-de] Fix typos (#5066) --- de-de/processing-de.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/processing-de.html.markdown b/de-de/processing-de.html.markdown index 707940db..78131ee7 100644 --- a/de-de/processing-de.html.markdown +++ b/de-de/processing-de.html.markdown @@ -34,7 +34,7 @@ offiziellen IDE, damit die Programme kompiliert und ausgeführt werden können. /* Da Processing von Java abstammt, ist die Syntax für Kommentare gleich wie bei Java (wie du vielleicht oben bemerkt hast)! - Mehrzeilige Kommentare werden wie hier umschloßen. + Mehrzeilige Kommentare werden wie hier umschlossen. */ /* ------------------------------------------------- @@ -107,7 +107,7 @@ double doubleValue = 1.12345D // Double (64-Bit Gleitkommazahl) // lediglich die wichtigsten durch. // String -// Während der Datentyp `char` einfache Anzührungszeichen (' ') braucht, haben +// Während der Datentyp `char` einfache Anführungszeichen (' ') braucht, haben // Strings doppelte Anführungszeichen (" "). String sampleString = "Hallo, Processing!"; // Strings können auch durch ein Array von `char`s erstellt werden. @@ -405,7 +405,7 @@ Wenn du weitere Dinge mit Processing kennenlernen willst, dann gibt es unzählig Dinge, welche du mit Processing machen kannst. Das Rendern von Modellen, Schattierungen und viele mehr. Für ein kurzes Tutorial bietet Processing zu viel, daher verweise ich dich, falls du interessiert bist, auf die offizielle -Dokumentaion. +Dokumentation. ``` // Bevor wir weiterfahren, werde ich einige Aspekte zum Importieren von @@ -431,7 +431,7 @@ was man in Processing mit nur wenigen Zeilen Code machen kann. Kopiere den nachfolgenden Code in deine Processing IDE. ``` -// Disclaimer: Ich habe das Porgramm nicht selbst geschriben. Diese Skizze +// Disclaimer: Ich habe das Programm nicht selbst geschrieben. Diese Skizze // stammt aus openprocessing, allerdings soll dieses Programm zeigen, wie wenig // Zeilen Code notwendig sind, um etwas Cooles zu machen. // Abgerufen von: (https://www.openprocessing.org/sketch/559769) From c5ab7e679e6a56d8af9dfae6878995ba7ddd439a Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 05:12:53 +0200 Subject: [PATCH 329/392] [html/de-de] Fix typos (#5065) --- de-de/html-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/html-de.html.markdown b/de-de/html-de.html.markdown index 79bdbb8e..7bb2802d 100644 --- a/de-de/html-de.html.markdown +++ b/de-de/html-de.html.markdown @@ -10,7 +10,7 @@ lang: de-de HTML steht für HyperText Markup Language (Hypertext-Auszeichnungssprache). Sie ist eine Sprache, um Seiten für das World Wide Web zu schreiben. -Es ist eine Auszeichnugssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien. +Es ist eine Auszeichnungssprache, die es uns ermöglicht Webseiten mithilfe des Codes zu schreiben, der kennzeichnet wie Text und Daten angezeigt werden sollen. Eigentlich sind HTML Dateien nur einfache Textdateien. Was sind das für Auszeichnungen? Es ist eine Methode, um die Daten der Website zu organisieren mithilfe von Start- und Endtags. Diese Auszeichnung dient dazu dem Text Bedeutung zu geben, welchen sie umschließt. Wie viele andere Computersprachen auch, besitzt HTML viele Versionen. Wir werden hier über HTML5 reden. @@ -65,7 +65,7 @@ Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben - + @@ -95,7 +95,7 @@ Dieser Artikel ist bedacht darauf, nur HTML Syntax und nützliche Tipps zu geben

      - + From b0c0ab24d2a9a564490fbc2403b49edb35dd93f3 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 05:12:59 +0200 Subject: [PATCH 330/392] [javascript/de-de] Fix typos (#5064) --- de-de/javascript-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index 3dc5b532..b01e8e0a 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -200,7 +200,7 @@ while (true) { // Eine unendliche Schleife! } -// Do-while-Scheifen arbeiten wie while-Schleifen, abgesehen davon, dass sie +// Do-while-Schleifen arbeiten wie while-Schleifen, abgesehen davon, dass sie // immer mindestens einmal ausgeführt werden. var input; do { @@ -370,7 +370,7 @@ var anotherFunc = function(s){ } anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" -// 'apply' funktioniert beiahe identisch, erwartet die übergebenen Argumente +// 'apply' funktioniert beinahe identisch, erwartet die übergebenen Argumente // aber in einem Array anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" From b8efa05f34236bff8b4d2c6de32572573a890ae0 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 05:13:06 +0200 Subject: [PATCH 331/392] [hack/de-de] Fix typo (#5063) --- de-de/hack-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/hack-de.html.markdown b/de-de/hack-de.html.markdown index 6e9b9da3..88882280 100644 --- a/de-de/hack-de.html.markdown +++ b/de-de/hack-de.html.markdown @@ -317,5 +317,5 @@ besuchen. Die offizielle Webseite [hhvm.com](http://hhvm.com/) bietet Infos zum Download und zur Installation der HHVM. -Hack's [nicht-untersützte PHP Syntax-Elemente](http://docs.hhvm.com/manual/en/hack.unsupported.php) +Hack's [nicht-unterstützte PHP Syntax-Elemente](http://docs.hhvm.com/manual/en/hack.unsupported.php) werden im offiziellen Handbuch beschrieben. From 0b2e2575c1e3e578aa61a0fb8775e54a1ba6c903 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 05:13:51 +0200 Subject: [PATCH 332/392] [asciidoc/de-de] Fix typos (#5042) --- de-de/asciidoc-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/asciidoc-de.html.markdown b/de-de/asciidoc-de.html.markdown index f375d656..df0347e0 100644 --- a/de-de/asciidoc-de.html.markdown +++ b/de-de/asciidoc-de.html.markdown @@ -8,8 +8,8 @@ filename: asciidoc-de.adoc lang: de-de --- -AsciiDoc ist eine Auszeichnungssprache, ähnlich zu Markdown. Sie kann für alles -verwendet werden von Büchern zu Blogs. Erfunden wurde sie 2002 von Stuart +AsciiDoc ist eine Auszeichnungssprache, ähnlich wie Markdown. Sie kann für alles +verwendet werden von Büchern bis zu Blogs. Erfunden wurde sie 2002 von Stuart Rackham. Die Sprache ist simpel, aber sie ermöglicht eine große Anzahl an Anpassungen. From 065116cdd544ba13d774f448368021ce680bdd27 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 05:14:23 +0200 Subject: [PATCH 333/392] [linker/en] Fix untranslated text (#5040) --- linker.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/linker.html.markdown b/linker.html.markdown index 40ad7020..e46ab65f 100644 --- a/linker.html.markdown +++ b/linker.html.markdown @@ -148,7 +148,7 @@ SECTIONS _sdata = .; # We indicate that in this section the .data areas of all - # объектных файлов + # object files *(.data) *(.data*) From 6dc0d4c0ca084ae98360b049ba7f0166baf77bd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Emre=20Kadir=20Karag=C3=B6z?= <63540157+R1cHero@users.noreply.github.com> Date: Fri, 30 Aug 2024 06:25:04 +0300 Subject: [PATCH 334/392] [GDScript/tr-tr] translate (#5012) --- tr-tr/gdscript-tr.html.markdown | 372 ++++++++++++++++++++++++++++++++ 1 file changed, 372 insertions(+) create mode 100644 tr-tr/gdscript-tr.html.markdown diff --git a/tr-tr/gdscript-tr.html.markdown b/tr-tr/gdscript-tr.html.markdown new file mode 100644 index 00000000..91be0327 --- /dev/null +++ b/tr-tr/gdscript-tr.html.markdown @@ -0,0 +1,372 @@ +--- +language: GDScript +contributors: + - ["Wichamir", "https://github.com/Wichamir/"] + - ["zacryol", "https://github.com/zacryol"] +filename: learngdscript.gd +translators: + - ["R1cHero", "https://github.com/R1cHero"] +lang: tr-tr +--- + +GDScript, özgür ve açık kaynaklı oyun motoru olan Godot için dinamik ve statik olarak +yazılmış bir kodlama dilidir. Yazılış şekli Python'a biraz benzerdir. +Başlıca avantajları kullanım kolaylığı ve motorla olan uyumudur. +Oyun geliştirme için mükemmel bir uyum sağlar. + +## Temeller + +```gdscript +# Tek satırlık yorumlar, '#' simgesi kullanılarak yazılır. +""" + Çok + satırlı + yorumlar + üç + tırnak + kullanılarak + yazılır +""" + +# Belge yorumları (Doc Comments) sınıflara ve alanlara açıklama ekleyebilir. +# bunlar, motor içi dokümanlarda görüntülenebilir. + +## Bu sınıf, GDScript'in bir gösterimidir + +# Komut dosyası kendi başına bir sınıftır ve isteğe bağlı olarak bunun için bir ad tanımlayabilirsiniz. +class_name MyClass + +# Kalıtım (Inheritance) komut dosyasının bağlı olduğu Node'a göre 'Node2D' kısmı değişkenlik gösterir. +extends Node2D + +# Değişken türleri +var x = 8 # int +var y = 1.2 # float +var b = true # bool +var s = "Merhaba Dünya!" # String +var a = [1, false, "turuncu kedi"] # Array - Python'daki listeye benzer, + # aynı anda farklı tipte + # değişkenleri tutabilir. +var d = { + "key" : "value", + 42 : true +} # Sözlük anahtar-değer (key-value) çiftlerini tutar. +var p_arr = PackedStringArray(["Hey", "selamlar", "!"]) # Paketlenmiş diziler yalnızca + # belirli bir türü tutabilir. + +# Doküman yorumları, özelliklere uygulanabilir. + +## Bu değişken nesnenin kaç kez zıpladığını tutar. +var jump_count = 0 + +# Motorda bulunan yerleşik vektör türleri: +var v2 = Vector2(1, 2) +var v3 = Vector3(1, 2, 3) + +# Sabitler (Constants) +const ANSWER_TO_EVERYTHING = 42 +const BREAKFAST = "Sucuklu yumurta!" + +# Enumlar +enum { ZERO, ONE , TWO, THREE } +enum NamedEnum { ONE = 1, TWO, THREE } + +# Dışa aktarılan değişkenler 'inspector' de görünür. +# +# Editörün hangi seçenekleri vereceğini bilmesi için bir tür ipucu (daha sonra açıklanacaktır) +# veya varsayılan bir değere ihtiyaç vardır. +@export var age: int +@export var height: float +@export var person_name = "Ahmet" +# Ama ikisi de kabul edilebilir. +@export var favorite_color: String = "Kırmızı" +@export var favorite_food := "Lahmacun" + +# Fonksiyonlar +func foo(): + pass # pass anahtar sözcüğü gelecekteki yazılacak olan kod için bir yer tutucudur. + # Editörde hata olarak göstermesini engellemek için de kullanılır. + +func add(first, second): + return first + second + +# Fonksiyonlar üzerinde doküman yorumları yazma + +## Zıplama Sayısını Artırma +func jump(): + jump_count += 1 + +# Değerleri yazdırma +func printing(): + print("GDScript ", "mükemmel.") + prints("Bu", "kelimeler", "boşluklarla", "ayrıldı.") + printt("Bu", "kelimeler", "tablarla", "ayrıldı.") + printraw("Bu sistem konsoluna yazdırılır.") + printerr("Bu konsolda hata olarak gösterilir.") + + # İsimsiz fonksiyonlar (Lambdas) + var my_lambda = func(): print("lambda'dan merhaba!") + + my_lambda.call() + +# Matematik +func doing_math(): + var first = 8 + var second = 4 + print(first + second) # 12 + print(first - second) # 4 + print(first * second) # 32 + print(first / second) # 2 + print(first % second) # 0 + # Ayrıca bunlar var +=, -=, *=, /=, %= vb., + # ++ veya -- operatörleri yok. + print(pow(first, 2)) # 64 + print(sqrt(second)) # 2 + printt(PI, TAU, INF, NAN) # Yerleşik (built-in) sabitler (constants) + +# Kontrol akışı +func control_flow(): + x = 8 + y = 2 # y orjinalde float'dı, + # ancak "dynamic typing" gücünü kullanarak + # tipini int'e değiştirebiliriz! + + if x < y: + print("x, y'den küçüktür.") + elif x > y: + print("x, y'den büyüktür.") + else: + print("x ve y eşittir.") + + var a = true + var b = false + var c = false + if a and b or not c: # alternatif olarak bunları kullanabilirsiniz: &&, || ve ! + print("Değer: true") + + for i in range(20): # GDScript'de "range" Python'dakine benzerdir. + print(i) # bu 0'dan 19'a kadar sayıları yazdıracaktır. + + for i in 20: # Python'dan farklı olarak, doğrudan bir int üzerinde "range" kullanmadan döngüye girebilirsiniz. + print(i) # bu da 0'dan 19'a kadar olan sayıları da yazdıracaktır. + + for i in ["two", 3, 1.0]: # Bir dizi üzerinde yineleme (iterasyon) yapma. + print(i) + + while x > y: + printt(x, y) + y += 1 + + x = 2 + y = 10 + while x < y: + x += 1 + if x == 6: + continue # 6, "continue" ifadesi nedeniyle yazdırılmayacak. + prints("x eşittir:", x) + if x == 7: + break # döngü 7'de duracak, bu yüzden 8, 9 ve 10 yazdırılmayacak. + + match x: + 1: + print("Match, switch'e benzerdir.") + 2: + print("Ancak her değerden önce "case" koymanıza gerek yok.") + 3: + print("Ayrıca her "case" varsayılan olarak durdurulur.") + break # HATA! "Break" ifadesi gereksiz! + 4: + print("Eğer "fallthrough" kullanmaya ihtiyacınız varsa "continue" kullanın.") + continue + _: + print("Alt çizgi varsayılan bir "case"dir.") + + # Üç terimli operatör (tek satırda yazılabilen if-else) + prints("x", "pozitif" if x >= 0 else "negatif") + +# Bir veri tipini başka bir veri tipine dönüştürme (Casting) +func casting_examples(): + var i = 42 + var f = float(42) # Değişkenlerin kurucusunu (constructor) kullanarak + var b = i as bool # veya "as" anahtar kelimesini kullanarak tür dönüştürme (casting) + +# Override fonksiyonlar +# Built-in kurallı "overridable functions" bir alt çizgi ile başlar +# ama pratikte hemen hemen her fonksiyonu geçersiz kılabilirsiniz. + +# _init nesne başlatıldığında çağrılır. +# Bu, nesnenin kurucusudur (constructor). +func _init(): + # Burada nesnenin iç öğelerini başlatın. + pass + +# _ready, komut dosyasında +# node ve children node sahneye girdiğinde çağrılır. +func _ready(): + pass + +# _process her karede çağrılır. +func _process(delta): + # Bu fonksiyona iletilen delta argümanı, + # son kare ile anlık kare arasında geçen saniye sayısıdır. + print("Delta zamanı: ", delta) + +# _physics_process her fizik karesinde çağrılır. +# Deltanın sabit olması gerektiği anlamına gelir. +func _physics_process(delta): + # Vektör toplama ve çarpma kullanarak hareket ettirme. + var direction = Vector2(1, 0) # ya da Vector2.RIGHT + var speed = 100.0 + self.global_position += direction * speed * delta + # self geçerli sınıf örneğini belirtir. + +# Geçersiz kılma sırasında, buradaki gibi nokta operatörünü kullanarak +# parent işlevini çağırabilirsiniz: +func get_children(): + # Bazı ek şeyler ekleyebilirsiniz. + var r = super() # Parent implementasyonunu çağırma + return r + +# Dahili sınıflar (Inner class) +class InnerClass: + extends Object + + func hello(): + print("Dahili sınıftan merhabalar!") + +func use_inner_class(): + var ic = InnerClass.new() + ic.hello() + ic.free() # Ramde yer açmak için "free" kullanın. +``` + +## Sahne ağacındaki (Scene Tree) diğer node'lara erişim + +```gdscript +extends Node2D + +var sprite # Bu değişken referansı tutacak. + +# _ready'de diğer node'lara referanslar alabilirsiniz. +func _ready() -> void: + # "NodePath" node'lara erişmek için kullanışlıdır. + var path1 = NodePath("path/to/something") + # Ya da böyle kullanabilirsiniz: + var path2 = ^"path/to/something" + # NodePath örnekleri: + var path3 = ^"Sprite" # geçerli node'un child node'u + var path4 = ^"Timers/Firerate" # child node'un child node'u + var path5 = ^".." # geçerli node'un parent node'u + var path6 = ^"../Enemy" # geçerli node'un kardeşi + var path7 = ^"/root" # ana yol, get_tree().get_root() ile eşdeğerdir. + var path8 = ^"/root/Main/Player/Sprite" # Player'ın Sprite'ına giden ana yol + var path9 = ^"Timers/Firerate:wait_time" # özelliklere erişme + var path10 = ^"Player:position:x" # alt özelliklere erişim + + # Son olarak, referans almak için bunlardan birini kullanabilirsiniz: + sprite = get_node(^"Sprite") as Sprite # her zaman belirttiğiniz türü yazın + sprite = get_node("Sprite") as Sprite # burada String + # NodePath'e dönüştürülür + sprite = get_node(path3) as Sprite + sprite = get_node_or_null("Sprite") as Sprite + sprite = $Sprite as Sprite + +func _process(delta): + # Artık referansı başka yerlerde tekrar kullanabiliriz. + prints("Sprite has global_position of", sprite.global_position) + +# _ready çalıştırılmadan hemen önce +# bir değişkene değer atamak için @onready kullanın. +@onready var other_sprite = $Sprite as Sprite + +# NodePath'i dışa aktarabilir, böylece onu "inspector" içinde atama yapabilirsiniz. +@export var nodepath = ^"" +@onready var reference = get_node(nodepath) as Node + +# Veya Node'u doğrudan dışa aktarın +@export var other_reference: Node +``` + +## Sinyaller (Signals) + +Sinyal sistemi Godot'nun gözlemci programlama modelinin uygulamasıdır. +İşte bir örnek: + +```gdscript +class_name Player extends Node2D + +var hp = 10 + +# Belge yorumları sinyallere de yansıyabilir + +## Oyuncu öldüğünde sinyal gönderir (emit). +signal died() # sinyali tanımlama +signal hurt(hp_old, hp_new) # sinyallere değişken tanımlanabilir. + +func apply_damage(dmg): + var hp_old = hp + hp -= dmg + hurt.emit(hp_old, hp) # sinyal gönderme ve değişkenleri iletme + if hp <= 0: + died.emit() + +func _ready(): + # "died" sinyali kendi içinde tanımlanan "_on_death" fonksiyonuna bağlama + died.connect(_on_death) + # Hedef nesne kendisi değilse + # alternatif bir yol gerekir. + # died.connect(Callable(self, &"_on_death")) + +func _on_death(): + queue_free() # oyuncu öldüğünde sahneden siler +``` + +## Faydalı İpuçları + +GDScript'te hem kod netliği hem de performans avantajları için +opsiyonel olarak "static typing" kullanılabilir. + +```gdscript +extends Node + +var x: int # değişkenin türünü belirtme +var y: float = 4.2 +var z := 1.0 # ":=" operatörünü kullanmak üstteki tanımlama ile aynıdır. + +var a: Array[int] = [1, 2, 3] # Dizinin tür içeriğini belirtme + +enum NamedEnum { ONE = 1, TWO, THREE } +var n: NamedEnum = NamedEnum.ONE # Enum da bir tür olarak kullanılabilir. + +@onready var node_ref_typed := $Child as Node + +@export var speed := 50.0 + +const CONSTANT := "Bu bir sabit atamadır (constant)." + +signal example(arg: int) + +func _ready() -> void: + # fonksiyon hiçbir şey döndürmez + x = "string" # HATA! Tür değiştirilemez! + a.append("q") # HATA! Array[int] string tutamaz! + return + +func join(arg1: String, arg2: String) -> String: + # Fonksiyon iki tane string alır ve bir tane string döndürür. + return arg1 + arg2 + +func get_child_at(index: int) -> Node: + # Fonksiyon int alır ve node döndürür. + return get_children()[index] +``` + +## Daha fazla bilgi almak için + +* [Godot's Website](https://godotengine.org/) +* [Godot Docs](https://docs.godotengine.org/en/stable/) +* [Getting started with GDScript](https://docs.godotengine.org/en/stable/getting_started/scripting/gdscript/index.html) +* [NodePath](https://docs.godotengine.org/en/stable/classes/class_nodepath.html) +* [Signals](https://docs.godotengine.org/en/stable/getting_started/step_by_step/signals.html) +* [GDQuest](https://www.gdquest.com/) +* [GDScript.com](https://gdscript.com/) From ffb5b7988e1bb4e1ea734b86a71517e6f794cf7d Mon Sep 17 00:00:00 2001 From: OscarMaestre Date: Fri, 30 Aug 2024 05:27:27 +0200 Subject: [PATCH 335/392] [RST/es-es] translate (#5011) --- es-es/rst-es.html.markdown | 120 +++++++++++++++++++++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 es-es/rst-es.html.markdown diff --git a/es-es/rst-es.html.markdown b/es-es/rst-es.html.markdown new file mode 100644 index 00000000..58daab19 --- /dev/null +++ b/es-es/rst-es.html.markdown @@ -0,0 +1,120 @@ +--- +language: restructured text (RST) +contributors: + - ["DamienVGN", "https://github.com/martin-damien"] + - ["Andre Polykanine", "https://github.com/Oire"] +translators: + - ["Oscar Maestre", "http://www.github.com/OscarMaestre"] +filename: restructuredtext-es.rst +lang: es-es +--- + + +RST, de Restructured Text, es un formato de fichero creado por la comunidad Python para escribir documentación. Es parte del paquete [Docutils](https://docutils.sourceforge.io/rst.html). + +RST es un lenguaje de marcas similar a HTML pero mucho más ligero y fácil de leer. + +## Instalación. + +Para utilizar Restructured Text, tendrás que instalar [Python](http://www.python.org) y el paquete `docutils`. + +`docutils` puede instalarse con el siguiente comando. + +```bash +$ easy_install docutils +``` + +Si tu sistema tiene `pip`, también puedes utilizarlo para instalar `docutils`. + +```bash +$ pip install docutils +``` + + +## Sintaxis. + +Un ejemplo simple de sintaxis: + +``` +.. Las líneas que empiezan por un punto seguido de otro punto son comandos especiales. Si no se encuentra ningún comando, se considerará que esa línea es un comentario. + +======================================================================== +Los títulos principales se escriben usando el signo igual arriba y abajo +======================================================================== + +Observa que cada caracter, incluyendo los espacios, necesita un signo igual por encima y por debajo. + +Los títulos de nivel medio también usan el signo igual, pero solo por debajo +============================================================================= + + +Títulos de nivel más bajo con guiones +------------------------------------- + + +Puedes poner texto en *cursiva* o en **negrita.** También puedes "marcar" texto como código usando la doble comilla inversa, como ``print()``. + +Los caracteres especiales pueden "escaparse" usando el backslash, como \\ o \*. + +Las listas son similares a las de Markdown, pero un poquito más sofisticadas. + +Recuerda alinear los símbolos de lista (como - o \*) al margen izquierdo del anterior bloque de texto. Recuerda también usar líneas en blanco para separar listas nuevas de las listas padre: + + +- Primer elemento +- Segundo elemento + + - Subelemento + +- Tercer elemento + +o + +* Primer elemento +* Segundo elemento + + * Subelemento + +* Tercer elemento + +Las tablas son muy fáciles de escribir. + +=========== ======== +País Capital +=========== ======== +Francia París +Japón Tokyo +=========== ======== + +Se pueden elaborar fácilmente tablas más complejas (con columnas y/o filas fusionadas) pero para esto es recomendable leer el documento completo. :) + +Hay varias formas de construir enlaces: + +- Añadiendo un guión bajo al final de una palabra: GitHub_ y poniendo despues del texto la URL (esto tiene la ventaja de no insertar URLs innecesarias en el texto visible) +- Tecleando un URL completa : https://github.com/ (se convertirá automáticamente en enlace) +- Creando un link al estilo Markdown: `GitHub `_ . + +.. _GitHub: https://github.com/ +``` + + +## Como utilizarlo + +RST viene con el paquete `docutils` dentro del cual está el comando `rst2html`, por ejemplo: + +```bash +$ rst2html myfile.rst output.html +``` + +*Nota : En algunos sistemas el comando podría ser rst2html.py* + +Hay aplicaciones más complejas que usan el formato RST: + +- [Pelican](http://blog.getpelican.com/), un generador de sitios web estáticos. +- [Sphinx](http://sphinx-doc.org/), un generador de documentación. +- y muchos otros. + + +## Otras lecturas + +- [Referencia rápida oficial](http://docutils.sourceforge.net/docs/user/rst/quickref.html) From 564c7704f4f446051679b7cd3829a88bfcd52379 Mon Sep 17 00:00:00 2001 From: zsh2517 Date: Fri, 30 Aug 2024 11:27:53 +0800 Subject: [PATCH 336/392] [fish/all] Fix typos and mistakes (#5025) --- fish.html.markdown | 6 +++--- it-it/fish-it.html.markdown | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/fish.html.markdown b/fish.html.markdown index 66fc7661..2ad2cab2 100644 --- a/fish.html.markdown +++ b/fish.html.markdown @@ -71,7 +71,7 @@ or by opening the aforementioned web settings: Adding something to your fish PATH Variable is easy: ``` -> fish_path_add ~/cowsay +> fish_add_path ~/cowsay ``` Can you do that with bash, huh? No, you always have to look it up... It's just that easy! @@ -85,7 +85,7 @@ To get help, contact your local psychiatrist or type `man`. That will bring up t > man set ``` -If you finally tried fish, you can see something other in fish that's really cool. Everything has cool colors, if you type in something wrong, it is red, without even executing, if you put something in quotes, you see where it ends and why that quote doesn't work, because there's another qoutation mark in the quote at position 26. +If you finally tried fish, you can see something other in fish that's really cool. Everything has cool colors, if you type in something wrong, it is red, without even executing, if you put something in quotes, you see where it ends and why that quote doesn't work, because there's another quotation mark in the quote at position 26. fish has even more cool things, like wildcards. For example, type @@ -195,7 +195,7 @@ As with every shell, you can not only execute commands in the shell, but also as # Let's start with variables. # for use inside a program, you can use the syntax -set name = 'My Variable' +set name 'My Variable' # Use... set -x name value diff --git a/it-it/fish-it.html.markdown b/it-it/fish-it.html.markdown index 551b3339..8a803efb 100644 --- a/it-it/fish-it.html.markdown +++ b/it-it/fish-it.html.markdown @@ -73,7 +73,7 @@ o aprendo l'interfaccia web: Aggiungere qualcosa alla variabile PATH di fish è semplice: ``` -> fish_path_add ~/cowsay +> fish_add_path ~/cowsay ``` Questo puoi farlo con bash, eh? No, devi sempre cercarlo... Così è facile! @@ -197,7 +197,7 @@ Come per ogni shell, puoi non solo eseguire comandi nella shell, ma anche da fil # Cominciamo con le variabili. # per l'uso interno a un programma, puoi usare la sintassi -set nome = 'La mia variabile' +set nome 'La mia variabile' # Utilizzo... set -x nome valore From 17c33c33b5a38a0c7d83e697078df7ef6700181c Mon Sep 17 00:00:00 2001 From: sai Date: Fri, 30 Aug 2024 09:02:02 +0530 Subject: [PATCH 337/392] [javascript/*] Update Javascript Garden link (#4984) --- cs-cz/javascript.html.markdown | 2 +- de-de/javascript-de.html.markdown | 2 +- es-es/javascript-es.html.markdown | 2 +- fa-ir/javascript-fa.html.markdown | 2 +- fr-fr/javascript-fr.html.markdown | 2 +- it-it/javascript-it.html.markdown | 2 +- javascript.html.markdown | 2 +- ko-kr/javascript-kr.html.markdown | 2 +- ms-my/javascript-my.html.markdown | 2 +- pt-br/javascript-pt.html.markdown | 2 +- ta-in/javascript-ta.html.markdown | 2 +- tr-tr/javascript-tr.html.markdown | 2 +- uk-ua/javascript-ua.html.markdown | 2 +- zh-cn/javascript-cn.html.markdown | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/cs-cz/javascript.html.markdown b/cs-cz/javascript.html.markdown index 408ddde0..e882a8ec 100644 --- a/cs-cz/javascript.html.markdown +++ b/cs-cz/javascript.html.markdown @@ -620,7 +620,7 @@ na stránkách Mozilla Developer Network. [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core [4]: http://www.learneroo.com/modules/64/nodes/350 -[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[5]: https://shamansir.github.io/JavaScript-Garden/ [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [8]: http://eloquentjavascript.net/ diff --git a/de-de/javascript-de.html.markdown b/de-de/javascript-de.html.markdown index b01e8e0a..732b8ee2 100644 --- a/de-de/javascript-de.html.markdown +++ b/de-de/javascript-de.html.markdown @@ -515,7 +515,7 @@ MDN's [A re-introduction to JavaScript](https://developer.mozilla.org/en-US/docs Dieses Tutorial hat nur die Sprache JavaScript vorgestellt; um mehr über den Einsatz in Websites zu lernen, ist es ein guter Start etwas über das [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) zu lernen. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache. +[JavaScript Garden](https://shamansir.github.io/JavaScript-Garden/) ist eine tiefgehende Einführung in die kontra-intuitiven Parts der Sprache. [JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) ist ein Klassiker unter den Referenzen. diff --git a/es-es/javascript-es.html.markdown b/es-es/javascript-es.html.markdown index a70c5160..1d80d323 100644 --- a/es-es/javascript-es.html.markdown +++ b/es-es/javascript-es.html.markdown @@ -518,7 +518,7 @@ sobre el [DOM](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_ [Aprende JavaScript con ejemplos y retos](http://www.learneroo.com/modules/64/nodes/350) es una variante de esta guía pero con retos. -[Jardín JavaScript](http://bonsaiden.github.io/JavaScript-Garden/) es una guía para todas las +[Jardín JavaScript](https://shamansir.github.io/JavaScript-Garden/) es una guía para todas las funciones y características contra-intuitivas del lenguaje. [JavaScript: La guía definitiva](http://www.amazon.com/gp/product/0596805527/) es una guía clásica / libro de referencia. diff --git a/fa-ir/javascript-fa.html.markdown b/fa-ir/javascript-fa.html.markdown index 0aa8079a..5a70377f 100644 --- a/fa-ir/javascript-fa.html.markdown +++ b/fa-ir/javascript-fa.html.markdown @@ -619,7 +619,7 @@ JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introdu [Document Object Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) -[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) +[Javascript Garden](https://shamansir.github.io/JavaScript-Garden/)

      راهنمای دقیقی از قسمت های غیر ملموس زبان.

      اضافه بر این در ویرایش این مقاله، قسمت هایی از سایت زیر مورد استفاده قرار گرفته است.

      diff --git a/fr-fr/javascript-fr.html.markdown b/fr-fr/javascript-fr.html.markdown index d0ea1e33..793e0859 100644 --- a/fr-fr/javascript-fr.html.markdown +++ b/fr-fr/javascript-fr.html.markdown @@ -771,7 +771,7 @@ Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) [Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) quelques challenges. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +[JavaScript Garden](https://shamansir.github.io/JavaScript-Garden/) is an in-depth un guide pour vous éviter les faux-amis dans le JavaScript. [JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) un classique. A lire. diff --git a/it-it/javascript-it.html.markdown b/it-it/javascript-it.html.markdown index 1d776535..eeb98144 100644 --- a/it-it/javascript-it.html.markdown +++ b/it-it/javascript-it.html.markdown @@ -609,7 +609,7 @@ In aggiunta ai contributori di questo articolo, alcuni contenuti sono adattati d [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core [4]: http://www.learneroo.com/modules/64/nodes/350 -[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[5]: https://shamansir.github.io/JavaScript-Garden/ [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [8]: http://eloquentjavascript.net/ diff --git a/javascript.html.markdown b/javascript.html.markdown index 4e7c5c09..c7ee6dea 100644 --- a/javascript.html.markdown +++ b/javascript.html.markdown @@ -668,7 +668,7 @@ Mozilla Developer Network. [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core [4]: http://www.learneroo.com/modules/64/nodes/350 -[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[5]: https://shamansir.github.io/JavaScript-Garden/ [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [8]: https://www.javascripttutorial.net/ diff --git a/ko-kr/javascript-kr.html.markdown b/ko-kr/javascript-kr.html.markdown index 267b5b2f..cb571a1f 100644 --- a/ko-kr/javascript-kr.html.markdown +++ b/ko-kr/javascript-kr.html.markdown @@ -422,7 +422,7 @@ MDN의 ['자바스크립트 재입문'](https://developer.mozilla.org/ko/docs/A_ [문서 객체 모델(Document Object Model)](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core)에 관해 배우는 것으로 시작하길 바랍니다. -[자바스크립트 가든](http://bonsaiden.github.io/JavaScript-Garden/)에서는 자바스크립트 언어에서 +[자바스크립트 가든](https://shamansir.github.io/JavaScript-Garden/)에서는 자바스크립트 언어에서 직관에 어긋나는 모든 부분들을 심도 있게 다룹니다. 더불어 이 글에 직접적으로 기여한 분들로, 내용 중 일부는 이 사이트에 있는 diff --git a/ms-my/javascript-my.html.markdown b/ms-my/javascript-my.html.markdown index c0555d5b..32b651d6 100644 --- a/ms-my/javascript-my.html.markdown +++ b/ms-my/javascript-my.html.markdown @@ -584,6 +584,6 @@ dan [JS Tutorial][7] di Mozilla Developer Network. [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core [4]: http://www.learneroo.com/modules/64/nodes/350 -[5]: http://bonsaiden.github.io/JavaScript-Garden/ +[5]: https://shamansir.github.io/JavaScript-Garden/ [6]: http://www.amazon.com/gp/product/0596805527/ [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript diff --git a/pt-br/javascript-pt.html.markdown b/pt-br/javascript-pt.html.markdown index c5be649d..ba9066e1 100644 --- a/pt-br/javascript-pt.html.markdown +++ b/pt-br/javascript-pt.html.markdown @@ -527,7 +527,7 @@ Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) [Aprenda Javascript por Exemplos e com Desafios](http://www.learneroo.com/modules/64/nodes/350) é uma variação desse guia com desafios. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) é um guia +[JavaScript Garden](https://shamansir.github.io/JavaScript-Garden/) é um guia profundo de todas as partes do JavaScript. [JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) é o guia clássico diff --git a/ta-in/javascript-ta.html.markdown b/ta-in/javascript-ta.html.markdown index f7fd282e..18d60dd1 100644 --- a/ta-in/javascript-ta.html.markdown +++ b/ta-in/javascript-ta.html.markdown @@ -579,7 +579,7 @@ Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) [Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) is a variant of this reference with built-in challenges. -[JavaScript Garden](http://bonsaiden.github.io/JavaScript-Garden/) is an in-depth +[JavaScript Garden](https://shamansir.github.io/JavaScript-Garden/) is an in-depth guide of all the counter-intuitive parts of the language. [JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) is a classic guide / reference book. diff --git a/tr-tr/javascript-tr.html.markdown b/tr-tr/javascript-tr.html.markdown index a20f1f4e..3c28f956 100644 --- a/tr-tr/javascript-tr.html.markdown +++ b/tr-tr/javascript-tr.html.markdown @@ -601,6 +601,6 @@ MDN'nin [A re-introduction to JavaScript(JavaScript'e Yeniden Giriş)][2] başl [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core [4]: https://academy.patika.dev/courses/javascript [5]: http://www.learneroo.com/modules/64/nodes/350 -[6]: http://bonsaiden.github.io/JavaScript-Garden/ +[6]: https://shamansir.github.io/JavaScript-Garden/ [7]: https://www.yusufsezer.com.tr/javascript-dersleri/ [8]: https://www.btkakademi.gov.tr/portal/course/javascript-8099 diff --git a/uk-ua/javascript-ua.html.markdown b/uk-ua/javascript-ua.html.markdown index 2f17f586..9a2121c3 100644 --- a/uk-ua/javascript-ua.html.markdown +++ b/uk-ua/javascript-ua.html.markdown @@ -487,7 +487,7 @@ if (Object.create === undefined) { // не перезаписуємо метод * [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript * [3]: https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core * [4]: http://www.learneroo.com/modules/64/nodes/350 -* [5]: http://bonsaiden.github.io/JavaScript-Garden/ +* [5]: https://shamansir.github.io/JavaScript-Garden/ * [6]: http://www.amazon.com/gp/product/0596805527/ * [7]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript * [8]: http://eloquentjavascript.net/ diff --git a/zh-cn/javascript-cn.html.markdown b/zh-cn/javascript-cn.html.markdown index d637c21c..96a70793 100644 --- a/zh-cn/javascript-cn.html.markdown +++ b/zh-cn/javascript-cn.html.markdown @@ -479,7 +479,7 @@ Model](https://developer.mozilla.org/en-US/docs/Using_the_W3C_DOM_Level_1_Core) [Learn Javascript by Example and with Challenges](http://www.learneroo.com/modules/64/nodes/350) 是本参考的另一个版本,并包含了挑战习题。 -[Javascript Garden](http://bonsaiden.github.io/JavaScript-Garden/) 是一个深入 +[Javascript Garden](https://shamansir.github.io/JavaScript-Garden/) 是一个深入 讲解所有Javascript反直觉部分的导引。 [JavaScript: The Definitive Guide](http://www.amazon.com/gp/product/0596805527/) 是一个经典的指导参考书。 From f5572497d9bb84ee58bc42a03e244e9a3440065e Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 19:56:14 +0200 Subject: [PATCH 338/392] [c/de-de] Fix typos (#5068) --- de-de/c-de.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/de-de/c-de.html.markdown b/de-de/c-de.html.markdown index 16f71b00..650a3a94 100644 --- a/de-de/c-de.html.markdown +++ b/de-de/c-de.html.markdown @@ -22,7 +22,7 @@ manuellen Speicherverwaltung bewusst sein. > Standards: > `-Wall -Wextra -Werror -O2 -std=c99 -pedantic` > -> Da gewisse Optionen (inbesondere der C-Standard) sehr stark vom Projekt +> Da gewisse Optionen (insbesondere der C-Standard) sehr stark vom Projekt > abhängen, lohnt es sich, wenn die unterschiedlichen Optionen genauer > angeschaut werden. Eine Übersicht über die Compiler-Optionen findet man unter > [diesem](https://stackoverflow.com/questions/3375697/useful-gcc-flags-for-c) Stackoverflow-Beitrag. @@ -69,7 +69,7 @@ int function_2(void); // Es muss ein Funktionsprototyp deklariert werden vor der `main()` Funktion, // wenn die Funktion nach der `main()` Funktion gebraucht wird. int add_two_ints(int x1, int x2); // Funktionsprototyp -// Auch wenn der Ausdrck `int add_two_ints(int, int)` auch valid wäre, +// Auch wenn der Ausdruck `int add_two_ints(int, int)` auch valid wäre, // ist es empfohlen, dass man die Namen der Argumente hinschreibt für eine // einfachere Analyse. @@ -437,7 +437,7 @@ int main (int argc, char** argv) { printf("%d\n", *px); // => 1 printf("%d\n", x); // => 1 - // Arrays sind eine gute Möglichekit, einen zusammenhängenden Block von + // Arrays sind eine gute Möglichkeit, einen zusammenhängenden Block von // Speicher zu allozieren. int x_array[20]; // deklariert einen Array der Größe 20 (Größe kann // nicht geändert werden.) @@ -712,7 +712,7 @@ void str_reverse_through_pointer(char *str_in) { /* Solange die Signaturen der Funktionen übereinstimmen, kann man sämtliche Funktionen -demselben Pointer zuweisen. Funktionspointer sind auf Grund der Einfacheit und +demselben Pointer zuweisen. Funktionspointer sind auf Grund der Einfachheit und Leserlichkeit normalerweise wie folgt `typedef`d */ typedef void (*my_fnp_type)(char *); @@ -722,7 +722,7 @@ typedef void (*my_fnp_type)(char *); // Spezialzeichen // Im folgenden sin die englischen Begriffe jeweils in Klammern geschrieben, -// da diese Begriffe auch im deutschten Sprachgebrauch verwendet werden. +// da diese Begriffe auch im deutschen Sprachgebrauch verwendet werden. '\a'; // Alarmzeichen (alert (bell) character) '\n'; // Zeichen für neue Linie (newline character) '\t'; // Tab (tab character (left justifies text)) @@ -804,7 +804,7 @@ befindet wie die C-Quelldatei. #ifndef EXAMPLE_H /* Wenn EXAMPLE_H noch nicht definiert wurde */ #define EXAMPLE_H /* definiere das Makro EXAMPLE_H */ -// Es könenn weitere Header innerhalb eines Headers eingebunden werden, was dazu +// Es können weitere Header innerhalb eines Headers eingebunden werden, was dazu // führt, dass diese bereits in anderen Dateien eingebunden wurden. So kann eine // Header-Datei in mehreren Dateien eingebunden werden. zum Beispiel: #include @@ -832,7 +832,7 @@ typedef struct Node { // Dies kann auch mit Aufzählungen gemacht werden. enum traffic_light_state {GREEN, YELLOW, RED}; -// Funktionsprototypen könenn auch in Header-Dateien definiert werden, um die +// Funktionsprototypen können auch in Header-Dateien definiert werden, um die // Funktion in unterschiedlichen Dateien zu verwenden, aber dies wird als schlechte // Praxis angesehen. Definitionen sollten in einer C-Datei erstellt werden. Node create_linked_list(int *value, int length); From 1a54a6dea107b1311cdb2b62f9c0d1c8f6979d73 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 19:56:29 +0200 Subject: [PATCH 339/392] [markdown/de-de] Fix typos (#5070) --- de-de/markdown-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/markdown-de.html.markdown b/de-de/markdown-de.html.markdown index 729e883c..cb2e5246 100644 --- a/de-de/markdown-de.html.markdown +++ b/de-de/markdown-de.html.markdown @@ -115,7 +115,7 @@ oder 3. Punkt drei +nicht mal korrekt nummerieren --> 1. Punkt eins 1. Punkt zwei @@ -148,7 +148,7 @@ indem du eine Zeile mit vier Leerzeichen oder einem Tabulator einrückst --> Hermann hatte nicht die leiseste Ahnung, was dieses `go_to()` bedeuten könnte! - \`\`\`ruby @@ -223,7 +223,7 @@ voranstellt! --> ist das selbe wie [http://testwebseite.de/](http://testwebseite.de/) - + From c64c022ca63e715b202f03c16ec8250924702ad5 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 19:56:39 +0200 Subject: [PATCH 340/392] [haml/de-de] Fix typo (#5071) --- de-de/haml-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/haml-de.html.markdown b/de-de/haml-de.html.markdown index 0f12eebf..5f303261 100644 --- a/de-de/haml-de.html.markdown +++ b/de-de/haml-de.html.markdown @@ -93,7 +93,7 @@ $ haml input_file.haml output_file.html / andere Attribute können über den Hash angegeben werden: %a{:href => '#', :class => 'bar', :title => 'Bar'} -/ Booleesche Attribute können mit 'true' gesetzt werden: +/ Boolesche Attribute können mit 'true' gesetzt werden: %input{:selected => true} / data-Attribute können in einem eigenen Hash im :data key angegeben werden: From 0272512a20609f2ee70cf70d0bc76338b612b37a Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 19:56:51 +0200 Subject: [PATCH 341/392] [haskell/de-de] Fix typos (#5072) --- de-de/haskell-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index a154c829..4a4147fd 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -50,7 +50,7 @@ not False -- True 1 /= 1 -- False 1 < 10 -- True --- `not` ist eine Funktion die ein Argument entgegenimmt. +-- `not` ist eine Funktion die ein Argument entgegennimmt. -- Haskell benötigt keine Klammern um Argumente. -- Sie werden einfach aufgelistet: func arg1 arg2 arg3... -- Wie man Funktionen definiert kommt weiter unten. @@ -282,7 +282,7 @@ for [0..5] $ \i -> show i -- wir hätten sie auch so benutzen können: for [0..5] show --- foldl oder foldr reduziren Listen auf einen Wert. +-- foldl oder foldr reduzieren Listen auf einen Wert. -- foldl foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 @@ -345,7 +345,7 @@ main' = interact countLines -- Man kann den Typ `IO ()` als Repräsentation einer Sequenz von -- Aktionen sehen, die der Computer abarbeiten muss. --- Wie bei einem Programm das in einer Imperativen Sprache geschreiben wurde. +-- Wie bei einem Programm das in einer Imperativen Sprache geschrieben wurde. -- Mit der `do` Notation können Aktionen verbunden werden. sayHello :: IO () From 3512a41177e109c3551802d2948a6d7ff54905af Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 30 Aug 2024 19:57:05 +0200 Subject: [PATCH 342/392] [go/de-de] Fix typo (#5069) --- de-de/go-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 1b09a1e1..9acf3528 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -124,7 +124,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ // keine Zeiger-Rechnungen. Fehler können sich durch "nil" einschleichen, jedoch // nicht durch erhöhen eines Zeigers. func learnMemory() (p, q *int) { - // Die bennanten Rückgabewerte p & q sind vom Typ *int + // Die benannten Rückgabewerte p & q sind vom Typ *int p = new(int) // Eingebaute Funktion "new" weist neuen Speicherplatz zu // Der zugewiesene Speicher ist mit 0 initialisiert, p ist nicht länger nil s := make([]int, 20) // So weist man 20 ints nebeneinander (im Speicher) zu From 13086ef43371cfe771da7a3ee9bd11586ef2ab26 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 2 Sep 2024 03:06:54 +0200 Subject: [PATCH 343/392] [java/de-de] Fix typos (#5075) --- de-de/java-de.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/java-de.html.markdown b/de-de/java-de.html.markdown index be96a7e8..be20cdce 100644 --- a/de-de/java-de.html.markdown +++ b/de-de/java-de.html.markdown @@ -125,9 +125,9 @@ public class LearnJavaDe { // Weitere nennenswerte Typen // ArrayLists - Ähnlich Arrays, allerdings werden mehr Funktionen geboten, - // ebenso ist die Arraygröße verwänderbar + // ebenso ist die Arraygröße veränderbar // LinkedLists - Implementierung einer doppelt verlinkten Liste. - // Alle Operationen funktioneren so, wie es von einer doppelt verlinkten Liste erwartet wird. + // Alle Operationen funktionieren so, wie es von einer doppelt verlinkten Liste erwartet wird. // Weitere Informationen: https://de.wikipedia.org/wiki/Liste_(Datenstruktur)#Doppelt_.28mehrfach.29_verkettete_Liste // Maps - Eine Sammlung von Objekten, welche eine Verknüpfung von Schlüsseln zu Werten (key => value) vornimmt. // Eine Map kann keine Duplikate enthalten; Jeder Schlüssel kann genau einen Wert beinhalten. @@ -173,7 +173,7 @@ public class LearnJavaDe { // Inkrementierungen int i = 0; System.out.println("\n->Inc/Dec-rementierung"); - // Die ++ und -- operatoren inkrementieren und dekrementieren jeweils um 1. + // Die ++ und -- Operatoren inkrementieren und dekrementieren jeweils um 1. // Werden sie vor die Variable gesetzt, ink-/dekrementieren sie und geben anschließend ihren Wert zurück. // Hinter der Variable geben sie ihren Wert zurück und ändern ihn anschließend. System.out.println(i++); // i = 1, schreibt 0 (post-increment) @@ -284,7 +284,7 @@ public class LearnJavaDe { // String // Tpe-Casting - // Java Objekte können benfalls konvertiert werden, hierbei gibt es vielfältige Konzepte. + // Java Objekte können ebenfalls konvertiert werden, hierbei gibt es vielfältige Konzepte. // Weitere Informationen finden sich hier (englisch): // http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html From 5a5ae79c53534ed78c645b34d63a97d18b57dec3 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 2 Sep 2024 03:07:06 +0200 Subject: [PATCH 344/392] [c++/de-de] Fix typos (#5074) --- de-de/c++-de.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/c++-de.html.markdown b/de-de/c++-de.html.markdown index 6224d179..de581043 100644 --- a/de-de/c++-de.html.markdown +++ b/de-de/c++-de.html.markdown @@ -278,7 +278,7 @@ string retVal = tempObjectFun(); // - ein String Objekt wird von "tempObjectFun" zurückgegeben // - ein neuer String wird mit dem zurückgegebenen Objekt als Argument für den Konstruktor erzeugt. // - das zurückgegebene Objekt wird zerstört -// Das zurückgegbene Objekt wird temporäres Objekt genannt. Temporäre Objekte werden erzeugt +// Das zurückgegebene Objekt wird temporäres Objekt genannt. Temporäre Objekte werden erzeugt // wann immer eine Funktion ein Objekt zurückgibt. Zerstört werden diese am Ende der Auswertung des Ausdrucks // (dies schreibt der Standard vor, aber Compiler sind berechtigt dieses Verhalten zu ändern. Siehe "return value optimization" // für Details). Wie in diesem Code: @@ -530,7 +530,7 @@ public: Point (double a, double b) : x(a), y(b) - { /* Außschließliche Initialisierung der Werte */ } + { /* Ausschließliche Initialisierung der Werte */ } // Überladung des "+" Operator. Point operator+(const Point& rhs) const; @@ -842,7 +842,7 @@ for (int i = 0; i < my_vector.size(); i++) } // Oder die Verwendung von Iteratoren: -vector::iterator it; // Initialisierng des Iterators. +vector::iterator it; // Initialisierung des Iterators. for (it = my_vector.begin(); it != my_vector.end(); ++it) { cout << *it << endl; @@ -913,7 +913,7 @@ for (it=mymap.begin(); it!=mymap.end(); ++it) it = mymap.find('Z'); cout << it->second; -// Ausabe: 26 +// Ausgabe: 26 // Bemerkung: für "hash maps" sollten die "unordered_map´s" verwendet werden. Diese // sind effizienter und benötigen keine Reihenfolge. "unordered_maps" sind ab From 80d5b77b809bd7da7ac80c051cd2933f499786e0 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 2 Sep 2024 18:33:47 +0200 Subject: [PATCH 345/392] [rust/de-de] Fix typos (#5076) --- de-de/rust-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown index 6208db68..22196654 100644 --- a/de-de/rust-de.html.markdown +++ b/de-de/rust-de.html.markdown @@ -11,7 +11,7 @@ filename: lernerust-de.rs Rust ist eine Programmiersprache von Mozilla Research. Rust vereint Sicherheit, Nebenläufigkeit und eine hohe Praxistauglichkeit. -Sicherheit bedeuted, dass Programmierfehler ausgeschlossen werden, die zu +Sicherheit bedeutet, dass Programmierfehler ausgeschlossen werden, die zu Speicherzugriffsfehlern führen könnten. Das funktioniert u.a. dadurch, dass es keinen Garbage Collector gibt, sondern ein besonderes Typsystem. @@ -22,7 +22,7 @@ nightly build zu nutzen. Am 15. Mai 2015 wurde Rust 1.0 freigegeben, und zwar mit der Garantie einer Abwärtskompatabilität. Verbesserungen der Kompilierzeit und andere Compiler -verbesserungen finden im Moment im nightly build statt. Von Rust gibt es im +Verbesserungen finden im Moment im nightly build statt. Von Rust gibt es im Moment ungefähr alle sechs Wochen ein Release. Rust 1.1 beta wurde zusammen mit dem 1.0 Release zur Verfügung gestellt. From 42edd1f1790ded927a877d49cd83092d67d3d4e7 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 4 Sep 2024 08:18:42 +0200 Subject: [PATCH 346/392] [clojure/de-de] Fix typos (#5077) --- de-de/clojure-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/clojure-de.html.markdown b/de-de/clojure-de.html.markdown index 6e8a50b8..0ee3d9ac 100644 --- a/de-de/clojure-de.html.markdown +++ b/de-de/clojure-de.html.markdown @@ -291,7 +291,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Result: [1 3 5 7 9] ; Wenn du in einer Situation bist, in der du mehr Freiheit willst, -; wohin du das Ergebnis vorheriger Datentransformationen in einem Ausruck +; wohin du das Ergebnis vorheriger Datentransformationen in einem Ausdruck ; platzieren möchtest, kannst du das as-> Macro verwenden. Mit diesem Macro ; kannst du einen speziellen Namen auf die Ausgabe einer Transformationen geben. ; Du kannst es als Platzhalter in verketteten Ausdrücken verwenden: @@ -323,7 +323,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; Hier verwenden wir das Modul clojure.string und die Funktion blank? (clojure.string/blank? "") ; => true -; Du kannst auch einem Modul einem kürzerern Namen beim Import geben +; Du kannst auch einem Modul einen kürzeren Namen beim Import geben (require '[clojure.string :as str]) (str/replace "Das ist ein Test." #"[a-o]" str/upper-case) ; => "DAs IsT EIN TEsT." ; (#"" bezeichnet einen regulären literalen Ausdruck) From 7046c3c41838aeca67d15b20f6ef3c846d4653ea Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 4 Sep 2024 08:18:50 +0200 Subject: [PATCH 347/392] [clojure-macros/de-de] Fix typo (#5078) --- de-de/clojure-macros-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/clojure-macros-de.html.markdown b/de-de/clojure-macros-de.html.markdown index 37477965..4fc1de0b 100644 --- a/de-de/clojure-macros-de.html.markdown +++ b/de-de/clojure-macros-de.html.markdown @@ -156,6 +156,6 @@ Wenn du mit Clojure vertraut sein möchtest, stelle sicher, dass du alles in [Cl [Macros schreiben](http://www.braveclojure.com/writing-macros/) -[Offiziele Docs](http://clojure.org/macros) +[Offizielle Docs](http://clojure.org/macros) [Wann verwendet man Macros?](https://lispcast.com/when-to-use-a-macro/) From 04a299bd3464ffda1a61c364ed1ee2e78b0eaec9 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Wed, 4 Sep 2024 08:19:02 +0200 Subject: [PATCH 348/392] [elm/de-de] Fix typos (#5079) --- de-de/elm-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/elm-de.html.markdown b/de-de/elm-de.html.markdown index a7fe20a9..9a188422 100644 --- a/de-de/elm-de.html.markdown +++ b/de-de/elm-de.html.markdown @@ -33,7 +33,7 @@ Hauptmerkmal von Elm sind die ausführlichen und gut erklärten Fehlermeldungen. -- Exponenten 5 ^ 2 -- 25 --- Boolsche Werte +-- Boolesche Werte not True -- False not False -- True 1 == 1 -- True @@ -274,7 +274,7 @@ otherOrigin : Point3D otherOrigin = Point3D 0 0 0 --- Aber es ist immernoch der selbe Typ, da es nur ein Alias ist! +-- Aber es ist immer noch derselbe Typ, da es nur ein Alias ist! origin == otherOrigin -- True -- Neben den Records gibt es auch noch so genannte Summentypen. From 321ca929a9ac5daf107a1ab814f34c5b03ee7326 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Thu, 5 Sep 2024 21:58:00 +0200 Subject: [PATCH 349/392] [bqn/en] Fix typo (#5081) --- bqn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bqn.html.markdown b/bqn.html.markdown index 928b3a54..b9f8dabe 100644 --- a/bqn.html.markdown +++ b/bqn.html.markdown @@ -134,7 +134,7 @@ array_or_atom {2⋆𝕩}↩ #≡ ⟨ 0.125, 0.0625, 0.03125 ⟩ 'a'-'d' #≡ ¯3 ## Logic Functions -∧, ∨, ¬ # For Booleans, retrun 1 or 0 +∧, ∨, ¬ # For Booleans, return 1 or 0 ≤, <, >, ≥, = # Vectorizing comparisons ≡, ≢ # Nonvectorizing comparisons From 1e27f2435cbb32df0e9d69eb6535f0bd565d6c9b Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Thu, 5 Sep 2024 21:58:12 +0200 Subject: [PATCH 350/392] [paren/de-de] Fix typo (#5082) --- de-de/paren-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/paren-de.html.markdown b/de-de/paren-de.html.markdown index 9ac75598..517c5c75 100644 --- a/de-de/paren-de.html.markdown +++ b/de-de/paren-de.html.markdown @@ -74,7 +74,7 @@ false ; for Falsch ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; 2. Variablen ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Du kannst Variablen setzen indem du (set) verwedest +;; Du kannst Variablen setzen indem du (set) verwendest ;; eine Variable kann alle Zeichen besitzen außer: ();#" (set some-var 5) ; => 5 some-var ; => 5 From 63f3055f28e3abf9678d53ce34b5a8b96cbc13ac Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 6 Sep 2024 11:46:13 +0200 Subject: [PATCH 351/392] [emacs/en] Fix typo (#5085) --- emacs.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/emacs.html.markdown b/emacs.html.markdown index 980e89f7..f58effc7 100644 --- a/emacs.html.markdown +++ b/emacs.html.markdown @@ -258,7 +258,7 @@ powerful and popular and may interest you in and of themselves. ## Org -Technnically, `org-mode`, a major mode for buffer editing that provides +Technically, `org-mode`, a major mode for buffer editing that provides organizational tools. It is very difficult to succinctly describe what Org can do because it's a behemoth of a tool that has many diverse uses to different people. I will attempt to describe the main features I use From aef852af855c821b6a2fb38a55852509e12d1e20 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 6 Sep 2024 11:46:26 +0200 Subject: [PATCH 352/392] [processing/de-de] Fix typos (#5086) --- de-de/processing-de.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/de-de/processing-de.html.markdown b/de-de/processing-de.html.markdown index 78131ee7..59348258 100644 --- a/de-de/processing-de.html.markdown +++ b/de-de/processing-de.html.markdown @@ -59,7 +59,7 @@ size(width, height, [renderer]); // bestimme die Canvasgröße mit dem optionale // Parameter `renderer`. // Du wirst innerhalb dieses Dokuments noch weitere Parameter sehen. -// Wenn du möchstest, dass Code unendlich oft ausgeführt wird, so muss dieser +// Wenn du möchtest, dass der Code unendlich oft ausgeführt wird, so muss dieser // Code innerhalb der `draw()`-Methode stehen. // `draw()` muss existieren, wenn du möchtest, dass das Programm durchgehend // läuft. Die `draw()`-Methode darf nur einmal vorkommen. @@ -137,11 +137,11 @@ ArrayList intArrayList = new ArrayList(); // Da Processing auf Java basiert, unterstützt Processing die Objektorientierte // Programmierung. Dies bedeutet, dass du grundsätzlich jegliche Datentypen // selber erstellen kannst und diese nach deinen Bedürfnissen manipulieren kannst. -// Selbstverständlich muss eine Klasse definiert werden bevor du ein Objekt -// davon instanzieren kannst. +// Selbstverständlich muss eine Klasse definiert werden, bevor du ein Objekt +// davon instanziieren kannst. // Format: ClassName InstanceName -SomeRandomClass myObject // hier musst du das Objekt später instazieren -// Hier wird das Objekt direkt instanziert: +SomeRandomClass myObject // hier musst du das Objekt später instanziieren +// Hier wird das Objekt direkt instanziiert: SomeRandomClass myObjectInstantiated = new SomeRandomClass(); // Processing hat noch weitere Collections (wie zum Beispiel Dictionaries und @@ -348,7 +348,7 @@ sphere(radius); // Die Größe wird definiert durch den Parameter `radius` ------------------------------------------------- */ -// Tranformationen sind nützlich, um ständig zu wissen, wo die Koordinaten und +// Transformationen sind nützlich, um ständig zu wissen, wo die Koordinaten und // die Ecken einer Form sind, welche du gezeichnet hast. Grundsätzlich sind dies // Matrizenoperationen. `pushMatrix()`, `popMatrix()` und `translate()`. pushMatrix(); // Speichert das aktuelle Koordinatensystem auf dem Stack @@ -362,7 +362,7 @@ translate(x,y); // Setzt den Ursprung zu diesem Punkt. translate(x, y, z); // Pendant zu der oberen Funktion im dreidimensionalen Raum // Rotationen -rotate(angle); // Rotiere, um den Betrag, welcher spezifiert wurde. +rotate(angle); // Rotiere, um den Betrag, welcher spezifiziert wurde. // Es gibt drei Pendants im dreidimensionalen Raum. // Namentlich sind dies: `rotateX(angle)`, `rotateY(angle)` und `rotateZ(angle)` @@ -482,7 +482,7 @@ void branch(float len) { } ``` -Processing ist einfach zu erlernen und ist vorallem nützlich, um Multimedia- +Processing ist einfach zu erlernen und ist vor allem nützlich, um Multimedia- Inhalte (auch in 3D) zu erstellen ohne viel Code zu schreiben. Es ist so einfach gehalten, dass man den Code durchlesen kann und man versteht den Programmablauf bereits. From c1e548ef4ac13975d9cdb335c7f775d62318992f Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Fri, 6 Sep 2024 21:52:26 +0200 Subject: [PATCH 353/392] [c/de-de] Fix typos (#5087) --- de-de/c-de.html.markdown | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/de-de/c-de.html.markdown b/de-de/c-de.html.markdown index 650a3a94..df654558 100644 --- a/de-de/c-de.html.markdown +++ b/de-de/c-de.html.markdown @@ -8,7 +8,7 @@ lang: de-de Ach, C. Immer noch **die** Sprache für modernes High-Performance Computing. -C ist wahrscheinlich die Programmiersprache mit dem niedrigsten Abstraktionsnvieau, +C ist wahrscheinlich die Programmiersprache mit dem niedrigsten Abstraktionsniveau, welche die meisten Programmierer je brauchen werden. Die Geschwindigkeit von C ist enorm, allerdings muss man sich stets der manuellen Speicherverwaltung bewusst sein. @@ -227,7 +227,7 @@ int main (int argc, char** argv) { // Wenn das Argument des `sizeof`-Operator ein Ausdruck ist, dann wird das // Argument nicht ausgewertet (außer Arrays mit variabler Länge) // Der Wert, der in diesem Fall zurückgegeben wird, ist eine Konstante zur - // Kompillierzeit. + // Kompilierzeit. int a = 1; //size_t ist ein vorzeichenloser Integer Typ mit mindestens 2 Byte um die @@ -283,7 +283,7 @@ int main (int argc, char** argv) { // repräsentiert. Wir müssen das Null-Byte nicht angeben in String-Literalen; // der Compiler fügt es am Ende des Array automatisch hinzu. char a_string[20] = "Das ist ein String"; - printf("%s\n", a_string); // %s formattiert einen String + printf("%s\n", a_string); // %s formatiert einen String printf("%d\n", a_string[18]); // => 0 // Hier ist das Byte #19 0 (wie auch Byte #20) @@ -394,7 +394,7 @@ int main (int argc, char** argv) { // aus der Header-Datei `` verwendet werden. // Integer-Typen können zu Gleitkommazahlen und umgekehrt umgewandelt werden. - printf("%f\n", (double) 100); // %f formattiert immer zu einem `double`... + printf("%f\n", (double) 100); // %f formatiert immer zu einem `double`... printf("%f\n", (flaot) 100); // ... auch mit einem `float` printf("%d\n", (char)100.0); @@ -414,7 +414,7 @@ int main (int argc, char** argv) { int x = 0; printf("%p\n", (void *)&x); // verwende & um die Adresse der Variable // zu erhalten - // %p formattiert einen Objektpointer des Typen void*) + // %p formatiert einen Objektpointer des Typen void*) // => Gibt eine Adresse im Speicher aus // Pointer starten mit einem * zu Beginn der Deklaration. @@ -446,7 +446,7 @@ int main (int argc, char** argv) { x_array[xx] 20 -xx; } // Initialisiere x_array zu 20, 19, 18, ... 2, 1 - // Deklariere ein Pointer des Typs int und initalisiere ihn, um auf `x_array` + // Deklariere ein Pointer des Typs int und initialisiere ihn, um auf `x_array` // zu zeigen. int *x_ptr = x_array; // x_ptr zeigt jetzt auf den ersten Wert innerhalb des Arrays (int 20) @@ -457,7 +457,7 @@ int main (int argc, char** argv) { // Ausnahme: Wenn das Array das Argument des Operators `&` ist. int arr[10]; int (*ptr_to_arr)[10] = &arr; //`&arr` ist nicht vom Typ `int *`! - // Es ist vom Typem "Pointer auf Array" (aus zehn `int`s) + // Es ist vom Typen "Pointer auf Array" (aus zehn `int`s) // oder wenn das Array ein Stringliteral ist, welches gebraucht wird um ein // `char`-Array zu initialisieren. char other_arr[] = "foobarbazquirk"; @@ -707,7 +707,7 @@ void str_reverse_through_pointer(char *str_in) { // reduziert werden (ähnlich wie Arrays) (*f)(str_in); // Die Funktion einfach mit dem Pointer aufrufen // f(str_in); // Dies ist eine weitere gültige Alternative um eine Funktion - // auzurufen. + // aufzurufen. } /* From f29cae52ed8cadbbcebb9b1cbf443edf4084c0db Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 11:49:14 +0200 Subject: [PATCH 354/392] [java/de-de] Fix typo (#5093) --- de-de/java-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/java-de.html.markdown b/de-de/java-de.html.markdown index be20cdce..f26d2237 100644 --- a/de-de/java-de.html.markdown +++ b/de-de/java-de.html.markdown @@ -311,7 +311,7 @@ public class LearnJavaDe { } // Ende der LearnJavaDe Klasse -// In einer .java-Datei können zusätzliche nicht öffentliche (non-public) äüßere Klassen vorhanden sein. +// In einer .java-Datei können zusätzliche nicht öffentliche (non-public) äußere Klassen vorhanden sein. // Syntax der Klassendeklaration: From e5821aaa786b9ac7d757cedc656ef98f8f984831 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 11:51:13 +0200 Subject: [PATCH 355/392] [python/de-de] Fix typos (#5092) --- de-de/python-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/python-de.html.markdown b/de-de/python-de.html.markdown index d5dbc95f..6469d43e 100644 --- a/de-de/python-de.html.markdown +++ b/de-de/python-de.html.markdown @@ -113,7 +113,7 @@ False or True #=> True "{0} mag Spaghetti, {0} liebt es zu Schwimmen und ganz besonders mag {0} {1}".format("Hans", "Blattsalat") #=> "Hans mag Spaghetti, Hans liebt es zu Schwimmen und ganz besonders mag Hans Blattsalat" -# Die Formatierung kann auch mit `f-strings` oder formattierten Strings gemacht +# Die Formatierung kann auch mit `f-strings` oder formatierten Strings gemacht # werden (ab Python 3.6+) name = "Sandra" f"Sie hat gesagt, ihr Name sei {name}." # => Sie hat gesagt, ihr Name sei Sandra." @@ -242,7 +242,7 @@ list(filled_dict.values()) #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False -# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +# Einen nicht vorhandenen Schlüssel zu suchen, löst einen KeyError aus filled_dict["four"] # KeyError # Mit der get-Methode verhindern wir das From 8ed62278b74b30fe84649e127b6d49ee1cc5f929 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 14:45:07 +0200 Subject: [PATCH 356/392] [gdscript/en] Fix typo (#5091) --- gdscript.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gdscript.html.markdown b/gdscript.html.markdown index ffc08b14..a65d23be 100644 --- a/gdscript.html.markdown +++ b/gdscript.html.markdown @@ -26,7 +26,7 @@ integration with the engine. It's a perfect fit for game development. strings """ -# Doc Comments can add a decription to classes and fields +# Doc Comments can add a description to classes and fields # which can be viewed in the in-engine docs. ## This class is a demonstration of GDScript From 8a78f0a79ff5d316f8ef0014ba8c77a9fdd6ab24 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 14:47:27 +0200 Subject: [PATCH 357/392] [tcl/de-de] Fix typos (#5090) --- de-de/tcl-de.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/tcl-de.html.markdown b/de-de/tcl-de.html.markdown index e75ce0aa..620c2a81 100644 --- a/de-de/tcl-de.html.markdown +++ b/de-de/tcl-de.html.markdown @@ -44,7 +44,7 @@ werden Tcl-intern diese Zeichenketten in Strukturierter-Form gepuffert. Ein Beispiel: Der "list" Befehl arbeitet mit diesen internen gepufferten Repräsentationen. Tcl kümmert sich selbständig darum die String-Repräsentationen zu aktualisieren, falls dies im Skript benötigt werden sollten. Das Kopieren- -beim-Schreiben-Design von Tcl erlaubt es Skript-Authoren mit großen Daten- +beim-Schreiben-Design von Tcl erlaubt es Skript-Autoren mit großen Daten- Strukturen zu arbeiten ohne zusätzlichen Speicher-Overhead. Prozeduren werden automatisch byte-kompiliert außer sie verwenden dynamische Befehle wie zum Beispiel "uplevel", "upvar und "trace". @@ -164,7 +164,7 @@ set {*}{name Neo} set name Neo -# Ein Array ist eine spezielle Varible die also Kontainer für andere Variablen +# Ein Array ist eine spezielle Variable die also Container für andere Variablen # dient. set person(name) Neo set person(gender) male @@ -344,7 +344,7 @@ set values [list one \{ three four] lappend values { } ;# Ein Leerzeichen als Element der Liste hinzufügen -# Mit "eval" können Werte als Skripts evaluiert weden. +# Mit "eval" können Werte als Skripts evaluiert werden. eval { set name Neo set greeting "Hello, $name" @@ -352,7 +352,7 @@ eval { # Eine Liste kann immer an "eval" übergeben werden, solange die Liste einen -# einzigen Befehl entält. +# einzigen Befehl enthält. eval {set name Neo} eval [list set greeting "Hello, $name"] From 94601c0b535526460da1908094345504ab7418a6 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 14:48:58 +0200 Subject: [PATCH 358/392] [vim/de-de] Fix typo (#5089) --- de-de/vim-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/vim-de.html.markdown b/de-de/vim-de.html.markdown index bac7e673..a299c23e 100644 --- a/de-de/vim-de.html.markdown +++ b/de-de/vim-de.html.markdown @@ -240,7 +240,7 @@ set wildmenu set ignorecase set smartcase -" Wenn eine neue Zeile erstellt wird und kein Dateispezifisches Einrücken +" Wenn eine neue Zeile erstellt wird und kein dateispezifisches Einrücken " aktiviert ist, behält die neue Zeile die gleiche Einrückung wie die aktuelle " Zeile set autoindent From f211a72a74f7383f8b7f55c206c57d9e51fcd6d9 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 14:50:17 +0200 Subject: [PATCH 359/392] [yaml/de-de Fix typo (#5088) --- de-de/yaml-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/yaml-de.html.markdown b/de-de/yaml-de.html.markdown index bdbfee23..aa1a967b 100644 --- a/de-de/yaml-de.html.markdown +++ b/de-de/yaml-de.html.markdown @@ -56,7 +56,7 @@ folded_style: > # COLLECTION TYPEN # #################### -# Verschachtelung wird duch Einrückung erzielt. +# Verschachtelung wird durch Einrückung erzielt. eine_verschachtelte_map: schlüssel: wert nochn_Schlüssel: Noch ein Wert. From d26f363b9135229ceade1e0c5af01c6a13fd21b5 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 21:24:30 +0200 Subject: [PATCH 360/392] [scala/de-de] Fix typos (#5095) --- de-de/scala-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown index 3f4ea367..41c85d41 100644 --- a/de-de/scala-de.html.markdown +++ b/de-de/scala-de.html.markdown @@ -796,7 +796,7 @@ import scala.collection.immutable.{List, Map} import scala.collection.immutable.{List => ImmutableList} -// Importiere alle Klasses, mit Ausnahem von.... +// Importiere alle Klassen, mit Ausnahme von.... // Hier ohne: Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} From c5e0a1721a192082a5481618ae61c27874138324 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sat, 7 Sep 2024 21:24:45 +0200 Subject: [PATCH 361/392] [go/de-de] Fix typos (#5094) --- de-de/go-de.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/de-de/go-de.html.markdown b/de-de/go-de.html.markdown index 9acf3528..8c677d48 100644 --- a/de-de/go-de.html.markdown +++ b/de-de/go-de.html.markdown @@ -85,7 +85,7 @@ Zeilenumbrüche beinhalten.` // Selber Zeichenketten-Typ f := 3.14159 // float64, eine IEEE-754 64-bit Dezimalzahl c := 3 + 4i // complex128, besteht intern aus zwei float64-er - // "var"-Syntax mit Initalwert + // "var"-Syntax mit Initialwert var u uint = 7 // Vorzeichenlos, aber die Größe ist implementationsabhängig var pi float32 = 22. / 7 @@ -130,7 +130,7 @@ func learnMemory() (p, q *int) { s := make([]int, 20) // So weist man 20 ints nebeneinander (im Speicher) zu s[3] = 7 // Einer von ihnen wird ein Wert zugewiesen r := -2 // Deklaration einer weiteren lokalen Variable - return &s[3], &r // & gibt die Addresse einer Variable + return &s[3], &r // & gibt die Adresse einer Variable } func expensiveComputation() int { @@ -292,7 +292,7 @@ func learnConcurrency() { // Eine einzige Funktion aus dem http-Paket kann einen Webserver starten. func learnWebProgramming() { - // Der erste Parameter von "ListenAndServe" ist eine TCP Addresse, an die + // Der erste Parameter von "ListenAndServe" ist eine TCP Adresse, an die // sich angeschlossen werden soll. // Der zweite Parameter ist ein Interface, speziell: ein http.Handler err := http.ListenAndServe(":8080", pair{}) From 58f411962e9e2a89e15db48e54701f5510648f42 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:10 +0200 Subject: [PATCH 362/392] [tcl/de-de] Fix typos (#5096) --- de-de/tcl-de.html.markdown | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/de-de/tcl-de.html.markdown b/de-de/tcl-de.html.markdown index 620c2a81..321c6d45 100644 --- a/de-de/tcl-de.html.markdown +++ b/de-de/tcl-de.html.markdown @@ -18,7 +18,7 @@ C-Bibliothek verwendet werden. Sogar in Fällen in denen die Script-Fähigkeiten nicht nötig sind. Denn Tcl stellt Daten-Strukturen wie dynamische Zeichenketten, Listen und Hash-Tabellen bereit. Die C-Bibliothek stellt auch portable Funktionen zur Verfügung: Laden von dynamischen Bibliotheken, Zeichenketten -formatierung und Code Konversion, Dateisystem Operationen, Netzwerk Operationen +Formatierung und Codekonvertierung, Dateisystemoperationen, Netzwerkoperationen und mehr. @@ -98,11 +98,11 @@ set greeting3 ations set greeting1 Sal; set greeting2 ut; set greeting3 ations -# Das Dollar-Zeichen zeigt eine Variablen-Substitution an. +# Das Dollar-Zeichen zeigt eine Variablen-Substitutionen an. set greeting $greeting1$greeting2$greeting3 -# Eckige-Klammern zeigen Befehls-Substitionen an. Das Ergebnis des Befehls wird an +# Eckige-Klammern zeigen Befehls-Substitutionen an. Das Ergebnis des Befehls wird an # Stelle des Klammern-Ausdrucks eingefügt. Wenn man dem "set" Befehl nur den # Namen einer Variablen übergibt, gibt er den Wert der Variablen zurück. set greeting $greeting1$greeting2[set greeting3] @@ -119,7 +119,7 @@ set greeting $greeting[ ] -# Der Backslash unterdrück die Bedeutung von Sonderzeichen +# Der Backslash unterdrückt die Bedeutung von Sonderzeichen set amount \$16.42 @@ -202,7 +202,7 @@ namespace delete :: # Wegen des Verhaltens der Namens-Auflösung ist es sicherer den "variable" # Befehl zu verwenden um in einem Namensraum einen Wert zu deklarieren oder -# zuzuweisen. Wenn eine Variable mit dem namen "name" bereits im globalen +# zuzuweisen. Wenn eine Variable mit dem Namen "name" bereits im globalen # Namensraum existiert, bewirkt der "set" Befehl das der globalen Variable ein # Wert zugewiesen wird, anstatt eine Variable im lokalen Namensraum zu erzeugen namespace eval people { @@ -316,7 +316,7 @@ set amount [lindex $amounts 1] # Geschwungene Klammern und Backslashes können verwendet werden um komplexe # Werte in einer Liste zu formatieren. Eine Liste sieht aus wie ein Skript, -# allerdings verlieren verlieren Zeilenumbrüche und Doppelüunkte ihre +# allerdings verlieren Zeilenumbrüche und Doppelpunkte ihre # besondere Bedeutung. Diese Funktionalität macht Tcl homoikonisch. Die # folgende Liste enthält drei Elemente. set values { @@ -364,7 +364,7 @@ lappend command {Archibald Sorbisol} eval $command -# Es ist ein häufiger Fehler die Listen funktionen beim Aufbauen von Listen +# Es ist ein häufiger Fehler die Listenfunktionen beim Aufbauen von Listen # nicht zu verwenden. set command {set name} append command { Archibald Sorbisol} @@ -431,7 +431,7 @@ proc set_double {varname value} { rename ::while {} -# Definieren einen neuen "while" Befehl mit hilfe des "proc" Befehls. +# Definieren einen neuen "while" Befehl mithilfe des "proc" Befehls. # Ausführlichere Fehler-Behandlung wird dem Leser als Übung überlassen. proc while {condition script} { if {[uplevel 1 [list expr $condition]]} { @@ -460,7 +460,7 @@ puts [countdown 1] ;# -> 2 puts [countdown 2] ;# -> 2 puts [countdown 1] ;# -> 1 puts [countdown 1] ;# -> 0 -puts [coundown 1] ;# -> invalid command name "countdown1" +puts [countdown 1] ;# -> invalid command name "countdown1" puts [countdown 2] ;# -> 1 ``` From e6a4c99ac1e3734ee424055ce6b9695dd916cffa Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:19 +0200 Subject: [PATCH 363/392] [tcl/en] Fix typo (#5097) --- tcl.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tcl.html.markdown b/tcl.html.markdown index f8ca6575..7d6f60aa 100644 --- a/tcl.html.markdown +++ b/tcl.html.markdown @@ -533,7 +533,7 @@ puts [countdown2] ;# -> 4 puts [countdown1] ;# -> 1 puts [countdown1] ;# -> 0 catch { - puts [coundown1] ;# -> invalid command name "countdown1" + puts [countdown1] ;# -> invalid command name "countdown1" } cres copts puts $cres puts [countdown2] ;# -> 3 From 7a327a3fe9656eff76f1717b5f0509db67dc49d6 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:25 +0200 Subject: [PATCH 364/392] [swift/de-de] Fix typo and spelling (#5098) --- de-de/swift-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/swift-de.html.markdown b/de-de/swift-de.html.markdown index c4da99f5..670a1a3c 100644 --- a/de-de/swift-de.html.markdown +++ b/de-de/swift-de.html.markdown @@ -210,7 +210,7 @@ default: // notwendig (um alle möglichen Eingaben zu verarbeiten) :param: name Ein Name :param: day Ein Tag - :returns: Ein String, der Name und Tag beinhält. + :returns: Ein String, der Name und Tag enthält. */ func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." @@ -585,7 +585,7 @@ prefix func !!! (inout shape: Square) -> Square { // Aktueller Wert print(mySquare.sideLength) // 4 -// Wert nach verwendung des eigenen Operators +// Wert nach Verwendung des eigenen Operators !!!mySquare print(mySquare.sideLength) // 12 ``` From 38548861615ef97829943d73f3fb480b7a7ebb42 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:29 +0200 Subject: [PATCH 365/392] [shutit/de-de] Fix typo (#5099) --- de-de/shutit-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/shutit-de.html.markdown b/de-de/shutit-de.html.markdown index f71f2d68..e0c6156f 100644 --- a/de-de/shutit-de.html.markdown +++ b/de-de/shutit-de.html.markdown @@ -323,7 +323,7 @@ Um mehr zu erfahren, siehe: [GitHub](https://github.com/ianmiell/shutit/blob/master/README.md) Es handelt sich um ein breiteres Automatisierungsframework, und das oben -sogenannte ist der sogennante 'standalone Modus'. +genannte ist der sogenannte 'standalone Modus'. Feedback, feature requests, 'Wie mache ich es' sind herzlich willkommen! Erreiche mit unter [@ianmiell](https://twitter.com/ianmiell) From 8638620fcb9309daaa1741eed1409ce97d42e011 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:35 +0200 Subject: [PATCH 366/392] [scala/de-de] Fix typos (#5100) --- de-de/scala-de.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/de-de/scala-de.html.markdown b/de-de/scala-de.html.markdown index 41c85d41..3dbf1b98 100644 --- a/de-de/scala-de.html.markdown +++ b/de-de/scala-de.html.markdown @@ -307,7 +307,7 @@ do { // Endrekursionen sind idiomatisch um sich wiederholende -// Aufgaben in Scala zu lösen. Rekursive Funtionen benötigen explizit einen +// Aufgaben in Scala zu lösen. Rekursive Funktionen benötigen explizit einen // Rückgabe-Typ, der Compiler kann ihn nicht erraten. // Der Rückgabe-Typ in diesem Beispiel ist Unit: @@ -457,7 +457,7 @@ class Dackel extends Hund { } // Object -// Wird ein Objekt ohne das Schlüsselwort "new" instanziert, wird das sog. +// Wird ein Objekt ohne das Schlüsselwort "new" instanziiert, wird das sog. // "companion object" aufgerufen. Mit dem "object" Schlüsselwort wird so // ein Objekt (Typ UND Singleton) erstellt. Damit kann man dann eine Klasse // verwenden, ohne ein Objekt instanziieren zu müssen. @@ -634,10 +634,10 @@ val patternFunc: Person => String = { // 7. "Higher-order"-Funktionen ///////////////////////////////////////////////// -// Scala erlaubt, dass Methoden und Funktionen wiederum Funtionen und Methoden +// Scala erlaubt, dass Methoden und Funktionen wiederum Funktionen und Methoden // als Aufrufparameter oder Rückgabewert verwenden. Diese Methoden heißen // higher-order functions. -// Es gibt zahlreiche higher-order-Funtionen nicht nur für Listen, auch für +// Es gibt zahlreiche higher-order-Funktionen nicht nur für Listen, auch für // die meisten anderen Collection-Typen, sowie andere Klassen in Scala. // Nennenswerte sind: // "filter", "map", "reduce", "foldLeft"/"foldRight", "exists", "forall" From 9c42a9b624afb1b90bce4bece630ca9420fe3146 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:41 +0200 Subject: [PATCH 367/392] [sass/de-de] Fix typos (#5101) --- de-de/sass-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/sass-de.html.markdown b/de-de/sass-de.html.markdown index 7ae200c9..52ade1ad 100644 --- a/de-de/sass-de.html.markdown +++ b/de-de/sass-de.html.markdown @@ -439,7 +439,7 @@ Du kannst beide Syntax-Optionen benutzen, gehe einfach in die Einstellungen und Sass kann in jedem Projekt verwendet werden, solange du ein Programm hast, um es in CSS zu kompilieren. Du solltest verifizieren, dass das CSS, was du verwendest, mit deinen Ziel-Browsern kompatibel ist. -[QuirksMode CSS](http://www.quirksmode.org/css/) und [CanIUse](http://caniuse.com) sind gute Resourcen um die Kompatibilät zu überpüfen. +[QuirksMode CSS](http://www.quirksmode.org/css/) und [CanIUse](http://caniuse.com) sind gute Resourcen um die Kompatibilität zu überprüfen. ## Literaturhinweise From 551df161036c6c6a5fd89561f04494de8ebf3bb8 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:45 +0200 Subject: [PATCH 368/392] [rust/de-de] Fix typo (#5102) --- de-de/rust-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/rust-de.html.markdown b/de-de/rust-de.html.markdown index 22196654..21c4e3cb 100644 --- a/de-de/rust-de.html.markdown +++ b/de-de/rust-de.html.markdown @@ -21,7 +21,7 @@ entwickelt, dass es einfach keine stabile gab und geraten wurde den nightly build zu nutzen. Am 15. Mai 2015 wurde Rust 1.0 freigegeben, und zwar mit der Garantie einer -Abwärtskompatabilität. Verbesserungen der Kompilierzeit und andere Compiler +Abwärtskompatibilität. Verbesserungen der Kompilierzeit und andere Compiler Verbesserungen finden im Moment im nightly build statt. Von Rust gibt es im Moment ungefähr alle sechs Wochen ein Release. Rust 1.1 beta wurde zusammen mit dem 1.0 Release zur Verfügung gestellt. From 4ea7ca31028e2b1b2eb59ab46a6e90df23a64838 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:52 +0200 Subject: [PATCH 369/392] [ruby-ecosystem/de-de] Fix typos (#5103) --- de-de/ruby-ecosystem-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/ruby-ecosystem-de.html.markdown b/de-de/ruby-ecosystem-de.html.markdown index 64d0dfac..f198818e 100644 --- a/de-de/ruby-ecosystem-de.html.markdown +++ b/de-de/ruby-ecosystem-de.html.markdown @@ -91,7 +91,7 @@ Weniger ausgereift/kompatibel: * [Topaz](http://topazruby.com/) - Geschrieben in RPython (via PyPy) Topaz ist noch ziemlich jung und versucht die schnellste Implementierung zu werden. -* [IronRuby](http://ironruby.net/) - Geschrieben in C# für die .NET Plaftform +* [IronRuby](http://ironruby.net/) - Geschrieben in C# für die .NET Plattform Das letzte Release von IronRuby ist mittlerweile 5 Jahre her. Die Ruby Implementierungen haben ihre eigenen Versionsnummern, sind aber From 250f8bbc2ab293743ebb90a1c1532bcc85ce559f Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:13:58 +0200 Subject: [PATCH 370/392] [ruby/de-de] Fix typos (#5104) --- de-de/ruby-de.html.markdown | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/de-de/ruby-de.html.markdown b/de-de/ruby-de.html.markdown index 23571377..6adc3b16 100644 --- a/de-de/ruby-de.html.markdown +++ b/de-de/ruby-de.html.markdown @@ -75,7 +75,7 @@ nil.class #=> NilClass true.class #=> TrueClass false.class #=> FalseClass -# Gleicheit +# Gleichheit 1 == 1 #=> true 2 == 1 #=> false @@ -190,7 +190,7 @@ array = [1, 2, 3, 4, 5] #=> [1, 2, 3, 4, 5] # Array können verschiedene Typen beinhalten [1, 'hello', false] #=> [1, "hello", false] -## Arrays könnenindiziert werden. +## Arrays können indiziert werden. # Von vorne... array[0] #=> 1 @@ -207,8 +207,8 @@ array[2, 3] #=> [3, 4, 5] # ...oder mit einem Range... array[1..3] #=> [2, 3, 4] -# Du kanns ein Array umkehren. -# Gib ein neues Array mit umgkehrten Werten zurück +# Du kannst ein Array umkehren. +# Gib ein neues Array mit umgekehrten Werten zurück [1,2,3].reverse #=> [3,2,1] # Kehre ein Array an Ort und Stelle um, um die Variable mit den @@ -257,7 +257,7 @@ hash.value?(3) #=> true # Tipp: Arrays und Hashes sind Enumerables! # Sie haben viele nützliche Methoden gemein, wie each, map, count, und andere. -# Kontrolstrukturen +# Kontrollstrukturen # Bedingungen if true @@ -427,7 +427,7 @@ surround { puts 'hallo Welt' } # Blocks können in ein 'Proc' Objekt umgewandelt werden. # Dieses ist eine Art Container um den Block und erlaubt ihn an eine -# andere Methode zu übergeben, ihn in einen anderen Gültigkeitsbereicht +# andere Methode zu übergeben, ihn in einen anderen Gültigkeitsbereich # einzubinden oder ihn andersweitig zu verändern. # Am häufigsten findet man dies bei Parameterlisten von Methoden, in Form # eines letzten '&block' Parameters, der den Block – wenn es einen gibt – @@ -487,7 +487,7 @@ best *ranked_competitors # Wenn ein Methodenname mit einem Ausrufezeichen endet, dann tut diese Methode # per Konvention etwas Destruktives, wie z.B. das aufrufende Objekt zu # verändern. -# Viele Mehtoden haben eine !-Version um eine direkte Änderung zu machen und +# Viele Methoden haben eine !-Version um eine direkte Änderung zu machen und # eine Nicht-!-Version, die ein neues Objekt mit den Veränderungen zurück gibt. company_name = "Dunder Mifflin" company_name.upcase #=> "DUNDER MIFFLIN" From 4c5c12f7880c1f6cdd9277bd728c7f36e1f5e8d8 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:14:04 +0200 Subject: [PATCH 371/392] [c/de-de] Fix typo (#5105) --- de-de/c-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/c-de.html.markdown b/de-de/c-de.html.markdown index df654558..b36ace3c 100644 --- a/de-de/c-de.html.markdown +++ b/de-de/c-de.html.markdown @@ -631,7 +631,7 @@ void test_function() { // Variablen mit 0 initialisiert, wenn sie nicht mit einem anderen Startwert // initialisiert werden. // Es ist auch möglich, Funktionen als statisch zu deklarieren, damit diese -// `private` sind. Privat heißt, dass sie nur in diesem Kontekt sichtbar sind. +// `private` sind. Privat heißt, dass sie nur in diesem Kontext sichtbar sind. //////////////////////////////////////////////// From ec4d8bcc70fd88752401fe6a7b80b3ff09c21c8f Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 22:14:07 +0200 Subject: [PATCH 372/392] [clojure/de-de] Fix typos (#5106) --- de-de/clojure-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/clojure-de.html.markdown b/de-de/clojure-de.html.markdown index 0ee3d9ac..350110da 100644 --- a/de-de/clojure-de.html.markdown +++ b/de-de/clojure-de.html.markdown @@ -51,7 +51,7 @@ Diese Verknüpfung erlaubt es, parallele Verarbeitung sehr einfach und häufig a ;;;;;;;;;;;;; ; Clojure verwendet Javas Objekt Typen für Booleans, Strings und Zahlen. -; Verwende `class` um sie zu inszipieren. +; Verwende `class` um sie zu inspizieren. (class 1) ; Integer-Literale sind standardmäßig java.lang.Long (class 1.); Float-Literale sind java.lang.Double (class ""); Strings sind immer in doppelten Anführungszeichen notiert und sind java.lang.String @@ -78,8 +78,8 @@ Diese Verknüpfung erlaubt es, parallele Verarbeitung sehr einfach und häufig a ; damit der Leser aufhört zu denken, es sei eine Funktion. ; Außerdem ist (list 1 2 3) dasselbe, wie '(1 2 3) -; "Kollektioen" sind nur Gruppen von Daten -; Listen und Vektoren sind Kolllektionen: +; "Kollektionen" sind nur Gruppen von Daten +; Listen und Vektoren sind Kollektionen: (coll? '(1 2 3)) ; => true (coll? [1 2 3]) ; => true @@ -115,7 +115,7 @@ Diese Verknüpfung erlaubt es, parallele Verarbeitung sehr einfach und häufig a ; = (+ (+ (+ 1 2) 3) 4) ; => 10 -; Reduce kann auch einen Initalwert als Argument verwenden +; Reduce kann auch einen Initialwert als Argument verwenden (reduce conj [] '(3 2 1)) ; = (conj (conj (conj [] 3) 2) 1) ; => [3 2 1] @@ -374,7 +374,7 @@ keymap ; => {:a 1, :b 2, :c 3} ; um mit persistenten Zuständen umzugehen. Es gibt ein Paar Konstrukte in ; Clojure die es verwenden. -; Ein Atom ist das Einfachste. Gebe es einen Initalwert +; Ein Atom ist das Einfachste. Gebe es einen Initialwert (def my-atom (atom {})) ; Update ein Atom mit swap!. From 516f5562d237194c7eb7c388836f64fe5bedbb9e Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 23:43:38 +0200 Subject: [PATCH 373/392] [lua/de-de] Fix typo (#5111) --- de-de/lua-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/lua-de.html.markdown b/de-de/lua-de.html.markdown index 5564cd79..619d18b0 100644 --- a/de-de/lua-de.html.markdown +++ b/de-de/lua-de.html.markdown @@ -230,7 +230,7 @@ s = f1 + f2 -- Rufe __add(f1, f2) vom der Metatabelle von f1 auf. -- Die nächste Zeile schlägt fehl weil s keine Metatabelle hat: -- t = s + s --- Mihilfe von Klassen ähnlichen Mustern kann das gelöst werden. +-- Mithilfe von Klassen ähnlichen Mustern kann das gelöst werden. -- Siehe weiter unten. -- Ein __index einer Metatabelle überlädt Punkt-Lookups: @@ -294,7 +294,7 @@ mrDog:makeSound() -- 'I say woof' -- 8. -- "function tablename.fn(self, ...)", Der : fügt nur ein Argument namens -- self hinzu. Siehe 7 & 8 um zu sehen wie self seinen Wert bekommt. -- 3. newObj wird eine Instanz von Dog. --- 4. "self" ist die zu Instanzierende Klasse. Meistern ist self = Dog, aber +-- 4. "self" ist die zu instanziierende Klasse. Meistern ist self = Dog, aber -- dies kann durch Vererbung geändert werden. newObj bekommt die Funktionen -- von self wenn wir die Metatabelle von newObj und __index von self auf -- self setzen. From da678b81ac38b26b9bf82e580ed5bafbd7a22bc0 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 23:44:51 +0200 Subject: [PATCH 374/392] [latex/de-de] Fix typo (#5110) --- de-de/latex-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/latex-de.html.markdown b/de-de/latex-de.html.markdown index 6286c2a0..faf90290 100644 --- a/de-de/latex-de.html.markdown +++ b/de-de/latex-de.html.markdown @@ -57,7 +57,7 @@ filename: latex-de.tex % LaTeX für uns eine Titelseite generieren \maketitle -% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigen Befehl an. +% Die meisten Paper haben ein Abstract. LaTeX bietet dafür einen vorgefertigten Befehl an. % Das Abstract sollte in der logischen Reihenfolge, also nach dem Titel, aber vor dem % Inhalt erscheinen. % Dieser Befehl ist in den Dokumentenklassen article und report verfügbar. From 9cd65058c5ebaadcd1fad5209fcb2d96e82527dc Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 23:47:16 +0200 Subject: [PATCH 375/392] [d/de-de] Fix typos (#5109) --- de-de/d-de.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/de-de/d-de.html.markdown b/de-de/d-de.html.markdown index 9eb5ef46..ac7a35c5 100644 --- a/de-de/d-de.html.markdown +++ b/de-de/d-de.html.markdown @@ -14,7 +14,7 @@ module hello; import std.stdio; -// argumente sind optional +// Argumente sind optional void main(string[] args) { writeln("Hello, World!"); } @@ -135,7 +135,7 @@ ist eine Funktion, die wie ein Wert agiert. Das gibt uns viel klarere Syntax im Stil von `structure.x = 7` was gleichgültig wäre zu `structure.setX(7)` ```d -// Diese Klasse ist parameterisiert mit T, U +// Diese Klasse ist parametrisiert mit T, U class MyClass(T, U) { T _data; @@ -186,7 +186,7 @@ void main() { } ``` -Mit properties können wir sehr viel logik hinter unseren gettern +Mit properties können wir sehr viel Logik hinter unseren gettern und settern hinter einer schönen Syntax verstecken Andere Objektorientierte features sind beispielsweise @@ -224,12 +224,12 @@ Ist dir aufgefallen, wie wir eine Haskell-Style Pipeline gebaut haben um num zu berechnen? Das war möglich durch die Uniform Function Call Syntax. Mit UFCS können wir auswählen, ob wir eine Funktion als Methode oder -als freie Funktion aufrufen. Walters artikel dazu findet ihr +als freie Funktion aufrufen. Walters Artikel dazu findet ihr [hier.](http://www.drdobbs.com/cpp/uniform-function-call-syntax/232700394) Kurzgesagt kann man Funktionen, deren erster Parameter vom typ A ist, als Methode auf A anwenden. -Parrallel Computing ist eine Tolle sache, findest du nicht auch? +Parallel Computing ist eine tolle Sache, findest du nicht auch? ```d import std.stdio; @@ -238,7 +238,7 @@ import std.math : sqrt; void main() { // Wir wollen die Wurzel von jeder Zahl in unserem Array berechnen - // und dabei alle Kerne verwenden, die wir zur verfügung haben + // und dabei alle Kerne verwenden, die wir zur Verfügung haben auto arr = new double[1_000_000]; // Wir verwenden den Index und das Element als Referenz From 0eff0a5115c8ebf1b4e968a7769203226d97ed97 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 23:49:39 +0200 Subject: [PATCH 376/392] [css/de-de] Fix grammar (#5108) --- de-de/css-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/css-de.html.markdown b/de-de/css-de.html.markdown index 02c7559f..8e1afc51 100644 --- a/de-de/css-de.html.markdown +++ b/de-de/css-de.html.markdown @@ -139,7 +139,7 @@ selector { /* Schriften */ font-family: Arial; - font-family: "Courier New"; /* wenn der Name ein Leerzeichen beinhält, kommt er in + font-family: "Courier New"; /* wenn der Name ein Leerzeichen enthält, kommt er in Anführungszeichen */ font-family: "Courier New", Trebuchet, Arial; /* wird die erste Schriftart nicht gefunden, wird die zweite benutzt, usw. */ From afc273c12db597d2986aaeafacba8cae301f9a72 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Sun, 8 Sep 2024 23:51:07 +0200 Subject: [PATCH 377/392] [crystal/de-de] Fix typo (#5107) --- de-de/crystal-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/crystal-de.html.markdown b/de-de/crystal-de.html.markdown index 423de5fb..106154c2 100644 --- a/de-de/crystal-de.html.markdown +++ b/de-de/crystal-de.html.markdown @@ -445,7 +445,7 @@ class Human end -# Eine Klasse instanzieren +# Eine Klasse instanziieren jim = Human.new("Jim Halpert") dwight = Human.new("Dwight K. Schrute") From f9a27fcb954af398db58a1bb79f37a119a00b852 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 9 Sep 2024 12:49:32 +0200 Subject: [PATCH 378/392] [make/de-de] Fix typo (#5112) --- de-de/make-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/make-de.html.markdown b/de-de/make-de.html.markdown index dd522b22..8986278b 100644 --- a/de-de/make-de.html.markdown +++ b/de-de/make-de.html.markdown @@ -132,7 +132,7 @@ small/%.png: %.svg %.png: %.ps @echo this rule is not chosen if *.svg and *.ps are both present -# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regelen. Zum Beispiel +# Make hat bereits ein paar eingebaute Muster-Vergleichs-Regeln. Zum Beispiel # weiß Make wie man aus *.c Dateien *.o Dateien erzeugt. # Ältere Versionen von Make verwenden möglicherweise Suffix-Regeln anstatt @@ -236,7 +236,7 @@ ls: * src/* include foo.mk sport = tennis -# Konditionale kompiliereung +# Konditionale Kompilierung report: ifeq ($(sport),tennis) @echo 'game, set, match' From cfb02ca8360876e9e5bd981ac7f07fd128f5a82d Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 9 Sep 2024 12:51:17 +0200 Subject: [PATCH 379/392] [perl/de-de] Fix typos (#5113) --- de-de/perl-de.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/de-de/perl-de.html.markdown b/de-de/perl-de.html.markdown index 71e775d7..f7931188 100644 --- a/de-de/perl-de.html.markdown +++ b/de-de/perl-de.html.markdown @@ -10,7 +10,7 @@ lang: de-de Perl ist eine sehr mächtige, funktionsreiche Programmiersprache mit über 25 Jahren Entwicklungsgeschichte. -Perl läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframes. Perl ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte. +Perl läuft auf über 100 Plattformen von portablen Geräten bis hin zu Mainframes. Perl ist geeignet für Rapid-Prototyping und auch groß angelegte Entwicklungs-Projekte. ```perl # Einzeilige Kommentare beginnen mit dem # Symbol. @@ -30,8 +30,8 @@ Perl läuft auf über 100 Platformen von portablen Geräten bis hin zu Mainframe my $animal = "camel"; my $answer = 42; -# Scalare Werte könnne Zeichenketten, Ganzzahlen und Gleitkomma-Zahlen sein. -# Perl convertiert automatisch zwischen diesen Werten wenn nötig. +# Scalare Werte können Zeichenketten, Ganzzahlen und Gleitkomma-Zahlen sein. +# Perl konvertiert automatisch zwischen diesen Werten wenn nötig. ## Arrays # Ein Array repräsentiert eine Liste von Werten: @@ -42,7 +42,7 @@ my @mixed = ("camel", 42, 1.23); ## Hashes -# Ein Hash representiert ein Set von Schlüssel/Wert Paaren: +# Ein Hash repräsentiert ein Set von Schlüssel/Wert Paaren: my %fruit_color = ("apple", "red", "banana", "yellow"); @@ -55,7 +55,7 @@ my %fruit_color = ( # Scalare, Arrays und Hashes sind in perldata sehr genau dokumentiert. # (perldoc perldata) -# Komplexere Daten-Typen können mit hilfe von Referenzen konstruiert werden. +# Komplexere Daten-Typen können mithilfe von Referenzen konstruiert werden. # Dies erlaubt das erstellen von Listen und Hashes in Listen und Hashes. #### Bedingte Ausführungs- und Schleifen-Konstrukte. From 5938f7f2fc5df92c02cf55b6581b3f578f2ed8b6 Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 9 Sep 2024 12:52:24 +0200 Subject: [PATCH 380/392] [pug/de-de] Fix typo (#5114) --- de-de/pug-de.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/de-de/pug-de.html.markdown b/de-de/pug-de.html.markdown index e4229622..ec03024a 100644 --- a/de-de/pug-de.html.markdown +++ b/de-de/pug-de.html.markdown @@ -87,7 +87,7 @@ div(class=meineKlasse) div(style=meineStile) //-
      -//- JS Attributte +//- JS Attribute - const meineAttribute = {"src": "foto.png", "alt": "meine Bilder"} img&attributes(meineAttribute) //- meine Bilder From bacc08e6d8a98a5ebb89a0cfcc7551c11b54b3ef Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Mon, 9 Sep 2024 12:53:33 +0200 Subject: [PATCH 381/392] [pythonlegacy/de-de] Fix typos (#5115) --- de-de/pythonlegacy-de.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/de-de/pythonlegacy-de.html.markdown b/de-de/pythonlegacy-de.html.markdown index bf871c17..c042f48a 100644 --- a/de-de/pythonlegacy-de.html.markdown +++ b/de-de/pythonlegacy-de.html.markdown @@ -192,7 +192,7 @@ d, e, f = 4, 5, 6 e, d = d, e # d is now 5 and e is now 4 -# Dictionarys (Wörterbucher) speichern Key-Value-Paare +# Dictionarys (Wörterbücher) speichern Key-Value-Paare empty_dict = {} # Hier ein gefülltes Wörterbuch filled_dict = {"one": 1, "two": 2, "three": 3} @@ -213,7 +213,7 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False -# Einen nicht vorhandenenen Schlüssel zu suchen, löst einen KeyError aus +# Einen nicht vorhandenen Schlüssel zu suchen, löst einen KeyError aus filled_dict["four"] # KeyError # Mit der get-Methode verhindern wir das From 6c2b588d9bb8d40b29cb7da479147e73c328a521 Mon Sep 17 00:00:00 2001 From: kelly betty <109933089+kbmackenzie@users.noreply.github.com> Date: Wed, 11 Sep 2024 02:45:00 -0300 Subject: [PATCH 382/392] [sed/en] Fix typo (#5118) --- sed.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sed.html.markdown b/sed.html.markdown index b544af5f..70423a17 100644 --- a/sed.html.markdown +++ b/sed.html.markdown @@ -253,8 +253,8 @@ b # recent reading of an input line or execution of a "t" (test) function. t my_label -# Here is a complete example of branching -# Join lines that end with a backspace into a single space-separated one +# Here is a complete example of branching: +# Join lines that end with a backslash into a single space-separated one. # Name this position "loop" : loop From 3623cbab7d78081b8953ac13f404545346b88087 Mon Sep 17 00:00:00 2001 From: Saurabh Sharma <22629916+itsjzt@users.noreply.github.com> Date: Sat, 14 Sep 2024 11:22:37 +0530 Subject: [PATCH 383/392] [gleam/en] Fixed grammar mistakes (#5121) --- gleam.html.markdown | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/gleam.html.markdown b/gleam.html.markdown index 751beac0..138e4a1f 100644 --- a/gleam.html.markdown +++ b/gleam.html.markdown @@ -11,12 +11,12 @@ and the highly concurrent fault-tolerant Erlang runtime using familiar and modern syntax inspired by languages like OCaml, Rust and Elixir. Being a pretty modern development, Gleam comes with a compiler, a build tool, -a code formatter, several editor integrations, and package manager. +a code formatter, several editor integrations, and a package manager. Being part of the larger BEAM ecosystem, the programs created with Gleam can also make use of thousands of published packages written in Erlang or Elixir. -The design of the language is very concise so it feature no null values, +The design of the language is very concise so it features no null values, no exceptions, clear error messages, and a practical type system. JavaScript is additionally supported as a compile target, so you can run Gleam @@ -53,7 +53,7 @@ pub fn main() { // io.println("This statement got commented out by a two slashes comment.!") // Modules are the units in which all Gleam code gets organized. - // In a module full will find a bunch of definitions of types, functions, etc. + // In a module you will find a bunch of definitions of types, functions, etc. // that seem to belong together. // For example, the gleam/io module contains a variety of functions for // printing, like println. @@ -125,7 +125,7 @@ pub fn main() { io.debug(0o17) io.debug(0xF) - // Use underscores to enhance integer readibility + // Use underscores to enhance integer readability io.debug(1_000_000) // Gleam's numerical operators are not overloaded, so there are dedicated @@ -143,7 +143,7 @@ pub fn main() { io.debug(2.2 >=. 1.3) io.debug(2.2 <=. 1.3) - // Floats are represented as 64 bit floating point numbers on both the Erlang + // Floats are represented as 64-bit floating point numbers on both the Erlang // and JavaScript runtimes. // The floating point behaviour is native to their respective runtimes, so // their exact behaviour will be slightly different on the two runtimes. @@ -169,7 +169,7 @@ pub fn main() { // Underscores for floats are also supported io.debug(10_000.01) - // Division by zero will not overflow, but is instead defined to be zero. + // Division by zero will not overflow but is instead defined to be zero. // Working with strings io.debug("⭐ Gleam ⭐ - 별") @@ -382,7 +382,7 @@ fn more_examples() { // True } -// Gleam supports higher order functions: +// Gleam supports higher-order functions: // They can be assigned to variables, passed as arguments to other functions // or even be returned as values from blocks or other functions fn call_func_on_int(func: fn(Int) -> Int, value: Int) -> Int { @@ -397,7 +397,7 @@ fn more_function_examples() -> Int { io.debug(square(3)) // 9 - // Calling an anonymous function inmediately after defining it + // Calling an anonymous function immediately after defining it io.debug(fn(x: Int) { x + 1 }(1)) // Closure example @@ -425,7 +425,7 @@ fn more_function_examples() -> Int { // 8 // A function capture is a shorthand syntax for creating anonymous functions - // that take one argument and immediately call another function with that + // that takes one argument and immediately calls another function with that // argument let quadruple_3 = multiply(4, _) io.debug(quadruple_3(4)) @@ -583,7 +583,7 @@ fn from_one_to_ten(n: Int) { } } -// In order to avoid memory exhaustion due to creating excesive +// In order to avoid memory exhaustion due to creating excessive // stack frames when calling functions recursively, Gleam supports // "tail call optimisation" which means that the compiler can reuse // the stack frame for the current function if a function call is @@ -623,11 +623,11 @@ fn more_on_pattern_matching() { // When pattern-matching on strings the <> operator match on strings // with a specific prefix and assigns the reminder to a variable io.debug(case "Hello, Lucy" { - "Hello, " <> name -> "Grettings for " <> name + "Hello, " <> name -> "Greetings for " <> name _ -> "Potentially no greetings" }) - // Alternative patters are supported so the same clause is used + // Alternative patterns are supported so the same clause is used // for multiple values let month = 2 let year = 2024 @@ -717,7 +717,7 @@ fn showcase_types() { let point_2 = Point(..point_1, y: 5.7) io.debug(point_2) - // In Gleam, values ar not nullable. + // In Gleam, values are not nullable. // Nil is the only value of its type. let some_var = Nil let result = io.println("Hello!") @@ -821,7 +821,7 @@ fn roll_two_dices_without_use() { }) } -// The use expression still let us write code that uses callbacks +// The use expression still lets us write code that uses callbacks // but cleans up excessive indentation: // - A call to higher order function go the right side of the <- operator // - The argument names for the callback function go on the left hand side of @@ -832,7 +832,7 @@ fn roll_two_dices_with_use() { use first_dice <- result.try(throw_dice_as_result()) use second_dice <- result.try(throw_dice_as_result()) use sum <- result.map(sum_dice_values(first_dice, second_dice)) - // this is the remaing code in innermost callback function + // This is the remaining code in innermost callback function sum } @@ -876,7 +876,7 @@ pub fn homework() { * [Gleam's awesome list](https://github.com/gleam-lang/awesome-gleam) * [Exercism track for Gleam](https://exercism.org/tracks/gleam) -There official docs have cheatsheets for people familiar with: +The official docs have cheatsheets for people familiar with: * [Elixir](https://gleam.run/cheatsheets/gleam-for-elixir-users) * [Elm](https://gleam.run/cheatsheets/gleam-for-elm-users) From 2b9e893079db1eea23efa4ea070f49944abb8026 Mon Sep 17 00:00:00 2001 From: Jason Klebes Date: Tue, 17 Sep 2024 15:19:21 +0100 Subject: [PATCH 384/392] [haskell/de] Added missing comment line about index operator (#5124) --- de-de/haskell-de.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/de-de/haskell-de.html.markdown b/de-de/haskell-de.html.markdown index 4a4147fd..134788a4 100644 --- a/de-de/haskell-de.html.markdown +++ b/de-de/haskell-de.html.markdown @@ -66,6 +66,8 @@ not False -- True -- Ein String ist eine Liste von Zeichen. ['H', 'a', 'l', 'l', 'o', '!'] -- "Hallo!" + +-- Der "!!"-Operator extrahiert das Element an einem bestimmten Index "Das ist eine String" !! 0 -- 'D' @@ -87,7 +89,7 @@ not False -- True [5..1] -- [], da Haskell standardmässig inkrementiert. [5,4..1] -- [5,4,3,2,1] --- Der "!!"-Operator extrahiert das Element an einem bestimmten Index: +-- Ein Element per Index extrahieren: [1..10] !! 3 -- 4 -- Haskell unterstützt unendliche Listen! From 495272cff94e548a4da93926773598a7270b69a6 Mon Sep 17 00:00:00 2001 From: Jason Klebes Date: Wed, 25 Sep 2024 10:45:27 +0100 Subject: [PATCH 385/392] [fortran/en] Fixed overly long comment lines (#5126) * [haskell/de] Added missing comment line about index operator * [fortran/en] Fixed overly long comment lines Including minor rewording and rearranging. A comment was added at 'subroutine' --- fortran.html.markdown | 86 ++++++++++++++++++++++++++----------------- 1 file changed, 52 insertions(+), 34 deletions(-) diff --git a/fortran.html.markdown b/fortran.html.markdown index 83074073..299f99ba 100644 --- a/fortran.html.markdown +++ b/fortran.html.markdown @@ -30,7 +30,8 @@ program example ! declare a program called example. ! All declarations must come before statements and expressions. - implicit none ! prevents dynamic declaration of variables (recommended!) + implicit none ! prevents dynamic declaration of variables + ! Recommended! ! Implicit none must be redeclared in every function/program/module... ! IMPORTANT - Fortran is case insensitive. @@ -45,10 +46,14 @@ program example ! declare a program called example. complex :: w = (0, 1) ! sqrt(-1) character(len=3) :: month ! string of 3 characters. - real :: array(6) ! declare an array of 6 reals. - real, dimension(4) :: arrayb ! another way to declare an array. - integer :: arrayc(-10:10) ! an array with a custom index. - real :: array2d(3, 2) ! multidimensional array. + ! declare an array of 6 reals. + real :: array(6) + ! another way to declare an array. + real, dimension(4) :: arrayb + ! an array with a custom index -10 to 10 (inclusive) + integer :: arrayc(-10:10) + ! A multidimensional array. + real :: array2d(3, 2) ! The '::' separators are not always necessary but are recommended. @@ -76,8 +81,8 @@ program example ! declare a program called example. ! Assignment & Arithmetic ! ======================= - - Z = 1 ! assign to variable z declared above (case insensitive). + + Z = 1 ! assign to variable z declared above j = 10 + 2 - 3 a = 11.54/(2.3*3.1) b = 2**3 ! exponentiation @@ -86,7 +91,7 @@ program example ! declare a program called example. ! =================================== ! Single-line if statement - if (z == a) b = 4 ! condition always need surrounding parentheses. + if (z == a) b = 4 ! conditions always need parentheses. if (z /= a) then ! z not equal to a ! Other symbolic comparisons are < > <= >= == /= @@ -98,13 +103,13 @@ program example ! declare a program called example. b = 5 ! execution block must be on a new line. else b = 10 - end if ! end statement needs the 'if' (or can use 'endif'). + end if ! end statement needs the 'if' if (.NOT. (x < c .AND. v >= a .OR. z == z)) then ! boolean operators. inner: if (.TRUE.) then ! can name if-construct. b = 1 end if inner ! then must name endif statement. - end if + endif ! 'endif' is equivalent to 'end if' i = 20 select case (i) @@ -128,16 +133,16 @@ program example ! declare a program called example. j = -1 end select monthly - do i = 2, 10, 2 ! loops from 2 to 10 (inclusive) in increments of 2. + do i = 2, 10, 2 ! loops from 2 to 10 (inclusive) in steps of 2. innerloop: do j = 1, 3 ! loops can be named too. exit ! quits the loop. end do innerloop cycle ! jump to next loop iteration. end do - ! Goto statement exists but it is heavily discouraged though. + ! Goto statement exists but it is heavily discouraged. goto 10 - stop 1 ! stops code immediately (returning specified condition code). + stop 1 ! stops the program, returns condition code 1. 10 j = 201 ! this line is labeled as line 10 ! Arrays @@ -209,8 +214,12 @@ program example ! declare a program called example. ! we can have multiple format specifications. print "(I5,F6.2,E6.2)", 120, 43.41, 43.41 - print "(3I5)", 10, 20, 30 ! 3 repeats of integers (field width = 5). - print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 ! repeated grouping of formats. + + ! 3 repeats of integers (field width = 5). + print "(3I5)", 10, 20, 30 + + ! repeated grouping of formats. + print "(2(I5,F6.2))", 120, 43.42, 340, 65.3 ! We can also read input from the terminal. read (*, *) v @@ -225,8 +234,9 @@ program example ! declare a program called example. ! To read a file. open (newunit=m, file="records.txt", status="old") - ! The file is referred to by a 'new unit number', an integer that the compiler - ! picks for you. + ! The file is referred to by a 'new unit number', + ! an integer that the compiler picks for you. + read (unit=m, fmt="(3F10.2)") a, b, c close (m) @@ -241,7 +251,7 @@ program example ! declare a program called example. call cpu_time(v) ! sets 'v' to a time in seconds. k = ior(i, j) ! bitwise OR of 2 integers. v = log10(x) ! log base 10. - i = floor(b) ! returns the closest integer less than or equal to x. + i = floor(b) ! converts b to integer by rounding down. v = aimag(w) ! imaginary part of a complex number. ! Functions & Subroutines @@ -252,7 +262,7 @@ program example ! declare a program called example. call routine(a, c, v) ! subroutine call. - ! A function takes a list of input parameters and returns a single value. + ! A function takes several input parameters and returns a single value. ! However the input parameters may still be modified and side effects ! executed. @@ -261,21 +271,22 @@ program example ! declare a program called example. ! Function calls can also be evoked within expressions. print *, func2(3, 2, k) - ! A pure function is a function that doesn't modify its input parameters - ! or cause any side-effects. + ! A pure function is a function that doesn't modify its input + ! parameters or cause any side-effects. m = func3(3, 2, k) -contains ! Zone for defining sub-programs internal to the program. +contains ! Start defining the program's internal procedures: ! Fortran has a couple of slightly different ways to define functions. integer function func(a, b, c) ! a function returning an integer value. - ! implicit none ! subvariable fields can no longer declare implicit none - integer, intent(in) :: a, b, c ! type of input parameters defined inside the function. + ! implicit none ! - no longer used in subvariable fields + integer, intent(in) :: a, b, c ! type of input parameters + ! the return variable defaults to the function name. if (a >= 2) then - func = a + b + c ! the return variable defaults to the function name. - return ! can return the current value from the function at any time. + func = a + b + c + return ! returns the current value at 'func' end if func = a + c @@ -286,24 +297,29 @@ contains ! Zone for defining sub-programs internal to the pro integer, intent(in) :: a, b ! can declare and enforce that variables !are not modified by the function. integer, intent(inout) :: c - integer :: f ! function return type declared inside the function. - integer :: cnt = 0 ! GOTCHA - initialisation implies variable is - !saved between function calls. + integer :: f + ! function return type declared inside the function. + integer :: cnt = 0 ! GOTCHA - + ! assigning a value at initalization + ! implies that the variable is + ! saved between function calls. f = a + b - c - c = 4 ! altering the value of an input variable. + c = 4 ! changing value of input variable c. cnt = cnt + 1 ! count number of function calls. end function func2 - pure function func3(a, b, c) ! a pure function can have no side-effects. + pure function func3(a, b, c) ! a pure function has no side-effects. integer, intent(in) :: a, b, c integer :: func3 func3 = a*b*c end function func3 - + + ! a subroutine does not return anything, + ! but can change the value of arguments. subroutine routine(d, e, f) real, intent(inout) :: f real, intent(in) :: d, e @@ -312,7 +328,8 @@ contains ! Zone for defining sub-programs internal to the pro end subroutine routine -end program example ! End of Program Definition ----------------------- +end program example +! End of Program Definition ----------------------- ! Functions and Subroutines declared externally to the program listing need ! to be declared to the program using an Interface declaration (even if they @@ -350,7 +367,8 @@ module fruity use fruit, only: apple, pear ! use apple and pear from fruit module. implicit none ! comes after module imports. - private ! make things private to the module (default is public). + ! By default all module data and functions will be public + private ! Instead set default to private ! Declare some variables/functions explicitly public. public :: apple, mycar, create_mycar ! Declare some variables/functions private to the module (redundant here). From 742574706bafdae32615bb3c85731a215035cfaf Mon Sep 17 00:00:00 2001 From: Mayuresh Kumbhar Date: Sun, 29 Sep 2024 04:29:02 +0200 Subject: [PATCH 386/392] [java/en] Update java.html.markdown with modern Java updates (#5128) --- java.html.markdown | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/java.html.markdown b/java.html.markdown index fc7383d8..24a9a47f 100644 --- a/java.html.markdown +++ b/java.html.markdown @@ -44,6 +44,9 @@ Multi-line comments look like this. import java.util.ArrayList; // Import all classes inside of java.security package import java.security.*; +// Java to illustrate calling of static members and methods without calling classname +import static java.lang.Math.*; +import static java.lang.System.*; public class LearnJava { @@ -211,9 +214,21 @@ public class LearnJava { // Prefer the String constructor when you need an exact value. BigDecimal tenCents = new BigDecimal("0.1"); + // Type inference with 'var' + var x = 100; // int + var y = 1.90; // double + var z = 'a'; // char + var p = "tanu"; // String + var q = false; // boolean + // Strings String fooString = "My String Is Here!"; + // Text blocks + vat textBlock = """ + This is a in Java + """; + // \n is an escaped character that starts a new line String barString = "Printing on a new line?\nNo Problem!"; // \t is an escaped character that adds a tab character @@ -459,6 +474,8 @@ public class LearnJava { System.out.println(br.readLine()); // In Java 7, the resource will always be closed, even if it throws // an Exception. + } catch (IOException | SQLException ex) { + // Java 7+ Multi catch block handle both exceptions } catch (Exception ex) { //The resource will be closed before the catch statement executes. System.out.println("readLine() failed."); @@ -852,6 +869,12 @@ public abstract class Mammal() } } +// Java Records are a concise way to define immutable data carrier classes, automatically +// generating boilerplate code like constructors, equals(), hashCode()and toString(). +// This automatically creates an immutable class Person with fields name and age. +public record Person(String name, int age) {} +Person p = new Person("Alice", 30); + // Enum Type // // An enum type is a special data type that enables for a variable to be a set From 96332456693a07457d67542a4bd5ca8527ab8a41 Mon Sep 17 00:00:00 2001 From: Darigov Research <30328618+darigovresearch@users.noreply.github.com> Date: Sun, 29 Sep 2024 23:15:39 +0100 Subject: [PATCH 387/392] [jinja/en] Fixes bullet point rendering issue (#5130) Resolves #5129 --- jinja.html.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/jinja.html.markdown b/jinja.html.markdown index 02cb7195..81d593c5 100644 --- a/jinja.html.markdown +++ b/jinja.html.markdown @@ -11,6 +11,7 @@ Jinja is a fast, expressive, and extensible templating engine for Python applications. Jinja includes a lot of functionalities, such as: + - Template inheritance and inclusion; - Defining and importing macros within templates; - Security mechanisms to prevent XSS attacks; From fa0e3c632f952ca58d14a398c737c4ee650031ed Mon Sep 17 00:00:00 2001 From: Jan Knobloch <116908874+jk4e@users.noreply.github.com> Date: Tue, 1 Oct 2024 01:03:06 +0200 Subject: [PATCH 388/392] [opengl/en] Fix typos (#5131) --- opengl.html.markdown | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/opengl.html.markdown b/opengl.html.markdown index 03e37c5c..46abfedb 100644 --- a/opengl.html.markdown +++ b/opengl.html.markdown @@ -161,7 +161,7 @@ sf::Event event{ }; // ... ``` -Ofcourse we have to create the vertex and fragment shader before we can load them, +Of course we have to create the vertex and fragment shader before we can load them, so lets create two basic shaders. **Vertex Shader** @@ -342,7 +342,7 @@ void main() { We define a new input variable ```color``` which represents our color data, this data is passed on to ```fColor```, which is an output variable of our vertex shader and becomes an input variable for our fragment shader. -It is imporatant that variables passed between shaders have the exact same name +It is important that variables passed between shaders have the exact same name and type. ## Handling VBO's @@ -501,7 +501,7 @@ glBindTexture(GL_TEXTURE_2D, 0); glDeleteTextures(1, &texture); ``` -Ofcourse there are more texture formats than only 2D textures, +Of course there are more texture formats than only 2D textures, You can find further information on parameters here: [glBindTexture - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindTexture.xhtml)
      [glTexImage2D - OpenGL Refpage](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml)
      @@ -574,7 +574,7 @@ in vec2 fTexCoords; out vec4 outColor; void main() { - // texture() loads the current texure data at the specified texture coords, + // texture() loads the current texture data at the specified texture coords, // then we can simply multiply them by our color. outColor = texture(tex, fTexCoords) * vec4(fColor, 1.0); } @@ -685,7 +685,7 @@ Geometry shaders are inbetween the vertex and the fragment shader. layout(location = 0) in vec3 position; layout(location = 1) in vec3 color; -// Create an output interface block passed to the next shadaer stage. +// Create an output interface block passed to the next shader stage. // Interface blocks can be used to structure data passed between shaders. out VS_OUT { vec3 color; From 90d544271e6a8be80c9ef7a7eb42d30473a8754a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20Dvo=C5=99=C3=A1k?= Date: Fri, 4 Oct 2024 01:50:47 +0200 Subject: [PATCH 389/392] [lean/en] add space before colon (#5132) --- lean4.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lean4.html.markdown b/lean4.html.markdown index 4d427cec..7dcbb7e7 100644 --- a/lean4.html.markdown +++ b/lean4.html.markdown @@ -256,7 +256,7 @@ We now state Collatz conjecture. The proof is left as an exercise to the reader. def collatz_next (n : Nat) : Nat := if n % 2 = 0 then n / 2 else 3 * n + 1 -def iter (k : Nat) (f: Nat → Nat) := +def iter (k : Nat) (f : Nat → Nat) := match k with | Nat.zero => fun x => x | Nat.succ k' => fun x => f (iter k' f x) From f1b0bb541366200b71cb998b2cb43c63c75fe3d9 Mon Sep 17 00:00:00 2001 From: Anton P Date: Sun, 6 Oct 2024 19:51:00 +0300 Subject: [PATCH 390/392] [d/ru] Update contributor links (#5134) --- ru-ru/d-ru.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ru-ru/d-ru.html.markdown b/ru-ru/d-ru.html.markdown index 82a53b46..2a28aa88 100644 --- a/ru-ru/d-ru.html.markdown +++ b/ru-ru/d-ru.html.markdown @@ -2,9 +2,9 @@ language: D filename: learnd-ru.d contributors: - - ["Anton Pastukhov", "http://dprogramming.ru/"] - - ["Robert Brights-Gray", "http://lhs-blog.info/"] - - ["Andre Polykanine", "http://oire.me/"] + - ["Anton Pastukhov", "https://anton9.com/"] + - ["Robert Brights-Gray", "https://lhs.su/"] + - ["Andre Polykanine", "https://oire.me/"] lang: ru-ru --- From 990878a11f03403e5e0733e8c5a8fba59f54da3d Mon Sep 17 00:00:00 2001 From: Boris Verkhovskiy Date: Sat, 12 Oct 2024 08:31:57 -0700 Subject: [PATCH 391/392] Update setup-ruby GitHub Action --- .github/workflows/lint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 1ade1774..4db0c300 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: ruby/setup-ruby@ec02537da5712d66d4d50a0f33b7eb52773b5ed1 + - uses: ruby/setup-ruby@v1 with: ruby-version: '3.2' - run: gem install mdl From 7678771275f4202c17cbf51116309bc78dd0c00a Mon Sep 17 00:00:00 2001 From: Woody Chang <42999338+kazettique@users.noreply.github.com> Date: Sun, 13 Oct 2024 22:53:41 +0800 Subject: [PATCH 392/392] [javascript/zh-tw] translate (#5138) --- zh-tw/javascript-tw.html.markdown | 611 ++++++++++++++++++++++++++++++ 1 file changed, 611 insertions(+) create mode 100644 zh-tw/javascript-tw.html.markdown diff --git a/zh-tw/javascript-tw.html.markdown b/zh-tw/javascript-tw.html.markdown new file mode 100644 index 00000000..711aac33 --- /dev/null +++ b/zh-tw/javascript-tw.html.markdown @@ -0,0 +1,611 @@ +--- +language: javascript +category: language +name: javascript +filename: javascript-zh-tw.js +contributors: + - ["Leigh Brenecki", "https://leigh.net.au"] + - ["Ariel Krakowski", "http://www.learneroo.com"] +translators: + - ["Woody Chang", "https://github.com/kazettique"] +lang: zh-tw +--- + +JavaScript 是由網景公司(Netscape)的布蘭登·艾克(Brendan Eich)於 1995 年創建的。它最初被設計為一種更簡單的網站腳本語言,用於補足 Java 在更複雜的網路應用程式中使用,但由於它與網頁的高度整合,以及瀏覽器對 JavaScript 的原生支援,使得它在網頁前端的應用遠比 Java 更加普及。 + +然而 JavaScript 並不僅限於網頁瀏覽器:Node.js,一個可提供 Google Chrome 的 V8 JavaScript 引擎執行環境的專案,正變得越來越熱門。 + +JavaScript 具備類似 C 語言的語法,所以若您曾使用過 C 或 Java 等語言,許多基本語法對您來說已經相當熟悉了。雖然在語法上、名稱上與 Java 很類似,但是 JavaScript 的物件模型卻與 Java 有顯著地不同。 + +```js +// 這是單行註解 +/* 這是 + 多行註解 */ + +// 陳述式可以用分號(;)終止 +doStuff(); + +// ... 然而不一定要加分號,當換行時會自動插入分號(除了某些特殊情況)。 +doStuff() + +// 避免意外結果的情況,本文會繼續使用分號 + +/////////////////////////////////// +// 1. 數字、字串和運算子 + +// JavaScript 只有一種數字型別(也就是 64 位元 IEEE 754 雙精度浮點數)。 +// 雙精度浮點數有一個 52 位的尾數,足以精確儲存整數最大至 9✕10¹⁵ 的整數。 +3; // = 3 +1.5; // = 1.5 + +// 所有基本算術運算都如您預期。 +1 + 1; // = 2 +0.1 + 0.2; // = 0.30000000000000004 +8 - 1; // = 7 +10 * 2; // = 20 +35 / 5; // = 7 + +// 包括無法整除的除法運算。 +5 / 2; // = 2.5 + +// 以及餘數運算。 +10 % 2; // = 0 +30 % 4; // = 2 +18.5 % 7; // = 4.5 + +// 位元運算也是如此,當執行位元運算時,浮點數會轉換「最多」32位元的有符號整數 +1 << 2; // = 4 + +// 以括號決定運算優先級。 +(1 + 3) * 2; // = 8 + +// 有三個非數值的值: +Infinity; // 1/0 的結果 +-Infinity; // -1/0 的結果 +NaN; // 0/0 的結果 + +// 也有布林值。 +true; +false; + +// 透過單引號(')或雙引號(")建立字串。 +'abc'; +"Hello, world"; + +// 以驚嘆號(!)執行否定運算 +!true; // = false +!false; // = true + +// 相等運算 `===` +1 === 1; // = true +2 === 1; // = false + +// 不相等運算 !== +1 !== 1; // = false +2 !== 1; // = true + +// 更多比較運算子 +1 < 10; // = true +1 > 10; // = false +2 <= 2; // = true +2 >= 2; // = true + +// 以加號(+)進行字串的串接 +"Hello " + "world!"; // = "Hello world!" + +// 也可以串接字串以外的資料型別 +"1, 2, " + 3; // = "1, 2, 3" +"Hello " + ["world", "!"]; // = "Hello world,!" + +// 這可能導致一些奇怪的行為 +13 + !0; // 14 +"13" + !0; // '13true' + +// 以 `<` 和 `>` 進行比較運算 +"a" < "b"; // = true + +// 使用「兩個等號」(==)做運算時,會執行資料強制轉型 +"5" == 5; // = true +null == undefined; // = true + +// 除非使用「三個等號」(===) +"5" === 5; // = false +null === undefined; // = false + +// 您可以使用 `charAt` 來取得字串中的字符 +"This is a string".charAt(0); // = 'T' + +// 或使用 `substring` 獲得更大的區塊。 +"Hello world".substring(0, 5); // = "Hello" + +// `length` 是一個屬性,因此不要使用 `()`。 +"Hello".length; // = 5 + +// 還有 `null` 和 `undefined` 兩個特殊值。 +null; // 用於表示刻意指定為空值 +undefined; // 用來表示目前尚未指定值(儘管 `undefined` 實際上本身是一個值) + +// `false`、`null`、`undefined`、`NaN`、`0` 及 `""`(空字串)皆為偽值(falsy), +// 其他的皆為真值(truthy)。 +// 特別注意,`0` 是偽值,`"0"` 則是真值,儘管 0 == "0"。(因為隱含地轉型) + +/////////////////////////////////// +// 2. 變數、陣列與物件 + +// 以 `var` 關鍵字宣告變數。JavaScript 是動態型別,因此無需指定型別。 +// 使用一個等號 `=` 來賦值。 +var someVar = 5; + +// 若忽略使用 `var` 關鍵字,也不會得到錯誤 +someOtherVar = 10; + +// ...但是您定義的變數將在自動建立在全域,而不在您定義的作用域中。 + +// 若在定義變數時未賦予初始值,則預設為 `undefined`。 +var someThirdVar; // = undefined + +// 若要一次宣告多個變數,可以使用逗號分隔 +var someFourthVar = 2, someFifthVar = 4; + +// 變數的數學運算有一些簡寫法: +someVar += 5; // 等效於 somevar = somevar + 5,現在為 10 +someVar *= 10; // 現在 someVar 為 100 + +// 對於增減 1 的運算,還有更簡略的寫法: +someVar++; // 現在 someVar 為 101 +someVar--; // 回到 100 + +// 陣列是以任何型別的資料所組成、有順序性的列表。 +var myArray = ["Hello", 45, true]; + +// 可使用中括號(方括號)`[]` 語法存取其成員。 +// 陣列的索引值(index)從 0 開始。 +myArray[1]; // = 45 + +// 陣列是可變的,並有隨成員數量變動的長度 `length`。 +myArray.push("World"); +myArray.length; // = 4 + +// 於指定的索引值新增/修改陣列的成員 +myArray[3] = "Hello"; + +// 從陣列的最前端或最後端新增或刪除元素 +myArray.unshift(3); // 新增元素至最前端 +someVar = myArray.shift(); // 移除第一個元素並回傳 +myArray.push(3); // 新增元素至最後端 +someVar = myArray.pop(); // 移除最後一個元素並回傳 + +// 以分號 `;` 結合陣列的所有元素 +var myArray0 = [32, false, "js", 12, 56, 90]; +myArray0.join(";"); // = "32;false;js;12;56;90" + +// 取得索引 1(包括)到 4(排除)元素的子陣列 +myArray0.slice(1, 4); // = [false, "js", 12] + +// 從索引 2 開始刪除 4 個元素,然後在那裡插入字串 "hi"、"wr" 和"ld",並回傳刪除的子陣列 +myArray0.splice(2, 4, "hi", "wr", "ld"); // = ["js", 12, 56, 90] +// myArray0 === [32, false, "hi", "wr", "ld"] + +// JavaScript 的物件等同於其他語言中的「字典」(Dictionary)或「映射」(Map): +// 無順序性的鍵值對(key value pair)集合。 +var myObj = { key1: "Hello", key2: "World" }; + +// 鍵的名稱是字串,若它們是有效的 JavaScript 標識字,則不需要使用引號。 +// 值則可以是任何資料型別。 +var myObj = { myKey: "myValue", "my other key": 4 }; + +// 物件屬性也可以使用下標語法存取 +myObj["my other key"]; // = 4 + +// ...或使用 `.` 來存取,前提是該鍵值必須是有效的標識字。 +myObj.myKey; // = "myValue" + +// 物件是可變的;其值可修改,並可新增新的鍵值。 +myObj.myThirdKey = true; + +// 如果您嘗試存取不存在的值,將得到 `undefined` 值。 +myObj.myFourthKey; // = undefined + +/////////////////////////////////// +// 3. 邏輯和控制結構 + +// `if` 結構,如同其他語言 +var count = 1; +if (count == 3){ + // count 等於 3 時執行 +} else if (count == 4){ + // count 等於 4 時執行 +} else { + // 其他情況下執行 +} + +// `while` 迴圈 +while (true){ + // 無窮迴圈! +} + +// Do-while 迴圈類似 While 迴圈,但它至少執行一次 +var input; +do { + input = getInput(); +} while (!isValid(input)); + +// `for` 迴圈和 C、Java 語言一樣: +// 初始化; 繼續條件; 迭代。 +for (var i = 0; i < 5; i++){ + // 會執行 5 次 +} + +// 類似 Java,利用迴圈標籤(label)來終止外層的迴圈 +outer: +for (var i = 0; i < 10; i++) { + for (var j = 0; j < 10; j++) { + if (i == 5 && j ==5) { + break outer; + // 不但終止內部迴圈,也終止外部迴圈 + } + } +} + +// for/in 陳述式可以迭代物件中的所有屬性。 +var description = ""; +var person = { fname: "Paul", lname: "Ken", age: 18 }; +for (var x in person){ + description += person[x] + " "; +} // description 為 'Paul Ken 18 ' + +// for/of 陳述式允許迭代可迭代物件(包括內建的字串、陣列、例如類陣列(array-like)參數 +// 或 NodeList 物件、Typedarray 物件、映射(Map)和集合(Set), +// 及用戶自定義的可迭代物件(iterables))。 +var myPets = ""; +var pets = ["cat", "dog", "hamster", "hedgehog"]; +for (var pet of pets){ + myPets += pet + " "; +} // myPets 為 'cat dog hamster hedgehog ' + +// `&&` 是邏輯且(and), `||` 是邏輯或(or) +if (house.size == "big" && house.colour == "blue"){ + house.contains = "bear"; +} +if (colour == "red" || colour == "blue"){ + // colour 等於 "red" 或 "blue" 時執行 +} + +// `||` 可用來設定初始值,稱做「短路」(short circuit)陳述式 +var name = otherName || "default"; + +// `switch` 陳述式使用 `===` 來檢查相等性。 +// 在每個 case 後使用 `break`,否則之後的 case 也會被執行。 +grade = 'B'; +switch (grade) { + case 'A': + console.log("Great job"); + break; + case 'B': + console.log("OK job"); + break; + case 'C': + console.log("You can do better"); + break; + default: + console.log("Oy vey"); + break; +} + + +/////////////////////////////////// +// 4. 函式、作用域與閉包 + +// JavaScript 函式是使用 `function` 關鍵字來宣告的。 +function myFunction(thing) { + return thing.toUpperCase(); +} +myFunction("foo"); // = "FOO" + +// 值得注意的是,要回傳的值必須開始於關鍵字 `return` 那一行, +// 否則會因為自動插入分號,而將回傳 `undefined`。 +// 在使用 Allman 程式碼風格時要特別注意。 +function myFunction() +{ + return // <- 分號在此自動插入 + { + thisIsAn: 'object literal' + }; +} +myFunction(); // = undefined + +// JavaScript 函式為一等物件(first-class objects), +// 所以它們可以被重新賦值給不同的變數, +// 並作為參數傳遞給其他函式 - 例如一個事件處理函式: +function myFunction() { + // 這段程式碼將在 5 秒後執行 +} +setTimeout(myFunction, 5000); +// 註:setTimeout 並不是 JS 語言的一部分,而是由瀏覽器和 Node.js 提供的 API。 + +// setInterval 是瀏覽器提供的另一個 API +function myFunction() { + // 這段程式碼每 5 秒執行一次 +} +setInterval(myFunction, 5000); + +// 函式物件甚至不需要用名稱來宣告 - 你可以直接在另一個函數的參數中直接定義匿名函式。 +setTimeout(function(){ + // 這段程式碼將在 5 秒後執行 +}, 5000); + +// JavaScript 具有函式作用域(scope);函式擁有自己的作用域,但其他區塊(block)則沒有。 +if (true){ + var i = 5; +} +i; // = 5 - 並非在其他語言所預期的 `undefined` + +// 這導致了一種常見的使用方式,即「立即執行匿名函式」,它可以防止臨時變數洩漏到全域作用域。 +(function(){ + var temporary = 5; + // 我們可以透過賦值給「全域物件」來訪問全域作用域, + // 在網頁瀏覽器中,這個全域物件始終是 `window`。 + // 在非瀏覽器環境中(例如 Node.js),全域物件可能有不同的名稱。 + window.permanent = 10; +})(); +temporary; // 拋出錯誤 ReferenceError +permanent; // = 10 + +// 閉包:JavaScript 最強大的特性之一。 +// 若一個函式在另一個函式內部定義,即使外部函式已經執行結束, +// 內部函式仍可以存取外部函式的所有變數。 +function sayHelloInFiveSeconds(name){ + var prompt = "Hello, " + name + "!"; + // 預設情況下,內部函式會被置於局部作用域中,就如同它們是以 `var` 宣告。 + function inner(){ + alert(prompt); + } + setTimeout(inner, 5000); + // setTimeout 是非同步的,所以 sayHelloInFiveSeconds 函式會立即退出。 + // 而 setTimeout 會在之後呼叫 inner 函式。 + // 然而,由於 inner 函式被「閉合包含」(closed over)在 sayHelloInFiveSeconds 函式中, + // 因此當它最終被呼叫時,仍然可以存取 `prompt` 變數。 +} +sayHelloInFiveSeconds("Adam"); // 將在 5 秒後跳出 "Hello, Adam!" 訊息 + +/////////////////////////////////// +// 5. 更多的物件、建構函式、原型 + +// 物件可以包含函式 +var myObj = { + myFunc: function(){ + return "Hello world!"; + } +}; +myObj.myFunc(); // 回傳 "Hello world!" + +// 當物件裡的函式被呼叫時,它們可以使用 `this` 關鍵字來存取所屬物件的其他成員。 +myObj = { + myString: "Hello world!", + myFunc: function() { + return this.myString; + } +}; +myObj.myFunc(); // 回傳 "Hello world!" + +// `this` 的設定與函式如何被呼叫有關,而非定義的位置。 +// 因此,若我們的函式不是在物件的脈絡(context)中被呼叫,就無法正常運作。 +var myFunc = myObj.myFunc; +myFunc(); // = undefined + +// 反之,一個函式可以被賦值給物件並透過 `this` 獲得對它的存取權限, +// 即使它在定義時並未依附於該物件上。 +var myOtherFunc = function() { + return this.myString.toUpperCase(); +}; +myObj.myOtherFunc = myOtherFunc; +myObj.myOtherFunc(); // 回傳 "HELLO WORLD!" + +// 我們也可以在呼叫函式時使用 `call` 或 `apply` 來指定函式的脈絡。 +var anotherFunc = function(s) { + return this.myString + s; +}; +anotherFunc.call(myObj, " And Hello Moon!"); // = "Hello World! And Hello Moon!" + +// `apply` 函式的用法幾乎一樣,差別在於要用陣列的格式傳遞參數 +anotherFunc.apply(myObj, [" And Hello Sun!"]); // = "Hello World! And Hello Sun!" + +// 這在處理接受一系列參數時很有用,特別是當您想要傳遞一個陣列時。 +Math.min(42, 6, 27); // = 6 +Math.min([42, 6, 27]); // = NaN(噢!) +Math.min.apply(Math, [42, 6, 27]); // = 6 + +// 然而 `call` 和 `apply` 只是暫時的。當我們希望它永久有效時,我們可以使用 `bind`。 +var boundFunc = anotherFunc.bind(myObj); +boundFunc(" And Hello Saturn!"); // = "Hello World! And Hello Saturn!" + +// `bind` 也可以用於部分應用,例如:柯里化(curry)的函式。 +var product = function(a, b) { return a * b; }; +var doubler = product.bind(this, 2); +doubler(8); // = 16 + +// 當您使用 `new` 關鍵字呼叫一個函式時,會建立一個新的物件, +// 並透過 `this` 關鍵字使該物件可用於該函式。用此方式呼叫的函式被稱為「建構函式」。 +var MyConstructor = function(){ + this.myNumber = 5; +}; +myNewObj = new MyConstructor(); // = { myNumber: 5 } +myNewObj.myNumber; // = 5 + +// 與大多數其他流行的物件導向語言不同,JavaScript 沒有從類別(class)藍圖建立 +// 實例(instance)的概念;相反地,JavaScript 將實例化(instantiation)和 +// 繼承(inheritance)結合成單一的概念:「原型」(prototype)。 + +// 每個 JavaScript 物件都有一個「原型」(prototype)。 +// 當你試圖存取一個物件上不存在的屬性時,直譯器(interpreter)會嘗試查找它的原型。 + +// 某些 JS 實作允許你透過屬性 `__proto__` 存取原型。雖然這對於解釋原型很有幫助, +// 但它不是標準的操作方式;稍後會介紹使用原型的標準方法。 +var myObj = { + myString: "Hello world!" +}; +var myPrototype = { + meaningOfLife: 42, + myFunc: function() { + return this.myString.toLowerCase(); + } +}; + +myObj.__proto__ = myPrototype; +myObj.meaningOfLife; // = 42 + +// 函式照常運作。 +myObj.myFunc(); // = "hello world!" + +// 當然,若您的屬性不在原型上,則會搜尋原型的原型,以此類推。 +myPrototype.__proto__ = { + myBoolean: true +}; +myObj.myBoolean; // = true + +// 這裡沒有涉及任何複製;每個物件都儲存了一個指向其原型的參考。 +// 這意味著我們可以修改原型,而此修改將反映在任何地方。 +myPrototype.meaningOfLife = 43; +myObj.meaningOfLife; // = 43 + +// for/in 陳述句允許循覽物件的屬性,沿著原型鏈向上查找,直到遇到 `null` 原型為止。 +for (var x in myObj){ + console.log(myObj[x]); +} +// 印出: +// Hello world! +// 43 +// [Function: myFunc] +// true + +// 若只考慮直接附加在物件本身而非其原型上的屬性,請使用 `hasOwnProperty()` 做檢查。 +for (var x in myObj){ + if (myObj.hasOwnProperty(x)){ + console.log(myObj[x]); + } +} +// 印出: +// Hello world! + +// 我們提到 `__proto__` 是非標準用法,而且沒有標準的方法來修改現有物件的原型。 +// 然而,有兩種方法可以建立具有指定原型的新物件。 + +// 第一種方法是 `Object.create`。 +var myObj = Object.create(myPrototype); +myObj.meaningOfLife; // = 43 + +// 第二種方法與建構函式有關,可在任何地方使用。建構函式有一個稱為 `prototype` 的屬性。 +// 這「不是」建構函式本身的原型;而是當使用該建構函式和 `new` 關鍵字建立新物件時,所賦予的原型。 +MyConstructor.prototype = { + myNumber: 5, + getMyNumber: function(){ + return this.myNumber; + } +}; +var myNewObj2 = new MyConstructor(); +myNewObj2.getMyNumber(); // = 5 +myNewObj2.myNumber = 6; +myNewObj2.getMyNumber(); // = 6 + +// 內建型別如字串和數字也有建構函式,可以建立等效的包裝物件(wrapper object)。 +var myNumber = 12; +var myNumberObj = new Number(12); +myNumber == myNumberObj; // = true + +// 然而,它們並非嚴格相等。 +typeof myNumber; // = 'number' +typeof myNumberObj; // = 'object' +myNumber === myNumberObj; // = false +if (0){ + // 這段程式碼不會執行,因為 0 是偽值。 +} +if (new Number(0)){ + // 這段程式碼將會執行,因為包裝過的數字是物件,而物件皆為真值。 +} + +// 然而,包裝物件和常見的內建型別共享一個原型,所以你實際上可以為字串擴充功能,例如: +String.prototype.firstCharacter = function(){ + return this.charAt(0); +}; +"abc".firstCharacter(); // = "a" + +// 此技巧常被用於「填充」(polyfilling),即在舊版的 JavaScript 中 +// 實作新版 JavaScript 才有的功能,以便它們可以在較舊的環境(例如過時的瀏覽器)中使用。 + +// 舉例來說,方才提到的 `Object.create` 並非在舊瀏覽器上使用, +// 但我們仍然可以透過這個 polyfill 來補足其功能: +if (Object.create === undefined){ // 若此方法存在,則不覆蓋 + Object.create = function(proto){ + // 製作一個具有正確原型的暫時建構函式 + var Constructor = function(){}; + Constructor.prototype = proto; + // 然後使用它來建立一個具有適當原型的新物件 + return new Constructor(); + }; +} + +// ES6 語法 + +// `let` 關鍵字讓您在語彙作用域(lexical scope)中定義變數, +// 而不像 `var` 關鍵字那樣在函式作用域(function scope)中定義。 +let name = "Billy"; + +// 以 `let` 關鍵字定義的變數,可以賦予新值。 +name = "William"; + +// `const` 關鍵字如同 `let` 可在語彙作用域中定義變數,差別在於歐,一旦賦值後就不能更改其值。 +const pi = 3.14; + +pi = 4.13; // 此操作並不合法。 + +// ES6 中有一種新的函式語法,稱為「lambda 語法」(lambda syntax)。 +// 這允許函式在語彙作用域中定義,如同 `const` 和 `let` 來定義變數。 +const isEven = (number) => { + return number % 2 === 0; +}; + +isEven(7); // 回傳 false 值 + +// 「等效」於以下傳統函式的宣告方式: +function isEven(number) { + return number % 2 === 0; +}; + +// 前面特別強調「等效」一詞,是因為使用 lambda 語法定義的函式不能在定義之前被呼叫。 +// 以下爲錯誤示範: +add(1, 8); + +const add = (firstNumber, secondNumber) => { + return firstNumber + secondNumber; +}; +``` + +## 延伸閱讀 + +[Mozilla 開發者網路(Mozilla Developer Network)][1] 為 JavaScript 詳細的文件,主要針對瀏覽器環境。此外,它是一個維基百科,當你學到更多時,你可以透過分享自己的知識來幫助他人。 + +MDN 的 [重新介紹 JavaScript][2] 一文中,提到關於本文之外的更多細節。本文聚焦於 JavaScript 語言本身;若您想學習更多關於如何在網頁中使用 JavaScript,可以從閱讀 [文件物件模型][3] 開始。 + +[Learn Javascript by Example and with Challenges][4] 是另一個參考網站,其包含線上的實戰練習。 + +[JavaScript Garden][5] 是一份深入探討這門語言所有反直覺部分的指南。 + +[JavaScript 大全][6] 是一本經典的指南和參考書。 + +[精通 Javascript][8] 由 Marijn Haverbeke 所著,是一本優秀的 JS 書籍/電子書,附帶終端機指令 + +[Javascript: The Right Way][10] 是一本指南,旨在向新入門的開發者介紹 JavaScript,並幫助有經驗的開發者學習更多關於其最佳實踐的知識。 + +[現代 JavaScript 教學][11] 為現代的 JavaScript 教學網站,涵蓋了基礎知識(核心語言和瀏覽器操作)以及進階主題,並提供簡明扼要的解釋。 + +除了本文的直接貢獻者外,部分內容改編自本站 Louie Dinh 的 Python 教學,以及 MDN 的 [重新介紹 JavaScript][2]。 + +[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript +[2]: https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Language_overview +[3]: https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Using_the_Document_Object_Model +[4]: http://www.learneroo.com/modules/64/nodes/350 +[5]: https://shamansir.github.io/JavaScript-Garden/zhtw/ +[6]: https://www.tenlong.com.tw/products/9789865027322 +[8]: https://www.tenlong.com.tw/products/9789865029890?list_name=srh +[10]: http://jstherightway.org/ +[11]: https://javascriptinfo.dev.org.tw
      Erster Tabellenkopf Zweiter TabllenkopfZweiter Tabellenkopf
      Erste Zeile, erste Spalte