Сообщения

maven

  mvn dependency:tree -Dverbose -Dincludes='org.apache.lucene' find ~/.m2/ -name "*.lastUpdated" | xargs rm src:  https://stackoverflow.com/a/26974691/2910338 maven опцию --thread для параллельной сборки проекта mvn dependency:purge-local-repository mvn spring-boot:run -Dspring-boot.run.profiles=foo,bar [ERROR] After correcting the problems, you can resume the build with the command [ERROR]  mvn <args> -rf :afd-vtb-aaap-ora-calc java -jar spring boot profile https://stackoverflow.com/a/37439625/2910338   https://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven https://stackoverflow.com/questions/30207842/add-external-library-jar-to-spring-boot-jar-internal-lib https://stackoverflow.com/questions/2065928/maven-2-assembly-with-dependencies-jar-under-scope-system-not-included https://www.apache-maven.ru/ ************************************* можно выкинуть пакеты из java 11*************************  ...

docker

start downloaded container: docker start hash or name from docker ps -a docker build ./ -t findli/ubuntu_base:18_03_2023 ************ docker-compose:     build:       context: ./frontend - контекст это директория в которой будет искаться dockerfile       dockerfile: Dockerfile равнозначно:     build:       #context: ./frontend       dockerfile: frontend/Dockerfile ************ ************ ********** error:  when docker-compose up --force-recreate --build --remove-orphans langapp-back strconv.Atoi: parsing "": invalid syntax to fix: comment existing containers in docker-compose.yaml file. replace them by something else. then docker compose up --remove-orphans then revert suspicious containers in docker-conpose file then docker compose up will work. src: https://github.com/docker/compose-cli/issues/1537#issuecomment-1284828193  ********** ********** https://stackoverflow.com/a/52...

@EnableWebMvc and LocalDateTime

@Configuration //@EnableWebMvc - if uncomment this then LocalDateTime will be as arrays public class WebConfig implements WebMvcConfigurer {

unix linux usefull commands; clear up disk space

df -h ncdu - check directory sizes ss -plunt for app and port list  clear log:  rm /var/log/btmp.* journalctl --disk-usage journalctl --vacuum-size=50M journalctl --verify nano /etc/systemd/journald.conf SystemMaxUse=50M SystemMaxFileSize=12M systemctl restart systemd-journald nano /etc/logrotate.conf daily rotate 1 https://unix.stackexchange.com/a/605809/346938 https://www.linuxuprising.com/2019/04/how-to-remove-old-snap-versions-to-free.html

elasticsearch howeaver

------------------------------- elasticsearch download zip elasticsearch.yml: # allow CORS requests from https://tauri.localhost http.cors.enabled: true http.cors.allow-origin: "https://tauri.localhost" # and if your cluster uses authorization: http.cors.allow-headers: X-Requested-With,Content-Type,Content-Length,Authorization action.auto_create_index: .monitoring*,.watches,.triggered_watches,.watcher-history*,.ml* roles.yml: # The default roles file is empty as the preferred method of defining roles is # through the API/UI. File based roles are useful in error scenarios when the # API based roles may not be available. admins:   cluster:     - all   indices:     - names:         - "*"       privileges:         - all devs:   cluster:     - manage   indices:     - names:         - "*"       privileges:         - write ...

consul

The downside with choosing the "first address" is that in the case of a docker network overlay, the first ip will likely be the wrong one. It would be better if it would bind to all ip's on a given interface, if you don't want it to bind to all of them then the ip should be specified. Perhaps something like: --bind eth0 to bind to all ip's on a given interface --bind eth0;10.0.0.0/16 bind to any ip on a given interface that matches the given cidr. --bind eth0;10.0.0.5 bind to a specific ip on a given interface --bind 10.0.0.5 bind to a specific ip regardless of interface --bind 10.0.0.0/16 bind to a given ip that matches a cidr regardless of interface

CORS another one

devtools console helps: Access to XMLHttpRequest at 'http://localhost:8443/api/essay/6' from origin 'http://localhost:8082' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Access to fetch at 'http://localhost:8443/graphql' from origin 'http://localhost:8082' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. login:109 Access to fetch at 'http://localhost:8443/graphql' from origin 'http://localhost:8082' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on th...

