row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
31,019
c++ program fisrt 20 numbers in fibonacci sequence
282a845c6b06f3da0e3103e543e33e5c
{ "intermediate": 0.33634158968925476, "beginner": 0.355001837015152, "expert": 0.3086565434932709 }
31,020
Can you make an ae script about an interesting effect for me to use
529a825e6d4d0463fc4d9004a5445aef
{ "intermediate": 0.3017341196537018, "beginner": 0.24799831211566925, "expert": 0.4502675533294678 }
31,021
python script send adaptive card user to user in ms teams use graph api
d64a177b21be8d4bf5711212b2909d08
{ "intermediate": 0.5123288631439209, "beginner": 0.13556692004203796, "expert": 0.35210418701171875 }
31,022
этот код правильный? import os file_path = 'base.txt' output_dir = 'base/' chunk_size = 100000 with open(file_path, 'r', encoding='utf-8') as input_file: chunk_count = 0 output_file = None for line in input_file: if chunk_count % chunk_size == 0: if output_file: output_file.close() output_file_path = os.path.join(output_dir, f'base_{chunk_count}.txt') output_file = open(output_file_path, 'w', encoding='utf-8') output_file.write(line.strip() + '\n') chunk_count += 1 if output_file: output_file.close()
d589f6ab82e945c62065f8b843f92d58
{ "intermediate": 0.4678705930709839, "beginner": 0.313815176486969, "expert": 0.21831421554088593 }
31,023
NameError: name 'concatenate' is not defined
dec8ece638a3c8eea41d05ec24f7e3cc
{ "intermediate": 0.402149498462677, "beginner": 0.19529327750205994, "expert": 0.4025571942329407 }
31,024
python code using BiLSTM encoder and decoder rnn to translate English text to Arabic text by splitting example data into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and use test data to evaluate
34dbf6e4adbab8e9974cdaf741992ad2
{ "intermediate": 0.42980825901031494, "beginner": 0.11859078705310822, "expert": 0.45160093903541565 }
31,025
how to override this——import java.util.concurrent.TimeUnit;
773cf0a44bafb03db8a2cb4480cf3940
{ "intermediate": 0.5138100981712341, "beginner": 0.24658262729644775, "expert": 0.2396072894334793 }
31,026
怎么引用import java.util.concurrent.TimeUnit;
c0445e41ed7c5fe3f0893b1216d68e2e
{ "intermediate": 0.37923121452331543, "beginner": 0.31773027777671814, "expert": 0.30303847789764404 }
31,027
Не могу добавить текст в сам слайдер, как сделать это. Напиши код. <div class=" swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <img src="./img/banner_1.jpg" /> </div> <div class="swiper-slide"> <img src="./img/banner_2.jpg" /> </div> <div class="swiper-slide"> <img src="./img/banner_3.jpg" /> </div> <div class="swiper-slide"> <img src="./img/banner_3.jpg" /> </div> </div> <div class="swiper-button-next"></div> <div class="swiper-button-prev"></div> <div class="swiper-pagination"></div> </div>
28ed18c11e4755893609b107e3080630
{ "intermediate": 0.38692352175712585, "beginner": 0.33938127756118774, "expert": 0.2736952304840088 }
31,028
怎么去override——import java.util.concurrent.TimeUnit;
ba6de783c8e4715a966ab51eef8c356f
{ "intermediate": 0.4047107696533203, "beginner": 0.3020036220550537, "expert": 0.293285608291626 }
31,029
INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (135874794, '1723709945486000129', '267376620', NULL, NULL, '199', '普通商品', '20', '20', '10', NULL, '2023-11-13', 'admin', NULL, NULL, '重量', '100KG'); INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (154825191, '1723709945486000129', '1952382663', NULL, NULL, '99', '普通商品', '10', '10', '999', NULL, '2023-11-13', 'admin', NULL, NULL, '转速', '100转'); INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (388124086, '1723709945486000129', '267376620', NULL, NULL, '199', '普通商品', '20', '20', '10', NULL, '2023-11-13', 'admin', NULL, NULL, '转速', '100转'); INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (595222892, '1723709945486000129', '1952382663', NULL, NULL, '99', '普通商品', '10', '10', '999', NULL, '2023-11-13', 'admin', NULL, NULL, '重量', '90KG'); INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (806805885, '1723709945486000129', '267376620', NULL, NULL, '199', '普通商品', '20', '20', '10', NULL, '2023-11-13', 'admin', NULL, NULL, '颜色', '灰色'); INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (1295610808, '1723709945486000129', '1952382663', NULL, NULL, '99', '普通商品', '10', '10', '999', NULL, '2023-11-13', 'admin', NULL, NULL, '颜色', '黑色'); INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (1720111770, '1723709945486000129', '267376620', NULL, NULL, '199', '普通商品', '20', '20', '10', NULL, '2023-11-13', 'admin', NULL, NULL, '转速', '200转'); INSERT INTO `fanpin`.`fan_category_product_goods` (`id`, `category_id`, `product_id`, `goods_specs`, `original_price`, `sales_price`, `type`, `integral`, `freight`, `inventory`, `status`, `create_time`, `create_by`, `update_by`, `update_time`, `attribute_name`, `attribute_value`) VALUES (2039846087, '1723709945486000129', '1952382663', NULL, NULL, '99', '普通商品', '10', '10', '999', NULL, '2023-11-13', 'admin', NULL, NULL, '颜色', '灰色'); 这个是8条sql语句,两个同类型不同规格价格的产品,插入数据库之后,如何用java把这个数据处理为{"颜色":"灰色","重量":"90G","转速":"100转","sales_price":"99"},{"颜色":"黑色","重量":"90G","转速":"100转","sales_price":"99"},{"颜色":"灰色","重量":"100G","转速":"100转","sales_price":"199"},{"颜色":"灰色","重量":"100G","转速":"200转","sales_price":"199"}这样的数据
864af9167fbee5624590a82f690c5081
{ "intermediate": 0.2916710376739502, "beginner": 0.3922523856163025, "expert": 0.3160765767097473 }
31,030
아래는 controller 코드야. 코드 해석하고 기억해놔. package egovframework.hbz.web; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import egovframework.hbz.service.impl.EgovHbzScrapServiceImpl; @Controller public class EgovHbzScrapController { Logger logger = LoggerFactory.getLogger(EgovHbzScrapController.class); @Autowired EgovHbzScrapServiceImpl egovHbzScrapServiceImpl; /* * @Scheduled(fixedDelay = 1000, initialDelay = 5000) public void * scheduledTest() throws Exception { * * Date date = new Date(); * * SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); * * String nowDate = dateFormat.format(date); * * System.out.println("스케줄러 현재시간 : " + nowDate ); } */ // 네이버 뉴스 랭킹 @RequestMapping(value="/hbz/newsRank.do") public String newsRank(Model model) throws Exception{ System.out.println("newsRank Start"); egovHbzScrapServiceImpl.newsRank(model); return "/scrp/newsRank"; } // 웹툰 페이지 스크래핑 @RequestMapping(value="/hbz/webtoonScrap.do") public String webtoonScrap(Model model) throws Exception{ egovHbzScrapServiceImpl.webtoonScrap(model); return "/scrp/webtoonScrap"; } // DB조회 후 스크래핑 페이지로 전환 @RequestMapping(value="/hbz/scrap.do", method=RequestMethod.GET) public String scrapPage(@RequestParam int pageNo, Model model) throws Exception{ logger.info("### scrapPage Start"); List<Map<String, Object>> list = egovHbzScrapServiceImpl.scrapView(pageNo,model); model.addAttribute("list", list); return "/scrp/ScrapPage"; } // 공공데이터포털 - 기상청 [초단기실황] 데이터 스크래핑 @RequestMapping(value="/hbz/datapotal.do", method=RequestMethod.GET) public String getUltraSrtNcst(Model model) throws Exception{ logger.info("### dataPotalScrap Start"); egovHbzScrapServiceImpl.getUltraSrtNcst(); int pageNo = 1; List<Map<String, Object>> list = egovHbzScrapServiceImpl.scrapView(pageNo,model); model.addAttribute("list", list); return "/scrp/ScrapPage"; } // 공공데이터포털 -기상청 [단기예보] @RequestMapping(value="/hbz/getVilageFcst.do", method=RequestMethod.GET) public String getVilageFcst(@RequestParam String in_area,@RequestParam String in_time, Model model) throws Exception{ System.out.println("in_area : " + in_area); System.out.println("in_time : " + in_time); Map<String, Object> map = egovHbzScrapServiceImpl.getVilageFcst(in_area, in_time); model.addAttribute("map",map); return "/scrp/getVilageFcst"; } // 병원 데이터 @RequestMapping(value="/hbz/Hospital.do", method=RequestMethod.GET) public String hostpitalInfo(@RequestParam("address") String address, Model model) throws Exception { List<Map<String, Object>> hospitalList = egovHbzScrapServiceImpl.hospitalInfo(address); System.out.println("Received address: " + address); model.addAttribute("hospitalList", hospitalList); return "/main/EgovMainView"; } // 맵테스트 @RequestMapping(value="/hbz/Map.do", method=RequestMethod.GET) public String MapTest(Model model) throws Exception { return "/main/EgovMainView"; } // 병원 상세정보 @RequestMapping(value="/hbz/HospitalInfo.do", method=RequestMethod.GET) public String HospitalPage(@RequestParam("ykiho") String ykiho,Model model) throws Exception{ System.out.println("Received ykiho: " + ykiho); Map<String, Object> map = egovHbzScrapServiceImpl.HospitalPage(ykiho); model.addAttribute("map",map); // 에러난거 //model.addAttribute("map2", map2); 되는 거 //model.addAttribute("map3", map3); 안되는 거 return "/main/EgovMainView"; } }
90423704e9d5b08393712d11d07302f3
{ "intermediate": 0.3196740448474884, "beginner": 0.3873768150806427, "expert": 0.2929491698741913 }
31,031
how send message to defold gui script from js?
319118ee6d9a2aaddac2210b0b383d01
{ "intermediate": 0.5756504535675049, "beginner": 0.2101651430130005, "expert": 0.21418441832065582 }
31,032
Write a python program that prints the results of addition of two polynomials. For instance, the first polynomials x^2+5x, , which can be expressed as [0, 5, 1]; the second polynomials -x^3-2x^2+3, can be presented as [3, 0, -2, -1]. The addition of two polynomials can be printed as [3, 5, -1, -1].
01527d247183c97f65db5c821fbf2bf1
{ "intermediate": 0.4062117636203766, "beginner": 0.30670177936553955, "expert": 0.28708645701408386 }
31,033
finde missing ) in this code: function buy_consume(inapp_id) { ysdk.getPayments({ }).then(_payments => { _payments.purchase({ id: inapp_id }).then(purchase => { _payments.consumePurchase(purchase.purchaseToken); return inapp_id; }).catch(err => { })}}
26ff355718e1b558cf858aab93b2b2cd
{ "intermediate": 0.32001906633377075, "beginner": 0.4842056930065155, "expert": 0.19577527046203613 }
31,034
make 2 function type one without return and one with return and one without return function c language
90d57f3f6e2b2892359e99c84f3827f8
{ "intermediate": 0.22930960357189178, "beginner": 0.5360746383666992, "expert": 0.23461569845676422 }
31,035
Write a c language average function one without passing argument and return and one with passing argument and return
3b57b68717b0920292e8adbd4d0220a2
{ "intermediate": 0.21803578734397888, "beginner": 0.5137436389923096, "expert": 0.26822057366371155 }
31,036
Are you familiar with the DeepFashion2 dataset?
5bdb359a2e10e85cd2febc94f73d4ca0
{ "intermediate": 0.1969989538192749, "beginner": 0.17668765783309937, "expert": 0.6263133883476257 }
31,037
У меня есть функция, которая решает уравнение: A (матрица) * x (вектор) = B (вектор) с помощью LU-разложения. Можно ли переписать мою функцию, используя Eigen::FullPivLU? Вот мой код: /* Calculate matrix equation: _A_matrix * result_Vector = _B_Vector with LU method */ Eigen::VectorXd solveLinearSystemWithLU(const SpMatD& _A_matrix, const Eigen::VectorXd& _B_Vector) { Eigen::SparseLU<Eigen::SparseMatrix<double>> solver{}; //solver.setTolerance(1e-12); solver.analyzePattern(_A_matrix); solver.factorize(_A_matrix); if (solver.info() != Eigen::Success) { std::cout << "Factorisation was NOT succeeded\n"; return {}; } else { std::cout << "Factorisation was succeeded\n"; Eigen::VectorXd result_Vector = solver.solve(_B_Vector); if (solver.info() != Eigen::Success) { std::cout << "solver.solve was NOT succeeded\n"; return {}; } else { std::cout << "solver.solve was succeeded\n"; //std::cout << "x.size(): " << x.size() << "\n"; return result_Vector; } } }
9f0418d6422a8c5710f0b027e398a3e4
{ "intermediate": 0.31796854734420776, "beginner": 0.3478696942329407, "expert": 0.33416175842285156 }
31,038
У меня есть функция, которая решает уравнение: A (матрица) * x (вектор) = B (вектор) с помощью LU-разложения. Можно ли переписать мою функцию, используя Eigen::FullPivLU? Я имею ввиду решить уравнение не через Eigen::SparseLU, а через Eigen::FullPivLU? Вот мой код: / Calculate matrix equation: _A_matrix * result_Vector = _B_Vector with LU method / Eigen::VectorXd solveLinearSystemWithLU(const SpMatD& _A_matrix, const Eigen::VectorXd& _B_Vector) { Eigen::SparseLU<Eigen::SparseMatrix<double>> solver{}; //solver.setTolerance(1e-12); solver.analyzePattern(_A_matrix); solver.factorize(_A_matrix); if (solver.info() != Eigen::Success) { std::cout << “Factorisation was NOT succeeded\n”; return {}; } else { std::cout << “Factorisation was succeeded\n”; Eigen::VectorXd result_Vector = solver.solve(_B_Vector); if (solver.info() != Eigen::Success) { std::cout << “solver.solve was NOT succeeded\n”; return {}; } else { std::cout << “solver.solve was succeeded\n”; //std::cout << "x.size(): " << x.size() << “\n”; return result_Vector; } } }
05694e6ceb46388b2a5984feb1fbe72a
{ "intermediate": 0.37399354577064514, "beginner": 0.2946088910102844, "expert": 0.33139750361442566 }
31,039
jest 单元测试 awsRum.recordEvent('buttonEvent', { buttonName: 'Search-Search', user_interaction: { interaction_1: 'click' }, visit_count: 1 });
a3e399a3684a376049509a9e2cb81ac4
{ "intermediate": 0.42640766501426697, "beginner": 0.28584790229797363, "expert": 0.2877444326877594 }
31,040
The CSRF token is missing. Error in Flask app. How to resolve?
be1046a7e5bcfac93b66b0eaab22ad14
{ "intermediate": 0.7161301374435425, "beginner": 0.13146188855171204, "expert": 0.1524079591035843 }
31,041
I want to program a ATmega 32A to turn on 3 DIP white color led and I want to turn on this led’s based on value of a 10K potentiometer ( this will act as a bar graph to indicate the value led one turn on in 100 ohm, LED2 turn on in 341 ohm and LED3 in 680 ohm) what the code to compile on atmega32 and how install this
851f04607f6be09121c746cb371c0360
{ "intermediate": 0.4723964035511017, "beginner": 0.14789767563343048, "expert": 0.37970590591430664 }
31,042
В цикле for ошибка, сам AccountBalanceResponse содержит в себе final Object response, а я пытаюсь привести его к List, как быть? public boolean checkBalance(Long partnerId, BigDecimal returnAmount, String accountNumber) { AccountBalanceRequest balanceRequest = new AccountBalanceRequest(); balanceRequest.setPartnerId(partnerId); balanceRequest.setSign(acquiringProcessingHelpService.getSignature("" + partnerId, partnerId)); Response response = requestPostCheckBalance(balanceRequest, "company/accounts/balance"); if (response.getStatus() == Response.Status.OK.getStatusCode()) { AccountBalanceResponse accountBalanceResponse = new Gson().fromJson(response.readEntity(String.class), AccountBalanceResponse.class); List<AccountBalance> balances = (List<AccountBalance>) accountBalanceResponse.getResponse(); for (AccountBalance balance : balances) { if (balance.getNumber().equals(accountNumber)) { return balance.getAmount().compareTo(returnAmount) > 0; } } } return false; } private Response requestPostCheckBalance(AccountBalanceRequest balanceRequest, String urlOperation) throws IllegalArgumentException { String srcRest="http://localhost:8080/acq-company-rest/"; String url = srcRest + urlOperation; Invocation invocation = externalBalanceManageExternal .target(url) .request(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) // .header("Authorization", authorizationHeaderValue) .buildPost(Entity.json(balanceRequest)); Response response = invocation.invoke(); int responseCode = response.getStatusInfo().getStatusCode(); LOGGER.info("result code " + responseCode); return response; }
8c68a1cf523ac9d97c8f1a980260579d
{ "intermediate": 0.3650769889354706, "beginner": 0.5166699886322021, "expert": 0.11825302988290787 }
31,043
python3 code to implement 2D convolution layer
ca44a72b4954835989089a5b8241038e
{ "intermediate": 0.2623160183429718, "beginner": 0.11311258375644684, "expert": 0.6245714426040649 }
31,044
Напиши функцию, которая бы вывела в файл (result.txt) std::map<CoordinatesInfo, size_t>. CoordinatesInfo - структура из int x и int y
daef02c2efc67e3882f5a85ad01a7271
{ "intermediate": 0.3346056640148163, "beginner": 0.33562955260276794, "expert": 0.32976484298706055 }
31,045
notifyicon.showballontip have it show notification until user clicks it
f1f9c4058dac7a056e83cc7794a4fe13
{ "intermediate": 0.38136574625968933, "beginner": 0.21380573511123657, "expert": 0.4048285484313965 }
31,046
What is in /etc/crypttab? Block devices? Be very concise.
a6d3834303cb59aa6239e49aa8f32f3f
{ "intermediate": 0.3878422677516937, "beginner": 0.3219650983810425, "expert": 0.2901926040649414 }
31,047
How can I make a second volume group in LVM be automatically loaded on bootup (of a Debian system)?
84241a31015c19a1e3a1ed0acf2fc59e
{ "intermediate": 0.47244834899902344, "beginner": 0.18105454742908478, "expert": 0.3464970886707306 }
31,048
I think I need vgchange -a y to be run upon Debian's bootup because I have another drive in fstab not mounting.
4323c32754644a28723af85ad7ada8e7
{ "intermediate": 0.44533002376556396, "beginner": 0.24394208192825317, "expert": 0.31072789430618286 }
31,049
make this code correct =Query(IMPORTRANGE("https://docs.google.com/spreadsheets/d/1_iO4G62IHBhLXvmQKo4nIaANxOVTdahNNAJLy2tGOeI/edit#gid=813582014","Temple Trip!A:b"),"where Col2>=date '"&TEXT(If(15>Day(Today()),DATE(Year(Today()),Month(Today()),15),DATE(Year(today()),MONTH(TODAY())+1,1)),"yyyy-MM-dd")&"' and Col2<date '"&Text(Date(YEAR(today()),MONTH(today())+1,IF(Day(today())>15,15,1)),"yyyy-MM-dd")&"'")
90ff59c37d88a1d8bc722243d7a49bca
{ "intermediate": 0.36493659019470215, "beginner": 0.3881595730781555, "expert": 0.24690388143062592 }
31,050
sub_n <-trt%>% + group_by(Subject_ID)%>% + summarise(n=n_distinct(Subject_ID)) Error in rep(seq_len(nrow(out)), cols$size) : 'times'参数不对 how to fix it
e10eb8317043e8d5bcc151faf7fe015b
{ "intermediate": 0.20322076976299286, "beginner": 0.520438551902771, "expert": 0.27634066343307495 }
31,051
How to create a http client in C#
55e0f8bd715146282b6bb27a140a5027
{ "intermediate": 0.43831947445869446, "beginner": 0.3354310691356659, "expert": 0.22624950110912323 }
31,052
bonjour, dans le contrat principal, j'ai des fonctions internal que j'ai dû dupliquer en fonction public pour les tester. j'ai créé un contrat pour les tests qui permet d'extraire ces fonctions public du contrat principal. question,1 ) ai je besoin de l'interface 2 ) est ce que le contrat est correct ? "// Fonctions internes du contrat principal exposées comme publiques pour les tests // SPDX-License-Identifier: MIT import "./Penduel.sol"; pragma solidity 0.8.17; interface TestHelper2 { function getFulfillRandomWords(uint256 _requestId, uint256[] memory randomWords) public { } function getValidFirstLetter(uint256 _gameId) public returns (string memory) { } function getFilteredLetter(string memory _letterToGuess) public pure returns (string memory) { } function getCheckLetter(uint256 _gameId, string memory _letterFiltered) public { } function getIsWordCorrect(string memory _filteredWord) public view returns (bool) { } function getBalance() public view returns (uint256) { } function getPlayer1Bet() public view returns (uint256) { } function getWordListAtIndex(uint256 index) public view returns (string memory) { } } contract TestHelper is TestHelper2 { Penduel public penduel; constructor(Penduel _penduel) { penduel = _penduel; } function getFulfillRandomWords(uint256 _requestId, uint256[] memory randomWords) public { penduel.fulfillRandomWords(_requestId, randomWords); } function getValidFirstLetter(uint256 _gameId) public returns (string memory) { return penduel.validFirstLetter(_gameId); } function getFilteredLetter(string memory _letterToGuess) public pure returns (string memory) { return penduel.filteredLetter(_letterToGuess); } function getCheckLetter(uint256 _gameId, string memory _letterFiltered) public { penduel.checkLetter(_gameId, _letterFiltered); } function getIsWordCorrect(string memory _filteredWord) public view returns (bool) { return penduel.isWordCorrect(_filteredWord); } function getBalance() public view returns (uint256) { return playerBalances[gameId][msg.sender].balance; } function getPlayer1Bet() public view returns (uint256) { return games[gameId].player1Bet.bet; } function getWordListAtIndex(uint256 index) public view returns (string memory) { require(index < wordList.length, "Invalid index"); return wordList[index]; } }
91000e27ea7de40d2942635c50439477
{ "intermediate": 0.37873414158821106, "beginner": 0.44836169481277466, "expert": 0.17290419340133667 }
31,053
generate console menu using c# with options
29ab2e96e310d668dd809c2e92d82beb
{ "intermediate": 0.4325987994670868, "beginner": 0.3010097146034241, "expert": 0.26639148592948914 }
31,054
i am a developer. what is the criteria for calling my api a microservice?
06da8240d9efebb8810bd021fc981adc
{ "intermediate": 0.770578920841217, "beginner": 0.13853423297405243, "expert": 0.09088686853647232 }
31,055
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: malformed \N character escape search_string = ["\N"]
8149e743795c6f9660a4c0440c7ed83f
{ "intermediate": 0.2760717570781708, "beginner": 0.4159491956233978, "expert": 0.30797913670539856 }
31,056
est ce correct ? "// Fonctions internes du contrat principal exposées comme publiques pour les tests // SPDX-License-Identifier: MIT import "./Penduel.sol"; pragma solidity 0.8.17; interface TestHelper2 { function getFulfillRandomWords(uint256 _requestId, uint256[] memory randomWords) external; function getValidFirstLetter(uint256 _gameId) external returns (string memory); function getFilteredLetter(string memory _letterToGuess) external pure returns (string memory); function getCheckLetter(uint256 _gameId, string memory _letterFiltered) external; function getIsWordCorrect(string memory _filteredWord) external view returns (bool); function getBalance() external view returns (uint256); function getPlayer1Bet() external view returns (uint256); function getWordListAtIndex(uint256 index) external view returns (string memory); } contract TestHelper is TestHelper2 { Penduel public penduel; uint256 public gameId; constructor(Penduel _penduel) { penduel = _penduel; } function getFulfillRandomWords(uint256 _requestId, uint256[] memory randomWords) public { penduel.fulfillRandomWords(_requestId, randomWords); } function getValidFirstLetter(uint256 _gameId) public returns (string memory) { return penduel.validFirstLetter(_gameId); } function getFilteredLetter(string memory _letterToGuess) public pure returns (string memory) { return penduel.filteredLetter(_letterToGuess); } function getCheckLetter(uint256 _gameId, string memory _letterFiltered) public { penduel.checkLetter(_gameId, _letterFiltered); } function getIsWordCorrect(string memory _filteredWord) public view returns (bool) { return penduel.isWordCorrect(_filteredWord); } function getBalance() public view returns (uint256) { return playerBalances[gameId][msg.sender].balance; } function getPlayer1Bet() public view returns (uint256) { return games[gameId].player1Bet.bet; } function getWordListAtIndex(uint256 index) public view returns (string memory) { require(index < wordList.length, "Invalid index"); return wordList[index]; } }
8e2ce82526054bbee1e1210c41e51236
{ "intermediate": 0.40875157713890076, "beginner": 0.3865950405597687, "expert": 0.20465338230133057 }
31,057
in visual basic code how do you search for a keyword in a csv file
b0560c15ddd1954707b9a85836472535
{ "intermediate": 0.26858067512512207, "beginner": 0.40918654203414917, "expert": 0.32223275303840637 }
31,058
How do I use the cut command to get the second token that's delimited by a double quotation mark?
9062b1c2bdd3e93315d8dabef7b1741f
{ "intermediate": 0.38004377484321594, "beginner": 0.3219298720359802, "expert": 0.2980263829231262 }
31,059
python code using BiLSTM encoder and decoder rnn to translate English text to Arabic text by splitting example data into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and use test data to evaluate and example prediction translation from test
35cab490e027c92e3ca9951c4a9daec0
{ "intermediate": 0.39724865555763245, "beginner": 0.0989353135228157, "expert": 0.5038160681724548 }
31,060
onData(socket, args) { if (this.tank === null || !this.hasPlayer(this.tank.name)) return; var tank = this.tank; if (args.length === 1) { if (args[0] === "get_garage_data") { this.updateMarket(); setTimeout(() => { this.initMarket(socket); this.initMountedItems(socket); }, 1500); } } else if (args.length === 3) { if (args[0] === "try_buy_item") { var itemStr = args[1]; var arr = itemStr.split("_"); var id = itemStr.replace("_m0", ""); var amount = parseInt(args[2]); var new_item = GarageItem.get(id, 0); if (new_item !== null) { if (tank.crystals >= new_item.price * amount && tank.rank >= new_item.rank) { var obj = {}; obj.itemId = id; if (new_item !== null && id !== "1000_scores") { var item = tank.garage.getItem(id); if (item === null) { new_item.count = amount; this.addItem(new_item); } else { item.count += amount; } } tank.crystals -= new_item.price * amount; if (id === "1000_scores") tank.addScore(1000 * amount); if (id === "supplies") { this.addKitItem("health",0,100,tank); this.addKitItem("armor",0,100,tank); this.addKitItem("damage",0,100,tank); this.addKitItem("nitro",0,100,tank); this.addKitItem("mine",0,100,tank); this.send(socket,"reload") } else { this.send(socket, "buy_item;" + itemStr + ";" + JSON.stringify(obj)); } tank.sendCrystals(); } } } } else if (args.length === 2) { if (args[0] === "try_mount_item") { var itemStr = args[1]; var itemStrArr = itemStr.split("_"); if (itemStrArr.length === 2) { var modificationStr = itemStrArr[1]; var item_id = itemStrArr[0]; if (modificationStr.length === 2) { var m = parseInt(modificationStr.charAt(1)); if (!isNaN(m)) { this.mountItem(item_id, m); this.sendMountedItem(socket, itemStr); tank.save(); } } } } else if (args[0] === "try_update_item") { var itemStr = args[1], arr = itemStr.split("_"), modStr = arr.pop(), id = arr.join("_"); if (modStr.length === 2) { var m = parseInt(modStr.charAt(1)); if (!isNaN(m) && m < 3) { if (this.hasItem(id, m) && this.getItem(id).attempt_upgrade(tank)) { this.send(socket, "update_item;" + itemStr); tank.sendCrystals(); } } } } } } как сюда добавить obj.multicounted
7c312cf711c282a0b6b9f7191e90c74a
{ "intermediate": 0.3405924439430237, "beginner": 0.5150299072265625, "expert": 0.14437760412693024 }
31,061
whats wrong Game.belongsTo called with something that's not a subclass of Sequelize.Model
26db8240ee6e179bc50808b7f22d9507
{ "intermediate": 0.275360643863678, "beginner": 0.5840516090393066, "expert": 0.14058779180049896 }
31,062
how to validate a telerik grid in blazor
d3d62d19ecdc3901b78190c84698f22e
{ "intermediate": 0.35757988691329956, "beginner": 0.11214914172887802, "expert": 0.5302709341049194 }
31,063
import operator import random class Process: def __init__(self, name, arrive_time, serve_time,): self.name = name self.arrive_time = arrive_time self.serve_time = serve_time self.left_serve_time = serve_time self.finish_time = 0 self.cycling_time = 0 flag = 1 class Queue: def __init__(self, priority, processlist): self.priority = priority self.processlist = processlist self.q = 0 def size(self): return len(self.processlist) def get(self, index): return self.processlist[index] def add(self, process): return self.processlist.append(process) def delete(self, index): return self.processlist.remove(self.processlist[index]) def Scan(queuelist, i, running_time): for j in range(i): index = 0 curqueue = queuelist[j] if(curqueue == []): print((f"第{j}队列为空。")) break else: for k in range(curqueue.size()): if (curqueue.get(index).arrive_time > running_time): print(f"当前以运行:{running_time},{curqueue.get(index).name}已到达") if(i==2 and j ==1): running_time = Scan(queuelist,j,running_time) elif(i == 3 and j ==2 ): running_time = Scan(queuelist, j, running_time) curqueue.get(index).left_serve_time -=queuelist[j].q running_time += queuelist[j].q if (j == len(queuelist)-1): queuelist[j].add(curqueue.get(index)) print(f"进程{curqueue.get(index).name}还未完成,已添加至{j}队列。") else: queuelist[j+1].add(curqueue.get(index)) print(f"进程{curqueue.get(index).name}还未完成,已添加至{j+1}队列。") elif(curqueue.get(index).left_serve_time ==queuelist[j].q): running_time += queuelist[j].q print(f"进程{curqueue.get(index).name}已完成弹出") curqueue.get(index).left_serve_time = 0 else: running_time += curqueue.get(index).left_serve_time print(f"进程{curqueue.get(index).name}已完成弹出") curqueue.get(index).left_serve_time = 0 if(curqueue.get(index).left_serve_time == 0): curqueue.get(index).finish_time =running_time curqueue.get(index).cycling_time = curqueue.get(index).finish_time-curqueue.get(index).arrive_time print(f"{curqueue.get(index).name}进程已完成。完成时间:{curqueue.get(index).finish_time},周转时间:{curqueue.get(index).cycling_time}") index -= 1 curqueue.delete(index) index += 1 if index == curqueue.size(): break return running_time def MFQ(queuelist, queuefirst, runningtime): global flag for i in range (0, len(queuelist)): if i == 0 : queuelist[0].q = queuefirst else: queuelist[i].q = (queuelist[i-1].q)*2 index = 0 curqueue = queuelist[i] if flag : runningtime = curqueue.get(0).arrive_time flag = 0 if curqueue.size()==0: print("此队列为空。") if queuelist[0].size != 0: MFQ(queuelist, queuelist, runningtime) else: while True: if curqueue.get(index).arrive_time > runningtime: break else: if(i != 0): runningtime = Scan(queuelist, i, runningtime) runningtime = Scan(queuelist, i, runningtime) if curqueue.get(index).left_serve_time > queuelist[i].q: curqueue.get(index).left_serve_time -= queuelist[i].q runningtime += queuelist[i].q if i == len(queuelist)-1: queuelist[i].add(curqueue.get(index)) print(f"进程{curqueue.get(index).name}未执行完毕,添加至{i}队列") else: queuelist[i+1].add(curqueue.get(index)) print(f"进程{curqueue.get(index).name}未执行完毕,添加至{i+1}队列") elif curqueue.get(index).left_serve_time == queuelist[i].q: runningtime += queuelist[i].q print(f"进程{curqueue.get(index).name}已完成。") curqueue.get(index).left_serve_time = 0 else : runningtime += curqueue.get(index).left_serve_time print(f"进程{curqueue.get(index).name}已完成。") curqueue.get(index).left_serve_time = 0 if curqueue.get(index).left_serve_time == 0 : curqueue.get(index).finish_time = runningtime curqueue.get(index).cycling_time = curqueue.get(index).finish_time-curqueue.get(index).arrive_time print(f"进程{curqueue.get(index).name}已完成。完成时间:{curqueue.get(index).finish_time}。周转使时间:{curqueue.get(index).cycling_time}。") index -=1 curqueue.delete(index) index +=1 if index == curqueue.size(): break # 随机生成进程 def CreatePcb(queue_list): process_list0, process_list1, process_list2 = [], [], [] num = random.randint(1, 5) print('进程数 %d' % num) name = random.sample('abcdefghijklmnopqrstuvwxyz', num) for i in range(num): arrive_time = random.randint(1, 10) serve_time = random.randint(1, 10) print('进程名%s 到达时间%d 服务时间%d' % (name[i], arrive_time, serve_time)) process = Process(name[i], arrive_time, serve_time) process_list0.append(process) # 按照arrive time进行排序 cmpfun = operator.attrgetter('arrive_time') process_list0.sort(key=cmpfun) queue_list = [] queue0 = Queue(0, process_list0) queue1 = Queue(1, process_list1) queue2 = Queue(2, process_list2) queue_list.append(queue0) queue_list.append(queue1) queue_list.append(queue2) return queue_list if __name__ == '__main__': # 队列 queue_list = [] # 创建就绪队列 cp = CreatePcb(queue_list) # 执行多级反馈队列调度算法,第一队列时间片为1 mfq = MFQ(cp, 1, 0) 请优化此程序
47d03c891b57b6434926b875d5c73523
{ "intermediate": 0.30218759179115295, "beginner": 0.5877736210823059, "expert": 0.11003877222537994 }
31,064
I have this code below for a Atmega32a, 3 withe led, 3 pin 10K potentiometer, but when I turn the 10K potentiometer just two LED in PC0 and PC1 turn on and off and LED3 not working, what could be a problem and please provide me with solution #define F_CPU 1000000 #include <avr/io.h> #include <util/delay.h> #define ADC_CHANNEL 0 #define LED_DDR DDRC #define LED_PORT PORTC #define LED1 PC0 #define LED2 PC1 #define LED3 PC3 void initADC() { ADMUX = (1 << REFS0); // Reference AVCC with external capacitor at AREF pin ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // Enable ADC with prescaler 128 } uint16_t readADC(uint8_t channel) { ADMUX = (ADMUX & 0xF0) | (channel & 0x0F); // Select ADC channel with safety mask ADCSRA |= (1 << ADSC); // Start conversion while (ADCSRA & (1 << ADSC)); // Wait for conversion to complete return ADC; // Read ADC value } void init() { LED_DDR |= (1 << LED1) | (1 << LED2) | (1 << LED3); // Configure LED pins as outputs initADC(); } int main(void) { init(); uint16_t adcValue; const uint16_t threshold1 = 100; const uint16_t threshold2 = 341; const uint16_t threshold3 = 682; while (1) { adcValue = readADC(ADC_CHANNEL); LED_PORT &= ~((1 << LED1) | (1 << LED2) | (1 << LED3)); // Clear all LED bits if (adcValue >= threshold1) { LED_PORT |= (1 << LED1); // First level, turn on LED1 } if (adcValue >= threshold2) { LED_PORT |= (1 << LED2); // Turn on LED1 and LED2 } if (adcValue >= threshold3) { LED_PORT |= (1 << LED3); // Turn all LEDs on } _delay_ms(100); // Debounce delay } }
9ed4aa3c91844b261c9eb821ef77f8a6
{ "intermediate": 0.45837509632110596, "beginner": 0.3207904100418091, "expert": 0.22083455324172974 }
31,065
@bp.route("/text_from_string/", methods=["GET", "POST"]) @check_user_logined_mailed('is_loginted') def printed_text(): form = query_from_string() if request.method == "POST": query_s = request.form.get("query_s") parameters = dict(read_text_from_string=query_s) return redirect('/zadachi/?'+urlencode(parameters)) excuting of the function results in an error
27d42bfac0be4066afb2bdc17c96e026
{ "intermediate": 0.2908025085926056, "beginner": 0.5227611660957336, "expert": 0.18643634021282196 }
31,066
我在matlab运行这段程序function [average_energy, average_magnetization, heat_capacity, magnetic_susceptibility] = metropolis_ising(N, temperature, steps) spins = sign(rand(N,N)-0.5); energy = zeros(1,steps); magnetization = zeros(1,steps); for step = 1:steps for k = 1:(NN) % 随机选择格点 i = randi([1, N]); j = randi([1, N]); % 计算旧能量 old_energy = - spins(i,j) * (spins(mod(i+1,N)+1,j) + spins(mod(i-1,N)+1,j) + spins(i,mod(j+1,N)+1) + spins(i,mod(j-1,N)+1)); % 翻转格点 spins(i,j) = -spins(i,j); % 计算新能量 new_energy = -spins(i,j) * (spins(mod(i+1,N)+1,j) + spins(mod(i-1,N)+1,j) + spins(i,mod(j+1,N)+1) + spins(i,mod(j-1,N)+1)); % 根据Metropolis准则接受或拒绝改变 if new_energy - old_energy > 0 if exp(-((new_energy - old_energy)/temperature)) < rand % 恢复原来的自旋 spins(i,j) = -spins(i,j); end end % 更新能量和磁化强度 energy(step) = energy(step) + calculate_energy(spins); magnetization(step) = magnetization(step) + sum(spins(:)); end % 计算平均能量和平均磁化强度 energy(step) = energy(step) / (NN); magnetization(step) = magnetization(step) / (N*N); end % 计算平均能量、平均磁化强度、比热和平均磁化率 average_energy = mean(energy); average_magnetization = mean(magnetization); heat_capacity = var(energy) / (temperature^2); magnetic_susceptibility = var(magnetization) / temperature; end function energy = calculate_energy(spins) energy = 0; N = size(spins, 1); for i = 1:N for j = 1:N energy = energy - spins(i,j) * (spins(mod(i+1,N)+1,j) + spins(mod(i-1,N)+1,j) + spins(i,mod(j+1,N)+1) + spins(i,mod(j-1,N)+1)); end end end % 设置参数 N = 100; % 格点的数量 temperature = 1.0; % 温度 steps = 1000; % 迭代步数 % 运行Metropolis算法 [average_energy, average_magnetization, heat_capacity, magnetic_susceptibility] = metropolis_ising(N, temperature, steps); % 输出结果 fprintf(‘Average Energy: %f\n’, average_energy); fprintf(‘Average Magnetization: %f\n’, average_magnetization); fprintf(‘Heat Capacity: %f\n’, heat_capacity); fprintf(‘Magnetic Susceptibility: %f\n’, magnetic_susceptibility);结果matlab显示:错误: 文件: metropolis_ising.m 行: 59 列: 1 该语句不在任何函数内。我应该怎么改
e16336e15e66175bca339ad028b8ed27
{ "intermediate": 0.26465359330177307, "beginner": 0.5582194328308105, "expert": 0.177126944065094 }
31,067
Привет. Вот мой код System.out.println("Введите строку на русском"); var b = new java.util.Scanner(System.in, "UTF-8").nextLine(); FileUtils.serializeA(b, "test.set"); var a = (String) FileUtils.deserializeA("test.set"); System.out.println("\"" + a + "\""); Вот что я вижу в консоли Введите строку на русском лвор " " почему не записываются или не считываются русские символы?? десериализация идет через try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(Settings.filesDir + filename))) {...} и соотвестственно сериализация что не так?
081f0d0b9bdfc78dfb41a29f81ff36a7
{ "intermediate": 0.5333237648010254, "beginner": 0.33236899971961975, "expert": 0.13430726528167725 }
31,068
what would be the easiest way to create transitions animation for the different states? can you suggest a transition animation to fade from different game states? function loadStates() require ('game/states/SplashScreen') require ('game/states/firststart') require ('game/states/tetris') require ('game/states/benchmark') require ('game/states/game') require ('game/states/options') require ('game/states/gamePlusOptions') require ('game/states/gameShaders') require ('game/states/briefcaseMessage') require ('game/states/credits') require ('game/states/creditsend') require ('game/states/levelcompleted') require ('game/states/levelselection') require ('game/states/levelselection2') require ('game/states/gameover') require ('game/states/music') require ('game/states/extras') require ('game/states/extras/intro') require ('game/states/leveleditorMain') require ('game/states/tetris') require ('game/states/ends') end function updateStates(dt) if gamestatus == "levelEditor" then loveUpdateLevelEditor(dt) elseif gamestatus=="game" then updateGameStateShaders(dt) elseif gamestatus=="gameplusoptions" then updategetjoystickaxis() updateRadialMenu() if screenshottaken==true then --if a screenshot has been taken updatetakescreenshot() end updateButtonHeld(dt) elseif gamestatus=="options" then updateOptions(dt) elseif gamestatus=="splashScreen" then updateSplashScreen(dt) elseif gamestatus=="firststart" then updateFirstStart(dt) elseif gamestatus=="briefcasemessage" then updateBriefcaseMessage(dt) elseif gamestatus == "credits" then updateCredits(dt) elseif gamestatus == "creditsend" then updateCreditsEnd(dt) elseif gamestatus == "music" then updateMusic(dt) elseif gamestatus == "tetris" then updateTetris(dt) elseif gamestatus=="levelselection" or gamestatus=="levelselection2" then updateLevelSelection(dt) elseif gamestatus=="endmenu" or gamestatus=="fishhouseend" or gamestatus=="shipwrecksend" or gamestatus=="silversshipend" or gamestatus=="cityinthedeepend" or gamestatus=="ufoend" or gamestatus=="coralreefend" or gamestatus=="treasurecaveend" or gamestatus=="barrelend" or gamestatus=="secretcomputerend" or gamestatus=="linuxend" or gamestatus=="gameend" then updateEnds(dt) elseif gamestatus=="extras" then updateExtras(dt) elseif gamestatus=="benchmark" then updateBenchmark(dt) elseif gamestatus=="levelcompleted" then updateLevelCompleted(dt) end end --||This code is responsible for rendering different screens depending on the current game status. --[[ If the game status is "levelselection", it will draw the level selection menu with a 3D background and an optional loading icon. If the game status is "levelselection2", it will draw the second level selection menu with the same background. If the game status is "levelcompleted", it will draw the level completed screen, and if the game status is "gameover", it will draw the game over screen. Finally, if the game status is "music", it will draw the music menu, and if the CD is playing, it will draw the equalizer. Additionally, the code draws FPS metrics and battery info if enabled. The code assumes that other required functions and variables are defined elsewhere in the code. --]] function drawstates() if gamestatus=="tetris" then drawTetris() elseif gamestatus=="splashScreen" then drawSplashScreen() elseif gamestatus=="firststart" then drawFirststart() elseif gamestatus=="game" then drawGamestate() pb:drawMap () -- draw exit areas and other elements elseif gamestatus=="gameplusoptions" then drawGamestate() if nLevel==120 then drawReturnToLevelEditor() end -- button for the playing custom level to return to level editor elseif gamestatus=="levelselection" then drawLevelselection() elseif gamestatus=="levelselection2" then drawLevelselection2() elseif gamestatus=="levelcompleted" then drawLevelcompleted() elseif gamestatus=="gameover" then drawGameover() elseif gamestatus=="music" then drawMusic() elseif gamestatus == "options" then optionsdraw(dt) elseif gamestatus == "credits" then creditsdraw(dt) --If the game status is "credits", the credits menu is drawn. elseif gamestatus == "creditsend" then drawcscene() creditsdraw(dt) -- This is like credits but with animations behind the credits and it could be used if the players beats the whole game (end credits) elseif gamestatus == "briefcasemessage" then briefcasedraw(dt) --If the game status is "briefcasemessage", the briefcase message is drawn, Talkies dialog is displayed, and the "Press any mouse key to skip" message is shown after 1 second. --extras menu elseif gamestatus=="extras" then drawExtras() elseif gamestatus=="intro" then drawIntro() elseif gamestatus == "cutscenes" then drawcutscenes(dt) --If the game status is "cutscenes", the cutscenes are drawn. elseif gamestatus == "benchmark" then benchmarkdraw(dt) --If the game status is "benchmark", the benchmark is drawn. elseif gamestatus == "leditor" then leditordraw(dt) --If the game status is "leditor", the level editor is drawn. elseif gamestatus == "assets" then assetsmenudraw() --If the game status is "assets", the assets menu is drawn. elseif gamestatus == "instructions" then instructionsdraw() -- If the game status is "instructions", the instructions are drawn. elseif gamestatus == "levelEditor" then loveDrawLevelEditor(dt) elseif gamestatus == "DragCustomLevel" then drawDragCustomLevel() --end scenes --[[This code is a conditional statement that checks the value of the variable gamestatus. Depending on its value, different functions will be called to draw the end menu for each level of the game. The levels include fishhouseend, shipwrecksend, silversshipend, cityinthedeepend, ufoend, coralreefend, treasurecaveend, barrelend, secretcomputerend, linuxend, and gameend. For the ufoend level, there is an additional check to see if a moonshine shader effect is enabled. If it is, the scene will be drawn with the effect applied. --]] elseif gamestatus == "endmenu" then endmenudraw(dt) elseif gamestatus == "fishhouseend" then fishhouseenddraw(dt) elseif gamestatus == "shipwrecksend" then shipwrecksenddraw(dt) elseif gamestatus == "silversshipend" then silversshipenddraw(dt) elseif gamestatus == "cityinthedeepend" then cityinthedeependdraw(dt) elseif gamestatus == "ufoend" then -- Apply moonshine shaders if enabled if moonshineeffect == 1 or moonshineeffect == 3 or moonshineeffect == 4 then love.graphics.setShader() effect(function() ufoenddraw(dt) end) drawscenetext() elseif moonshineeffect == 2 then love.graphics.setShader() effect(function() ufoenddraw(dt) drawscenetext() end) else ufoenddraw(dt) drawscenetext() end -- Draw end menu for different levels elseif gamestatus == "coralreefend" then coralreefenddraw(dt) elseif gamestatus == "treasurecaveend" then treasurecaveenddraw(dt) elseif gamestatus == "barrelend" then barrelenddraw(dt) elseif gamestatus == "secretcomputerend" then secretcomputerenddraw(dt) elseif gamestatus == "linuxend" then linuxenddraw(dt) elseif gamestatus == "gameend" then gameenddraw(dt) end end
318b6759e7d21927865979d216487d50
{ "intermediate": 0.3984946608543396, "beginner": 0.33381932973861694, "expert": 0.2676859498023987 }
31,069
Write a program that gets input from user until user enters -1, and display the output.Use for loop.
c6b666c01e205e66e487958a9634b529
{ "intermediate": 0.2635240852832794, "beginner": 0.44856134057044983, "expert": 0.287914514541626 }
31,070
Write a program that gets input from the user until user enters -1, and display the output. Use for loop. in C++.
573fe482c32f849905c809f2abb5311e
{ "intermediate": 0.2960037887096405, "beginner": 0.45903801918029785, "expert": 0.24495822191238403 }
31,071
I am creating a FastAPI python app with SQLAlchemy, and am currently running into an error, this is the log:
26f5c95b3a3123fbb7f0a707611dec4e
{ "intermediate": 0.8406571745872498, "beginner": 0.06836922466754913, "expert": 0.09097352623939514 }
31,072
hi
950dc14a5a893f424ffb0ff2d0bdcb8b
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
31,073
python code using BiLSTM encoder and decoder rnn to translate English text to Arabic text by splitting example data into train. validate and test ,Tokenize the sentences and convert them into numerical representations ,Pad or truncate the sentences to a fixed length and use test data to evaluate and example prediction translation from test
ef26e651bf6f37f91b252feb5396633f
{ "intermediate": 0.39724865555763245, "beginner": 0.0989353135228157, "expert": 0.5038160681724548 }
31,074
Can I edit fstab via an (initramfs) prompt? If so, how? Be very concise.
18b09375e2d9f74f0cbcd60477d952bb
{ "intermediate": 0.48799896240234375, "beginner": 0.2101738601922989, "expert": 0.30182716250419617 }
31,075
I am working on a FastAPI python application with SQLAlchemy, and I am getting the following error:
dceaa33103704ff43db969be6cdb3374
{ "intermediate": 0.7318924069404602, "beginner": 0.1231839507818222, "expert": 0.14492367208003998 }
31,076
database/sql получить список всех orders golang
2d5812f527fd2c8721b55fed1b1d7727
{ "intermediate": 0.46343734860420227, "beginner": 0.30028972029685974, "expert": 0.236272931098938 }
31,077
while(!znaki.empty() && znaki.top() != '(') { postfix += znaki.top(); znaki.pop(); } Describe what do this code on C++
7367dc775d46bd1c863a85c7a10403bc
{ "intermediate": 0.3329267203807831, "beginner": 0.49998989701271057, "expert": 0.16708339750766754 }
31,078
I'm trying to get two LUKS devices to be unlocked before their btrfs raid 1 filesystems are attempted to be mounted individually because they should be mounted together. When I try to boot Debian, I get BTRFS error (device dm-1): devid 2 uuid wtv is missing and then blabla failed to read the system array: -2 and stuff like that. Very concisely tell me how to solve my problem.
fb4f2b3a1e2dcd2da8fb9ba9d60c8f82
{ "intermediate": 0.45867103338241577, "beginner": 0.2678431570529938, "expert": 0.27348577976226807 }
31,079
How can I make crypttab unlock both luks containers before either filesystem is mounted?: The guide below is simplified in a way that preparing the boot partition is not covered. Software based btrfs RAID1 requires two devices, which conceptually don’t even need to be on different disks. But for obvious reasons, it’s a good idea if they are… Having mirroring against encrypted storage brings its own set of challenges: It’s easy to encrypt a mirrored device (e.g. using md whereby each device has exactly the same data blocks), then use LVM and file systems on top. It’s not so easy to have this done if the mirroring is done at a layer “higher” than the encryption, since it is necessary to deal with multiple individually encrypted devices. Which is fine. More complicated but certainly not impossible. This post aims to guide through implementing btrfs mirroring on two encrypted storage devices. Disk partitioning The basic requirement for btrfs RAID1 is having two partitions, ideally in different disks, as described below: # fdisk -l /dev/sda Disk /dev/sda: 978.1 GiB, 1050214588416 bytes, 2051200368 sectors Disk model: Crucial_CT1050MX Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disklabel type: gpt Disk identifier: D2E25ADE-25A7-F056-9982-F40C48B55D53 Device Start End Sectors Size Type /dev/sda1 2048 526335 524288 256M EFI System /dev/sda2 526336 1574911 1048576 512M BIOS boot /dev/sda3 1574912 2623487 1048576 512M Linux filesystem /dev/sda4 2623488 935856127 933232640 445G Linux filesystem Similarly, there was a /dev/sdb4 on the second disk which had the same size. For btrfs, it is not a requirement that both devices have the same size, since the RAID setup will take as much space as the smallest device allows. Since LVM2 will be in place, all components of the system will live under /dev/sda4 and /dev/sdb4 as logical volumes sitting on encrypted physical volumes. The disks in this example were partitioned with a GPT label. This is helpful but not required for the purpose of this howto. Lastly the boot partitions (/dev/sda3 and /dev/sdb3) were equally configured in a btrfs raid1 layout, except these were not under LUKS2 encryption. LUKS2 encryption and boot tricks Before considering the file system, the partitions need encrypting using cryptsetup to implement luks2. For the purpose of this tutorial, and for the boot process to be simple, both devices are encrypted with the same passphrase. This means the actual keys are unique per device but the passphrase used to decrypt the storage encryption keys is the same on both devices. This is optional, just makes life easier. Volume names ‘crypt-d1’ and ‘crypt-d2’ were chosen, which will tie in with /etc/crypttab’s content. # cryptsetup luksFormat /dev/sda4 --type luks2 # cryptsetup luksOpen /dev/sda4 crypt-d1 # cryptsetup luksFormat /dev/sdb4 --type luks2 # cryptsetup luksOpen /dev/sdb4 crypt-d2 At this point, it’s worth noting down the respective partition UUIDs and creating /etc/crypttab # echo "crypt-d1 PARTUUID=$(lsblk /dev/sda4 -o partuuid -n) btrfs_r1 luks,keyscript=/lib/cryptsetup/scripts/decrypt_keyctl > /etc/crypttab # echo "crypt-d2 PARTUUID=$(lsblk /dev/sdb4 -o partuuid -n) btrfs_r1 luks,keyscript=/lib/cryptsetup/scripts/decrypt_keyctl >> /etc/crypttab Beyond the automation, here’s what /etc/crypttab looks like: # cat /etc/crypttab crypt-d1 PARTUUID=ab4f59d1-8e44-2839-8e8f-3b42e2db5192 btrfs_r1 luks,keyscript=/lib/cryptsetup/scripts/decrypt_keyctl crypt-d2 PARTUUID=aa3a4e05-84b7-b758-b66f-bbafa1271f6a btrfs_r1 luks,keyscript=/lib/cryptsetup/scripts/decrypt_keyctl The above lines under /etc/crypttab have the following impact: labels crypt-d1 and crypt-d2 as ‘btrfs_r1’ for the purpose of handling by cryptsetup tools; Once the passphrase has been entered for crypt-d1, it’s handled by the decrypt_keyctl to assign transparently to crypt-d2 (and any other device matching the ‘btrfs_r1’ label); LVM2 Now that the encrypted volumes exist and are available, LVM is used to manage the encrypted space. Each encrypted device will become a physical volume (PV) and hold its own volume group (VG) and logical volumes (LV). # pvcreate /dev/mapper/crypt-d1 # vgcreate disk1 /dev/mapper/crypt-d1 # lvcreate -l 90%VG -n root disk1 # lvcreate -l 100%VG -n swap disk1 ### repeat for PV crypt-d2 into a VG 'disk2' ### After setting up, the layout should be similar to the following: ... ├─sda4 8:4 0 445G 0 part │ └─crypt-d1 253:0 0 445G 0 crypt │ ├─disk1-swap 253:1 0 16G 0 lvm [SWAP] │ └─disk1-root 253:2 0 429G 0 lvm / ... └─sdb4 8:20 0 445G 0 part | └─crypt-d2 253:3 0 445G 0 crypt | ├─disk2-swap 253:4 0 16G 0 lvm [SWAP] | └─disk2-root 253:5 0 429G 0 lvm ... You will notice that until this point both disks have been setup individually, each with their own encrypted space and LVM layout. # pvs PV VG Fmt Attr PSize PFree /dev/mapper/crypt-d1 disk1 lvm2 a-- 444.98g 0 /dev/mapper/crypt-d2 disk2 lvm2 a-- 444.98g 0 # lvs LV VG Attr LSize Pool Origin Data% Meta% Move Log Cpy%Sync Convert root disk1 -wi-ao---- 428.98g swap disk1 -wi-ao---- 16.00g root disk2 -wi-ao---- 428.98g swap disk2 -wi-ao---- 16.00g btrfs RAID1 filesystem It is at this point that btrfs makes an appearance. First by being created under /dev/mapper/disk1–root, then by being extended under RAID1 into /dev/mapper/disk2-root. # mkfs.btrfs /dev/disk1/root # mount /dev/disk1/root /mnt/root # btrfs device add /dev/disk2/root /mnt/root # btrfs filesystem label /mnt/root root-r1 # btrfs filesystem balance start -dconvert=raid1 -mconvert=raid2 /mnt/root The above sequence of commands creates a btrfs filesystem under /dev/disk1/root, labels it as ‘root-r1’, adds the device /dev/disk2/root and balances the file system across the two devices in a raid1 configuration. Checking the btrfs RAID filesystem can be done using btrfs filesystem usage and btrfs device usage as shown below: # btrfs filesystem usage / Overall: Device size: 857.96GiB Device allocated: 258.06GiB Device unallocated: 599.90GiB Device missing: 0.00B Used: 248.08GiB Free (estimated): 303.13GiB (min: 303.13GiB) Data ratio: 2.00 Metadata ratio: 2.00 Global reserve: 138.28MiB (used: 0.00B) Data,RAID1: Size:127.00GiB, Used:123.82GiB /dev/mapper/disk1-root 127.00GiB /dev/mapper/disk2-root 127.00GiB Metadata,RAID1: Size:2.00GiB, Used:226.30MiB /dev/mapper/disk1-root 2.00GiB /dev/mapper/disk2-root 2.00GiB System,RAID1: Size:32.00MiB, Used:48.00KiB /dev/mapper/disk1-root 32.00MiB /dev/mapper/disk2-root 32.00MiB Unallocated: /dev/mapper/disk1-root 299.95GiB /dev/mapper/disk2-root 299.95GiB # btrfs device usage / /dev/mapper/disk1-root, ID: 1 Device size: 428.98GiB Device slack: 0.00B Data,RAID1: 127.00GiB Metadata,RAID1: 2.00GiB System,RAID1: 32.00MiB Unallocated: 299.95GiB /dev/mapper/disk2-root, ID: 2 Device size: 428.98GiB Device slack: 0.00B Data,RAID1: 127.00GiB Metadata,RAID1: 2.00GiB System,RAID1: 32.00MiB Unallocated: 299.95GiB Local fstab For the purpose of fstab, both /dev/disk1/root and /dev/disk2/root will have the same file system UUID so either can be mounted. However, using the UUID will solve the problem transparently. Conceptually, after swap space has been created under /dev/disk1/swap and /dev/disk2/swap (not RAID), then root and swap entries on fstab can be created as follows: echo " UUID=$(lsblk /dev/disk1/root -o uuid -n) / btrfs defaults 0 0 UUID=$(lsblk /dev/disk1/swap -o uuid -n) none swap sw 0 0 " >> /etc/fstab Notice that under fstab UUID is used, whereas under /etc/crypttab PARTUUID was used instead. Only one UUID was necessary to reference the root file system (not both). Also notice that since PARTUUID and UUIDs are used, there’s no fiddling with device names or locations – if you’re not using UUIDs instead of device paths, do it, it will change your life. Here’s what fstab looks like: # cat /etc/fstab UUID= /boot btrfs defaults 00 UUID= /boot/efi vfat defaults,noatime 0 0 UUID=e76a6d38-096c-301b-f56b-ab0d7170f725 / btrfs defaults 00 UUID=ad711836-473e-2449-2bde-5419c7cef40f none swap sw 0 0 UUID=316d8414-371f-6910-3b5f-cce6b1dd0bf9 none swap sw 0 0 Boot loader and initramfs Ensuring that the boot loader and initramfs are setup correctly are not entirely trivial matters. If the above has been done on a running system with existing /boot partition (with bootloader files) with correctly labelled LUKS2 volumes (crypt-d1 and crypt-d2) with correct LVM names (disk1 and disk2) with correctly constructed /etc/fstab and /etc/crypttab, then running the following sequence of commands should enable preparation of the initramfs with the correct cryptsetup binaries and helper scripts (decrypt_keyctl) as well as correctly constructed grub.conf. # update-initramfs -u # update-grub # grub-install /dev/sda # grub-install /dev/sdb
7824f6a2ea87880179afbd09fa44a1b9
{ "intermediate": 0.40428829193115234, "beginner": 0.4098820984363556, "expert": 0.18582956492900848 }
31,080
Исправь программу так, чтобы она выводила фрактальное изображение крестика из звёздочек в c++:#include <iostream> #include <vector> #include <math.h> using namespace std; char frakt(vector<vector <char>>& vec, vector <vector<char>> &change,int &c,int &k) { k += 1; if (k == 1) { k += 1; } vector <vector<char>> miss(pow(3,k),vector<char> (pow(3, k),' ')); change = vec; vector <vector<char>> dop; dop = miss; for (int i = 0; i < dop.size(); i++) { for (int j = 0; j < change[i].size(); j++) { dop[i].push_back(change[i][j]); } } for (int i = 0; i < dop.size(); i++) { for (int j = 0; j < miss[i].size(); j++) { dop[i].push_back(miss[i][j]); } } while (c > 1) { c--; for (int i = 0; i < vec.size(); i++) { for (int j = 0; j < change[i].size(); j++) { vec[i].push_back(change[i][j]); } } for (int i = 0; i < vec.size(); i++) { for (int j = change[i].size() - 1; j >= 0; j--) { vec[i].insert(vec[i].begin(), change[i][j]); } } vec.insert(vec.end(), dop.begin(), dop.end()); vec.insert(vec.begin(), dop.begin(), dop.end()); frakt(vec, change, c, k); } return 0; } int main() { vector <vector <char>>vec; vector <vector<char>> change; vec.insert(vec.end(),{'*'}); int c,k=-1; cin >> c; if (c <= 0) { cout << vec[0][0]; } else { frakt(vec,change,c,k); } for (const auto& row : vec) { for (const auto& element : row) { cout << element << " "; } cout <<endl; } return 0; }
0ad0b4bcb74dcf170133179443f5d54b
{ "intermediate": 0.24824057519435883, "beginner": 0.5681151151657104, "expert": 0.18364426493644714 }
31,081
write java code that looks for an exclamation point and then records in it a int value
77a5eaa6e997235d37940dbf3f43ec4a
{ "intermediate": 0.3745770752429962, "beginner": 0.30843740701675415, "expert": 0.31698548793792725 }
31,082
How do I pass the passphrase via /etc/crypttab?
a363e2ece34fc88e27c270d66383f350
{ "intermediate": 0.3727399706840515, "beginner": 0.2417628914117813, "expert": 0.38549715280532837 }
31,083
How does one update grub in the (initramfs) prompt?
0a6316b533337968f000cffb815e00a4
{ "intermediate": 0.42448607087135315, "beginner": 0.18459874391555786, "expert": 0.3909151554107666 }
31,084
understand and execute commands for a custom programming language. Define the following commands: Run_3DS: This command should be interpreted as ‘Run 3D scene’. spawn_Cube: This command should be interpreted as ‘spawning a 3D cube’. Utilize the characters [ | _ + \ / , . < > ( ) * # ] to represent the syntax and structure of the 3D scene, Make up commands if you need to, If understood, write “Program gpt Runned”
c7a12e16feaa9481faddb7fc53beb81b
{ "intermediate": 0.2026328146457672, "beginner": 0.6038084626197815, "expert": 0.1935586929321289 }
31,085
give me a hello world in java
bf66adf814a3d444bee4124626df2916
{ "intermediate": 0.3611893951892853, "beginner": 0.3911703824996948, "expert": 0.24764017760753632 }
31,086
C# send notification to phone
1b5dcb38abe3623b58c69136aa29a981
{ "intermediate": 0.4697033166885376, "beginner": 0.2577558755874634, "expert": 0.27254077792167664 }
31,087
hey
842a3fcec5906c74c16cc2d6b9af1cca
{ "intermediate": 0.33180856704711914, "beginner": 0.2916048467159271, "expert": 0.3765866458415985 }
31,088
what is the diff between sub "full" and "forced" ?
eefb04162a3ad669b3340cecd16fd3fa
{ "intermediate": 0.31327176094055176, "beginner": 0.23912136256694794, "expert": 0.4476068317890167 }
31,089
Write a class StringLength.java with a class method stringLength() that takes a String as parameter and returns the length of your string with the following return value: “Your string is <length of the String> characters long” (Hint: <length of the String> to be replaced with the actual length of the string). Use an instance method of the class String in your method. Run and test the method. explain me this code simply please
e4bb7c33fb3fc171a774a7700e0fbb2a
{ "intermediate": 0.31256625056266785, "beginner": 0.545426607131958, "expert": 0.14200715720653534 }
31,090
image = cv2.imread(“0.0/00.pgm”) %time import numpy as np import matplotlib.pyplot as plt from math import atan2, degrees def gaussian_filter(image: np.ndarray, sigma: float=1.5) -> np.ndarray: “”“Returns image with gaussian filter.”“” size = int(2 * np.ceil(3 * sigma) + 1) kernel = np.fromfunction( lambda x, y: (1 / (2 * np.pi * sigma**2)) * np.exp( -((x - size//2)**2 + (y - size//2)2) / (2 * sigma2)), (size, size)) smoothed_image = np.zeros_like(image) for i in range(image.shape[0]): for j in range(image.shape[1]): neighborhood = image[max(i-size//2, 0):min(i+size//2+1, image.shape[0]), max(j-size//2, 0):min(j+size//2+1, image.shape[1])] smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]) return smoothed_image def sobel_operator(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]) gradient_x = np.zeros_like(image) gradient_y = np.zeros_like(image) for i in range(image.shape[0] - 2): for j in range(image.shape[1] - 2): neighborhood = image[i:i+3, j:j+3] gradient_x[i+1, j+1] = np.sum(neighborhood * kernel_x) gradient_y[i+1, j+1] = np.sum(neighborhood * kernel_y) edges = np.hypot(gradient_x, gradient_y) return edges def binary_threshold(image, threshold): binary_image = np.zeros_like(image) binary_image[image > threshold] = 1 return binary_image def binary_closing(image, iterations=1): closed_image = np.copy(image) for i in range(iterations): dilated_image = np.maximum(closed_image, np.maximum(np.roll(closed_image, 1, axis=0), np.roll(closed_image, -1, axis=0))) dilated_image = np.maximum(dilated_image, np.maximum(np.roll(dilated_image, 1, axis=1), np.roll(dilated_image, -1, axis=1))) closed_image = np.minimum(closed_image, dilated_image) return closed_image def binary_opening(image, iterations=1): opened_image = np.copy(image) for i in range(iterations): eroded_image = np.minimum(opened_image, np.minimum(np.roll(opened_image, 1, axis=0), np.roll(opened_image, -1, axis=0))) eroded_image = np.minimum(eroded_image, np.minimum(np.roll(eroded_image, 1, axis=1), np.roll(eroded_image, -1, axis=1))) opened_image = np.maximum(opened_image, eroded_image) return opened_image def probabilistic_hough_line(image, threshold, line_length, line_gap): lines = [] indices = np.argwhere(image > threshold) x_coords, y_coords = indices[:, 1], indices[:, 0] while len(indices) > 0: x1, y1 = x_coords[0], y_coords[0] distances = np.abs((x_coords - x1) + (y_coords - y1) * 1j) line_indices = np.where(distances < line_length)[0] line_x_coords = x_coords[line_indices] line_y_coords = y_coords[line_indices] x2, y2 = line_x_coords[-1], line_y_coords[-1] lines.append([(x1, y1), (x2, y2)]) line_indices = np.where((x_coords >= x1-line_gap) & (x_coords <= x2+line_gap) & (y_coords >= y1-line_gap) & (y_coords <= y2+line_gap))[0] x_coords = np.delete(x_coords, line_indices) y_coords = np.delete(y_coords, line_indices) return np.array(lines) def label(image): labeled_image = np.zeros_like(image) current_label = 1 for i in range(image.shape[0]): for j in range(image.shape[1]): if image[i, j] == 1 and labeled_image[i, j] == 0: stack = [(i, j)] while len(stack) > 0: x, y = stack.pop() labeled_image[x, y] = current_label for m in range(max(x-1, 0), min(x+2, image.shape[0])): for n in range(max(y-1, 0), min(y+2, image.shape[1])): if image[m, n] == 1 and labeled_image[m, n] == 0: stack.append((m, n)) current_label += 1 return labeled_image, current_label - 1 def detect_triangle_angles(image): # Сглаживаем изображение для удаления шума smoothed_image = gaussian_filter(image, sigma=1.5) # Применяем оператор Собеля для выделения границ edges = sobel_operator(smoothed_image) # Применяем пороговую обработку для получения бинарного изображения threshold_image = binary_threshold(edges, threshold=0.2) # Замыкаем линии и объединяем границы треугольника closed_image = binary_closing(threshold_image, iterations=3) # Разделяем связанные границы треугольника opened_image = binary_opening(closed_image, iterations=2) # Используем алгоритм Хафа для поиска линий lines = probabilistic_hough_line(opened_image, threshold=10, line_length=10, line_gap=3) # Применяем фильтр к найденным линиям для удаления ненужных сегментов labeled_image, num_labels = label(opened_image) for i in range(1, num_labels + 1): indices = np.argwhere(labeled_image == i) if len(indices) < 50: # Фильтр сегментов по длине opened_image[tuple(indices.T)] = 0 # Используем найденные границы для определения углов треугольника angles = [] for line in lines: x1, y1 = line[0] x2, y2 = line[1] angles.append(degrees(atan2(y2 - y1, x2 - x1))) return angles # Пример использования # image_path = “example.jpg’ # Путь к изображению # image = load_image(image_path) # angles = detect_triangle_angles(image) # print(‘Углы треугольника:’, angles) angles = detect_triangle_angles(image) print(f"Corners of 3angle: {angles}”) Получаю на этот код ошибку: 21 for j in range(image.shape[1]): 22 neighborhood = image[max(i-size//2, 0):min(i+size//2+1, image.shape[0]), max(j-size//2, 0):min(j+size//2+1, image.shape[1])] —> 23 smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]) 24 25 return smoothed_image ValueError: operands could not be broadcast together with shapes (6,6,3) (6,6
f9c5bee3ff81d30567adeca8b1247973
{ "intermediate": 0.2490556240081787, "beginner": 0.45811232924461365, "expert": 0.29283201694488525 }
31,091
image = cv2.imread(“0.0/00.pgm”) %time import numpy as np import matplotlib.pyplot as plt from math import atan2, degrees def gaussian_filter(image: np.ndarray, sigma: float=1.5) -> np.ndarray: “”“Returns image with gaussian filter.”“” size = int(2 * np.ceil(3 * sigma) + 1) kernel = np.fromfunction( lambda x, y: (1 / (2 * np.pi * sigma**2)) * np.exp( -((x - size//2)**2 + (y - size//2)2) / (2 * sigma2)), (size, size)) smoothed_image = np.zeros_like(image) for i in range(image.shape[0]): for j in range(image.shape[1]): neighborhood = image[max(i-size//2, 0):min(i+size//2+1, image.shape[0]), max(j-size//2, 0):min(j+size//2+1, image.shape[1])] smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]) return smoothed_image def sobel_operator(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]) gradient_x = np.zeros_like(image) gradient_y = np.zeros_like(image) for i in range(image.shape[0] - 2): for j in range(image.shape[1] - 2): neighborhood = image[i:i+3, j:j+3] gradient_x[i+1, j+1] = np.sum(neighborhood * kernel_x) gradient_y[i+1, j+1] = np.sum(neighborhood * kernel_y) edges = np.hypot(gradient_x, gradient_y) return edges def binary_threshold(image, threshold): binary_image = np.zeros_like(image) binary_image[image > threshold] = 1 return binary_image def binary_closing(image, iterations=1): closed_image = np.copy(image) for i in range(iterations): dilated_image = np.maximum(closed_image, np.maximum(np.roll(closed_image, 1, axis=0), np.roll(closed_image, -1, axis=0))) dilated_image = np.maximum(dilated_image, np.maximum(np.roll(dilated_image, 1, axis=1), np.roll(dilated_image, -1, axis=1))) closed_image = np.minimum(closed_image, dilated_image) return closed_image def binary_opening(image, iterations=1): opened_image = np.copy(image) for i in range(iterations): eroded_image = np.minimum(opened_image, np.minimum(np.roll(opened_image, 1, axis=0), np.roll(opened_image, -1, axis=0))) eroded_image = np.minimum(eroded_image, np.minimum(np.roll(eroded_image, 1, axis=1), np.roll(eroded_image, -1, axis=1))) opened_image = np.maximum(opened_image, eroded_image) return opened_image def probabilistic_hough_line(image, threshold, line_length, line_gap): lines = [] indices = np.argwhere(image > threshold) x_coords, y_coords = indices[:, 1], indices[:, 0] while len(indices) > 0: x1, y1 = x_coords[0], y_coords[0] distances = np.abs((x_coords - x1) + (y_coords - y1) * 1j) line_indices = np.where(distances < line_length)[0] line_x_coords = x_coords[line_indices] line_y_coords = y_coords[line_indices] x2, y2 = line_x_coords[-1], line_y_coords[-1] lines.append([(x1, y1), (x2, y2)]) line_indices = np.where((x_coords >= x1-line_gap) & (x_coords <= x2+line_gap) & (y_coords >= y1-line_gap) & (y_coords <= y2+line_gap))[0] x_coords = np.delete(x_coords, line_indices) y_coords = np.delete(y_coords, line_indices) return np.array(lines) def label(image): labeled_image = np.zeros_like(image) current_label = 1 for i in range(image.shape[0]): for j in range(image.shape[1]): if image[i, j] == 1 and labeled_image[i, j] == 0: stack = [(i, j)] while len(stack) > 0: x, y = stack.pop() labeled_image[x, y] = current_label for m in range(max(x-1, 0), min(x+2, image.shape[0])): for n in range(max(y-1, 0), min(y+2, image.shape[1])): if image[m, n] == 1 and labeled_image[m, n] == 0: stack.append((m, n)) current_label += 1 return labeled_image, current_label - 1 def detect_triangle_angles(image): # Сглаживаем изображение для удаления шума smoothed_image = gaussian_filter(image, sigma=1.5) # Применяем оператор Собеля для выделения границ edges = sobel_operator(smoothed_image) # Применяем пороговую обработку для получения бинарного изображения threshold_image = binary_threshold(edges, threshold=0.2) # Замыкаем линии и объединяем границы треугольника closed_image = binary_closing(threshold_image, iterations=3) # Разделяем связанные границы треугольника opened_image = binary_opening(closed_image, iterations=2) # Используем алгоритм Хафа для поиска линий lines = probabilistic_hough_line(opened_image, threshold=10, line_length=10, line_gap=3) # Применяем фильтр к найденным линиям для удаления ненужных сегментов labeled_image, num_labels = label(opened_image) for i in range(1, num_labels + 1): indices = np.argwhere(labeled_image == i) if len(indices) < 50: # Фильтр сегментов по длине opened_image[tuple(indices.T)] = 0 # Используем найденные границы для определения углов треугольника angles = [] for line in lines: x1, y1 = line[0] x2, y2 = line[1] angles.append(degrees(atan2(y2 - y1, x2 - x1))) return angles # Пример использования # image_path = “example.jpg’ # Путь к изображению # image = load_image(image_path) # angles = detect_triangle_angles(image) # print(‘Углы треугольника:’, angles) angles = detect_triangle_angles(image) print(f"Corners of 3angle: {angles}”) ВОТ МОЙ КОД, получаю вот такую ошибку : ValueError Traceback (most recent call last) <ipython-input-19-71b7edb3cf9b> in <cell line: 147>() 145 # angles = detect_triangle_angles(image) 146 # print(‘Углы треугольника:’, angles) –> 147 angles = detect_triangle_angles(image) 148 print(f"Corners of 3angle: {angles}") 1 frames <ipython-input-19-71b7edb3cf9b> in gaussian_filter(image, sigma) 21 for j in range(image.shape[1]): 22 neighborhood = image[max(i-size//2, 0):min(i+size//2+1, image.shape[0]), max(j-size//2, 0):min(j+size//2+1, image.shape[1])] —> 23 smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]) 24 25 return smoothed_image ValueError: operands could not be broadcast together with shapes (6,6,3) (6,6) Что делать?!?!?!?!
6adb6a5d22c3ed34170916bafb4162e1
{ "intermediate": 0.2490556240081787, "beginner": 0.45811232924461365, "expert": 0.29283201694488525 }
31,092
suivant le contrat "testHelpers" qui permet de tester les fonctions du contrat principal "penduel" qui sont "internal" et l'interface "TesHelpers2", pourquoi Game n'est pas reconnu ? contract "Penduel" : mapping(uint256 => Game) public games; - contract "testHelper" : "import "./Penduel.sol"; pragma solidity 0.8.17; interface TestHelper2 { function getGame(uint256 gameId) external view returns (Game memory); } - contract TestHelper is TestHelper2 { Penduel public penduel; uint256 public gameId; constructor(Penduel _penduel) { penduel = _penduel; } function getGame() public view override returns (Game memory) { (ici pas de probleme avec Game) return penduel.games(gameId); }
3821497399ef496a99f6425393d266bb
{ "intermediate": 0.6027029752731323, "beginner": 0.2714100182056427, "expert": 0.1258869469165802 }
31,093
What should the permissions of /var/lib/libvirt/images/ be (in the context of virt-manager and libvirtd or whatever in Debian)?
dd8d2cc324adcf9f9f2c1d5845188c04
{ "intermediate": 0.6068798303604126, "beginner": 0.20998969674110413, "expert": 0.18313050270080566 }
31,094
can I have a VBA code to unlock all the protected sheets in my workbook
a57837ed01f0830474b25d07b58afa43
{ "intermediate": 0.4875187575817108, "beginner": 0.23849524557590485, "expert": 0.27398595213890076 }
31,095
image = cv2.imread("0.0/00.pgm") ImageService.show_image(image) %time import numpy as np import matplotlib.pyplot as plt from math import atan2, degrees def gaussian_filter(image: np.ndarray, sigma: float=1.5) -> np.ndarray: """Returns image with gaussian filter.""" size = int(2 * np.ceil(3 * sigma) + 1) kernel = np.fromfunction( lambda x, y: (1 / (2 * np.pi * sigma**2)) * np.exp( -((x - size//2)**2 + (y - size//2)**2) / (2 * sigma**2)), ( size, size)) smoothed_image = np.zeros_like(image) for i in range(image.shape[0]): for j in range(image.shape[1]): neighborhood = image[max(i-size//2, 0):min(i+size//2+1, image.shape[0]), max(j-size//2, 0):min(j+size//2+1, image.shape[1])] smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]) return smoothed_image def sobel_operator(image): kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.array([[-1, -2, -1], [0, 0, 0], [1, 2, 1]]) gradient_x = np.zeros_like(image) gradient_y = np.zeros_like(image) for i in range(image.shape[0] - 2): for j in range(image.shape[1] - 2): neighborhood = image[i:i+3, j:j+3] gradient_x[i+1, j+1] = np.sum(neighborhood * kernel_x) gradient_y[i+1, j+1] = np.sum(neighborhood * kernel_y) edges = np.hypot(gradient_x, gradient_y) return edges def binary_threshold(image, threshold): binary_image = np.zeros_like(image) binary_image[image > threshold] = 1 return binary_image def binary_closing(image, iterations=1): closed_image = np.copy(image) for i in range(iterations): dilated_image = np.maximum(closed_image, np.maximum(np.roll(closed_image, 1, axis=0), np.roll(closed_image, -1, axis=0))) dilated_image = np.maximum(dilated_image, np.maximum(np.roll(dilated_image, 1, axis=1), np.roll(dilated_image, -1, axis=1))) closed_image = np.minimum(closed_image, dilated_image) return closed_image def binary_opening(image, iterations=1): opened_image = np.copy(image) for i in range(iterations): eroded_image = np.minimum(opened_image, np.minimum(np.roll(opened_image, 1, axis=0), np.roll(opened_image, -1, axis=0))) eroded_image = np.minimum(eroded_image, np.minimum(np.roll(eroded_image, 1, axis=1), np.roll(eroded_image, -1, axis=1))) opened_image = np.maximum(opened_image, eroded_image) return opened_image def probabilistic_hough_line(image, threshold, line_length, line_gap): lines = [] indices = np.argwhere(image > threshold) x_coords, y_coords = indices[:, 1], indices[:, 0] while len(indices) > 0: x1, y1 = x_coords[0], y_coords[0] distances = np.abs((x_coords - x1) + (y_coords - y1) * 1j) line_indices = np.where(distances < line_length)[0] line_x_coords = x_coords[line_indices] line_y_coords = y_coords[line_indices] x2, y2 = line_x_coords[-1], line_y_coords[-1] lines.append([(x1, y1), (x2, y2)]) line_indices = np.where((x_coords >= x1-line_gap) & (x_coords <= x2+line_gap) & (y_coords >= y1-line_gap) & (y_coords <= y2+line_gap))[0] x_coords = np.delete(x_coords, line_indices) y_coords = np.delete(y_coords, line_indices) return np.array(lines) def label(image): labeled_image = np.zeros_like(image) current_label = 1 for i in range(image.shape[0]): for j in range(image.shape[1]): if image[i, j] == 1 and labeled_image[i, j] == 0: stack = [(i, j)] while len(stack) > 0: x, y = stack.pop() labeled_image[x, y] = current_label for m in range(max(x-1, 0), min(x+2, image.shape[0])): for n in range(max(y-1, 0), min(y+2, image.shape[1])): if image[m, n] == 1 and labeled_image[m, n] == 0: stack.append((m, n)) current_label += 1 return labeled_image, current_label - 1 def detect_triangle_angles(image): # Сглаживаем изображение для удаления шума smoothed_image = gaussian_filter(image, sigma=1.5) # Применяем оператор Собеля для выделения границ edges = sobel_operator(smoothed_image) # Применяем пороговую обработку для получения бинарного изображения threshold_image = binary_threshold(edges, threshold=0.2) # Замыкаем линии и объединяем границы треугольника closed_image = binary_closing(threshold_image, iterations=3) # Разделяем связанные границы треугольника opened_image = binary_opening(closed_image, iterations=2) # Используем алгоритм Хафа для поиска линий lines = probabilistic_hough_line(opened_image, threshold=10, line_length=10, line_gap=3) # Применяем фильтр к найденным линиям для удаления ненужных сегментов labeled_image, num_labels = label(opened_image) for i in range(1, num_labels + 1): indices = np.argwhere(labeled_image == i) if len(indices) < 50: # Фильтр сегментов по длине opened_image[tuple(indices.T)] = 0 # Используем найденные границы для определения углов треугольника angles = [] for line in lines: x1, y1 = line[0] x2, y2 = line[1] angles.append(degrees(atan2(y2 - y1, x2 - x1))) return angles # Пример использования # image_path = "example.jpg’ # Путь к изображению # image = load_image(image_path) # angles = detect_triangle_angles(image) # print(‘Углы треугольника:’, angles) angles = detect_triangle_angles(image) print(f"Corners of 3angle: {angles}") Вот это код, а ниже ошибка: ValueError Traceback (most recent call last) <ipython-input-22-98ebb8eb0367> in <cell line: 148>() 146 # angles = detect_triangle_angles(image) 147 # print(‘Углы треугольника:’, angles) --> 148 angles = detect_triangle_angles(image) 149 print(f"Corners of 3angle: {angles}") 1 frames <ipython-input-22-98ebb8eb0367> in gaussian_filter(image, sigma) 22 for j in range(image.shape[1]): 23 neighborhood = image[max(i-size//2, 0):min(i+size//2+1, image.shape[0]), max(j-size//2, 0):min(j+size//2+1, image.shape[1])] ---> 24 smoothed_image[i, j] = np.sum(neighborhood * kernel[:neighborhood.shape[0], :neighborhood.shape[1]]) 25 26 return smoothed_image ValueError: operands could not be broadcast together with shapes (6,6,3) (6,6)
d3fbd52d603bbc7e32b4bededa1288ff
{ "intermediate": 0.24586552381515503, "beginner": 0.49169406294822693, "expert": 0.26244041323661804 }
31,096
private async Task LogResponse(HttpContext context, RequestDelegate next) { var responseTime = new DateTimeOffset(); var request = context.Request; var response = context.Response; var originalBodyStream = context.Response.Body; await using var responseBody = _recyclableMemoryStreamManager.GetStream(); context.Response.Body = responseBody; await next(context); context.Response.Body.Seek(0, SeekOrigin.Begin); var body = await new StreamReader(context.Response.Body).ReadToEndAsync(); context.Response.Body.Seek(0, SeekOrigin.Begin); if (!string.IsNullOrWhiteSpace(body) && response.StatusCode >= 200 && response.StatusCode <= 299) body = request.GetResponseBodyToString(body); _logger.LogDebug( "Response: {Schema} {@Host} {@Path} {@QueryString} {StatusCode} {@Body} {@ResponseTime}", request.Scheme, request.Host, request.Path, request.GetObfuscateQueryString(), response.StatusCode, body, responseTime ); await responseBody.CopyToAsync(originalBodyStream); } comom modificar la parte response.StatusCode >= 200 && response.StatusCode <= 299 por algo mas simple estilo issuccesfulstatuscode
741457b4419b4edde844e96fa6f0e36d
{ "intermediate": 0.533011794090271, "beginner": 0.29034358263015747, "expert": 0.17664453387260437 }
31,097
Write a python script to get access to internal system https://10.10.117.203/prod/ru/reports/finance_client_status using credentials
d4b96ffb4ac7f745723913c5c3a912fa
{ "intermediate": 0.4104454517364502, "beginner": 0.2550630569458008, "expert": 0.3344915211200714 }
31,098
import numpy as np def restore_triangle(image: np.ndarray) -> np.ndarray | None: # Размеры изображения height, width = image.shape[1], image.shape[0] # Параметры алгоритма threshold = 100 # Порог для определения вершин треугольника min_pixels = 3 # Минимальное количество пикселей для интервала значений max_deviation = 5 # Максимальное отклонение вершин треугольника # Временный массив для хранения пикселей temp_pixels = [] # Проход по каждому пикселю изображения for y in range(height): for x in range(width): pixel = image[y, x] # Проверка значения пикселя if pixel > threshold: temp_pixels.append((x, y)) # Проверка количества сохраненных пикселей if len(temp_pixels) < min_pixels: return None # Поиск интервалов вершин треугольника intervals = [] temp_pixels = sorted(temp_pixels) for i in range(len(temp_pixels) - 1): x1, y1 = temp_pixels[i] x2, y2 = temp_pixels[i + 1] if y2 - y1 > 1: intervals.append((x1, x2)) # Поиск координат вершин треугольника max_area = 0 triangle_points = None for interval in intervals: x1, x2 = interval # Интервал значений пикселей pixel_interval = image[:, x1:x2+1] # Поиск координат вершин треугольника points = find_triangle_points(pixel_interval) if points is not None: # Расчет площади треугольника area = calculate_triangle_area(points) # Проверка максимальной площади if area > max_area: max_area = area triangle_points = points # Проверка максимальной площади и отклонения if max_area == 0 or max_deviation < 0: return None # Восстановленные координаты вершин треугольника triangle_points_restored = restore_coordinates(triangle_points, width, height) return triangle_points_restored def find_triangle_points(image): # Размеры изображения height, width = image.shape # Временный массив для хранения координат вершин треугольника temp_points = [] # Проход по каждому пикселю изображения for y in range(height): for x in range(width): if image[y, x] > 0: temp_points.append((x, y)) # Проверка количества найденных пикселей if len(temp_points) < 3: return None # Восстановление координат вершин треугольникя # … def calculate_triangle_area(points): """""" def restore_coordinates(points, image_width, image_height): """""" # Пример использования triangle_points = restore_triangle(image) print(triangle_points) Ты не дописал алгоритм, допиши
ca3f8e67397c02fa57eb4ab8b1171707
{ "intermediate": 0.2932800054550171, "beginner": 0.5845590829849243, "expert": 0.1221608892083168 }
31,099
Можно ли следующий код как-то упростить? std::vector<Eigen::SparseMatrix<size_t>> matrices_blocks{}; if (sou_matrix_block.size() != 0) { if (sou_matrix_block.rows() < max_rows) { sou_matrix_block = addExtraRowToBlock(true, sou_matrix_block, 0); } matrices_blocks.push_back(sou_matrix_block); } if (rec_matrix_block.size() != 0) { if (rec_matrix_block.rows() < max_rows) { rec_matrix_block = addExtraRowToBlock(true, rec_matrix_block, 0); } matrices_blocks.push_back(rec_matrix_block); } if (cdp_matrix_block.size() != 0) { if (cdp_matrix_block.rows() < max_rows) { cdp_matrix_block = addExtraRowToBlock(true, cdp_matrix_block, 0); } matrices_blocks.push_back(cdp_matrix_block); } if (off_matrix_block.size() != 0) { if (off_matrix_block.rows() < max_rows) { off_matrix_block = addExtraRowToBlock(true, off_matrix_block, 0); } matrices_blocks.push_back(off_matrix_block); }
cf562a3e1708aa21fdd80175440046b3
{ "intermediate": 0.3500865399837494, "beginner": 0.3705189824104309, "expert": 0.2793944776058197 }
31,100
Как можно упростить следующий код? std::vector<size_t> sou_ordered_nums = readInput(“sou.txt”); Eigen::SparseMatrix<size_t> sou_matrix_block = createSparseBlock(sou_ordered_nums); sou_matrix_block = addExtraRowToBlock(true, sou_matrix_block, 1); std::vector<size_t> rec_ordered_nums = readInput(“rec.txt”); Eigen::SparseMatrix<size_t> rec_matrix_block = createSparseBlock(rec_ordered_nums); rec_matrix_block = addExtraRowToBlock(false, rec_matrix_block); std::vector<size_t> cdp_ordered_nums = readInput(“cdpo.txt”); Eigen::SparseMatrix<size_t> cdp_matrix_block = createSparseBlock(cdp_ordered_nums); cdp_matrix_block = addExtraRowToBlock(false, cdp_matrix_block); std::vector<size_t> off_ordered_nums = readInput(“offo.txt”); Eigen::SparseMatrix<size_t> off_matrix_block = createSparseBlock(off_ordered_nums); off_matrix_block = addExtraRowToBlock(false, off_matrix_block);
5f968c8407d867708c3dc0fac52d2ee5
{ "intermediate": 0.3274032175540924, "beginner": 0.3214687407016754, "expert": 0.3511280417442322 }
31,101
Fix the following MatLab code. Figure 4 doesn't display anything, and this line of code is wrong: histogram(y_positions(numSteps_histogram(i), :)); Code: % Define parameters width = 5; % width of the pipe in mm a = 0.01; % lattice constant in mm tau = 1; % time step pw = 0; % probability of waiting at each time step numSteps = 10; % number of time steps to simulate numWalks = 1000; % number of walks for histograms % Calculate the number of lattice points in the width dimension numPoints = width / a; % Initialize arrays to store x and y positions x_positions = zeros(numSteps, numWalks); y_positions = zeros(numSteps, numWalks); % Initialize the step counts in each direction stepsRight = zeros(numSteps, 1); stepsUp = zeros(numSteps, 1); % Simulate the random walk for each walk for w = 1:numWalks % Initialize the random walker’s position x = 0; y = floor(numPoints / 2); % starting in the middle of the pipe % Simulate the random walk for i = 1:numSteps % Record the position at each step x_positions(i, w) = x; y_positions(i, w) = y; % Check if the random walker makes a step or waits if rand > pw % Randomly choose the direction of the step direction = randi(4); % Make the step and update the position if direction == 1 % right x = x + a; stepsRight(i) = stepsRight(i) + 1; elseif direction == 2 % up y = y + 1; stepsUp(i) = stepsUp(i) + 1; elseif direction == 3 % left x = x - a; stepsRight(i) = stepsRight(i) - 1; else % down y = y - 1; stepsUp(i) = stepsUp(i) - 1; end end % Reflective boundary conditions in the y-direction if y < 0 y = -y; elseif y >= numPoints y = 2 * numPoints - y - 1; end end end % Visualize the random walk trajectories figure; plot(x_positions, y_positions); xlabel('x-position (mm)'); ylabel('y-position (mm)'); title('Random Walk Trajectories'); % Calculate the mean squared displacement in the x-direction msd_x = mean(x_positions.^2, 2); steps = (1:numSteps)'; figure; plot(steps, msd_x); xlabel('Number of steps'); ylabel('Mean Squared Displacement in x-direction (mm^2)'); title('Mean Squared Displacement in x-direction'); % Calculate the mean squared displacement in the y-direction msd_y = mean(y_positions.^2, 2); figure; plot(steps, msd_y); xlabel('Number of steps'); ylabel('Mean Squared Displacement in y-direction (mm^2)'); title('Mean Squared Displacement in y-direction'); % Plot histograms of x-positions for different numbers of steps numSteps_histogram = [100, 1000, 10000, 100000]; figure; for i = 1:length(numSteps_histogram) subplot(2, 3, i); histogram(x_positions(numSteps_histogram(i), :)); xlabel('x-position (mm)'); ylabel('Frequency'); title(['Histogram after ', num2str(numSteps_histogram(i)), ' steps']); end % Plot histograms of y-positions for different numbers of steps figure; for i = 1:length(numSteps_histogram) subplot(2, 3, i); histogram(y_positions(numSteps_histogram(i), :)); xlabel('y-position (mm)'); ylabel('Frequency'); title(['Histogram after ', num2str(numSteps_histogram(i)), ' steps']); end % Calculate the required time per step (tau) for a diffusion constant of 10^7 cm^2/s required_D = 1e7; % cm^2/s required_tau = a^2 / required_D; % s fprintf('The average time per step (tau) should be %.4f seconds to obtain a diffusion constant of 10^7 cm^2/s.\n', required_tau); % Calculate the diffusion constant in the x-direction by taking the slope of the mean squared displacement as a function of time coefficients_x = polyfit(tau*steps, msd_x, 1); D_x = coefficients_x(1) / 2; fprintf('The diffusion constant (D) in the x-direction is %.4f mm^2/tau.\n', D_x);
71b3a6ecdf17ff60e4e86e9763f9f85c
{ "intermediate": 0.3247919976711273, "beginner": 0.37954896688461304, "expert": 0.29565906524658203 }
31,102
I have date stored in variable Date (2023-11-16) but I want to display Oct using that Date in workflow email task how can use the syntax to display Oct from that Date
43591d1ccbf54fae261ae4b6803a9b40
{ "intermediate": 0.39721742272377014, "beginner": 0.4863288104534149, "expert": 0.11645372956991196 }
31,103
I have a column of strings consisting of three parts separated by ' '. How can I retrieve a column of only second parts?
b588d6d598134a2a4b2ccb6555394dd5
{ "intermediate": 0.4503202736377716, "beginner": 0.14630679786205292, "expert": 0.40337297320365906 }
31,104
python script graph api http post request https://graph.microsoft.com/v1.0/chats/{chatId}/messages sent adaptive card to user
1f71c91fc5d6524702e658aadc4e7b58
{ "intermediate": 0.4344783425331116, "beginner": 0.22563418745994568, "expert": 0.33988744020462036 }
31,105
fix my python code: def sort_lo_hi(list): sorted_list = [] for i in unsorted_list: if i == 0: if unsorted_list[i] > unsorted_list[i+1]: sorted_list.append(unsorted_list[i+1]) else: if unsorted_list[i-1] > unsorted_list[i]: sorted_list.append(unsorted_list[i]) #return sorted_list print(sorted_list)
d108aab7d97b1229e196886ca63e476d
{ "intermediate": 0.41943153738975525, "beginner": 0.37387847900390625, "expert": 0.2066899836063385 }
31,106
namespace Logic.Service.Services { public class ProductService : IProductService { private readonly IProductRepository _productRepository; public ProductService(IProductRepository productRepository) { _productRepository = productRepository; } public async Task<GeneralResponseModel<ProductDto>> AddProductByAdmin(ProductViewModel ProductViewModel) { var response = new GeneralResponseModel<ProductDto>(); //check if this category is created or not if (ProductViewModel == null) { response.isSuccess = false; response.status = 400; response.message = "محصولی برای ذخیره شدن وجود ندارد "; } else if (ProductViewModel.ID.HasValue) { response.isSuccess = false; response.status = 400; response.message = "این محصول ذخیره شده است "; } else { var productDto = new ProductDto() { Title = ProductViewModel.Title, Amount = ProductViewModel.Amount, Price = ProductViewModel.Price, CategoryID = ProductViewModel.CategoryID, ImageURL = ProductViewModel.ImageURL, Description = ProductViewModel.Description, IsActive = ProductViewModel.IsActive, }; var test = await _productRepository.UpdateAsync(productDto); if (test == null) { response.isSuccess = false; response.status = 400; response.message = "به بک اطلاع دهید "; } response.Data = productDto; } return response; } write test
ada7b948c333ec8516d13ec588126281
{ "intermediate": 0.3954850435256958, "beginner": 0.5179498791694641, "expert": 0.0865650624036789 }
31,107
Use python. Here is the assignment. Please write a program which asks for the user's name and address. The program should also print out the given information, as follows: Sample output Given name: Steve Family name: Sanders Street address: 91 Station Road City and postal code: London EC05 6AW Steve Sanders 91 Station Road London EC05 6AW
2821f017689fae3bf2fa13000a51c570
{ "intermediate": 0.538569450378418, "beginner": 0.12543214857578278, "expert": 0.33599838614463806 }
31,108
While cardinal(PReloc)-cardinal(PRelocs)<RelocsSize do //Так как вся таблица перемещений заполнена целиком, то признак конца таблицы – выход за // пределы отведенной для нее области памяти begin ModCount:=(PReloc.SizeOfBlock-Sizeof(PReloc^)) div 2; P:=pointer(cardinal(PReloc)+sizeof(PReloc^)); for i:=0 to ModCount-1 do begin if P^ and $f000<>0 //Если тип ссылки - не IMAGE_REL_BASED_ABSOLUTE(=0) then Inc(pdword(cardinal(ImageBase)+PReloc.VirtualAddress+(P^ and $0fff))^, ImageBaseDelta); //Исправляем ссылку Inc(P); end; PReloc:=pointer(P); end; напиши этот код на C
eff0e96163b7c164d57b769d8b9ebc82
{ "intermediate": 0.37938427925109863, "beginner": 0.34466034173965454, "expert": 0.27595534920692444 }
31,109
.gitlab-ci.yml create json dictionary
892f3fe4ff431461190094fda3859aa4
{ "intermediate": 0.466773122549057, "beginner": 0.21332049369812012, "expert": 0.31990644335746765 }
31,110
elif command == "Z": print("Buzzer is beeping") if buzzer_on() == True: buzzer_off() else: buzzer_on()
7dda93ae7bdda0e7ab4fdf36cb709387
{ "intermediate": 0.2602982521057129, "beginner": 0.5658983588218689, "expert": 0.1738034188747406 }
31,111
.blue{ color: blue; } main{ position: relative; color: blue; /* /background-color: aqua; */ background: aqua; } .blue{ height: 100px; width: 100px; margin: 20px; left: 10%; bottom: 10%; color: blue; } html^ цdiv не раскрашиваются: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Adaptive Web-site</title> </head> <body> <!-- <main> <h1>@media - Медиа запросы</h1> <div class="blue item1"></div> <div class="blue item2"></div> </main> --> <main> <div class="blue"></div> <div class="blue"></div> </main> </body> </body> </html> почему?
89f4c03ca0c7be299b44abfe25008a09
{ "intermediate": 0.33026954531669617, "beginner": 0.3178260326385498, "expert": 0.35190436244010925 }
31,112
sequl scripydivide by zero
8e0ded426e5ff6db609dd0abb835fdb9
{ "intermediate": 0.25347286462783813, "beginner": 0.4973098635673523, "expert": 0.24921730160713196 }
31,113
In Python, create a code that displays a rotating three-dimensional heart
26eb674a3289e871144ef4f7461886d4
{ "intermediate": 0.34913915395736694, "beginner": 0.21870015561580658, "expert": 0.43216070532798767 }
31,114
hi. please write SQL code in Postgres to extract the email domain from an email address
ebe7935d0a3408c4aed9a513e0235d2b
{ "intermediate": 0.6473297476768494, "beginner": 0.14432863891124725, "expert": 0.2083415538072586 }
31,115
#scriptA.py: import time from multiprocessing import shared_memory, Process def main(): # Cria uma memória compartilhada para o inteiro e lê o valor inicial dele int_shm = shared_memory.SharedMemory(name='numeroA') numeroA = shared_memory.RawValue('i', 0) numeroA = shared_memory.RawValue('i', numeroA.value) # Cria uma memória compartilhada para a string e lê o valor inicial dela str_shm = shared_memory.SharedMemory(name='nomeA') nomeA = shared_memory.RawArray('c', b'nome original') nomeA = shared_memory.RawArray('c', nomeA) # Define a função que será executada pelo processo filho def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) # Cria o processo filho processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: # Modifica os valores das variáveis compartilhadas numeroA.value += 1 nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5) [WinError 2] O sistema não conseguiu localizar o ficheiro especificado: 'numeroA' File "C:\meu\scripta.py", line 100, in main int_shm = shared_memory.SharedMemory(name='numeroA') File "C:\meu\scripta.py", line 136, in <module> main() FileNotFoundError: [WinError 2] O sistema não conseguiu localizar o ficheiro especificado: 'numeroA' # Libera a memória compartilhada int_shm.close() str_shm.close() if __name__ == "__main__": main()
c43f16142c26c2e2f62d5f5630abed42
{ "intermediate": 0.45929938554763794, "beginner": 0.36178058385849, "expert": 0.1789199858903885 }
31,116
Design a website for me with the following features and to your liking.
d4bcbeb8e7d017e76c4365044f98758c
{ "intermediate": 0.3628210425376892, "beginner": 0.26282843947410583, "expert": 0.3743504583835602 }
31,117
how to write line by different element width like this <Line X1="0" Y1="0" X2="{Binding ElementName=mainContentGrid, Path=ActualWidth}" Y2="0" StrokeThickness="2.5">
1a80cfe7441a8f56b39c0b388eae956b
{ "intermediate": 0.4845263659954071, "beginner": 0.20796896517276764, "expert": 0.30750465393066406 }
31,118
write in text of textblock actualwidth of different element wpf xaml
2cc26bdf93478f2f1a5b45a51bf73071
{ "intermediate": 0.3955153524875641, "beginner": 0.2764495015144348, "expert": 0.3280351459980011 }