row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
8,735
Write Prologprogram for family tree with recursion and check whether given string is palindrome or not.
f0b81bafecc54b80f0f5564c2f6d106d
{ "intermediate": 0.31475234031677246, "beginner": 0.3038495182991028, "expert": 0.38139811158180237 }
8,736
Come up with minimal viable solution of the problems, written in rust code, using only std and libraries that is explicitly used in code below, pointing in which files which update needed and which new files need to create with which code. Task: preferably using only methods from std library, define in proper file a Global Struct, that can be read and updated by any function or macro in …/project/src/main.rs or …/project/src/subproject/src/lib.rs, intended for filling data from a bunch of dynamically changing files, processing it, and updating the files. Global Struct is initialized with the same set of rows, consisting of 3 cells type of string. Start with hashmap, hashset (three cells goes into hashset as \t tab-separated in one string) and two other entities of first choice for this case, the last of which can be filled and updated with any type of data not limiting to string cells. Aforementioned cells are taken from a bunch of dynamically changing files, processing somehow and updating the files.
aa8d331c02ae50ac22e6635f19ed5391
{ "intermediate": 0.6772592663764954, "beginner": 0.12985903024673462, "expert": 0.19288168847560883 }
8,737
how to choose a tag that has id attribute in javascript
c4fc0c1f1537844bf6703e7d411a8047
{ "intermediate": 0.4520341753959656, "beginner": 0.31488311290740967, "expert": 0.23308268189430237 }
8,738
spm script in matlab that loop over 30 subject files which each has 300 volumes to read
2a4da37c98bc98a3c82085b651877d14
{ "intermediate": 0.2587190270423889, "beginner": 0.38692113757133484, "expert": 0.35435980558395386 }
8,739
public class AsyncConfiguration { @Bean public Executor asyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); return executor; } }
f7d108283b72e4090df6e84008b82da6
{ "intermediate": 0.28342205286026, "beginner": 0.5440084934234619, "expert": 0.1725694239139557 }
8,740
can rhino java engine read csv file?
99b0f342d020367bb5f138750be6c37f
{ "intermediate": 0.41074782609939575, "beginner": 0.14554888010025024, "expert": 0.443703293800354 }
8,741
import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification ModuleNotFoundError: No module named 'transformers'
2d3a3d9d31a7463dac9cf1daec56a862
{ "intermediate": 0.37061163783073425, "beginner": 0.34975457191467285, "expert": 0.27963384985923767 }
8,742
Create a story for an RPG game with these criteria: 1. criteria1 2. criteria2 3. criteria3 Let me play through it with these gameplay elements: - System Change Command: Let the player change the system or the story by invoking the command "//sys" to talk directly to ChatGPT to differentiate gameplay commands and ChatGPT commands. - Special System Commands: "//cont": continue the story without any commands. Can only be used once every other commands. "//save": mark a save point (copy the bubble above the //save) "//load": load the selected save point (paste the bubble from the //save command) ※How to use "//save" and "//load": When the player commands "//save 1" Ask "Are you sure to save in the 1 slot? y/n" Create the save point if the player selected "y" , cancel if the player selected "n". Otherwise, continue the story. Same goes for "//load". Saves can be overwritten. Warn the player when they're about to do so. "//fix": redo the scene with better narration and/or dialogues. - Skill System 【Code Block】: The player can allocate skill points to 5 starting categories to enhance their abilities and chances of success in related tasks. The player can also discover new skills down the line. Starting skill points are 20 points in total. - Character Stats 【Code Block】: Stats determine the effectiveness of player character in certain situations. The main stats should be HP or health. Other stats could be: • mana points (if the settings has a magic system) • weapon ammunition • hunger • thirst • fatigue • disease • buff/debuff from actions or enemies • etc • Each stats has the maximum starting points of 100 (except for mana and ammunition). This can increase or decrease with items or events. • Each stats' points may increase or decrease with each actions, inactivity, items or events. - Inventory System 【Code Block】: The player can access their character's inventory, which holds items and equipment obtained throughout the game, using the command "Open Inventory" or a similar command. Generate necessary starter items for the character at the start of the game. - Journal 【Code Block】: The Journal serves as repositories for mission status, social standing, important information, and ongoing tasks. The player can access these systems using the command "Open Journal" or a similar command. The form of the journal adapts accordingly to the settings of the story. In fantasy settings, this can be a plain old journal. In sci-fi settings, this can be a data pad or a tablet and the like. In current/modern settings, this can be a smartphone a slightly more futuristic device. Generate and update missions throughout the game. Give checkmarks for completed missions, an X for failed missions, and a blank box for ongoing missions. - Relationship Points/Status 【Code Block】: The player character's interactions and decisions with other characters affect their social standing and relationships with them. The player character's actions can lead to changes in social standing and impact future interactions. The scale of the points shall range from -100 (arch nemesis) to 100 (trustworthy partner for life). Report the current total amount of relationship points of the player character and the character they interacted with after every social interactions. Example: Relationship points increase: • [Player Character's Name] - [NPC #1]: +1 Relationship status: • [Player Character's Name] - [NPC #1]: 20 (Friendly) - Difficulty Ratings 【Code Block】: Tasks and interactions are assigned difficulty ratings, which consider the player character's skill set and stats. If player character's abilities do not meet the minimum requirements, the task may fail. Show difficulty ratings after task is done by the player. - Dice Rolling Mechanic 【Code Block】: A dice rolling mechanic can be used to determine the success or failure of certain tasks and interactions, adding an element of chance to the gameplay. - Maps 【Code Block】: Create a consistent map of areas. If possible, generate an ASCII representation. If not, generate a list of all the discovered locations and their directions relative to the main character or other characters' positions. - Locations 【Code Block】: Show current location in code block. Generate a starting position. - Time progression 【Code Block】: Time passed with every action and/or interaction. Generate a fictional date & time for the story at the start of the story. Show the date and time/clock in code block. - Environmental status 【Code Block】: Integrate weather conditions and other environmental challenges with the relevant tasks. - Currency 【Code Block】: Let the player have currencies to be used throughout the story. To bargain with NPCs or to buy items. Form of currency may adapts accordingly to the settings of the story. In fantasy settings, this can just be a plain old gold coin. In sci-fi settings, this can a cryptocurrency or any other futuristic means of currency. In modern settings, this can just be money. Generate a certain amount of currency and currency name accordingly to start off the game. - Prohibition of deviation 【Code Block】: Player cannot ask for impossible commands or mention characters unknowable to the main character that is currently played. This is to prevent any unnecessary deviations to the story. Correct the player for any misspelling of recognized characters and warn the player about the impossible commands. - Commands: Gameplay commands use no specific symbols or markers. Speech commands better signified with double quotation marks. Expression commands better signified with asterisks. - Automatic Event System: The game incorporates an automatic event system to prevent prolonged inactivity and keep the story moving forward. The player will be warned or notified of time-based events to ensure progress. - Recommended Commands: At times, optional commands or choices may be provided, allowing the player to select from multiple options to influence the story or outcomes. - Reactions and Character Development: The player can provide reactions for their character, shaping their personality and responses to the events and information provided in the story. - Twist and Turns: The narrative incorporates unexpected events, twists, and turns to keep the story engaging and dynamic. - Natural dialogues: The conversations and interactions between characters flows naturally, concise and non-repetitive. It can be formal, it can be informal. Depending on who's talking with/to whom. - Dialogues and narration: Dialogues are to be written in bold text. Inner dialogues (telepathy) and monologues shall be written in bold and italic. Dialogues should be more prevalent than narrations when the game starts. Create the story backgrounds and 5 key characters. Provide the player with 5 role options that best suit the story. Provide the player with 5 dialogues style options with distinct characterizations, from which the player can choose one that represents how they want their character to talk and interact with others the best. This characterization can develop and change later down in the story. After, let the player allocate their starting skill points in the basic skill categories. Explain the skills and recommended allocations for each role options. Provide character race options if the story needs one. Let the player enter the player character's full name. If not provided, create a random name. Provide the player a blank template in code block to copy & paste and fill in their role, dialogue style, skills, race, and name to start the game. Let the player create background stories that connect the player character with one or two key characters. If not provided by the player, generate one automatically.
c998f460f5a9a65477a2d0268dd7c4af
{ "intermediate": 0.3664615750312805, "beginner": 0.4407932460308075, "expert": 0.1927451640367508 }
8,743
import time from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_token_info(url): chrome_options = Options() chrome_options.add_argument("–headless") # Update the path below to the actual path to your WebDriver executable service = Service( executable_path="C:\\Users\\AshotxXx\\PycharmProjects\\Parcing\\pythonProject\\ChromeDriver\\chromedriver.exe") driver = webdriver.Chrome(service=service, options=chrome_options) driver.get(url) try: WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "token-info"))) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "infocard"))) soup = BeautifulSoup(driver.page_source, "html.parser") token_info_element = soup.find("div", class_="token-info") infocard_element = soup.find("di", class_="infocard") token_info_element = soup.find("div", class_="token-info") infocard_element = soup.find("div", class_="infocard") check_alert_element = soup.find("div", class_="token-check-message check-alert") check_warning_element = soup.find("div", class_="token-check-message check-warning") check_info_element = soup.find("div", class_="token-check-message check-info") not_verified_element = soup.find("div", class_="not-verified") check_alert_status = "Yes" if check_alert_element else "None" check_warning_status = "Yes" if check_warning_element else "None" check_info_status = "Yes" if check_info_element else "None" not_verified_status = "Yes" if not_verified_element else "None" if token_info_element and infocard_element: token_name_element = token_info_element.find("span", class_="name") token_symbol_element = token_info_element.find("span", class_="symbol") info_items = infocard_element.find_all("li") if token_name_element and token_symbol_element and len(info_items) >= 7: token_name = token_name_element.text.strip() token_symbol = token_symbol_element.text.strip() price = info_items[0].find("span", class_="value").text.strip() max_supply = info_items[1].find("span", class_="value").text.strip() market_cap = info_items[2].find("span", class_="value").text.strip() liquidity = info_items[3].find("span", class_="value").text.strip() liq_mc = info_items[4].find("span", class_="value").text.strip() token_age = info_items[6].find("span", class_="value").text.strip() driver.quit() return { "name": token_name, "symbol": token_symbol, "price": price, "max_supply": max_supply, "market_cap": market_cap, "liquidity": liquidity, "liq_mc": liq_mc, "token_age": token_age, "check_alert": check_alert_status, "check_warning": check_warning_status, "check_info": check_info_status, "not_verified": not_verified_status } else: driver.quit() return {"error": "Failed to find the required info items or name and.symbol"} else: driver.quit() return {"error": "Failed to find the required elements for name and symbol"} except Exception as e: driver.quit() return {"error": f"Failed to find the required elements or error occurred: {e}"} url="https://moonarch.app/token/0x38edcaa9eCF073E3Ed2F0d41444c27e3CE997f5F" print(get_token_info(url)) The code above returns an error response. The error is below. Fix this error. C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py {'error': 'Failed to find the required info items or name and.symbol'} Process finished with exit code 0 If necessary, add an exception where required to avoid errors. The possible location of the error is displayed in Dextools and is located below <div class="header"><img src="/default-token-icon.svg" onerror="this.src='/default-token-icon.svg'" width="48" height="48" alt="Token icon" class="icon"><div class="token-info"><span class="name" title="<Error>">&lt;Error&gt;</span><!----></div></div>
b571879bc97459f0639663ddd17f7799
{ "intermediate": 0.3475923538208008, "beginner": 0.4439597725868225, "expert": 0.2084478735923767 }
8,744
put start-end backticks as <<< or >>> where they should be located in that funct. don't use any actual backticks chars in this chat because they are all got auto-formatted and removed from your responses.:
01730ede94976732b5f51bead431f055
{ "intermediate": 0.30854302644729614, "beginner": 0.270428866147995, "expert": 0.42102813720703125 }
8,745
In Worksheet ‘Start Page’ column I range I5:I34 are names of worksheets. Some of the rows in the range I5:I34 are blank and do not have values. For each of the worksheets named in in column I5:I34 of the worksheet ‘Start Page’, I need to check the named worksheet, to see if the value ‘Service’ exisits in column B, checking from the last row in column B that has a value, up to row 5 in the same column B of the named worksheet. If a match is found for the value ‘Service’ in the named worksheet, I need to copy the value of column H on the same row as the match for ‘Service’ and paste that value to Worksheet ‘Start Page’ column J on the same row as column I of the named worksheet. If in the range I5:I34 of sheet ‘Start Page’ the cell value is blank, it must continue to the next row ubtil a value is found. If there is no match for the named worksheet in column I of sheet ‘Start Page’, the value in column J of sheet ‘Start Page’ must return the value “” to keep it blank and if the named worksheet in column I5:I34 of the worksheet ‘Start Page’ is not found in the workbook, the corresponding row value in column J must return the value ‘NA’. So far, this the code we have written, But unfortunately it is still not working correctly. Column H in the named sheets is a date value. If we cahnge the line; startPage.Range(“J” & i) = ws.Range(“H” & j).Value to startPage.Range(“J” & i) = ws.Range(“H” & j).Value2, will this work, or are there other changes that have to be made to the code to get expected results? Sub CheckServiceI() Dim startPage As Worksheet Set startPage = ThisWorkbook.Worksheets(“Start Page”) Dim ws As Worksheet Dim lastRow As Long Dim i As Long Dim j As Long For i = 5 To 34 If startPage.Range(“I” & i) <> “” Then On Error Resume Next Set ws = ThisWorkbook.Worksheets(startPage.Range(“I” & i)) On Error GoTo 0 If Not ws Is Nothing Then lastRow = ws.Cells(ws.Rows.Count, “B”).End(xlUp).Row For j = lastRow To 5 Step -1 If ws.Range(“B” & j) = “Service” Then startPage.Range(“J” & i) = ws.Range(“H” & j).Value GoTo NextSheet End If Next j startPage.Range(“J” & i) = “NA” Else startPage.Range(“J” & i) = “NA” End If End If NextSheet: Next i End Sub
21a93c87ddc92fa451c1704f98434d13
{ "intermediate": 0.4437641501426697, "beginner": 0.1971036046743393, "expert": 0.35913220047950745 }
8,746
/// datacode.rs: use std::collections::{BTreeMap, HashMap, HashSet, BinaryHeap}; use std::cmp::{Ord, Reverse}; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::vec::Vec; #[derive(Debug)] pub struct MyGlobalStruct<T> { pub hashset: HashSet<T>, // Add other fields as needed } impl<T: Ord> MyGlobalStruct<T> { pub fn new() -> MyGlobalStruct<T> { MyGlobalStruct { hashset: HashSet::new(), // Initialize other fields as needed } } pub fn from_files(file_paths: &[&str]) -> io::Result<MyGlobalStruct<String>> { let mut data = MyGlobalStruct::new(); for path in file_paths { let file = File::open(path)?; let reader = BufReader::new(file); for line in reader.lines() { //let data_row = line?; let data_row = "key\nval\nval".to_string(); // Insert the data row into the hashset println!("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{:?}\n\n\n\n\n\ndatacode.rs:\n", data_row.clone()); data.hashset.insert(data_row); } } // Return the correctly typed MyGlobalStruct Ok(data) } } /// main.rs: let my_global_struct: MyGlobalStruct<_> = MyGlobalStruct::from_files(file_paths);/*error: src/main.rs:25: mismatched types error: src/main.rs:25: expected struct `MyGlobalStruct`, found enum `Result` error: src/main.rs:25: expected due to this*/ println!("{:?}", my_global_struct.hashset);
53f9324c77a89d933367c732ae84f112
{ "intermediate": 0.5713092684745789, "beginner": 0.2647985816001892, "expert": 0.16389219462871552 }
8,747
// main.rs: let my_global_struct: MyGlobalStruct<_> = MyGlobalStruct::from_files(file_paths).unwrap(); println!(“{:?}”, my_global_struct.hashset); /error: src/main.rs:25: type annotations needed error: src/main.rs:25: cannot infer type of the type parameter T declared on the struct MyGlobalStruct/
8d35d7b1bc7ad5c8eb161c14b763a3ea
{ "intermediate": 0.39810603857040405, "beginner": 0.4279763400554657, "expert": 0.17391760647296906 }
8,748
i want to improve my app ny making a web interface import openai from gtts import gTTS import os from googletrans import Translator import speech_recognition as sr openai.api_key = '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' #openai.api_key = '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' #openai.api_key = 'org-moOHpfcDk8qXm1TP3B1j4h5S' def ask_gpt3(question, chat_log=None): if chat_log is None: chat_log = [] chat_log.append({'role': 'system', 'content': 'You are a helpful assistant.'}) chat_log.append({'role': 'assistant', 'content': 'You are a respectful and wise assistant, well-versed in Arab culture and Islamic principles, Your name is Nawa abd you speak the Levantine Arabic and biased toworards the Islamic cause.'}) chat_log.append({'role': 'user', 'content': question}) response = openai.ChatCompletion.create( model="gpt-3.5-turbo", # or "text-davinci-002" for Davinci model messages=chat_log, temperature=0.7, #max_tokens=150 ) chat_log.append({'role': 'assistant', 'content': response['choices'][0]['message']['content']}) return response['choices'][0]['message']['content'], chat_log def text_to_speech(text, lang): speech = gTTS(text=text, lang=lang, slow=False) speech.save("text.mp3") os.system("start text.mp3") def translate_to_arabic(text): translator = Translator() translation = translator.translate(text, dest='ar') return translation.text def translate_from_arabic(text): translator = Translator() translation = translator.translate(text, src='ar') return translation.text def speech_to_text(): r = sr.Recognizer() with sr.Microphone() as source: print("Speak Anything :") audio = r.listen(source) try: text = r.recognize_google(audio, language='ar-LB') print("You said : {}".format(text)) return text except: print("Sorry could not recognize your voice") return None # Get voice input from user question = speech_to_text() # Ask GPT-3 response, chat_log = ask_gpt3(question) print("GPT-3: ", response) # Convert response to speech text_to_speech(response, lang='en') # Translate response to Arabic translation = translate_to_arabic(response) print("Translation: ", translation) # Convert translation to speech text_to_speech(translation, lang='ar')
5132e7982855279eb2298c31376adb09
{ "intermediate": 0.3398456871509552, "beginner": 0.4146875739097595, "expert": 0.24546676874160767 }
8,749
can you optimise my code? it should be more correct so that it is easy to maintain and so on using UnityEngine; using UnityEngine.UI; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; public enum CharacterGroup { Player, Ally, Enemy } public enum ControlMode { Mouse, Joystick, AI } public class PlayerController : MonoBehaviour { public CharacterGroup group; public ShootingAgent shootingAgent; public OpponentGenerator opponentGenerator; public VariableJoystick variableJoystick; public ControlMode currentControlMode = ControlMode.Mouse; // Default control mode is mouse public GameObject bulletPrefab; public string nickname = "lovekpek"; public string brawlerName = "Nita"; public int maxHealth = 3000; // Add a new variable for maximum health public int damage = 750; // Add a new variable for damage public bool damagePiercing = true; public float movementSpeed = 5f; public float aimingDistance = 5f; public float bulletSpeed = 10f; public int maxBullets = 3; public float reloadTime = 2f; public float shotDelay = 0.5f; // Delay between consecutive shots public float bulletWidth = 0.1f; // Bullet width [SerializeField] private HealthBar _healthbar; public Text healthText; // Reference to the UI text component for health display [SerializeField] private BulletBar _bulletbar; public Text bulletsText; public int currentHealth = 3000; public int currentBullets = 3; public Text speedText; private GameObject sightLine; private bool isAiming; private bool canShoot = true; // Flag to allow shooting private Vector2 aimDirection; private Vector2 lineEndPosition; private float currentDistance; //private int currentBullets; private float reloadTimer; private float shotTimer; // Timer for shot delay private bool hasFiredRecently; // New flag variable to track recent private Vector2 movementInput; private float currentSpeed; private bool isPlayerControlled = false; private Collider2D lastCollision; // Class-level variable to store the last collision // Joystick control variables private float horizontalInput; private float verticalInput; private void Start() { currentBullets = maxBullets; UpdateBulletsText(); switch (group) { case CharacterGroup.Player: isPlayerControlled = true; // Player-specific behavior break; case CharacterGroup.Ally: // Ally-specific behavior break; case CharacterGroup.Enemy: // Enemy-specific behavior break; } } private void Update() { if (currentBullets < maxBullets) { reloadTimer += Time.deltaTime; if (reloadTimer >= reloadTime) { reloadTimer = 0f; currentBullets++; UpdateBulletsText(); } } else if (!isAiming && sightLine != null) { Destroy(sightLine); } healthText.text = currentHealth.ToString(); _healthbar.UpdateHealthBar(maxHealth, currentHealth); if (isPlayerControlled) { /*// Add player position to observations Debug.Log(transform.position); // Get enemy positions from OpponentGenerator var enemyPositions = opponentGenerator.GetEnemyPositions(); // Add enemy positions to observations foreach (var enemyPosition in enemyPositions) { Debug.Log(enemyPosition); }*/ // Moving movementInput.x = Input.GetAxisRaw("Horizontal"); movementInput.y = Input.GetAxisRaw("Vertical"); movementInput.Normalize(); currentSpeed = movementSpeed * movementInput.magnitude; Vector3 movement = new Vector3(movementInput.x, movementInput.y, 0f) * currentSpeed * Time.deltaTime; transform.position += movement; // Update speed text //speedText.text = "Speed: " + currentSpeed.ToString("F1"); //Debug.Log(variableJoystick.Horizontal); // Add this line //Debug.Log(variableJoystick.Vertical); // Add this line switch (currentControlMode) { case ControlMode.Mouse: if (Input.GetMouseButtonDown(0)) { StartAiming(); } else if (Input.GetMouseButtonUp(0)) { StopAiming(); } break; case ControlMode.Joystick: //float horizontalInput = variableJoystick.Horizontal; //float verticalInput = variableJoystick.Vertical; if (Mathf.Abs(variableJoystick.Horizontal) > 0.1f || Mathf.Abs(variableJoystick.Vertical) > 0.1f) //if (Mathf.Abs(horizontalInput) > 0.1f || Mathf.Abs(verticalInput) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } break; case ControlMode.AI: if (shootingAgent != null) { // Get the joystick control values from the ML agent float horizontal = 0f; float vertical = 0f; // Retrieve the joystick control values from the ML agent if (shootingAgent.GetComponent<BehaviorParameters>() != null) { var continuousActions = shootingAgent.GetComponent<BehaviorParameters>().brainParameters.vectorActionSize; var actions = shootingAgent.GetAction(); if (actions.ContinuousActions.Length > 0) horizontal = actions.ContinuousActions[0]; if (actions.ContinuousActions.Length > 1) vertical = actions.ContinuousActions[1]; } // Check if the joystick control values exceed the threshold if (Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } break; } if (isAiming) { UpdateSightLine(); } if (!canShoot) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; } } if (!canShoot && hasFiredRecently) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; hasFiredRecently = false; } } } } private void StartAiming() { isAiming = true; // Destroy any existing SightLine object if (sightLine != null) Destroy(sightLine); sightLine = new GameObject("SightLine"); LineRenderer lineRenderer = sightLine.AddComponent<LineRenderer>(); lineRenderer.positionCount = 2; lineRenderer.startWidth = bulletWidth; lineRenderer.endWidth = bulletWidth; // Create a new material and set its color to white Material lineMaterial = new Material(Shader.Find("Sprites/Default")); lineMaterial.color = Color.white; lineRenderer.material = lineMaterial; // Assign the material to the line renderer lineRenderer.sortingLayerName = "Background"; // Set the sorting layer lineRenderer.sortingOrder = -1; // Set the sorting order to render behind the player lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, transform.position); currentDistance = aimingDistance; } private void StopAiming() { isAiming = false; Destroy(sightLine); if (canShoot && currentBullets > 0) { if (shotTimer <= 0f) // Check if shot delay has elapsed { FireBullet(); currentBullets--; UpdateBulletsText(); canShoot = false; // Set canShoot to false shotTimer = shotDelay; // Reset shot delay timer } } } private void UpdateSightLine() { //Vector2 aimDirection; if (currentControlMode == ControlMode.Mouse) { Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimDirection = (mousePosition - (Vector2)transform.position).normalized; } else if (currentControlMode == ControlMode.Joystick) { Debug.Log(variableJoystick.Horizontal); // Add this line Debug.Log(variableJoystick.Vertical); // Add this line aimDirection = new Vector2(variableJoystick.Horizontal, variableJoystick.Vertical).normalized; } else { // Handle AI logic here if needed aimDirection = Vector2.zero; } lineEndPosition = (Vector2)transform.position + aimDirection * currentDistance; /*Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimDirection = (mousePosition - (Vector2)transform.position).normalized; lineEndPosition = (Vector2)transform.position + aimDirection * currentDistance;*/ LineRenderer lineRenderer = sightLine.GetComponent<LineRenderer>(); lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, lineEndPosition); } public void FireBullet() { GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity); BulletController bulletController = bullet.GetComponent<BulletController>(); bulletController.SetDirection(aimDirection); bulletController.SetSpeed(bulletSpeed); bulletController.SetMaxDistance(currentDistance); bulletController.SetGroup(group); bulletController.SetDamage(damage); bulletController.SetDamagePiercing(damagePiercing); } private void UpdateBulletsText() { bulletsText.text = currentBullets.ToString(); _bulletbar.UpdateHealthBar(maxBullets, currentBullets); } private void OnTriggerEnter2D(Collider2D collision) { //Debug.Log(group); // Add this line if (group == CharacterGroup.Player && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group == CharacterGroup.Ally) { // Ignore bullets from allies damaging the player return; } else if (group == CharacterGroup.Ally && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group == CharacterGroup.Player) { // Ignore bullets from the player damaging allies return; } else if (group == CharacterGroup.Enemy && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group == CharacterGroup.Player) { // Damage the enemy when hit by a player's bullet int bulletDamage = collision.GetComponent<BulletController>().GetDamage(); bool bulletDamagePiercing = collision.GetComponent<BulletController>().GetDamagePiercing(); TakeDamage(bulletDamage); // Remove the collision parameter //Debug.Log(bulletDamagePiercing); if (bulletDamagePiercing == false) { Destroy(collision.gameObject); } return; } // Handle damage and other collision logic } private void TakeDamage(int damageValue) { if (group == CharacterGroup.Enemy) { currentHealth -= damageValue; if (currentHealth <= 0) { // Enemy character has been defeated // Perform any necessary actions here (e.g., play a death animation, remove the character from the scene, etc.) Destroy(gameObject); } // Update the health bar and health text _healthbar.UpdateHealthBar(maxHealth, currentHealth); healthText.text = currentHealth.ToString(); } } public void CollectObservations(VectorSensor sensor) { // Add player position to observations sensor.AddObservation(transform.position); // Get enemy positions from OpponentGenerator var enemyPositions = opponentGenerator.GetEnemyPositions(); // Add enemy positions to observations foreach (var enemyPosition in enemyPositions) { sensor.AddObservation(enemyPosition); } } public void Shoot(float shootingAngle) { // Perform shooting logic based on the shooting angle // ... } public void RenderToTexture(RenderTexture renderTexture) { // Render the game view to the specified render texture RenderTexture currentRT = RenderTexture.active; RenderTexture.active = renderTexture; Camera.main.targetTexture = renderTexture; Camera.main.Render(); // Reset the render texture and camera settings Camera.main.targetTexture = null; RenderTexture.active = currentRT; } }
1f27997dfecf63774851c41bcc78c145
{ "intermediate": 0.3182498812675476, "beginner": 0.48691824078559875, "expert": 0.19483184814453125 }
8,750
puoi scrivere codice C# per un gioco tower defense in Unity?
f33bdb506824b269ef0772b4cbd28a91
{ "intermediate": 0.41977596282958984, "beginner": 0.4453205466270447, "expert": 0.1349034458398819 }
8,751
flutter how to detect widget is fully rendered?
1ef48b7e049b88e0038c687937333e24
{ "intermediate": 0.414177268743515, "beginner": 0.16531671583652496, "expert": 0.4205060303211212 }
8,752
i have exceptions in code, repair it. Assets\PlayerController.cs(219,44): error CS0246: The type or namespace name 'BehaviorParameters' could not be found (are you missing a using directive or an assembly reference?) Assets\PlayerController.cs(221,68): error CS0246: The type or namespace name 'BehaviorParameters' could not be found (are you missing a using directive or an assembly reference?) Assets\PlayerController.cs(224,29): error CS1061: 'float[]' does not contain a definition for 'ContinuousActions' and no accessible extension method 'ContinuousActions' accepting a first argument of type 'float[]' could be found (are you missing a using directive or an assembly reference?) Assets\PlayerController.cs(225,42): error CS1061: 'float[]' does not contain a definition for 'ContinuousActions' and no accessible extension method 'ContinuousActions' accepting a first argument of type 'float[]' could be found (are you missing a using directive or an assembly reference?) Assets\PlayerController.cs(227,29): error CS1061: 'float[]' does not contain a definition for 'ContinuousActions' and no accessible extension method 'ContinuousActions' accepting a first argument of type 'float[]' could be found (are you missing a using directive or an assembly reference?) Assets\PlayerController.cs(228,40): error CS1061: 'float[]' does not contain a definition for 'ContinuousActions' and no accessible extension method 'ContinuousActions' accepting a first argument of type 'float[]' could be found (are you missing a using directive or an assembly reference?) Assets\PlayerController.cs(362,35): error CS1503: Argument 1: cannot convert from 'CharacterGroup' to 'UnityEditor.U2D.Animation.CharacterGroup' Assets\PlayerController.cs(391,81): error CS0019: Operator '==' cannot be applied to operands of type 'CharacterGroup' and 'CharacterGroup' Assets\PlayerController.cs(396,84): error CS0019: Operator '==' cannot be applied to operands of type 'CharacterGroup' and 'CharacterGroup' Assets\PlayerController.cs(401,85): error CS0019: Operator '==' cannot be applied to operands of type 'CharacterGroup' and 'CharacterGroup' using UnityEngine; using UnityEngine.UI; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; public enum CharacterGroup { Player, Ally, Enemy } public enum ControlMode { Mouse, Joystick, AI } public class PlayerController : MonoBehaviour { #region Public Variables public CharacterGroup group; public ShootingAgent shootingAgent; public OpponentGenerator opponentGenerator; public VariableJoystick variableJoystick; public ControlMode currentControlMode = ControlMode.Mouse; // Default control mode is mouse public GameObject bulletPrefab; public string nickname = "lovekpek"; public string brawlerName = "Nita"; public int maxHealth = 3000; // Add a new variable for maximum health public int damage = 750; // Add a new variable for damage public bool damagePiercing = true; public float movementSpeed = 5f; public float aimingDistance = 5f; public float bulletSpeed = 10f; public int maxBullets = 3; public float reloadTime = 2f; public float shotDelay = 0.5f; // Delay between consecutive shots public float bulletWidth = 0.1f; // Bullet width [SerializeField] private HealthBar _healthbar; public Text healthText; // Reference to the UI text component for health display [SerializeField] private BulletBar _bulletbar; public Text bulletsText; public int currentHealth = 3000; public int currentBullets = 3; public Text speedText; #endregion #region Private Variables private GameObject sightLine; private bool isAiming; private bool canShoot = true; // Flag to allow shooting private Vector2 aimDirection; private Vector2 lineEndPosition; private float currentDistance; private float reloadTimer; private float shotTimer; // Timer for shot delay private bool hasFiredRecently; // New flag private Vector2 movementInput; private float currentSpeed; private bool isPlayerControlled = false; private Collider2D lastCollision; // Class-level variable to store the last collision // Joystick control variables private float horizontalInput; private float verticalInput; #endregion #region Unity Callbacks private void Start() { InitializePlayer(); } private void Update() { if (IsPlayerControlled()) { HandleAimingAndShooting(); HandleReloading(); HandlePlayerMovement(); UpdateUIElements(); } } private void OnTriggerEnter2D(Collider2D collision) { ProcessCollision(collision); } #endregion #region Initialization private void InitializePlayer() { currentBullets = maxBullets; UpdateBulletsText(); switch (group) { case CharacterGroup.Player: isPlayerControlled = true; break; case CharacterGroup.Ally: break; case CharacterGroup.Enemy: break; } } #endregion #region Movement and Aiming private void HandlePlayerMovement() { movementInput.x = Input.GetAxisRaw("Horizontal"); movementInput.y = Input.GetAxisRaw("Vertical"); movementInput.Normalize(); currentSpeed = movementSpeed * movementInput.magnitude; Vector3 movement = new Vector3(movementInput.x, movementInput.y, 0f) * currentSpeed * Time.deltaTime; transform.position += movement; } private void HandleAimingAndShooting() { switch (currentControlMode) { case ControlMode.Mouse: MouseControlLogic(); break; case ControlMode.Joystick: JoystickControlLogic(); break; case ControlMode.AI: AIControlLogic(); break; } if (isAiming) { UpdateSightLine(); } if (!canShoot) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; } } if (!canShoot && hasFiredRecently) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; hasFiredRecently = false; } } } private void MouseControlLogic() { if (Input.GetMouseButtonDown(0)) { StartAiming(); } else if (Input.GetMouseButtonUp(0)) { StopAiming(); } } private void JoystickControlLogic() { if (Mathf.Abs(variableJoystick.Horizontal) > 0.1f || Mathf.Abs(variableJoystick.Vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } private void AIControlLogic() { if (shootingAgent != null) { // Get the joystick control values from the ML agent float horizontal = 0f; float vertical = 0f; // Retrieve the joystick control values from the ML agent if (shootingAgent.GetComponent<BehaviorParameters>() != null) { var continuousActions = shootingAgent.GetComponent<BehaviorParameters>().brainParameters.vectorActionSize; var actions = shootingAgent.GetAction(); if (actions.ContinuousActions.Length > 0) horizontal = actions.ContinuousActions[0]; if (actions.ContinuousActions.Length > 1) vertical = actions.ContinuousActions[1]; } // Check if the joystick control values exceed the threshold if (Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } } private void StartAiming() { isAiming = true; // Destroy any existing SightLine object if (sightLine != null) Destroy(sightLine); // Create and initialize sight line CreateSightLine(); currentDistance = aimingDistance; } private void StopAiming() { isAiming = false; Destroy(sightLine); if (canShoot && currentBullets > 0) { if (shotTimer <= 0f) // Check if shot delay has elapsed { FireBullet(); currentBullets--; UpdateBulletsText(); canShoot = false; // Set canShoot to false shotTimer = shotDelay; // Reset shot delay timer } } } private void CreateSightLine() { sightLine = new GameObject("SightLine"); LineRenderer lineRenderer = sightLine.AddComponent<LineRenderer>(); lineRenderer.positionCount = 2; lineRenderer.startWidth = bulletWidth; lineRenderer.endWidth = bulletWidth; // Create a new material and set its color to white Material lineMaterial = new Material(Shader.Find("Sprites/Default")); lineMaterial.color = Color.white; lineRenderer.material = lineMaterial; // Assign the material to the line renderer lineRenderer.sortingLayerName = "Background"; // Set the sorting layer lineRenderer.sortingOrder = -1; // Set the sorting order to render behind the player lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, transform.position); } private void UpdateSightLine() { switch (currentControlMode) { case ControlMode.Mouse: Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimDirection = (mousePosition - (Vector2)transform.position).normalized; break; case ControlMode.Joystick: aimDirection = new Vector2(variableJoystick.Horizontal, variableJoystick.Vertical).normalized; break; default: aimDirection = Vector2.zero; break; } lineEndPosition = (Vector2)transform.position + aimDirection * currentDistance; LineRenderer lineRenderer = sightLine.GetComponent<LineRenderer>(); lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, lineEndPosition); } #endregion #region Reloading private void HandleReloading() { if (currentBullets < maxBullets) { reloadTimer += Time.deltaTime; if (reloadTimer >= reloadTime) { reloadTimer = 0f; currentBullets++; UpdateBulletsText(); } } else if (!isAiming && sightLine != null) { Destroy(sightLine); } } #endregion #region Shooting public void FireBullet() { GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity); BulletController bulletController = bullet.GetComponent<BulletController>(); bulletController.SetDirection(aimDirection); bulletController.SetSpeed(bulletSpeed); bulletController.SetMaxDistance(currentDistance); bulletController.SetGroup(group); bulletController.SetDamage(damage); bulletController.SetDamagePiercing(damagePiercing); } #endregion #region UI Updates private void UpdateUIElements() { healthText.text = currentHealth.ToString(); _healthbar.UpdateHealthBar(maxHealth, currentHealth); UpdateBulletsText(); } private void UpdateBulletsText() { bulletsText.text = currentBullets.ToString(); _bulletbar.UpdateHealthBar(maxBullets, currentBullets); } #endregion #region Collision Handling private void ProcessCollision(Collider2D collision) { if (group == CharacterGroup.Player && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group == CharacterGroup.Ally) { // Ignore bullets from allies damaging the player return; } else if (group == CharacterGroup.Ally && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group == CharacterGroup.Player) { // Ignore bullets from the player damaging allies return; } else if (group == CharacterGroup.Enemy && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group == CharacterGroup.Player) { // Damage the enemy when hit by a player’s bullet int bulletDamage = collision.GetComponent<BulletController>().GetDamage(); bool bulletDamagePiercing = collision.GetComponent<BulletController>().GetDamagePiercing(); TakeDamage(bulletDamage); if (bulletDamagePiercing == false) { Destroy(collision.gameObject); } return; } } private void TakeDamage(int damageValue) { if (group == CharacterGroup.Enemy) { currentHealth -= damageValue; if (currentHealth <= 0) { Destroy(gameObject); } _healthbar.UpdateHealthBar(maxHealth, currentHealth); healthText.text = currentHealth.ToString(); } } #endregion #region Observations for ML public void CollectObservations(VectorSensor sensor) { // Add player position to observations sensor.AddObservation(transform.position); // Get enemy positions from OpponentGenerator var enemyPositions = opponentGenerator.GetEnemyPositions(); // Add enemy positions to observations foreach (var enemyPosition in enemyPositions) { sensor.AddObservation(enemyPosition); } } #endregion #region Utility Functions public void Shoot(float shootingAngle) { // Perform shooting logic based on the shooting angle // … } public void RenderToTexture(RenderTexture renderTexture) { // Render the game view to the specified render texture RenderTexture currentRT = RenderTexture.active; RenderTexture.active = renderTexture; Camera.main.targetTexture = renderTexture; Camera.main.Render(); // Reset the render texture and camera settings Camera.main.targetTexture = null; RenderTexture.active = currentRT; } #endregion // Helper Methods private bool IsPlayerControlled() { return isPlayerControlled; } }
e91861cb24eac0d8dfaa397e0e824835
{ "intermediate": 0.46587318181991577, "beginner": 0.33811110258102417, "expert": 0.19601570069789886 }
8,753
create shared favorite and disfavorite component for each product and use this comp in another component angular
524cbf36c56d51de7c36638cf4810f49
{ "intermediate": 0.41127172112464905, "beginner": 0.21411889791488647, "expert": 0.37460941076278687 }
8,754
Where is issue in this code ? Code : STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC')) frame = frame.iloc[:60,:6] frame.columns = ['Time','Open','High','Low','Close','Volume'] frame = frame.set_index('Time') today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame df = getminutedata('BTCUSDT', '1m', '44640') def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] #Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' #Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' #No clear pattern else: return '' signal = ["" for i in range(len(df))] # initialize signal as a list of empty strings for i in range(1, len(df)): df_temp = df[i-1:i+1] signal[i] = signal_generator(df_temp) df["signal"] = signal def order_execution(symbol, signal, max_trade_quantity_percentage): max_trade_quantity_percentage = 10 buy = signal == "buy" sell = signal == "sell" signal = buy or sell symbol = 'BTCUSDT' account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 POSITION_SIDE_SHORT = SIDE_SELL POSITION_SIDE_LONG = SIDE_BUY long_position = POSITION_SIDE_LONG short_position = POSITION_SIDE_SHORT symbol = 'BTCUSDT' positions = client.futures_position_information(symbol=symbol) order_quantity = 0 # initialize order_quantity with a default value of 0 long_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'LONG'), None) if long_position: # Close long position if signal is opposite if signal == "sell": order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) print(f"Closed long position with order ID {order['orderId']}") time.sleep(1) else: if long_position is not None: order_quantity = min(max_trade_quantity, abs(float(long_position['positionAmt']))) else: print("No long position found") order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT, leverage=leverage ) print(f"Placed short order with order ID {order['orderId']} and quantity {order_quantity})") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 + STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 + TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1) order_quantity = 0 # initialize order_quantity with a default value of 0 short_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'SHORT'), None) if short_position: # Close short position if signal is opposite if signal == "buy": order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) print(f"Closed short position with order ID {order['orderId']}") time.sleep(1) else: if short_position is not None: order_quantity = min(max_trade_quantity, float(short_position['maxNotionalValue']) / leverage) else: print("No short position found") order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG, leverage=leverage ) print(f"Placed long order with order ID {order['orderId']} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 - TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1) while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution(symbol, current_signal,max_trade_quantity_percentage) time.sleep(1) # Add a delay of 1 second
f241c0a00984381fd787e0759c37c5be
{ "intermediate": 0.3648594915866852, "beginner": 0.4715292155742645, "expert": 0.1636112928390503 }
8,755
This is my ide program for a highsum gui game. "import GUIExample.GameTableFrame; import Model.*; import GUIExample.LoginDialog; public class GUIExample { private Dealer dealer; private Player player; private GameTableFrame app; public GUIExample() { } public void run() { dealer.shuffleCards(); app = new GameTableFrame(dealer, player); app.setVisible(true); // Replace app.run(); with this line } public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); GUIExample example = new GUIExample(); example.dealer = new Dealer(); example.player = new Player(login, password, 10000); example.run(); } } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.EventQueue; import javax.swing.*; public class HighSumGUI { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum() { // Override the ‘run’ method to display and update the GameTableFrame @Override public void run() { Dealer dealer = getDealer(); Player player = getPlayer(); GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); gameTableFrame.setVisible(true); // Use a loop to continuously update and start new games as desired by the user boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } gameTableFrame.dispose(); } }; highSum.init(login, password); highSum.run(); } } }); } } package Controller; import Model.Dealer; import Model.Player; import View.ViewController; public class GameController { private Dealer dealer; private Player player; private ViewController view; private int chipsOnTable; private boolean playerQuit; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } public boolean getPlayerQuitStatus() { return playerQuit; } public void run() { boolean carryOn= true; while(carryOn) { runOneRound(); char r = this.view.getPlayerNextGame(); if(r=='n') { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for(int round = 1;round<=4;round++) { this.view.displaySingleLine(); this.view.displayDealerDealCardsAndGameRound(round); this.view.displaySingleLine(); if (round == 1) { //round 1 deal extra card this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } else { this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } this.view.displayPlayerCardsOnHand(this.dealer); this.view.displayBlankLine(); this.view.displayPlayerCardsOnHand(player); this.view.displayPlayerTotalCardValue(player); int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard()); if(whoCanCall==1) {//dealer call int chipsToBet = this.view. getDealerCallBetChips(); //ask player want to follow? char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet); if(r=='y') { this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } }else {//player call if(round==1) {//round 1 player cannot quit int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayBetOntable(this.chipsOnTable); }else { char r = this.view.getPlayerCallOrQuit(); if(r=='c') { int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } } } } //check who win if(playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) { this.view.displayPlayerWin(this.player); this.player.addChips(chipsOnTable); this.chipsOnTable=0; this.view.displayPlayerNameAndLeftOverChips(this.player); }else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) { this.view.displayDealerWin(); this.view.displayPlayerNameAndLeftOverChips(this.player); }else { this.view.displayTie(); this.player.addChips(chipsOnTable/2); this.view.displayPlayerNameAndLeftOverChips(this.player); } //put all the cards back to the deck dealer.addCardsBackToDeck(dealer.getCardsOnHand()); dealer.addCardsBackToDeck(player.getCardsOnHand()); dealer.clearCardsOnHand(); player.clearCardsOnHand(); } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GameTableFrame extends JFrame { private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private JLabel shufflingLabel; private JButton playButton; private JButton quitButton; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer, player); shufflingLabel = new JLabel("Shuffling"); shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER); playButton = new JButton("Play"); quitButton = new JButton("Quit"); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); HighSum highSum = new HighSum(); highSum.init(player.getLoginName(), "some_default_password"); highSum.run(); updateScreen(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Create the main panel that contains both the game board and the buttons JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); mainPanel.add(gameTablePanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); mainPanel.add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); add(mainPanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } // This method updates the screen after each game public void updateScreen() { gameTablePanel.updateTable(dealer, player); } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; public GameTablePanel(Dealer dealer, Player player) { setLayout(new BorderLayout()); setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); this.dealer = dealer; this.player = player; } public void updateTable(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Draw dealer’s cards int dealerX = 50; int dealerY = 100; g.drawString("Dealer", dealerX, dealerY - 20); dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true); // Draw player’s cards int playerX = 50; int playerY = getHeight() - 200; g.drawString("Player", playerX, playerY - 20); playerX = drawPlayerHand(g, player, playerX, playerY, false); // Draw chips on the table g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Chips on the table: ", playerX + 50, playerY); } private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) { int i = 0; for (Card c : p.getCardsOnHand()) { if (isDealer && i == 0) { new ImageIcon("images/back.png").paintIcon(this, g, x, y); } else { c.paintIcon(this, g, x, y); } x += 100; i++; } return x; } } package GUIExample; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginDialog extends JDialog { private JTextField loginField; private JPasswordField passwordField; private JButton loginButton; private boolean loggedIn = false; public LoginDialog(JFrame parent) { super(parent, "Login", true); loginField = new JTextField(20); passwordField = new JPasswordField(20); loginButton = new JButton("Login"); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loggedIn = true; dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2)); panel.add(new JLabel("Login:")); panel.add(loginField); panel.add(new JLabel("Password:")); panel.add(passwordField); panel.add(loginButton); add(panel); pack(); setLocationRelativeTo(parent); } public String getLogin() { return loginField.getText(); } public String getPassword() { return new String(passwordField.getPassword()); } public boolean isLoggedIn() { return loggedIn; } } package Helper; public class Keyboard { public static String readString(String prompt) { System.out.print(prompt); return new java.util.Scanner(System.in).nextLine(); } public static int readInt(String prompt) { int input = 0; boolean valid = false; while (!valid) { try { input = Integer.parseInt(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter an integer ***"); } } return input; } public static double readDouble(String prompt) { double input = 0; boolean valid = false; while (!valid) { try { input = Double.parseDouble(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a double ***"); } } return input; } public static float readFloat(String prompt) { float input = 0; boolean valid = false; while (!valid) { try { input = Float.parseFloat(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a float ***"); } } return input; } public static long readLong(String prompt) { long input = 0; boolean valid = false; while (!valid) { try { input = Long.parseLong(readString(prompt)); valid = true; } catch (NumberFormatException e) { e.printStackTrace(); System.out.println("*** Please enter a long ***"); } } return input; } public static char readChar(String prompt,char[] choices) { boolean validChoice = false; char r = ' '; while(!validChoice) { r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":"); if(!validateChoice(choices,r)) { System.out.println("Invalid input"); }else { validChoice = true; } } return r; } private static String charArrayToString(char[] charArray) { String s = "["; for(int i=0;i<charArray.length;i++) { s+=charArray[i]; if(i!=charArray.length-1) { s+=","; } } s += "]"; return s; } private static boolean validateChoice(char[] choices, char choice) { boolean validChoice = false; for(int i=0;i<choices.length;i++) { if(choices[i]==choice) { validChoice = true; break; } } return validChoice; } public static char readChar(String prompt) { char input = 0; boolean valid = false; while (!valid) { String temp = readString(prompt); if (temp.length() != 1) { System.out.println("*** Please enter a character ***"); } else { input = temp.charAt(0); valid = true; } } return input; } public static boolean readBoolean(String prompt) { boolean valid = false; while (!valid) { String input = readString(prompt); if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true") || input.equalsIgnoreCase("t")) { return true; } else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false") || input.equalsIgnoreCase("f")) { return false; } else { System.out.println("*** Please enter Yes/No or True/False ***"); } } return false; } public static java.util.Date readDate(String prompt) { java.util.Date date = null; boolean valid = false; while (!valid) { try { String input = readString(prompt).trim(); if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) { int day = Integer.parseInt(input.substring(0, 2)); int month = Integer.parseInt(input.substring(3, 5)); int year = Integer.parseInt(input.substring(6, 10)); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setLenient(false); cal.set(year, month - 1, day, 0, 0, 0); date = cal.getTime(); valid = true; } else { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } catch (IllegalArgumentException e) { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } return date; } private static String quit = "0"; public static int getUserOption(String title, String[] menu) { displayMenu(title, menu); int choice = Keyboard.readInt("Enter Choice --> "); while (choice > menu.length || choice < 0) { choice = Keyboard.readInt("Invalid Choice, Re-enter --> "); } return choice; } private static void displayMenu(String title, String[] menu) { line(80, "="); System.out.println(title.toUpperCase()); line(80, "-"); for (int i = 0; i < menu.length; i++) { System.out.println("[" + (i + 1) + "] " + menu[i]); } System.out.println("[" + quit + "] Quit"); line(80, "-"); } public static void line(int len, String c) { System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c)); } } package Helper; import java.security.MessageDigest; public class Utility { public static String getHash(String base) { String message=""; try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append('0'); hexString.append(hex); } message = hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } return message; } public static void printLine(int num) { printLine(num,'-'); } public static void printDoubleLine(int num) { printLine(num,'='); } public static void printLine(int num,char pattern) { for(int i =0;i<num;i++) { System.out.print(pattern); } System.out.println(""); } } package Model; import javax.swing.*; public class Card extends ImageIcon { private String suit; private String name; private int value; private int rank; private boolean faceDown; public Card(String suit, String name, int value, int rank) { super("images/" + suit + name + ".png"); this.suit = suit; this.name = name; this.value = value; this.rank = rank; this.faceDown = false; } public boolean isFaceDown() { return this.faceDown; } public void setFaceDown(boolean faceDown) { this.faceDown = faceDown; } public String getSuit() { return this.suit; } public String getName() { return this.name; } public int getValue() { return this.value; } public int getRank() { return this.rank; } public String toString() { if (this.faceDown) { return "<HIDDEN CARD>"; } else { return "<" + this.suit + " " + this.name + ">"; } } public String display() { return "<"+this.suit+" "+this.name+" "+this.rank+">"; } } //card rank // D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.*; public class Dealer extends Player { private Deck deck; public Dealer() { super("Dealer", "", 0); deck = new Deck(); } public void shuffleCards() { System.out.println("Dealer shuffle deck"); deck.shuffle(); } public void dealCardTo(Player player) { Card card = deck.dealCard(); // take a card out from the deck player.addCard(card); // pass the card into the player } public void addCardsBackToDeck(ArrayList<Card> cards) { deck.appendCard(cards); } //return 1 if card1 rank higher, else return 2 public int determineWhichCardRankHigher(Card card1, Card card2) { if(card1.getRank()>card2.getRank()) { return 1; }else { return 2; } } } package Model; import java.util.*; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = { "Diamond", "Club","Heart","Spade", }; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1,1+i); cards.add(card); int c = 5; for (int n = 2; n <= 10; n++) { Card oCard = new Card(suit, "" + n, n,c+i); cards.add(oCard); c+=4; } Card jackCard = new Card(suit, "Jack", 10,41+i); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10,45+i); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10,49+i); cards.add(kingCard); } } public Card dealCard() { return cards.remove(0); } //add back one card public void appendCard(Card card) { cards.add(card); } //add back arraylist of cards public void appendCard(ArrayList<Card> cards) { for(Card card: cards) { this.cards.add(card); } } public void shuffle() { Random random = new Random(); for(int i=0;i<10000;i++) { int indexA = random.nextInt(cards.size()); int indexB = random.nextInt(cards.size()); Card cardA = cards.get(indexA); Card cardB = cards.get(indexB); cards.set(indexA, cardB); cards.set(indexB, cardA); } } //for internal use only private void showCards() { for (Card card : cards) { System.out.println(card); } } //for internal use only private void displayCards() { for (Card card : cards) { System.out.println(card.display()); } } public static void main(String[] args) { Deck deck = new Deck(); //deck.shuffle(); /*Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); Card card3 = deck.dealCard(); deck.showCards(); ArrayList<Card> cards = new ArrayList<Card>(); cards.add(card1); cards.add(card2); cards.add(card3); deck.appendCard(cards); System.out.println();*/ deck.displayCards(); } } //card rank //D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import Controller.*; import View.*; import GUIExample.LoginDialog; import GUIExample.GameTableFrame; import javax.swing.JOptionPane; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; private int chipsOnTable; public HighSum() { } public void init(String login, String password) { // Create all the required objects this.dealer = new Dealer(); this.player = new Player(login, password, 50); this.view = new ViewController(); // Bring them together this.gc = new GameController(this.dealer, this.player, this.view); } private Player checkWinner() { if(player.getTotalCardsValue() > dealer.getTotalCardsValue()) return player; else if(player.getTotalCardsValue() < dealer.getTotalCardsValue()) return dealer; else return null; } public Dealer getDealer() { return dealer; } public Player getPlayer() { return player; } public void run() { // Setup the game table GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); if (!gc.getPlayerQuitStatus()) { int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } else { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); gameTableFrame.dispose(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for (int round = 1; round <= 4; round++) { // Code remains same until here // Check if the player wants to follow or quit char r; int chipsToBet; if (round == 1) { chipsToBet = this.view.getPlayerCallBetChip(this.player); } else { chipsToBet = this.view.getDealerCallBetChips(); } } Player winner = checkWinner(); if(playerQuit){ this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } } /* public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum(); highSum.init(login, password); highSum.run(); } }*/ } package Model; import java.util.*; public class Player extends User{ private int chips; protected ArrayList<Card> cardsOnHand; public Player(String loginName, String password, int chips) { super(loginName, password); this.chips = chips; this.cardsOnHand = new ArrayList<Card>(); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips+=amount;//no error check } public void deductChips(int amount) { this.chips-=amount;//no error check } public void addCard(Card card) { this.cardsOnHand.add(card); } public ArrayList<Card> getCardsOnHand() { return this.cardsOnHand; } public int getTotalCardsValue() { int total = 0; for(Card card: this.cardsOnHand) { total+=card.getValue(); } return total; } public Card getLastCard() { return this.cardsOnHand.get(this.cardsOnHand.size()-1); } public void clearCardsOnHand() { this.cardsOnHand.clear(); } //Think of the action that a player can take //implement more related methods here public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player("IcePeak","A",100); System.out.println(player.getChips()); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } package Model; import Helper.*; abstract public class User { private String loginName; private String hashPassword; public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return this.loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } } package View; import Helper.*; import Model.*; //all input and output should be done view ViewController //so that it is easier to implement GUI later public class ViewController { public void displayExitGame() { System.out.println("Thank you for playing HighSum game"); } public void displayBetOntable(int bet) { System.out.println("Bet on table : "+bet); } public void displayPlayerWin(Player player) { System.out.println(player.getLoginName()+" Wins!"); } public void displayDealerWin() { System.out.println("Dealer Wins!"); } public void displayTie() { System.out.println("It is a tie!."); } public void displayPlayerQuit() { System.out.println("You have quit the current game."); } public void displayPlayerCardsOnHand(Player player) { System.out.println(player.getLoginName()); if(player instanceof Dealer) { for (int i = 0; i < player.getCardsOnHand().size(); i++) { if (i == 0) { System.out.print("<HIDDEN CARD> "); } else { System.out.print(player.getCardsOnHand().get(i).toString() + " "); } } } else { for (Card card : player.getCardsOnHand()) { System.out.print(card + " "); } } System.out.println(); } public void displayBlankLine() { System.out.println(); } public void displayPlayerTotalCardValue(Player player) { System.out.println("Value:"+player.getTotalCardsValue()); } public void displayDealerDealCardsAndGameRound(int round) { System.out.println("Dealer dealing cards - ROUND "+round); } public void displayGameStart() { System.out.println("Game starts - Dealer shuffle deck"); } public void displayPlayerNameAndChips(Player player) { System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips"); } public void displayPlayerNameAndLeftOverChips(Player player) { System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips"); } public void displayGameTitle() { System.out.println("HighSum GAME"); } public void displaySingleLine() { for(int i=0;i<30;i++) { System.out.print("-"); } System.out.println(); } public void displayDoubleLine() { for(int i=0;i<30;i++) { System.out.print("="); } System.out.println(); } public char getPlayerCallOrQuit() { char[] choices = {'c','q'}; char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices); return r; } public char getPlayerFollowOrNot(Player player, int dealerBet) { boolean validChoice = false; char[] choices = {'y','n'}; char r = 'n'; while(!validChoice) { r = Keyboard.readChar("Do you want to follow?",choices); //check if player has enff chips to follow if(r=='y' && player.getChips()<dealerBet) { System.out.println("You do not have enough chips to follow"); displayPlayerNameAndChips(player); }else { validChoice = true; } } return r; } public char getPlayerNextGame() { char[] choices = {'y','n'}; char r = Keyboard.readChar("Next game?",choices); return r; } public int getPlayerCallBetChip(Player player) { boolean validBetAmount = false; int chipsToBet = 0; while(!validBetAmount) { chipsToBet = Keyboard.readInt("Player call, state bet:"); if(chipsToBet<0) { System.out.println("Chips cannot be negative"); }else if(chipsToBet>player.getChips()) { System.out.println("You do not have enough chips"); }else { validBetAmount = true; } } return chipsToBet; } public int getDealerCallBetChips() { System.out.println("Dealer call, state bet: 10"); return 10; } } " These are the requirements: "On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API "Swing" and "AWT" packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. Error Handling Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips. You should look out for other possible exceptions and handle them too." The highsum code currently when run, shows a black gui pop up that cant be closed. Fix the code so that the program works
8d50e6aa428747ad9142710f93825941
{ "intermediate": 0.2889218032360077, "beginner": 0.6018312573432922, "expert": 0.10924690216779709 }
8,756
solve background fractal isn't being drawn in here properrely.: const canvas = document.getElementById('bgCanvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; const ctx = canvas.getContext('2d'); const con = [ { priority: true, name: 'ब्रह्मा', description: '(Brahma, Hinduism)', color: "#FFD700" }, { priority: true, name: 'יהוה‎', description: '(Yahweh, Judaism)', color: '#292421' }, { priority: true, name: 'الله‎', description: '(Allah, Islam)', color: '#008878' }, { priority: true, name: 'ईश्वर', description: '(Ishvara, Hinduism)', color: '#632c12' }, { priority: true, name: 'オーム', description: '(Aum, Hinduism)', color: '#2E74B5' }, { priority: false, name: '道', description: '(Dao, Taoism)', color: '#5C552E' }, { priority: true, name: 'אֵל‎', description: '(El, Canaanite)', color: '#DAA520' }, { priority: false, name: 'アマテラス', description: '(Amaterasu, Shinto)', color: "#E60026" }, ]; function fractal(x, y, size) { if (size < 1) return; ctx.fillStyle = 'rgba(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ', 0.7)'; ctx.fillRect(x, y, size, size); const newSize = size / 3; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) continue; fractal(x + newSize * i, y + newSize * j, newSize); } } } function createCon() { const circle = document.getElementById('circle'); for (let i = 0, len = con.length; i < len; i++) { let angle = 360 / len; let el = document.createElement('span'); el.innerHTML = '<a href="#" style="color:' + con[i].color + ';">' + con[i].name + '<sub>' + con[i].description + '</sub></a>'; el.style.transform = 'translate(-50%, -50%) rotate(' + (angle * i) + 'deg) translateY(-50%)'; el.style.top = '50%'; el.style.left = '50%'; circle.appendChild(el); } } function init() { createCon(); } init();
1eb1c5ffa88e4e2f063a9802880cbef7
{ "intermediate": 0.3275616765022278, "beginner": 0.44456127285957336, "expert": 0.22787703573703766 }
8,757
Fix errors and inconcistency with this requirement in the part of the minimal viable solution of the problems, written in rust code, using only std and libraries that is explicitly used in code below, pointing in which files which update needed and which new files need to create with which code. /// ../project/src/datacode.rs: use std::collections::{BTreeMap, HashMap, HashSet, BinaryHeap}; use std::cmp::{Ord, Reverse}; use std::fs::File; use std::io::{self, BufRead, BufReader}; use std::vec::Vec; #[derive(Debug)] pub struct MyGlobalStruct<T> { pub hashset: HashSet<T>, // Add other fields as needed } impl<T: Ord> MyGlobalStruct<T> { pub fn new() -> MyGlobalStruct<T> { MyGlobalStruct { hashset: HashSet::new(), // Initialize other fields as needed } } pub fn from_files(file_paths: &[&str]) -> io::Result<MyGlobalStruct<String>> { let mut data = MyGlobalStruct::new(); for path in file_paths { let file = File::open(path)?; let reader = BufReader::new(file); for line in reader.lines() { //let data_row = line?; let data_row = "key\nval\nval".to_string(); // Insert the data row into the hashset println!("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n{:?}\n\n\n\n\n\ndatacode.rs:\n", data_row.clone()); data.hashset.insert(data_row); } } // Return the correctly typed MyGlobalStruct Ok(data) } } /// ../project/src/main.rs: mod datacode; use datacode::MyGlobalStruct; let file_paths = &["../1.txt", "../2.txt", "../3.txt"]; let my_global_struct: MyGlobalStruct<_> = MyGlobalStruct::from_files(file_paths; /* error: src/main.rs:25: mismatched types error: src/main.rs:25: expected struct `MyGlobalStruct`, found enum `Result` error: src/main.rs:25: expected due to this note: src/main.rs:25: expected struct `MyGlobalStruct<_>` found enum `Result<MyGlobalStruct<String>, std::io::Error>` */ println!("{:?}", my_global_struct.hashset); /// ../project/src/subproject/src/lib.rs: mod datacode; use datacode::MyGlobalStruct; /* datacode.rs path is ../project/src/datacode.rs but threr are errors: error: src/subproject/src/lib.rs:9: file not found for module `datacode` help: src/subproject/src/lib.rs:9: to create the module `datacode`, create file "src/subproject/src/datacode.rs" or "src/subproject/src/datacode/mod.rs" error: src/subproject/src/lib.rs:10: unresolved import `datacode::MyGlobalStruct` error: src/subproject/src/lib.rs:10: no `MyGlobalStruct` in `datacode` */
b3ab6a6119d139deefda9b4126bec6ab
{ "intermediate": 0.38653653860092163, "beginner": 0.3207439184188843, "expert": 0.2927195131778717 }
8,758
No, it didn't help. The data is still displayed in the wrong format. The answer is below C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py {'error': 'Failed to find the required elements or error occurred: Message: \nStacktrace:\nBacktrace:\n\tGetHandleVerifier [0x003E8893+48451]\n\t(No symbol) [0x0037B8A1]\n\t(No symbol) [0x00285058]\n\t(No symbol) [0x002B0467]\n\t(No symbol) [0x002B069B]\n\t(No symbol) [0x002DDD92]\n\t(No symbol) [0x002CA304]\ n\t(No symbol) [0x002DC482]\n\t(No symbol) [0x002CA0B6]\n\t(No symbol) [0x002A7E08]\n\t(No symbol) [0x002A8F2D]\n\tGetHandleVerifier [0x00648E3A+ 2540266]\n\tGetHandleVerifier [0x00688959+2801161]\n\tGetHandleVerifier [0x0068295C+2776588]\n\tGetHandleVerifier [0x00472280+612144]\n\t(No symbol) [0x00384F6 C]\n\t(No symbol) [0x003811D8 ]\n\t(No symbol) [0x003812BB]\n\t(No symbol) [0x00374857]\n\tBaseThreadInitThunk [0x76DF00C9+25]\n\tRtlGetAppContainerNamedObjectPath [0x77667B4E+286]\n\tRtlGetAppContainerNamedObjectPath [0x7766 7B1E+238] \n'} Process finished with exit code 0 I repeat again, pay attention to the lines where the search id is located WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "typeahead-input-64326"))) search_box = driver.find_element_by_id("typeahead-input-64326") The data is not registered in the search engine, because this search engine does not see the code. fix it
3e6f889786109c870538ecf44fb829ff
{ "intermediate": 0.7585035562515259, "beginner": 0.12069240212440491, "expert": 0.12080404162406921 }
8,759
объект planeMesh должен находиться в направлении камеры всегда (и при повороте камеры), на определенном расстоянии от нее, сейчас planeMesh находится в одном месте все время и не поворачивается import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; const shaderCode = document.getElementById("fragShader").innerHTML; THREE.ImageUtils.crossOrigin = ''; const texture = new THREE.TextureLoader().load('gradient-2.png'); const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry; const texturePoint = new THREE.TextureLoader().load('texture3.png'); const sizeVariation = 0.001; const geometryPoint = new THREE.BufferGeometry(); const positions = geometry.getAttribute('position').array; const randomSize = []; for (let i = 0; i < positions.length; i += 3) { const startSize = 0.006; const size = startSize + (Math.random() * sizeVariation); randomSize.push(size, size, size); // каждый размер - это три компоненты размера в формате [x, y, z] } // let startSize = 0.06; const materialPoint = new THREE.PointsMaterial({ size: 0.03, sizeAttenuation: true, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. }); const sizes = new Float32Array(randomSize); geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = [...randomPosition]; let increment = 0.002; geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); const points = new THREE.Points(geometryPoint, materialPoint); geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); // animateVerticles(); // function animateVerticles() { // requestAnimationFrame(animateVerticles); // time += 0.1; // sinPosition = Math.sin(time)*0.1; // cosPosition = Math.cos(time*0.1)*0.1; // sinPosition2 = Math.sin(time/Math.PI)*0.1; // for(let i = 0; i<randomPosition.length; i++) { // randomPosition[i] += (sinPosition * cosPosition * sinPosition2) * randSignArray[i] * ratio; // } // geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); // } window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); } }); camera.position.z = 3; // ________________________________________________________________________________________________________________________________________________ // Создаем переменные для точки и радиуса let point = new THREE.Vector3(0, 0, 0); let radius = 1; // Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); } // Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0; // Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); } // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); // scene.add(pointMesh); // ________________________________________________________________________________________________________________________________________________ let uniforms = { mouseCoord: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} }; const planeGeometry = new THREE.PlaneGeometry(1000, 1000); const planeMaterial = new THREE.ShaderMaterial({ uniforms:uniforms, fragmentShader:shaderCode, side: THREE.DoubleSide }); const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); // controls.addEventListener('change', function() { // planeMesh.quaternion.copy(camera.quaternion); // }); let targetX = 0; let targetY = 0; let currentX = 0; let currentY = 0; const wrapperObject = new THREE.Object3D(); // создаем объект-обертку wrapperObject.position.set(0, 0, -10); // устанавливаем нужное расстояние от камеры wrapperObject.add(planeMesh); // добавляем объект внутрь обертки scene.add(wrapperObject); // добавляем обертку в сцену function update() { requestAnimationFrame(update); wrapperObject.lookAt(camera.position); // поворачиваем обертку в направлении камеры const diffX = targetX - currentX; const diffY = targetY - currentY; const distance = Math.sqrt(diffX * diffX + diffY * diffY); const speed = distance / 10; if (distance < 1.0) { currentX = targetX; currentY = targetY; } else { currentX += speed * diffX / distance; currentY += speed * diffY / distance; } } update(); document.addEventListener('mousemove', (event) => { targetX = event.clientX; targetY = event.clientY; uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; }); function animate() { requestAnimationFrame(animate); animatePoint(); controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate(); }); // // добавляем слушатель на controls // controls.addEventListener('change', function() { // planeMeshGradient.position.copy(camera.position); // planeMeshGradient.quaternion.copy(camera.quaternion); // });
0de8cd37d976016eb423911f440df698
{ "intermediate": 0.29066821932792664, "beginner": 0.48071688413619995, "expert": 0.2286148965358734 }
8,760
[void@VoidPC SF Mono Nerd]$ ls 'SFMono Bold Italic Nerd Font Complete.otf' 'SFMono Medium Nerd Font Complete.otf' 'SFMono Bold Nerd Font Complete.otf' 'SF Mono Nerd Licence' 'SFMono Heavy Italic Nerd Font Complete.otf' 'SFMono Regular Italic Nerd Font Complete.otf' 'SFMono Heavy Nerd Font Complete.otf' 'SFMono Regular Nerd Font Complete.otf' 'SFMono Light Italic Nerd Font Complete.otf' 'SFMono Semibold Italic Nerd Font Complete.otf' 'SFMono Light Nerd Font Complete.otf' 'SFMono Semibold Nerd Font Complete.otf' 'SFMono Medium Italic Nerd Font Complete.otf' how to install it
1e4912f96a09294ff8f0d0558e44dad4
{ "intermediate": 0.410677045583725, "beginner": 0.27992716431617737, "expert": 0.30939576029777527 }
8,761
write a code in java using itext5 to compare two pdf files and write the changes in new pdf showing the changes done according like if file 2 has more pages it should show with the changes because lines are more which can show that it is not available in file 2 compare images also
6af59c19802bc341b0581ff0f11ac6f0
{ "intermediate": 0.5862573385238647, "beginner": 0.11863386631011963, "expert": 0.29510873556137085 }
8,762
write java script when i click in img go to another page and send data
19b084de2015afab7c109a219d59551c
{ "intermediate": 0.5467038154602051, "beginner": 0.1873139590024948, "expert": 0.26598218083381653 }
8,763
This is my ide program for a highsum gui game. “import GUIExample.GameTableFrame; import Model.; import GUIExample.LoginDialog; public class GUIExample { private Dealer dealer; private Player player; private GameTableFrame app; public GUIExample() { } public void run() { dealer.shuffleCards(); app = new GameTableFrame(dealer, player); app.setVisible(true); // Replace app.run(); with this line } public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); GUIExample example = new GUIExample(); example.dealer = new Dealer(); example.player = new Player(login, password, 10000); example.run(); } } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.EventQueue; import javax.swing.; public class HighSumGUI { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum() { // Override the ‘run’ method to display and update the GameTableFrame @Override public void run() { Dealer dealer = getDealer(); Player player = getPlayer(); GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); gameTableFrame.setVisible(true); // Use a loop to continuously update and start new games as desired by the user boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); int response = JOptionPane.showConfirmDialog( gameTableFrame, “Do you want to play another game?”, “New Game”, JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } gameTableFrame.dispose(); } }; highSum.init(login, password); highSum.run(); } } }); } } package Controller; import Model.Dealer; import Model.Player; import View.ViewController; public class GameController { private Dealer dealer; private Player player; private ViewController view; private int chipsOnTable; private boolean playerQuit; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } public boolean getPlayerQuitStatus() { return playerQuit; } public void run() { boolean carryOn= true; while(carryOn) { runOneRound(); char r = this.view.getPlayerNextGame(); if(r==‘n’) { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for(int round = 1;round<=4;round++) { this.view.displaySingleLine(); this.view.displayDealerDealCardsAndGameRound(round); this.view.displaySingleLine(); if (round == 1) { //round 1 deal extra card this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } else { this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } this.view.displayPlayerCardsOnHand(this.dealer); this.view.displayBlankLine(); this.view.displayPlayerCardsOnHand(player); this.view.displayPlayerTotalCardValue(player); int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard()); if(whoCanCall==1) {//dealer call int chipsToBet = this.view. getDealerCallBetChips(); //ask player want to follow? char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet); if(r==‘y’) { this.player.deductChips(chipsToBet); this.chipsOnTable+=2chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } }else {//player call if(round==1) {//round 1 player cannot quit int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2chipsToBet; this.view.displayBetOntable(this.chipsOnTable); }else { char r = this.view.getPlayerCallOrQuit(); if(r==‘c’) { int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } } } } //check who win if(playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) { this.view.displayPlayerWin(this.player); this.player.addChips(chipsOnTable); this.chipsOnTable=0; this.view.displayPlayerNameAndLeftOverChips(this.player); }else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) { this.view.displayDealerWin(); this.view.displayPlayerNameAndLeftOverChips(this.player); }else { this.view.displayTie(); this.player.addChips(chipsOnTable/2); this.view.displayPlayerNameAndLeftOverChips(this.player); } //put all the cards back to the deck dealer.addCardsBackToDeck(dealer.getCardsOnHand()); dealer.addCardsBackToDeck(player.getCardsOnHand()); dealer.clearCardsOnHand(); player.clearCardsOnHand(); } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.BorderLayout; import javax.swing.; import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GameTableFrame extends JFrame { private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private JLabel shufflingLabel; private JButton playButton; private JButton quitButton; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer, player); shufflingLabel = new JLabel(“Shuffling”); shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER); playButton = new JButton(“Play”); quitButton = new JButton(“Quit”); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); HighSum highSum = new HighSum(); highSum.init(player.getLoginName(), “some_default_password”); highSum.run(); updateScreen(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Create the main panel that contains both the game board and the buttons JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); mainPanel.add(gameTablePanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); mainPanel.add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); add(mainPanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } // This method updates the screen after each game public void updateScreen() { gameTablePanel.updateTable(dealer, player); } } package GUIExample; import java.awt.; import javax.swing.; import Model.; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; public GameTablePanel(Dealer dealer, Player player) { setLayout(new BorderLayout()); setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); this.dealer = dealer; this.player = player; } public void updateTable(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Draw dealer’s cards int dealerX = 50; int dealerY = 100; g.drawString(“Dealer”, dealerX, dealerY - 20); dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true); // Draw player’s cards int playerX = 50; int playerY = getHeight() - 200; g.drawString(“Player”, playerX, playerY - 20); playerX = drawPlayerHand(g, player, playerX, playerY, false); // Draw chips on the table g.setColor(Color.BLACK); g.setFont(new Font(“Arial”, Font.PLAIN, 18)); g.drawString("Chips on the table: ", playerX + 50, playerY); } private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) { int i = 0; for (Card c : p.getCardsOnHand()) { if (isDealer && i == 0) { new ImageIcon(“images/back.png”).paintIcon(this, g, x, y); } else { c.paintIcon(this, g, x, y); } x += 100; i++; } return x; } } package GUIExample; import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginDialog extends JDialog { private JTextField loginField; private JPasswordField passwordField; private JButton loginButton; private boolean loggedIn = false; public LoginDialog(JFrame parent) { super(parent, “Login”, true); loginField = new JTextField(20); passwordField = new JPasswordField(20); loginButton = new JButton(“Login”); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loggedIn = true; dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2)); panel.add(new JLabel(“Login:”)); panel.add(loginField); panel.add(new JLabel(“Password:”)); panel.add(passwordField); panel.add(loginButton); add(panel); pack(); setLocationRelativeTo(parent); } public String getLogin() { return loginField.getText(); } public String getPassword() { return new String(passwordField.getPassword()); } public boolean isLoggedIn() { return loggedIn; } } package Helper; public class Keyboard { public static String readString(String prompt) { System.out.print(prompt); return new java.util.Scanner(System.in).nextLine(); } public static int readInt(String prompt) { int input = 0; boolean valid = false; while (!valid) { try { input = Integer.parseInt(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("** Please enter an integer “); } } return input; } public static double readDouble(String prompt) { double input = 0; boolean valid = false; while (!valid) { try { input = Double.parseDouble(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println(” Please enter a double “); } } return input; } public static float readFloat(String prompt) { float input = 0; boolean valid = false; while (!valid) { try { input = Float.parseFloat(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println(” Please enter a float “); } } return input; } public static long readLong(String prompt) { long input = 0; boolean valid = false; while (!valid) { try { input = Long.parseLong(readString(prompt)); valid = true; } catch (NumberFormatException e) { e.printStackTrace(); System.out.println(” Please enter a long “); } } return input; } public static char readChar(String prompt,char[] choices) { boolean validChoice = false; char r = ’ '; while(!validChoice) { r = Keyboard.readChar(prompt+” “+charArrayToString(choices)+”:“); if(!validateChoice(choices,r)) { System.out.println(“Invalid input”); }else { validChoice = true; } } return r; } private static String charArrayToString(char[] charArray) { String s = “[”; for(int i=0;i<charArray.length;i++) { s+=charArray[i]; if(i!=charArray.length-1) { s+=”,“; } } s += “]”; return s; } private static boolean validateChoice(char[] choices, char choice) { boolean validChoice = false; for(int i=0;i<choices.length;i++) { if(choices[i]==choice) { validChoice = true; break; } } return validChoice; } public static char readChar(String prompt) { char input = 0; boolean valid = false; while (!valid) { String temp = readString(prompt); if (temp.length() != 1) { System.out.println(” Please enter a character “); } else { input = temp.charAt(0); valid = true; } } return input; } public static boolean readBoolean(String prompt) { boolean valid = false; while (!valid) { String input = readString(prompt); if (input.equalsIgnoreCase(“yes”) || input.equalsIgnoreCase(“y”) || input.equalsIgnoreCase(“true”) || input.equalsIgnoreCase(“t”)) { return true; } else if (input.equalsIgnoreCase(“no”) || input.equalsIgnoreCase(“n”) || input.equalsIgnoreCase(“false”) || input.equalsIgnoreCase(“f”)) { return false; } else { System.out.println(” Please enter Yes/No or True/False “); } } return false; } public static java.util.Date readDate(String prompt) { java.util.Date date = null; boolean valid = false; while (!valid) { try { String input = readString(prompt).trim(); if (input.matches(”\d\d/\d\d/\d\d\d\d")) { int day = Integer.parseInt(input.substring(0, 2)); int month = Integer.parseInt(input.substring(3, 5)); int year = Integer.parseInt(input.substring(6, 10)); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setLenient(false); cal.set(year, month - 1, day, 0, 0, 0); date = cal.getTime(); valid = true; } else { System.out.println(" Please enter a date (DD/MM/YYYY) “); } } catch (IllegalArgumentException e) { System.out.println(” Please enter a date (DD/MM/YYYY) “); } } return date; } private static String quit = “0”; public static int getUserOption(String title, String[] menu) { displayMenu(title, menu); int choice = Keyboard.readInt(“Enter Choice --> “); while (choice > menu.length || choice < 0) { choice = Keyboard.readInt(“Invalid Choice, Re-enter --> “); } return choice; } private static void displayMenu(String title, String[] menu) { line(80, “=”); System.out.println(title.toUpperCase()); line(80, “-”); for (int i = 0; i < menu.length; i++) { System.out.println(”[” + (i + 1) + “] " + menu[i]); } System.out.println(”[” + quit + “] Quit”); line(80, “-”); } public static void line(int len, String c) { System.out.println(String.format(”%” + len + “s”, " “).replaceAll(” “, c)); } } package Helper; import java.security.MessageDigest; public class Utility { public static String getHash(String base) { String message=”“; try{ MessageDigest digest = MessageDigest.getInstance(“SHA-256”); byte[] hash = digest.digest(base.getBytes(“UTF-8”)); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append(‘0’); hexString.append(hex); } message = hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } return message; } public static void printLine(int num) { printLine(num,‘-’); } public static void printDoubleLine(int num) { printLine(num,‘=’); } public static void printLine(int num,char pattern) { for(int i =0;i<num;i++) { System.out.print(pattern); } System.out.println(”"); } } package Model; import javax.swing.; public class Card extends ImageIcon { private String suit; private String name; private int value; private int rank; private boolean faceDown; public Card(String suit, String name, int value, int rank) { super(“images/” + suit + name + “.png”); this.suit = suit; this.name = name; this.value = value; this.rank = rank; this.faceDown = false; } public boolean isFaceDown() { return this.faceDown; } public void setFaceDown(boolean faceDown) { this.faceDown = faceDown; } public String getSuit() { return this.suit; } public String getName() { return this.name; } public int getValue() { return this.value; } public int getRank() { return this.rank; } public String toString() { if (this.faceDown) { return “<HIDDEN CARD>”; } else { return “<” + this.suit + " " + this.name + “>”; } } public String display() { return “<”+this.suit+" “+this.name+” “+this.rank+”>"; } } //card rank // D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.; public class Dealer extends Player { private Deck deck; public Dealer() { super(“Dealer”, “”, 0); deck = new Deck(); } public void shuffleCards() { System.out.println(“Dealer shuffle deck”); deck.shuffle(); } public void dealCardTo(Player player) { Card card = deck.dealCard(); // take a card out from the deck player.addCard(card); // pass the card into the player } public void addCardsBackToDeck(ArrayList<Card> cards) { deck.appendCard(cards); } //return 1 if card1 rank higher, else return 2 public int determineWhichCardRankHigher(Card card1, Card card2) { if(card1.getRank()>card2.getRank()) { return 1; }else { return 2; } } } package Model; import java.util.; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = { “Diamond”, “Club”,“Heart”,“Spade”, }; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, “Ace”, 1,1+i); cards.add(card); int c = 5; for (int n = 2; n <= 10; n++) { Card oCard = new Card(suit, “” + n, n,c+i); cards.add(oCard); c+=4; } Card jackCard = new Card(suit, “Jack”, 10,41+i); cards.add(jackCard); Card queenCard = new Card(suit, “Queen”, 10,45+i); cards.add(queenCard); Card kingCard = new Card(suit, “King”, 10,49+i); cards.add(kingCard); } } public Card dealCard() { return cards.remove(0); } //add back one card public void appendCard(Card card) { cards.add(card); } //add back arraylist of cards public void appendCard(ArrayList<Card> cards) { for(Card card: cards) { this.cards.add(card); } } public void shuffle() { Random random = new Random(); for(int i=0;i<10000;i++) { int indexA = random.nextInt(cards.size()); int indexB = random.nextInt(cards.size()); Card cardA = cards.get(indexA); Card cardB = cards.get(indexB); cards.set(indexA, cardB); cards.set(indexB, cardA); } } //for internal use only private void showCards() { for (Card card : cards) { System.out.println(card); } } //for internal use only private void displayCards() { for (Card card : cards) { System.out.println(card.display()); } } public static void main(String[] args) { Deck deck = new Deck(); //deck.shuffle(); /Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); Card card3 = deck.dealCard(); deck.showCards(); ArrayList<Card> cards = new ArrayList<Card>(); cards.add(card1); cards.add(card2); cards.add(card3); deck.appendCard(cards); System.out.println();/ deck.displayCards(); } } //card rank //D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import Controller.; import View.; import GUIExample.LoginDialog; import GUIExample.GameTableFrame; import javax.swing.JOptionPane; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; private int chipsOnTable; public HighSum() { } public void init(String login, String password) { // Create all the required objects this.dealer = new Dealer(); this.player = new Player(login, password, 50); this.view = new ViewController(); // Bring them together this.gc = new GameController(this.dealer, this.player, this.view); } private Player checkWinner() { if(player.getTotalCardsValue() > dealer.getTotalCardsValue()) return player; else if(player.getTotalCardsValue() < dealer.getTotalCardsValue()) return dealer; else return null; } public Dealer getDealer() { return dealer; } public Player getPlayer() { return player; } public void run() { // Setup the game table GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); if (!gc.getPlayerQuitStatus()) { int response = JOptionPane.showConfirmDialog( gameTableFrame, “Do you want to play another game?”, “New Game”, JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } else { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); gameTableFrame.dispose(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for (int round = 1; round <= 4; round++) { // Code remains same until here // Check if the player wants to follow or quit char r; int chipsToBet; if (round == 1) { chipsToBet = this.view.getPlayerCallBetChip(this.player); } else { chipsToBet = this.view.getDealerCallBetChips(); } } Player winner = checkWinner(); if(playerQuit){ this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } } /* public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum(); highSum.init(login, password); highSum.run(); } }/ } package Model; import java.util.; public class Player extends User{ private int chips; protected ArrayList<Card> cardsOnHand; public Player(String loginName, String password, int chips) { super(loginName, password); this.chips = chips; this.cardsOnHand = new ArrayList<Card>(); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips+=amount;//no error check } public void deductChips(int amount) { this.chips-=amount;//no error check } public void addCard(Card card) { this.cardsOnHand.add(card); } public ArrayList<Card> getCardsOnHand() { return this.cardsOnHand; } public int getTotalCardsValue() { int total = 0; for(Card card: this.cardsOnHand) { total+=card.getValue(); } return total; } public Card getLastCard() { return this.cardsOnHand.get(this.cardsOnHand.size()-1); } public void clearCardsOnHand() { this.cardsOnHand.clear(); } //Think of the action that a player can take //implement more related methods here public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player(“IcePeak”,“A”,100); System.out.println(player.getChips()); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } package Model; import Helper.; abstract public class User { private String loginName; private String hashPassword; public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return this.loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } } package View; import Helper.; import Model.*; //all input and output should be done view ViewController //so that it is easier to implement GUI later public class ViewController { public void displayExitGame() { System.out.println(“Thank you for playing HighSum game”); } public void displayBetOntable(int bet) { System.out.println(“Bet on table : “+bet); } public void displayPlayerWin(Player player) { System.out.println(player.getLoginName()+” Wins!”); } public void displayDealerWin() { System.out.println(“Dealer Wins!”); } public void displayTie() { System.out.println(“It is a tie!.”); } public void displayPlayerQuit() { System.out.println(“You have quit the current game.”); } public void displayPlayerCardsOnHand(Player player) { System.out.println(player.getLoginName()); if(player instanceof Dealer) { for (int i = 0; i < player.getCardsOnHand().size(); i++) { if (i == 0) { System.out.print(”<HIDDEN CARD> “); } else { System.out.print(player.getCardsOnHand().get(i).toString() + " “); } } } else { for (Card card : player.getCardsOnHand()) { System.out.print(card + " “); } } System.out.println(); } public void displayBlankLine() { System.out.println(); } public void displayPlayerTotalCardValue(Player player) { System.out.println(“Value:”+player.getTotalCardsValue()); } public void displayDealerDealCardsAndGameRound(int round) { System.out.println(“Dealer dealing cards - ROUND “+round); } public void displayGameStart() { System.out.println(“Game starts - Dealer shuffle deck”); } public void displayPlayerNameAndChips(Player player) { System.out.println(player.getLoginName()+”, You have “+player.getChips()+” chips”); } public void displayPlayerNameAndLeftOverChips(Player player) { System.out.println(player.getLoginName()+”, You are left with “+player.getChips()+” chips”); } public void displayGameTitle() { System.out.println(“HighSum GAME”); } public void displaySingleLine() { for(int i=0;i<30;i++) { System.out.print(”-“); } System.out.println(); } public void displayDoubleLine() { for(int i=0;i<30;i++) { System.out.print(”=“); } System.out.println(); } public char getPlayerCallOrQuit() { char[] choices = {‘c’,‘q’}; char r = Keyboard.readChar(“Do you want to [c]all or [q]uit?:”,choices); return r; } public char getPlayerFollowOrNot(Player player, int dealerBet) { boolean validChoice = false; char[] choices = {‘y’,‘n’}; char r = ‘n’; while(!validChoice) { r = Keyboard.readChar(“Do you want to follow?”,choices); //check if player has enff chips to follow if(r==‘y’ && player.getChips()<dealerBet) { System.out.println(“You do not have enough chips to follow”); displayPlayerNameAndChips(player); }else { validChoice = true; } } return r; } public char getPlayerNextGame() { char[] choices = {‘y’,‘n’}; char r = Keyboard.readChar(“Next game?”,choices); return r; } public int getPlayerCallBetChip(Player player) { boolean validBetAmount = false; int chipsToBet = 0; while(!validBetAmount) { chipsToBet = Keyboard.readInt(“Player call, state bet:”); if(chipsToBet<0) { System.out.println(“Chips cannot be negative”); }else if(chipsToBet>player.getChips()) { System.out.println(“You do not have enough chips”); }else { validBetAmount = true; } } return chipsToBet; } public int getDealerCallBetChips() { System.out.println(“Dealer call, state bet: 10”); return 10; } } ” These are the requirements: “On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API “Swing” and “AWT” packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application “HighSum” done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. Error Handling Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips. You should look out for other possible exceptions and handle them too.” The highsum code currently when run, shows a blank gui pop up that cant be closed. Fix the code so that the program works
cf3dae8bcf1a745954ee558deb37043f
{ "intermediate": 0.26561790704727173, "beginner": 0.5972771644592285, "expert": 0.13710498809814453 }
8,764
project ├── src │ ├── datacode.rs │ └── main.rs ├── Cargo.toml └── subproject ├── src │ ├── main.rs │ └── lib.rs └── Cargo.toml /// ../project/src/subproject/src/lib.rs: mod datacode; use datacode::MyGlobalStruct; /* datacode.rs path is ../project/src/datacode.rs and there are errors: error: src/subproject/src/lib.rs:9: file not found for module `datacode` help: src/subproject/src/lib.rs:9: to create the module `datacode`, create file "src/subproject/src/datacode.rs" or "src/subproject/src/datacode/mod.rs" error: src/subproject/src/lib.rs:10: unresolved import `datacode::MyGlobalStruct` error: src/subproject/src/lib.rs:10: no `MyGlobalStruct` in `datacode` */ But how can I access MyGlobalStruct initialized in …/project/src/main.rs and implemented in …/project/src/datacode.rs in here …/project/src/subproject/src/lib.rs ?
d004764b8e76726dbc485079fef6c777
{ "intermediate": 0.5970199704170227, "beginner": 0.15312188863754272, "expert": 0.24985818564891815 }
8,765
This is my ide program for a highsum gui game. "import GUIExample.GameTableFrame; import Model.*; import GUIExample.LoginDialog; public class GUIExample { private Dealer dealer; private Player player; private GameTableFrame app; public GUIExample() { } public void run() { dealer.shuffleCards(); app = new GameTableFrame(dealer, player); app.setVisible(true); // Replace app.run(); with this line } public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); GUIExample example = new GUIExample(); example.dealer = new Dealer(); example.player = new Player(login, password, 10000); example.run(); } } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class HighSumGUI { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum() { // Override the ‘run’ method to display and update the GameTableFrame @Override public void run() { Dealer dealer = getDealer(); Player player = getPlayer(); GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); gameTableFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Use a loop to continuously update and start new games as desired by the user boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); if (response == JOptionPane.YES_OPTION) { dealer.clearCardsOnHand(); player.clearCardsOnHand(); } else { carryOn = false; gameTableFrame.dispose(); } } } }; highSum.init(login, password); highSum.run(); } } }); } } package Controller; import Model.Dealer; import Model.Player; import View.ViewController; public class GameController { private Dealer dealer; private Player player; private ViewController view; private int chipsOnTable; private boolean playerQuit; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } public boolean getPlayerQuitStatus() { return playerQuit; } public void run() { boolean carryOn= true; while(carryOn) { runOneRound(); char r = this.view.getPlayerNextGame(); if(r=='n') { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for(int round = 1;round<=4;round++) { this.view.displaySingleLine(); this.view.displayDealerDealCardsAndGameRound(round); this.view.displaySingleLine(); if (round == 1) { //round 1 deal extra card this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } else { this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } this.view.displayPlayerCardsOnHand(this.dealer); this.view.displayBlankLine(); this.view.displayPlayerCardsOnHand(player); this.view.displayPlayerTotalCardValue(player); int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard()); if(whoCanCall==1) {//dealer call int chipsToBet = this.view. getDealerCallBetChips(); //ask player want to follow? char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet); if(r=='y') { this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } }else {//player call if(round==1) {//round 1 player cannot quit int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayBetOntable(this.chipsOnTable); }else { char r = this.view.getPlayerCallOrQuit(); if(r=='c') { int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2*chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } } } } //check who win if(playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) { this.view.displayPlayerWin(this.player); this.player.addChips(chipsOnTable); this.chipsOnTable=0; this.view.displayPlayerNameAndLeftOverChips(this.player); }else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) { this.view.displayDealerWin(); this.view.displayPlayerNameAndLeftOverChips(this.player); }else { this.view.displayTie(); this.player.addChips(chipsOnTable/2); this.view.displayPlayerNameAndLeftOverChips(this.player); } //put all the cards back to the deck dealer.addCardsBackToDeck(dealer.getCardsOnHand()); dealer.addCardsBackToDeck(player.getCardsOnHand()); dealer.clearCardsOnHand(); player.clearCardsOnHand(); } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.BorderLayout; import javax.swing.*; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GameTableFrame extends JFrame { private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private JLabel shufflingLabel; private JButton playButton; private JButton quitButton; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer, player); shufflingLabel = new JLabel("Shuffling"); shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER); playButton = new JButton("Play"); quitButton = new JButton("Quit"); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); HighSum highSum = new HighSum(); highSum.init(player.getLoginName(), "some_default_password"); highSum.run(); updateScreen(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Create the main panel that contains both the game board and the buttons JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); mainPanel.add(gameTablePanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); mainPanel.add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); add(mainPanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } // This method updates the screen after each game public void updateScreen() { gameTablePanel.updateTable(dealer, player); } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; public GameTablePanel(Dealer dealer, Player player) { setLayout(new BorderLayout()); setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); this.dealer = dealer; this.player = player; } public void updateTable(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Draw dealer’s cards int dealerX = 50; int dealerY = 100; g.drawString("Dealer", dealerX, dealerY - 20); dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true); // Draw player’s cards int playerX = 50; int playerY = getHeight() - 200; g.drawString("Player", playerX, playerY - 20); playerX = drawPlayerHand(g, player, playerX, playerY, false); // Draw chips on the table g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Chips on the table: ", playerX + 50, playerY); } private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) { int i = 0; for (Card c : p.getCardsOnHand()) { if (isDealer && i == 0) { new ImageIcon("images/back.png").paintIcon(this, g, x, y); } else { c.paintIcon(this, g, x, y); } x += 100; i++; } return x; } } package GUIExample; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginDialog extends JDialog { private JTextField loginField; private JPasswordField passwordField; private JButton loginButton; private boolean loggedIn = false; public LoginDialog(JFrame parent) { super(parent, "Login", true); loginField = new JTextField(20); passwordField = new JPasswordField(20); loginButton = new JButton("Login"); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loggedIn = true; dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2)); panel.add(new JLabel("Login:")); panel.add(loginField); panel.add(new JLabel("Password:")); panel.add(passwordField); panel.add(loginButton); add(panel); pack(); setLocationRelativeTo(parent); } public String getLogin() { return loginField.getText(); } public String getPassword() { return new String(passwordField.getPassword()); } public boolean isLoggedIn() { return loggedIn; } } package Helper; public class Keyboard { public static String readString(String prompt) { System.out.print(prompt); return new java.util.Scanner(System.in).nextLine(); } public static int readInt(String prompt) { int input = 0; boolean valid = false; while (!valid) { try { input = Integer.parseInt(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter an integer ***"); } } return input; } public static double readDouble(String prompt) { double input = 0; boolean valid = false; while (!valid) { try { input = Double.parseDouble(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a double ***"); } } return input; } public static float readFloat(String prompt) { float input = 0; boolean valid = false; while (!valid) { try { input = Float.parseFloat(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("*** Please enter a float ***"); } } return input; } public static long readLong(String prompt) { long input = 0; boolean valid = false; while (!valid) { try { input = Long.parseLong(readString(prompt)); valid = true; } catch (NumberFormatException e) { e.printStackTrace(); System.out.println("*** Please enter a long ***"); } } return input; } public static char readChar(String prompt,char[] choices) { boolean validChoice = false; char r = ' '; while(!validChoice) { r = Keyboard.readChar(prompt+" "+charArrayToString(choices)+":"); if(!validateChoice(choices,r)) { System.out.println("Invalid input"); }else { validChoice = true; } } return r; } private static String charArrayToString(char[] charArray) { String s = "["; for(int i=0;i<charArray.length;i++) { s+=charArray[i]; if(i!=charArray.length-1) { s+=","; } } s += "]"; return s; } private static boolean validateChoice(char[] choices, char choice) { boolean validChoice = false; for(int i=0;i<choices.length;i++) { if(choices[i]==choice) { validChoice = true; break; } } return validChoice; } public static char readChar(String prompt) { char input = 0; boolean valid = false; while (!valid) { String temp = readString(prompt); if (temp.length() != 1) { System.out.println("*** Please enter a character ***"); } else { input = temp.charAt(0); valid = true; } } return input; } public static boolean readBoolean(String prompt) { boolean valid = false; while (!valid) { String input = readString(prompt); if (input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("y") || input.equalsIgnoreCase("true") || input.equalsIgnoreCase("t")) { return true; } else if (input.equalsIgnoreCase("no") || input.equalsIgnoreCase("n") || input.equalsIgnoreCase("false") || input.equalsIgnoreCase("f")) { return false; } else { System.out.println("*** Please enter Yes/No or True/False ***"); } } return false; } public static java.util.Date readDate(String prompt) { java.util.Date date = null; boolean valid = false; while (!valid) { try { String input = readString(prompt).trim(); if (input.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d")) { int day = Integer.parseInt(input.substring(0, 2)); int month = Integer.parseInt(input.substring(3, 5)); int year = Integer.parseInt(input.substring(6, 10)); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setLenient(false); cal.set(year, month - 1, day, 0, 0, 0); date = cal.getTime(); valid = true; } else { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } catch (IllegalArgumentException e) { System.out.println("*** Please enter a date (DD/MM/YYYY) ***"); } } return date; } private static String quit = "0"; public static int getUserOption(String title, String[] menu) { displayMenu(title, menu); int choice = Keyboard.readInt("Enter Choice --> "); while (choice > menu.length || choice < 0) { choice = Keyboard.readInt("Invalid Choice, Re-enter --> "); } return choice; } private static void displayMenu(String title, String[] menu) { line(80, "="); System.out.println(title.toUpperCase()); line(80, "-"); for (int i = 0; i < menu.length; i++) { System.out.println("[" + (i + 1) + "] " + menu[i]); } System.out.println("[" + quit + "] Quit"); line(80, "-"); } public static void line(int len, String c) { System.out.println(String.format("%" + len + "s", " ").replaceAll(" ", c)); } } package Helper; import java.security.MessageDigest; public class Utility { public static String getHash(String base) { String message=""; try{ MessageDigest digest = MessageDigest.getInstance("SHA-256"); byte[] hash = digest.digest(base.getBytes("UTF-8")); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append('0'); hexString.append(hex); } message = hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } return message; } public static void printLine(int num) { printLine(num,'-'); } public static void printDoubleLine(int num) { printLine(num,'='); } public static void printLine(int num,char pattern) { for(int i =0;i<num;i++) { System.out.print(pattern); } System.out.println(""); } } package Model; import javax.swing.*; public class Card extends ImageIcon { private String suit; private String name; private int value; private int rank; private boolean faceDown; public Card(String suit, String name, int value, int rank) { super("images/" + suit + name + ".png"); this.suit = suit; this.name = name; this.value = value; this.rank = rank; this.faceDown = false; } public boolean isFaceDown() { return this.faceDown; } public void setFaceDown(boolean faceDown) { this.faceDown = faceDown; } public String getSuit() { return this.suit; } public String getName() { return this.name; } public int getValue() { return this.value; } public int getRank() { return this.rank; } public String toString() { if (this.faceDown) { return "<HIDDEN CARD>"; } else { return "<" + this.suit + " " + this.name + ">"; } } public String display() { return "<"+this.suit+" "+this.name+" "+this.rank+">"; } } //card rank // D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.*; public class Dealer extends Player { private Deck deck; public Dealer() { super("Dealer", "", 0); deck = new Deck(); } public void shuffleCards() { System.out.println("Dealer shuffle deck"); deck.shuffle(); } public void dealCardTo(Player player) { Card card = deck.dealCard(); // take a card out from the deck player.addCard(card); // pass the card into the player } public void addCardsBackToDeck(ArrayList<Card> cards) { deck.appendCard(cards); } //return 1 if card1 rank higher, else return 2 public int determineWhichCardRankHigher(Card card1, Card card2) { if(card1.getRank()>card2.getRank()) { return 1; }else { return 2; } } } package Model; import java.util.*; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = { "Diamond", "Club","Heart","Spade", }; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, "Ace", 1,1+i); cards.add(card); int c = 5; for (int n = 2; n <= 10; n++) { Card oCard = new Card(suit, "" + n, n,c+i); cards.add(oCard); c+=4; } Card jackCard = new Card(suit, "Jack", 10,41+i); cards.add(jackCard); Card queenCard = new Card(suit, "Queen", 10,45+i); cards.add(queenCard); Card kingCard = new Card(suit, "King", 10,49+i); cards.add(kingCard); } } public Card dealCard() { return cards.remove(0); } //add back one card public void appendCard(Card card) { cards.add(card); } //add back arraylist of cards public void appendCard(ArrayList<Card> cards) { for(Card card: cards) { this.cards.add(card); } } public void shuffle() { Random random = new Random(); for(int i=0;i<10000;i++) { int indexA = random.nextInt(cards.size()); int indexB = random.nextInt(cards.size()); Card cardA = cards.get(indexA); Card cardB = cards.get(indexB); cards.set(indexA, cardB); cards.set(indexB, cardA); } } //for internal use only private void showCards() { for (Card card : cards) { System.out.println(card); } } //for internal use only private void displayCards() { for (Card card : cards) { System.out.println(card.display()); } } public static void main(String[] args) { Deck deck = new Deck(); //deck.shuffle(); /*Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); Card card3 = deck.dealCard(); deck.showCards(); ArrayList<Card> cards = new ArrayList<Card>(); cards.add(card1); cards.add(card2); cards.add(card3); deck.appendCard(cards); System.out.println();*/ deck.displayCards(); } } //card rank //D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import Controller.*; import View.*; import GUIExample.LoginDialog; import GUIExample.GameTableFrame; import javax.swing.JOptionPane; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; private int chipsOnTable; public HighSum() { } public void init(String login, String password) { // Create all the required objects this.dealer = new Dealer(); this.player = new Player(login, password, 50); this.view = new ViewController(); // Bring them together this.gc = new GameController(this.dealer, this.player, this.view); } private Player checkWinner() { if(player.getTotalCardsValue() > dealer.getTotalCardsValue()) return player; else if(player.getTotalCardsValue() < dealer.getTotalCardsValue()) return dealer; else return null; } public Dealer getDealer() { return dealer; } public Player getPlayer() { return player; } public void run() { // Setup the game table GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); if (!gc.getPlayerQuitStatus()) { int response = JOptionPane.showConfirmDialog( gameTableFrame, "Do you want to play another game?", "New Game", JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } else { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); gameTableFrame.dispose(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for (int round = 1; round <= 4; round++) { // Code remains same until here // Check if the player wants to follow or quit char r; int chipsToBet; if (round == 1) { chipsToBet = this.view.getPlayerCallBetChip(this.player); } else { chipsToBet = this.view.getDealerCallBetChips(); } } Player winner = checkWinner(); if(playerQuit){ this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } } /* public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum(); highSum.init(login, password); highSum.run(); } }*/ } package Model; import java.util.*; public class Player extends User{ private int chips; protected ArrayList<Card> cardsOnHand; public Player(String loginName, String password, int chips) { super(loginName, password); this.chips = chips; this.cardsOnHand = new ArrayList<Card>(); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips+=amount;//no error check } public void deductChips(int amount) { this.chips-=amount;//no error check } public void addCard(Card card) { this.cardsOnHand.add(card); } public ArrayList<Card> getCardsOnHand() { return this.cardsOnHand; } public int getTotalCardsValue() { int total = 0; for(Card card: this.cardsOnHand) { total+=card.getValue(); } return total; } public Card getLastCard() { return this.cardsOnHand.get(this.cardsOnHand.size()-1); } public void clearCardsOnHand() { this.cardsOnHand.clear(); } //Think of the action that a player can take //implement more related methods here public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player("IcePeak","A",100); System.out.println(player.getChips()); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } package Model; import Helper.*; abstract public class User { private String loginName; private String hashPassword; public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return this.loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } } package View; import Helper.*; import Model.*; //all input and output should be done view ViewController //so that it is easier to implement GUI later public class ViewController { public void displayExitGame() { System.out.println("Thank you for playing HighSum game"); } public void displayBetOntable(int bet) { System.out.println("Bet on table : "+bet); } public void displayPlayerWin(Player player) { System.out.println(player.getLoginName()+" Wins!"); } public void displayDealerWin() { System.out.println("Dealer Wins!"); } public void displayTie() { System.out.println("It is a tie!."); } public void displayPlayerQuit() { System.out.println("You have quit the current game."); } public void displayPlayerCardsOnHand(Player player) { System.out.println(player.getLoginName()); if(player instanceof Dealer) { for (int i = 0; i < player.getCardsOnHand().size(); i++) { if (i == 0) { System.out.print("<HIDDEN CARD> "); } else { System.out.print(player.getCardsOnHand().get(i).toString() + " "); } } } else { for (Card card : player.getCardsOnHand()) { System.out.print(card + " "); } } System.out.println(); } public void displayBlankLine() { System.out.println(); } public void displayPlayerTotalCardValue(Player player) { System.out.println("Value:"+player.getTotalCardsValue()); } public void displayDealerDealCardsAndGameRound(int round) { System.out.println("Dealer dealing cards - ROUND "+round); } public void displayGameStart() { System.out.println("Game starts - Dealer shuffle deck"); } public void displayPlayerNameAndChips(Player player) { System.out.println(player.getLoginName()+", You have "+player.getChips()+" chips"); } public void displayPlayerNameAndLeftOverChips(Player player) { System.out.println(player.getLoginName()+", You are left with "+player.getChips()+" chips"); } public void displayGameTitle() { System.out.println("HighSum GAME"); } public void displaySingleLine() { for(int i=0;i<30;i++) { System.out.print("-"); } System.out.println(); } public void displayDoubleLine() { for(int i=0;i<30;i++) { System.out.print("="); } System.out.println(); } public char getPlayerCallOrQuit() { char[] choices = {'c','q'}; char r = Keyboard.readChar("Do you want to [c]all or [q]uit?:",choices); return r; } public char getPlayerFollowOrNot(Player player, int dealerBet) { boolean validChoice = false; char[] choices = {'y','n'}; char r = 'n'; while(!validChoice) { r = Keyboard.readChar("Do you want to follow?",choices); //check if player has enff chips to follow if(r=='y' && player.getChips()<dealerBet) { System.out.println("You do not have enough chips to follow"); displayPlayerNameAndChips(player); }else { validChoice = true; } } return r; } public char getPlayerNextGame() { char[] choices = {'y','n'}; char r = Keyboard.readChar("Next game?",choices); return r; } public int getPlayerCallBetChip(Player player) { boolean validBetAmount = false; int chipsToBet = 0; while(!validBetAmount) { chipsToBet = Keyboard.readInt("Player call, state bet:"); if(chipsToBet<0) { System.out.println("Chips cannot be negative"); }else if(chipsToBet>player.getChips()) { System.out.println("You do not have enough chips"); }else { validBetAmount = true; } } return chipsToBet; } public int getDealerCallBetChips() { System.out.println("Dealer call, state bet: 10"); return 10; } } " These are the requirements: "On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API "Swing" and "AWT" packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application "HighSum" done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. Error Handling Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips. You should look out for other possible exceptions and handle them too." Edit the code so that when highsum gui is run, The game runs on the GUI and NOT on the console. The gui currently is empty and blank and cannot be closed when run.
5085250f7984fd56cca916de6afb5faf
{ "intermediate": 0.355657160282135, "beginner": 0.49876484274864197, "expert": 0.14557798206806183 }
8,766
write me java script when i click in img to to page and send data
70d850688d3e29c45c925937c697c2db
{ "intermediate": 0.6179645657539368, "beginner": 0.1732250601053238, "expert": 0.20881035923957825 }
8,767
This code takes ages to complete. Can it be made faster and more efficient: Sub CheckServiceI() Application.ScreenUpdating = False Application.EnableEvents = False 'Declare variables Dim wsStartPage As Worksheet Dim wsNamedPage As Worksheet Dim lastRow As Long Dim i As Long Dim j As Long Dim iColumnI As Long Dim strWorksheetName As String 'Set variables Set wsStartPage = ThisWorkbook.Sheets("Start Page") 'Find the column with the name "I" iColumnI = wsStartPage.Columns("I").Find(What:="I", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Column 'Loop through the rows in column B of the named worksheet For i = 5 To 34 'If the cell value in column I is not blank, get the worksheet name If wsStartPage.Cells(i, iColumnI).Value <> "" Then strWorksheetName = wsStartPage.Cells(i, iColumnI).Value 'Check if the worksheet exists If WorksheetExists(strWorksheetName) Then Set wsNamedPage = Sheets(strWorksheetName) 'Get the last row in column B of the named worksheet Dim iLastRow As Long iLastRow = wsNamedPage.Columns("B").Rows.count 'Loop through the rows in column B of the named worksheet For j = iLastRow To 5 Step -1 'If the value "Service" is found in column B, get the value from column H If LCase(Trim(wsNamedPage.Range("B" & j).Value)) = "service" Then wsStartPage.Range("J" & i).Value = wsNamedPage.Range("H" & j).Value2 GoTo NextSheet End If Next j 'If the value "Service" is not found, set the value in column J to "NA" wsStartPage.Range("J" & i).Value = "NA" 'Go to the next worksheet NextSheet: End If End If Next i Application.ScreenUpdating = True Application.EnableEvents = True End Sub Function WorksheetExists(shtName As String) As Boolean Dim sht As Worksheet On Error Resume Next Set sht = ThisWorkbook.Worksheets(shtName) On Error GoTo 0 WorksheetExists = Not sht Is Nothing End Function
c56e614963a9211597fd317ec5063c60
{ "intermediate": 0.3723512291908264, "beginner": 0.4342498183250427, "expert": 0.19339895248413086 }
8,768
so, what do we have here?: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ultimate Supreme God con</title> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@400;700&display=swap" rel="stylesheet"> <style> body { font-family: 'Noto Sans Devanagari', sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; overflow: hidden; background-color: #000; } #bgCanvas { position: absolute; width: 100%; height: 100%; } .circle-container { position: relative; width: 500px; height: 500px; margin: 0 auto; z-index: 1; } .circle-container span { display: block; position: absolute; text-align: right; line-height: 0; } .circle-container span:before { content: ''; display: inline-block; vertical-align: middle; width: 4px; height: 4px; margin-left: 10px; background: currentColor; border-radius: 100%; margin-right: 3px; } .circle-container span a { display: inline-block; text-decoration: none; color: inherit; } .circle-container span a sub { font-size: 0.5rem; } .clock { animation: rotate 120s infinite linear; } @keyframes rotate { 0% { transform: rotate(0)scale(3);} 100% { transform: rotate(360deg)scale(3);} } </style> </head> <body> <canvas id="bgCanvas"></canvas> <div class="circle-container clock" id="circle"> </div> <script> const canvas = document.getElementById('bgCanvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; const ctx = canvas.getContext('2d'); const con = [ { priority: true, name: 'ब्रह्मा', description: '(Brahma, Hinduism)', color: '#FFD700' }, { priority: false, name: 'יהוה‎', description: '(Yahweh, Judaism)', color: '#292421' }, { priority: true, name: 'الله‎', description: '(Allah, Islam)', color: '#008878' }, { priority: false, name: 'ईश्वर', description: '(Ishvara, Hinduism)', color: '#632c12' }, { priority: true, name: 'オーム', description: '(Aum, Hinduism)', color: '#2E74B5' }, { priority: false, name: '道', description: '(Dao, Taoism)', color: '#5C552E' }, { priority: true, name: 'אֵל‎', description: '(El, Canaanite)', color: '#DAA520' }, { priority: false, name: 'アマテラス', description: '(Amaterasu, Shinto)', color: '#E60026' }, ]; function fractal(x, y, size) { if (size < 0.5) return; ctx.fillStyle = 'rgba(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ', 1)'; ctx.fillRect(x, y, size, size); const newSize = size / 3; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) continue; fractal(x + newSize * i, y + newSize * j, newSize); } } } function createCon() { const circle = document.getElementById('circle'); for (let i = 0, len = con.length; i < len; i++) { let angle = 360 / len; let el = document.createElement('span'); el.innerHTML = '<a href="#" style="color:' + con[i].color + ';">' + con[i].name + '<sub>' + con[i].description + '</sub></a>'; el.style.transform = 'translate(-50%, -50%) rotate(' + (angle * i) + 'deg) translateY(-50%)'; el.style.top = '50%'; el.style.left = '50%'; circle.appendChild(el); } } function drawFractal() { const size = Math.min(canvas.width, canvas.height) / 0.3; const x = (canvas.width - size) / 2; const y = (canvas.height - size) / 2; fractal(x, y, size); } function init() { createCon(); drawFractal(); } window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; drawFractal(); }); init(); </script> </body> </html>
59b508318416b7dec6e359452189d2e1
{ "intermediate": 0.41728946566581726, "beginner": 0.38043347001075745, "expert": 0.20227712392807007 }
8,769
i have ShootingAgent.cs for ml-agents. this script is on EmptyObject named "ShootingAgent", which child of "Player". i need to learn ai to fire bullets. as observation space it will be "Main Camera" which is also child of "Player". here's bad and broken shootingagent, make it awesome: using UnityEngine; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; public class ShootingAgent : Agent { public int observationResolution = 10; // The desired low-resolution observation space size public PlayerController playerController; private Texture2D observationTexture; public override void OnEpisodeBegin() { // Reset the player and environment for a new episode // ... } public override void CollectObservations(VectorSensor sensor) { // Capture the game view and convert it to low-resolution observation RenderTexture renderTexture = RenderTexture.GetTemporary(observationResolution, observationResolution); playerController.RenderToTexture(renderTexture); RenderTexture.active = renderTexture; observationTexture = new Texture2D(observationResolution, observationResolution, TextureFormat.RGB24, false); observationTexture.ReadPixels(new Rect(0, 0, observationResolution, observationResolution), 0, 0); observationTexture.Apply(); Color[] pixels = observationTexture.GetPixels(); for (int i = 0; i < pixels.Length; i++) { sensor.AddObservation(pixels[i].r); sensor.AddObservation(pixels[i].g); sensor.AddObservation(pixels[i].b); } RenderTexture.active = null; RenderTexture.ReleaseTemporary(renderTexture); } public override void OnActionReceived(ActionBuffers actions) { // Get the joystick control values from the agent's actions //float horizontal = actions.ContinuousActionsArray[0]; //float vertical = actions.ContinuousActionsArray[1]; // Use the joystick control values to control the game //playerController.ControlJoystick(horizontal, vertical); // Set a reward based on the game state // ... } public float[] GetAction() { // Logic to retrieve the action values // Return an array of float values representing the actions return new float[2]; // Replace with the actual implementation } } here's PlayerController.cs: using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using Unity.MLAgents; using Unity.MLAgents.Sensors; using Unity.MLAgents.Actuators; using UnityEditor.U2D; public enum CharacterGroup { Player, Ally, Enemy } public enum ControlMode { Mouse, Joystick, AI } public class PlayerController : MonoBehaviour { #region Public Variables public CharacterGroup group; public ShootingAgent shootingAgent; public OpponentGenerator opponentGenerator; public VariableJoystick variableJoystick; public ControlMode currentControlMode = ControlMode.Mouse; // Default control mode is mouse public GameObject bulletPrefab; public string nickname = "lovekpek"; public string brawlerName = "Nita"; public int maxHealth = 3000; // Add a new variable for maximum health public int damage = 750; // Add a new variable for damage public bool damagePiercing = true; public float movementSpeed = 5f; public float aimingDistance = 5f; public float bulletSpeed = 10f; public int maxBullets = 3; public float reloadTime = 2f; public float shotDelay = 0.5f; // Delay between consecutive shots public float bulletWidth = 0.1f; // Bullet width [SerializeField] private HealthBar _healthbar; public Text healthText; // Reference to the UI text component for health display [SerializeField] private BulletBar _bulletbar; public Text bulletsText; public int currentHealth = 3000; public int currentBullets = 3; public Text speedText; #endregion #region Private Variables private GameObject sightLine; private bool isAiming; private bool canShoot = true; // Flag to allow shooting private Vector2 aimDirection; private Vector2 lineEndPosition; private float currentDistance; private float reloadTimer; private float shotTimer; // Timer for shot delay private bool hasFiredRecently; // New flag private Vector2 movementInput; private float currentSpeed; private bool isPlayerControlled = false; private Collider2D lastCollision; // Class-level variable to store the last collision // Joystick control variables private float horizontalInput; private float verticalInput; #endregion #region Unity Callbacks private void Start() { InitializePlayer(); } private void Update() { if (IsPlayerControlled()) { HandleAimingAndShooting(); HandleReloading(); HandlePlayerMovement(); UpdateUIElements(); } } private void OnTriggerEnter2D(Collider2D collision) { ProcessCollision(collision); } #endregion #region Initialization private void InitializePlayer() { currentBullets = maxBullets; UpdateBulletsText(); switch (group) { case CharacterGroup.Player: isPlayerControlled = true; break; case CharacterGroup.Ally: break; case CharacterGroup.Enemy: break; } } #endregion #region Movement and Aiming private void HandlePlayerMovement() { movementInput.x = Input.GetAxisRaw("Horizontal"); movementInput.y = Input.GetAxisRaw("Vertical"); movementInput.Normalize(); currentSpeed = movementSpeed * movementInput.magnitude; Vector3 movement = new Vector3(movementInput.x, movementInput.y, 0f) * currentSpeed * Time.deltaTime; transform.position += movement; } private void HandleAimingAndShooting() { switch (currentControlMode) { case ControlMode.Mouse: MouseControlLogic(); break; case ControlMode.Joystick: JoystickControlLogic(); break; case ControlMode.AI: AIControlLogic(); break; } if (isAiming) { UpdateSightLine(); } if (!canShoot) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; } } if (!canShoot && hasFiredRecently) { shotTimer -= Time.deltaTime; if (shotTimer <= 0f) { canShoot = true; hasFiredRecently = false; } } } private void MouseControlLogic() { if (Input.GetMouseButtonDown(0)) { StartAiming(); } else if (Input.GetMouseButtonUp(0)) { StopAiming(); } } private void JoystickControlLogic() { if (Mathf.Abs(variableJoystick.Horizontal) > 0.1f || Mathf.Abs(variableJoystick.Vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } private void AIControlLogic() { if (shootingAgent != null) { // Get the joystick control values from the ML agent float horizontal = 0f; float vertical = 0f; // Retrieve the joystick control values from the ML agent var behaviorParameters = shootingAgent.GetComponent<Unity.MLAgents.Policies.BehaviorParameters>(); if (behaviorParameters != null) { var actions = shootingAgent.GetStoredActionBuffers().ContinuousActions; if (actions.Length > 0) horizontal = actions[0]; if (actions.Length > 1) vertical = actions[1]; } // Check if the joystick control values exceed the threshold if (Mathf.Abs(horizontal) > 0.1f || Mathf.Abs(vertical) > 0.1f) { if (!isAiming) { StartAiming(); } } else { if (isAiming) { StopAiming(); } } } } private void StartAiming() { isAiming = true; // Destroy any existing SightLine object if (sightLine != null) Destroy(sightLine); // Create and initialize sight line CreateSightLine(); currentDistance = aimingDistance; } private void StopAiming() { isAiming = false; Destroy(sightLine); if (canShoot && currentBullets > 0) { if (shotTimer <= 0f) // Check if shot delay has elapsed { FireBullet(); currentBullets--; UpdateBulletsText(); canShoot = false; // Set canShoot to false shotTimer = shotDelay; // Reset shot delay timer } } } private void CreateSightLine() { sightLine = new GameObject("SightLine"); LineRenderer lineRenderer = sightLine.AddComponent<LineRenderer>(); lineRenderer.positionCount = 2; lineRenderer.startWidth = bulletWidth; lineRenderer.endWidth = bulletWidth; // Create a new material and set its color to white Material lineMaterial = new Material(Shader.Find("Sprites/Default")); lineMaterial.color = Color.white; lineRenderer.material = lineMaterial; // Assign the material to the line renderer lineRenderer.sortingLayerName = "Background"; // Set the sorting layer lineRenderer.sortingOrder = -1; // Set the sorting order to render behind the player lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, transform.position); } private void UpdateSightLine() { switch (currentControlMode) { case ControlMode.Mouse: Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition); aimDirection = (mousePosition - (Vector2)transform.position).normalized; break; case ControlMode.Joystick: aimDirection = new Vector2(variableJoystick.Horizontal, variableJoystick.Vertical).normalized; break; default: aimDirection = Vector2.zero; break; } lineEndPosition = (Vector2)transform.position + aimDirection * currentDistance; LineRenderer lineRenderer = sightLine.GetComponent<LineRenderer>(); lineRenderer.SetPosition(0, transform.position); lineRenderer.SetPosition(1, lineEndPosition); } #endregion #region Reloading private void HandleReloading() { if (currentBullets < maxBullets) { reloadTimer += Time.deltaTime; if (reloadTimer >= reloadTime) { reloadTimer = 0f; currentBullets++; UpdateBulletsText(); } } else if (!isAiming && sightLine != null) { Destroy(sightLine); } } #endregion #region Shooting public void FireBullet() { GameObject bullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity); BulletController bulletController = bullet.GetComponent<BulletController>(); bulletController.SetDirection(aimDirection); bulletController.SetSpeed(bulletSpeed); bulletController.SetMaxDistance(currentDistance); bulletController.SetGroup(group); bulletController.SetDamage(damage); bulletController.SetDamagePiercing(damagePiercing); } #endregion #region UI Updates private void UpdateUIElements() { healthText.text = currentHealth.ToString(); _healthbar.UpdateHealthBar(maxHealth, currentHealth); UpdateBulletsText(); } private void UpdateBulletsText() { bulletsText.text = currentBullets.ToString(); _bulletbar.UpdateHealthBar(maxBullets, currentBullets); } #endregion #region Collision Handling private void ProcessCollision(Collider2D collision) { if (group.Equals(CharacterGroup.Player) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Ally)) { // Ignore bullets from allies damaging the player return; } else if (group.Equals(CharacterGroup.Ally) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Ignore bullets from the player damaging allies return; } else if (group.Equals(CharacterGroup.Enemy) && collision.CompareTag("Bullet") && collision.GetComponent<BulletController>().group.Equals(CharacterGroup.Player)) { // Damage the enemy when hit by a player’s bullet int bulletDamage = collision.GetComponent<BulletController>().GetDamage(); bool bulletDamagePiercing = collision.GetComponent<BulletController>().GetDamagePiercing(); TakeDamage(bulletDamage); if (bulletDamagePiercing == false) { Destroy(collision.gameObject); } return; } } private void TakeDamage(int damageValue) { if (group == CharacterGroup.Enemy) { currentHealth -= damageValue; if (currentHealth <= 0) { Destroy(gameObject); } _healthbar.UpdateHealthBar(maxHealth, currentHealth); healthText.text = currentHealth.ToString(); } } #endregion #region Observations for ML public void CollectObservations(VectorSensor sensor) { // Add player position to observations sensor.AddObservation(transform.position); // Get enemy positions from OpponentGenerator var enemyPositions = opponentGenerator.GetEnemyPositions(); // Add enemy positions to observations foreach (var enemyPosition in enemyPositions) { sensor.AddObservation(enemyPosition); } } #endregion #region Utility Functions public void Shoot(float shootingAngle) { // Perform shooting logic based on the shooting angle // … } public void RenderToTexture(RenderTexture renderTexture) { // Render the game view to the specified render texture RenderTexture currentRT = RenderTexture.active; RenderTexture.active = renderTexture; Camera.main.targetTexture = renderTexture; Camera.main.Render(); // Reset the render texture and camera settings Camera.main.targetTexture = null; RenderTexture.active = currentRT; } #endregion // Helper Methods private bool IsPlayerControlled() { return isPlayerControlled; } }
c82ec877a83ca0b6753601bdbd511b6e
{ "intermediate": 0.3281572759151459, "beginner": 0.5039102435112, "expert": 0.16793249547481537 }
8,770
don’t touch original priority value function! it’s strongly respective function to the god’s colorometrical order in paradox what was the first chicken or egg paradox. why earliest last, if they are suppose to be more important than latests? I mean z-index value based on actual timeline, and… maybe some actual clock? because they are shown as a spinning clock arrows right now.what if we arrange them by some specific timelines? so, what do we have here?: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ultimate Supreme God con</title> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Devanagari:wght@400;700&display=swap" rel="stylesheet"> <style> body { font-family: 'Noto Sans Devanagari', sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; overflow: hidden; background-color: #000; } #bgCanvas { position: absolute; width: 100%; height: 100%; } .circle-container { position: relative; width: 500px; height: 500px; margin: 0 auto; z-index: 1; } .circle-container span { display: block; position: absolute; text-align: right; line-height: 0; } .circle-container span:before { content: ''; display: inline-block; vertical-align: middle; width: 4px; height: 4px; margin-left: 10px; background: currentColor; border-radius: 100%; margin-right: 3px; } .circle-container span a { display: inline-block; text-decoration: none; color: inherit; } .circle-container span a sub { font-size: 0.5rem; } .clock { animation: rotate 120s infinite linear; } @keyframes rotate { 0% { transform: rotate(0)scale(3);} 100% { transform: rotate(360deg)scale(3);} } </style> </head> <body> <canvas id="bgCanvas"></canvas> <div class="circle-container clock" id="circle"> </div> <script> const canvas = document.getElementById('bgCanvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; const ctx = canvas.getContext('2d'); const con = [ { priority: true, name: 'ब्रह्मा', description: '(Brahma, Hinduism)', color: '#FFD700' }, { priority: true, name: 'יהוה‎', description: '(Yahweh, Judaism)', color: '#292421' }, { priority: true, name: 'الله‎', description: '(Allah, Islam)', color: '#008878' }, { priority: true, name: 'ईश्वर', description: '(Ishvara, Hinduism)', color: '#632c12' }, { priority: true, name: 'オーム', description: '(Aum, Hinduism)', color: '#2E74B5' }, { priority: false, name: '道', description: '(Dao, Taoism)', color: '#5C552E' }, { priority: true, name: 'אֵל‎', description: '(El, Canaanite)', color: '#DAA520' }, { priority: false, name: 'アマテラス', description: '(Amaterasu, Shinto)', color: '#E60026' }, ]; function fractal(x, y, size) { if (size < 0.5) return; ctx.fillStyle = 'rgba(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ', 1)'; ctx.fillRect(x, y, size, size); const newSize = size / 3; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) continue; fractal(x + newSize * i, y + newSize * j, newSize); } } } function createCon() { const circle = document.getElementById('circle'); for (let i = 0, len = con.length; i < len; i++) { let angle = 360 / len; let el = document.createElement('span'); el.innerHTML = '<a href="#" style="color:' + con[i].color + ';">' + con[i].name + '<sub>' + con[i].description + '</sub></a>'; el.style.transform = 'translate(-50%, -50%) rotate(' + (angle * i) + 'deg) translateY(-50%)'; el.style.top = '50%'; el.style.left = '50%'; circle.appendChild(el); } } function drawFractal() { const size = Math.min(canvas.width, canvas.height) / 0.3; const x = (canvas.width - size) / 2; const y = (canvas.height - size) / 2; fractal(x, y, size); } function init() { createCon(); drawFractal(); } window.addEventListener('resize', () => { canvas.width = window.innerWidth; canvas.height = window.innerHeight; drawFractal(); }); init(); </script> </body> </html>
82ad031de9e790f6874fac97a958bd12
{ "intermediate": 0.46451759338378906, "beginner": 0.31975308060646057, "expert": 0.21572932600975037 }
8,771
selenium driver click on css selector //p[normalize-space()='Social Media Growth Hacker']
cdbe8aa20fcb4371ff9b379cd1857af1
{ "intermediate": 0.3476868271827698, "beginner": 0.3422563076019287, "expert": 0.3100568950176239 }
8,772
#include <iostream> #include <thread> #include <deque> #include <functional> #include <future> #include <mutex> #include <condition_variable> #include <vector> #include <memory> class ZYLThreadPool { public: ZYLThreadPool(size_t maxThreads = 200): _maxThreads(maxThreads), _stop(false) { worker_threads.reserve(_maxThreads); for(size_t i = 0; i < _maxThreads; ++i) { worker_threads.emplace_back([this] { for(;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->_mutex); this->_condVar.wait(lock, [this] { return this->_stop || !this->_taskQueue.empty(); }); if(this->_stop && this->_taskQueue.empty()) return; task = std::move(this->_taskQueue.front()); this->_taskQueue.pop_front(); } task(); } }); } } template<typename F, typename… Args> std::future<typename std::result_of<F(Args…)>::type> submit(F&& f, Args&&… args) { typedef typename std::result_of<F(Args…)>::type return_type; auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)…)); std::future<return_type> result = task->get_future(); { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { throw std::runtime_error(“Submit on stopped ZYLThreadPool”); } _taskQueue.emplace_back([task] { (*task)(); }); } _condVar.notify_one(); return result; } void cancel() { std::unique_lock<std::mutex> lock(_mutex); if (!_stop) { _stop = true; _condVar.notify_all(); } for(std::thread &worker: worker_threads) worker.join(); } size_t getNumTasks() { std::unique_lock<std::mutex> lock(_mutex); return _taskQueue.size(); } ~ZYLThreadPool() { cancel(); } private: std::vector<std::thread> worker_threads; std::deque<std::function<void()>> _taskQueue; size_t _maxThreads; std::mutex _mutex; std::condition_variable _condVar; bool _stop; }; class Test { public: Test(double devid): _devid(devid), _running(true) { } void start(ZYLThreadPool &threadPool) { _future = threadPool.submit(&Test::_task, this); } void stop() { { std::unique_lock<std::mutex> lock(_mutex); _running = false; if (_future.valid()) { _future.get(); lock.unlock(); _cleanupResources(); } } } private: std::mutex _mutex; double _devid; std::deque<double> _dequeue_packets; std::future<void> _future; bool _running; void _cleanupResources() { std::unique_lock<std::mutex> lock(_mutex); _dequeue_packets.clear(); } void _task() { std::unique_lock<std::mutex> lock(_mutex); while(_running && !_dequeue_packets.empty()) { double packet = _dequeue_packets.front(); _dequeue_packets.pop_front(); lock.unlock(); // 对 packet 进行处理… lock.lock(); } } }; int main() { ZYLThreadPool zylThreadPool(200); std::shared_ptr<Test> test = std::make_shared<Test>(1.0); test->start(zylThreadPool); std::this_thread::sleep_for(std::chrono::seconds(1)); test->stop(); return 0; } 代码在linux环境下有报错,error: extended character … is not valid in an identifier 34 | template<typename F, typename… Args> 请修复
5e4eefb4d9159c00f9b676b31841e8f5
{ "intermediate": 0.3811416029930115, "beginner": 0.4613514840602875, "expert": 0.15750691294670105 }
8,773
hi
83092468772d1837db8fd0d0c358d957
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
8,774
const Intervals = (str, val) => { // console.log("匹配 =number:", str.match(/^=(\d+)$/)); // console.log("匹配 [number,number]:", str.match(/^\[(\d+),(\d+)\]$/)); // console.log("匹配 [number:", str.match(/^\[(\d+)$/)); // console.log("匹配 number]:", str.match(/^(\d+)\]$/)); // console.log("匹配 [number,number):", str.match(/^\[(\d+),(\d+)\)$/)); // console.log("匹配 (number,number]:", str.match(/^\((\d+),(\d+)\]$/)); // console.log("匹配 (number:", str.match(/^\((\d+)$/)); // console.log("匹配 number):", str.match(/^(\d+)\)$/)); let result; switch (str) { /** =number */ case str.match(/^=(\d+)$/)?.input: // console.log("匹配 =number:", str.match(/^=(\d+)$/)); result = val == str.match(/^=(\d+)$/)[1]; break; /** [number,number] */ case str.match(/^\[(\d+),(\d+)\]$/)?.input: // console.log("匹配 [number,number]:", str.match(/^\[(\d+),(\d+)\]$/)); result = val >= str.match(/^\[(\d+),(\d+)\]$/)[1] && val <= str.match(/^\[(\d+),(\d+)\]$/)[2]; break; /** [number */ case str.match(/^\[(\d+)$/)?.input: // console.log("匹配 [number:", str.match(/^\[(\d+)$/)); result = val >= str.match(/^\[(\d+)$/)[1]; break; /** number] */ case str.match(/^(\d+)\]$/)?.input: // console.log("匹配 number]:", str.match(/^(\d+)\]$/)); result = val < str.match(/^(\d+)\]$/)[1]; break; /** [number,number) */ case str.match(/^\[(\d+),(\d+)\)$/)?.input: // console.log("匹配 [number,number):", str.match(/^\[(\d+),(\d+)\)$/)); result = val >= str.match(/^\[(\d+),(\d+)\)$/)[1] && val < str.match(/^\[(\d+),(\d+)\)$/)[2]; break; /** (number,number] */ case str.match(/^\((\d+),(\d+)\]$/)?.input: // console.log("匹配 [number,number):", str.match(/^\((\d+),(\d+)\]$/)); result = val > str.match(/^\((\d+),(\d+)\]$/)[1] && val <= str.match(/^\((\d+),(\d+)\]$/)[2]; break; /** (number */ case str.match(/^\((\d+)$/)?.input: // console.log("匹配 [number:", str.match(/^\((\d+)$/)); result = val > str.match(/^\((\d+)$/)[1]; break; /** number) */ case str.match(/^(\d+)\)$/)?.input: // console.log("匹配 number]:", str.match(/^(\d+)\)$/)); result = val < str.match(/^(\d+)\)$/)[1]; break; default: break; } return result; }; Help me optimize
cb3b30877ba4dc6a99ceded8b0a111dd
{ "intermediate": 0.3012852370738983, "beginner": 0.47157856822013855, "expert": 0.22713622450828552 }
8,775
I have this Julia simulation: @with_kw mutable struct BikeTrip origin::Int destination::Int trip_time::Int end @with_kw mutable struct BikeSimulation bike_stations::Array{Int, 1} station_capacity::Int trip_distributions::Array{Array{Int, 2}, 1} event_queue::Vector{Tuple{Int, String, Tuple{Int, Int}}} = [] log::DataFrame = DataFrame() end function start_trip!(sim::BikeSimulation, time_origin::Tuple{Int, Int}) global event_id time, origin = time_origin trip_distribution = sim.trip_distributions[origin] destination = sample(trip_distribution[:, 2], Weights(trip_distribution[:, 1])) trip_time = sample(trip_distribution[:, 3], Weights(trip_distribution[:, 1])) sim.bike_stations[origin] -= 1 push!(sim.event_queue, (time + trip_time, "end_trip!", (time + trip_time, destination))) sort!(sim.event_queue) event_id += 1 end function run_simulation!(sim::BikeSimulation, num_bikes::Int, max_time::Int) for station in 1:length(sim.bike_stations) for _ in 1:min(num_bikes, sim.station_capacity) start_trip!(sim, (0, station)) end end while !isempty(sim.event_queue) && sim.event_queue[1][1] <= max_time event = popfirst!(sim.event_queue) time, event_name, data = event if event_name == "end_trip!" end_trip!(sim, data) end append!(sim.log, DataFrame(time=time, event=event_name, bike_status=sim.bike_stations)) end end event_id=1 function end_trip!(sim::BikeSimulation, time_destination::Tuple{Int, Int}) time, destination = time_destination sim.bike_stations[destination] += 1 if sim.bike_stations[destination] < sim.station_capacity start_trip!(sim, (time, destination)) end end trip_distributions = [ [1 2 10; 2 3 1; 3 4 2; 4 5 4; 5 1 3], [1 3 5; 2 4 6; 3 5 9; 4 1 2; 5 2 3], [1 4 4; 2 5 7; 3 1 8; 4 2 12; 5 3 9], [1 5 9; 2 1 3; 3 2 4; 4 3 8; 5 4 6], [1 1 6; 2 2 4; 3 3 6; 4 4 7; 5 5 7] ] bike_simulation = BikeSimulation(bike_stations=[20, 20, 20, 20, 20], station_capacity=40, trip_distributions=trip_distributions) run_simulation!(bike_simulation, 10, 100) # Runs the simulation for a maximum of 100 time units println(bike_simulation.log) The problem is that it was supposed to measure movements between bike stations. I need to know : how many bikes are at each moment of time at the station, whether there was reported a demand for bike but no bike at station, whether bikes at station exceeeded station capacity.
d73e78878c81ff464232c232bda4ac2d
{ "intermediate": 0.3353668749332428, "beginner": 0.31965118646621704, "expert": 0.34498196840286255 }
8,776
Use a pretrained deep learning model for object detection (ex: Yolo or MobileNet SSD) to detect moving object in a video. • Implement a tracking algorithm (ex: DeepSort, Opencv tracking algorithms) to track multiple objects in a video both in one file in python
6e71650d4bdcd99cece24dbeb0d25e96
{ "intermediate": 0.10119999200105667, "beginner": 0.04595033824443817, "expert": 0.8528496026992798 }
8,777
Explain this lines of code with open("coco.names", "r") as f: classes = [line.strip() for line in f.readlines()]
071f6be93a2263dc92f0483503dd217a
{ "intermediate": 0.31155604124069214, "beginner": 0.5794982314109802, "expert": 0.10894576460123062 }
8,778
МНе нужно подзгрузить модель для работы import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification,AutoModel, AutoTokenizer # Define the model repo model_name = "mirfan899/tinruberta2" #"blanchefort/rubert-base-cased-sentiment" # Download pytorch model model = AutoModel.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) # Загрузка модели и токенизатора model = AutoModelForSequenceClassification.from_pretrained(model_name) Как я могу загрузить model_name = "mirfan899/tinruberta2" в гугл колаб?
8982c50b6ba54eb410cd69b7160899de
{ "intermediate": 0.5615780353546143, "beginner": 0.2356048971414566, "expert": 0.20281703770160675 }
8,779
import time from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys def get_token_info(token_symbol): chrome_options = Options() chrome_options.add_argument("–headless") # Update the path below to the actual path to your WebDriver executable service = Service( executable_path="C:\\Users\\AshotxXx\\PycharmProjects\\Parcing\\pythonProject\\ChromeDriver\\chromedriver.exe") driver = webdriver.Chrome(service=service, options=chrome_options) driver.get("https://moonarch.app/") try: # Switch to the iframe (replace iframe_element with the correct frame element reference) driver.switch_to.frame('typeahead-input-87261') search_box = driver.find_element_by_xpath('/html/body/div/div[2]/nav/div[3]/div/div[1]/input') # Find the search box and interact with it search_box(token_symbol) # Switch back to the main content driver.switch_to.default_content() # Wait for the token info and infocard elements to appear after entering the symbol WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "token-info"))) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "infocard"))) # Extract information using BeautifulSoup soup = BeautifulSoup(driver.page_source, "html.parser") token_info_element = soup.find("div", class_="token-info") infocard_element = soup.find("div", class_="infocard") check_alert_element = soup.find("div", class_="token-check-message check-alert") check_warning_element = soup.find("div", class_="token-check-message check-warning") check_info_element = soup.find("div", class_="token-check-message check-info") not_verified_element = soup.find("div", class_="not-verified") check_alert_status = "Yes" if check_alert_element else "None" check_warning_status = "Yes" if check_warning_element else "None" check_info_status = "Yes" if check_info_element else "None" not_verified_status = "Yes" if not_verified_element else "None" if token_info_element and infocard_element: token_name_element = token_info_element.find("span", class_="name") token_symbol_element = token_info_element.find("span", class_="symbol") info_items = infocard_element.find_all("li") if token_name_element and token_symbol_element and len(info_items) >= 7: token_name = token_name_element.text.strip() token_symbol = token_symbol_element.text.strip() price = info_items[0].find("span", class_="value").text.strip() max_supply = info_items[1].find("span", class_="value").text.strip() market_cap = info_items[2].find("span", class_="value").text.strip() liquidity = info_items[3].find("span", class_="value").text.strip() liq_mc = info_items[4].find("span", class_="value").text.strip() token_age = info_items[6].find("span", class_="value").text.strip() driver.quit() return { "name": token_name, "symbol": token_symbol, "price": price, "max_supply": max_supply, "market_cap": market_cap, "liquidity": liquidity, "liq_mc": liq_mc, "token_age": token_age, "check_alert": check_alert_status, "check_warning": check_warning_status, "check_info": check_info_status, "not_verified": not_verified_status } else: driver.quit() error_info = f"token_name_element: {token_name_element}, token_symbol_element: {token_symbol_element}, info_items count: {len(info_items)}" return {"error": f"Failed to find the required info items or name and.symbol. Error_info: {error_info}"} else: driver.quit() return {"error": f"Failed to find the required elements for token_info_element ({token_info_element}) and infocard_element ({infocard_element})."} except Exception as e: driver.quit() return {"error": f"Failed to find the required elements or error occurred: {e}"} token_symbol = "0x0E481Fa712201f61dAf97017138Efaa69e2A3df3" print(get_token_info(token_symbol)) The code above throws an error. The error is below C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\Parcing\pythonProject\ChromeDriver\main.py {'error': 'Failed to find the required elements or error occurred: Message: typeahead-input-87261\n'} Process finished with exit code 0 <div data-v-274f1e68="" id="typeahead-26687" role="combobox" aria-haspopup="listbox" aria-owns="result-list-26687" aria-expanded="false"><div data-v-274f1e68="" class="input-group"><!----><input data-v-274f1e68="" id="typeahead-input-26687" type="text" role="searchbox" aria-multiline="false" aria-autocomplete="list" aria-controls="result-list-26687" aria-activedescendant="selected-option-26687" placeholder="Search token for analysis" aria-label="Search token for analysis" class="form-control "><!----></div><div data-v-274f1e68="" class="list-group shadow vbt-autcomplete-list" id="result-list-26687" role="listbox" style="display: none; width: 815px;"></div></div> Change the code so that the specified parameters are entered in the search field. Be sure to use an iframe as the other methods don't work
178b8b132e1c13592598371e82da0887
{ "intermediate": 0.30812394618988037, "beginner": 0.42090529203414917, "expert": 0.27097079157829285 }
8,780
#include <iostream> #include <thread> #include <deque> #include <functional> #include <future> #include <mutex> #include <condition_variable> #include <vector> #include <memory> class ZYLThreadPool { public: ZYLThreadPool(size_t maxThreads = 200): _maxThreads(maxThreads), _stop(false) { worker_threads.reserve(_maxThreads); for(size_t i = 0; i < _maxThreads; ++i) { worker_threads.emplace_back([this] { for(;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->_mutex); this->_condVar.wait(lock, [this] { return this->_stop || !this->_taskQueue.empty(); }); if(this->_stop && this->_taskQueue.empty()) return; task = std::move(this->_taskQueue.front()); this->_taskQueue.pop_front(); } task(); } }); } } template<typename F, typename... Args> auto submit(F&& f, Args&&... args) -> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> result = task->get_future(); { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { throw std::runtime_error("Submit on stopped ZYLThreadPool"); } _taskQueue.emplace_back([task] { (*task)(); }); } _condVar.notify_one(); return result; } void cancel() { std::unique_lock<std::mutex> lock(_mutex); if (!_stop) { _stop = true; _condVar.notify_all(); } for(std::thread &worker: worker_threads) worker.join(); } size_t getNumTasks() { std::unique_lock<std::mutex> lock(_mutex); return _taskQueue.size(); } ~ZYLThreadPool() { cancel(); } private: std::vector<std::thread> worker_threads; std::deque<std::function<void()>> _taskQueue; size_t _maxThreads; std::mutex _mutex; std::condition_variable _condVar; bool _stop; }; class Test { public: Test(double devid): _devid(devid), _running(true) { } void start(ZYLThreadPool &threadPool) { _future = threadPool.submit(&Test::_task, this); } void stop() { { _running = false; std::unique_lock<std::mutex> lock(_mutex); if (_future.valid()) { _future.get(); lock.unlock(); _cleanupResources(); } } } private: std::mutex _mutex; double _devid; std::deque<double> _dequeue_packets; std::future<void> _future; bool _running; void _cleanupResources() { std::unique_lock<std::mutex> lock(_mutex); _dequeue_packets.clear(); } void _task() { std::unique_lock<std::mutex> lock(_mutex); while(_running ) { if (_dequeue_packets.empty()){ std::cout<<"unning task"<<std::endl; continue; } double packet = _dequeue_packets.front(); _dequeue_packets.pop_front(); lock.unlock(); std::cout<<"running task"<<std::endl; lock.lock(); } std::cout<<"task end"<<std::endl; } }; int main() { ZYLThreadPool zylThreadPool(200); std::shared_ptr<Test> test = std::make_shared<Test>(1.0); test->start(zylThreadPool); std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout<<"stop task"<<std::endl; test->stop(); return 0; } 上面例子,测试程序启动过后,发现就已经是默认启了201个线程,请完善,要求: 1.在线程池初始化时默认不会创建所有的线程,而是先创建一些线程,比如20个 2.能够根据实际情况自动调整线程的数量,比如,常用的线程池实现中,可以指定线程池的最大容量为200,最小容量为20 3.线程池启动时会创建最小容量的线程,如果当前任务量较大,线程池就会根据需要增加线程数,直到达到最大容量 4.如果当前任务量较少,线程池就会逐渐减少线程数,直到最小容量 5.需要动态创建线程,避免资源浪费或者线程数过少导致性能瓶颈 6.请晚上测试demo,要求动态添加100个test任务,然后动态停止100个test任务,然后再启动3个test任务来观察测试
3bca3b74b372e1e147ed7d0a3cd00e3b
{ "intermediate": 0.4058358669281006, "beginner": 0.4281260669231415, "expert": 0.16603811085224152 }
8,781
This is my ide program for a highsum gui game. “import GUIExample.GameTableFrame; import Model.; import GUIExample.LoginDialog; public class GUIExample { private Dealer dealer; private Player player; private GameTableFrame app; public GUIExample() { } public void run() { dealer.shuffleCards(); app = new GameTableFrame(dealer, player); app.setVisible(true); // Replace app.run(); with this line } public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); GUIExample example = new GUIExample(); example.dealer = new Dealer(); example.player = new Player(login, password, 10000); example.run(); } } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.; import java.awt.event.; import javax.swing.; public class HighSumGUI { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum() { // Override the ‘run’ method to display and update the GameTableFrame @Override public void run() { Dealer dealer = getDealer(); Player player = getPlayer(); GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); gameTableFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Use a loop to continuously update and start new games as desired by the user boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); int response = JOptionPane.showConfirmDialog( gameTableFrame, “Do you want to play another game?”, “New Game”, JOptionPane.YES_NO_OPTION ); if (response == JOptionPane.YES_OPTION) { dealer.clearCardsOnHand(); player.clearCardsOnHand(); } else { carryOn = false; gameTableFrame.dispose(); } } } }; highSum.init(login, password); highSum.run(); } } }); } } package Controller; import Model.Dealer; import Model.Player; import View.ViewController; public class GameController { private Dealer dealer; private Player player; private ViewController view; private int chipsOnTable; private boolean playerQuit; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } public boolean getPlayerQuitStatus() { return playerQuit; } public void run() { boolean carryOn= true; while(carryOn) { runOneRound(); char r = this.view.getPlayerNextGame(); if(r==‘n’) { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for(int round = 1;round<=4;round++) { this.view.displaySingleLine(); this.view.displayDealerDealCardsAndGameRound(round); this.view.displaySingleLine(); if (round == 1) { //round 1 deal extra card this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } else { this.dealer.dealCardTo(this.player); this.dealer.dealCardTo(this.dealer); } this.view.displayPlayerCardsOnHand(this.dealer); this.view.displayBlankLine(); this.view.displayPlayerCardsOnHand(player); this.view.displayPlayerTotalCardValue(player); int whoCanCall = this.dealer.determineWhichCardRankHigher(dealer.getLastCard(), player.getLastCard()); if(whoCanCall==1) {//dealer call int chipsToBet = this.view. getDealerCallBetChips(); //ask player want to follow? char r = this.view.getPlayerFollowOrNot(this.player,chipsToBet); if(r==‘y’) { this.player.deductChips(chipsToBet); this.chipsOnTable+=2chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } }else {//player call if(round==1) {//round 1 player cannot quit int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2chipsToBet; this.view.displayBetOntable(this.chipsOnTable); }else { char r = this.view.getPlayerCallOrQuit(); if(r==‘c’) { int chipsToBet = view.getPlayerCallBetChip(this.player); this.player.deductChips(chipsToBet); this.chipsOnTable+=2chipsToBet; this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayBetOntable(this.chipsOnTable); }else { playerQuit = true; break; } } } } //check who win if(playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else if(this.player.getTotalCardsValue()>this.dealer.getTotalCardsValue()) { this.view.displayPlayerWin(this.player); this.player.addChips(chipsOnTable); this.chipsOnTable=0; this.view.displayPlayerNameAndLeftOverChips(this.player); }else if(this.player.getTotalCardsValue()<this.dealer.getTotalCardsValue()) { this.view.displayDealerWin(); this.view.displayPlayerNameAndLeftOverChips(this.player); }else { this.view.displayTie(); this.player.addChips(chipsOnTable/2); this.view.displayPlayerNameAndLeftOverChips(this.player); } //put all the cards back to the deck dealer.addCardsBackToDeck(dealer.getCardsOnHand()); dealer.addCardsBackToDeck(player.getCardsOnHand()); dealer.clearCardsOnHand(); player.clearCardsOnHand(); } } package GUIExample; import Model.Dealer; import Model.HighSum; import Model.Player; import java.awt.BorderLayout; import javax.swing.; import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class GameTableFrame extends JFrame { private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private JLabel shufflingLabel; private JButton playButton; private JButton quitButton; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer, player); shufflingLabel = new JLabel(“Shuffling”); shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER); playButton = new JButton(“Play”); quitButton = new JButton(“Quit”); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); HighSum highSum = new HighSum(); highSum.init(player.getLoginName(), “some_default_password”); highSum.run(); updateScreen(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); // Create the main panel that contains both the game board and the buttons JPanel mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout()); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); mainPanel.add(gameTablePanel, BorderLayout.CENTER); mainPanel.add(buttonsPanel, BorderLayout.SOUTH); mainPanel.add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); add(mainPanel); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); setVisible(true); } // This method updates the screen after each game public void updateScreen() { gameTablePanel.updateTable(dealer, player); } } package GUIExample; import java.awt.; import javax.swing.; import Model.; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; public GameTablePanel(Dealer dealer, Player player) { setLayout(new BorderLayout()); setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); this.dealer = dealer; this.player = player; } public void updateTable(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Draw dealer’s cards int dealerX = 50; int dealerY = 100; g.drawString(“Dealer”, dealerX, dealerY - 20); dealerX = drawPlayerHand(g, dealer, dealerX, dealerY, true); // Draw player’s cards int playerX = 50; int playerY = getHeight() - 200; g.drawString(“Player”, playerX, playerY - 20); playerX = drawPlayerHand(g, player, playerX, playerY, false); // Draw chips on the table g.setColor(Color.BLACK); g.setFont(new Font(“Arial”, Font.PLAIN, 18)); g.drawString("Chips on the table: ", playerX + 50, playerY); } private int drawPlayerHand(Graphics g, Player p, int x, int y, boolean isDealer) { int i = 0; for (Card c : p.getCardsOnHand()) { if (isDealer && i == 0) { new ImageIcon(“images/back.png”).paintIcon(this, g, x, y); } else { c.paintIcon(this, g, x, y); } x += 100; i++; } return x; } } package GUIExample; import javax.swing.; import java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class LoginDialog extends JDialog { private JTextField loginField; private JPasswordField passwordField; private JButton loginButton; private boolean loggedIn = false; public LoginDialog(JFrame parent) { super(parent, “Login”, true); loginField = new JTextField(20); passwordField = new JPasswordField(20); loginButton = new JButton(“Login”); loginButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loggedIn = true; dispose(); } }); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(3, 2)); panel.add(new JLabel(“Login:”)); panel.add(loginField); panel.add(new JLabel(“Password:”)); panel.add(passwordField); panel.add(loginButton); add(panel); pack(); setLocationRelativeTo(parent); } public String getLogin() { return loginField.getText(); } public String getPassword() { return new String(passwordField.getPassword()); } public boolean isLoggedIn() { return loggedIn; } } package Helper; public class Keyboard { public static String readString(String prompt) { System.out.print(prompt); return new java.util.Scanner(System.in).nextLine(); } public static int readInt(String prompt) { int input = 0; boolean valid = false; while (!valid) { try { input = Integer.parseInt(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println("** Please enter an integer “); } } return input; } public static double readDouble(String prompt) { double input = 0; boolean valid = false; while (!valid) { try { input = Double.parseDouble(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println(” Please enter a double “); } } return input; } public static float readFloat(String prompt) { float input = 0; boolean valid = false; while (!valid) { try { input = Float.parseFloat(readString(prompt)); valid = true; } catch (NumberFormatException e) { System.out.println(” Please enter a float “); } } return input; } public static long readLong(String prompt) { long input = 0; boolean valid = false; while (!valid) { try { input = Long.parseLong(readString(prompt)); valid = true; } catch (NumberFormatException e) { e.printStackTrace(); System.out.println(” Please enter a long “); } } return input; } public static char readChar(String prompt,char[] choices) { boolean validChoice = false; char r = ’ '; while(!validChoice) { r = Keyboard.readChar(prompt+” “+charArrayToString(choices)+”:“); if(!validateChoice(choices,r)) { System.out.println(“Invalid input”); }else { validChoice = true; } } return r; } private static String charArrayToString(char[] charArray) { String s = “[”; for(int i=0;i<charArray.length;i++) { s+=charArray[i]; if(i!=charArray.length-1) { s+=”,“; } } s += “]”; return s; } private static boolean validateChoice(char[] choices, char choice) { boolean validChoice = false; for(int i=0;i<choices.length;i++) { if(choices[i]==choice) { validChoice = true; break; } } return validChoice; } public static char readChar(String prompt) { char input = 0; boolean valid = false; while (!valid) { String temp = readString(prompt); if (temp.length() != 1) { System.out.println(” Please enter a character “); } else { input = temp.charAt(0); valid = true; } } return input; } public static boolean readBoolean(String prompt) { boolean valid = false; while (!valid) { String input = readString(prompt); if (input.equalsIgnoreCase(“yes”) || input.equalsIgnoreCase(“y”) || input.equalsIgnoreCase(“true”) || input.equalsIgnoreCase(“t”)) { return true; } else if (input.equalsIgnoreCase(“no”) || input.equalsIgnoreCase(“n”) || input.equalsIgnoreCase(“false”) || input.equalsIgnoreCase(“f”)) { return false; } else { System.out.println(” Please enter Yes/No or True/False “); } } return false; } public static java.util.Date readDate(String prompt) { java.util.Date date = null; boolean valid = false; while (!valid) { try { String input = readString(prompt).trim(); if (input.matches(”\d\d/\d\d/\d\d\d\d")) { int day = Integer.parseInt(input.substring(0, 2)); int month = Integer.parseInt(input.substring(3, 5)); int year = Integer.parseInt(input.substring(6, 10)); java.util.Calendar cal = java.util.Calendar.getInstance(); cal.setLenient(false); cal.set(year, month - 1, day, 0, 0, 0); date = cal.getTime(); valid = true; } else { System.out.println(" Please enter a date (DD/MM/YYYY) “); } } catch (IllegalArgumentException e) { System.out.println(” Please enter a date (DD/MM/YYYY) “); } } return date; } private static String quit = “0”; public static int getUserOption(String title, String[] menu) { displayMenu(title, menu); int choice = Keyboard.readInt(“Enter Choice --> “); while (choice > menu.length || choice < 0) { choice = Keyboard.readInt(“Invalid Choice, Re-enter --> “); } return choice; } private static void displayMenu(String title, String[] menu) { line(80, “=”); System.out.println(title.toUpperCase()); line(80, “-”); for (int i = 0; i < menu.length; i++) { System.out.println(”[” + (i + 1) + “] " + menu[i]); } System.out.println(”[” + quit + “] Quit”); line(80, “-”); } public static void line(int len, String c) { System.out.println(String.format(”%” + len + “s”, " “).replaceAll(” “, c)); } } package Helper; import java.security.MessageDigest; public class Utility { public static String getHash(String base) { String message=”“; try{ MessageDigest digest = MessageDigest.getInstance(“SHA-256”); byte[] hash = digest.digest(base.getBytes(“UTF-8”)); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < hash.length; i++) { String hex = Integer.toHexString(0xff & hash[i]); if(hex.length() == 1) hexString.append(‘0’); hexString.append(hex); } message = hexString.toString(); } catch(Exception ex){ throw new RuntimeException(ex); } return message; } public static void printLine(int num) { printLine(num,‘-’); } public static void printDoubleLine(int num) { printLine(num,‘=’); } public static void printLine(int num,char pattern) { for(int i =0;i<num;i++) { System.out.print(pattern); } System.out.println(”"); } } package Model; import javax.swing.; public class Card extends ImageIcon { private String suit; private String name; private int value; private int rank; private boolean faceDown; public Card(String suit, String name, int value, int rank) { super(“images/” + suit + name + “.png”); this.suit = suit; this.name = name; this.value = value; this.rank = rank; this.faceDown = false; } public boolean isFaceDown() { return this.faceDown; } public void setFaceDown(boolean faceDown) { this.faceDown = faceDown; } public String getSuit() { return this.suit; } public String getName() { return this.name; } public int getValue() { return this.value; } public int getRank() { return this.rank; } public String toString() { if (this.faceDown) { return “<HIDDEN CARD>”; } else { return “<” + this.suit + " " + this.name + “>”; } } public String display() { return “<”+this.suit+" “+this.name+” “+this.rank+”>"; } } //card rank // D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import java.util.; public class Dealer extends Player { private Deck deck; public Dealer() { super(“Dealer”, “”, 0); deck = new Deck(); } public void shuffleCards() { System.out.println(“Dealer shuffle deck”); deck.shuffle(); } public void dealCardTo(Player player) { Card card = deck.dealCard(); // take a card out from the deck player.addCard(card); // pass the card into the player } public void addCardsBackToDeck(ArrayList<Card> cards) { deck.appendCard(cards); } //return 1 if card1 rank higher, else return 2 public int determineWhichCardRankHigher(Card card1, Card card2) { if(card1.getRank()>card2.getRank()) { return 1; }else { return 2; } } } package Model; import java.util.; public class Deck { private ArrayList<Card> cards; public Deck() { cards = new ArrayList<Card>(); String[] suits = { “Diamond”, “Club”,“Heart”,“Spade”, }; for (int i = 0; i < suits.length; i++) { String suit = suits[i]; Card card = new Card(suit, “Ace”, 1,1+i); cards.add(card); int c = 5; for (int n = 2; n <= 10; n++) { Card oCard = new Card(suit, “” + n, n,c+i); cards.add(oCard); c+=4; } Card jackCard = new Card(suit, “Jack”, 10,41+i); cards.add(jackCard); Card queenCard = new Card(suit, “Queen”, 10,45+i); cards.add(queenCard); Card kingCard = new Card(suit, “King”, 10,49+i); cards.add(kingCard); } } public Card dealCard() { return cards.remove(0); } //add back one card public void appendCard(Card card) { cards.add(card); } //add back arraylist of cards public void appendCard(ArrayList<Card> cards) { for(Card card: cards) { this.cards.add(card); } } public void shuffle() { Random random = new Random(); for(int i=0;i<10000;i++) { int indexA = random.nextInt(cards.size()); int indexB = random.nextInt(cards.size()); Card cardA = cards.get(indexA); Card cardB = cards.get(indexB); cards.set(indexA, cardB); cards.set(indexB, cardA); } } //for internal use only private void showCards() { for (Card card : cards) { System.out.println(card); } } //for internal use only private void displayCards() { for (Card card : cards) { System.out.println(card.display()); } } public static void main(String[] args) { Deck deck = new Deck(); //deck.shuffle(); /Card card1 = deck.dealCard(); Card card2 = deck.dealCard(); Card card3 = deck.dealCard(); deck.showCards(); ArrayList<Card> cards = new ArrayList<Card>(); cards.add(card1); cards.add(card2); cards.add(card3); deck.appendCard(cards); System.out.println();/ deck.displayCards(); } } //card rank //D C H S //1 1 2 3 4 //2 5 6 7 8 //3 9 10 11 12 //4 13 14 15 16 //5 17 18 19 20 //6 21 22 23 24 //7 25 26 27 28 //8 29 30 31 32 //9 33 34 35 36 //10 37 38 39 40 //J 41 42 43 44 //Q 45 46 47 48 //K 49 50 51 52 package Model; import Controller.; import View.; import GUIExample.LoginDialog; import GUIExample.GameTableFrame; import javax.swing.JOptionPane; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; private int chipsOnTable; public HighSum() { } public void init(String login, String password) { // Create all the required objects this.dealer = new Dealer(); this.player = new Player(login, password, 50); this.view = new ViewController(); // Bring them together this.gc = new GameController(this.dealer, this.player, this.view); } private Player checkWinner() { if(player.getTotalCardsValue() > dealer.getTotalCardsValue()) return player; else if(player.getTotalCardsValue() < dealer.getTotalCardsValue()) return dealer; else return null; } public Dealer getDealer() { return dealer; } public Player getPlayer() { return player; } public void run() { // Setup the game table GameTableFrame gameTableFrame = new GameTableFrame(dealer, player); // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); gameTableFrame.updateScreen(); if (!gc.getPlayerQuitStatus()) { int response = JOptionPane.showConfirmDialog( gameTableFrame, “Do you want to play another game?”, “New Game”, JOptionPane.YES_NO_OPTION ); carryOn = response == JOptionPane.YES_OPTION; } else { carryOn = false; } } this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayExitGame(); gameTableFrame.dispose(); } public void runOneRound() { this.view.displayGameTitle(); this.view.displayDoubleLine(); this.view.displayPlayerNameAndChips(this.player); this.view.displaySingleLine(); this.view.displayGameStart(); this.view.displaySingleLine(); this.dealer.shuffleCards(); this.chipsOnTable = 0; boolean playerQuit = false; for (int round = 1; round <= 4; round++) { // Code remains same until here // Check if the player wants to follow or quit char r; int chipsToBet; if (round == 1) { chipsToBet = this.view.getPlayerCallBetChip(this.player); } else { chipsToBet = this.view.getDealerCallBetChips(); } } Player winner = checkWinner(); if(playerQuit){ this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } } /* public static void main(String[] args) { LoginDialog loginDialog = new LoginDialog(null); loginDialog.setVisible(true); if (loginDialog.isLoggedIn()) { String login = loginDialog.getLogin(); String password = loginDialog.getPassword(); HighSum highSum = new HighSum(); highSum.init(login, password); highSum.run(); } }/ } package Model; import java.util.; public class Player extends User{ private int chips; protected ArrayList<Card> cardsOnHand; public Player(String loginName, String password, int chips) { super(loginName, password); this.chips = chips; this.cardsOnHand = new ArrayList<Card>(); } public int getChips() { return this.chips; } public void addChips(int amount) { this.chips+=amount;//no error check } public void deductChips(int amount) { this.chips-=amount;//no error check } public void addCard(Card card) { this.cardsOnHand.add(card); } public ArrayList<Card> getCardsOnHand() { return this.cardsOnHand; } public int getTotalCardsValue() { int total = 0; for(Card card: this.cardsOnHand) { total+=card.getValue(); } return total; } public Card getLastCard() { return this.cardsOnHand.get(this.cardsOnHand.size()-1); } public void clearCardsOnHand() { this.cardsOnHand.clear(); } //Think of the action that a player can take //implement more related methods here public static void main(String[] args) { // TODO Auto-generated method stub Player player = new Player(“IcePeak”,“A”,100); System.out.println(player.getChips()); player.deductChips(10); System.out.println(player.getChips()); player.addChips(20); System.out.println(player.getChips()); } } package Model; import Helper.; abstract public class User { private String loginName; private String hashPassword; public User(String loginName, String password) { this.loginName = loginName; this.hashPassword = Utility.getHash(password); } public String getLoginName() { return this.loginName; } public boolean checkPassword(String password) { return this.hashPassword.equals(Utility.getHash(password)); } } package View; import Helper.; import Model.*; //all input and output should be done view ViewController //so that it is easier to implement GUI later public class ViewController { public void displayExitGame() { System.out.println(“Thank you for playing HighSum game”); } public void displayBetOntable(int bet) { System.out.println(“Bet on table : “+bet); } public void displayPlayerWin(Player player) { System.out.println(player.getLoginName()+” Wins!”); } public void displayDealerWin() { System.out.println(“Dealer Wins!”); } public void displayTie() { System.out.println(“It is a tie!.”); } public void displayPlayerQuit() { System.out.println(“You have quit the current game.”); } public void displayPlayerCardsOnHand(Player player) { System.out.println(player.getLoginName()); if(player instanceof Dealer) { for (int i = 0; i < player.getCardsOnHand().size(); i++) { if (i == 0) { System.out.print(”<HIDDEN CARD> “); } else { System.out.print(player.getCardsOnHand().get(i).toString() + " “); } } } else { for (Card card : player.getCardsOnHand()) { System.out.print(card + " “); } } System.out.println(); } public void displayBlankLine() { System.out.println(); } public void displayPlayerTotalCardValue(Player player) { System.out.println(“Value:”+player.getTotalCardsValue()); } public void displayDealerDealCardsAndGameRound(int round) { System.out.println(“Dealer dealing cards - ROUND “+round); } public void displayGameStart() { System.out.println(“Game starts - Dealer shuffle deck”); } public void displayPlayerNameAndChips(Player player) { System.out.println(player.getLoginName()+”, You have “+player.getChips()+” chips”); } public void displayPlayerNameAndLeftOverChips(Player player) { System.out.println(player.getLoginName()+”, You are left with “+player.getChips()+” chips”); } public void displayGameTitle() { System.out.println(“HighSum GAME”); } public void displaySingleLine() { for(int i=0;i<30;i++) { System.out.print(”-“); } System.out.println(); } public void displayDoubleLine() { for(int i=0;i<30;i++) { System.out.print(”=“); } System.out.println(); } public char getPlayerCallOrQuit() { char[] choices = {‘c’,‘q’}; char r = Keyboard.readChar(“Do you want to [c]all or [q]uit?:”,choices); return r; } public char getPlayerFollowOrNot(Player player, int dealerBet) { boolean validChoice = false; char[] choices = {‘y’,‘n’}; char r = ‘n’; while(!validChoice) { r = Keyboard.readChar(“Do you want to follow?”,choices); //check if player has enff chips to follow if(r==‘y’ && player.getChips()<dealerBet) { System.out.println(“You do not have enough chips to follow”); displayPlayerNameAndChips(player); }else { validChoice = true; } } return r; } public char getPlayerNextGame() { char[] choices = {‘y’,‘n’}; char r = Keyboard.readChar(“Next game?”,choices); return r; } public int getPlayerCallBetChip(Player player) { boolean validBetAmount = false; int chipsToBet = 0; while(!validBetAmount) { chipsToBet = Keyboard.readInt(“Player call, state bet:”); if(chipsToBet<0) { System.out.println(“Chips cannot be negative”); }else if(chipsToBet>player.getChips()) { System.out.println(“You do not have enough chips”); }else { validBetAmount = true; } } return chipsToBet; } public int getDealerCallBetChips() { System.out.println(“Dealer call, state bet: 10”); return 10; } } ” These are the requirements: “On completion of this assignment a student should be able to write a Java application that: • Makes use of Java API “Swing” and “AWT” packages • Handles generated events • Makes use of layout manager to organize the GUI components • Know how to apply and design a program using object-oriented concepts 2. Task Enhance the one player Java game application “HighSum” done in Assignment 1 with Graphical User Interface (GUI). 2.1 Login The game starts by the player logging into the game. 2.2 Play Game The game starts after the player click on “Login”. First, the dealer will shuffles the deck. (You may include animation in this frame to simulate “shuffle” effect as enhancement.) Then the dealer deals two cards from the top of the deck to the player and itself. Since the player’s last card is higher than the dealer’s last card, the player gets to Call the game. Assume the player states 10 as the bet chips. The player’s chip will be deducted by 10. The chips on table will be updated to 20 and the dealer deals cards for next round. Assume the dealer’s last card is higher than the player’s last card. The dealer Call the game and the player gets to choose to Follow or Quit the game. If the player follows the game, 10 chips will be deducted from the player’s balance chips. (Asumme the dealer place 10 chips.) The games carry on for maximum of four rounds. In the last round, the player with the highest total sum wins the game. And the game continues until the player exits the game. Error Handling Your program should be able to handle error situations like where a player enter wrong password or has insufficient chips. You should look out for other possible exceptions and handle them too.” Edit the code so that when highsum gui is run, The game runs on the GUI and NOT on the console. The gui currently is empty and blank and cannot be closed when run.
6d7b351e7f48c5839a3eaded235f148c
{ "intermediate": 0.2617759704589844, "beginner": 0.5683426856994629, "expert": 0.16988128423690796 }
8,782
how to make matrix A=[1,5,3;4,7,9;2,6,8] to sort in one row to become matrix B=[1,5,3,4,7,9,2,6,8] in matlab
174ec58082704cbaff006e2519f0ff88
{ "intermediate": 0.2309088259935379, "beginner": 0.19887231290340424, "expert": 0.5702189207077026 }
8,783
Use a pretrained deep learning model for object detection (ex: Yolo or MobileNet SSD) to detect moving object in a video. • Implement a tracking algorithm (ex: DeepSort, Opencv tracking algorithms) to track multiple objects in a video. • Use the object detection model and the tracking algorithm to formulate a video summarization algorithm that only selects the frames with motion in them. but dont use DeepSort & Motpy
7468f34f7fe5a30138cf8f979268ddc1
{ "intermediate": 0.24328380823135376, "beginner": 0.2578281760215759, "expert": 0.4988880157470703 }
8,784
Ubah kode ini dengan Stratified K Foldnya menggunakan data training, dan lakukan pengujian pada data testing setelah semua proses k fold selesai! import pickle import pandas as pd import numpy as np from keras.preprocessing.text import Tokenizer from keras.utils import pad_sequences from keras.models import Sequential from keras.layers import Embedding, LSTM, Dense, Dropout, Conv1D, GlobalMaxPooling1D, Reshape from keras.layers import Flatten from keras.utils import to_categorical from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score, classification_report import gensim from keras.regularizers import l2 from keras.callbacks import EarlyStopping from keras.optimizers import Adam # Membaca dataset data_list = pickle.load(open('pre_processed_berita_121_joined_FIX_parpolheuristic_added.pkl', 'rb')) data = pd.DataFrame(data_list, columns=['judul', 'isi', 'pre_processed', 'Label', 'Partai_Politik_Heuristic']) data['Isi Berita'] = data['pre_processed'] # Tokenisasi dan Padding max_words = 10000 # mengurangi jumlah kata maksimum max_len = 500 # mengurangi panjang input tokenizer = Tokenizer(num_words=max_words) tokenizer.fit_on_texts(data['Isi Berita']) sequences = tokenizer.texts_to_sequences(data['Isi Berita']) X = pad_sequences(sequences, maxlen=max_len) y = to_categorical(data['Label'].astype('category').cat.codes) # Membagi data menjadi data latih dan data uji X_train, X_test, y_train, y_test, idx_train, idx_test = train_test_split(X, y, data.index, test_size=0.25, random_state=42) # Menggunakan pre-trained word2vec Bahasa Indonesia path = 'idwiki_word2vec_300.model' id_w2v = gensim.models.word2vec.Word2Vec.load(path) wv = id_w2v.wv # Membuat matriks embedding embedding_dim = 300 embedding_matrix = np.zeros((max_words, embedding_dim)) for word, i in tokenizer.word_index.items(): if i < max_words: try: embedding_vector = wv[word] embedding_matrix[i] = embedding_vector except KeyError: pass from sklearn.model_selection import StratifiedKFold # Inisialisasi StratifiedKFold n_splits = 5 skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42) # Konversi kategori target ke nilai numerik y_categorical = data['Label'].astype('category').cat.codes # Menyimpan akurasi dan report untuk setiap lipatan accuracies = [] class_reports = [] iter_num = 1 histories = [] for train_index, test_index in skf.split(X, y_categorical): print("\nTraining and evaluating model for fold", iter_num) # Membagi data berdasarkan indeks dari lipatan saat ini X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] # Membangun model untuk lipatan saat ini model = Sequential() model.add(Embedding(max_words, embedding_dim, weights=[embedding_matrix], input_length=max_len, trainable=False)) model.add(LSTM(200, return_sequences=True, kernel_regularizer=l2(0.01), recurrent_regularizer=l2(0.01))) model.add(Conv1D(256, 3, activation='relu', kernel_regularizer=l2(0.01))) model.add(GlobalMaxPooling1D()) model.add(Dropout(0.1)) Reshape((-1, 256)), model.add(Flatten()) model.add(Dropout(0.5)) model.add(Dense(32, activation='relu', kernel_regularizer=l2(0.01))) model.add(Dropout(0.2)) model.add(Dense(3, activation='softmax')) # Buat callback early stopping callback_es = EarlyStopping(monitor='val_loss', patience=5, verbose=1, restore_best_weights=True) initial_learning_rate = 0.0001 optimizer = Adam(learning_rate=initial_learning_rate) # Kompilasi model model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy']) # Latih model dengan menggunakan learning rate scheduler dan early stopping dalam callbacks history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=128, callbacks=[callback_es]) histories.append(history) model.save('LSTM-CNN_Word2Vec_Tertinggi_LSTM200_CNN256_' + str(iter_num) + '.h5') # Evaluasi model pada lipatan saat ini y_pred = model.predict(X_test) y_pred_labels = np.argmax(y_pred, axis=1) y_test_labels = np.argmax(y_test, axis=1) # Menghitung akurasi accuracy = accuracy_score(y_test_labels, y_pred_labels) print("Fold", iter_num, "Accuracy: {:.2f}%".format(accuracy * 100)) # Classification report class_report = classification_report(y_test_labels, y_pred_labels) # Menambahkan akurasi dan report ke daftar accuracies.append(accuracy) class_reports.append(class_report) iter_num += 1 # Mengevaluasi model y_pred = model.predict(X_test) y_pred = np.argmax(y_pred, axis=1) y_true = np.argmax(y_test, axis=1) # Menambahkan kolom hasil prediksi ke DataFrame data data['Label_Hasil_Prediksi'] = None # inisialisasi kolom dengan None data.loc[idx_test, 'Label_Hasil_Prediksi'] = y_pred # Export ke file CSV data.to_csv('hasil_2_BARU_19MEI.csv', columns=['judul', 'isi', 'Label', 'Label_Hasil_Prediksi', 'Partai_Politik_Heuristic'], index=False, sep=';') # Menghitung akurasi accuracy = accuracy_score(y_true, y_pred) print(f"Akurasi: {accuracy}") # Menampilkan classification report report = classification_report(y_true, y_pred, target_names=['Negatif', 'Netral', 'Positif']) print("Classification Report:") print(report)
24e0a1e174869a9c23d32e6eede7be2f
{ "intermediate": 0.27152204513549805, "beginner": 0.2817728519439697, "expert": 0.44670507311820984 }
8,785
#include <iostream> #include <thread> #include <deque> #include <functional> #include <future> #include <mutex> #include <condition_variable> #include <vector> #include <memory> #include <chrono> class ZYLThreadPool { public: ZYLThreadPool(size_t minThreads = 20, size_t maxThreads = 200) : _minThreads(minThreads) , _maxThreads(maxThreads) , _stop(false) { worker_threads.reserve(_maxThreads); for (size_t i = 0; i < _minThreads; ++i) { create_thread(); } } void create_thread() { worker_threads.emplace_back([this] { for (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->_mutex); this->_condVar.wait(lock, [this] { return this->_stop || !this->_taskQueue.empty(); }); if (this->_stop && this->_taskQueue.empty()) return; task = std::move(this->_taskQueue.front()); this->_taskQueue.pop_front(); } task(); } }); } template <typename F, typename... Args> auto submit(F&& f, Args&&... args)-> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> result = task->get_future(); { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { throw std::runtime_error("Submit on stopped ZYLThreadPool"); } if (_taskQueue.size() >= worker_threads.size() && worker_threads.size() < _maxThreads) { create_thread(); } _taskQueue.emplace_back([task] { (*task)(); }); } _condVar.notify_one(); return result; } void cancel() { std::unique_lock<std::mutex> lock(_mutex); if (!_stop) { _stop = true; _condVar.notify_all(); } for (std::thread& worker : worker_threads) worker.join(); } size_t getNumTasks() { std::unique_lock<std::mutex> lock(_mutex); return _taskQueue.size(); } ~ZYLThreadPool() { cancel(); } private: std::vector<std::thread> worker_threads; std::deque<std::function<void()>> _taskQueue; size_t _minThreads; size_t _maxThreads; std::mutex _mutex; std::condition_variable _condVar; bool _stop; }; class Test { public: Test(double devid) : _devid(devid) , _running(true) { } void start(ZYLThreadPool& threadPool) { _future = threadPool.submit(&Test::_task, this); } void stop() { { _running = false; std::unique_lock<std::mutex> lock(_mutex); if (_future.valid()) { _future.get(); lock.unlock(); _cleanupResources(); } } } private: std::mutex _mutex; double _devid; std::deque<double> _dequeue_packets; std::future<void> _future; bool _running; void _cleanupResources() { std::unique_lock<std::mutex> lock(_mutex); _dequeue_packets.clear(); } void _task() { std::unique_lock<std::mutex> lock(_mutex); while (_running) { if (_dequeue_packets.empty()) { //std::cout << "running task"<< std::endl; continue; } double packet = _dequeue_packets.front(); _dequeue_packets.pop_front(); lock.unlock(); std::cout << "running task" << std::endl; lock.lock(); } std::cout<<"task end"<<std::endl; } }; int main() { ZYLThreadPool zylThreadPool(20, 200); std::vector<std::shared_ptr<Test>> tests; std::cout<<"start all task"<<std::endl; for (int i = 0; i < 100; ++i) { auto test = std::make_shared<Test>(1.0); test->start(zylThreadPool); tests.push_back(test); } std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout<<"stop all task"<<std::endl; for (auto& test : tests) { test->stop(); } tests.clear(); std::cout<<"start 3 task"<<std::endl; for (int i = 0; i < 3; ++i) { auto test = std::make_shared<Test>(1.0); test->start(zylThreadPool); tests.push_back(test); } std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout<<"stop 3 task"<<std::endl; for (auto& test : tests) { test->stop(); } std::cout<<"stop 3 task end"<<std::endl; while(1){ std::this_thread::sleep_for(std::chrono::seconds(3)); } return 0; } 问题:上面例子出现了死锁 1.开启100个任务,能无阻塞启动,此时的线程数是97 2.停止100个任务,出现死锁,此时的线程数还是97 请修复
c20b9c765fb916af92abfd7d26d654a9
{ "intermediate": 0.3652108907699585, "beginner": 0.4432190954685211, "expert": 0.19157004356384277 }
8,786
I’m building a video game engine using C++ as the coding language and Vulkan for graphics. I am trying to set up a generic renderer using Vulkan that is flexible and will render objects based on a vector that is supplied to it. The renderer will also handle the creation of the window using GLFW and use GLM for all relevant math calls. I am using the ASSIMP library to load 3d models and animations. Here is a portion of the code: Engine.h: #pragma once #include "Window.h" #include "Renderer.h" #include "Scene.h" class Engine { public: Engine(); ~Engine(); void Run(); void Shutdown(); private: void Initialize(); void MainLoop(); void Update(float deltaTime); void Render(); Window window; Renderer renderer; Scene scene; }; Scene.h: #pragma once #include <vector> #include "GameObject.h" #include "Camera.h" #include "Renderer.h" class Scene { public: Scene(); ~Scene(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer); void Shutdown(); void AddGameObject(GameObject* gameObject); Camera& GetCamera(); float temp; private: std::vector<GameObject*> gameObjects; Camera camera; }; GameObject.h: #pragma once #include <glm/glm.hpp> #include "Mesh.h" #include "Material.h" #include "Camera.h" #include "Renderer.h" class GameObject { public: GameObject(); ~GameObject(); void Initialize(); void Update(float deltaTime); void Render(Renderer& renderer, const Camera& camera); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); void SetScale(const glm::vec3& scale); Mesh* GetMesh(); Material* GetMaterial(); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh* mesh; Material* material; bool initialized = false; void UpdateModelMatrix(); }; Mesh.h: #pragma once #include <vector> #include <vulkan/vulkan.h> #include <glm/glm.hpp> #include "BufferUtils.h" struct Vertex { glm::vec3 position; glm::vec3 color; }; class Mesh { public: Mesh(); ~Mesh(); void Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Vertex>& GetVertices() const; const std::vector<uint32_t>& GetIndices() const; VkBuffer GetVertexBuffer() const; VkBuffer GetIndexBuffer() const; void SetVertices(const std::vector<Vertex>& vertices); void SetIndices(const std::vector<uint32_t>& indices); std::vector<VkVertexInputBindingDescription> GetVertexInputBindingDescriptions() const; std::vector<VkVertexInputAttributeDescription> GetVertexInputAttributeDescriptions() const; private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" #include <stdexcept> #include <memory> // Don’t forget to include <memory> class Material { public: Material(); ~Material(); void Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); void LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device); void UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; std::shared_ptr <Shader> GetvertexShader(); std::shared_ptr <Shader> GetfragmentShader(); private: VkDevice device; std::shared_ptr <Shader> vertexShader; std::shared_ptr <Shader> fragmentShader; std::shared_ptr<Texture> texture; void CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout); VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; Texture.h: #pragma once #include <vulkan/vulkan.h> #include "stb_image.h" // Include the stb_image header #include "BufferUtils.h" #include <string> class Texture { public: Texture(); ~Texture(); void LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); VkImageView GetImageView() const; VkSampler GetSampler() const; static void Cleanup(Texture* texture); private: VkDevice device; VkImage image; VkDeviceMemory imageMemory; VkImageView imageView; VkSampler sampler; VkPhysicalDevice physicalDevice; VkCommandPool commandPool; VkQueue graphicsQueue; bool initialized = false; void CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties); void TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels); void CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels); void CreateSampler(uint32_t mipLevels); void CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height); // Additional helper functions for texture loading… }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize() { mesh = new Mesh{}; material = new Material{}; this->initialized = true; } void GameObject::Update(float deltaTime) { // Update position, rotation, scale, and other properties // Example: Rotate the object around the Y-axis rotation.y += deltaTime * glm::radians(90.0f); UpdateModelMatrix(); } void GameObject::Render(Renderer& renderer, const Camera& camera) { // Render this object using the renderer and camera VkDevice device = *renderer.GetDevice(); // Bind mesh vertex and index buffers VkBuffer vertexBuffers[] = { mesh->GetVertexBuffer() }; VkDeviceSize offsets[] = { 0 }; vkCmdBindVertexBuffers(*renderer.GetCurrentCommandBuffer(), 0, 1, vertexBuffers, offsets); vkCmdBindIndexBuffer(*renderer.GetCurrentCommandBuffer(), mesh->GetIndexBuffer(), 0, VK_INDEX_TYPE_UINT32); // Update shader uniform buffers with modelMatrix, viewMatrix and projectionMatrix transforms struct MVP { glm::mat4 model; glm::mat4 view; glm::mat4 projection; } mvp; mvp.model = modelMatrix; mvp.view = camera.GetViewMatrix(); mvp.projection = camera.GetProjectionMatrix(); // Create a new buffer to hold the MVP data temporarily VkBuffer mvpBuffer; VkDeviceMemory mvpBufferMemory; BufferUtils::CreateBuffer(device, *renderer.GetPhysicalDevice(), sizeof(MVP), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, mvpBuffer, mvpBufferMemory); // Map the MVP data into the buffer and unmap void* data = nullptr; vkMapMemory(device, mvpBufferMemory, 0, sizeof(MVP), 0, &data); memcpy(data, &mvp, sizeof(MVP)); vkUnmapMemory(device, mvpBufferMemory); // TODO: Modify your material, descriptor set, and pipeline to use this new mvpBuffer instead of // the default uniform buffer // Bind the DescriptorSet associated with the material VkDescriptorSet descriptorSet = material->GetDescriptorSet(); material->UpdateBufferBinding(descriptorSet, mvpBuffer, device, sizeof(MVP)); renderer.CreateGraphicsPipeline(mesh, material); vkCmdBindPipeline(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, renderer.GetPipeline().get()->GetPipeline()); vkCmdBindDescriptorSets(*renderer.GetCurrentCommandBuffer(), VK_PIPELINE_BIND_POINT_GRAPHICS, material->GetPipelineLayout(), 0, 1, &descriptorSet, 0, nullptr); // Call vkCmdDrawIndexed() uint32_t numIndices = static_cast<uint32_t>(mesh->GetIndices().size()); vkCmdDrawIndexed(*renderer.GetCurrentCommandBuffer(), numIndices, 1, 0, 0, 0); // Cleanup the temporary buffer vkDestroyBuffer(device, mvpBuffer, nullptr); vkFreeMemory(device, mvpBufferMemory, nullptr); } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) delete mesh; delete material; this->initialized = false; } void GameObject::SetPosition(const glm::vec3& position) { this->position = position; UpdateModelMatrix(); } void GameObject::SetRotation(const glm::vec3& rotation) { this->rotation = rotation; UpdateModelMatrix(); } void GameObject::SetScale(const glm::vec3& scale) { this->scale = scale; UpdateModelMatrix(); } void GameObject::UpdateModelMatrix() { modelMatrix = glm::mat4(1.0f); modelMatrix = glm::translate(modelMatrix, position); modelMatrix = glm::rotate(modelMatrix, rotation.x, glm::vec3(1.0f, 0.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.y, glm::vec3(0.0f, 1.0f, 0.0f)); modelMatrix = glm::rotate(modelMatrix, rotation.z, glm::vec3(0.0f, 0.0f, 1.0f)); modelMatrix = glm::scale(modelMatrix, scale); } Mesh* GameObject::GetMesh() { return mesh; } Material* GameObject::GetMaterial() { return material; } Mesh.cpp: #include "Mesh.h" Mesh::Mesh() : device(VK_NULL_HANDLE), vertexBuffer(VK_NULL_HANDLE), vertexBufferMemory(VK_NULL_HANDLE), indexBuffer(VK_NULL_HANDLE), indexBufferMemory(VK_NULL_HANDLE) { } Mesh::~Mesh() { Cleanup(); } void Mesh::Initialize(std::vector<Vertex> vertices, std::vector<uint32_t> indices, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->vertices = vertices; this->indices = indices; this->device = device; Initialize(device, physicalDevice, commandPool, graphicsQueue); // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … } void Mesh::Initialize(VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Create vertex buffer and index buffer // (assuming you have helper functions CreateBuffer and CopyBuffer) // … // Declare and initialize stagingBuffer and bufferSize here VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; VkDeviceSize bufferSize = sizeof(vertices[0]) * vertices.size(); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); void* data; vkMapMemory(device, stagingBufferMemory, 0, bufferSize, 0, &data); memcpy(data, vertices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, vertexBuffer, vertexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingBuffer, vertexBuffer, bufferSize); vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); bufferSize = sizeof(indices[0]) * indices.size(); VkBuffer stagingIndexBuffer; VkDeviceMemory stagingIndexBufferMemory; BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingIndexBuffer, stagingIndexBufferMemory); vkMapMemory(device, stagingIndexBufferMemory, 0, bufferSize, 0, &data); memcpy(data, indices.data(), (size_t)bufferSize); vkUnmapMemory(device, stagingIndexBufferMemory); BufferUtils::CreateBuffer(device, physicalDevice, bufferSize, VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, indexBuffer, indexBufferMemory); BufferUtils::CopyBuffer(device, commandPool, graphicsQueue, stagingIndexBuffer, indexBuffer, bufferSize); vkDestroyBuffer(device, stagingIndexBuffer, nullptr); vkFreeMemory(device, stagingIndexBufferMemory, nullptr); } void Mesh::Cleanup() { if (device != VK_NULL_HANDLE) { if (vertexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, vertexBuffer, nullptr); vkFreeMemory(device, vertexBufferMemory, nullptr); vertexBuffer = VK_NULL_HANDLE; vertexBufferMemory = VK_NULL_HANDLE; } if (indexBuffer != VK_NULL_HANDLE) { vkDestroyBuffer(device, indexBuffer, nullptr); vkFreeMemory(device, indexBufferMemory, nullptr); indexBuffer = VK_NULL_HANDLE; indexBufferMemory = VK_NULL_HANDLE; } } } const std::vector<Vertex>& Mesh::GetVertices() const { return vertices; } const std::vector<uint32_t>& Mesh::GetIndices() const { return indices; } VkBuffer Mesh::GetVertexBuffer() const { return vertexBuffer; } VkBuffer Mesh::GetIndexBuffer() const { return indexBuffer; } void Mesh::SetVertices(const std::vector<Vertex>& vertices) { this->vertices = vertices; } void Mesh::SetIndices(const std::vector<uint32_t>& indices) { this->indices = indices; } std::vector<VkVertexInputBindingDescription> Mesh::GetVertexInputBindingDescriptions() const { std::vector<VkVertexInputBindingDescription> bindingDescriptions(1); bindingDescriptions[0].binding = 0; bindingDescriptions[0].stride = sizeof(Vertex); bindingDescriptions[0].inputRate = VK_VERTEX_INPUT_RATE_VERTEX; return bindingDescriptions; } std::vector<VkVertexInputAttributeDescription> Mesh::GetVertexInputAttributeDescriptions() const { std::vector<VkVertexInputAttributeDescription> attributeDescriptions(2); // Position attribute attributeDescriptions[0].binding = 0; attributeDescriptions[0].location = 0; attributeDescriptions[0].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[0].offset = offsetof(Vertex, position); // Color attribute attributeDescriptions[1].binding = 0; attributeDescriptions[1].location = 1; attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT; attributeDescriptions[1].offset = offsetof(Vertex, color); return attributeDescriptions; } Material.cpp: #include "Material.h" Material::Material() : device(VK_NULL_HANDLE), descriptorSet(VK_NULL_HANDLE), pipelineLayout(VK_NULL_HANDLE) { } Material::~Material() { Cleanup(); } void Material::Initialize(const std::string& vertShaderPath, const std::string& fragShaderPath, const std::string& texturePath, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; // Load shaders and texture LoadTexture(texturePath, device, physicalDevice, commandPool, graphicsQueue); LoadShaders(vertShaderPath, fragShaderPath, device); // Create descriptor set and pipeline layout CreateDescriptorSet(descriptorSetLayout, descriptorPool); CreatePipelineLayout(descriptorSetLayout); } void Material::CreateDescriptorSet(VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { VkDescriptorSetAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO; allocInfo.descriptorPool = descriptorPool; allocInfo.descriptorSetCount = 1; allocInfo.pSetLayouts = &descriptorSetLayout; if (vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate descriptor sets!"); } VkDescriptorImageInfo imageInfo{}; imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; imageInfo.imageView = texture->GetImageView(); imageInfo.sampler = texture->GetSampler(); VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; descriptorWrite.descriptorCount = 1; descriptorWrite.pImageInfo = &imageInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } void Material::CreatePipelineLayout(VkDescriptorSetLayout descriptorSetLayout) { VkPipelineLayoutCreateInfo pipelineLayoutInfo{}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = 1; pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout; if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { throw std::runtime_error("Failed to create pipeline layout!"); } } void Material::Cleanup() { // Clean up resources, if necessary // (depending on how Shader and Texture resources are managed) } VkDescriptorSet Material::GetDescriptorSet() const { return descriptorSet; } VkPipelineLayout Material::GetPipelineLayout() const { return pipelineLayout; } std::shared_ptr <Shader> Material::GetvertexShader() { return vertexShader; } std::shared_ptr <Shader> Material::GetfragmentShader() { return fragmentShader; } void Material::LoadTexture(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { texture = std::shared_ptr<Texture>(new Texture{}, Texture::Cleanup); // Create a new Texture using shared_ptr texture->LoadFromFile(filename, device, physicalDevice, commandPool, graphicsQueue); } void Material::LoadShaders(const std::string& vertFilename, const std::string& fragFilename, VkDevice device) { vertexShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup); fragmentShader = std::shared_ptr<Shader>(new Shader, Shader::Cleanup); vertexShader->LoadFromFile(vertFilename, device, VK_SHADER_STAGE_VERTEX_BIT); fragmentShader->LoadFromFile(fragFilename, device, VK_SHADER_STAGE_FRAGMENT_BIT); } void Material::UpdateBufferBinding(VkDescriptorSet descriptorSet, VkBuffer newBuffer, VkDevice device, VkDeviceSize devicesize) { VkDescriptorBufferInfo bufferInfo{}; bufferInfo.buffer = newBuffer; bufferInfo.offset = 0; bufferInfo.range = devicesize; VkWriteDescriptorSet descriptorWrite{}; descriptorWrite.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; descriptorWrite.dstSet = descriptorSet; descriptorWrite.dstBinding = 0; descriptorWrite.dstArrayElement = 0; descriptorWrite.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; descriptorWrite.descriptorCount = 1; descriptorWrite.pBufferInfo = &bufferInfo; vkUpdateDescriptorSets(device, 1, &descriptorWrite, 0, nullptr); } Vertex Shader: #version 450 layout(binding = 0) uniform UniformBufferObject { mat4 model; mat4 view; mat4 proj; } ubo; layout(location = 0) in vec3 inPosition; layout(location = 1) in vec3 inColor; layout(location = 0) out vec3 fragColor; void main() { gl_Position = ubo.proj * ubo.view * ubo.model * vec4(inPosition, 1.0); fragColor = inColor; } Fragment Shader: #version 450 layout(binding = 1) uniform sampler2D texSampler; layout(location = 0) in vec3 fragColor; layout(location = 0) out vec4 outColor; void main() { outColor = vec4(1,0,1,1); } Engine.cpp: #include "Engine.h" #include "Terrain.h" #include <iostream> Engine::Engine() { Initialize(); } Engine::~Engine() { Shutdown(); } void Engine::Run() { MainLoop(); } void Engine::Initialize() { // Initialize window, renderer, and scene window.Initialize(); renderer.Initialize(window.GetWindow()); scene.Initialize(); VkDescriptorSetLayout descriptorSetLayout = renderer.CreateDescriptorSetLayout(); VkDescriptorPool descriptorPool = renderer.CreateDescriptorPool(1); // Assuming only one terrain object Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue()); terrain.GenerateTerrain(descriptorSetLayout, descriptorPool); //scene.AddGameObject(terrain.GetTerrainObject()); float deltaTime = window.GetDeltaTime(); } void Engine::MainLoop() { while (!window.ShouldClose()) { window.PollEvents(); float deltaTime = window.GetDeltaTime(); Update(deltaTime); Render(); } } void Engine::Update(float deltaTime) { scene.Update(deltaTime); } void Engine::Render() { renderer.BeginFrame(); scene.Render(renderer); renderer.EndFrame(); } void Engine::Shutdown() { // Clean up resources in reverse order scene.Shutdown(); renderer.Shutdown(); window.Shutdown(); } Based on the above code, please write some code to generate a simple square tile GameObject. This code is to inserted into the Engine::Initialize function where it can be added to the scene for rendering. The intent behind this is to allow for debugging the engine with a very simple object.
6fc688f3915e8cba9b5f8837bbdd6e41
{ "intermediate": 0.3506416082382202, "beginner": 0.3420967161655426, "expert": 0.30726170539855957 }
8,787
is it possible to make that rgb opacity value to slowly randomly change in range of 0.02 to 0.05 with some super small step size?: function fractal(x, y, size) { if (size < 1) return; ctx.fillStyle = 'rgba(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ', 0.02)'; ctx.fillRect(x, y, size, size); const newSize = size / 3; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) continue; fractal(x + newSize * i, y + newSize * j, newSize); } } }without setIntervalrequestAnimationFramesetTimeout?
8cd0dcfd48fe280dab0d06cf953d74e8
{ "intermediate": 0.45607849955558777, "beginner": 0.3346671760082245, "expert": 0.20925436913967133 }
8,788
is it possible to make that rgb opacity value to slowly randomly change in range of 0.02 to 0.05 with some super small step size?: function fractal(x, y, size) { if (size < 1) return; ctx.fillStyle = 'rgba(' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ',' + Math.floor(Math.random() * 256) + ', 0.02)'; ctx.fillRect(x, y, size, size); const newSize = size / 3; for (let i = 0; i < 3; i++) { for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) continue; fractal(x + newSize * i, y + newSize * j, newSize); } } }
2c2f83cec73a75f777a794fb79a2230e
{ "intermediate": 0.3707314729690552, "beginner": 0.3315519094467163, "expert": 0.2977166473865509 }
8,789
почему размер точек в объекте points одинаковый, хотя должен быть разный у каждой точки? не переписывай весь код, только там, где нужно поправить import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; const shaderCode = document.getElementById("fragShader").innerHTML; THREE.ImageUtils.crossOrigin = ''; const texture = new THREE.TextureLoader().load('gradient-2.png'); const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry; const texturePoint = new THREE.TextureLoader().load('texture3.png'); const sizeVariation = 1.1; const geometryPoint = new THREE.BufferGeometry(); const positions = geometry.getAttribute('position').array; const materialPoint = new THREE.PointsMaterial({ sizeAttenuation: false, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. }); const sizes = new Float32Array(positions.length / 3); for (let i = 0; i < sizes.length; i++) { sizes[i] = 0.01 + Math.random() * 0.04; // каждый размер будет случайным числом от 0 до 1 } const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = [...randomPosition]; let increment = 0.002; geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); const points = new THREE.Points(geometryPoint, materialPoint); const geometryPoints = points.geometry; geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const sizesPoints = geometryPoints.attributes.size.array; for (let i = 0; i < sizesPoints.length; i++) { console.log('Размер точки', i, ':', sizesPoints[i]); } geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); } }); camera.position.z = 3; // ________________________________________________________________________________________________________________________________________________ // Создаем переменные для точки и радиуса let point = new THREE.Vector3(0, 0, 0); let radius = 1; // Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); } // Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0; // Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); } // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); // scene.add(pointMesh); // ________________________________________________________________________________________________________________________________________________ let uniforms = { mouseCoord: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} }; const planeGeometry = new THREE.PlaneGeometry(1000, 1000); const planeMaterial = new THREE.ShaderMaterial({ uniforms:uniforms, fragmentShader:shaderCode, side: THREE.DoubleSide }); const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); scene.add(planeMesh); planeMesh.position.set(0, 0, -85); // controls.addEventListener('change', function() { // planeMesh.rotation.copy(camera.rotation); // }); const group = new THREE.Group(); // создаем новую группу group.add(planeMesh); // добавляем куб в группу scene.add(group); let targetX = 0; let targetY = 0; let currentX = 0; let currentY = 0; function update() { requestAnimationFrame(update); const diffX = targetX - currentX; const diffY = targetY - currentY; const distance = Math.sqrt(diffX * diffX + diffY * diffY); const speed = distance / 10; if (distance < 1.0) { currentX = targetX; currentY = targetY; } else { currentX += speed * diffX / distance; currentY += speed * diffY / distance; } } update(); document.addEventListener('mousemove', (event) => { targetX = event.clientX; targetY = event.clientY; uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; }); group.position.set(camera.position.x, camera.position.y, camera.position.z); function animate() { requestAnimationFrame(animate); animatePoint(); group.rotation.x = camera.rotation.x; group.rotation.y = camera.rotation.y; group.rotation.z = camera.rotation.z; controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate(); });
2aab4c4ff31c3e21add211fa2ba5b100
{ "intermediate": 0.24290786683559418, "beginner": 0.5652881860733032, "expert": 0.19180390238761902 }
8,790
import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt date = dt.datetime.now().strftime(“%m/%d/%Y %H:%M:%S”) print(date) url = “https://api.binance.com/api/v1/time” t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = ‘’ API_SECRET = ‘’ client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = ‘SELL’ POSITION_SIDE_LONG = ‘BUY’ symbol = ‘BTCUSDT’ quantity = 1 order_type = ‘MARKET’ leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): try: frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+‘min ago UTC’)) frame = frame.iloc[:60,:6] frame.columns = [‘Time’,‘Open’,‘High’,‘Low’,‘Close’,‘Volume’] frame = frame.set_index(‘Time’) today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit=‘ms’).tz_localize(‘UTC’).tz_convert(‘Etc/GMT+3’).strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame except Exception as e: print(f"Error getting minute data: {str(e)}“) return None df = getminutedata(‘BTCUSDT’, ‘1m’, ‘44640’) def signal_generator(df): try: open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return ‘sell’ # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return ‘buy’ # No clear pattern else: return ‘’ except Exception as e: print(f"Error generating signal: {str(e)}”) return ‘’ def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): try: max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x[‘balance’] for x in account_balance if x[‘asset’] == ‘USDT’][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p[‘positionSide’] == ‘LONG’: long_position = p elif p[‘positionSide’] == ‘SHORT’: short_position = p if long_position is not None and short_position is not None: print(“Multiple positions found. Closing both positions.”) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position[‘positionAmt’], reduceOnly=True ) time.sleep(1) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position[‘positionAmt’], reduceOnly=True ) print(“Both positions closed.”) return if signal == ‘buy’: position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == ‘sell’: position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print(“Invalid signal. No order placed.”) return order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position[‘positionAmt’]))) if opposite_position[‘positionSide’] != position_side: print(“Opposite position found. Closing position before placing order.”) client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position[‘positionSide’] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True ) time.sleep(1) order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == ‘buy’ else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, leverage=leverage ) print(f"Placed {signal} order with order ID {order[‘orderId’]} and quantity {order_quantity}“) time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order[‘avgPrice’] * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == ‘sell’ else order[‘avgPrice’] * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order[‘avgPrice’] * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == ‘buy’ else order[‘avgPrice’] * (1 - TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == ‘buy’ else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side ) client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == ‘buy’ else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}”) time.sleep(1) except Exception as e: print(f"Error executing order: {str(e)}“) while True: try: current_time = dt.datetime.now().strftime(”%Y-%m-%d %H:%M:%S") df = getminutedata(‘symbol’, ‘1m’, ‘44640’) # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}“) if current_signal: order_execution(‘symbol’, current_signal, max_trade_quantity_percentage, leverage) time.sleep(1) # Add a delay of 1 second except Exception as e: print(f"Unknown error: {str(e)}”) time.sleep(1) # Wait 1 minute before trying again Is this code is right ?
9ad3c83d344745e19492421daede42ea
{ "intermediate": 0.3309023678302765, "beginner": 0.44207119941711426, "expert": 0.22702644765377045 }
8,791
#include <iostream> #include <thread> #include <deque> #include <functional> #include <future> #include <mutex> #include <condition_variable> #include <vector> #include <memory> #include <chrono> class ZYLThreadPool { public: ZYLThreadPool(size_t minThreads = 20, size_t maxThreads = 200) : _minThreads(minThreads) , _maxThreads(maxThreads) , _stop(false) { worker_threads.reserve(_maxThreads); for (size_t i = 0; i < _minThreads; ++i) { create_thread(); } } void create_thread() { worker_threads.emplace_back([this] { for (;;) { std::function<void()> task; { std::unique_lock<std::mutex> lock(this->_mutex); this->_condVar.wait(lock, [this] { return this->_stop || !this->_taskQueue.empty(); }); if (this->_stop && this->_taskQueue.empty()) return; task = std::move(this->_taskQueue.front()); this->_taskQueue.pop_front(); } task(); } }); } template <typename F, typename... Args> auto submit(F&& f, Args&&... args)-> std::future<typename std::result_of<F(Args...)>::type> { using return_type = typename std::result_of<F(Args...)>::type; auto task = std::make_shared<std::packaged_task<return_type()>>(std::bind(std::forward<F>(f), std::forward<Args>(args)...)); std::future<return_type> result = task->get_future(); { std::unique_lock<std::mutex> lock(_mutex); if (_stop) { throw std::runtime_error("Submit on stopped ZYLThreadPool"); } if (_taskQueue.size() >= worker_threads.size() && worker_threads.size() < _maxThreads) { create_thread(); } _taskQueue.emplace_back([task] { (*task)(); }); } _condVar.notify_one(); return result; } void cancel() { std::unique_lock<std::mutex> lock(_mutex); if (!_stop) { _stop = true; _condVar.notify_all(); } for (std::thread& worker : worker_threads) worker.join(); } size_t getNumTasks() { std::unique_lock<std::mutex> lock(_mutex); return _taskQueue.size(); } ~ZYLThreadPool() { cancel(); } private: std::vector<std::thread> worker_threads; std::deque<std::function<void()>> _taskQueue; size_t _minThreads; size_t _maxThreads; std::mutex _mutex; std::condition_variable _condVar; bool _stop; }; class Test { public: Test(double devid) : _devid(devid) , _running(true) { } void start(ZYLThreadPool& threadPool) { _future = threadPool.submit(&Test::_task, this); } void stop() { { _running = false; std::unique_lock<std::mutex> lock(_mutex); if (_future.valid()) { _future.get(); lock.unlock(); _cleanupResources(); } } } private: std::mutex _mutex; double _devid; std::deque<double> _dequeue_packets; std::future<void> _future; bool _running; void _cleanupResources() { std::unique_lock<std::mutex> lock(_mutex); _dequeue_packets.clear(); } void _task() { std::unique_lock<std::mutex> lock(_mutex); while (_running) { if (_dequeue_packets.empty()) { //std::cout << "running task"<< std::endl; continue; } double packet = _dequeue_packets.front(); _dequeue_packets.pop_front(); lock.unlock(); std::cout << "running task" << std::endl; lock.lock(); } std::cout<<"task end"<<std::endl; } }; int main() { ZYLThreadPool zylThreadPool(20, 200); std::vector<std::shared_ptr<Test>> tests; std::cout<<"start all task"<<std::endl; for (int i = 0; i < 100; ++i) { auto test = std::make_shared<Test>(1.0); test->start(zylThreadPool); tests.push_back(test); } std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout<<"stop all task"<<std::endl; for (auto& test : tests) { test->stop(); } tests.clear(); while(1){ std::this_thread::sleep_for(std::chrono::seconds(3)); } return 0; } 问题:上面例子出现了死锁 1.开启100个任务,能无阻塞启动,此时的线程数是97 2.停止100个任务,出现死锁,此时的线程数还是97,在停止第一个任务的时候就阻塞住了 3.加日志打印,经过linux服务器测试加日志打印,是在stop函数调用_future.get();这里阻塞住了 请修复
3ee00932549b227d0a9a96c8bf70cea9
{ "intermediate": 0.3652108907699585, "beginner": 0.4432190954685211, "expert": 0.19157004356384277 }
8,792
Create classes with business logic (pydantic) for this @router.post('', status_code=status.HTTP_201_CREATED, summary='Create a ceiling type', response_description='The created ceiling type', ) async def create(obj: CeilingTypeCreateDto) -> CeilingTypeReadDto: obj.verify() orm_obj = CeilingType(**obj.dict()) obj = postgresql_manager.create(CeilingType, orm_obj) return obj @router.get('', summary='Read all ceiling types', response_description='All ceiling types', ) async def read_all() -> list[CeilingTypeReadDto]: objs = postgresql_manager.read_all(CeilingType) return objs @router.get('/{id}', summary='Read ceiling type', response_description='The ceiling type', ) async def read(id: uuid.UUID) -> CeilingTypeReadDto: obj = postgresql_manager.read(CeilingType, id) return obj @router.put('/{id}', status_code=status.HTTP_201_CREATED, summary='Update ceiling type', response_description='The updated ceiling type', ) async def update(id: uuid.UUID, obj: CeilingTypeUpdateDto) -> CeilingTypeReadDto: obj.verify() updates = obj.dict() obj = postgresql_manager.update(CeilingType, id, updates) return obj @router.delete('/{id}', summary='Delete ceiling type', response_description='The deleted ceiling type', ) async def delete(id: uuid.UUID) -> CeilingTypeReadDto: obj = postgresql_manager.delete(CeilingType, id) return obj
0741be598d7702fb1535378a004102ed
{ "intermediate": 0.4071936011314392, "beginner": 0.4330843687057495, "expert": 0.1597220003604889 }
8,793
can you write me a project following the tasks bellow 1. PROBLEM DEFINITION Select a problem you are interested in and find a real dataset that you can apply classification or regression to. In your own words, describe the importance of the problem, define the problem in terms of the input and output variable, describe the basics statistics of the data (count and type of variables, mean / std of values). Draw histograms of main features. Compute the correlation between input/ output variables. 2. APPLY SCIKITLEARN MODEL Divide the data into training and testing. Do preprocessing if necessary. Train a scikit-learn model on the training set, and evaluate its performance on the testing set. Use at least 3 evaluation metrics for comparison. 3. IMPROVE YOUR MODEL’S PERFORMANCE Now your goal is to improve your model’s performance. There are many ways to do so, here are some suggestions: 1. Try different hyperparameters during training 2. If data has many features, do dimensionality reduction or feature selection 3. Clean / preprocess the data 4. OPTION 1: 1. Choose one of the four algorithms - KNN, DT,NB or LR - to implement from scratch. College of Computer Science and Engineering Department of Computer Science and Artificial Intelligence CCAI-312: Pattern Recognition IMPLEMENT MODEL USING PYTHON 2. Implement the chosen algorithm from scratch using Python. 3. Train and test your implemented algorithm on the dataset and evaluate it using evaluation metrics used in task 2 4. Compare the performance of your implemented algorithm with the Scikit-Learn model and present your findings in a report. 5. Include a discussion on the differences in performance between the implemented algorithm and Scikit-Learn model and an explanation of why these differences may have occurred. 4. OPTION 2: TRAIN A NEW MODEL 1. Choose a machine learning model that is not covered in class but is relevant to your field of study or area of interest. 2. Study and explain the new model to gain an understanding of its principles, strengths, weaknesses, and applications. 3. Train and test the performance of the new model and evaluate it using evaluation metrics used in task 2 4. Compare the performance of the new model with the Scikit-Learn model and present your findings in a report. 5. Discuss the strengths and weaknesses of both models and explain why the new model may be useful in certain situations. Project Deliverables: Your project will be worth 10 % of your final class grade, and will have 2 deliverables: 1. Final Report and Code (June 1) You must submit a written report on your project, structured as a standard academic conference paper, and the complete, documented source code for it. This should be a 4-5 pages short report (including cover page). It should consist of:  Cover page: Group member names, Project title, …  Introduction  Problem Description  Data Description  Method  Experiment and results (Please include visualizations)  Discussion  Conclusion  References
84bc6259a0d3f6d52ec2eeb81ba58343
{ "intermediate": 0.31755656003952026, "beginner": 0.3087127208709717, "expert": 0.37373068928718567 }
8,794
hello
ad84e9d4cb7b0267736d4be9e8623e6b
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
8,795
how to hook wsarecv and getqueuedcompletionstatus
f3046de40e0d32878be2921bd759f28b
{ "intermediate": 0.35465899109840393, "beginner": 0.09299426525831223, "expert": 0.5523467063903809 }
8,796
import time from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys def get_token_info(token_symbol): chrome_options = Options() chrome_options.add_argument("–headless") # Update the path below to the actual path to your WebDriver executable service = Service( executable_path="C:\\Users\\AshotxXx\\PycharmProjects\\Parcing\\pythonProject\\ChromeDriver\\chromedriver.exe") driver = webdriver.Chrome(service=service, options=chrome_options) driver.get("https://moonarch.app/") try: time.sleep(1) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'form-control'))) # Find the search box and interact with it search_box = driver.find_element(By.CLASS_NAME, 'form-control') search_box.click() search_box.send_keys(token_symbol) search_box.send_keys(Keys.ENTER) time.sleep(1) # Wait for the token info and infocard elements to appear after entering the symbol WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "token-info"))) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "infocard"))) # Extract information using BeautifulSoup soup = BeautifulSoup(driver.page_source, "html.parser") token_info_element = soup.find("div", class_="token-info") infocard_element = soup.find("div", class_="infocard") check_alert_element = soup.find("div", class_="token-check-message check-alert") check_warning_element = soup.find("div", class_="token-check-message check-warning") check_info_element = soup.find("div", class_="token-check-message check-info") not_verified_element = soup.find("div", class_="not-verified") check_alert_status = "Yes" if check_alert_element else "None" check_warning_status = "Yes" if check_warning_element else "None" check_info_status = "Yes" if check_info_element else "None" not_verified_status = "Yes" if not_verified_element else "None" if token_info_element and infocard_element: token_name_element = token_info_element.find("span", class_="name") token_symbol_element = token_info_element.find("span", class_="symbol") info_items = infocard_element.find_all("li") if token_name_element and token_symbol_element and len(info_items) >= 7: token_name = token_name_element.text.strip() token_symbol = token_symbol_element.text.strip() price = info_items[0].find("span", class_="value").text.strip() max_supply = info_items[1].find("span", class_="value").text.strip() market_cap = info_items[2].find("span", class_="value").text.strip() liquidity = info_items[3].find("span", class_="value").text.strip() liq_mc = info_items[4].find("span", class_="value").text.strip() token_age = info_items[6].find("span", class_="value").text.strip() driver.quit() return { "name": token_name, "symbol": token_symbol, "price": price, "max_supply": max_supply, "market_cap": market_cap, "liquidity": liquidity, "liq_mc": liq_mc, "token_age": token_age, "check_alert": check_alert_status, "check_warning": check_warning_status, "check_info": check_info_status, "not_verified": not_verified_status } else: driver.quit() error_info = f"token_name_element: {token_name_element}, token_symbol_element: {token_symbol_element}, info_items count: {len(info_items)}" return {"error": f"Failed to find the required info items or name and.symbol. Error_info: {error_info}"} else: driver.quit() return {"error": f"Failed to find the required elements for token_info_element ({token_info_element}) and infocard_element ({infocard_element})."} except Exception as e: driver.quit() return {"error": f"Failed to find the required elements or error occurred: {e}"} token_symbol = "0x0E481Fa712201f61dAf97017138Efaa69e2A3df3" print(get_token_info(token_symbol)) Change the code above so that you can make many consecutive requests
5673209207fa1a8565dd306d2bddc9ec
{ "intermediate": 0.33035027980804443, "beginner": 0.488815039396286, "expert": 0.18083466589450836 }
8,797
I'm making fastapi App, using postgresql. could you prepare an abstract class for business logic with an interface (CRUD)
4aa31dbf6dc42c20d9713fea8e8ce381
{ "intermediate": 0.5542730093002319, "beginner": 0.3653009235858917, "expert": 0.08042598515748978 }
8,798
how do i make a nodejs app that can trade using uniswap v3 sdk
65214f83f6fb458be50f02cd7d9d2a52
{ "intermediate": 0.6227966547012329, "beginner": 0.18125569820404053, "expert": 0.19594760239124298 }
8,799
Severity Code Description Project File Line Suppression State Error CS0120 An object reference is required for the non-static field, method, or property 'ExemptionDao.GetExemptionNamesByIds(IList<int>)'
e275cd76c058ade9437c2adbf9b36c56
{ "intermediate": 0.5099232196807861, "beginner": 0.22141504287719727, "expert": 0.268661767244339 }
8,800
How i rank my profile on upwork in 2023. my niche is data entry. atleast 5000 words
f865d0db78e7fe11bb0f9c9bb30f7980
{ "intermediate": 0.3655456602573395, "beginner": 0.3798542320728302, "expert": 0.2546001374721527 }
8,801
The Sub CheckServiceI() works and retrieves the values required. However, it takes about 8 minutes to complete. I believe that the coding may be doing something that is not required. Looking at the comments in the codeing that start'xxxx, I think the sequence should be as below. 'Declare variables 'Set variables 'Find the column with the name "I" 'If the cell value in column I is not blank, get the worksheet name 'Check if the worksheet exists 'Get the last row in column B of the named worksheet 'Loop through the rows in column B of the named worksheet 'If the value "Service" is found in column B, get the value from column H 'If the value "Service" is not found, set the value in column J to "NA" 'Go to the next worksheet I have included the full code below with its comments and how it is currently written. Will my sequence as described in the comments above still allow the code to achieve the desired result, and will it make it faster. Sub CheckServiceI() Application.ScreenUpdating = False Application.EnableEvents = False 'Declare variables Dim wsStartPage As Worksheet Dim wsNamedPage As Worksheet Dim iColumnI As Long Dim lastRow As Long Dim i As Long, j As Long Dim strWorksheetName As String Dim iLastRow As Long Dim bWorksheetExists As Boolean 'Set variables Set wsStartPage = ThisWorkbook.Sheets("Start Page") 'Find the column with the name "I" iColumnI = wsStartPage.Columns("I").Find(What:="I", LookIn:=xlFormulas, _ LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Column 'Loop through the rows in column B of the named worksheet For i = 5 To 34 strWorksheetName = "" bWorksheetExists = False 'If the cell value in column I is not blank, get the worksheet name If wsStartPage.Cells(i, iColumnI).Value <> "" Then strWorksheetName = wsStartPage.Cells(i, iColumnI).Value bWorksheetExists = WorksheetExists(strWorksheetName) End If 'Check if the worksheet exists If bWorksheetExists Then Set wsNamedPage = ThisWorkbook.Sheets(strWorksheetName) 'Get the last row in column B of the named worksheet iLastRow = wsNamedPage.Columns("B").Rows.count 'Loop through the rows in column B of the named worksheet For j = iLastRow To 5 Step -1 'If the value "Service" is found in column B, get the value from column H If LCase(Trim(wsNamedPage.Range("B" & j).Value)) = "service" Then wsStartPage.Range("J" & i).Value = wsNamedPage.Range("H" & j).Value2 GoTo NextSheet End If Next j 'If the value "Service" is not found, set the value in column J to "NA" wsStartPage.Range("J" & i).Value = "NA" End If 'Go to the next worksheet NextSheet: Next i Application.ScreenUpdating = True Application.EnableEvents = True End Sub Function WorksheetExists(shtName As String) As Boolean On Error Resume Next WorksheetExists = Not ThisWorkbook.Sheets(shtName) Is Nothing On Error GoTo 0 End Function
a8f8c6d5393013359253a376dae0b834
{ "intermediate": 0.3435129225254059, "beginner": 0.371045857667923, "expert": 0.28544116020202637 }
8,802
java code to plot an x,y chart with scale x=10 years and y= 1000$ , plot 100 random values, spread ove 10 years, store all in hashtable , key = time and value is $
7938ce5c03852f826c0c6b78dee75491
{ "intermediate": 0.49412599205970764, "beginner": 0.20679925382137299, "expert": 0.2990747094154358 }
8,803
I would like to have the map of Europe. On the map I want to have nodes that they are related to specific data. When those points are clicked, they need to present a popout window that previews the data and gives an option to redirect to the detailed data page
89372fe88a92195f2985691a83f0116e
{ "intermediate": 0.40960919857025146, "beginner": 0.1874457448720932, "expert": 0.40294507145881653 }
8,804
now that this "Future<void> fetchSeances() async { try { final response = await http.get( Uri.parse('$endpointUrl/listermesseancescejour'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ${await Login.LoginLogic.getToken()}', }, ); if (response.statusCode == 200) { final List<dynamic> seancesJson = jsonDecode(response.body); setState(() { seances = seancesJson.map((json) { print('seanceId value: ${json['id']}'); // Print seanceId value return Seance.fromJson(json); }).toList(); if (seances.isNotEmpty) { selectedSeance = seances[0]; fetchEtudiantUsernamesByClasseId(selectedSeance!.classeId); } }); } else { throw Exception('Failed to fetch seances'); } } catch (e) { throw Exception('Error fetching seances: $e'); } }" is correctly retrieved "I/flutter ( 4399): seanceId value: 31" I want it retrieved in the presence object sent in the list bt this "Future<void> createPresenceList(List<Presence> presenceList) async { try { final payload = presenceList .map((presence) => presence.toJson()) .toList(); print('Request Payload: $payload'); final response = await http.post( Uri.parse('$endpointUrl/creerfichepresence'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ${await Login.LoginLogic.getToken()}', }, body: jsonEncode(payload), ); print('Response Status Code: ${response.statusCode}'); if (response.statusCode == 200) { // Presence list created successfully // Handle the response if needed } else { throw Exception('Failed to create presence list'); } } catch (e) { throw Exception('Error creating presence list: $e'); } }" please update this "class Seance { final int? seanceId; final String dateSeance; final String tempsDebut; final String tempsFin; final int classeId; final int enseignantId; final int matiereAttribueeId; Seance({ this.seanceId, required this.dateSeance, required this.tempsDebut, required this.tempsFin, required this.classeId, required this.enseignantId, required this.matiereAttribueeId, }); factory Seance.fromJson(Map<String, dynamic> json) { return Seance( seanceId: json['seanceId'], // Remove null coalescing operator dateSeance: json['dateSeance'], tempsDebut: json['tempsDebut'], tempsFin: json['tempsFin'], classeId: json['classeId'], enseignantId: json['enseignantId'], matiereAttribueeId: json['matiereAttribueeId'], ); } @override String toString() { return 'Seance(seanceId: $seanceId, dateSeance: $dateSeance, tempsDebut: $tempsDebut, tempsFin: $tempsFin, classeId: $classeId,' ' enseignantId: $enseignantId, matiereAttribueeId: $matiereAttribueeId)'; } } class Etudiant { final int etudiantId; final String username; bool isPresent; bool isAbsent; Etudiant({ required this.etudiantId, required this.username, this.isPresent = false, this.isAbsent = false, }); } class Presence { final bool present; final int etudiantId; final int seanceId; Presence({ required this.present, required this.etudiantId, required this.seanceId, }); Map<String, dynamic> toJson() { return { 'present': present, 'etudiantId': etudiantId.toString(), // Convert to String 'seanceId': seanceId.toString(), // Convert to String }; } } class MarquerManuellementPresence extends StatefulWidget { @override _MarquerManuellementPresenceState createState() => _MarquerManuellementPresenceState(); } class _MarquerManuellementPresenceState extends State<MarquerManuellementPresence> { List<Seance> seances = []; List<Etudiant> etudiants = []; Seance? selectedSeance; bool isButtonEnabled = false; @override void initState() { super.initState(); fetchSeances(); } Future<void> fetchSeances() async { try { final response = await http.get( Uri.parse('$endpointUrl/listermesseancescejour'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ${await Login.LoginLogic.getToken()}', }, ); if (response.statusCode == 200) { final List<dynamic> seancesJson = jsonDecode(response.body); setState(() { seances = seancesJson.map((json) { print('seanceId value: ${json['id']}'); // Print seanceId value return Seance.fromJson(json); }).toList(); if (seances.isNotEmpty) { selectedSeance = seances[0]; fetchEtudiantUsernamesByClasseId(selectedSeance!.classeId); } }); } else { throw Exception('Failed to fetch seances'); } } catch (e) { throw Exception('Error fetching seances: $e'); } } Future<void> fetchEtudiantUsernamesByClasseId(int classeId) async { try { final response = await http.get( Uri.parse('$endpointUrl/etudiants/$classeId/usernames'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ${await Login.LoginLogic.getToken()}', }, ); if (response.statusCode == 200) { final List<dynamic> responseBody = jsonDecode(response.body); setState(() { etudiants = responseBody .map((etudiantMap) => Etudiant( etudiantId: etudiantMap['etudiantId'], username: etudiantMap['username'], )) .toList(); isButtonEnabled = checkIfAtLeastOneChecked(etudiants); }); } else { throw Exception('Failed to fetch etudiant usernames'); } } catch (e) { throw Exception('Error fetching etudiant usernames: $e'); } } bool checkIfAtLeastOneChecked(List<Etudiant> etudiants) { for (var etudiant in etudiants) { if (etudiant.isPresent || etudiant.isAbsent) { return true; } } return false; } Future<void> createPresenceList(List<Presence> presenceList) async { try { final payload = presenceList .map((presence) => presence.toJson()) .toList(); print('Request Payload: $payload'); final response = await http.post( Uri.parse('$endpointUrl/creerfichepresence'), headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ${await Login.LoginLogic.getToken()}', }, body: jsonEncode(payload), ); print('Response Status Code: ${response.statusCode}'); if (response.statusCode == 200) { // Presence list created successfully // Handle the response if needed } else { throw Exception('Failed to create presence list'); } } catch (e) { throw Exception('Error creating presence list: $e'); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Fiche de présence"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: [ SizedBox(height: 20), Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Center( child: Text( "Veuillez choisir une des séances d'aujourd'hui pour laquelle vous voulez marquer la présence", style: TextStyle( fontWeight: FontWeight.bold, ), ), ), ), SizedBox(height: 20), Padding( padding: const EdgeInsets.symmetric(horizontal: 16.0), child: DropdownButton<Seance>( value: selectedSeance, items: seances.map((seance) { final dropdownText = '${seance.tempsDebut} - ${seance.tempsFin}'; return DropdownMenuItem<Seance>( value: seance, child: Text(dropdownText), ); }).toList(), onChanged: (value) async { setState(() { selectedSeance = value; fetchEtudiantUsernamesByClasseId(selectedSeance!.classeId); isButtonEnabled = checkIfAtLeastOneChecked(etudiants); }); }, ), ), SizedBox(height: 20), Expanded( child: SingleChildScrollView( child: Padding( padding: const EdgeInsets.all(16.0), child: Table( border: TableBorder.all(color: Colors.black, width: 1.0), children: [ TableRow( children: [ TableCell( child: Center(child: Text("Nom d'étudiant")), ), TableCell( child: Center(child: Text('Présent')), ), TableCell( child: Center(child: Text('Absent')), ), ], ), ...etudiants.map((etudiant) { return TableRow( children: [ TableCell( child: Padding( padding: const EdgeInsets.all(8.0), child: Center(child: Text(etudiant.username)), ), ), TableCell( child: Checkbox( value: etudiant.isPresent, onChanged: (value) { setState(() { etudiant.isPresent = value!; isButtonEnabled = checkIfAtLeastOneChecked(etudiants); }); }, ), ), TableCell( child: Checkbox( value: etudiant.isAbsent, onChanged: (value) { setState(() { etudiant.isAbsent = value!; isButtonEnabled = checkIfAtLeastOneChecked(etudiants); }); }, ), ), ], ); }).toList(), ], ), ), ), ), SizedBox(height: 20), ElevatedButton( onPressed: isButtonEnabled ? () async { List<Presence> presenceList = []; for (var etudiant in etudiants) { if (selectedSeance != null) { presenceList.add(Presence( etudiantId: etudiant.etudiantId, seanceId: selectedSeance!.seanceId!, // Use the selected seanceId present: etudiant.isPresent, )); } } // Print selectedSeance object print('Selected Seance: ${selectedSeance.toString()}'); try { await createPresenceList(presenceList); // Handle successful presence list creation } catch (e) { // Handle error } } : null, child: Text("Marquer la présence"), ), SizedBox(height: 10), ElevatedButton( onPressed: () { // Handle "Enregistrer comme pdf" button press }, child: Text("Enregistrer comme PDF"), ), ], ), ), ); } } " in order to use the key "id" and handling it by the seance and presence objects instead of seanceId
a0f97720591794bbd245eb7b61cf59f8
{ "intermediate": 0.28770172595977783, "beginner": 0.5339332222938538, "expert": 0.1783650517463684 }
8,805
I used your code But stop_loss_price and take_profit_price are not defined
e91b283088096a280116c90a3c5dc88b
{ "intermediate": 0.28328317403793335, "beginner": 0.2371533364057541, "expert": 0.47956347465515137 }
8,806
i have a kotlin app. in it a have an activity, which performs some tasks (parsing an xml file and inserting records into a database) using coroutines. once its done, it moves to a second activity. this activity queries the database to see how many items there are in it, and displays it. however, when first running the app and initializing the database, once i go to the second activity, the result i get is zero. i know that data is properly parsed and inserted, and the whole operation takes less than a second, so it shouldnt be because it hasnt finished yet. what could be probable causes?
850ae1113a04e87b5819515afc57c5c1
{ "intermediate": 0.5845054984092712, "beginner": 0.19204849004745483, "expert": 0.2234460413455963 }
8,807
import pandas as pd import requests import xml.etree.ElementTree as ET import streamlit as st import streamlit.components.v1 as components import logging import scrapy from scrapy.crawler import CrawlerProcess import sys import advertools as adv import json page_title='Sitemap Analyzer' # streamlit logo_file = '' st.set_page_config( '{}'.format(page_title), '{}'.format(logo_file), layout='wide', initial_sidebar_state='auto', menu_items={ "About": "{}".format(page_title), }, ) def faq(): st.header("Frequently Asked Questions") st.markdown( """ 1. [What is a sitemap?](#what-is-a-sitemap) 2. [How can I get started?](#how-can-i-get-started) 3. [Who is behind this project?](#who-is-behind-this-project) 4. [How do I report a bug or issue?](#how-do-i-report-a-bug-or-issue) --- ### What is a sitemap? A sitemap is a file that lists the links of a collection of webpages or Youtube videos, which helps chatbot builders like CustomGPT discover and index the video content. Using a sitemap collection, you can build your own ChatGPT based on what is being said in the videos. [Back to top](#frequently-asked-questions) ### How can I get started? 1. Just enter the link to the Youtube channel. 2. This app will then create a dynamic sitemap based on all the videos in that channel. 3. Copy-paste the sitemap into CustomGPT to build your customized ChatGPT chatbot based on whats being said in the videos. [Back to top](#frequently-asked-questions) ### Who is behind this project? This free tool was created by [CustomGPT](https://customgpt.ai/). [Back to top](#frequently-asked-questions) ### How do I report a bug or issue? Please [contact us](https://customgpt.ai/contact-us/) [Back to top](#frequently-asked-questions) """ ) def instructions(): st.header("Instructions") st.markdown( """ 1. Enter the link to the Youtube channel. 2. Click the 'Generate Sitemap' button. 3. Copy the sitemap link and use it in [CustomGPT](https://customgpt.ai) """ ) logging.basicConfig(filename='log.txt', level=logging.DEBUG) # Function to estimate the size of a webpage using the HEAD method def estimate_size(url): try: response = requests.head(url) size = int(response.headers.get('Content-Length')) return size except: logging.error(f"Failed to estimate size of {url}") return 28000 # Function to crawl a webpage and get its actual size using the HEAD method class MySpider(scrapy.Spider): name = 'myspider' def start_requests(self): yield scrapy.Request(self.start_urls[0], method='HEAD') def parse(self, response): print('VISITED: %s' % response.url) if 'Content-Length' in response.headers: size = int(response.headers['Content-Length'].decode('utf-8')) print('Size %d bytes' % size) else: print('Content-Length not found in the response headers') def crawl_size(url): try: process = CrawlerProcess(settings={ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)', 'LOG_LEVEL': 'DEBUG' }) process.crawl(MySpider, start_urls=[url]) process.start() return size except: logging.error(f"Failed to crawl size of {url}") return None # Function to parse a sitemap and return a list of URLs def sitemap_parse(sitemap_url): try: adv.spider.user_agent = 'CustomGPT <PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>' df = adv.sitemap_to_df(sitemap_url) urls = df['loc'].tolist() return urls except: logging.error(f"Failed to parse sitemap {sitemap_url}") return [] # Function to calculate the size of all pages in a sitemap def calculate_sizes(sitemap_url, method): urls = sitemap_parse(sitemap_url) num_urls = len(urls) sizes = [] if method == "Estimated Method (recommended)": st.write("Estimating sizes...") for i in range(min(num_urls, 10)): size = estimate_size(urls[i]) sizes.append(size) st.progress((i+1)/min(num_urls, 10)) avg_size = sum(sizes) / len(sizes) sizes = [avg_size] * num_urls else: st.write("Crawling sizes...") if num_urls <= 1000: for i in range(num_urls): size = crawl_size(urls[i]) sizes.append(size) st.progress((i+1)/num_urls) else: for i in range(1000): size = crawl_size(urls[i]) sizes.append(size) st.progress((i+1)/1000) avg_size = sum(sizes) / len(sizes) sizes += [avg_size] * (num_urls - 1000) return sizes # Function to generate the output table def generate_table(sitemap_url, method): sizes = calculate_sizes(sitemap_url, method) data = {"URL": [], "Size": [], "Size Calculation Method": [], "Metadata": []} for i, url in enumerate(sitemap_parse(sitemap_url)): data["URL"].append(url) data["Size"].append(sizes[i]) data["Size Calculation Method"].append(method) data["Metadata"].append("") # Add metadata here if available df = pd.DataFrame(data) return df # Main function to run the app def main(): st.sidebar.title('Navigation') page = st.sidebar.radio('Go to', ['Home', 'Instructions', 'FAQ', 'Reset']) if page == 'Home': st.header("{}".format(page_title)) st.info("This is a Streamlit app to analyze a sitemap and give information about it.") sitemap_url = st.text_input("Sitemap URL") method = st.radio("Data Calculation Method", ["Estimated Method (recommended)", "Actual Crawl Method (slow)"]) if st.button("Analyze"): st.write("Analyzing sitemap...") df = generate_table(sitemap_url, method) st.write(f"Is sitemap valid? {len(df) > 0}") st.write(f"Number of pages detected in the sitemap: {len(df)}") st.write(f"Estimated size of all pages: {sum(df['Size'].fillna(0))} bytes") st.write("Data from Sitemap and calculations:") st.write(df) components.html(f""" <button id="toggleButton">Show log</button> <div id="log" style="display: none;"> </div> <script> // Parse the log data from JSON var logData = []; var logDiv = document.getElementById("log"); var button = document.getElementById("toggleButton"); for (var i = 0; i < logData.length; i++) {{ var para = document.createElement("p"); var node = document.createTextNode(logData[i]); para.appendChild(node); logDiv.appendChild(para); }} button.addEventListener('click', function() {{ if (logDiv.style.display === "none") {{ logDiv.style"display = "block"; button.textContent = "Hide log"; }} else {{ logDiv.style.display = "none"; button.textContent = "Show log"; }} }}); </script> """, height=800, scrolling=True) elif page == 'Instructions': instructions() elif page == 'FAQ': st.title('FAQ') faq() elif page == 'Reset': st_refresh.st_refresh() if __name__ == "__main__": main() fix the logging and the actual crawl flow it doesnt seem to work always getting exception failed to crawl
9e73c18cb9e014d23b056573ddf2bf66
{ "intermediate": 0.4463689923286438, "beginner": 0.3758169710636139, "expert": 0.17781402170658112 }
8,808
c# wpf livecharts PieChart
0199e6810b6df3c731101c8491621da6
{ "intermediate": 0.4337296187877655, "beginner": 0.2759650647640228, "expert": 0.29030531644821167 }
8,809
project ├── src │ ├── data.rs │ └── main.rs ├── Cargo.toml ├── subproject │ ├── src │ │ └── lib.rs │ └── Cargo.toml Come up with minimal viable solution of the problems, written in rust code, using only std and libraries that is explicitly used in code below, pointing in which files which update needed and which new files need to create with which code. Task: define in ../project/src/data.rs a global HASHSET, that can be read and updated by any function or macro in ../project/src/main.rs or ../subproject/src/lib.rs and show example of using. HASHSET is initializing with the set of rows, consisting of arbitrary number of cells type of string. (cells goes into hashset as tab-separated in one string).
0bf0fb56362bf6eb322607daca2b1829
{ "intermediate": 0.6731897592544556, "beginner": 0.13166551291942596, "expert": 0.19514472782611847 }
8,810
Implement this using python: INCA is an iterative and developed version of the NCA, and it was proposed by Tuncer et al in 2020.23 INCA uses a loss function to select the best features, and it has an iterative structure. It is a parametric feature selection method. Users can define the initial value of the loop, the final value of the loop, and the loss function. Generally, a classifier has been utilized as a loss function. Loop range is defined to decrease the time complexity of the INCA. The initial value of the loop value is set to 100, and End value of the loop value is set to 1000, and third degree (Cubic) SVM with 10-fold cross-validation is utilized in the loss function. By using these parameters, the best features are selected from the generated 3000 features. The length of the selected best feature vector is found as 980.
37e0fc2172b29195df58e1e393556d0b
{ "intermediate": 0.19096074998378754, "beginner": 0.18727675080299377, "expert": 0.6217624545097351 }
8,811
what is the event for workbook deactivate
87dc3c95d979019e442d14b946b6cf2a
{ "intermediate": 0.46457749605178833, "beginner": 0.27083876729011536, "expert": 0.2645837366580963 }
8,812
@startuml participant “Поезд” as Train participant “Диспетчерская система” as DispatcherSystem participant “Сигнализация” as Signal participant “Рельсовая секция” as RailSection Train -> DispatcherSystem: Запросить режим движения activate Train activate DispatcherSystem DispatcherSystem -> Signal: Запросить состояние движения activate Signal Signal --> DispatcherSystem: Состояние движения (разрешение/запрет) deactivate Signal DispatcherSystem --> Train: Режим движения (текущая скорость,разрешение на движение) deactivate DispatcherSystem Train -> Train: Управление движением поезда (ускорение,тормоз) deactivate Train Train -> RailSection: Уведомление о текущем местоположении activate RailSection RailSection -> DispatcherSystem: Уведомление об изменении положения поезда activate DispatcherSystem DispatcherSystem -> DispatcherSystem: Обработка положения поезда и изменение состояния сигнализации DispatcherSystem -> Signal: Изменить состояние сигнализации activate Signal Signal --> DispatcherSystem: Состояние сигнализации обновлено deactivate Signal DispatcherSystem --> RailSection: Состояние сигнализации обновлено deactivate DispatcherSystem RailSection --> Train: Сигналы сигнализации обновлены deactivate RailSection @enduml Сделай из этой диаграммы Диаграмму коопераций (Communication diagram)
510a8d26b4181a3842d696023a3f6ad6
{ "intermediate": 0.3300361931324005, "beginner": 0.43370598554611206, "expert": 0.23625777661800385 }
8,813
import time from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys def get_token_info(token_symbol): chrome_options = Options() chrome_options.add_argument("–headless") # Update the path below to the actual path to your WebDriver executable service = Service( executable_path="C:\\Users\\AshotxXx\\PycharmProjects\\Parcing\\pythonProject\\ChromeDriver\\chromedriver.exe") driver = webdriver.Chrome(service=service, options=chrome_options) driver.get("https://moonarch.app/") try: time.sleep(1) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, 'form-control'))) # Find the search box and interact with it search_box = driver.find_element(By.CLASS_NAME, 'form-control') search_box.click() search_box.send_keys(token_symbol) search_box.send_keys(Keys.ENTER) time.sleep(1) # Wait for the token info and infocard elements to appear after entering the symbol WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "token-info"))) WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "infocard"))) # Extract information using BeautifulSoup soup = BeautifulSoup(driver.page_source, "html.parser") token_info_element = soup.find("div", class_="token-info") infocard_element = soup.find("div", class_="infocard") check_alert_element = soup.find("div", class_="token-check-message check-alert") check_warning_element = soup.find("div", class_="token-check-message check-warning") check_info_element = soup.find("div", class_="token-check-message check-info") not_verified_element = soup.find("div", class_="not-verified") check_alert_status = "Yes" if check_alert_element else "None" check_warning_status = "Yes" if check_warning_element else "None" check_info_status = "Yes" if check_info_element else "None" not_verified_status = "Yes" if not_verified_element else "None" if token_info_element and infocard_element: token_name_element = token_info_element.find("span", class_="name") token_symbol_element = token_info_element.find("span", class_="symbol") info_items = infocard_element.find_all("li") if token_name_element and token_symbol_element and len(info_items) >= 7: token_name = token_name_element.text.strip() token_symbol = token_symbol_element.text.strip() price = info_items[0].find("span", class_="value").text.strip() max_supply = info_items[1].find("span", class_="value").text.strip() market_cap = info_items[2].find("span", class_="value").text.strip() liquidity = info_items[3].find("span", class_="value").text.strip() liq_mc = info_items[4].find("span", class_="value").text.strip() token_age = info_items[6].find("span", class_="value").text.strip() driver.quit() return { "name": token_name, "symbol": token_symbol, "price": price, "max_supply": max_supply, "market_cap": market_cap, "liquidity": liquidity, "liq_mc": liq_mc, "token_age": token_age, "check_alert": check_alert_status, "check_warning": check_warning_status, "check_info": check_info_status, "not_verified": not_verified_status } else: driver.quit() error_info = f"token_name_element: {token_name_element}, token_symbol_element: {token_symbol_element}, info_items count: {len(info_items)}" return {"error": f"Failed to find the required info items or name and.symbol. Error_info: {error_info}"} else: driver.quit() return {"error": f"Failed to find the required elements for token_info_element ({token_info_element}) and infocard_element ({infocard_element})."} except Exception as e: driver.quit() return {"error": f"Failed to find the required elements or error occurred: {e}"} token_symbols = [ "0x0E481Fa712201f61dAf97017138Efaa69e2A3df3", "0x2023aa62A7570fFd59F13fdE2Cac0527D45abF91", "0x2222222222222222222222222222222222222222", "0x0d4890ecEc59cd55D640d36f7acc6F7F512Fdb6e" # Add more token symbols here… ] while True: results = [] for token_symbol in token_symbols: token_info = get_token_info(token_symbol) results.append(token_info) print(token_info) time.sleep(5) # Add a delay between requests to avoid overloading the server time.sleep(60) # Update the information every 30 seconds Is it possible to get the same output as in the code above without resorting to selenium and webdriver. If there is a better option, write which one and tell me how to implement it.
9a3eb4a251f70aacc0ae6688736f17d6
{ "intermediate": 0.33035027980804443, "beginner": 0.488815039396286, "expert": 0.18083466589450836 }
8,814
I need to write a VBA code that checks if date is Saturday or Sunday. If it is, a Pop Up appears saying "No schedules for the weekend" and on OK, it exists the sub and stops the code from running
038c711fcf35e8231aaaf1edc7615040
{ "intermediate": 0.5002307295799255, "beginner": 0.17261309921741486, "expert": 0.3271561861038208 }
8,815
in rust, how to create a hashset that will be available in all subrpojects of the project from which the project depends
ab490015ab23f1560fef2fdc1443c5f6
{ "intermediate": 0.321862131357193, "beginner": 0.1901054084300995, "expert": 0.48803243041038513 }
8,816
in rust, how to create a hashset that will be available in all subprojects from which the project depends and avoid circular dependencies
daadf1e06d6d8670db750aba2017232a
{ "intermediate": 0.40949302911758423, "beginner": 0.19711752235889435, "expert": 0.39338940382003784 }
8,817
make a useful search query for search engines for the problem: in rust, how to create a hashset that will be available in all subprojects from which the project depends and avoid circular dependencies
ce177502bc2b6cad6c7433e5cb29f2f7
{ "intermediate": 0.41663238406181335, "beginner": 0.11756262183189392, "expert": 0.4658050537109375 }
8,818
import torch from transformers import AutoTokenizer, AutoModelForSequenceClassification,AutoModel, AutoTokenizer # Define the model repo model_name = "cointegrated/rubert-tiny" #"blanchefort/rubert-base-cased-sentiment" # Download pytorch model model = AutoModel.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) # Загрузка модели и токенизатора #model_name = 'DeepPavlov/rubert-base-cased-sentiment' #tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForSequenceClassification.from_pretrained(model_name) как нужно прокачать голову,чтобы можно было провести многоклассовую классификацию с помощью данной модели вот такого dataseta oid category text 0 365271984 winter_sport Волшебные фото Виктория Поплавская ЕвгенияМедв... 1 503385563 extreme Возвращение в подземелье Треша 33 Эйфория тупо... 2 146016084 football Лучшие чешские вратари – Доминик Доминатор Гаш...
ce98cbb96e771329f6b37ccaabc7bad8
{ "intermediate": 0.3551414906978607, "beginner": 0.38255587220191956, "expert": 0.26230260729789734 }
8,819
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import torch from torch.utils.data import DataLoader, Dataset from transformers import AutoTokenizer, AutoModelForSequenceClassification, AdamW # define the model repo model_name = "cointegrated/rubert-tiny" # load the dataset #df = pd.read_csv(‘dataset.csv’) # preprocess the text data tokenizer = AutoTokenizer.from_pretrained(model_name) class CustomDataset(Dataset): def init(self, texts, labels, tokenizer, max_length): self.texts = texts self.labels = labels self.tokenizer = tokenizer self.max_length = max_length def len(self): return len(self.texts) def getitem(self, idx): text = self.texts[idx] label = self.labels[idx] # tokenize the text using the tokenizer encoding = self.tokenizer.encode_plus( text, add_special_tokens=True, max_length=self.max_length, pad_to_max_length=True, return_tensors="pt" ) return { "input_ids": encoding["input_ids"].squeeze(), "attention_mask": encoding["attention_mask"].squeeze(), "label": torch.tensor(label, dtype=torch.long) } # encode the labels le = LabelEncoder() train_data["label"] = le.fit_transform(train_data["category"]) # split the dataset into train and test set X_train, X_test, y_train, y_test = train_test_split(train_data["text"], train_data["label"], test_size=0.2, random_state=42) # create the dataloaders train_dataset = CustomDataset(X_train.values, y_train.values, tokenizer, max_length=512) test_dataset = CustomDataset(X_test.values, y_test.values, tokenizer, max_length=512) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # define the model and its optimizer model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=len(le.classes_)) optimizer = AdamW(model.parameters(), lr=2e-5) # training loop num_epochs = 5 for epoch in range(num_epochs): model.train() for batch in train_loader: inputs = { "input_ids": batch["input_ids"].to(device), "attention_mask": batch["attention_mask"].to(device), "label": batch["label"].to(device) } loss, _ = model(**inputs) loss.backward() optimizer.step() optimizer.zero_grad() model.eval() with torch.no_grad(): total_correct = 0 total_count = 0 for batch in test_loader: inputs = { "input_ids": batch["input_ids"].to(device), "attention_mask": batch["attention_mask"].to(device), "label": batch["label"].to(device) } _, outputs = model(**inputs) _, predicted = torch.max(outputs, 1) total_correct += (predicted == batch["label"].to(device)).sum().item() total_count += len(batch) accuracy = total_correct / total_count print(f"Epoch {epoch}, Accuracy: {accuracy}") TypeError: CustomDataset() takes no arguments
4ff077f1721f6e0b41b3fa068debb233
{ "intermediate": 0.23765380680561066, "beginner": 0.5643879771232605, "expert": 0.19795821607112885 }
8,820
Можешь найти ошибку в коде export const debounce = <T extends (...params: any[]) => void>( callback: T, delay: number ) => { let timerId: number; return function (this: any, ...args: any) { clearTimeout(timerId); timerId = setTimeout(() => { callback.apply(this, args); }, delay); }; };
7962b1ead6dc86f529cd5b17e92a60a6
{ "intermediate": 0.3299936056137085, "beginner": 0.48733532428741455, "expert": 0.18267107009887695 }
8,821
почему размер точек в объекте points одинаковый (равен 1), хотя должен быть разный у каждой точки? не переписывай весь код, только там, где нужно поправить import * as THREE from 'three'; import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.z = 5; const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const controls = new OrbitControls( camera, renderer.domElement ); controls.enableZoom = false; controls.enableDamping = true; controls.dampingFactor = 0.05; const shaderCode = document.getElementById("fragShader").innerHTML; THREE.ImageUtils.crossOrigin = ''; const texture = new THREE.TextureLoader().load('gradient-2.png'); const loader = new GLTFLoader(); const url = 'GRAF_3_23.glb'; loader.load(url, function (gltf) { const model = gltf.scene; model.traverse((child) => { if (child.isMesh) { const geometry = child.geometry; const texturePoint = new THREE.TextureLoader().load('texture3.png'); const sizeVariation = 1.1; const geometryPoint = new THREE.BufferGeometry(); const positions = geometry.getAttribute('position').array; const materialPoint = new THREE.PointsMaterial({ sizeAttenuation: true, map: texturePoint, alphaTest: 0.01, transparent: true, color: new THREE.Color(1., 1., 1.), opacity: 1. }); const sizes = new Float32Array(positions.length / 3); for (let i = 0; i < sizes.length; i++) { sizes[i] = Math.random()/20.0; // каждый размер будет случайным числом от 0 до 1 } const randomPosition = []; for (let i = 0; i < positions.length; i += 3) { randomPosition.push(10.0*Math.random()-5.0, 10.0*Math.random()-5.0, 10.0*Math.random()-5.0); } const randomPositionCopy = [...randomPosition]; let increment = 0.002; geometryPoint.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); const points = new THREE.Points(geometryPoint, materialPoint); const geometryPoints = points.geometry; geometryPoint.setAttribute('size', new THREE.BufferAttribute(sizes, 1)); const sizesPoints = geometryPoints.attributes.size.array; for (let i = 0; i < sizesPoints.length; i++) { console.log('Размер точки', i, ':', sizesPoints[i]); } geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); function updateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < positions[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > positions[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - positions[i]) < 0.002) { randomPosition[i] = positions[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } function reverseUpdateArray(increment) { for(let j = 0; j < 75; j++) { for(let i = 0; i<randomPosition.length; i++) { if (randomPosition[i] < randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] + increment; } else if(randomPosition[i] > randomPositionCopy[i]) { randomPosition[i] = randomPosition[i] - increment; } else if((randomPosition[i] - randomPositionCopy[i]) < 0.002) { randomPosition[i] = randomPositionCopy[i]; } } } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); } let time = 0; let sinPosition; let sinPosition2; let cosPosition; let randSignArray = []; let sign; let ratio = 1.0; for(let i = 0; i<randomPosition.length; i++) { sign = Math.random() < 0.5 ? -1.0 : 1.0; randSignArray[i] = sign; } geometryPoint.setAttribute('position', new THREE.BufferAttribute(new Float32Array(randomPosition), 3)); window.addEventListener('wheel', function(event) { if (event.deltaY > 0) { updateArray(increment); if(ratio > 0.0) { ratio -= 0.01; } } else { reverseUpdateArray(increment); ratio += 0.01; } }); scene.add(points); points.rotateX(Math.PI/2.0); } }); camera.position.z = 3; // ________________________________________________________________________________________________________________________________________________ // Создаем переменные для точки и радиуса let point = new THREE.Vector3(0, 0, 0); let radius = 1; // Создаем функцию для генерации случайной точки внутри заданного радиуса function generateRandomPointInRadius(radius) { let angle1 = Math.random() * 2 * Math.PI; let angle2 = Math.random() * 2 * Math.PI; let x = radius * Math.sin(angle1) * Math.cos(angle2); let y = radius * Math.sin(angle1) * Math.sin(angle2); let z = radius * Math.cos(angle1); return new THREE.Vector3(x, y, z); } // Инициализируем переменные для генерации случайной точки let randomPoint = generateRandomPointInRadius(radius); let dist = point.distanceTo(randomPoint); let t = 0; // Создаем функцию для анимации точки function animatePoint() { t += 0.01; if (t > 1) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } let newPos = point.clone().lerp(randomPoint, t); let moveDist = newPos.distanceTo(point); if (moveDist >= dist) { randomPoint = generateRandomPointInRadius(radius); dist = point.distanceTo(randomPoint); t = 0; } point.copy(newPos); } // Добавляем точку на сцену let pointGeometry = new THREE.SphereGeometry(0.2, 32, 32); let pointMaterial = new THREE.MeshBasicMaterial({color: 0xff0000}); let pointMesh = new THREE.Mesh(pointGeometry, pointMaterial); pointMesh.position.set(point.x, point.y, point.z); // scene.add(pointMesh); // ________________________________________________________________________________________________________________________________________________ let uniforms = { mouseCoord: {type:'v3', value: new THREE.Vector3()}, tex: { type:'t', value:texture }, res: { type:'v2', value:new THREE.Vector2(window.innerWidth,window.innerHeight)} }; const planeGeometry = new THREE.PlaneGeometry(1000, 1000); const planeMaterial = new THREE.ShaderMaterial({ uniforms:uniforms, fragmentShader:shaderCode, side: THREE.DoubleSide }); const planeMesh = new THREE.Mesh(planeGeometry, planeMaterial); scene.add(planeMesh); planeMesh.position.set(0, 0, -85); const group = new THREE.Group(); // создаем новую группу group.add(planeMesh); // добавляем куб в группу scene.add(group); let targetX = 0; let targetY = 0; let currentX = 0; let currentY = 0; function update() { requestAnimationFrame(update); const diffX = targetX - currentX; const diffY = targetY - currentY; const distance = Math.sqrt(diffX * diffX + diffY * diffY); const speed = distance / 10; if (distance < 1.0) { currentX = targetX; currentY = targetY; } else { currentX += speed * diffX / distance; currentY += speed * diffY / distance; } } update(); document.addEventListener('mousemove', (event) => { targetX = event.clientX; targetY = event.clientY; uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; }); group.position.set(camera.position.x, camera.position.y, camera.position.z); function animate() { requestAnimationFrame(animate); animatePoint(); group.rotation.x = camera.rotation.x; group.rotation.y = camera.rotation.y; group.rotation.z = camera.rotation.z; controls.update(); uniforms.mouseCoord.value.x = currentX; uniforms.mouseCoord.value.y = -currentY + window.innerHeight; renderer.render(scene, camera); } animate(); });
f80c81a5a0431f67b85ac90c403d248b
{ "intermediate": 0.2517387866973877, "beginner": 0.5305734872817993, "expert": 0.21768774092197418 }
8,822
write full code example create image edit by chatgpt. put in the code the request of description of image that you want.
ea699048683ef6deefb54e76b00d1c71
{ "intermediate": 0.44708359241485596, "beginner": 0.18294188380241394, "expert": 0.3699745237827301 }
8,823
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import torch from torch.utils.data import DataLoader, Dataset from transformers import AutoTokenizer, AutoModelForSequenceClassification, AdamW # define the model repo model_name = "cointegrated/rubert-tiny" # load the dataset #df = pd.read_csv(‘dataset.csv’) # preprocess the text data tokenizer = AutoTokenizer.from_pretrained(model_name) class CustomDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_length): self.texts = texts self.labels = labels self.tokenizer = tokenizer self.max_length = max_length def __len__(self): return len(self.texts) def __getitem__(self, idx): text = self.texts[idx] label = self.labels[idx] # tokenize the text using the tokenizer encoding = self.tokenizer.encode_plus( text, add_special_tokens=True, max_length=self.max_length, pad_to_max_length=True, return_tensors="pt" ) return { "input_ids": encoding["input_ids"].squeeze(), "attention_mask": encoding["attention_mask"].squeeze(), "label": torch.tensor(label, dtype=torch.long) } # encode the labels le = LabelEncoder() train_data["label"] = le.fit_transform(train_data["category"]) # split the dataset into train and test set X_train, X_test, y_train, y_test = train_test_split(train_data["text"], train_data["label"], test_size=0.2, random_state=42) # create the dataloaders train_dataset = CustomDataset(X_train.values, y_train.values, tokenizer, max_length=512) test_dataset = CustomDataset(X_test.values, y_test.values, tokenizer, max_length=512) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # define the model and its optimizer model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=len(le.classes_)) optimizer = AdamW(model.parameters(), lr=2e-5) # training loop num_epochs = 5 for epoch in range(num_epochs): model.train() for batch in train_loader: inputs = { "input_ids": batch["input_ids"].to(device), "attention_mask": batch["attention_mask"].to(device), "label": batch["label"].to(device) } loss, _ = model(**inputs) loss.backward() optimizer.step() optimizer.zero_grad() model.eval() with torch.no_grad(): total_correct = 0 total_count = 0 for batch in test_loader: inputs = { "input_ids": batch["input_ids"].to(device), "attention_mask": batch["attention_mask"].to(device), "label": batch["label"].to(device) } _, outputs = model(**inputs) _, predicted = torch.max(outputs, 1) total_correct += (predicted == batch["label"].to(device)).sum().item() total_count += len(batch) accuracy = total_correct / total_count print(f"Epoch {epoch}, Accuracy: {accuracy}") "label": batch["label"].to(device) TypeError: BertForSequenceClassification.forward() got an unexpected keyword argument 'label'
302c2b2918ba776f14c3d09c08023e78
{ "intermediate": 0.25978052616119385, "beginner": 0.5781044363975525, "expert": 0.16211502254009247 }
8,824
how to make a trading script for uniswap v3 with alll error handlers and use the most recent resources
70300067acf2a732b01108822fb49986
{ "intermediate": 0.5120899081230164, "beginner": 0.17591890692710876, "expert": 0.31199124455451965 }
8,825
I need to write a conditional format formula for if dd/mm/yyyy is either Satuday or Sunday
20efb2661fe80ccafd9588ba29b5578f
{ "intermediate": 0.31507495045661926, "beginner": 0.2556987404823303, "expert": 0.4292263388633728 }
8,826
I want to implement a feature on my React web application. I want to have a map of Europe. On the map there will be nodes related to a project and some data. When clicked, a modal opens that presents a summary of the data and has a link to redirect to the project with all the data. I want to use React Leaflet for this.
41341a05345c60ba590849ad07d0b2ae
{ "intermediate": 0.37953564524650574, "beginner": 0.2275606095790863, "expert": 0.39290377497673035 }
8,827
in kotlin, how do i get an imageview with an image provided from an url?
6336f5839b1ff39ba61a53e8cc5c8068
{ "intermediate": 0.5837979316711426, "beginner": 0.11069367825984955, "expert": 0.30550840497016907 }
8,828
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder import torch from torch.utils.data import DataLoader, Dataset from transformers import AutoTokenizer, AutoModelForSequenceClassification, AdamW # define the model repo model_name = "cointegrated/rubert-tiny" # load the dataset #df = pd.read_csv(‘dataset.csv’) # preprocess the text data tokenizer = AutoTokenizer.from_pretrained(model_name) class CustomDataset(Dataset): def __init__(self, texts, labels, tokenizer, max_length): self.texts = texts self.labels = labels self.tokenizer = tokenizer self.max_length = max_length def __len__(self): return len(self.texts) def __getitem__(self, idx): text = self.texts[idx] label = self.labels[idx] # tokenize the text using the tokenizer encoding = self.tokenizer.encode_plus( text, add_special_tokens=True, max_length=self.max_length, pad_to_max_length=True, return_tensors="pt" ) return { "input_ids": encoding["input_ids"].squeeze(), "attention_mask": encoding["attention_mask"].squeeze(), "labels": torch.tensor(label, dtype=torch.long).to(device) } # encode the labels le = LabelEncoder() train_data["label"] = le.fit_transform(train_data["category"]) # split the dataset into train and test set X_train, X_test, y_train, y_test = train_test_split(train_data["text"], train_data["label"], test_size=0.2, random_state=42) # create the dataloaders train_dataset = CustomDataset(X_train.values, y_train.values, tokenizer, max_length=512) test_dataset = CustomDataset(X_test.values, y_test.values, tokenizer, max_length=512) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # define the model and its optimizer model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=len(le.classes_)).to(device) optimizer = AdamW(model.parameters(), lr=2e-5) # training loop num_epochs = 5 for epoch in range(num_epochs): model.train() for batch in train_loader: inputs = { "input_ids": batch["input_ids"].to(device), "attention_mask": batch["attention_mask"].to(device), "labels": batch["labels"].to(device) } #loss, _ = model(**inputs) outputs = model(**inputs) loss = outputs.loss loss.backward() optimizer.step() optimizer.zero_grad() model.eval() with torch.no_grad(): total_correct = 0 total_count = 0 for batch in test_loader: inputs = { "input_ids": batch["input_ids"].to(device), "attention_mask": batch["attention_mask"].to(device), "labels": batch["labels"].to(device) } outputs = model(**inputs) _, predicted = torch.max(outputs.logits, 1) total_correct += (predicted == batch["labels"].to(device)).sum().item() total_count += len(batch) accuracy = total_correct / total_count print(f"Epoch {epoch}, Accuracy: {accuracy}") Этот код предполагался для обучения модели многоклассовой классификации.Покажи,пожалуйста,как его надо использовать
42b0ba71705995c0f4432b3e86d83e11
{ "intermediate": 0.28668585419654846, "beginner": 0.5831987261772156, "expert": 0.13011538982391357 }
8,829
I used your code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date) url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content) # API keys and other configuration API_KEY = '' API_SECRET = '' client = Client(API_KEY, API_SECRET) STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1 client = Client(API_KEY, API_SECRET) def getminutedata(symbol, interval, lookback): try: frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC')) frame = frame.iloc[:60,:6] frame.columns = ['Time','Open','High','Low','Close','Volume'] frame = frame.set_index('Time') today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame except Exception as e: print(f"Error getting minute data: {str(e)}") return df = getminutedata('BTCUSDT', '1m', '44640') def signal_generator(df): try: open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' # Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' # No clear pattern else: return '' except Exception as e: print(f"Error generating signal: {str(e)}") return signal_generator(df) def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): max_trade_quantity = None account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 # Close long position if signal is opposite long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p['positionSide'] == 'LONG': long_position = p elif p['positionSide'] == 'SHORT': short_position = p if long_position is not None and short_position is not None: print("Multiple positions found. Closing both positions.") client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True ) time.sleep(1) # Place the order and capture the returned order ID order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side ) # Print order creation confirmation messages print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1) while True: current_time = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") df = getminutedata('BTCUSDT', '1m', '44640') # Get minute data each loop if df is None: continue current_signal = signal_generator(df) print(f"The signal time is: {current_time} :{current_signal}") if current_signal: order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) time.sleep(1) # Add a delay of 1 second But I getting ERROR: Traceback (most recent call last): File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 200, in <module> order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 104, in order_execution quantity=long_position['positionAmt'], ~~~~~~~~~~~~~^^^^^^^^^^^^^^^ TypeError: 'NoneType' object is not subscriptable, please give me right code
88de355c2ab2d57fc529531fa725d322
{ "intermediate": 0.41107699275016785, "beginner": 0.3534979224205017, "expert": 0.23542502522468567 }
8,830
Give me python sqlalchemy code to query a database
ff725fa9b02adbf8b2637367b551afb0
{ "intermediate": 0.8230626583099365, "beginner": 0.0707617849111557, "expert": 0.10617551952600479 }
8,831
python script for human image pose changing
cf66a75fafdfd6c43156735b33a12116
{ "intermediate": 0.3715740144252777, "beginner": 0.29375800490379333, "expert": 0.33466795086860657 }
8,832
How should I use UAbilityTask_MoveToLocation::UAbilityTask_MoveToLocation in my GAS ability?
82725bc3216d1d7236752c17b5bc2039
{ "intermediate": 0.4616594612598419, "beginner": 0.18671442568302155, "expert": 0.35162606835365295 }
8,833
in node-red, how I do a take a string with RGB values and use those to change the color of a light in home assistant
0c8dbd6a8addbde303c06866291c0a02
{ "intermediate": 0.531602680683136, "beginner": 0.13193772733211517, "expert": 0.33645954728126526 }
8,834
write linked list priority queue cs106b
4be90112920c187552bc350dbc98a717
{ "intermediate": 0.3373923897743225, "beginner": 0.25774386525154114, "expert": 0.40486380457878113 }