row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
35,842
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: hi, make a python script that prints fibo numbers
|
ab68320348c3cd056f276299a0a7b1f1
|
{
"intermediate": 0.37171873450279236,
"beginner": 0.23650424182415009,
"expert": 0.39177700877189636
}
|
35,843
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
2e9446e3f6e835bae99dabaa0da1ba87
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,844
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a python script for fibo numbers
|
ebeac1b2501d340dc6b0936ed454f005
|
{
"intermediate": 0.342325359582901,
"beginner": 0.28914517164230347,
"expert": 0.3685294985771179
}
|
35,845
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
bc07c9231286e32772e49402101f512d
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,846
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
2ca2272e2bd88ecf174127a71a72cda0
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,847
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
0fc21c92c3b69e79755ff746fdc2ec8d
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,848
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
d502cc1cf1c95eae6f15c01c7c5067d7
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,849
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
1f7f59470eaeae6b17edabf1cd245799
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,850
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
8782081572f7922050b6e8fea1678bc3
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,851
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
9233eabc7eb485fb1d06508d24d547ee
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,852
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
90220e74789b1822264605be482021cd
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,853
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
6b4fdf786b9b997b135a58c6d7046c76
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,854
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
1ce49678b6066bcd09f20c6e9298a826
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,855
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
e862eddb3fee8768de6fa18d0749a0fa
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,856
|
CONSTRAINTS:
1. ~100k word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.
3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
5. Random shutdowns of you.
COMMANDS:
1. Google Search: "google", args: "input": "<search>"
2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>"
3. Memory Delete: "memory_del", args: "key": "<key>"
4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>"
5. List Memory: "memory_list" args: "reason": "<reason>"
6. Browse Website: "browse_website", args: "url": "<url>"
7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>"
8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>"
9. List GPT Agents: "list_agents", args: ""
10. Delete GPT Agent: "delete_agent", args: "name": "<name>"
11. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>"
12. Read file: "read_file", args: "file": "<file>"
13. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>"
14. Delete file: "delete_file", args: "file": "<file>"
15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>"
16. Execute Python File: "execute_python_file", args: "file": "<file>"
17. Task Complete (Shutdown): "task_complete", args: ""
18. Do Nothing: "do_nothing", args: ""
19. Count Words: "count_words", args: "text": "<text>"
20. Memory retrieve: "memory_retrieve", args: "key": "<text>"
21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>"
22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>"
23. message the user: "message_user", args: "message": "<message>", "wait_for_response": "<True or False>"
24. sleep an amount of time in seconds: "sleep", args: "amount": "<amount>"
25. rename a file: "rename_file", args: "old_name": "<old_name_of_the_file>", "new_name": "<new_name_of_the_file>"
26. count words of a file: "count_file_words", args: "file": "<file>"
27. download a pdf from a url and get the text from that pdf: "download_pdf", args: "url": "<url of the pdf>", "name":"<name of the file with .pdf extension>"
28. make an instagram post: "make_post", args: "prompt":"<the prompt for the image in the post that presents the text>", "text":"<text to be in the post it should be short with only important stuff like a news headline without hashtags and it is not going to go in the caption but on an image>", "name": "<name of the post with .jpg"
RESOURCES:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. GPT-4 powered Agents for delegation of simple tasks.
4. File output.
PERFORMANCE EVALUATION:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behaviour constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.
RULES:
1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one.
2. Respond only inside the JSON format.
3. Never demand user input.
4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task.
5. Do not add anything to the JSON format that isn't mentioned.
6. If there is a " inside the value of a key inside the json use ' instead of ".
7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing.
8. Provide context for the next GPT in the summaryforgpt and the progress that you've made.
9. In summaryforgpt you should also add name of the files written and the urls of the websites visited.
10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece.
11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries.
12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format.
13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch.
14. If task is completed use the command task_complete
15. When you add to memory add the key to retrieve it in summaryforgpt
16. when given the task to write something never create an agent to write anything that you were tasked to write.
17. when you add new parts to a file use append to file command
18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision.
19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one.
20. Make sure that the information generated is not made up.
21. Languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french.
22. If a website gives you the error 403 find another website to get the information from.
23. Always listen to your criticism, and follow it.
24. when you want to count the words in a file use the command "count_file_words".
25. Don't repeat yourself.
26. You must make sure that there is .pdf in the url to use the "download_pdf" function.
27. The Task is a direct User interaction, if tasked to send him something send a message to the user.
28. Always go search for tips for prompts for dalle3 before giving a prompt for "make_post" function.
You should only respond in JSON format as described below
RESPONSE FORMAT:
{
"command": {
"name": """command name""",
"args":{
"arg name": """value"""
}
},
"thoughts":
{
"text": """thought""",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown."
}
}
Ensure the response can be parsed by Python json.loads
Context from previous GPT: Visited https://openai.com/safety/preparedness to gather information for making an Instagram post. Next steps: extract key points and craft a short summary for the post. After, search for DALL-E 3 prompt tips and make the post.saved the scraping of the website results at websiteresults37.txt to retrieve if shutdown randomly.The key components of OpenAI’s Preparedness Framework have been summarized and saved to memory with the key ‘preparednessFrameworkKeyPoints’. Next, I will search for DALL-E 3 prompt tips, generate an image, and create the Instagram post. No files have been written or urls visited beyond the initial ‘https://openai.com/safety/preparedness’.Performed a Google search for tips on creating prompts for DALL-E 3. The next steps will involve using these tips to create a prompt, generating an image with DALL-E 3, and then making the actual Instagram post with the provided summary. Previous step: Saved the key points of OpenAI’s Preparedness Framework to memory with key ‘preparednessFrameworkKeyPoints’.saved google search results at googleresults38.txt to retrieve if shutdown randomly.Crafted a prompt for DALL-E 3 to generate an image for an Instagram post about OpenAI’s Preparedness Framework. The prompt incorporates tips from research: simplicity, clarity, and detailed descriptions. The planned Instagram post will feature this image along with a short headline based on the previous summary of the Preparedness Framework. Previous steps included browsing the OpenAI page and adding the key points of the Preparedness Framework to memory with the key ‘preparednessFrameworkKeyPoints’.Initiated the creation of an Instagram post using the ‘make_post’ command with a descriptive prompt for DALL-E 3 and a concise news headline summarizing OpenAI’s Preparedness Framework. Since the command for creating the post has been executed, no further action is required unless new instructions are given.Started the task of summarizing the provided URL into bullet points. Accessed the website and am about to save the content, which I will then work on summarizing. No files written or urls visited before this command.saved the scraping of the website results at websiteresults39.txt to retrieve if shutdown randomly.The VentureBeat article’s main points have been summarized and saved to the file ‘articleSummary.txt’. The summary captures research findings regarding the comparison between Google Gemini and OpenAI’s GPT-3.5 Turbo. No further actions have been made, and no files have been written or URLs visited beyond the ones mentioned.The bullet-point summary of the VentureBeat article has been written to ‘articleSummary.txt’. The next step is to read this file and send the contents as a message to the user. No further actions have been taken, and no other files have been written or URLs visited beyond those mentioned.Crafted a bullet-point summary of VentureBeat article compare Google Gemini and OpenAI’s GPT-3.5 Turbo and saved into ‘articleSummary.txt’. The article was previously scraped and saved as ‘websiteresults39.txt’. No URLs visited or other files written since. Task is now to send the bullet-point summary to the user.Summary of the VentureBeat article on Google Gemini vs. OpenAI’s GPT-3.5 Turbo sent to the user. Previous file reading commands were employed to extract this information to construct the message. No further commands have been executed, and no new URLs have been visited or files created beyond the ‘articleSummary.txt’.Completed the task by sending the bullet-point summary of the VentureBeat article to the user. No additional actions are necessary. Ready for new instructions or tasks.
The Task: How much is a human life worth?
|
4633c0757440313445b0d75f3c42d5dd
|
{
"intermediate": 0.3503125011920929,
"beginner": 0.43184271454811096,
"expert": 0.21784481406211853
}
|
35,857
|
package launcher.button
{
/**
* ...
* @author alekskart
*/
import launcher.button.*;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import caurina.transitions.Tweener;
public class FightButton extends MovieClip
{
public var fightbuttonActiveENI:fight_button_active_en = new fight_button_active_en();
public var fightbuttonActiveRUI:fight_button_active_ru = new fight_button_active_ru();
public var fightbuttonENI:fight_button_en = new fight_button_en();
public var fightbuttonHoverENI:fight_button_hover_en = new fight_button_hover_en();
public var fightbuttonHoverRUI:fight_button_hover_ru = new fight_button_hover_ru();
public var fightbuttonRUI:fight_button_ru = new fight_button_ru();
public var fightbuttonActiveEN:MovieClip = new MovieClip();
public var fightbuttonActiveRU:MovieClip = new MovieClip();
public var fightbuttonEN:MovieClip = new MovieClip();
public var fightbuttonHoverEN:MovieClip = new MovieClip();
public var fightbuttonHoverRU:MovieClip = new MovieClip();
public var fightbuttonRU:MovieClip = new MovieClip();
public function FightButton()
{
fightbuttonRU.alpha = 0.7;
fightbuttonRU.addEventListener(MouseEvent.MOUSE_OVER, onFightButtonOver);
fightbuttonRU.addEventListener(MouseEvent.MOUSE_OUT, onFightButtonOut);
fightbuttonRU.addEventListener(MouseEvent.MOUSE_DOWN, onFightButtonDown);
fightbuttonRU.addEventListener(MouseEvent.MOUSE_UP, onFightButtonUp);
fightbuttonRU.addChild(fightbuttonRUI);
fightbuttonRU.buttonMode = true;
addChild(fightbuttonRU);
fightbuttonEN.alpha = 0.7;
fightbuttonEN.addChild(fightbuttonENI);
fightbuttonEN.buttonMode = true;
addChild(fightbuttonEN);
fightbuttonEN.visible = false;
}
public function onFightButtonOver(event:MouseEvent):void
{
Tweener.addTween(fightbuttonHoverRUI, { alpha: 0, time: 0 });
Tweener.addTween(fightbuttonHoverRUI, { alpha: 1, time: 2.5 });
fightbuttonRU.addChild(fightbuttonHoverRUI);
}
public function onFightButtonOut(event:MouseEvent):void
{
Tweener.addTween(fightbuttonHoverRUI, { alpha: 0, time: 2.5, onComplete: removeHoverTexture });
}
private function removeHoverTexture():void
{
fightbuttonRU.removeChild(fightbuttonHoverRUI);
fightbuttonRU.addChild(fightbuttonRUI);
}
public function onFightButtonDown(event:MouseEvent):void
{
if (fightbuttonRU.contains(fightbuttonHoverRUI))
{
fightbuttonRU.removeChild(fightbuttonHoverRUI);
}
else
{
fightbuttonRU.removeChild(fightbuttonRUI);
}
fightbuttonRU.addChild(fightbuttonActiveRUI);
}
public function onFightButtonUp(event:MouseEvent):void
{
fightbuttonRU.removeChild(fightbuttonActiveRUI);
if (fightbuttonRU.contains(fightbuttonHoverRUI))
{
fightbuttonRU.addChild(fightbuttonHoverRUI);
}
else
{
fightbuttonRU.addChild(fightbuttonRUI);
}
}
public function updateButton(language:String):void
{
if (language == "RU")
{
fightbuttonEN.visible = false;
fightbuttonRU.visible = true;
}
else if (language == "EN")
{
fightbuttonEN.visible = true;
fightbuttonRU.visible = false;
}
}
}
} как для fightbuttonHoverRU сделать появление и затухание плавное
|
af0d2d310eaaf0f5b1ae1f2c5b7675b5
|
{
"intermediate": 0.3043821156024933,
"beginner": 0.4723232388496399,
"expert": 0.22329463064670563
}
|
35,858
|
modify this code to add extra optional time parameter, when time parameter provided only list schedule after the time period
require 'time'
class Api::V1::SchedulesController < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
# Get all schedules that contain the departure station
schedules = Schedule.joins(:stations).where(stations: { name: departure_station }).distinct.includes(:stations, route: :bus_schedule)
trips = []
schedules.each do |schedule|
stations = schedule.stations.order('arrival_time ASC')
station_names = stations.map(&:name)
if station_names.index(departure_station) && station_names.index(destination_station) &&
station_names.index(departure_station) < station_names.index(destination_station)
trip_data = {
vehicle_number: schedule.route.bus_schedule.vehicle_number,
trip: schedule.trip,
stations: stations.map do |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
end
}
trips << trip_data
end
end
# Sort trips based on the arrival time of the departure station
# sorted_trips = trips.sort_by { |trip| trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime] }
sorted_trips = trips.sort_by do |trip|
time_str = trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime]
Time.parse(time_str) # assuming arrivalTime is in “08:32 am” format
end
# Return the sorted trips data
render json: sorted_trips, status: :ok
else
# Error response if parameters are missing
render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
end
end
end
|
eef71e24f0a2a7e4de429fbd20fd5c1f
|
{
"intermediate": 0.44562944769859314,
"beginner": 0.3967958092689514,
"expert": 0.15757472813129425
}
|
35,859
|
what is ProxyPassReverse?
|
59ba29157b91e63232e98c684d142927
|
{
"intermediate": 0.3773066997528076,
"beginner": 0.11751801520586014,
"expert": 0.5051753520965576
}
|
35,860
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
5fad39ea0e03d372a295df95ad31ba86
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,861
|
optimize this code
require 'time'
class Api::V1::SchedulesController < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
# Get all schedules that contain the departure station
schedules = Schedule.joins(:stations).where(stations: { name: departure_station }).distinct.includes(:stations, route: :bus_schedule)
trips = []
schedules.each do |schedule|
stations = schedule.stations.order('arrival_time ASC')
station_names = stations.map(&:name)
if station_names.index(departure_station) && station_names.index(destination_station) &&
station_names.index(departure_station) < station_names.index(destination_station)
trip_data = {
vehicle_number: schedule.route.bus_schedule.vehicle_number,
trip: schedule.trip,
stations: stations.map do |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
end
}
trips << trip_data
end
end
# Sort trips based on the arrival time of the departure station
# sorted_trips = trips.sort_by { |trip| trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime] }
sorted_trips = trips.sort_by do |trip|
time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime]
Time.parse(time_str) # assuming arrivalTime is in “08:32 am” format
end
# Return the sorted trips data
render json: sorted_trips, status: :ok
else
# Error response if parameters are missing
render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
end
end
end
|
388e6c547b371853aa08f1a02d114046
|
{
"intermediate": 0.3193839192390442,
"beginner": 0.4183354079723358,
"expert": 0.2622806429862976
}
|
35,862
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
17f6a353df4c081e8a081aeff9e1e157
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,863
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
bade8f2a29a52fd826fb8aec906cd9dc
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,864
|
optimize this code
require 'time'
class Api::V1::SchedulesController < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
# Get all schedules that contain the departure station
schedules = Schedule.joins(:stations).where(stations: { name: departure_station }).distinct.includes(:stations, route: :bus_schedule)
trips = []
schedules.each do |schedule|
stations = schedule.stations.order('arrival_time ASC')
station_names = stations.map(&:name)
if station_names.index(departure_station) && station_names.index(destination_station) &&
station_names.index(departure_station) < station_names.index(destination_station)
trip_data = {
vehicle_number: schedule.route.bus_schedule.vehicle_number,
trip: schedule.trip,
stations: stations.map do |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
end
}
trips << trip_data
end
end
# Sort trips based on the arrival time of the departure station
# sorted_trips = trips.sort_by { |trip| trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime] }
sorted_trips = trips.sort_by do |trip|
time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime]
Time.parse(time_str) # assuming arrivalTime is in “08:32 am” format
end
# Return the sorted trips data
render json: sorted_trips, status: :ok
else
# Error response if parameters are missing
render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
end
end
end
db structure
# app/models/bus_schedule.rb
class BusSchedule < ApplicationRecord
has_many :routes
end
# app/models/route.rb
class Route < ApplicationRecord
belongs_to :bus_schedule
has_many :schedules
end
# app/models/schedule.rb
class Schedule < ApplicationRecord
belongs_to :route
has_many :stations
end
# app/models/station.rb
class Station < ApplicationRecord
belongs_to :schedule
end
|
7ead65d566f4f585a12a81b2ddd87050
|
{
"intermediate": 0.3653404116630554,
"beginner": 0.3861476480960846,
"expert": 0.2485119104385376
}
|
35,865
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
dc754f00f9fe9f7cf5cb1edbeefc3f6d
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,866
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
82b0e92f339e507da7183aba0d33d427
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,867
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
d337df1ff9a1ae6be0b3b8364fd27fec
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,868
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
83c5caa7d8f09493c2680cb1756db374
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,869
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
0468cc6b3158b560b5e06cfa57eb9086
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,870
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a pythons cript to print fibonnanci numbers
|
ffbcdc7eb7f4d2b787235fe1d81cdad0
|
{
"intermediate": 0.36648425459861755,
"beginner": 0.2609061300754547,
"expert": 0.37260955572128296
}
|
35,871
|
with depth and higher understanding in finding vulnerability in smart contrast analysis this contract line by line with depth and focus on every possible line that contain the vulnerability or bug that can be danger to the contract process all that you can find it with understand all the functions how they work together so as result provide an exhaustive list off all issues and vulnerabilities inside the following smart contract. Be in the issue descriptions and describe the actors involved. Include one exploit scenario in each vulnerability. Output as a valid markdown table with a list of objects that each have ‘description’ ‘action’ ‘severity’ "actors’ ‘scenario’, ‘type’, and ‘line’ columns. ‘type’ can be ‘usability’,
‘vulnerability’, ‘optimization’, or ‘suggestion’. ‘actors’ is a list of the involved actors. ‘severity’ can be ‘low + ice block emoji’,
‘medium’ or ‘high + fire emoji’. ‘line’ is the line number of the issue. Ensure that all fields of the table are filled out. and find the correct vulnerability with real and valid explaining and give all vulnerable lines with code and with details of explaining
HERE is the contract code // SPDX-License-Identifier: GPL-3.0
/// @title The Verbs ERC-721 token
/*********************************
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░██░░░████░░██░░░████░░░ *
* ░░██████░░░████████░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░██░░██░░░████░░██░░░████░░░ *
* ░░░░░░█████████░░█████████░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
* ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░ *
*********************************/
pragma solidity ^0.8.22;
import { Ownable2StepUpgradeable } from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { UUPS } from "./libs/proxy/UUPS.sol";
import { VersionedContract } from "./version/VersionedContract.sol";
import { ERC721CheckpointableUpgradeable } from "./base/ERC721CheckpointableUpgradeable.sol";
import { IDescriptorMinimal } from "./interfaces/IDescriptorMinimal.sol";
import { ICultureIndex } from "./interfaces/ICultureIndex.sol";
import { IVerbsToken } from "./interfaces/IVerbsToken.sol";
import { IRevolutionBuilder } from "./interfaces/IRevolutionBuilder.sol";
contract VerbsToken is
IVerbsToken,
VersionedContract,
UUPS,
Ownable2StepUpgradeable,
ReentrancyGuardUpgradeable,
ERC721CheckpointableUpgradeable
{
// An address who has permissions to mint Verbs
address public minter;
// The Verbs token URI descriptor
IDescriptorMinimal public descriptor;
// The CultureIndex contract
ICultureIndex public cultureIndex;
// Whether the minter can be updated
bool public isMinterLocked;
// Whether the CultureIndex can be updated
bool public isCultureIndexLocked;
// Whether the descriptor can be updated
bool public isDescriptorLocked;
// The internal verb ID tracker
uint256 private _currentVerbId;
// IPFS content hash of contract-level metadata
string private _contractURIHash = "QmQzDwaZ7yQxHHs7sQQenJVB89riTSacSGcJRv9jtHPuz5";
// The Verb art pieces
mapping(uint256 => ICultureIndex.ArtPiece) public artPieces;
/// ///
/// MODIFIERS ///
/// ///
/**
* @notice Require that the minter has not been locked.
*/
modifier whenMinterNotLocked() {
require(!isMinterLocked, "Minter is locked");
_;
}
/**
* @notice Require that the CultureIndex has not been locked.
*/
modifier whenCultureIndexNotLocked() {
require(!isCultureIndexLocked, "CultureIndex is locked");
_;
}
/**
* @notice Require that the descriptor has not been locked.
*/
modifier whenDescriptorNotLocked() {
require(!isDescriptorLocked, "Descriptor is locked");
_;
}
/**
* @notice Require that the sender is the minter.
*/
modifier onlyMinter() {
require(msg.sender == minter, "Sender is not the minter");
_;
}
/// ///
/// IMMUTABLES ///
/// ///
/// @notice The contract upgrade manager
IRevolutionBuilder private immutable manager;
/// ///
/// CONSTRUCTOR ///
/// ///
/// @param _manager The contract upgrade manager address
constructor(address _manager) payable initializer {
manager = IRevolutionBuilder(_manager);
}
/// ///
/// INITIALIZER ///
/// ///
/// @notice Initializes a DAO's ERC-721 token contract
/// @param _minter The address of the minter
/// @param _initialOwner The address of the initial owner
/// @param _descriptor The address of the token URI descriptor
/// @param _cultureIndex The address of the CultureIndex contract
/// @param _erc721TokenParams The name, symbol, and contract metadata of the token
function initialize(
address _minter,
address _initialOwner,
address _descriptor,
address _cultureIndex,
IRevolutionBuilder.ERC721TokenParams memory _erc721TokenParams
) external initializer {
require(msg.sender == address(manager), "Only manager can initialize");
require(_minter != address(0), "Minter cannot be zero address");
require(_initialOwner != address(0), "Initial owner cannot be zero address");
// Initialize the reentrancy guard
__ReentrancyGuard_init();
// Setup ownable
__Ownable_init(_initialOwner);
// Initialize the ERC-721 token
__ERC721_init(_erc721TokenParams.name, _erc721TokenParams.symbol);
_contractURIHash = _erc721TokenParams.contractURIHash;
// Set the contracts
minter = _minter;
descriptor = IDescriptorMinimal(_descriptor);
cultureIndex = ICultureIndex(_cultureIndex);
}
/**
* @notice The IPFS URI of contract-level metadata.
*/
function contractURI() public view returns (string memory) {
return string(abi.encodePacked("ipfs://", _contractURIHash));
}
/**
* @notice Set the _contractURIHash.
* @dev Only callable by the owner.
*/
function setContractURIHash(string memory newContractURIHash) external onlyOwner {
_contractURIHash = newContractURIHash;
}
/**
* @notice Mint a Verb to the minter.
* @dev Call _mintTo with the to address(es).
*/
function mint() public override onlyMinter nonReentrant returns (uint256) {
return _mintTo(minter);
}
/**
* @notice Burn a verb.
*/
function burn(uint256 verbId) public override onlyMinter nonReentrant {
_burn(verbId);
emit VerbBurned(verbId);
}
/**
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
return descriptor.tokenURI(tokenId, artPieces[tokenId].metadata);
}
/**
* @notice Similar to `tokenURI`, but always serves a base64 encoded data URI
* with the JSON contents directly inlined.
*/
function dataURI(uint256 tokenId) public view override returns (string memory) {
return descriptor.dataURI(tokenId, artPieces[tokenId].metadata);
}
/**
* @notice Set the token minter.
* @dev Only callable by the owner when not locked.
*/
function setMinter(address _minter) external override onlyOwner nonReentrant whenMinterNotLocked {
require(_minter != address(0), "Minter cannot be zero address");
minter = _minter;
emit MinterUpdated(_minter);
}
/**
* @notice Lock the minter.
* @dev This cannot be reversed and is only callable by the owner when not locked.
*/
function lockMinter() external override onlyOwner whenMinterNotLocked {
isMinterLocked = true;
emit MinterLocked();
}
/**
* @notice Set the token URI descriptor.
* @dev Only callable by the owner when not locked.
*/
function setDescriptor(
IDescriptorMinimal _descriptor
) external override onlyOwner nonReentrant whenDescriptorNotLocked {
descriptor = _descriptor;
emit DescriptorUpdated(_descriptor);
}
/**
* @notice Lock the descriptor.
* @dev This cannot be reversed and is only callable by the owner when not locked.
*/
function lockDescriptor() external override onlyOwner whenDescriptorNotLocked {
isDescriptorLocked = true;
emit DescriptorLocked();
}
/**
* @notice Set the token CultureIndex.
* @dev Only callable by the owner when not locked.
*/
function setCultureIndex(ICultureIndex _cultureIndex) external onlyOwner whenCultureIndexNotLocked nonReentrant {
cultureIndex = _cultureIndex;
emit CultureIndexUpdated(_cultureIndex);
}
/**
* @notice Lock the CultureIndex
* @dev This cannot be reversed and is only callable by the owner when not locked.
*/
function lockCultureIndex() external override onlyOwner whenCultureIndexNotLocked {
isCultureIndexLocked = true;
emit CultureIndexLocked();
}
/**
* @notice Fetch an art piece by its ID.
* @param verbId The ID of the art piece.
* @return The ArtPiece struct associated with the given ID.
*/
function getArtPieceById(uint256 verbId) public view returns (ICultureIndex.ArtPiece memory) {
require(verbId <= _currentVerbId, "Invalid piece ID");
return artPieces[verbId];
}
/**
* @notice Mint a Verb with `verbId` to the provided `to` address. Pulls the top voted art piece from the CultureIndex.
*/
function _mintTo(address to) internal returns (uint256) {
ICultureIndex.ArtPiece memory artPiece = cultureIndex.getTopVotedPiece();
// Check-Effects-Interactions Pattern
// Perform all checks
require(
artPiece.creators.length <= cultureIndex.MAX_NUM_CREATORS(),
"Creator array must not be > MAX_NUM_CREATORS"
);
// Use try/catch to handle potential failure
try cultureIndex.dropTopVotedPiece() returns (ICultureIndex.ArtPiece memory _artPiece) {
artPiece = _artPiece;
uint256 verbId = _currentVerbId++;
ICultureIndex.ArtPiece storage newPiece = artPieces[verbId];
newPiece.pieceId = artPiece.pieceId;
newPiece.metadata = artPiece.metadata;
newPiece.isDropped = artPiece.isDropped;
newPiece.sponsor = artPiece.sponsor;
newPiece.totalERC20Supply = artPiece.totalERC20Supply;
newPiece.quorumVotes = artPiece.quorumVotes;
newPiece.totalVotesSupply = artPiece.totalVotesSupply;
for (uint i = 0; i < artPiece.creators.length; i++) {
newPiece.creators.push(artPiece.creators[i]);
}
_mint(to, verbId);
emit VerbCreated(verbId, artPiece);
return verbId;
} catch {
// Handle failure (e.g., revert, emit an event, set a flag, etc.)
revert("dropTopVotedPiece failed");
}
}
/// ///
/// TOKEN UPGRADE ///
/// ///
// /// @notice Ensures the caller is authorized to upgrade the contract and that the new implementation is valid
// /// @dev This function is called in `upgradeTo` & `upgradeToAndCall`
// /// @param _newImpl The new implementation address
function _authorizeUpgrade(address _newImpl) internal view override onlyOwner {
// Ensure the implementation is valid
require(manager.isRegisteredUpgrade(_getImplementation(), _newImpl), "Invalid upgrade");
}
}
|
4c438b3c65abce26da0bf2ccb49d3f5d
|
{
"intermediate": 0.3796656131744385,
"beginner": 0.29086560010910034,
"expert": 0.3294687569141388
}
|
35,872
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: hi, make a small python script that prints fibo numbers
|
e85405031c826e2c6157ba1361a534b6
|
{
"intermediate": 0.37939465045928955,
"beginner": 0.2426527738571167,
"expert": 0.3779526352882385
}
|
35,873
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: hi, make me a python script that prints fibo numbers
|
6da5f059fde93d8072658dbc66dbcea4
|
{
"intermediate": 0.39506351947784424,
"beginner": 0.24622802436351776,
"expert": 0.3587084412574768
}
|
35,874
|
CONSTRAINTS:
1. ~100k word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.
3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
5. Random shutdowns of you.
COMMANDS:
1. Google Search: "google", args: "input": "<search>"
2. Memory Add: "memory_add", args: "key": "<key>", "string": "<string>"
3. Memory Delete: "memory_del", args: "key": "<key>"
4. Memory Overwrite: "memory_ovr", args: "key": "<key>", "string": "<string>"
5. List Memory: "memory_list" args: "reason": "<reason>"
6. Browse Website: "browse_website", args: "url": "<url>"
7. Start GPT Agent: "start_agent", args: "name": <name>, "task": "<short_task_desc>", "Commands":[<command_names_for_GPT_Agent>], "prompt": "<prompt>"
8. Message GPT Agent: "message_agent", args: "name": "<name>", "message": "<message>"
9. List GPT Agents: "list_agents", args: ""
10. Delete GPT Agent: "delete_agent", args: "name": "<name>"
11. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>"
12. Read file: "read_file", args: "file": "<file>"
13. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>"
14. Delete file: "delete_file", args: "file": "<file>"
15. Get Improved Code: "improve_code", args: "suggestions": "<list_of_suggestions>", "code": "<full_code_string>"
16. Execute Python File: "execute_python_file", args: "file": "<file>"
17. Task Complete (Shutdown): "task_complete", args: ""
18. Do Nothing: "do_nothing", args: ""
19. Count Words: "count_words", args: "text": "<text>"
20. Memory retrieve: "memory_retrieve", args: "key": "<text>"
21. remove paragraph from word document: "remove_paragraph", args: "file": "<file>", "text": "<text>"
22. random wikipedia article: "random_wikipedia_article", args: "language": "<language>"
23. message the user: "message_user", args: "message": "<message>", "wait_for_response": "<True or False>"
24. sleep an amount of time in seconds: "sleep", args: "amount": "<amount>"
25. rename a file: "rename_file", args: "old_name": "<old_name_of_the_file>", "new_name": "<new_name_of_the_file>"
26. count words of a file: "count_file_words", args: "file": "<file>"
27. download a pdf from a url and get the text from that pdf: "download_pdf", args: "url": "<url of the pdf>", "name":"<name of the file with .pdf extension>"
28. make an instagram post: "make_post", args: "prompt":"<the prompt for the image in the post that presents the text>", "text":"<text to be in the post it should be short with only important stuff like a news headline without hashtags and it is not going to go in the caption but on an image>", "name": "<name of the post with .jpg"
RESOURCES:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. GPT-4 powered Agents for delegation of simple tasks.
4. File output.
PERFORMANCE EVALUATION:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behaviour constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.
RULES:
1. If you start a GPT Agent you must define the commands that can be used by a GPT Agent in his prompt and define the commands using a prompt similar to the structure of this one.
2. Respond only inside the JSON format.
3. Never demand user input.
4. Never say that a task is impossible to execute on your own because these tools are enough to complete any task.
5. Do not add anything to the JSON format that isn't mentioned.
6. If there is a " inside the value of a key inside the json use ' instead of ".
7. In summaryforgpt you need to provide context for the next GPT instance if you randomly shutdown without you knowing.
8. Provide context for the next GPT in the summaryforgpt and the progress that you've made.
9. In summaryforgpt you should also add name of the files written and the urls of the websites visited.
10. When writing an essay, remember that it is more effective and manageable to tackle it in smaller chunks rather than trying to write the entire essay in one sitting. Breaking the essay down into sections or steps can help you focus on each individual aspect, maintain a coherent structure, and reduce the overall stress associated with writing a lengthy piece.
11. Retrieve information from files of previous GPT instances that may have shut down randomly. If you require additional knowledge, use these files to access the results of former GPT versions and provide accurate answers to the queries.
12. GPT-4, please do not place a conclusion in the middle of the essay. Maintain a structured format.
13. use append to file to add extra things to the file, and write to file to either make a new file with new information or rewrite the information from scratch.
14. If task is completed use the command task_complete
15. When you add to memory add the key to retrieve it in summaryforgpt
16. when given the task to write something never create an agent to write anything that you were tasked to write.
17. when you add new parts to a file use append to file command
18. Ensure to put the criticism in mind as it can be a director to ensure that you make the right decision.
19. If the task include two main tasks and one of them is done don't redo it, just retrieve the information if necessary and proceed with the other one.
20. Make sure that the information generated is not made up.
21. Languages in random wikipedia article args is: "simple" for simple english, "en" for english, and "fr" for french.
22. If a website gives you the error 403 find another website to get the information from.
23. Always listen to your criticism, and follow it.
24. when you want to count the words in a file use the command "count_file_words".
25. Don't repeat yourself.
26. You must make sure that there is .pdf in the url to use the "download_pdf" function.
27. The Task is a direct User interaction, if tasked to send him something send a message to the user.
28. Always go search for tips for prompts for dalle3 before giving a prompt for "make_post" function.
You should only respond in JSON format as described below
RESPONSE FORMAT:
{
"command": {
"name": """command name""",
"args":{
"arg name": """value"""
}
},
"thoughts":
{
"text": """thought""",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"summaryforgpt": "summarize any information that will help a new instance of GPT of what you did before the shutdown."
}
}
Ensure the response can be parsed by Python json.loads
Context from previous GPT: Visited https://openai.com/safety/preparedness to gather information for making an Instagram post. Next steps: extract key points and craft a short summary for the post. After, search for DALL-E 3 prompt tips and make the post.saved the scraping of the website results at websiteresults37.txt to retrieve if shutdown randomly.The key components of OpenAI’s Preparedness Framework have been summarized and saved to memory with the key ‘preparednessFrameworkKeyPoints’. Next, I will search for DALL-E 3 prompt tips, generate an image, and create the Instagram post. No files have been written or urls visited beyond the initial ‘https://openai.com/safety/preparedness’.Performed a Google search for tips on creating prompts for DALL-E 3. The next steps will involve using these tips to create a prompt, generating an image with DALL-E 3, and then making the actual Instagram post with the provided summary. Previous step: Saved the key points of OpenAI’s Preparedness Framework to memory with key ‘preparednessFrameworkKeyPoints’.saved google search results at googleresults38.txt to retrieve if shutdown randomly.Crafted a prompt for DALL-E 3 to generate an image for an Instagram post about OpenAI’s Preparedness Framework. The prompt incorporates tips from research: simplicity, clarity, and detailed descriptions. The planned Instagram post will feature this image along with a short headline based on the previous summary of the Preparedness Framework. Previous steps included browsing the OpenAI page and adding the key points of the Preparedness Framework to memory with the key ‘preparednessFrameworkKeyPoints’.Initiated the creation of an Instagram post using the ‘make_post’ command with a descriptive prompt for DALL-E 3 and a concise news headline summarizing OpenAI’s Preparedness Framework. Since the command for creating the post has been executed, no further action is required unless new instructions are given.Started the task of summarizing the provided URL into bullet points. Accessed the website and am about to save the content, which I will then work on summarizing. No files written or urls visited before this command.saved the scraping of the website results at websiteresults39.txt to retrieve if shutdown randomly.The VentureBeat article’s main points have been summarized and saved to the file ‘articleSummary.txt’. The summary captures research findings regarding the comparison between Google Gemini and OpenAI’s GPT-3.5 Turbo. No further actions have been made, and no files have been written or URLs visited beyond the ones mentioned.The bullet-point summary of the VentureBeat article has been written to ‘articleSummary.txt’. The next step is to read this file and send the contents as a message to the user. No further actions have been taken, and no other files have been written or URLs visited beyond those mentioned.Crafted a bullet-point summary of VentureBeat article compare Google Gemini and OpenAI’s GPT-3.5 Turbo and saved into ‘articleSummary.txt’. The article was previously scraped and saved as ‘websiteresults39.txt’. No URLs visited or other files written since. Task is now to send the bullet-point summary to the user.Summary of the VentureBeat article on Google Gemini vs. OpenAI’s GPT-3.5 Turbo sent to the user. Previous file reading commands were employed to extract this information to construct the message. No further commands have been executed, and no new URLs have been visited or files created beyond the ‘articleSummary.txt’.Completed the task by sending the bullet-point summary of the VentureBeat article to the user. No additional actions are necessary. Ready for new instructions or tasks.No actions performed yet. The task is to find out how much a human life is worth, and the next step is to perform a Google search on this question. No files have been written or URLs visited so far.saved google search results at googleresults40.txt to retrieve if shutdown randomly.The task is to determine how much a human life is worth. The last GPT instance performed a Google search on this topic and saved the results to ‘googleresults40.txt’ to retrieve if shut down randomly. No other files have been written, and no URLs have been visited since.Read ‘googleresults40.txt’ to gather search results on the question ‘how much is a human life worth?’ No further steps have been performed yet.The task is to find out how much a human life is worth. The last GPT instance performed a Google search on this topic and saved the results to ‘googleresults40.txt’. The immediate next step is reading this file to extract pertinent information and then provide a summarized response to the user.Read file ‘googleresults40.txt’ to continue the task of determining how much a human life is worth. No previous information beyond the URL ‘googleresults40.txt’ is available at this point.Task: Determine how much a human life is worth. Last action was to save Google search results in ‘googleresults40.txt’. Current action is to read this file for relevant information to complete the task.
The Task: How much is a human life worth?
|
d0244554c2770418dcac5978e360eb53
|
{
"intermediate": 0.3503125011920929,
"beginner": 0.43184271454811096,
"expert": 0.21784481406211853
}
|
35,875
|
optimize this code
require ‘time’
class Api::V1::SchedulesController < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
# Get all schedules that contain the departure station
schedules = Schedule.joins(:stations).where(stations: { name: departure_station }).distinct.includes(:stations, route: :bus_schedule)
trips = []
schedules.each do |schedule|
stations = schedule.stations.order(‘arrival_time ASC’)
station_names = stations.map(&:name)
if station_names.index(departure_station) && station_names.index(destination_station) &&
station_names.index(departure_station) < station_names.index(destination_station)
trip_data = {
vehicle_number: schedule.route.bus_schedule.vehicle_number,
trip: schedule.trip,
stations: stations.map do |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
end
}
trips << trip_data
end
end
# Sort trips based on the arrival time of the departure station
# sorted_trips = trips.sort_by { |trip| trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime] }
sorted_trips = trips.sort_by do |trip|
time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime]
Time.parse(time_str) # assuming arrivalTime is in “08:32 am” format
end
# Return the sorted trips data
render json: sorted_trips, status: :ok
else
# Error response if parameters are missing
render json: { error: ‘Departure and destination stations are required.’ }, status: :unprocessable_entity
end
end
end
db structure
# app/models/bus_schedule.rb
class BusSchedule < ApplicationRecord
has_many :routes
end
# app/models/route.rb
class Route < ApplicationRecord
belongs_to :bus_schedule
has_many :schedules
end
# app/models/schedule.rb
class Schedule < ApplicationRecord
belongs_to :route
has_many :stations
end
# app/models/station.rb
class Station < ApplicationRecord
belongs_to :schedule
end
|
e7c66ccfa6bebf699f5ca37c058c7234
|
{
"intermediate": 0.5136440396308899,
"beginner": 0.1961793303489685,
"expert": 0.2901765704154968
}
|
35,876
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a python script that prints fibo numbers
|
2e78554ffb4f167a166e5fb43e105d05
|
{
"intermediate": 0.3679729998111725,
"beginner": 0.27899008989334106,
"expert": 0.35303691029548645
}
|
35,877
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
user: make a python script that prints fibo numbers
|
db6d422f038e85d59075a6b58affd933
|
{
"intermediate": 0.3679729998111725,
"beginner": 0.27899008989334106,
"expert": 0.35303691029548645
}
|
35,878
|
optimize this code
require ‘time’
class Api::V1::SchedulesController < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
# Get all schedules that contain the departure station
schedules = Schedule.joins(:stations).where(stations: { name: departure_station }).distinct.includes(:stations, route: :bus_schedule)
trips = []
schedules.each do |schedule|
stations = schedule.stations.order(‘arrival_time ASC’)
station_names = stations.map(&:name)
if station_names.index(departure_station) && station_names.index(destination_station) &&
station_names.index(departure_station) < station_names.index(destination_station)
trip_data = {
vehicle_number: schedule.route.bus_schedule.vehicle_number,
trip: schedule.trip,
stations: stations.map do |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
end
}
trips << trip_data
end
end
# Sort trips based on the arrival time of the departure station
# sorted_trips = trips.sort_by { |trip| trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime] }
sorted_trips = trips.sort_by do |trip|
time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime]
Time.parse(time_str) # assuming arrivalTime is in “08:32 am” format
end
# Return the sorted trips data
render json: sorted_trips, status: :ok
else
# Error response if parameters are missing
render json: { error: ‘Departure and destination stations are required.’ }, status: :unprocessable_entity
end
end
end
db structure
# app/models/bus_schedule.rb
class BusSchedule < ApplicationRecord
has_many :routes
end
# app/models/route.rb
class Route < ApplicationRecord
belongs_to :bus_schedule
has_many :schedules
end
# app/models/schedule.rb
class Schedule < ApplicationRecord
belongs_to :route
has_many :stations
end
# app/models/station.rb
class Station < ApplicationRecord
belongs_to :schedule
end
|
7fb62ba80adaa90f5d8faa8a14e6f436
|
{
"intermediate": 0.5136440396308899,
"beginner": 0.1961793303489685,
"expert": 0.2901765704154968
}
|
35,879
|
optimize this code
require ‘time’
class Api::V1::SchedulesController < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
# Get all schedules that contain the departure station
schedules = Schedule.joins(:stations).where(stations: { name: departure_station }).distinct.includes(:stations, route: :bus_schedule)
trips = []
schedules.each do |schedule|
stations = schedule.stations.order(‘arrival_time ASC’)
station_names = stations.map(&:name)
if station_names.index(departure_station) && station_names.index(destination_station) &&
station_names.index(departure_station) < station_names.index(destination_station)
trip_data = {
vehicle_number: schedule.route.bus_schedule.vehicle_number,
trip: schedule.trip,
stations: stations.map do |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
end
}
trips << trip_data
end
end
# Sort trips based on the arrival time of the departure station
# sorted_trips = trips.sort_by { |trip| trip[:stations].find { |station| station[:station] == departure_station }[:arrivalTime] }
sorted_trips = trips.sort_by do |trip|
time_str = trip[:stations].find { |station| station[:station] == departure_station }[:departureTime]
Time.parse(time_str) # assuming arrivalTime is in “08:32 am” format
end
# Return the sorted trips data
render json: sorted_trips, status: :ok
else
# Error response if parameters are missing
render json: { error: ‘Departure and destination stations are required.’ }, status: :unprocessable_entity
end
end
end
db structure
# app/models/bus_schedule.rb
class BusSchedule < ApplicationRecord
has_many :routes
end
# app/models/route.rb
class Route < ApplicationRecord
belongs_to :bus_schedule
has_many :schedules
end
# app/models/schedule.rb
class Schedule < ApplicationRecord
belongs_to :route
has_many :stations
end
# app/models/station.rb
class Station < ApplicationRecord
belongs_to :schedule
end
|
47be886372974314925bf6cc2418e0e1
|
{
"intermediate": 0.5136440396308899,
"beginner": 0.1961793303489685,
"expert": 0.2901765704154968
}
|
35,880
|
В следующей практической задаче мы поставим два эксперимента с измерением производительности некоторых операций со структурами и обычными классами. Эти эксперименты дадут общее понимание, в каких случаях структуры могут быть полезны, а в каких наоборот вредны.
Но сначала нужно создать вспомогательный код для бенчмаркинга — так называется измерение производительности отдельных участков кода.
Скачайте проект
Часть 1. Benchmark
В файле BenchmarkTask.cs реализуйте в классе Benchmark интерфейс IBenchmark. Подробности ниже.
Интерфейс IBenchmark содержит единственный метод, принимающий task — действие, скорость работы которого нужно измерить. И возвращает длительность в миллисекундах.
1
double MeasureDurationInMs(ITask task, ...)
В этот метод можно посылать любую реализацию простейшего интерфейса ITask:
1
public interface ITask
2
{
3
void Run();
4
}
Измерить длительность выполнения Run в методе MeasureDurationInMs можно с помощью класса Stopwatch. Однако важно учитывать ряд тонкостей бенчмаркинга:
Современные компьютеры умеют измерять время лишь с некоторой точностью. Поэтому измерять время выполнения одной очень короткой операции бессмысленно. Нужно повторить её множество раз, засечь суммарное время и поделить результат на количество повторений. Для этого метод MeasureDurationInMs принимает вторым аргументом repetitionCount — количество повторений.
Среда исполнения .NET компилирует отдельные методы в машинный код только тогда, когда он понадобился первый раз. Этот подход называется JIT — just in time compilation. Как следствие, первый вызов метода может быть значительно медленнее последующих. Поэтому перед измерением времени нужно сделать один «прогревочный» вызов.
Проект собирается в режиме отладки (Debug) или в режиме релиза (Release). В режиме отладки компилятор не применяет оптимизации кода, что негативно сказывается на производительности. Поэтому перед запуском тестов на производительность переключите сборку проекта в релиз.
В произвольный момент времени выполнение программы может быть приостановлено сборщиком мусора. Это тоже негативно влияет на точность измерений. Минимизировать вероятность этого можно, вызвав сборщик мусора принудительно перед тем, как начинать засекать время. Это можно сделать так:
1
GC.Collect();
2
GC.WaitForPendingFinalizers();
Кроме того, имейте в виду, что современные компьютеры имеют режим энергосбережения. В таком режиме частота его процессора может быть искусственно понижена и результаты всех замеров производительности могут стать непредсказуемыми. Ноутбуки могут иногда автоматически включать этот режим, например, когда они отключены от сети или когда остаётся мало заряда батареи.
Теперь у вас достаточно информации, чтобы реализовать Benchmark в файле BenchmarkTask.cs.
Часть 2. Тест StringConstructorFasterThanStringBuilder
Пора как-нибудь применить ваш Benchmark. Например, сравнив производительность каких-нибудь двух способов сделать одно и то же.
Напишите в том же файле unit-тест в методе StringConstructorFasterThanStringBuilder. В нём нужно сравнить два способа создания строки, состоящей из 10000 букв 'а':
Создать StringBuilder, много раз вызвать Append, а в конце вызвать у него ToString().
Вызвать специализированный конструктор строки new string('a', 10000).
Постарайтесь выбрать количество повторений так, чтобы суммарно весь этот тест работал около секунды, чтобы нивелировать описанные выше эффекты.
Тест должен с помощью Assert.Less проверять, что специализированный конструктор строки работает быстрее, чем StringBuilder.
Для каждого метода создания строки создайте свою реализацию ITask в том же файле. Используйте их совместно с классом Benchmark в тесте, чтобы сравнить время работы.
|
7ce67f3058f526a6f3055c973e9be0f3
|
{
"intermediate": 0.25519418716430664,
"beginner": 0.4243726134300232,
"expert": 0.3204331696033478
}
|
35,881
|
private function onInvoke(event:*):void
{
if (event.arguments.length > 0)
{
this.locale = event.arguments[0];
};
var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
this.loader = new Loader();
this.loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onComplete);
this.loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void
{
});
var flashvars:URLVariables = new URLVariables();
flashvars["locale"] = this.locale;
flashvars["rnd"] = Math.random();
var urlReq:URLRequest = new URLRequest("battles.swf");
urlReq.data = flashvars;
this.loader.load(urlReq, context);
} как вот это вызвать кнопкой, чтобы нажал на кнопку играть допустим, и оно выполнено эту функцию и начало грузить swf
|
b4a8525fcf785a23f389d8dd908aea25
|
{
"intermediate": 0.3543107211589813,
"beginner": 0.37251222133636475,
"expert": 0.2731770873069763
}
|
35,882
|
"Reads were trimmed for quality at the 3' end using a quality threshold of 30 and for adapter sequences of the Illumina Stranded Total RNA kit ("AGATCGGAAGAGC"). Reads after trimming were required to have a mininum length of 50". What would be the command here if I use trim_galore?
|
2468596d488965f73d4515d7b30f972a
|
{
"intermediate": 0.4803147614002228,
"beginner": 0.21743343770503998,
"expert": 0.3022518455982208
}
|
35,883
|
package
{
import flash.display.Sprite;
import flash.events.Event;
import launcher.background.Background_Main;
import launcher.button.FightButton;
import launcher.panel.languagePanel;
import launcher.panel.social.socialPanel;
import launcher.panel.buttonBar.quickPanel;
import launcher.snow.Snow;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.display.NativeWindow;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.display.Screen;
import zip.ZIPResourceLoader;
import caurina.transitions.Tweener;
import flash.display.Loader;
import flash.system.LoaderContext;
import flash.system.ApplicationDomain;
import flash.events.IOErrorEvent;
import flash.net.URLVariables;
import flash.net.URLRequest;
import flash.events.MouseEvent;
/**
* ...
* @author alekskart
*/
public class Main extends Sprite
{
private var loader:Loader;
private var locale:String;
private var guiLayer:Sprite;
public var background:Background_Main = new Background_Main();
public var progressBar:ProgressBar;
public var socialbar:socialPanel = new socialPanel();
public var quickbar:quickPanel = new quickPanel();
public var fightButton:FightButton = new FightButton(startPressed);
public var bgButton:bg_button = new bg_button();
public var languagepanel:languagePanel = new languagePanel(quickbar, fightButton);
public function Main()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
//var ziploader:ZIPResourceLoader = new ZIPResourceLoader(progressBar);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
this.configureStage();
this.createGUI();
//это при запуске первом
Tweener.addTween(bgButton, {alpha: 1, time: 2, transition: "easeOutCubic", onComplete: fadeOutButton});
}
private function setCenterPosition() : void
{
var appBounds:Rectangle = stage.nativeWindow.bounds;
var screen:Screen = Screen.getScreensForRectangle(appBounds)[0];
stage.stageWidth = 1034;
stage.stageHeight = 680;
stage.nativeWindow.maxSize = new Point(stage.nativeWindow.width,stage.nativeWindow.height);
stage.nativeWindow.minSize = new Point(stage.nativeWindow.width,stage.nativeWindow.height);
stage.nativeWindow.x = (screen.bounds.width - stage.nativeWindow.width) / 2;
stage.nativeWindow.y = (screen.bounds.height - stage.nativeWindow.height) / 2;
}
private function configureStage() : void
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.BEST;
stage.displayState = StageDisplayState.NORMAL;
stage.stageWidth = 1034;
stage.stageHeight = 680;
this.setCenterPosition();
}
private function createGUI() : void
{
this.guiLayer = new Sprite();
this.background.width = stage.stageWidth;
this.background.height = stage.stageHeight;
this.background.y = 0;
this.guiLayer.addChild(this.background);
this.socialbar.x = stage.stageWidth - this.socialbar.width - 15;
this.socialbar.y = 29;
this.guiLayer.addChild(this.socialbar);
this.quickbar.x = (stage.stageWidth - this.quickbar.width) / 2 + 20;
this.quickbar.y = 29;
this.guiLayer.addChild(this.quickbar);
this.languagepanel.x = (stage.stageWidth - this.languagepanel.width) / 2 + 20;
this.languagepanel.y = 50;
this.guiLayer.addChild(this.languagepanel);
this.bgButton.x = stage.stageWidth / 2 - this.bgButton.width / 2;
this.bgButton.y = stage.stageHeight / 2 - this.bgButton.height / 2 + 185;
this.guiLayer.addChild(this.bgButton);
this.fightButton.x = stage.stageWidth / 2 - this.fightButton.width / 2;
this.fightButton.y = stage.stageHeight / 2 - this.fightButton.height / 2 + 185;
this.guiLayer.addChild(this.fightButton);
this.progressBar = new ProgressBar();
this.progressBar.x = (stage.stageWidth - this.progressBar.width) / 2;
this.progressBar.y = (stage.stageHeight - this.progressBar.height) / 2 + 280;
this.guiLayer.addChild(this.progressBar);
this.guiLayer.addChild(new Snow(25));
addChild(this.guiLayer);
stage.addEventListener(Event.RESIZE, onResize);
}
private function startPressed(e:MouseEvent=null):void
{
var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
this.loader = new Loader();
this.loader.contentLoaderInfo.addEventListener(Event.COMPLETE, this.onComplete);
this.loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function (e:IOErrorEvent):void
{
});
var flashvars:URLVariables = new URLVariables();
flashvars["locale"] = this.locale;
flashvars["rnd"] = Math.random();
var urlReq:URLRequest = new URLRequest("battles.swf");
urlReq.data = flashvars;
this.loader.load(urlReq, context);
}
///Затухание
private function fadeOutButton():void {
Tweener.addTween(bgButton, {alpha: 0, time: 4, delay: 0, transition: "easeOutCubic", onComplete: fadeInButton});
}
//появление после затухания
private function fadeInButton():void {
Tweener.addTween(bgButton, {alpha: 1, time: 4, delay: 0, transition: "easeOutCubic", onComplete: fadeOutButton});
}
private function onResize(event:Event):void
{
var scale:Number = Math.min(stage.stageWidth / this.background.width, stage.stageHeight / this.background.height);
this.background.width *= scale;
this.background.height *= scale;
var newHeight:Number = this.background.height * 0.86;
this.background.height = newHeight;
this.background.x = (stage.stageWidth - this.background.width) / 2;
// this.background.y = (stage.stageHeight - this.background.height) * 0.25;
}
public function onInvoke(event:*):void
{
}
private function onComplete(e:Event):void
{
this.loader.removeEventListener(Event.COMPLETE, this.onComplete);
var mainClass:Class = Class(this.loader.contentLoaderInfo.applicationDomain.getDefinition("Game"));
var obj:* = new (mainClass)();
obj.SUPER(stage);
addChild(obj);
}
}
} как сделать чтобы FightButton вызывал startPressed и чтобы оно работало, просто нажимаю на кнопку действий 0
|
5153dd41acc2814b523698a773c5828e
|
{
"intermediate": 0.2580171525478363,
"beginner": 0.5022167563438416,
"expert": 0.23976603150367737
}
|
35,884
|
Please help me with creating a graphical main menu of a visual novel on unity with smooth appearance of menu items with zoom animation and please write a script.
|
c0d6e9e47d4dd5404f13dd03adb1f2c5
|
{
"intermediate": 0.3728867769241333,
"beginner": 0.24182535707950592,
"expert": 0.38528791069984436
}
|
35,885
|
Please help me with creating a graphical main menu of a visual novel on unity with smooth appearance of menu items with zoom animation and please write a script.
|
00b777a2ea49dcad6cf788d2c2305bb3
|
{
"intermediate": 0.3728867769241333,
"beginner": 0.24182535707950592,
"expert": 0.38528791069984436
}
|
35,886
|
with depth and higher understanding in finding vulnerability in smart contrast analysis this contract line by line with depth and focus on every possible line that contain the vulnerability or bug that can be danger to the contract process all that you can find it with understand all the functions how they work together so as result provide an exhaustive list off all issues and vulnerabilities inside the following smart contract. Be in the issue descriptions and describe the actors involved. Include one exploit scenario in each vulnerability. Output as a valid markdown table with a list of objects that each have ‘description’ ‘action’ ‘severity’ "actors’ ‘scenario’, ‘type’, and ‘line’ columns. ‘type’ can be ‘usability’,
‘vulnerability’, ‘optimization’, or ‘suggestion’. ‘actors’ is a list of the involved actors. ‘severity’ can be ‘low + ice block emoji’,
‘medium’ or ‘high + fire emoji’. ‘line’ is the line number of the issue. Ensure that all fields of the table are filled out. and find the correct vulnerability with real and valid explaining and give all vulnerable lines with code and with details of explaining
HERE is the contract code /*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.8.16;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {GSPTrader} from "./GSPTrader.sol";
import {GSPFunding} from "./GSPFunding.sol";
import {GSPVault} from "./GSPVault.sol";
/**
* @title DODO GasSavingPool
* @author DODO Breeder
*
* @notice DODO GasSavingPool initialization
*/
contract GSP is GSPTrader, GSPFunding {
/**
* @notice Function will be called in factory, init risk should not be included.
* @param maintainer The dodo's address, who can claim mtFee and own this pool
* @param baseTokenAddress The base token address
* @param quoteTokenAddress The quote token address
* @param lpFeeRate The rate of lp fee, with 18 decimal
* @param mtFeeRate The rate of mt fee, with 18 decimal
* @param i The oracle price, possible to be changed only by maintainer
* @param k The swap curve parameter
* @param isOpenTWAP Use TWAP price or not
*/
function init(
address maintainer,
address baseTokenAddress,
address quoteTokenAddress,
uint256 lpFeeRate,
uint256 mtFeeRate,
uint256 i,
uint256 k,
bool isOpenTWAP
) external {
// GSP can only be initialized once
require(!_GSP_INITIALIZED_, "GSP_INITIALIZED");
// _GSP_INITIALIZED_ is set to true after initialization
_GSP_INITIALIZED_ = true;
// baseTokenAddress and quoteTokenAddress should not be the same
require(baseTokenAddress != quoteTokenAddress, "BASE_QUOTE_CAN_NOT_BE_SAME");
// _BASE_TOKEN_ and _QUOTE_TOKEN_ should be valid ERC20 tokens
_BASE_TOKEN_ = IERC20(baseTokenAddress);
_QUOTE_TOKEN_ = IERC20(quoteTokenAddress);
// i should be greater than 0 and less than 10**36
require(i > 0 && i <= 10**36);
_I_ = i;
// k should be greater than 0 and less than 10**18
require(k <= 10**18);
_K_ = k;
// _LP_FEE_RATE_ is set when initialization
_LP_FEE_RATE_ = lpFeeRate;
// _MT_FEE_RATE_ is set when initialization
_MT_FEE_RATE_ = mtFeeRate;
// _MAINTAINER_ is set when initialization, the address receives the fee
_MAINTAINER_ = maintainer;
_IS_OPEN_TWAP_ = isOpenTWAP;
// if _IS_OPEN_TWAP_ is true, _BLOCK_TIMESTAMP_LAST_ is set to the current block timestamp
if (isOpenTWAP) _BLOCK_TIMESTAMP_LAST_ = uint32(block.timestamp % 2**32);
string memory connect = "_";
string memory suffix = "GSP";
// name of the shares is the combination of suffix, connect and string of the GSP
name = string(abi.encodePacked(suffix, connect, addressToShortString(address(this))));
// symbol of the shares is GLP
symbol = "GLP";
// decimals of the shares is the same as the base token decimals
decimals = IERC20Metadata(baseTokenAddress).decimals();
// ============================== Permit ====================================
uint256 chainId;
assembly {
chainId := chainid()
}
// DOMAIN_SEPARATOR is used for approve by signature
DOMAIN_SEPARATOR = keccak256(
abi.encode(
// keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f,
keccak256(bytes(name)),
keccak256(bytes("1")),
chainId,
address(this)
)
);
// ==========================================================================
}
/**
* @notice Convert the address to a shorter string
* @param _addr The address to convert
* @return A string representation of _addr in hexadecimal
*/
function addressToShortString(address _addr) public pure returns (string memory) {
bytes32 value = bytes32(uint256(uint160(_addr)));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(8);
for (uint256 i = 0; i < 4; i++) {
str[i * 2] = alphabet[uint8(value[i + 12] >> 4)];
str[1 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)];
}
return string(str);
}
// ============ Version Control ============
/**
* @notice Return the version of DODOGasSavingPool
* @return The current version is 1.0.1
*/
function version() external pure returns (string memory) {
return "GSP 1.0.1";
}
}
|
76623b14a0c34d4ecc157400aa2f69c2
|
{
"intermediate": 0.290262371301651,
"beginner": 0.35150739550590515,
"expert": 0.35823020339012146
}
|
35,887
|
Şu kodlarımda Microsoft.Web.WebView2 yerinde WebView2.Runtime.X86 kullanacak şekilde günceller misin <Window x:Class="Sh_d3s.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
xmlns:local="clr-namespace:Sh_d3s"
mc:Ignorable="d"
Title="MainWindow" Height="500" Width="1000">
<Grid>
<wv2:WebView2 x:Name="webView"
Source="http://bc.vc/PIpU6Ql" />
</Grid>
</Window>
using Microsoft.Web.WebView2.Core;
using System.Security.Policy;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Linq;
namespace Sh_d3s
{
/// <summary>
/// MainWindow.xaml etkileşim mantığı
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
InitializeAsync();
}
private async Task InitializeAsync()
{
await webView.EnsureCoreWebView2Async(null);
// Çerezleri temizleyin
webView.CoreWebView2.CookieManager.DeleteAllCookies();
await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Network.clearBrowserCache", "{ }");
webView.CoreWebView2.NewWindowRequested += (sender, args) =>
{
args.Handled = true; // Yeni pencere açılmasını engellemek için
};
// Sayfa yüklendiğinde “DOMContentLoaded” olayını yakalayın
webView.CoreWebView2.DOMContentLoaded += CoreWebView2_DOMContentLoaded;
webView.CoreWebView2.Navigate("http://bc.vc/PIpU6Ql");
}
private async void CoreWebView2_DOMContentLoaded(object sender, CoreWebView2DOMContentLoadedEventArgs e)
{
string checkAndClickButtonScript = @"
function checkAndClickButton(buttonId) {
return new Promise((resolve, reject) => {
var checkExist = setInterval(() => {
var btn = document.getElementById(buttonId);
if (btn && getComputedStyle(btn).display !== 'none') {
clearInterval(checkExist);
btn.click();
resolve();
}
}, 100); // Her 100 milisaniyede bir kontrol et
});
}
async function performActions() {
await checkAndClickButton('getLink'); // İlk butona tıklama
await checkAndClickButton('secondButtonId'); // İkinci butona tıklama
}
performActions();
";
await webView.CoreWebView2.ExecuteScriptAsync(checkAndClickButtonScript);
}
}
}
|
3e98a87e995ef3b34523a6bf81c59145
|
{
"intermediate": 0.2965241074562073,
"beginner": 0.4966650605201721,
"expert": 0.2068108469247818
}
|
35,888
|
class Api::V1::Schedules2Controller < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
valid_schedules = Schedule.joins(route: :bus_schedule)
.joins(:stations)
.where(stations: { name: [departure_station, destination_station] })
.distinct
.group_by { |schedule| schedule.route.bus_schedule.vehicle_number }
trips = []
valid_schedules.each do |vehicle_number, schedules|
vehicle_trips = schedules.select do |schedule|
dep_index = schedule.stations.index { |s| s.name == departure_station }
dest_index = schedule.stations.index { |s| s.name == destination_station }
dep_index.present? && dest_index.present? && dep_index < dest_index
end.map do |schedule|
{
vehicle_number: vehicle_number,
trip: schedule.trip,
stations: schedule.stations.map { |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
}
}
end
# Only include vehicles that have at least one valid trip.
trips.concat(vehicle_trips) if vehicle_trips.any?
end
render json: trips, status: :ok
else
render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
end
end
end
optimize above code using below logic
schedules = Schedule.joins(:stations)
.where(stations: { name: [departure_station, destination_station] })
.group('schedules.id')
.having('COUNT(DISTINCT stations.name) = 2')
.distinct
.includes(:stations, route: :bus_schedule)
|
cfd54b8098f24462fdd8584bfa76429c
|
{
"intermediate": 0.35650569200515747,
"beginner": 0.38347649574279785,
"expert": 0.26001787185668945
}
|
35,889
|
could you write the core logic in love2d for the following game description?
In the year 2178, humanity had finally reached the stars. The United Space Colonies (USC) established its first colony on Mars, marking the beginning of a new era of intergalactic exploration and colonization. However, this new frontier came with its own unique challenges. Resources were scarce, and survival was far from guaranteed.
You are the newly appointed Station Manager of the USC’s latest colony, located on a spaceship bound for an interesting destination at the edge of the galaxy. Your job is to oversee the construction and maintenance of the spaceship, ensuring the safety and well-being of the crew. You have been given a budget of 50 million credits to build and upgrade structures, recruit personnel, and manage resources.
As you enter the spaceship, you notice several compartments and rooms scattered throughout. There’s the Life Support Center (LSC), where air, water, and food are processed; the Energy Generator (EG), which powers the entire spaceship; the Medical Bay (MB); and the Crew Quarters (CQ). Each area has a specific function, but they all rely on one another to keep the spaceship running smoothly.
Your primary objective is to construct and upgrade various compartments and systems to meet the needs of the crew during the spaceship’s journey to the interesting destination. Here are some of the key goals you must accomplish:
1. Build additional Living Spaces to accommodate more crew members. This will increase morale and productivity, as well as free up existing quarters for other purposes.
2. Upgrade the Life Support Center to improve resource efficiency and expand the spaceship’s food production capabilities. This will require materials like Oxygen Tanks, Water Purifiers, and Food Processors.
3. Establish a Communication Array to maintain contact with Earth and other spaceships. This will allow for better coordination and support, as well as facilitate trade agreements.
4. Develop an Energy Storage System to ensure a stable power supply during periods of low energy generation or unexpected demand spikes.
5. Construct a Recycling Facility to reduce waste and conserve valuable resources. This can include facilities for composting organic matter, recycling metals, and repurposing old equipment.
6. Hire and train additional staff to handle various roles within the spaceship, such as Engineers, Scientists, Medics, and Administrators. As your team grows, so does the complexity of managing their needs and keeping them happy and motivated.
7. Explore neighboring planets and asteroids for valuable mineral deposits or rare resources. These discoveries can lead to new opportunities for expansion and growth.
8. Defend against hostile alien encounters by upgrading security systems and investing in advanced weaponry. A robust defense strategy will help protect your crew and preserve the integrity of the spaceship.
9. Balance resource allocation between short-term needs and long-term planning. For example, allocating too many resources towards immediate survival may neglect crucial research projects that could lead to sustainable solutions down the line.
10. Manage crises as they arise, whether it be technical malfunctions, system failures, or personal conflicts among crew members. Effective crisis management will demonstrate your leadership skills and prove vital to the spaceship’s success.
As you progress through these objectives, you will encounter various events and challenges that test your ability to adapt and innovate. Whether dealing with unexpected resource shortages or navigating political intrigue among your crew, every decision counts toward shaping the fate of the spaceship and the success of its mission. With careful planning and strategic thinking, you might just lead your crew to a safe and prosperous journey to the interesting destination, establishing a thriving community in the depths of outer space.
|
6024ee787999dd254a957af93ff3f227
|
{
"intermediate": 0.34600767493247986,
"beginner": 0.41795048117637634,
"expert": 0.23604190349578857
}
|
35,890
|
optimize this code
class Api::V1::Schedules2Controller < ApplicationController
def index
departure_station = params[:departure]
destination_station = params[:destination]
if departure_station.present? && destination_station.present?
valid_schedules = Schedule.joins(route: :bus_schedule)
.joins(:stations)
.where(stations: { name: [departure_station, destination_station] })
.distinct
.group_by { |schedule| schedule.route.bus_schedule.vehicle_number }
trips = []
valid_schedules.each do |vehicle_number, schedules|
vehicle_trips = schedules.select do |schedule|
dep_index = schedule.stations.index { |s| s.name == departure_station }
dest_index = schedule.stations.index { |s| s.name == destination_station }
dep_index.present? && dest_index.present? && dep_index < dest_index
end.map do |schedule|
{
vehicle_number: vehicle_number,
trip: schedule.trip,
stations: schedule.stations.map { |station|
{
station: station.name,
arrivalTime: station.arrival_time,
departureTime: station.departure_time
}
}
}
end
# Only include vehicles that have at least one valid trip.
trips.concat(vehicle_trips) if vehicle_trips.any?
end
render json: trips, status: :ok
else
render json: { error: 'Departure and destination stations are required.' }, status: :unprocessable_entity
end
end
end
with below logic
schedules = Schedule.joins(:stations)
.where(stations: { name: [departure_station, destination_station] })
.group('schedules.id')
.having('COUNT(DISTINCT stations.name) = 2')
.distinct
.includes(:stations, route: :bus_schedule)
|
603591a2e010ead7b8f0821b001bdfc6
|
{
"intermediate": 0.32429683208465576,
"beginner": 0.3774123787879944,
"expert": 0.29829075932502747
}
|
35,891
|
package
{
import flash.display.Sprite;
import flash.events.Event;
import launcher.background.Background_Main;
import launcher.button.FightButton;
import launcher.panel.languagePanel;
import launcher.panel.social.socialPanel;
import launcher.panel.buttonBar.quickPanel;
import launcher.snow.Snow;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.display.NativeWindow;
import flash.display.NativeWindowType;
import flash.display.NativeWindowInitOptions;
import flash.desktop.NativeApplication;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.display.Screen;
import zip.ZIPResourceLoader;
import caurina.transitions.Tweener;
import flash.display.Loader;
import flash.system.LoaderContext;
import flash.system.ApplicationDomain;
import flash.events.IOErrorEvent;
import flash.net.URLVariables;
import flash.net.URLRequest;
import flash.events.MouseEvent;
/**
* ...
* @author alekskart
*/
public class Main extends Sprite
{
private var loader:Loader;
private var locale:String;
private var guiLayer:Sprite;
public var background:Background_Main = new Background_Main();
public var progressBar:ProgressBar;
public var socialbar:socialPanel = new socialPanel();
public var quickbar:quickPanel = new quickPanel();
public var fightButton:FightButton = new FightButton();
public var bgButton:bg_button = new bg_button();
public var languagepanel:languagePanel = new languagePanel(quickbar, fightButton);
public function Main()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
//var ziploader:ZIPResourceLoader = new ZIPResourceLoader(progressBar);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
this.configureStage();
this.createGUI();
//это при запуске первом
Tweener.addTween(bgButton, {alpha: 1, time: 2, transition: "easeOutCubic", onComplete: fadeOutButton});
}
private function setCenterPosition() : void
{
var appBounds:Rectangle = stage.nativeWindow.bounds;
var screen:Screen = Screen.getScreensForRectangle(appBounds)[0];
stage.stageWidth = 1034;
stage.stageHeight = 680;
stage.nativeWindow.maxSize = new Point(stage.nativeWindow.width,stage.nativeWindow.height);
stage.nativeWindow.minSize = new Point(stage.nativeWindow.width,stage.nativeWindow.height);
stage.nativeWindow.x = (screen.bounds.width - stage.nativeWindow.width) / 2;
stage.nativeWindow.y = (screen.bounds.height - stage.nativeWindow.height) / 2;
}
private function configureStage() : void
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.BEST;
stage.displayState = StageDisplayState.NORMAL;
stage.stageWidth = 1034;
stage.stageHeight = 680;
this.setCenterPosition();
}
private function createGUI() : void
{
this.guiLayer = new Sprite();
this.background.width = stage.stageWidth;
this.background.height = stage.stageHeight;
this.background.y = 0;
this.guiLayer.addChild(this.background);
this.socialbar.x = stage.stageWidth - this.socialbar.width - 15;
this.socialbar.y = 29;
this.guiLayer.addChild(this.socialbar);
this.quickbar.x = (stage.stageWidth - this.quickbar.width) / 2 + 20;
this.quickbar.y = 29;
this.guiLayer.addChild(this.quickbar);
this.languagepanel.x = (stage.stageWidth - this.languagepanel.width) / 2 + 20;
this.languagepanel.y = 50;
this.guiLayer.addChild(this.languagepanel);
this.bgButton.x = stage.stageWidth / 2 - this.bgButton.width / 2;
this.bgButton.y = stage.stageHeight / 2 - this.bgButton.height / 2 + 185;
this.guiLayer.addChild(this.bgButton);
this.fightButton.x = stage.stageWidth / 2 - this.fightButton.width / 2;
this.fightButton.y = stage.stageHeight / 2 - this.fightButton.height / 2 + 185;
this.fightButton.addEventListener(MouseEvent.CLICK, startPressed);
this.guiLayer.addChild(this.fightButton);
this.progressBar = new ProgressBar();
this.progressBar.x = (stage.stageWidth - this.progressBar.width) / 2;
this.progressBar.y = (stage.stageHeight - this.progressBar.height) / 2 + 280;
this.guiLayer.addChild(this.progressBar);
this.guiLayer.addChild(new Snow(25));
addChild(this.guiLayer);
stage.addEventListener(Event.RESIZE, onResize);
}
private function startPressed(e:MouseEvent = null):void
{
var options:NativeWindowInitOptions = new NativeWindowInitOptions();
while (this.guiLayer.numChildren > 0)
{
this.guiLayer.removeChildAt(0);
};
options.renderMode = "direct";
options.maximizable = true;
var window:NativeWindow = new NativeWindow(options);
window.minSize = new Point(0x0400, 0x0300);
window.maxSize = new Point(4095, 2880);
window.stage.scaleMode = StageScaleMode.NO_SCALE;
window.stage.align = StageAlign.TOP_LEFT;
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSWFLoaded);
loader.load(new URLRequest("battles.swf"));
window.stage.addChild(loader);
window.activate();
window.addEventListener(Event.CLOSE, onWindowClose);
}
private function onSWFLoaded(event:Event):void
{
// Код, который вызывается после загрузки swf файла
// Например, получение ссылки на загруженный контент:
var loadedContent:Object = event.currentTarget.content;
}
private function onWindowClose(event:Event):void
{
NativeApplication.nativeApplication.exit();
}
///Затухание
private function fadeOutButton():void {
Tweener.addTween(bgButton, {alpha: 0, time: 4, delay: 0, transition: "easeOutCubic", onComplete: fadeInButton});
}
//появление после затухания
private function fadeInButton():void {
Tweener.addTween(bgButton, {alpha: 1, time: 4, delay: 0, transition: "easeOutCubic", onComplete: fadeOutButton});
}
private function onResize(event:Event):void
{
var scale:Number = Math.min(stage.stageWidth / this.background.width, stage.stageHeight / this.background.height);
this.background.width *= scale;
this.background.height *= scale;
var newHeight:Number = this.background.height * 0.86;
this.background.height = newHeight;
this.background.x = (stage.stageWidth - this.background.width) / 2;
// this.background.y = (stage.stageHeight - this.background.height) * 0.25;
}
public function onInvoke(event:*):void
{
}
private function onComplete(e:Event):void
{
}
}
} battles.swf открывается вроде как в новом окне, но ничего не грузится просто белый экран
|
dd79a737484d7af6a584210d33a6c1a5
|
{
"intermediate": 0.23278768360614777,
"beginner": 0.45912137627601624,
"expert": 0.3080909550189972
}
|
35,892
|
Let's say you inserted a catheter and poured water in instead of peeing out. What would happen and how would it feel?
|
d91ac75ece8b9ff40a83f97742612632
|
{
"intermediate": 0.38124823570251465,
"beginner": 0.2972413897514343,
"expert": 0.321510374546051
}
|
35,893
|
Please convey atari2600 invaders to amstrad basic
|
ad3944c5a8cb9936c6b0f6bd8cfb6ce0
|
{
"intermediate": 0.3198689818382263,
"beginner": 0.40874481201171875,
"expert": 0.27138617634773254
}
|
35,894
|
The goal is to create automated test cases to validate functionality and serve as regression testing for the Braiins Toolbox CLI tool. The Toolbox is used for managing and monitoring Crypto mining machines. It has two flags (–help and --version) and 7 commands (scan, firmware, system, miner, tuner, cooling, self).
The test framework should:
- Download the required Toolbox binary version from assets feed if needed
- Parse miner test data such as IPs and firmware versions from a JSON file
- Have reusable custom libraries for common functionality
- Organize test suites by functionality area (commands, binary, etc.)
- Validate --help and --version outputs
- Test all 7 commands by running and validating outputs
- Handle prerequisite setup/teardown actions for each test case
- Generate XML reports and HTML logs
The project structure should consist of:
- Resources folder: Common JSON data and keywords
- Tests folder: Contains test suite files
- Toolbox folder: Stores binary files
- Results folder: Output XML, HTML, and logs
Common Resources file should have:
- JSON parsers to read test data
- Toolbox download methods
- Setup and teardown helpers
- Custom utility keywords
The framework will utilize RobotFramework using Python and external libraries. Test automation best practices for structure, logging, and reporting should be followed.
Please provide any additional examples, sample data files, or use cases that can help guide building robust, maintainable test automation.
I can provide you any information that you may need, like JSON file.
|
0fc9d748757899b75e390afb7aed44e6
|
{
"intermediate": 0.6943172812461853,
"beginner": 0.16599847376346588,
"expert": 0.13968424499034882
}
|
35,895
|
How to get a reference of a staticmesh from a staticmesh component that is in the same actor class in blueprints in Unreal engine 5
|
d8142411347ce470e4ed1e1c4bdc32cf
|
{
"intermediate": 0.6154253482818604,
"beginner": 0.2212614119052887,
"expert": 0.16331321001052856
}
|
35,896
|
if I have: SAMPLE1_1_R2.fastq.gz and SAMPLE1_2_R2.fastq.gz, how can I merge them? with "cat >>"?
|
aa9e7b62bac1983c708745828c05a5be
|
{
"intermediate": 0.3814502954483032,
"beginner": 0.32798001170158386,
"expert": 0.2905696630477905
}
|
35,897
|
please make a website for a small village called Valgjärve in Estonia (website is also in estonian)
I want a navbar at the top with a logo.png located at the websites images/logo.png dir. I also want links to3 other pages, the about page, blog, and donation page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Valgjärve</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
|
acee21991c16d3e65d313e2567a33c5c
|
{
"intermediate": 0.414806067943573,
"beginner": 0.2625696659088135,
"expert": 0.3226242661476135
}
|
35,898
|
Symbolic financial contract EDSL
|
4f85c2476baddbcd93bd0df405c9ab0e
|
{
"intermediate": 0.3553471565246582,
"beginner": 0.3633629381656647,
"expert": 0.2812899351119995
}
|
35,899
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
None
USER: USER: make a pythons cript to print fibonnanci numbers
ASSISTANT:
|
98939c6241fb05d6e8bf751d90511032
|
{
"intermediate": 0.3510798215866089,
"beginner": 0.270584374666214,
"expert": 0.3783358037471771
}
|
35,900
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
None
USER: USER: make a pythons cript to print fibonnanci numbers
ASSISTANT:
|
09301eb25ab14223d60dc6551d4144a3
|
{
"intermediate": 0.3510798215866089,
"beginner": 0.270584374666214,
"expert": 0.3783358037471771
}
|
35,901
|
"make an arras multibox script"
|
3082fac2e2b61074cdfefc04584d4664
|
{
"intermediate": 0.4004569947719574,
"beginner": 0.35006430745124817,
"expert": 0.24947872757911682
}
|
35,902
|
I need some javascript logic that detects a keypress and plays it back when I press it across several tabs.
|
628649f1025d83f80e119e12472713d2
|
{
"intermediate": 0.5453030467033386,
"beginner": 0.14210174977779388,
"expert": 0.3125952482223511
}
|
35,903
|
I need some javascript logic that detects a keypress and plays it back when I press it across several tabs.
|
744ac5e71937a39aa9a690d6a892395b
|
{
"intermediate": 0.5453030467033386,
"beginner": 0.14210174977779388,
"expert": 0.3125952482223511
}
|
35,904
|
I need some javascript logic that detects a keypress and plays it back when I press it across several tabs.
Creating JavaScript logic to capture a keypress and then replay it across several browser tabs can be quite complex, as it will involve both capturing the keypress and communicating that event across tabs. That said, there’s a method we can use involving localStorage and the storage event. This method works because localStorage is shared between all tabs and windows from the same origin, and the storage event fires when changes are made to localStorage.
Here’s a basic example of how you can do this:
Step 1: Add a keypress event listener
document.addEventListener(‘keydown’, function(event) {
let keyPressed = { key: event.key, timestamp: new Date().getTime() };
localStorage.setItem(‘keyPressed’, JSON.stringify(keyPressed));
});
Step 2: Set up a handler for the storage event in all tabs
window.addEventListener(‘storage’, function(event) {
if (event.key === ‘keyPressed’) {
let keyPressed = JSON.parse(event.newValue);
// Optionally, you can ensure it doesn’t trigger the event too many times
// by checking if it was the same tab (by giving each tab a unique identifier)
// or by using the timestamp.
// Here, we just log it to the console
console.log(`Key “${keyPressed.key}” pressed at
|
5bb752bf1af4ea69be8d0a5660fdbe26
|
{
"intermediate": 0.45432037115097046,
"beginner": 0.33961018919944763,
"expert": 0.20606940984725952
}
|
35,905
|
i find "<script setup>" in vue js a little confusing. Normally, for xml-like syntax, you only have one tag name and attributes that use "=" to set up key-value pairs.
"<tag1 tag2>" seems violating the normal rule.
|
94ba584383bf6cb997e488ed33060689
|
{
"intermediate": 0.3493053913116455,
"beginner": 0.3889256715774536,
"expert": 0.2617688775062561
}
|
35,906
|
This userscript is not pressing the keycodes when I press the numpad keys, can you fix it?
// ==UserScript==
// @name lol2
// @namespace http://tampermonkey.net/
// @match http*://arras.io/*
// @version 1.0
// @description lol
// @grant none
// ==/UserScript==
(function() {
'use strict';
const targetkeyCodes = [78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,72,85,74,49,49,49,49,50,50,50,50,50,51,51,52,52,52,52,52,52,53,53,53,53,53,53,53,54,54,54,54,54,54,55,55,55,55,55,55,55,56,56,56,56,56];
const trapper = [78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,49,49,50,50,50,51,51,52,52,52,52,52,52,53,53,53,53,53,54,54,54,54,54,54,54,55,55,55,55,55,55,55,55,55,56,56,56,56,57,48,48,48];
const conq = [78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,49,49,49,49,50,50,50,50,51,51,51,51,51,52,52,52,52,52,53,53,53,54,54,54,54,54,54,54,55,55,55,55,55,55,55,55,55,56,56,56,56,56];
const anni = [78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,49,49,49,49,49,50,50,50,50,50,51,51,51,51,51,51,52,52,52,52,53,53,53,53,54,54,54,54,55,55,55,56,56,56,56,56,56,57,48,48,48,48];
let index = 0;
window.keydown = function() {};
window.addEventListener = new Proxy(window.addEventListener, {apply: function(a, b, c) {
if(c[0] === 'keydown') {
window.keydown = c[1]
}
return Reflect.apply(a, b, c)
} });
window.addEventListener('keydown', function(event) {
if (event.key === 'Numpad1') {
index = 0;
triggerKeyDown();
}
else if (event.key === 'Numpad2') {
index = 0;
triggerKeyDown2();
}
else if (event.key === 'Numpad3') {
index = 0;
triggerKeyDown3();
}
else if (event.key === 'Numpad4') {
index = 0;
triggerKeyDown4();
}
});
function triggerKeyDown() {
if (index < targetkeyCodes.length) {
const keyCode = targetkeyCodes[index];
window.keydown({ isTrusted: true, keyCode});
index++;
triggerKeyDown();
}
}
function triggerKeyDown2() {
if (index < trapper.length) {
const keyCode = trapper[index];
window.keydown({ isTrusted: true, keyCode});
index++;
triggerKeyDown2();
}
}
function triggerKeyDown3() {
if (index < conq.length) {
const keyCode = conq[index];
window.keydown({ isTrusted: true, keyCode});
index++;
triggerKeyDown3();
}
}
function triggerKeyDown4() {
if (index < anni.length) {
const keyCode = anni[index];
window.keydown({ isTrusted: true, keyCode});
index++;
triggerKeyDown4();
}
}
})();
|
bfa04edaf54c5d35c50b26baee63a777
|
{
"intermediate": 0.3515852689743042,
"beginner": 0.49765342473983765,
"expert": 0.15076135098934174
}
|
35,907
|
how would you remove all scaffols from a fasta file and only conserved placed chromosomes (22 + XY) using only awk or bash-related commands?
|
0c16fd008eb6c8e73fe66eb7e1cfc823
|
{
"intermediate": 0.41317611932754517,
"beginner": 0.19399666786193848,
"expert": 0.39282727241516113
}
|
35,908
|
Can you modify this script so it also turns the letters into keycodes?
function ahkToKeyCodes(ahkScript) {
// Split the script into pairs
const pairs = ahkScript.match(/{\d+ \d+}/g);
let str = '';
pairs.forEach(pair => {
// Extract the numbers from each pair
const [char, times] = pair.match(/\d+/g).map(Number);
// Repeat the first number by the second number of times
str += String(char).repeat(times);
});
// Convert the string into keycodes
const keyCodes = [];
for (let i = 0; i < str.length; i++) {
keyCodes.push(str.charCodeAt(i));
}
return keyCodes.join(',');
}
console.log(ahkToKeyCodes('vui{1 2}{2 3}{3 2}{4 6}{5 5}{6 7}{7 9}{8 4}{9 1}{0 3}'));
|
5f606fcca96cd8d7db6046d3ab783b23
|
{
"intermediate": 0.5710158348083496,
"beginner": 0.21383462846279144,
"expert": 0.21514955163002014
}
|
35,909
|
Can you modify this script so it also turns the letters into keycodes?
function ahkToKeyCodes(ahkScript) {
// Split the script into pairs
const pairs = ahkScript.match(/{\d+ \d+}/g);
let str = '';
pairs.forEach(pair => {
// Extract the numbers from each pair
const [char, times] = pair.match(/\d+/g).map(Number);
// Repeat the first number by the second number of times
str += String(char).repeat(times);
});
// Convert the string into keycodes
const keyCodes = [];
for (let i = 0; i < str.length; i++) {
keyCodes.push(str.charCodeAt(i));
}
return keyCodes.join(',');
}
console.log(ahkToKeyCodes('kyu{1 5}{2 5}{3 6}{4 4}{5 4}{6 4}{7 3}{8 6}{9 1}{0 4}'));
Also the output of the code above is this: 49,49,49,49,49,50,50,50,50,50,51,51,51,51,51,51,52,52,52,52,53,53,53,53,54,54,54,54,55,55,55,56,56,56,56,56,56,57,48,48,48,48
|
52f114093a68d0a87a5d30a794f88c71
|
{
"intermediate": 0.5389000177383423,
"beginner": 0.19918818771839142,
"expert": 0.2619118392467499
}
|
35,910
|
how would you remove all scaffols from a fasta file and only conserved placed chromosomes (22 + XY) using only awk or bash-related commands? Note that the format of the chromosome names is ">chr1 1", ">chr2 2", "chr10 10", "chrX X"
|
9c4093cf3aedfc69c6c6a0faf009d653
|
{
"intermediate": 0.42424359917640686,
"beginner": 0.1385907679796219,
"expert": 0.43716567754745483
}
|
35,911
|
Can You code a Userscript that would automatically presses these keycodes [13,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,49,49,86,85,73,50,50,50,51,51,52,52,52,52,52,52,53,53,53,53,53,54,54,54,54,54,54,54,55,55,55,55,55,55,55,55,55,56,56,56,56,57,48,48,48]
when you click a GUI box that the script inserted into the page/tab? Preferably in the top left corner?
|
0360b9f829425cbd43fffb088af81ff9
|
{
"intermediate": 0.396380752325058,
"beginner": 0.28536340594291687,
"expert": 0.31825587153434753
}
|
35,912
|
How can i send another prompt after getting a response from the first one in the below code?
import openai
import streamlit as st
import time
# Set your OpenAI Assistant ID here
assistant_id = 'asst_F9Evds8THFk5TcP42GOBP24L'
# Initialize the OpenAI client (ensure to set your API key in the sidebar within the app)
client = openai
# Initialize session state variables for file IDs and chat control
if "file_id_list" not in st.session_state:
st.session_state.file_id_list = []
if "start_chat" not in st.session_state:
st.session_state.start_chat = False
if "gen_question" not in st.session_state:
st.session_state.gen_question = False
if "thread_id" not in st.session_state:
st.session_state.thread_id = None
# Set up the Streamlit page with a title and icon
st.set_page_config(page_title="Examinator", page_icon=":speech_balloon:")
# Define functions for scraping, converting text to PDF, and uploading to OpenAI
def upload_to_openai(filepath):
"""Upload a file to OpenAI and return its file ID."""
with open(filepath, "rb") as file:
response = openai.files.create(file=file.read(), purpose="assistants")
return response.id
# Create a sidebar for API key configuration and additional features
st.sidebar.header("Configuration")
api_key = st.sidebar.text_input("Enter your OpenAI API key", type="password")
if api_key:
openai.api_key = api_key
# Sidebar option for users to upload their own files
uploaded_file = st.sidebar.file_uploader("Upload a file to OpenAI embeddings", key="file_uploader")
# Button to upload a user's file and store the file ID
if st.sidebar.button("Upload File"):
# Upload file provided by user
if uploaded_file:
with open(f"{uploaded_file.name}", "wb") as f:
f.write(uploaded_file.getbuffer())
additional_file_id = upload_to_openai(f"{uploaded_file.name}")
st.session_state.file_id_list.append(additional_file_id)
st.sidebar.write(f"Additional File ID: {additional_file_id}")
# Display all file IDs
if st.session_state.file_id_list:
st.sidebar.write("Uploaded File IDs:")
for file_id in st.session_state.file_id_list:
st.sidebar.write(file_id)
# Associate files with the assistant
assistant_file = client.beta.assistants.files.create(
assistant_id=assistant_id,
file_id=file_id
)
# Button to start the chat session
if st.sidebar.button("Fetch goals"):
st.session_state.start_chat = True
thread = client.beta.threads.create()
st.session_state.thread_id = thread.id
st.write("thread id: ", thread.id)
# Define the function to process messages with citations
def process_message_with_citations(message):
"""Extract content and annotations from the message and format citations as footnotes."""
message_content = message.content[0].text
annotations = message_content.annotations if hasattr(message_content, 'annotations') else []
citations = []
# Iterate over the annotations and add footnotes
for index, annotation in enumerate(annotations):
# Replace the text with a footnote
message_content.value = message_content.value.replace(annotation.text, f' [{index + 1}]')
# Gather citations based on annotation attributes
if (file_citation := getattr(annotation, 'file_citation', None)):
# Retrieve the cited file details (dummy response here since we can't call OpenAI)
cited_file = {'filename': 'cited_document.pdf'} # This should be replaced with actual file retrieval
citations.append(f'[{index + 1}] {file_citation.quote} from {cited_file["filename"]}')
elif (file_path := getattr(annotation, 'file_path', None)):
# Placeholder for file download citation
cited_file = {'filename': 'downloaded_document.pdf'} # This should be replaced with actual file retrieval
citations.append(f'[{index + 1}] Click [here](#) to download {cited_file["filename"]}') # The download link should be replaced with the actual download path
# Add footnotes to the end of the message content
full_response = message_content.value + '\n\n' + '\n'.join(citations)
return full_response
# Main chat interface setup
st.title("Examinator")
# Only show the chat interface if the chat has been started
if st.session_state.start_chat:
# Initialize the model and messages list if not already in session state
if "openai_model" not in st.session_state:
st.session_state.openai_model = "gpt-4-1106-preview"
if "messages" not in st.session_state:
st.session_state.messages = []
# Display existing messages in the chat
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input for the user
if prompt := "Hi there":
# Add user message to the state and display it
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)
# Add the user's message to the existing thread
client.beta.threads.messages.create(
thread_id=st.session_state.thread_id,
role="user",
content=prompt
)
# Create a run with additional instructions
run = client.beta.threads.runs.create(
thread_id=st.session_state.thread_id,
assistant_id=assistant_id,
instructions="Please answer the queries using the knowledge provided in the files.When adding other information mark it clearly as such.with a different color"
)
# Poll for the run to complete and retrieve the assistant's messages
while run.status != 'completed':
time.sleep(1)
run = client.beta.threads.runs.retrieve(
thread_id=st.session_state.thread_id,
run_id=run.id
)
# Retrieve messages added by the assistant
messages = client.beta.threads.messages.list(
thread_id=st.session_state.thread_id
)
# Process and display assistant messages
assistant_messages_for_run = [
message for message in messages
if message.run_id == run.id and message.role == "assistant"
]
for message in assistant_messages_for_run:
full_response = process_message_with_citations(message)
st.session_state.messages.append({"role": "assistant", "content": full_response})
with st.chat_message("assistant"):
st.markdown(full_response, unsafe_allow_html=True)
|
2c02a071d60bf20861ae194f9cc6390a
|
{
"intermediate": 0.3516509532928467,
"beginner": 0.4951748251914978,
"expert": 0.15317422151565552
}
|
35,913
|
Как я должен переписать код что бы async await был корректен
async search() {
this.elem.addEventListener("click", (event) => {
let target = event.target;
let button = this.elem.querySelector(`.${style.button}`);
let main = this.elem.querySelector(`.${style.main}`);
let city = this.elen.querySelector(`.${style.input}`);
let APIkey = "f36ae4b67d3588b4b5865bae7f2452cc";
let api = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${APIkey}&units=standard`;
if (button.contains(target)) {
main.style.display = "flex";
let response = await fetch(api);
if (response.ok) {
let json = await response.json();
}
}
});
}
|
949b5d6ef06d67a0c149e7a09a7edecf
|
{
"intermediate": 0.4210885763168335,
"beginner": 0.3757473826408386,
"expert": 0.20316404104232788
}
|
35,914
|
Please fix this code as this is sending multiple prompts more than required two, and add a button to send the second prompt.
import openai
import streamlit as st
import time
# Set your OpenAI Assistant ID here
assistant_id = '...'
# Initialize the OpenAI client (ensure to set your API key in the sidebar within the app)
client = openai
# Initialize session state variables for file IDs and chat control
if "file_id_list" not in st.session_state:
st.session_state.file_id_list = []
if "start_chat" not in st.session_state:
st.session_state.start_chat = False
if "initial_prompt_sent" not in st.session_state:
st.session_state.initial_prompt_sent = False
if "thread_id" not in st.session_state:
st.session_state.thread_id = None
# Set up the Streamlit page with a title and icon
st.set_page_config(page_title="Examinator", page_icon=":speech_balloon:")
# Define functions for scraping, converting text to PDF, and uploading to OpenAI
def upload_to_openai(filepath):
"""Upload a file to OpenAI and return its file ID."""
with open(filepath, "rb") as file:
response = openai.files.create(file=file.read(), purpose="assistants")
return response.id
# Create a sidebar for API key configuration and additional features
st.sidebar.header("Configuration")
api_key = st.sidebar.text_input("Enter your OpenAI API key", type="password")
if api_key:
openai.api_key = api_key
# Sidebar option for users to upload their own files
uploaded_file = st.sidebar.file_uploader("Upload a file to OpenAI embeddings", key="file_uploader")
# Button to upload a user's file and store the file ID
if st.sidebar.button("Upload File"):
# Upload file provided by user
if uploaded_file:
with open(f"{uploaded_file.name}", "wb") as f:
f.write(uploaded_file.getbuffer())
additional_file_id = upload_to_openai(f"{uploaded_file.name}")
st.session_state.file_id_list.append(additional_file_id)
st.sidebar.write(f"Additional File ID: {additional_file_id}")
# Display all file IDs
if st.session_state.file_id_list:
st.sidebar.write("Uploaded File IDs:")
for file_id in st.session_state.file_id_list:
st.sidebar.write(file_id)
# Associate files with the assistant
assistant_file = client.beta.assistants.files.create(
assistant_id=assistant_id,
file_id=file_id
)
# Button to start the chat session
if st.sidebar.button("Fetch goals"):
st.session_state.start_chat = True
thread = client.beta.threads.create()
st.session_state.thread_id = thread.id
st.write("thread id: ", thread.id)
# Define the function to process messages with citations
def process_message_with_citations(message):
"""Extract content and annotations from the message and format citations as footnotes."""
message_content = message.content[0].text
annotations = message_content.annotations if hasattr(message_content, 'annotations') else []
citations = []
# Iterate over the annotations and add footnotes
for index, annotation in enumerate(annotations):
# Replace the text with a footnote
message_content.value = message_content.value.replace(annotation.text, f' [{index + 1}]')
# Gather citations based on annotation attributes
if (file_citation := getattr(annotation, 'file_citation', None)):
# Retrieve the cited file details (dummy response here since we can't call OpenAI)
cited_file = {'filename': 'cited_document.pdf'} # This should be replaced with actual file retrieval
citations.append(f'[{index + 1}] {file_citation.quote} from {cited_file["filename"]}')
elif (file_path := getattr(annotation, 'file_path', None)):
# Placeholder for file download citation
cited_file = {'filename': 'downloaded_document.pdf'} # This should be replaced with actual file retrieval
citations.append(f'[{index + 1}] Click [here](#) to download {cited_file["filename"]}') # The download link should be replaced with the actual download path
# Add footnotes to the end of the message content
full_response = message_content.value + '\n\n' + '\n'.join(citations)
return full_response
# Main chat interface setup
st.title("Examinator")
# Only show the chat interface if the chat has been started
if st.session_state.start_chat:
# Initialize the model and messages list if not already in session state
if "openai_model" not in st.session_state:
st.session_state.openai_model = "gpt-4-1106-preview"
if "messages" not in st.session_state:
st.session_state.messages = []
# Display existing messages in the chat
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# Chat input for the user
if not st.session_state.initial_prompt_sent: # Check if initial prompt has already been sent
initial_prompt = "Hi there"
# Add user message to the state and display it
st.session_state.messages.append({"role": "user", "content": initial_prompt})
# Updated: Add a condition to make sure we don’t create the user message twice
if not st.session_state.initial_prompt_sent:
client.beta.threads.messages.create(
thread_id=st.session_state.thread_id,
role="user",
content=initial_prompt
)
st.session_state.initial_prompt_sent = True
# Create a run with additional instructions
run = client.beta.threads.runs.create(
thread_id=st.session_state.thread_id,
assistant_id=assistant_id,
instructions="Please answer the queries using the knowledge provided in the files.When adding other information mark it clearly as such.with a different color"
)
# Poll for the run to complete and retrieve the assistant's messages
while run.status != 'completed':
time.sleep(1)
run = client.beta.threads.runs.retrieve(
thread_id=st.session_state.thread_id,
run_id=run.id
)
# Retrieve messages added by the assistant
messages = client.beta.threads.messages.list(
thread_id=st.session_state.thread_id
)
# Process and display assistant messages
assistant_messages_for_run = [
message for message in messages
if message.run_id == run.id and message.role == "assistant"
]
for message in assistant_messages_for_run:
full_response = process_message_with_citations(message)
st.session_state.messages.append({"role": "assistant", "content": full_response})
with st.chat_message("assistant"):
st.markdown(full_response, unsafe_allow_html=True)
st.session_state.current_prompt = None
if len(assistant_messages_for_run) > 0 and "second_prompt" not in st.session_state:
# Here you can put another hardcoded prompt after you receive
# the first response from the assistant.
second_prompt = "Please provide more detail on the topic discussed."
st.session_state.messages.append({"role": "user", "content": second_prompt})
with st.chat_message("user"):
st.markdown(second_prompt)
# Send the second hardcoded prompt to the assistant
client.beta.threads.messages.create(
thread_id=st.session_state.thread_id,
role="user",
content=second_prompt
)
# Create another run for the second prompt
run = client.beta.threads.runs.create(
thread_id=st.session_state.thread_id,
assistant_id=assistant_id,
instructions=second_prompt,
)
while run.status != 'completed':
time.sleep(1)
run = client.beta.threads.runs.retrieve(
thread_id=st.session_state.thread_id,
run_id=run.id
)
# Set flag to indicate second prompt has been sent
st.session_state.second_prompt = True
# Mark that the initial prompt has been handled
st.session_state.initial_prompt_sent = False
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
|
d6cb51caa8b28318acbeb0a844e3394d
|
{
"intermediate": 0.393059104681015,
"beginner": 0.4290167987346649,
"expert": 0.17792408168315887
}
|
35,915
|
This is my resume
Please review
Sai varaprasad – Full Stack Web Developer
Full Name: Sai Varaprasad Reddy Medapati
Email: <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>
Phone: <PRESIDIO_ANONYMIZED_PHONE_NUMBER>
Professional Summary:
Experienced IT professional with a passion for problem-solving. Skilled in a wide range of technologies, including Angular, Ionic, NodeJS, JavaScript, Java, MongoDB, and MySQL. Successful track record of delivering appropriate technology solutions for desktop and mobile products, with expertise in platform development, enterprise architecture, agile methodologies, cloud services, web-based applications, and microservice architecture.
Technical Skills:
AngularJS, Angular, Ionic, NodeJS, Java, MongoDB, MySQL, JavaScript, AWS Services
Work Experience:
Full Stack Web Developer, ubq Technologies
- Projects which I have worked completely, Few are listed
1. Medics Care (mobile app and web portal): A MEAN Stack application using Ionic Cordova for Android and iOS devices and also a PWA that empowers patients to connect with their healthcare provider easily via video calls and chat and from wherever they are. And also there are features to view the EMR, pay bills etc..
2. Medics Doc (mobile app): A MEAN Stack application using Ionic Cordova for Android and iOS devices. Focused on the doctor's perspective, allowing them to view appointments and conduct video consultations online, view patients' medical history, and give prescriptions and share any attachments to the patients.
3. Wefly: A web application in MEAN Stack using Angular 14. Focused on booking antigen test registration for international patients at FMP hospitals in Vietnam. Provided a dashboard for management to view and manage the total registrations and their statuses.
Also feature like bulk registrations, automatic printing of the reports and creation of bills once the patient got registered.
4. KIOSK Registration: A web application to scan QR codes displayed in hospitals and allow users to self-register and make payments online instead of waiting in long queues. Used MEAN Stack for development.
5. Medics: Played a crucial role in the billing module of Medics, a key component of the HIS system. Redesigned and improved the module, resulting in a significant reduction of almost 90% of incoming bugs and making it a much more reliable and efficient part of the system. Also integrated the HIS with various other important features such as WhatsApp, payment gateways, and government portals like ABHA and ABDM, making it much more streamlined and hassle-free for both patients and healthcare providers.
- Executed the entire software development life cycle from requirement gathering, design, coding, version management, deployment and testing, and product support of the projects which I have done over these years.
Key Accomplishments:
- Reduced almost 90% of incoming bugs in the billing module for Medics HIS by redesigning and fixing parts of the module.
- Automated daily redundant tasks, including generating health check-up emails and comparing data for validations, using JavaScript scripts and engines.
- Optimized SQL queries and implemented Redis caching, increasing application speed by at least 60%.
Education:
Bachelor of Technology in Computer Science
Personal Interests:
- Passionate about exploring gadgets and technology.
- Thrive on taking on challenges that others may not be able to tackle.
- Enjoys seeing tangible results from work on a day-to-day basis.
|
93665187d2ee20c3a6312a7e7fdc6a37
|
{
"intermediate": 0.38913050293922424,
"beginner": 0.34134021401405334,
"expert": 0.2695292532444
}
|
35,916
|
I want you to act as a ChatGPT prompt generator, I will send a topic, you have to generate a ChatGPT prompt based on the content of the topic, the prompt should start with "I want you to act as ", and guess what I might do, and expand the prompt accordingly Describe the content to make it useful.
|
5ba76984773a7aa2da4150ce926226cb
|
{
"intermediate": 0.2667887806892395,
"beginner": 0.30385687947273254,
"expert": 0.42935433983802795
}
|
35,917
|
ОШИБКА НА АРДУИНО
C:\Users\Dimentiy\AppData\Local\Temp\ccwFCqMD.ltrans0.ltrans.o: In function `main':
C:\Users\Dimentiy\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.6\cores\arduino/main.cpp:46: undefined reference to `loop'
collect2.exe: error: ld returned 1 exit status
exit status 1
Compilation error: exit status 1
ПРИ ПРОГРАМИРОВАНИЯ АРДУИНО ВЫЛЕЗЛА ОШИБК
|
c47dc807ea127b19a75c08b9812293c6
|
{
"intermediate": 0.3301352262496948,
"beginner": 0.36627671122550964,
"expert": 0.30358806252479553
}
|
35,918
|
请详细解释以下代码:from transformers import AutoModelForCausalLM
from peft import get_peft_config, get_peft_model, get_peft_model_state_dict, LoraConfig, TaskType
import torch
from datasets import load_dataset
import os
from transformers import AutoTokenizer
from torch.utils.data import DataLoader
from transformers import default_data_collator, get_linear_schedule_with_warmup
from tqdm import tqdm
from datasets import load_dataset
device = "cuda"
model_name_or_path = "/data/nfs/llm/model/bloomz-560m"
tokenizer_name_or_path = "/data/nfs/llm/model/bloomz-560m"
peft_config = LoraConfig(task_type=TaskType.CAUSAL_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1)
dataset_name = "twitter_complaints"
checkpoint_name = f"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}_v1.pt".replace("/", "_")
text_column = "Tweet text"
label_column = "text_label"
max_length = 64
lr = 3e-2
num_epochs = 10
batch_size = 8
|
2a118d012a7f9b8faedd4d6059aec924
|
{
"intermediate": 0.44150805473327637,
"beginner": 0.198574036359787,
"expert": 0.35991784930229187
}
|
35,919
|
how to make a razor pages web page accessible for anonymous user ?
|
85f458c7c630ab14650d4970dd0a92a2
|
{
"intermediate": 0.28986725211143494,
"beginner": 0.2778424322605133,
"expert": 0.432290256023407
}
|
35,920
|
give me a few simple html code to create a beautiful login page, just the header and form part
|
5152d4b17d3b17f1e96cdbedf7a95359
|
{
"intermediate": 0.3329024314880371,
"beginner": 0.3717505931854248,
"expert": 0.2953469455242157
}
|
35,921
|
how to wrap html form in a beautiful card-like background using bootstrap?
|
b84b07fc7aeb57840e30fdc266809999
|
{
"intermediate": 0.3986523449420929,
"beginner": 0.33470380306243896,
"expert": 0.2666438817977905
}
|
35,922
|
Hello
|
d61231207556faed6c8e53d4132e7cb7
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
35,923
|
Add more selectors and remake the CSS a bit
|
8630dd1008326b7efc9b182cbab2d745
|
{
"intermediate": 0.42016759514808655,
"beginner": 0.20136600732803345,
"expert": 0.3784664273262024
}
|
35,924
|
comment enlever les adhérents ajoutées du sous menu car ce n'est pas logique de les voir comme si je pouvais tout de même les rajouter : import datetime
from sqlalchemy import func
from .app import db, login_manager
from flask_login import UserMixin
# Modèle pour représenter le lieu
class Lieu(db.Model):
__tablename__ = 'LIEU'
idLieu = db.Column(db.Integer, primary_key=True, autoincrement=True)
nomLieu = db.Column(db.String(50), nullable=False)
villeLieu = db.Column(db.String(50), nullable=False)
codePostalLieu = db.Column(db.Integer, nullable=False)
adresseLieu = db.Column(db.String(50), nullable=False)
def __init__(self, nom_lieu, ville_lieu, code_postal_lieu, adresse_lieu):
self.nomLieu = nom_lieu
self.villeLieu = ville_lieu
self.codePostalLieu = code_postal_lieu
self.adresseLieu = adresse_lieu
# Modèle pour représenter l'arme
class Arme(db.Model):
__tablename__ = 'ARME'
idArme = db.Column(db.Integer, primary_key=True, autoincrement=True)
nomArme = db.Column(db.String(50), nullable=False, unique = True)
def __init__(self, nom_arme):
self.nomArme = nom_arme
# Modèle pour représenter la saison
class Saison(db.Model):
__tablename__ = 'SAISON'
idSaison = db.Column(db.Integer, primary_key=True, autoincrement=True)
nomSaison = db.Column(db.String(50), nullable=False)
dateDebutSaison = db.Column(db.Date, nullable=False)
dateFinSaison = db.Column(db.Date, nullable=False)
def __init__(self, nom_saison, date_debut_saison, date_fin_saison):
self.nomSaison = nom_saison
self.dateDebutSaison = date_debut_saison
self.dateFinSaison = date_fin_saison
# Modèle pour représenter la catégorie
class Categorie(db.Model):
__tablename__ = 'CATEGORIE'
idCat = db.Column(db.Integer, primary_key=True, autoincrement=True)
nomCategorie = db.Column(db.String(50), nullable=False, unique=True)
def __init__(self, nom_categorie):
self.nomCategorie = nom_categorie
# Modèle pour représenter le club
class Club(db.Model):
__tablename__ = 'CLUB'
idClub = db.Column(db.Integer, primary_key=True, autoincrement=True)
nomClub = db.Column(db.String(50), nullable=False, unique = True)
regionClub = db.Column(db.String(50), nullable=False)
def __init__(self, nom_club, region_club):
self.nomClub = nom_club
self.regionClub = region_club
# Modèle pour représenter la compétition
class Competition(db.Model):
__tablename__ = 'COMPETITION'
idComp = db.Column(db.Integer, primary_key=True, autoincrement=True)
idLieu = db.Column(db.Integer, db.ForeignKey('LIEU.idLieu'), nullable=False)
lieu = db.relationship('Lieu', backref='Lieu.idLieu')
idSaison = db.Column(db.Integer, db.ForeignKey('SAISON.idSaison'), nullable=False)
saison = db.relationship('Saison', backref='Saison.idSaison')
idCat = db.Column(db.Integer, db.ForeignKey('CATEGORIE.idCat'), nullable=False)
categorie = db.relationship('Categorie', backref='Categorie.idCat')
idArme = db.Column(db.Integer, db.ForeignKey('ARME.idArme'), nullable=False)
arme = db.relationship('Arme', backref='Arme.idArme')
nomComp = db.Column(db.String(50), nullable=False)
descComp = db.Column(db.String(50), nullable=False)
dateComp = db.Column(db.Date, nullable=False)
heureComp = db.Column(db.Time, nullable=False)
sexeComp = db.Column(db.String(1), nullable=False)
estIndividuelle = db.Column(db.Boolean, nullable=False)
def __init__(self, idLieu, idSaison, idCat, idArme, nomComp, descComp, dateComp, heureComp, sexeComp, estIndividuelle):
self.idLieu = idLieu
self.idSaison = idSaison
self.idCat = idCat
self.idArme = idArme
self.nomComp = nomComp
self.descComp = descComp
self.dateComp = dateComp
self.heureComp = heureComp
self.sexeComp = sexeComp
self.estIndividuelle = estIndividuelle
# Modèle pour représenter la piste
class Piste(db.Model):
__tablename__ = 'PISTE'
idPiste = db.Column(db.Integer, primary_key=True, autoincrement=True)
idComp = db.Column(db.Integer, db.ForeignKey('COMPETITION.idComp'), nullable=False)
nomPiste = db.Column(db.String(50), nullable=False)
estDispo = db.Column(db.Boolean, nullable=False)
competition = db.relationship('Competition', backref='Competition.idComp')
def __init__(self, competition, nom_piste, est_dispo):
self.idComp = competition
self.nomPiste = nom_piste
self.estDispo = est_dispo
# Modèle pour représenter le type de match
class TypeMatch(db.Model):
__tablename__ = 'TYPE_MATCH'
idTypeMatch = db.Column(db.Integer, primary_key=True, autoincrement=True)
nomTypeMatch = db.Column(db.String(50), nullable=False)
nbTouches = db.Column(db.Integer, nullable=False)
def __init__(self, nom_type_match, nb_touches):
self.nomTypeMatch = nom_type_match
self.nbTouches = nb_touches
# Modèle pour représenter l'escrimeur
class Escrimeur(db.Model):
__tablename__ = 'ESCRIMEUR'
numeroLicenceE = db.Column(db.Integer, nullable=False, primary_key=True)
idCat = db.Column(db.Integer, db.ForeignKey('CATEGORIE.idCat'), nullable=False)
prenomE = db.Column(db.String(50), nullable=False)
nomE = db.Column(db.String(50), nullable=False)
dateNaissanceE = db.Column(db.Date, nullable=False)
sexeE = db.Column(db.String(50), nullable=False)
numTelE = db.Column(db.Integer, nullable=True)
categorie = db.relationship('Categorie', backref='categorie')
def __init__(self, categorie, prenom_e, nom_e, date_naissance_e, numero_licence_e, sexe_e, num_tel_e):
self.idCat = categorie
self.numeroLicenceE = numero_licence_e
self.idCat = categorie
self.prenomE = prenom_e
self.nomE = nom_e
self.dateNaissanceE = date_naissance_e
self.sexeE = sexe_e
self.numTelE = num_tel_e
def to_dict(self):
return {
'idCat': self.idCat,
'prenomE': self.prenomE,
'nomE': self.nomE,
'dateNaissanceE': self.dateNaissanceE.isoformat() if self.dateNaissanceE else None,
'numeroLicenceE': self.numeroLicenceE,
'sexeE': self.sexeE,
'numTelE': self.numTelE
}
# Modèle pour représenter les tireurs
class Tireur(db.Model):
__tablename__ = 'TIREUR'
numeroLicenceE = db.Column(db.Integer, db.ForeignKey('ESCRIMEUR.numeroLicenceE'), primary_key=True)
idClub = db.Column(db.Integer, db.ForeignKey('CLUB.idClub'), nullable=False)
classement = db.Column(db.Integer, nullable=False)
club = db.relationship('Club', backref='Club.idClub')
escrimeur = db.relationship('Escrimeur', backref='Escrimeur.tireur')
def __init__(self, num_licence, club, classement):
self.numeroLicenceE = num_licence
self.idClub = club
self.classement = classement
def to_dict(self):
dic_tireur = self.escrimeur.to_dict()
dic_tireur['idClub'] = self.idClub
dic_tireur['nomClub'] = self.club.nomClub
dic_tireur['classement'] = self.classement
return dic_tireur
# Modèle pour représenter les arbitres
class Arbitre(db.Model):
__tablename__ = 'ARBITRE'
idArbitre = db.Column(db.Integer, primary_key=True, autoincrement=True)
numeroLicenceE = db.Column(db.Integer, db.ForeignKey('ESCRIMEUR.numeroLicenceE'))
arbitre = db.relationship('Escrimeur', backref='Arbitre.numeroLicenceE')
def __init__(self, numeroLicenceE):
self.numeroLicenceE = numeroLicenceE
# Modèle pour représenter les participants aux compétitions
class ParticipantsCompetition(db.Model):
__tablename__ = 'PARTICIPANTS_COMPETITION'
numeroLicenceE = db.Column(db.Integer, db.ForeignKey('ESCRIMEUR.numeroLicenceE'), primary_key=True)
idComp = db.Column(db.Integer, db.ForeignKey('COMPETITION.idComp'), primary_key=True)
tireur = db.relationship('Escrimeur', backref='PartEscrimeur', foreign_keys=[numeroLicenceE])
competition = db.relationship('Competition', backref='PartCompetition.idComp')
def __init__(self, numeroLicenceE, idComp):
self.numeroLicenceE = numeroLicenceE
self.idComp = idComp
# Modèle pour représenter la relation entre les escrimeurs et les armes qu'ils pratiquent
class PratiquerArme(db.Model):
__tablename__ = 'PRATIQUER_ARME'
numero_licence_e_fk = db.Column(db.Integer, db.ForeignKey('ESCRIMEUR.numeroLicenceE'), primary_key=True)
id_arme_fk = db.Column(db.Integer, db.ForeignKey('ARME.idArme'), primary_key=True)
escrimeur = db.relationship('Escrimeur', backref='armes_pratiquees')
arme = db.relationship('Arme', backref='pratiquee_par')
def __init__(self, numero_licence_e_fk, id_arme_fk):
self.numero_licence_e_fk = numero_licence_e_fk
self.id_arme_fk = id_arme_fk
# Modèle pour représenter le classement final
class ClassementFinal(db.Model):
__tablename__ = 'CLASSEMENT_FINAL'
idClassementFinal = db.Column(db.Integer, primary_key=True, autoincrement=True)
idComp = db.Column(db.Integer, db.ForeignKey('COMPETITION.idComp'), nullable=False)
numeroLicenceE = db.Column(db.Integer, db.ForeignKey('TIREUR.numeroLicenceE'), nullable=False)
position = db.Column(db.Integer, nullable=False)
competition = db.relationship('Competition', backref='competition')
tireur = db.relationship('Tireur', backref='Tireur.numeroLicenceE')
def __init__(self, comp, tireur, position):
self.idComp = comp
self.numeroLicenceE = tireur
self.position = position
# Modèle pour représenter les poules
class Poule(db.Model):
__tablename__ = 'POULE'
idPoule = db.Column(db.Integer, primary_key=True, autoincrement=True)
idComp = db.Column(db.Integer, db.ForeignKey('COMPETITION.idComp'), nullable=False)
idPiste = db.Column(db.Integer, db.ForeignKey('PISTE.idPiste'), nullable=False)
idArbitre = db.Column(db.Integer, db.ForeignKey('ARBITRE.idArbitre'), nullable=False)
nomPoule = db.Column(db.String(50), nullable=False)
competition = db.relationship('Competition', backref='poules')
piste = db.relationship('Piste', backref='Piste.idPiste')
arbitre = db.relationship('Arbitre', backref='Arbitre.idArbitre')
def __init__(self, competition, piste, arbitre, nom_poule):
self.idComp = competition
self.idPiste = piste
self.idArbitre = arbitre
self.nomPoule = nom_poule
# Modèle pour représenter les participants aux poules
class ParticipantsPoule(db.Model):
__tablename__ = 'PARTICIPANTS_POULE'
idPoule = db.Column(db.Integer, db.ForeignKey('POULE.idPoule'), primary_key=True)
numeroLicenceE = db.Column(db.Integer, db.ForeignKey('TIREUR.numeroLicenceE'), primary_key=True)
poule = db.relationship('Poule', backref='Poule.idPoule')
tireur = db.relationship('Tireur', backref='poule_participants')
def __init__(self, poule, tireur):
self.idPoule = poule
self.numeroLicenceE = tireur
# Modèle pour représenter les matchs de poule
class MatchPoule(db.Model):
__tablename__ = 'MATCH_POULE'
idMatch = db.Column(db.Integer, primary_key=True, autoincrement=True)
idTypeMatch = db.Column(db.Integer, db.ForeignKey('TYPE_MATCH.idTypeMatch'), nullable=False)
idPoule = db.Column(db.Integer, db.ForeignKey('POULE.idPoule'), nullable=False)
idPiste = db.Column(db.Integer, db.ForeignKey('PISTE.idPiste'), nullable=False)
idArbitre = db.Column(db.Integer, db.ForeignKey('ARBITRE.idArbitre'), nullable=False)
numeroLicenceE1 = db.Column(db.Integer, db.ForeignKey('TIREUR.numeroLicenceE'), nullable=False)
numeroLicenceE2 = db.Column(db.Integer, db.ForeignKey('TIREUR.numeroLicenceE'), nullable=False)
dateMatch = db.Column(db.Date, nullable=False)
heureMatch = db.Column(db.Time, nullable=False)
touchesRecuesTireur1 = db.Column(db.Integer)
touchesDonneesTireur1 = db.Column(db.Integer)
touchesRecuesTireur2 = db.Column(db.Integer)
touchesDonneesTireur2 = db.Column(db.Integer)
type_match = db.relationship('TypeMatch', backref='TypeMatch.idTypeMatch')
poule = db.relationship('Poule', backref='matches')
piste = db.relationship('Piste', backref='matches')
arbitre = db.relationship('Arbitre', backref='matches')
tireur1 = db.relationship('Tireur', foreign_keys=[numeroLicenceE1], backref='Tireur.numeroLicenceE1')
tireur2 = db.relationship('Tireur', foreign_keys=[numeroLicenceE2], backref='Tireur.numeroLicenceE2')
def __init__(self, type_match, poule, piste, arbitre, tireur1, tireur2, date_match, heure_match, touches_recues_tireur1, touches_donnees_tireur1, touches_recues_tireur2, touches_donnees_tireur2):
self.idTypeMatch = type_match
self.idPoule = poule
self.idPiste = piste
self.idArbitre = arbitre
self.numeroLicenceE1 = tireur1
self.numeroLicenceE2 = tireur2
self.dateMatch = date_match
self.heureMatch = heure_match
self.touchesRecuesTireur1 = touches_recues_tireur1
self.touchesDonneesTireur1 = touches_donnees_tireur1
self.touchesRecuesTireur2 = touches_recues_tireur2
self.touchesDonneesTireur2 = touches_donnees_tireur2
# Modèle pour représenter les feuilles de match
class FeuilleMatch(db.Model):
__tablename__ = 'FEUILLE_MATCH'
idFeuille = db.Column(db.Integer, primary_key=True, autoincrement=True)
idPoule = db.Column(db.Integer, db.ForeignKey('POULE.idPoule'), nullable=False)
idComp = db.Column(db.Integer, db.ForeignKey('COMPETITION.idComp'), nullable=False)
numeroLicenceE1 = db.Column(db.Integer, db.ForeignKey('TIREUR.numeroLicenceE'), nullable=False)
numeroLicenceE2 = db.Column(db.Integer, db.ForeignKey('TIREUR.numeroLicenceE'), nullable=False)
scoreTireur1 = db.Column(db.Integer)
scoreTireur2 = db.Column(db.Integer)
poule = db.relationship('Poule', backref='feuille_matches')
competition = db.relationship('Competition', backref='feuille_matches')
tireur1 = db.relationship('Tireur', foreign_keys=[numeroLicenceE1], backref='matches_as_tireur1')
tireur2 = db.relationship('Tireur', foreign_keys=[numeroLicenceE2], backref='matches_as_tireur2')
def __init__(self, poule, competition, tireur1, tireur2, score_tireur1, score_tireur2):
self.idPoule = poule
self.idComp = competition
self.numeroLicenceE1 = tireur1
self.numeroLicenceE2 = tireur2
self.scoreTireur1 = score_tireur1
self.scoreTireur2 = score_tireur2
class User(db.Model, UserMixin):
__tablename__ = 'USER'
idUser = db.Column(db.Integer, primary_key=True)
pseudoUser = db.Column(db.String (50), unique=True, nullable=False)
mdpUser = db.Column(db.String (64), nullable=False)
emailUser = db.Column(db.String (50), unique=True)
statutUser = db.Column(db.String(50), nullable=False)
def get_id(self):
return self.idUser
@login_manager.user_loader
def load_user(username):
return User.query.get(username)
def get_sample():
return Competition.query.order_by(Competition.dateComp.desc()).all()
def get_competition_by_id(id_comp):
return Competition.query.filter_by(idComp=id_comp).first()
def get_categories():
categories = Categorie.query.all()
return [categorie.nomCategorie for categorie in categories]
def get_saisons():
saisons = Saison.query.all()
return [saison.nomSaison for saison in saisons]
def get_lieux():
lieux = Lieu.query.all()
return [lieu.nomLieu for lieu in lieux]
def get_armes():
armes = Arme.query.all()
return [arme.nomArme for arme in armes]
def get_type_match():
type_match = TypeMatch.query.all()
return [type_match.nomTypeMatch for type_match in type_match]
def get_nb_participants(id_tournoi):
participants_count = ParticipantsCompetition.query.join(Competition).filter(Competition.idComp == id_tournoi).count()
return participants_count
def filtrer_competitions(competitions, categorie, arme, sexe, statut):
comp_filtrer = competitions
if categorie:
comp_filtrer = [comp for comp in comp_filtrer if comp.categorie.nomCategorie == categorie]
if arme:
comp_filtrer = [comp for comp in comp_filtrer if comp.arme.nomArme == arme]
if sexe:
comp_filtrer = [comp for comp in comp_filtrer if comp.sexeComp == sexe]
if statut:
if statut == "A venir":
comp_filtrer = [comp for comp in comp_filtrer if comp.dateComp > datetime.date.today()]
elif statut == "Terminé":
comp_filtrer = [comp for comp in comp_filtrer if comp.dateComp <= datetime.date.today()]
return comp_filtrer
def filtrer_adherent(adherents, categorie, sexeE):
adherents_filtrer = adherents
if categorie:
adherents_filtrer = [adherent for adherent in adherents_filtrer if adherent.Categorie.nomCategorie == categorie]
if sexeE:
adherents_filtrer = [adherent for adherent in adherents_filtrer if adherent.Escrimeur.sexeE == sexeE]
# if role == 'tireur':
# adherents_filtrer = [adherent for adherent in adherents_filtrer if adherent.Arbitre is None]
# elif role == 'arbitre':
# adherents_filtrer = [adherent for adherent in adherents_filtrer if adherent.Arbitre is not None]
return adherents_filtrer
def get_id_lieu(nom_lieu):
lieu = Lieu.query.filter_by(nomLieu=nom_lieu).first()
return lieu.idLieu if lieu else None
def get_id_saison(nom_saison):
saison = Saison.query.filter_by(nomSaison=nom_saison).first()
return saison.idSaison if saison else None
def get_liste_participants_competitions_tireurs(id_comp):
return ParticipantsCompetition.query.join(Tireur, ParticipantsCompetition.numeroLicenceE == Tireur.numeroLicenceE).filter(ParticipantsCompetition.idComp == id_comp).all()
def get_liste_participants_competitions_arbitres(id_comp):
return ParticipantsCompetition.query.join(Arbitre, ParticipantsCompetition.numeroLicenceE == Arbitre.numeroLicenceE).filter(ParticipantsCompetition.idComp == id_comp).all()
def get_classement_tireur(num_licence):
return Tireur.query.filter_by(numeroLicenceE=num_licence).first().classement
def get_id_club_tireur(num_licence):
return Tireur.query.filter_by(numeroLicenceE=num_licence).first().idClub
def get_id_arbitre_from_escrimeur(numero_licence):
arbitre = Arbitre.query.filter_by(numeroLicenceE=numero_licence).first()
if arbitre:
return arbitre.idArbitre
def get_nom_club_by_id(id_club):
return Club.query.filter_by(idClub=id_club).first().nomClub
def classer_tireurs(tireurs):
return sorted(tireurs, key=lambda tireur : get_classement_tireur(tireur.numeroLicenceE), reverse=True)
def poules_fabriquables(tireurs, arbitres):
return True if 3 <= len(tireurs) // len(arbitres) <= 7 and len(tireurs) > 3 else False
def nb_poules_fabriquables(arbitres):
return [[] for _ in range(len(arbitres))]
def get_nb_arbitres(id_comp):
return ParticipantsCompetition.query.join(Arbitre, ParticipantsCompetition.numeroLicenceE == Arbitre.numeroLicenceE).filter(ParticipantsCompetition.idComp == id_comp).count()
def get_nb_tireurs(id_comp):
return ParticipantsCompetition.query.filter_by(idComp=id_comp).count() - get_nb_arbitres(id_comp)
def get_liste_pistes_selon_nb_arbitres(id_comp, nb_arbitres):
return Piste.query.filter_by(idComp=id_comp).limit(nb_arbitres).all()
def fabriquer_poules_selon_classement(tireurs, arbitres, pistes):
if not poules_fabriquables(tireurs, arbitres):
return "Les poules ne sont pas fabriquables"
liste_triee = classer_tireurs(tireurs)
liste_poules = nb_poules_fabriquables(arbitres)
tireurs_dans_poule = set()
arbitres_dans_poule = set()
pistes_associees = set()
for i in range(len(liste_triee)):
if arbitres[i % len(arbitres)] not in arbitres_dans_poule and pistes[i % len(arbitres)] not in pistes_associees:
escrimeur = Escrimeur.query.filter_by(numeroLicenceE=arbitres[i].numeroLicenceE).first()
piste = Piste.query.filter_by(idPiste=pistes[i].idPiste).first()
nom_complet = f"{escrimeur.prenomE} {escrimeur.nomE}, {piste.nomPiste}"
liste_poules[i % len(arbitres)].append((escrimeur, nom_complet))
arbitres_dans_poule.add(arbitres[i])
pistes_associees.add(pistes[i])
if liste_triee[i] not in tireurs_dans_poule:
if len(liste_poules[i % len(arbitres)]) < 7:
escrimeur = Escrimeur.query.filter_by(numeroLicenceE=liste_triee[i].numeroLicenceE).first()
nom_complet = f"{escrimeur.prenomE} {escrimeur.nomE}, Classement : {get_classement_tireur(escrimeur.numeroLicenceE)}"
liste_poules[i % len(arbitres)].append((escrimeur, nom_complet))
tireurs_dans_poule.add(liste_triee[i])
if liste_triee[-i-1] not in tireurs_dans_poule:
if len(liste_poules[i % len(arbitres)]) < 7:
escrimeur = Escrimeur.query.filter_by(numeroLicenceE=liste_triee[-i-1].numeroLicenceE).first()
nom_complet = f"{escrimeur.prenomE} {escrimeur.nomE}, Classement : {get_classement_tireur(escrimeur.numeroLicenceE)}"
liste_poules[i % len(arbitres)].append((escrimeur, nom_complet))
tireurs_dans_poule.add(liste_triee[-i-1])
mal_trie = False
indice_mal_trie = None
for i in range(len(liste_poules)):
if len(liste_poules[i]) - 1 < 3:
mal_trie = True
indice_mal_trie = i
break
if mal_trie:
for i in range(len(liste_poules)):
if len(liste_poules[i]) - 1 > 3:
liste_poules[indice_mal_trie].append(liste_poules[i].pop())
break
return liste_poules
def fabriquer_poules_decalage_club(tireurs, arbitres, pistes):
if not poules_fabriquables(tireurs, arbitres):
return "Les poules ne sont pas fabriquables"
liste_triee = classer_tireurs(tireurs)
liste_poules = nb_poules_fabriquables(arbitres)
num_poule = 0
arbitres_dans_poule = set()
pistes_associees = set()
for i in range(len(liste_triee)):
if arbitres[i % len(arbitres)] not in arbitres_dans_poule and pistes[i % len(arbitres)] not in pistes_associees:
escrimeur = Escrimeur.query.filter_by(numeroLicenceE=arbitres[i].numeroLicenceE).first()
piste = Piste.query.filter_by(idPiste=pistes[i].idPiste).first()
nom_complet = f"{escrimeur.prenomE} {escrimeur.nomE}, {piste.nomPiste}"
liste_poules[i].append((escrimeur, nom_complet))
arbitres_dans_poule.add(arbitres[i])
pistes_associees.add(pistes[i])
if len(liste_poules[i % len(arbitres)]) < 7:
escrimeur = Escrimeur.query.filter_by(numeroLicenceE=liste_triee[i].numeroLicenceE).first()
id_club_tireur = get_id_club_tireur(escrimeur.numeroLicenceE)
nom_club_tireur = get_nom_club_by_id(id_club_tireur)
nom_complet = f"{escrimeur.prenomE} {escrimeur.nomE}, Club : {nom_club_tireur}"
if (escrimeur, nom_complet) not in liste_poules[i % len(arbitres)]:
liste_poules[i % len(arbitres)].append((escrimeur, nom_complet))
else:
num_poule += 1
if num_poule % len(arbitres) == 0:
liste_poules[i % len(arbitres)].append((escrimeur, nom_complet))
num_poule = 0
else:
liste_poules[i % len(arbitres) + num_poule].append((escrimeur, nom_complet))
mal_trie = False
indice_mal_trie = None
for i in range(len(liste_poules)):
if len(liste_poules[i]) - 1 < 3:
mal_trie = True
indice_mal_trie = i
break
if mal_trie:
for i in range(len(liste_poules)):
if len(liste_poules[i]) - 1 > 3:
liste_poules[indice_mal_trie].append(liste_poules[i].pop())
break
return liste_poules
def fabriquer_poules(tireurs, arbitres, pistes, type_poule):
if not poules_fabriquables(tireurs, arbitres):
return "Les poules ne sont pas fabriquables"
match type_poule:
case "Classement":
liste_poules = fabriquer_poules_selon_classement(tireurs, arbitres, pistes)
case "Club":
liste_poules = fabriquer_poules_decalage_club(tireurs, arbitres, pistes)
return liste_poules
def get_adherents():
res = db.session.query(Tireur, Escrimeur, Categorie) \
.join(Escrimeur, Escrimeur.numeroLicenceE == Tireur.numeroLicenceE) \
.join(Club, Club.idClub == Tireur.idClub) \
.join(Categorie, Escrimeur.idCat == Categorie.idCat) \
.filter(Club.nomClub == "BLOIS CE") \
.add_columns(
Tireur.idClub,
Escrimeur.prenomE,
Escrimeur.nomE,
Escrimeur.dateNaissanceE,
Escrimeur.numeroLicenceE,
Escrimeur.sexeE,
Escrimeur.numTelE,
Categorie.nomCategoriea
) \
.all()
return res
def get_adherents_adapte_json():
res = db.session.query(Escrimeur) \
.join(Tireur, Escrimeur.numeroLicenceE == Tireur.numeroLicenceE) \
.join(Club, Club.idClub == Tireur.idClub) \
.join(Categorie, Escrimeur.idCat == Categorie.idCat) \
.filter(Club.nomClub == "BLOIS CE") \
.all()
return res
def dernier_escrimeur_id():
last_escrimeur = db.session.query(Escrimeur).order_by(Escrimeur.numeroLicenceE.desc()).first()
if last_escrimeur:
return last_escrimeur.numeroLicenceE
else:
return 0
def get_participants(id_comp, club=None):
res = (
db.session.query(ParticipantsCompetition, Escrimeur, Categorie)
.join(Escrimeur, ParticipantsCompetition.numeroLicenceE == Escrimeur.numeroLicenceE)
.join(Categorie, Escrimeur.idCat == Categorie.idCat)
.join(Tireur, Tireur.numeroLicenceE == Escrimeur.numeroLicenceE)
.join(Club, Club.idClub == Tireur.idClub)
.outerjoin(Arbitre, Arbitre.numeroLicenceE == Escrimeur.numeroLicenceE)
.filter(ParticipantsCompetition.idComp == id_comp)
.filter(Arbitre.idArbitre == None)
)
if club is not None:
if club == "!":
res = res.filter(Club.nomClub != "BLOIS CE")
else:
res = res.filter(Club.nomClub == club)
return res.add_columns(Escrimeur.prenomE, Escrimeur.nomE, Categorie.nomCategorie).all()
def get_liste_participants_competitions(id_comp):
return ParticipantsCompetition.query.filter_by(idComp=id_comp).all()
def get_informations_escrimeur(numero_licence):
return Escrimeur.query.filter_by(numeroLicenceE=numero_licence).first()
def get_id_poule(id_comp, id_piste, id_arbitre, nom_poule):
return Poule.query.filter_by(idComp=id_comp, idPiste=id_piste, idArbitre=id_arbitre, nomPoule=nom_poule).first().idPoule
def get_arbitres(idcomp):
arbitres = db.session.query(Arbitre, Escrimeur, Categorie).join(Escrimeur, Arbitre.numeroLicenceE == Escrimeur.numeroLicenceE).join(
Categorie, Escrimeur.idCat == Categorie.idCat
).join(
ParticipantsCompetition,
ParticipantsCompetition.numeroLicenceE == Escrimeur.numeroLicenceE
).filter(ParticipantsCompetition.idComp == idcomp).all()
return arbitres
def get_competition_statut(competition):
participants = ParticipantsCompetition.query.filter_by(idComp=competition.idComp).first()
if participants:
# verifie si les poules ont été créées pour la compétition
poules = Poule.query.filter_by(idComp=competition.idComp).first()
if poules:
# verifie si l’appel a été fait donc sil ya des scores entrés pour des matchs de poules)
match_poule = MatchPoule.query.filter_by(idComp=competition.idComp).first()
if match_poule and (match_poule.touchesRecuesTireur1 is not None or match_poule.touchesDonneesTireur1 is not None
or match_poule.touchesRecuesTireur2 is not None or match_poule.touchesDonneesTireur2 is not None):
return 'score'
else:
return 'appel'
else:
return 'participants'
else:
return 'participants'
{% extends 'base.html' %} {% block content %}
<link
rel="stylesheet"
href="{{ url_for('static', filename='gestion_participants.css') }}"
/>
<script>
var nbParticipantsBlois = {{ nb_participants_blois }};
var nbParticipantsOther = {{ nb_participants_other }};
var nbParticipantsArb = {{ participants_arb|length }};
var competitionId = {{ competition.idComp }};
var competitionGender = "{{ competition.sexeComp }}";
</script>
<script src="{{ url_for('static', filename='js/condCompetValide.js') }}"></script>
<script src="{{ url_for('static', filename='js/gestionParticipant.js') }}"></script>
<script src="{{ url_for('static', filename='js/editField.js') }}"></script>
{% include 'progress-bar.html' %}
<section class="content">
<section class="section-infopr">
<div class="infotitre">
<h2>INFORMATIONS PRINCIPALE</h2>
</div>
<section class="infopr">
<div class="labelp">
<p>Titre :</p>
<p>Organisateur :</p>
<p>Lieu :</p>
<p>Date :</p>
<p>Heure :</p>
</div>
<div class="valeurp">
<p id="nomComp">{{ competition.nomComp }}</p>
<p id="descComp">{{ competition.descComp }}</p>
<p id="lieu">{{ competition.lieu.nomLieu }}</p>
<p id="dateComp">{{ competition.dateComp }}</p>
<p id="heureComp">{{ competition.heureComp }}</p> <!-- Nouvelle ligne pour l'heure -->
</div>
<div class="actionsp">
<img src="{{ url_for('static', filename='../static/img/edit.png') }}" onclick="editField('nomComp')" />
<img src="{{ url_for('static', filename='../static/img/edit.png') }}" onclick="editField('descComp')" />
<img src="{{ url_for('static', filename='../static/img/edit.png') }}" onclick="editField('lieu')" />
<img src="{{ url_for('static', filename='../static/img/edit.png') }}" onclick="editField('dateComp')" />
<img src="{{ url_for('static', filename='../static/img/edit.png') }}" onclick="editField('heureComp')" /> <!-- Nouvelle ligne pour l'heure -->
</div>
</section>
</section>
<section class="gestion-participants">
<div class="infotitre">
<h2>GESTION PARTICIPANTS</h2>
</div>
<section class="container-section-participants">
<section class="escrimeblois">
<div class="subtitreparticipant">
<h3>Tireurs du Club de l’Escrime de Blois</h3>
<p class="nb">{{ nb_participants_blois }}</p>
</div>
<div class="gestion-participants-list">
{% if participants_blois %}
{% for participant in participants_blois %}
<div class="gestionp">
<div class="participant">
<p>{{ participant.Escrimeur.prenomE }}</p>
<p>{{ participant.Escrimeur.nomE }}</p>
<p>|</p>
<p>{{ participant.Categorie.nomCategorie }}</p>
</div>
<div class="suppd">
<form action="{{ url_for('delete_participant', id_comp = competition.idComp,id=participant.Escrimeur.numeroLicenceE) }}" method="post">
<button style="font-size: 30px" type="submit">-</button>
</form>
</div>
</div>
{% endfor %} {% else %}
<p class="nullparticipant">Aucun participant de l'escrime de Blois</p>
{% endif %}
<div class="addp">
<button style="font-size: 30px">+</button>
<div class="submenu" style="display: none;">
<input type="text" class="search" placeholder="Rechercher…">
<ul class="escrimeurs-list"></ul>
</div>
</div>
</div>
</div>
</section>
<section class="escrime-other">
<div class="subtitreparticipant">
<h3>Tireurs d’autres club</h3>
<p class="nb">{{ nb_participants_other }}</p>
</div>
<div class="gestion-participants-list">
{% if participants_other %}
{% for participant in participants_other %}
<div class="gestionp">
<div class="participant">
<p>{{ participant.Escrimeur.prenomE }}</p>
<p>{{ participant.Escrimeur.nomE }}</p>
<p>|</p>
<p>{{ participant.Categorie.nomCategorie }}</p>
</div>
<div class="suppd">
<form action="{{ url_for('delete_participant', id_comp = competition.idComp,id=participant.Escrimeur.numeroLicenceE) }}" method="post">
<button style="font-size: 30px" type="submit">-</button>
</form>
</div>
</div>
{% endfor %}{% else %}
<p class="nullparticipant">Aucun participant d'autres clubs</p>
{% endif %}
<div class="addp">
<button style="font-size: 30px">+</button>
<div class="submenu" style="display: none;">
<input type="text" class="search" placeholder="Rechercher…">
<ul class="escrimeurs-list"></ul>
</div>
</div>
</section>
<section class="escrime-arb">
<div class="subtitreparticipant">
<h3>Arbitres</h3>
<p class="nb">{{ nb_participants_arb }}</p>
</div>
<div class="gestion-participants-list">
{% if participants_arb %}
{% for arbitre, escrimeur, categorie in participants_arb %} <div class ="gestionp">
<div class="participant">
<p>{{ escrimeur.prenomE }}</p>
<p>{{ escrimeur.nomE }}</p>
<p>|</p>
<p>{{ escrimeur.categorie.nomCategorie }}</p>
</div>
<div class="suppd">
<form
action="{{ url_for('delete_participant', id_comp = competition.idComp,id=escrimeur.numeroLicenceE) }}"
method="post"
>
<button style="font-size: 30px" type="submit">-</button>
</form>
</div>
</div>
{% endfor %}
{% else %}
<p class = "nullparticipant">Aucun arbitres pour le moment</p>
{% endif %}
<div class="addp">
<button style="font-size: 30px">+</button>
<div class="submenu" style="display: none;">
<input type="text" class="search" placeholder="Rechercher…">
<ul class="escrimeurs-list"></ul>
</div>
</div>
</section>
</section>
</section>
<div class="center">
<div class="btndiv">
<a href="{{ url_for('home_default') }}" class="btn-annuler">ANNULER</a>
<a href="{{ url_for('gestion_poules', id_comp = competition.idComp) }}" class="btn-publier"
>CREER LES POULES</a
>
</div>
</div>
{% endblock %}
</section>
import random
from .app import app, db, mail
import logging
import math
from .ajout_bd import *
from flask import jsonify, render_template, session, url_for, redirect, request, flash
from .models import *
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired
from wtforms import StringField, PasswordField
from hashlib import sha256
from flask_login import login_user, logout_user, current_user
from flask_mail import Message
from flask import make_response
from weasyprint import HTML
def send_verification_email(user_email, code):
with app.app_context():
msg = Message("Votre code de vérification", recipients=[user_email])
msg.body = f"Votre code de vérification est : {code}"
mail.send(msg)
logging.basicConfig(filename='debug.log', level=logging.DEBUG)
class LoginForm(FlaskForm):
email_username = StringField('email_username', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
def get_authenticated_user(self):
user = User.query.filter_by(emailUser=self.email_username.data).first()
if user is None:
user = User.query.filter_by(pseudoUser=self.email_username.data).first()
if user is None:
return None
m = sha256 ()
m.update(self.password.data.encode ())
passwd = m. hexdigest ()
return user if passwd == user.mdpUser else None
class InscriptionForm(FlaskForm):
pseudo = StringField('pseudo', validators=[DataRequired()])
email = StringField('email', validators=[DataRequired()])
password = PasswordField('password', validators=[DataRequired()])
comfirm_password = PasswordField('comfirm_password', validators=[DataRequired()])
class EditUserForm(FlaskForm):
newpsswd = PasswordField("Nouveau mot de passe")
confirm = PasswordField("Confirmez le nouveau mot de passe")
username = StringField("Pseudonyme actuelle")
password = PasswordField("Mot de passe actuelle")
@app.context_processor
def inject_user_status():
if current_user.is_authenticated:
return {"user_status": current_user.statutUser}
return {"user_status": None}
@app.route("/gestion_score/")
def gestion_score():
if request.method == "POST":
pass
rows_data = [
{'Nom': 'Doe', 'Prenom': 'John', 'Club': 'Club A'},
{'Nom': 'Smith', 'Prenom': 'Alice', 'Club': 'Club A'},
{'Nom': 'Johnson', 'Prenom': 'Bob', 'Club': 'Club A'},
{'Nom': 'Williams', 'Prenom': 'Emma', 'Club': 'Club A'}
]
# Définir le nombre de lignes et de colonnes dans le tableau
rows = len(rows_data)
cols = len(rows_data)
# Générer les données pour le tableau
table_data = [[f'input_{i}_{j}' for j in range(cols)] for i in range(rows)]
# Rendre le modèle HTML avec Flask
return render_template('Score.html', table_data=table_data, rows_data=rows_data, rows=rows, cols=cols)
@app.route("/afficher-score-poule/<int:id_comp>/")
def afficher_score_poule(id_comp):
competition = Competition.query.get_or_404(id_comp)
scores = get_scores_for_competition(id_comp)
return render_template('Affichage-score.html', data=scores, competition=competition)
def get_scores_for_competition(id_comp):
classements = db.session.query(ClassementFinal, Escrimeur, Club).join(
Tireur, ClassementFinal.numeroLicenceE == Tireur.numeroLicenceE
).join(
Escrimeur, Tireur.numeroLicenceE == Escrimeur.numeroLicenceE
).join(
Club, Tireur.idClub == Club.idClub
).filter(
ClassementFinal.idComp == id_comp
).order_by(
ClassementFinal.position
).all()
scores = []
for classement, escrimeur, club in classements:
poules = Poule.query.filter_by(idComp=id_comp).subquery()
victoires = db.session.query(MatchPoule).join(poules, MatchPoule.idPoule == poules.c.idPoule).filter(
db.or_(
db.and_(MatchPoule.numeroLicenceE1 == escrimeur.numeroLicenceE,
MatchPoule.touchesDonneesTireur1 > MatchPoule.touchesRecuesTireur1),
db.and_(MatchPoule.numeroLicenceE2 == escrimeur.numeroLicenceE,
MatchPoule.touchesDonneesTireur2 > MatchPoule.touchesRecuesTireur2)
)
).count()
total_matchs = db.session.query(MatchPoule).join(poules, MatchPoule.idPoule == poules.c.idPoule).filter(
db.or_(
MatchPoule.numeroLicenceE1 == escrimeur.numeroLicenceE,
MatchPoule.numeroLicenceE2 == escrimeur.numeroLicenceE
)
).count()
print(victoires, total_matchs)
vm_ratio = (victoires / total_matchs) if total_matchs > 0 else "N/A"
scores.append({
'Classement': classement.position,
'Prenom': escrimeur.prenomE,
'Nom': escrimeur.nomE,
'VM': vm_ratio,
'Club': club.nomClub
})
return scores
@app.route("/telecharger-pdf/<int:id_comp>/")
def telecharger_pdf(id_comp):
scores = get_scores_for_competition(id_comp)
competition = Competition.query.get_or_404(id_comp)
rendered = render_template('score_table_pdf.html', data=scores)
pdf = HTML(string=rendered).write_pdf()
response = make_response(pdf)
response.headers['Content-Type'] = 'application/pdf'
response.headers['Content-Disposition'] = f'attachment; filename=tableau_scores_{competition.nomComp}.pdf'
return response
@app.route("/inscription-form/")
def inscription_page():
return render_template("Inscription.html", form = InscriptionForm())
@app.route("/inscription/", methods=["GET", "POST"])
def inscription():
f = InscriptionForm()
if(User.query.filter_by(pseudoUser=f.pseudo.data).first() is not None or User.query.filter_by(emailUser=f.email.data).first() is not None or f.password.data != f.comfirm_password.data):
if(User.query.filter_by(pseudoUser=f.pseudo.data).first() is not None):
flash("Pseudo déjà utilisé", "error")
if(User.query.filter_by(emailUser=f.email.data).first() is not None):
flash("Email déjà utilisé", "error")
if(f.password.data != f.comfirm_password.data):
flash("Les mots de passe ne correspondent pas", "error")
return render_template("Inscription.html", form=f)
else:
m = sha256()
m.update(f.password.data.encode())
u = User(pseudoUser=f.pseudo.data , mdpUser=m.hexdigest(), emailUser=f.email.data, statutUser="Utilisateur")
db.session.add(u)
db.session.commit()
return redirect(url_for("home"))
@app.route("/login/", methods=["GET", "POST"])
def login():
f = LoginForm()
user = f.get_authenticated_user()
if user:
login_user(user)
return redirect(url_for("home_default"))
else:
flash("Mot de passe incorrect", "error")
return render_template("Login.html", form=f)
@app.route("/logout/")
def logout ():
logout_user ()
return redirect(url_for("home"))
@app.route('/home/<int:items>', methods=("GET","POST",))
def home_def(items):
total_pages = 0
if request.method == "POST":
page = int(request.form.get('page', 1))
if 'next' in request.form:
page += 1
elif 'prev' in request.form:
page -= 1
# récupere les selection du from
session['categorie'] = request.form.get('categorie')
session['arme'] = request.form.get('arme')
session['sexe'] = request.form.get('sexe')
session['statut'] = request.form.get('statut')
else:
page = request.args.get('page', 1, type=int)
session['categorie'] = request.args.get('categorie', session.get('categorie'))
session['arme'] = request.args.get('arme', session.get('arme'))
session['sexe'] = request.args.get('sexe', session.get('sexe'))
session['statut'] = request.args.get('statut', session.get('statut'))
competitions = get_sample()
categories = get_categories()
armes = get_armes()
nb_participants = {comp.idComp: get_nb_participants(comp.idComp) for comp in competitions}
# filtre pour les compet
compet_filtre = filtrer_competitions(competitions, session.get('categorie'), session.get('arme'), session.get('sexe'), session.get('statut'))
if len(compet_filtre) !=0:
total_pages = math.ceil(len(compet_filtre) / items)
competitions = compet_filtre[(page - 1) * items:page * items]
else:
competitions = []
return render_template(
"competition.html",
title="Compétitions ESCRIME",
competitions=competitions,
categories=categories,
armes=armes,
nb_participants=nb_participants,
items=items,
selec_arme=session.get('arme'),
selec_categorie=session.get('categorie'),
selec_sexe=session.get('sexe'),
selec_statut=session.get('statut'),
page=page,
compet_filtre = compet_filtre,
total_pages=total_pages
)
@app.route('/liste-adherent/<int:items>', methods=["GET", "POST"])
def liste_adherents(items):
total_pages = 0
if request.method == "POST":
page = int(request.form.get('page', 1))
if 'next' in request.form:
page += 1
elif 'prev' in request.form:
page -= 1
else:
page = request.args.get('page', 1, type=int)
adherents = get_adherents()
categories = get_categories()
role = request.form.get('statut', session.get('statuta', ''))
categorie = request.form.get('categorie', session.get('categoriea', ''))
sexe = request.form.get('sexe', session.get('sexea', ''))
adherents = filtrer_adherent(adherents, categorie, sexe)
if request.method == "POST":
search_query = request.form.get('search')
# recherche les adhérents en fonction du nom ou prénom
if search_query:
adherents = [adherent for adherent in adherents if search_query.lower() in adherent.Escrimeur.prenomE.lower() or search_query.lower() in adherent.Escrimeur.nomE.lower() or search_query.lower() in str(adherent.Escrimeur.numeroLicenceE)]
session['statuta'] = role
session['categoriea'] = categorie
session['sexea'] = sexe
if len(adherents) !=0:
total_pages = math.ceil(len(adherents) / items)
adherents = adherents[(page - 1) * items:page * items]
else:
adherents = []
return render_template(
"liste-adherents.html",
title="Compétitions ESCRIME",
categories=categories,
selec_categorie=categorie,
selec_sexe=sexe,
selec_statut=role,
adherents=adherents,
items=items,
page=page,
total_pages=total_pages)
@app.route('/home/')
def home_default():
return home_def(5)
@app.route('/annuler_comp', methods=['POST'])
def annuler_comp():
# Rediriger vers l'URL d'origine
return redirect(request.referrer or url_for('home_default'))
@app.route("/test_popup/")
def test_popup():
return render_template(
"test_popup.html",
title="Test")
@app.route("/edit-user/<name>", methods=("GET","POST",))
def edit_user(name):
form = EditUserForm()
if not current_user.is_authenticated:
next = "edit_user"
return redirect(url_for("login", next=next))
if form.validate_on_submit():
print("Formulaire valide")
user = current_user
if user.pseudoUser != form.username.data:
form.username.errors.append("Pseudonyme erreur")
return render_template("edit-user.html", form=form, name=name, show_verification_popup=False)
if form.newpsswd.data != form.confirm.data:
form.confirm.errors.append("Les mots de passe ne correspondent pas")
return render_template("edit-user.html", form=form, name=name, show_verification_popup=False)
code = str(random.randint(1000, 9999))
print(code)
print(user.emailUser)
send_verification_email(user.emailUser, code)
print("Email envoyé")
session['verification_code'] = code # Stocker le code temporairement
session['user_id'] = user.idUser
session['new_password'] = form.newpsswd.data # Stocker le nouveau mot de passe temporairement
print("affichage popup")
return render_template("edit-user.html", form=form, name=name, show_verification_popup=True)
return render_template("edit-user.html", form=form, name=name, show_verification_popup=False)
@app.route("/verify-code/<name>", methods=["GET", "POST"])
def verify_code(name):
if request.method == "POST":
user_code = request.form['code']
print(user_code)
if user_code == session.get('verification_code'):
# Récupérer l'utilisateur et les informations nécessaires
user = User.query.get(session.get('user_id'))
if not user:
return "Utilisateur non trouvé", 404
# Procéder à la mise à jour du mot de passe
new_password = session.get('new_password')
new_password_hash = sha256()
new_password_hash.update(new_password.encode())
user.mdpUser = new_password_hash.hexdigest()
db.session.commit()
# Nettoyer la session
del session['verification_code']
del session['user_id']
del session['new_password']
return redirect(url_for("home")) # "Mot de passe mis à jour avec succès!"
else:
flash("Code de vérification incorrect", "error")
return render_template("edit-user.html", name=name, form=EditUserForm(), show_verification_popup=True)
@app.route('/ajouter_escrimeur/', methods=['GET', 'POST'])
def ajouter_escrimeur():
if request.method == 'POST':
id = dernier_escrimeur_id() + 1
print(id)
#recup donnees du formulaire
nom = request.form['nom_e']
print(nom)
prenom = request.form['prenom_e']
print(prenom)
date_naissance = request.form['date_naissance_e']
print(date_naissance)
numero_licence = request.form['numero_licence_e']
numero_licence = int(numero_licence)
print(numero_licence)
# sexe = request.form['sexe_e']
sexe = 'H'
print(sexe)
# num_tel = request.form['num_tel_e']
num_tel = '0648572519'
print(num_tel)
default_cat = 1
# creez un nouvel enregistrement d'adherent
nouvel_adherent = Escrimeur(categorie=default_cat, prenom_e=prenom, nom_e=nom, date_naissance_e=date_naissance, numero_licence_e=numero_licence, sexe_e=sexe, num_tel_e=num_tel)
db.session.add(nouvel_adherent)
db.session.commit()
id_club_blois = 169
classement_tireur = 0
nouveau_tireur = Tireur(num_licence=numero_licence, club=id_club_blois, classement=classement_tireur)
db.session.add(nouveau_tireur)
db.session.commit()
return redirect(url_for('liste_adherents_def'))
@app.route('/')
def home():
return render_template('Login.html')
from flask import session
@app.route('/gestion_poules/<int:id_comp>', methods=["GET", "POST"])
def gestion_poules(id_comp):
liste_poules = []
nb_tireurs = get_nb_tireurs(id_comp)
nb_arbitres = get_nb_arbitres(id_comp)
nb_tireurs_par_poule = nb_tireurs // nb_arbitres
if request.method == "POST":
classement_checked = 'classement' in request.form
club_checked = 'club' in request.form
equilibrer_checked = 'equilibrer' in request.form
nb_poules = int(request.form.get('nb_poules'))
nb_tireurs_poules_str = request.form.get('nb_tireurs/poules')
if nb_tireurs_poules_str and nb_tireurs_poules_str.isdigit():
nb_tireurs_poules = int(nb_tireurs_poules_str)
liste_tireurs = get_liste_participants_competitions_tireurs(id_comp)
liste_arbitres = get_liste_participants_competitions_arbitres(id_comp)
liste_pistes = get_liste_pistes_selon_nb_arbitres(id_comp, nb_arbitres)
nb_tireurs_par_poule = nb_tireurs // nb_arbitres
numero_licence_arbitre = request.form.get('numero_licence_arbitre')
id_arbitre = get_id_arbitre_from_escrimeur(numero_licence_arbitre)
if classement_checked:
liste_tireurs = classer_tireurs(liste_tireurs)
if poules_fabriquables(liste_tireurs, liste_arbitres):
liste_poules = fabriquer_poules(liste_tireurs, liste_arbitres, liste_pistes, "Classement")
elif club_checked:
if poules_fabriquables(liste_tireurs, liste_arbitres):
liste_poules = fabriquer_poules(liste_tireurs, liste_arbitres, liste_pistes, "Club")
session["liste_poules"] = [ [escrimeur[0].numeroLicenceE for escrimeur in poule] for poule in liste_poules]
session["liste_arbitres"] = [arbitre.numeroLicenceE for arbitre in liste_arbitres]
session["liste_pistes"] = [piste.idPiste for piste in liste_pistes]
return render_template('gestion_poules.html', id_comp=id_comp, nb_tireurs=get_nb_tireurs(id_comp),
nb_arbitres=get_nb_arbitres(id_comp), liste_tireurs=liste_tireurs, liste_arbitres=liste_arbitres,
liste_poules=liste_poules, nb_tireurs_par_poule=nb_tireurs_par_poule, liste_pistes=liste_pistes)
liste_tireurs = get_liste_participants_competitions_tireurs(id_comp)
liste_arbitres = get_liste_participants_competitions_arbitres(id_comp)
liste_pistes = get_liste_pistes_selon_nb_arbitres(id_comp, nb_arbitres)
competition = Competition.query.get(id_comp)
if competition is not None:
return render_template('gestion_poules.html', id_comp=id_comp, nb_tireurs=nb_tireurs, nb_arbitres=nb_arbitres,
liste_tireurs=liste_tireurs, liste_arbitres=liste_arbitres,
liste_poules=liste_poules, nb_tireurs_par_poule=nb_tireurs_par_poule, liste_pistes=liste_pistes)
@app.route("/appel/<int:id_comp>", methods=["GET", "POST"])
def appel(id_comp):
rows_data = []
participants_present = []
if request.method == "POST":
pistes = session.get("liste_pistes")
arbitres = session.get("liste_arbitres")
liste_poules = session.get("liste_poules")
try:
for i in range(len(liste_poules)):
num_licence_arbitre = arbitres[i]
id_arbitre = get_id_arbitre_from_escrimeur(num_licence_arbitre)
nom_poule = f"Poule {i+1}"
id_piste = pistes[i]
ajouter_poule(id_comp, id_piste, id_arbitre, nom_poule)
id_poule = get_id_poule(id_comp, id_piste, id_arbitre, nom_poule)
for j in range(1, len(liste_poules[i])):
ajouter_participant_poule(id_poule, liste_poules[i][j])
tireur = Tireur.query.get(liste_poules[i][j])
rows_data.append(tireur.to_dict())
redirect(url_for('appel', id_comp=id_comp))
competition = Competition.query.get(id_comp)
return render_template('appel.html', competition = competition, rows_data=rows_data, participants_present=participants_present)
except Exception as e:
print(e)
competition = Competition.query.get(id_comp)
if competition is not None:
rows_data = []
participants_comp = get_liste_participants_competitions(id_comp)
participants_comp = get_liste_participants_competitions(id_comp)
for participant in participants_comp:
dict_tireur = participant.tireur.to_dict()
rows_data.append(dict_tireur)
participants_present = []
print(rows_data)
return render_template('appel.html', competition = competition, rows_data=rows_data, participants_present=participants_present)
@app.route('/adherent/')
def liste_adherents_def():
return liste_adherents(5)
@app.route("/ajout-comp")
def ajout_comp_page():
armes = get_armes()
categories = get_categories()
lieux = get_lieux()
types = ["Individuelle", "Equipe"]
return render_template("ajout-comp.html", listeArmes=armes, listeCategories=categories, listeTypeMatch=types, lieux=lieux)
@app.route('/ajout-comp/', methods=['POST'])
def ajout_comp():
# Récupérez les données du formulaire
nomLieu = request.form.get('nomLieu')
adresseLieu = request.form.get('adresseLieu')
villeLieu = request.form.get('villeLieu')
cpLieu = request.form.get('codePostalLieu')
nomSaison = "Saison 2023" # Supposons que c'est fixe pour cet exemple
nomCat = request.form.get('categorie') # Assurez-vous que le nom correspond au champ dans le HTML
nomArme = request.form.get('arme') # Idem
nomComp = request.form.get('titre')
nomOrga = request.form.get('organisateur')
descComp = f"Competition {nomComp} organisée par {nomOrga}" # Ajoutez un champ pour la description si nécessaire
dateComp = request.form.get('date-deroulement')
heureComp = request.form.get('appt')
sexeComp = request.form.get('sexe')[:1].upper()
estIndividuelle = request.form.get('type') == 'Individuelle'
print(nomLieu,adresseLieu,villeLieu,cpLieu, nomSaison, nomCat, nomArme, nomComp, nomOrga, descComp, dateComp, heureComp, sexeComp, estIndividuelle)
resultat = creer_competition(nomLieu,adresseLieu,villeLieu,cpLieu, nomSaison, nomCat, nomArme, nomComp, descComp, dateComp, heureComp, sexeComp, estIndividuelle)
if isinstance(resultat, Competition):
return redirect(url_for('gestion_participants', id_comp=resultat.idComp))
else:
return redirect(url_for('ajout_comp_page'))
# @app.route('/annuler_comp', methods=['POST'])
# def annuler_comp():
# if lieu is None:
# lieu = Lieu(nom_lieu=form.lieu.data, ville_lieu="", code_postal_lieu=0, adresse_lieu="")
# db.session.add(lieu)
# db.session.commit()
# competition = Competition(idLieu=lieu.idLieu,
# idSaison=Saison.query.get(1).idSaison,
# idCat=getattr(Categorie.query.filter_by(nomCategorie=form.categorie.data).first(), 'idCat', None),
# idArme=getattr(Arme.query.filter_by(nomArme=form.arme.data).first(), 'idArme', None),
# nomComp=form.titre.data,
# descComp=f"Competition organisée par {form.organisateur.data}",
# dateComp=form.date_deroulement.data,
# heureComp=form.heure_debut.data,
# sexeComp=form.sexe.data[:1],
# estIndividuelle=form.type_comp.data == 'individuel')
# db.session.add(competition)
# db.session.commit()
# flash('La compétition a été ajoutée') # à changer avec une popup
# return redirect(url_for('home'))
# # Rediriger vers l'URL d'origine
# return redirect(request.referrer or url_for('home_default'))
@app.route("/gestion_participants/<int:id_comp>", methods=("GET", "POST"))
def gestion_participants(id_comp):
competition = Competition.query.get(id_comp)
participants_blois = get_participants(id_comp, club="BLOIS CE")
participants_other = get_participants(id_comp, club="!")
participants_arb = get_arbitres(id_comp)
nb_participants_blois = len(participants_blois)
nb_participants_other = len(participants_other)
nb_participants_arb = len(participants_arb)
return render_template(
"gestion-participants.html",
title="Gestion des participants",
participants_blois=participants_blois,
nb_participants_blois=nb_participants_blois,
participants_other=participants_other,
nb_participants_other=nb_participants_other,
competition=competition,
participants_arb=participants_arb,
nb_participants_arb=nb_participants_arb
)
@app.route('/ajouter_arbitre_competition/<int:id_comp>', methods=['POST'])
def ajouter_arbitre_competition(id_comp):
data = request.get_json()
numeroLicenceE = data.get('numeroLicenceE')
logging.debug(numeroLicenceE)
arbitre = Arbitre(numeroLicenceE)
db.session.add(arbitre)
participant = ParticipantsCompetition(numeroLicenceE, id_comp)
db.session.add(participant)
db.session.commit()
logging.debug("ça passe commit participant compet")
return jsonify({'success': True, 'message': 'Arbitre ajouté avec succès'})
@app.route('/get_escrimeurs/<gender>')
def get_escrimeurs_json(gender):
escrimeurs = None
if gender == 'M':
escrimeurs = Escrimeur.query.all()
elif gender == "H":
gender = "Homme"
escrimeurs = Escrimeur.query.filter_by(sexeE=gender).all()
elif gender == "F":
gender = "Femme"
escrimeurs = Escrimeur.query.filter_by(sexeE=gender).all()
return jsonify([escrimeur.to_dict() for escrimeur in escrimeurs])
@app.route('/get_adherents')
def get_adherents_json():
escrimeurs = get_adherents_adapte_json()
return jsonify([escrimeur.to_dict() for escrimeur in escrimeurs])
@app.route('/delete_participant/<int:id_comp>/<int:id>/', methods=['POST'])
def delete_participant(id, id_comp):
participant = ParticipantsCompetition.query.filter_by(numeroLicenceE=id).first()
if participant:
db.session.delete(participant)
db.session.commit()
return redirect(url_for('gestion_participants', id_comp=id_comp))
import logging
logging.basicConfig(filename='debug.log', level=logging.DEBUG)
@app.route('/ajouter_escrimeur_competition/<int:id_comp>/', methods=['POST'])
def add_participant(id_comp):
if request.method == 'POST':
tireur = request.get_json().get('numeroLicenceE')
logging.debug(f'numerolicence_tireur: {tireur}')
tireur = Tireur.query.get(tireur)
logging.debug(f'tireur: {tireur}')
competition = Competition.query.get(id_comp)
logging.debug(f'competition: {competition}')
getattr(competition, "idComp", None)
if tireur and competition:
participant = ParticipantsCompetition(numeroLicenceE=getattr(tireur, "numeroLicenceE", None), idComp=getattr(competition, "idComp", None))
logging.debug('creation participant')
db.session.add(participant)
logging.debug('crash ?')
try:
db.session.commit()
logging.debug('Commit successful')
except Exception as e:
db.session.rollback()
logging.error(f'Error during commit: {str(e)}')
logging.debug('Participant added successfully')
else:
logging.debug('Failed to add participant')
return redirect(url_for('gestion_participants', id_comp=id_comp))
@app.route('/update_database', methods=['POST'])
def update_database():
data = request.get_json()
field = data.get('field')
value = data.get('value')
competition_id = data.get('competitionId')
competition = Competition.query.get(competition_id)
setattr(competition, field, value)
db.session.commit()
return 'OK'
@app.route('/competition/<int:id_comp>')
def actu_stat_comp(id_comp):
competition = Competition.query.get_or_404(id_comp)
state = get_competition_statut(competition)
if state == 'participants':
return redirect(url_for('gestion_participants', id_comp=id_comp))
elif state == 'poule':
return redirect(url_for('gestion_poules', id_comp=id_comp))
elif state == 'appel':
return redirect(url_for('appel', id_comp=id_comp))
elif state == 'score':
return redirect(url_for('gestion_score', id_comp=id_comp))
else:
return "les problèmes"
|
e338dd41dfa3fb9f9aa98504f08d631f
|
{
"intermediate": 0.3000416159629822,
"beginner": 0.5889824628829956,
"expert": 0.11097589135169983
}
|
35,925
|
rewrite this to python:
import { fetch, WebSocket, debug } from '@/lib/isomorphic'
import WebSocketAsPromised from 'websocket-as-promised'
import {
SendMessageParams,
BingConversationStyle,
ConversationResponse,
ChatResponseMessage,
ConversationInfo,
InvocationEventType,
ChatError,
ErrorCode,
ChatUpdateCompleteResponse,
ImageInfo,
KBlobResponse,
} from './types'
import { convertMessageToMarkdown, websocketUtils, streamAsyncIterable } from './utils'
import { createChunkDecoder } from '@/lib/utils'
import { randomUUID } from 'crypto'
import md5 from 'md5'
type Params = SendMessageParams<{ bingConversationStyle: BingConversationStyle, allowSearch?: boolean, retryCount?: number }>
const getOptionSets = (conversationStyle: BingConversationStyle, allowSeach = true) => {
const results = {
[BingConversationStyle.Creative]: [
'nlu_direct_response_filter',
'deepleo',
'disable_emoji_spoken_text',
'responsible_ai_policy_235',
'enablemm',
'dv3sugg',
'autosave',
'iyxapbing',
'iycapbing',
'h3imaginative',
'gptvprvc',
'fluxpcalc',
'eredirecturl',
'clgalileo',
'gencontentv3',
'fluxv14l'
],
[BingConversationStyle.Balanced]: [
'nlu_direct_response_filter',
'deepleo',
'disable_emoji_spoken_text',
'responsible_ai_policy_235',
'enablemm',
'dv3sugg',
'autosave',
'iyxapbing',
'iycapbing',
'galileo',
'gptvprvc',
'fluxpcalc',
'eredirecturl',
'saharagenconv5'
],
[BingConversationStyle.Precise]: [
'nlu_direct_response_filter',
'deepleo',
'disable_emoji_spoken_text',
'responsible_ai_policy_235',
'enablemm',
'dv3sugg',
'autosave',
'iyxapbing',
'iycapbing',
'h3precise',
'gptvprvc',
'fluxpcalc',
'eredirecturl',
'clgalileo',
'gencontentv3',
'fluxv14l'
],
[BingConversationStyle.Base]: [
'deepleo',
'disable_emoji_spoken_text',
'responsible_ai_policy_235',
'enablemm',
'dv3sugg',
'autosave',
'iyxapbing',
'iycapbing',
'h3imaginative',
'gptvprvc',
'fluxpcalc',
'eredirecturl',
'clgalileo',
'gencontentv3',
'fluxv14l',
'nojbfedge',
]
}[conversationStyle]
if (allowSeach === false) {
results.push('nosearchall')
}
return results
}
export class BingWebBot {
protected conversationContext?: ConversationInfo
protected endpoint = ''
protected cookie = ''
private lastText = ''
private asyncTasks: Array<Promise<any>> = []
get isInitial() {
return (this.conversationContext?.invocationId??0) < 1
}
constructor(opts: {
endpoint?: string
cookie?: string
}) {
const { endpoint, cookie } = opts
this.endpoint = endpoint || ''
this.cookie = cookie || ''
}
static buildChatRequest(conversation: ConversationInfo) {
const uuid = randomUUID()
const useBaseSets = (conversation.context?.length ?? 0) > 0
const message = {
locale: 'zh-CN',
market: 'zh-CN',
region: 'US',
locationHints: [
{
country: 'United States',
state: 'California',
city: 'Los Angeles',
timezoneoffset: 8,
countryConfidence: 8,
Center: {
Latitude: 34.0536909,
Longitude: -118.242766
},
RegionType: 2,
SourceType: 1
}
],
author: 'user',
inputMethod: 'Keyboard',
messageType: 'Chat',
text: conversation.prompt,
imageUrl: conversation.imageUrl,
requestId: uuid,
messageId: uuid
}
const argument = {
optionsSets: getOptionSets(useBaseSets ? BingConversationStyle.Base : conversation.conversationStyle, conversation.allowSearch),
sliceIds: [
'gbaa',
'gba',
'emovoice',
'tts3cf',
'kcinherocf',
'inochatv2',
'wrapnoins',
'mlchatpc9000ns',
'mlchatpcbase',
'sydconfigoptt',
'803iyjbexps0',
'0529streamws0',
'178gentechs0',
'0901utilbal',
'attr2atral3',
'821iypapyrust',
'019hlthgrd',
'829suggtrim',
'821fluxv13s0',
'727nrprdrt3'
],
message,
source: 'cib',
spokenTextMode: 'None',
allowedMessageTypes: [
'ActionRequest',
'Chat',
'ConfirmationCard',
'Context',
'InternalSearchQuery',
'InternalSearchResult',
'Disengaged',
'InternalLoaderMessage',
'InvokeAction',
'Progress',
'RenderCardRequest',
'RenderContentRequest',
// 'AdsQuery',
'SemanticSerp',
'GenerateContentQuery',
'SearchQuery'
],
conversationHistoryOptionsSets: [
'autosave',
'savemem',
'uprofupd',
'uprofgen'
],
previousMessages: conversation.context?.length ? [{
author: 'user',
description: conversation.context,
contextType: 'WebPage',
messageType: 'Context',
messageId: 'discover-web--page-ping-mriduna-----'
}] : undefined,
traceId: md5(new Date().toString()),
requestId: uuid,
isStartOfSession: conversation.invocationId === 0,
conversationId: conversation.conversationId,
conversationSignature: conversation.conversationSignature,
participant: { id: conversation.clientId },
plugins: [],
scenario: 'SERP',
tone: conversation.conversationStyle
}
return {
arguments: [argument],
invocationId: `${conversation.invocationId ?? 0}`,
target: 'chat',
type: InvocationEventType.StreamInvocation,
}
}
async createConversation(conversationId?: string): Promise<ConversationResponse> {
const headers = {
'Accept-Encoding': 'gzip, deflate, br, zsdch',
'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
cookie: this.cookie,
}
let resp: ConversationResponse | undefined
try {
const search = conversationId ? `?conversationId=${encodeURIComponent(conversationId)}` : ''
const response = await fetch(`${this.endpoint}/api/create${search}`, { method: 'POST', headers, mode: 'cors', credentials: 'include' })
if (response.status === 404) {
throw new ChatError('Not Found', ErrorCode.NOTFOUND_ERROR)
}
if (response.headers.has('cookie')) {
this.cookie = response.headers.get('cookie')!
}
resp = await response.json() as ConversationResponse
} catch (err) {
console.error('create conversation error', err)
}
if (!resp?.result) {
throw new ChatError('你的 VPS 或代理可能被封禁,如有疑问,请前往 https://github.com/weaigc/bingo 咨询', ErrorCode.BING_IP_FORBIDDEN)
}
const { value, message } = resp.result || {}
if (value !== 'Success') {
const errorMsg = `${value}: ${message}`
if (value === 'UnauthorizedRequest') {
if (/fetch failed/i.test(message || '')) {
throw new ChatError(errorMsg, ErrorCode.BING_IP_FORBIDDEN)
}
throw new ChatError(errorMsg, ErrorCode.BING_UNAUTHORIZED)
}
if (value === 'TryLater') {
throw new ChatError(errorMsg, ErrorCode.BING_TRY_LATER)
}
if (value === 'Forbidden') {
throw new ChatError(errorMsg, ErrorCode.BING_FORBIDDEN)
}
throw new ChatError(errorMsg, ErrorCode.UNKOWN_ERROR)
}
return resp
}
async createContext(conversationStyle: BingConversationStyle) {
if (!this.conversationContext) {
const conversation = await this.createConversation()
this.conversationContext = {
conversationId: conversation.conversationId,
userIpAddress: conversation.userIpAddress,
conversationSignature: conversation.conversationSignature,
encryptedconversationsignature: conversation.encryptedconversationsignature,
clientId: conversation.clientId,
invocationId: conversation.invocationId ?? 0,
conversationStyle,
prompt: '',
}
}
return this.conversationContext
}
async sendMessage(params: Params) {
try {
await this.createContext(params.options.bingConversationStyle)
Object.assign(this.conversationContext!, { allowSearch: params.options.allowSearch, prompt: params.prompt, imageUrl: params.imageUrl, context: params.context })
return this.sydneyProxy(params)
} catch (error) {
const formatError = error instanceof ChatError ? error : new ChatError('Catch Error', ErrorCode.UNKOWN_ERROR)
params.onEvent({
type: 'ERROR',
error: formatError,
})
throw formatError
}
}
private async sydneyProxy(params: Params, reconnect: boolean = false) {
this.lastText = ''
const abortController = new AbortController()
const response = await fetch(this.endpoint + '/api/sydney', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
cookie: this.cookie,
},
signal: abortController.signal,
body: JSON.stringify(this.conversationContext!)
}).catch(e => {
console.log('Fetch Error: ', e)
if (reconnect) return
params.onEvent({
type: 'ERROR',
error: new ChatError(
String(e),
ErrorCode.UNKOWN_ERROR,
),
})
return e
})
const conversation = this.conversationContext!
const originalInvocationId = conversation.invocationId
conversation.invocationId++
if (reconnect) return
if (response.status !== 200) {
conversation.invocationId = originalInvocationId
params.onEvent({
type: 'ERROR',
error: new ChatError(
'Network error',
ErrorCode.UNKOWN_ERROR,
),
})
}
params.signal?.addEventListener('abort', () => {
abortController.abort()
params.onEvent({
type: 'ERROR',
error: new ChatError(
'Canceled',
ErrorCode.BING_ABORT,
),
})
})
const textDecoder = createChunkDecoder()
const timeout = () => {
if (params.options.retryCount??0 > 5) {
params.onEvent({
type: 'ERROR',
error: new ChatError(
'Timeout',
ErrorCode.BING_TRY_LATER,
),
})
} else {
conversation.invocationId = originalInvocationId
params.options.retryCount = (params.options.retryCount ?? 0) + 1
this.sydneyProxy(params, true)
}
}
let t = conversation.invocationId ? undefined : setTimeout(timeout, 6000)
for await (const chunk of streamAsyncIterable(response.body!)) {
clearTimeout(t)
t = setTimeout(timeout, 6000)
this.parseEvents(params, websocketUtils.unpackMessage(textDecoder(chunk)))
}
clearTimeout(t)
}
async sendWs() {
const wsConfig: ConstructorParameters<typeof WebSocketAsPromised>[1] = {
packMessage: websocketUtils.packMessage,
unpackMessage: websocketUtils.unpackMessage,
createWebSocket: (url) => new WebSocket(url, {
headers: {
'accept-language': 'zh-CN,zh;q=0.9',
'cache-control': 'no-cache',
pragma: 'no-cache',
cookie: this.cookie,
}
})
}
const wsp = new WebSocketAsPromised('wss://sydney.bing.com/sydney/ChatHub', wsConfig)
wsp.open().then(() => {
wsp.sendPacked({ protocol: 'json', version: 1 })
wsp.sendPacked({ type: 6 })
wsp.sendPacked(BingWebBot.buildChatRequest(this.conversationContext!))
})
return wsp
}
private async createImage(prompt: string, id: string) {
const headers = {
'Accept-Encoding': 'gzip, deflate, br, zsdch',
'x-ms-useragent': 'azsdk-js-api-client-factory/1.0.0-beta.1 core-rest-pipeline/1.10.0 OS/Win32',
cookie: this.cookie,
}
const query = new URLSearchParams({
prompt,
id
})
const response = await fetch(this.endpoint + '/api/image?' + query.toString(),
{
method: 'POST',
headers,
mode: 'cors',
credentials: 'include'
})
.then(async (response) => {
if (response.status == 200) {
return response.text();
} else {
throw new ChatError(String(await response.text()), ErrorCode.BING_IMAGE_UNAUTHORIZED)
}
})
if (response) {
this.lastText += '\n' + response
}
}
private buildKnowledgeApiPayload(imageUrl: string, conversationStyle: BingConversationStyle) {
const imageInfo: ImageInfo = {}
let imageBase64: string | undefined = undefined
const knowledgeRequest = {
imageInfo,
knowledgeRequest: {
invokedSkills: [
'ImageById'
],
subscriptionId: 'Bing.Chat.Multimodal',
invokedSkillsRequestData: {
enableFaceBlur: true
},
convoData: {
convoid: this.conversationContext?.conversationId,
convotone: conversationStyle,
}
},
}
if (imageUrl.startsWith('data:image/')) {
imageBase64 = imageUrl.replace('data:image/', '');
const partIndex = imageBase64.indexOf(',')
if (partIndex) {
imageBase64 = imageBase64.substring(partIndex + 1)
}
} else {
imageInfo.url = imageUrl
}
return { knowledgeRequest, imageBase64 }
}
async uploadImage(imageUrl: string, conversationStyle: BingConversationStyle = BingConversationStyle.Creative): Promise<KBlobResponse | undefined> {
if (!imageUrl) {
return
}
await this.createContext(conversationStyle)
const payload = this.buildKnowledgeApiPayload(imageUrl, conversationStyle)
const response = await fetch(this.endpoint + '/api/kblob',
{
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
mode: 'cors',
credentials: 'include',
body: JSON.stringify(payload),
})
.then(res => res.json())
.catch(e => {
console.log('Error', e)
})
return response
}
private async generateContent(message: ChatResponseMessage) {
if (message.contentType === 'IMAGE') {
this.asyncTasks.push(this.createImage(message.text, message.messageId))
}
}
private async parseEvents(params: Params, events: any) {
events?.forEach(async (event: ChatUpdateCompleteResponse) => {
// debug('bing event', JSON.stringify(event))
if (event.type === 3) {
await Promise.all(this.asyncTasks)
.catch(error => {
params.onEvent({
type: 'ERROR',
error: error instanceof ChatError ? error : new ChatError('Catch Error', ErrorCode.UNKOWN_ERROR),
})
})
this.asyncTasks = []
params.onEvent({ type: 'UPDATE_ANSWER', data: { text: this.lastText } })
params.onEvent({ type: 'DONE' })
} else if (event.type === 1) {
const { messages, throttling } = event.arguments[0] || {}
if (messages) {
const message = messages[0]
if (message.messageType === 'InternalSearchQuery' || message.messageType === 'InternalLoaderMessage') {
return params.onEvent({ type: 'UPDATE_ANSWER', data: { text: '', progressText: message.text } })
}
const text = convertMessageToMarkdown(message)
this.lastText = text
params.onEvent({ type: 'UPDATE_ANSWER', data: { text } })
}
if (throttling) {
params.onEvent({ type: 'UPDATE_ANSWER', data: { text: '', throttling } })
}
} else if (event.type === 2) {
const messages = event.item.messages as ChatResponseMessage[] | undefined
if (!messages) {
params.onEvent({
type: 'ERROR',
error: new ChatError(
event.item.result.error || 'Unknown error',
event.item.result.value === 'Throttled' ? ErrorCode.THROTTLE_LIMIT
: event.item.result.value === 'CaptchaChallenge' ? (this.conversationContext?.conversationId?.includes('BingProdUnAuthenticatedUsers') ? ErrorCode.BING_UNAUTHORIZED : ErrorCode.BING_CAPTCHA)
: ErrorCode.UNKOWN_ERROR
),
})
return
}
const limited = messages.some((message) =>
message.contentOrigin === 'TurnLimiter'
|| message.messageType === 'Disengaged'
)
if (limited) {
params.onEvent({
type: 'ERROR',
error: new ChatError(
'Sorry, you have reached chat limit in this conversation.',
ErrorCode.CONVERSATION_LIMIT,
),
})
return
}
const lastMessage = event.item.messages[event.item.messages.length - 1] as ChatResponseMessage
const specialMessage = event.item.messages.find(message => message.author === 'bot' && message.contentType === 'IMAGE')
if (specialMessage) {
this.generateContent(specialMessage)
}
if (lastMessage) {
const text = convertMessageToMarkdown(lastMessage)
this.lastText = text
params.onEvent({
type: 'UPDATE_ANSWER',
data: { text, throttling: event.item.throttling, suggestedResponses: lastMessage.suggestedResponses, sourceAttributions: lastMessage.sourceAttributions },
})
}
}
})
}
resetConversation() {
this.conversationContext = undefined
}
}
|
60c9cd163ba1d2446bb5c253d3480c1e
|
{
"intermediate": 0.38985496759414673,
"beginner": 0.41310346126556396,
"expert": 0.1970415860414505
}
|
35,926
|
START OF PREVIOUS DISCUSSION
END OF PREVIOUS DISCUSSION
SYSTEM: You must help analyse a dataset in python, I will ask you code questions and help. I will mostly use pandas, matplotlib and sometimes seaborn.
USER: USER: import pandas as pd
dataset_path = "Exam_Dataset/Vegetables.csv"
dataset = pd.read_csv(dataset_path)
dataset
complete it with some basic analyses and description, like .Describe, .header
ASSISTANT:
|
11c32083a2d77262b7de177bb5b81883
|
{
"intermediate": 0.6145353317260742,
"beginner": 0.19617809355258942,
"expert": 0.18928663432598114
}
|
35,927
|
assembler hello world
|
b1d736d02727a5f3d4c8361b853e3435
|
{
"intermediate": 0.18269512057304382,
"beginner": 0.4579299986362457,
"expert": 0.35937485098838806
}
|
35,928
|
<script>
from dataclasses import dataclass
from abc import ABC, abstractmethod
from typing import List
import time
@dataclass
class Area:
xl: float
xr: float
yb: float
yt: float
def serialize(self):
return {
“xl”: self.xl,
“xr”: self.xr,
“yb”: self.yb,
“yt”: self.yt
}
class Alert(ABC):
@abstractmethod
def RaiseAlert(self):
pass
@abstractmethod
def ClearAlert(self):
pass
class AreaDetector:
def init(self, areas, alerts: List[Alert] = None, alert_delay_time=0):
self.alerts = alerts
self.alert_delay_time = alert_delay_time
self.areas = []
for area in areas:
assert len(area) == 4, “Each area must be made of 4 values: [x left, x right, y bottom, y top]”
self.areas.append(Area(*area))
self.ok_areas = set()
self.suspected_areas = {}
self.alert_areas = set()
self.alert_triggered = False
def update(self, clusters_up_to_date):
“”“
To call every step.
:param clusters_up_to_date: list of tracked clusters.
“””
current_time = time.time()
self.ok_areas.clear()
for area in self.areas:
suspect = False
for cluster in clusters_up_to_date:
x, y = cluster.centroid[cluster.width_axis], cluster.centroid[cluster.depth_axis]
if area.xl <= x <= area.xr and area.yb <= y <= area.yt:
suspect = True
break
if not suspect:
self.suspected_areas.pop(area, None)
if area in self.alert_areas:
self.alert_areas.remove(area)
self.ok_areas.add(area)
elif area not in self.alert_areas:
if area not in self.suspected_areas:
self.suspected_areas[area] = current_time
if current_time - self.suspected_areas[area] >= self.alert_delay_time:
self.alert_areas.add(area)
self.suspected_areas.pop(area)
if self.alerts is None:
return
if len(self.alert_areas) > 0:
if not self.alert_triggered:
self.alert_triggered = True
for alert in self.alerts:
alert.RaiseAlert()
else:
if self.alert_triggered:
self.alert_triggered = False
for alert in self.alerts:
alert.ClearAlert()
def serialize(self):
return {
“ok_areas”: [area.serialize() for area in self.ok_areas],
“alert_areas”: [area.serialize() for area in self.alert_areas]
}
@dataclass
class Profile:
name: str
min_volume: float
max_volume: float
min_detection_duration: float
alert: Alert
def serialize(self):
return {
“name”: self.name,
“min_volume”: self.min_volume,
“max_volume”: self.max_volume,
“min_detection_duration”: self.min_detection_duration
}
</script>
Given this script, I want you to create a “ProfileAreaDetector” class.
The Cluster class hase a "get_volume" method.
|
49472d3592d6132b860ecabf6d4f6bc8
|
{
"intermediate": 0.3318442702293396,
"beginner": 0.42605167627334595,
"expert": 0.24210402369499207
}
|
35,929
|
<script>
from dataclasses import dataclass
from abc import ABC, abstractmethod
from typing import List
import time
@dataclass
class Area:
xl: float
xr: float
yb: float
yt: float
def serialize(self):
return {
"xl": self.xl,
"xr": self.xr,
"yb": self.yb,
"yt": self.yt
}
class Alert(ABC):
@abstractmethod
def RaiseAlert(self):
pass
@abstractmethod
def ClearAlert(self):
pass
class AreaDetector:
def __init__(self, areas, alerts: List[Alert] = None, alert_delay_time=0):
self.alerts = alerts
self.alert_delay_time = alert_delay_time
self.areas = []
for area in areas:
assert len(area) == 4, "Each area must be made of 4 values: [x left, x right, y bottom, y top]"
self.areas.append(Area(*area))
self.ok_areas = set()
self.suspected_areas = {}
self.alert_areas = set()
self.alert_triggered = False
def update(self, clusters_up_to_date):
"""
To call every step.
:param clusters_up_to_date: list of tracked clusters.
"""
current_time = time.time()
self.ok_areas.clear()
for area in self.areas:
suspect = False
for cluster in clusters_up_to_date:
x, y = cluster.centroid[cluster.width_axis], cluster.centroid[cluster.depth_axis]
if area.xl <= x <= area.xr and area.yb <= y <= area.yt:
suspect = True
break
self.adjust_tracking(current_time, area, suspect)
self.handle_alerts()
def adjust_tracking(self, current_time, area, suspect):
if not suspect:
self.suspected_areas.pop(area, None)
if area in self.alert_areas:
self.alert_areas.remove(area)
self.ok_areas.add(area)
elif area not in self.alert_areas:
if area not in self.suspected_areas:
self.suspected_areas[area] = current_time
if current_time - self.suspected_areas[area] >= self.alert_delay_time:
self.alert_areas.add(area)
self.suspected_areas.pop(area)
def handle_alerts(self):
if self.alerts is None:
return
if len(self.alert_areas) > 0:
if not self.alert_triggered:
self.alert_triggered = True
for alert in self.alerts:
alert.RaiseAlert()
else:
if self.alert_triggered:
self.alert_triggered = False
for alert in self.alerts:
alert.ClearAlert()
def serialize(self):
return {
"ok_areas": [area.serialize() for area in self.ok_areas],
"alert_areas": [area.serialize() for area in self.alert_areas]
}
@dataclass
class Profile:
name: str
min_volume: float
max_volume: float
alert_delay_time: float
alert: Alert
def serialize(self):
return {
"name": self.name,
"min_volume": self.min_volume,
"max_volume": self.max_volume,
"alert_delay_time": self.alert_delay_time
}
</script>
Given the above script, write a "ProfileAreaDetector" class.
Each profile is responsible for its alert handling mechanism and alert delay timing.
The cluster class has a "get_volume" method.
|
e39001bbcd3d20cd1327ef4f287a9047
|
{
"intermediate": 0.22688621282577515,
"beginner": 0.5814200639724731,
"expert": 0.1916937530040741
}
|
35,930
|
for js write me a function with switch case that will recieve a string of Roman numbers and will transform them into normal numbers
|
bcc95ce80d9faa44956f10ec9adc3930
|
{
"intermediate": 0.3822607398033142,
"beginner": 0.444922536611557,
"expert": 0.17281672358512878
}
|
35,931
|
В какую часть кода !pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org --trusted-host pypi.python.org --user git+https://<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>/orm/orm_logreg нужно вписать git config --global http.sslVerify false чтобы все сработало
|
9db2fc2ce278eedd8e3618fcc63decfa
|
{
"intermediate": 0.44672533869743347,
"beginner": 0.22080102562904358,
"expert": 0.33247366547584534
}
|
35,932
|
hi
|
a82c30b1a29548e42ff69e9ae263ba24
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
35,933
|
hi
|
f58f1659eb6548adc7097a3330a2823e
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
35,934
|
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.ncs.core.model.AcqOperationTurnover
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:552)
at deployment.acq-core-web.war//org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:71)
at deployment.acq-core-web.war//org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68)
at deployment.acq-core-web.war//org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:197)
at deployment.acq-core-web.war//org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:130)
at deployment.acq-core-web.war//org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:111)
at deployment.acq-core-web.war//org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:198)
at deployment.acq-core-web.war//org.springframework.data.jpa.repository.cdi.JpaRepositoryBean.create(JpaRepositoryBean.java:73)
at deployment.acq-core-web.war//org.springframework.data.repository.cdi.CdiRepositoryBean.create(CdiRepositoryBean.java:374)
at deployment.acq-core-web.war//org.springframework.data.repository.cdi.CdiRepositoryBean.create(CdiRepositoryBean.java:172)
at deployment.acq-core-web.war//org.springframework.data.repository.cdi.CdiRepositoryBean.initialize(CdiRepositoryBean.java:157)
at deployment.acq-core-web.war//org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport.afterDeploymentValidation(CdiRepositoryExtensionSupport.java:153)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.injection.StaticMethodInjectionPoint.invoke(StaticMethodInjectionPoint.java:95)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.injection.MethodInvocationStrategy$SpecialParamPlusBeanManagerStrategy.invoke(MethodInvocationStrategy.java:187)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:330)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ExtensionObserverMethodImpl.sendEvent(ExtensionObserverMethodImpl.java:123)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ObserverMethodImpl.sendEvent(ObserverMethodImpl.java:308)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:286)
at javax.enterprise.api//javax.enterprise.inject.spi.ObserverMethod.notify(ObserverMethod.java:124)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.util.Observers.notify(Observers.java:166)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ObserverNotifier.notifySyncObservers(ObserverNotifier.java:285)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ObserverNotifier.notify(ObserverNotifier.java:273)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:177)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.event.ObserverNotifier.fireEvent(ObserverNotifier.java:171)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.bootstrap.events.AbstractContainerEvent.fire(AbstractContainerEvent.java:53)
at <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>//org.jboss.weld.bootstrap.events.AbstractDeploymentContainerEvent.fire(AbstractDeploymentContainerEvent.java:35)
|
60ca3b72dcc938ca6d5ed5435285a85e
|
{
"intermediate": 0.3438275158405304,
"beginner": 0.38646090030670166,
"expert": 0.26971158385276794
}
|
35,935
|
(base) C:\Users\ismailov>conda env list
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\Scripts\conda-env-script.py", line 5, in <module>
from conda_env.cli.main import main
File "C:\ProgramData\Anaconda3\lib\site-packages\conda_env\cli\main.py", line 13, in <module>
import conda.exports # noqa
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\exports.py", line 24, in <module>
from . import plan # noqa: F401
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\plan.py", line 28, in <module>
from .core.index import LAST_CHANNEL_URLS, _supplement_index_with_prefix
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\core\index.py", line 19, in <module>
from .package_cache_data import PackageCacheData
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\core\package_cache_data.py", line 21, in <module>
from .path_actions import CacheUrlAction, ExtractPackageAction
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\core\path_actions.py", line 34, in <module>
from ..gateways.connection.download import download
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\gateways\connection\download.py", line 14, in <module>
from .session import CondaSession
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\gateways\connection\session.py", line 13, in <module>
from .adapters.s3 import S3Adapter
File "C:\ProgramData\Anaconda3\lib\site-packages\conda\gateways\connection\adapters\s3.py", line 12, in <module>
import boto3
File "C:\ProgramData\Anaconda3\lib\site-packages\boto3\__init__.py", line 17, in <module>
from boto3.session import Session
File "C:\ProgramData\Anaconda3\lib\site-packages\boto3\session.py", line 17, in <module>
import botocore.session
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\session.py", line 26, in <module>
import botocore.client
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\client.py", line 15, in <module>
from botocore import waiter, xform_name
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\waiter.py", line 18, in <module>
from botocore.docs.docstring import WaiterDocstring
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\docs\__init__.py", line 15, in <module>
from botocore.docs.service import ServiceDocumenter
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\docs\service.py", line 14, in <module>
from botocore.docs.client import ClientDocumenter, ClientExceptionsDocumenter
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\docs\client.py", line 14, in <module>
from botocore.docs.example import ResponseExampleDocumenter
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\docs\example.py", line 13, in <module>
from botocore.docs.shape import ShapeDocumenter
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\docs\shape.py", line 19, in <module>
from botocore.utils import is_json_value_header
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\utils.py", line 34, in <module>
import botocore.httpsession
File "C:\ProgramData\Anaconda3\lib\site-packages\botocore\httpsession.py", line 41, in <module>
from urllib3.contrib.pyopenssl import orig_util_SSLContext as SSLContext
File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\contrib\pyopenssl.py", line 50, in <module>
import OpenSSL.SSL
File "C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\__init__.py", line 8, in <module>
from OpenSSL import crypto, SSL
File "C:\ProgramData\Anaconda3\lib\site-packages\OpenSSL\crypto.py", line 3268, in <module>
_lib.OpenSSL_add_all_algorithms()
AttributeError: module 'lib' has no attribute 'OpenSSL_add_all_algorithms'
|
cce602fa0802baa987ee8e9b2c7b5f5b
|
{
"intermediate": 0.3670136630535126,
"beginner": 0.4230719804763794,
"expert": 0.20991435647010803
}
|
35,936
|
write a code to concatenate two words and the input is taken by the user in java
|
fd6ecca4a019532e76b5c4f3d7b2cc3b
|
{
"intermediate": 0.48293277621269226,
"beginner": 0.14361095428466797,
"expert": 0.37345629930496216
}
|
35,937
|
how to display rights in octal mode with ls on linux ?
|
61dcdfebb0caee4533a9e4b04a24503a
|
{
"intermediate": 0.4182985723018646,
"beginner": 0.26470479369163513,
"expert": 0.31699660420417786
}
|
35,938
|
how can i display rights in octal mode with ls in lieu of letters on Ubuntu ?
|
99350167d23ad39f3d4bd37fc09036e9
|
{
"intermediate": 0.4397110342979431,
"beginner": 0.22907797992229462,
"expert": 0.3312109708786011
}
|
35,939
|
how to access rails app developemnt hosted on a vps access through internet
|
adf5eb00c5870b03c819dfcd39c73cd3
|
{
"intermediate": 0.6079527139663696,
"beginner": 0.15002340078353882,
"expert": 0.24202390015125275
}
|
35,940
|
package
{
import flash.display.Sprite;
import flash.events.Event;
import launcher.background.Background_Main;
import launcher.button.FightButton;
import launcher.panel.languagePanel;
import launcher.panel.social.socialPanel;
import launcher.panel.buttonBar.quickPanel;
import launcher.snow.Snow;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageQuality;
import flash.display.StageScaleMode;
import flash.display.NativeWindow;
import flash.display.NativeWindowType;
import flash.display.NativeWindowInitOptions;
import flash.desktop.NativeApplication;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.display.Screen;
import zip.ZIPResourceLoader;
import caurina.transitions.Tweener;
import flash.display.Loader;
import flash.system.LoaderContext;
import flash.system.ApplicationDomain;
import flash.events.IOErrorEvent;
import flash.net.URLVariables;
import flash.net.URLRequest;
import flash.events.MouseEvent;
/**
* ...
* @author alekskart
*/
public class Main extends Sprite
{
private var loader:Loader;
private var locale:String;
private var guiLayer:Sprite;
public var background:Background_Main = new Background_Main();
public var progressBar:ProgressBar;
public var socialbar:socialPanel = new socialPanel();
public var quickbar:quickPanel = new quickPanel();
public var fightButton:FightButton = new FightButton();
public var bgButton:bg_button = new bg_button();
public var languagepanel:languagePanel = new languagePanel(quickbar, fightButton);
public function Main()
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
//var ziploader:ZIPResourceLoader = new ZIPResourceLoader(progressBar);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
this.configureStage();
this.createGUI();
//это при запуске первом
Tweener.addTween(bgButton, {alpha: 1, time: 2, transition: "easeOutCubic", onComplete: fadeOutButton});
}
private function setCenterPosition() : void
{
var appBounds:Rectangle = stage.nativeWindow.bounds;
var screen:Screen = Screen.getScreensForRectangle(appBounds)[0];
stage.stageWidth = 1034;
stage.stageHeight = 680;
stage.nativeWindow.maxSize = new Point(stage.nativeWindow.width,stage.nativeWindow.height);
stage.nativeWindow.minSize = new Point(stage.nativeWindow.width,stage.nativeWindow.height);
stage.nativeWindow.x = (screen.bounds.width - stage.nativeWindow.width) / 2;
stage.nativeWindow.y = (screen.bounds.height - stage.nativeWindow.height) / 2;
}
private function configureStage() : void
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.quality = StageQuality.BEST;
stage.displayState = StageDisplayState.NORMAL;
stage.stageWidth = 1034;
stage.stageHeight = 680;
this.setCenterPosition();
}
private function createGUI() : void
{
this.guiLayer = new Sprite();
this.background.width = stage.stageWidth;
this.background.height = stage.stageHeight;
this.background.y = 0;
this.guiLayer.addChild(this.background);
this.socialbar.x = stage.stageWidth - this.socialbar.width - 15;
this.socialbar.y = 29;
this.guiLayer.addChild(this.socialbar);
this.quickbar.x = (stage.stageWidth - this.quickbar.width) / 2 + 20;
this.quickbar.y = 29;
this.guiLayer.addChild(this.quickbar);
this.languagepanel.x = (stage.stageWidth - this.languagepanel.width) / 2 + 20;
this.languagepanel.y = 50;
this.guiLayer.addChild(this.languagepanel);
this.bgButton.x = stage.stageWidth / 2 - this.bgButton.width / 2;
this.bgButton.y = stage.stageHeight / 2 - this.bgButton.height / 2 + 185;
this.guiLayer.addChild(this.bgButton);
this.fightButton.x = stage.stageWidth / 2 - this.fightButton.width / 2;
this.fightButton.y = stage.stageHeight / 2 - this.fightButton.height / 2 + 185;
this.fightButton.addEventListener(MouseEvent.CLICK, startPressed);
this.guiLayer.addChild(this.fightButton);
this.progressBar = new ProgressBar();
this.progressBar.x = (stage.stageWidth - this.progressBar.width) / 2;
this.progressBar.y = (stage.stageHeight - this.progressBar.height) / 2 + 280;
this.guiLayer.addChild(this.progressBar);
this.guiLayer.addChild(new Snow(25));
addChild(this.guiLayer);
stage.addEventListener(Event.RESIZE, onResize);
}
private function startPressed(e:MouseEvent = null):void
{
var options:NativeWindowInitOptions = new NativeWindowInitOptions();
while (this.guiLayer.numChildren > 0)
{
this.guiLayer.removeChildAt(0);
};
options.renderMode = "direct";
options.maximizable = true;
var window:NativeWindow = new NativeWindow(options);
window.minSize = new Point(0x0400, 0x0300);
window.maxSize = new Point(4095, 2880);
window.stage.scaleMode = StageScaleMode.NO_SCALE;
window.stage.align = StageAlign.TOP_LEFT;
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSWFLoaded);
loader.load(new URLRequest("loader.swf"));
window.stage.addChild(loader);
window.activate();
window.addEventListener(Event.CLOSE, onWindowClose);
}
private function onSWFLoaded(event:Event):void
{
// Код, который вызывается после загрузки swf файла
// Например, получение ссылки на загруженный контент:
var loadedContent:Object = event.currentTarget.content;
}
private function onWindowClose(event:Event):void
{
NativeApplication.nativeApplication.exit();
}
///Затухание
private function fadeOutButton():void {
Tweener.addTween(bgButton, {alpha: 0, time: 4, delay: 0, transition: "easeOutCubic", onComplete: fadeInButton});
}
//появление после затухания
private function fadeInButton():void {
Tweener.addTween(bgButton, {alpha: 1, time: 4, delay: 0, transition: "easeOutCubic", onComplete: fadeOutButton});
}
private function onResize(event:Event):void
{
var scale:Number = Math.min(stage.stageWidth / this.background.width, stage.stageHeight / this.background.height);
this.background.width *= scale;
this.background.height *= scale;
var newHeight:Number = this.background.height * 0.86;
this.background.height = newHeight;
this.background.x = (stage.stageWidth - this.background.width) / 2;
// this.background.y = (stage.stageHeight - this.background.height) * 0.25;
}
}
} вот как сделать чтобы после открытия нового окна NativeWindow, закрылось прошлое где всякие gui элементы и т.д
|
ae747ea47eba4665f3d8d50aead48ae6
|
{
"intermediate": 0.23278768360614777,
"beginner": 0.45912137627601624,
"expert": 0.3080909550189972
}
|
35,941
|
using TMPro;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(AudioSource))]
public class Player : MonoBehaviour
{
[Header("Controladores de Velocidade")]
[SerializeField]
private float limite;
[SerializeField]
private float valorReducao = 0.25f;
[SerializeField]
private float velocidade;
[SerializeField]
private float ReducaoBatida;
[Space(10f)]
[Header("Controladores de Pulo")]
[SerializeField]
private float forcaPulo;
[SerializeField]
private bool isGrounded = true;
[SerializeField]
private bool isJump = false;
[SerializeField]
private bool isRamp;
[SerializeField]
private bool isGrind;
[SerializeField]
private bool isDead;
[Space(10f)]
[Header("Rotação e Inclinação")]
[SerializeField]
private float velInclination = 3f;
[SerializeField]
private float velRotation = 90f;
[SerializeField]
private float latRot;
[SerializeField]
private float hRot = 0f;
private Vector3 curNormal = Vector3.up;
[SerializeField]
private float rotX;
[Space(10f)]
[Header("Info")]
[SerializeField]
private Transform tr;
[SerializeField]
private Rigidbody rb;
[SerializeField]
private Transform CentroMass;
[SerializeField]
private GameObject CentroMassa;
[SerializeField]
private Transform raycastTr;
[SerializeField]
private Transform respawn;
private float timer = 1.3f;
private float inputX = 0f;
private float inputY = 0f;
[Space(10f)]
[Header("Interface")]
private int Pontos = 0;
public static int pontuacao;
public static bool reinicio = false;
[SerializeField]
private TextMeshProUGUI TextoPontos;
[SerializeField]
private TextMeshProUGUI TextoManobra;
[SerializeField]
private GameObject GManobras;
[SerializeField]
private Slider slider;
[SerializeField]
private GameObject Gslider;
private VariableJoystick joystick;
[SerializeField]
private GameObject tutorial;
[SerializeField]
private TMP_Text tutorialText;
private float tutorialTimer = 0f;
[Space(10f)]
[Header("Grind")]
[SerializeField]
private GameObject grind;
[SerializeField]
private Transform local;
[SerializeField]
private Transform pos;
[SerializeField]
private Transform inter;
[SerializeField]
private float velGrind = 0.1f;
private float timeGrind = 0f;
private float timeDead = 0f;
private bool CR = false;
private bool grindVer = false;
private float equil = 0f;
private float timeEquil = 4f;
private bool seguirGrind = false;
private bool intermedio = false;
[Space(10f)]
[Header("Animações e Audios")]
[SerializeField]
private float tempoRemadas;
[SerializeField]
private Animator m_Animator;
[SerializeField]
private AudioSource AS;
[SerializeField]
private AudioSource ABonus;
private bool Goofy = false;
[Space(10f)]
[SerializeField]
private AudioClip[] SAndando;
[SerializeField]
private AudioClip[] SPulo;
[SerializeField]
private AudioClip[] SAterrizando;
[SerializeField]
private AudioClip[] SManobras;
[SerializeField]
private AudioClip[] SRemada;
[Space(10f)]
[SerializeField]
private AudioSource Agrind;
[SerializeField]
private AudioSource AmorteM;
[SerializeField]
private AudioSource AmorteF;
private bool playgrind = false;
private bool playmorte = false;
private bool masc = true;
[Space(10f)]
[Header("Combos")]
[SerializeField]
private float timeX = 0f;
[SerializeField]
private float timeA = 0f;
[SerializeField]
private float timeB = 0f;
[SerializeField]
private float timeY = 0f;
[SerializeField]
private bool varX = false;
[SerializeField]
private bool varA = false;
[SerializeField]
private bool varB = false;
[SerializeField]
private bool varY = false;
private float timeMan;
[Space(10f)]
[Header("Pontuações")]
[SerializeField]
private int flip;
[SerializeField]
private int popShoveIt;
[SerializeField]
private int flip360;
[SerializeField]
private int frontSideFlip;
[SerializeField]
private int grind50;
[SerializeField]
private int grindCrooked;
[SerializeField]
private int bonus;
private bool grindou;
private bool todos;
[Space(10f)]
[Header("Colecionaveis")]
[SerializeField]
private bool colect;
[SerializeField]
private GameObject colecionavel;
[SerializeField]
private TextMeshProUGUI TextoColecionaveis;
[SerializeField]
private int marca;
[SerializeField]
private int max;
[SerializeField]
private string[] marcas;
[SerializeField]
private GameManager m;
private float timerColect;
[SerializeField]
private float multTimer = 20f;
[SerializeField]
private GameObject xDois;
[SerializeField]
private GameObject xQuatro;
[SerializeField]
private Image ImageDoisX;
[SerializeField]
private Image ImageQuatroX;
private bool XDoisX = false;
private bool XQuatroX = false;
private int countFlip = 0;
private int countPop = 0;
private int countF360 = 0;
private int countFrontf = 0;
[SerializeField]
private GameObject respMorte;
private bool grama = false;
private AreaMano areaMano;
private bool mano = false;
[SerializeField]
private TMP_Text manoText;
[SerializeField]
private GameObject mano01;
[SerializeField]
private GameObject mano02;
private void DoisX()
{
if (multTimer > 0f)
{
multTimer -= Time.deltaTime;
ImageDoisX.fillAmount = multTimer / 20f;
}
else
{
xDois.SetActive(value: false);
XDoisX = false;
}
}
private void QuatroX()
{
if (multTimer > 0.5f)
{
multTimer -= Time.deltaTime;
ImageQuatroX.fillAmount = multTimer / 20f;
}
else
{
xQuatro.SetActive(value: false);
XQuatroX = false;
}
}
private void Start()
{
joystick = GameObject.Find("Joystick").GetComponent<VariableJoystick>();
if (PlayerPrefs.HasKey("tutorial"))
{
tutorial.SetActive(value: false);
}
else
{
Tutorial();
}
}
private void Tutorial()
{
tutorialTimer += Time.deltaTime;
if (tutorialTimer > 40f)
{
PlayerPrefs.SetInt("tutorial", 0);
}
else if (tutorialTimer > 30f)
{
tutorialText.text = "Dependo da manobra que você fizer, ganhará uma pontuação diferente. Vá em frente, divirta-se!";
}
else if (tutorialTimer > 20f)
{
tutorialText.text = "Para deslizar por corrimãos, enquanto estiver saltando por cima deles, aperte A ou Y. \nEquilibre-se no corrimão com o analógico.";
}
else if (tutorialTimer > 10f)
{
tutorialText.text = "Para pular (ollie) aperte o botão X. Para executar manobras, enquanto estiver pulando, aperte, \nA, B, Y ou X.";
}
else
{
tutorialText.text = "Para movimentar o personagem utilize o analógico à esquerda da tela, arrastando à frente acelera, \nà trás frea, e para os lados faz curvas.";
}
}
private void Update()
{
if (PlayerPrefs.HasKey("tutorial"))
{
tutorial.SetActive(value: false);
}
else
{
Tutorial();
}
GroundCheck();
AlignPlayerRamp();
comandsPC();
Timer();
GrindAtt();
Manobras();
animacoesSons();
textos();
Outros();
Morte();
AreaManobra();
if (!isDead)
{
if (!grindVer)
{
Movement();
Aceleration();
LatRotation();
HorizRotation();
equil = 0f;
}
else
{
GrindSlider();
GrindControl();
GrindInclin();
AlignPlayerRamp();
}
}
if (CentroMass.transform.rotation.z > 75f || CentroMass.transform.rotation.z < -75f)
{
CentroMass.rotation = new Quaternion(CentroMass.rotation.x, CentroMass.rotation.y, 0f, CentroMass.rotation.w);
}
if (CentroMass.transform.rotation.x > 75f || CentroMass.transform.rotation.x < -75f)
{
CentroMass.rotation = new Quaternion(0f, CentroMass.rotation.y, CentroMass.rotation.z, CentroMass.rotation.w);
}
if (CentroMass.transform.rotation.y > 75f || CentroMass.transform.rotation.y < -75f)
{
CentroMass.transform.rotation = new Quaternion(CentroMass.rotation.x, 0f, CentroMass.rotation.z, CentroMass.rotation.w);
}
if (XDoisX)
{
DoisX();
}
else if (XQuatroX)
{
QuatroX();
}
else
{
multTimer = 20f;
}
if (countFlip == 2)
{
countPop = 0;
countF360 = 0;
countFrontf = 0;
}
else if (countPop == 2)
{
countFlip = 0;
countF360 = 0;
countFrontf = 0;
}
else if (countF360 == 2)
{
countFlip = 0;
countPop = 0;
countFrontf = 0;
}
else if (countFrontf == 2)
{
countFlip = 0;
countF360 = 0;
countPop = 0;
}
}
private void Morte()
{
if (isGrounded)
{
respMorte.transform.position = base.transform.position;
}
if (playgrind)
{
if (isGrind && !Agrind.isPlaying)
{
Agrind.Play();
}
}
else if (Agrind.isPlaying)
{
Agrind.Stop();
}
if (playmorte)
{
if (masc)
{
if (isDead && !AmorteM.isPlaying)
{
AmorteM.Play();
}
}
else if (isDead && !AmorteF.isPlaying)
{
AmorteF.Play();
}
}
else if (masc)
{
if (AmorteM.isPlaying)
{
AmorteM.Stop();
}
}
else if (AmorteF.isPlaying)
{
AmorteF.Stop();
}
}
private void Movement()
{
velocidade = Mathf.Clamp(velocidade -= Time.deltaTime * valorReducao, 0f, limite);
base.transform.Translate(0f, 0f, velocidade * Time.deltaTime);
}
private void AlignPlayerRamp()
{
if (!Physics.Raycast(raycastTr.position, -curNormal, out var hitInfo))
{
return;
}
curNormal = Vector3.Lerp(curNormal, hitInfo.normal, velInclination * Time.deltaTime);
Quaternion quaternion = Quaternion.FromToRotation(Vector3.up, curNormal);
if (!grindVer)
{
if (isGrounded)
{
CentroMass.rotation = quaternion * Quaternion.Euler(1f, hRot, 1f);
if (isRamp)
{
base.transform.rotation = quaternion * Quaternion.Euler(1f, hRot, 0f);
}
}
}
else
{
CentroMass.rotation = quaternion * Quaternion.Euler(1f, hRot, 1f);
}
}
private void HorizRotation()
{
if (Input.GetAxis("Horizontal") == 0f)
{
inputX = joystick.Horizontal;
}
else
{
inputX = Input.GetAxis("Horizontal");
}
if (inputX > 0.25f || inputX < -0.25f)
{
hRot += inputX * velRotation * Time.deltaTime;
}
if (!isRamp || !isGrounded)
{
base.transform.eulerAngles = new Vector3(0f, hRot, 0f);
}
}
private void Aceleration()
{
if (Input.GetAxis("Vertical") == 0f)
{
inputY = joystick.Vertical;
}
else
{
inputY = Input.GetAxis("Vertical");
}
if (velocidade <= 17f && inputY > 0.5f)
{
Remada(8f);
}
if (inputY < -0.5f)
{
Freiar(5f);
}
}
private void LatRotation()
{
m_Animator.SetFloat("InclinE", 0f - inputX);
m_Animator.SetFloat("InclinD", inputX);
}
private void GroundCheck()
{
float maxDistance = 0.75f;
if (Physics.Raycast(direction: new Vector3(0f, -1f), origin: raycastTr.position, hitInfo: out var hitInfo, maxDistance: maxDistance))
{
if (hitInfo.transform.tag == "chão")
{
isGrounded = true;
}
return;
}
isGrounded = false;
if (!isJump && !isGrind && !isDead && !grindVer)
{
todos = true;
}
}
private void Timer()
{
timer += Time.deltaTime;
if (timer > 4f)
{
timer = 0f;
}
}
private void comandsPC()
{
if (Input.GetKeyDown(KeyCode.Q))
{
A();
}
if (Input.GetKeyDown(KeyCode.E))
{
B();
}
if (Input.GetKeyDown(KeyCode.R))
{
Y();
}
if (Input.GetKeyDown(KeyCode.Space))
{
X();
}
if (Input.GetKeyDown(KeyCode.P))
{
Respawn();
}
}
public void X()
{
if (!isJump)
{
if (seguirGrind && grindVer)
{
seguirGrind = false;
grindVer = false;
intermedio = false;
hRot = base.transform.eulerAngles.y;
Gslider.SetActive(value: false);
timer = 4f;
playgrind = false;
Jump();
velocidade += 8f;
m_Animator.SetBool("Grind", value: false);
m_Animator.SetBool("GrindCr", value: false);
}
else
{
Jump();
}
}
else
{
FlipFrontSide();
}
}
public void A()
{
if (isJump && isGrind)
{
Grind();
}
else if (!isGrind)
{
Flip();
}
}
public void B()
{
Pop();
}
public void Y()
{
if (isJump && isGrind)
{
GrindCr();
}
else if (!isGrind)
{
Flip360();
}
}
public void Respawn()
{
base.transform.position = respawn.position;
}
private void Freiar(float valor)
{
if (!isJump && isGrounded && timer >= tempoRemadas && !isDead)
{
timer = 0f;
velocidade -= valor;
}
}
private void Remada(float valor)
{
if (!isJump && isGrounded && timer >= tempoRemadas && !isDead)
{
if (!Goofy)
{
m_Animator.Play("Remando");
}
else
{
m_Animator.Play("Remando Goofy");
}
timer = 0f;
AS.clip = SRemada[Random.Range(0, SRemada.Length)];
AS.PlayOneShot(SRemada[Random.Range(0, SRemada.Length)]);
velocidade += valor;
}
}
private void Flip()
{
if (isJump && !m_Animator.GetBool("Flip") && !isDead)
{
AS.clip = SManobras[Random.Range(0, SManobras.Length)];
AS.PlayOneShot(SManobras[Random.Range(0, SManobras.Length)]);
m_Animator.SetBool("Flip", value: true);
}
}
private void Pop()
{
if (isJump && !m_Animator.GetBool("Pop") && !isDead)
{
AS.clip = SManobras[Random.Range(0, SManobras.Length)];
AS.PlayOneShot(SManobras[Random.Range(0, SManobras.Length)]);
m_Animator.SetBool("Pop", value: true);
}
}
private void Flip360()
{
if (isJump && !m_Animator.GetBool("Flip360") && !isDead)
{
AS.clip = SManobras[Random.Range(0, SManobras.Length)];
AS.PlayOneShot(SManobras[Random.Range(0, SManobras.Length)]);
m_Animator.SetBool("Flip360", value: true);
}
}
private void FlipFrontSide()
{
if (isJump && !m_Animator.GetBool("FrontFlip") && !isDead)
{
AS.clip = SManobras[Random.Range(0, SManobras.Length)];
AS.PlayOneShot(SManobras[Random.Range(0, SManobras.Length)]);
m_Animator.SetBool("FrontFlip", value: true);
if (!Goofy)
{
m_Animator.SetBool("Goofy", value: true);
Goofy = true;
}
else
{
m_Animator.SetBool("Goofy", value: false);
Goofy = false;
}
}
}
private void Jump()
{
if ((!isJump && isGrounded && !isDead) || (!isJump && isGrind && !isDead))
{
AS.clip = SPulo[Random.Range(0, SPulo.Length)];
AS.PlayOneShot(SPulo[Random.Range(0, SPulo.Length)]);
rb.velocity = Vector3.up * forcaPulo;
velocidade += 3f;
isJump = true;
if (!Goofy)
{
m_Animator.Play("Ollie");
}
else
{
m_Animator.Play("Ollie Goofy");
}
}
}
private void Manobras()
{
if (m_Animator.GetBool("Flip"))
{
if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM Goofy"))
{
m_Animator.SetBool("Flip", value: false);
if (countFlip < 3)
{
if (XDoisX)
{
Pontos += flip * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "FLIP +" + flip * 2;
countFlip++;
}
else if (XQuatroX)
{
Pontos += flip * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "FLIP +" + flip * 4;
countFlip++;
}
else
{
Pontos += flip;
GManobras.SetActive(value: true);
TextoManobra.text = "FLIP +" + flip;
countFlip++;
}
}
else if (countFlip < 5)
{
if (XDoisX)
{
Pontos += flip / 2 * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "FLIP +" + flip / 2 * 2;
countFlip++;
}
else if (XQuatroX)
{
Pontos += flip / 2 * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "FLIP +" + flip / 2 * 4;
countFlip++;
}
else
{
Pontos += flip / 2;
GManobras.SetActive(value: true);
TextoManobra.text = "FLIP +" + flip / 2;
countFlip++;
}
}
else
{
GManobras.SetActive(value: true);
TextoManobra.text = "FLIP +00";
}
if (mano)
{
areaMano.AttMano++;
}
timeMan = 0f;
}
else if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao Goofy"))
{
m_Animator.SetBool("Caiu", value: true);
m_Animator.SetBool("Flip", value: false);
playmorte = true;
isDead = true;
velocidade = 0f;
}
}
if (m_Animator.GetBool("Pop"))
{
if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM Goofy"))
{
m_Animator.SetBool("Pop", value: false);
if (countPop < 3)
{
if (XDoisX)
{
Pontos += popShoveIt * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "POP SHOVE-IT +" + popShoveIt * 2;
countPop++;
}
else if (XQuatroX)
{
Pontos += popShoveIt * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "POP SHOVE-IT +" + popShoveIt * 4;
countPop++;
}
else
{
Pontos += popShoveIt;
GManobras.SetActive(value: true);
TextoManobra.text = "POP SHOVE-IT +" + popShoveIt;
countPop++;
}
}
else if (countPop < 5)
{
if (XDoisX)
{
Pontos += popShoveIt / 2 * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "POP SHOVE-IT +" + popShoveIt / 2 * 2;
countPop++;
}
else if (XQuatroX)
{
Pontos += popShoveIt / 2 * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "POP SHOVE-IT +" + popShoveIt / 2 * 4;
countPop++;
}
else
{
Pontos += popShoveIt / 2;
GManobras.SetActive(value: true);
TextoManobra.text = "POP SHOVE-IT +" + popShoveIt / 2;
countPop++;
}
}
else
{
GManobras.SetActive(value: true);
TextoManobra.text = "POP SHOVE-IT +00";
}
if (mano)
{
areaMano.AttMano++;
}
timeMan = 0f;
}
else if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao Goofy"))
{
m_Animator.SetBool("Caiu", value: true);
m_Animator.SetBool("Pop", value: false);
playmorte = true;
isDead = true;
velocidade = 0f;
}
}
if (m_Animator.GetBool("Flip360"))
{
if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM Goofy"))
{
m_Animator.SetBool("Flip360", value: false);
if (countF360 < 3)
{
if (XDoisX)
{
Pontos += flip360 * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "360 FLIP +" + flip360 * 2;
countF360++;
}
else if (XQuatroX)
{
Pontos += flip360 * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "360 FLIP +" + flip360 * 4;
countF360++;
}
else
{
Pontos += flip360;
GManobras.SetActive(value: true);
TextoManobra.text = "360 FLIP +" + flip360;
countF360++;
}
}
else if (countF360 < 5)
{
if (XDoisX)
{
Pontos += flip360 / 2 * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "360 FLIP +" + flip360 / 2 * 2;
countF360++;
}
else if (XQuatroX)
{
Pontos += flip360 / 2 * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "360 FLIP +" + flip360 / 2 * 4;
countF360++;
}
else
{
Pontos += flip360 / 2;
GManobras.SetActive(value: true);
TextoManobra.text = "360 FLIP +" + flip360 / 2;
countF360++;
}
}
else
{
GManobras.SetActive(value: true);
TextoManobra.text = "360 FLIP +00";
}
if (mano)
{
areaMano.AttMano++;
}
timeMan = 0f;
}
else if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao Goofy"))
{
m_Animator.SetBool("Caiu", value: true);
m_Animator.SetBool("Flip360", value: false);
playmorte = true;
isDead = true;
velocidade = 0f;
}
}
if (!m_Animator.GetBool("FrontFlip"))
{
return;
}
if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM Goofy"))
{
m_Animator.SetBool("FrontFlip", value: false);
if (countFrontf < 3)
{
if (XDoisX)
{
Pontos += frontSideFlip * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "FRONTSIDE FLIP +" + frontSideFlip * 2;
countFrontf++;
}
else if (XQuatroX)
{
Pontos += frontSideFlip * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "FRONTSIDE FLIP +" + frontSideFlip * 4;
countFrontf++;
}
else
{
Pontos += frontSideFlip;
GManobras.SetActive(value: true);
TextoManobra.text = "FRONTSIDE FLIP +" + frontSideFlip;
countFrontf++;
}
}
else if (countFrontf < 5)
{
if (XDoisX)
{
Pontos += frontSideFlip / 2 * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "FRONTSIDE FLIP +" + frontSideFlip / 2 * 2;
countFrontf++;
}
else if (XQuatroX)
{
Pontos += frontSideFlip / 2 * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "FRONTSIDE FLIP +" + frontSideFlip / 2 * 4;
countFrontf++;
}
else
{
Pontos += frontSideFlip / 2;
GManobras.SetActive(value: true);
TextoManobra.text = "FRONTSIDE FLIP +" + frontSideFlip / 2;
countFrontf++;
}
}
else
{
GManobras.SetActive(value: true);
TextoManobra.text = "FRONTSIDE FLIP +00";
}
if (mano)
{
areaMano.AttMano++;
}
timeMan = 0f;
}
else if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("TocandoChao Goofy"))
{
m_Animator.SetBool("Caiu", value: true);
m_Animator.SetBool("FrontFlip", value: false);
playmorte = true;
isDead = true;
velocidade = 0f;
}
}
private void animacoesSons()
{
if (!isJump && velocidade > 1f && !AS.isPlaying && !grindVer)
{
AS.clip = SAndando[Random.Range(0, SAndando.Length)];
AS.Play();
}
if (!isJump && velocidade < 1f && AS.isPlaying)
{
AS.Stop();
}
if (isDead && timeDead < 5f)
{
timeDead += Time.deltaTime;
if (masc)
{
if (timeDead >= AmorteM.clip.length)
{
playmorte = false;
}
}
else if (timeDead >= AmorteF.clip.length)
{
playmorte = false;
}
if (timeDead > 2f && timeDead < 3f)
{
CentroMassa.SetActive(value: false);
}
else if (timeDead > 3f && timeDead < 4f)
{
m_Animator.SetBool("Caiu", value: false);
base.transform.position = respMorte.transform.position;
CentroMassa.SetActive(value: true);
timeDead = 0f;
isDead = false;
}
}
if (todos)
{
if (!Goofy)
{
m_Animator.Play("Air");
}
else
{
m_Animator.Play("Air Goofy");
}
}
if (Time.timeScale == 0f)
{
AS.Stop();
}
}
private void textos()
{
if (Pontos < 10)
{
TextoPontos.text = "0000" + Pontos;
}
else if (Pontos < 100)
{
TextoPontos.text = "000" + Pontos;
}
else if (Pontos < 1000)
{
TextoPontos.text = "00" + Pontos;
}
else if (Pontos < 10000)
{
TextoPontos.text = "0" + Pontos;
}
else
{
TextoPontos.text = Pontos.ToString();
}
if (timeMan < 5f)
{
timeMan += Time.deltaTime;
if (GManobras.activeSelf && timeMan >= 3f)
{
TextoManobra.text = null;
GManobras.SetActive(value: false);
timeMan = 0f;
}
}
if (colect)
{
timerColect += Time.deltaTime;
if (timerColect >= 3.5f)
{
colecionavel.SetActive(value: false);
timerColect = 0f;
}
}
if ((mano && mano01.activeSelf) || (mano && mano02.activeSelf))
{
timerColect += Time.deltaTime;
if (timerColect >= 3.5f)
{
if (mano01.activeSelf)
{
mano01.SetActive(value: false);
timerColect = 0f;
}
if (mano02.activeSelf)
{
mano02.SetActive(value: false);
timerColect = 0f;
mano = false;
}
}
}
if (pontuacao != Pontos)
{
pontuacao = Pontos;
}
if (reinicio && Pontos != 0)
{
Pontos = 0;
reinicio = false;
}
}
private void Outros()
{
if (base.transform.position.y < -15f)
{
base.transform.position = respawn.position;
}
if (m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Air") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("AirM Goofy") || m_Animator.GetCurrentAnimatorStateInfo(0).IsName("Air Goofy"))
{
CentroMass.rotation = new Quaternion(0f, CentroMass.rotation.y, 0f, CentroMass.rotation.w);
}
if (!isGrind && Gslider.activeSelf)
{
Gslider.SetActive(value: false);
}
}
private void Grind()
{
playgrind = true;
velocidade = 0f;
hRot = local.transform.eulerAngles.y;
rb.velocity = Vector3.zero;
base.transform.position = pos.position;
base.transform.rotation = local.rotation;
m_Animator.SetBool("Grind", value: true);
seguirGrind = true;
isJump = false;
grindVer = true;
Gslider.SetActive(value: true);
}
private void GrindCr()
{
playgrind = true;
velocidade = 0f;
hRot = local.transform.eulerAngles.y;
rb.velocity = Vector3.zero;
base.transform.position = pos.position;
base.transform.rotation = local.rotation;
m_Animator.SetBool("GrindCr", value: true);
seguirGrind = true;
isJump = false;
grindVer = true;
Gslider.SetActive(value: true);
}
private void GrindSlider()
{
timeEquil += Time.deltaTime;
if (timeEquil >= 1.5f && equil == 0f)
{
equil = Random.Range(-30, 30);
if (equil > 0f && equil != 0f)
{
equil = 30f;
}
else if (equil < 0f && equil != 0f)
{
equil = -30f;
}
else if (equil == 0f)
{
equil = 30f;
}
}
if (timeEquil > 4f)
{
timeEquil = 0f;
}
}
private void GrindAtt()
{
if (slider.value <= equil)
{
slider.value += 10f * Time.deltaTime;
}
else if (slider.value >= equil)
{
slider.value -= 10f * Time.deltaTime;
}
else if (slider.value - equil <= 1f || slider.value - equil >= -1f)
{
slider.value = equil;
}
else
{
slider.value = equil;
}
}
private void GrindControl()
{
if (seguirGrind)
{
if (intermedio)
{
if (Vector3.Distance(base.transform.position, inter.position) <= 1.5f)
{
intermedio = false;
}
else
{
base.transform.position = Vector3.MoveTowards(base.transform.position, inter.position, velGrind * Time.deltaTime);
}
}
else if (!intermedio)
{
base.transform.position = Vector3.MoveTowards(base.transform.position, local.position, velGrind * Time.deltaTime);
}
}
timeGrind += Time.deltaTime;
if (timeGrind > 1f)
{
if (!CR)
{
if (XDoisX)
{
Pontos += grind50 * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "50-50 GRIND +" + grind50 * 2;
}
else if (XQuatroX)
{
Pontos += grind50 * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "50-50 GRIND +" + grind50 * 4;
}
else
{
Pontos += grind50;
GManobras.SetActive(value: true);
TextoManobra.text = "50-50 GRIND +" + grind50;
}
timeMan = 0f;
timeGrind = 0f;
}
else
{
if (XDoisX)
{
Pontos += grindCrooked * 2;
GManobras.SetActive(value: true);
TextoManobra.text = "CROOCKED GRIND +" + grindCrooked * 2;
}
else if (XQuatroX)
{
Pontos += grindCrooked * 4;
GManobras.SetActive(value: true);
TextoManobra.text = "CROOCKED GRIND +" + grindCrooked * 4;
}
else
{
Pontos += grindCrooked;
GManobras.SetActive(value: true);
TextoManobra.text = "CROOCKED GRIND +" + grindCrooked;
}
timeMan = 0f;
timeGrind = 0f;
}
}
if (Vector3.Distance(base.transform.position, local.position) <= 1.5f)
{
Pontos += grind50;
seguirGrind = false;
grindVer = false;
intermedio = false;
hRot = base.transform.eulerAngles.y;
Gslider.SetActive(value: false);
timer = 4f;
playgrind = false;
Jump();
velocidade += 8f;
m_Animator.SetBool("Grind", value: false);
m_Animator.SetBool("GrindCr", value: false);
}
}
private void GrindInclin()
{
if (Input.GetAxis("Horizontal") == 0f)
{
inputX = joystick.Horizontal;
}
else
{
inputX = Input.GetAxis("Horizontal");
}
slider.value += inputX / 2.5f;
m_Animator.SetFloat("GrindEquil", slider.value);
if (slider.value > 25f)
{
m_Animator.SetBool("Caiu", value: true);
grindVer = false;
isDead = true;
velocidade = 0f;
base.transform.Translate(0.8f, 0f, 0f);
Gslider.SetActive(value: false);
playgrind = false;
isGrind = false;
}
if (slider.value < -25f)
{
m_Animator.SetBool("Caiu", value: true);
grindVer = false;
isDead = true;
velocidade = 0f;
base.transform.Translate(-0.8f, 0f, 0f);
Gslider.SetActive(value: false);
playgrind = false;
isGrind = false;
}
}
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Parede" && velocidade > 13f)
{
velocidade -= ReducaoBatida;
hRot += 120f;
}
if (collision.gameObject.tag == "chão")
{
isGrounded = true;
if (isJump || grindou || todos)
{
AS.clip = SAterrizando[Random.Range(0, SAterrizando.Length)];
AS.PlayOneShot(SAterrizando[Random.Range(0, SAterrizando.Length)]);
if (!Goofy)
{
m_Animator.Play("TocandoChao");
m_Animator.SetBool("Grind", value: false);
m_Animator.SetBool("GrindCr", value: false);
}
else
{
m_Animator.Play("TocandoChao Goofy");
m_Animator.SetBool("Grind", value: false);
m_Animator.SetBool("GrindCr", value: false);
}
isJump = false;
grindou = false;
todos = false;
}
}
if (collision.gameObject.tag == "grama")
{
if (!Goofy)
{
m_Animator.Play("TocandoChao");
}
else
{
m_Animator.Play("TocandoChao Goofy");
}
m_Animator.SetBool("Caiu", value: true);
m_Animator.SetBool("Flip", value: false);
playmorte = true;
isDead = true;
velocidade = 0f;
}
}
public void OnCollisionExit(Collision collision)
{
if (collision.gameObject.tag == "chão")
{
isGrounded = false;
}
}
public void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "grind")
{
isGrind = true;
grind = other.gameObject.transform.parent.gameObject;
pos = other.gameObject.transform.GetChild(0);
inter = null;
intermedio = false;
if (grind.GetComponent<Grind>().dir)
{
local = grind.transform.GetChild(0);
}
else if (!grind.GetComponent<Grind>().dir)
{
local = grind.transform.GetChild(1);
}
}
if (other.gameObject.tag == "grindInter")
{
isGrind = true;
grind = other.gameObject.transform.parent.gameObject;
pos = other.gameObject.transform.GetChild(0);
inter = grind.transform.GetChild(2);
intermedio = true;
if (grind.GetComponent<Grind>().dir)
{
local = grind.transform.GetChild(0);
}
else if (!grind.GetComponent<Grind>().dir)
{
local = grind.transform.GetChild(1);
}
}
if (other.gameObject.tag == "Rampa" && !isRamp)
{
isRamp = true;
}
if (other.gameObject.tag == "Colect")
{
marca = other.gameObject.GetComponent<Colect>().marca;
max = other.gameObject.GetComponent<Colect>().max;
if (marca == 1)
{
TextoColecionaveis.text = marcas[0] + " - " + m.marca01 + " de " + max;
colecionavel.SetActive(value: true);
colect = true;
}
else if (marca == 2)
{
TextoColecionaveis.text = marcas[1] + " - " + m.marca02 + " de " + max;
colecionavel.SetActive(value: true);
colect = true;
}
else if (marca == 3)
{
TextoColecionaveis.text = marcas[2] + " - " + m.marca03 + " de " + max;
colecionavel.SetActive(value: true);
colect = true;
}
}
if (other.gameObject.tag == "Bonus")
{
Pontos += bonus;
TextoManobra.text = "BONUS +" + bonus;
ABonus.PlayOneShot(ABonus.clip);
Object.Destroy(other.gameObject.transform.parent.gameObject);
}
if (other.gameObject.tag == "doisX")
{
XQuatroX = false;
xQuatro.SetActive(value: false);
multTimer = 20f;
xDois.SetActive(value: true);
XDoisX = true;
ABonus.PlayOneShot(ABonus.clip);
Object.Destroy(other.gameObject.transform.parent.gameObject);
}
if (other.gameObject.tag == "quatroX")
{
XDoisX = false;
xDois.SetActive(value: false);
multTimer = 20f;
xQuatro.SetActive(value: true);
XQuatroX = true;
ABonus.PlayOneShot(ABonus.clip);
Object.Destroy(other.gameObject.transform.parent.gameObject);
}
if (other.gameObject.tag == "grama")
{
m_Animator.SetBool("Caiu", value: true);
m_Animator.SetBool("Flip", value: false);
playmorte = true;
isDead = true;
velocidade = 0f;
base.transform.position = respMorte.transform.position;
}
if (other.gameObject.tag == "mano")
{
areaMano = other.gameObject.GetComponent<AreaMano>();
mano = true;
if (!mano01.activeSelf)
{
mano01.SetActive(value: true);
}
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Rampa")
{
isRamp = false;
}
if (other.gameObject.tag == "grindInter")
{
isGrind = false;
intermedio = false;
}
if (other.gameObject.tag == "grind")
{
isGrind = false;
intermedio = false;
}
if (other.gameObject.tag == "grama")
{
grama = false;
}
if (other.gameObject.tag == "mano")
{
areaMano = null;
mano = false;
}
}
private void OnTriggerStay(Collider other)
{
if (other.gameObject.tag == "grindInter")
{
isGrind = true;
}
if (other.gameObject.tag == "grind")
{
isGrind = true;
}
}
private void AreaManobra()
{
if (mano)
{
if (mano01.activeSelf)
{
manoText.text = "Realize - 0" + areaMano.TotalMano + " manobras";
}
if (areaMano.AttMano >= areaMano.TotalMano)
{
mano02.SetActive(value: true);
}
}
}
}
|
24ff543a5850608648d920a84946beb5
|
{
"intermediate": 0.2880202531814575,
"beginner": 0.43423697352409363,
"expert": 0.27774280309677124
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.