묻고 답해요
158만명의 커뮤니티!! 함께 토론해봐요.
인프런 TOP Writers
-
미해결[C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part3: 유니티 엔진
press, pointdown, pointup부분이요
24줄의 코드가 이해가 되지 않아서 문의 드려요.왼쪽 마우스 버튼을 클릭한 이벤트가 발생 시에, 처음으로 누른상태라면 PointDown 이벤트와 누른시간을 적립해주는 걸로 보이는데요. 여기서 PointDown은 길게 누르고 있는 상태로 알고 있는데요. 이미 한번 눌려진 상태 pressed =true에서 왼쪽마우스 이벤트가 발생했을 시에 실행시켜줘야 하는거 아닌가 의문이 들어서요. 24줄에서의 조건을 _pressed ==true일 때로 고쳐야 되는거 아닌가 의문이 들어서요. ㅠ 또, 36라인에서 Time.time은 실행시간이라고 알고 있는데 이거는 마우스 왼쪽버튼을 클릭하지 않은 실행시간, 즉 마우스를 뗀 시점에서부터 실행시간을 의미하는건가요? 저는 36줄에서 if(_pressedTime < 0.2f) 이렇게 수정하면 클릭으로 판별하는 건 줄 알았는데 어떻게 코드를 분석해야 할지 모르겠어요. 완강하고 프레임워크를 익히려 혼자 분석하고 코드를 쳐보면서 외우고 있는데요. 궁금증이 생기네요.
-
해결됨[퇴근후딴짓] 빅데이터 분석기사 실기 (작업형1,2,3)
빅분기 실기 체험 작업형 2 문제 관해서 질문드립니다!
안녕하세요 선생님 실기 체험 작업형 2문제 관련해서 질문드립니다. 고객의 성별 값에 대한 확률을 구하는 문제인데 여자와 남자중에 어떤 성별의 예측 결과를 구하는지 명시가 안되어 있어서요 이럴 때는 여자인 확률을 구하는건가요 아니면 남자인 확률을 구해줘야 하는건가요? 이때 동안 계속 양성인 1의 확률을 구해왔는데 실제 시험 때도 이렇게 명시가 안되어 있나 해서 질문드립니다.성별 (0: 여자, 1:남자)predict_proba[:,0] 여자 : 0 predict_proba[:,1] 남자 : 1
-
해결됨2주만에 통과하는 알고리즘 코딩테스트 (2024년)
(해결)정수론 #1978 자바코드로는 통과, 파이선으로는 통과가 안돼요...
+) 자바코드로는 통과했습니다. 파이썬코드로는 왜 통과를 못하는 걸까요?ㅠㅠimport java.util.Scanner; public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int N = s.nextInt(); int [] num = new int[N]; int cnt = 0; for(int i = 0; i<N; i++){ num[i] = s.nextInt(); if(num[i] == 1) continue; int j; for( j= 1; j<(int)Math.sqrt(num[i])+1; j++){ if((num[i] % j == 0) & (j != 1)) break; } if(j == (int)Math.sqrt(num[i])+1) cnt += 1; } System.out.println(cnt); } } 파이선은 백준에 제출했는데 틀렸다고 나옵니다... 제 알고리즘에 문제를 찾아주실 수 있나요?ㅠㅠimport math #약수 빠르게 구하기(n의 제곱근까지만 구하기) #1978 N = int(input()) num = list(map(int, input().split())) cnt = 0 for i in range(len(num)): if num[i] == 1: continue for j in range(1, int(math.sqrt(num[i])+1)): if ((num[i] % j == 0) & (j != 1)): break if (j*j != num[i]) & (j == int(math.sqrt(num[i]))): cnt += 1 print(cnt)
-
해결됨코딩테스트 [ ALL IN ONE ]
백트래킹
안녕하세요!백트래킹 강의들은 언제 업로드가 완료되나요?
-
미해결10주완성 C++ 코딩테스트 | 알고리즘 코딩테스트
8-U 다른풀이 질문
안녕하세요 큰돌 선생님 강의 감사합니다..해당 문제를 처음에 보고 dp로 풀 수 있을것 같아서 접근했는데 원하는 답이 나오지 않아 선생님 강의를 보고 다익스트라로 해결하였습니다.근데 혹시 이 문제 dp로는 해결할 수 없을까요?http://boj.kr/b2b9e324cd1644e7a5edb8caf23830aa처음 dp로 해결하려던 코드입니다. 사실 예제 2번 부터 답이 틀려서 완전 틀린 코드이지만 어디가 틀렸는지 잘 모르겠습니다.dp의 매개변수로는 y좌표, x좌표, 그리고 d라는 이전에 왔던 방향을 뜻하는 매개변수를 넣었습니다. 현재의 값이 상하좌우 어디에서 온건지에 따라 최적의 값이 달라지기에 d를 추가하였습니다.dp배열의 초기값은 -1로 초기화했고, 또한 방문여부를 해결하기 위해서 visited배열을 만들어 해결하였습니다.
-
미해결
c++ 엑세스 위반 질문..
c++를 이용하여 kiosk 프로그램을 만들고 있는 과정 중 실행을 했는데 엑세스 위반으로 프로그램이 종료됩니다.. 어떻게 해야할지 모르겠어서 질문 올립니다 ㅜㅜ 도움 부탁드립니다..queue 이용하여 공부차원으로 해보았는데 실행이 되지 않아서 도움 부탁드립니다!!<전체 코드> #include<iostream> #include<string> #define MAX_SIZE 10 using namespace std; class Kiosk { //Kiosk Class가 queue 역할 int t_number; int size; string name; public: int queuemoney = 0; Kiosk* queue; Kiosk(); Kiosk(int size_in); ~Kiosk(); static int AllMoney; static int front; //front : queue의 앞 요소를 가리킴 static int rear; //rear : queue 마지막 요소 가리킴 static int real_size(); //queue 현재 사이즈 void Money(int Money, int index); void push_drink(string name_in, int table); void show(); //현재 주문 현황 real_size를 이용하기 string bring_menu(); bool Menu_payment(char check_in, int table_num_in); bool isfull(); bool isEmpty(); }; int Kiosk::AllMoney = 0; //전체 매출액 int Kiosk::front = 0; int Kiosk::rear = 0; Kiosk::Kiosk() { t_number = 0; size = 0; name = " "; queuemoney = 0; } Kiosk::Kiosk(int size_in) { this->size = size_in; queue = new Kiosk[MAX_SIZE]; if (queue == NULL) { cout << "메모리 할당 실패"; } } Kiosk::~Kiosk() { delete[]queue; } void Kiosk::Money(int Money, int index) { AllMoney += Money; //전체 매출액 queue[index].queuemoney = Money; } void Kiosk::show() { for (int i = 0; i < real_size(); i++) { cout << queue[(front + i) % this->size].t_number << "번 테이블 음료 제작 중입니다 : " << queue[(front + i) % this->size].name; } } int Kiosk::real_size() { return(front > rear ? front - rear : rear - front); } void Kiosk::push_drink(string name_in, int table) { //enqueue if (isfull()) { cout << "메뉴를 더 이상 주문 할 수 없습니다." << endl; } else { queue[rear].name = name_in; //queue(rear번호)에 음료 이름을 넣음 rear = (rear + 1) % this->size; //rear값을 계속 초기화 queue[rear].t_number = table; //table_num 저장 } } string Kiosk::bring_menu() { if (!isEmpty()) { return queue[front].name; front = (front + 1) % this->size; } else cout << "메뉴가 없습니다." << endl; } bool Kiosk::isEmpty() { if (front == rear) return true; else return false; } bool Kiosk::isfull() { if (rear + 1 % size == front) return true; else return false; } bool Kiosk::Menu_payment(char check_in, int table_num_in) { if (check_in == 'Y' || check_in == 'y') { cout << "총 결제 금액은 " << queue[table_num_in - 1].queuemoney << "원입니다." << endl; return true; } else { cout << "다시 결제 해주세요 " << endl; return false; } } class Menu :public Kiosk { int index; int price; int number; string name; public: Menu(int index_in, string menu_in, int price_in); void Menu_list(); void Menu_select(int table_num_in, Menu& M_selc, int number); }; Menu::Menu(int index_in, string menu_in, int price_in) { this->index = index_in; this->name = menu_in; this->price = price_in; } void Menu::Menu_list() { cout << "###### MENU_LIST #####" << endl; cout << "Number Menu Price" << endl; cout << "#1 Ice Americano 4500" << endl; cout << "#2 Ice Latte 5000" << endl; cout << "#3 Ice Tea 5000" << endl; cout << "#4 Chamomile 6000" << endl; cout << "#5 Caramel Macchiato 6500" << endl; cout << "#####################" << endl; cout << "1. 주문입력\n2. 주문현황\n3. 가게 매출\n4. 종료\n#####################" << endl; cout << "번호를 입력하시오 >> "; } void Menu::Menu_select(int table_num_in, Menu& M_selc, int number) { int price = 0; price = M_selc.price; Money(price, table_num_in - 1); } int main() { Menu M[5] = { Menu(1,"Ice Americano",4500),Menu(2,"Ice Latte",5000),Menu(3,"Ice tea",5000),Menu(4,"Chamomile",6000),Menu(5,"Caramel Macchiato",6500) }; Menu* M_ptr; M_ptr = M; int select; int table_num; //손님 이름 int number;// 주문 수(음료 갯수) int price; //가격 int cafe_num; //음료번호 string name[10]; string name_sum; Kiosk queue(10);//최대 주문 수 10개, queue 사이즈 10 int x = 0; while (1) { M_ptr->Menu_list(); //메뉴판 호출 cin >> select; //번호 입력 if (select == 1) { cout << "테이블 번호를 입력해주세요 >> "; cin >> table_num; cout << "몇 잔을 주문하시겠습니까? >> "; cin >> number; //갯수 ++x; if (number > 1 && number < 11) { for (int i = 0; i < number; i++) { cout << "음료 번호와 메뉴 이름을 작성해주세요 >>"; cin >> cafe_num; getline(cin, name[i]); name_sum += name[i]; M_ptr[cafe_num - 1].Menu_select(table_num, M_ptr[cafe_num - 1], x); } queue.queue[table_num - 1].push_drink(name_sum, table_num - 1); } else if (number == 1) { string name_1; cout << "음료 번호와 메뉴 이름을 작성해주세요 >> "; cin >> cafe_num; getline(cin, name_1); M_ptr[cafe_num - 1].Menu_select(table_num, M_ptr[cafe_num - 1], x); queue.queue[table_num - 1].push_drink(name_1, table_num - 1); } char check; restart: cout << "주문 결제 하시겠습니까? ( Y / N ) >> "; cin >> check; int skip = queue.queue[table_num - 1].Menu_payment(check, table_num); if (skip == 1) { cout << "결제가 완료 되었습니다. 잠시만 기다려주세요. " << endl; string bring_menu; bring_menu = queue.queue[table_num - 1].bring_menu(); cout << table_num << "번 테이블 " << bring_menu << " 나왔습니다." << endl; } else if (skip == 0) goto restart; } else if (select == 2) { queue.show(); //실시간 주문현황 } else if (select == 3) { for (int i = 0; i < x; i++) { cout << table_num << "번 테이블 판매액 : " << queue.queue[table_num - 1].queuemoney << endl; } cout << "전체 매출액 : " << queue.AllMoney << endl; } else if (select == 4) { cout << "종료" << endl; break; } } return 0; }
-
해결됨[개정3판] Node.js 교과서 - 기본부터 프로젝트 실습까지
자바스크립트 변수 스코프에 대해 질문드립니다.
강사님 안녕하세요변수 스코프에 대해 질문드립니다.자바스크립트는 변수를 참조할 때 현재 블록 부터 시작해 상위 블록으로 올라가며 변수를 찾는다고 이해하고 있습니다.그래서 아래의1번째 코드는 이해가 됩니다.const b=10; 함수(a=>({ a: b //b는 10입니다. }));여기서 2번째 b는 상위 블록으로 올라가며 const b =10 을 찾습니다.그래서 a: 10이 됩니다. 그러나 2번째 코드의 경우 이해가 어려웠습니다.const b=10; 함수(b=>({ //b는 undefined 입니다. a: 11 }));이때는 콜백함수의 매개변수 b에 10이 아닌 undefined가 들어갑니다.여기서 이해가 어려웠습니다.자바스크립트는 변수를 참조할 때 현재 블록 부터 시작해 상위 블록으로 올라가며 변수를 찾습니다. 그렇다면 1번째 코드처럼 2번째 코드에서도 파라미터 b에 10이 들어간다고 생각했는데, 제가 잘못 생각한 부분을 가르쳐주시면 감사하겠습니다.
-
미해결실무자를 위한 구글애널리틱스(GA4+GTM) 활용법(25년 Update)
cafe24 실습용쇼핑몰
섹션1에서 실습용 쇼핑몰 만드셨는데 과정이 거의 다 생략된 것처럼 보입니다...cafe24 들어가서 회원가입까지는 마쳤고 그 이후에 쇼핑몰 개인설정 부분은 어찌저찌 따라가긴했는데실습용쇼핑몰은 어떻게 따로 만들어진건지 아예 설명이 없어서요따로 사업자등록을 해야하는건지 어떻게 해야하는 건지 막혀서 글 남기게 되었습니다.
-
미해결실전! 스프링 부트와 JPA 활용1 - 웹 애플리케이션 개발
테스트 에러 질문드립니다.
package com.service.com.service; import static org.junit.Assert.assertEquals; import javax.persistence.EntityManager; import javax.transaction.Transactional; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import com.service.com.domain.Member; import com.service.com.repository.MemberRepository; @RunWith(SpringRunner.class) @SpringBootTest @Transactional public class MemberServiceTest { @Autowired MemberService memberService; @Autowired MemberRepository memberRepository; @Autowired EntityManager em; @Test public void 회원가입() throws Exception{ Member member = new Member(); member.setName("Kim"); // when Long saveId = memberService.join(member); // then assertEquals(member, memberRepository.findOne(saveId)); } @Test(expected = IllegalStateException.class) public void 중복_회원_예외() throws Exception { Member member1 = new Member(); member1.setName("kim"); Member member2 = new Member(); member2.setName("kim"); fail("예외가 발생해야 한다"); } } 2023-11-16 20:00:08.269 INFO 22664 --- [ main] o.s.t.c.transaction.TransactionContext : Rolled back transaction for test: [DefaultTestContext@1c3b9394 testClass = MemberServiceTest, testInstance = com.service.com.service.MemberServiceTest@5cc152f9, testMethod = 중복_회원_예외@MemberServiceTest, testException = java.lang.AssertionError: Expected exception: java.lang.IllegalStateException, mergedContextConfiguration = [WebMergedContextConfiguration@6f2cfcc2 testClass = MemberServiceTest, locations = '{}', classes = '{class com.service.com.JpashopApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@4310d43, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@3527942a, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@4f80542f, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@576d5deb, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@2794eab6, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@3972a855], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -> true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -> true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -> false]]java.lang.NoSuchMethodError: org.junit.platform.engine.TestDescriptor.getAncestors()Ljava/util/Set;at org.junit.platform.launcher.core.StackTracePruningEngineExecutionListener.getTestClassNames(StackTracePruningEngineExecutionListener.java:50)at org.junit.platform.launcher.core.StackTracePruningEngineExecutionListener.executionFinished(StackTracePruningEngineExecutionListener.java:39)at org.junit.platform.launcher.core.DelegatingEngineExecutionListener.executionFinished(DelegatingEngineExecutionListener.java:46)at org.junit.platform.launcher.core.OutcomeDelayingEngineExecutionListener.reportEngineFailure(OutcomeDelayingEngineExecutionListener.java:83)at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:203)at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:169)at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:93)at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:58)at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:141)at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:57)at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:103)at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:94)at org.junit.platform.launcher.core.DelegatingLauncher.execute(DelegatingLauncher.java:52)at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:70)at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:529)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)plugins {id 'java'id 'org.springframework.boot' version '2.7.17'id 'io.spring.dependency-management' version '1.0.15.RELEASE'} group = 'com.example'version = '0.0.1-SNAPSHOT' java {sourceCompatibility = '11'} repositories {mavenCentral()} dependencies {implementation 'org.springframework.boot:spring-boot-starter-data-jpa'implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'implementation 'org.springframework.boot:spring-boot-starter-validation'implementation 'org.springframework.boot:spring-boot-starter-web'implementation 'org.projectlombok:lombok'runtimeOnly 'com.h2database:h2'developmentOnly 'org.springframework.boot:spring-boot-devtools'testImplementation 'org.springframework.boot:spring-boot-starter-test'//JUnit4 추가testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' tasks.named('bootBuildImage') {builder = 'paketobuildpacks/builder-jammy-base:latest'} tasks.named('test') {useJUnitPlatform()}이거 어디가 잘못된걸까요 예제 파일 다운받아서 4로 해도 마찬가지고 5로 해도 마찬가지로 나오네요 ..
-
미해결설계독학맛비's 실전 Verilog HDL Season 2 (AMBA AXI4 완전정복)
AXI4 버스 점유와 관련된 질문이 있습니다!
=================현업자인지라 업무때문에 답변이 늦을 수 있습니다. (길어도 만 3일 안에는 꼭 답변드리려고 노력중입니다 ㅠㅠ)강의에서 다룬 내용들의 질문들을 부탁드립니다!! (설치과정, 강의내용을 듣고 이해가 안되었던 부분들, 강의의 오류 등등)이런 질문은 부담스러워요.. (답변거부해도 양해 부탁드려요)개인 과제, 강의에서 다루지 않은 내용들의 궁금증 해소, 영상과 다른 접근방법 후 디버깅 요청, 고민 상담 등..글쓰기 에티튜드를 지켜주세요 (저 포함, 다른 수강생 분들이 함께보는 공간입니다.)서로 예의를 지키며 존중하는 문화를 만들어가요.질문글을 보고 내용을 이해할 수 있도록 남겨주시면 답변에 큰 도움이 될 것 같아요. (상세히 작성하면 더 좋아요! )먼저 유사한 질문이 있었는지 검색해보세요.잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.================== 안녕하세요 맛비님 늘 많이 배우고 있습니다. 날이 급격하게 추워졌는데 감기 조심하시길 바랍니다 😃 다름이 아니라 이렇게 질문글을 남기게 된 건 버스 점유와 관련된 질문이 있어서인데요.아래 사진이 잘 보이실 지 모르겠는데, 하얀색 네모 박스로 쳐져있는 부분에서 READ, WRITE transaction이 일어난 것 같은데 이러면 버스 width를 64bit로 설정해둔 지금(chapter20) 버스의 점유 원칙(이런 말이 있나모르겠네요)? 이런 거에 위배되지 않나요? 강의에서 놓친 부분이 있다면 미리 죄송하다는 말씀 드립니다..ㅠ 그럼 답변 기다리겠습니다. 감사합니다.
-
해결됨
김영한님의 스프링 입문을 들을려고 하는데
스프링 입문 시 db의 기초지식은 어느 정도 있어야 하나요 ? crud 정도면 되는 것인가요 ?바쁘신 와중에 답변 부탁드립니다
-
해결됨Flutter로 SNS 앱 만들기
사용자 정보, 게시글 정보를 Model 클래스로 관리 강의 관련 질문
안녕하세요.강의 잘 듣고 있습니다.사용자 정보, 게시글 정보를 Model 클래스로 관리 강의 관련 질문 있습니다.그 전 강의인 firestore에 게시글 정보 저장 강의 까지는 firestore database에 정상적으로 data가 올라갔습니다.하지만, 사용자 정보, 게시글정보를 Model 클래스로 관리 강의에 따라 코드 작성 후firestore database에 data가 올라가지 않습니다.(storage는 잘 작동합니다.)//feed_model.dart // ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:collection/collection.dart'; import 'package:sns_clonecode/models/urser_model.dart'; class FeedModel { final String uid; final String feedId; final String desc; final List<String> imageUrls; final List<String> likes; final int commentCount; final int likeCount; final Timestamp creatAt; final UserModel writer; const FeedModel({ required this.uid, required this.feedId, required this.desc, required this.imageUrls, required this.likes, required this.commentCount, required this.likeCount, required this.creatAt, required this.writer, }); Map<String, dynamic> toMap({ required DocumentReference<Map<String, dynamic>> userDocRef, }) { return { 'uid': this.uid, 'feedId': this.feedId, 'desc': this.desc, 'imageUrls': this.imageUrls, 'likes': this.likes, 'commentCount': this.commentCount, 'likeCount': this.likeCount, 'creatAt': this.creatAt, 'writer': userDocRef, }; } factory FeedModel.fromMap(Map<String, dynamic> map) { return FeedModel( uid: map['uid'], feedId: map['feedId'], desc: map['desc'], imageUrls: List<String>.from((map['imageUrls'])), likes: List<String>.from((map['likes'])), commentCount: map['commentCount'], likeCount: map['likeCount'], creatAt: map['creatAt'], writer: map['writer'], ); } } //user_model.dart // ignore_for_file: public_member_api_docs, sort_constructors_first import 'dart:convert'; class UserModel { final String uid; final String name; final String email; final String? profileImage; final int feedCount; final List<String> followers; final List<String> following; final List<String> likes; const UserModel({ required this.uid, required this.name, required this.email, required this.profileImage, required this.feedCount, required this.followers, required this.following, required this.likes, }); factory UserModel.init() { return UserModel( uid: '', name: '', email: '', profileImage: null, feedCount: 0, followers: [], following: [], likes: [], ); } //usermodle 이 가지고 있는 filed 변수로 가지고 있는 데이터들을 가지고 map 형태 데이터를 만들어 준다. Map<String, dynamic> toMap() { return { 'uid': this.uid, 'name': this.name, 'email': this.email, 'profileImage': this.profileImage, 'feedCount': this.feedCount, 'followers': this.followers, 'following': this.following, 'likes': this.likes, }; } //map 형태 데이터를 인자값을 전달 받아 usermolde 객체를 만들어 준다. factory UserModel.fromMap(Map<String, dynamic> map) { return UserModel( uid: map['uid'], name: map['name'], email: map['email'], profileImage: map['profileImage'], feedCount: map['feedCount'], followers: List<String>.from(map['followers']), following: List<String>.from(map['following']), likes: List<String>.from(map['likes']), ); } } //feed_repository.dart import 'dart:io'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:sns_clonecode/models/feed_model.dart'; import 'package:sns_clonecode/models/urser_model.dart'; import 'package:sns_clonecode/utils/logger.dart'; import 'package:uuid/uuid.dart'; class FeedRepository { final FirebaseStorage firebaseStorage; final FirebaseFirestore firebaseFirestore; const FeedRepository({ required this.firebaseFirestore, required this.firebaseStorage, }); Future<void> uploadFeed({ required List<String> files, required String desc, required String uid, //feeds 컬렉션에 저장 //피드 각각이 문서 //이미지는 storage에 직접 저장하고 firestore에 접근할 수 있는 url 문자열로 받을 것이다. //좋아요 수 //이 게시글에 달린 댓글의 수 //게시글을 작성한 날짜 //feeds에서 user의 정보를 바로 가져올 수 있게 reference 타입의 데이터를 저장한다. }) async { //파이어스토어에 데이터 저장하기위해서 //문서 아이디는 겹치지 않는 고유한 값으로 만들어야 한다. //a-z 알파벳 //0~9 숫자 //이 두가지를 조합해서 32글자의 고유한 값을 만들어 준다. //32글자에 - 4개씩 들어가서 36글자가 된다. //고유한 값을 만드는 방법 여러가지 version1 .... //우리는 version1을 사용 (현재 시간을 기준으로 random값을 만들어 준다.) String feedId = Uuid().v1(); //firestore 문서 참조 DocumentReference<Map<String, dynamic>> feedDocRef = firebaseFirestore.collection('feeds').doc(feedId); DocumentReference<Map<String, dynamic>> userDocRef = firebaseFirestore.collection('users').doc(uid); //storage 참조 Reference ref = firebaseStorage.ref().child('feeds').child(feedId); List<String> imageUrls = await Future.wait(files.map((e) async { //문자열 e는 이미지 파일에 접근할 수 있는 경로 String imageId = Uuid().v1(); TaskSnapshot taskSnapshot = await ref.child(imageId).putFile(File(e)); return await taskSnapshot.ref.getDownloadURL(); }).toList()); DocumentSnapshot<Map<String, dynamic>> userSnapshot = await userDocRef.get(); UserModel userModel = UserModel.fromMap(userSnapshot.data()!); FeedModel feedModel = FeedModel.fromMap({ 'uid': uid, 'feedId': feedId, 'desc': desc, 'imageUrls': imageUrls, 'likes': [], 'likeCount': 0, 'commentCount': 0, 'createAt': Timestamp.now(), 'writer': userModel, }); await feedDocRef.set(feedModel.toMap(userDocRef: userDocRef)); // await feedDocRef.set({ // 'uid': uid, // 'feedId': feedId, // 'desc': desc, // 'imageUrls': imageUrls, // 'likes': [], // 'commentCount': 0, // 'likeCount': 0, // 'creatAt': Timestamp.now(), // 'writer': userDocRef, // }); await userDocRef.update({ 'feedCount': FieldValue.increment(1), }); } } 바쁘실 텐데 질문 읽어주셔서 감사합니다.
-
미해결
JPA 문제
public ResponseEntity<?> updateBoard(Long boardId, CreateBoardDTO boardDTO, String memberEmail) { try { // 게시글 조회 BoardEntity findBoard = boardRepository.findByBoardId(boardId) .orElseThrow(EntityNotFoundException::new); log.info("게시글 닉네임 : " + findBoard.getMember().getNickName()); // 유저 조회 MemberEntity findUser = memberRepository.findByEmail(memberEmail); log.info("유저 : " + findUser); // 받아온 유저를 조회하고 그 유저 정보와 게시글에 담긴 유저가 일치하는지 boolean equalsEmail = findUser.getEmail().equals(findBoard.getMember().getEmail()); if(equalsEmail) { // 수정할 내용, 유저정보, 게시글을 작성할 때 받은 상품의 정보를 넘겨준다. findBoard = BoardEntity.builder() .boardId(findBoard.getBoardId()) .title(boardDTO.getTitle()) .content(boardDTO.getContent()) .item(findBoard.getItem()) .member(findBoard.getMember()) .boardSecret(BoardSecret.UN_LOCK) .build(); BoardEntity updateBoard = boardRepository.save(findBoard); BoardDTO returnBoard = BoardDTO.toBoardDTO(updateBoard, findUser.getNickName()); log.info("게시글 : " + returnBoard); return ResponseEntity.ok().body(returnBoard); } else { return ResponseEntity.badRequest().body("일치하지 않습니다."); } } catch (Exception e) { e.printStackTrace(); return ResponseEntity.badRequest().body("수정하는데 실패했습니다. : " + e.getMessage()); } }package com.example.shopping.entity.board; import com.example.shopping.domain.board.BoardDTO; import com.example.shopping.domain.board.BoardSecret; import com.example.shopping.domain.board.CreateBoardDTO; import com.example.shopping.domain.comment.CommentDTO; import com.example.shopping.entity.Base.BaseEntity; import com.example.shopping.entity.comment.CommentEntity; import com.example.shopping.entity.item.ItemEntity; import com.example.shopping.entity.member.MemberEntity; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.ArrayList; import java.util.List; @Entity(name = "board") @Table @Getter @NoArgsConstructor public class BoardEntity extends BaseEntity { @Id @GeneratedValue @Column(name = "board_id") private Long boardId; @Column(length = 300, nullable = false) private String title; private String content; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "member_id") private MemberEntity member; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "item_id") private ItemEntity item; @Enumerated(EnumType.STRING) private BoardSecret boardSecret; // 댓글 // 여기에 적용해야 합니다. 보통 게시물을 삭제해야 이미지가 삭제되므로 // 게시물이 주축이기 때문에 여기에 cascade = CascadeType.ALL을 추가 // orphanRemoval = true도 게시글을 삭제하면 // 댓글도 삭제되므로 여기서 작업을 해야합니다. @OneToMany(mappedBy = "board", cascade = CascadeType.ALL, orphanRemoval = true) @OrderBy("commentId asc ") private List<CommentEntity> commentEntityList = new ArrayList<>(); @Builder public BoardEntity(Long boardId, String title, String content, MemberEntity member, ItemEntity item, BoardSecret boardSecret, List<CommentEntity> commentEntityList) { this.boardId = boardId; this.title = title; this.content = content; this.member = member; this.item = item; this.boardSecret = boardSecret; this.commentEntityList = commentEntityList; } // 게시글 DTO를 엔티티로 변환 public static BoardEntity toBoardEntity(BoardDTO board, MemberEntity member, ItemEntity item) { BoardEntity boardEntity = com.example.shopping.entity.board.BoardEntity.builder() .boardId(board.getBoardId()) .title(board.getTitle()) .content(board.getContent()) .member(member) .item(item) .build(); // 댓글 처리 List<CommentDTO> commentDTOList = board.getCommentDTOList(); for (CommentDTO commentDTO : commentDTOList) { CommentEntity commentEntity = CommentEntity.toCommentEntity(commentDTO, member, boardEntity); boardEntity.commentEntityList.add(commentEntity); } return boardEntity; } /* 비즈니스 로직 */ // 게시글 작성 public static BoardEntity createBoard(CreateBoardDTO boardDTO, MemberEntity member, ItemEntity item) { return com.example.shopping.entity.board.BoardEntity.builder() .title(boardDTO.getTitle()) .content(boardDTO.getContent()) // 본인이 작성한 글은 읽을 수 있어야하기 때문에 UN_ROCK .boardSecret(BoardSecret.UN_LOCK) .member(member) .item(item) .build(); } // 문의글 상태 변화 public void changeSecret(BoardSecret secret) { this.boardSecret = secret; } } package com.example.shopping.domain.board; import com.example.shopping.domain.comment.CommentDTO; import com.example.shopping.entity.board.BoardEntity; import com.example.shopping.entity.comment.CommentEntity; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import javax.validation.constraints.NotNull; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Collections; import java.util.List; @Getter @ToString @NoArgsConstructor public class BoardDTO { @Schema(description = "문의글 번호", example = "1", required = true) private Long boardId; @Schema(description = "문의글 제목", required = true) @NotNull(message = "문의글 제목은 필 수 입력입니다.") private String title; @Schema(description = "문의글 본문") private String content; @Schema(description = "유저 닉네임") private String nickName; @Schema(description = "문의글 작성 시간") private LocalDateTime regTime; @Schema(description = "관리자 답변") private List<CommentDTO> commentDTOList = new ArrayList<>(); @Schema(description = "문의글이 본인글인지 확인") private BoardSecret boardSecret; @Builder public BoardDTO(Long boardId, String title, String content, String nickName, LocalDateTime regTime, List<CommentDTO> commentDTOList, BoardSecret boardSecret) { this.boardId = boardId; this.title = title; this.content = content; this.nickName = nickName; this.regTime = regTime; this.commentDTOList = commentDTOList; this.boardSecret = boardSecret; } // 엔티티를 DTO로 변환하는 작업 public static BoardDTO toBoardDTO(BoardEntity board, String nickName) { // 게시글 댓글 처리 List<CommentEntity> commentEntityList = board.getCommentEntityList(); List<CommentDTO> commentDTOS = new ArrayList<>(); // 엔티티 댓글을 DTO 리스트에 담아주는 작업을 진행하고 있다. if (commentEntityList != null) { for (CommentEntity commentEntity : commentEntityList) { CommentDTO commentDTO = CommentDTO.toCommentDTO(commentEntity); commentDTOS.add(commentDTO); } } else { // commentEntityList가 null일 경우 빈 리스트로 초기화 commentDTOS = Collections.emptyList(); } return BoardDTO.builder() .boardId(board.getBoardId()) .title(board.getTitle()) .content(board.getContent()) .nickName(nickName) .commentDTOList(commentDTOS) .regTime(LocalDateTime.now()) .boardSecret(board.getBoardSecret()) .build(); } } 수정 문구인데 로그를 확인하면 게시글 로그까지 제대로 나오는 것을 볼 수있는데 근데 리턴이 안되고 400번 오류가 발생하는데 body에 적은 내용은 안나오는 상황입니다. 로그까지 찍혔는데 왜 리턴이 안되는 걸까요?? 아무 에러 표시도 안나옵니다.
-
해결됨Slack 클론 코딩[실시간 채팅 with React]
unread Count 같은 경우 실무에선는 DB에 마지막 일자를 기록하나요?
강의에서 localStorage 를 이용하여 접속시간 or 마지막 불러온 일자를 저장하고그 local 값을 unreads 에 after 파람으로 전송하여 읽지않은 메시지를 카운트 햇는데해당 방식은 다른 아이디로 로그인 시 같은 local 데이터를 활용하기도 하고 다른 기기에 접속시 해당값은 날라가게 될텐데 이는 에러사항으로 이어질 것으로 예상됩니다.마지막 일자를 활용하게 된다면 이 값은 db에 저장되야 할걸로 생각이 되는데 맞을까요?
-
해결됨Microservice 구현 (with EDA,Hexagonal, DDD)
@Repository 두 곳에서 사용하시는 이유
코드를 보면, Adpater 클래스와 Repository 인터페이스, 이렇게 2곳에서 @Repository을 사용하고 계시는데, 2곳에서 사용하시는지 이유가 궁금합니다!
-
해결됨모든 개발자를 위한 HTTP 웹 기본 지식
표현 헤더 안에 페이로드 메시지가 있는 건가요?
[질문 템플릿]1. 강의 내용과 관련된 질문인가요? (예)2. 인프런의 질문 게시판과 자주 하는 질문에 없는 내용인가요? (예)3. 질문 잘하기 메뉴얼을 읽어보셨나요? (예)[질문 내용]아래 사진에서 참고 부분의 설명이 이해가 안 갑니다.표현 헤더는 표현 메타데이터와, 페이로드 메시지를 구분해야 하지만 ... 페이로드 메시지는 메시지 본문에 포함되는 거 아닌가요?사진상으로 봐선 표현 헤더와 메시지 본문은 분리되어 있는 것 같은데, 참고에 나온 설명으론 페이로드 메시지가 표현 헤더 안에 있는 것처럼 느껴져셔 헷갈립니다.. 이걸 어떻게 받아들이면 될까요? +) 지금 이 강의인 'HTTP 헤더 개요'의 다음 강의인 '표현' 강의를 듣고 있는데요2분쯤에 Content-Length는 페이로드 헤더라고 말씀하시는데, 혹시 아래 피피티 마지막의 참고 부분에 나온 내용도 '페이로드 헤더'를 말하는 것인가요?
-
해결됨10주완성 C++ 코딩테스트 | 알고리즘 코딩테스트
1-G 이왜틀..
http://boj.kr/7a58b316a27d4759a0374f44dba24267 질문을 너무 많이해서 죄송합니다... 강의를 보기전에 작성한 것인데.. 이게 왜 틀렸는지 모르겠습니다. 선생님 알고리즘과 유사한 것 같고 반례도 잡은 것 같은데.. 다음부터는 딴 짓 안하고 substr 쓰겠습니다..
-
미해결파이썬 무료 강의 (기본편) - 6시간 뒤면 나도 개발자
퀴즈 8 리스트 질문입니다.
houses = [house1, house2, house3] house1 = House("강남", "아파트", "매매", "10억", "2010년") house2 = House("마포", "오피스텔", "전세", "5억", "2007년") house3 = House("송파", "빌라", "월세", "500/50", "2000년") 이렇게는 왜 안되는걸까요? [] 비워놓고 append로 해야만 프린트되네요...
-
해결됨쥬쥬와 함께 하루만에 끝내는 스프링 테스트
Mysql테스트중 에러발생
2023-11-16 18:20:48 Creating network "fqata9qnvuci_default" with the default driver 2023-11-16 18:20:48 Creating fqata9qnvuci_local-db-migrate_1 ... 2023-11-16 18:20:48 Creating fqata9qnvuci_local-db_1 ... 2023-11-16 18:20:50 Creating fqata9qnvuci_local-db-migrate_1 ... error 2023-11-16 18:20:50 2023-11-16 18:20:50 ERROR: for fqata9qnvuci_local-db-migrate_1 Cannot start service local-db-migrate: error while creating mount source path '/c/Users/Recorvery/Desktop/Workspace/dayonetest/db/flyway.conf': mkdir /c: file exists 2023-11-16 18:20:50 Creating fqata9qnvuci_local-db_1 ... done 2023-11-16 18:20:50 2023-11-16 18:20:50 ERROR: for local-db-migrate Cannot start service local-db-migrate: error while creating mount source path '/c/Users/Recorvery/Desktop/Workspace/dayonetest/db/flyway.conf': mkdir /c: file exists 2023-11-16 18:20:50 Encountered errors while bringing up the project.위는 도커에서 발생하는 에러로그아래는 springboot에서 발생하는 에러로그입니다.18:20:50.925 [Test worker] ERROR tc.docker/compose:1.29.2 -- Could not start container java.lang.IllegalStateException: Container did not start correctly. r.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74) 18:20:50.995 [Test worker] ERROR tc.docker/compose:1.29.2 -- Log output from the failed container: Creating network "fqata9qnvuci_default" with the default driver Creating fqata9qnvuci_local-db-migrate_1 ... Creating fqata9qnvuci_local-db_1 ... Creating fqata9qnvuci_local-db-migrate_1 ... error ERROR: for fqata9qnvuci_local-db-migrate_1 Cannot start service local-db-migrate: error while creating mount source path '/c/Users/Recorvery/Desktop/Workspace/dayonetest/db/flyway.conf': mkdir /c: file exists Creating fqata9qnvuci_local-db_1 ... done ERROR: for local-db-migrate Cannot start service local-db-migrate: error while creating mount source path '/c/Users/Recorvery/Desktop/Workspace/dayonetest/db/flyway.conf': mkdir /c: file exists Encountered errors while bringing up the project. MYSQL 테스트하기를 따라하던중 에러가났습니다! 그전 강의들은 문제없이 잘봤습니다.뭐가 문제일까요 ㅠㅠ 안되서 복붙했는데도 안되네요 ㅠ https://github.com/ygy7265/dayonetest깃주소입니다.
-
미해결
데이터베이스 강의
안녕하세요 강사님 다름이 아니고데이터베이스 섹션으로 강의 넘어가서 수업들으려 하니 DB 파트 전체 업데이트 중이라는 내용이 떠 있어서요. 혹시 현재 업데이트 진행중에 있으신걸까요?곧 내용이 업데이트 완료 된다고 하면 자료구조 파트 먼저 듣고 그 다음에 들을까 해서요~