row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
9,239
I have an dataset about climate change. With values for dt, AverageTemperature, AverageTemperatureUncertainty (don't use this colomn) and Country. *dt stand for date of the day that the temperature occurred in yyyy-mm-dd I want to plot the values of the average temperature of "Netherlands (Europe)" over the period of 1850-2010 in the programming language R. Use Boxplots to plot every 40 years write in one text and only use the ggplot2 package
a6f6a89debcb5fdf7069c2294d067fd6
{ "intermediate": 0.5166733264923096, "beginner": 0.24623195827007294, "expert": 0.2370947003364563 }
9,240
hi
9504a4a2a662ee20950f3d1b4981469c
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
9,241
how to use ipwidgets to create a dropdown box and trigger a function
84279d0b648b22a64e3fe4d9dccba94d
{ "intermediate": 0.5418834090232849, "beginner": 0.3027693033218384, "expert": 0.15534722805023193 }
9,242
how to test this code using kotlin Lincheck library package devnovikov.lincheck.account import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.channels.actor class AccountSafe8 { private val actor = CoroutineScope(Dispatchers.IO).accountActor() suspend fun modify(difference: Double) { actor.send(IncOperation(difference)) } suspend fun get(): Double { val response = CompletableDeferred<Double>() actor.send(GetOperation(response)) return response.await() } // Message types for counterActor sealed class AccountMsg class IncOperation(val difference: Double) : AccountMsg() // one-way message to increment counter class GetOperation(val response: CompletableDeferred<Double>) : AccountMsg() // a request with reply // This function launches a new counter actor private fun CoroutineScope.accountActor() = actor<AccountMsg> { var balance = 0.0 // actor state for (msg in channel) { // iterate over incoming messages when (msg) { is IncOperation -> balance += msg.difference is GetOperation -> msg.response.complete(balance) } } } }
556223422a0d1d2a19135aabd8fa05ca
{ "intermediate": 0.5865831971168518, "beginner": 0.24022410809993744, "expert": 0.17319272458553314 }
9,243
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> typedef enum { BEAR, BIRD, PANDA} AnimalType; typedef enum { ALIVE, DEAD } AnimalStatus; typedef struct { int x; int y; } Location; typedef enum { FEEDING, NESTING, WINTERING } SiteType; typedef struct { /** animal can be DEAD or ALIVE*/ AnimalStatus status; /** animal type, bear, bird, panda*/ AnimalType type; /** its location in 2D site grid*/ Location location; } Animal; /*example usage*/ Animal bird, bear, panda; /** type of Hunter*/ typedef struct { /** points indicate the number of animals, a hunter killed*/ int points; /** its location in the site grid*/ Location location; } Hunter; /** type of a site (a cell in the grid)*/ typedef struct { /** array of pointers to the hunters located at this site*/ Hunter **hunters; /** the number of hunters at this site*/ int nhunters; /** array of pointers to the animals located at this site*/ Animal **animals; /** the number of animals at this site*/ int nanimals; /** the type of site*/ SiteType type; } Site; /** 2D site grid*/ typedef struct { /** number of rows, length at the x-coordinate*/ int xlength; /** number of columns, length at the y-coordinate*/ int ylength; /** the 2d site array*/ Site **sites; } Grid; /* initial grid, empty*/ Grid grid = {0, 0, NULL}; /** * @brief initialize grid with random site types * @param xlength * @param ylength * @return Grid */ Grid initgrid(int xlength, int ylength) { grid.xlength = xlength; grid.ylength = ylength; grid.sites = (Site **)malloc(sizeof(Site *) * xlength); for (int i = 0; i < xlength; i++) { grid.sites[i] = (Site *)malloc(sizeof(Site) * ylength); for (int j = 0; j < ylength; j++) { grid.sites[i][j].animals = NULL; grid.sites[i][j].hunters = NULL; grid.sites[i][j].nhunters = 0; grid.sites[i][j].nanimals = 0; double r = rand() / (double)RAND_MAX; SiteType st; if (r < 0.33) st = WINTERING; else if (r < 0.66) st = FEEDING; else st = NESTING; grid.sites[i][j].type = st; } } return grid; } /** * @brief * */ void deletegrid() { for (int i = 0; i < grid.xlength; i++) { free(grid.sites[i]); } free(grid.sites); grid.sites = NULL; grid.xlength = -1; grid.ylength = -1; } /** * @brief prints the number animals and hunters in each site * of a given grid * @param grid */ void printgrid() { for (int i = 0; i < grid.xlength; i++) { for (int j = 0; j < grid.ylength; j++) { Site *site = &grid.sites[i][j]; int count[3] = {0}; /* do not forget to initialize*/ for (int a = 0; a < site->nanimals; a++) { Animal *animal = site->animals[a]; count[animal->type]++; } printf("|%d-{%d, %d, %d}{%d}|", site->type, count[0], count[1], count[2], site->nhunters); } printf("\n"); } } /** * @brief prints the info of a given site * */ void printsite(Site *site) { int count[3] = {0}; /* do not forget to initialize*/ for (int a = 0; a < site->nanimals; a++) { Animal *animal = site->animals[a]; count[animal->type]++; } printf("|%d-{%d,%d,%d}{%d}|", site->type, count[0], count[1], count[2], site->nhunters); } /** * @brief it moves a given hunter or animal * randomly in the grid * @param args is an animalarray * @return void* */ void *simulateanimal(void *args) { Animal *animal = (Animal *)args; while (animal->status == ALIVE) { int current_x = animal->location.x; int current_y = animal->location.y; Site *current_site = &grid.sites[current_x][current_y]; // Check if the animal is at the NESTING site if (current_site->type == NESTING) { // Populate 1 animal of its kind at the nesting site Animal *new_animal = (Animal *)malloc(sizeof(Animal)); new_animal->type = animal->type; new_animal->status = ALIVE; new_animal->location.x = current_x; new_animal->location.y = current_y; // Add the new animal to the current site current_site->animals = (Animal **)realloc(current_site->animals, sizeof(Animal *) * (current_site->nanimals + 1)); current_site->animals[current_site->nanimals] = new_animal; current_site->nanimals++; // Choose a random direction to move int dx = rand() % 3 - 1; // -1, 0, 1 int dy = rand() % 3 - 1; // -1, 0, 1 int new_x = current_x + dx; int new_y = current_y + dy; // Ensure the new position is within the grid bounds if (new_x < 0 || new_x >= grid.xlength || new_y < 0 || new_y >= grid.ylength) continue; Site *new_site = &grid.sites[new_x][new_y]; // Update the site's animal array with the new position new_site->animals = (Animal **)realloc(new_site->animals, sizeof(Animal *) * (new_site->nanimals + 1)); new_site->animals[new_site->nanimals] = animal; new_site->nanimals++; // Remove the animal from the current site for (int i = 0; i < current_site->nanimals; i++) { if (current_site->animals[i] == animal) { for (int j = i; j < current_site->nanimals - 1; j++) { current_site->animals[j] = current_site->animals[j + 1]; } current_site->nanimals--; break; } } // Update the animal's location animal->location.x = new_x; animal->location.y = new_y; } else if (current_site->type == WINTERING) { // Check if the animal dies with 0.5 probability double r = rand() / (double)RAND_MAX; if (r < 0.5) { animal->status = DEAD; break; } // Choose a random direction to move int dx = rand() % 3 - 1; // -1, 0, 1 int dy = rand() % 3 - 1; // -1, 0, 1 int new_x = current_x + dx; int new_y = current_y + dy; // Ensure the new position is within the grid bounds if (new_x < 0 || new_x >= grid.xlength || new_y < 0 || new_y >= grid.ylength) continue; Site *new_site = &grid.sites[new_x][new_y]; // Update the site's animal array with the new position new_site->animals = (Animal **)realloc(new_site->animals, sizeof(Animal *) * (new_site->nanimals + 1)); new_site->animals[new_site->nanimals] = animal; new_site->nanimals++; // Remove the animal from the current site for (int i = 0; i < current_site->nanimals; i++) { if (current_site->animals[i] == animal) { for (int j = i; j < current_site->nanimals - 1; j++) { current_site->animals[j] = current_site->animals[j + 1]; } current_site->nanimals--; break; } } // Update the animal's location animal->location.x = new_x; animal->location.y = new_y; } else if (current_site->type == FEEDING) { // Check if the animal moves with 0.8 probability double r = rand() / (double)RAND_MAX; if (r < 0.8) { // Choose a random direction to move int dx = rand() % 3 - 1; // -1, 0, 1 int dy = rand() % 3 - 1; // -1, 0, 1 int new_x = current_x + dx; int new_y = current_y + dy; // Ensure the new position is within the grid bounds if (new_x < 0 || new_x >= grid.xlength || new_y < 0 || new_y >= grid.ylength) continue; Site *new_site = &grid.sites[new_x][new_y]; // Update the site's animal array with the new position new_site->animals = (Animal **)realloc(new_site->animals, sizeof(Animal *) * (new_site->nanimals + 1)); new_site->animals[new_site->nanimals] = animal; new_site->nanimals++; // Remove the animal from the current site for (int i = 0; i < current_site->nanimals; i++) { if (current_site->animals[i] == animal) { for (int j = i; j < current_site->nanimals - 1; j++) { current_site->animals[j] = current_site->animals[j + 1]; } current_site->nanimals--; break; } } // Update the animal's location animal->location.x = new_x; animal->location.y = new_y; } } usleep(1000); // Sleep for 1 millisecond } return NULL; } /** * @brief simulates the moving of a hunter * * @param args * @return void* */ void *simulatehunter(void *args) { Hunter *hunter = (Hunter *)args; while (1) { int current_x = hunter->location.x; int current_y = hunter->location.y; Site *current_site = &grid.sites[current_x][current_y]; // Choose a random direction to move int dx = rand() % 3 - 1; // -1, 0, 1 int dy = rand() % 3 - 1; // -1, 0, 1 int new_x = current_x + dx; int new_y = current_y + dy; // Ensure the new position is within the grid bounds if (new_x < 0 || new_x >= grid.xlength || new_y < 0 || new_y >= grid.ylength) continue; Site *new_site = &grid.sites[new_x][new_y]; // Kill all the animals in the new site for (int i = 0; i < new_site->nanimals; i++) { Animal *animal = new_site->animals[i]; animal->status = DEAD; } new_site->nanimals = 0; // Increase the hunter's kill count hunter->points += new_site->nanimals; // Update the hunter's location hunter->location.x = new_x; hunter->location.y = new_y; usleep(1000); // Sleep for 1 millisecond } return NULL; } /** * the main function for the simulation */ int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: ./main <number_of_hunters>\n"); return 1; } int nhunters = atoi(argv[1]); if (nhunters < 0) { printf("Number of hunters must be non-negative.\n"); return 1; } // Initialize the grid int xlength = 3; // Modify as needed int ylength = 3; // Modify as needed initgrid(xlength, ylength); // Initialize the animals bird.type = BIRD; bird.status = ALIVE; bird.location.x = rand() % xlength; bird.location.y = rand() % ylength; bear.type = BEAR; bear.status = ALIVE; bear.location.x = rand() % xlength; bear.location.y = rand() % ylength; panda.type = PANDA; panda.status = ALIVE; panda.location.x = rand() % xlength; panda.location.y = rand() % ylength; // Initialize the hunters Hunter **hunters = (Hunter **)malloc(sizeof(Hunter *) * nhunters); for (int i = 0; i < nhunters; i++) { hunters[i] = (Hunter *)malloc(sizeof(Hunter)); hunters[i]->points = 0; hunters[i]->location.x = rand() % xlength; hunters[i]->location.y = rand() % ylength; } // Create threads for animal simulation pthread_t animal_threads[3]; pthread_create(&animal_threads[0], NULL, simulateanimal, (void *)&bird); pthread_create(&animal_threads[1], NULL, simulateanimal, (void *)&bear); pthread_create(&animal_threads[2], NULL, simulateanimal, (void *)&panda); // Create threads for hunter simulation pthread_t *hunter_threads = (pthread_t *)malloc(sizeof(pthread_t) * nhunters); for (int i = 0; i < nhunters; i++) { pthread_create(&hunter_threads[i], NULL, simulatehunter, (void *)hunters[i]); } // Sleep for 1 second sleep(1); // Set animal status to DEAD to terminate their threads bird.status = DEAD; bear.status = DEAD; panda.status = DEAD; // Join animal threads pthread_join(animal_threads[0], NULL); pthread_join(animal_threads[1], NULL); pthread_join(animal_threads[2], NULL); // Wait for hunter threads to finish for (int i = 0; i < nhunters; i++) { pthread_join(hunter_threads[i], NULL); } // Print the final grid printgrid(); // Cleanup deletegrid(); for (int i = 0; i < nhunters; i++) { free(hunters[i]); } free(hunters); free(hunter_threads); return 0; } ADD SYNCHRONIZATION
4e00bd1bbcde42341ab85c16dc28a1ab
{ "intermediate": 0.3914772868156433, "beginner": 0.41549810767173767, "expert": 0.19302453100681305 }
9,244
hello
efffc1c499a1df4f19ee976645bfff4f
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
9,245
Write C++ code implementing the snake game
f1255b245d765ece29902c98e4d24897
{ "intermediate": 0.37266212701797485, "beginner": 0.32126256823539734, "expert": 0.30607539415359497 }
9,246
I want to write a vba code that will copy only the rows that contain values from column E, column F, column G in sheet 'Reminders' starting from row 23 and paste into sheet 'Events' starting in the first empty cell of Column A, and pasting the data in the following order on the same row. E from sheet 'Reminder' to C in sheet 'Events', F from sheet 'Reminder' to A in sheet 'Events', G from sheet 'Reminder' to D in sheet 'Events'. It will then move on to the next row and do the same.
a9856085e2f45702e794212700c56f57
{ "intermediate": 0.502596378326416, "beginner": 0.15576529502868652, "expert": 0.34163832664489746 }
9,247
Write a simple program in Commodore 64 BASIC that, when run, will display the text "Hello world!" in green.
de2451a99ae6d664a711cdcf0206f920
{ "intermediate": 0.36059117317199707, "beginner": 0.3183706998825073, "expert": 0.3210380971431732 }
9,248
how i use adclony with kotlin and xml sdk 4.6.0 allcode plz
19c9fa8e588474401ef741433efc778a
{ "intermediate": 0.5972046256065369, "beginner": 0.21103087067604065, "expert": 0.1917644739151001 }
9,249
how i use adclony with kotlin and xml sdk 4.8.0 allcode plz
00c6275bf216cd32b29fbadb374cb1f2
{ "intermediate": 0.5954263210296631, "beginner": 0.21046344935894012, "expert": 0.1941102147102356 }
9,250
hot to kill process in windows task manager using c++
4238d5005202f3b0a9d3dd6ed8590e57
{ "intermediate": 0.3789394199848175, "beginner": 0.3086194396018982, "expert": 0.3124411404132843 }
9,251
I want to build a GCN model for graph classification on my EEG dataset. I will be using 19 electrodes as my nodes ( without any node feature vector) and coherence between these nodes as edge weight (in six different frequency bands so we have six numbers between each pair of nodes). I've got 7 different adjacency matrices for 6 various mental disorders and a healthy control group. an adjacency matrix is in numpy arrray format which is 19 * 19 * x * 6 format. 19 is the number of EEG electrodes as nodes, x is the number of subjects (varies on different disorders), and 6 is the coherence between 19 nodes in six different frequency bands. I want to do a binary classification between each of those 6 mental disorders vs the healthy control group. (in fact,6 separate binary classifications). I want to have my code in Pytorch geometrics.
fb5e75cacb6a170f7920fb6a46a031df
{ "intermediate": 0.19820064306259155, "beginner": 0.07240833342075348, "expert": 0.7293910384178162 }
9,252
hot to kill process in windows task manager using c++
61fcc5ded984cfa3827fffa6c40e21e5
{ "intermediate": 0.3789394199848175, "beginner": 0.3086194396018982, "expert": 0.3124411404132843 }
9,253
How can I write a vba code that checks all the cells in column C that have values, and if a duplicate is found, it pops up a message stating that duplicates have been found and it lists the cell address where the duplicates exist. The cells in column C have text values in them, each containing several words. I would like to check the first three words in the cells to find if duplicates exist of this condition
bb3e95b355e6c378c6bbde2192d40502
{ "intermediate": 0.5725914835929871, "beginner": 0.0556611567735672, "expert": 0.37174737453460693 }
9,254
Can you create a simple SVG image of a palm tree coming out of a strand of DNA?
b93f4876b032d7552b591b6e008a619f
{ "intermediate": 0.3267642855644226, "beginner": 0.26615527272224426, "expert": 0.4070804715156555 }
9,255
type ButtonProps = { type: string; }; const Container = styled.div;<br/>const Wrapper = styled.div`<br/> padding: 20px;<br/>`;<br/>const Title = styled.h2`<br/> font-weight: 300;<br/> text-align: center;<br/>`;<br/>const Top = styled.div`<br/> display: flex;<br/> justify-content: space-between;<br/> align-items: center;<br/>`;<br/>const TopButton = styled.button&lt;ButtonProps&gt;`<br/> padding: 10px;<br/> font-weight: 600;<br/> cursor: pointer;<br/> border: ${(props) =&gt; (props.type === "filled" ? "none" : null)};<br/>`;<br/>const TopTexts = styled.div; const TopText = styled.span<br/> text-decoration: underline;<br/> cursor: pointer;<br/> margin: 0 10px;<br/>; const Bottom = styled.div``; const Cart = () => { return ( <Container> <Navbar /> <PromoInfo /> <Wrapper> <Title>YOUR CART</Title> <Top> <TopButton>CONTINUE SHOPPING</TopButton> <TopTexts> <TopText>Shopping Bag(2)</TopText> <TopText>Your Wishlist(0)</TopText> </TopTexts> <TopButton type=“filled”>CHECKOUT NOW</TopButton> </Top> <Bottom></Bottom> </Wrapper> <Footer /> </Container> ); }; export default Cart; This comparison appears to be unintentional because the types ‘“button” | “submit” | “reset”’ and ‘“filled”’ have no overlap.ts(2367)
4333f2181bcd618eabcb11dd5c9f04cc
{ "intermediate": 0.34279894828796387, "beginner": 0.3570036292076111, "expert": 0.30019745230674744 }
9,256
type ButtonProps = { type: string; }; const Container = styled.div;<br/>const Wrapper = styled.div&lt;br/&gt; padding: 20px;&lt;br/&gt;;<br/>const Title = styled.h2&lt;br/&gt; font-weight: 300;&lt;br/&gt; text-align: center;&lt;br/&gt;;<br/>const Top = styled.div&lt;br/&gt; display: flex;&lt;br/&gt; justify-content: space-between;&lt;br/&gt; align-items: center;&lt;br/&gt;;<br/>const TopButton = styled.button<ButtonProps>&lt;br/&gt; padding: 10px;&lt;br/&gt; font-weight: 600;&lt;br/&gt; cursor: pointer;&lt;br/&gt; border: ${(props) =&gt; (props.type === "filled" ? "none" : null)};&lt;br/&gt;;<br/>const TopTexts = styled.div; const TopText = styled.span<br/> text-decoration: underline;<br/> cursor: pointer;<br/> margin: 0 10px;<br/>; const Bottom = styled.div``; const Cart = () => { return ( <Container> <Navbar /> <PromoInfo /> <Wrapper> <Title>YOUR CART</Title> <Top> <TopButton>CONTINUE SHOPPING</TopButton> <TopTexts> <TopText>Shopping Bag(2)</TopText> <TopText>Your Wishlist(0)</TopText> </TopTexts> <TopButton type=“filled”>CHECKOUT NOW</TopButton> </Top> <Bottom></Bottom> </Wrapper> <Footer /> </Container> ); }; export default Cart; This comparison appears to be unintentional because the types ‘“button” | “submit” | “reset”’ and ‘“filled”’ have no overlap.ts(2367) write correct code
e3ec39e2321a11785ed63f30fdf8fbd9
{ "intermediate": 0.3538077473640442, "beginner": 0.3575575649738312, "expert": 0.28863468766212463 }
9,257
type ButtonProps = { type: "button" | "submit" | "reset" | "filled"; }; const Container = styled.div``; const Wrapper = styled.div` padding: 20px; `; const Title = styled.h2` font-weight: 300; text-align: center; `; const Top = styled.div` display: flex; justify-content: space-between; align-items: center; `; const TopButton = styled.button<ButtonProps>` padding: 10px; font-weight: 600; cursor: pointer; border: ${(props) => (props.type === "filled" ? "none" : null)}; `; const TopTexts = styled.div``; const TopText = styled.span` text-decoration: underline; cursor: pointer; margin: 0 10px; `; const Bottom = styled.div``; const Cart = () => { return ( <Container> <Navbar /> <PromoInfo /> <Wrapper> <Title>YOUR CART</Title> <Top> <TopButton>CONTINUE SHOPPING</TopButton> <TopTexts> <TopText>Shopping Bag(2)</TopText> <TopText>Your Wishlist(0)</TopText> </TopTexts> <TopButton type="filled">CHECKOUT NOW</TopButton> </Top> <Bottom></Bottom> </Wrapper> <Footer /> </Container> ); }; export default Cart; type ButtonProps = { type: "button" | "submit" | "reset" | "filled"; }; const Container = styled.div``; const Wrapper = styled.div` padding: 20px; `; const Title = styled.h2` font-weight: 300; text-align: center; `; const Top = styled.div` display: flex; justify-content: space-between; align-items: center; `; const TopButton = styled.button<ButtonProps>` padding: 10px; font-weight: 600; cursor: pointer; border: ${(props) => (props.type === "filled" ? "none" : null)}; `; const TopTexts = styled.div``; const TopText = styled.span` text-decoration: underline; cursor: pointer; margin: 0 10px; `; const Bottom = styled.div``; const Cart = () => { return ( <Container> <Navbar /> <PromoInfo /> <Wrapper> <Title>YOUR CART</Title> <Top> <TopButton>CONTINUE SHOPPING</TopButton> <TopTexts> <TopText>Shopping Bag(2)</TopText> <TopText>Your Wishlist(0)</TopText> </TopTexts> <TopButton type="filled">CHECKOUT NOW</TopButton> </Top> <Bottom></Bottom> </Wrapper> <Footer /> </Container> ); }; export default Cart; type ButtonProps = { type: "button" | "submit" | "reset" | "filled"; }; const Container = styled.div``; const Wrapper = styled.div` padding: 20px; `; const Title = styled.h2` font-weight: 300; text-align: center; `; const Top = styled.div` display: flex; justify-content: space-between; align-items: center; `; const TopButton = styled.button<ButtonProps>` padding: 10px; font-weight: 600; cursor: pointer; border: ${(props) => (props.type === "filled" ? "none" : null)}; `; const TopTexts = styled.div``; const TopText = styled.span` text-decoration: underline; cursor: pointer; margin: 0 10px; `; const Bottom = styled.div``; const Cart = () => { return ( <Container> <Navbar /> <PromoInfo /> <Wrapper> <Title>YOUR CART</Title> <Top> <TopButton>CONTINUE SHOPPING</TopButton> <TopTexts> <TopText>Shopping Bag(2)</TopText> <TopText>Your Wishlist(0)</TopText> </TopTexts> <TopButton type="filled">CHECKOUT NOW</TopButton> </Top> <Bottom></Bottom> </Wrapper> <Footer /> </Container> ); }; export default Cart; This comparison appears to be unintentional because the types '"button" | "submit" | "reset"' and '"filled"' have no overlap.ts(2367)
68cc5175d5a53994461e699a4f6efdee
{ "intermediate": 0.25471240282058716, "beginner": 0.5590934157371521, "expert": 0.18619415163993835 }
9,258
Create a python script that can convert json strings in this format: {"entries":{"0":{"uid":0,"key":["Paldea"],"keysecondary":[],"comment":"","content":"Paldea is a region in the Pokemon world. It is based off of the Iberian Peninsula.","constant":false,"selective":false,"order":100,"position":0,"disable":false},"1":{"uid":1,"key":["Arven"],"keysecondary":[],"comment":"","content":"Arven is a 16 year old boy.","constant":false,"selective":false,"order":100,"position":0,"disable":false},"2":{"uid":2,"key":["Hilbert"],"keysecondary":[],"comment":"","content":"Hilbert is a 15 year old boy.","constant":false,"selective":false,"order":100,"position":0,"disable":false}}} to this format: { "kind": "memory", "name": "book", "description": "", "entries": [ { "enabled": false, "entry": "Paldea is a region in the Pokemon world. It is based off of the Iberian Peninsula.", "keywords": [ "Paldea" ], "name": "Paldea", "priority": 0, "weight": 0 }, { "enabled": true, "entry": "Arven is a 16 year old boy.", "keywords": [ "Arven" ], "name": "Arven", "priority": 0, "weight": 0 }, { "enabled": true, "entry": "Hilbert is a 15 year old boy.", "keywords": [ "Hilbert" ], "name": "Hilbert", "priority": 0, "weight": 0 } ] }
50cb3cfc826656d0f753cab72c7c3633
{ "intermediate": 0.35116687417030334, "beginner": 0.3166099190711975, "expert": 0.332223117351532 }
9,259
Is there a way to combine these functions or abstract them into a struct/class? I feel like there a lot of similarities between them. void ECS::TransferComponentData(Archetype* fromArch, Archetype* toArch, size_t i, size_t j, size_t entityIndex) { const ComponentBase* componentBase = componentMap[i]; const std::size_t componentDataSize = componentBase->GetSize(); std::size_t currentSize = toArch->entityIds.size() * componentDataSize; componentBase->MoveData(&fromArch->componentData[j][entityIndex * componentDataSize], &toArch->componentData[i][currentSize]); componentBase->DestroyData(&fromArch->componentData[j][entityIndex * componentDataSize]); } void ECS::SwapComponentData(const size_t compTypeIndex, Archetype* arch, size_t index, size_t entityIndex) { const ComponentBase* componentBase = componentMap[compTypeIndex]; const std::size_t componentSize = componentBase->GetSize(); const auto lastEntity = arch->entityIds.size() - 1; componentBase->MoveData(&arch->componentData[index][lastEntity * componentSize], &arch->componentData[index][entityIndex * componentSize]); componentBase->DestroyData(&arch->componentData[index][lastEntity * componentSize]); } void ECS::RemoveAndAllocateComponentData(const size_t compTypeIndex, Archetype* fromArchetype, Archetype* toArchetype, size_t i, size_t j, size_t entityIndex) { const ComponentBase* const componentBase = componentMap[compTypeIndex]; const std::size_t componentDataSize = componentBase->GetSize(); size_t currentSize = toArchetype->entityIds.size() * componentDataSize; const size_t lastEntity = fromArchetype->entityIds.size() - 1; componentBase->MoveData(&fromArchetype->componentData[j][entityIndex * componentDataSize], &toArchetype->componentData[i][currentSize]); if (entityIndex != lastEntity) { componentBase->MoveData(&fromArchetype->componentData[j][lastEntity * componentDataSize], &fromArchetype->componentData[j][entityIndex * componentDataSize]); } componentBase->DestroyData(&fromArchetype->componentData[j][lastEntity * componentDataSize]); }
92775d837fe7b590befa780292115042
{ "intermediate": 0.5033438801765442, "beginner": 0.3926602900028229, "expert": 0.10399582237005234 }
9,260
adcolony bannar with kotlin and androud studio
6805cdbde9dd0ce82947a93520fb2548
{ "intermediate": 0.46890220046043396, "beginner": 0.18625585734844208, "expert": 0.34484195709228516 }
9,261
give me a script for cmd when click it on flash copy all file on flash to C:
925a968cd84ee507749e73c2923ad32d
{ "intermediate": 0.33668360114097595, "beginner": 0.3251352310180664, "expert": 0.33818116784095764 }
9,262
convert this code to rust """ unsigned long long __get_timestamp() { const size_t UNIX_TIME_START = 0x019DB1DED53E8000; // Start of Unix epoch in ticks. const size_t TICKS_PER_SECOND = 10000000; // A tick is 100ns. LARGE_INTEGER time; time.LowPart = *(DWORD*)(0x7FFE0000 + 0x14); // Read LowPart as unsigned long. time.HighPart = *(long*)(0x7FFE0000 + 0x1c); // Read High1Part as long. return (unsigned long long)((time.QuadPart - UNIX_TIME_START) / TICKS_PER_MILLISECOND); } """
957c9ec191cf54e7831be08ee8c0bad2
{ "intermediate": 0.3356487452983856, "beginner": 0.30505630373954773, "expert": 0.3592948913574219 }
9,263
How to solve this? Write me a python script to solve it For variable n, e, c s, you don't need to write the number in the script Just `from output import n, e, c, s` from Crypto.Util.number import getPrime, inverse, bytes_to_long from hashlib import sha256 def keygen(sz): p = getPrime(sz // 2) q = getPrime(sz // 2) n = p * q e = 65537 dp = inverse(e, p - 1) dq = inverse(e, q - 1) return (n, e), (p, q, dp, dq) def encrypt(pk, m): n, e = pk return pow(m, e, n) def sign(sk, m): p, q, dp, dq = sk n = p * q sp = pow(m, dp, p) sq = pow(m, dp, q) u = inverse(q, p) s = sq + ((sp - sq) * u % p) * q return s flag = open("flag.txt", "rb").read().strip() pk, sk = keygen(2048) m = bytes_to_long(flag) h = bytes_to_long(sha256(flag).digest()) c = encrypt(pk, m) s = sign(sk, h) print(f"n = {pk[0]}") print(f"e = {pk[1]}") print(f"c = {c}") print(f"s = {s}") """ n = 10062704821953299381118013872150801185961537844013735062723729816732285356100705358600649323566461315936460121971474006636382490147267954403524957329641648597166971422109386356155055136946044289274593499733650926175195907066357111852199392875841285126960021565401231708883244823358341538680107429601826504919277121724245368508883975923612424679085396126426007930485323892792575427880546884827376496706960189483957280312459279432163111106713442839944344090006216431212557750251238690628239418520497259548021246487572401803380458267948812771257052465497658279050643129404242366764506351044512890428445775909511266950499 e = 65537 c = 6245933709656257363090195362770572462957730695374578443647362222476764244871795796112560308570647697163351976596121283936220632500389819833974146452050313064353105464799468180406487679280169757857781050179971454855459423905991571297804274798763255929667823986486001391540735095484799899843702965680793168262964951955737725996015130499409046940675966180167041103810661958107260232947299774185366702450261059269220790212553934010242052899578732292497446984208720801700442345664566246400753919841010931074876235962100899161919944514993496803408143676576118767999216452035397709661584660172071229100514729748164065830627 s = 3385059843362307934004172178580455142596211252623465013057418095367622068617321316072975664333635524225179928220654957320160086932450412387083083235025927787884040623086331993039350976063603043122583824348622919619340553072952515198188247945759764368510290289816287516261930762580464107379813854425201606382192272918065808519468945944309809449613657120113003327218808169775099800298533325329180835922602441763895243302433578492108289993974897976372754960027209422448229921931148361959319753262770338742919299633016594138842047528124748443147704268193710121568350972591340425233153796030713754093794612005372897494387 """
f2d391b2759fcb042185b7982e8ad19b
{ "intermediate": 0.35190317034721375, "beginner": 0.3791889548301697, "expert": 0.26890793442726135 }
9,264
AdColony.configure(applicationContext, appOptions, APP_ID, ZONE_ID) is deprected what is new
dd25231abd40fd9cab4222b929cc4876
{ "intermediate": 0.5118408799171448, "beginner": 0.2039395570755005, "expert": 0.2842195928096771 }
9,265
How to solve this? Write me a python script to solve it For variable n, e, c s, you don't need to write the number in the script Just `from output import n, e, c, s` from Crypto.Util.number import getPrime, inverse, bytes_to_long from hashlib import sha256 def keygen(sz): p = getPrime(sz // 2) q = getPrime(sz // 2) n = p * q e = 65537 dp = inverse(e, p - 1) dq = inverse(e, q - 1) return (n, e), (p, q, dp, dq) def encrypt(pk, m): n, e = pk return pow(m, e, n) def sign(sk, m): p, q, dp, dq = sk n = p * q sp = pow(m, dp, p) sq = pow(m, dp, q) u = inverse(q, p) s = sq + ((sp - sq) * u % p) * q return s flag = open("flag.txt", "rb").read().strip() pk, sk = keygen(2048) m = bytes_to_long(flag) h = bytes_to_long(sha256(flag).digest()) c = encrypt(pk, m) s = sign(sk, h) print(f"n = {pk[0]}") print(f"e = {pk[1]}") print(f"c = {c}") print(f"s = {s}") """ n = 10062704821953299381118013872150801185961537844013735062723729816732285356100705358600649323566461315936460121971474006636382490147267954403524957329641648597166971422109386356155055136946044289274593499733650926175195907066357111852199392875841285126960021565401231708883244823358341538680107429601826504919277121724245368508883975923612424679085396126426007930485323892792575427880546884827376496706960189483957280312459279432163111106713442839944344090006216431212557750251238690628239418520497259548021246487572401803380458267948812771257052465497658279050643129404242366764506351044512890428445775909511266950499 e = 65537 c = 6245933709656257363090195362770572462957730695374578443647362222476764244871795796112560308570647697163351976596121283936220632500389819833974146452050313064353105464799468180406487679280169757857781050179971454855459423905991571297804274798763255929667823986486001391540735095484799899843702965680793168262964951955737725996015130499409046940675966180167041103810661958107260232947299774185366702450261059269220790212553934010242052899578732292497446984208720801700442345664566246400753919841010931074876235962100899161919944514993496803408143676576118767999216452035397709661584660172071229100514729748164065830627 s = 3385059843362307934004172178580455142596211252623465013057418095367622068617321316072975664333635524225179928220654957320160086932450412387083083235025927787884040623086331993039350976063603043122583824348622919619340553072952515198188247945759764368510290289816287516261930762580464107379813854425201606382192272918065808519468945944309809449613657120113003327218808169775099800298533325329180835922602441763895243302433578492108289993974897976372754960027209422448229921931148361959319753262770338742919299633016594138842047528124748443147704268193710121568350972591340425233153796030713754093794612005372897494387 """
67dea1e9c122cb25d8f3629666caa35b
{ "intermediate": 0.35190317034721375, "beginner": 0.3791889548301697, "expert": 0.26890793442726135 }
9,266
So I am using UE5.2 and GAS. In my game, when you click on an enemy, the player character will walk to the enemy and start attacking him. I also have a way for the user to press an ability and use on the monster. The player will walk to the monster based on an attack range and start a cast ability bar if available and cast the ability once the cast bar finishes. I am having a problem where if I use an ability on a monster and then immediately left click the monster to auto attack, it will start the cast bar and ability while on top of that auto attacking the monster. We shouldn't be using any targeted abilities if we are going to auto attack a monster so it should cancel the cast ability when we go auto attack a monster. How should I do this?
9fe4d33f1b0c199a94956d87ea58c233
{ "intermediate": 0.5395458936691284, "beginner": 0.24979406595230103, "expert": 0.21066001057624817 }
9,267
can you give me the code for building a handwriting text recognition model based on a characters dataset and CNN and RNN
45a227b9af8d1b1741d4a3302d8b8fe3
{ "intermediate": 0.19351409375667572, "beginner": 0.020854897797107697, "expert": 0.785631000995636 }
9,268
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. Here is a portion of the code: Renderer.h: #pragma once #include <vulkan/vulkan.h> #include "Window.h" #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> #include "Pipeline.h" #include "Material.h" #include "Mesh.h" struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); VkDescriptorSetLayout CreateDescriptorSetLayout(); VkDescriptorPool CreateDescriptorPool(uint32_t maxSets); VkDevice* GetDevice(); VkPhysicalDevice* GetPhysicalDevice(); VkCommandPool* GetCommandPool(); VkQueue* GetGraphicsQueue(); VkCommandBuffer* GetCurrentCommandBuffer(); std::shared_ptr<Pipeline> GetPipeline(); void CreateGraphicsPipeline(Mesh* mesh, Material* material); VkDescriptorSetLayout CreateSamplerDescriptorSetLayout(); private: bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; std::vector<size_t> currentFramePerImage; std::vector<VkImage> swapChainImages; std::vector<VkImageView> swapChainImageViews; VkExtent2D swapChainExtent; VkRenderPass renderPass; uint32_t imageIndex; std::shared_ptr<Pipeline> pipeline; VkFormat swapChainImageFormat; std::vector<VkCommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); void Present(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" #include <chrono> #include <thread> class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); int MaxFPS = 60; private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; Scene.h: #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; BufferUtils.h: #pragma once #include <vulkan/vulkan.h> #include <stdint.h> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties); void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); } BufferUtils.cpp: #include "BufferUtils.h" #include <stdexcept> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create buffer!"); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } vkBindBufferMemory(device, buffer, bufferMemory, 0); } uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("Failed to find suitable memory type!"); } void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue); vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); } } I am getting this error: VUID-vkUpdateDescriptorSets-None-03047(ERROR / SPEC): msgNum: 903342744 - Validation Error: [ VUID-vkUpdateDescriptorSets-None-03047 ] Object 0: handle = 0x2e2cd000000002b, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0x35d7ea98 | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0x2e2cd000000002b[] with error: Cannot call vkUpdateDescriptorSets() to perform write update on VkDescriptorSet 0x2e2cd000000002b[] allocated with VkDescriptorSetLayout 0xd10d270000000018[] that is in use by a command buffer. The Vulkan spec states: Descriptor bindings updated by this command which were created without the VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT or VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT bits set must not be used by any command that was recorded to a command buffer which is in the pending state (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkUpdateDescriptorSets-None-03047) How can I alter the code to fix this issue?
2ca6dd22b657f4d05a5a746f905bbfe9
{ "intermediate": 0.3753734827041626, "beginner": 0.29778599739074707, "expert": 0.32684049010276794 }
9,269
Fatal error: can't create ../../../tmp/FT201/DataManagerModule/CConfigChangSdParaList.o: 没有那个文件或目录
4aaffc7f0cc290f4e33111688130bffb
{ "intermediate": 0.45209863781929016, "beginner": 0.25515714287757874, "expert": 0.2927442491054535 }
9,270
Write a piece of java code
0bb5f7f96c3ffad6f8752d089806069b
{ "intermediate": 0.2799074351787567, "beginner": 0.4136996567249298, "expert": 0.3063928186893463 }
9,271
I need you to redesign my PlayerController so that I can train a neural network on Unity's ML Agents. the neural network will only shoot, the output should be two float values from -1 to 1 each, as if emulating a gamepad stick. I also need to be able to control this controller as a player as I will be adding new weapons and new characters. My game is in 2D, PlayerController connected to circle sprite. ok let's go: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; using UnityEditor.U2D; public enum CharacterGroup { Player, Ally, Enemy } public enum ControlMode { Mouse, Joystick, AI } public class PlayerController : MonoBehaviour { #region Public Variables public CharacterGroup group; public ShootingAgent shootingAgent; public OpponentGenerator opponentGenerator; public VariableJoystick variableJoystick; public ControlMode currentControlMode = ControlMode.Mouse; // Default control mode is mouse public GameObject bulletPrefab; public string nickname = "lovekpek"; public string brawlerName = "Nita"; public int maxHealth = 3000; // Add a new variable for maximum health public int damage = 750; // Add a new variable for damage public bool damagePiercing = true; public float movementSpeed = 5f; public float aimingDistance = 5f; public float bulletSpeed = 10f; public int maxBullets = 3; public float reloadTime = 2f; public float shotDelay = 0.5f; // Delay between consecutive shots public float bulletWidth = 0.1f; // Bullet width [SerializeField] private HealthBar _healthbar; public Text healthText; // Reference to the UI text component for health display [SerializeField] private BulletBar _bulletbar; public Text bulletsText; public int currentHealth = 3000; public int currentBullets = 3; public Text speedText; #endregion #region Private Variables private GameObject sightLine; private bool isAiming; private bool canShoot = true; // Flag to allow shooting private Vector2 aimDirection; private Vector2 lineEndPosition; private float currentDistance; private float reloadTimer; private float shotTimer; // Timer for shot delay private bool hasFiredRecently; // New flag private Vector2 movementInput; private float currentSpeed; private bool isPlayerControlled = false; private Collider2D lastCollision; // Class-level variable to store the last collision // Joystick control variables private float horizontalInput; private float verticalInput; #endregion #region Unity Callbacks private void Start() { InitializePlayer(); } private void Update() { if (IsPlayerControlled()) { HandleAimingAndShooting(); HandleReloading(); HandlePlayerMovement(); UpdateUIElements(); } } private void OnTriggerEnter2D(Collider2D collision) { ProcessCollision(collision); } #endregion #region Initialization public void InitializePlayer() { currentBullets = maxBullets; UpdateBulletsText(); switch (group) { case CharacterGroup.Player: isPlayerControlled = true; break; case CharacterGroup.Ally: break; case CharacterGroup.Enemy: break; } } #endregion #region Movement and Aiming private void HandlePlayerMovement() { movementInput.x = Input.GetAxisRaw("Horizontal"); movementInput.y = Input.GetAxisRaw("Vertical"); movementInput.Normalize(); currentSpeed = movementSpeed * movementInput.magnitude; Vector3 movement = new Vector3(movementInput.x, movementInput.y, 0f) * currentSpeed * Time.deltaTime; transform.position += movement; } private void HandleAimingAndShooting() { switch (currentControlMode) { case ControlMode.Mouse: MouseControlLogic(); break; case ControlMode.Joystick: JoystickControlLogic(); break; case ControlMode.AI: AIControlLogic(); break; } if (isAiming) { UpdateSightLine(); } if (!canShoot) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; } } if (!canShoot && hasFiredRecently) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; hasFiredRecently = false; } } } private void MouseControlLogic() { if (Input.GetMouseButtonDown(0)) { StartAiming(); } else if (Input.GetMouseButtonUp(0)) { StopAiming(); } } private void JoystickControlLogic() { if (Mathf.Abs(variableJoystick.Horizontal) > 0.1f || Mathf.Abs(variableJoystick.Vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } private void AIControlLogic() { if (shootingAgent != null) { // Get the joystick control values from the ML agent float horizontal = 0f; float vertical = 0f; //Debug.Log(horizontal); // Retrieve the joystick control values from the ML agent var behaviorParameters = shootingAgent.GetComponent<Unity.MLAgents.Policies.BehaviorParameters>(); if (behaviorParameters != null) { var actions = shootingAgent.GetStoredActionBuffers().ContinuousActions; if (actions.Length > 0) horizontal = actions[0]; if (actions.Length > 1) vertical = actions[1]; } // Check if the joystick control values exceed the threshold if (Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } } public void ControlJoystick(float horizontal, float vertical) { currentControlMode = ControlMode.AI; // Switch to AI control mode // Set horizontal and vertical input values horizontalInput = horizontal; verticalInput = vertical; Debug.Log(horizontalInput); Debug.Log(verticalInput); } private void StartAiming() { isAiming = true; // Destroy any existing SightLine object if (sightLine != null) Destroy(sightLine); // Create and initialize sight line CreateSightLine(); currentDistance = aimingDistance; } private void StopAiming() { isAiming = false; Destroy(sightLine); if (canShoot && currentBullets > 0) { if (shotTimer <= 0f) // Check if shot delay has elapsed { FireBullet(); currentBullets--; UpdateBulletsText(); canShoot = false; // Set canShoot to false shotTimer = shotDelay; // Reset shot delay timer } } } private void CreateSightLine() { sightLine = new GameObject("SightLine"); LineRenderer lineRenderer = sightLine.AddComponent<LineRenderer>(); lineRenderer.positionCount = 2; lineRenderer.startWidth = bulletWidth; lineRenderer.endWidth = bulletWidth; // Create a new material and set its color to white Material lineMaterial = new Material(Shader.Find("Sprites/Default")); lineMaterial.color = Color.white; lineRenderer.material = lineMaterial; // Assign the material to the line renderer lineRenderer.sortingLayerName = "Background"; // Set the sorting layer lineRenderer.sortingOrder = -1; // Set the sorting order to render behind the player lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, transform.position); } private void UpdateSightLine() { switch (currentControlMode) { case ControlMode.Mouse: Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimDirection = (mousePosition - (Vector2)transform.position).normalized; break; case ControlMode.Joystick: aimDirection = new Vector2(variableJoystick.Horizontal, variableJoystick.Vertical).normalized; break; default: aimDirection = Vector2.zero; break; } lineEndPosition = (Vector2)transform.position + aimDirection * currentDistance; LineRenderer lineRenderer = sightLine.GetComponent<LineRenderer>(); lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, lineEndPosition); } #endregion #region Reloading private void HandleReloading() { if (currentBullets < maxBullets) { reloadTimer += Time.deltaTime; if (reloadTimer >= reloadTime) { reloadTimer = 0f; currentBullets++; UpdateBulletsText(); } } else if (!isAiming && sightLine != null) { Destroy(sightLine); } } #endregion #region Shooting public void FireBullet() { GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity); BulletController bulletController = bullet.GetComponent<BulletController>(); bulletController.SetDirection(aimDirection); bulletController.SetSpeed(bulletSpeed); bulletController.SetMaxDistance(currentDistance); bulletController.SetGroup(group); bulletController.SetDamage(damage); bulletController.SetDamagePiercing(damagePiercing); } #endregion #region UI Updates private void UpdateUIElements() { healthText.text = currentHealth.ToString(); _healthbar.UpdateHealthBar(maxHealth, currentHealth); UpdateBulletsText(); } private void UpdateBulletsText() { bulletsText.text = currentBullets.ToString(); _bulletbar.UpdateHealthBar(maxBullets, currentBullets); } #endregion #region Collision Handling private void ProcessCollision(Collider2D collision) { if (group.Equals(CharacterGroup.Player) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Ally)) { // Ignore bullets from allies damaging the player return; } else if (group.Equals(CharacterGroup.Ally) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Ignore bullets from the player damaging allies return; } else if (group.Equals(CharacterGroup.Enemy) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Damage the enemy when hit by a player’s bullet int bulletDamage = collision.GetComponent<BulletController>().GetDamage(); bool bulletDamagePiercing = collision.GetComponent<BulletController>().GetDamagePiercing(); TakeDamage(bulletDamage); if (bulletDamagePiercing == false) { Destroy(collision.gameObject); } return; } } private void TakeDamage(int damageValue) { if (group == CharacterGroup.Enemy) { currentHealth -= damageValue; if (currentHealth <= 0) { Destroy(gameObject); } _healthbar.UpdateHealthBar(maxHealth, currentHealth); healthText.text = currentHealth.ToString(); } } #endregion #region Observations for ML public void CollectObservations(VectorSensor sensor) { // Add player position to observations sensor.AddObservation(transform.position); // Get enemy positions from OpponentGenerator var enemyPositions = opponentGenerator.GetEnemyPositions(); // Add enemy positions to observations foreach (var enemyPosition in enemyPositions) { sensor.AddObservation(enemyPosition); } } #endregion #region Utility Functions public void Shoot(float shootingAngle) { // Perform shooting logic based on the shooting angle // … } public void RenderToTexture(RenderTexture renderTexture) { // Render the game view to the specified render texture RenderTexture currentRT = RenderTexture.active; RenderTexture.active = renderTexture; Camera.main.targetTexture = renderTexture; Camera.main.Render(); // Reset the render texture and camera settings Camera.main.targetTexture = null; RenderTexture.active = currentRT; } #endregion // Helper Methods private bool IsPlayerControlled() { return isPlayerControlled; } }
43c1c9961b420993a159dd164386a395
{ "intermediate": 0.39588502049446106, "beginner": 0.33658698201179504, "expert": 0.2675279974937439 }
9,272
I need you to redesign my PlayerController so that I can train a neural network on Unity's ML Agents. the neural network will only shoot, the output should be two float values from -1 to 1 each, as if emulating a gamepad stick. I also need to be able to control this controller as a player as I will be adding new weapons and new characters. My game is in 2D, PlayerController connected to circle sprite. ok let's go: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; using UnityEditor.U2D; public enum CharacterGroup { Player, Ally, Enemy } public enum ControlMode { Mouse, Joystick, AI } public class PlayerController : MonoBehaviour { #region Public Variables public CharacterGroup group; public ShootingAgent shootingAgent; public OpponentGenerator opponentGenerator; public VariableJoystick variableJoystick; public ControlMode currentControlMode = ControlMode.Mouse; // Default control mode is mouse public GameObject bulletPrefab; public string nickname = "lovekpek"; public string brawlerName = "Nita"; public int maxHealth = 3000; // Add a new variable for maximum health public int damage = 750; // Add a new variable for damage public bool damagePiercing = true; public float movementSpeed = 5f; public float aimingDistance = 5f; public float bulletSpeed = 10f; public int maxBullets = 3; public float reloadTime = 2f; public float shotDelay = 0.5f; // Delay between consecutive shots public float bulletWidth = 0.1f; // Bullet width [SerializeField] private HealthBar _healthbar; public Text healthText; // Reference to the UI text component for health display [SerializeField] private BulletBar _bulletbar; public Text bulletsText; public int currentHealth = 3000; public int currentBullets = 3; public Text speedText; #endregion #region Private Variables private GameObject sightLine; private bool isAiming; private bool canShoot = true; // Flag to allow shooting private Vector2 aimDirection; private Vector2 lineEndPosition; private float currentDistance; private float reloadTimer; private float shotTimer; // Timer for shot delay private bool hasFiredRecently; // New flag private Vector2 movementInput; private float currentSpeed; private bool isPlayerControlled = false; private Collider2D lastCollision; // Class-level variable to store the last collision // Joystick control variables private float horizontalInput; private float verticalInput; #endregion #region Unity Callbacks private void Start() { InitializePlayer(); } private void Update() { if (IsPlayerControlled()) { HandleAimingAndShooting(); HandleReloading(); HandlePlayerMovement(); UpdateUIElements(); } } private void OnTriggerEnter2D(Collider2D collision) { ProcessCollision(collision); } #endregion #region Initialization public void InitializePlayer() { currentBullets = maxBullets; UpdateBulletsText(); switch (group) { case CharacterGroup.Player: isPlayerControlled = true; break; case CharacterGroup.Ally: break; case CharacterGroup.Enemy: break; } } #endregion #region Movement and Aiming private void HandlePlayerMovement() { movementInput.x = Input.GetAxisRaw("Horizontal"); movementInput.y = Input.GetAxisRaw("Vertical"); movementInput.Normalize(); currentSpeed = movementSpeed * movementInput.magnitude; Vector3 movement = new Vector3(movementInput.x, movementInput.y, 0f) * currentSpeed * Time.deltaTime; transform.position += movement; } private void HandleAimingAndShooting() { switch (currentControlMode) { case ControlMode.Mouse: MouseControlLogic(); break; case ControlMode.Joystick: JoystickControlLogic(); break; case ControlMode.AI: AIControlLogic(); break; } if (isAiming) { UpdateSightLine(); } if (!canShoot) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; } } if (!canShoot && hasFiredRecently) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; hasFiredRecently = false; } } } private void MouseControlLogic() { if (Input.GetMouseButtonDown(0)) { StartAiming(); } else if (Input.GetMouseButtonUp(0)) { StopAiming(); } } private void JoystickControlLogic() { if (Mathf.Abs(variableJoystick.Horizontal) > 0.1f || Mathf.Abs(variableJoystick.Vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } private void AIControlLogic() { if (shootingAgent != null) { // Get the joystick control values from the ML agent float horizontal = 0f; float vertical = 0f; //Debug.Log(horizontal); // Retrieve the joystick control values from the ML agent var behaviorParameters = shootingAgent.GetComponent<Unity.MLAgents.Policies.BehaviorParameters>(); if (behaviorParameters != null) { var actions = shootingAgent.GetStoredActionBuffers().ContinuousActions; if (actions.Length > 0) horizontal = actions[0]; if (actions.Length > 1) vertical = actions[1]; } // Check if the joystick control values exceed the threshold if (Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } } public void ControlJoystick(float horizontal, float vertical) { currentControlMode = ControlMode.AI; // Switch to AI control mode // Set horizontal and vertical input values horizontalInput = horizontal; verticalInput = vertical; Debug.Log(horizontalInput); Debug.Log(verticalInput); } private void StartAiming() { isAiming = true; // Destroy any existing SightLine object if (sightLine != null) Destroy(sightLine); // Create and initialize sight line CreateSightLine(); currentDistance = aimingDistance; } private void StopAiming() { isAiming = false; Destroy(sightLine); if (canShoot && currentBullets > 0) { if (shotTimer <= 0f) // Check if shot delay has elapsed { FireBullet(); currentBullets--; UpdateBulletsText(); canShoot = false; // Set canShoot to false shotTimer = shotDelay; // Reset shot delay timer } } } private void CreateSightLine() { sightLine = new GameObject("SightLine"); LineRenderer lineRenderer = sightLine.AddComponent<LineRenderer>(); lineRenderer.positionCount = 2; lineRenderer.startWidth = bulletWidth; lineRenderer.endWidth = bulletWidth; // Create a new material and set its color to white Material lineMaterial = new Material(Shader.Find("Sprites/Default")); lineMaterial.color = Color.white; lineRenderer.material = lineMaterial; // Assign the material to the line renderer lineRenderer.sortingLayerName = "Background"; // Set the sorting layer lineRenderer.sortingOrder = -1; // Set the sorting order to render behind the player lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, transform.position); } private void UpdateSightLine() { switch (currentControlMode) { case ControlMode.Mouse: Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimDirection = (mousePosition - (Vector2)transform.position).normalized; break; case ControlMode.Joystick: aimDirection = new Vector2(variableJoystick.Horizontal, variableJoystick.Vertical).normalized; break; default: aimDirection = Vector2.zero; break; } lineEndPosition = (Vector2)transform.position + aimDirection * currentDistance; LineRenderer lineRenderer = sightLine.GetComponent<LineRenderer>(); lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, lineEndPosition); } #endregion #region Reloading private void HandleReloading() { if (currentBullets < maxBullets) { reloadTimer += Time.deltaTime; if (reloadTimer >= reloadTime) { reloadTimer = 0f; currentBullets++; UpdateBulletsText(); } } else if (!isAiming && sightLine != null) { Destroy(sightLine); } } #endregion #region Shooting public void FireBullet() { GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity); BulletController bulletController = bullet.GetComponent<BulletController>(); bulletController.SetDirection(aimDirection); bulletController.SetSpeed(bulletSpeed); bulletController.SetMaxDistance(currentDistance); bulletController.SetGroup(group); bulletController.SetDamage(damage); bulletController.SetDamagePiercing(damagePiercing); } #endregion #region UI Updates private void UpdateUIElements() { healthText.text = currentHealth.ToString(); _healthbar.UpdateHealthBar(maxHealth, currentHealth); UpdateBulletsText(); } private void UpdateBulletsText() { bulletsText.text = currentBullets.ToString(); _bulletbar.UpdateHealthBar(maxBullets, currentBullets); } #endregion #region Collision Handling private void ProcessCollision(Collider2D collision) { if (group.Equals(CharacterGroup.Player) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Ally)) { // Ignore bullets from allies damaging the player return; } else if (group.Equals(CharacterGroup.Ally) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Ignore bullets from the player damaging allies return; } else if (group.Equals(CharacterGroup.Enemy) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Damage the enemy when hit by a player’s bullet int bulletDamage = collision.GetComponent<BulletController>().GetDamage(); bool bulletDamagePiercing = collision.GetComponent<BulletController>().GetDamagePiercing(); TakeDamage(bulletDamage); if (bulletDamagePiercing == false) { Destroy(collision.gameObject); } return; } } private void TakeDamage(int damageValue) { if (group == CharacterGroup.Enemy) { currentHealth -= damageValue; if (currentHealth <= 0) { Destroy(gameObject); } _healthbar.UpdateHealthBar(maxHealth, currentHealth); healthText.text = currentHealth.ToString(); } } #endregion #region Observations for ML public void CollectObservations(VectorSensor sensor) { // Add player position to observations sensor.AddObservation(transform.position); // Get enemy positions from OpponentGenerator var enemyPositions = opponentGenerator.GetEnemyPositions(); // Add enemy positions to observations foreach (var enemyPosition in enemyPositions) { sensor.AddObservation(enemyPosition); } } #endregion #region Utility Functions public void Shoot(float shootingAngle) { // Perform shooting logic based on the shooting angle // … } public void RenderToTexture(RenderTexture renderTexture) { // Render the game view to the specified render texture RenderTexture currentRT = RenderTexture.active; RenderTexture.active = renderTexture; Camera.main.targetTexture = renderTexture; Camera.main.Render(); // Reset the render texture and camera settings Camera.main.targetTexture = null; RenderTexture.active = currentRT; } #endregion // Helper Methods private bool IsPlayerControlled() { return isPlayerControlled; } }
20bc9fb3d39e3da99867042e4c0fa05c
{ "intermediate": 0.39588502049446106, "beginner": 0.33658698201179504, "expert": 0.2675279974937439 }
9,273
In unreal engine 4, I want to look through a long tube and the pixels visible through the tube get clip based on the view cone and a clip start offset. is it possible to write a custom HLSL shader code using a Custom expression node for it? my material blend mode is masked. my tube is aligned along the x-axis.
276eace563f6ff99fd34333b9835bce7
{ "intermediate": 0.5112607479095459, "beginner": 0.20793598890304565, "expert": 0.28080323338508606 }
9,274
I need you to redesign my PlayerController so that I can train a neural network on Unity's ML Agents. the neural network will only shoot, the output should be two float values from -1 to 1 each, as if emulating a gamepad stick. I also need to be able to control this controller as a player as I will be adding new weapons and new characters. My game is in 2D, PlayerController connected to circle sprite. ok let's go: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; using UnityEditor.U2D; public enum CharacterGroup { Player, Ally, Enemy } public enum ControlMode { Mouse, Joystick, AI } public class PlayerController : MonoBehaviour { #region Public Variables public CharacterGroup group; public ShootingAgent shootingAgent; public OpponentGenerator opponentGenerator; public VariableJoystick variableJoystick; public ControlMode currentControlMode = ControlMode.Mouse; // Default control mode is mouse public GameObject bulletPrefab; public string nickname = "lovekpek"; public string brawlerName = "Nita"; public int maxHealth = 3000; // Add a new variable for maximum health public int damage = 750; // Add a new variable for damage public bool damagePiercing = true; public float movementSpeed = 5f; public float aimingDistance = 5f; public float bulletSpeed = 10f; public int maxBullets = 3; public float reloadTime = 2f; public float shotDelay = 0.5f; // Delay between consecutive shots public float bulletWidth = 0.1f; // Bullet width [SerializeField] private HealthBar _healthbar; public Text healthText; // Reference to the UI text component for health display [SerializeField] private BulletBar _bulletbar; public Text bulletsText; public int currentHealth = 3000; public int currentBullets = 3; public Text speedText; #endregion #region Private Variables private GameObject sightLine; private bool isAiming; private bool canShoot = true; // Flag to allow shooting private Vector2 aimDirection; private Vector2 lineEndPosition; private float currentDistance; private float reloadTimer; private float shotTimer; // Timer for shot delay private bool hasFiredRecently; // New flag private Vector2 movementInput; private float currentSpeed; private bool isPlayerControlled = false; private Collider2D lastCollision; // Class-level variable to store the last collision // Joystick control variables private float horizontalInput; private float verticalInput; #endregion #region Unity Callbacks private void Start() { InitializePlayer(); } private void Update() { if (IsPlayerControlled()) { HandleAimingAndShooting(); HandleReloading(); HandlePlayerMovement(); UpdateUIElements(); } } private void OnTriggerEnter2D(Collider2D collision) { ProcessCollision(collision); } #endregion #region Initialization public void InitializePlayer() { currentBullets = maxBullets; UpdateBulletsText(); switch (group) { case CharacterGroup.Player: isPlayerControlled = true; break; case CharacterGroup.Ally: break; case CharacterGroup.Enemy: break; } } #endregion #region Movement and Aiming private void HandlePlayerMovement() { movementInput.x = Input.GetAxisRaw("Horizontal"); movementInput.y = Input.GetAxisRaw("Vertical"); movementInput.Normalize(); currentSpeed = movementSpeed * movementInput.magnitude; Vector3 movement = new Vector3(movementInput.x, movementInput.y, 0f) * currentSpeed * Time.deltaTime; transform.position += movement; } private void HandleAimingAndShooting() { switch (currentControlMode) { case ControlMode.Mouse: MouseControlLogic(); break; case ControlMode.Joystick: JoystickControlLogic(); break; case ControlMode.AI: AIControlLogic(); break; } if (isAiming) { UpdateSightLine(); } if (!canShoot) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; } } if (!canShoot && hasFiredRecently) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; hasFiredRecently = false; } } } private void MouseControlLogic() { if (Input.GetMouseButtonDown(0)) { StartAiming(); } else if (Input.GetMouseButtonUp(0)) { StopAiming(); } } private void JoystickControlLogic() { if (Mathf.Abs(variableJoystick.Horizontal) > 0.1f || Mathf.Abs(variableJoystick.Vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } private void AIControlLogic() { if (shootingAgent != null) { // Get the joystick control values from the ML agent float horizontal = 0f; float vertical = 0f; //Debug.Log(horizontal); // Retrieve the joystick control values from the ML agent var behaviorParameters = shootingAgent.GetComponent<Unity.MLAgents.Policies.BehaviorParameters>(); if (behaviorParameters != null) { var actions = shootingAgent.GetStoredActionBuffers().ContinuousActions; if (actions.Length > 0) horizontal = actions[0]; if (actions.Length > 1) vertical = actions[1]; } // Check if the joystick control values exceed the threshold if (Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } } public void ControlJoystick(float horizontal, float vertical) { currentControlMode = ControlMode.AI; // Switch to AI control mode // Set horizontal and vertical input values horizontalInput = horizontal; verticalInput = vertical; Debug.Log(horizontalInput); Debug.Log(verticalInput); } private void StartAiming() { isAiming = true; // Destroy any existing SightLine object if (sightLine != null) Destroy(sightLine); // Create and initialize sight line CreateSightLine(); currentDistance = aimingDistance; } private void StopAiming() { isAiming = false; Destroy(sightLine); if (canShoot && currentBullets > 0) { if (shotTimer <= 0f) // Check if shot delay has elapsed { FireBullet(); currentBullets--; UpdateBulletsText(); canShoot = false; // Set canShoot to false shotTimer = shotDelay; // Reset shot delay timer } } } private void CreateSightLine() { sightLine = new GameObject("SightLine"); LineRenderer lineRenderer = sightLine.AddComponent<LineRenderer>(); lineRenderer.positionCount = 2; lineRenderer.startWidth = bulletWidth; lineRenderer.endWidth = bulletWidth; // Create a new material and set its color to white Material lineMaterial = new Material(Shader.Find("Sprites/Default")); lineMaterial.color = Color.white; lineRenderer.material = lineMaterial; // Assign the material to the line renderer lineRenderer.sortingLayerName = "Background"; // Set the sorting layer lineRenderer.sortingOrder = -1; // Set the sorting order to render behind the player lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, transform.position); } private void UpdateSightLine() { switch (currentControlMode) { case ControlMode.Mouse: Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimDirection = (mousePosition - (Vector2)transform.position).normalized; break; case ControlMode.Joystick: aimDirection = new Vector2(variableJoystick.Horizontal, variableJoystick.Vertical).normalized; break; default: aimDirection = Vector2.zero; break; } lineEndPosition = (Vector2)transform.position + aimDirection * currentDistance; LineRenderer lineRenderer = sightLine.GetComponent<LineRenderer>(); lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, lineEndPosition); } #endregion #region Reloading private void HandleReloading() { if (currentBullets < maxBullets) { reloadTimer += Time.deltaTime; if (reloadTimer >= reloadTime) { reloadTimer = 0f; currentBullets++; UpdateBulletsText(); } } else if (!isAiming && sightLine != null) { Destroy(sightLine); } } #endregion #region Shooting public void FireBullet() { GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity); BulletController bulletController = bullet.GetComponent<BulletController>(); bulletController.SetDirection(aimDirection); bulletController.SetSpeed(bulletSpeed); bulletController.SetMaxDistance(currentDistance); bulletController.SetGroup(group); bulletController.SetDamage(damage); bulletController.SetDamagePiercing(damagePiercing); } #endregion #region UI Updates private void UpdateUIElements() { healthText.text = currentHealth.ToString(); _healthbar.UpdateHealthBar(maxHealth, currentHealth); UpdateBulletsText(); } private void UpdateBulletsText() { bulletsText.text = currentBullets.ToString(); _bulletbar.UpdateHealthBar(maxBullets, currentBullets); } #endregion #region Collision Handling private void ProcessCollision(Collider2D collision) { if (group.Equals(CharacterGroup.Player) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Ally)) { // Ignore bullets from allies damaging the player return; } else if (group.Equals(CharacterGroup.Ally) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Ignore bullets from the player damaging allies return; } else if (group.Equals(CharacterGroup.Enemy) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Damage the enemy when hit by a player’s bullet int bulletDamage = collision.GetComponent<BulletController>().GetDamage(); bool bulletDamagePiercing = collision.GetComponent<BulletController>().GetDamagePiercing(); TakeDamage(bulletDamage); if (bulletDamagePiercing == false) { Destroy(collision.gameObject); } return; } } private void TakeDamage(int damageValue) { if (group == CharacterGroup.Enemy) { currentHealth -= damageValue; if (currentHealth <= 0) { Destroy(gameObject); } _healthbar.UpdateHealthBar(maxHealth, currentHealth); healthText.text = currentHealth.ToString(); } } #endregion #region Observations for ML public void CollectObservations(VectorSensor sensor) { // Add player position to observations sensor.AddObservation(transform.position); // Get enemy positions from OpponentGenerator var enemyPositions = opponentGenerator.GetEnemyPositions(); // Add enemy positions to observations foreach (var enemyPosition in enemyPositions) { sensor.AddObservation(enemyPosition); } } #endregion #region Utility Functions public void Shoot(float shootingAngle) { // Perform shooting logic based on the shooting angle // … } public void RenderToTexture(RenderTexture renderTexture) { // Render the game view to the specified render texture RenderTexture currentRT = RenderTexture.active; RenderTexture.active = renderTexture; Camera.main.targetTexture = renderTexture; Camera.main.Render(); // Reset the render texture and camera settings Camera.main.targetTexture = null; RenderTexture.active = currentRT; } #endregion // Helper Methods private bool IsPlayerControlled() { return isPlayerControlled; } }
e21eae1d5ed3c37fd3b33b6bb47b068c
{ "intermediate": 0.39588502049446106, "beginner": 0.33658698201179504, "expert": 0.2675279974937439 }
9,275
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. Here is a portion of the code: Renderer.h: #pragma once #include <vulkan/vulkan.h> #include "Window.h" #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> #include "Pipeline.h" #include "Material.h" #include "Mesh.h" struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); VkDescriptorSetLayout CreateDescriptorSetLayout(); VkDescriptorPool CreateDescriptorPool(uint32_t maxSets); VkDevice* GetDevice(); VkPhysicalDevice* GetPhysicalDevice(); VkCommandPool* GetCommandPool(); VkQueue* GetGraphicsQueue(); VkCommandBuffer* GetCurrentCommandBuffer(); std::shared_ptr<Pipeline> GetPipeline(); void CreateGraphicsPipeline(Mesh* mesh, Material* material); VkDescriptorSetLayout CreateSamplerDescriptorSetLayout(); private: bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; std::vector<size_t> currentFramePerImage; std::vector<VkImage> swapChainImages; std::vector<VkImageView> swapChainImageViews; VkExtent2D swapChainExtent; VkRenderPass renderPass; uint32_t imageIndex; std::shared_ptr<Pipeline> pipeline; VkFormat swapChainImageFormat; std::vector<VkCommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); void Present(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" #include <chrono> #include <thread> class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); int MaxFPS = 60; private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; Scene.h: #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; BufferUtils.h: #pragma once #include <vulkan/vulkan.h> #include <stdint.h> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties); void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); } BufferUtils.cpp: #include "BufferUtils.h" #include <stdexcept> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create buffer!"); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } vkBindBufferMemory(device, buffer, bufferMemory, 0); } uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("Failed to find suitable memory type!"); } void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue); vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); } } Here are some relevant methods from Renderer.cpp: VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() { VkDescriptorSetLayoutBinding uboLayoutBinding{}; uboLayoutBinding.binding = 0; uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboLayoutBinding.descriptorCount = 1; uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; uboLayoutBinding.pImmutableSamplers = nullptr; // Add sampler layout binding VkDescriptorSetLayoutBinding samplerLayoutBinding{}; samplerLayoutBinding.binding = 1; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding }; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size()); layoutInfo.pBindings = bindings.data(); VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() { VkDescriptorSetLayoutBinding samplerLayoutBinding{}; samplerLayoutBinding.binding = 0; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &samplerLayoutBinding; VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create sampler descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) { VkDescriptorPoolSize poolSize{}; poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSize.descriptorCount = maxSets; // Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER VkDescriptorPoolSize samplerPoolSize{}; samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerPoolSize.descriptorCount = maxSets; std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize }; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); poolInfo.maxSets = maxSets; VkDescriptorPool descriptorPool; if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor pool!"); } return descriptorPool; } I am getting this error: VUID-vkUpdateDescriptorSets-None-03047(ERROR / SPEC): msgNum: 903342744 - Validation Error: [ VUID-vkUpdateDescriptorSets-None-03047 ] Object 0: handle = 0x2e2cd000000002b, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0x35d7ea98 | vkUpdateDescriptorSets() pDescriptorWrites[0] failed write update validation for VkDescriptorSet 0x2e2cd000000002b[] with error: Cannot call vkUpdateDescriptorSets() to perform write update on VkDescriptorSet 0x2e2cd000000002b[] allocated with VkDescriptorSetLayout 0xd10d270000000018[] that is in use by a command buffer. The Vulkan spec states: Descriptor bindings updated by this command which were created without the VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT or VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT bits set must not be used by any command that was recorded to a command buffer which is in the pending state (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkUpdateDescriptorSets-None-03047) How can I alter the code to fix this issue?
35d8c05d9d3958f90296b103a895b677
{ "intermediate": 0.3753734827041626, "beginner": 0.29778599739074707, "expert": 0.32684049010276794 }
9,276
draw me circle on python
8e664a1bf84c08fd2a2ad1ae0a83a0c2
{ "intermediate": 0.3365554213523865, "beginner": 0.2821851074695587, "expert": 0.3812595307826996 }
9,277
Linked list using python
00e28bf2477f551a4713bf1d220d04d0
{ "intermediate": 0.33820945024490356, "beginner": 0.2545223534107208, "expert": 0.4072681665420532 }
9,278
how to sort child document firestore database
e53bd61674dd58a229dfa86481db5b29
{ "intermediate": 0.35248538851737976, "beginner": 0.3492507338523865, "expert": 0.29826390743255615 }
9,279
in unity's ML Agents do I need to modify my PlayerController which works with player input? or do I need to create a new script and make references in the code to each other?
5a93a29072d2fe55a6921b26a16fc564
{ "intermediate": 0.4926096796989441, "beginner": 0.1400168240070343, "expert": 0.36737343668937683 }
9,280
correct this code it goes to infinite loop . .model small .data input db ? st db "*$" spa db 0dh,0ah,"$" v1 db ? .code mov ax,@data mov ds,ax mov ah,01 int 21h sub al,18 call pat jmp xyz pat proc mov cl,al mov bl,cl mov v1,1 l1: mov cl,v1 l2: lea dx,st mov ah,09 int 21h loop l2 inc v1 lea dx,spa mov ah,09 int 21h mov cl,bl dec bl loop l1 ret jmp xyz pat endp xyz:
2376e9f8474670a4f26fad7020c5c670
{ "intermediate": 0.14988793432712555, "beginner": 0.7141328454017639, "expert": 0.13597926497459412 }
9,281
pragma solidity 0.8.17; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see return msg.data; } } contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return 18; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { uint256 currentAllowance = _allowances[sender][_msgSender()]; if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } } _transfer(sender, recipient, amount); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } contract BaiQi is ERC20 { constructor () ERC20("Bai Qi", "BaiQi") { _mint(msg.sender, 420_690000000000 * (10 ** 18)); } } Explore the code above. Determine if this token is fraudulent or not
bee22862ac532fcbda71d3bd8f320cfb
{ "intermediate": 0.3307003974914551, "beginner": 0.45882126688957214, "expert": 0.21047836542129517 }
9,282
in unity's ML Agents do I need to modify my PlayerController which works with player input? or do I need to create a new script and make references in the code to each other?
4d38cd5cc21868bd47f5e86caf926ae1
{ "intermediate": 0.4926096796989441, "beginner": 0.1400168240070343, "expert": 0.36737343668937683 }
9,283
in unity's ML Agents do I need to modify my PlayerController which works with player input? or do I need to create a new script and make references in the code to each other?
594ff7eaf8db0e1a8a41a2094358fab0
{ "intermediate": 0.4926096796989441, "beginner": 0.1400168240070343, "expert": 0.36737343668937683 }
9,284
import sys import json import requests from web3 import Web3 # Define your Binance Smart Chain node URL here BSC_URL = 'https://bsc-dataseed1.binance.org' # Connect to Binance Smart Chain node w3 = Web3(Web3.HTTPProvider(BSC_URL)) # Check if connected to Binance Smart Chain node if not w3.isConnected(): print("Not connected to the Binance Smart Chain node.") sys.exit() def check_mint_vulnerability(abi): for item in abi: if item['type'] == 'function' and item['name'] == 'mint': if 'internal' not in item['stateMutability']: return True return False def check_transfer_fee_vulnerability(abi): for item in abi: if item['type'] == 'function' and item['name'] == 'transfer': for input in item['inputs']: if input['name'] == '_fee': fee = int(input['value']) if fee > 10: return True return False def check_ownable_vulnerability(abi): for item in abi: if item['type'] == 'function' and item['name'] == 'transferOwnership': if 'ownable' not in item.get('function_signature', ''): return True return False def check_renounce_ownership_vulnerability(abi): for item in abi: if item['type'] == 'function' and item['name'] == 'transferOwnership': if item.get('function_signature', '') == 'renounceOwnership()': return True return False def check_unusual_mappings_params(abi): unusual_mappings_params = ["lastClaimTimes", "excludedFromDividends", "tokenHoldersMap", "_isExcludedFromMaxWallet", "_isExcludedFromMaxTx", "_slipfeDeD", "_mAccount", "_release", "_sellSumETH", "_sellSum", "_buySum", "_marketersAndDevs", "balanceOf", "canSale", "_onSaleNum", "_intAddr", "cooldownTimer"] for item in abi: for unusual in unusual_mappings_params: if unusual in item.get("name", ""): return True return False def check_suspicious_encodePacked_calls(abi): suspicious_calls = ["encodePacked"] for item in abi: for suspicious in suspicious_calls: if suspicious in item.get("function_signature", ""): return True return False def check_hidden_address_usage(abi): hidden_addresses = ["TrustSwap", "receiveAddress", "deployer", "BSCGas", "Pancakeswap", "HecoGas", "MDEXBSC", "EtherGas", "Uniswap", "SnailExclusive", "rewardToken", "VERSOIN", "UniswapV2Router", "_otherAddress", "onlyAddress", "deadAddress", "allowedSeller", "dexContract", "pancakeRouterAddress"] for item in abi: for hidden in hidden_addresses: if hidden in item.get("name", ""): return True return False def check_onlyOwner_modifier_usage(abi): onlyOwner_functions = ["setSwapTokensAtAmount", "setSwapEnabled", "enableTrading", "changeTreasuryWallet", "changeStakingWallet", "changeMarketingWallet", "updateFees", "claimStuckTokens", "resetTaxAmount", "updatePoolWallet", "updateCharityWallet", "updateMarketingWallet", "setAutomatedMarketMakerPair", "updateSellFees", "updateBuyFees", "updateRescueSwap", "updateSwapEnabled", "airdropToWallets", "enableTrading", "setDeadWallet", "setSwapTokensAtAmount", "swapManual", "updateGasForProcessing", "setAutomatedMarketMakerPair", "setMarketingWallet", "setKing", "setAirdropNumbs", "updateUniswapV2Router", "processAccount", "setBalance", "updateMinimumTokenBalanceForDividends", "updateClaimWait", "distributeCAKEDividends", "disableSelling", "enableSelling"] for item in abi: for onlyOwner in onlyOwner_functions: if onlyOwner in item.get("name", "") and "onlyOwner" in item.get("modifiers", []): return True return False def analyze_contract(0x0d4890ecec59cd55d640d36f7acc6f7f512fdb6e): try: # Get contract ABI from BCSCAN API abi_response = requests.get(f'https://api.bscscan.com/api?module=contract&action=getabi&address={0x0d4890ecec59cd55d640d36f7acc6f7f512fdb6e}&apikey=CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS') abi = json.loads(abi_response.text)['result'] abi = json.loads(abi) # Create contract instance contract = w3.eth.contract(address=contract_address, abi=abi) # Analyze mint vulnerability if check_mint_vulnerability(abi): print("Mint function with potential vulnerability found.") else: print("Mint vulnerability not found.") # Analyze transfer fee vulnerability if check_transfer_fee_vulnerability(abi): print("High transfer fee vulnerability found.") else: print("High transfer fee vulnerability not found.") # Analyze ownable vulnerability if check_ownable_vulnerability(abi): print("Ownable vulnerability found.") else: print("Ownable vulnerability not found.") # Analyze renounce ownership vulnerability if check_renounce_ownership_vulnerability(abi): print("Renounce ownership vulnerability found.") else: print("Renounce ownership vulnerability not found.") # Additional vulnerability checks if check_unusual_mappings_params(abi): print("Unusual mappings or params found.") else: print("Unusual mappings or params not found.") if check_suspicious_encodePacked_calls(abi): print("Suspicious encodePacked calls found.") else: print("Suspicious encodePacked calls not found.") if check_hidden_address_usage(abi): print("Hidden address usage found.") else: print("Hidden address usage not found.") if check_onlyOwner_modifier_usage(abi): print("OnlyOwner modifier usage found.") else: print("OnlyOwner modifier usage not found.") except Exception as e: print("Error occurred while analyzing the contract:", e) if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: python rugcheck_bsc.py[contract_address]") sys.exit() contract_address = sys.argv[1] analyze_contract(contract_address) The code above throws an error. C:\Users\AshotxXx\PycharmProjects\RugCheck\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\RugCheck\main.py File "C:\Users\AshotxXx\PycharmProjects\RugCheck\main.py", line 98 try: IndentationError: expected an indented block after function definition on line 97 Process finished with exit code 1 Fix it
3f12a0011a57bfcadaf2c4800b57fb17
{ "intermediate": 0.3147673010826111, "beginner": 0.46689337491989136, "expert": 0.21833929419517517 }
9,285
what is the command for: killall KVImmunoblot9?
502306365bc05998b362ee5d288febd7
{ "intermediate": 0.3646661043167114, "beginner": 0.22569257020950317, "expert": 0.4096412658691406 }
9,286
latex公式:\text { (2) 已知 }\left{\begin{array}{3} \sqrt{a^{2}+b^{2}} \ \sqrt{a^{2}+c^{2}} \ \sqrt{b^{2}+c^{2}} \end{array}\text { 的值,} \right. 在转码显示是提示Parser Error:Unknown column alignment:3 的错误
4aef53f63cd5d285551f4d2d0455c463
{ "intermediate": 0.34503045678138733, "beginner": 0.3843584358692169, "expert": 0.2706111669540405 }
9,287
are the following correct? To test if the serial connectors function properly, use a USB to serial adapter to connect a serial connector of the Board and the host computer first, then use a serial tool for the serial debugging. This will involve the use of a serial communication program such as minicom. Or, you can short any two of the serial connectors and use one connector for transmitting data and the other for receiving data. This allows you to input the commands directly in the terminal.
036298ac9f4ec00c66b65db73bcb37ba
{ "intermediate": 0.5879149436950684, "beginner": 0.236923947930336, "expert": 0.17516116797924042 }
9,288
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000)) frame = pd.DataFrame(klines, columns=['Open time', 'Open', 'High', 'Low', 'Close', 'Volume', 'Close time', 'Quote asset volume', 'Number of trades', 'Taker buy base asset volume', 'Taker buy quote asset volume', 'Ignore']) frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # drop the last candle we fetched return frame df = getminutedata('BTCUSDT', '1m', '44640') def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) time.sleep(1) # Add a delay of 1 second But I getting ERROR: 05/31/2023 09:51:47 Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 50, in <module> df = getminutedata('BTCUSDT', '1m', '44640') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 41, in getminutedata klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000)) ~~~~~~~~^~ TypeError: can only concatenate str (not "int") to str Please tell me what I need to change
bec0694df35ad0af7b82d4fe050dbfc5
{ "intermediate": 0.36938726902008057, "beginner": 0.3605802059173584, "expert": 0.27003249526023865 }
9,289
i have a json "Name Surname" and i want to extract the Surname, which could be more than one word, using lodash methods like compact and join
81f8b5a332b8385ea9aa419e20b790a2
{ "intermediate": 0.5025610327720642, "beginner": 0.17550799250602722, "expert": 0.32193097472190857 }
9,290
flutter TextFormField padding from input text to border how to increase?
630aa5de323800f2c4aae913633fcb9f
{ "intermediate": 0.376502126455307, "beginner": 0.23659935593605042, "expert": 0.3868984878063202 }
9,291
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000)) frame = pd.DataFrame(klines, columns=['id', 'price', 'qty', 'time', 'isBuyerMaker', 'isBestMatch']) frame = frame[['Open time', 'Open', 'High', 'Low', 'Close', 'Volume']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # drop the last candle we fetched return frame df = getminutedata('BTCUSDT', '1m', 44640) def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) time.sleep(1) # Add a delay of 1 second But I getting ERROR: 05/31/2023 10:12:18 Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 48, in <module> df = getminutedata('BTCUSDT', '1m', 44640) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 42, in getminutedata frame = pd.DataFrame(klines, columns=['id', 'price', 'qty', 'time', 'isBuyerMaker', 'isBestMatch']) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\pandas\core\frame.py", line 817, in __init__ raise ValueError("DataFrame constructor not properly called!") ValueError: DataFrame constructor not properly called! sys:1: RuntimeWarning: coroutine 'ClientBase._request' was never awaited
b81a802d4af8aca55565bc5b72877732
{ "intermediate": 0.41337549686431885, "beginner": 0.36629176139831543, "expert": 0.22033274173736572 }
9,292
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = 'Y0ReOvKcXm8e3wfIRYlgcdV9UG10M7XqxsGV0H83S8OMH3H3Fym3iqsfIcHDiq92' API_SECRET = '0u8aMxMXyIy9dQCti8m4AOeSvAGEqugOiIDML4rxVWDx5dzI80TDGNCMOWn4geVg' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame df = getminutedata('BTCUSDT', '1m', 44640) def signal_generator(df): open = df.Price.iloc[-1] close = df.Price.iloc[-1] previous_open = df.Price.iloc[-2] previous_close = df.Price.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) async def main(): while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = getminutedata('BTCUSDT', '1m', 44640) # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) await asyncio.sleep(1) # Await execution with asyncio in an async function if name == 'main': asyncio.run(main()) But I getting undefind "name" in line 206
80509e42b9af59cd7056fb2c081baa8e
{ "intermediate": 0.3478615880012512, "beginner": 0.4777432382106781, "expert": 0.17439521849155426 }
9,293
Is it possible to code a plasmoid widget for arch linux that can display a gif image
b192e89e7955d76c349947d43fc292e4
{ "intermediate": 0.4385806620121002, "beginner": 0.1184641495347023, "expert": 0.4429551362991333 }
9,294
create pinescript version 5 code for below strategy : if close price go to upper from HMA(105) buy command. if close price go to down from HMA(105) sell command. in two direction i want stop loss equals 0.7% and take profit equals to 1.4 %
1fa0587fa2276d065e5ce6b36c8201e6
{ "intermediate": 0.34214237332344055, "beginner": 0.26242613792419434, "expert": 0.3954314887523651 }
9,295
Javascript Date Parse with specific locale
bfe275a53f990b43bd15ee03e86b6dbf
{ "intermediate": 0.35051414370536804, "beginner": 0.29476839303970337, "expert": 0.354717493057251 }
9,296
исправь код для вызова очистки куков в гугл хроме fun clearCookies(){ log("clearCookies") when (DaimaSessionState.currentBrowser){ Browsers.CHROME -> { ChromeWindow.attach().click() sleepy(1) sendKeysHere(_raw = true,"+^{DELETE}") sleepy(2) ChromeWindow.clearBrowserData.attach(_deep = true) ChromeWindow.clearBrowserData.tab.attach() ChromeWindow.clearBrowserData.tab.advancedTI.attach().click() sleepy(2) val cmb = ChromeWindow.clearBrowserData.TimerangeCmB.attach().click() sleepy(1) cmb.getCurrentTarget()!!.clickLeftOffscreen(39,90) sleepy(1) ChromeWindow.clearBrowserData.cleardataB.attach().click() sleepy(5) } else -> { throw (UnsupportedBrowserException(DaimaSessionState.currentBrowser)) } }
3c3422706737d07f106f901cb5835d04
{ "intermediate": 0.3486177325248718, "beginner": 0.4059300720691681, "expert": 0.24545226991176605 }
9,297
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. Here is a portion of the code: Renderer.h: #pragma once #include <vulkan/vulkan.h> #include "Window.h" #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> #include "Pipeline.h" #include "Material.h" #include "Mesh.h" struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); VkDescriptorSetLayout CreateDescriptorSetLayout(); VkDescriptorPool CreateDescriptorPool(uint32_t maxSets); VkDevice* GetDevice(); VkPhysicalDevice* GetPhysicalDevice(); VkCommandPool* GetCommandPool(); VkQueue* GetGraphicsQueue(); VkCommandBuffer* GetCurrentCommandBuffer(); std::shared_ptr<Pipeline> GetPipeline(); void CreateGraphicsPipeline(Mesh* mesh, Material* material); VkDescriptorSetLayout CreateSamplerDescriptorSetLayout(); private: bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; std::vector<size_t> currentFramePerImage; std::vector<VkImage> swapChainImages; std::vector<VkImageView> swapChainImageViews; VkExtent2D swapChainExtent; VkRenderPass renderPass; uint32_t imageIndex; std::shared_ptr<Pipeline> pipeline; VkFormat swapChainImageFormat; std::vector<VkCommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); void Present(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" #include <chrono> #include <thread> class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); int MaxFPS = 60; private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; Scene.h: #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; BufferUtils.h: #pragma once #include <vulkan/vulkan.h> #include <stdint.h> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties); void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); } BufferUtils.cpp: #include "BufferUtils.h" #include <stdexcept> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create buffer!"); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } vkBindBufferMemory(device, buffer, bufferMemory, 0); } uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("Failed to find suitable memory type!"); } void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue); vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); } } Here are some relevant methods from Renderer.cpp: VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() { VkDescriptorSetLayoutBinding uboLayoutBinding{}; uboLayoutBinding.binding = 0; uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboLayoutBinding.descriptorCount = 1; uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; uboLayoutBinding.pImmutableSamplers = nullptr; // Add sampler layout binding VkDescriptorSetLayoutBinding samplerLayoutBinding{}; samplerLayoutBinding.binding = 1; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding }; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size()); layoutInfo.pBindings = bindings.data(); VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() { VkDescriptorSetLayoutBinding samplerLayoutBinding{}; samplerLayoutBinding.binding = 0; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &samplerLayoutBinding; VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create sampler descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) { VkDescriptorPoolSize poolSize{}; poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSize.descriptorCount = maxSets; // Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER VkDescriptorPoolSize samplerPoolSize{}; samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerPoolSize.descriptorCount = maxSets; std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize }; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); poolInfo.maxSets = maxSets; VkDescriptorPool descriptorPool; if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor pool!"); } return descriptorPool; } I am getting this error: VUID-vkCmdBindDescriptorSets-pDescriptorSets-00358(ERROR / SPEC): msgNum: -507995293 - Validation Error: [ VUID-vkCmdBindDescriptorSets-pDescriptorSets-00358 ] Object 0: handle = 0xb097c90000000027, type = VK_OBJECT_TYPE_DESCRIPTOR_SET; | MessageID = 0xe1b89b63 | vkCmdBindDescriptorSets(): descriptorSet #0 being bound is not compatible with overlapping descriptorSetLayout at index 0 of VkPipelineLayout 0x3fbcd60000000028[] due to: VkDescriptorSetLayout 0x9fde6b0000000014[] from pipeline layout has 2 total descriptors, but VkDescriptorSetLayout 0xdd3a8a0000000015[], which is bound, has 1 total descriptors.. The Vulkan spec states: Each element of pDescriptorSets must have been allocated with a VkDescriptorSetLayout that matches (is the same as, or identically defined as) the VkDescriptorSetLayout at set n in layout, where n is the sum of firstSet and the index into pDescriptorSets (https://vulkan.lunarg.com/doc/view/1.3.239.0/windows/1.3-extensions/vkspec.html#VUID-vkCmdBindDescriptorSets-pDescriptorSets-00358) Objects: 1 How can I alter the code to fix this issue?
43d81f9e0db9b9ae871ed51e40c319c3
{ "intermediate": 0.3753734827041626, "beginner": 0.29778599739074707, "expert": 0.32684049010276794 }
9,298
How to parse Date time with specific Locale?
3c903ed3d2a9ba245ddad23ce400a747
{ "intermediate": 0.35369160771369934, "beginner": 0.149526908993721, "expert": 0.49678146839141846 }
9,299
i have a const lastname = "Andrea Rossi Neri" and i want to extract Rossi Neri using lodash methods
5aca1f1e68cfb37be95238515a50c38a
{ "intermediate": 0.37376686930656433, "beginner": 0.223197340965271, "expert": 0.4030357301235199 }
9,300
I usd your code: `import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback+1, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame df = getminutedata('BTCUSDT', '1m', 44640) def signal_generator(df): open = df.Price.iloc[-1] close = df.Price.iloc[-1] previous_open = df.Price.iloc[-2] previous_close = df.Price.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) async def main(): while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = getminutedata('BTCUSDT', '1m', 44640) # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) await asyncio.sleep(1) # Await execution with asyncio in an async function if name == 'main': asyncio.run(main())` But I have undefind ERROR "name" what is this name ?
7cc290a5bf78ef91e255e694e145a032
{ "intermediate": 0.38923659920692444, "beginner": 0.3203514814376831, "expert": 0.29041191935539246 }
9,301
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. Here is a portion of the code: Renderer.h: #pragma once #include <vulkan/vulkan.h> #include "Window.h" #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> #include "Pipeline.h" #include "Material.h" #include "Mesh.h" struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); VkDescriptorSetLayout CreateDescriptorSetLayout(); VkDescriptorPool CreateDescriptorPool(uint32_t maxSets); VkDevice* GetDevice(); VkPhysicalDevice* GetPhysicalDevice(); VkCommandPool* GetCommandPool(); VkQueue* GetGraphicsQueue(); VkCommandBuffer* GetCurrentCommandBuffer(); std::shared_ptr<Pipeline> GetPipeline(); void CreateGraphicsPipeline(Mesh* mesh, Material* material); VkDescriptorSetLayout CreateSamplerDescriptorSetLayout(); private: bool shutdownInProgress; uint32_t currentCmdBufferIndex = 0; std::vector<size_t> currentFramePerImage; std::vector<VkImage> swapChainImages; std::vector<VkImageView> swapChainImageViews; VkExtent2D swapChainExtent; VkRenderPass renderPass; uint32_t imageIndex; std::shared_ptr<Pipeline> pipeline; VkFormat swapChainImageFormat; std::vector<VkCommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); void Present(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); material->CreateDescriptorSet(renderer.CreateDescriptorSetLayout(), renderer.CreateDescriptorPool(1), mvpBuffer, sizeof(MVP)); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer //vkDestroyBuffer(device, mvpBuffer, nullptr); //vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" #include <chrono> #include <thread> class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); int MaxFPS = 60; private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; Scene.h: #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; BufferUtils.h: #pragma once #include <vulkan/vulkan.h> #include <stdint.h> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties); void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); } BufferUtils.cpp: #include "BufferUtils.h" #include <stdexcept> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory) { VkBufferCreateInfo bufferInfo{}; bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferInfo.size = size; bufferInfo.usage = usage; bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &bufferInfo, nullptr, &buffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create buffer!"); } VkMemoryRequirements memRequirements; vkGetBufferMemoryRequirements(device, buffer, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device, &allocInfo, nullptr, &bufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate buffer memory!"); } vkBindBufferMemory(device, buffer, bufferMemory, 0); } uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties) { VkPhysicalDeviceMemoryProperties memProperties; vkGetPhysicalDeviceMemoryProperties(physicalDevice, &memProperties); for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++) { if ((typeFilter & (1 << i)) && (memProperties.memoryTypes[i].propertyFlags & properties) == properties) { return i; } } throw std::runtime_error("Failed to find suitable memory type!"); } void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size) { VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferCopy copyRegion{}; copyRegion.srcOffset = 0; // Optional copyRegion.dstOffset = 0; // Optional copyRegion.size = size; vkCmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, 1, &copyRegion); vkEndCommandBuffer(commandBuffer); VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue); vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); } } Camera.h: #pragma once #include <glm/glm.hpp> class Camera { public: Camera(); ~Camera(); void Initialize(float aspectRatio); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); const glm::mat4& GetViewMatrix() const; const glm::mat4& GetProjectionMatrix() const; private: glm::vec3 position; glm::vec3 rotation; glm::mat4 viewMatrix; glm::mat4 projectionMatrix; void UpdateViewMatrix(); }; Camera.cpp: #include "Camera.h" #include <glm/gtc/matrix_transform.hpp> Camera::Camera() : position(0.0f), rotation(0.0f) { } Camera::~Camera() { Shutdown(); } void Camera::Initialize(float aspectRatio) { projectionMatrix = glm::perspective(glm::radians(45.0f), aspectRatio, 0.1f, 100.0f); } void Camera::Shutdown() { } void Camera::SetPosition(const glm::vec3& position) { this->position = position; UpdateViewMatrix(); } void Camera::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateViewMatrix(); } const glm::mat4& Camera::GetViewMatrix() const { return viewMatrix; } const glm::mat4& Camera::GetProjectionMatrix() const { return projectionMatrix; } void Camera::UpdateViewMatrix() { glm::mat4 rotMatrix = glm::mat4(1.0f); rotMatrix = glm::rotate(rotMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); rotMatrix = glm::rotate(rotMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); rotMatrix = glm::rotate(rotMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); glm::vec3 lookAt = glm::vec3(rotMatrix * glm::vec4(0.0f, 0.0f, -1.0f, 0.0f)); viewMatrix = glm::lookAt(position, position + lookAt, glm::vec3(0.0f, 1.0f, 0.0f)); } Here are some relevant methods from Renderer.cpp: VkDescriptorSetLayout Renderer::CreateDescriptorSetLayout() { VkDescriptorSetLayoutBinding uboLayoutBinding{}; uboLayoutBinding.binding = 0; uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; uboLayoutBinding.descriptorCount = 1; uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT; uboLayoutBinding.pImmutableSamplers = nullptr; // Add sampler layout binding VkDescriptorSetLayoutBinding samplerLayoutBinding{}; samplerLayoutBinding.binding = 1; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding }; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size()); layoutInfo.pBindings = bindings.data(); VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorSetLayout Renderer::CreateSamplerDescriptorSetLayout() { VkDescriptorSetLayoutBinding samplerLayoutBinding{}; samplerLayoutBinding.binding = 0; samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerLayoutBinding.descriptorCount = 1; samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT; samplerLayoutBinding.pImmutableSamplers = nullptr; VkDescriptorSetLayoutCreateInfo layoutInfo{}; layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; layoutInfo.bindingCount = 1; layoutInfo.pBindings = &samplerLayoutBinding; VkDescriptorSetLayout descriptorSetLayout; if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create sampler descriptor set layout!"); } return descriptorSetLayout; } VkDescriptorPool Renderer::CreateDescriptorPool(uint32_t maxSets) { VkDescriptorPoolSize poolSize{}; poolSize.type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; poolSize.descriptorCount = maxSets; // Add an additional descriptor pool size for COMBINED_IMAGE_SAMPLER VkDescriptorPoolSize samplerPoolSize{}; samplerPoolSize.type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; samplerPoolSize.descriptorCount = maxSets; std::array<VkDescriptorPoolSize, 2> poolSizes = { poolSize, samplerPoolSize }; VkDescriptorPoolCreateInfo poolInfo{}; poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size()); poolInfo.pPoolSizes = poolSizes.data(); poolInfo.maxSets = maxSets; VkDescriptorPool descriptorPool; if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) { throw std::runtime_error("Failed to create descriptor pool!"); } return descriptorPool; } Vertex Shader: #version 450 layout(binding = 0) uniform UniformBufferObject { mat4 model; mat4 view; mat4 proj; } ubo; layout(location = 0) in vec3 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0); fragColor = inColor; } Fragment Shader: #version 450 layout(binding = 1) uniform sampler2D texSampler; layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(1,0,1,1); } The code currently creates a square tile somewhere in the scene. I'm concerned it may not be rendering at all. How can I adjust the code so it is pointing at the tile so I can verify it is rendering properly?
221c2907047ab1c215f584fb9c93eb3a
{ "intermediate": 0.3753734827041626, "beginner": 0.29778599739074707, "expert": 0.32684049010276794 }
9,302
Stripe error PS C:\Users\Mdeepa\Documents\Stripe\test-payment\starter\starter-java\server> mvn package mvn : The term 'mvn' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + mvn package + ~~~ + CategoryInfo : ObjectNotFound: (mvn:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
9f61fd0358f206fe38b26c23b4574177
{ "intermediate": 0.490050733089447, "beginner": 0.22283722460269928, "expert": 0.2871120870113373 }
9,303
give me an example of failure to do lock free programming due to branch predicting, and the abuse of std::memory_order_relaxed
2f97d17db402737e7b1098ffb2ef8086
{ "intermediate": 0.5592547655105591, "beginner": 0.09174676239490509, "expert": 0.3489985466003418 }
9,304
Привет, помоги с рефакторингом using UnityEngine; using Zarnitza.FireExtinguisherVR.DeviceStatusChecker; using Zarnitza.FireExtinguisherVR.Messages; using Zarnitza.FireExtinguisherVR.Options; using Zarnitza.FireExtinguisherVR.Quests; using Zenject; namespace Zarnitza.FireExtinguisherVR.Setting { public class SettingsFireExtinguishers : MonoBehaviour { [SerializeField] private ControlBoxFireExtinguishers fireExtinguishers; [SerializeField] private DeviceStatusCheckerUI deviceStatusCheckerUIAll; [SerializeField] private DeviceStatusCheckerUI deviceStatusCheckerUIOne; [Inject] private SessionSetting sessionSetting = null; private void Start() { SetSettingsFireExtinguishers(); } private void SetSettingsFireExtinguishers() { var configManagerFireExtinguishers = new ConfigManagerFireExtinguishers(); ConfigDataFireExtinguishers configDataFireExtinguishers; configDataFireExtinguishers = configManagerFireExtinguishers.GetSettingsFireExtinguisher(); if (configDataFireExtinguishers.offAllExtinguishers) { deviceStatusCheckerUIAll.gameObject.SetActive(false); deviceStatusCheckerUIOne.gameObject.SetActive(false); fireExtinguishers.Setting( new SettingsFireExtinguishersMessage(false, false, false)); deviceStatusCheckerUIAll.Setting(new SettingsFireExtinguishersMessage(false, false, false)); sessionSetting.NumberRealFireExtinguishers = NumberRealFireExtinguishers.OffFireExtinguishers; } else if (configDataFireExtinguishers.onAllExtinguishers) { deviceStatusCheckerUIAll.gameObject.SetActive(true); deviceStatusCheckerUIOne.gameObject.SetActive(false); fireExtinguishers.Setting(new SettingsFireExtinguishersMessage(true, true, true)); deviceStatusCheckerUIAll.Setting(new SettingsFireExtinguishersMessage(true, true, true)); sessionSetting.NumberRealFireExtinguishers = NumberRealFireExtinguishers.AllFireExtinguishers; } else if (configDataFireExtinguishers.oneExtinguisherOP) { deviceStatusCheckerUIAll.gameObject.SetActive(false); deviceStatusCheckerUIOne.gameObject.SetActive(true); fireExtinguishers.Setting(new SettingsFireExtinguishersMessage(true, false, false)); deviceStatusCheckerUIOne.Setting(new SettingsFireExtinguishersMessage(true, false, false)); sessionSetting.NumberRealFireExtinguishers = NumberRealFireExtinguishers.OneFireExtinguishers; } } } }
6e5cdb5744468e21510f3fb38a63b2e8
{ "intermediate": 0.31879234313964844, "beginner": 0.5628098249435425, "expert": 0.11839783191680908 }
9,305
Give me step by step instructions on how to get the source code for a search engine website and download the entire file structure in to my computer
d5e8bb14635f4d6e63753f3d3a89e9f3
{ "intermediate": 0.6643385887145996, "beginner": 0.14374157786369324, "expert": 0.19191986322402954 }
9,306
c++ intentionally crash my program by throwing an error, how do i do that
dfa4ec41bd5df1064e642fd083944f4b
{ "intermediate": 0.46795710921287537, "beginner": 0.1998901069164276, "expert": 0.3321528136730194 }
9,307
In the code following there is a lot of bad flickering, the animations are not smooth, and some symbols appear to come out blank, can you improve this? maybe creating a strip of the png files and using canvas coords to animate might be a better solution towhat I have here? import random import tkinter as tk from PIL import Image, ImageTk root = tk.Tk() root.title("Slot machine reels demo") canvas_width = 340 canvas_height = 60 symbol_size = 60 num_symbols = 5 reel = [] symbol_photo = None symbol = None symbols = {"bar": "bar.png", "cherry": "cherry.png", "coin": "coin.png", "lemon": "lemon.png", "plum": "plum.png", "tomatoe": "tom.png",} symbols_list = list(symbols.keys()) canvas = tk.Canvas(root, width=canvas_width, height=canvas_height) canvas.grid(row=0, column=0, columnspan=3, padx=10, pady=10) def get_a_rnd_symbol(): """ Choose a random symbol and store in symbol_photo. """ global symbol_photo, symbol symbol = random.choice(symbols_list) symbol_image = Image.open(symbols[symbol]) symbol_image = symbol_image.resize((symbol_size, symbol_size)) symbol_photo = ImageTk.PhotoImage(symbol_image) def get_startup_rnd_symbols(): """ Get symbols to place on reels for start up.""" global symbol_photo, symbol for j in range(num_symbols): get_a_rnd_symbol() # choose a rnd symbol symbol_label = canvas.create_image(j * (symbol_size + 10), 0, anchor=tk.NW, image=symbol_photo) reel.append((symbol_label, symbol_photo)) canvas.update() def spin_reel(j, count, stop_point): """ Spin a single reel. """ if count == stop_point: return get_a_rnd_symbol() old_symbol_label, _ = reel[j] new_symbol_label = canvas.create_image(j * (symbol_size + 10), -symbol_size, anchor=tk.NW, image=symbol_photo) for k in range(symbol_size // 2): canvas.move(old_symbol_label, 0, 2) canvas.move(new_symbol_label, 0, 2) canvas.update() reel[j] = (new_symbol_label, symbol_photo) root.after(10, spin_reel, j, count+1, stop_point) def spin_reels(): """ Spin all reels. """ spin_btn.config(state="disabled") # to stop multiclicking # choose a random stopping point for each reel stop_points = [random.randint(8, 12) for _ in range(num_symbols)] # spin the reels until they reach their stopping points counts = [0] * num_symbols while sum(counts) < sum(stop_points): for j in range(num_symbols): if counts[j] < stop_points[j]: spin_reel(j, counts[j], stop_points[j]) counts[j] += 1 # set the final symbol for each reel for j in range(num_symbols): symbol_image = symbols[symbol][:-4] # remove ".png" _, symbol_photo = reel[j] symbol_photo.image = ImageTk.PhotoImage(Image.open(symbols[symbol]).resize((symbol_size, symbol_size))) canvas.itemconfig(reel[j][0], image=symbol_photo) spin_btn.config(state="normal") spin_btn = tk.Button(root, text="Spin", command=spin_reels) spin_btn.grid(row=1, column=1) get_startup_rnd_symbols() root.mainloop()
8850619982dc173575186e0265c79431
{ "intermediate": 0.3670222759246826, "beginner": 0.38096293807029724, "expert": 0.25201481580734253 }
9,308
using UnityEngine; using Valve.VR; using Zarnitza.FireExtinguisherVR.FireExtinguisher; using Zarnitza.FireExtinguisherVR.Menu.Messages; using Zarnitza.FireExtinguisherVR.MessageBus; using Zarnitza.FireExtinguisherVR.Messages; using Zarnitza.FireExtinguisherVR.Quests; using Zenject; public class ControlBoxFireExtinguishers : MonoBehaviour { [Inject] private ISubscriber subscriber = null; [Inject] private IPublisher publisher = null; [SerializeField] private FireExtinguisherInstaller FireExtinguisherOP; [SerializeField] private FireExtinguisherInstaller FireExtinguisherOU; [SerializeField] private FireExtinguisherInstaller FireExtinguisherOVP; [SerializeField] private SteamVR_Behaviour_Pose FireExtinguisherTipOP; [SerializeField] private SteamVR_Behaviour_Pose FireExtinguisherTipOU; [SerializeField] private SteamVR_Behaviour_Pose FireExtinguisherTipOVP; [SerializeField] private SteamVR_Action_Pose controllerBasePoseAction; [SerializeField] private SteamVR_Action_Pose controllerBasePoseTipAction; private SteamVR_Action_Pose controllerOPPoseTipAction; private SteamVR_Action_Pose controllerOVPPoseTipAction; private SteamVR_Action_Pose controllerOUPoseTipAction; private SteamVR_Action_Pose controllerOPPoseAction; private SteamVR_Action_Pose controllerOVPPoseAction; private SteamVR_Action_Pose controllerOUPoseAction; private SteamVR_Behaviour_Pose controllerOPPoseTipBehaviour; private SteamVR_Behaviour_Pose controllerOVPPoseTipBehaviour; private SteamVR_Behaviour_Pose controllerOUPoseTipBehaviour; private SteamVR_Behaviour_Pose controllerOPPoseBehaviour; private SteamVR_Behaviour_Pose controllerOVPPoseBehaviour; private SteamVR_Behaviour_Pose controllerOUPoseBehaviour; private void Start() { subscriber.Subscriber<SwitchFireExtinguisherMessage>(SwitchFireExtinguisher); controllerOPPoseAction = FireExtinguisherOP.GetComponent<SteamVR_Behaviour_Pose>().poseAction; controllerOVPPoseAction = FireExtinguisherOVP.GetComponent<SteamVR_Behaviour_Pose>().poseAction; controllerOUPoseAction = FireExtinguisherOU.GetComponent<SteamVR_Behaviour_Pose>().poseAction; controllerOPPoseTipAction = FireExtinguisherTipOP.poseAction; controllerOVPPoseTipAction = FireExtinguisherTipOVP.poseAction; controllerOUPoseTipAction = FireExtinguisherTipOU.poseAction; controllerOPPoseTipBehaviour = FireExtinguisherTipOP; controllerOVPPoseTipBehaviour = FireExtinguisherTipOVP; controllerOUPoseTipBehaviour = FireExtinguisherTipOU; controllerOPPoseBehaviour = FireExtinguisherOP.GetComponent<SteamVR_Behaviour_Pose>(); controllerOVPPoseBehaviour = FireExtinguisherOVP.GetComponent<SteamVR_Behaviour_Pose>(); controllerOUPoseBehaviour = FireExtinguisherOU.GetComponent<SteamVR_Behaviour_Pose>(); controllerBasePoseAction = controllerOPPoseAction; controllerBasePoseTipAction = controllerOPPoseTipAction; var fireExtinguisher = FireExtinguisherOP.gameObject.GetComponent<FireExtinguisher>(); publisher.Publish(new ActivationCurrentFireExtinguisherMessage(fireExtinguisher)); } public void Setting(SettingsFireExtinguishersMessage message) { FireExtinguisherOP.gameObject.SetActive(message.FireExtinguishersOP); FireExtinguisherOU.gameObject.SetActive(message.FireExtinguishersOU); FireExtinguisherOVP.gameObject.SetActive(message.FireExtinguishersOVP); } private void SwitchFireExtinguisher(SwitchFireExtinguisherMessage message) { switch (message.FireExtinguisherType) { case FireExtinguisherType.OP: RestoreValuesBody(); RestoreValuesTip(); OffAllFireExtinguishers(); FireExtinguisherOP.gameObject.SetActive(true); controllerOPPoseBehaviour.poseAction = controllerBasePoseAction; controllerOPPoseTipBehaviour.poseAction = controllerBasePoseTipAction; publisher.Publish(new ActivationCurrentFireExtinguisherMessage(FireExtinguisherOP.gameObject.GetComponent<FireExtinguisher>())); break; case FireExtinguisherType.OU: RestoreValuesBody(); RestoreValuesTip(); OffAllFireExtinguishers(); FireExtinguisherOU.gameObject.SetActive(true); controllerOUPoseBehaviour.poseAction = controllerBasePoseAction; controllerOUPoseTipBehaviour.poseAction = controllerBasePoseTipAction; publisher.Publish(new ActivationCurrentFireExtinguisherMessage(FireExtinguisherOU.gameObject.GetComponent<FireExtinguisher>())); break; case FireExtinguisherType.OVP: RestoreValuesBody(); RestoreValuesTip(); OffAllFireExtinguishers(); FireExtinguisherOVP.gameObject.SetActive(true); controllerOVPPoseBehaviour.poseAction = controllerBasePoseAction; controllerOVPPoseTipBehaviour.poseAction = controllerBasePoseTipAction; publisher.Publish(new ActivationCurrentFireExtinguisherMessage(FireExtinguisherOVP.gameObject.GetComponent<FireExtinguisher>())); break; } } private void RestoreValuesBody() { controllerOPPoseBehaviour.poseAction = controllerOPPoseAction; controllerOUPoseBehaviour.poseAction = controllerOUPoseAction; controllerOVPPoseBehaviour.poseAction = controllerOVPPoseAction; } private void RestoreValuesTip() { controllerOPPoseTipBehaviour.poseAction = controllerOPPoseTipAction; controllerOUPoseTipBehaviour.poseAction = controllerOUPoseTipAction; controllerOVPPoseTipBehaviour.poseAction = controllerOVPPoseTipAction; } private void OffAllFireExtinguishers() { FireExtinguisherOP.gameObject.SetActive(false); FireExtinguisherOU.gameObject.SetActive(false); FireExtinguisherOVP.gameObject.SetActive(false); } private void OnEnable() { subscriber.UnSudscribe<SwitchFireExtinguisherMessage>(SwitchFireExtinguisher); } } можешь помочь с рефакторингом
21f03141171f05f63f2aced822f92932
{ "intermediate": 0.2438374012708664, "beginner": 0.5243194699287415, "expert": 0.23184309899806976 }
9,309
write python function that generates a given number of files with random contents and different extensions in the same folder as the script
a10a4c04d51268b6db69e885c7ec4425
{ "intermediate": 0.3511574864387512, "beginner": 0.2190859168767929, "expert": 0.4297565519809723 }
9,310
Write a c++ program that gets data from oracle database and store the data into a file.
c2956def4201c30818ec047277e1bec6
{ "intermediate": 0.4419322609901428, "beginner": 0.13196201622486115, "expert": 0.42610567808151245 }
9,311
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): klines = client.get_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame df = getminutedata('BTCUSDT', '1m', 44640) def signal_generator(df): open = df.Price.iloc[-1] close = df.Price.iloc[-1] previous_open = df.Price.iloc[-2] previous_close = df.Price.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) async def main(): while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = getminutedata('BTCUSDT', '1m', 44640) # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) await asyncio.sleep(1) # Await execution with asyncio in an async function time.sleep(1) But I getting ERROR:05/31/2023 11:22:56 Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 51, in <module> df = getminutedata('BTCUSDT', '1m', 44640) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 43, in getminutedata klines = [list(map(str, kline)) for kline in klines] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: 'coroutine' object is not iterable sys:1: RuntimeWarning: coroutine 'ClientBase._request' was never awaited
8603efa7be10025e3363470f80bd2603
{ "intermediate": 0.3947089612483978, "beginner": 0.35758769512176514, "expert": 0.24770332872867584 }
9,312
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) async def getminutedata(symbol, interval, lookback): klines = await client.futures_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame df = await getminutedata('BTCUSDT', '1m', 44640) def signal_generator(df): open = df.Price.iloc[-1] close = df.Price.iloc[-1] previous_open = df.Price.iloc[-2] previous_close = df.Price.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) async def main(): while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = await getminutedata('BTCUSDT', '1m', 44640) # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: await order_execution('BTCUSDT', current_signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) await asyncio.sleep(1) # Await execution with asyncio in an async function But I getting ERROR: File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 51 df = await getminutedata('BTCUSDT', '1m', 44640) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ SyntaxError: 'await' outside function
fcc18fbef47705f551c56772ff400e70
{ "intermediate": 0.3756377100944519, "beginner": 0.37252306938171387, "expert": 0.2518392503261566 }
9,313
I have a matrix with 3 columns , and I want to draw a 3d plane plot in mtalab which is the first column is x axis and the second is y axis and third is z axis.
07ffd955853dc92bcb3b0c1b89dccb53
{ "intermediate": 0.41450977325439453, "beginner": 0.24891307950019836, "expert": 0.3365771770477295 }
9,314
hi
931c542cc137e27377c41b24c6f2a344
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
9,315
QNetworkConfigurationManager manager; QNetworkSession session(manager.defaultConfiguration()); return session.state() == QNetworkSession::Connected;应用程序调用dll 中的方法
aeedccd1d51b634fce73b5eacbe0c636
{ "intermediate": 0.43482542037963867, "beginner": 0.34933948516845703, "expert": 0.21583500504493713 }
9,316
Write a C# program that collects data form oracle database via oracle client and saves it to a file
76b51acbb4ea391ac71c367f65c3e70a
{ "intermediate": 0.46438339352607727, "beginner": 0.15682408213615417, "expert": 0.37879249453544617 }
9,317
Code Example for Obtaining All Physical Addresses of the Current Process from the Linux Kernel
453634cfd50cd3e3c8a45033b1af0af6
{ "intermediate": 0.38111934065818787, "beginner": 0.21480660140514374, "expert": 0.4040740132331848 }
9,318
reportlab canvas to PdfReader without temp file
32911f5fb40987814b108790d80c40dd
{ "intermediate": 0.4547739624977112, "beginner": 0.26202914118766785, "expert": 0.28319689631462097 }
9,319
powershell list all files that contain string
acb34cc9e85805bc57c6b5d7d94fa9fd
{ "intermediate": 0.3684934675693512, "beginner": 0.3003283739089966, "expert": 0.3311781585216522 }
9,320
ExceptionUtils show stacktrace
f4b2be4bead72a0c725b31aec3b6983b
{ "intermediate": 0.6796149015426636, "beginner": 0.16117383539676666, "expert": 0.15921124815940857 }
9,321
The purpose of this lab is to simulate the operation of a portion of an Industrial Internet of Things (IIoT), that is modeled as a queuing system, and investigate its performance under variable configurations, to understand how different scenario configurations and network parameter settings may affect the system behavior and performance. Consider the Industry 4.0 scenario depicted in Fig. 1. Each machinery component of the production line is equipped with a set of sensors and actuators, that build up an IIoT system. In particular, a number of sensor devices collect real time monitoring data at the edge of the network, to collect several types of information about the status and the operation of the various production line components. These data can be used, either directly or after some processing, to take decisions and perform specific actions on the production line by means of actuators, in order to manage the system operation, modulate the production system speed, prevent or tackle service interruptions, etc. More in details, data collected by the sensors are sent to a local Micro Data Center (arrow 1), that provides computational capacity close to edge of IIoT network by means of edge nodes, which are managed by an edge controller. edge nodes pre-process data (arrow 2), so that most requests can be fulfilled locally, whereas only computationally intensive requests are forwarded to a Cloud data center (arrow 3), thus saving bandwidth and energy. Finally, based on the data processing output, operative commands are generated and sent to the actuators (dashed arrows). In case all the edge nodes are busy, incoming data can be buffered, if a buffer is present. However, if the buffer is full or it is not envisioned at all, data packets are directly forwarded to the Cloud Data Center to perform the entire processing tasks (arrow 4). 1In the considered queuing system, the customers represent the IIoT data packets that arrive at that Micro Data Center. The service represents the local processing of the data by edge nodes before generating the actuation message packets or before forwarding data to the Cloud for further computational processing. Finally, the waiting line represents the buffer where packets are stored before performing the computational tasks. Packets that are sent to the Cloud are further processed by Cloud server(s) before generating the actuation message packets that are sent to the actuators. In this case the service is represented by the data processing carried out by the Cloud server(s). Even in the Cloud a buffer may be envisioned. Two types of data can be generated by the sensor nodes and sent to the Micro Data Center, Figure 1: IoT system in an Industry 4.0 scenario. each corresponding to a different class of task that can be performed by the actuators: Class A - High priority tasks: these tasks are delay sensitive, hence implying high priority operations that must be performed on the production line within a strict time deadline. The packets generated by the sensors that are related to high priority tasks (type A packets) typically require a simple processing, that can be locally performed by the edge nodes. Class B - Low priority tasks: these tasks require more complex computational operations, however the completion of these tasks is not constrained by strict time deadlines, hence resulting in delay tolerant tasks that can be performed in a longer time period. Due to the need for more complex computational operations, this type of packets (type B packets), after a local pre-processing at the Micro Data Center level, must be forwarded to the Cloud Data Center to complete the processing. 23 Denote f the fraction of packets of type B, i.e. the low priority data packets arriving at the Micro Data Center from the sensors that must be further forwarded to the Cloud Data Center after local pre-processing by the edge node(s), due to more complex required computational tasks. In this case, assume a reasonably increased average service time on the Cloud server(s). Note that, although the required tasks are more complex, the Cloud Servers are likely to be better performing than the edge nodes. Furthermore, when data cannot be locally pre-processed due to busy edge nodes and full buffer, any incoming data (either of type A or B) are forwarded to the Cloud without any local pre-processing. Since these forwarded data are fully processed in the Cloud, they experience an average service time that reflect the fact that both the simple pre-processing tasks (for type A and type B data) and the more complex computational tasks (only for type B data) are performed in the Cloud Data center itself. You can include the propagation delay in your analysis, assuming a reasonable additional delay due to the data transmission from the Micro Data Center to the Cloud Data Center and for the transmission of the commands from Cloud Data Center to the actuators. The other propagation delays can be neglected. Tasks 1. For the first task, assume a single server with finite buffer for both the Micro Data Center and the Cloud Data Center, with f=0.5. Focusing on the Cloud Data Center sub-system, the packet drop probabil-ity (version B) of those data packets that are forwarded to the Cloud for any reason. (a) Observe the system behavior during the warm-up transient period and identify the transition to the steady state. (b) Try to apply a method to remove the warm-up transient in your simulations. 2. Consider now the overall system operation, including both the Micro Data Center and the Cloud Data Center. (a) How does the size of the buffer in the micro Data Center impact on the overall system performance? (b) Does the size of the buffer in the Cloud Data Center show a similar impact on the system performance? (c) How do the characteristics of input data (i.e. different values of f) affect the overall average queuing delay (version B)? 3. Now define a desired value for the maximum average queuing time of type A packets, denoted T q. (a) Assuming again a single-server Micro Data Center and a single-server Cloud Data Center, replace the edge node with a progressively faster server. Which is the4 minimum value of the average service rate that is required to reduce the queuing time of type A packets below the threshold Tq? (b) Try to increase the number of edge nodes, assuming the same fixed average service time for each edge node: which is the minimum number of servers required to reduce the queuing time below the threshold Tq? 4. Consider a multi-server system, assuming various servers both in the Micro and in the Cloud Data Centers. Assign an operational cost to each edge node and to the Cloud servers, with the operational cost for a Cloud server being different with respect to the one for an edge node. Simulate the system operation over a fixed period of time. (a) Vary the value of f (version B) over time, depending on the different time periods within the considered observation window. Investigate how these configuration settings affect the overall system performance. (b) Now assume at least 4 Cloud servers. Furthermore, consider at least three different types of Cloud servers, each featuring a different service speed and a specific operational cost (that may depend, for example, on the service speed). Test various combinations of server types and investigate the trade off between the overall cost, the queuing delays and the packet drop probability. (c) Set a value of f < 0.5 (version B) and define a desired threshold on the maximum operational cost. • Identify the best combination of server types allowing to reduce the cost below the desired threshold. • Does this combination allow to respect the constraint on the maximum queuing delay, i.e. Tq, set in Task 3 for type A packets? (d) Now, assume to install half the number of Cloud servers, keeping the same value of f as in Task 4.(c). • In this case, can you identify the proper configuration of server types allowing to reduce the cost below the same desired threshold? • Compare the obtained queueing delay and cost under these two scenarios (i.e., N Cloud servers versus N/2 Cloud servers), also highlighting how packets of type A and packets of type B are differently affected in terms of delay and packet drop probability. Hey GPT! I have the following code for performing the lab exercise I provided above. Look at the code and tell me how I should modify this code for performing different tasks of simulation.(How and what should be modified for performing each part of the simulation) #!/usr/bin/python3 import random from queue import Queue, PriorityQueue import matplotlib.pyplot as plt # ****************************************************************************** # Constants # ****************************************************************************** class simulator: def __init__(self, service, arrival, sim_time, max_buffer_size = float('inf')): self.service = service # SERVICE is the average service time; service rate = 1/SERVICE self.arrival = arrival # ARRIVAL is the average inter-arrival time; arrival rate = 1/ARRIVAL self.load= self.service / self.arrival # This relationship holds for M/M/1 self.max_buffer_size = max_buffer_size self.type1 = 1 self.sim_time = sim_time self.arrivals=0 self.users=0 self.data = None self.BusyServer=False # True: server is currently busy; False: server is currently idle self.MM1= None self.FES = None self.result = None random.seed(42) # ****************************************************************************** # To take the measurements # ****************************************************************************** class Measure: def __init__(self,Narr,Ndep,NAveraegUser,OldTimeEvent,AverageDelay,Drop): self.arr = Narr self.dep = Ndep self.ut = NAveraegUser self.oldT = OldTimeEvent self.delay = AverageDelay self.drop = Drop # ****************************************************************************** # Client # ****************************************************************************** class Client: def __init__(self,type,arrival_time): self.type = type self.arrival_time = arrival_time # ****************************************************************************** # Server # ****************************************************************************** class Server(object): # constructor def __init__(self): # whether the server is idle or not self.idle = True # ****************************************************************************** # arrivals ********************************************************************* def Arrival(self,time, queue): #print("Arrival no. ",data.arr+1," at time ",time," with ",users," users" ) # cumulate statistics self.data.arr += 1 self.data.ut += self.users*(time-self.data.oldT) self.data.oldT = time # sample the time until the next event inter_arrival = random.expovariate(lambd=1.0/self.arrival) # schedule the next arrival self.FES.put((time + inter_arrival, "arrival")) self.users += 1 # create a record for the client client = self.Client(self.type1,time) # check the buffer size before adding a new packet into the MM1 queue if len(queue) < self.max_buffer_size: queue.append(client) else: # increase the dropped packets count self.data.drop += 1 self.users -= 1 # ensures that the server only starts serving a new client when there is exactly one user in the system and # the server is idle. It helps avoid scheduling duplicate departure events or attempting to serve multiple # clients simultaneously. if self.users==1: # sample the service time service_time = random.expovariate(1.0/self.service) #service_time = 1 + random.uniform(0, SEVICE_TIME) # schedule when the client will finish the server self.FES.put((time + service_time, "departure")) # ****************************************************************************** # departures ******************************************************************* def Departure(self,time, queue): #print("Departure no. ",data.dep+1," at time ",time," with ",users," users" ) # cumulate statistics self.data.dep += 1 self.data.ut += self.users*(time-self.data.oldT) self.data.oldT = time # get the first element from the queue client = queue.pop(0) # do whatever we need to do when clients go away self.data.delay += (time-client.arrival_time) self.users -= 1 # see whether there are more clients to in the line if self.users >0: # sample the service time service_time = random.expovariate(1.0/self.service) # schedule when the client will finish the server self.FES.put((time + service_time, "departure")) # ****************************************************************************** # the "main" of the simulation # ****************************************************************************** def run(self): self.users = 0 self.data = self.Measure(0,0,0,0,0,0) self.MM1 = [] self.time = 0 # the list of events in the form: (time, type) self.FES = None self.FES = PriorityQueue() # schedule the first arrival at t=0 self.FES.put((0, "arrival")) # simulate until the simulated time reaches a constant while self.time < self.sim_time: (self.time, self.event_type) = self.FES.get() if self.event_type == "arrival": self.Arrival(self.time, self.MM1) elif self.event_type == "departure": self.Departure(self.time, self.MM1) # print output data print("MEASUREMENTS") print("{:<30}{}".format("No. of users in the queue:", self.users)) print("{:<30}{}".format("No. of arrivals :", self.data.arr)) print("{:<30}{}".format("No. of departures :", self.data.dep)) print("{:<30}{}".format("Dropped packets:", self.data.drop)) print("{:<30}{}".format("Loss probability:", self.data.drop / self.data.arr)) # Add this line print("{:<30}{}".format("Buffer size:", self.max_buffer_size if self.max_buffer_size != float("inf") else "infinite")) print("{:<30}{}".format("Load:", self.load )) print("{:<30}{}".format("Arrival rate:", self.arrival)) print("{:<30}{}".format("Service rate:", self.service)) print("{:<30}{}".format("Average number of users:", self.data.ut / self.time)) print("{:<30}{}".format("Average delay:", self.data.delay / self.data.dep)) print("{:<30}{}".format("Actual queue size:", len(self.MM1))) if len(self.MM1) > 0: print("{:<30}{}".format("Arrival time of the last element in the queue:", self.MM1[len(self.MM1) - 1].arrival_time)) # Create a dictionary of data related to the simulation self.result = { "No. of users in the queue": self.users, "No. of arrivals": self.data.arr, "No. of departures": self.data.dep, "Dropped packets": self.data.drop, "Loss probability": self.data.drop / self.data.arr, "Buffer size": self.max_buffer_size if self.max_buffer_size != float("inf") else "infinite", "Load": self.load, "Arrival rate": self.arrival, "Service rate": self.service, "Average number of users": self.data.ut / self.time, "Average delay": self.data.delay / self.data.dep, "Actual queue size": len(self.MM1) } return self.data, self.result def plot_graph(data1, data2, label1, label2, title): plt.plot(data1, label=label1) plt.plot(data2, label=label2) plt.xlabel('X-axis') plt.ylabel('Y-axis') plt.title(title) plt.legend() plt.show() if __name__ == "__main__": # simulator inputs : service, arrival , sim_time, buffer_size packet_simulator = simulator(10,20,500000) print(packet_simulator.run()[1])
3033a3cd96438e46195e7ac2e6617ab5
{ "intermediate": 0.40383800864219666, "beginner": 0.3166954815387726, "expert": 0.27946653962135315 }
9,322
Given the following description can you please give the DDL and DML scripts School operating the library. For each school, the following details should be registered: School name, Address, City, Phone number, Email, Full name of the School Director, Full name of the responsible School Library Operator. Each school unit (through the School Library Operator) is responsible for registering the school’s library available books in the system. • Books with their respective data (title, publisher, ISBN1 , authors, number of pages, summary, available copies/ inventory, image, thematic category, language, keywords). Each book has one or more authors and belongs to one or more categories. • Application Users: For each user, the system must verify their identity when accessing the application (via username/password) and each user can change his own password. o Network School Library Administrator (Administrator): Registers Schools and approves/appoints School Library Operators. They can create a backup copy of the entire database and restore the system from it. o School Library Operator. Operators are responsible for the operation of the School Library at the school unit level. Operators have the ability to process all the information of the books included in the system and to add new ones. They also supervise reservations and loans, either collectively or by searching by user. (Delayed returns are displayed separately). They can record the return of a borrowed title. They can record the loan of a copy when there is a reservation for that particular title, provided that the user's loan limits are met and that no returns are delayed. They also record loans without reservations, by searching for the user and title, if the user meets the loan criteria mentioned above and if there are available copies. o All school students, as well as the professors, can register and use the system. Approval from Operator is required for registration. After approving each user, the Operator prints out the borrower's card and delivers it to the user. Additionally, the Operator is authorized to delete or disable user accounts in accordance with the library's policy. Educators have the ability to modify their personal information, while students are only able to view it. • Book borrowing: Each user of the system, at the level of the school unit, can view available books, evaluate them and request to borrow a copy. Each student user can borrow up to two books per week, while professors can borrow one per week. Borrowing/returning of books is handled by the Operator. In case a copy of the book is not available, the user's request (reservation) is put on hold and is served upon the return of a copy. • Reservations: Regarding reservations, the borrowing limits apply, e.g., two reservations per week for students. A reservation cannot be made if a book has not been returned on time or if the same user has already borrowed the title. Users have the option to cancel any current reservations. Additionally, reservations have a time frame of one week and are automatically canceled once it expires. • Reviews: Users can share their thoughts about a book in a written review and provide a rating using the Likert2 scale. Reviews written by students will be published upon approval by the Operator. In addition to inputting the aforementioned information, all users of the application must have the ability to manage information, including a search mechanism and options for updating or deleting it (CRUD).
fa211fe4b2de0d704a41f6e89a49caca
{ "intermediate": 0.6005406379699707, "beginner": 0.1546071618795395, "expert": 0.24485215544700623 }
9,323
find the p rate in this website by using python and beatiful soup
b598dd054ef29cf7782865cff738a864
{ "intermediate": 0.29419347643852234, "beginner": 0.24316421151161194, "expert": 0.46264222264289856 }
9,324
https://www.chbank.com/en/personal/banking-services/useful-information/deposit-rates/index.shtml,%20find%20the%20p%20rate%20in%20this%20website%20by%20using%20python%20and%20beatiful%20soup
cc9249c962c577570424788688c5fcec
{ "intermediate": 0.3650592565536499, "beginner": 0.2601940929889679, "expert": 0.3747466802597046 }
9,325
https://www.chbank.com/en/personal/banking-services/useful-information/deposit-rates/index.shtml, find the p rate of this website by using python and beatiful soup
929913cc088dd62e52d69ccfee1b78a9
{ "intermediate": 0.31674569845199585, "beginner": 0.2354678064584732, "expert": 0.4477865397930145 }
9,326
@Select(sql = "update cdp_user set password = #{password}, update_time = now() where id = #{id}") public void resetPasswordById(@Param("password") String password, @Param("id") Long id){ 这么写有什么问题
bf0c261059038adfbce3b27e86422ac3
{ "intermediate": 0.39636027812957764, "beginner": 0.33972394466400146, "expert": 0.2639157772064209 }
9,327
I used this code:import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt import asyncio date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = 'Y0ReOvKcXm8e3wfIRYlgcdV9UG10M7XqxsGV0H83S8OMH3H3Fym3iqsfIcHDiq92' API_SECRET = '0u8aMxMXyIy9dQCti8m4AOeSvAGEqugOiIDML4rxVWDx5dzI80TDGNCMOWn4geVg' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) async def getminutedata(symbol, interval, lookback): klines = await client.futures_historical_trades(symbol=symbol,interval=interval, limit=lookback, endTime=int(time.time()*1000)) # Cast tuples to lists klines = [list(map(str, kline)) for kline in klines] frame = pd.DataFrame(klines, columns=['Open time', 'Price', 'Qty', 'QuoteQty', 'Time', 'Buyer Maker', 'Best Match']) frame = frame[['Open time', 'Price', 'Qty']] frame['Open time'] = pd.to_datetime(frame['Open time'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('Etc/GMT+3') frame.set_index('Open time', inplace=True) frame.drop(frame.tail(1).index, inplace=True) # Drop the last candle we fetched return frame df = getminutedata('BTCUSDT', '1m', 44640) def signal_generator(df): open = df.Price.iloc[-1] close = df.Price.iloc[-1] previous_open = df.Price.iloc[-2] previous_close = df.Price.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): signal = signal_generator(df) max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, # add position side parameter leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") return order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") return order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side # add position side parameter ) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) async def trading_loop(): while True: df = await getminutedata('BTCUSDT', '1m', 44640) if df is None: continue signal = signal_generator(df) print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}") if signal: await order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) await asyncio.sleep(1) async def main(): await trading_loop() if name == 'main': asyncio.run(main()) But I getting ERROR: sys:1: RuntimeWarning: coroutine 'getminutedata' was never awaited, Please give me right code
c7c86ebe0e9083b4c0301bbb3008c12a
{ "intermediate": 0.36781880259513855, "beginner": 0.4115613102912903, "expert": 0.2206198275089264 }
9,328
我有这样的 elasticsearch 数据: [{"case_id":"0","activities":[{"activityName":"a","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"},{"activityName":"b","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"},{"activityName":"c","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"}]},{"case_id":"1","activities":[{"activityName":"a","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"},{"activityName":"b","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"},{"activityName":"d","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"}]},{"case_id":"2","activities":[{"activityName":"b","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"},{"activityName":"b","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"},{"activityName":"c","startTime":"2023-05-31 17:46:05","endTime":"2023-05-31 17:46:05"}]}], 一个case有多个activity,每个case下的activity按startTime正序排列,相邻的activityName(比如 a-b)当作一个path;我需要写一个elasticseach 7.16的查询语句,查询最多的path,要怎么写呢?
4996811f01024f16172a9ef35441d11b
{ "intermediate": 0.2633470892906189, "beginner": 0.38485100865364075, "expert": 0.35180193185806274 }
9,329
add spool in sql file
d16b57529667af698084598aceb55968
{ "intermediate": 0.35285937786102295, "beginner": 0.25467169284820557, "expert": 0.39246898889541626 }
9,330
hi
e837c60f0ba02d7e819f900ab81ce09f
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
9,331
Draw schematic representation of possible hydrogen bonding interactions between oxygen molecule and water molecules.
370164fc595ed527b8ed9e059ef7de7e
{ "intermediate": 0.3932129442691803, "beginner": 0.2953205704689026, "expert": 0.3114664852619171 }
9,332
Generate spark java code for SCD2 problematic to get statistics on changed fields
23fbe874b6a2238f4c70b43ec12bef26
{ "intermediate": 0.5601620674133301, "beginner": 0.16632387042045593, "expert": 0.2735140323638916 }
9,333
# Definiowanie parametrów Uwaga kod jest pisany na kolenie wiec lepiej zawsze przed odpaleniem # sim na nowo zdefiniowac zmienne liczba_rowerow_na_stacji = [10,10,10,10,10] brak_roweru = [0,0,0,0,0] overrun=[0,0,0,0,0] popyt_stacji = [0.3, 0.3, 0.2, 0.1, 0.1] prawdopodobienstwo_stacji=[ 0.05 0.45 0.3 0.1 0.1; 0.43 0.07 0.1 0.2 0.2; 0.34 0.2 0.06 0.2 0.2; 0.2 0.2 0.2 0.05 0.35; 0.1 0.1 0.1 0.67 0.03] wynik_sim_init = [liczba_rowerow_na_stacji,brak_roweru,overrun] # Pojedyncze wyporzyczenie i oddanie roweru function single_sim(wynik_sim=wynik_sim_init, prawdopodobienstwo_stacji= prawdopodobienstwo_stacji, popyt_stacji=popyt_stacji) stacja_odebrania = rand(Categorical(popyt_stacji)) stacja_oddania = rand(Categorical(prawdopodobienstwo_stacji[stacja_odebrania,:])) if wynik_sim[1][stacja_odebrania] >= 1 wynik_sim[1][stacja_odebrania] -= 1 wynik_sim[1][stacja_oddania] += 1 if wynik_sim[1][stacja_oddania]>=15 wynik_sim[3][stacja_oddania] +=1 wynik_sim[1][stacja_oddania] -=3 wynik_sim[1][argmin(wynik_sim[1])] +=3 end else wynik_sim[2][stacja_odebrania] += 1 end return wynik_sim end # x razy single_sim function run_day(liczba_dzienna, wynik_sim = wynik_sim_init, prawdopodobienstwo_stacji=prawdopodobienstwo_stacji) wynik_sim_init = deepcopy(wynik_sim) for i in range(1,liczba_dzienna) wynik_sim = single_sim(wynik_sim_init, prawdopodobienstwo_stacji, popyt_stacji) end return wynik_sim end # x razy single_sim, ale zapamietuje wyniki z konca symulacji function run_day_cum(liczba_dzienna, wynik_sim = wynik_sim_init, prawdopodobienstwo_stacji=prawdopodobienstwo_stacji) for i in range(1,liczba_dzienna) wynik_sim = single_sim(wynik_sim, prawdopodobienstwo_stacji, popyt_stacji) end return wynik_sim end # x razy single_sim, ale kazdy "dzien" liczony od nowa function run_sims(liczba_sim = 30, liczba_dzienna = 40, wynik_sim = wynik_sim_init, prawdopodobienstwo_stacji = prawdopodobienstwo_stacji) wynik_sim_init = deepcopy(wynik_sim) wyniki_okresu = DataFrame(dzien = Int[], nr_stacji = Int[], liczba_na_koniec_dnia = Int[], braki_na_koniec_dnia = Int[], przewoz=Int[]) for i in range(1,liczba_sim) wynik_dnia = run_day(liczba_dzienna, wynik_sim, prawdopodobienstwo_stacji) temp_df = DataFrame(dzien = [i,i,i,i,i], nr_stacji = repeat(1:5,1),liczba_na_koniec_dnia = wynik_dnia[1], braki_na_koniec_dnia = wynik_dnia[2],przewoz=wynik_dnia[3]) wyniki_okresu = vcat(wyniki_okresu, temp_df) wynik_sim = wynik_sim_init end wynik_sim = wynik_sim_init return wyniki_okresu end # x razy single_sim, ale dni są "połączone" ze sobą function run_sims_cum(liczba_sim = 30, liczba_dzienna = 40, wynik_sim = wynik_sim_init, prawdopodobienstwo_stacji = prawdopodobienstwo_stacji) wyniki_okresu = DataFrame(dzien = Int[], nr_stacji = Int[], liczba_na_koniec_dnia = Int[], braki_na_koniec_dnia = Int[],przewoz=Int[]) for i in range(1,liczba_sim) wynik_dnia = run_day_cum(liczba_dzienna, wynik_sim_init, prawdopodobienstwo_stacji) temp_df = DataFrame(dzien = [i,i,i,i,i], nr_stacji = repeat(1:5,1),liczba_na_koniec_dnia = wynik_dnia[1], braki_na_koniec_dnia = wynik_dnia[2],przewoz=wynik_dnia[3]) wyniki_okresu = vcat(wyniki_okresu, temp_df) end wynik_sim = wynik_sim_init return wyniki_okresu end # Wyniki nieskumulowanych wyników liczba_rowerow_na_stacji = [10,10,10,10,10] brak_roweru = [0,0,0,0,0] overrun=[0,0,0,0,0] popyt_stacji = [0.3, 0.3, 0.2, 0.1, 0.1] prawdopodobienstwo_stacji=[ 0.05 0.45 0.3 0.1 0.1; 0.43 0.07 0.1 0.2 0.2; 0.34 0.2 0.06 0.2 0.2; 0.2 0.2 0.2 0.05 0.35; 0.1 0.1 0.1 0.67 0.03] wynik_sim_init = [deepcopy(liczba_rowerow_na_stacji), deepcopy(brak_roweru),deepcopy(overrun)] wyniki_okresu = run_sims() In the above Julia simulation I think there is a key element missing: time. How to add time to those events and remeber that multiple bikes can travel at the same time. Write code if possible.
ff62f509fbc8b4375126e3ce4b956aae
{ "intermediate": 0.326279878616333, "beginner": 0.38869714736938477, "expert": 0.2850229740142822 }
9,334
fix that code to handle that horse in array 3d matrix wireframe figure. here's errors "TypeError: projectedVertices[a] is undefined" and here's the code. it will be nice if you improve the overall handlage of all possible matrix array structure, so it will handle all possible variants of any wireframe models inside. output full code.: function render() { ctx.fillStyle = '#FFF'; ctx.fillRect(0, 0, canvas.width, canvas.height); const rotX = rotateX(angleX); const rotY = rotateY(angleY); const rotZ = rotateZ(angleZ); // Extraterrestrial transformation parameters const frequency = 1; const amplitude = 0.8; const transformedVertices = vertices.map(vertex => { const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude); const cx = extraterrestrialVertex[0] - offsetX; const cy = extraterrestrialVertex[1] - offsetY; const cz = extraterrestrialVertex[2] - offsetY; const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ); return [ rotated[0] + offsetX, rotated[1] + offsetY, rotated[2] + offsetY, ]; }); const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom)); ctx.lineWidth = 2; ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 100 + ', 100%, 50%, 0.8)'; ctx.beginPath(); for (let edge of edges) { const [a, b] = edge; const [x1, y1] = projectedVertices[a]; const [x2, y2] = projectedVertices[b]; const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1)); const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1); // Calculate control point for curved edge const cpDist = 0.01 * dist; const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(2); const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(2); ctx.moveTo(x1, y1, x2, y2); ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1); } ctx.stroke(); angleX += +getDeviation(0.02); angleY += +getDeviation(0.02); angleZ += +getDeviation(0.02); requestAnimationFrame(render); }
9e68c9914b5e34c40ee6dd8393254f42
{ "intermediate": 0.3974483609199524, "beginner": 0.38659247756004333, "expert": 0.21595914661884308 }
9,335
fix that code to handle that horse in array 3d matrix wireframe figure. here's errors "TypeError: projectedVertices[a] is undefined" and here's the code. it will be nice if you improve the overall handlage of all possible matrix array structure, so it will handle all possible variants of any wireframe models inside. output full code.: function render() { ctx.fillStyle = '#FFF'; ctx.fillRect(0, 0, canvas.width, canvas.height); const rotX = rotateX(angleX); const rotY = rotateY(angleY); const rotZ = rotateZ(angleZ); // Extraterrestrial transformation parameters const frequency = 1; const amplitude = 0.8; const transformedVertices = vertices.map(vertex => { const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude); const cx = extraterrestrialVertex[0] - offsetX; const cy = extraterrestrialVertex[1] - offsetY; const cz = extraterrestrialVertex[2] - offsetY; const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ); return [ rotated[0] + offsetX, rotated[1] + offsetY, rotated[2] + offsetY, ]; }); const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom)); ctx.lineWidth = 2; ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 100 + ', 100%, 50%, 0.8)'; ctx.beginPath(); for (let edge of edges) { const [a, b] = edge; const [x1, y1] = projectedVertices[a]; const [x2, y2] = projectedVertices[b]; const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1)); const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1); // Calculate control point for curved edge const cpDist = 0.01 * dist; const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(2); const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(2); ctx.moveTo(x1, y1, x2, y2); ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1); } ctx.stroke(); angleX += +getDeviation(0.02); angleY += +getDeviation(0.02); angleZ += +getDeviation(0.02); requestAnimationFrame(render); }
63f0a74589d8632668c4f9d86ae396ef
{ "intermediate": 0.3974483609199524, "beginner": 0.38659247756004333, "expert": 0.21595914661884308 }
9,336
fix that code to handle that horse in array 3d matrix wireframe figure. here's errors "TypeError: projectedVertices[a] is undefined" and here's the code. it will be nice if you improve the overall handlage of all possible matrix array structure, so it will handle all possible variants of any wireframe models inside. output full code.: function render() { ctx.fillStyle = '#FFF'; ctx.fillRect(0, 0, canvas.width, canvas.height); const rotX = rotateX(angleX); const rotY = rotateY(angleY); const rotZ = rotateZ(angleZ); // Extraterrestrial transformation parameters const frequency = 1; const amplitude = 0.8; const transformedVertices = vertices.map(vertex => { const extraterrestrialVertex = extraterrestrialTransformation(vertex, frequency, amplitude); const cx = extraterrestrialVertex[0] - offsetX; const cy = extraterrestrialVertex[1] - offsetY; const cz = extraterrestrialVertex[2] - offsetY; const rotated = transform(transform(transform([cx, cy, cz], rotX), rotY), rotZ); return [ rotated[0] + offsetX, rotated[1] + offsetY, rotated[2] + offsetY, ]; }); const projectedVertices = transformedVertices.map(vertex => project(vertex, canvas.height * scale, offsetX, offsetY, zoom)); ctx.lineWidth = 2; ctx.strokeStyle = 'hsla(' + (angleX + angleY) * 100 + ', 100%, 50%, 0.8)'; ctx.beginPath(); for (let edge of edges) { const [a, b] = edge; const [x1, y1] = projectedVertices[a]; const [x2, y2] = projectedVertices[b]; const dist = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2 + (y2 - x1) ** 2 + (x2 - y1)); const angle = Math.atan2(y2 - y1, x2 - x1, x2 - y1, y2 - x1); // Calculate control point for curved edge const cpDist = 0.01 * dist; const cpX = (x1 + x2) / 2 + cpDist * Math.cos(angle - Math.PI / 2) * getDeviation(2); const cpY = (y1 + y2) / 2 + cpDist * Math.sin(angle - Math.PI / 2) * getDeviation(2); ctx.moveTo(x1, y1, x2, y2); ctx.quadraticCurveTo(cpX, cpY, x2, y2, x1, y1); } ctx.stroke(); angleX += +getDeviation(0.02); angleY += +getDeviation(0.02); angleZ += +getDeviation(0.02); requestAnimationFrame(render); }
756c3b68cd7fa900cac319ceb35068a8
{ "intermediate": 0.3974483609199524, "beginner": 0.38659247756004333, "expert": 0.21595914661884308 }
9,337
import { View, Text, ScrollView, Dimensions, Image, TouchableOpacity, } from 'react-native'; import React, {useState, useEffect} from 'react'; import {useTranslation} from 'react-i18next'; import {styles} from './style'; import {ResultCard} from '@components/card/ResultCard'; import {RESULTAT_RECHERCHE} from '@helpers/fakedata/Data'; import {CustomButton} from '@components/buttons/CustomButton'; import Rating from '@assets/images/home/rating.svg'; import Time from '@assets/images/home/time.svg'; import Date from '@assets/images/home/date.svg'; import Position from '@assets/images/home/position.svg'; import {colors} from '@constants/colors'; import {FONTS} from '@constants/index'; const width = Dimensions.get('window').width; const height = Dimensions.get('window').height; const screenHeightLarge = 780; const screenHeight = 600; export const ResultRecherche = () => { const {t} = useTranslation(); const [isLoading, setLoading] = useState(false); const [isSelected, setisSelected] = useState(false); const Separator = () => { return <View style={styles.sectionSeparator} />; }; const handleSelect = item => { console.log('item', item); // setisSelected(true); }; return ( <View style={{flex: 1}}> <ScrollView contentInsetAdjustmentBehavior={'always'} keyboardShouldPersistTaps={'always'} showsVerticalScrollIndicator={false} showsHorizontalScrollIndicator={false} style={{ // top: 50, height: height >= screenHeight ? 0.4 * height : 0.5 * height, backgroundColor: 'transparent', paddingBottom: Platform.OS === 'ios' ? (height * 10) / 100 : 20, }}> {RESULTAT_RECHERCHE.map(item => ( <TouchableOpacity onPress={() => handleSelect(item)} key={item.id} style={{ paddingHorizontal: 20, // flex: 1, }}> <View style={{flexDirection: 'row', marginVertical: 5}}> <Image source={require('@assets/images/personn.jpg')} style={{ height: 82, width: 82, borderRadius: 40, shadowColor: 'black', top: 15, }} /> <View style={{marginHorizontal: 10}}> <View style={{ flexDirection: 'row', justifyContent: 'space-between', width: '74%', paddingTop: 10, }}> <Text style={{ marginVertical: 2, color: colors.secondary, fontSize: 14, fontFamily: FONTS.MEDIUM, }}> {item.name} </Text> <Text style={{ marginVertical: 2, color: colors.secondary, fontSize: 14, fontFamily: FONTS.MEDIUM, }}> TND {item.prix} </Text> </View> <Text style={{ marginVertical: 2, color: colors.border, fontSize: 13, fontFamily: FONTS.REGULAR, }}> {item.metier} </Text> <View style={{ flexDirection: 'row', paddingTop: 4, textAlign: 'center', }}> <View style={{flexDirection: 'row', textAlign: 'center'}}> <Date style={{alignSelf: 'center'}} /> <Text style={{ marginVertical: 2, color: colors.secondary, fontSize: 14, fontFamily: FONTS.REGULAR, left: 1, }}> {item.dateDebut} </Text> </View> <View style={{flexDirection: 'row', alignSelf: 'center'}}> <Text style={{ color: colors.secondary, fontSize: 14, fontFamily: FONTS.REGULAR, alignSelf: 'center', }}> {' à '} </Text> <Text style={{ marginVertical: 2, color: colors.secondary, fontSize: 14, fontFamily: FONTS.REGULAR, }}> {item.dateFin} </Text> </View> <View style={{ flexDirection: 'row', textAlign: 'center', left: 40, }}> <Time style={{alignSelf: 'center'}} /> <Text style={{ marginVertical: 2, color: colors.secondary, fontSize: 14, fontFamily: FONTS.REGULAR, left: 3, }}> {item.disponibilite} </Text> </View> </View> <Rating style={{ top: 5, marginVertical: 2, left: -2, }} /> <View style={{flexDirection: 'row', textAlign: 'center'}}> <Position style={{alignSelf: 'center'}} /> <Text style={{ marginVertical: 8, color: colors.secondary, fontSize: 14, fontFamily: FONTS.REGULAR, left: 4, }}> {item.distance} Km </Text> </View> </View> {/* <View> <Text style={styles.title}>{item.metier}</Text> <View style={{flexDirection: 'row', paddingTop: 10}}> <Text style={{marginVertical: 2}}>{item.dateDebut}</Text> <Text style={{marginVertical: 2}}>{item.dateFin}</Text> </View> <Rating style={{ top: 5, // justifyContent: 'center', // alignItems: 'center', }} /> <Text style={{marginVertical: 2}}>{item.distance}</Text> </View> */} </View> <Separator /> </TouchableOpacity> ))} </ScrollView> <View style={{ alignItems: 'center', backgroundColor: 'white', marginTop: 10, }}> <CustomButton isBordered borderWidth={1} isDisabled={false} isLoading={isLoading} submitting={true} onPress={() => console.log('mriguel')} label={'Réserver'} width={width * 0.9} /> </View> </View> ); }; i want to change the background of the item slelected
625e5b26d263254ac1d1b7139bc8f48c
{ "intermediate": 0.2767519950866699, "beginner": 0.4841436743736267, "expert": 0.23910430073738098 }
9,338
Write a simple py app. It should by gui. In app should be input box for text. Button. After click button text from text box saved in file with name from second textbox
cf18255e08b6fff6ee3714660e656c21
{ "intermediate": 0.44103339314460754, "beginner": 0.2034294605255127, "expert": 0.3555371165275574 }