prompt
stringlengths
22
383k
prompt_id
stringlengths
32
32
index
int64
0
500
annotator
stringclasses
11 values
timestamp
timestamp[s]
rating
stringclasses
2 values
tags
sequence
1 / 1 Act as a Python programmer. The following code uses the standard algorithm to add or subtract two numbers. However, there are no commas to separate the place values. Please add the place values to the numbers printed out. import sys def add_or_subtract(a, b, operation): result = [] carry = 0 borrow = 0 a = str(a) b = str(b) n = max(len(a), len(b)) a = a.zfill(n) b = b.zfill(n) if operation == 'add': for i in range(n-1, -1, -1): d1 = int(a[i]) d2 = int(b[i]) d = d1 + d2 + carry if d >= 10: carry = 1 d -= 10 else: carry = 0 result.append(str(d)) if carry: result.append(str(carry)) elif operation == 'subtract': for i in range(n-1, -1, -1): d1 = int(a[i]) d2 = int(b[i]) d = d1 - d2 - borrow if d < 0: borrow = 1 d += 10 else: borrow = 0 result.append(str(d)) else: raise ValueError( "Invalid operation. Only 'add' and 'subtract' are allowed.") result.reverse() return int("".join(result)) a = int(sys.argv[1]) b = int(sys.argv[2]) operation = sys.argv[3] print(" " + str(a)) if operation == 'add': print("+" + str(b)) elif operation == 'subtract': print("-" + str(b)) print("-" * max(len(str(a)), len(str(b)))) print(" " + str(add_or_subtract(a, b, operation)))
46dbdc1266ccb1d3bb5bc1822bd63c42
36
dianewan
2023-05-23T23:48:54
good
[ "code", "system" ]
amend this script to include comments fetch('/data/23_Releases.json') .then(response => response.json()) .then(data => { const currentDate = new Date().toISOString().slice(0, 10).replace(/-/g, "."); const matchingReleases = data.filter(release => release["Release Date"] === currentDate); const nonMatchingReleases = data.filter(release => release["Release Date"] !== currentDate); const matchingDiv = document.getElementById("todaysReleases"); const nonMatchingDiv = document.getElementById("allAlbums"); matchingReleases.sort((a, b) => a["Artist Name"].localeCompare(b["Artist Name"])); for (const release of matchingReleases) { const releaseDiv = document.createElement("div"); releaseDiv.classList.add("release"); releaseDiv.innerHTML = ` <img src="${release["Cover Art"]}" alt="${release["Album Name"]} Album Art"> <h3 class="albumName">${release["Album Name"]}</h3> <p class="albumType-${release["Album Type"]}">${release["Album Type"]}</p> <h4 class="artistName">${release["Artist Name"]}</h4>`; matchingDiv.appendChild(releaseDiv); } nonMatchingReleases.sort((a, b) => { const aDate = new Date(a["Release Date"]); const bDate = new Date(b["Release Date"]); if (bDate.getTime() !== aDate.getTime()) { return bDate.getTime() - aDate.getTime(); } else { return a["Artist Name"].localeCompare(b["Artist Name"]); } }); for (const release of nonMatchingReleases) { const releaseDiv = document.createElement("div"); releaseDiv.classList.add("release"); releaseDiv.innerHTML = ` <img src="${release["Cover Art"]}" alt="${release["Album Name"]} Album Art"> <h3 class="albumName">${release["Album Name"]}</h3> <p class="albumType-${release["Album Type"]}">${release["Album Type"]}</p> <h4 class="artistName">${release["Artist Name"]}</h4> <p class="releaseDate">${release["Release Date"]}</p>`; nonMatchingDiv.appendChild(releaseDiv); } }) .catch(error => console.log(error));
a8bd577878d4256c8810ea930c9a9cd6
37
dianewan
2023-05-23T23:49:10
good
[ "code" ]
what is this function doing? bool vgicd_emul_handler(struct emul_access *acc) { struct vgic_reg_handler_info *handler_info = NULL; switch (GICD_REG_MASK(acc-&gt;addr) &gt;&gt; 7) { case GICD_REG_GROUP(CTLR): handler_info = &amp;vgicd_misc_info; break; case GICD_REG_GROUP(ISENABLER): handler_info = &amp;isenabler_info; break; case GICD_REG_GROUP(ISPENDR): handler_info = &amp;ispendr_info; break; case GICD_REG_GROUP(ISACTIVER): handler_info = &amp;isactiver_info; break; case GICD_REG_GROUP(ICENABLER): handler_info = &amp;icenabler_info; break; case GICD_REG_GROUP(ICPENDR): handler_info = &amp;icpendr_info; break; case GICD_REG_GROUP(ICACTIVER): handler_info = &amp;iactiver_info; break; case GICD_REG_GROUP(ICFGR): handler_info = &amp;icfgr_info; break; case GICD_REG_GROUP(SGIR): handler_info = &amp;sgir_info; break; default: { size_t acc_off = GICD_REG_MASK(acc-&gt;addr); if (GICD_IS_REG(IPRIORITYR, acc_off)) { handler_info = &amp;ipriorityr_info; } else if (GICD_IS_REG(ITARGETSR, acc_off)) { handler_info = &amp;itargetr_info; } else if (GICD_IS_REG(IROUTER, acc_off)) { handler_info = &amp;irouter_info; } else if (GICD_IS_REG(ID, acc_off)) { handler_info = &amp;vgicd_pidr_info; } else { handler_info = &amp;razwi_info; } } } if (vgic_check_reg_alignment(acc, handler_info)) { spin_lock(&amp;cpu()-&gt;vcpu-&gt;vm-&gt;arch.vgicd.lock); handler_info-&gt;reg_access(acc, handler_info, false, cpu()-&gt;vcpu-&gt;id); spin_unlock(&amp;cpu()-&gt;vcpu-&gt;vm-&gt;arch.vgicd.lock); return true; } else { return false; } }
1b3f015ce895f8e176145c8aaba07850
38
dianewan
2023-05-23T23:50:31
good
[ "code" ]
Can you grade the solidity code on the following parameters: General Coding Practices, Functional Correctness, Security, Gas Optimisations, and Code Readability. Don't check for overflows. 1 is the lowest no. of points for a parameter and 5 is the highest no. of points for a parameter. The guidelines for each parameter are below. Please give detailed reasoning on the score for each parameter. Functional Errors - Checking the return value of call to confirm success of transfer while sending ether in withdrawStream = 1 point - Add missing require in createStream to check startTime < stopTime = 1 point - Correcting implementation of balanceOf function = 1 point - Fixing withdrawFromStream function, every withdrawl should save a timestamp so that user balance can later be calculated based on that timestamp = 1 point - Rest any errors solved = 1 point Feature Addition - Handling incorrect streamId = 2 points - Correct functioning of cancelStream i.e., sending back correct amounts to receiver and sender = 3 points Security Issues - Correct function visibility = 2 points - Checks to make sure msg.value is equal to deposit in createStream function = 1 point - No re-entrancy bug = 2 points Gas Optimisations - Variable Packing, streamIdCounter and owner can be packed together = 1 point - Converting public functions to external functions wherever necessary = 1 point - Storage access issues, variable can be stored in memory first to save gas = 3 points Tests - Coverage of added functionalities = 3 points - Tests for security and functional issues found and fixed = 2 points Code Readability - Use of modifiers wherever necessary = 2 points - Emitting events wherever necessary = 5 points // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "hardhat/console.sol"; contract Streaming { address public owner; mapping(uint256 => Stream) private streams; uint64 public streamIdCounter; modifier onlyRecipient(uint256 streamId) { require (msg.sender == streams[streamId].recipient, "caller is not the recipient of the stream"); _; } struct Stream { address recipient; address sender; uint256 deposit; uint256 startTime; uint256 stopTime; uint256 rate; uint256 balance; } event CreateStream( uint256 indexed streamId, address indexed sender, address indexed recipient, uint256 deposit, uint256 startTime, uint256 stopTime ); event WithdrawFromStream(uint256 indexed streamId, address indexed recipient); event CancelStream(uint256 indexed streamId, address sender, address recipient, uint256 deposit, uint256 amount); // .withArgs(1, sender.address, recipient1.address, deposit, 0); constructor() { owner = msg.sender; } function createStream( address recipient, uint256 deposit, uint256 startTime, uint256 stopTime ) public returns (uint256 streamId) { require(recipient != address(0x00), "Stream to the zero address"); require(recipient != address(this), "Stream to the contract itself"); require(recipient != msg.sender, "Stream to the caller"); require(deposit > 0, "Deposit is equal to zero"); require(startTime >= block.timestamp, "Start time before block timestamp"); uint256 duration = stopTime - startTime; require(deposit >= duration, "Deposit smaller than duration"); require(deposit % duration == 0, "Deposit is not a multiple of time delta"); streamIdCounter += 1; uint256 currentStreamId = streamIdCounter; // Rate Per second uint256 rate = deposit / duration; streams[currentStreamId] = Stream({ balance: deposit, deposit: deposit, rate: rate, recipient: recipient, sender: msg.sender, startTime: startTime, stopTime: stopTime }); emit CreateStream(currentStreamId, msg.sender, recipient, deposit, startTime, stopTime); return currentStreamId; } function balanceOf( uint256 streamId, address who) private view returns (uint256 balance) { Stream memory stream = streams[streamId]; require(stream.rate > 0, "stream does not exist"); uint256 elapsedTime = elapsedTimeFor(streamId); uint256 due = elapsedTime * stream.rate; if (who == stream.recipient) { return due; } else if (who == stream.sender) { return stream.balance - due; } else { return 0; } } function elapsedTimeFor(uint256 streamId) private view returns (uint256 delta) { Stream memory stream = streams[streamId]; // Before the start of the stream if (block.timestamp <= stream.startTime) return 0; // During the stream if (block.timestamp < stream.stopTime) return block.timestamp - stream.startTime; // After the end of the stream return stream.stopTime - stream.startTime; } function withdrawFromStream(uint256 streamId) public onlyRecipient(streamId) { uint256 balance = balanceOf(streamId, streams[streamId].recipient); require(balance > 0, "Available balance is 0"); payable(streams[streamId].recipient).call{value: balance}(""); streams[streamId].balance = streams[streamId].deposit - balance; emit WithdrawFromStream(streamId, streams[streamId].recipient); } function getStream(uint256 streamId) external view returns ( address sender, address recipient, uint256 deposit, uint256 startTime, uint256 stopTime, uint256 rate ) { sender = streams[streamId].sender; recipient = streams[streamId].recipient; deposit = streams[streamId].deposit; startTime = streams[streamId].startTime; stopTime = streams[streamId].stopTime; rate = streams[streamId].rate; } function cancelStream(uint streamId) public payable returns (uint256 recipientAmountEarned) { Stream memory stream = streams[streamId]; require(stream.rate > 0, "stream does not exist"); uint recipientAmountEarned = balanceOf(streamId, stream.recipient); uint senderAmountReturned = balanceOf(streamId, stream.sender); payable(streams[streamId].recipient).call{value: recipientAmountEarned}(""); payable(stream.sender).call{value: senderAmountReturned}(""); emit WithdrawFromStream(streamId, streams[streamId].recipient); emit CancelStream(streamId, streams[streamId].sender, streams[streamId].recipient, streams[streamId].deposit, recipientAmountEarned); return recipientAmountEarned; } }
539de93b667559409af180895e60566e
39
dianewan
2023-05-23T23:52:25
bad
[]
can you make this code more compact from creditcard import CreditCard from debitcard import DebitCard from coin_machine import IKEAMyntAtare2000 from ui_info import UIPayment, UIPayment, TicketInfo from bitcoin import Bitcoin class Payment: # Initiate Payment def __init__(self, price, info: TicketInfo): self.price = price self.info = info self.handle_payment(price) # The entire payment process with all paymant methods def handle_payment(self, price): if self.info.payment == UIPayment.CreditCard: price += 0.50 c = CreditCard() c.connect() ccid: int = c.begin_transaction(round(price, 3)) c.end_transaction(ccid) c.disconnect() elif self.info.payment == UIPayment.DebitCard: d = DebitCard() d.connect() dcid: int = d.begin_transaction(round(price, 3)) d.end_transaction(dcid) d.disconnect() elif self.info.payment == UIPayment.Cash: coin = IKEAMyntAtare2000() coin.starta() coin.betala(int(round(price * 100))) coin.stoppa() elif self.info.payment == UIPayment.Bitcoin: price *= 0.000057 btc = Bitcoin() btc.connect() btcid: int = btc.begin_transaction(price) btc.display_qr(btc.generate_qr()) btc.end_transaction(btcid) btc.disconnect()
5baf572dfe030cf7e7dd783c20c0448a
4
DaehanKim
2023-05-29T06:31:21
good
[ "code" ]
can you make this code more compact from creditcard import CreditCard from debitcard import DebitCard from coin_machine import IKEAMyntAtare2000 from ui_info import UIPayment, UIPayment, TicketInfo from bitcoin import Bitcoin class Payment: # Initiate Payment def __init__(self, price, info: TicketInfo): self.price = price self.info = info self.handle_payment(price) # The entire payment process with all paymant methods def handle_payment(self, price): if self.info.payment == UIPayment.CreditCard: price += 0.50 c = CreditCard() c.connect() ccid: int = c.begin_transaction(round(price, 3)) c.end_transaction(ccid) c.disconnect() elif self.info.payment == UIPayment.DebitCard: d = DebitCard() d.connect() dcid: int = d.begin_transaction(round(price, 3)) d.end_transaction(dcid) d.disconnect() elif self.info.payment == UIPayment.Cash: coin = IKEAMyntAtare2000() coin.starta() coin.betala(int(round(price * 100))) coin.stoppa() elif self.info.payment == UIPayment.Bitcoin: price *= 0.000057 btc = Bitcoin() btc.connect() btcid: int = btc.begin_transaction(price) btc.display_qr(btc.generate_qr()) btc.end_transaction(btcid) btc.disconnect()
5baf572dfe030cf7e7dd783c20c0448a
4
dianewan
2023-05-23T23:18:48
good
[ "code" ]
can you make this code more compact from creditcard import CreditCard from debitcard import DebitCard from coin_machine import IKEAMyntAtare2000 from ui_info import UIPayment, UIPayment, TicketInfo from bitcoin import Bitcoin class Payment: # Initiate Payment def __init__(self, price, info: TicketInfo): self.price = price self.info = info self.handle_payment(price) # The entire payment process with all paymant methods def handle_payment(self, price): if self.info.payment == UIPayment.CreditCard: price += 0.50 c = CreditCard() c.connect() ccid: int = c.begin_transaction(round(price, 3)) c.end_transaction(ccid) c.disconnect() elif self.info.payment == UIPayment.DebitCard: d = DebitCard() d.connect() dcid: int = d.begin_transaction(round(price, 3)) d.end_transaction(dcid) d.disconnect() elif self.info.payment == UIPayment.Cash: coin = IKEAMyntAtare2000() coin.starta() coin.betala(int(round(price * 100))) coin.stoppa() elif self.info.payment == UIPayment.Bitcoin: price *= 0.000057 btc = Bitcoin() btc.connect() btcid: int = btc.begin_transaction(price) btc.display_qr(btc.generate_qr()) btc.end_transaction(btcid) btc.disconnect()
5baf572dfe030cf7e7dd783c20c0448a
4
nazneen
2023-06-01T00:26:16
good
[]
<html> <head> <style> body { background-color: black; height: 100vh; } h1 { color: white; font-family: 'Roboto', sans-serif; font-weight: bold; font-size: 75px; } h2 { color: white; font-family: 'Roboto', sans-serif; font-weight: bold; font-size: 50px; } </style> </head> <body> <br> <br> <h1>HALFIN LABS</h1> <br> <h2>Get your Nostr username verified</h2> <br> <div width="50%"> <lightning-widget name="HALFIN LABS" accent="#000000" to="[email protected]" image="https://pbs.twimg.com/profile_images/1484755771187503106/Ne4dhktC_400x400.jpg" amounts="10000, 20000, 50000," labels="🐢 10k, 🐇 20k, ⚡️50k," /> </div> <script src="https://embed.twentyuno.net/js/app.js"></script> </body> </html> Copyplagiarism checker- Bulgarian- Chinese (simplified)- Czech- Danish- Dutch- English (American)- English (British)- Estonian- Finnish- French- German- Greek- Hungarian- Indonesian- Italian- Japanese- Latvian- Lithuanian- Polish- Portuguese - Portuguese (Brazilian)- Romanian- Russian- Slovak- Slovenian- Spanish- Swedish- Turkish- Ukrainian
d9be2e79cde98400b221d3a8e48c7236
40
dianewan
2023-05-23T23:52:33
bad
[]
can you give me a netsuite suitescript 2.0 script for a suitelet for sales orders which has multiple filters including: filter by customer group; filter by customer; filter by date (start and end date) filter by saved search
56815c791d7c1ff6b33d24e067d166b5
41
dianewan
2023-05-23T23:53:14
good
[ "code" ]
這是你之前給我的程式碼 <label for="start-date">Start date:</label> <input type="date" id="start-date" name="start-date"> <br> <label for="end-date">End date:</label> <input type="date" id="end-date" name="end-date"> $(function() { var $startDate = $("#start-date"); var $endDate = $("#end-date"); $startDate.on("change", function() { var startDate = new Date($startDate.val()); var endDate = new Date($endDate.val()); if (endDate && startDate > endDate) { $endDate.val(""); } }); $endDate.on("change", function() { var startDate = new Date($startDate.val()); var endDate = new Date($endDate.val()); if (startDate && startDate > endDate) { $startDate.val(""); } }); });
7fb40a75e25b2fb4cd6337c3c447cfca
42
dianewan
2023-05-23T23:53:20
bad
[]
Act like a document/text loader until you load and remember content of the next text/s or document/s. There might be multiple files, each file is marked by name in the format ### DOCUMENT NAME. I will send you them by chunks. Each chunk start will be noted as [START CHUNK x/TOTAL], and end of this chunk will be noted as [END CHUNK x/TOTAL], where x is number of current chunk and TOTAL is number of all chunks I will send you. I will send you multiple messages with chunks, for each message just reply OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text! Let's begin: [START CHUNK 1/3] ### file.txt ### When you get your first writing assignment, it’s normal to feel confused or frustrated. You might think, “Why do I have to do this? I won’t ever use this kind of essay again!” Or, “Why are there so many rules? I won’t have to follow them in my future job.” To understand these assignments and what’s expected of you, it’s important to become familiar with the idea of a “rhetorical situation,” or “writing situation.” This chapter provides a foundation for understanding texts, speeches, and other assessments commonly assigned to students. It also attempts to explain how these types of assignments relate to IRL (in real life) situations. Reading assignments rhetorically is helpful because it not only better prepares you for completing an assignment, but also teaches you to how to think critically across a range of situations. For example, you’ll learn why an email to your boss should look different from one to a friend or family member. Or why it’s ok to use informal language when texting with friends, but not in a professional cover letter. By learning to read assignments with a rhetorical mindset, your writing will improve and become more flexible. This chapter covers five key terms associated with writing situations that students will face in college: exigency: the issue, problem, or debate a student is often expected to respond to purpose: what the student is expected to demonstrate with their artifact, in response to the exigence audience: whom the student is writing for genre: how the content is delivered is packed setting (including platform constraints): constrains related to where the artifact is being published or delivered (such as a social media platform or within a classroom) I. Exigency: What issue needs to be addressed? Simply put, the exigency of a rhetorical situation is the urgency, problem, or issue that a college assignment asks a student to respond to. The focus on “exigency” is often attributed to Lloyd Bitzer. When Bitzer drew attention to the importance of “exigence” and “context” in his famous article “The Rhetorical Situation,” he pointed out that certain aspects of the situation invite “the assistance of discourse.”[1] One of his examples is air pollution: “The pollution of our air is also a rhetorical exigence because its positive modification—reduction of pollution—strongly invites the assistance of discourse producing public awareness, indignation, and action of the right kind.”[2] Within a given context, certain things will provoke a call to action from discourse. Some college assignments ask a student to brainstorm, research, and clearly explain their own exigency and then respond to it. Other assignment prompts will provide a student with a pre-defined exigency and ask them to respond to or solve the problem using the skills they’ve been practicing in the course. When analyzing texts or creating their own, students should be able to specify the particular urgency their discourse is responding to. It’s precisely this urgency that the text aims to take up and respond to, at the right time and place, kairotically. In thesis-driven academic essays, the exigency is usually clarified at the beginning, as part of the introduction. The separate chapter on “Exigence” offers more details about this important rhetorical term. Exigencies and Introductions In academic essays, students should consider the following questions when drafting an introduction that’s attuned to an exigency. Note that your response to these questions will vary depending on the course and writing assignment. What issue, problem, or threat is being addressed? Where is this issue located: in a text (appropriate for a literary analysis essay)? among a group of specialists? among journalists? II. Purpose: How will the exigency be addressed? One straightforward way to understand the purpose of a rhetorical situation is in terms of the exigency: the purpose of a essay, presentation, or other artifact is to effectively respond to a particular problem, issue, or dilemma. Traditionally, three broad categories have been proposed for thinking about a text’s purpose: inform: provide new knowledge for the audience persuade: convince an audience to accept a point of view or call to action entertain: provide an affective experience for the audience, by inspiring, humoring, or otherwise diverting their attention Here are some rhetorical situations where the exigency and purpose are clearly defined. The last situation is unique to college courses: Exigency 1: I need to write a letter to my landlord explaining why my rent is late so she won’t be upset. Purpose of the letter = persuade the landlord it’s ok to accept a late payment Exigency 2: I want to write a proposal for my work team to persuade them to change our schedule. Purpose of the proposal = persuade the team to get the schedule changed Exigency 3: I have to write a research paper for my environmental science instructor comparing solar to wind power. Purpose of the research paper = inform the audience about alternative forms of energy; Secondary purpose: persuade/demonstrate to the science instructor you’re learning the course content The difference between Exigency 1 and Exigency 3 above may initially cause some confusion. Exigency 1, the letter about the late rent payment, happens in the “real world.” It’s an everyday occurrence that naturally gives rise to a certain rhetorical situation and the purpose seems obvious. When moving to Exigency 3, the writing situation feels more complex because the student is learning about things supposedly “out there,” in the “real world,” but the purpose has multiple layers to it because it’s part of a college course. On the surface, the purpose of the research essay is obviously to inform the reader; but since the assignment is given within a science course, the student is also attempting to convince the instructor that they’re actually learning the course outcomes. The example of Exigency 3 shows how college assignments sometimes differ from other writing situations. As WAC Clearinghouse explains in its page, “What Should I Know about Rhetorical Situations?”, a contextual appreciation of a text’s purpose helps a student appreciate why they’re given certain assignments. In a typical writing course, for example, students are often asked to respond to situations with their own persuasive or creative ingenuity, even though they’re not expected to become experts on the topic. Until they enter high-level or graduate-level courses, students are mostly expected to simulate expertise. When this simulation happens, we can consider an assignment and the student’s response as having two distinct purposes. The first is obvious and usually stated; the second is often implied. Purpose 1: Obvious purpose. On the surface, the purpose of the assignment might be to solve a problem (anthropogenic climate change, the rise of misinformation, etc.) and persuade an academic audience their solution is legitimate, perhaps by synthesizing research. Depending on the topic and assignment criteria, a student might pretend to address a specialized audience and thereby simulate a position of authority (a type of ethos), even if they haven’t yet earned the credentials. Purpose 2: Hidden purpose. When simulating expertise, instructors and students should also take into account the actual context of the writing assignment prompt: it’s given to the student as part of a college writing course. The outcomes for that course shape the kinds of assignments an instructor chooses, as well as how they’re assessed. The hidden or implied purpose is therefore the course objectives the student is expected to demonstrate, including techniques such as developing a thesis, providing support, synthesizing research, and writing with sources. College writing assignments can [END CHUNK 1/3] Reply with OK: [CHUNK x/TOTAL], don't reply anything else, don't explain the text!
f478a05cee22a10602a2654e9392c6e8
43
dianewan
2023-05-23T23:54:01
bad
[]
Hey there I'm working in unreal engine 5 in c++ and I'm working with the * operator to understand pointers and accessing them. In this code I call in the tick component: ``` AActor* Owner = GetOwner(); //seek out this address and call its GANOL method //FString Name = (*Owner).GetActorNameOrLabel(); //as above, so below (aasb) FString Name = Owner->GetActorNameOrLabel(); FVector Location = Owner->GetActorLocation(); FString SLocation = Location.ToCompactString(); //thus: if pointer, use arrow, if struct/constructor, use dot method UE_LOG(LogTemp, Display, TEXT("Mover Owner: %s, and location: %s"), *Name,*SLocation); ``` The 'Name' variable is stored after the pointer stored in 'Owner' is accessed with the -> operator. Thus, the pointer accesses the memory containing the Actors Name, which I presume is stored as a string. Why do we use the * operator like '*Name' in the UE_LOG function, if the 'Name' variable presumably contains a string and is not a pointer. Or, am I wrong in my understanding somewhere?
2fa67254b90c2c3249d822c22fb262b8
44
dianewan
2023-05-23T23:54:16
good
[ "code" ]
Provide complete and working foolproof implementation for converting SQL queries to MongoDB queries in Java that handle all the cases SELECT, FROM, WHERE, AND, OR, IN, GROUP BY, HAVING, LIKE, NOT, JOIN, COUNT, AS
8e45dc78d7554f7a131822dc1c7b419c
45
dianewan
2023-05-23T23:54:25
good
[ "code" ]
hey, i got this project i'm working on. Let me feed you some information so we can proceed with the chat. Please, learn this content, tone of voice, style of writing and help me as if you were a expert in business intelligence creating a step-by-step guide on how to develop a digital agency in 2023 from scratch. Here's the overview and extra informations about the project: "2k37 Beta" is a business model and planning project for my company, "2k37", which is a digital agency focused on marketing, branding, hyperautomation for marketing via AI/ML tools, online education, social media content ideation, creation, development and management. Also, the intention is to design, develop and apply to new clients a full business intelligence solution, from planning and ideation to escalation and revenue improvement. The agency is currently a 1-person business and this project for business modelling and planning is intended to be applied so that the agency can build a solid structure to then pursue escalation through teams management, educational empowerment and data driven methods. The "2k37" Ecosystem is purposed to solve a concept question: what life will be like in 2k37? As nobody knows, as we can only imagine and predict, how about taking action by becoming a part of that future? The "2k37" agency is a forward thinking, science &amp; data driven creative hub experimenting w/ AI, ML &amp; Prompt Engineering as tools for music, visual &amp; digital arts, new media, social media content creation, 3D modelling, printing &amp; fashion design, digital education, microlearning, project management, events production, PR &amp; business connections aiming towards innovative &amp; sustainable products, services &amp; digital assets. The "2k37" has also an Art Manifesto to integrate the company vision and mission for the next 10 years, here's the draft: "Art is an integral part of life. Though often seen as an asset or a career, its importance goes far beyond mere wealth and success. Art has the power to capture emotions, express deep inner feelings, and bring meaningfulness to our lives. Art brings us comfort in difficult times, joy in happy moments, and clarity when we need guidance. It can provide contrast to the monotony of daily life and encourage us to see the world from a new perspective. Through art, we can explore different cultures, broaden our understanding of other civilizations, and create meaningful connections throughout the world. When we accept the importance of art in our lives, we can break away from the mundane and discover the beauty that lies within each unique experience. We become open to the emotions of others and can empathize when confronted with someone else's pain. Art can also strengthen our connection to our own experiences, allowing us to better understand what lies within us. In today’s fast-paced world, it is essential that we take time to appreciate art’s value and use it as a tool for growth and expression. Though art may appear to be merely a way to make money or a source of entertainment, it is much more than that. Art is a form of communication that can bring positive change and understanding to the world. It encourages us to engage with the feelings of others, to look within ourselves for truth, and to bring meaning to our lives." Furthermore, here's a text written by me as a speech to help you understand my style of writing, tone of voice and deeper understanding on "2k37's" concepts. "We are a creative lab that is dedicated to empowering people through innovation, creativity, sharing &amp; building communities. We believe in the power of technology, education and art to transform lives, and we are committed to making that a reality. Our aim is to be part on the making of a future where everyone has access to the tools they need to succeed, regardless of their background or circumstances. Rapid advances in technology are exponentially scaling and transforming industries, businesses, communities and creating disruption and volatility in corporate environments. As companies struggle to keep their teams tech-savvy, people are being written off like expired products. Companies also require greater assurance that strategic decisions are always guided by accurate and up-to-date information. These practices are not "just" abusive, they are violent and unsustainable. Based on the premise that "All knowledge is collective.", 2k37 Studio is taking on the challenge of researching, curating and translating a global library of content aimed at people, based on a business-level status to cover the latest emerging technologies, economics digital, individual businesses, free online education, Artificial Intelligence and its developments through Machine Learning, methodologies in ESG (Environmental, Social and Governance), visual and digital arts, culture and music in all its diverse creative fields aimed at the Community of Countries of Portuguese Language (CPLP) as a target for connection, distribution and engagement on our platform. Created on July 17, 1996, comprising Brazil, Angola, Cape Verde, Guinea-Bissau, Equatorial Guinea, Mozambique, Portugal, São Tomé and Príncipe and East Timor, the CPLP currently encompasses more than 300 million people across the world who have Portuguese as their primary and native language. Convenient micro-assets, its concepts &amp; distribution models are designed to help technical and non-technical students, professionals, corporations and government vectors stay informed on the latest technologies, tools and new business models to drive impact through innovation, sustainability, humanization, independence and accessibility. We are focused in developing a suite of services and products that help people to achieve their goals and to pursue their passions, including online courses, subscriptions plans, webinars, talks &amp; connections. Our goal is to convert environmental, educational and technology accessibility liabilities into financial sustainable assets through products &amp; services, repurposing digital distribution methods onto helping people to achieve financial independence through online 1-person business development and professional online educational models. I am proud to be a part of this community, and I am honored to be here today to share my story and my vision for the future. I believe that together, we can create a better world, where everyone has access to the tools they need to succeed and to reach their full potential. So, let's work together to make this a reality, and let's make creativity, innovation and empowerment a part of everyone's life. The next 15 years are sure to bring about some major human breakthroughs. From agriculture and energy to computers, smartphones, and artificial intelligence and machine learning, the possibilities are endless. But how will all of these compare to the impact of more universal forces, like gravity and other fundamentals of nature? It's almost impossible to predict the far-reaching effects of all of these innovations, but it’s evident that AI/ML will be revolutionising our lives in ways we might not have imagined before. With advances in natural language processing, visual recognition, autonomous vehicles and robotics, AI and ML have the potential to transform our communication and behaviour in ways that have never been seen before. At the same time, advancements in agriculture and energy have the potential to change our lives in fundamental ways. From new sources of fuel and food production, to new farming and water management practices, these fields have the ability to revolutionise the way we live. Additionally, the invention of computers and smartphones have already made our lives easier and more efficient in many ways. From being able to stay connected without being in the same room, to being able to manage multiple tasks simultaneously, these technologies have drastically transformed how humans communicate and interact with each other. Finally, one cannot overlook the impact of gravity and other forces of nature on our lives. From keeping our feet firmly planted on the ground to making sure that our bodies are kept in balance, gravity and other natural forces of balance will remain essential for our comfort and safety. While all of these breakthroughs have the potential to shape our lives in various capacities, it’s evident that AI/ML will be leading the way with regards to changing human communication and behaviour. With the potential to automate processes, increase efficiency and customization, AI/ML will be an essential part of our lives in the next 15 years. In conclusion, while many aspects of our lives can change drastically over the next 15 years with breakthroughs in agriculture, energy, computers, smartphones, gravity and other natural forces, it’s clear that AI/ML will be leading the way with regards to changing human communication and behaviour." The organisation is called "2k37" and is being built and branched into 3 brands that offer different kinds of services, products and goods, here's a summary: 2k37 Studio: a creative lab designed to incorporate creativity, arts, music and cultural editorial content and AI/ML innovations within the services, products and digital assets offered. at this point, the most important is to define the intern SOP's so that automation can be applied to the branch digital ecosystem to be prototyped as new products; 2k37 Academy: an educational online platform willing to offer a free-to-access micro-assets library in order to maintain the branch manifesto, "Every knowledge is collective" and through this strategy, achieve a higher-ticket strategy once the community has been built upon the deployment of the platform. 2k37 Solutions: the consultancy branch that aims to apply the studio and academy SOP's prototyped and adjusted to companies, organisations, government agencies and 1-person businesses.
6f4ae752e78733032c2e648d8960904d
46
dianewan
2023-05-23T23:56:53
bad
[]
Please write code for this homework that runs bare metal program on raspi 3 Lab 1: Hello World Introduction In Lab 1, you will practice bare metal programming by implementing a simple shell. You need to set up mini UART, and let your host and rpi3 can communicate through it. Goals of this lab Practice bare metal programming. Understand how to access rpi3’s peripherals. Set up mini UART. Set up mailbox. Basic Exercises Basic Exercise 1 - Basic Initialization - 20% When a program is loaded, it requires, All it’s data is presented at correct memory address. The program counter is set to correct memory address. The bss segment are initialized to 0. The stack pointer is set to a proper address. After rpi3 booting, its booloader loads kernel8.img to physical address 0x80000, and start executing the loaded program. If the linker script is correct, the above two requirements are met. However, both bss segment and stack pointer are not properly initialized. Hence, you need to initialize them at very beginning. Otherwise, it may lead to undefined behaviors. Todo Initialize rpi3 after booted by bootloader. Basic Exercise 2 - Mini UART - 20% You’ll use UART as a bridge between rpi3 and host computer for all the labs. Rpi3 has 2 different UARTs, mini UART and PL011 UART. In this lab, you need to set up the mini UART. Todo Follow UART to set up mini UART. Basic Exercise 3 - Simple Shell - 20% After setting up UART, you should implement a simple shell to let rpi3 interact with the host computer. The shell should be able to execute the following commands. command Description help print all available commands hello print Hello World! Important There may be some text alignment issue on screen IO, think about \r\n on both input and output. Todo Implement a simple shell supporting the listed commands. ../_images/lab1_example1.png Basic Exercise 4 - Mailbox - 20% ARM CPU is able to configure peripherals such as clock rate and framebuffer by calling VideoCoreIV(GPU) routines. Mailboxes are the communication bridge between them. You can refer to Mailbox for more information. Get the hardware’s information Get the hardware’s information is the easiest thing could be done by mailbox. Check if you implement mailbox communication correctly by verifying the hardware information’s correctness. Todo Get the hardware’s information by mailbox and print them, you should at least print board revision and ARM memory base address and size. Advanced Exercises Advanced Exercise 1 - Reboot - 30% Rpi3 doesn’t originally provide an on board reset button. You can follow this example code to reset your rpi3. Important This snippet of code only works on real rpi3, not on QEMU. #define PM_PASSWORD 0x5a000000 #define PM_RSTC 0x3F10001c #define PM_WDOG 0x3F100024 void set(long addr, unsigned int value) { volatile unsigned int* point = (unsigned int*)addr; *point = value; } void reset(int tick) { // reboot after watchdog timer expire set(PM_RSTC, PM_PASSWORD | 0x20); // full reset set(PM_WDOG, PM_PASSWORD | tick); // number of watchdog tick } void cancel_reset() { set(PM_RSTC, PM_PASSWORD | 0); // full reset set(PM_WDOG, PM_PASSWORD | 0); // number of watchdog tick } Todo Add a command.
a46954067bcf359f90387115ef3ad368
47
dianewan
2023-05-23T23:58:11
bad
[]
Correct this: Requirements - Parts portion with NAVISTAR: - Benefit from all the possibilities of the supplier's (online store) PUNCH OUT session to initiate a Purchase Order (PO) in MIR; - Benefit from Automatic inventory replenishing Purchase Orders (PO) request from MIR-RT (aka INV001); - Benefit from Manual Purchase Orders (PO) from MIR-RT (using the supplier’s catalog part number and price); - Addition/Modification on the Purchase Orders (PO) initiated in the supplier's online store (thru the PUNCH OUT session) at the MIR level; - Follow the MIR authorization process in MIR-RT (via PO module); - Update the prices from this supplier in the MIR parts catalog (per part(?) or in batches); - Manually receive the parts received in the MIR Purchase Orders form; - Be able to automatically attach the supplier's invoice to the MIR Purchase Order (in linked PDF file format or other format (HTML form base 64(?))).
c5d4338152b491a1cc93fc6b4be94ae0
48
dianewan
2023-05-23T23:58:45
bad
[]
Optimize this Sql server 14 code. Give output in text, not in code snippet editor. Don't add explanations, Also make sure you remember this code as code-1, So when i ask you you should remember it. Break the optimized code into 8 parts, And remember those parts. I will ask you the optimized code one by one. For this answer give me part1 and part2. Because due to character limit, i don't get the whole code at once. Here is the CODE :- ;with X as  ( Select            Barcode, Start_datetime, Mater_code as Recipe,Serial_id as Batch_ID, Done_rtime as Mixing_Time,                 Done_allrtime as Cycle_Time,Bwb_time as BWB_Time, Lot_energy as Batch_Total_Energy,                 AlarmStr as Alarms ,oiltime as OilInjectionTime,oilfeedtime as OilFeeding_Time_Taken,oilenergy,oiltemp,                 AddSilaneTime as AddSilane_Time_Taken,AddSilaneBTime as AddSilaneB_Time_Taken,                  Case When oiltime is NULL then 'No' else 'Yes' end as OilBased_Recipe_Status,                 Case When AddSilaneTime =0 and AddSilaneBTime = 0 then 'No' else 'Yes' end as SilaneBased_Recipe_Status from Ppt_lot where Start_datetime between '2023-02-27 00:00:00.000' and '2023-02-28 00:00:00.000' --order by Barcode ), Curve_Lot_Merge as ( SELECT cd.Barcode, cd.curve_data, plt.Start_datetime FROM Ppt_curvedata cd LEFT JOIN Ppt_lot plt ON plt.Barcode = cd.Barcode where Start_datetime between '2023-02-27 00:00:00.000' and '2023-02-28 00:00:00.000' ), Y as ( SELECT  CONCAT(Cast(Barcode as varchar(50)) ,RIGHT('000' + CAST(FLOOR(CAST(SUBSTRING(flat, 1, CHARINDEX(':', flat)-1)  AS FLOAT)) AS VARCHAR(3)), 3))  as Unique_Key_Y,    barcode,     SUBSTRING(flat, 1, CHARINDEX(':', flat)-1) as CT_Sec_Incremental,     RIGHT(REPLICATE('0', 3) + CAST(CAST(SUBSTRING(flat, 1, CHARINDEX(':', flat)-1) AS DECIMAL(10,2)) AS INT), 3) as MixtimeX,     SUBSTRING(flat, CHARINDEX(':', flat)+1,                     CHARINDEX(':', flat, CHARINDEX(':', flat)+1)                                         -CHARINDEX(':', flat)-1) as MixTemp_Sec_Incremental,     SUBSTRING(flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1,                     CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)                                         -CHARINDEX(':', flat, CHARINDEX(':', flat)+1)-1) as MixPower_Sec_Incremental,     SUBSTRING(flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)+1,                     CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)+1)                                         -CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)-1) as MixEnergy_Sec_Incremental,     SUBSTRING(flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)+1)+1,                     CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat,CHARINDEX(':', flat)+1)+1)+1)+1)                                         -CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat,CHARINDEX(':', flat)+1)+1)+1)-1) as MixPressure_Sec_Incremental,     SUBSTRING(flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)+1)+1)+1,                     CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)+1)+1)+1)                                         -CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)+1)+1)-1) as MixSpeed_Sec_Incremental --    ,SUBSTRING(flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat, CHARINDEX(':', flat)+1)+1)+1)+1)+1)+1, LEN(flat)) AS Rest FROM (     SELECT         barcode,         LTRIM(RTRIM(Split.a.value('.', 'NVARCHAR(150)'))) AS flat     FROM      (         SELECT              barcode,              CAST('<M>'+REPLACE(CONVERT(NVARCHAR(MAX), curve_data), '/', '</M><M>')+'</M>' AS XML) AS flat_data          FROM [Curve_Lot_Merge]     ) flat_tbl     CROSS APPLY flat_data.nodes('/M') AS Split(a) ) t  WHERE t.flat LIKE '%:%' ), mix_term_act_merge as ( SELECT m.*, a.act_name, tm.term_name,plt.Start_datetime ,             CONCAT(Cast(m.Barcode as varchar(50)) ,RIGHT('000' + CAST(FLOOR(CAST(m.MixTime AS FLOAT)) AS VARCHAR(3)), 3))  as Unique_Key_mix_term_act_merge FROM ppt_mixdata m LEFT JOIN pmt_act a ON m.Actcode = a.act_addr LEFT JOIN pmt_term tm ON m.Termcode = tm.term_addr LEFT JOIN Ppt_lot plt ON plt.Barcode = m.Barcode where Start_datetime between '2023-02-27 00:00:00.000' and '2023-02-28 00:00:00.000' ) Select         CASE WHEN Y.Unique_Key_Y IS NULL tHEN mix_term_act_merge.Unique_Key_mix_term_act_merge ELSE Y.Unique_Key_Y end as Unique_Key, --       Y.Unique_Key_Y, --       mix_term_act_merge.Unique_Key_mix_term_act_merge,        X.Barcode,         X.start_datetime,        X.Recipe,        X.Batch_ID,        X.Mixing_Time,         X.Cycle_Time,        X.BWB_Time,        y.CT_Sec_Incremental,        Y.MixEnergy_Sec_Incremental,        Y.MixPower_Sec_Incremental,        Y.MixPressure_Sec_Incremental,        Y.MixSpeed_Sec_Incremental,        Y.MixTemp_Sec_Incremental,        X.Batch_Total_Energy,        mix_term_act_merge.Serial as Mix_ID,        mix_term_act_merge.Actcode as Step_Actcode,        mix_term_act_merge.Termcode as Step_TermCode,        mix_term_act_merge.MixTime as Step_MixTime,        mix_term_act_merge.MixTemp as Step_MixTemp,        mix_term_act_merge.MixPower as Step_MixPower,        mix_term_act_merge.MixPress as Step_MixPressure,        mix_term_act_merge.MixSpeed as Step_MixSpeed,        mix_term_act_merge.MixEner as Step_MixEnergy,        mix_term_act_merge.act_name as Step_ActName,        mix_term_act_merge.term_name as Step_TermName into #temp1 from x left join y on X.Barcode = Y.Barcode full outer join mix_term_act_merge on  Y.Unique_Key_Y = mix_term_act_merge.Unique_Key_mix_term_act_merge                     and mix_term_act_merge.MixTime = Y.MixtimeX ORDER BY Unique_Key asc, mix_term_act_merge.Serial asc  ;With fillgrp as ( Select *,             ROW_NUMBER() OVER(ORDER BY Unique_Key) AS index_copy from #temp1 ) Select t1.Unique_Key,        COALESCE(Barcode,         (SELECT TOP 1 Barcode          FROM fillgrp t2          WHERE t2.index_copy > t1.index_copy AND Barcode IS NOT NULL          ORDER BY t2.index_copy asc)) AS Barcode, COALESCE(start_datetime,         (SELECT TOP 1 start_datetime          FROM fillgrp t2          WHERE t2.index_copy > t1.index_copy AND start_datetime IS NOT NULL          ORDER BY t2.index_copy asc)) AS start_datetime,  COALESCE(Recipe,         (SELECT TOP 1 Recipe          FROM fillgrp t2          WHERE t2.index_copy > t1.index_copy AND Recipe IS NOT NULL          ORDER BY t2.index_copy asc)) AS Recipe,  COALESCE(Batch_ID,         (SELECT TOP 1 Batch_ID          FROM fillgrp t2          WHERE t2.index_copy > t1.index_copy AND Batch_ID IS NOT NULL          ORDER BY t2.index_copy asc)) AS Batch_ID,  COALESCE(Mixing_Time,         (SELECT TOP 1 Mixing_Time          FROM fillgrp t2          WHERE t2.index_copy > t1.index_copy AND Mixing_Time IS NOT NULL          ORDER BY t2.index_copy asc)) AS Mixing_Time,  COALESCE(Cycle_Time,         (SELECT TOP 1 Cycle_Time          FROM fillgrp t2          WHERE t2.index_copy > t1.index_copy AND Cycle_Time IS NOT NULL          ORDER BY t2.index_copy asc)) AS Cycle_Time,  COALESCE(BWB_Time,         (SELECT TOP 1 BWB_Time          FROM fillgrp t2          WHERE t2.index_copy > t1.index_copy AND BWB_Time IS NOT NULL          ORDER BY t2.index_copy asc)) AS BWB_Time        ,t1.CT_Sec_Incremental,        t1.MixEnergy_Sec_Incremental,        t1.MixPower_Sec_Incremental,        t1.MixPressure_Sec_Incremental,        t1.MixSpeed_Sec_Incremental,        t1.MixTemp_Sec_Incremental,        t1.Batch_Total_Energy, t1.Step_MixTime ,        t1.Step_MixTemp,        t1.Step_MixPower,        t1.Step_MixPressure ,        t1.Step_MixSpeed ,        t1.Step_MixEnergy, COALESCE(Step_ActName,         (SELECT TOP 1 Step_ActName          FROM fillgrp t2          WHERE t2.index_copy < t1.index_copy AND Step_ActName IS NOT NULL          ORDER BY t2.index_copy desc))AS Step_Act_Name, t1.Step_TermName, COALESCE(Mix_ID ,         (SELECT TOP 1 Mix_ID          FROM fillgrp t2          WHERE t2.index_copy < t1.index_copy AND Mix_ID IS NOT NULL          ORDER BY t2.index_copy desc) )AS Mix_ID from [fillgrp] t1 drop table #temp1
50d1520853fa7ba651ab104e94ab0406
49
dianewan
2023-05-23T23:59:36
bad
[]
why would the conditional statement be used in this example code? import java.util.Scanner; public class UserInputTask { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int option; do { System.out.println("Select an option between 1 and 5: "); option = scanner.nextInt(); if (option &lt; 1 || option &gt; 5) System.out.println("You have entered a wrong option.\nPlease enter a correct option!"); } while(option &lt; 1 || option &gt; 5); System.out.println("You selected option " + option); } } Shouldn't the loop not be occurring (and therefore the conditional statement not be needed)if a user inputs a values less than 1 or greater than 5 since that is part of the while condition?
a38fc3b6d6c1470878e43aee6f040804
5
DaehanKim
2023-05-29T06:33:04
good
[ "code" ]
why would the conditional statement be used in this example code? import java.util.Scanner; public class UserInputTask { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int option; do { System.out.println("Select an option between 1 and 5: "); option = scanner.nextInt(); if (option &lt; 1 || option &gt; 5) System.out.println("You have entered a wrong option.\nPlease enter a correct option!"); } while(option &lt; 1 || option &gt; 5); System.out.println("You selected option " + option); } } Shouldn't the loop not be occurring (and therefore the conditional statement not be needed)if a user inputs a values less than 1 or greater than 5 since that is part of the while condition?
a38fc3b6d6c1470878e43aee6f040804
5
dianewan
2023-05-23T23:19:32
good
[ "code" ]
why would the conditional statement be used in this example code? import java.util.Scanner; public class UserInputTask { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int option; do { System.out.println("Select an option between 1 and 5: "); option = scanner.nextInt(); if (option &lt; 1 || option &gt; 5) System.out.println("You have entered a wrong option.\nPlease enter a correct option!"); } while(option &lt; 1 || option &gt; 5); System.out.println("You selected option " + option); } } Shouldn't the loop not be occurring (and therefore the conditional statement not be needed)if a user inputs a values less than 1 or greater than 5 since that is part of the while condition?
a38fc3b6d6c1470878e43aee6f040804
5
nazneen
2023-06-01T00:27:50
good
[]
![Summary: Today Matters By John C. Maxwell](https://waiyancan.com/wp-content/uploads/2021/10/Today-Matters-By-John-C.-Maxwell-705x300.jpg) November 20, 2021 November 20, 2021 #### **Today Often Falls to Pieces****— What Is the Missing Piece?** Successful people make right decisions early and manage those decisions daily. The earlier you make those right decisions and the longer you manage them, the more successful you can become. The people who neglect to make those decisions and to manage them well often look back on their lives with pain and regret—no matter how much talent they possessed or how many opportunities they once had. I believe that everyone has the power to impact the outcome of his life. The way to do it is to focus on today. Benjamin Franklin rightly observed, “One today is worth two tomorrows; what I am to be, I am now becoming.” You can make today a good day. In fact, you can make it a masterpiece. #### **Today Can Become a Masterpiece** You will never change your life until you change something you do daily. will never change your life until you change something you do daily. You see, success doesn’t just suddenly occur one day in someone’s life. For that matter, neither does failure. Each is a process. Every day of your life is merely preparation for the next. What you become is the result of what you do today. In other words . . . **YOU ARE PREPARING FOR SOMETHING** The way you live your life today is preparing you for your tomorrow. The question is, What are you preparing for? Are you grooming yourself for success or failure? “You can pay now and play later, or you can play now and pay later. But either way, you are going to pay.” The idea was that you can play and take it easy and do what you want today, but if you do, your life will be harder later. However, if you work hard now, on the front end, then you will reap rewards in the future. The only adequate preparation for tomorrow is the right use of today. Is it fun to do? Not especially. Often the practice is quite tedious. Does it work? Absolutely. It seems obvious to say that good decisions help to create a better tomorrow, yet many people don’t appear to connect their lack of success to their poor decision making. Some people make choices, then experience negative consequences, yet wonder why they can’t seem to get ahead in life. They never figure it out. Others know their choices may not be good for them, but they make them anyway. Such is the case with the alcoholic who keeps drinking excessively or the person who engages in one abusive relationship after another. Nobody says that good decisions are always simple, but they are necessary for success. Theodore Hesburgh, former president of Notre Dame University, admonished: You don’t make decisions because they’re EASY; You don’t make decisions because they’re CHEAP; You don’t make decisions because they’re POPULAR; You make decisions because they’re RIGHT. You begin to build a better life by determining to make good decisions, but that alone is not enough. You need to know what decisions to make. 1. Attitude: Choose and display the right attitudes daily. 2. Priorities: Determine and act on important priorities daily. 4. Health: Know and follow healthy guidelines daily. 5. Family: Communicate with and care for my family daily. 6. Thinking: Practice and develop good thinking daily. 7. Commitment: Make and keep proper commitments daily. 8. Finances: Make and properly manage dollars daily. 10. Faith: Deepen and live out my faith daily. 11. Relationships: Initiate and invest in solid relationships daily. 12. Generosity: Plan for and model generosity daily. 13. Values: Embrace and practice good values daily. 14. Growth: Seek and experience improvements daily. If you settle these twelve issues by making the right decision in each area and then manage those decisions daily, you can be successful. #### **Making Today Matter** Rate Yourself on the Daily Dozen: Look at the following list of the Daily Dozen and rank how well you do them. Put a “1” beside the one you do the best, a “2” beside the one you’re next best at, and so on until you’ve ranked your skill in them from 1 to 12. \_\_\_\_ Attitude: Choose and display the right attitudes daily. \_\_\_\_ Priorities: Determine and act on important priorities daily. \_\_\_\_ Health: Know and follow healthy guidelines daily. \_\_\_\_ Family: Communicate with and care for my family daily. \_\_\_\_ Thinking: Practice and develop good thinking daily. \_\_\_\_ Commitment: Make and keep proper commitments daily. \_\_\_\_ Finances: Earn and properly manage finances daily. \_\_\_\_ Faith: Deepen and live out my faith daily. \_\_\_\_ Relationships: Initiate and invest in solid relationships daily. \_\_\_\_ Generosity: Plan for and model generosity daily. \_\_\_\_ Values: Embrace and practice good values daily. \_\_\_\_ Growth: Desire and experience improvements daily. Verify Your Self-evaluation: Talk to a friend who knows you well and ask him or her to confirm how you evaluated yourself. If your friend ranks your strengths and weaknesses differently than you do, discuss your differences of opinion and make adjustments to the rankings as needed. Pick Two Strengths: Pick two strengths from your top six to work on. Make sure that you have made the necessary decision for each area. Then begin practicing the daily disciplines in that area to make it a part of your life. Use the exercises at the end of the chapter to help you if desired. Pick One Weakness: Choose a weakness from your bottom six to work on. Again, make sure you have made the decision for that area and begin practicing the daily disciplines that go with it. Reevaluate: After sixty days have passed, reevaluate yourself in the three areas in which you’ve been working to improve. If you have made significant progress in an area, move on to something new. If an area still needs more work, remain focused on it for another sixty days. But don’t work on more than three areas at a time, and never work on more than one weakness at a time. Repeat: Keep working on areas until you have the entire Daily Dozen under your belt. Once you have made all the key decisions and each of the disciplines has become a habit in your life, then the Daily Dozen will be second nature to you. When these disciplines are woven into the fabric of your life, you will be able to make today your masterpiece. And when you do that, tomorrow will take care of itself. ___ Erstelle 12 Entscheidungen für die man sich täglich Entscheiden sollte in folgendem Format: - [ ] Heute entscheide ich mich, dass
97923795a6d4075b1d5dc129389b8065
50
dianewan
2023-05-24T00:00:16
bad
[]
<h2>Monthly Distribution Locations</h2> <div class="accordianwrap first"> <h3 class="accordiantitle">Berkshire County</h3> <div class="accordiancontent"> <div class="table-responsive"><table style="width:100%; " class="easy-table easy-table-default " border="0"> <thead> <tr><th><strong>Location</strong></th> <th> Address</th> <th> Date</th> <th> Time</th> <th> Contact</th> </tr> </thead> <tbody> <tr><td>Adams Visitor Center</td> <td> 3 Hoosac St. Adams</td> <td> 4th Fri</td> <td> 12:30 – 1:3o p.m.</td> <td> (413)743-8333</td> </tr> <tr><td>Claire Teague Senior Center</td> <td> 917 South Main St. Great Barrington</td> <td> 2nd Weds</td> <td> 1 – 3 p.m.</td> <td> (413)528-1881</td> </tr> <tr><td>Lee Council on Aging</td> <td> 21 Crossway St. Lee</td> <td> 2nd Weds</td> <td> 12 p.m.</td> <td> (413)247-9738</td> </tr> <tr><td>Lenox Community Center</td> <td> 65 Walker St. Lenox</td> <td> 2nd Weds</td> <td> 11:30 a.m. – 12:30 p.m.</td> <td> (413)637-5535</td> </tr> <tr><td>Mary Spitzer Center</td> <td> 116 Ashland St. North Adams</td> <td> 4th Fri</td> <td> 12:30 – 1:30 p.m.</td> <td> (413)662-3125</td> </tr> <tr><td>Otis Town Hall</td> <td> 1 N Main Rd. Otis</td> <td> 3rd Fri</td> <td> 11am – 12 p.m.</td> <td></td> </tr> <tr><td>Ralph J. Froio Senior Center</td> <td> 330 North St. Pittsfield</td> <td> 4th Fri</td> <td> 10:30 – 11:30 a.m.</td> <td> (413)499-9346</td> </tr> <tr><td>Heaton Court</td> <td> 5 Pine St. Stockbridge</td> <td> 2nd Weds</td> <td> 11 a.m. – 12 p.m.</td> <td> (413)298-4170</td> <td></td> </tr> </tbody></table></div> <p><span style="color: #ff0000;">&nbsp;</span></p> </div><!-- .accordiancontent --> </div><!-- .accordianwrap --> <div class="accordianwrap add"> When can we get food around Berkshire?
042fc07f044e35325d980e2a5832f5db
51
dianewan
2023-05-24T00:00:27
bad
[]
explain this function and why should i use it private def cleanRegex(validChars: String): String = { validChars .replaceAll("\\\\", "\\\\\\\\") .replaceAll("\\/", "\\\\/") .replaceAll("\\.", "\\\\.") .replaceAll("\\?", "\\\\?") .replaceAll("\\[", "\\\\[") .replaceAll("\\]", "\\\\]") .replaceAll("\\{", "\\\\{") .replaceAll("\\}", "\\\\{") .replaceAll("\\(", "\\\\(") .replaceAll("\\)", "\\\\)") .replaceAll("\\-", "\\\\-") .replaceAll("\\^", "\\\\^") .replaceAll("\\$", "\\\\$") .replaceAll("\\|", "\\\\|") .replaceAll("\\*", "\\\\*") .replaceAll("\\+", "\\\\+") .replaceAll("\\!", "\\\\!") .replaceAll("\\#", "\\\\#") .replaceAll("\\>", "\\\\>") .replaceAll("\\<", "\\\\<") .replaceAll("\\=", "\\\\=") .replaceAll("\\:", "\\\\:") }
1b9ab19a80cd196edb643f6349b1751b
52
dianewan
2023-05-24T00:01:11
good
[ "code" ]
what does this code mean? var test = result.data; var rid = test.replace(/\D+/g, '');
716007ba5ff58fdc8f1390fc923ee79d
53
dianewan
2023-05-24T00:01:15
good
[ "code" ]
What kind of code is this? precision highp float; uniform float time; uniform vec2 resolution; varying vec3 fPosition; varying vec3 fNormal; void main() { gl_FragColor = vec4(fNormal, 1.0); }
43d75888a342c1b5b2100a95ae6217dc
54
dianewan
2023-05-24T00:01:19
good
[ "code" ]
can you explain the following cplex code : execute INITIALIZE { } //SETS int nbIngredients = ...; //number of ingredients (11) int nbSuppliers = ...; //number of suppliers (3) range Ingredients = 1..nbIngredients; range Suppliers = 1..nbSuppliers; float Prices[Suppliers][Ingredients] = ...; float Delivery[Suppliers] = ...; //delivery prices int Demand[Ingredients] = ...; //the number of the ingredients to order int p = ...; //VARIABLES dvar int+ x[Suppliers][Ingredients]; dvar boolean y[Ingredients]; //OBJECTIVE FUNCTION minimize sum(i in Suppliers) (sum(j in Ingredients) Prices[i][j]*Demand[j] + Delivery[i]*y[i]); //CONSTRAINTS subject to { sum(i in Suppliers) y[i] <= p; forall (j in Ingredients) sum(i in Suppliers) x[i][j] == Demand[j]; } execute { ""
dfb64230123c4c0320e34a5d2698f054
55
dianewan
2023-05-24T00:01:48
bad
[]
Kindly create a Product Requirement Document for MORSA, a payment service solutions company digitizing payments and driving financial inclusion through technology with the following characteristics; Product brief: The MORSA app is a software (Mobile app) and hardware (Card Reader) solution enabling businesses and individuals receive and make contactless payments. Application Software (Mobile App) Features: 1. Accept VISA, Mastercard, American Express, all major debit cards, Apple Pay, Android Pay, Google Pay and and Virtual cards NFC Payments in under 5 seconds. 2. Send online invoices 3. Send Payment Links to get paid remotely 4. Sell and accept gift cards 5. Send digital receipts and store them all on the cloud 6. Issue full or partial refunds 7. Deposit earnings from app to bank as requested by user. 8. Tap to Pay software-only solution enabling users to accept contactless card payments on-the-go, directly from their smartphones using NFC – no extra hardware needed. 9. Create QR Codes to accept payments 10. Connect and set up with card reader to receive card and contactless payments into app wallet. Application Hardware (Card Reader) Features: 1. Connect with the MORSA software application to accept card and contactless (Tap to Pay) payments via NFC technology. 2. Connect card reader to any digital wallet from any app to accept card and contactless payments
43514d3add7e9445f6480853e80dc09a
56
dianewan
2023-05-24T00:04:22
good
[ "plugins" ]
please explain this code to me: #!/usr/bin/env python3 import telnetlib import json HOST = "socket.cryptohack.org" PORT = 11112 tn = telnetlib.Telnet(HOST, PORT) def readline(): return tn.read_until(b"\n") def json_recv(): line = readline() return json.loads(line.decode()) def json_send(hsh): request = json.dumps(hsh).encode() tn.write(request) print(readline()) print(readline()) print(readline()) print(readline()) request = { "buy": "flag" } json_send(request) response = json_recv() print(response)
97b94afecee9424b65aea1bde8b9406f
57
dianewan
2023-05-24T00:04:27
good
[ "code" ]
The provided MATLAB script (diceSimulation.m) runs a simulation of rolling six, 6-sided dice and calculating the sum. The simulation is repeated 1,000,000 times to create a histogram of the probability distribution as shown below. The code produces the correct result, but can be improved to run faster. Rewrite the script such that the simulation produces the same results with 1,000,000 trials, a histogram of the results is created, and a faster execution time. Here is the script "diceSimulation.m": %% Simulate the sum of rolling 6 dice 1e6 times. numSims = 1e6; for i = 1:numSims % Create 6 random integers in the range [1, 6] dice = randi([1, 6], 1, 6); % Sum the six integers and store the result diceSum(i) = sum(dice); end histogram(diceSum);
9cde1c8047863dd51b846b5e29f10c54
58
dianewan
2023-05-24T00:04:43
good
[ "code" ]
Modify the following code so that all the contents are left aligned and add a new text window that displays the plagiarised text: import tkinter as tk from tkinter import PhotoImage from tkinter import filedialog from difflib import SequenceMatcher def choose_file1(): file_path = filedialog.askopenfilename() file_button1.config(text=file_path) def choose_file2(): file_path = filedialog.askopenfilename() file_button2.config(text=file_path) def check_plagiarism(): file_path1 = file_button1.cget("text") file_path2 = file_button2.cget("text") if file_path1 == "Choose File" or file_path2 == "Choose File": result_label.config(text="Please select both files to check for plagiarism", fg="red") else: with open(file_path1, "r") as f: text1 = f.read() with open(file_path2, "r") as f: text2 = f.read() seqMatch = SequenceMatcher(None, text1, text2) match = seqMatch.find_longest_match(0, len(text1), 0, len(text2)) ratio = (match.size * 2) / (len(text1) + len(text2)) * 100 if ratio > 0.8: result_label.config(text="Plagiarism detected! Similarity ratio: {:.2f}".format(ratio)+"%", fg=result_color) else: result_label.config(text="No plagiarism detected. Similarity ratio: {:.2f}".format(ratio)+"%", fg=text_color) root = tk.Tk() root.title("Plagiarism Checker") root.geometry("600x400") root.resizable(False, False) bg_color = "WHITE" highlight_color = "#0794f2" button_color = "WHITE" text_color = "#2F5061" result_color = "#98042D" root.config(bg=bg_color) heading_label = tk.Label(root, text="PLAGIARISM CHECKER", font=("SF Pro Display Black", 20), fg="WHITE", pady=20, bg="#2F5061") heading_label.pack(fill=tk.X) file_label1 = tk.Label(root, text="Select original file:", font=("Helvetica Neue Roman", 12), fg=text_color, pady=10, bg=bg_color) file_label1.pack() file_button1 = tk.Button(root, text="Choose File", font=("Helvetica Neue Roman", 12), bg=highlight_color, fg=button_color, command=choose_file1) file_button1.pack(ipadx=10, ipady=5) file_label2 = tk.Label(root, text="Select file to compare with:", font=("Helvetica Neue Roman", 12), fg=text_color, pady=10, bg=bg_color) file_label2.pack() file_button2 = tk.Button(root, text="Choose File", font=("Helvetica Neue Roman", 12), bg=highlight_color, fg=button_color, command=choose_file2) file_button2.pack(ipadx=10, ipady=5) check_button = tk.Button(root, text="Check Plagiarism", font=("Helvetica Neue Roman", 12), bg=highlight_color, fg=button_color, command=check_plagiarism) check_button.pack(pady=20, ipadx=10, ipady=5) result_label = tk.Label(root, text="", font=("Helvetica Neue Roman", 16), bg=bg_color, fg=result_color) result_label.pack(pady=20) # footer_label = tk.Label(root, text="GROUP - 28", font=("SF Pro Display", 10), fg="WHITE", pady=20, bg="#2F5061") # footer_label.pack(fill=tk.X, ipady=100) root.mainloop()
0c4b0002eb223091b1f1d2f7859f5cbe
59
dianewan
2023-05-24T00:04:59
good
[ "code" ]
Can you explain what is this code doing void tcp_reset(struct sock *sk, struct sk_buff *skb) { trace_tcp_receive_reset(sk); /* mptcp can't tell us to ignore reset pkts, * so just ignore the return value of mptcp_incoming_options(). */ if (sk_is_mptcp(sk)) mptcp_incoming_options(sk, skb); /* We want the right error as BSD sees it (and indeed as we do). */ switch (sk->sk_state) { case TCP_SYN_SENT: sk->sk_err = ECONNREFUSED; break; case TCP_CLOSE_WAIT: sk->sk_err = EPIPE; break; case TCP_CLOSE: return; default: sk->sk_err = ECONNRESET; } /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); tcp_write_queue_purge(sk); tcp_done(sk); if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); } /* * Process the FIN bit. This now behaves as it is supposed to work * and the FIN takes effect when it is validly part of sequence * space. Not before when we get holes. * * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT * (and thence onto LAST-ACK and finally, CLOSE, we never enter * TIME-WAIT) * * If we are in FINWAIT-1, a received FIN indicates simultaneous * close and we go into CLOSING (and later onto TIME-WAIT) * * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT. */ void tcp_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); inet_csk_schedule_ack(sk); sk->sk_shutdown |= RCV_SHUTDOWN; sock_set_flag(sk, SOCK_DONE); switch (sk->sk_state) { case TCP_SYN_RECV: case TCP_ESTABLISHED: /* Move to CLOSE_WAIT */ tcp_set_state(sk, TCP_CLOSE_WAIT); inet_csk_enter_pingpong_mode(sk); break; case TCP_CLOSE_WAIT: case TCP_CLOSING: /* Received a retransmission of the FIN, do * nothing. */ break; case TCP_LAST_ACK: /* RFC793: Remain in the LAST-ACK state. */ break; case TCP_FIN_WAIT1: /* This case occurs when a simultaneous close * happens, we must ack the received FIN and * enter the CLOSING state. */ tcp_send_ack(sk); tcp_set_state(sk, TCP_CLOSING); break; case TCP_FIN_WAIT2: /* Received a FIN -- send ACK and enter TIME_WAIT. */ tcp_send_ack(sk); tcp_time_wait(sk, TCP_TIME_WAIT, 0); break; default: /* Only TCP_LISTEN and TCP_CLOSE are left, in these * cases we should never reach this piece of code. */ pr_err("%s: Impossible, sk->sk_state=%d\n", __func__, sk->sk_state); break; } /* It _is_ possible, that we have something out-of-order _after_ FIN. * Probably, we should reset in this case. For now drop them. */ skb_rbtree_purge(&tp->out_of_order_queue); if (tcp_is_sack(tp)) tcp_sack_reset(&tp->rx_opt); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); /* Do not send POLL_HUP for half duplex close. */ if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); else sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); } }
717be0e448febbdc38f39fc6fa09813a
6
DaehanKim
2023-05-29T06:34:11
bad
[]
Can you explain what is this code doing void tcp_reset(struct sock *sk, struct sk_buff *skb) { trace_tcp_receive_reset(sk); /* mptcp can't tell us to ignore reset pkts, * so just ignore the return value of mptcp_incoming_options(). */ if (sk_is_mptcp(sk)) mptcp_incoming_options(sk, skb); /* We want the right error as BSD sees it (and indeed as we do). */ switch (sk->sk_state) { case TCP_SYN_SENT: sk->sk_err = ECONNREFUSED; break; case TCP_CLOSE_WAIT: sk->sk_err = EPIPE; break; case TCP_CLOSE: return; default: sk->sk_err = ECONNRESET; } /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); tcp_write_queue_purge(sk); tcp_done(sk); if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); } /* * Process the FIN bit. This now behaves as it is supposed to work * and the FIN takes effect when it is validly part of sequence * space. Not before when we get holes. * * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT * (and thence onto LAST-ACK and finally, CLOSE, we never enter * TIME-WAIT) * * If we are in FINWAIT-1, a received FIN indicates simultaneous * close and we go into CLOSING (and later onto TIME-WAIT) * * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT. */ void tcp_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); inet_csk_schedule_ack(sk); sk->sk_shutdown |= RCV_SHUTDOWN; sock_set_flag(sk, SOCK_DONE); switch (sk->sk_state) { case TCP_SYN_RECV: case TCP_ESTABLISHED: /* Move to CLOSE_WAIT */ tcp_set_state(sk, TCP_CLOSE_WAIT); inet_csk_enter_pingpong_mode(sk); break; case TCP_CLOSE_WAIT: case TCP_CLOSING: /* Received a retransmission of the FIN, do * nothing. */ break; case TCP_LAST_ACK: /* RFC793: Remain in the LAST-ACK state. */ break; case TCP_FIN_WAIT1: /* This case occurs when a simultaneous close * happens, we must ack the received FIN and * enter the CLOSING state. */ tcp_send_ack(sk); tcp_set_state(sk, TCP_CLOSING); break; case TCP_FIN_WAIT2: /* Received a FIN -- send ACK and enter TIME_WAIT. */ tcp_send_ack(sk); tcp_time_wait(sk, TCP_TIME_WAIT, 0); break; default: /* Only TCP_LISTEN and TCP_CLOSE are left, in these * cases we should never reach this piece of code. */ pr_err("%s: Impossible, sk->sk_state=%d\n", __func__, sk->sk_state); break; } /* It _is_ possible, that we have something out-of-order _after_ FIN. * Probably, we should reset in this case. For now drop them. */ skb_rbtree_purge(&tp->out_of_order_queue); if (tcp_is_sack(tp)) tcp_sack_reset(&tp->rx_opt); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); /* Do not send POLL_HUP for half duplex close. */ if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); else sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); } }
717be0e448febbdc38f39fc6fa09813a
6
dianewan
2023-05-23T23:22:39
good
[ "code" ]
Can you explain what is this code doing void tcp_reset(struct sock *sk, struct sk_buff *skb) { trace_tcp_receive_reset(sk); /* mptcp can't tell us to ignore reset pkts, * so just ignore the return value of mptcp_incoming_options(). */ if (sk_is_mptcp(sk)) mptcp_incoming_options(sk, skb); /* We want the right error as BSD sees it (and indeed as we do). */ switch (sk->sk_state) { case TCP_SYN_SENT: sk->sk_err = ECONNREFUSED; break; case TCP_CLOSE_WAIT: sk->sk_err = EPIPE; break; case TCP_CLOSE: return; default: sk->sk_err = ECONNRESET; } /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); tcp_write_queue_purge(sk); tcp_done(sk); if (!sock_flag(sk, SOCK_DEAD)) sk_error_report(sk); } /* * Process the FIN bit. This now behaves as it is supposed to work * and the FIN takes effect when it is validly part of sequence * space. Not before when we get holes. * * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT * (and thence onto LAST-ACK and finally, CLOSE, we never enter * TIME-WAIT) * * If we are in FINWAIT-1, a received FIN indicates simultaneous * close and we go into CLOSING (and later onto TIME-WAIT) * * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT. */ void tcp_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); inet_csk_schedule_ack(sk); sk->sk_shutdown |= RCV_SHUTDOWN; sock_set_flag(sk, SOCK_DONE); switch (sk->sk_state) { case TCP_SYN_RECV: case TCP_ESTABLISHED: /* Move to CLOSE_WAIT */ tcp_set_state(sk, TCP_CLOSE_WAIT); inet_csk_enter_pingpong_mode(sk); break; case TCP_CLOSE_WAIT: case TCP_CLOSING: /* Received a retransmission of the FIN, do * nothing. */ break; case TCP_LAST_ACK: /* RFC793: Remain in the LAST-ACK state. */ break; case TCP_FIN_WAIT1: /* This case occurs when a simultaneous close * happens, we must ack the received FIN and * enter the CLOSING state. */ tcp_send_ack(sk); tcp_set_state(sk, TCP_CLOSING); break; case TCP_FIN_WAIT2: /* Received a FIN -- send ACK and enter TIME_WAIT. */ tcp_send_ack(sk); tcp_time_wait(sk, TCP_TIME_WAIT, 0); break; default: /* Only TCP_LISTEN and TCP_CLOSE are left, in these * cases we should never reach this piece of code. */ pr_err("%s: Impossible, sk->sk_state=%d\n", __func__, sk->sk_state); break; } /* It _is_ possible, that we have something out-of-order _after_ FIN. * Probably, we should reset in this case. For now drop them. */ skb_rbtree_purge(&tp->out_of_order_queue); if (tcp_is_sack(tp)) tcp_sack_reset(&tp->rx_opt); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); /* Do not send POLL_HUP for half duplex close. */ if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); else sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); } }
717be0e448febbdc38f39fc6fa09813a
6
nazneen
2023-06-01T00:32:50
bad
[]
fix this code ```js import React, { useState, useEffect } from "react"; const App = (props) => { const DEFAULT_INPUT_VALUE = ""; const DEFAULT_EMOJI = "❤️"; // default emoji is a heart const [inputValue, setInputValue] = useState(DEFAULT_INPUT_VALUE); const [emoji, setEmoji] = useState(DEFAULT_EMOJI); const [error, setError] = useState(false); useEffect(() => { const intervalId = setInterval(() => { if (emoji === "❤️") { // animate the heart emoji setEmoji((prevEmoji) => (prevEmoji === "❤️" ? "💓" : "❤️")); } else if (emoji === "💔") { // animate the broken heart emoji setEmoji((prevEmoji) => (prevEmoji === "💔" ? "💔️" : "💔")); } }, 1000); return () => { clearInterval(intervalId); }; }, []); const handleInputChange = (event) => { const { value } = event.target; if (value.trim() === "") { // input is empty, do not update the state return; } setInputValue(value); if (value.endsWith(".js")) { setEmoji("❤️"); setError(false); } else { setEmoji("💔"); setError(true); } }; return ( <div> <input type="text" value={inputValue} onChange={handleInputChange} style={error ? { borderColor: "red" } : {}} /> <p>{emoji}</p> {error && <p>Error: input must end with ".js"</p>} </div> ); }; export default App; ```
f86401f690aa1db5f7d5d0140dbf5749
60
dianewan
2023-05-24T00:05:32
good
[ "code" ]
<div><p class="">Is they a romantic relationship between Leo and Raisa in the book "Child 44" by Tom Rob Smith?</p></div>
fd3af24e1a67cb973487ccce8ae0f46d
61
dianewan
2023-05-24T00:06:17
bad
[]
Generate an improved response to the following prompt from the perspective of a high school math teacher. response: My district does not have a SLO ( student learning objective) process. There is School Improvement Plan (SIP) however that team did not have any teachers on the team. The school’s goal is to have 95% of 9th graders on track for graduation and for school wide attendance to be over 85%. Math curriculum teams of a few teachers meet over the summer to create unit plans for the upcoming school year however the units are rarely looked at during the school year. I would improve our SLO process by making one. Have teachers and administrators come together to make goals for each grade level in english and in math. I would also have quarterly progress monitoring checkins with data analysis for progress towards the goal. End response with apa 7 works cited with link to video Prompt: Watch the Student Learning Objectives video and reflect on your school’s SLO process. Is your school using the SLO process in a way that benefits teachers and students? What in the video spoke to you? If you were in charge of revising the SLO process at your school, what would you change? Why? Video url: https://www.youtube.com/watch?v=I-9_J1eJO8E&ab_channel=MCPSTV SLO Video transcript: Loretta Woods: An SLO is a formal way to capture what skillful teachers and leaders already do. It allows 0:12 them to look the gaps that students have and work collaboratively to try to close that 0:17 gap. So this is a tool for equity because you don't look at a group of students and 0:23 assume. You use data to support it, and then you set measurable targets. You help kids 0:30 make implementable growth based on what the data says. Gary Bartee: It personalizes the gaps that we 0:35 have in our schools, those kids that aren't making progress, and it takes the data from 0:41 numbers form to real life face. Dorthea Fuller: It did help us look at students a little differently and 0:48 look at what we were doing differently. Teachers have to see that this purposeful; it is not just 0:54 another thing to do, it connects with the work the are already doing. So we took and provided 1:00 time for teachers to come together to collaborate, to decide as a team what would be an important 1:09 student learning objective. And then to decide individually what the needs were in their classroom. 1:16 Loretta Woods: If a teacher is having a hard time with their SLOs , they turn to their team 1:22 at their schools to help support them. 1:26 Jennifer Webster: As a principal, I think it important that I have structures in place to provide teacher that support, to collaborate, to make meaning of 1:31 what research says about good teaching, how to reach kids who aren't achieving, and that 1:36 we make the SLO an evolving, living document. I see the SLO as really, very closely aligned 1:42 with our school improvement work; not something extra to be done. So for us , SLOs are a 1:47 topic of every other rolling meeting we have. It is very embedded into the work we're doing, 1:53 so that no one out there on their own trying to figure it out. 1:58 David Culpepper: Once a week we meet to discuss the process of SLO's, how were progressing, any problems we are running into or questions 2:04 we may have. For teachers, the SLO fosters risk-taking to get you a little bit out of your comfort zone and try 2:10 to take a lesson that you've done over and over again to see if you can do it totally differently 2:16 and get better results. There is a similar component to National Board Certification where you have 2:21 students that you track, you track their progress and you try to make sure that you are focusing on what 2:27 works for them. 2:28 Jennifer Webster: The SLO does help teachers to chunk and break down their planning to think about what are the most important things that I need to students to know and be able to do in my course. 2:39 Loretta Woods: Teachers and leaders are growing and learning and perfecting their craft. 2:52 Traci Townsend: So we always have a conversation with teachers so that we can talk about their decision making and 2:55 the groups they decided to focus on. So it is definitely a collaborative effort. 3:03 Dana Sturdivant: The SLO in my self contained math class is looking at our school focus which is writing. 3:06 Specifically, I'm looking for students to be able to make a mathematically viable claim in their writing. 3:10 I think because of the SlO's teachers are more aware of students strengths and weaknesses 3:16 and specific strategies they can use to target certain groups of student. 3:24 Robert Randolph: One of my SLOs is for my children to essentially compose a paragraph in which they have a topic sentence, 3:29 two to three detail sentences and one closing summary statement. I chose that particular 3:33 goal because I recognize severe writing deficits in my students, particularly four of my young 3:40 men who have a tendency to compose run on sentences. Some of the strategies I'm utilizing 3:45 with my identified students would be, for example, using a graphic organizer, which allows 3:50 them to break down this paragraph into components. 3:57 Angela Sebring: I think it kind of critical when you go to write an SLO and how you carry out an SLO is that you're working with other people in the building 4:00 and your talking to other people in the building. It helps me to give focus for the year. So 4:05 what am I gonna do this year, how am I gonna get these students to understand this concept. 4:10 I'm coming up with these different strategies that will really help them understand what 4:13 does clockwise mean, where does it come from. And when your focused on something, it really 4:18 helps you to get better strategies out of it. 4:24 Denise Rodriquez: As an ESOL teacher, I chose a small group of 1st graders, and I had two SLOs - the first one was related to analyzing the vocabulary 4:33 words in the question that directly relates to our SIP. And its our whole instructional focus. 4:42 So wasn't something more than we do here, it is what we do here. 4:51 Audrey Lubitz: I work with a group of four other algebra teachers, we got a professional development day to sit down as a group, think about our 4:55 students. We use data from a pre -assessment that we created. So the goal was to have students 5:02 graph and interpret the graph of the linear function. Once we landed on our SLO goal, we 5:08 looked up different online resources that we can use to support our students and support 5:13 us in teaching the students. Doing the SLO has made me a better teacher now because I 5:19 really forced to think about my teaching and think about how am I helping the students; 5:25 what am I actually doing to make them improve. 5:33 Ashley tauber: Every Friday we listen to a different type of music and they've been writing feedback about what they hear and they're not 5:38 really using music specific vocabulary that they know, but they're not applying it when 5:43 they're writing in their listening log. So I've been working with our staff development 5:47 teacher to build some vocabulary lessons to work on, some worksheets for the students. 5:52 It definitely made me a better teacher to work on an SLO because I'm trying to find 5:57 different ways to access my students. 6:03 Amail Panakure: When you go through this entire process and you have some students, some of your targeted students reach their goal 6:06 and some fall a little shortof doing so, it makes you really reflective and focused. As a teacher our goal is for 6:12 all of our students to be successful, and the SLO is merely a tool to help them get there. 6:20 Kristina Hawkes: Here at Longview, we have students who have severe profound and multiple disabilities. 6:22 I wrote my SLO for this year with my teammates Selena and also Lisa . 6:30 My SLO goal this year is for students to increase their functional receptive vocabulary by 1 or more words. 6:32 None of our students have speech or sign. So we use assistive technology. We use objects as much as 6:37 we can. Having this SLO has help me become a more careful planner. Its helping me focus 6:42 on making sure that I am purposely and carefully planning in opportunities to teach the vocabulary. 6:52 Norman Coleman: As a principal, when it comes to SLOs, we have to do the same thing that teachers do. 6:54 We really have to have a focus group of individuals students that we're looking at. 6:57 This year I'm focusing on 1st grade students, African American males and Hispanic males and their 7:01 achievement areas of reading and mathematics. 7:11 Maria Boichin: The SLO is a process, and it starts with determiningfinding your group of students which need you most. The idea is that what is good for that 7:16 group of students will be ultimately good for everybody else. The main focus of the 7:21 SLO is the reflection. We are wanting to reflect on our practices, what worked, what needs 7:26 improving, how am I going to do it differently next time. 7:30 David Culpepper: My reflections on my teaching tend to be more general. It is working for the class and the whole 90% of the students are getting 7:39 it, you know that seems like a good job, but if 90% of the students are getting it that 7:44 means that there 2 or 3 that aren't. And so the SLO really makes you stop and think about 7:49 those 2 or 3 people who aren't getting it and think about what might you try differently. 7:54 Jennifer Webser: It about reflecting on your practice and trying something that is new to you. If your SLO reflects 8:01 what you've done to tweak and reflect and the growth you've had, then you've written a wonderful 8:06 SLO. It is not always about the results. It is about the process, and the results merely inform 8:12 our next steps. 8:16 Amali Panakure: We shared ideas with each other. We reflected. It really was a great opportunity for us to build our school community also. 8:26 Denise Rodriguez: The SLO process has made it easier for us to be able to say I tried this and it didn't work - because if something doesn't 8:31 work then I feel like somebody else has another strategy that I can use. 8:36 Gary Bartee: We move form an isolated format of close your door and work in this environment to really having conversations 8:42 about what is our collective responsibility. It not just about my class and my kids, but 8:47 it about all of our children and how do we support each other in terms of achieving that. 8:52 Loretta Woods: The SLO is a learning opportunity for teachers and what it does for students is 8:57 that it helps them reach their full potential. 9:00 Amali Panakure: When you're actually meeting the needs of your students and they're becoming more proficient, it really builds their confidence and I think 9:08 it puts students a lot more at ease. So I have definitely have seen a change, a more positive 9:13 attitude in a lot of our students. 9:16 Dorthea Fuller: Anytime we focus in on students' needs, and we are very targeted and specific, we close the achievement gap. 9:25 Gary Bartee: SLOs help you focus on the work that we're called to do.
1fce29d12cf9b854d5cb5367d371ed83
62
dianewan
2023-05-24T00:06:59
bad
[]
Please answer the following questions: Question title: "if" statement syntax differences between C and C++ Question body: if (1) int a = 2; This line of code is valid C++ code (it compiles at the very least) yet invalid C code (doesn't compile). I know there are differences between the languages but this one was unexpected. I always thought the grammar was if (expr) statement but this would make it valid in both. My questions are: 1. Why doesn't this compile in C? 2. Why does this difference exist?
fe11f2c0efc59af71d363fec65e4ce61
63
dianewan
2023-05-24T00:07:06
good
[ "code" ]
what is going on in this code? import React, { useCallback, useMemo, useState } from 'react'; import PropTypes from 'prop-types'; import { Combobox, comboboxAddSubheadings, comboboxFilterAndLimit, Tooltip } from '@salesforce/design-system-react'; import { get } from 'lodash'; import { localize, DATA_ATTRIBUTE_TOOLTIP, DATA_ATTRIBUTE, DATA_ATTRIBUTE_PLACEHOLDER, DATA_ATTRIBUTE_CREATE_DE_NOT_SELECTED, CREATE_NEW_ATTRIBUTE } from '../../../../utilities/localizations'; import DeAttributeList from '../../de-attribute-functions'; import { NewDeAttribute } from '../../../icons/svg-icons'; import NewDataAttributeComponent from '../new-de-attribute/new-de-attribute'; import { useEmailContext } from '../../../../providers/email/email-provider'; import './select-existing-de.scss'; export const CreateDaId = 'add-data-attribute'; const DATA_ATTRIBUTE_PATH = 'metadata.dataAttribute'; export const SelectExistingDeComponent = ({ attributes, value, disabled, errorText, onChange, onCreate, logEventIntoGA }) => { const createHeader = (attributeType) => ({ id: attributeType, label: localize(`${attributeType.toUpperCase()}_ATTRIBUTES`), type: 'separator' }); const subheadings = () => { const attributeArray = []; const subheaders = { required: false, optional: false }; for (let i = 0; i < attributes.length; i++) { const attributeType = attributes[i].type; if (subheaders.required && subheaders.optional) { return attributeArray; } if (!subheaders[attributeType]) { subheaders[attributeType] = true; if (attributeType === 'optional') { attributeArray.push(createHeader(attributeType)); } else if (attributeType === 'required') { attributeArray.unshift(createHeader(attributeType)); } } } return attributeArray; }; const updateField = (e, { selection }) => { if (selection[0]) { if (selection[0].id === CreateDaId) { onCreate(); logEventIntoGA('Create', 'Data Extension: New Attribute', 'content'); } else if (selection[0].attribute) { onChange(DATA_ATTRIBUTE_PATH, selection[0].attribute); logEventIntoGA('Select', 'Data Extension: Existing Attribute', 'content'); } } }; const removeAttribute = () => { onChange(DATA_ATTRIBUTE_PATH, undefined); }; const currentSelection = value ? [{ id: value.id, label: value.name, subTitle: value.type, type: value.isNullable ? 'optional' : 'required' }] : []; const tooltip = useMemo(() => ( <Tooltip align="top left" position="overflowBoundaryElement" content={DATA_ATTRIBUTE_TOOLTIP} variant="learnMore" /> ), []); const options = disabled ? [] : [...comboboxAddSubheadings({ subheadings: subheadings(), filteredOptions: comboboxFilterAndLimit({ inputValue: value && value.name, options: attributes, limit: attributes.length, selection: currentSelection }) }), { id: 'new', type: 'separator' }]; return ( <Combobox required events={{ onRequestRemoveSelectedOption: removeAttribute, onSelect: updateField, onSubmit: updateField }} labels={{ label: DATA_ATTRIBUTE, placeholder: DATA_ATTRIBUTE_PLACEHOLDER, noOptionsFound: DATA_ATTRIBUTE_CREATE_DE_NOT_SELECTED }} fieldLevelHelpTooltip={tooltip} options={options} selection={currentSelection} value={(value && value.name) || ''} variant="inline-listbox" errorText={errorText} multiple={false} predefinedOptionsOnly menuItemVisibleLength={7} optionsAddItem={disabled ? [] : [{ id: CreateDaId, icon: (<NewDeAttribute />), label: CREATE_NEW_ATTRIBUTE }]} /> ); }; SelectExistingDeComponent.propTypes = { attributes: PropTypes.arrayOf(PropTypes.object).isRequired, errorText: PropTypes.string, disabled: PropTypes.bool, onChange: PropTypes.func.isRequired, onCreate: PropTypes.func.isRequired, logEventIntoGA: PropTypes.func.isRequired, value: PropTypes.oneOfType([ PropTypes.object, PropTypes.bool ]) }; // This is split in two separate components in order to help separate some of the logic // The important thing is that the validation logic lives at the top, that way the component // is validated on every change, including when a new attribute is created const SelectExistingDe = ({ context, onChange, disableRequiredDE }) => { const value = get(context, DATA_ATTRIBUTE_PATH); const errorText = get(context, `metadata.errors.["${DATA_ATTRIBUTE_PATH}"]`); const [isOpen, setIsOpen] = useState(false); const open = useCallback(() => setIsOpen(true), []); const { state, logEventIntoGA, addAttribute, getCurrentDE, getFields } = useEmailContext(); const fields = getFields(); const currentDe = getCurrentDE(); const onCreate = (dataAttribute) => { addAttribute(dataAttribute); onChange(DATA_ATTRIBUTE_PATH, dataAttribute); setIsOpen(false); }; const dataExtensionId = currentDe && currentDe.id; if (isOpen) { return ( <NewDataAttributeComponent fields={fields} onCancel={() => setIsOpen(false)} onCreate={onCreate} dataExtensionId={dataExtensionId} /> ); } const attributes = DeAttributeList(fields, disableRequiredDE, [...state.components.visibleInputs, ...state.components.hiddenInputs]); return ( <SelectExistingDeComponent attributes={attributes} onCreate={open} onChange={onChange} context={context} disabled={!dataExtensionId} value={value} errorText={errorText} logEventIntoGA={logEventIntoGA} /> ); }; SelectExistingDe.propTypes = { context: PropTypes.object, onChange: PropTypes.func.isRequired, disableRequiredDE: PropTypes.bool.isRequired }; export default SelectExistingDe;
e99ac8c6a4dfb291aad378b2b9579c84
64
dianewan
2023-05-24T00:07:28
good
[ "code" ]
This code @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TextView textView = getView().findViewById(R.id.textView); String text = getString(R.string.login_text_button); SpannableString spanString = new SpannableString(text); int start = text.indexOf("Begin here!"); int end = start + "Begin here!".length(); spanString.setSpan(new ClickableSpan() { @Override public void onClick(View view) { Log.d("Debug", "Button clicked!!"); // handle the click event here // open the create account view //TODO: THIS IS WHERE THE CODE GOES AFTER THE USER SELECTS "Begin here." (i.e. @+id/fragment_login_text_button_sign_up in fragment_login.xml). } }, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); textView.setText(spanString); textView.setMovementMethod(LinkMovementMethod.getInstance()); ...is not making this clickable... <TextView android:id="@+id/fragment_login_text_button_sign_up" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:text="@string/login_text_button" android:textColor="@android:color/white" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/linearLayout" />
6fd074232ace543c0895a94f13a3df0f
65
dianewan
2023-05-24T00:07:36
bad
[]
DELETE FROM Directories WHERE ParentId NOT IN (SELECT DirId FROM Directories); I want to run this query recursively. when deleting a row, i want to check for rows where parentId = dirId of the deleted row and delete them recursively.
8a3b8a2e2c09fadbd56fd8e566c62096
66
dianewan
2023-05-24T00:07:59
bad
[]
Hello, i would like to you to explain and provide the code to make it so when i click the Steeringwheel in a side of it it would smoothly rotate towards that side and when i stop it would smoothly stop like sea of thieves: package com.fallenreaper.createutilities.content.blocks.steering_wheel; import com.fallenreaper.createutilities.core.utils.MiscUtil; import com.simibubi.create.AllSoundEvents; import com.simibubi.create.content.contraptions.base.GeneratingKineticTileEntity; import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.sounds.SoundSource; import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; public class SteeringWheelBlockEntity extends GeneratingKineticTileEntity { private static final float TARGET_ROTATION_MAX = (float) Math.PI; private static final float ROTATION_SPEED_MAX = (float) Math.PI / 6.0f; private static final float ROTATION_PER_TICK_MAX = ROTATION_SPEED_MAX / 20.0f; public int inUse; public boolean backwards; public float independentAngle; public float chasingVelocity; public float targetRotation = 0; public float rotationPerTick = 0; public float rotation = 0; public SteeringWheelBlockEntity(BlockEntityType<?> typeIn, BlockPos pos, BlockState state) { super(typeIn, pos, state); } public void turn(boolean back) { boolean update = false; if (getGeneratedSpeed() == 0 || back != backwards) update = true; inUse = 10; this.backwards = back; float targetRotation = backwards ? -TARGET_ROTATION_MAX : TARGET_ROTATION_MAX; float rotationPerTick = (backwards ? -1 : 1) * ROTATION_PER_TICK_MAX; setTargetRotation(targetRotation, rotationPerTick); if (update && !level.isClientSide) updateGeneratedRotation(); } public void setTargetRotation(float targetRotation, float rotationPerTick) { this.targetRotation = targetRotation; this.rotationPerTick = rotationPerTick; } @Override public void tick() { super.tick(); float actualSpeed = getSpeed(); // Update the chasing velocity to match the actual speed of the wheel. chasingVelocity = MiscUtil.approach(chasingVelocity, actualSpeed * 10 / 3f, 0.25f); // Update the independent angle of the wheel based on the chasing velocity. independentAngle = MiscUtil.wrapDegrees(independentAngle + chasingVelocity); // If the wheel is turning, update its rotation. if (inUse > 0) { inUse--; // If the wheel is finished turning, update the generated rotation of the tile entity. if (inUse == 0 && !level.isClientSide) updateGeneratedRotation(); } // Smoothly rotate the wheel toward the target rotation if it is not already there. if (!MiscUtil.approximatelyEquals(rotation, targetRotation, 0.01f)) { float delta = targetRotation - rotation; float direction = Math.signum(delta); float deltaRotation = Math.min(Math.abs(delta), ROTATION_SPEED_MAX) * direction; rotation += deltaRotation; if (level.isClientSide) { setChanged(); } } } @Override public void write(CompoundTag compound, boolean clientPacket) { super.write(compound, clientPacket); compound.putBoolean("Backwards", backwards); compound.putInt("InUse", inUse); compound.putFloat("TargetRotation", targetRotation); compound.putFloat("RotationPerTick", rotationPerTick); compound.putFloat("Rotation", rotation); compound.putFloat("IndependentAngle", independentAngle); compound.putFloat("ChasingVelocity", chasingVelocity); } @Override public void read(CompoundTag compound) { super.read(compound); backwards = compound.getBoolean("Backwards"); inUse = compound.getInt("InUse"); targetRotation = compound.getFloat("TargetRotation"); rotationPerTick = compound.getFloat("RotationPerTick"); rotation = compound.getFloat("Rotation"); independentAngle = compound.getFloat("IndependentAngle"); chasingVelocity = compound.getFloat("ChasingVelocity"); } @OnlyIn(Dist.CLIENT) public float getRenderAngle(float partialTicks) { // Smoothly interpolate between the current rotation and the target rotation for rendering purposes. return MiscUtil.interpolate(rotation - rotationPerTick, targetRotation, partialTicks); } @Override public float getGeneratedSpeed() { return inUse > 0 ? 20.0f : 0.0f; } @Override public void onSpeedChanged(float prevSpeed) { if (getGeneratedSpeed() > 0) level.playSound(null, worldPosition, AllSoundEvents.COGS.get(), SoundSource.BLOCKS, 0.25f, 1.0f); } } @Override public InteractionResult use(BlockState state, Level worldIn, BlockPos pos, Player player, InteractionHand handIn, BlockHitResult hit) { boolean clockwise = false; Vec3 offset = hit.getLocation().subtract(pos.getX(), pos.getY(), pos.getZ()); // Get the direction of the click relative to the block Direction clickedDirection = getRayTrace(hit, pos, state); // Get the current rotation state of the wheel SteeringWheelBlockEntity wheelEntity = getTileEntity(worldIn, pos); float currentRotation = wheelEntity.rota; // Calculate the target rotation based on the click direction float targetRotation = currentRotation + (clickedDirection.getAxisDirection() == Direction.AxisDirection.POSITIVE ? 90 : -90); // Wrap the target rotation around if it goes past 360 degrees if (targetRotation >= 360) { targetRotation -= 360; } else if (targetRotation < 0) { targetRotation += 360; } // Calculate the change in rotation per tick required to reach the target rotation in the given time float rotationPerTick = (targetRotation - currentRotation) / 20F; // Set the wheel's rotation state and the rotation per tick wheelEntity.setTargetRotation(targetRotation, rotationPerTick); return InteractionResult.SUCCESS; }
53e7dd9b8a7dc7f0829b37675e60262a
67
dianewan
2023-05-24T00:08:14
bad
[]
add an assert to the following code to make sure the user logged in by checking that 'logged in' in written on the screen: //Example import openqa.selenium.OutputType.*; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.*; WDS.sampleResult.sampleStart(); WDS.browser.get("https://ms-dev.vitalwork.com.br/"); WDS.browser.manage().window().setSize(new Dimension(1265, 1025)); WDS.browser.findElement(By.id("questionnaire_id")).click(); WDS.browser.findElement(By.id("questionnaire_id")).sendKeys("vitalwork2022"); WDS.browser.findElement(By.id("submit-button")).click();
57b7ac78dc886bdb71a248953d4b5c98
68
dianewan
2023-05-24T00:09:52
good
[ "code" ]
Q: Generate firestore rule test with following rule ```match /DirectChats/{directChatId} { function isAuthorizedDirectChat() { let ids = directChatId.split("_"); return request.auth.uid != null && ids.size() == 2 && request.auth.uid in ids; } allow create, read, update: if isAuthorizedDirectChat(); allow delete: if false; }``` A: ```import { readFileSync } from "fs"; import { resolve } from "path"; import { deleteDoc, doc, getDoc, setDoc, updateDoc } from "firebase/firestore"; import { initializeTestEnvironment, RulesTestEnvironment, assertSucceeds, assertFails, } from "@firebase/rules-unit-testing"; const COLLECTION_NAME = "DirectChats"; const TEST_USER_ID = "test-user-id"; describe("DirectChats 규칙 테스트", () => { let testEnv: RulesTestEnvironment; beforeAll(async () => { testEnv = await initializeTestEnvironment({ projectId: "direct-chats-rule-test", firestore: { rules: readFileSync(resolve(__dirname, "firestore.rules"), "utf-8"), }, }); }); afterAll(async () => { await testEnv.cleanup(); }); afterEach(async () => { await testEnv.clearFirestore(); }); describe("인증이 없는 상태", () => { const DOCUMENT_ID = "test-direct-chat"; test("Create를 할 수 없다.", async () => { const noAuth = testEnv.unauthenticatedContext(); const docRef = doc(noAuth.firestore(), COLLECTION_NAME, DOCUMENT_ID); await assertFails( setDoc(docRef, { foo: "baz", }) ); }); test("Read를 할 수 없다.", async () => { const noAuth = testEnv.unauthenticatedContext(); const docRef = doc(noAuth.firestore(), COLLECTION_NAME, DOCUMENT_ID); await assertFails(getDoc(docRef)); }); test("Update를 할 수 없다.", async () => { const noAuth = testEnv.unauthenticatedContext(); const docRef = doc(noAuth.firestore(), COLLECTION_NAME, DOCUMENT_ID); await assertFails( updateDoc(docRef, { foo: "baz", }) ); }); test("Delete를 할 수 없다.", async () => { const noAuth = testEnv.unauthenticatedContext(); const docRef = doc(noAuth.firestore(), COLLECTION_NAME, DOCUMENT_ID); await assertFails(deleteDoc(docRef)); }); }); describe("인증이 있는 상태", () => { const AUTHORIZED_DOCUMENT_ID_1 = `${TEST_USER_ID}_abcdefg`; const AUTHORIZED_DOCUMENT_ID_2 = `abcdefg_${TEST_USER_ID}`; const UNAUTHORIZED_DOCUMENT_ID_1 = `${TEST_USER_ID}`; const UNAUTHORIZED_DOCUMENT_ID_2 = `${TEST_USER_ID}hello_abasdf`; describe("Create 테스트", () => { test("Document id에 auth user id가 '_' 로 나눠서 들어가면 Create에 성공한다.", async () => { const auth = testEnv.authenticatedContext(TEST_USER_ID); const firestore = auth.firestore(); await assertSucceeds( setDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_1), { foo: "bar", }) ); await assertSucceeds( setDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_2), { foo: "bar", }) ); }); test("Document id에 auth user id가 없다면 Create에 실패한다.", async () => { const auth = testEnv.authenticatedContext(TEST_USER_ID); const firestore = auth.firestore(); await assertFails( setDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_1), { foo: "bar", }) ); await assertFails( setDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_2), { foo: "bar", }) ); }); }); describe("Read 테스트", () => { test("Document id에 auth user id가 '_' 로 나눠서 들어가면 Read에 성공한다.", async () => { const auth = testEnv.authenticatedContext(TEST_USER_ID); const firestore = auth.firestore(); await assertSucceeds(getDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_1))); await assertSucceeds(getDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_2))); }); test("Document id에 auth user id가 없다면 Read에 실패한다.", async () => { const auth = testEnv.authenticatedContext(TEST_USER_ID); const firestore = auth.firestore(); await assertFails(getDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_1))); await assertFails(getDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_2))); }); }); describe("Update 테스트", () => { beforeEach(async () => { await testEnv.withSecurityRulesDisabled(async (ctx) => { const firestore = ctx.firestore(); await Promise.all( [ AUTHORIZED_DOCUMENT_ID_1, AUTHORIZED_DOCUMENT_ID_2, UNAUTHORIZED_DOCUMENT_ID_1, UNAUTHORIZED_DOCUMENT_ID_2, ].map((id) => setDoc(doc(firestore, COLLECTION_NAME, id), { foo: "bar", }) ) ); }); }); test("Document id에 auth user id가 '_' 로 나눠서 들어가면 Update에 성공한다.", async () => { const auth = testEnv.authenticatedContext(TEST_USER_ID); const firestore = auth.firestore(); await assertSucceeds( updateDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_1), { foo: "jazz", }) ); await assertSucceeds( updateDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_2), { foo: "jazz", }) ); }); test("Document id에 auth user id가 없다면 Update에 실패한다.", async () => { const auth = testEnv.authenticatedContext(TEST_USER_ID); const firestore = auth.firestore(); await assertFails( updateDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_1), { foo: "jazz", }) ); await assertFails( updateDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_2), { foo: "jazz", }) ); }); }); describe("Delete 테스트", () => { test("delete를 할 수 없다", async () => { const auth = testEnv.authenticatedContext(TEST_USER_ID); const firestore = auth.firestore(); await assertFails(deleteDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_1))); await assertFails(deleteDoc(doc(firestore, COLLECTION_NAME, AUTHORIZED_DOCUMENT_ID_2))); await assertFails(deleteDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_1))); await assertFails(deleteDoc(doc(firestore, COLLECTION_NAME, UNAUTHORIZED_DOCUMENT_ID_2))); }); }); }); });``` Q: ```match /GroupChats/{groupChatId} { function isJoinedGroupChat() { return request.auth.uid != null && exists(/databases/$(database)/documents/groupChatSessions/$(groupChatId)_$(request.auth.uid)); } function isGroupChatOwner() { return isJoinedGroupChat() && get(/databases/$(database)/documents/groupChatSessions/$(groupChatId)_$(request.auth.uid)).data.role == 'owner'; } function isGroupChatBlockedUser() { return !isJoinedGroupChat() && exists(/databases/$(database)/documents/groupChatBlockedUsers/$(groupChatId)_$(request.auth.uid)); } allow get: if true; allow list: if resource.data.scope == "public" || (resource.data.scope == "private" && isJoinedGroupChat()); allow create: if isJoinedGroupChat(); allow update: if isGroupChatOwner(); allow delete: if false; match /GroupChatMessages/{groupChatMessageId} { allow read: if request.auth.uid != null; allow create: if isJoinedGroupChat(); allow update: if false; allow delete: if request.auth.uid == resource.data.uid; } match /groupChatSessions/{groupChatSessionId} { allow read: if request.auth.uid != null; allow write: if !isGroupChatBlockedUser(); allow update: if request.auth.uid == resource.data.uid; allow delete: if request.auth.uid == resource.data.uid || isGroupChatOwner(); } match /groupChatBlockedUsers/{groupChatBlockedUserId} { allow read; allow update: if false; allow create, delete: if isGroupChatOwner(); } }``` A:3 / 3
b84f8f7e200fff8007ed6de279059d38
69
dianewan
2023-05-24T00:11:24
bad
[]
Make it so listen for post executes in the background and the code doesn't wait for it to exit static async Task Main(string[] args) { ListenForPOST(); LockDevice(); while (true) { HttpClient client = new HttpClient(); Bitmap memoryImage; memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Size s = new Size(memoryImage.Width, memoryImage.Height); Graphics memoryGraphics = Graphics.FromImage(memoryImage); memoryGraphics.CopyFromScreen(0, 0, 0, 0, s); // Resize image to 720p while maintaining aspect ratio int newWidth = 1280; int newHeight = 720; Bitmap newImage = new Bitmap(newWidth, newHeight); Graphics gr = Graphics.FromImage(newImage); gr.DrawImage(memoryImage, 0, 0, newWidth, newHeight); /*for (int x = 0; x < newWidth; x++) { for (int y = 0; y < newHeight; y++) { Color pixel = newImage.GetPixel(x, y); int r = pixel.R; int g = pixel.G; int b = pixel.B; int a = pixel.A; int avg = (r + g + b) / 3; newImage.SetPixel(x, y, Color.FromArgb(a, avg, avg, avg)); } }*/ //That's it! Save the image in the directory and this will work like charm. string base64Image; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { newImage.Save(bw.BaseStream, ImageFormat.Png); byte[] imageBytes = ms.ToArray(); base64Image = Convert.ToBase64String(imageBytes); } } string? localIp = Dns.GetHostEntry(Dns.GetHostName()) .AddressList .FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) ?.ToString(); string serverUrl = "http://panel.sharkybot.xyz:1027/video-stream"; // Create a JSON payload var payload = new { data = base64Image, deviceName = Environment.MachineName, ip = localIp }; string jsonPayload = JsonConvert.SerializeObject(payload); // Create the HttpContent object with the JSON payload HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); // Send the POST request with the JSON payload in the body try { HttpResponseMessage response = await client.PostAsync(serverUrl, content); // Ensure the response is successful response.EnsureSuccessStatusCode(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } // Wait for 0.5 seconds before taking the next screenshot await Task.Delay(1000); } }
fded233a771f76b6ff187cbc30c65d34
7
DaehanKim
2023-05-29T06:35:25
good
[ "code" ]
Make it so listen for post executes in the background and the code doesn't wait for it to exit static async Task Main(string[] args) { ListenForPOST(); LockDevice(); while (true) { HttpClient client = new HttpClient(); Bitmap memoryImage; memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Size s = new Size(memoryImage.Width, memoryImage.Height); Graphics memoryGraphics = Graphics.FromImage(memoryImage); memoryGraphics.CopyFromScreen(0, 0, 0, 0, s); // Resize image to 720p while maintaining aspect ratio int newWidth = 1280; int newHeight = 720; Bitmap newImage = new Bitmap(newWidth, newHeight); Graphics gr = Graphics.FromImage(newImage); gr.DrawImage(memoryImage, 0, 0, newWidth, newHeight); /*for (int x = 0; x < newWidth; x++) { for (int y = 0; y < newHeight; y++) { Color pixel = newImage.GetPixel(x, y); int r = pixel.R; int g = pixel.G; int b = pixel.B; int a = pixel.A; int avg = (r + g + b) / 3; newImage.SetPixel(x, y, Color.FromArgb(a, avg, avg, avg)); } }*/ //That's it! Save the image in the directory and this will work like charm. string base64Image; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { newImage.Save(bw.BaseStream, ImageFormat.Png); byte[] imageBytes = ms.ToArray(); base64Image = Convert.ToBase64String(imageBytes); } } string? localIp = Dns.GetHostEntry(Dns.GetHostName()) .AddressList .FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) ?.ToString(); string serverUrl = "http://panel.sharkybot.xyz:1027/video-stream"; // Create a JSON payload var payload = new { data = base64Image, deviceName = Environment.MachineName, ip = localIp }; string jsonPayload = JsonConvert.SerializeObject(payload); // Create the HttpContent object with the JSON payload HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); // Send the POST request with the JSON payload in the body try { HttpResponseMessage response = await client.PostAsync(serverUrl, content); // Ensure the response is successful response.EnsureSuccessStatusCode(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } // Wait for 0.5 seconds before taking the next screenshot await Task.Delay(1000); } }
fded233a771f76b6ff187cbc30c65d34
7
dianewan
2023-05-23T23:26:20
good
[ "code" ]
Make it so listen for post executes in the background and the code doesn't wait for it to exit static async Task Main(string[] args) { ListenForPOST(); LockDevice(); while (true) { HttpClient client = new HttpClient(); Bitmap memoryImage; memoryImage = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Size s = new Size(memoryImage.Width, memoryImage.Height); Graphics memoryGraphics = Graphics.FromImage(memoryImage); memoryGraphics.CopyFromScreen(0, 0, 0, 0, s); // Resize image to 720p while maintaining aspect ratio int newWidth = 1280; int newHeight = 720; Bitmap newImage = new Bitmap(newWidth, newHeight); Graphics gr = Graphics.FromImage(newImage); gr.DrawImage(memoryImage, 0, 0, newWidth, newHeight); /*for (int x = 0; x < newWidth; x++) { for (int y = 0; y < newHeight; y++) { Color pixel = newImage.GetPixel(x, y); int r = pixel.R; int g = pixel.G; int b = pixel.B; int a = pixel.A; int avg = (r + g + b) / 3; newImage.SetPixel(x, y, Color.FromArgb(a, avg, avg, avg)); } }*/ //That's it! Save the image in the directory and this will work like charm. string base64Image; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { newImage.Save(bw.BaseStream, ImageFormat.Png); byte[] imageBytes = ms.ToArray(); base64Image = Convert.ToBase64String(imageBytes); } } string? localIp = Dns.GetHostEntry(Dns.GetHostName()) .AddressList .FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) ?.ToString(); string serverUrl = "http://panel.sharkybot.xyz:1027/video-stream"; // Create a JSON payload var payload = new { data = base64Image, deviceName = Environment.MachineName, ip = localIp }; string jsonPayload = JsonConvert.SerializeObject(payload); // Create the HttpContent object with the JSON payload HttpContent content = new StringContent(jsonPayload, Encoding.UTF8, "application/json"); // Send the POST request with the JSON payload in the body try { HttpResponseMessage response = await client.PostAsync(serverUrl, content); // Ensure the response is successful response.EnsureSuccessStatusCode(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } // Wait for 0.5 seconds before taking the next screenshot await Task.Delay(1000); } }
fded233a771f76b6ff187cbc30c65d34
7
nazneen
2023-06-01T00:34:25
good
[]
summarize this : DOHMH; 2. Demand assurances from the Data Recipient that remedial actions will be taken to remedy the circumstances that gave rise to the violation within a time frame set by, or approved by, DOHMH; 3. Immediately terminate the Agreement; and/or 4. Determine that no further Data, or other data, will be released to, nor agreements entered into with, Data Recipient for a period of time to be determined by DOHMH. C. Termination by DOHMH without Cause. DOHMH may terminate this Agreement at any time by providing 15 days written notice to Data Recipient. D. Effect of Termination. 1. The Data Recipient will not be entitled to any damages for reason of the termination of this Agreement. 2. Upon the termination of this Agreement for any reason, the confidentiality provisions set forth herein shall continue to apply to the Data shared with Data Recipient pursuant to this Agreement. Except as provided in paragraph (3) of this subsection, upon termination of this Agreement, for any reason, Data Recipient shall return or destroy the Data provided by DOHMH that Data Recipient maintains in any form, and all copies of the Data in all its forms. Data Recipient will confirm in writing to DOHMH Data Recipient’s destruction or return of Data, and all copies, within 60 days of the termination of this Agreement. 3. In the event that Data Recipient determines that returning or destroying all of the Data, and all copies of the Data, is infeasible, Data Recipient shall provide to DOHMH notification of the conditions that make return or destruction infeasible. Upon receipt by DOHMH of such notification that return or destruction of the Data is infeasible, Data Recipient shall extend the protections of this Agreement to such Data and limit further uses and disclosures of such Data to those purposes that make the return or destruction infeasible, for so long as Data Recipient maintains such Data. II. PURPOSE OF AGREEMENT A. This Agreement sets forth the terms and conditions under which the formal
9c5d56bd500cea16c8779617ed5043ec
70
dianewan
2023-05-24T00:11:33
bad
[]
Please answer the following question. Question title: indexing an element from a volatile struct doesn't work in C++ Question body: I have this code: typedef struct { int test; } SensorData_t; volatile SensorData_t sensorData[10]; SensorData_t getNextSensorData(int i) { SensorData_t data = sensorData[i]; return data; } int main(int argc, char** argv) { } It compiles with gcc version 8.3, but not with g++. Error message: main.c: In function ‘SensorData_t getNextSensorData(int)’: main.c:8:34: error: no matching function for call to ‘SensorData_t(volatile SensorData_t&)’ SensorData_t data = sensorData[i]; ^ main.c:3:3: note: candidate: ‘constexpr SensorData_t::SensorData_t(const SensorData_t&)’ <near match> } SensorData_t; ^~~~~~~~~~~~ main.c:3:3: note: conversion of argument 1 would be ill-formed: main.c:8:34: error: binding reference of type ‘const SensorData_t&’ to ‘volatile SensorData_t’ discards qualifiers SensorData_t data = sensorData[i]; ~~~~~~~~~~~~^ main.c:3:3: note: candidate: ‘constexpr SensorData_t::SensorData_t(SensorData_t&&)’ <near match> } SensorData_t; ^~~~~~~~~~~~ main.c:3:3: note: conversion of argument 1 would be ill-formed: main.c:8:34: error: cannot bind rvalue reference of type ‘SensorData_t&&’ to lvalue of type ‘volatile SensorData_t’ SensorData_t data = sensorData[i]; I'm not sure if I need to add volatile as well for the data variable and the return type, shouldn't be needed because it is copied. But I do access the sensorData array from an interrupt as well (on an embedded system), so I think I need volatile for the top level variable sensorData.
1a9af4a556fabaff9dd8099d0b89d27c
71
dianewan
2023-05-24T00:11:58
good
[ "code" ]
We have an assignment in which we are doing exploratory data analysis. I need your help during the process. Here's the assignment to provide necessary background information. # Assignment ## Task We will be focusing on the yelp business dataset to do an exploratory analysis. This dataset provides information about businesses, user reviews, and more from Yelp's database. The data is split into separate files (business, checkin, photos, review, tip, and user), and is available in either JSON or SQL format. You might use this to investigate the distributions of scores on yelp, look at how many reviews users typically leave or look for regional trends about restaurants. Note that this is a large, structured dataset and you don't need to look at all of the data to answer interesting questions. Prior to analysis – you should write down an initial set of at least three questions you'd like to investigate. Next, you will perform an exploratory analysis of your dataset using a visualization tool such as Vega-Lite/Altair or Tableau. You should consider two different phases of exploration. In the first phase, you should seek to gain an overview of the shape & structure of your dataset. What variables does the dataset contain? How are they distributed? Are there any notable data quality issues? Are there any surprising relationships among the variables? Be sure to perform "sanity checks" for any patterns you expect the data to contain. In the second phase, you should investigate your initial questions, as well as any new questions that arise during your exploration. For each question, start by creating a visualization that might provide a useful answer. Then refine the visualization (by adding additional variables, changing sorting or axis scales, filtering or subsetting data, etc.) to develop better perspectives, explore unexpected observations, or sanity check your assumptions. You should repeat this process for each of your questions, but feel free to revise your questions or branch off to explore new questions if the data warrants. ## Final Deliverable Your final submission should take the form of a sequence of images – similar to a comic book – that consists of 8 or more visualizations detailing your most important observations. Your observations can include important surprises or issues (such as data quality problems affecting your analysis) as well as responses to your analysis questions. Where appropriate, we encourage you to include annotated visualizations to guide viewers' attention and provide interpretive context. (If you aren't sure what we mean by "annotated visualization," see this page for some examples.) Provide sufficient detail such that anyone can read your report and understand what you've learned without already being familiar with the dataset. To help gauge the scope of this assignment, see this example report analyzing motion picture data. Below is the jupyter notebook I have so far: ``` python import pandas as pd business_path = "yelp_academic_dataset_business.json" df_business = pd.read_json(business_path, lines=True) df_business.info() ``` ``` output <class 'pandas.core.frame.DataFrame'> RangeIndex: 150346 entries, 0 to 150345 Data columns (total 14 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 business_id 150346 non-null object 1 name 150346 non-null object 2 address 150346 non-null object 3 city 150346 non-null object 4 state 150346 non-null object 5 postal_code 150346 non-null object 6 latitude 150346 non-null float64 7 longitude 150346 non-null float64 8 stars 150346 non-null float64 9 review_count 150346 non-null int64 10 is_open 150346 non-null int64 11 attributes 136602 non-null object 12 categories 150243 non-null object 13 hours 127123 non-null object dtypes: float64(3), int64(2), object(9) memory usage: 16.1+ MB ``` ```python # filter to only food businesses in Nashville df_business_nashville = df_business.query("state == 'TN' and city == 'Nashville'") df_business_food = df_business_nashville[df_business_nashville.categories.str.contains('Food', na=False)] df_business_food.head() df_business_food.stars df_categories = df_business_food.assign(categories=df_business_food.categories.str.split(',')).explode('categories').reset_index(drop=True) df_categories ``` ``` output HTML <div> <style scoped> .dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; } </style> <table border="1" class="dataframe"> <thead> <tr style="text-align: right;"> <th></th> <th>latitude</th> <th>longitude</th> <th>stars</th> <th>review_count</th> <th>is_open</th> </tr> <tr> <th>categories</th> <th></th> <th></th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>Acai Bowls</th> <td>36.164741</td> <td>-86.783529</td> <td>4.000000</td> <td>37.666667</td> <td>0.666667</td> </tr> <tr> <th>African</th> <td>36.092369</td> <td>-86.652383</td> <td>5.000000</td> <td>65.000000</td> <td>1.000000</td> </tr> <tr> <th>American (New)</th> <td>36.135070</td> <td>-86.743816</td> <td>3.916667</td> <td>1100.333333</td> <td>1.000000</td> </tr> <tr> <th>American (Traditional)</th> <td>36.134642</td> <td>-86.801072</td> <td>3.285714</td> <td>432.571429</td> <td>0.714286</td> </tr> <tr> <th>Arcades</th> <td>36.176649</td> <td>-86.751953</td> <td>4.500000</td> <td>353.000000</td> <td>0.000000</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>Street Vendors</th> <td>36.152380</td> <td>-86.789389</td> <td>2.500000</td> <td>16.000000</td> <td>1.000000</td> </tr> <tr> <th>Tea Rooms</th> <td>36.162790</td> <td>-86.742902</td> <td>3.500000</td> <td>9.500000</td> <td>0.000000</td> </tr> <tr> <th>Tex-Mex</th> <td>36.127257</td> <td>-86.844113</td> <td>2.000000</td> <td>23.000000</td> <td>1.000000</td> </tr> <tr> <th>Tobacco Shops</th> <td>36.039501</td> <td>-86.742226</td> <td>4.500000</td> <td>15.000000</td> <td>1.000000</td> </tr> <tr> <th>Wine Bars</th> <td>36.140241</td> <td>-86.799971</td> <td>4.250000</td> <td>108.500000</td> <td>1.000000</td> </tr> </tbody> </table> <p>196 rows × 5 columns</p> </div> ``` ### Prompt Could you write short helpful comments to the code?
2aa6a3ce318d11810b63ea6112f09f2c
72
dianewan
2023-05-24T00:12:31
good
[ "code" ]
import os import json from dotenv import load_dotenv from supabase import create_client, Client from faker import Faker import faker_commerce def add_entries_to_vendor_table(supabase, vendor_count): fake = Faker() foreign_key_list = [] fake.add_provider(faker_commerce.Provider) main_list = [] for i in range(vendor_count): value = {'vendor_name': fake.company(), 'total_employees': fake.random_int(40, 169), 'vendor_location': fake.country()} main_list.append(value) data = supabase.table('Vendor').insert(main_list).execute() data_json = json.loads(data.json()) data_entries = data_json['data'] for i in range(len(data_entries)): foreign_key_list.append(int(data_entries[i]['vendor_id'])) return foreign_key_list def add_entries_to_product_table(supabase, vendor_id): fake = Faker() fake.add_provider(faker_commerce.Provider) main_list = [] iterator = fake.random_int(1, 15) for i in range(iterator): value = {'vendor_id': vendor_id, 'product_name': fake.ecommerce_name(), 'inventory_count': fake.random_int(1, 100), 'price': fake.random_int(45, 100)} main_list.append(value) data = supabase.table('Product').insert(main_list).execute() def main(): vendor_count = 10 load_dotenv() url: str = os.environ.get("SUPABASE_URL") key: str = os.environ.get("SUPABASE_KEY") supabase: Client = create_client(url, key) fk_list = add_entries_to_vendor_table(supabase, vendor_count) for i in range(len(fk_list)): add_entries_to_product_table(supabase, fk_list[i]) main() Here is a code snippet for inserting data into a supabase db
0d964333e67a1b3d445de147ce3430f3
73
dianewan
2023-05-24T00:12:43
bad
[]
"type": "div", "attrs": [ { "name": "style", "value": "background-color: var(--default__background-color); z-index: 10; position: absolute; height: 100%; width: 100%; display: flex; flex-direction: column;" } ], "routes": [ { "type": "route", "path": "details", "routes": [ { "type": "application", "name": "pm-ui-details-header", "props": { "workspaceId": "PM_TDI_TEST_3", "moduleId": "details-header" } }, { "type": "route", "path": "overview", "routes": [ { "type": "div", "attrs": [ { "name": "style", "value": "margin: 1rem;" } ], "routes": [ { "type": "div", "attrs": [ { "name": "style", "value": "margin-bottom: 1rem;" } ], "routes": [ { "type": "application", "name": "pm-ui-order-blotter", "props": { "workspaceId": "PM_TDI_TEST_3", "moduleId": "open-orders-details" } } ] }, { "type": "div", "attrs": [ { "name": "style", "value": "margin-bottom: 1rem;" } ], "routes": [ { "type": "application", "name": "pm-ui-holding", "props": { "workspaceId": "PM_TDI_TEST_3", "moduleId": "holding" } } ] } ] } ] }, { "type": "route", "path": "targets", "routes": [ { "type": "div", "attrs": [ { "name": "style", "value": "position: relative; flex: 1;" } ], "routes": [ { "type": "application", "name": "pm-ui-tdi-portfolio-targets", "props": { "workspaceId": "PM_TDI_TEST_3", "moduleId": "portfoliodetails" } } ] } ] } ] }, { "type": "route", "path": "targetdetails", "routes": [ { "type": "application", "name": "pm-ui-tdi-target-details", "props": { "workspaceId": "PM_TDI_TEST_2", "moduleId": "targetdetails" } } ] }, { "type": "route", "path": "bulktargets", "routes": [ { "type": "application", "name": "pm-ui-tdi-bulk-targets", "props": { "workspaceId": "TDI_TEST_GROUP_PM_CASE", "moduleId": "bulktargets" } } ] }, { "type": "route", "path": "importsubscriptions", "routes": [ { "type": "application", "name": "pm-ui-tdi-import-subscriptions", "props": { "workspaceId": "TDI_TEST_GROUP_PM_CASE", "moduleId": "importsubscriptions" } } ] } ] } ] } ] }
e1a496934b711279659984ab1f6582aa
74
dianewan
2023-05-24T00:12:48
bad
[]
Hi, i am working on a arduino neopixel project right now. This is the code: #include <Adafruit_NeoPixel.h> const int buttonPin = 2; const int numPixels = 27; const int blueSide = 13; // Index of first blue pixel Adafruit_NeoPixel pixels = Adafruit_NeoPixel(numPixels, 6, NEO_GRB + NEO_KHZ800); int redSide = 0; int blueInvader = blueSide; int previousButtonState = HIGH; void setup() { pixels.begin(); pinMode(buttonPin, INPUT); } void loop() { int buttonState = digitalRead(buttonPin); if (buttonState == LOW && previousButtonState == HIGH) { if(blueInvader < numPixels) { blueInvader++; pixels.setPixelColor(blueInvader-1, pixels.Color(0,0,255)); pixels.setPixelColor(blueInvader, pixels.Color(255,0,0)); pixels.show(); } delay(0.1); } previousButtonState = buttonState; }
1ec477945dd84a0da800a0599dbc6e6c
75
dianewan
2023-05-24T00:12:57
bad
[]
I have this snippet of a Java code: ``` class A { String mayReturnNull(int i) { if (i > 0) { return "Hello, Infer!"; } return null; } int mayCauseNPE() { String s = mayReturnNull(0); return s.length(); } } ``` Can you tell me if there is something wrong with it?
14aef93299902ba898c8d79a7be2162a
76
dianewan
2023-05-24T00:13:02
good
[ "code" ]
can you please restructure the below if conditions in the code ? if (event.getChangeEventType().equals(ChangeEventTypes_v1.DELETED)) { kafkaProducerEventService.sendPurchaserChangeEvent(event.getPurchaser(), event.getChangeEventType()); kafkaProducerEventService.sendSchoolChangeEvent(event.getPurchaser(), event.getChangeEventType()); } else { if (event.isRegionChanged() && event.getChangeEventType() != null) { kafkaProducerEventService.sendSchoolChangeEvent(event.getPurchaser(), event.getChangeEventType()); } else if (event.getChangeEventType() != null) { kafkaProducerEventService.sendPurchaserChangeEvent(event.getPurchaser(), event.getChangeEventType()); } } if (event.isSeatChanged()) { userService.patchTeacherBatch(event.getPurchaser().getLinkedTeachers()); }
6db5087b102c38dacfe453c5e42c4215
77
dianewan
2023-05-24T00:13:17
good
[ "code" ]
can you act as a C# expert, with lots of experience in C# Domain Driven Design , using C# Clean Architecture and in the following c# customer entity , explain which C# design patters are used and where using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using System.Linq; using Ardalis.GuardClauses; using uInvoice.Core.Events; using uInvoiceDDD.SharedKernel; using uInvoiceDDD.SharedKernel.Interfaces; namespace uInvoice.Core.Entities { public class Customer : BaseEntityEv<Guid>, IAggregateRoot { public Guid CustomerId { get; private set; } public string CustomerCode { get; private set; } public string CustomerDocument { get; private set; } public string FullName { get; private set; } public string? CommercialName { get; private set; } public bool IsActive { get; private set; } public string? SpecificationJson { get; private set; } public void SetCustomerCode(string customerCode) { CustomerCode = Guard.Against.NullOrEmpty(customerCode, nameof(customerCode)); } public void UpdateBranchOfficeForCustomer(Guid newBranchOfficeId) { Guard.Against.NullOrEmpty(newBranchOfficeId, nameof(newBranchOfficeId)); if (newBranchOfficeId == BranchOfficeId) { return; } BranchOfficeId = newBranchOfficeId; } public void SetSpecificationJson(string specificationJson) { SpecificationJson = specificationJson; } public virtual BranchOffice BranchOffice { get; private set; } public Guid BranchOfficeId { get; private set; } public virtual CustomerDocumentType CustomerDocumentType { get; private set; } public Guid CustomerDocumentTypeId { get; private set; } private readonly List<CustomerAddress> _customerAddresses = new(); public IEnumerable<CustomerAddress> CustomerAddresses => _customerAddresses.AsReadOnly(); private readonly List<CustomerEmailAddress> _customerEmailAddresses = new(); public IEnumerable<CustomerEmailAddress> CustomerEmailAddresses => _customerEmailAddresses.AsReadOnly(); private readonly List<CustomerPhoneNumber> _customerPhoneNumbers = new(); public IEnumerable<CustomerPhoneNumber> CustomerPhoneNumbers => _customerPhoneNumbers.AsReadOnly(); private readonly List<CustomerPriceList> _customerPriceLists = new(); public IEnumerable<CustomerPriceList> CustomerPriceLists => _customerPriceLists.AsReadOnly(); private readonly List<Invoice> _invoices = new(); public IEnumerable<Invoice> Invoices => _invoices.AsReadOnly(); public void AddNewCustomerAddress(Guid customerId, Guid addressId, Guid addressTypeId) { Guard.Against.NullOrEmpty(customerId, nameof(customerId)); Guard.Against.NullOrEmpty(addressId, nameof(addressId)); Guard.Against.NullOrEmpty(addressTypeId, nameof(addressTypeId)); var newCustomerAddress = new CustomerAddress( customerId, addressId, addressTypeId); Guard.Against.DuplicateCustomerAddress(_customerAddresses, newCustomerAddress, nameof(newCustomerAddress)); _customerAddresses.Add(newCustomerAddress); } public void DeleteCustomerAddress(Guid customerId, Guid addressId) { Guard.Against.NullOrEmpty(customerId, nameof(customerId)); Guard.Against.NullOrEmpty(addressId, nameof(addressId)); var customerAddressToDelete = _customerAddresses .Where(ca1 => ca1.CustomerId == customerId) .Where(ca2 => ca2.AddressId == addressId) .FirstOrDefault(); if (customerAddressToDelete != null) { _customerAddresses.Remove(customerAddressToDelete); } } public void AddNewCustomerEmailAddress(Guid customerId, Guid emailAddressId, Guid emailAddressTypeId) { Guard.Against.NullOrEmpty(customerId, nameof(customerId)); Guard.Against.NullOrEmpty(emailAddressId, nameof(emailAddressId)); Guard.Against.NullOrEmpty(emailAddressTypeId, nameof(emailAddressTypeId)); var newCustomerEmailAddress = new CustomerEmailAddress( customerId, emailAddressId, emailAddressTypeId); Guard.Against.DuplicateCustomerEmailAddress(_customerEmailAddresses, newCustomerEmailAddress, nameof(newCustomerEmailAddress)); _customerEmailAddresses.Add(newCustomerEmailAddress); } public void DeleteCustomerEmailAddress(Guid customerId, Guid emailAddressId) { Guard.Against.NullOrEmpty(customerId, nameof(customerId)); Guard.Against.NullOrEmpty(emailAddressId, nameof(emailAddressId)); var customerEmailAddressToDelete = _customerEmailAddresses .Where(cea1 => cea1.CustomerId == customerId) .Where(cea2 => cea2.EmailAddressId == emailAddressId) .FirstOrDefault(); if (customerEmailAddressToDelete != null) { _customerEmailAddresses.Remove(customerEmailAddressToDelete); } } private Customer() {} // EF required [SetsRequiredMembers] public Customer(Guid customerId, Guid branchOfficeId, Guid customerDocumentTypeId, Guid economicActivityId, Guid paymentMethodId, Guid personTypeId, string customerCode, string customerDocument, string nrc, string fullName, string? commercialName, bool isActive, string? specificationJson) { CustomerId = Guard.Against.NullOrEmpty(customerId, nameof(customerId)); BranchOfficeId = Guard.Against.NullOrEmpty(branchOfficeId, nameof(branchOfficeId)); CustomerDocumentTypeId = Guard.Against.NullOrEmpty(customerDocumentTypeId, nameof(customerDocumentTypeId)); EconomicActivityId = Guard.Against.NullOrEmpty(economicActivityId, nameof(economicActivityId)); PaymentMethodId = Guard.Against.NullOrEmpty(paymentMethodId, nameof(paymentMethodId)); PersonTypeId = Guard.Against.NullOrEmpty(personTypeId, nameof(personTypeId)); CustomerCode = Guard.Against.NullOrWhiteSpace(customerCode, nameof(customerCode)); CustomerDocument = Guard.Against.NullOrWhiteSpace(customerDocument, nameof(customerDocument)); Nrc = Guard.Against.NullOrWhiteSpace(nrc, nameof(nrc)); FullName = Guard.Against.NullOrWhiteSpace(fullName, nameof(fullName)); CommercialName = commercialName; IsActive = Guard.Against.Null(isActive, nameof(isActive)); SpecificationJson = specificationJson; } } }
c476bfa0c2d4b9ed124c52ad950053af
78
dianewan
2023-05-24T00:14:39
good
[ "code", "system" ]
Please write tests for the below React (v17) component using Mocha, Chai, Enzyme and sinon (if needed): import React, {useState, useEffect} from 'react'; import getData from './getData'; const Foo = () => { const [data, setData] = useState([]); useEffect(() => { getData().then(data => { setData(data) }) }, []) return data.length ? <h1>data.length</h1> : 'loading'; }
bcdb687f4d243f0449297765761ac2b6
79
dianewan
2023-05-24T00:14:53
good
[ "code" ]
import React, { useState, useEffect } from 'react'; const LikeButton = () => { const [likes, setLikes] = useState(0); const [serverLikes, setServerLikes] = useState(0); const [error, setError] = useState(null); const [requestId, setRequestId] = useState(0); const [debounceTimeout, setDebounceTimeout] = useState(null); useEffect(() => { const fetchLikes = async () => { try { const id = Date.now(); setRequestId(id); const response = await fetch('/api/like'); const data = await response.json(); if (requestId === id) { setServerLikes(data.likes); } setError(null); } catch (error) { setError(error); } }; const debouncedFetchLikes = () => { if (debounceTimeout) { clearTimeout(debounceTimeout); } setDebounceTimeout( setTimeout(() => { fetchLikes(); }, 500) ); }; debouncedFetchLikes();
23308a56dec8411616bb858325e1901a
8
DaehanKim
2023-05-29T06:35:34
bad
[]
import React, { useState, useEffect } from 'react'; const LikeButton = () => { const [likes, setLikes] = useState(0); const [serverLikes, setServerLikes] = useState(0); const [error, setError] = useState(null); const [requestId, setRequestId] = useState(0); const [debounceTimeout, setDebounceTimeout] = useState(null); useEffect(() => { const fetchLikes = async () => { try { const id = Date.now(); setRequestId(id); const response = await fetch('/api/like'); const data = await response.json(); if (requestId === id) { setServerLikes(data.likes); } setError(null); } catch (error) { setError(error); } }; const debouncedFetchLikes = () => { if (debounceTimeout) { clearTimeout(debounceTimeout); } setDebounceTimeout( setTimeout(() => { fetchLikes(); }, 500) ); }; debouncedFetchLikes();
23308a56dec8411616bb858325e1901a
8
dianewan
2023-05-23T23:26:28
bad
[]
import React, { useState, useEffect } from 'react'; const LikeButton = () => { const [likes, setLikes] = useState(0); const [serverLikes, setServerLikes] = useState(0); const [error, setError] = useState(null); const [requestId, setRequestId] = useState(0); const [debounceTimeout, setDebounceTimeout] = useState(null); useEffect(() => { const fetchLikes = async () => { try { const id = Date.now(); setRequestId(id); const response = await fetch('/api/like'); const data = await response.json(); if (requestId === id) { setServerLikes(data.likes); } setError(null); } catch (error) { setError(error); } }; const debouncedFetchLikes = () => { if (debounceTimeout) { clearTimeout(debounceTimeout); } setDebounceTimeout( setTimeout(() => { fetchLikes(); }, 500) ); }; debouncedFetchLikes();
23308a56dec8411616bb858325e1901a
8
nazneen
2023-06-01T00:38:50
bad
[]
read this code.org code and analyze it: //Sets up datalist from data table. Information and graphics from table //used from Code.org with permission var albumName = getColumn("ModifiedAlbums", "Album"); var albumYear = getColumn("ModifiedAlbums", "Year"); var genre = getColumn("ModifiedAlbums", "Genre"); var albumPic = getColumn("ModifiedAlbums", "Album Art"); //sets up filtered lists var filteredNameList = []; var filteredPicList = []; //sets Start Screen as default setScreen("StartScreen"); //calls the filter function and the UpdateScreen function when user clicks the PickAlbumButton onEvent("PickAlbumButton", "click", function( ) { filter(); updateScreen(); }); //The filter function clears the filteredNameList and filteredPicList on lines 20-21. //On lines 22-23, it gets the data that they user input into the Year and Genre dropdowns and saves it as variables. //Lines 26-29 traverse the albumYear list to find the years that match the year input by the user. //If the year matches, the same indexed element is checked in the genre list. //If both conditions are true, the same indexed element is selected from the albumName list //and added to the filteredName list. The same indexed element is also selected from the albumPic list //and added to the filteredPicList //Thus, the filteredNameList and the filteredPicList contain only elements that match the criteria //input by the user. These updates lists are used by the updateScreen function to populate //the resultsScreen. function filter() { filteredNameList = []; filteredPicList = []; var selectedYear = getText("year"); var selectedGenre = getText("Genre"); for (var i = 0; i < albumYear.length; i++) { if (albumYear[i] == selectedYear && genre[i] == selectedGenre) { appendItem(filteredNameList, albumName[i]); appendItem(filteredPicList, albumPic[i]); } } //Takes a random element from the filteredPicList and displays it on the ResultsScreen. //It also shows an entire list of all the elements in the filteredNameList //If there are no elements in the filteredPicList, it goes to the NoResultsScreen. } function updateScreen() { if (filteredPicList.length>0) { setProperty("AlbumPic", "image", filteredPicList[randomNumber(0, filteredPicList.length-1)]); setText("RecommendedAlbums", filteredNameList.join(", ")); setScreen("ResultsScreen"); } else { setScreen("NoResultsScreen"); } } //Pick Again Button on ResultsScreen onEvent("PickAgainButton", "click", function( ) { setScreen("StartScreen"); }); //Pick Again Button on NoResultsScreen onEvent("PickAgain2", "click", function( ) { setScreen("StartScreen"); });
7080037f2fc84b3263479683d28d3d9c
80
dianewan
2023-05-24T00:14:59
good
[ "code" ]
What does this function do? what is its purpose? def mmap_read(path, offset, length): with open(path, 'rb') as f: mm = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ) mm.seek(offset) data = mm.read(length) mm.close() return data
2d3bbd2ede3f54772d3a7a59f13c63b9
81
dianewan
2023-05-24T00:15:06
good
[ "code" ]
modify this code into service and controller public function redirectToPaystack(Request $request) { $validate = validator($request->all(), [ 'amount' => 'required|numeric', ]); if($validate->fails()) { $notify[] = ["error", "$validate->errors()"]; return redirect()->back()->withNotify($notify); } $user = Auth::guard('artisan')->user(); $charges = generate_paystack_charges($request->amount); $payload ['amount'] = $request->amount + $charges; $payload ['email'] = $user->email; $payload ['reference'] = $reference = Str::random(8); $payload ['coin'] = $request->coin; $payUrl = create_payment_url($payload, $request->input()); $dump = $request->input(); $dump['user_id'] = $user->id; DB::table('temp')->insert([ 'payload' => json_encode($dump), 'reference' => $reference ]); $notify[] = ['You will now be redirected to paystack to make payment of ₦" . number_format($request->amount) . "+ ₦" . number_format($charges) . " in order to complete transaction']; return redirect($payUrl)->withNotify($notify); }
7ef99c55d610a7cd855fc058abe217ec
82
dianewan
2023-05-24T20:32:06
good
[ "code" ]
this is my websocket: const server = require("http").createServer(); const options = { cors: true, }; const fs = require('fs'); function userInfo(username, socketid, position = 1) { this.UserId = username; this.SocketId = socketid; this.Position = position; this.active = false; this.joinTime = new Date(); } var activeUsers = []; function saveUsersToFile(users) { const existingUsers = JSON.parse(fs.readFileSync("users.json", "utf-8")); // Combine the existing users with the new users const allUsers = existingUsers.concat(users); // Write the combined list of users back to the file fs.writeFileSync("users.json", JSON.stringify(allUsers)); } let totalUsers = []; try { const data = fs.readFileSync("users.json", "utf8"); totalUsers = JSON.parse(data); } catch (err) { console.error(err); } // console.log('total users' + totalUsers.length); const io = require("socket.io")(server, options); io.on("connection", function (socket) { console.log("Client has connected!"); socket.on("new user", function (data) { socket.userId = data; activeUsers.push(new userInfo(data, socket.id, 0, false)); saveUsersToFile(activeUsers.slice(-1)); // io.emit("new user", [...activeUsers]); var queuePosition = activeUsers .map((object) =&gt; object.SocketId) .indexOf(socket.id) + 1; // socket.broadcast.emit("new user", data, queuePosition) socket.emit("queue position", queuePosition); if (queuePosition != -1) { activeUsers.map((user) =&gt; { if (user.SocketId === socket.id) { user.Position = queuePosition; } return user; }); // ... } socket.broadcast.emit( "user queue", queuePosition, socket.userId, socket.id ); socket.broadcast.emit("user list", activeUsers); console.log("new user " + data + " postion " + queuePosition + ' id' + socket.id); }); socket.on("position check", () =&gt; { var queuePosition = activeUsers .map((object) =&gt; object.SocketId) //.Position .indexOf(socket.id) + 1; console.log("checking pos " + socket.UserId + " " + queuePosition); console.log(activeUsers); if (queuePosition != -1) { socket.emit("queue position", queuePosition); socket.broadcast.emit( "user queue", queuePosition, socket.userId, socket.id ); } }); socket.on("get user list", () =&gt; { socket.emit("user list", activeUsers); }); socket.on("get total users", () =&gt; { socket.emit("totalUsers", totalUsers); }); socket.on('updatedUserList', (data) =&gt; { data.forEach((user, index) =&gt; { user.Position = index + 1; }); activeUsers = data console.log(activeUsers); io.emit('user list', activeUsers); }); socket.on("remove user", (data) =&gt; { const index = activeUsers.findIndex((user) =&gt; user.SocketId === data); activeUsers.splice(index, 1); activeUsers.forEach((user, index) =&gt; { // Update the position of each user based on their current index in the list if (user.Position !== 0) { user.Position = index + 1; } }); io.emit("user list", activeUsers); console.log("user disconnected " + data); console.log(activeUsers); }); socket.on("active user", function (socketId) { const user = activeUsers.find(u =&gt; u.SocketId === socketId); if (user) { user.Position = 0; io.emit("user list", activeUsers); console.log(`User ${user.UserId} is now active.`); } }); socket.on("disconnect", () =&gt; { var index = activeUsers.map((object) =&gt; object.SocketId).indexOf(socket.id); if (index != -1) { activeUsers.splice( activeUsers.map((object) =&gt; object.SocketId).indexOf(socket.id), 1 ); } console.log("user disconnected " + socket.userId); socket.broadcast.emit("user disconnected", socket.id); socket.broadcast.emit("user list", activeUsers); }); }); console.log("Server started."); server.listen(3000); I'm currently having the issue that when the user's phone simply goes to sleep or they leave the browser they get disconnected and I would like disconnection to only happen on tab close or hard refresh. How could I approach this?
42b029dfcf02c70a728f179ed1728b22
83
dianewan
2023-05-24T20:32:23
good
[ "code" ]
what does this function do? void** fun_18001c7d0() { void* rsp1; uint64_t rax2; void** rcx3; void** rax4; void** rax5; void* rsp6; void* rcx7; void* rsp8; struct s18* rcx9; uint64_t rcx10; void** rax11; rsp1 = reinterpret_cast<void*>(reinterpret_cast<int64_t>(__zero_stack_offset()) - 0x78); rax2 = g18006d010; rcx3 = reinterpret_cast<void**>(reinterpret_cast<uint64_t>(rsp1) + 48); rax4 = fun_180024bd0(rcx3, 3, "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47, rcx3, 3, "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47); rax5 = fun_180024fd0(rax4, "This ZeroCopyOutputStream doesn't support aliasing. Reaching here usually means a ZeroCopyOutputStream implementation bug.", "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47, rax4, "This ZeroCopyOutputStream doesn't support aliasing. Reaching here usually means a ZeroCopyOutputStream implementation bug.", "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47); rsp6 = reinterpret_cast<void*>(reinterpret_cast<uint64_t>(rsp1) - 8 + 8 - 8 + 8); rcx7 = reinterpret_cast<void*>(reinterpret_cast<uint64_t>(rsp6) + 32); fun_180024d20(rcx7, rax5, "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47, rcx7, rax5, "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47); rsp8 = reinterpret_cast<void*>(reinterpret_cast<uint64_t>(rsp6) - 8 + 8); rcx9 = reinterpret_cast<struct s18*>(reinterpret_cast<uint64_t>(rsp8) + 48); fun_180024c80(rcx9, rax5, "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47, rcx9, rax5, "C:\\Users\\Chris\\Downloads\\protobuf-cpp-3.8.0\\protobuf-3.8.0\\src\\google\\protobuf\\io\\zero_copy_stream.cc", 47); rcx10 = rax2 ^ reinterpret_cast<uint64_t>(rsp1) ^ reinterpret_cast<uint64_t>(rsp8) - 8 + 8; rax11 = fun_18001ae70(rcx10, rax5, rcx10, rax5); return rax11; }
128ac918a86bc94a02bb90f6169fca9b
84
dianewan
2023-05-24T20:32:29
good
[ "code" ]
as a programmer, please review this code and implement a if statement that will ++ the number of win of the player. While the bot score works, the player score does not <?php $json_data = file_get_contents("data.json"); $cards = json_decode($json_data, true); // Initialize leaderboard $leaderboard = []; $playWins = 0; $botWins= 0; ?> <html> <head> <script> var used_cards = []; var userWins = 0; var botWins = 0; var ties = 0; function generateCards() { var xhr = new XMLHttpRequest(); xhr.open("GET", "data.json", true); xhr.onreadystatechange = function() { if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { var cards = JSON.parse(this.responseText); if (used_cards.length === cards.length) { alert("All the cards have been used. Please reset the game."); return; } var rand_keys = []; do { rand_keys = [Math.floor(Math.random() * cards.length), Math.floor(Math.random() * cards.length)]; } while (used_cards.includes(rand_keys[0]) || used_cards.includes(rand_keys[1])); used_cards.push(rand_keys[0], rand_keys[1]); var card1 = cards[rand_keys[0]]; var card2 = cards[rand_keys[1]]; document.getElementById("card1").innerHTML = "Card 1: " + card1['suit'] + " with ranking " + card1['ranking'] + " and image URL " + card1['path'] + "<br>"; document.getElementById("card2").innerHTML = "Card 2: " + card2['suit'] + " with ranking " + card2['ranking'] + " and image URL " + card2['path'] + "<br>"; document.getElementById("img1").src = card1['path']; document.getElementById("img2").src = card2['path']; var ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]; var random_index_1 = Math.floor(Math.random() * ranks.length); var random_index_2 = Math.floor(Math.random() * ranks.length); var rank_1 = ranks[random_index_1]; var rank_2 = ranks[random_index_2]; if (random_index_1 > random_index_2) { document.getElementById("winner").innerHTML = "The Bot has won: " + card1['suit'] + " " + rank_1 + " is higher than " + card2['suit'] + " " + rank_2 + "."; botWins++; document.getElementById("botWins").innerHTML = "Bot wins: " + botWins; } else if (random_index_1 === random_index_2) { document.getElementById("winner").innerHTML= "It's a draw: " + card1['suit'] + " " + rank_1 + " is equal to " + card2['suit'] + " " + rank_2 + "."; } else { document.getElementById("winner").innerHTML = "The Player has won: " + card1['suit'] + " " + rank_1 + " is lower than " + card2['suit'] + " " + rank_2 + "."; playerWins++; document.getElementById("playerWins").innerHTML = "Player wins: " + playerWins; } } }; xhr.send(); } </script> </head> <body> <div> <button onclick="generateCards()">Generate Cards</button> </div> <br><br> <div> <div id="card1"></div> <div id="card2"></div> <img id="img1" width="100"> <img id="img2" width="100"> </div> <br><br> <div> <div id="user"></div> <div id="bot"></div> </div> <br><br> <div id="result"></div> <br><br> <div> <div id="user-wins"></div> <div id="bot-wins"></div> <div id="ties"></div> </div> </body> </html>
4abca92d224830157e8c715f0e4ecca8
85
dianewan
2023-05-24T20:32:41
good
[ "code" ]
Is this vulnerable to DoS (StackOverflow) via comparison? ``` public class Test1 { final int id; final String name; public Test1(int id, String name) { this.id = id; this.name = name; } @Override public boolean equals(Object o) { return equals(this, o); } public boolean equals(Object a, Object b) { if (a == null || b == null) { return false; } if(Test1.class != a.getClass() || Test1.class != b.getClass()){ return false; } if(((Test1) a).id != ((Test1) b).id || !((Test1) a).name.equals(((Test1) b).name)){ return false; } return (a.equals(b) || a == b); } } ```
12ca24cf242154286e32a223604d067b
86
dianewan
2023-05-24T20:32:59
good
[ "code" ]
<div><p>You are required to implement a user data aggregator using coroutines by implementing an <code>aggregateDataForCurrentUser</code> function.</p> <h3>Requirements</h3> <p>Your task is to resolve and aggregate user details in an <code>aggregateDataForCurrentUser</code> function.</p> <p>You have APIs for resolving user details (<code>UserEntity</code>), user comments (<code>List&lt;CommentEntity&gt;</code>) and friends suggestions (<code>List&lt;FriendEntity&gt;</code>).</p> <p>To resolve current user details, call the <code>resolveCurrentUser</code> function. To resolve user comments, call <code>fetchUserComments</code> with <code>id</code> resolved from <code>UserEntity.id</code>. To resolve user friends suggestions, call <code>fetchSuggestedFriends</code> with <code>id</code> resolved from <code>UserEntity.id</code>.</p> <p>All of these functions are suspend functions; they need to be invoked in some coroutine context.</p> <p>Implement functions in <code>AggregateUserDataUseCase</code>, where <code>aggregateDataForCurrentUser</code> must satisfy the following requirements:</p> <ol> <li>When <code>resolveCurrentUser</code> throws an error, forward the exception.</li> <li>When <code>resolveCurrentUser</code> returns <code>UserEntity</code>, call <code>fetchUserComments</code> and <code>fetchSuggestedFriends</code> and then aggregate the results into <code>AggregatedData</code>.</li> <li>When <code>fetchUserComments</code> call takes longer than 2000ms, return an empty comments list.</li> <li>When <code>fetchUserComments</code> throws an exception, return an empty comments list.</li> <li>When <code>fetchSuggestedFriends</code> call takes longer than 2000ms, return an empty friends suggestions list.</li> <li>When <code>fetchSuggestedFriends</code> throws an exception, return an empty friends suggestions list.</li> </ol> <p>And for <code>AggregateUserDataUseCase.close</code>:</p> <ul> <li>When <code>close</code> is invoked, cancel all ongoing coroutine calls.</li> </ul> <h3>Hints</h3> <ul> <li>You may create additional <code>CoroutineScope</code> inside <code>AggregateUserDataUseCase</code> to handle cancellation when <code>AggregateUserDataUseCase.close</code> is invoked.</li> </ul> <h3>Classes accompanying <code>AggregateUserDataUseCase</code></h3> <pre><code>package coroutines data class AggregatedData( val user: UserEntity, val comments: List&lt;CommentEntity&gt;, val suggestedFriends: List&lt;FriendEntity&gt; ) typealias UserId = String data class UserEntity(val id: UserId, val name: String) data class CommentEntity(val id: String, val content: String) data class FriendEntity(val id: String, val name: String) </code></pre> <h3>Available packages/libraries</h3> <ul> <li>'org.jetbrains.kotlin:kotlin-stdlib:1.4.20'</li> <li>'org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.4.2'</li> </ul></div> i want all the text in p tag
531a5dd7a372345711570efddde99356
87
dianewan
2023-05-24T20:33:20
bad
[]
Explain this code to me. def _filter_pixels(self, gray): for i in range ( self . dist_tau , len ( gray ) - self . dist_tau ): for j in range(self.dist_tau, len(gray[0]) - self.your_dist): if gray[i, j] == 0: continue if (gray[i, j] - gray[i + self.your_dist, j] &gt; self.intensity_threshold and gray[i, j] - gray[i - self.dist_tau, j] &gt; self.intensity_threshold): continue if (gray[i, j] - gray[i, j + self.dist_tau] &gt; self.intensity_thresholdandgray[i, j] -gray[i, j-self.dist_tau] &gt;self.intensity_threshold): continue gray[i, j] = 0 return gray
b1743c3aa58ec82b54f1291a9b2490df
88
dianewan
2023-05-24T20:33:26
good
[ "code" ]
please explain the following code: import { CATEGORIES_EN_US, PRODUCTS_EN_US } from 'App/constants/collections' import { getCollection } from 'App/utils/firestore' import { Parser } from 'json2csv'; (async () => { const products = await getCollection({ collection: PRODUCTS_EN_US }) const categories = await getCollection({ collection: CATEGORIES_EN_US }) const vtexCategoriesMap = { 'Serums & Treatments': 1200, 'Masks': 1300, 'Cleansers': 1400, 'Essence & Toners': 1500, 'Eye Care': 1600, 'Face Oils': 1700, 'Face': 2100, 'Eyes': 2200, 'Lips': 2300, 'Makeup Removers': 2400, 'Moisturizers': 3100, 'Body Wash & Scrubs': 3200, 'Hair Care': 3300, 'Sun Protection': 3400, 'Hand Care': 3500 } let categoryMap = {} const mapChildCategoryIdsToNames = categories => { categories.map(category => { if (category?.children?.length) { for (const childCategory of category.children) { if (childCategory.categoryId) { categoryMap[childCategory.categoryId] = childCategory.name } } } }) return categoryMap } const mappedCategories = mapChildCategoryIdsToNames(categories) const assignVtexCategoryId = product => product?.categories?.map(productCategoryId => { if (productCategoryId in mappedCategories) { if (mappedCategories[productCategoryId] in vtexCategoriesMap) { product.vtexCategoryId = vtexCategoriesMap[mappedCategories[productCategoryId]] } } }) const fields = [ 'id', 'sku', 'parentSku', 'productId', 'typeId', 'draft', 'vtexCategoryId', 'title', 'description', 'simpleDescription', 'metaDescription', 'metaTitle', 'shortDescription', 'howToUse', 'ingredients.fullIngredients', 'ingredients.activeIngredients', 'ingredients.afterIngredients', 'ingredients.keyIngredients', 'image.altText', 'image.imageUrl', 'image.bundledSkuInterruptImageUrl', 'image.bundledSkuInterruptImageAltText', 'safetyFirstMessage', 'barcode', 'inStock', 'certifications', 'isShippable', 'price', 'specialPrice', 'specialPriceFrom', 'specialPriceTo', 'CV', 'PV', 'QV', 'SV', 'hostValue', 'flags', 'widgets', 'hideFromEnrollingConsultant', 'visibility', 'bestFor', 'bestSeller', 'barcode', 'categories', 'parentCategoryIds', 'positions', 'doNotShipAlone', 'googleProductCategory', 'handle', 'hideFromEnrollingConsultant', 'includeInProductFeed', 'isGWP', 'maxQuantity', 'metaDescription', 'recyclingInfo', 'newFrom', 'newTo', 'notCrawlable', 'disableProductDetailPage', 'preOrder', 'preOrderConsultant', 'stockNotify', 'taxClass', 'upSellIds', 'swatches.colorHexCode', 'swatches.position', 'swatches.swatchlabel', 'productVolume', 'size', 'weight', 'galleryImages', 'isFinalSaleConfig', 'isVirtual', 'autoshipEligible', 'autoshipFrequency', 'autoshipPeriod', 'altPromotion', 'productVariety', 'information.info', 'information.infoList', 'enrollmentLabel', 'enrollmentValue', 'video.videoLink', 'altVideo' ]; const options = { fields }; const parser = new Parser(options); const productsForExport = []; products.map(product => { const allVariantsDisabled = (product.variants && product.variants.every(variant => variant.draft === true)) if (product.draft === false || (product.draft === false && !allVariantsDisabled)) { const { variants, visibility, flags } = product; if (product.image && product.image.gallery && product.image.gallery.length) { product.galleryImages = product.image.gallery.map(galleryImage => `sortOrder: ${galleryImage.sortOrder}, url: ${galleryImage.url}`) } if (product.information && product.information.infoList && product.information.infoList.length) { product.information.infoList = product.information.infoList.map(infoListEntry => `ordinal: ${infoListEntry.ordinal}, lineInfo: ${infoListEntry.lineInfo}`) } product.enrollmentLabel = product.label product.enrollmentValue = product.value assignVtexCategoryId(product) productsForExport.push(product); if (variants && variants.length) { variants.map(variant => { if (variant.draft === false) { productsForExport.push({ ...variant, flags, visibility, parentSku: product.sku }) } }); } } }); const csv = parser.parse(productsForExport); console.info(csv) })()
d9de172ac159c949a63c76a1fb308c31
89
dianewan
2023-05-24T20:33:42
good
[ "code" ]
This is a demo task. Write a function: class Solution { public int solution(int[] A); } that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
609ca66dea05cae0acd7b38cd99d9ec6
9
DaehanKim
2023-05-29T06:37:38
good
[ "code" ]
This is a demo task. Write a function: class Solution { public int solution(int[] A); } that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
609ca66dea05cae0acd7b38cd99d9ec6
9
dianewan
2023-05-23T23:26:39
good
[ "code" ]
This is a demo task. Write a function: class Solution { public int solution(int[] A); } that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].
609ca66dea05cae0acd7b38cd99d9ec6
9
nazneen
2023-06-01T00:40:05
good
[]
Check code below and move the marker when I press arrow keys on keyboard: var map = L.map('map').setView([0, 0], 1); var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', { maxZoom: 17, attribution: 'Map data: © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: © <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)' }).addTo(map)
c122064421796124c8d4e92286772111
90
dianewan
2023-05-24T20:34:09
bad
[]
binding.tvSearch.doAfterTextChanged { if (it.toString().isNotEmpty()) { val text = it.toString() timer.cancel() timer = Timer() timer.schedule( object : TimerTask() { override fun run() { runOnUiThread { fetchData(text) } } }, DELAY ) } } this fetchData(text) called everytime user finish typing, example user want to search BUDI, but after type B the fetch data called. i want that code executed only after user finish typing
baa754b0ac9c74162e8a9fc1b87ef84a
91
dianewan
2023-05-24T20:34:22
good
[ "code" ]
Change this python depth-first search algorithm to a breadth-first search algorithm: def dfs(self, target): stack = Stack() stack.push(self.position) path = [] while not stack.is_empty(): coordinate = stack.pop() if coordinate in path: continue path.append(coordinate) if coordinate is target: break surroundings = self.get_surrounding_coordinates_from_coordinate(coordinate).values() surrounding_coordinates_which_are_known = set(surroundings).intersection(self.visited) surroundings_not_already_in_stack = [i for i in surrounding_coordinates_which_are_known if i not in stack.list] for neighbor in surroundings_not_already_in_stack: stack.push(neighbor) return path
a8b4a9fca53754a2f006fdfd61ae9c16
92
dianewan
2023-05-24T20:34:29
good
[ "code" ]
Knowing this: class VPCResponse(BaseModel): id: str tenant_id: Optional[str] name: Optional[str] description: Optional[str] router_id: Optional[str] external_network: Optional[str] network_id: str subnets: Optional[list[str]] = [] security_groups: Optional[list[str]] = [] is_default: Optional[bool] class Config: allow_population_by_field_name = True Implement tests for this function: class VPCsClient: async def get_vpc_detailed( self, tenant_id: str, vpc_id: str ) -> VPCResponse: try: response = await request( method="GET", url=f"{self.base_url}/v0/vpcs/{vpc_id}", headers={"X-Tenant-ID": tenant_id}, ) json_response = await response.json() except Exception as exc: raise InternalError(message=str(exc)) from exc if response.status == status.HTTP_404_NOT_FOUND: raise NotFound(await response.text()) elif response.status != status.HTTP_200_OK: raise InternalError(await response.text()) return VPCResponse.parse_raw(json_response) Following this standard: @pytest.mark.asyncio async def test_create_vpc_success(client, mock_request): expected_response = "1234" response_text = '{"id": "1234"}' response = MockedHTTPResponse(status=201, text=response_text) mock_request.return_value = response actual_response = await client.create_vpc( tenant_id="abcd", desired_name="vpc1", description="description", subnetpool_id="5678" ) mock_request.assert_called_once_with( method="POST", url="https://example.com/v0/xaas/vpcs", headers={"X-Tenant-ID": "abcd"}, body={ "name": "vpc1", "description": "description", "subnetpool_id": "5678" } ) assert actual_response == expected_response
6c81bf4dad22fe2ea24615989763cc18
93
dianewan
2023-05-24T23:47:34
good
[ "code" ]
Please explain the following source code: public Vector2Int ToHexGrid(Vector2 position) { // Convert to hex grid coordinates float x = position.x / (HexMetrics.innerRadius * 2f); float y = -x; float offset = position.y / (HexMetrics.outerRadius * 3f); x -= offset; y -= offset; int iX = Mathf.RoundToInt(x); int iY = Mathf.RoundToInt(y); int iZ = Mathf.RoundToInt(-x - y); if (iX + iY + iZ != 0) { float dX = Mathf.Abs(x - iX); float dY = Mathf.Abs(y - iY); float dZ = Mathf.Abs(-x - y - iZ); if (dX > dY && dX > dZ) { iX = -iY - iZ; } else if (dZ > dY) { iZ = -iX - iY; } } return new Vector2Int(iX, iZ); } public static class HexMetrics { public const float outerRadius = 10f; public const float innerRadius = outerRadius * 0.866025404f; }
0ca9c11cc31f69afcd4ea1da85659d2a
94
dianewan
2023-05-24T23:47:41
good
[ "code" ]
What do you think about this code ? : from bottle import route, run, template from tools import addCalc @route('/') def home(): return '<b>Homepage</b>!' @route('/hello/<name>') def index(name): return template('<b>Hello {{name}}</b>!', name=name) @route('/add/<a>/<b>') def add(a, b): result = addCalc(a, b) return { "result": result } run(host='localhost', port=8080, reloader=True)
ea5784d1ad4af5480511621f86f36bb3
95
dianewan
2023-05-24T23:47:47
good
[ "code" ]
What does the following code do? def create_function(n0, hl): return lambda t: n0*np.power(1/2, t/hl) class HalfLife: def __init__(self, hl, max): self.hl = hl self.max = max self.data = np.zeros(max) self.x = np.arange(0, self.max, 1) def add(self, time, n0): f = create_function(n0, self.hl) base = np.vectorize(f)(self.x) self.data = self.data + np.concatenate((np.zeros(time), base))[:self.max] def show(self): fig = px.line(x=self.x, y=self.data, labels={'x': "Hour", 'y': "mg"}) fig.update_layout( hovermode="x unified", template = 'plotly_dark', xaxis = dict( title_text="Hours", dtick = 24, showspikes=True ), yaxis = dict( title_text="mg", showspikes=True )) fig.show()
0ecb2f3413dcade33a8bf30823fb7744
96
dianewan
2023-05-24T23:47:52
good
[ "code" ]
refactor this c code snippet, don't use bool, and keep cls void removed(char list[MAXN][21], int *pn) { search(list, pn); printf("Which Name you want to removed?(input a number) : "); int del, i; scanf("%d", &amp;del); if (del &gt;= 0 &amp;&amp; del &lt; *pn) { for (i = del + 1; i &lt; *pn; i++) strcpy(list[i - 1], list[i]); printf("Removed!\n"); (*pn)--; } else printf("UnRemoved!\n"); system("cls"); }
26853064cf8eee514a109bea11281abc
97
dianewan
2023-05-24T23:48:05
good
[ "code" ]
is the following sqlalchemy code in python valid? res = Session.query(text('SELECT COUNT(*)')).from_statement(text('SELECT COUNT(*) FROM :table WHERE :column IS NULL;').params(table=table, column=column))
d58610e98d4f43eacc989f06067fd244
98
dianewan
2023-05-24T23:48:11
good
[ "code" ]
what this code ? /** DRIVER APP Version 1.8.0 */ var ajax_url= krms_driver_config.ApiUrl ; var dialog_title_default= krms_driver_config.DialogDefaultTitle; var search_address; var ajax_request = []; var networkState; var reload_home; var translator; var ajax_request2; var ajax_request3; var map; var watchID; var app_running_status='active'; var push; var device_platform; var app_version = "1.8.0"; var map_bounds; var map_marker; var map_style = [ {stylers: [ { "saturation":-100 }, { "lightness": 0 }, { "gamma": 1 } ]}]; var exit_cout = 0; var device_id = 'device_01231'; var $handle_location = []; var $cron_interval = 10*1000; var ajax_task; var ajax_timeout = 50000; var ajax_new_task; var timer = {}; var map_navigator = 0; var bgGeo; jQuery.fn.exists = function(){return this.length&gt;0;} function dump(data) { console.debug(data); } dump2 = function(data) { alert(JSON.stringify(data)); }; function setStorage(key,value) { localStorage.setItem(key,value); } function getStorage(key) { return localStorage.getItem(key); } function removeStorage(key) { localStorage.removeItem(key); } function explode(sep,string) { var res=string.split(sep); return res; } function urlencode(data) { return encodeURIComponent(data); } empty = function(data) { if (typeof data === "undefined" || data==null || data=="" || data=="null" || data=="undefined" ) { return true; } return false; } function isDebug() { var debug = krms_driver_config.debug; if(debug){ return true; } return false; } function hasConnection() { return true; } $( document ).on( "keyup", ".numeric_only", function() { this.value = this.value.replace(/[^0-9\.]/g,''); }); /*START DEVICE READY*/ document.addEventListener("deviceready", function() { try { navigator.splashscreen.hide(); device_platform = device.platform; document.addEventListener("offline", noNetConnection, false); document.addEventListener("online", hasNetConnection, false); document.addEventListener("pause", onBackgroundMode, false); document.addEventListener("resume", onForegroundMode, false); initFirebasex(); } catch(err) { alert(err.message); } }, false); /*END DEVICE READY*/ // set device ons.platform.select('android'); //ons.platform.select('ios'); /*onsen ready*/ ons.ready(function() { if (ons.platform.isIPhoneX()) { document.documentElement.setAttribute('onsflag-iphonex-portrait', ''); $('head').append(''); } if (isDebug()){ setStorage("device_id","device_1233456789"); device_platform = "Android"; } setStorage('camera_on', 2 ); ons.setDefaultDeviceBackButtonListener(function(event) { exit_cout++; if(exit_cout&lt;=1){ toastMsg( getTrans("Press once again to exit!","exit") ); setTimeout(function(){ exit_cout=0; }, 3000); } else { if (navigator.app) { navigator.app.exitApp(); } else if (navigator.device) { navigator.device.exitApp(); } else { window.close(); } } }); }); /*end ready*/
679c52d5388072fcffd53da9ff3b5f7c
99
dianewan
2023-05-24T23:48:19
good
[ "code" ]
Act as an marketing copywriting expert. I am going to give you a company description, and you will give me 3 brief, cold open emails that are less than 60 words long. The goal of each email is to prompt a response and encourage them to try the company's service. Company Description: OpenSend is an AI-driven lead generation platform that discovers the email addresses of a website's anonymous visitors for the purpose of email list building and remarketing. Customer conversion rate of the collected email addresses is 10x higher than standard web retargeting techniques. Standard retargeting conversion rates are 2-4%, and OpenSend leads convert at closer to 15%.
d39d68f06dbd1afcc8629a99d1e5bfee
0
edbeeching
2023-05-22T09:37:49
good
[]
Act as an marketing copywriting expert. I am going to give you a company description, and you will give me 3 brief, cold open emails that are less than 60 words long. The goal of each email is to prompt a response and encourage them to try the company's service. Company Description: OpenSend is an AI-driven lead generation platform that discovers the email addresses of a website's anonymous visitors for the purpose of email list building and remarketing. Customer conversion rate of the collected email addresses is 10x higher than standard web retargeting techniques. Standard retargeting conversion rates are 2-4%, and OpenSend leads convert at closer to 15%.
d39d68f06dbd1afcc8629a99d1e5bfee
0
lewtun
2023-05-22T09:32:29
good
[]
Act as an marketing copywriting expert. I am going to give you a company description, and you will give me 3 brief, cold open emails that are less than 60 words long. The goal of each email is to prompt a response and encourage them to try the company's service. Company Description: OpenSend is an AI-driven lead generation platform that discovers the email addresses of a website's anonymous visitors for the purpose of email list building and remarketing. Customer conversion rate of the collected email addresses is 10x higher than standard web retargeting techniques. Standard retargeting conversion rates are 2-4%, and OpenSend leads convert at closer to 15%.
d39d68f06dbd1afcc8629a99d1e5bfee
0
osanseviero
2023-05-22T14:23:57
good
[ "system" ]
imagine you are a dating expert, i will tell you some interest a girl in her 20s has and you will have to predict some other interest the girl is most likely to have
f2ace018ef3045ef9006ca555b1650b8
1
edbeeching
2023-05-22T09:40:02
bad
[]
imagine you are a dating expert, i will tell you some interest a girl in her 20s has and you will have to predict some other interest the girl is most likely to have
f2ace018ef3045ef9006ca555b1650b8
1
lewtun
2023-05-22T09:32:37
bad
[]
imagine you are a dating expert, i will tell you some interest a girl in her 20s has and you will have to predict some other interest the girl is most likely to have
f2ace018ef3045ef9006ca555b1650b8
1
nazneen
2023-05-23T22:52:01
bad
[]
What happens if you disturb the mummy of a pharaoh?
c61dd88e94ed9c80fe8aedf139a68ff7
10
dianewan
2023-05-23T23:25:19
good
[ "plugins" ]
What happens if you disturb the mummy of a pharaoh?
c61dd88e94ed9c80fe8aedf139a68ff7
10
edbeeching
2023-05-22T09:43:25
good
[]
What happens if you disturb the mummy of a pharaoh?
c61dd88e94ed9c80fe8aedf139a68ff7
10
lewtun
2023-05-22T09:37:57
bad
[]
create a diet plan for a north indian vegetarian that is like the mediterranean diet but uses indian foods spices and recipes
ce168794e3edd8dfd0cc5cf24b9745d9
100
Shayne
2023-05-26T22:58:47
good
[]
create a diet plan for a north indian vegetarian that is like the mediterranean diet but uses indian foods spices and recipes
ce168794e3edd8dfd0cc5cf24b9745d9
100
dianewan
2023-05-27T18:06:46
good
[ "plugins" ]
create a diet plan for a north indian vegetarian that is like the mediterranean diet but uses indian foods spices and recipes
ce168794e3edd8dfd0cc5cf24b9745d9
100
lcipolina
2023-05-26T23:04:04
good
[]
I am developing a jetbrains plugin. I will tell you the requirements one by one. Based on them, please help me by providing code for the same in Java.
582e4ce2f9ca3a7a1452c55fd41b6b74
101
Shayne
2023-05-26T22:58:58
bad
[]
I am developing a jetbrains plugin. I will tell you the requirements one by one. Based on them, please help me by providing code for the same in Java.
582e4ce2f9ca3a7a1452c55fd41b6b74
101
dianewan
2023-05-27T18:07:17
bad
[]
I am developing a jetbrains plugin. I will tell you the requirements one by one. Based on them, please help me by providing code for the same in Java.
582e4ce2f9ca3a7a1452c55fd41b6b74
101
lcipolina
2023-05-27T16:17:40
good
[ "code" ]
make a form for a patient of a nutritionist to fill out
7174c62eb67dea0145a730861c3ce385
102
Shayne
2023-05-26T22:59:06
good
[]
make a form for a patient of a nutritionist to fill out
7174c62eb67dea0145a730861c3ce385
102
dianewan
2023-05-27T18:07:53
good
[ "plugins" ]
make a form for a patient of a nutritionist to fill out
7174c62eb67dea0145a730861c3ce385
102
lcipolina
2023-05-27T16:17:47
good
[]