Паттерн Декоратор — специальный способ организации модулей в программе, который позволяет подставить какую-то новую функцию прямо в середину цепочки вызовов, тем самым чуть-чуть подкорректировав поведение.
Например, в реальном мире очки для чтения это декоратор. Вы ставите их между вашими глазами и текстом. Глобально взаимодействие ваших глаз и текста не меняется: отражённые световые лучи от страницы книги попадают в ваши зрачки, что с очками, что без них. Но очки располагаются посередине: они принимают лучи на вход и преломляют их, передавая дальше вам в глаза уже изменёнными.
Важной особенностью является тот факт, что очки можно снять. Они не требуют ни модификации вашего тела, ни модификации книги. Вообще никакие условия не нужны, кроме наличия самих очков. А если вы в линзах, то внешний наблюдатель может даже этого не знать.
Класс-декоратор должен быть спроектирован так, чтобы не требовать никаких изменений в объектах, с которыми он работает. Его можно отключить, чаще всего буквально закомментировав одну строку.
В примере ниже программа выведет текст "Привет, мир, в натуре.", и вот это дополнение в конце как раз дописано декоратором. Можно убрать или закомментировать подчёркнутую строчку, не трогая остальной код, для всех внешних вызовов сигнатуры останутся теми же самыми, но выводиться будет уже просто "Привет, мир".
В декораторы можно прятать логику, которую буквально навешивают поверх основной функции программы. Например, проверку прав на выполнение операции. Перевод на другой язык, логирование, поддержку обратной совместимости при обновлении и так далее.
#dev
#npm#nodejs#dasturlash_hayoti
NPM — paketlar, package.json va oddiy qo‘llanma
NPM — Node.js ekotizimidagi paketlar ombori va paket menejeri. package.json loyihaning “pasporti”.
Boshlash:
npm init -y # package.json yaratadi
npm install express # express o'rnatish (dependencies)
npm install -D nodemon # ishlab chiqishda dev dependency
package.json skript misoli:
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js",
"test": "jest"
}
Eslatma:
◾️package-lock.json loyihaning qat’iy versiyalarini saqlaydi — uni gitga qo‘yish kerak.
◾️node_modules/➡️.gitignore ga qo‘ying (reponing ichiga kiritmang).
◾️npm audit bilan xavfsizlik tekshiruvini bajaring.
Maslahat:
◾️Kichik loyihalarda ham scripts dan foydalaning — bir buyruq bilan test, build va start qilinadi.
◾️Global o‘rniga lokal paketlarni afzal ko‘ring (-g dan saqlaning).
NPM bilan ishlashni o‘rganish — Node ekosistemida samarali bo‘lishning asosiy sharti.
Oramizda 📱Node.js ni biladiganlar bo'lsa reaksiya qoldiring 🔥
💻@dasturlash_hayoti— xatosiz kod bo‘lmaydi😅
THE COMPOSITION OF THE COORDINATING COUNCIL OF THE NPM AGAINST TORTURE UNDER THE COMMISSIONER FOR HUMAN RIGHTS IN THE REPUBLIC OF KAZAKHSTAN HAS BEEN UPDATED
July 26, 2022 – The next online meeting of the updated composition of the Coordinating Council of the National Preventive Mechanism against Torture (NPM) was held under the chairmanship of the Commissioner for Human Rights in the Republic of Kazakhstan Elvira Azimova.
The members of the Coordinating Council discussed issues of strengthening independent monitoring on the ground, interacting with the regional representative offices of the Commissioner, as well as participating in the discussion of draft laws on improving criminal and criminal procedure legislation, taking into account the recommendations of the NPM participants. Within two months, the presentation and discussion of the consolidated NPM report on the results of visits to social institutions, institutions where citizens are located by court decision or based on a verdict will take place. The presentation will be held with the invitation of local self-government bodies and central bodies, including the Prosecutor General's Office, which oversees compliance with the rule of law, representatives of public councils, and boards of trustees of institutions. During the presentation of the report, the participants will talk about the violations identified on the ground.
Updated composition of the Coordinating Council By the link: https://www.gov.kz/memleket/entities/ombudsman/press/news/details/401234?lang=ru
#Ombudsman#HumanRights#CoordinatingCouncil#NPM
https://www.gov.kz/memleket/entities/ombudsman/press/news/details/405528?lang=en
NEW MEMBERS OF THE COORDINATING COUNCIL OF THE NATIONAL PREVENTIVE MECHANISM HAVE BEEN ELECTED
On July 5, 2022, a meeting of the commission for the election of members of the Coordinating Council for the activities of the National Preventive Mechanism (NPM) was held.
The Commission under the Commissioner for Human Rights included: Deputy of the Senate of the Parliament of the Republic of Kazakhstan Nurlan Beknazarov, Deputy Prosecutor General of the Republic of Kazakhstan Asset Chindaliev, Head of the National Center for Human Rights Zere Utebayeva, Secretary of the Human Rights Commission under the President of the Republic of Kazakhstan Tastemir Abishev, Executive Director of the Charter for Human Rights Public Foundation Zhemis Turmagambetova, Director Kazakhstan International Bureau for Human Rights and Rule of Law Yevgeny Zhovtis, Commissioner for Children's Rights in Kazakhstan Aruzhan Sayn, Head of the Department of Effective Governance and Territorial Development of the United Nations Development Program in Kazakhstan Ainur Baymyrza, Director of the Center for Applied Research TALAP Rahim Oshakbayev.
According to the results of a secret ballot, 10 citizens of Kazakhstan were elected from among the citizens who submitted their applications for participation in the activities of the NPM for the prevention of torture and ill-treatment.
The updated list of members of the Coordinating Council will be available on the website of the Commissioner for Human Rights in the Republic of Kazakhstan at the link: https://www.gov.kz/memleket/entities/ombudsman/activities/1030?lang=ru.
#Ombudsman#HumanRights#CoordinatingCouncil#NPM
ОМБУДСМЕН И ПРАВОЗАЩИТНИКИ ОБСУДИЛИ КОНСТИТУЦИОННЫЕ ПОПРАВКИ, ВЫНОСИМЫЕ НА РЕСПУБЛИКАНСКИЙ РЕФЕРЕНДУМ
2 июня в формате онлайн состоялась дискуссия с участием Омбудсмена и участников Национального превентивного механизма в связи с конституционными поправками, выносимыми на республиканский референдум. Он пройдёт 5 июня 2022 года. Участники встречи обменялись мнениями по предлагаемым поправкам и предстоящей законотворческой работе по их реализации. Напомним, что принятие поправок в Конституцию повлечёт внесение изменений в действующие законы и принятие новых трёх конституционных законов - о Конституционном суде, прокуратуре и Уполномоченном по правам человека.
В ходе обсуждения правозащитники озвучили рекомендации по обеспечению эффективности предстоящего законотворческого процесса, широком обсуждении проектов законов, которые будут разработаны в реализацию конституционных поправок. Правозащитники обозначили основные моменты, на которые должны обратить внимание разработчики проектов законов, чтобы не допустить превышение полномочий со стороны государственных органов при реализации новых конституционных механизмов.
Участники встречи обменялись мнениями относительно принятого второго плана Правительства о дальнейших мерах в области прав человека и верховенства закона. Правозащитники предложили алгоритм действий, усиливающий новый механизм защиты конституционных прав и свобод граждан и выразили готовность участвовать в его разработке и обсуждении.
#ОмбудсменKZ#ПраваЧеловека#NPM#НПМ