Following video includes features, related to work with Russian-language applications and resources:
Category Archives: QA (rus)
ArrayList (Implementation class)
Пожалуй, самая часто используемая коллекция. ArrayList инкапсулирует в себе обычный массив, длина которого автоматически увеличивается при добавлении новых элементов.
Так как ArrayList использует массив, то время доступа к элементу по индексу минимально (В отличии от LinkedList). При удалении произвольного элемента из списка, все элементы находящиеся «правее» смещаются на одну ячейку влево, при этом реальный размер массива (его емкость, capacity) не изменяется. Если при добавлении элемента, оказывается, что массив полностью заполнен, будет создан новый массив размером (n * 3) / 2 + 1, в него будут помещены все элементы из старого массива + новый, добавляемый элемент Java ArrayList represents an automatic re-sizable array and used in place of array. Since we can not modify size of an array after creating it, we prefer to use ArrayList in Java which re-size itself automatically once it gets full. ArrayList in Java implements List interface and allow null. Java ArrayList also maintains insertion order of elements and allows duplicates opposite to any Set implementation which doesn’t allow duplicates.
ArrayList is not synchronized and should not be shared between multiple threadsArrayList stringList = new ArrayList(); //Generic ArrayList to Store only String objects stringList.add(“Item”); //no error because we are storing String
stringList.add(new Integer(2)); //compilation error
int size = stringList.size();
get value: for, foreach, arraylistwithdata.get(int i)
set value: stringList.set(0,”Item2″);
stingList.clear();
ArrayList stringList = Arrays.asList(new String[]{“One”, “Two”, “Three”); //this is not read only List you can still update value of existing elements: Link
HashMap
основан на хэш-таблицах, реализует интерфейс Map (что подразумевает хранение данных в виде пар ключ/значение). Ключи и значения могут быть любых типов, в том числе и null. Данная реализация не дает гарантий относительно порядка элементов с течением времени. Continue reading
Java terms (Collections)
Java terms compilation (basic)
abstract
|
The abstract keyword is used to declare a class or method to be abstract. An abstract method has no implementation; all classes containing abstract methods must themselves be abstract, although not all abstract classes have abstract methods. Objects of a class which is abstract cannot be instantiated, but can be extended by other classes.
Если по-русски: когда вы отмечаете класс как abstract, вы тем самым запрещаете создавать его экземпляры. Поскольку в классе Operation не определен метод calculate, вы не должны иметь возможность создавать его экземпляры:Operation o = new Operation();
Если в классе нет абстрактных методов, то “переделывание” его в обычный никак себя не проявит внешне. Просто появится возможность создать экземпляр этого класса. Например, пишем систему учёта самолётов в аэропорте. Есть грузовые и пассажирские самолёты и надо, например, чтоб был список самолётов, которые сейчас в аэропорту. Делаем абстрактный класс “самолёт” (мы же заранее не знаем, какой самолёт прилетит) и определяем какие-то базовые поля, пригодные для любого самолёта (скорость полёта и длина, например)public abstract class Flight { int speed, width; } Далее создаём два класса, один для пассажирского самолёта и один для грузового, и в каждом дописываем уже спецефические ему параметрыpublic class PassFlight extends Flight { int maxPassengers; //макс число пассажиров }public class Freighter extends Flight { int maxCargo; //макс грузоподъёмность } Далее уже в классе, который со всем этим делом будет работать, создаём лист и пихаем туда те самолёты, которые прилетаютpublic class Runner{ public static void main(String[] args) { List flightList = new ArrayList(); flightList.add(new PassFlight()); flightList.add(new Freighter()); } } Теперь в принципе понятно, что у нас есть список с самолётами, а какие они – уже не совсем важно. Для меня основная фишка абстрактных классов в том, что с помощью них можно задать логику работы, не реализуя её. |
assert | The assert keyword, which was added in J2SE is used to make an assertion—a statement which the programmer believes is always true at that point in the program. If assertions are enabled when the program is run and it turns out that an assertion is false, an AssertionError is thrown and the program terminates. This keyword is intended to aid indebugging |
assertion | In computer programming, an assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. If an assertion evaluates to false at run-time, an assertion failure results, which typically causes execution to abort. |
break | Used to resume program execution at the statement immediately following the current enclosing block or statement |
case | The case keyword is used to create individual cases in a switch statement; see switch |
catch | Defines an exception handler—a group of statements that are executed if an exception is thrown in the block defined by a preceding try keyword. The code is executed only if the class of the thrown exception is assignment compatible with the exception class declared by the catch clause. Catch block is an exception handler and handles the type of exception indicated by its argument. try {} catch (FileNotFoundException e) { System.err.println(“FileNotFoundException: ” + e.getMessage()); throw new SampleException(e);} catch (IOException e) { System.err.println(“Caught IOException: ” + e.getMessage()); } |
char | The char keyword is used to declare a field that can store a 16-bit Unicode character. |
class | A type that defines the implementation of a particular kind of object. A class definition defines instance and class fields, methods, and inner classes as well as specifying the interfaces the class implements and the immediate superclass of the class. If the superclass is not explicitly specified, the superclass is implicitly Objecthttp://developer.alexanderklimov.ru/android/java/class.php class ИмяКласса { тип переменная_экземпляра1;тип имяМетода(список параметров){ // тело метода } } |
database tests | 1) Data writes, data reads. That they simply don’t fail. (Normally they don’t fail though, so it is not that important) 2) Referential integrity. Check that all the connected tables have proper connection keys and data. 3) Business Logic. Most of the Databases use triggers/stored procedures, which modify data before it gets written or retrieved. That logic needs to be tested.For that there are two ways: – Testing externally from a client, like Java, C#, Python via ODBC-style technologies. – Testing those internally with another set of stored procedure, if DB dialect is powerful enough for that. |
deadlock | Deadlock describes a situation where two or more threads are blocked forever, waiting for each other. |
default | The default keyword can optionally be used in a switch statement to label a block of statements to be executed if no case matches the specified value |
do | int counter = 5; int factorial = 1; do { factorial *= counter–; /* Multiply, then decrement. */ } while (counter > 0); System.out.println(factorial); |
exception | Definition: While a program is running, it may encounter an error that prevents it from continuing; such an error is called an exception.Examples: A program tries to read a file that does not exist. A “file not found” exception would occur. |
extends | Used in a class declaration to specify the superclass; used in an interface declaration to specify one or more superinterfaces. Class X extends class Y to add functionality, either by adding fields or methods to class Y, or by overriding methods of class Y. An interface Z extends one or more interfaces by adding methods. Class X is said to be a subclass of class Y; Interface Z is said to be a subinterface of the interfaces it extends. Also used to specify an upper bound on a type parameter in Generics. |
final | Define an entity once that cannot be changed nor derived from later. More specifically: a final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression. All methods in a final class are implicitly final. |
final int FILE NEW = 1 | Все методы и переменные объектов могут быть замещены по умолчанию. |
finally | Used to define a block of statements for a block defined previously by the try keyword. The finally block is executed after execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught, or execution left method in the middle of the try or catch blocks using the return keyword.final – объявление константы. finally – управляет исключениями. Блок finally необязательный и обеспечивает механизм очистки независимо от того, что произошло в try блоке. Используйте finally для закрытия файлов или для освобождения других системных ресурсов таких, как соединения с базой данных.finalize() – метод, который помогает при сборке мусора. Метод, который вызывается перед тем, как объект будет уничтожен сборщиком мусора.Не должен быть использован для освобождения ресурсов вне оперативной памяти, потому что Java имеет лимитированное количество этих ресурсов. Resource r = new Resource(); try { //work } finally { r.dispose(); } |
implements | Included in a class declaration to specify one or more interfaces that are implemented by the current class. A class inherits the types and abstract methods declared by the interfaces. |
inherits | public class Bicycle {// the Bicycle class has three fields public int gear;// the Bicycle class has one constructor public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear;// the Bicycle class has four methods public void setGear(int newValue) { gear = newValue; } A class declaration for a MountainBike class that is a subclass of Bicycle might look like this: public class MountainBike extends Bicycle {// the MountainBike subclass adds one field public int seatHeight;// the MountainBike subclass has one constructor public MountainBike(int startGear) { super(startGear); seatHeight = startHeight; }// the MountainBike subclass adds one method public void setHeight(int newValue) { seatHeight = newValue; } } A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. |
instanceof | A binary operator that takes an object reference as its first operand and a class or interface as its second operand and produces a boolean result. The instanceof operator evaluates to true if and only if the runtime type of the object is assignment compatible with the class or interface. |
Int | The int keyword is used to declare a field that can hold a 32-bit signed two’s complement intege |
interface | Used to declare a special type of class that only contains abstract methods, constant (static final) fields and static interfaces. It can later be implemented by classes that declare the interface with the implements keyword. |
long | The long keyword is used to declare a field that can hold a 64-bit signed two’s complement integer |
native | Used in method declarations to specify that the method is not implemented in the same Java source file, but rather in another language |
new | Used to create an instance of a class or array object |
Object | Set of data combined with methods/actions, statuses, and behavior. Example: JButton fire = new JbuttonThe principal code building block of Java programs. Each object in a program consists of both variables (data) and methods (functionality) |
package | A group of types. Packages are declared with the package keyword. |
parameter | a variable or object passed into a method.Example 1: a method, myMethod is defined which takes 2 parameters. public class MyClass{ public void myMethod(int var1, double var2){ } } |
private | The private keyword is used in the declaration of a method, field, or inner class; private members can only be accessed by other members of their own class |
protected | The protected keyword is used in the declaration of a method, field, or inner class; protected members can only be accessed by members of their own class, that classes from the same package |
public | The public keyword is used in the declaration of a class, method, or field; public classes, methods, and fields can be accessed by the members of any class |
pure virtual method | “A virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature” – wikipedia “A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class that is not abstract” – Wikipedia So, the virtual function can be overriden and the pure virtual must be implemented. The virtual keyword gives C++ its’ ability to support polymorphism. When you have a pointer to an object of some class such as:class Animal { public: virtual int GetNumberOfLegs() = 0; };class Duck : public Animal { public: int GetNumberOfLegs() { return 2; } };class Horse : public Animal { public: int GetNumberOfLegs() { return 4; } };void SomeFunction(Animal * pAnimal) { cout <GetNumberOfLegs(); } In this (silly) example, the GetNumberOfLegs() function returns the appropriate number based on the class of the object that it is called for.Now, consider the function ‘SomeFunction’. It doesn’t care what type of animal object is passed to it, as long as it is derived from Animal. The compiler will automagically cast any Animal-derived class to a Animal as it is a base class.If we do this:Duck d; SomeFunction(&d); it’d output ‘2’. If we do this:Horse h; SomeFunction(&h); it’d output ‘4’. We can’t do this: Animal a; Pure Virtual Functions are mostly used to define: a) abstract classes These are base classes where you have to derive from them and then implement the pure virtual functions. b) interfaces These are ’empty’ classes where all functions are pure virtual and hence you have to derive and then implement all of the functions. |
return | Used to finish the execution of a method. It can be followed by a value required by the method definition that is returned to the caller. |
short | The short keyword is used to declare a field that can hold a 16-bit signed two’s complement integer |
static | Used to declare a field, method, or inner class as a class field. Classes maintain one copy of class fields regardless of how many instances exist of that class. static also is used to define a method as a class method. Class methods are bound to the class instead of to a specific instance, and can only operate on class fields. (Classes and interfaces declared as static members of another class or interface are actually top-level classes and are not inner classes.Нужен для – данных, которые должны существовать в единственном экземпляре на всю программу, а не в каждом объекте. Например, константы. Или, действительно, что-то вроде количества экземпляров класса. – методов, которые не оперируют ни с какими данными (полями) объекта. Например, метод, который меняет все буквы в передаваемой ему строке с маленьких на большие.На методы, объявленные как static, накладывается ряд ограничений: Они могут вызывать только другие статические методы. Они должны осуществлять доступ только к статическим переменным. Они ни коим образом не могут ссылаться на члены типа this или super. (Ключевое слово super связано с наследованием) Если для инициализации переменных типа static нужно выполнить вычисления, можно объявить статический блок, который будет выполняться только один раз при первой загрузке класса. В следующем примере показан класс, который содержит статический метод, несколько статических переменных и статический блок инициализации:// Демонстрация статических переменных, методов и блоков. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println (“x = ” + x) ; System.out.println (“a = ” + a); System.out.println(“b = ” + b) ; } static { System.out.println(“Статический блок инициализирован.”); b = a * 4; } public static void main(String args[]) { meth(42); } } |
strictfp | A Java keyword used to restrict the precision and rounding of floating point calculations to ensure portability |
super | Used to access members of a class inherited by the class in which it appears. Allows a subclass to access overridden methods and hidden members of its superclass. The super keyword is also used to forward a call from a constructor to a constructor in the superclass. Also used to specify a lower bound on a type parameter in Generics. |
super | Ключевое слово super() являет собой ссылку на базовый класс, которую можна использовать в дочерних классах. В основном используется для вызова методов родительского класса. К примеру чтобы не потерять функциональность, можна использовать его для вызова конструктора базового класса с параметрами:class A { private int value; public A() {} public A(int val) { value = val; } } public class B extends A { public B() { super(); } public B(int val) { super(val); } public static void main(Srting []args) { new B(10); } } Есть одна особенность – если использовать такую форму вызова конструктора базового класса, то этот вызов должен стоять первым в конструкторе. |
synchronized | Used in the declaration of a method or code block to acquire the mutex lock for an object while the current thread executes the code.[3] For static methods, the object locked is the class’Class. Guarantees that at most one thread at a time operating on the same object executes that code. The mutex lock is automatically released when execution exits the synchronized code. Fields, classes and interfaces cannot be declared as synchronized. |
term | description |
this | Used to represent an instance of the class in which it appears. this can be used to access class members and as a reference to the current instance. The this keyword is also used to forward a call from one constructor in a class to another constructor in the same class. |
thread | http://www.quizful.net/post/java-threadspublic class Thread extends Object implements Runnable A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method. There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread.Thread thread1 = new Thread(new makeSmth()); —-> class makeSmth implements Runnable{ |
throw | Causes the declared exception instance to be thrown. This causes execution to continue with the first enclosing exception handler declared by the catch keyword to handle an assignment compatible exception type. If no such exception handler is found in the current method, then the method returns and the process is repeated in the calling method. If no exception handler is found in any method call on the stack, then the exception is passed to the thread’s uncaught exception handler. |
throws | Used in method declarations to specify which exceptions are not handled within the method but rather passed to the next higher level of the program. All uncaught exceptions in a method that are not instances of RuntimeException must be declared using the throws keyword. Синтаксис: throw .Инициирует ошибку, которую можно поймать в catch. Объектом ошибки может быть что угодно, например число: |
try | Defines a block of statements that have exception handling. If an exception is thrown inside the try block, an optional catch block can handle declared exception types. Also, an optional finally block can be declared that will be executed when execution exits the try block and catch clauses, regardless of whether an exception is thrown or not. A try block must have at least one catch clause or a finally block. Выполняется код внутри блока try. Если в нём возникнет ошибка, то выполнение try прерывается, и управление прыгает в начало блока catch. |
try | try { code, which could damage smth or fail: int i = 10/0; } catch and finally blocks . . . |
variable | Represents objects (words, letters, numbers, and so on) |
void | The void keyword is used to declare that a method does not return any value |
Деструкторы | В Java существует возможность объявлять методы с именем finalize. Методы finalize – это деструкторы – методы, которые уничтожают объект. Исполняющая среда Java будет вызывать его каждый раз, когда сборщик мусора соберется уничтожить объект этого класса. |
Конструктор | То же самое для класса Human, только надо private String name; public Human(String name){ this.name = name; } |
Collection | В библиотеке коллекций Java существует два базовых интерфейса, реализации которых и представляют совокупность всех классов коллекций:1. Collection – коллекция содержит набор объектов (элементов). Здесь определены основные методы для манипуляции с данными, такие как вставка (add, addAll), удаление (remove, removeAll, clear), поиск (contains) 2. Map – описывает коллекцию, состоящую из пар “ключ — значение”. У каждого ключа только одно значение, что соответствует математическому понятию однозначной функции или отображения (тар). Такую коллекцию часто называют еще словарем (dictionary) или ассоциативным массивом (associative array). Никак НЕ относится к интерфейсу Collection и является самостоятельным.Хотя фреймворк называется Java Collections Framework, интерфейс map и его реализации входят в фреймворк тоже ! интерфейс Collection расширяют интерфейсы List, Set и Queue: 1. List (Interface) – Представляет собой неупорядоченную коллекцию, в которой допустимы дублирующие значения. Иногда их называют последовательностями (sequence ). Элементы такой коллекции пронумерованы, начиная от нуля, к ним можно обратиться по индексу. – ArrayList (Implementation class) – LinkedList (Implementation class) 2. Set (Interface) – описывает неупорядоченную коллекцию, не содержащую повторяющихся элементов. Это соответствует математическому понятию множества (set): – HashSet (Implementation) – LinkedHashSet – TreeSet 3. Queue – очередь. – PriorityQueue – HashMap – LinkedHashMap – TreeMap – WeakHashMap |
Strong refference | First I need to start with a refresher on strong references. A strong reference is an ordinary Java reference, the kind you use every day. For example, the code:StringBuffer buffer = new StringBuffer(); creates a new StringBuffer() and stores a strong reference to it in the variable buffer. The important part about strong references — the part that makes them “strong” — is how they interact with the garbage collector. Specifically, if an object is reachable via a chain of strong references (strongly reachable), it is not eligible for garbage collection. As you don’t want the garbage collector destroying objects you’re working on, this is normally exactly what you want.When strong references are too strongIt’s not uncommon for an application to use classes that it can’t reasonably extend. The class might simply be marked final, or it could be something more complicated, such as an interface returned by a factory method backed by an unknown (and possibly even unknowable) number of concrete implementations. Suppose you have to use a class Widget and, for whatever reason, it isn’t possible or practical to extend Widget to add new functionality.What happens when you need to keep track of extra information about the object? In this case, suppose we find ourselves needing to keep track of each Widget’s serial number, but the Widget class doesn’t actually have a serial number property — and because Widget isn’t extensible, we can’t add one. No problem at all, that’s what HashMaps are for:serialNumberMap.put(widget, widgetSerialNumber); This might look okay on the surface, but the strong reference to widget will almost certainly cause problems. We have to know (with 100% certainty) when a particular Widget’s serial number is no longer needed, so we can remove its entry from the map. Otherwise we’re going to have a memory leak (if we don’t remove Widgets when we should) or we’re going to inexplicably find ourselves missing serial numbers (if we remove Widgets that we’re still using). If these problems sound familiar, they should: they are exactly the problems that users of non-garbage-collected languages face when trying to manage memory, and we’re not supposed to have to worry about this in a more civilized language like Java.Another common problem with strong references is caching, particular with very large structures like images. Suppose you have an application which has to work with user-supplied images, like the web site design tool I work on. Naturally you want to cache these images, because loading them from disk is very expensive and you want to avoid the possibility of having two copies of the (potentially gigantic) image in memory at once.Because an image cache is supposed to prevent us from reloading images when we don’t absolutely need to, you will quickly realize that the cache should always contain a reference to any image which is already in memory. With ordinary strong references, though, that reference itself will force the image to remain in memory, which requires you (just as above) to somehow determine when the image is no longer needed in memory and remove it from the cache, so that it becomes eligible for garbage collection. Once again you are forced to duplicate the behavior of the garbage collector and manually determine whether or not an object should be in memory. |
Weak references | A weak reference, simply put, is a reference that isn’t strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector’s ability to determine reachability for you, so you don’t have to do it yourself. You create a weak reference like this:WeakReference weakWidget = new WeakReference(widget); and then elsewhere in the code you can use weakWidget.get() to get the actual Widget object. Of course the weak reference isn’t strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that weakWidget.get() suddenly starts returning null.To solve the “widget serial number” problem above, the easiest thing to do is use the built-in WeakHashMap class. WeakHashMap works exactly like HashMap, except that the keys (not the values!) are referred to using weak references. If a WeakHashMap key becomes garbage, its entry is removed automatically. This avoids the pitfalls I described and requires no changes other than the switch from HashMap to a WeakHashMap. If you’re following the standard convention of referring to your maps via the Map interface, no other code needs to even be aware of the change.https://weblogs.java.net/blog/2006/05/04/understanding-weak-references |
Soft reference | A soft reference is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are WeakReferences) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.SoftReferences aren’t required to behave any differently than WeakReferences, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will never be removed from the cache) and how badly it needs the memory they are consuming. |
Complexity | О – все перебрать 0, 1- пока не нашел |
loose coupling | Другие классы должны знать о нашем абстрактном классe, если, например, надо использовать его методы. Но ничего не знают о субклассах. |
BASH commands | $ cd / — переместиться в папку (local/bin — относительный путь, /local — абсолютный) $ pwd / — получить текущую дирректорию $ ls — список файлов директории $ ls -l /usr — файлы с подробной информацией $ ls -id /usr/local — получить инод намбер — уникальный номер дирректории $ mkdir won — сделать папку $ touch copyme — создать файл$ echo “firstfile” firstfile — принять переменую для записи в файл $ echo “firstfile” > copyme — записать переменную в файл справа $ cat copyme firstfile –вывод содержимого файла на терминал $ cp copyme copiedme — справа – название новой копии $ mv copiedme movedme — изменить наименование файла, либо его даже можно переместить: $ mv /var/tmp/myfile.txt /home/user $ rm file1 file2 – удаление файла (здесь – сразу нескольких, $ rm -i file1 file2 — удаление файла с запросом на подтверждение) $ rm -rf mydir — удаление директории со всем содержимым $ ls -d /etc/g* — вывод списка файлов, начинающихся с буквы g ссылки Первый вид называют жесткими ссылками. Каждый инод может иметь несколько связанных с ним жестких ссылок. Таким образом, получается что файл присутствует в системе под несколькими разными именами. Файл существует до тех пор, пока с его инодом связано хотя бы одно имя. Понятия «жёсткая ссылка на файл» и «имя файла» являются синонимами. Новые жесткие ссылки на файл можно сделать при помощи команды ln $ cd /tmp $ touch firstlink $ ln firstlink secondlink $ ls -i firstlink secondlink 15782 firstlink 15782 secondlink — на дирректории сделать нельзяСимлинк это специальный вид файла, который ссылается на другой файл по имени, а не напрямую на инод. Симлинки не предохраняют файл от удаления. Если файл удалить, то симлинк на него станет нерабочим (или битым). Симлинки создаются командой ln с опцией ‘-s’: $ ln -s secondlink thirdlink $ ls -l firstlink secondlink thirdlink -rw-rw-r– 2 agriffis agriffis 0 Dec 31 19:08 firstlink -rw-rw-r– 2 agriffis agriffis 0 Dec 31 19:08 secondlink lrwxrwxrwx 1 agriffis agriffis 10 Dec 31 19:39 thirdlink -> secondlink Символическую ссылку можно распознать по выводу команды ls -l: во-первых, в первой колонке у симлинков стоит буква ‘l’ (первая буква английского слова link–ссылка), во-вторых, размер симлинка равен количеству букв в имени файла на который он ссылается (‘secondlink’ в нашем случае), в-третьих, последняя колонка помимо имени ссылки содержит имя файла на который она ссылается после знака –>if [ “$myvar” -eq 3 ] then echo “myvar равно 3” fiif [ “$myvar” = “3” ] then echo “myvar равно 3” fihttp://linuxgeeks.ru/bash-2.htm http://www.thegeekstuff.com/2010/08/bash-shell-builtin-commands/ |
Bash синтаксис шаблона | Синтаксис шаблона: * и ? Мы посмотрели как работает глоббинг (подстановка имен файлов). А теперь рассмотрим подробнее синтаксис шаблонов: * соответствует нулю или большему количеству символов: /etc/g* — все файлы в директории /etc/ имена которых начинаются с “g” и файл с именем “g”. /tmp/my*1 — все файлы в директории /tmp имена которых начинаются с “my” и заканчиваются на “1” (включая файл с именем “my1”) ? заменяет один любой символ: myfile? — любой файл чье имя начинается со слова “myfile” за которым следует один любой символ. /tmp/notes?txt — соответствует файлам с именами “notes.txt” и “notes_txt” (если они существуют в /tmp/). Квадратные скобки: [] Шаблон ‘[]’ очень похож на ‘?’ но позволяет явно указывать набор символов. Шаблон ‘[]’ совпадает с одним символом из тех что указаны в скобках. Также в скобках можно указать диапазон символов (для этого используется символ –/дефис) или несколько диапазонов подряд, тогда шаблон будет совпадать с одним любым символом из этого диапазона: myfile[12] — соответствует myfile1 и myfile2. Шаблон будет работать пока существует хотя бы один из этих двух файлов. [Cc]hange[Ll]og — соответствует файлам с именами Changelog, ChangeLog, changeLog, и changelog. Как вы могли заметить, использование шаблона [] полезно при поиске имен отличающихся регистром букв. ls /etc/[0-9]* — вывести список файлов в директории /etc/ имена которых начинаются с цифры. ls /tmp/[A-Za-z]* — вывести список файлов в директории /tmp/ имена которых начинаются с буквы (заглавной или прописной) Конструкция [!] похожа на [], за исключением того что она соответствует единичному символу, не упомянутому между [! и ]. Например: rm myfile[!9] — удалит все файлы, имена которых состоят из слова “myfile” и идущей за ним одной цифрой, кроме файла “myfile9”. |
Свежая подборка курсов
За последние пол года я хотел бы отметить следующие, как мне кажется, важные курсы (по крайне мере для меня):
-
Introduction to Data Structures & Algorithms in Java: https://www.udemy.com/introduction-to-data-structures-algorithms-in-java/#/
-
Learn Test Driven Development in Java: https://www.udemy.com/learn-test-driven-development-in-java/#/
-
Advanced Java Programming: https://www.udemy.com/advanced-java-programming/#/
-
Selenium WebDriver Training with Java – Basics: https://www.udemy.com/selenium-training/#/
-
Programming for Entrepreneurs – JavaScript: https://www.udemy.com/javascript-tutorial/#/
-
Java Multithreading: https://www.udemy.com/java-multithreading/#/
И на закуску – курс coursera.org по алгоритмам (большое спасибо за него моим друзьям): https://class.coursera.org/algs4partI-006
А также в очередной раз напоминаю о существовании такого инструмента прототипирования как Balsamiq и Visio (недавно опять пробовал работать в Axure и снова не впечатлился)
Всем добра!
Delivery livecycle
Additional information (ru): http://software-testing.ru/forum/index.php?/topic/27165/
Статья “Введение в автоматизированное тестирование для аналитиков”
На странице Белорусского сообщества бизнес и системных аналитиков опубликована моя статья-заметка на тему автоматизированного тестирования для аналитиков (а я продолжаю обучение у Алексея Баранцева и могу давать свои комментарии по этому поводу).
А я опять прикладываю нечитабельный скрин:
Николай Гребнев, SWP11. TDD
Заранее приношу извинения за опечатки, пунктуацию и некоторые грамматически ошибки – мне было не до этого по ходу мероприятия (во время конспектирования)..
Кадровые риски – есть незаменимые люди, “Не знал и сломал”, квалификция сотрудника ниже (чем мы ожидали), обучение новых сотрудников.
Условия возникновения: кто-то уехал в отпуск, смена сотрудника, или уволился или же взяли нового сотрудника.
Короткие циклы разработчика, начиная тестов, далее под эти тесты мы пишем код запускаем вообще все тесты и правим до посинения. Переходим к следующему куску, начиная с написания теста. Здесь мы смотрим модульные тесты и их пишет тот же человек, который будет реализовывать.
Самый главный лозунг – тесты пишем вперед.
Юнит тест – мы тестируем класс и только класс и его взаимодействие с другими классами. Каждый класс тестируется отдельно.
Что вызывает риски – сильносвязанная архитектура (изменение одного объекта влияет ещё на 20, например). Проблема в том, что всё держим в голове… Позднообнаруженая ошибка, тут всё ясно. Плохая документированность тоже понятна (хотя у нас в компании с этим всё четко, даже с поддержанием актуальности).
Итак мы тестируем 1 класс. Декомпозиция долна быть и плохо связанная архитектура (плохо – не в плане качетсва). Человек быстро видит сои ошибки.
Что может дать ТДД?
Высокое качество, слабосвязанная архитектура, хороший дизайн кода, уверенностьп ри модификации. И тут – хлоп, и незаменимых уже якобы нет 🙂 Утрирую, но примерно так.
Выгодно в длительных проектах, с опытными людьми и желательно это делать сначала проекта. Вообще нужны опытные ребята. Короче доклад был мне полезен, пойду на обед.
Роман Шарыгин, SWP11. Эволюция процесса тестирования.
Заранее приношу извинения за опечатки, пунктуацию и некоторые грамматически ошибки – мне было не до этого по ходу мероприятия (во время конспектирования)..
Тесты – sanity tests, интеграционные, проверка на клиентских приложениях (как они с ним работают, in-depth tests, тесты производительности.
Аналитиков на схемках нет 😦
Разработчики отправляют изменения для билда – билд тряжер выбирает – то из этого выбрать. Проходит тестирование, что поломалось выкидывается, далее этот билд отправляется в список “Хороших.
Едем дальше.
Акивности перед выпуском продукта – за 2-3 недели начинается ручное тестирование продукта. Тут низкая скорость, высокие риски и видимо ничего хорошего. Это мы процесс с картинки обсуждаем, если что.
Сделали:
Сделали санити тесты (жестко ограничены по времени – не более 30 мин) и праймари пул (тестирование задач первого приоритета). Билд ряжера – ввели принцип дежурства, каждый вовлечен в процесс + общедоступная конфигурация. Объеденили QA и разработчиков (работают вместе и позволяю разработчикам проектировать продукт с тем условием, что его потребуется тестировать). Высокие риски сменили на регуярную автоматизированную ежедевную активность – application and perfomance tests. Как стало – см картинку. Санити тесты делаются на маленьком числе конфигураций (мог не так понять).
Перед релизом осталос ручное тестироание. in-peth and app tests. App tests могут быть с участием людей, но человек менее вовлечен. Активности за 1-2 недели. Сдвиг релиза маловероятен.
В итоге наступило счастье. А, счастье есть, но надо ещё больше счастья.. Билд тряжера автоматизировать надо, а, приметил, что нужен Аджайл 🙂 Как же без него в докладе))))) Ещё статистика покрытия кода и интеграция иснтрменов статического анализа кода
Алексей Теренин, SWP11. Тестирование хранилищ данных.
Заранее приношу извинения за опечатки, пунктуацию и некоторые грамматически ошибки – мне было не до этого по ходу мероприятия (во время конспектирования)..
Я снова тут, вчера, кстати, Максом Цепков выложил обзор первго дня (вечером).
Идет теория про хранилища данных (я заслушался, даже сюда не записывал). Хранилие надо чтоб быстро строить отчеты и не джоинить данные до сумасшествия. Позволяют быстрее реагироватьи гибче отвечать на изменения (короче консолидация данных).
Вутренние причины для внедрения – системы содержат часть инфы, и не могут содержать всё и вся.
Копятся данные – можно строить прогнозы и проч (то есть копим историю).
Дефекты хранилищ – плохое качество данные.
Витрины даных – хранят уже подготовленные данные.
Решения – по команде, кто имеет доступ (консультантов могут нанять). Лучше всего – запустить пилотный проект. Администраторов лучше определить в начале.
Разрабатывам – сверху вниз (от требовани) и снизу вверх (от данных).
Тестовая стратегия – из стратеги тестирования кадого компонента. Отсюда идут требования к тестированию и ресурсы (вкл железки и тп).
Этапы – анализ требований, проектирование, загрузка ифы и тд. Главное – что по итогам надо тестировать.
Тестировать уже можно н а этапе проектирования.
Источнки гетерогенны и нужно учесть, как мы из будем собирать. Это ETL.
Этап первоначальной загрузки – заполняем хранилищ данных. Процесс итеративный и может занимать несколько лет.
Вообще если посмотреть его слайды, то мою писанину можно не читать. Доклад отличный, буду только слушать.
Лассе Коскела, SWP11. Спецификация через пример.
Заранее приношу извинения за опечатки, пунктуацию и некоторые грамматически ошибки – мне было не до этого по ходу мероприятия (во время конспектирования)..
Поломали крыло самолета – впечатлило 🙂 Проверка – берем требование – то ли это, что нам надо. Подтверждение – мы это точно знаем, что надо, но отвечаем ли мы этому (можем ли мы это), это работа инженерного характера.
Если вы не можете спрогнозировать результаты испытания – вы не понимаете продукт. Мы должны понимать то, что нам необходимо. При тестировании надо устранить недостатки. Неисправноть – то что происходит из ряда источников (программирование и т.п.). Необходим делать конкретные примеры или клиентский обзор. Спеификация чрез пример – использование всех членов команды, отсюда повышается эффективность автоматизации тестирования.
Проверка и понимание спецификации самое главное.
Собираем всех членов команды, прекращаем абстрактные вещи и начинаем привоить примеры (забываем про формулы и тп). Конкретный пример – самый полезный. Бумага для таких примеов наиболее эффективна.
Необходимо сотрудничество людей с разными ролями.
Не надо сосредотачивать все усилия на деталях вместо общих целей. Не нужно слишом детализировать спецификации.
Не надо пытаться решать все проблемы и создавать все примеры. Спецификация – не пример для тестирования.
Не надо сосредотачитваться на инструментарии! Главное – продукт.
Уделяйте достаточное внимание обучению.
Действия необходимо согласовывать с заказчиком. (что-то я тут упустил, если что)
Главное уметь выделить правильные примеры