@Transactional(propagation = Propagation.REQUIRES_NEW)

 @Transactional(propagation = Propagation.REQUIRES_NEW)     public BigDecimal getCurrentUserBonus(UserEntity user) { final Page<UserProfileDto> map = filtered.map(user -> {             UserEntity user2 = userService.fetchAllEagersUser(user);             BigDecimal currentUserBonus = userService.getCurrentUserBonus(user2);             user2.setCurrentBonusBalance(currentUserBonus);// it's async!!!!!!!!!!!             return new UserProfileDto(user2);         });

js.. what can I say more?

typeof null == 'object' typeof null === 'object' * let var = var2 ?? 'default_if_null'; * obj.mayNotExistFunc?.() - same as obj1?.obj2?.param1 obj1.mayNotExistArray?.[0] - check if it's non undefined and it's array * script defer - stay in header before dom elements used in script anbd it's work - no need to put it in the end of dom.  src: https://www.youtube.com/watch?v=v2tJ3nzXh8I&t=51&ab_channel=WebDevSimplified  * console.log("%c blabla %c blabla2", "color:red", "color:green"); todo https://www.youtube.com/watch?v=yJDofSGTSPQ&t=562s&ab_channel=WebDevSimplified 

postgres allow only one null value contrain

 The i_nulltest2 index allows only one y null value for each x value.  src: https://www.enterprisedb.com/postgres-tutorials/postgresql-unique-constraint-null-allowing-only-one-null 

и снова здрасьте - reactjs спустя годы - понаделали тут всякого понимашь!

https://stackoverflow.com/a/70937134/2910338 events - syntheticEvent - in reactjs events catches from root mount dom element. that's why propagation goes from top to bottom. на самом верхнем уровне где react app там ловятся все события и создается реакт SyntheticEvent - потом прежде чем всплывет к корню dom дерева проходит через них всех. event.stopPropagation(); src: https://blog.saeloun.com/2021/07/08/react-17-event-delagation.html  https://habr.com/ru/post/467361/ console.trace(); *************** error boundary( componentDidCatch) в хуках нет аналога хуки неззя юзать в классах хуки можно юзать только в react компонентах и в других хуках хуки неззя использовать в циклах и условиях тк значения хуков пишутся последовательно в массив внутри реакта. useCallback кеширует функцию  useMemo кеширует результат функции useCallback и useMemo не гарантируют что будут вызваны только при мутировании функции/данных - это лишь оптимизация производительности. const usePlanetName = (id) ...

algos

 public static T[] slice<T>(T[] l, int from, int to) {     T[] r = new T[to - from];     for (int i = from; i < to; i++)     {         r[i-from]=l[i];     }     return r; } src: https://stackoverflow.com/a/32965043/2910338 

access token vs refresh token differences and why refresh token hasn't been exposed to web browser( SPA among them).

in short: refresh token lived in about a year or more. access token should be valid for a short amount of time. when refresh token compromised it means that hacker can get access for a year. description: refresh token accepts by authentication server with user id and user secret code. access token purpose is to get resources from resourceS servers which can have lacks in security. that's why access token short lived. that's why SPA send to the server email and password over https and then api server which is secured properly send to oauth2 authentication server reguest with user id and user secret. then oauth2 auth server response with access token and refresh token. then api server keeps refresh token locally( it means securely) and response to SPA with only short lived access token. then SPA send access token to resources servers.  so I can conclude access tokens is just the way not to store session through cookies in the case of SPA. and I can assume that SPA should track ex...

debugging...

Изображение
 

spring transaction annotation quirks

  По умолчанию Spring откатывает транзакции только в случае   непроверяемого  исключения.   Проверяемые   же считаются «восстанавливаемыми» из-за чего Spring вместо   rollback   делает   commit . Поэтому   personRepository.count()   возращает   2 . Самый простой исправить это — заменить  Exception  на непроверяемое исключение. Например,  NullPointerException . Либо можно переопределить атрибут  rollbackFor  у аннотации. Когда какой-нибудь bean указывает транзакционный сервис в качестве DI зависимости, Spring на самом деле внедряет прокси. Параметр  propagation  у  @Transactional  по умолчанию имеет значение  REQUIRED . Это значит, что новая транзакция создается, если она отсутствует. Иначе выполнение продолжается в текущей. Так что в нашем случае весь запрос выполняется в рамках единственной транзакции. Однако здесь есть нюанс. Если  RuntimeException  был выброшен из-за гра...

Рекурсивный запрос на postgres

 src: https://devmark.ru/article/postgres-recursive-query ))

Clean Architecture another аля дядя Боб

Clean Architecture : Layers ( from the most abstract to the most concrete ) : domain : abstract data structures uc : "use cases", the pure business logic implem : implementations of the interfaces used in the business logic (uc layer) infra : setup/configuration of the implementation Golden rules : a layer never imports something from a layer below it 3rd-party libraries are forbidden in the 2 topmost layers  

kafka конспект однако

------------------------ part 1 ---------------------  schema evolution 1: avro - в сообщении содержится схема данных. предоставляет API для сериализации данных соответственно схеме и десериализации по схеме. exactly once processing: тут проблема в том что нет контроля над тем какой partition будет назначен. есть две стратегии: range: round robin: rebalance listener: случай когда consumer group coordinator запустил rebalance и consumer, обработавший часть сообщений хочет commit offset. чтобы это сделать надо знать: how to commit a particular offset? how to know that a rebalance is triggered? ConsumerRebalanceListener onPartitionsRevoked - будет вызван перед переключением partition. onPartitionsAssigned - будет вызвано после назначения partition и перед передачей сообщений. offset management: current offset: kafka broker у себя хранит указатель на на отправленные сообщения клонкретному consumer. maintain offset from which send next banch of ...

java serialize object for json

commonlang 3  //      var cloneDto = SerializationUtils.clone(puvMv26InfoPaymentDto); //      cloneDto.setReportingPeriod("3");

totp 2fa c# net core reactjs

 https://deblokt.com/2020/01/24/07-identityserver4-mfa-totp-net-core-3-1/ рабочая версия https://github.com/kspearrin/Otp.NET <img src="data:image/png;base64, ..." /> https://github.com/esp0/googleAuthNet.git тут старая версия. it appears for google auth app its need to be used special algo  this lib uses different algo so it's not work with google auth app : https://github.com/brandonpotter/GoogleAuthenticator