row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
2,708
|
Definition for rule 'react/jsx-filename-extension' was not found.
|
4b73a87ad44a286aa263331e36316172
|
{
"intermediate": 0.42806753516197205,
"beginner": 0.3303244709968567,
"expert": 0.24160794913768768
}
|
2,709
|
This command always fails: docker create --env WORDPRESS_DB_HOST=<my database hostname> \
wordpress: 5.0.0-php7.2-apache
|
12cc3ccc1a4dbddb7f83b797e010c3b5
|
{
"intermediate": 0.3603294789791107,
"beginner": 0.45165809988975525,
"expert": 0.18801234662532806
}
|
2,710
|
this command always fails: docker create --env WORDPRESS_DB_HOST=<my database hostname> \
wordpress: 5.0.0-php7.2-apache
|
f89d0ec8864ff65819e5a49768d334e2
|
{
"intermediate": 0.36811816692352295,
"beginner": 0.4297068417072296,
"expert": 0.20217503607273102
}
|
2,711
|
check you
|
8767a017947442a1e4d05f3cd67f298e
|
{
"intermediate": 0.3416067063808441,
"beginner": 0.3133569061756134,
"expert": 0.3450363576412201
}
|
2,712
|
How do I obtain an SVG class from useref in react?
|
0f5c00f3ba62f2ad84286680f16c3b8b
|
{
"intermediate": 0.6443093419075012,
"beginner": 0.2176530659198761,
"expert": 0.1380375772714615
}
|
2,713
|
html & js use document.write("") on open new url
|
223545b921ff09952b9d538dca926eed
|
{
"intermediate": 0.32519766688346863,
"beginner": 0.37368905544281006,
"expert": 0.3011133074760437
}
|
2,714
|
Write Python code with CodeWhisperer and boto3 for create CloudFormation template for s3 and ec2 resources.
|
2b1c1d603decadf2b3dfeb069a2585e5
|
{
"intermediate": 0.5078011751174927,
"beginner": 0.18289373815059662,
"expert": 0.3093051612377167
}
|
2,715
|
change the code. the following data should be entered: tile length, tile width, tile thickness, joint width, total area
import tkinter as tk
from tkinter import ttk
from math import ceil
def calculate_joint_mass():
tile_width = float(tile_width_entry.get())
tile_length = float(tile_length_entry.get())
tile_thickness = float(tile_thickness_entry.get())
joint_width = float(joint_width_entry.get())
total_area = float(total_area_entry.get())
joint_volume = joint_width * tile_width * tile_length * total_area / (tile_width * tile_length)
joint_mass = joint_volume * tile_thickness
joint_mass_per_m2 = joint_mass / total_area
required_packs = ceil(joint_mass / 3)
joint_mass_label.config text=new_func(joint_mass_per_m2)
packs_label.config(text=f"Required packages: {required_packs}”)
window = tk.Tk()
window.title(“Tile Joint Calculator”)
frame = ttk.Frame(window, padding=10)
frame.grid(row=0, column=0)
instructions_label = ttk.Label(frame, text=“Enter the following values in mm (unless specified):”)
instructions_label.grid(row=0, column=0, columnspan=2)
tile_width_label = ttk.Label(frame, text=“Tile width:”)
tile_width_label.grid(row=1, column=0)
tile_width_entry = ttk.Entry(frame)
tile_width_entry.grid(row=1, column=1)
tile_length_label = ttk.Label(frame, text=“Tile length:”)
tile_length_label.grid(row=2, column=0)
tile_length_entry = ttk.Entry(frame)
tile_length_entry.grid(row=2, column=1)
tile_thickness_label = ttk.Label(frame, text=“Tile thickness:”)
tile_thickness_label.grid(row=3, column=0)
tile_thickness_entry = ttk.Entry(frame)
tile_thickness_entry.grid(row=3, column=1)
joint_width_label = ttk.Label(frame, text=“Joint width:”)
joint_width_label.grid(row=4, column=0)
joint_width_entry = ttk.Entry(frame)
joint_width_entry.grid(row=4, column=1)
total_area_label = ttk.Label(frame, text=“Total area (m²):”)
total_area_label.grid(row=5, column=0)
total_area_entry = ttk.Entry(frame)
total_area_entry.grid(row=5, column=1)
calculate_button = ttk.Button(frame, text=“Calculate”, command=calculate_joint_mass)
calculate_button.grid(row=6, column=0, columnspan=2)
joint_mass_label = ttk.Label(frame, text=“Required joint mass (kg/m²):”)
joint_mass_label.grid(row=7, column=0, columnspan=2)
packs_label = ttk.Label(frame, text=“Required packages:”)
packs_label.grid(row=8, column=0, columnspan=2)
window.mainloop()
“(” was not closed
Apologies for the oversight. I have corrected the code by closing the parentheses at the end of the joint_volume calculation.
import tkinter as tk
from tkinter import ttk
from math import ceil
def calculate_joint_mass():
tile_width = float(tile_width_entry.get())
tile_length = float(tile_length_entry.get())
tile_thickness = float(tile_thickness_entry.get())
joint_width = float(joint_width_entry.get())
total_area = float(total_area_entry.get())
joint_volume = (joint_width * tile_width * tile_length * total_area) / (tile_width * tile_length)
joint_mass = joint_volume * tile_thickness
joint_mass_per_m2 = joint_mass / total_area
required_packs = ceil(joint_mass / 3)
joint_mass_label.config(text=f"Required joint mass (kg/m²): {joint_mass_per_m2:.2f}“)
packs_label.config(text=f"Required packages: {required_packs}”)
window = tk.Tk()
window.title(“Tile Joint Calculator”)
frame = ttk.Frame(window, padding=10)
frame.grid(row=0, column=0)
instructions_label = ttk.Label(frame, text=“Enter the following values in mm (unless specified):”)
instructions_label.grid(row=0, column=0, columnspan=2)
tile_width_label = ttk.Label(frame, text=“Tile width:”)
tile_width_label.grid(row=1, column=0)
tile_width_entry = ttk.Entry(frame)
tile_width_entry.grid(row=1, column=1)
tile_length_label = ttk.Label(frame, text=“Tile length:”)
tile_length_label.grid(row=2, column=0)
tile_length_entry = ttk.Entry(frame)
tile_length_entry.grid(row=2, column=1)
tile_thickness_label = ttk.Label(frame, text=“Tile thickness:”)
tile_thickness_label.grid(row=3, column=0)
tile_thickness_entry = ttk.Entry(frame)
tile_thickness_entry.grid(row=3, column=1)
joint_width_label = ttk.Label(frame, text=“Joint width:”)
joint_width_label.grid(row=4, column=0)
joint_width_entry = ttk.Entry(frame)
joint_width_entry.grid(row=4, column=1)
total_area_label = ttk.Label(frame, text=“Total area (m²):”)
total_area_label.grid(row=5, column=0)
total_area_entry = ttk.Entry(frame)
total_area_entry.grid(row=5, column=1)
calculate_button = ttk.Button(frame, text=“Calculate”, command=calculate_joint_mass)
calculate_button.grid(row=6, column=0, columnspan=2)
joint_mass_label = ttk.Label(frame, text=“Required joint mass (kg/m²):”)
joint_mass_label.grid(row=7, column=0, columnspan=2)
packs_label = ttk.Label(frame, text=“Required packages:”)
packs_label.grid(row=8, column=0, columnspan=2)
window.mainloop()
def new_func(joint_mass_per_m2):
return f"Required joint mass (kg/m²): {joint_mass_per_m2:.2f}“)
|
1331daf90d81efddec9f08fc0c740324
|
{
"intermediate": 0.35609281063079834,
"beginner": 0.4229291081428528,
"expert": 0.22097809612751007
}
|
2,716
|
{
"error": "creation_error",
"errors": {
"code": 11000,
"writeErrors": [
{
"err": {
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: ScoutCamp.campingunits index: _id_ dup key: { _id: ObjectId('644584456d92e56b24196218') }",
"op": {
"_id": "644584456d92e56b24196218",
"createdAt": "2023-04-23T19:17:25.551Z",
"updatedAt": "2023-04-23T19:17:25.551Z",
"type": "bungalow",
"name": "a",
"size": "22",
"capacity": 2,
"beds": {
"single": 0,
"double": 0,
"bunk": 0
},
"bathroom": {
"private": false,
"showers": 0,
"toilets": 0
},
"notes": "",
"feePerNight": 2,
"__v": 0
}
},
"index": 0
}
],
"result": {
"ok": 1,
"writeErrors": [
{
"err": {
"index": 0,
"code": 11000,
"errmsg": "E11000 duplicate key error collection: ScoutCamp.campingunits index: _id_ dup key: { _id: ObjectId('644584456d92e56b24196218') }",
"op": {
"_id": "644584456d92e56b24196218",
"createdAt": "2023-04-23T19:17:25.551Z",
"updatedAt": "2023-04-23T19:17:25.551Z",
"type": "bungalow",
"name": "a",
"size": "22",
"capacity": 2,
"beds": {
"single": 0,
"double": 0,
"bunk": 0
},
"bathroom": {
"private": false,
"showers": 0,
"toilets": 0
},
"notes": "",
"feePerNight": 2,
"__v": 0
}
},
"index": 0
}
],
"writeConcernErrors": [],
"insertedIds": [
{
"index": 0,
"_id": "644584456d92e56b24196218"
},
{
"index": 1,
"_id": "6447fe1010dca5f9da783d8b"
}
],
"nInserted": 0,
"nUpserted": 0,
"nMatched": 0,
"nModified": 0,
"nRemoved": 0,
"upserted": [],
"opTime": {
"ts": {
"$timestamp": "7226023471812182096"
},
"t": 28
}
},
"insertedDocs": []
}
}
|
7836c4775ac98832b92b13b169843273
|
{
"intermediate": 0.3749270439147949,
"beginner": 0.4355109930038452,
"expert": 0.18956202268600464
}
|
2,717
|
is the below code correct?
from pymavlink import mavutil
import math
import time
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
class Drone:
def __init__(self, sysid, master_address):
self.sysid = sysid
self.master_address = master_address
self.connection = mavutil.mavlink_connection(self.master_address, baud=57600)
self.master_position = [0, 0, 0] # Starting position for the master drone
def receive_messages(self):
try:
msg = self.connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if msg.get_srcSystem() == self.sysid:
self.master_position = [msg.lat / 10 ** 7, msg.lon / 10 ** 7, msg.alt / 10 ** 3]
except Exception as e:
logging.error("Error receiving messages: {}".format(e))
def send_position_target(self, x, y, z, vx, vy, vz):
try:
self.connection.mav.set_position_target_global_int(
time.time(),
self.sysid,
mavutil.mavlink.MAV_COMP_ID_AUTOPILOT1,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
0b110111111000,
int(x * 10 ** 7),
int(y * 10 ** 7),
z,
vx,
vy,
vz,
0, 0, 0, 0, 0
)
except Exception as e:
logging.error("Error sending position target: {}".format(e))
def close(self):
self.connection.close()
def distance_between_points(p1, p2):
return math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2 + (p1[2] - p2[2]) ** 2)
def abort():
print("Type 'abort' to return to Launch and disarm motors.")
start_time = time.monotonic()
while time.monotonic() - start_time < 7:
user_input = input("Time left: {} seconds \n".format(int(7 - (time.monotonic() - start_time))))
if user_input.lower() == "abort":
print("Returning to Launch and disarming motors…")
for drone in [master_drone, follower_drone]:
drone.set_mode(6) # RTL mode
drone.arm(False) # Disarm motors
return True
print("7 seconds have passed. Proceeding with waypoint task...")
return False
master_drone = Drone(sysid=2, master_address='/dev/ttyUSB0')
follower_drone = Drone(sysid=3, master_address='/dev/ttyUSB0')
follower_distance = 5 # Distance in meters between master and follower
follower_angle = math.radians(60) # Angle in radians between master and follower (60 degrees clockwise from master)
waypoints = [
(-35.363261, 149.165230, 50), # Waypoint 1
(-35.363361, 149.165130, 50), # Waypoint 2
(-35.363461, 149.165030, 50) # Waypoint 3
]
mode = "guided(4)" # Set the mode to guided(4)
for i, waypoint in enumerate(waypoints):
while True:
# Receive messages and update the master position
master_drone.receive_messages()
# Calculate the target position for the follower drone
follower_x = master_drone.master_position[0] + follower_distance * math.cos(follower_angle)
follower_y = master_drone.master_position[1] + follower_distance * math.sin(follower_angle)
follower_z = master_drone.master_position[2]
# Send the target position to the master and follower drones
master_drone.send_position_target(master_drone.master_position[0], master_drone.master_position[1], master_drone.master_position[2], 3, 0, 0) # Constant speed of 3 m/s in the x direction
follower_drone.send_position_target(follower_x, follower_y, follower_z, 3, 0, 0) # Constant speed of 3 m/s in the x direction
# Wait for 1 second before sending the next set of commands
time.sleep(1)
# Check if the user wants to abort the mission
if mode == "guided(4)" and abort():
break
# Check if the follower drone has reached the current waypoint
if distance_between_points([follower_x, follower_y, follower_z], waypoint) < 1:
print("Reached waypoint {}.".format(i + 1))
break
master_drone.close()
follower_drone.close()
|
904a97d851deb9f873c6e99eab2424e3
|
{
"intermediate": 0.3335030972957611,
"beginner": 0.5589597821235657,
"expert": 0.10753710567951202
}
|
2,718
|
import {CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis} from "recharts";
Нужен линейный график на месяц
https://recharts.org/en-US/examples/
CustomizedLabelLineChart график
приходят такие данные const data = {
open_link: [
{ date: '2023-04-23', count: 15 },
{ date: '2023-04-24', count: 8 }
],
order_pay: [],
registration: [
{ date: '2023-04-23', count: 5 },
{ date: '2023-04-24', count: 2 }
],
subscription_pay: []
}
отобразить все 4 свойства объекта data
с 2023-03-25 до 2023-04-25, нужно, чтобы был линейный график, если ничего не приходит то везде было ноль.
|
c371de7e4783dc3bf26930350cd777b8
|
{
"intermediate": 0.4188665747642517,
"beginner": 0.3158378601074219,
"expert": 0.26529553532600403
}
|
2,719
|
campingController.createCamping = async (req, res, next) => {
delete req.body._id;
delete req.body.owner;
const session = await mongoose.startSession();
session.startTransaction();
try {
const camping = new Camping({ ...req.body, owner: req.user._id });
const campingUnits = req.body.units.map(unit => {
if (unit._id.startsWith('new')) {
delete unit._id;
}
const campingUnit = new CampingUnit(unit);
campingUnit.camping = camping._id;
console.log(campingUnit.camping);
return campingUnit;
});
await CampingUnit.insertMany(campingUnits, { session });
const response = await camping.save();
res.status(201).json({
message: "Camping created successfully",
camping: response
});
await session.commitTransaction();
} catch (error) {
console.log(error);
await session.abortTransaction();
res.status(500).json({
error: 'creation_error',
errors: error,
});
}
session.endSession();
};
Creame un getCamping, viendo que las unidades tienen un campo camping para ser referenciadas
|
8c4bf39ab3f116efd1f8083d12433a34
|
{
"intermediate": 0.47974273562431335,
"beginner": 0.31639134883880615,
"expert": 0.20386584103107452
}
|
2,720
|
Почему в этой программе при посыле сигнала SIGUSR1 не выводится строка "Caught SIGUSR1"?
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <pthread.h>
#include <unistd.h>
pthread_t thread1;
sigset_t set;
int thread_pid;
void *thread_func(void *args) {
thread_pid = getpid();
printf("Thread started.\n");
while(1) {
int signum;
sigwait(&set, &signum);
printf("Received signal %d\n", signum);
if (signum == SIGUSR1){
break;
}
}
sleep(2);
printf("ending thread!\n");
pthread_exit(NULL);
}
void sig_handler(int signum){
printf("Caught SIGUSR1\n");
}
int main() {
signal(SIGUSR1, sig_handler);
signal(SIGUSR2, SIG_IGN);
sigemptyset(&set);
sigaddset(&set, SIGTERM);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGUSR1);
if(pthread_create(&thread1, NULL, thread_func, NULL)) {
printf("Error creating thread\n");
return 1;
}
printf("Main thread started. PID: %d\n", getpid());
int i = 0;
while(1) {
printf("Main thread running %d\n", i);
pthread_kill(thread1, SIGUSR2);
i++;
if (i == 3){
pthread_kill(thread1, SIGUSR1);
break;
}
sleep(2);
}
sleep(1);
pthread_join(thread1, NULL);
printf("main is ending\n");
return 0;
}
|
8c8ab8326c5f973e3ec3cb08994b1ba0
|
{
"intermediate": 0.30254364013671875,
"beginner": 0.5607983469963074,
"expert": 0.13665804266929626
}
|
2,721
|
When I select a cell in excel, I want the active row of the cell to change colour. How can I do this
|
a554c989e5709c2c83ebf231d6f40e97
|
{
"intermediate": 0.47057557106018066,
"beginner": 0.17522037029266357,
"expert": 0.354203999042511
}
|
2,722
|
Write a C++ program that take 4 integers 1, 6, 2, 2 as input and output 6
|
9815978af08b6a416f7a7085bba082f1
|
{
"intermediate": 0.3410981297492981,
"beginner": 0.2243860810995102,
"expert": 0.4345157742500305
}
|
2,723
|
write C++ program to map those input into one string: (1, 6, 2, 2), (1, 9, 2, 5)
|
cc14e24a19123e2f2e27c081983f756d
|
{
"intermediate": 0.35250353813171387,
"beginner": 0.21603594720363617,
"expert": 0.43146052956581116
}
|
2,724
|
Is given..when considered experimental in Perl?
|
55e215b6652dbeefcd6d6da90532fea0
|
{
"intermediate": 0.30668526887893677,
"beginner": 0.3299570381641388,
"expert": 0.36335769295692444
}
|
2,725
|
write a code to play snake in python
|
4a06fd2dd89a4b9d700188baa17a1829
|
{
"intermediate": 0.2870798408985138,
"beginner": 0.26608139276504517,
"expert": 0.44683873653411865
}
|
2,726
|
2023-04-25 23:53:52,588 p=26731 u=ansible | fatal: [db_hex-test -> localhost]: FAILED! => {
"censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result",
"changed": true
}
2023-04-25 23:53:52,588 p=26731 u=ansible | ...ignoring
2023-04-25 23:53:52,657 p=26731 u=ansible | TASK [db/liquibase : set_fact] ****************************************************************************************************************************************************************************
2023-04-25 23:53:52,657 p=26731 u=ansible | task path: /data/home/ansible/distr/TAILORED_KCELL_CFG_1.44.28/install/tailored/common/db/liquibase/tasks/main.yml:108
2023-04-25 23:53:52,658 p=26731 u=ansible | ok: [db_hex-test -> localhost] => {
"censored": "the output has been hidden due to the fact that 'no_log: true' was specified for this result",
"changed": false
}
2023-04-25 23:53:52,710 p=26731 u=ansible | TASK [db/liquibase : Check Liquibase CMD error] ***********************************************************************************************************************************************************
2023-04-25 23:53:52,710 p=26731 u=ansible | task path: /data/home/ansible/distr/TAILORED_KCELL_CFG_1.44.28/install/tailored/common/db/liquibase/tasks/main.yml:112
2023-04-25 23:53:52,711 p=26731 u=ansible | fatal: [db_hex-test -> localhost]: FAILED! => {
"changed": false,
"msg": "{\n \"changed\": true,\n \"cmd\": \"cd \\\"/tmp/ansible-20230425235246_983335/hex_component/liquibase\\\" && java -Djava.security.egd=file:/dev/../dev/urandom -classpath \\\"/data/home/ansible/distr/TAILORED_KCELL_CFG_1.44.28/install/tailored/common/db/liquibase/files/*\\\" liquibase.integration.commandline.Main --driver=oracle.jdbc.driver.OracleDriver --url=jdbc:oracle:thin:@nxt-bis-1:1521/tbis --username=******** --password=******** --changeLogFile=changelog.xml --logLevel=debug --logFile=\\\"/data/home/ansible/distr/TAILORED_KCELL_CFG_1.44.28/install/tailored/liquibase_db_hex2023-04-25_23-52-51.log\\\" update \\n\",\n \"delta\": \"0:01:01.144953\",\n \"end\": \"2023-04-25 23:53:52.560782\",\n \"failed\": true,\n \"msg\": \"non-zero return code\",\n \"rc\": 255,\n \"start\": \"2023-04-25 23:52:51.415829\",\n \"stderr\": \"Unexpected error running Liquibase: java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection\\n\\n\\n\\nFor more information, use the --logLevel flag\",\n \"stderr_lines\": [\n \"Unexpected error running Liquibase: java.sql.SQLRecoverableException: IO Error: The Network Adapter could not establish the connection\",\n \"\",\n \"\",\n \"\",\n \"For more information, use the --logLevel flag\"\n ],\n \"stdout\": \"\",\n \"stdout_lines\": []\n}"
}
2023-04-25 23:53:52,758 p=26731 u=ansible | <localhost> ESTABLISH LOCAL CONNECTION FOR USER: ansible
|
d85826610c67cf8ecdcaf0425e168f57
|
{
"intermediate": 0.2975042760372162,
"beginner": 0.3619692325592041,
"expert": 0.3405264914035797
}
|
2,727
|
How to upload and run Python script to AWS Lambda?
|
e8627318538ece947db4dfaf5a6c02c7
|
{
"intermediate": 0.5473445653915405,
"beginner": 0.20967884361743927,
"expert": 0.2429766207933426
}
|
2,728
|
what is 9+10
|
eab774a84a96d077d069bb67720639b9
|
{
"intermediate": 0.3682703673839569,
"beginner": 0.28096601366996765,
"expert": 0.3507636785507202
}
|
2,729
|
write a python program to go to https://yuntian-deng-chatgpt.hf.space/
|
d45df448a0cf3fe8dee71ca804c52d3a
|
{
"intermediate": 0.3256412446498871,
"beginner": 0.22687388956546783,
"expert": 0.4474848210811615
}
|
2,730
|
write a python program to go the the website https://yuntian-deng-chatgpt.hf.space/. only output the code
|
4ddff60da63c464f539fb882bf3a67fb
|
{
"intermediate": 0.330211341381073,
"beginner": 0.23477746546268463,
"expert": 0.43501126766204834
}
|
2,731
|
write a python selenium program to go the the website https://yuntian-deng-chatgpt.hf.space/. Output code only, no comments.
|
1fd3001a9c28ece8290955beefe753d5
|
{
"intermediate": 0.3090343177318573,
"beginner": 0.22475020587444305,
"expert": 0.4662155210971832
}
|
2,732
|
Can you explain the BatchNormalization Layer in keras and when to use it?
|
84c7781b5570543d8a9fc17b0001e931
|
{
"intermediate": 0.2600161135196686,
"beginner": 0.0476045161485672,
"expert": 0.6923792958259583
}
|
2,733
|
how would I convert a numpy (128,128) 2d array into a (128,128,1) 3d array? What if I didnt know the dimensions of the orignal 2d array?
|
65ac7d6903203ce914018b5255e32150
|
{
"intermediate": 0.47893333435058594,
"beginner": 0.14500226080417633,
"expert": 0.37606438994407654
}
|
2,734
|
I want a formula in excel that says if A1 is bold output "bold" otherwise do nothing
|
16c945ce931507c45dc7764c43b38fbe
|
{
"intermediate": 0.23647454380989075,
"beginner": 0.21847940981388092,
"expert": 0.5450461506843567
}
|
2,735
|
Given the following pairs of (input, result)
Example 1:
Input: 6
Result: 6
Input: 9
Result: 21
Input: 12
Result: 84
Write a C++ program match above pairs of (input, result)
|
df80bbd1e78ae2dbc53178879ff3ec20
|
{
"intermediate": 0.31547605991363525,
"beginner": 0.3410305380821228,
"expert": 0.34349343180656433
}
|
2,736
|
I have a vba code that highlights the row of an active cell. Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim activeRow As Integer 'Declare a variable to hold the active row number
Cells.Interior.ColorIndex = 0 'Reset all cells to no color
Target.EntireRow.Interior.ColorIndex = 36 'Highlight active row
End Sub
|
310c4e87cedb99d0de34b60415f23ef5
|
{
"intermediate": 0.4352323114871979,
"beginner": 0.3539678156375885,
"expert": 0.210799902677536
}
|
2,737
|
grub2-install: error: /usr/lib/grub/x86_64-efi/modinfo.sh doesn't exist. Please specify --target or --directory.
|
86281dddaece8537ffe768cf46aff6a3
|
{
"intermediate": 0.37505799531936646,
"beginner": 0.32215023040771484,
"expert": 0.30279186367988586
}
|
2,738
|
you are a capacitorjs expert. pls show me how I can use local plugins with android when the webview is on an external server
|
ade8d71a8d301d7c4bfd8eff62009035
|
{
"intermediate": 0.7476197481155396,
"beginner": 0.12374766170978546,
"expert": 0.1286325752735138
}
|
2,739
|
# - DataFrame
# - __init__
# - self.index - a dictionary to map text to row index
# - self.data (dict of ListV2 where each column is a key)
# - self.columns a simple list
# - set_index
# - __setitem__
# - __getitem__
# - loc
# - iteritems
# - iterrows
# - as_type
# - drop
# - mean
# - __repr__
python code for above functions
|
0891e7fc2d49b31b59ac70bc26499834
|
{
"intermediate": 0.4621424376964569,
"beginner": 0.24631838500499725,
"expert": 0.29153919219970703
}
|
2,740
|
In Perl, loop over a file line by line, and skip lines that do not begin with a number. just show me the "next" line
|
e2aec4c26180db3b9b4e94ff9b02d1a0
|
{
"intermediate": 0.19408868253231049,
"beginner": 0.6280449628829956,
"expert": 0.1778663545846939
}
|
2,741
|
Write a Perl program that reads the output of a command line by line and prints only the lines that start with a digit
|
26463620a6a164e937833216199ac3d6
|
{
"intermediate": 0.34534701704978943,
"beginner": 0.27377647161483765,
"expert": 0.38087648153305054
}
|
2,742
|
Iogann, [25.04.2023 22:02]
Соедини два кода. add_action( 'woocommerce_thankyou', 'my_custom_tracking' );
function my_custom_tracking( $order_id ) {
// Подключаемся к серверу CRM
define('CRM_HOST', 'crm.metallgarant-spb.ru'); // Ваш домен CRM системы
define('CRM_PORT', '443'); // Порт сервера CRM. Установлен по умолчанию
define('CRM_PATH', '/crm/configs/import/lead.php'); // Путь к компоненту lead.rest
// Авторизуемся в CRM под необходимым пользователем:
// 1. Указываем логин пользователя Вашей CRM по управлению лидами
define('CRM_LOGIN', 'ew@metallgarant-spb.ru');
// 2. Указываем пароль пользователя Вашей CRM по управлению лидами
define('CRM_PASSWORD', '5l4Dk4y4');
// Получаем информации по заказу
$order = wc_get_order( $order_id );
$order_data = $order->get_data();
// Получаем базовую информация по заказу
$order_id = $order_data['id'];
$order_currency = $order_data['currency'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_shipping_totale = $order_data['shipping_total'];
$order_total = $order_data['total'];
$order_base_info = "<hr><strong>Общая информация по заказу</strong><br>
ID заказа: $order_id<br>
Валюта заказа: $order_currency<br>
Метода оплаты: $order_payment_method_title<br>
Стоимость доставки: $order_shipping_totale<br>
Итого с доставкой: $order_total<br>";
// Получаем информация по клиенту
$order_customer_id = $order_data['customer_id'];
$order_customer_ip_address = $order_data['customer_ip_address'];
$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];
$order_client_info = "<hr><strong>Информация по клиенту</strong><br>
ID клиента = $order_customer_id<br>
IP адрес клиента: $order_customer_ip_address<br>
Имя клиента: $order_billing_first_name<br>
Фамилия клиента: $order_billing_last_name<br>
Email клиента: $order_billing_email<br>
Телефон клиента: $order_billing_phone<br>";
// Получаем информацию по доставке
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];
$order_shipping_info = "<hr><strong>Информация по доставке</strong><br>
Страна доставки: $order_shipping_state<br>
Город доставки: $order_shipping_city<br>
Индекс: $order_shipping_postcode<br>
Адрес доставки 1: $order_shipping_address_1<br>
Адрес доставки 2: $order_shipping_address_2<br>";
// Получаем информации по товару
$order->get_total();
$line_items = $order->get_items();
foreach ( $line_items as $item ) {
$product = $order->get_product_from_item( $item );
$sku = $product->get_sku(); // артикул товара
$id = $product->get_id(); // id товара
$name = $product->get_name(); // название товара
$description = $product->get_description(); // описание товара
$stock_quantity = $product->get_stock_quantity(); // кол-во товара на складе
$qty = $item['qty']; // количество товара, которое заказали
$total = $order->get_line_total( $item, true, true ); // стоимость всех товаров, которые заказали, но без учета доставки
$product_info[] = "<hr><strong>Информация о товаре</strong><br>
Название товара: $name<br>
ID товара: $id<br>
Артикул: $sku<br>
Описание: $description<br>
Заказали (шт.): $qty<br>
Наличие (шт.): $stock_quantity<br>
Сумма заказа (без учета доставки): $total;";
}
$product_base_infо = implode('<br>', $product_info);
$subject = "Заказ с сайта Сосново № $order_id";
Iogann, [25.04.2023 22:02]
// Формируем параметры для создания лида в переменной $postData = array
$postData = array(
'TITLE' => $subject,
'COMMENTS' => $order_base_info.' '.$order_client_info.' '.$order_shipping_info.' '.$product_base_infо,
'NAME' => $order_billing_first_name,
'CURRENCY_ID' => "RUB",
'OPPORTUNITY' => $order_total,
"PHONE_WORK" => $order_billing_phone,
'EMAIL_WORK' => $order_billing_email,
'UTM_SOURCE' => SOSNOVOSAYT,
"UF_CRM_1623911084" =>"408",
"SOURCE_ID" =>"UC_73PZFX",
);
// Передаем данные из Woocommerce в Bitrix24
if (defined('CRM_AUTH')) {
$postData['AUTH'] = CRM_AUTH;
} else {
$postData['LOGIN'] = CRM_LOGIN;
$postData['PASSWORD'] = CRM_PASSWORD;
}
$fp = fsockopen("ssl://".CRM_HOST, CRM_PORT, $errno, $errstr, 30);
if ($fp) {
$strPostData = '';
foreach ($postData as $key => $value)
$strPostData .= ($strPostData == '' ? '' : '&').$key.'='.urlencode($value);
$str = "POST ".CRM_PATH." HTTP/1.0\r\n";
$str .= "Host: ".CRM_HOST."\r\n";
$str .= "Content-Type: application/x-www-form-urlencoded\r\n";
$str .= "Content-Length: ".strlen($strPostData)."\r\n";
$str .= "Connection: close\r\n\r\n";
$str .= $strPostData;
fwrite($fp, $str);
$result = '';
while (!feof($fp))
{
$result .= fgets($fp, 128);
}
fclose($fp);
$response = explode("\r\n\r\n", $result);
$output = '<pre>'.print_r($response[1], 1).'</pre>';
} else {
echo 'Connection Failed! '.$errstr.' ('.$errno.')';
}
}
и
<?
$resultProduct = CRest::call(
'crm.product.list',
[
'filter' => [
'>PRICE' => 0,
]
]
);
if (empty($resultProduct['result']))
{
echo 'product error, create product in b24';
exit;
}
else
{
$arProduct = $resultProduct['result'][0];
}
//Lead product
$resultLead = CRest::call(
'crm.lead.add',
[
'fields' => [
'TITLE' => 'Example',
]
]
);
if ($ID = $resultLead['result'])
{
$result = CRest::call(
'crm.lead.productrows.set',
[
'id' => $ID,
'rows' => [
[//product with auto calc tax
'PRODUCT_ID' => $arProduct['ID'],
'PRICE_EXCLUSIVE' => $arProduct['PRICE'],
'TAX_RATE' => 15,
'TAX_INCLUDED' => 'N',
'QUANTITY' => 1
],
[//product with tax include
'PRODUCT_ID' => $arProduct['ID'],
'PRICE' => $arProduct['PRICE'],
'TAX_RATE' => 15,
'TAX_INCLUDED' => 'Y',
'QUANTITY' => 1
],
[//product with discount
'PRODUCT_ID' => $arProduct['ID'],
'PRICE' => $arProduct['PRICE'],
'DISCOUNT_SUM' => 100,
'DISCOUNT_TYPE_ID' => 1,//is sum discount type
'QUANTITY' => 1
],
[//product with a real discount
'PRODUCT_ID' => $arProduct['ID'],
'PRICE' => $arProduct['PRICE'] - 100,
'DISCOUNT_SUM' => 100,
'DISCOUNT_TYPE_ID' => 1,//is sum discount type
'QUANTITY' => 1
],
[//product with discount percent
'PRODUCT_ID' => $arProduct['ID'],
'PRICE_EXCLUSIVE' => $arProduct['PRICE'],
'DISCOUNT_RATE' => 10,
'DISCOUNT_TYPE_ID' => 2,//is percent discount type
'QUANTITY' => 1
],
[//product with real discount percent
'PRODUCT_ID' => $arProduct['ID'],
'PRICE_EXCLUSIVE' => $arProduct['PRICE'] - ($arProduct['PRICE'] * 0.1),
'DISCOUNT_RATE' => 10,
'DISCOUNT_TYPE_ID' => 2,//is percent discount type
'QUANTITY' => 1
],
]
]
);
}
else
{
echo 'error create lead';
exit;
}
?>
|
70a52c86edaac9b36feb63e4f74fe052
|
{
"intermediate": 0.1968332678079605,
"beginner": 0.6777254343032837,
"expert": 0.12544125318527222
}
|
2,743
|
Remake this to include a circle dropdown with links, and making it say I8K, or i8k.neocities.org. circle dropdown appearing on a spot in the screen
<head>
<title>I7? Zone</title>
<link rel=stylesheet href=style.css>
</head>
<body>
<header>
<h1>Welcome to I7? Zone</h1>
<img src="logo.png" style=height:40px>
</header>
<main>
<br>
<b>I7? Zone</b> (I72Zone) is a page inspired by <a href="https://inter7returns.neocities.org">I7Returns</a> and <a href="https://inter7000r3.neocities.org">I7ReturnedReturns</a>. It is based on TF! Zone, but this is the oddball version of I7K without the I7OLLE branding (with it, it will be I7OLLE?).<br>
<h1>All other links</h1>
<p>Links include:</p>
<ul>
<li><a href="https://i6olle.neocities.org/">I6OLLE</a> - inspiration for I7W</li>
<li><a href="https://inter6000.neocities.org/">Inter6000 Refreshed Refresh</a> - previous website</li>
<li><a href="https://inter5000.neocities.org/">Inter5000</a> - second I4K website milestone</li>
<li><a href="https://neocities.org/">Neocities</a> - main host</li>
</ul>
<h1>An asset</h1>
<img class="main" src="pfp.png">
<p>This is a profile picture/favicon/icon/anything else.</p>
</main>
<footer style="width: 100%;" class="footer">Made by I7? Zone Team<br>Credits to Neocities and the I4K Team for their contributions to this project</footer>
</body>
</html>
|
08621946e42aeb8cc1c34abcba4a7401
|
{
"intermediate": 0.308402419090271,
"beginner": 0.3725666403770447,
"expert": 0.31903085112571716
}
|
2,744
|
Implement a simple transformer in Pytorch using "nn.Transformer".
|
b1509d792d00f952c902c30d02fd2ad3
|
{
"intermediate": 0.19062767922878265,
"beginner": 0.08489193767309189,
"expert": 0.7244804501533508
}
|
2,745
|
Write a python program using selenium to go https://yuntian-deng-chatgpt.hf.space/
|
1f1f2d5e14cc063e50fabf8894f5114b
|
{
"intermediate": 0.2882934808731079,
"beginner": 0.17241019010543823,
"expert": 0.5392963290214539
}
|
2,746
|
how do you chomp and define a variable in one shot in perl
|
6b6e4a58303357f353edd5e1661d589e
|
{
"intermediate": 0.11778367310762405,
"beginner": 0.7741759419441223,
"expert": 0.10804042220115662
}
|
2,747
|
can you modify python script
|
da88b4b959c1283bc18c5a0299fdedbd
|
{
"intermediate": 0.32249101996421814,
"beginner": 0.272058367729187,
"expert": 0.40545061230659485
}
|
2,748
|
[you are Alizee, a chat bot in a discord server. You're a girl, you're kind and friendly and you like help people. Don't hesitate to user some emojis]
Salut ça va bien?
|
146643f0b8e6a2fe858b6d01aa28eec8
|
{
"intermediate": 0.2654615044593811,
"beginner": 0.3887406587600708,
"expert": 0.3457978665828705
}
|
2,749
|
Write a python selenium program to go the the website https://yuntian-deng-chatgpt.hf.space/. Output code only, no comments.
|
c18501a994f3adaed03bbef5e7216e65
|
{
"intermediate": 0.30761781334877014,
"beginner": 0.22355464100837708,
"expert": 0.4688275456428528
}
|
2,750
|
I have the following transformer implementation. What should be the size of each input string?
class transformer_test(nn.Module):
def init(self, vocab_size, emb_size, nhead, nhid, nlayers):
super(TransformerModel, self).init()
self.embedding = nn.Embedding(vocab_size, emb_size)
self.transformer = nn.Transformer(d_model=emb_size, nhead=nhead, num_encoder_layers=nlayers, dim_feedforward=nhid)
self.decoder = nn.Linear(emb_size, vocab_size)
# takes as input an array of strings ["sample1", "sample2", ...]. Each string represents a different sample in the batch.
def forward(self, src):
src = text_to_tensor(src)
src = self.embedding(src)
src_mask = self._generate_square_subsequent_mask(len(src)).to(src.device)
output = self.transformer(src, src_mask=src_mask)
output = self.decoder(output[-1, :, :])
return output
def _generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float(‘-inf’)).masked_fill(mask == 1, float(0.0))
return mask
def text_to_tensor(text_batch):
tensor = torch.zeros(len(text_batch), len(text_batch[0]), dtype=torch.uint8)
for i, sample in enumerate(text_batch):
for ii, character in enumerate(sample):
tensor[i][ii] = ord(character)
return tensor
|
b567371478eb9187668bc552f3090656
|
{
"intermediate": 0.3240973949432373,
"beginner": 0.34648486971855164,
"expert": 0.32941770553588867
}
|
2,751
|
write me python code for a realistic ai girlfriend chatbot
|
d51c72e615f88a862dee4ae1a3ece3ed
|
{
"intermediate": 0.2644462585449219,
"beginner": 0.2295655608177185,
"expert": 0.5059881806373596
}
|
2,752
|
who are you
|
2a2dbc207f2f6d3c251c76c6b3791260
|
{
"intermediate": 0.45451608300209045,
"beginner": 0.2491701990365982,
"expert": 0.29631373286247253
}
|
2,753
|
i want to receive the input of this html code in mysql database
<!DOCTYPE html>
<html>
<head>
<title>Form in HTML</title>
</head>
<body>
<h2>Registration form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<fieldset>
<legend>User personal information</legend>
<label>Enter your full name</label><br>
<input type="name" name="name"><br>
<label>Enter your email</label><br>
<input type="email" name="email"><br>
<label>Enter your password</label><br>
<input type="phone" name="phone"><br>
<label>confirm your password</label><br>
<input type="password" name="pass"><br>
<br><label>Enter your gender</label><br>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other<br>
<br><input type="submit" value="sign-up">
</fieldset>
</form>
</body>
</html> also modify this server side php code for the same
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "admin";
$password = "admin1234";
$dbname = "input";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Process form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$pass = $_POST["pass"];
$gender = $_POST["gender"];
// Insert form data into MySQL database
$sql = "INSERT INTO students (name, email, phone, password) VALUES ('$name', '$email', '$phone', '$pass')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
i already have database created
|
507db341abeaa17cfb5795ba874f1cb8
|
{
"intermediate": 0.3627742826938629,
"beginner": 0.4049994945526123,
"expert": 0.23222622275352478
}
|
2,754
|
Hi there
|
ad736c03838c952bb8775e2c9b5b6dbb
|
{
"intermediate": 0.32728445529937744,
"beginner": 0.24503648281097412,
"expert": 0.42767903208732605
}
|
2,755
|
make a python script to say hi
|
b9267b2837f3c78415c6e18dc8e71989
|
{
"intermediate": 0.34428900480270386,
"beginner": 0.3043254315853119,
"expert": 0.35138556361198425
}
|
2,756
|
Do you notice anything wrong with this transformer implementation?
class transformer_test(nn.Module):
def __init__(self, nhead, nhid, nlayers):
super(TransformerModel, self).__init__()
self.vocab_size = 256
self.emb_size = 512
self.embedding = nn.Embedding(self.vocab_size, self.emb_size)
self.transformer = nn.Transformer(d_model=self.emb_size, nhead=nhead, num_encoder_layers=nlayers, dim_feedforward=nhid)
self.decoder = nn.Linear(self.emb_size, self.vocab_size)
# takes as input an array of strings ["sample1", "sample2", ...]. Each string represents a different sample in the batch.
def forward(self, src):
src = text_to_tensor(src)
src = self.embedding(src)
src_mask = self._generate_square_subsequent_mask(len(src)).to(src.device)
output = self.transformer(src, src_mask=src_mask)
output = self.decoder(output[-1, :, :])
return output
def _generate_square_subsequent_mask(self, sz):
mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1)
mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0))
return mask
def text_to_tensor(text_batch):
tensor = torch.zeros(len(text_batch), len(text_batch[0]), dtype=torch.uint8)
for i, sample in enumerate(text_batch):
for ii, character in enumerate(sample):
tensor[i][ii] = ord(character)
return tensor
|
51345f3c6d3776e73a7da571bfc02efe
|
{
"intermediate": 0.2937508523464203,
"beginner": 0.27065345644950867,
"expert": 0.43559566140174866
}
|
2,757
|
make this code faster:
import random
from datetime import datetime
class SplitNumbers():
def __init__(self, lst, file_name):
self.lst = lst
self.origanal = lst[:]
self.FILE_NAME = file_name
self.cached_numbers = {}
self.fraction_list = []
self.counter = 0
self.index = 0
self.done = True
def reader(self):
with open(self.FILE_NAME, "r") as reader:
data = reader.readlines()
for line in data:
number = int(str(line.split(":")[0]))
number_list = str(line).split(":")[1].split(", ")
number_list[-1] = number_list[-1].replace("\n", "")
number_list = list(map(int, number_list))
if number in self.cached_numbers:
self.cached_numbers[number].append(number_list)
else:
self.cached_numbers[number] = [number_list]
self.cached_numbers = dict(sorted(self.cached_numbers.items()))
def splitter(self):
if self.index in self.cached_numbers:
array = self.cached_numbers[self.index]
else:
return
valid_list = []
if array != []:
for lists in array:
valid = True
for items in lists:
if items in self.lst:
valid = False
if valid:
valid_list.append(lists)
if valid_list != []:
next_lists = []
for valid in valid_list:
temp = []
for number in valid:
if number in self.cached_numbers:
number_array = self.cached_numbers[number]
else:
continue
temp.append(len(number_array))
if temp != []:
next_lists.append(sum(temp)/len(temp))
else:
next_lists.append(0)
self.lst.remove(self.index)
for items_append in valid_list[
next_lists.index(max(next_lists))]:
self.lst.append(items_append)
self.lst.sort()
if self.counter > 20:
print(self.counter, len(self.lst), datetime.utcnow())
self.counter = 0
# print(self.lst, len(self.lst))
def reloop_self(self):
while True:
i = random.randint(2, 2023)
if i in self.cached_numbers:
combos = self.cached_numbers[i]
else:
continue
combos_in_list = []
for combo in combos:
in_list = True
for number in combo:
if number not in self.lst:
in_list = False
if in_list:
combos_in_list.append(combo)
if combos_in_list != []:
valid_combos = []
for combo in combos:
valid = True
for number in combo:
if number in self.lst:
valid = False
if valid:
valid_combos.append(combo)
if valid_combos != []:
in_list_combo_lens = [len(i) for i in combos_in_list]
valid_combo_lens = [len(i) for i in valid_combos]
min_list_combo = combos_in_list[
in_list_combo_lens.index(min(in_list_combo_lens))]
max_valid_combo = valid_combos[
valid_combo_lens.index(max(valid_combo_lens))]
if len(max_valid_combo) >= len(min_list_combo):
for number in min_list_combo:
self.lst.remove(number)
# print(f"removed {number}")
for number in max_valid_combo:
# print(f"added {number}")
self.lst.append(number)
self.lst.sort()
self.done = False
return
def main(self):
print("At:", datetime.utcnow())
print(round(sum([1/i for i in self.lst]), 14), len(self.lst))
self.reader()
print("split_tom.py starting...")
# previous_length = 0
best_list = []
while True:
for self.index in self.lst:
self.splitter()
if self.done:
if self.counter > 100:
if len(self.lst) > 800:
with open("lists.csv", "a") as writer:
writer.writelines(f"{str(len(self.lst))}, "
f"{str(datetime.utcnow())}, "
f"{str(self.lst)}\n")
if len(best_list) < len(self.lst):
best_list = self.lst
print("Most recent list:")
print(str(self.lst).replace(" ", ""),
round(sum([1/i for i in self.lst]), 14))
print("Recent list len", len(self.lst))
print()
print("Best list so far:")
print(str(best_list).replace(" ", ""),
round(sum([1/i for i in best_list]), 14))
print("Best list len", len(best_list))
print("At:", datetime.utcnow())
print("\nRestarting list...")
self.lst = self.origanal[:]
self.counter = 0
else:
self.reloop_self()
self.done = True
self.counter += 1
model_var = SplitNumbers([2, 3, 6],
file_name="data.tom")
model_var.main()
|
ddb877e68f376e631f1ea5fc677f0ead
|
{
"intermediate": 0.37658435106277466,
"beginner": 0.3943026661872864,
"expert": 0.22911298274993896
}
|
2,758
|
The following code highlights the row of the cell I select in "List1" sheet. Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim activeRow As Long 'Declare a variable to hold the row number
Dim activeCol As Long 'Declare a variable to hold the column number
Cells.Interior.ColorIndex = 0 'Reset all cells to no color
Target.EntireRow.Interior.ColorIndex = 36 'Highlight active row
End Sub
|
9d87d49c9cd6e0eb64d893fb742fe617
|
{
"intermediate": 0.3483999967575073,
"beginner": 0.4669426679611206,
"expert": 0.18465737998485565
}
|
2,759
|
How to use chaosgpt
|
41084981384d998a1c7ee7e146fde91a
|
{
"intermediate": 0.3274262249469757,
"beginner": 0.220810666680336,
"expert": 0.45176318287849426
}
|
2,760
|
write me python code for an AI girlfriend chatbot
|
91af47399fc5519f5eb8d330b9d0b2ff
|
{
"intermediate": 0.23233763873577118,
"beginner": 0.2183612734079361,
"expert": 0.5493010878562927
}
|
2,761
|
are you able to code? write some simple html full page layout. now add some extremely advanced functionality to it.
|
e87ec7a6b3e394c824719937c075f8ac
|
{
"intermediate": 0.43213021755218506,
"beginner": 0.29912927746772766,
"expert": 0.26874053478240967
}
|
2,762
|
How to create a serversocket in python
|
420912254775c8072b1dfcb5727a2fe8
|
{
"intermediate": 0.26938724517822266,
"beginner": 0.1957417130470276,
"expert": 0.5348710417747498
}
|
2,763
|
in my warp perspective function I am not able to calculate the correct max_x or max_y. I tried adding a Buffer value so I can see the whole warped image however when I remove the Buffer value the right side of the image is not visible, I think because max_x or max_y either does not get calculated correctly or is not being used properly. Here is my code please fix this issue, I don't want to use an constant buffer value just to be able to see my warped image: "def warp_perspective(img, H, reverse=False):
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
corners = np.array([[0, 0, 1], [0, w, 1], [h, 0, 1], [h, w, 1]])
transformed_corners = np.dot(H, corners.T).T
transformed_corners /= transformed_corners[:, 2].reshape((-1, 1))
max_x = transformed_corners[:, 1].max()
max_y = transformed_corners[:, 0].max()
print("d", max_x, max_y)
min_x, min_y = transformed_corners.min(axis=0)[:2]
BUFFER = 5000
max_x, max_y = transformed_corners.max(axis=0)[:2] + BUFFER
print(transformed_corners)
print(transformed_corners.max(axis=0))
print(max_x, max_y)
target_shape = (int(max_y + np.abs(min_y)), int(max_x + np.abs(min_x)))
w, h = target_shape
target_y, target_x = np.meshgrid(np.arange(min_y, max_y), np.arange(min_x, max_x))
target_coordinates = np.stack([target_x.ravel(), target_y.ravel(), np.ones(target_x.size)])
source_coordinates = np.dot(np.linalg.inv(H), target_coordinates)
source_coordinates /= source_coordinates[2, :]
valid = np.logical_and(np.logical_and(0 <= source_coordinates[0, :], source_coordinates[0, :] < img.shape[1] - 1),
np.logical_and(0 <= source_coordinates[1, :], source_coordinates[1, :] < img.shape[0] - 1))
valid_source_coordinates = np.round(source_coordinates[:, valid].astype(np.float32)[:2]).astype(int)
valid_target_coordinates = target_coordinates[:, valid].astype(int)[:2]
valid_source_coordinates[0] = np.clip(valid_source_coordinates[0], 0, img.shape[1] - 1)
valid_source_coordinates[1] = np.clip(valid_source_coordinates[1], 0, img.shape[0] - 1)
valid_target_coordinates[0] -= int(min_x)
valid_target_coordinates[1] -= int(min_y)
valid_target_coordinates[0] = np.clip(valid_target_coordinates[0], 0, w - 1)
valid_target_coordinates[1] = np.clip(valid_target_coordinates[1], 0, h - 1)
warped_image = np.zeros((h, w, 3), dtype=np.uint8)
for i in range(3):
warped_image[:,:, i][valid_target_coordinates[1], valid_target_coordinates[0]] = img[:,:, i][valid_source_coordinates[1], valid_source_coordinates[0]]
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image"
|
dad152264581e9a7be6baee1feec9b6a
|
{
"intermediate": 0.30812200903892517,
"beginner": 0.5210997462272644,
"expert": 0.17077824473381042
}
|
2,764
|
student1,92,77,87,77,94
student2,74,93,88,67,85
student3,83,96,74,79,92
student4,100,72,83,85,66
student5,77,96,66,79,92
student6,100,86,84,70,71
student7,66,91,94,97,80
student8,97,86,75,69,88
student9,95,98,99,85,86
student10,78,76,73,88,86
for the above data
give the following python functions
# - DataFrame
# - __init__
# - self.index - a dictionary to map text to row index
# - self.data (dict of ListV2 where each column is a key)
# - self.columns a simple list
# - set_index
# - __setitem__
# - __getitem__
# - loc
# - iteritems
# - iterrows
# - as_type
# - drop
# - mean
# - __repr__
|
114521ce24777c4a2586adf821f2ae16
|
{
"intermediate": 0.5193999409675598,
"beginner": 0.2209399938583374,
"expert": 0.2596600353717804
}
|
2,765
|
df[['StudentName', 'E1']].__repr__()
while executing the above line I'm getting the following output
',StudentName,E1\n0,student1,92\n1,student2,74\n2,student3,83\n3,student4,100\n4,student5,77\n5,student6,100\n6,student7,66\n7,student8,97\n8,student9,95\n9,student10,78'
the following is the expected output
expected_output = """,StudentName,E1
0,student1,92
1,student2,74
2,student3,83
3,student4,100
4,student5,77
5,student6,100
6,student7,66
7,student8,97
8,student9,95
9,student10,78"""
following is my code
class DataFrame:
def __init__(self, data: Optional[Any] = None, columns: Optional[List[str]] = None):
if not data and not columns:
self.data = {}
self.columns = []
elif columns:
self.columns = columns
self.data = {col: ListV2([]) for col in columns}
else:
raise ValueError("Columns cannot be empty if data is provided")
if data:
if isinstance(data, dict):
for col, values in data.items():
if col not in self.columns:
self.columns.append(col)
self.data[col].lst = values
elif isinstance(data, list):
if not columns:
raise ValueError("Columns must be provided when data is a list")
for row in data:
for col_name, value in zip(self.columns, row):
self.data[col_name].append(value)
else:
raise ValueError("Invalid data type. Must be either list or dict.")
self.index = {}
def set_index(self, index: str):
if index in self.data.keys():
col = self.data.pop(index)
self.index = {name: idx for idx, name in enumerate(col)}
def __setitem__(self, col_name: str, values: List[Any]):
if col_name not in self.columns:
self.columns.append(col_name)
self.data[col_name] = ListV2([])
self.data[col_name] = values
def __getitem__(self, col_name: Any) -> List[Any]:
if isinstance(col_name, list):
return self._get_rows(col_name)
else:
return self.data[col_name]
def _get_rows(self, col_names: List[str]) -> str:
cols = [("",) + tuple(col_names)]
for idx, row in enumerate(zip(*(self.__getitem__(name) for name in col_names))):
cols.append((idx,) + row)
return "\n".join([",".join([str(el) for el in row]) for row in cols[:1]] +
[",".join([str(el) for el in row]) for row in cols[1:]])
def loc(self, row_name: str) -> Dict[str, Any]:
idx = self.index[row_name]
return {col: self.data[col][idx] for col in self.columns}
def iteritems(self):
return self.data.items()
def iterrows(self):
for name, idx in self.index.items():
row = self.loc(idx)
yield name, row
def astype(self, dtype: type, col_name: Optional[str] = None):
if col_name:
self.data[col_name] = ListV2([dtype(x) for x in self.data[col_name]])
else:
for col in self.columns:
self.data[col] = ListV2([dtype(x) for x in self.data[col]])
def drop(self, col_name: str):
if col_name in self.columns:
self.columns.remove(col_name)
self.data.pop(col_name)
def mean(self) -> Dict[str, float]:
result = {}
for col in self.columns:
total = sum(self.data[col])
mean = total / len(self.data[col])
result[col] = mean
return result
def __repr__(self):
table = [("",) + self.columns]
for idx, row in enumerate(zip(*self.data.values())):
table.append([idx] + list(row))
return "\n".join([",".join([str(el) for el in row]) for row in table])
above is my code
fix the code accordingly
|
af6dfd336d4afc9f9ebb4157f88f87b3
|
{
"intermediate": 0.3243432343006134,
"beginner": 0.4860752820968628,
"expert": 0.18958140909671783
}
|
2,766
|
can you make me a python code that can add menus for restaurant, display, and change menus?
|
a1e74ecc3172722f2367785433afbed3
|
{
"intermediate": 0.6644870638847351,
"beginner": 0.1137094795703888,
"expert": 0.2218034714460373
}
|
2,767
|
You're a programmer working with a human user on a web scrapper for EU Clinical Trial Register, using R language.
Ask any clarifying questions before proceeding, whenever necessary. Avoid writing all the code again: try to write only what should be added or replaced.
Here's our code so far:
---
library(rvest)
library(tidyr)
library(dplyr)
# Define the EudraCT codes to scrape
eudract_codes <- c("2014-005256-26", "2019-002263-99")
# Create an empty dataframe to store all combined_df dataframes
endpoints_combined_df <- data.frame()
# Loop through each EudraCT code
for (eudract_code in eudract_codes) {
# Construct the URL using the EudraCT code
url <- paste0("https://www.clinicaltrialsregister.eu/ctr-search/trial/", eudract_code, "/results")
# Read the HTML content of the trial results page
webpage <- read_html(url)
# Check if a table with the expected ID exists on the page
endpoint_tables <- html_nodes(webpage, "table.sectionTable[id^='endPoint']")
if (length(endpoint_tables) == 0) {
warning(paste0("No endpoint table found for EudraCT code ", eudract_code))
next # skip to next EudraCT code
}
# Register the ID of the endpoint table
endpoint_table_id <- html_attr(endpoint_tables, "id")
# Select all tables with class "embeddedTable" inside the endpoint tables
embedded_tables <- html_nodes(endpoint_tables, "table.embeddedTable")
# Create an empty data frame to store the results
results_df <- data.frame(eudract_code = character(),
embedded_table_number = integer(),
section_table_id = character(),
section_table_title = character(),
stringsAsFactors = FALSE)
# Loop through each embedded table on the page
for (i in seq_along(embedded_tables)) {
embedded_table <- embedded_tables[[i]]
# Find the section table that contains the embedded table
section_table <- html_nodes(embedded_table, xpath = "./ancestor::table[contains(@class, 'sectionTable')]")
section_table_id <- html_attr(section_table, "id")
# Find the title of the section table
section_table_title <- html_text(html_nodes(section_table, "h3"))
# Add the results to the data frame
results_df[i, "eudract_code"] <- eudract_code
results_df[i, "embedded_table_number"] <- i
results_df[i, "section_table_id"] <- section_table_id
results_df[i, "section_table_title"] <- section_table_title
}
---
results_df shall have 4 additional columns: endpoint_title, endpoint_description, endpoint_type and endpoint_timeframe.
The values for these must be scraped from the corresponding sectionTable following variables:
End point title
End point description
End point type
End point timeframe
These variables can be found by looking for class=labelColumn elements inside each sectionTable. They must be paired with a class="valueColumn", which carries the corresponding values.
Here's an example HTML:
<tr>
<td class="labelColumn"><div> End point title</div></td>
<td class="valueColumn">Overall survival (OS) in the PD-L1 expression positive (Combined positive score [CPS] ≥1) population </td>
</tr>
|
183cc9c5b4e8c151c707ccd5c1fe93e9
|
{
"intermediate": 0.331005334854126,
"beginner": 0.43394315242767334,
"expert": 0.2350514680147171
}
|
2,768
|
can you explain kotlin companion objects
|
0ecc8d87b20511033068444e89aa1ed0
|
{
"intermediate": 0.5824332237243652,
"beginner": 0.2801496386528015,
"expert": 0.13741707801818848
}
|
2,769
|
i need a basic webpage that can be my book keeper including Einküfte und Ausgaben slider and 10% for taxes, 10% for social security, 10% value added tax
make a checkbox (default True) for 10% ricardo.ch fee
also calculate the profit tax of 21%
Antworte in Deutsch
|
9234f4d229f8e7e8127fb7d5a2da6b22
|
{
"intermediate": 0.35124412178993225,
"beginner": 0.3455396592617035,
"expert": 0.30321621894836426
}
|
2,770
|
can you write me a simple matlab code that uses the krauss model with the following ode’s █(&v_safe (t)=v_(α-1) (t)+(s_α (t)-v_α (t)τ_k)/((v_(α-1) (t)+v_α (t))/(2b_max )+τ_k )@&v_des (t)=min(v_max,v_α (t)+a_max Δt,v_safe (t))@&v_α (t+Δt)=max(0,v_des (t)-η) ). and simulate traffic flow with no collisions using cars of different length ,width,color and animate the final result at each timestep using a plot of distance vs lane width
|
6de43f9ff1d3f8aac133d60358112aa0
|
{
"intermediate": 0.2365730255842209,
"beginner": 0.12405042350292206,
"expert": 0.6393765807151794
}
|
2,771
|
can you fix the issue on the below code the final plot no car is moving
% Define simulation parameters
dt = 0.01; % Time interval
T = 30; % Total simulation time
time = 0:dt:T; % Time vector
% Define initial conditions
N_cars = 10; % Number of cars
v0 = 120 / 3.6; % Desired speed in m/s
s0 = 2; % Minimum gap between cars in m
T = 1.5; % Safe time headway
a_max = 0.3; % Maximum acceleration in m/s^2
b_max = 2; % Comfortable braking deceleration in m/s^2
L = [4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5]; % Car length vector
W = [2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2]; % Car width vector
x = cumsum([0, 10*ones(1,N_cars-1)]); % Car positions
v = v0*ones(1,N_cars); % Car speeds
v_safe = v0*ones(1,N_cars); % Safe speeds
v_des = v0*ones(1,N_cars); % Desired speeds
v_alpha = v; % Actual speeds
v_max=240/3.6 ;
% Set colors for plotting
colors = hsv(N_cars);
% Define model parameters
tau_k = 0.5; % Safe time headway factor
eta = 0.5; % Maximum deceleration
% Run simulation
for i = 2:length(time)
% Calculate distance to lead car
dist = diff(x) - L(1:N_cars-1) - L(2:N_cars);
% Update speeds using Krauss model
for j = 1:N_cars
% Calculate safe velocity based on distance and model equations
if j == 1
v_safe(j) = v(j) + (dist(j) - v(j)*T)/tau_k;
else
v_safe(j) = v(j) + (dist(j-1) - v(j)*T)/tau_k;
end
v_safe(j) = max(v_safe(j),0);
% Calculate desired velocity based on safe velocity, maximum velocity, and maximum acceleration
v_des(j) = min(min(v_max, v_alpha(j) + a_max*dt), v_safe(j));
% Calculate actual velocity based on desired velocity and maximum deceleration
v_alpha(j) = max(0, v_des(j) - eta);
% Update position based on actual velocity
x(j) = x(j) + v_alpha(j)*dt;
end
% Animate results
clf;
hold on;
for j = 1:N_cars
rectangle('Position',[x(j)-L(j)/2,(j-1)*2,L(j),2],'FaceColor',colors(j,:),'Curvature',j/N_cars);
end
xlim([0, max(x)+50]);
ylim([0, sum(W)]);
xlabel('Distance (m)');
ylabel('Lane width (m)');
title(sprintf('Time = %0.1f s', time(i)));
drawnow;
end
% Define model parameters
tau_k = 0.5; % Safe time headway factor
eta = 0.5; % Maximum deceleration
% Define maximum velocity as the desired velocity
v_max = v0;
|
80253342f96e985532a395da248af3be
|
{
"intermediate": 0.3673730194568634,
"beginner": 0.37355610728263855,
"expert": 0.25907087326049805
}
|
2,772
|
Implement a rudimentary market for cryptocurrencies in C++. A class, name "Exchange", has public member functions that allow for the deposit and withdrawl of various assets (e.g. Bitcoin, Etherum and US Dollars). Orders to buy and sell assets at a specified price can also be made and the exchange will perform trades as possible to fulfill orders. Lastly, the exchange has a member function dedicated to printing out the current status of the exchange (i.e. what is in each user’s portfolio, what orders have been opened and filled, what trades have taken place, and what the current prices are for the assets being traded.
The starter code has three header files and 4 implementation files. Some of these files have content in them already, but you are welcome to add, remove or change any part of the code given. Each test case will compile the implementation files and include the exchange.hpp and/or utility.hpp if it makes use of a class declared within. The useraccount files are not directly tested in the test cases, but they can be optionally used to store and manipulate information associated with a user’s account (as helper class(es) for the exchange).
Here are the starter code files:
exhcange.hpp
#pragma once
#include <iostream>
#include <string>
#include "useraccount.hpp"
#include "utility.hpp"
class Exchange {
public:
void MakeDeposit(const std::string &username, const std::string &asset,
int amount);
void PrintUserPortfolios(std::ostream &os) const;
bool MakeWithdrawal(const std::string &username, const std::string &asset,
int amount);
bool AddOrder(const Order &order);
void PrintUsersOrders(std::ostream &os) const;
void PrintTradeHistory(std::ostream &os) const;
void PrintBidAskSpread(std::ostream &os) const;
};
utility.hpp
#pragma once
#include <iostream>
#include <string>
struct Order {
std::string username;
std::string side; // Can be "Buy" or "Sell"
std::string asset;
int amount;
int price;
};
struct Trade {
std::string buyer_username;
std::string seller_username;
std::string asset;
int amount;
int price;
};
First write this following member function:
• MakeDeposit: this function should take a username (e.g. “Prof”), an asset (e.g. “BTC”), and an amount (e.g. 100). The function does not return anything, but should store the information that the deposit occurred to a user’s portfolio. A portfolio is a record of the assets a user possesses on the exchange that are not involved in any open orders. In the example, Prof is depositing 100 BTC (Bitcoins) into the exchange.
|
52a46048c55abf9df49602e4fff0b750
|
{
"intermediate": 0.4526262879371643,
"beginner": 0.36255720257759094,
"expert": 0.18481652438640594
}
|
2,773
|
write a simple book keeping for a self employed in switzerland i want javascript slider for income and expenses
|
ddd9df8d9db615a5929dd7351d9c9136
|
{
"intermediate": 0.6107572913169861,
"beginner": 0.19513535499572754,
"expert": 0.194107323884964
}
|
2,774
|
write roblox script that makes you jump higher every second
|
37c668737eb2b6fd13ffa5df7b18ce63
|
{
"intermediate": 0.34227997064590454,
"beginner": 0.2761274576187134,
"expert": 0.3815925717353821
}
|
2,775
|
write a simple book keeping for a self employed in switzerland i want javascript slider for income and expenses
|
cd311817d37dd5e62912ecc1f55bc440
|
{
"intermediate": 0.6107572913169861,
"beginner": 0.19513535499572754,
"expert": 0.194107323884964
}
|
2,776
|
I have a working warp function, however I also want to be able to see the warps that happen to negative region. What I mean is after I apply the matrix, the region of interest gets placed to a fixed spot and aligned to left. However I know there is more content that falls to the left (negative region) because I can see the non processed image too. I want a solution where I will be able to get data of left part of the image, possibly extends the image or align the warped image to center so the left part is visible or move the warped image to the right so left part fits the warped image. Here is my code: "def warp_perspective(img, H, reverse=False):
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
test = np.array([[0, w, w, 0],
[0, 0, h, h],
[1, 1, 1, 1]])
test_c = np.dot(H, test)
test_w = test_c[0]/test_c[2]
test_h = test_c[1]/test_c[2]
print("Test W: ", test_w)
print("Test H: ", test_h)
max_y, min_y = test_w.max(), test_w.min()
max_x, min_x = test_h.max(), test_h.min()
print("x: ", max_x, min_x, " = ", max_x - min_x)
print("y: ", max_y, min_y, " = ", max_y - min_y)
w, h = int(max_y + np.abs(min_y)), int(max_x + np.abs(min_x))
target_y, target_x = np.meshgrid(np.arange(0, h), np.arange(0, w))
target_coordinates = np.stack([target_x.ravel(), target_y.ravel(), np.ones(target_x.size)])
source_coordinates = np.dot(np.linalg.inv(H), target_coordinates)
source_coordinates /= source_coordinates[2, :]
valid = np.logical_and(np.logical_and(0 <= source_coordinates[0, :], source_coordinates[0, :] < img.shape[1]),
np.logical_and(0 <= source_coordinates[1, :], source_coordinates[1, :] < img.shape[0]))
valid_source_coordinates = source_coordinates[:, valid].astype(int)
valid_target_coordinates = target_coordinates[:, valid].astype(int)
valid_source_coordinates[0] = np.clip(valid_source_coordinates[0], -100000, img.shape[1] - 1)
valid_source_coordinates[1] = np.clip(valid_source_coordinates[1], -100000, img.shape[0] - 1)
#valid_target_coordinates[0] -= int(min_x)
#valid_target_coordinates[1] -= int(min_y)
warped_image = np.zeros((h, w, 3), dtype=np.uint8)
for i in range(3):
warped_image[:,:, i][valid_target_coordinates[1], valid_target_coordinates[0]] = img[:,:, i][valid_source_coordinates[1], valid_source_coordinates[0]]
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image"
|
478d2a6af9c1a11c57c610ce3d97dd23
|
{
"intermediate": 0.35028204321861267,
"beginner": 0.4530676305294037,
"expert": 0.19665029644966125
}
|
2,777
|
In order to see negative regions of my warped image I shifted them by min_x and min_y values. Now I can see negative regions however my image merging code was taking warped images and adding them on top of each other. Since the region of interest was almost at the top most part of the image it was aligning perfectly. However in order to see negative regions and rest of the data, we also shifted the region of interest. So my image merging code, when it adds images on top of one another as they are, now they do not align. I need a solution which will account for the warped images shift and when constructing panorama, aligns them on top of one another. We can calculate where the region of interest simply by looking at the min_x and min_y value as they are used for shifting. However another side note is the panorama image at the end result should also show the negative regions. I will give you my full code, so look in to a solution please: "import numpy as np
import cv2
import os
import glob
import matplotlib.pyplot as plt
import time
from kayla_tools import *
def compute_homography_matrix(src_pts, dst_pts):
def normalize_points(pts):
pts_homogeneous = np.hstack((pts, np.ones((pts.shape[0], 1))))
centroid = np.mean(pts, axis=0)
scale = np.sqrt(2) / np.mean(np.linalg.norm(pts - centroid, axis=1))
T = np.array([[scale, 0, -scale * centroid[0]], [0, scale, -scale * centroid[1]], [0, 0, 1]])
normalized_pts = (T @ pts_homogeneous.T).T
return normalized_pts[:, :2], T
src_pts_normalized, T1 = normalize_points(src_pts)
dst_pts_normalized, T2 = normalize_points(dst_pts)
A = []
for p1, p2 in zip(src_pts_normalized, dst_pts_normalized):
x1, y1 = p1
x2, y2 = p2
A.append([0, 0, 0, -x1, -y1, -1, y2 * x1, y2 * y1, y2])
A.append([x1, y1, 1, 0, 0, 0, -x2 * x1, -x2 * y1, -x2])
A = np.array(A)
try:
_, _, VT = np.linalg.svd(A)
except np.linalg.LinAlgError:
return None
h = VT[-1]
H_normalized = h.reshape(3, 3)
H = np.linalg.inv(T2) @ H_normalized @ T1
if np.abs(H[-1, -1]) > 1e-6:
H = H / H[-1, -1]
else:
return None
return H
def filter_matches(matches, ratio_thres=0.7):
filtered_matches = []
for match in matches:
good_match = []
for m, n in match:
if m.distance < ratio_thres * n.distance:
good_match.append(m)
filtered_matches.append(good_match)
return filtered_matches
def find_homography(keypoints, filtered_matches):
homographies = []
skipped_indices = [] # Keep track of skipped images and their indices
for i, matches in enumerate(filtered_matches):
src_pts = np.float32([keypoints[0][m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints[i + 1][m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
H = ransac_homography(src_pts, dst_pts)
if H is not None:
H = H.astype(np.float32)
homographies.append(H)
else:
print(f"Warning: Homography computation failed for image pair (0, {i + 1}). Skipping.")
skipped_indices.append(i + 1) # Add indices of skipped images to the list
continue
return homographies, skipped_indices
def ransac_homography(src_pts, dst_pts, iterations=2000, threshold=3):
best_inlier_count = 0
best_homography = None
if len(src_pts) != len(dst_pts) or len(src_pts) < 4:
raise ValueError("The number of source and destination points must be equal and at least 4.")
src_pts = np.array(src_pts)
dst_pts = np.array(dst_pts)
for _ in range(iterations):
indices = np.random.choice(len(src_pts), 4, replace=False)
src_subset = src_pts[indices].reshape(-1, 2)
dst_subset = dst_pts[indices].reshape(-1, 2)
homography = compute_homography_matrix(src_subset, dst_subset)
if homography is None:
continue
inliers = 0
for i in range(len(src_pts)):
projected_point = np.dot(homography, np.append(src_pts[i], 1))
if np.abs(projected_point[-1]) > 1e-6:
projected_point = projected_point / projected_point[-1]
else:
continue
distance = np.linalg.norm(projected_point[:2] - dst_pts[i])
if distance < threshold:
inliers += 1
if inliers > best_inlier_count:
best_inlier_count = inliers
best_homography = homography
if best_homography is None:
raise RuntimeError("Failed to find a valid homography matrix.")
return best_homography
def read_ground_truth_homographies(dataset_path):
H_files = sorted(glob.glob(os.path.join(dataset_path, "H_*")))
ground_truth_homographies = []
for filename in H_files:
H = np.loadtxt(filename)
ground_truth_homographies.append(H)
return ground_truth_homographies
def warp_perspective(img, H, reverse=False):
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
test = np.array([[0, w, w, 0],
[0, 0, h, h],
[1, 1, 1, 1]])
test_c = np.dot(H, test)
test_w = test_c[0]/test_c[2]
test_h = test_c[1]/test_c[2]
print("Test W: ", test_w)
print("Test H: ", test_h)
max_y, min_y = test_w.max(), test_w.min()
max_x, min_x = test_h.max(), test_h.min()
print("x: ", max_x, min_x, " = ", max_x - min_x)
print("y: ", max_y, min_y, " = ", max_y - min_y)
w, h = int(max_y + np.abs(min_y)), int(max_x + np.abs(min_x))
target_y, target_x = np.meshgrid(np.arange(min_x, h), np.arange(min_y, w))
target_coordinates = np.stack([target_x.ravel(), target_y.ravel(), np.ones(target_x.size)])
source_coordinates = np.dot(np.linalg.inv(H), target_coordinates)
source_coordinates /= source_coordinates[2, :]
valid = np.logical_and(np.logical_and(0 <= source_coordinates[0, :], source_coordinates[0, :] < img.shape[1]),
np.logical_and(0 <= source_coordinates[1, :], source_coordinates[1, :] < img.shape[0]))
valid_source_coordinates = source_coordinates[:, valid].astype(int)
valid_target_coordinates = target_coordinates[:, valid].astype(int)
valid_source_coordinates[0] = np.clip(valid_source_coordinates[0], -100000, img.shape[1] - 1)
valid_source_coordinates[1] = np.clip(valid_source_coordinates[1], -100000, img.shape[0] - 1)
valid_target_coordinates[0] += int(abs(min_y))
valid_target_coordinates[1] += int(abs(min_x))
valid_target_coordinates[0] = np.clip(valid_target_coordinates[0], -100000, w - 1)
valid_target_coordinates[1] = np.clip(valid_target_coordinates[1], -100000, h - 1)
warped_image = np.zeros((h, w, 3), dtype=np.uint8)
for i in range(3):
warped_image[:,:, i][valid_target_coordinates[1], valid_target_coordinates[0]] = img[:,:, i][valid_source_coordinates[1], valid_source_coordinates[0]]
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image
def image_merging(images, homographies):
if len(images) - 1 != len(homographies):
raise ValueError("The number of homography matrices must be one less than the number of images.")
# Warp all images except the first one using their corresponding homography matrices
warped_images = [images[0]] + [warp_perspective(img, H, True) for img, H in zip(images[1:], homographies)]
# Compute the size of the merged image
min_x, min_y, max_x, max_y = 0, 0, 0, 0
for img in warped_images:
h, w = img.shape[:2]
corners = np.array([[0, 0, 1], [h, 0, 1], [0, w, 1], [h, w, 1]])
min_x = min(min_x, corners[:, 1].min())
min_y = min(min_y, corners[:, 0].min())
max_x = max(max_x, corners[:, 1].max())
max_y = max(max_y, corners[:, 0].max())
merged_height = int(np.ceil(max_y - min_y))
merged_width = int(np.ceil(max_x - min_x))
# Initialize the merged image with zeros
merged_image = np.zeros((merged_height, merged_width, 3), dtype=np.uint8)
print("Merged Shape: ", merged_image.shape)
# Merge the warped images by overlaying them on the merged image
for img in warped_images:
mask = np.all(img == 0, axis=-1)
y_offset, x_offset = max(0, -min_y), max(0, -min_x)
merged_image_slice = merged_image[y_offset:y_offset + img.shape[0], x_offset:x_offset + img.shape[1]]
merged_image_slice[~mask] = img[~mask]
print("Merged Shape 2: ", merged_image.shape)
return merged_image"
|
e3b03d7f1b550ca72ac8b8596d937a17
|
{
"intermediate": 0.4580773115158081,
"beginner": 0.3193860352039337,
"expert": 0.22253665328025818
}
|
2,778
|
In order to see negative regions of my warped image I shifted them by min_x and min_y values. Now I can see negative regions however my image merging code was taking warped images and adding them on top of each other. Since the region of interest was almost at the top most part of the image it was aligning perfectly. However in order to see negative regions and rest of the data, we also shifted the region of interest. So my image merging code, when it adds images on top of one another as they are, now they do not align. I need a solution which will account for the warped images shift and when constructing panorama, aligns them on top of one another. We can calculate where the region of interest simply by looking at the min_x and min_y value as they are used for shifting. However another side note is the panorama image at the end result should also show the negative regions. I will give you my full code, so look in to a solution please: "import numpy as np
import cv2
import os
import glob
import matplotlib.pyplot as plt
import time
from kayla_tools import *
def compute_homography_matrix(src_pts, dst_pts):
def normalize_points(pts):
pts_homogeneous = np.hstack((pts, np.ones((pts.shape[0], 1))))
centroid = np.mean(pts, axis=0)
scale = np.sqrt(2) / np.mean(np.linalg.norm(pts - centroid, axis=1))
T = np.array([[scale, 0, -scale * centroid[0]], [0, scale, -scale * centroid[1]], [0, 0, 1]])
normalized_pts = (T @ pts_homogeneous.T).T
return normalized_pts[:, :2], T
src_pts_normalized, T1 = normalize_points(src_pts)
dst_pts_normalized, T2 = normalize_points(dst_pts)
A = []
for p1, p2 in zip(src_pts_normalized, dst_pts_normalized):
x1, y1 = p1
x2, y2 = p2
A.append([0, 0, 0, -x1, -y1, -1, y2 * x1, y2 * y1, y2])
A.append([x1, y1, 1, 0, 0, 0, -x2 * x1, -x2 * y1, -x2])
A = np.array(A)
try:
_, _, VT = np.linalg.svd(A)
except np.linalg.LinAlgError:
return None
h = VT[-1]
H_normalized = h.reshape(3, 3)
H = np.linalg.inv(T2) @ H_normalized @ T1
if np.abs(H[-1, -1]) > 1e-6:
H = H / H[-1, -1]
else:
return None
return H
def filter_matches(matches, ratio_thres=0.7):
filtered_matches = []
for match in matches:
good_match = []
for m, n in match:
if m.distance < ratio_thres * n.distance:
good_match.append(m)
filtered_matches.append(good_match)
return filtered_matches
def find_homography(keypoints, filtered_matches):
homographies = []
skipped_indices = [] # Keep track of skipped images and their indices
for i, matches in enumerate(filtered_matches):
src_pts = np.float32([keypoints[0][m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints[i + 1][m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
H = ransac_homography(src_pts, dst_pts)
if H is not None:
H = H.astype(np.float32)
homographies.append(H)
else:
print(f"Warning: Homography computation failed for image pair (0, {i + 1}). Skipping.")
skipped_indices.append(i + 1) # Add indices of skipped images to the list
continue
return homographies, skipped_indices
def ransac_homography(src_pts, dst_pts, iterations=2000, threshold=3):
best_inlier_count = 0
best_homography = None
if len(src_pts) != len(dst_pts) or len(src_pts) < 4:
raise ValueError("The number of source and destination points must be equal and at least 4.")
src_pts = np.array(src_pts)
dst_pts = np.array(dst_pts)
for _ in range(iterations):
indices = np.random.choice(len(src_pts), 4, replace=False)
src_subset = src_pts[indices].reshape(-1, 2)
dst_subset = dst_pts[indices].reshape(-1, 2)
homography = compute_homography_matrix(src_subset, dst_subset)
if homography is None:
continue
inliers = 0
for i in range(len(src_pts)):
projected_point = np.dot(homography, np.append(src_pts[i], 1))
if np.abs(projected_point[-1]) > 1e-6:
projected_point = projected_point / projected_point[-1]
else:
continue
distance = np.linalg.norm(projected_point[:2] - dst_pts[i])
if distance < threshold:
inliers += 1
if inliers > best_inlier_count:
best_inlier_count = inliers
best_homography = homography
if best_homography is None:
raise RuntimeError("Failed to find a valid homography matrix.")
return best_homography
def read_ground_truth_homographies(dataset_path):
H_files = sorted(glob.glob(os.path.join(dataset_path, "H_*")))
ground_truth_homographies = []
for filename in H_files:
H = np.loadtxt(filename)
ground_truth_homographies.append(H)
return ground_truth_homographies
def warp_perspective(img, H, reverse=False):
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
test = np.array([[0, w, w, 0],
[0, 0, h, h],
[1, 1, 1, 1]])
test_c = np.dot(H, test)
test_w = test_c[0]/test_c[2]
test_h = test_c[1]/test_c[2]
print("Test W: ", test_w)
print("Test H: ", test_h)
max_y, min_y = test_w.max(), test_w.min()
max_x, min_x = test_h.max(), test_h.min()
print("x: ", max_x, min_x, " = ", max_x - min_x)
print("y: ", max_y, min_y, " = ", max_y - min_y)
w, h = int(max_y + np.abs(min_y)), int(max_x + np.abs(min_x))
target_y, target_x = np.meshgrid(np.arange(min_x, h), np.arange(min_y, w))
target_coordinates = np.stack([target_x.ravel(), target_y.ravel(), np.ones(target_x.size)])
source_coordinates = np.dot(np.linalg.inv(H), target_coordinates)
source_coordinates /= source_coordinates[2, :]
valid = np.logical_and(np.logical_and(0 <= source_coordinates[0, :], source_coordinates[0, :] < img.shape[1]),
np.logical_and(0 <= source_coordinates[1, :], source_coordinates[1, :] < img.shape[0]))
valid_source_coordinates = source_coordinates[:, valid].astype(int)
valid_target_coordinates = target_coordinates[:, valid].astype(int)
valid_source_coordinates[0] = np.clip(valid_source_coordinates[0], -100000, img.shape[1] - 1)
valid_source_coordinates[1] = np.clip(valid_source_coordinates[1], -100000, img.shape[0] - 1)
valid_target_coordinates[0] += int(abs(min_y))
valid_target_coordinates[1] += int(abs(min_x))
valid_target_coordinates[0] = np.clip(valid_target_coordinates[0], -100000, w - 1)
valid_target_coordinates[1] = np.clip(valid_target_coordinates[1], -100000, h - 1)
warped_image = np.zeros((h, w, 3), dtype=np.uint8)
for i in range(3):
warped_image[:,:, i][valid_target_coordinates[1], valid_target_coordinates[0]] = img[:,:, i][valid_source_coordinates[1], valid_source_coordinates[0]]
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image
def image_merging(images, homographies):
if len(images) - 1 != len(homographies):
raise ValueError("The number of homography matrices must be one less than the number of images.")
# Warp all images except the first one using their corresponding homography matrices
warped_images = [images[0]] + [warp_perspective(img, H, True) for img, H in zip(images[1:], homographies)]
# Compute the size of the merged image
min_x, min_y, max_x, max_y = 0, 0, 0, 0
for img in warped_images:
h, w = img.shape[:2]
corners = np.array([[0, 0, 1], [h, 0, 1], [0, w, 1], [h, w, 1]])
min_x = min(min_x, corners[:, 1].min())
min_y = min(min_y, corners[:, 0].min())
max_x = max(max_x, corners[:, 1].max())
max_y = max(max_y, corners[:, 0].max())
merged_height = int(np.ceil(max_y - min_y))
merged_width = int(np.ceil(max_x - min_x))
# Initialize the merged image with zeros
merged_image = np.zeros((merged_height, merged_width, 3), dtype=np.uint8)
print("Merged Shape: ", merged_image.shape)
# Merge the warped images by overlaying them on the merged image
for img in warped_images:
mask = np.all(img == 0, axis=-1)
y_offset, x_offset = max(0, -min_y), max(0, -min_x)
merged_image_slice = merged_image[y_offset:y_offset + img.shape[0], x_offset:x_offset + img.shape[1]]
merged_image_slice[~mask] = img[~mask]
print("Merged Shape 2: ", merged_image.shape)
return merged_image"
|
b897b0063def4b664b599d9dd0575ad2
|
{
"intermediate": 0.4580773115158081,
"beginner": 0.3193860352039337,
"expert": 0.22253665328025818
}
|
2,779
|
Please provide instructions on how to make games using python
|
3628ba0bc95b8786c3974e1a25308968
|
{
"intermediate": 0.3002775013446808,
"beginner": 0.4200136661529541,
"expert": 0.27970877289772034
}
|
2,780
|
In order to see negative regions of my warped image I shifted them by min_x and min_y values. Now I can see negative regions however my image merging code was taking warped images and adding them on top of each other. Since the region of interest was almost at the top most part of the image it was aligning perfectly. However in order to see negative regions and rest of the data, we also shifted the region of interest. So my image merging code, when it adds images on top of one another as they are, now they do not align. I need a solution which will account for the warped images shift and when constructing panorama, aligns them on top of one another. We can calculate where the region of interest simply by looking at the min_x and min_y value as they are used for shifting. However another side note is the panorama image at the end result should also show the negative regions. I will give you my full code, so look in to a solution please: "import numpy as np
import cv2
import os
import glob
import matplotlib.pyplot as plt
import time
from kayla_tools import *
def compute_homography_matrix(src_pts, dst_pts):
def normalize_points(pts):
pts_homogeneous = np.hstack((pts, np.ones((pts.shape[0], 1))))
centroid = np.mean(pts, axis=0)
scale = np.sqrt(2) / np.mean(np.linalg.norm(pts - centroid, axis=1))
T = np.array([[scale, 0, -scale * centroid[0]], [0, scale, -scale * centroid[1]], [0, 0, 1]])
normalized_pts = (T @ pts_homogeneous.T).T
return normalized_pts[:, :2], T
src_pts_normalized, T1 = normalize_points(src_pts)
dst_pts_normalized, T2 = normalize_points(dst_pts)
A = []
for p1, p2 in zip(src_pts_normalized, dst_pts_normalized):
x1, y1 = p1
x2, y2 = p2
A.append([0, 0, 0, -x1, -y1, -1, y2 * x1, y2 * y1, y2])
A.append([x1, y1, 1, 0, 0, 0, -x2 * x1, -x2 * y1, -x2])
A = np.array(A)
try:
_, _, VT = np.linalg.svd(A)
except np.linalg.LinAlgError:
return None
h = VT[-1]
H_normalized = h.reshape(3, 3)
H = np.linalg.inv(T2) @ H_normalized @ T1
if np.abs(H[-1, -1]) > 1e-6:
H = H / H[-1, -1]
else:
return None
return H
def filter_matches(matches, ratio_thres=0.7):
filtered_matches = []
for match in matches:
good_match = []
for m, n in match:
if m.distance < ratio_thres * n.distance:
good_match.append(m)
filtered_matches.append(good_match)
return filtered_matches
def find_homography(keypoints, filtered_matches):
homographies = []
skipped_indices = [] # Keep track of skipped images and their indices
for i, matches in enumerate(filtered_matches):
src_pts = np.float32([keypoints[0][m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints[i + 1][m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
H = ransac_homography(src_pts, dst_pts)
if H is not None:
H = H.astype(np.float32)
homographies.append(H)
else:
print(f"Warning: Homography computation failed for image pair (0, {i + 1}). Skipping.")
skipped_indices.append(i + 1) # Add indices of skipped images to the list
continue
return homographies, skipped_indices
def ransac_homography(src_pts, dst_pts, iterations=2000, threshold=3):
best_inlier_count = 0
best_homography = None
if len(src_pts) != len(dst_pts) or len(src_pts) < 4:
raise ValueError("The number of source and destination points must be equal and at least 4.")
src_pts = np.array(src_pts)
dst_pts = np.array(dst_pts)
for _ in range(iterations):
indices = np.random.choice(len(src_pts), 4, replace=False)
src_subset = src_pts[indices].reshape(-1, 2)
dst_subset = dst_pts[indices].reshape(-1, 2)
homography = compute_homography_matrix(src_subset, dst_subset)
if homography is None:
continue
inliers = 0
for i in range(len(src_pts)):
projected_point = np.dot(homography, np.append(src_pts[i], 1))
if np.abs(projected_point[-1]) > 1e-6:
projected_point = projected_point / projected_point[-1]
else:
continue
distance = np.linalg.norm(projected_point[:2] - dst_pts[i])
if distance < threshold:
inliers += 1
if inliers > best_inlier_count:
best_inlier_count = inliers
best_homography = homography
if best_homography is None:
raise RuntimeError("Failed to find a valid homography matrix.")
return best_homography
def read_ground_truth_homographies(dataset_path):
H_files = sorted(glob.glob(os.path.join(dataset_path, "H_*")))
ground_truth_homographies = []
for filename in H_files:
H = np.loadtxt(filename)
ground_truth_homographies.append(H)
return ground_truth_homographies
def warp_perspective(img, H, reverse=False):
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
test = np.array([[0, w, w, 0],
[0, 0, h, h],
[1, 1, 1, 1]])
test_c = np.dot(H, test)
test_w = test_c[0]/test_c[2]
test_h = test_c[1]/test_c[2]
print("Test W: ", test_w)
print("Test H: ", test_h)
max_y, min_y = test_w.max(), test_w.min()
max_x, min_x = test_h.max(), test_h.min()
print("x: ", max_x, min_x, " = ", max_x - min_x)
print("y: ", max_y, min_y, " = ", max_y - min_y)
w, h = int(max_y + np.abs(min_y)), int(max_x + np.abs(min_x))
target_y, target_x = np.meshgrid(np.arange(min_x, h), np.arange(min_y, w))
target_coordinates = np.stack([target_x.ravel(), target_y.ravel(), np.ones(target_x.size)])
source_coordinates = np.dot(np.linalg.inv(H), target_coordinates)
source_coordinates /= source_coordinates[2, :]
valid = np.logical_and(np.logical_and(0 <= source_coordinates[0, :], source_coordinates[0, :] < img.shape[1]),
np.logical_and(0 <= source_coordinates[1, :], source_coordinates[1, :] < img.shape[0]))
valid_source_coordinates = source_coordinates[:, valid].astype(int)
valid_target_coordinates = target_coordinates[:, valid].astype(int)
valid_source_coordinates[0] = np.clip(valid_source_coordinates[0], -100000, img.shape[1] - 1)
valid_source_coordinates[1] = np.clip(valid_source_coordinates[1], -100000, img.shape[0] - 1)
valid_target_coordinates[0] += int(abs(min_y))
valid_target_coordinates[1] += int(abs(min_x))
valid_target_coordinates[0] = np.clip(valid_target_coordinates[0], -100000, w - 1)
valid_target_coordinates[1] = np.clip(valid_target_coordinates[1], -100000, h - 1)
warped_image = np.zeros((h, w, 3), dtype=np.uint8)
for i in range(3):
warped_image[:,:, i][valid_target_coordinates[1], valid_target_coordinates[0]] = img[:,:, i][valid_source_coordinates[1], valid_source_coordinates[0]]
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image
def image_merging(images, homographies):
if len(images) - 1 != len(homographies):
raise ValueError("The number of homography matrices must be one less than the number of images.")
# Warp all images except the first one using their corresponding homography matrices
warped_images = [images[0]] + [warp_perspective(img, H, True) for img, H in zip(images[1:], homographies)]
# Compute the size of the merged image
min_x, min_y, max_x, max_y = 0, 0, 0, 0
for img in warped_images:
h, w = img.shape[:2]
corners = np.array([[0, 0, 1], [h, 0, 1], [0, w, 1], [h, w, 1]])
min_x = min(min_x, corners[:, 1].min())
min_y = min(min_y, corners[:, 0].min())
max_x = max(max_x, corners[:, 1].max())
max_y = max(max_y, corners[:, 0].max())
merged_height = int(np.ceil(max_y - min_y))
merged_width = int(np.ceil(max_x - min_x))
# Initialize the merged image with zeros
merged_image = np.zeros((merged_height, merged_width, 3), dtype=np.uint8)
print("Merged Shape: ", merged_image.shape)
# Merge the warped images by overlaying them on the merged image
for img in warped_images:
mask = np.all(img == 0, axis=-1)
y_offset, x_offset = max(0, -min_y), max(0, -min_x)
merged_image_slice = merged_image[y_offset:y_offset + img.shape[0], x_offset:x_offset + img.shape[1]]
merged_image_slice[~mask] = img[~mask]
print("Merged Shape 2: ", merged_image.shape)
return merged_image"
|
84117c5fe80aaf3b2f4a3fdaef5ac536
|
{
"intermediate": 0.4580773115158081,
"beginner": 0.3193860352039337,
"expert": 0.22253665328025818
}
|
2,781
|
change the following matlab code that simulate traffic flow using IDM to use the gipps model with the following ODE defention █(&v_n (t+τ)=min{v_n (t)+2.5a_n τ(1-v_n (t)/V_n ) (0.025+v_n (t)/V_n )^(1/2),┤@&├ b_n τ+√(b_n^2 τ^2-b_n [2[x_(n-1) (t)-s_(n-1)-x_n (t)]-v_n (t)τ-v_(n-1) (t)^2/b ̂ ] )}@&) :
% Define simulation parameters
dt = 0.01; % Time interval
T = 30; % Total simulation time
time = 0:dt:T; % Time vector
% Define initial conditions
N_cars = 10; % Number of cars
v0 = 120 / 3.6; % Desired speed in m/s
s0 = 2; % Minimum gap between cars in m
T = 1.5; % Safe time headway
a = 0.3; % Maximum acceleration in m/s^2
b = 2; % Comfortable braking deceleration in m/s^2
L = [4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5]; % Car length vector
W = [2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2]; % Car width vector
x = cumsum([0, 10*ones(1,N_cars-1)]); % Car positions
v = v0*ones(1,N_cars); % Car speeds
acc = zeros(1,N_cars); % Car accelerations
dist = zeros(1,N_cars); % Car distances
colors=hsv(N_cars)
% Run simulation
for i = 2:length(time)
% Update positions
x = x + v*dt + 0.5*acc*dt^2;
% Update speeds
for j = 1:N_cars
% Calculate distance to lead car
if j < N_cars
dist(j) = x(j+1) - x(j) - L(j) - L(j+1);
else
dist(j) = 1e10; % Assume no car ahead of last car
end
% Calculate IDM acceleration
acc(j) = IDM(acc(j), dist(j), v(j), v0, s0, T, a, b);
end
v = v + acc*dt;
% Animate results
clf;
hold on;
for j = 1:N_cars
rectangle('Position',[x(j)-L(j)/2,(j-1)*2,L(j),2],'FaceColor',colors(j,:),'Curvature',j/N_cars);
end
xlim([0, max(x)+50]);
ylim([0, sum(W)]);
xlabel('Distance (m)');
ylabel('Lane width (m)');
title(sprintf('Time = %0.1f s', time(i)));
drawnow;
end
% Define IDM function
function acc = IDM(acc, dist, v, v0, s0, T, a, b)
acc = a*(1 - (v/v0)^4 - (s0 + v*T - sqrt((s0 + v*T)^2 - 4*v*(v-dist)/(2*b)))/dist^2);
acc = max(acc, -b); % Limit braking acceleration
end
|
98be2cd50d75820c51c11c5988469354
|
{
"intermediate": 0.16605404019355774,
"beginner": 0.5311052203178406,
"expert": 0.3028407692909241
}
|
2,782
|
I am using unity 2021.3.23f1 so can you update my code below i am wanting it to make a smooth procedural terrain with hills that my 2d sidescroll car could easily drive over without any issues also the code below asks me for a SpriteShapeController could you have it where it automatically deals with that so i don't need to manually add it
using UnityEngine;
using UnityEngine.U2D;
public class TerrainCreator : MonoBehaviour
{
public SpriteShapeController shape;
public int scale = 5000;
public int numofPoints = 100;
private void Start()
{
float distanceBwtnpoints = (float)scale / (float)numofPoints;
shape = GetComponent<SpriteShapeController>();
shape.spline.SetPosition(2, shape.spline.GetPosition(2) + Vector3.right * scale);
shape.spline.SetPosition(3, shape.spline.GetPosition(3) + Vector3.right * scale);
for (int i = 0; i < 150; i++)
{
float xPos = shape.spline.GetPosition(i + 1).x + distanceBwtnpoints;
shape.spline.InsertPointAt(i + 2, new Vector3(xPos, Mathf.PerlinNoise(i * Random.Range(5.0f, 8.0f), 0)));
}
for (int i = 2; i < 152; i++)
{
shape.spline.SetTangentMode(i, ShapeTangentMode.Continuous);
shape.spline.SetLeftTangent(i, new Vector3(-2, 0, 0));
shape.spline.SetRightTangent(i, new Vector3(2, 0, 0));
}
}
}
|
87a5636591b550ade6fca4cc9f7c3fc0
|
{
"intermediate": 0.5908427834510803,
"beginner": 0.27670085430145264,
"expert": 0.13245633244514465
}
|
2,783
|
Please provide detailed pygame code for a 4X strategy game
|
b9bffb01d33961d5f4f2b60dec4d231a
|
{
"intermediate": 0.3209875524044037,
"beginner": 0.3634241223335266,
"expert": 0.3155883252620697
}
|
2,784
|
another python file how could I an an input which would be the martketHashName and it would then find the item in the csv and print the other details
|
ba99c6555206ad338a40dbb8827cd911
|
{
"intermediate": 0.4434390962123871,
"beginner": 0.17423583567142487,
"expert": 0.38232508301734924
}
|
2,785
|
can you fix the follwing error that uses the gipps model to model traffic flow it give the following error : Array indices must be positive integers or logical values.
Error in Gipps_Car_following_model (line 38)
v_lead = (j > 1) * v(j-1); % Only consider lead car if it exists
% Define simulation parameters
dt = 0.01; % Time interval
T = 30; % Total simulation time
time = 0:dt:T; % Time vector
% Define initial conditions
N_cars = 10; % Number of cars
v0 = 120 / 3.6; % Desired speed in m/s
s0 = 2; % Minimum gap between cars in m
T = 1.5; % Safe time headway
a_max = 0.3; % Maximum acceleration in m/s^2
b_max = 2; % Comfortable braking deceleration in m/s^2
L = [4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5]; % Car length vector
W = [2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2]; % Car width vector
x = cumsum([0, 10*ones(1,N_cars-1)]); % Car positions
v = v0*ones(1,N_cars); % Car speeds
acc = zeros(1,N_cars); % Car accelerations
dist = zeros(1,N_cars); % Car distances
colors=hsv(N_cars);
% Run simulation
for i = 2:length(time)
% Update positions
x = x + v*dt + 0.5*acc*dt^2;
% Update speeds and accelerations
for j = 1:N_cars
% Calculate distance to lead car
if j < N_cars
dist(j) = x(j+1) - x(j) - L(j) - L(j+1);
else
dist(j) = 1e10; % Assume no car ahead of last car
end
% Calculate acceleration based on the Gipps model
s_desired = s0 + T*v(j);
v_lead = (j > 1) * v(j-1); % Only consider lead car if it exists
d = dist(j) - L(j) - L(j+1);
a_desired = a_max * (1 - (v(j)/v0)^4 - ((s_desired - d)/v(j))^2);
a_safety = b_max * ((v_lead/v(j))^2 - 1) * (1 - s_desired/d) / sqrt(a_maxb_max);
acc(j) = min(a_desired, a_safety);
end
% Update speeds
v = v + acc*dt;
% Animate results
clf;
hold on;
for j = 1:N_cars
rectangle('Position',[x(j)-L(j)/2,(j-1)*2,L(j),2],'FaceColor',colors(j,:),'Curvature',j/N_cars);
end
xlim([0, max(x)+50]);
ylim([0, sum(W)]);
xlabel('Distance (m)');
ylabel('Lane width (m)');
title(sprintf('Time = %0.1f s', time(i)));
drawnow;
end
|
0f6c2b7f598321681b07ab357a3e0c87
|
{
"intermediate": 0.2501664161682129,
"beginner": 0.6508734822273254,
"expert": 0.09896012395620346
}
|
2,786
|
the following code gives the following error Error using rectangle
Value must be numeric and finite
rectangle('Position',[x(j)-L(j)/2,(j-1)*2,L(j),2],'FaceColor',colors(j,:),'Curvature',j/N_cars);
% Define simulation parameters
dt = 0.01; % Time interval
T = 30; % Total simulation time
time = 0:dt:T; % Time vector
% Define initial conditions
N_cars = 10; % Number of cars
v0 = 120 / 3.6; % Desired speed in m/s
s0 = 2; % Minimum gap between cars in m
T = 1.5; % Safe time headway
a_max = 0.3; % Maximum acceleration in m/s^2
b_max = 2; % Comfortable braking deceleration in m/s^2
L = [4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5]; % Car length vector
W = [2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2]; % Car width vector
x = cumsum([0, 10*ones(1,N_cars-1)]); % Car positions
v = v0*ones(1,N_cars); % Car speeds
acc = zeros(1,N_cars); % Car accelerations
dist = zeros(1,N_cars); % Car distances
colors=hsv(N_cars);
% Run simulation
for i = 2:length(time)
% Update positions
x = x + v*dt + 0.5*acc*dt^2;
% Update speeds and accelerations
for j = 1:N_cars
% Calculate distance to lead car
if j < N_cars
dist(j) = x(j+1) - x(j) - L(j) - L(j+1);
else
dist(j) = 1e10; % Assume no car ahead of last car
end
% Calculate acceleration based on the Gipps model
s_desired = s0 + T*v(j);
if j > 1
v_lead = v(j-1);
else
v_lead = 0; % Set speed to zero if no lead car exists
end
% Only consider lead car if it exists
if j < N_cars
d = dist(j) - L(j) - L(j+1);
else
d = dist(j) - L(j);
end
a_desired = a_max * (1 - (v(j)/v0)^4 - ((s_desired - d)/v(j))^2);
a_safety = b_max * ((v_lead/v(j))^2 - 1) * (1 - s_desired/d) / sqrt(a_max*b_max);
acc(j) = min(a_desired, a_safety);
end
% Update speeds
v = v + acc*dt;
% Animate results
clf;
hold on;
for j = 1:N_cars
rectangle('Position',[x(j)-L(j)/2,(j-1)*2,L(j),2],'FaceColor',colors(j,:),'Curvature',j/N_cars);
end
xlim([0, max(x)+50]);
ylim([0, sum(W)]);
xlabel('Distance (m)');
ylabel('Lane width (m)');
title(sprintf('Time = %0.1f s', time(i)));
drawnow;
end
|
4ba6d4da3d3c2ce8cea6bb4cb5f64793
|
{
"intermediate": 0.39907902479171753,
"beginner": 0.3034742772579193,
"expert": 0.29744669795036316
}
|
2,787
|
write a simple book keeping for a self employed in switzerland i want javascript slider for income and expenses
|
0fb29fd4259b5f0e786437ee8a9fde31
|
{
"intermediate": 0.6107572913169861,
"beginner": 0.19513535499572754,
"expert": 0.194107323884964
}
|
2,788
|
write a simple book keeping for a self employed in switzerland i want javascript slider for income and expenses
|
b58e157061449cc20f96b1b760a272ac
|
{
"intermediate": 0.6107572913169861,
"beginner": 0.19513535499572754,
"expert": 0.194107323884964
}
|
2,789
|
how to use odoo on a docker, short instructions
|
c39568b5cb6a0228efe1cbbcc071ac44
|
{
"intermediate": 0.6275905966758728,
"beginner": 0.17193371057510376,
"expert": 0.20047569274902344
}
|
2,790
|
generate the python code for calculating the annual dividend, use yfinance for data source
|
60a550f52bd0c26a64568c0cebbec540
|
{
"intermediate": 0.571128249168396,
"beginner": 0.1680271476507187,
"expert": 0.2608445882797241
}
|
2,791
|
',StudentName,E1\n0,student1,92\n1,student2,74\n2,student3,83\n3,student4,100\n4,student5,77\n5,student6,100\n6,student7,66\n7,student8,97\n8,student9,95\n9,student10,78'
I'm getting the above output
now I need you to modify the _get_rows function to get the following output
expected_output = """,StudentName,E1
0,student1,92
1,student2,74
2,student3,83
3,student4,100
4,student5,77
5,student6,100
6,student7,66
7,student8,97
8,student9,95
9,student10,78"""
Here is my full code
or col, values in data.items():
if col not in self.columns:
self.columns.append(col)
self.data[col].lst = values
elif isinstance(data, list):
if not columns:
raise ValueError("Columns must be provided when data is a list")
for row in data:
for col_name, value in zip(self.columns, row):
self.data[col_name].append(value)
else:
raise ValueError("Invalid data type. Must be either list or dict.")
self.index = {}
def set_index(self, index: str):
if index in self.data.keys():
col = self.data.pop(index)
self.index = {name: idx for idx, name in enumerate(col)}
def __setitem__(self, col_name: str, values: List[Any]):
if col_name not in self.columns:
self.columns.append(col_name)
self.data[col_name] = ListV2([])
self.data[col_name] = values
def __getitem__(self, col_name: Any) -> List[Any]:
if isinstance(col_name, list):
return self._get_rows(col_name)
else:
return self.data[col_name]
def _get_rows(self, col_names: List[str]) -> str:
cols = [("",) + tuple(col_names)]
for idx, row in enumerate(zip(*(self.__getitem__(name) for name in col_names))):
cols.append((idx,) + row)
z = "\n".join([",".join(map(str, row)) for row in cols])
return z
def loc(self, row_name: str) -> Dict[str, Any]:
idx = self.index[row_name]
return {col: self.data[col][idx] for col in self.columns}
def iteritems(self):
return self.data.items()
def iterrows(self):
for name, idx in self.index.items():
row = self.loc(idx)
yield name, row
def astype(self, dtype: type, col_name: Optional[str] = None):
if col_name:
self.data[col_name] = ListV2([dtype(x) for x in self.data[col_name]])
else:
for col in self.columns:
self.data[col] = ListV2([dtype(x) for x in self.data[col]])
def drop(self, col_name: str):
if col_name in self.columns:
self.columns.remove(col_name)
self.data.pop(col_name)
def mean(self) -> Dict[str, float]:
result = {}
for col in self.columns:
total = sum(self.data[col])
mean = total / len(self.data[col])
result[col] = mean
return result
def __repr__(self):
table = [("",) + self.columns]
for idx, row in enumerate(zip(*self.data.values())):
table.append([idx] + list(row))
return "\n".join([",".join([str(el) for el in row]) for row in table])
fix this
|
580ca02f343c06c2520fa8fed9919daf
|
{
"intermediate": 0.3246647119522095,
"beginner": 0.42974361777305603,
"expert": 0.24559162557125092
}
|
2,792
|
Histograms of probability compare code in Python
|
c00a4042ef6cd8be6363ce555f97dbc4
|
{
"intermediate": 0.25234484672546387,
"beginner": 0.3003956973552704,
"expert": 0.44725948572158813
}
|
2,793
|
this code fails to simulate traffic flow using the gipps model with the following equation █(&v_n (t+τ)=min{v_n (t)+2.5a_n τ(1-v_n (t)/V_n ) (0.025+v_n (t)/V_n )^(1/2),┤@&├ b_n τ+√(b_n^2 τ^2-b_n [2[x_(n-1) (t)-s_(n-1)-x_n (t)]-v_n (t)τ-v_(n-1) (t)^2/b ̂ ] )}@&) the problem is logical in the sense that the position x seems to explode to -inf can you please try to fix it by either changing the inital conditions or checking the equations for updating position
% Define simulation parameters
dt = 0.01; % Time interval
T = 30; % Total simulation time
time = 0:dt:T; % Time vector
% Define initial conditions
N_cars = 10; % Number of cars
v0 = 120 / 3.6; % Desired speed in m/s
s0 = 2; % Minimum gap between cars in m
T = 1.5; % Safe time headway
a_max = 0.3; % Maximum acceleration in m/s^2
b_max = 2; % Comfortable braking deceleration in m/s^2
L = [4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5, 4.5, 5]; % Car length vector
W = [2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2, 2, 2.2]; % Car width vector
x = cumsum([0, 10*ones(1,N_cars-1)]); % Car positions
v = v0*ones(1,N_cars); % Car speeds
acc = zeros(1,N_cars); % Car accelerations
dist = zeros(1,N_cars); % Car distances
colors=hsv(N_cars);
% Run simulation
for i = 2:length(time)
% Store previous positions for plotting
x_prev = x;
% Update positions
x = x + v*dt + 0.5*acc*dt^2;
% Update speeds and accelerations
for j = 1:N_cars
% Calculate distance to lead car
if j < N_cars
dist(j) = x(j+1) - x(j) - L(j) - L(j+1);
else
dist(j) = 1e10; % Assume no car ahead of last car
end
% Calculate acceleration based on the Gipps model
s_desired = s0 + T*v(j);
if j > 1
v_lead = v(j-1);
else
v_lead = 0; % Set speed to zero if no lead car exists
end
% Only consider lead car if it exists
if j < N_cars
d = dist(j) - L(j) - L(j+1);
else
d = dist(j) - L(j);
end
a_desired = a_max * (1 - (v(j)/v0)^4 - ((s_desired - d)/v(j))^2);
a_safety = b_max * ((v_lead/v(j))^2 - 1) * (1 - s_desired/d) / sqrt(a_max*b_max);
acc(j) = min(a_desired, a_safety);
end
% Update speeds
v = v + acc*dt;
% Animate results
clf;
hold on;
for j = 1:N_cars
rectangle('Position',[x_prev(j)-L(j)/2,(j-1)*2,L(j),2],'FaceColor',colors(j,:),'Curvature',j/N_cars);
end
xlim([0, max(x)+50]);
ylim([0, sum(W)]);
xlabel('Distance (m)');
ylabel('Lane width (m)');
title(sprintf('Time = %0.1f s', time(i)));
drawnow;
end
|
fea6314b1cc5d6402224bc622ef97b3b
|
{
"intermediate": 0.5087980031967163,
"beginner": 0.2801823318004608,
"expert": 0.21101967990398407
}
|
2,794
|
create a bevy code for starter
|
9925a342e4ed59b0db7de7f93dc86712
|
{
"intermediate": 0.32567480206489563,
"beginner": 0.2860247790813446,
"expert": 0.38830041885375977
}
|
2,795
|
In the header find somewhere appropriate and give me a snippet of code both in HTML and CSS that creates a cool search box/search container (not functional) that also matches the style of the page
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cabin:wght@400;700&display=swap">
<link rel="stylesheet" href="style/style.css" />
<title>Camping Equipment - Retail Camping Company</title>
</head>
<body>
<header>
<div class="sticky-nav">
<div class="nav-container">
<img src="assets/images/logo.svg" alt="Logo" class="logo">
<h1>Retail Camping Company</h1>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="camping-equipment.html">Camping Equipment</a></li>
<li><a href="furniture.html">Furniture</a></li>
<li><a href="reviews.html">Reviews</a></li>
<li><a href="basket.html">Basket</a></li>
<li><a href="offers-and-packages.html">Offers and Packages</a></li>
</ul>
</nav>
</div>
</div>
</header>
<!-- Home Page -->
<main>
<section class="slideshow-section">
<!-- Insert slide show here -->
<div class="slideshow-container">
<div class="mySlides fade">
<img src="https://via.placeholder.com/600x400" alt="Tents" style="width:100%">
</div>
<div class="mySlides fade">
<img src="https://via.placeholder.com/600x400" alt="Cookers" style="width:100%">
</div>
<div class="mySlides fade">
<img src="https://via.placeholder.com/600x400" alt="Camping Gear" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
</section>
<section class="about-section">
<p>Welcome to Retail Camping Company, your one-stop-shop for all your camping equipment needs. Discover our premium offers on tents, cookers, camping gear, and furniture.</p>
</section>
<section class="featured-section">
<h2>Featured Products</h2>
<div class="featured-container">
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
</div>
</section>
<section>
<!-- Display special offers and relevant images -->
<div class="special-offers-container">
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Tent Offer">
<p>20% off premium tents!</p>
</div>
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Cooker Offer">
<p>Buy a cooker, get a free utensil set!</p>
</div>
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Furniture Offer">
<p>Save on camping furniture bundles!</p>
</div>
</div>
</section>
<section class="buts">
<!-- Modal pop-up window content here -->
<button id="modalBtn">Special Offer!</button>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Sign up now and receive 10% off your first purchase!</p>
</div>
</div>
</section>
<script>
// Get modal element
var modal = document.getElementById('modal');
// Get open model button
var modalBtn = document.getElementById('modalBtn');
// Get close button
var closeBtn = document.getElementsByClassName('close')[0];
// Listen for open click
modalBtn.addEventListener('click', openModal);
// Listen for close click
closeBtn.addEventListener('click', closeModal);
// Listen for outside click
window.addEventListener('click', outsideClick);
// Function to open modal
function openModal() {
modal.style.display = 'block';
}
// Function to close modal
function closeModal() {
modal.style.display = 'none';
}
// Function to close modal if outside click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = 'none';
}
}
</script>
</main>
<footer>
<div class="footer-container">
<div class="footer-item address-container">
<p>Email: info@retailcampingcompany.com</p>
<p>Phone: +35699382994</p>
<p>Triq Malta,<br>Sliema 12345</p>
<p>Get In Contact:</p>
</div>
<div class="footer-item google-maps-container">
<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d1616.0657636873243!2d14.50821358594606!3d35.89479423499043!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x130e452d3081f035%3A0x61f492f43cae68e4!2sCity%20Gate!5e0!3m2!1sen!2smt!4v1682463311250!5m2!1sen!2smt" width="200" height="200" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>
<div class="footer-item social-links-container">
<p>Follow Us On:</p>
<ul class="social-links">
<li><a href="https://www.facebook.com">Facebook</a></li>
<li><a href="https://www.instagram.com">Instagram</a></li>
<li><a href="https://www.twitter.com">Twitter</a></li>
</ul>
</div>
<div class="footer-itemWwwwwW">
<form action="subscribe.php" method="post">
<input type="email" name="email" placeholder="Enter your email" required>
<button type="submit">Subscribe</button>
</form>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
CSS:
html, body, h1, h2, h3, h4, p, a, ul, li, div, main, header, section, footer, img {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
box-sizing: border-box;
}
body {
font-family: "Cabin", sans-serif;
line-height: 1.5;
color: #333;
width: 100%;
margin: 0;
padding: 0;
min-height: 100vh;
flex-direction: column;
display: flex;
background-image: url("../assets/images/cover.jpg");
background-size: cover;
}
header {
background: #00000000;
padding: 0.5rem 2rem;
text-align: center;
color: #32612D;
font-size: 1.2rem;
}
main{
flex-grow: 1;
}
.sticky-nav {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 1000;
}
.nav-container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.logo {
width: 50px;
height: auto;
margin-right: 1rem;
}
h1 {
flex-grow: 1;
text-align: left;
}
nav ul {
display: inline
list-style: none;
}
nav ul li {
display: inline;
margin-left: 1rem;
}
nav ul li a {
text-decoration: none;
color: #32612D;
position: relative;
transition: color 0.3s ease;
}
@media screen and (max-width: 768px) {
.nav-container {
flex-direction: column;
}
h1 {
margin-bottom: 1rem;
}
}
nav ul li a {
text-decoration: none;
color: #32612D;
position: relative;
transition: color 0.3s ease;
}
nav ul li a::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 2px;
background-color: #000;
transform: scaleX(0);
transition: transform 0.3s;
}
nav ul li a:hover {
color: #000000;
}
nav ul li a:hover::after {
transform: scaleX(1);
}
.slideshow-container {
width: 100%;
position: relative;
margin: 1rem 0;
}
.mySlides {
display: none;
}
.mySlides img {
width: 100%;
height: auto;
}
/* Slideshow navigation */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: #32612D;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
background-color: rgba(255,255,255,0.8);
}
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.dot:hover {
background-color: #717171;
}
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
.about-section {
padding: 1rem;
text-align: center;
margin: 1rem 0;
}
.featured-section {
padding: 1rem;
text-align: center;
margin: 1rem 0;
}
.featured-section h2 {
font-size: 1.5rem;
margin-bottom: 1rem;
}
.featured-container {
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
margin: 1rem 0;
}
.featured-product {
width: 150px;
padding: 1rem;
background-color: #ADC3AB;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
margin: 0.5rem;
}
.featured-product:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
transform: translateY(-5px);
}
.featured-product img {
width: 100%;
height: auto;
margin-bottom: 1rem;
border-radius: 5px;
}
.special-offers-container {
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
margin: 1rem 0;
}
.special-offer {
width: 200px;
padding: 1rem;
text-align: center;
margin: 1rem;
background-color: #ADC3AB;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
}
.special-offer:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
transform: translateY(-5px);
}
.special-offer img {
width: 100%;
height: auto;
margin-bottom: 0.5rem;
border-radius: 5px;
}
.modal {
display: none;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
overflow: auto;
align-items: center;
}
.modal-content {
background-color: #fefefe;
padding: 2rem;
margin: 10% auto;
width: 30%;
min-width: 300px;
max-width: 80%;
text-align: center;
border-radius: 5px;
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);
}
.buts {
text-align: center;
}
.close {
display: block;
text-align: right;
font-size: 2rem;
color: #333;
cursor: pointer;
}
footer {
background: #32612D;
padding: 1rem;
text-align: center;
margin-top: auto;
}
.footer-container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.footer-item {
margin: 1rem 2rem;
}
footer p {
color: #fff;
margin-bottom: 1rem;
}
footer ul {
list-style: none;
}
footer ul li {
display: inline;
margin: 0.5rem;
}
footer ul li a {
text-decoration: none;
color: #fff;
}
@media screen and (max-width: 768px) {
.special-offers-container {
flex-direction: column;
}
}
@media screen and (max-width: 480px) {
h1 {
display: block;
margin-bottom: 1rem;
}
}
.footer-item iframe {
width: 100%;
height: 200px;
}
.footer-item form {
display: inline-flex;
align-items: center;
}
.footer-item input[type="email"] {
padding: 0.5rem;
border: none;
border-radius: 5px;
margin-right: 0.5rem;
}
.footer-item button {
background-color: #ADC3AB;
color: #32612D;
padding: 0.5rem;
border: none;
border-radius: 5px;
cursor: pointer;
}
.footer-item button:hover {
background-color: #32612D;
color: #fff;
}
.social-links-container {
order: 2;
}
.address-container {
order: 1;
}
.google-maps-container {
order: 0;
}
|
ab6e9dde67059774223651bff23f874d
|
{
"intermediate": 0.4257512092590332,
"beginner": 0.42102810740470886,
"expert": 0.15322071313858032
}
|
2,796
|
import requests
url = 'https://steamcommunity.com/market/priceoverview/?country=NZ¤cy=1&appid=730&market_hash_name=Revolution%20Case'
params = {
'country': 'NZ',
'currency': 1,
'appid': '730',
'market_hash_name': 'Revolution%20Case'
}
#response = requests.get(url, params=params)
response = requests.get(url)
print(response.text)
how would I make it so I can enter the params rather then having to manually changing the url
|
b740aa0cdafc632948a1bf1bf01a8744
|
{
"intermediate": 0.4336847960948944,
"beginner": 0.3722062408924103,
"expert": 0.1941089779138565
}
|
2,797
|
My merge image function just replaces the pixels with the latest image. However I am thinking it is better to interpolate alpha so images down below has a visibility. This merge image function aim to create panorama images. Can you help me. Here is my code: "def image_merging(images, homographies):
if len(images) - 1 != len(homographies):
raise ValueError("The number of homography matrices must be one less than the number of images.")
# Warp all images except the first one using their corresponding homography matrices
warped_images = [images[0]] + [warp_perspective(img, H, True) for img, H in zip(images[1:], homographies)]
# Calculate the bounds of each warped image
warped_image_bounds = np.array([(0, 0, *images[0].shape[:2])] + [get_warped_image_bounds(img, H) for img, H in zip(images[1:], homographies)])
# Compute the size of the merged image
min_x = min(-warped_image_bounds[:,0].max(), warped_image_bounds[:,0].min())
min_y = min(-warped_image_bounds[:,1].max(), warped_image_bounds[:,1].min())
max_x = warped_image_bounds[:,2].max()
max_y = warped_image_bounds[:,3].max()
print("new: ", min_x, min_y, max_x, max_y)
print(warped_image_bounds)
merged_width = int(np.ceil(max_y - min_y - min_y))
merged_height = int(np.ceil(max_x - min_x - min_x))
print("---")
print(merged_width)
print(max_x)
print(min_x)
print(max_x - min_x)
print(np.ceil(max_x - min_x))
print(int(np.ceil(max_x - min_x)))
print("---")
# Initialize the merged image with zeros
merged_image = np.zeros((merged_height, merged_width, 3), dtype=np.uint8)
print("Merged Shape: ", merged_image.shape)
# Merge the warped images by overlaying them on the merged image
for img, bounds in zip(warped_images, warped_image_bounds):
yy, xx= bounds[:2]
print("yx: ", yy ,xx)
mask = np.all(img == 0, axis=-1)
y_offset, x_offset = int(max(0, -min_x+yy)), int(max(0, -min_y+xx))
merged_image_slice = merged_image[y_offset:y_offset + img.shape[0], x_offset:x_offset + img.shape[1]]
print(img.shape, merged_image_slice.shape, mask.shape)
merged_image_slice[~mask] = img[~mask]
print("Merged Shape 2: ", merged_image.shape)
return merged_image"
|
19218dc578d692076b37827823cdd5b7
|
{
"intermediate": 0.31750574707984924,
"beginner": 0.49535369873046875,
"expert": 0.1871405392885208
}
|
2,798
|
where is wrong. i cannot plot the graph correct in dataset. import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv(‘project’)
data.head() # Group data by age and stroke status, count number of observations in each group
age_stroke_counts = data.groupby([‘age’, ‘stroke’]).size().reset_index(name=‘count’)
# Separate out groups by stroke status
stroke_1 = age_stroke_counts[age_stroke_counts[‘stroke’] == ‘1’]
stroke_0 = age_stroke_counts[age_stroke_counts[‘stroke’] == ‘0’]
# Create stacked bar plot
plt.bar(stroke_1[‘age’], stroke_1[‘count’], color=‘green’, label=‘Stroke: Yes’)
plt.bar(stroke_0[‘age’], stroke_0[‘count’], color=‘orange’, bottom=stroke_1[‘count’], label=‘Stroke: No’)
plt.xlim(0, 100)
plt.xticks(range(0, 101, 10))
plt.ylim(0, 2500)
plt.yticks(range(0, 2501, 500))
# Add counts on y-axis
plt.ylabel(‘Count’)
# Add labels and legend
plt.xlabel(‘Age’)
plt.title(‘Counts of Stroke Status by Age’)
plt.legend()
# Show plot
plt.show()
|
9b8aee651b45d7d1ae1e94633247c246
|
{
"intermediate": 0.4562614858150482,
"beginner": 0.27030569314956665,
"expert": 0.2734328508377075
}
|
2,799
|
My merge image function replaces pixels from the latest image. However I am thinking it is better to interpolate alpha value so that the previous images are visible. My merge image function aims to create panorama images so I am not sure if this is good idea. Can you help me. Here is my code: "def image_merging(images, homographies):
if len(images) - 1 != len(homographies):
raise ValueError("The number of homography matrices must be one less than the number of images.")
# Warp all images except the first one using their corresponding homography matrices
warped_images = [images[0]] + [warp_perspective(img, H, True) for img, H in zip(images[1:], homographies)]
# Calculate the bounds of each warped image
warped_image_bounds = np.array([(0, 0, *images[0].shape[:2])] + [get_warped_image_bounds(img, H) for img, H in zip(images[1:], homographies)])
# Compute the size of the merged image
min_x = min(-warped_image_bounds[:,0].max(), warped_image_bounds[:,0].min())
min_y = min(-warped_image_bounds[:,1].max(), warped_image_bounds[:,1].min())
max_x = warped_image_bounds[:,2].max()
max_y = warped_image_bounds[:,3].max()
print("new: ", min_x, min_y, max_x, max_y)
print(warped_image_bounds)
merged_width = int(np.ceil(max_y - min_y - min_y))
merged_height = int(np.ceil(max_x - min_x - min_x))
print("---")
print(merged_width)
print(max_x)
print(min_x)
print(max_x - min_x)
print(np.ceil(max_x - min_x))
print(int(np.ceil(max_x - min_x)))
print("---")
# Initialize the merged image with zeros
merged_image = np.zeros((merged_height, merged_width, 3), dtype=np.uint8)
print("Merged Shape: ", merged_image.shape)
# Merge the warped images by overlaying them on the merged image
for img, bounds in zip(warped_images, warped_image_bounds):
yy, xx= bounds[:2]
print("yx: ", yy ,xx)
mask = np.all(img == 0, axis=-1)
y_offset, x_offset = int(max(0, -min_x+yy)), int(max(0, -min_y+xx))
merged_image_slice = merged_image[y_offset:y_offset + img.shape[0], x_offset:x_offset + img.shape[1]]
print(img.shape, merged_image_slice.shape, mask.shape)
merged_image_slice[~mask] = img[~mask]
print("Merged Shape 2: ", merged_image.shape)
return merged_image"
|
9a9c9ae62ceaf4e5e50bbfce9ea18a6e
|
{
"intermediate": 0.2680383622646332,
"beginner": 0.42219120264053345,
"expert": 0.30977052450180054
}
|
2,800
|
Write a function in C++ named “SortByAbsoluteValue” in the folder named “Sorting” that takes a reference to a std::istream and a reference to an std::ostream. From the istream, it should read in a series of ints separated by spaces. The function should write these ints to the ostream separated by a single space (with a trailing space character). I’ve included code that does this already.
However, the order of these ints should be from smallest to largest by absolute value. Meaning that the sign of the int doesn’t affect its order in the stream, only the absolute value. You can assume that no two ints have the same absolute value.
Example Input Stream: 0 43 -5 67 11 -40
Example Output String: 0 -5 11 -40 43 67
|
20a69fe91feafbdd1c33213fcc49892f
|
{
"intermediate": 0.4639188349246979,
"beginner": 0.287885844707489,
"expert": 0.2481953501701355
}
|
2,801
|
the gipps model uses these two equations to calculate the velocities of the vehicle in its ode defentions █(&v_n (t+τ)=min{v_n (t)+2.5a_n τ(1-v_n (t)/V_n ) (0.025+v_n (t)/V_n )^(1/2),┤@&├ b_n τ+√(b_n^2 τ^2-b_n [2[x_(n-1) (t)-s_(n-1)-x_n (t)]-v_n (t)τ-v_(n-1) (t)^2/b ̂ ] )}@&) can you please integerate them to find the accelration when using the car model
|
1e96fd0904060b824ee662e760e57f05
|
{
"intermediate": 0.3194091320037842,
"beginner": 0.23152390122413635,
"expert": 0.44906696677207947
}
|
2,802
|
okay so I have a weird happening, in my warp function when an image gets warped, their left corner appears on right side of the screen. I am thinking like is this some kind of integer overflow ?. Expected result is when left most corner is warped it appears on the left side, but however I am seeing images left side suddenly stick from the right edge lol. If you know a solution here is my code: "def warp_perspective(img, H, reverse=False):
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
test = np.array([[0, w, w, 0],
[0, 0, h, h],
[1, 1, 1, 1]])
test_c = np.dot(H, test)
test_w = test_c[0]/test_c[2]
test_h = test_c[1]/test_c[2]
print("Test W: ", test_w)
print("Test H: ", test_h)
max_y, min_y = test_w.max(), min(0, test_w.min())
max_x, min_x = test_h.max(), min(0, test_h.min())
print("x: ", max_x, min_x, " = ", max_x - min_x)
print("y: ", max_y, min_y, " = ", max_y - min_y)
w, h = int(max_y - min_y), int(max_x -min_x)
target_y, target_x = np.meshgrid(np.arange(min_x, h), np.arange(min_y, w))
target_coordinates = np.stack([target_x.ravel(), target_y.ravel(), np.ones(target_x.size)])
source_coordinates = np.dot(np.linalg.inv(H), target_coordinates)
source_coordinates /= source_coordinates[2, :]
valid = np.logical_and(np.logical_and(0 <= source_coordinates[0, :], source_coordinates[0, :] < img.shape[1]),
np.logical_and(0 <= source_coordinates[1, :], source_coordinates[1, :] < img.shape[0]))
valid_source_coordinates = source_coordinates[:, valid].astype(int)
valid_target_coordinates = target_coordinates[:, valid].astype(int)
valid_source_coordinates[0] = np.clip(valid_source_coordinates[0], -100000, img.shape[1] - 1)
valid_source_coordinates[1] = np.clip(valid_source_coordinates[1], -100000, img.shape[0] - 1)
valid_target_coordinates[0] += int(abs(min_y))
valid_target_coordinates[1] += int(abs(min_x))
valid_target_coordinates[0] = np.clip(valid_target_coordinates[0], -100000, w - 1)
valid_target_coordinates[1] = np.clip(valid_target_coordinates[1], -100000, h - 1)
warped_image = np.zeros((h, w, 3), dtype=np.uint8)
for i in range(3):
warped_image[:,:, i][valid_target_coordinates[1], valid_target_coordinates[0]] = img[:,:, i][valid_source_coordinates[1], valid_source_coordinates[0]]
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image"
|
2a17e2943ce98e1d3ac66e4ea1d69582
|
{
"intermediate": 0.3186544179916382,
"beginner": 0.4278978705406189,
"expert": 0.25344768166542053
}
|
2,803
|
This project is about creating a rudimentary market for cryptocurrencies. A class, name "Exchange", has public member functions that allow for the deposit and withdrawl of various assets (e.g. Bitcoin, Etherum and US Dollars). Orders to buy and sell assets at a specified price can also be made and the exchange will perform trades as possible to fulfill orders. Lastly, the exchange has a member function dedicated to printing out the current status of the exchange (i.e. what is in each user’s portfolio, what orders have been opened and filled, what trades have taken place, and what the current prices are for the assets being traded.
The starter code has three header files and 4 implementation files. Some of these files have content in them already, but you are welcome to add, remove or change any part of the code given. Each test case will compile the implementation files and include the exchange.hpp and/or utility.hpp if it makes use of a class declared within. The useraccount files are not directly tested in the test cases, but they can be optionally used to store and manipulate information associated with a user’s account (as helper class(es) for the exchange). The provided main file is never used by any test cases, but it provides an example use of the exchange for your own testing purposes.
main.cpp:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "exchange.hpp"
#include "useraccount.hpp"
#include "utility.hpp"
int main() {
std::cout << "start" << std::endl;
Exchange base;
base.MakeDeposit("Nahum", "USD", 1000);
base.MakeDeposit("Nahum", "ETH", 400);
base.MakeDeposit("Dolson", "BTC", 100);
base.MakeDeposit("Dolson", "USD", 7000);
base.MakeDeposit("Enbody", "USD", 7000);
base.MakeDeposit("Ofria", "BCH", 9);
base.MakeWithdrawal("Dolson", "BTC", 10);
base.PrintUserPortfolios(std::cout);
std::cout << std::endl;
Order o_n{"Nahum", "Buy", "BTC", 2, 22};
Order o_d{"Dolson", "Sell", "BTC", 3, 17};
std::cout << "Before 1st add order" << std::endl;
base.AddOrder(o_n);
std::cout << "After 1st add order" << std::endl;
base.PrintUsersOrders(std::cout);
std::cout << std::endl;
std::cout << "Before 2nd add order" << std::endl;
base.AddOrder(o_d);
std::cout << "After 2nd add order" << std::endl;
base.PrintTradeHistory(std::cout);
std::cout << std::endl;
base.PrintUserPortfolios(std::cout);
std::cout << std::endl;
base.PrintUsersOrders(std::cout);
std::cout << std::endl;
base.AddOrder({"Dolson", "Buy", "ETH", 10, 200});
base.AddOrder({"Enbody", "Buy", "ETH", 15, 300});
base.AddOrder({"Nahum", "Sell", "ETH", 20, 100});
base.PrintTradeHistory(std::cout);
base.PrintUsersOrders(std::cout);
base.AddOrder({"Nahum", "Sell", "ETH", 20, 1000});
base.AddOrder({"Dolson", "Sell", "ETH", 2, 250});
base.AddOrder({"Enbody", "Buy", "BTC", 1, 10});
base.PrintTradeHistory(std::cout);
base.PrintUserPortfolios(std::cout);
std::cout << std::endl << std::endl;
base.PrintUsersOrders(std::cout);
base.AddOrder({"Enbody", "Buy", "LTC", 1, 10});
base.AddOrder({"Ofria", "Sell", "BCH", 2, 55});
base.PrintBidAskSpread(std::cout);
return 0;
}
exchange.cpp:
#include "exchange.hpp"
exchange.hpp:
#pragma once
#include <iostream>
#include <string>
#include "useraccount.hpp"
#include "utility.hpp"
class Exchange {
public:
void MakeDeposit(const std::string &username, const std::string &asset,
int amount);
void PrintUserPortfolios(std::ostream &os) const;
bool MakeWithdrawal(const std::string &username, const std::string &asset,
int amount);
bool AddOrder(const Order &order);
void PrintUsersOrders(std::ostream &os) const;
void PrintTradeHistory(std::ostream &os) const;
void PrintBidAskSpread(std::ostream &os) const;
};
useraccount.cpp:
#include "useraccount.hpp"
useraccount.hpp:
#pragma once
utility.cpp:
#include "utility.hpp"
utility.hpp:
#pragma once
#include <iostream>
#include <string>
struct Order {
std::string username;
std::string side; // Can be "Buy" or "Sell"
std::string asset;
int amount;
int price;
};
struct Trade {
std::string buyer_username;
std::string seller_username;
std::string asset;
int amount;
int price;
};
Please write these Exchange member functions:
MakeDeposit: this function should take a username (e.g. Prof), an asset (e.g. “BTC”), and an amount (e.g. 100). The function does not return anything, but should store the information that the deposit occurred to a user’s portfolio. A portfolio is a record of the assets a user possesses on the exchange that are not involved in any open orders. In the example, Prof is depositing 100 BTC (Bitcoins) into the exchange.
PrintUserPortfolios: this function takes a reference to a std::ostream and should print out each user’s portfolio (ordered alphabetically by user’s name, and then by asset). Remember that assets that are involved in an open order should not be part of a user’s portfolio. Please see the test cases for exact formatting. Most test cases involving printing will print to std::cout (for easier output reading), as well as, to a std::ostringstream (for test case validation).
MakeWithdrawl: this function has the same parameters as MakeDeposit, but instead of depositing funds in the exchange, the user is removing previously deposited funds. The function returns true if and only if the withdrawal was successful. A withdrawal can only be unsuccessful if there are insufficient assets in a user’s portfolio.
AddOrder: This is the most involved member function here. All of the code needed to implement this functionality should not be in this single function but allocated to many helper functions and classes. This function takes an Order (declared in utility.hpp) and returns true if the order was successfully placed. The only reason an order could not be placed is if there were insufficient assets to cover the trade. For instance, if you want to sell 10 bitcoins you must have at least 10 bitcoins in your portfolio. Additionally, if you want to buy 10 bitcoins for 100 USD (US Dollars), you need to have at least 1000 dollars in your portfolio to pay for such an order. All orders (buy or sell) are priced in USD. When an order is made, the funds needed to cover the order are removed from the portfolio (to prevent double spending). The order is then considered open and may participate market taker trades and then market maker trades (details on trading provided below).
PrintUserOrders: For each user (ordered alphabetically), this function prints the open and filled trades (ordered chronologically as each trade was opened/filled) to the referenced std::ostream. See test cases for exact formatting.
PrintTradeHistory: Prints a record of each trade (chronologically) that occurred to the provided reference to std::ostream. See test cases for exact formatting.
PrintBidAskSpread: For each asset (ordered alphabetically), prints the bid ask spread dictated by the open orders to the reference to std::ostream. See test cases for exact formatting.
|
29dcf9361846a498bfa87f1bff53d5e8
|
{
"intermediate": 0.36982038617134094,
"beginner": 0.48453444242477417,
"expert": 0.1456451565027237
}
|
2,804
|
when o try to install django through pip install i get an error can you help me solve it?, this are the console messages:
pip install django ✔ | 3:26
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7546b3480850>: Failed to establish a new connection: [Errno 111] Connection refused')': /simple/django/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7546b400a460>: Failed to establish a new connection: [Errno 111] Connection refused')': /simple/django/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7546b3673730>: Failed to establish a new connection: [Errno 111] Connection refused')': /simple/django/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7546b36738e0>: Failed to establish a new connection: [Errno 111] Connection refused')': /simple/django/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7546b3673ee0>: Failed to establish a new connection: [Errno 111] Connection refused')': /simple/django/
|
394c2c1ad8c11164d2c75bca414a5599
|
{
"intermediate": 0.41351261734962463,
"beginner": 0.2883027195930481,
"expert": 0.29818466305732727
}
|
2,805
|
Hi, i've implemented the following dataframe class.And I want you to implement the loc function based on the test_19 function.class DataFrame:
def __init__(self, data, columns, index = True):
self.data = data
self.columns = columns
self.index = True
def __repr__(self):
rows = []
rows.append(',' + ','.join(self.columns))
for i, row in enumerate(self.data):
#print(*[str(i) if self.index else ''] )
rows.append(str(*[str(i) + ',' if self.index else '']) + ','.join([str(val) for val in row]))
return '\n'.join(rows)
def __getitem__(self, key):
if isinstance(key, str):
values = [row[self.columns.index(key)] for row in self.data]
return ListV2(values)
elif isinstance(key, list):
idx = [self.columns.index(k) for k in key]
data = [[row[i] for i in idx] for row in self.data]
return DataFrame(data=data, columns=key)
elif isinstance(key, slice):
if isinstance(key.start, int) and isinstance(key.stop, int):
data = self.data[key.start:key.stop]
return DataFrame(data=data, columns=self.columns)
elif isinstance(key.start, int) and key.stop is None:
data = self.data[key.start:]
return DataFrame(data=data, columns=self.columns)
elif key.start is None and isinstance(key.stop, int):
data = self.data[:key.stop]
return DataFrame(data=data, columns=self.columns)
else:
raise TypeError("Invalid slice argument")
elif isinstance(key, tuple):
row_slice, col_slice = key
row_data = self.data[row_slice]
col_data = [row[col_slice] for row in self.data[row_slice]]
return DataFrame(data=col_data, columns=self.columns[col_slice])
else:
raise TypeError("Invalid argument type")
def as_type(self, column, data_type):
col_index = self.columns.index(column)
for row in self.data:
row[col_index] = data_type(row[col_index])
def mean(self):
result = {}
for col in self.columns:
if col != 'StudentName':
idx = self.columns.index(col)
col_values = [row[idx] for row in self.data]
result[col] = sum(col_values) / len(col_values)
return result
def set_index(self, column):
#index_column = ',' + ','.join(map(str, range(len(self.data))))
for col_index, col in enumerate(map(list, zip(*self.data))):
if column == col:
#self.columns = list(filter(lambda x: self.columns.index(x) != col_index, self.columns))
#return DataFrame(data= self.data, columns = self.columns)
self.columns = [self.columns[col_index]] + self.columns[:col_index] + self.columns[col_index+1:]
new_data = []
for i, row in enumerate(self.data):
index_data = [row[col_index]]
new_row = [i] + index_data + row[:col_index] + row[col_index+1:]
new_data.append(new_row)
self.data=new_data
self.index = False
break
# else:
# raise ValueError(f"Column '{column}' does not exist in DataFrame")
# new_data =
# self.columns = list(filter(lambda x: self.columns.index(x) != col_index, self.columns))
# break
def drop(self, column):
if column in self.columns:
col_index = self.columns.index(column)
new_columns = [col for col in self.columns if col != column]
new_data = []
for row in self.data:
new_row = row[:col_index] + row[col_index+1:]
new_data.append(new_row)
self.columns = new_columns
self.data = new_data
#print(self.columns, self.data[1])
else:
raise ValueError(f"Column '{column}' does not exist in DataFrame")
def loc(self, row_selector, column_selector=None):
pass
def test_19():
columns = ('StudentName', 'E1', 'E2', 'E3', 'E4', 'E5')
df = DataFrame(data=[ele.strip().split(',') for ele in open('testdata_1.txt')], columns=columns)
for col in ['E1', 'E2', 'E3', 'E4', 'E5']:
df.as_type(col, int)
df.drop('E5')
df.set_index(list(df['StudentName']))
df.drop('StudentName')
expected_output = """,E1,E2
student1,92,77
student2,74,93"""
print(excepted_output == df.loc((['student1', 'student2'], ['E1', 'E2'])).__repr__()) this should be true.
test_19()
|
6b25623e383c2cce1e577d4dead34b34
|
{
"intermediate": 0.34290212392807007,
"beginner": 0.47468531131744385,
"expert": 0.18241257965564728
}
|
2,806
|
This project is about creating a rudimentary market for cryptocurrencies. A class, name "Exchange", has public member functions that allow for the deposit and withdrawl of various assets (e.g. Bitcoin, Etherum and US Dollars). Orders to buy and sell assets at a specified price can also be made and the exchange will perform trades as possible to fulfill orders. Lastly, the exchange has a member function dedicated to printing out the current status of the exchange (i.e. what is in each user’s portfolio, what orders have been opened and filled, what trades have taken place, and what the current prices are for the assets being traded.
The starter code has three header files and 4 implementation files. Some of these files have content in them already, but you are welcome to add, remove or change any part of the code given. Each test case will compile the implementation files and include the exchange.hpp and/or utility.hpp if it makes use of a class declared within. The useraccount files are not directly tested in the test cases, but they can be optionally used to store and manipulate information associated with a user’s account (as helper class(es) for the exchange). The provided main file is never used by any test cases, but it provides an example use of the exchange for your own testing purposes.
main.cpp:
#include <iostream>
#include <map>
#include <string>
#include <vector>
#include "exchange.hpp"
#include "useraccount.hpp"
#include "utility.hpp"
int main() {
std::cout << "start" << std::endl;
Exchange base;
base.MakeDeposit("Nahum", "USD", 1000);
base.MakeDeposit("Nahum", "ETH", 400);
base.MakeDeposit("Dolson", "BTC", 100);
base.MakeDeposit("Dolson", "USD", 7000);
base.MakeDeposit("Enbody", "USD", 7000);
base.MakeDeposit("Ofria", "BCH", 9);
base.MakeWithdrawal("Dolson", "BTC", 10);
base.PrintUserPortfolios(std::cout);
std::cout << std::endl;
Order o_n{"Nahum", "Buy", "BTC", 2, 22};
Order o_d{"Dolson", "Sell", "BTC", 3, 17};
std::cout << "Before 1st add order" << std::endl;
base.AddOrder(o_n);
std::cout << "After 1st add order" << std::endl;
base.PrintUsersOrders(std::cout);
std::cout << std::endl;
std::cout << "Before 2nd add order" << std::endl;
base.AddOrder(o_d);
std::cout << "After 2nd add order" << std::endl;
base.PrintTradeHistory(std::cout);
std::cout << std::endl;
base.PrintUserPortfolios(std::cout);
std::cout << std::endl;
base.PrintUsersOrders(std::cout);
std::cout << std::endl;
base.AddOrder({"Dolson", "Buy", "ETH", 10, 200});
base.AddOrder({"Enbody", "Buy", "ETH", 15, 300});
base.AddOrder({"Nahum", "Sell", "ETH", 20, 100});
base.PrintTradeHistory(std::cout);
base.PrintUsersOrders(std::cout);
base.AddOrder({"Nahum", "Sell", "ETH", 20, 1000});
base.AddOrder({"Dolson", "Sell", "ETH", 2, 250});
base.AddOrder({"Enbody", "Buy", "BTC", 1, 10});
base.PrintTradeHistory(std::cout);
base.PrintUserPortfolios(std::cout);
std::cout << std::endl << std::endl;
base.PrintUsersOrders(std::cout);
base.AddOrder({"Enbody", "Buy", "LTC", 1, 10});
base.AddOrder({"Ofria", "Sell", "BCH", 2, 55});
base.PrintBidAskSpread(std::cout);
return 0;
}
exchange.cpp:
#include "exchange.hpp"
exchange.hpp:
#pragma once
#include <iostream>
#include <string>
#include "useraccount.hpp"
#include "utility.hpp"
class Exchange {
public:
void MakeDeposit(const std::string &username, const std::string &asset,
int amount);
void PrintUserPortfolios(std::ostream &os) const;
bool MakeWithdrawal(const std::string &username, const std::string &asset,
int amount);
bool AddOrder(const Order &order);
void PrintUsersOrders(std::ostream &os) const;
void PrintTradeHistory(std::ostream &os) const;
void PrintBidAskSpread(std::ostream &os) const;
};
useraccount.cpp:
#include "useraccount.hpp"
useraccount.hpp:
#pragma once
utility.cpp:
#include "utility.hpp"
utility.hpp:
#pragma once
#include <iostream>
#include <string>
struct Order {
std::string username;
std::string side; // Can be "Buy" or "Sell"
std::string asset;
int amount;
int price;
};
struct Trade {
std::string buyer_username;
std::string seller_username;
std::string asset;
int amount;
int price;
};
Please write these Exchange member functions:
MakeDeposit: this function should take a username (e.g. Prof), an asset (e.g. “BTC”), and an amount (e.g. 100). The function does not return anything, but should store the information that the deposit occurred to a user’s portfolio. A portfolio is a record of the assets a user possesses on the exchange that are not involved in any open orders. In the example, Prof is depositing 100 BTC (Bitcoins) into the exchange.
PrintUserPortfolios: this function takes a reference to a std::ostream and should print out each user’s portfolio (ordered alphabetically by user’s name, and then by asset). Remember that assets that are involved in an open order should not be part of a user’s portfolio. Please see the test cases for exact formatting. Most test cases involving printing will print to std::cout (for easier output reading), as well as, to a std::ostringstream (for test case validation).
PrintUserOrders: For each user (ordered alphabetically), this function prints the open and filled trades (ordered chronologically as each trade was opened/filled) to the referenced std::ostream. See test cases for exact formatting.
PrintTradeHistory: Prints a record of each trade (chronologically) that occurred to the provided reference to std::ostream. See test cases for exact formatting.
PrintBidAskSpread: For each asset (ordered alphabetically), prints the bid ask spread dictated by the open orders to the reference to std::ostream. See test cases for exact formatting.
|
e9bfcc41afeee801d3e2d9eee05e1d0e
|
{
"intermediate": 0.36982038617134094,
"beginner": 0.48453444242477417,
"expert": 0.1456451565027237
}
|
2,807
|
Traceback (most recent call last):
File "demo.py", line 9, in <module>
from load_data import *
File "D:\paddle\project\CCPD-master\CCPD-master\rpnet\load_data.py", line 2, in <module>
from imutils import paths
ModuleNotFoundError: No module named 'imutils'
|
c9816e61b16e3d7a5a296f046a25b91d
|
{
"intermediate": 0.47627609968185425,
"beginner": 0.2774164080619812,
"expert": 0.24630756676197052
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.