row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
7,227
make some real functioning dropdown menu at top-left that you can press and it will popup. add sliders for "const widthSegments" and "const heightSegments". use some regenerategeometry and make these values to not affect each other when you try to adjust. set these sliders to 0 to 512 with 0.1 step in sliders and show the values in nearby boxes. also in new three.js they changed ""THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.""THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry."":
2c9e5ee08430bd1c53d664372026eda1
{ "intermediate": 0.4428586959838867, "beginner": 0.22625558078289032, "expert": 0.33088573813438416 }
7,228
make some real functioning dropdown menu at top-left that you can press and it will popup. add sliders for "const widthSegments" and "const heightSegments". use some regenerategeometry and make these values to not affect each other when you try to adjust. set these sliders to 0 to 512 with 0.1 step in sliders and show the values in nearby boxes. also in new three.js they changed ""THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.""THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry."":
d9fff48d3a5040cf7ce2e2188c785d1d
{ "intermediate": 0.4428586959838867, "beginner": 0.22625558078289032, "expert": 0.33088573813438416 }
7,229
Create in Python code that will count every other number from 1 to 100, then select every 5th number.
d4ba27ab9153fe57811d13f372df6f26
{ "intermediate": 0.3547757863998413, "beginner": 0.14782661199569702, "expert": 0.49739760160446167 }
7,230
make some real functioning dropdown menu at top-left that you can press and it will popup. add sliders for "const widthSegments" and "const heightSegments". use some regenerategeometry and make these values to not affect each other when you try to adjust. set these sliders to 0 to 512 with 0.1 step in sliders and show the values in nearby boxes. also in new three.js they changed ""THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.""THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry."" output full code.:
a0e813a73d67627cedb0f7fe0ae840e3
{ "intermediate": 0.42464080452919006, "beginner": 0.2720908224582672, "expert": 0.30326834321022034 }
7,231
make some real functioning dropdown menu at top-left that you can press and it will popup. add sliders for "const widthSegments" and "const heightSegments". use some regenerategeometry and make these values to not affect each other when you try to adjust. set these sliders to 0 to 512 with 0.1 step in sliders and show the values in nearby boxes. also in new three.js they changed ""THREE.PlaneBufferGeometry has been renamed to THREE.PlaneGeometry.""THREE.SphereBufferGeometry has been renamed to THREE.SphereGeometry."":
60f773fcf8678583f94990af97c4c426
{ "intermediate": 0.4428586959838867, "beginner": 0.22625558078289032, "expert": 0.33088573813438416 }
7,232
In Column A2 to A30, values are entered but not always the entire range. However for the values entered in column A, each row of A, B and C must have associated values. If there is no value in a row column A, there should not be values in Column B and in column C of that row. I would like to write a vba code that checks if all the entries made in column A2 to A30 have values in the same row of column B and Column C and if not, notify the user that 'All enteries need to be completed'. The preceeding code should therefore not run unless all parameters are true.
b18d0b39e4ded5cfe0b9db8640709be4
{ "intermediate": 0.6039289832115173, "beginner": 0.16084614396095276, "expert": 0.2352249175310135 }
7,233
Suppose that 40% of all students who have to buy a text for a particular course want a new copy (the successes!), whereas the other 60% want a used copy. Consider randomly selecting 12 purchasers. a) What are the mean value and standard deviation of the number who want to new copy of the book? (Round your standard deviation to two decimal places). mean = standard deviation = b) What is the probability that the number who want new copies is more than two standard deviations from the mean value? (Round your answer to 3 decimal places). c) The bookstore has 8 new copies and 8 used copies in stock. If 12 people come in one by one to purchase this text, what is the probability that all 12 will get the type of book they want from current stock? [Hint: Let X = the number who want a new copy. For what values of X will all 12 get what they want?] (Round your answer to three decimal places.) d) Suppose that new copies cost $120 and used copies cost $60. Assume the bookstore currently has 50 new copies and 50 used copies. What is the expected value of total revenue from the sale of the next 12 copies purchased? [Hint: Let h(X) = the revenue when X of the 12 purchasers want new copies. Express this as a linear function.] Indicate what rule of expected value you are using.
5691cd06f71913f4a8d5075dcd1e6a37
{ "intermediate": 0.22790424525737762, "beginner": 0.3464485704898834, "expert": 0.42564713954925537 }
7,234
make these sliders more extremely precise, because when you move them with mouse it's not smooth. also, make real dropdown popup menu, so you can press it and open and close back. also paint all the colors in properre oceanic shades of royal and dark blue transparent rgba or something.: <!DOCTYPE html> <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; } label { display: block; margin-bottom: 5px; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.152.2/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script> </head> <body> <div id="menu"> <label> Width Segments <input type="range" id="widthSegments" min="1" max="512" step="0.01" /> <span id="widthSegmentsValue"></span> </label> <label> Height Segments <input type="range" id="heightSegments" min="1" max="512" step="0.01" /> <span id="heightSegmentsValue"></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 64; let heightSegments = 64; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute("position").array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x111111); const shallowWaterColor = new THREE.Color(0x222222); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 1] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute("color").array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById("widthSegments"); const widthSegmentsValue = document.getElementById("widthSegmentsValue"); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener("input", (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById("heightSegments"); const heightSegmentsValue = document.getElementById("heightSegmentsValue"); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener("input", (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); </script> </body> </html>
5a019373bcf3fa8294518aece90c4ab2
{ "intermediate": 0.354512482881546, "beginner": 0.3575383722782135, "expert": 0.2879491448402405 }
7,235
make these sliders more extremely precise, because when you move them with mouse it's not smooth. also, make real dropdown popup menu, so you can press it and open and close back. also paint all the colors in properre oceanic shades of royal and dark blue transparent rgba or something.: <!DOCTYPE html> <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; } label { display: block; margin-bottom: 5px; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/0.152.2/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script> </head> <body> <div id="menu"> <label> Width Segments <input type="range" id="widthSegments" min="1" max="512" step="0.01" /> <span id="widthSegmentsValue"></span> </label> <label> Height Segments <input type="range" id="heightSegments" min="1" max="512" step="0.01" /> <span id="heightSegmentsValue"></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 64; let heightSegments = 64; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute("position").array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x111111); const shallowWaterColor = new THREE.Color(0x222222); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 1] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute("color").array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById("widthSegments"); const widthSegmentsValue = document.getElementById("widthSegmentsValue"); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener("input", (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById("heightSegments"); const heightSegmentsValue = document.getElementById("heightSegmentsValue"); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener("input", (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); </script> </body> </html>
42ca2a90cd7476a79305cf5b0248c93c
{ "intermediate": 0.354512482881546, "beginner": 0.3575383722782135, "expert": 0.2879491448402405 }
7,236
make these sliders more extremely precise by not simply lowering the step value but with something else, because when you move them with mouse it’s glitching. also, make real onhover popup menu, so you can press it and open and close back. also paint all the colors of terrain in properre oceanic shades of royal and dark blue transparent or something, so it can look as real motherfucking waves.: <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; } label { display: block; margin-bottom: 5px; } </style> <script src=“https://cdnjs.cloudflare.com/ajax/libs/three.js/0.152.2/three.min.js”></script> <script src=“https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js”></script> </head> <body> <div id=“menu”> <label> Width Segments <input type=“range” id=“widthSegments” min=“1” max=“512” step=“0.01” /> <span id=“widthSegmentsValue”></span> </label> <label> Height Segments <input type=“range” id=“heightSegments” min=“1” max=“512” step=“0.01” /> <span id=“heightSegmentsValue”></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 64; let heightSegments = 64; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute(“position”).array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x111111); const shallowWaterColor = new THREE.Color(0x222222); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute(“color”, new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 1] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute(“color”).array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById(“widthSegments”); const widthSegmentsValue = document.getElementById(“widthSegmentsValue”); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener(“input”, (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById(“heightSegments”); const heightSegmentsValue = document.getElementById(“heightSegmentsValue”); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener(“input”, (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); </script> </body> </html>
ea1476fc4767094e93894976985a9599
{ "intermediate": 0.3534437119960785, "beginner": 0.39260444045066833, "expert": 0.25395187735557556 }
7,237
make these sliders more extremely precise by not simply lowering the step value but with something else, because when you move them with mouse it’s glitching. also, make real onhover popup menu, so you can press it and open and close back. also paint all the colors of terrain in properre oceanic shades of royal and dark blue transparent or something, so it can look as real motherfucking waves.: <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; } label { display: block; margin-bottom: 5px; } </style> <script src=“https://cdnjs.cloudflare.com/ajax/libs/three.js/0.152.2/three.min.js”></script> <script src=“https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js”></script> </head> <body> <div id=“menu”> <label> Width Segments <input type=“range” id=“widthSegments” min=“1” max=“512” step=“0.01” /> <span id=“widthSegmentsValue”></span> </label> <label> Height Segments <input type=“range” id=“heightSegments” min=“1” max=“512” step=“0.01” /> <span id=“heightSegmentsValue”></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 64; let heightSegments = 64; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute(“position”).array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x111111); const shallowWaterColor = new THREE.Color(0x222222); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute(“color”, new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 1] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute(“color”).array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById(“widthSegments”); const widthSegmentsValue = document.getElementById(“widthSegmentsValue”); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener(“input”, (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById(“heightSegments”); const heightSegmentsValue = document.getElementById(“heightSegmentsValue”); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener(“input”, (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); </script> </body> </html>
ddba9716905a97db90503724f788dd49
{ "intermediate": 0.3534437119960785, "beginner": 0.39260444045066833, "expert": 0.25395187735557556 }
7,238
make these sliders more extremely precise by not simply lowering the step value but with something else, because when you move them with mouse it’s glitching. also, make real onhover popup menu, so you can press it and open and close back. also paint all the colors of terrain in properre oceanic shades of royal and dark blue transparent or something, so it can look as real motherfucking waves.: <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; } label { display: block; margin-bottom: 5px; } </style> <script src=“https://cdnjs.cloudflare.com/ajax/libs/three.js/0.152.2/three.min.js”></script> <script src=“https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js”></script> </head> <body> <div id=“menu”> <label> Width Segments <input type=“range” id=“widthSegments” min=“1” max=“512” step=“0.01” /> <span id=“widthSegmentsValue”></span> </label> <label> Height Segments <input type=“range” id=“heightSegments” min=“1” max=“512” step=“0.01” /> <span id=“heightSegmentsValue”></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 64; let heightSegments = 64; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute(“position”).array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x111111); const shallowWaterColor = new THREE.Color(0x222222); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute(“color”, new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 1] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute(“color”).array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById(“widthSegments”); const widthSegmentsValue = document.getElementById(“widthSegmentsValue”); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener(“input”, (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById(“heightSegments”); const heightSegmentsValue = document.getElementById(“heightSegmentsValue”); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener(“input”, (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); </script> </body> </html>
8e46c889286ad9d767db624eaf3454a9
{ "intermediate": 0.3534437119960785, "beginner": 0.39260444045066833, "expert": 0.25395187735557556 }
7,239
Как уменьшить требование до мего текущего уровня , до 11 : Build file 'C:\Users\bel-i\AndroidStudioProjects\MYapp_9_Ivan\MYapp_9\app\build.gradle' line: 2 An exception occurred applying plugin request [id: 'com.android.application'] > Failed to apply plugin 'com.android.internal.application'. > Android Gradle plugin requires Java 17 to run. You are currently using Java 11. Your current JDK is located in C:\Program Files\Android\Android Studio\jbr You can try some of the following options: - changing the IDE settings. - changing the JAVA_HOME environment variable. - changing `org.gradle.java.home` in `gradle.properties`. * Try: > Run with --stacktrace option to get the stack trace. > Run with --info or --debug option to get more log output. > Run with --scan to get full insights.
cf564c914776d6f6cbaeef6bb3d34a31
{ "intermediate": 0.43546146154403687, "beginner": 0.2928045690059662, "expert": 0.27173399925231934 }
7,240
do some collision detection on terrain surface and some balls constantly falling from above in the center of it with some periodicity, and they got disappear when fall beyond borders or edges to the bottom of the screen.: <!DOCTYPE html> <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; display: none; z-index: 1000; } label { display: block; margin-bottom: 5px; } #menu-btn { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; cursor: pointer; z-index: 999; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script> </head> <body> <div id="menu-btn">Settings</div> <div id="menu"> <label> Width Segments <input type="range" id="widthSegments" min="0.99999999999999999999999999" max="512" step="0.01" /> <span id="widthSegmentsValue"></span> </label> <label> Height Segments <input type="range" id="heightSegments" min="0.99999999999999999999999999" max="512" step="0.01" /> <span id="heightSegmentsValue"></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 0.99999999999999999999999999; let heightSegments = 0.99999999999999999999999999; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute("position").array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x001A6D); const shallowWaterColor = new THREE.Color(0x0251A1); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute("color").array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById("widthSegments"); const widthSegmentsValue = document.getElementById("widthSegmentsValue"); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener("input", (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById("heightSegments"); const heightSegmentsValue = document.getElementById("heightSegmentsValue"); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener("input", (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); // Menu functionality const menu = document.getElementById("menu"); const menuBtn = document.getElementById("menu-btn"); menuBtn.addEventListener("mouseover", () => { menu.style.display = "block"; }); menuBtn.addEventListener("mouseout", () => { menu.style.display = "none"; }); menu.addEventListener("mouseover", () => { menu.style.display = "block"; }); menu.addEventListener("mouseout", () => { menu.style.display = "none"; }); </script> </body> </html>
7a144e35f522f89c7c8c599a3b8fc4b9
{ "intermediate": 0.31289947032928467, "beginner": 0.5003476142883301, "expert": 0.18675294518470764 }
7,241
do some collision detection on terrain surface and some balls constantly falling from above in the center of it with some periodicity, and they got disappear when fall beyond borders or edges to the bottom of the screen.: <!DOCTYPE html> <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; display: none; z-index: 1000; } label { display: block; margin-bottom: 5px; } #menu-btn { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; cursor: pointer; z-index: 999; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script> </head> <body> <div id="menu-btn">Settings</div> <div id="menu"> <label> Width Segments <input type="range" id="widthSegments" min="0.99999999999999999999999999" max="512" step="0.01" /> <span id="widthSegmentsValue"></span> </label> <label> Height Segments <input type="range" id="heightSegments" min="0.99999999999999999999999999" max="512" step="0.01" /> <span id="heightSegmentsValue"></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 0.99999999999999999999999999; let heightSegments = 0.99999999999999999999999999; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute("position").array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x001A6D); const shallowWaterColor = new THREE.Color(0x0251A1); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute("color").array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById("widthSegments"); const widthSegmentsValue = document.getElementById("widthSegmentsValue"); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener("input", (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById("heightSegments"); const heightSegmentsValue = document.getElementById("heightSegmentsValue"); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener("input", (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); // Menu functionality const menu = document.getElementById("menu"); const menuBtn = document.getElementById("menu-btn"); menuBtn.addEventListener("mouseover", () => { menu.style.display = "block"; }); menuBtn.addEventListener("mouseout", () => { menu.style.display = "none"; }); menu.addEventListener("mouseover", () => { menu.style.display = "block"; }); menu.addEventListener("mouseout", () => { menu.style.display = "none"; }); </script> </body> </html>
bb7aff27e3526f014d2f3cd539806406
{ "intermediate": 0.31289947032928467, "beginner": 0.5003476142883301, "expert": 0.18675294518470764 }
7,242
do some collision detection on terrain surface and some balls constantly falling from above in the center of it with some periodicity, and they got disappear when fall beyond borders or edges to the bottom of the screen.: <!DOCTYPE html> <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; display: none; z-index: 1000; } label { display: block; margin-bottom: 5px; } #menu-btn { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; cursor: pointer; z-index: 999; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js"></script> </head> <body> <div id="menu-btn">Settings</div> <div id="menu"> <label> Width Segments <input type="range" id="widthSegments" min="0.99999999999999999999999999" max="512" step="0.01" /> <span id="widthSegmentsValue"></span> </label> <label> Height Segments <input type="range" id="heightSegments" min="0.99999999999999999999999999" max="512" step="0.01" /> <span id="heightSegmentsValue"></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 0.99999999999999999999999999; let heightSegments = 0.99999999999999999999999999; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute("position").array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x001A6D); const shallowWaterColor = new THREE.Color(0x0251A1); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute("color").array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById("widthSegments"); const widthSegmentsValue = document.getElementById("widthSegmentsValue"); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener("input", (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById("heightSegments"); const heightSegmentsValue = document.getElementById("heightSegmentsValue"); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener("input", (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); // Menu functionality const menu = document.getElementById("menu"); const menuBtn = document.getElementById("menu-btn"); menuBtn.addEventListener("mouseover", () => { menu.style.display = "block"; }); menuBtn.addEventListener("mouseout", () => { menu.style.display = "none"; }); menu.addEventListener("mouseover", () => { menu.style.display = "block"; }); menu.addEventListener("mouseout", () => { menu.style.display = "none"; }); </script> </body> </html>
365016f0ded56119b88f2730ee1dac8d
{ "intermediate": 0.31289947032928467, "beginner": 0.5003476142883301, "expert": 0.18675294518470764 }
7,243
Come up with an entirely unique, creative, and extremely helpful idea for an AI-related Github repo. Include a name for the repo, a description, tags to use that will make sure it gets seen, and a full possible file structure for the repo.
258145ea1ceb9d4b2a7aa35431811067
{ "intermediate": 0.14159294962882996, "beginner": 0.13490784168243408, "expert": 0.7234991788864136 }
7,244
read the first sheet of xls by pandas
aa42b1ea3cef093fe8a92c2c41adfc28
{ "intermediate": 0.3197363317012787, "beginner": 0.28233441710472107, "expert": 0.39792922139167786 }
7,245
Is it possible to have a vba code that can add information from an open workbooks active sheet into a sheet of another workbook that is not open
ec32250ea4928f197d6f44a88cbed980
{ "intermediate": 0.6306363940238953, "beginner": 0.1041572168469429, "expert": 0.2652064263820648 }
7,246
do some collision detection on terrain surface and some balls constantly falling from above to the center of it with some periodicity, and they got disappear when fall beyond borders or edges to the bottom of the screen. make some real phys model for balls that will interact with actual terrain surface angle animation: <html> <head> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #menu { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; display: none; z-index: 1000; } label { display: block; margin-bottom: 5px; } #menu-btn { position: absolute; top: 10px; left: 10px; background-color: white; padding: 10px; border: 1px solid black; cursor: pointer; z-index: 999; } </style> <script src=“https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js”></script> <script src=“https://cdnjs.cloudflare.com/ajax/libs/simplex-noise/2.4.0/simplex-noise.min.js”></script> </head> <body> <div id=“menu-btn”>Settings</div> <div id=“menu”> <label> Width Segments <input type=“range” id=“widthSegments” min=“0.99999999999999999999999999” max=“512” step=“0.01” /> <span id=“widthSegmentsValue”></span> </label> <label> Height Segments <input type=“range” id=“heightSegments” min=“0.99999999999999999999999999” max=“512” step=“0.01” /> <span id=“heightSegmentsValue”></span> </label> </div> <script> const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 90.01, window.innerWidth / window.innerHeight, 0.9001, 9001 ); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); const width = 100; const height = 50; let widthSegments = 0.99999999999999999999999999; let heightSegments = 0.99999999999999999999999999; function createGeometry() { const geometry = new THREE.PlaneGeometry( width, height, widthSegments, heightSegments ); const positions = geometry.getAttribute(“position”).array; const simplex = new SimplexNoise(Math.random()); return { geometry, positions, simplex }; } let { geometry, positions, simplex } = createGeometry(); function colorGradient(height) { const deepWaterColor = new THREE.Color(0x001A6D); const shallowWaterColor = new THREE.Color(0x0251A1); const color = deepWaterColor.lerp( shallowWaterColor, Math.min(height / 0.6, 0.9) ); color.lerp(new THREE.Color(0x333333), Math.max(0, (height - 0.2) / 3)); return color; } function generateTerrain(positions, simplex, scale = 0.1, elevation = 0.1) { const colors = new Float32Array(positions.length); geometry.setAttribute(“color”, new THREE.BufferAttribute(colors, 3)); for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * scale; const ny = positions[i + 1] * scale; const height = (simplex.noise2D(nx, ny) + 1) * 0.1 * elevation; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.computeVertexNormals(); } generateTerrain(positions, simplex); const material = new THREE.MeshPhongMaterial({ vertexColors: true, side: THREE.DoubleSide, transparent: true, opacity: 1 }); const terrain = new THREE.Mesh(geometry, material); terrain.rotation.x = Math.PI / 2; scene.add(terrain); const light = new THREE.DirectionalLight(0x222233, 0.5); light.position.set(1, 1, 1); scene.add(light); const ambientLight = new THREE.AmbientLight(0x5599aa); scene.add(ambientLight); camera.position.z = 50; camera.position.y = 5; camera.rotation.x = -Math.PI / 10; let clock = new THREE.Clock(); function updatePositions() { const elapsedTime = clock.getElapsedTime(); const colors = geometry.getAttribute(“color”).array; for (let i = 0; i < positions.length; i += 3) { const nx = positions[i] * 0.1 + elapsedTime * 0.1; const ny = positions[i + 1] * 0.1 + elapsedTime * 0.1; const height = (simplex.noise2D(nx, ny) + 1) * 0.5 * 5; positions[i + 2] = height; const vertexColor = colorGradient(height); colors[i] = vertexColor.r; colors[i + 1] = vertexColor.g; colors[i + 2] = vertexColor.b; } geometry.attributes.position.needsUpdate = true; geometry.attributes.color.needsUpdate = true; geometry.computeVertexNormals(); } function regenerateGeometry() { scene.remove(terrain); ({ geometry, positions, simplex } = createGeometry()); generateTerrain(positions, simplex); terrain.geometry.dispose(); terrain.geometry = geometry; scene.add(terrain); } const widthSegmentsInput = document.getElementById(“widthSegments”); const widthSegmentsValue = document.getElementById(“widthSegmentsValue”); widthSegmentsInput.value = widthSegments; widthSegmentsValue.innerHTML = widthSegments; widthSegmentsInput.addEventListener(“input”, (event) => { widthSegments = parseFloat(event.target.value); regenerateGeometry(); widthSegmentsValue.innerHTML = widthSegments; }); const heightSegmentsInput = document.getElementById(“heightSegments”); const heightSegmentsValue = document.getElementById(“heightSegmentsValue”); heightSegmentsInput.value = heightSegments; heightSegmentsValue.innerHTML = heightSegments; heightSegmentsInput.addEventListener(“input”, (event) => { heightSegments = parseFloat(event.target.value); regenerateGeometry(); heightSegmentsValue.innerHTML = heightSegments; }); function animate() { requestAnimationFrame(animate); updatePositions(); renderer.render(scene, camera); } animate(); // Menu functionality const menu = document.getElementById(“menu”); const menuBtn = document.getElementById(“menu-btn”); menuBtn.addEventListener(“mouseover”, () => { menu.style.display = “block”; }); menuBtn.addEventListener(“mouseout”, () => { menu.style.display = “none”; }); menu.addEventListener(“mouseover”, () => { menu.style.display = “block”; }); menu.addEventListener(“mouseout”, () => { menu.style.display = “none”; }); </script> </body> </html>
f32337233d7fde5d9cc33a1c61a05fcd
{ "intermediate": 0.3799055814743042, "beginner": 0.44485682249069214, "expert": 0.17523765563964844 }
7,247
here's my code [import express from "express"; import { createPost, searchPosts, viewPost, createComment, displayPosts, deletePost, displayUserPosts, } from "../controllers/post.js"; import { verifyToken } from "../verifyToken.js"; import multer from "multer"; const router = express.Router(); const imgConfig = multer.diskStorage({ destination: (req, file, callback) => { callback(null, "./uploads"); }, filename: (req, file, callback) => { callback(null, `image-${Date.now()}.${file.originalName}`); }, }); const vidConfig = multer.diskStorage({ destination: (req, file, callback) => { callback(null, "./uploads"); }, filename: (req, file, callback) => { callback(null, `video-${Date.now()}.${file.originalname}`); }, }); const isImage = (req, file, callback) => { if (file.mimetype.startsWith("image_data")) { callback(null, true); } else { callback(null, Error("only image is allowed")); } }; const isVideo = (req, file, callback) => { if (file.mimetype.startsWith("video")) { callback(null, true); } else { callback(null, Error("Only video files are allowed.")); } }; const uploadImage = multer({ storage: imgConfig, fileFilter: isImage, }).single("image_data"); const uploadVideo = multer({ storage: vidConfig, fileFilter: isVideo, }).single("video_url"); // Route for creating a new video post router.post("/", (req, res) => { uploadImage(req, res, (imageError) => { if (imageError) { console.error(imageError); return res.status(500).json({ message: "Error uploading image file." }); } uploadVideo(req, res, (videoError) => { if (videoError) { console.error(videoError); return res.status(500).json({ message: "Error uploading video file." }); } console.log(req.file); // Contains the uploaded image file console.log(req.file); // Contains the uploaded video file // Rest of your code for creating a new video post // Retrieve other form data from req.body and process accordingly // Example response return res .status(200) .json({ message: "Video post created successfully." }); }); }); }); ] and i got this error MulterError: Unexpected field at wrappedFileFilter (/Users/billy/csc317-code-bilguungzt/api/node_modules/multer/index.js:40:19) at Multipart.<anonymous> (/Users/billy/csc317-code-bilguungzt/api/node_modules/multer/lib/make-middleware.js:107:7) at Multipart.emit (node:events:513:28) at HeaderParser.cb (/Users/billy/csc317-code-bilguungzt/api/node_modules/busboy/lib/types/multipart.js:358:14) at HeaderParser.push (/Users/billy/csc317-code-bilguungzt/api/node_modules/busboy/lib/types/multipart.js:162:20) at SBMH.ssCb [as _cb] (/Users/billy/csc317-code-bilguungzt/api/node_modules/busboy/lib/types/multipart.js:394:37) at feed (/Users/billy/csc317-code-bilguungzt/api/node_modules/streamsearch/lib/sbmh.js:248:10) at SBMH.push (/Users/billy/csc317-code-bilguungzt/api/node_modules/streamsearch/lib/sbmh.js:104:16) at Multipart._write (/Users/billy/csc317-code-bilguungzt/api/node_modules/busboy/lib/types/multipart.js:567:19) at writeOrBuffer (node:internal/streams/writable:392:12) { code: 'LIMIT_UNEXPECTED_FILE', field: 'video_url', storageErrors: [] }
466587adf497d1a5f3bbb5542487cbd3
{ "intermediate": 0.40138527750968933, "beginner": 0.37221890687942505, "expert": 0.2263958901166916 }
7,248
hi
0165dd5d16fe0c0261db0e24273b6c43
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
7,249
how to get container file in docker
44b3143d52b3fc218a55b073052c5cbb
{ "intermediate": 0.3936612606048584, "beginner": 0.3871096670627594, "expert": 0.21922911703586578 }
7,250
Make a Web App like Trello, where you can keep management of tasks, using HTML, CSS and JavaScript. Include the ability to customsie and edit the boards, lists, and cards, including moving, adding, editing and removing them. You should also include the ability to import and export your boards and all of your data. The design should be extremely modern and futuristic, dark, slick and include glassmorphism and animations. Only output the code in three seperate code blocks, one for the HTML, one for the CSS and one for the JavaScript please! Thanks :)
743fcb5ef481ca97d3198400833fecb6
{ "intermediate": 0.5030052065849304, "beginner": 0.2869359254837036, "expert": 0.21005889773368835 }
7,251
Flutter how to pass class to function? Not instance but class itself
03f3ef2b8850156176615ba9163e9d98
{ "intermediate": 0.34503665566444397, "beginner": 0.5006905198097229, "expert": 0.15427277982234955 }
7,252
帮我写一篇文章,用于发表在CSDN上,写出人工智能中强化学习的运用,写出强化学习的原理,给出简单的数据样例,使得程序可运行,要求写出完整的文章目录结构,以及全套实现代码,代码必须可运行,不能出错,生成高质量文章。
3c23be5c3121092c9b85693d915e9f42
{ "intermediate": 0.29410138726234436, "beginner": 0.2897900342941284, "expert": 0.4161086082458496 }
7,253
flutter 3.7 how to pass class to function? not an instance, but class itself, so can use it's static methods and instantinate it?
7c4853b9450c0af8b08b9ccb5f28abac
{ "intermediate": 0.3080931603908539, "beginner": 0.5819585919380188, "expert": 0.10994825512170792 }
7,254
select_players <- function(selected_players_df, position_vectors_list, probability) { n_rows <- nrow(selected_players_df) selected_players_matrix <- selected_players_df select_random_player <- function(idx_list, probability, selected_players = NULL) { if (runif(1) <= probability) { repeat { random_idx <- sample(idx_list, 1) if (!random_idx %in% selected_players) { return(random_idx) } } } else { return(NA) } } for (i in 1:n_rows) { for (pos_idx in 1:length(position_vectors_list)) { selected_players_matrix[i, pos_idx] <- select_random_player(position_vectors_list[[pos_idx]], probability = probability, selected_players = selected_players_matrix[i, ]) } } selected_players_df <- data.frame(selected_players_matrix) return(selected_players_df) } In this R function I do not want to replace every argument of selected_players_matrix. Instead of return(NA) the value in selected_players_matrix should not change.
3f4f23e666f47de1fdf9d0e695aa1e5a
{ "intermediate": 0.3643137812614441, "beginner": 0.41652730107307434, "expert": 0.21915890276432037 }
7,255
I need C++ WinAPI code for getting video from web camera and storing into disk
79e4ff135ce1af2a84d0739f2e04d8d4
{ "intermediate": 0.8536525368690491, "beginner": 0.06119886785745621, "expert": 0.08514856547117233 }
7,256
I need C++ WinAPI code using DirectShow library which reading web camera usb stream and processing analyze of video samples (each sample time long configured by user) by dividing video from this sample to elements (such as table which have brown-yellow colour different from area with brightness not different to table but different to area) by colour&&brightness and creating red outline of each element before shows sample with this outlines
735e8f9f74aa32123ed03a92a8a1b818
{ "intermediate": 0.897528350353241, "beginner": 0.040155086666345596, "expert": 0.06231654807925224 }
7,257
So in R I have players that looks like this: V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 1 15104 13017 18232 13722 676 5727 15418 12375 19179 11068 15015 8824 17002 5423 8020 Each value of column in players represents index in dataframe Data. I want to extract those rows from Data into a dataframe.
b0ff38cf84a9ec68da999de4fb0aaeac
{ "intermediate": 0.4989635646343231, "beginner": 0.25001445412635803, "expert": 0.25102195143699646 }
7,258
I want to start a chat with you for my purpose of research i want to use unsupervised learning model called transformer to classify the vessels in sea here is the descreption of my dataset • Pacific Northwest coast, close to Canada’s busiest port, Vancouver. • 265 ships in four categories: Cargo, Passengership, Tanker, and Tug • 613 samples of the recording ranging from 6 seconds to 1530 seconds • Using icListen hydrophone place 141-147meter below the horizontal place bandwidth of 1 Hz-12 kHz range of 120 dB message numbers 03 and 05 were considered for data extraction. • Message 3: provides dynamic information about the ship, such as longitude, latitude, navigational status, true heading, timestamp, speed and maritime mobile service identity (MMSI) etc. • Message5 provides static information about any ship such as MMSI, name, type, max draught, length, breadth and dimension etc. • AIS system use to mark the location and timestamp of vessels passing through the sensor. As per AIS standards, ship type IDs from 70 to 79 represent cargo ship, Ids from 60 to 69 represent passenger ship, IDs from 80 to 89 represent tanker, and ID 52 represents tugs • 47h and 4 min of recording in wav form and the sample rate are 32 kHz. • Metadata in CSV format including information of (i) class id, (ii) recording id, (iii) ship name, (iii) date and time of recording, (iv) duration of each recording in seconds, (v) distances of the ship from the sensor. its just for yoru understanding Now i am in coding phase where i have 4 folders in My google Drive named ['Cargo', 'Tanker', 'Passengership', 'Tug'] each folder have multiple subfolders and each sub folder cntain only one .wav file collectively there are 609 audio file with length of 6s to 1530s there is to much large in number i want to load data with suitable technique like generator or any other alternative you hve for me
39773c6b836e6adac396435c6f1e37f7
{ "intermediate": 0.21978594362735748, "beginner": 0.2647951543331146, "expert": 0.5154189467430115 }
7,259
hello
07823f611443def0622f65e70e17af98
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
7,260
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. The basic class structure is as follows: 1. Core: - class Engine - This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.) 2. Window: - class Window - This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events. 3. Renderer: - class Renderer - This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines. - class Shader - To handle shader modules creation and destruction. - class Texture - To handle texture loading and destruction. - class Pipeline - To encapsulate the description and creation of a Vulkan graphics or compute pipeline. 4. Scene: - class Scene - This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering. - class GameObject - To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices. - class Camera - To store and manage camera properties such as position, rotation, view, and projection matrices. - class Mesh - To handle mesh data (e.g., vertices, indices, etc.) for individual objects. - class Material - To store and manage material properties such as colors, shaders, and textures. 5. Math: - Utilize GLM library to handle vector and matrix math operations. Here are the header files for context: BufferUtils.h: #pragma once #include <vulkan/vulkan.h> #include <stdint.h> namespace BufferUtils { void CreateBuffer( VkDevice device, VkPhysicalDevice physicalDevice, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer& buffer, VkDeviceMemory& bufferMemory); uint32_t FindMemoryType(VkPhysicalDevice physicalDevice, uint32_t typeFilter, VkMemoryPropertyFlags properties); void CopyBuffer( VkDevice device, VkCommandPool commandPool, VkQueue graphicsQueue, VkBuffer srcBuffer, VkBuffer dstBuffer, VkDeviceSize size); } Camera.h: #pragma once #include <glm/glm.hpp> class Camera { public: Camera(); ~Camera(); void Initialize(float aspectRatio); void Shutdown(); void SetPosition(const glm::vec3& position); void SetRotation(const glm::vec3& rotation); const glm::mat4& GetViewMatrix() const; const glm::mat4& GetProjectionMatrix() const; private: glm::vec3 position; glm::vec3 rotation; glm::mat4 viewMatrix; glm::mat4 projectionMatrix; void UpdateViewMatrix(); }; 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; }; 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(const Mesh& mesh, const Material& material); 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); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh mesh; Material material; void UpdateModelMatrix(); }; Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" class Material { public: Material(); ~Material(); void Initialize(const Shader& vertexShader, const Shader& fragmentShader, const Texture& texture, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void Cleanup(); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; private: VkDevice device; Shader vertexShader; Shader fragmentShader; Texture texture; VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; 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); private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; Model.h: #pragma once #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include "Mesh.h" #include <string> #include <vector> #include <vulkan/vulkan.h> #include <stdexcept> class Model { public: Model(); ~Model(); void LoadModel(const std::string& filepath, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); void Cleanup(); const std::vector<Mesh>& GetMeshes() const; private: std::vector<Mesh> meshes; void LoadNode(aiNode* node, const aiScene* scene, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue); Mesh LoadMesh(aiMesh* mesh, const aiScene* scene); }; Pipeline.h: #pragma once #include <vulkan/vulkan.h> #include <vector> #include <array> #include <stdexcept> #include "Shader.h" class Pipeline { public: Pipeline(); ~Pipeline(); void CreateGraphicsPipeline(const std::vector<VkVertexInputBindingDescription>& vertexBindingDescriptions, const std::vector<VkVertexInputAttributeDescription>& vertexAttributeDescriptions, VkExtent2D swapchainExtent, const std::vector<Shader*>& shaders, VkRenderPass renderPass, VkPipelineLayout pipelineLayout, VkDevice device); void Cleanup(); VkPipeline GetPipeline() const; private: VkDevice device; VkPipeline pipeline; void CreateShaderStages(const std::vector<Shader*>& shaders, std::vector<VkPipelineShaderStageCreateInfo>& shaderStages); }; Renderer.h: #pragma once #include <vulkan/vulkan.h> #include "Window.h" #include <vector> #include <stdexcept> #include <set> #include <optional> #include <iostream> struct QueueFamilyIndices { std::optional<uint32_t> graphicsFamily; std::optional<uint32_t> presentFamily; bool IsComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); } }; struct SwapChainSupportDetails { VkSurfaceCapabilitiesKHR capabilities; std::vector<VkSurfaceFormatKHR> formats; std::vector<VkPresentModeKHR> presentModes; }; class Renderer { public: Renderer(); ~Renderer(); void Initialize(GLFWwindow* window); void Shutdown(); void BeginFrame(); void EndFrame(); VkDevice* GetDevice(); VkPhysicalDevice* GetPhysicalDevice(); VkCommandPool* GetCommandPool(); VkQueue* GetGraphicsQueue(); private: bool shutdownInProgress; std::vector<VkImage> swapChainImages; std::vector<VkImageView> swapChainImageViews; VkExtent2D swapChainExtent; VkRenderPass renderPass; uint32_t imageIndex; VkFormat swapChainImageFormat; std::vector<VkCommandBuffer> commandBuffers; void CreateImageViews(); void CleanupImageViews(); void CreateRenderPass(); void CleanupRenderPass(); void CreateSurface(); void DestroySurface(); void CreateInstance(); void CleanupInstance(); void ChoosePhysicalDevice(); void CreateDevice(); void CleanupDevice(); void CreateSwapchain(); void CleanupSwapchain(); void CreateCommandPool(); void CleanupCommandPool(); void CreateFramebuffers(); void CleanupFramebuffers(); void CreateCommandBuffers(); void CleanupCommandBuffers(); GLFWwindow* window; VkInstance instance = VK_NULL_HANDLE; VkPhysicalDevice physicalDevice = VK_NULL_HANDLE; VkDevice device = VK_NULL_HANDLE; VkSurfaceKHR surface; VkSwapchainKHR swapchain; VkCommandPool commandPool; VkCommandBuffer currentCommandBuffer; std::vector<VkFramebuffer> framebuffers; // Additional Vulkan objects needed for rendering… const uint32_t kMaxFramesInFlight = 2; std::vector<VkSemaphore> imageAvailableSemaphores; std::vector<VkSemaphore> renderFinishedSemaphores; std::vector<VkFence> inFlightFences; size_t currentFrame; VkQueue graphicsQueue; VkQueue presentQueue; void CreateSyncObjects(); void CleanupSyncObjects(); SwapChainSupportDetails querySwapChainSupport(VkPhysicalDevice device, VkSurfaceKHR surface); VkSurfaceFormatKHR chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats); VkPresentModeKHR chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes); VkExtent2D chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities, GLFWwindow* window); std::vector<const char*> deviceExtensions = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; std::vector<const char*> CheckPhysicalDeviceExtensionSupport(VkPhysicalDevice physicalDevice); QueueFamilyIndices GetQueueFamilyIndices(VkPhysicalDevice physicalDevice); }; 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(); private: std::vector<GameObject*> gameObjects; Camera camera; }; Shader.h: #pragma once #include <vulkan/vulkan.h> #include <string> class Shader { public: Shader(); ~Shader(); void LoadFromFile(const std::string& filename, VkDevice device, VkShaderStageFlagBits stage); void Cleanup(); VkPipelineShaderStageCreateInfo GetPipelineShaderStageCreateInfo() const; private: VkDevice device; VkShaderModule shaderModule; VkShaderStageFlagBits stage; }; Simplex.h: #pragma once #ifndef SIMPLEX_H #define SIMPLEX_H #include <iostream> class SimplexNoise { private: int testvar; int grad3[12][3]{ { 1, 1, 0 }, { -1, 1, 0 }, { 1, -1, 0 }, { -1, -1, 0 }, { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 }, { -1, 0, -1 }, { 0, 1, 1 }, { 0, -1, 1 }, { 0, 1, -1 }, { 0, -1, -1 } }; int grad4[32][4] = { { 0, 1, 1, 1 }, { 0, 1, 1, -1 }, { 0, 1, -1, 1 }, { 0, 1, -1, -1 }, { 0, -1, 1, 1 }, { 0, -1, 1, -1 }, { 0, -1, -1, 1 }, { 0, -1, -1, -1 }, { 1, 0, 1, 1 }, { 1, 0, 1, -1 }, { 1, 0, -1, 1 }, { 1, 0, -1, -1 }, { -1, 0, 1, 1 }, { -1, 0, 1, -1 }, { -1, 0, -1, 1 }, { -1, 0, -1, -1 }, { 1, 1, 0, 1 }, { 1, 1, 0, -1 }, { 1, -1, 0, 1 }, { 1, -1, 0, -1 }, { -1, 1, 0, 1 }, { -1, 1, 0, -1 }, { -1, -1, 0, 1 }, { -1, -1, 0, -1 }, { 1, 1, 1, 0 }, { 1, 1, -1, 0 }, { 1, -1, 1, 0 }, { 1, -1, -1, 0 }, { -1, 1, 1, 0 }, { -1, 1, -1, 0 }, { -1, -1, 1, 0 }, { -1, -1, -1, 0 } }; int p_supply[256] = { 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 }; // To remove the need for index wrapping, double the permutation table // length int perm[512] = {}; /*static { for (int i = 0; i < 512; i++) perm[i] = p[i & 255]; }*/ // A lookup table to traverse the simplex around a given point in 4D. // Details can be found where this table is used, in the 4D noise method. int simplex[64][4] = { { 0, 1, 2, 3 }, { 0, 1, 3, 2 }, { 0, 0, 0, 0 }, { 0, 2, 3, 1 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 2, 3, 0 }, { 0, 2, 1, 3 }, { 0, 0, 0, 0 }, { 0, 3, 1, 2 }, { 0, 3, 2, 1 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 3, 2, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 2, 0, 3 }, { 0, 0, 0, 0 }, { 1, 3, 0, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 2, 3, 0, 1 }, { 2, 3, 1, 0 }, { 1, 0, 2, 3 }, { 1, 0, 3, 2 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 2, 0, 3, 1 }, { 0, 0, 0, 0 }, { 2, 1, 3, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 2, 0, 1, 3 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 3, 0, 1, 2 }, { 3, 0, 2, 1 }, { 0, 0, 0, 0 }, { 3, 1, 2, 0 }, { 2, 1, 0, 3 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 3, 1, 0, 2 }, { 0, 0, 0, 0 }, { 3, 2, 0, 1 }, { 3, 2, 1, 0 } }; int p[256] = {}; int RANDOMSEED = 0; int NUMBEROFSWAPS = 400; public: SimplexNoise(int inseed); double noise(double xin, double yin); double noise(double xin, double yin, double zin); double noise(double xin, double yin, double zin, double win); }; #endif Terrain.h: #pragma once #include "Simplex.h" #include "Mesh.h" #include "Material.h" #include "GameObject.h" class Terrain { public: Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue); ~Terrain(); void GenerateTerrain(); GameObject* GetTerrainObject(); private: void GenerateHeightMap(); void ConvertHeightMapToMeshData(); int seed; int worldSize; float scale; VkDevice* device; VkPhysicalDevice* physicalDevice; VkCommandPool* commandPool; VkQueue* graphicsQueue; SimplexNoise noise; std::vector<std::vector<float>> heightMap; std::vector<Vertex> vertices; std::vector<uint32_t> indices; Mesh terrainMesh; Material terrainMaterial; GameObject terrainObject; }; 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); void Cleanup(); VkImageView GetImageView() const; VkSampler GetSampler() const; private: VkDevice device; VkImage image; VkDeviceMemory imageMemory; VkImageView imageView; VkSampler sampler; VkPhysicalDevice physicalDevice; VkCommandPool commandPool; VkQueue graphicsQueue; 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… }; Window.h: #pragma once #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> class Window { public: Window(int width = 800, int height = 600, const char* title = "Game Engine"); ~Window(); void Initialize(); void PollEvents(); void Shutdown(); bool ShouldClose() const; GLFWwindow* GetWindow() const; float GetDeltaTime(); private: static void FramebufferResizeCallback(GLFWwindow* window, int width, int height); static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); int width; int height; const char* title; GLFWwindow* window; double lastFrameTime; }; The GameObject.cpp file has a number of incomplete methods. Based on the rest of the codebase, can you help me fill them in? Here is the current version of the GameObject.cpp file: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { Shutdown(); } void GameObject::Initialize(const Mesh& mesh, const Material& material) { this->mesh = mesh; // copy or share mesh data this->material = material; // copy or share material data } 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 // // Example: // - Pass appropriate pipeline and descriptor sets to the renderer // - Bind mesh vertex and index buffers // - Update shader uniform buffers with modelMatrix and camera properties // - Call renderer.Draw() or vkCmdDrawIndexed() } void GameObject::Shutdown() { // Clean up resources, if necessary // (depending on how Mesh and Material resources are managed) } 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); }
68b62d1bf6884432ca60a2085e1386da
{ "intermediate": 0.45648056268692017, "beginner": 0.32650935649871826, "expert": 0.21701014041900635 }
7,261
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Word } from './entities/words.entity'; import * as wordData from '../../../../all_5000_mots.json'; @Injectable() export class WordSeederService { constructor( @InjectRepository(Word) private readonly wordRepository: Repository<Word>, ) {} async run() { const data = wordData; await Promise.all(data.map((item) => this.wordRepository.insert(item))); } } Why does the above code throws the following error Error: read ECONNRESET at TCP.onStreamRead (node:internal/stream_base_commons:217:20) { errno: -4077, code: 'ECONNRESET', syscall: 'read' }
40e982035c9a2f757e3a3f1001e69c19
{ "intermediate": 0.5758814215660095, "beginner": 0.2717013359069824, "expert": 0.15241725742816925 }
7,262
example of c++ code: struct model { int num_of_coordinates; int *X_average_coordinates;//loaded from file int *Y_average_coordinates;//loaded from file int *X_plus_minus;//loaded from file int *Y_plus_minus;//loaded from file int *X_generated;//generated by cycle int *Y_generated;//generated by cycle int average_fill;//e.g. 0x778899 int plus_minus_fill//e.g. 0x889977 int generated_fill;//generated void generate() { X_generated=new int[num_of_coordinates]; Y_generated=new int[num_of_coordinates]; bool bx=0, by=0, bfill=0; for (int i=0; i<num_of_coordinates; i++) { if(bx) X_generated[i]=X_average_coordinates-(rand()%X_plus_minus[i]);//if bx==1 minus else X_generated[i]=X_average_coordinates+(rand()%X_plus_minus[i]);//else so if bx==0 plus if(by) Y_generated[i]=Y_average_coordinates-(rand()%Y_plus_minus[i]);//if by==1 minus else Y_generated[i]=Y_average_coordinates+(rand()%Y_plus_minus[i]);//else so if by==0 plus bx=rand(); by=rand();//update bx and by value, random } bfill=rand(); if (bfill) generated_fill=average_fill-rand()%plus_minus_fill;//if bfill=1 minus else generated_fill=average_fill+rand()%plus_minus_fill;//else so if bfill=0 plus } }; Next you need to tell me how I can to create average X, average Y, and average fill of model, using 1000 BMP images
c8515829c07a5aa1cc8d04fa07249bcf
{ "intermediate": 0.363586962223053, "beginner": 0.2433282732963562, "expert": 0.3930847644805908 }
7,263
Explain the building blocks of a commercial RTOS
d82761aa2f79b043b2f80aa72b29405d
{ "intermediate": 0.3773639500141144, "beginner": 0.23877602815628052, "expert": 0.3838600218296051 }
7,264
This is my current ide code for highsum game: "import GUIExample.GameTableFrame; import Model.*; 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.run(); } 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(); } } } import Model.*; import Controller.*; import View.*; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; 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); } public void run() { //starts the game! gc.run(); } 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(); } } } Controller package: 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; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } 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); } 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 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 GUIExample; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import Model.*; package GUIExample; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import Model.*; public class GameTableFrame extends JFrame{ private GameTablePanel gameTablePanel; private Dealer dealer; private Player player; private int count=0; private JButton playButton; private JButton quitButton; public GameTableFrame(Dealer dealer, Player player) { this.dealer = dealer; this.player = player; gameTablePanel = new GameTablePanel(dealer,player); this.count=0; playButton = new JButton("Play"); quitButton = new JButton("Quit"); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Call run() when playButton is clicked run(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Close the program when quitButton is clicked System.exit(0); } }); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); add(gameTablePanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.SOUTH); pack(); setVisible(true); } public void updateGameTable() { gameTablePanel.repaint(); } public void run() { JLabel shufflingLabel = new JLabel("Shuffling"); shufflingLabel.setHorizontalAlignment(SwingConstants.CENTER); add(shufflingLabel, BorderLayout.NORTH); for (int i = 0; i < 5; i++) { dealer.dealCardTo(dealer); dealer.dealCardTo(player); updateGameTable(); pause(); // You can adjust the pause duration to control the shuffling speed } remove(shufflingLabel); // Remove the shuffling label after dealing all cards updateGameTable(); } //pause for 500msec private void pause() { try{ Thread.sleep(500); }catch(Exception e){} } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; private ImageIcon cardBackImage; public GameTablePanel(Dealer dealer, Player player) { setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); cardBackImage = new ImageIcon("images/back.png"); this.dealer = dealer; this.player = player; } public void paintComponent(Graphics g) { super.paintComponent(g); int x = 50; int y = 70; int i = 0; for (Card c : dealer.getCardsOnHand()) { // display dealer cards if (i == 0d) { cardBackImage.paintIcon(this, g, x, y); i++; } else { c.paintIcon(this, g, x, y); } x += 200; } // display player cards x = 50; y = 550; for (Card c : player.getCardsOnHand()) { // display dealer cards c.paintIcon(this, g, x, y); x += 200; } } } Helper Package: 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(""); } } Model Package: package Model; import javax.swing.*; public class Card extends ImageIcon{ private String suit; private String name; private int value; //used for card ranking - see below //to determine which card has higher power to determine who can call. private int rank; 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; } 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() { 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 deck player.addCard(card);//pass the card into 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 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)); } } View Package: package View; import Helper.Keyboard; 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: “Game Start The game starts with the dealer shuffles the deck of cards. The dealer will deal (distribute) the cards to the players. The dealer make two passes so that the players and the dealer have two cards each. Two passes means that the dealer must distribute the cards in such a way that, the first card belongs to the player, the second card belongs to the dealer, the third card belongs to the player and the fourth card belows to the dealer. Round 1 The first card of the dealer and player are both hidden, that is face down. The dealer and player can view their own hidden first card. The second card is visible to both the dealer and player. The player with the highest second visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 2 The dealer make one pass. Dealer and player each have 3 cards now. The player with the highest third visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet or choose to quit the current game. Dearler is not allowed to quit the game. If the human player choose to quit at this round, all the chips on the table belongs to the dealer and the current game ends here. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 3 Similar to round 2. Round 4 Similar to round 2 plus the following rule: Each player compares the values of cards hold by other players at the end of each game to determine the winner. The player with the highest accumulate values win the game. The winner gets all the bet on the table. Next Game All the cards on the table are shuffled and placed at the end of the deck. The game will start again unless the player choose to leave the game. Please note that the above game description is a simplified version of the real game and there are also many different versions in different countries. The specifications given in this document are more than sufficient for you to complete this assignment. If you have doubts on the game logic, please feel free to clarify with your tutor. Do take note that the emphasis of this assignment is to implement the game logic using Object-oriented programming."
f38275d95ec33454ea33192ed9199943
{ "intermediate": 0.2906542420387268, "beginner": 0.4795202910900116, "expert": 0.2298254817724228 }
7,265
Рассмотрим систему из n серверов, расположенных в d дата-центрах. Серверы пронумерованы натуральными числами от 1 до n. На первом сервере расположен уникальный файл размера m GB. Наша задача — продублировать его на остальные серверы. Для каждого сервера s известны входящая скорость передачи данных, исходящая скорость передачи данных и номер дата-центра, где расположен сервер. В этой задаче скорость передачи данных будем измерять в секундах, затрачиваемых на 1 GB получаемых или отправляемых данных. В задаче используется нестандартная характеристика скорости. С сервера S на сервер T файл передается за время m⋅dcSdTd⋅max(Sout,Tin), где dcij — некоторый коэффициент, задающий замедление передачи данных от дата-центра с номером i в дата-центр с номером j, Sout — минимальное время передачи 1 GB данных с сервера S, Tin — минимальное время получения 1 GB данные сервером T. Информация передаётся по серверам в соответствии с порядком их номеров. Пока два сервера обмениваются данными, они оба заблокированы. В начальный момент времени 0 файл доступен только на первом сервере. Будем считать, что обработка очереди копирования файлов происходит по следующему принципу: Сначала завершается операция копирования, которая должна завершиться в этот момент. Затем в порядке возрастания номеров серверов, получивших в данный момент времени файл, выводятся сообщения в лог. Затем формируется пул из серверов, с которых в этот момент может начаться копирование. Это все сервера, которые завершили передачу данных или получение. В порядке возрастания номеров доступных серверов они получают новое задание (в порядке возрастания номеров серверов для получения данных). Если в какой-то момент все сервера уже получили файл или получают его, то новых запусков копирования не происходит. Выведите лог процесса копирования. Каждая строка должна содержать запись Time X: server A received file from server B. Строки лога должны быть отсортированы по возрастанию времени X, а при равенстве X по возрастанию серверов-получателей A. Формат ввода В первой строке записано три целых числа n, d и m (2≤n≤1000000, 1≤d≤10, 1≤m≤1000). В каждой из следующих n строк записаны параметры очередного сервера: три целых числа Sin, Sout и Sd (1≤Sin≤1000000, 1≤Sout≤1000000, 1≤Sd≤d). В следующих d строках записана матрица dij (1≤dij≤3). Величина dij, расположенная на j-й позиции i-й строки, задает коэффициент замедления передачи данных от дата-центра с номером i в дата-центр с номером j. Формат вывода Выведите лог копирования данных. пример вывода: Time 20: server 2 received file from server 1 Time 40: server 3 received file from server 1 Time 40: server 4 received file from server 2 Time 60: server 5 received file from server 1 реши на c++
fbd252153855d165fb2af9178922caeb
{ "intermediate": 0.16846436262130737, "beginner": 0.5621175169944763, "expert": 0.26941806077957153 }
7,266
Hello, I’m a total beginner and I would like to make a blog using codeberg pages and neovim. Here is the explanation of someone doing it : 1) make a new article and open it with Neovim. 2)The next step is commiting, which is what I will do as soon as I type “:wq”. Then, Codeberg handles it from there. It looks really simple but some steps are too blurry, and I can't reproduce it. Can you explain me this in a step by step guide ?
1941f4748acc5e998e39c56dfc7a4315
{ "intermediate": 0.39711785316467285, "beginner": 0.2305700182914734, "expert": 0.37231209874153137 }
7,267
请帮我生成一张猫的图片
1d831505395c1f3a0850f3a4feaf7f14
{ "intermediate": 0.3297922611236572, "beginner": 0.3261387348175049, "expert": 0.3440690338611603 }
7,268
I am running mongodb on localhost on port 27017 and a server app on same host, what would be database uri
7e50c4631f0d63db5ee5e3baf2a283c0
{ "intermediate": 0.41190674901008606, "beginner": 0.31455400586128235, "expert": 0.2735392451286316 }
7,269
Flutter how to trigger action from statelessWidget when drawing part complete?
b584bb36ef18e76cee4e3d0deeef5d10
{ "intermediate": 0.4191097021102905, "beginner": 0.14101232588291168, "expert": 0.439877986907959 }
7,270
How is machine learning and optimization techniques applied for electric drives?
32fccd681998a70a2f96e1abcf85bb61
{ "intermediate": 0.024310048669576645, "beginner": 0.016998162493109703, "expert": 0.9586917757987976 }
7,271
flutter how to detect widget build is complete from statefull widget?
0de30f2ed7dc4d5180830c60530cd793
{ "intermediate": 0.38241854310035706, "beginner": 0.120566725730896, "expert": 0.49701476097106934 }
7,272
list the speed control methods used in induction motor
48a346f519dfd41a3d3f19156e0ef359
{ "intermediate": 0.3735238313674927, "beginner": 0.3563949465751648, "expert": 0.27008122205734253 }
7,273
Hi
d34306ddb1aa73ef0b78994a2b6a20a2
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
7,274
So I have this R code: parent_pop<- as.data.frame(matrix(NA, n_rows, length(position_vectors))) for(c in 1:(population_size/2)){ parent_pop[c,]<-tournament_selection (parents,t_size=2) } parents_temp<- as.data.frame(matrix(NA, 1, length(position_vectors))) for (c in seq(1, population_size, by = 1)){ print(c) parent1<-parent_pop[c,] parent2<-parent_pop[c+1,] offsprings<-crossover(parent1, parent2,corssover_point) o1<-unlist(offsprings[1,]) o2<-unlist(offsprings[2,]) parents_temp<-rbind(parents_temp,o1) parents_temp<-rbind(parents_temp,o2) } parents_temp <- parents_temp[-1, ] The issue is that it is supposed
9f6030e1aa2915d109d74668788d8fa8
{ "intermediate": 0.40700477361679077, "beginner": 0.38168036937713623, "expert": 0.2113148272037506 }
7,275
I have an angular, asp.net mvc core website, domain name is mmm.com, when i enter in the browser mmm.com it works but it gives me a timeout when i enter www.mmm.com, why?
6a63560ec4095cd18a78c5d5fe229dbc
{ "intermediate": 0.44887253642082214, "beginner": 0.2934107780456543, "expert": 0.25771671533584595 }
7,276
You're a gamer and a copywriter. Tell us about the Equal opportunity rule set in the game Splinterlands. Give examples of strategies and card layouts
97445fc15a2bc24312ac8946d73cf10c
{ "intermediate": 0.32319188117980957, "beginner": 0.39599862694740295, "expert": 0.28080952167510986 }
7,277
This is my current ide code for highsum 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.run(); } 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(); } } } import Model.*; import Controller.*; import View.*; import GUIExample.LoginDialog; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; 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); } public void run() { //starts the game! gc.run(); } 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 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; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } 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, true); this.dealer.dealCardTo(this.dealer, true); } this.dealer.dealCardTo(this.player, false); this.dealer.dealCardTo(this.dealer, false); 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 java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import Model.*; 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"); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); run(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); add(gameTablePanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.SOUTH); add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); pack(); setVisible(true); } public void run() { for (int i = 0; i < 5; i++) { dealer.dealCardTo(dealer); dealer.dealCardTo(player); gameTablePanel.repaint(); pause(); } shufflingLabel.setVisible(false); gameTablePanel.repaint(); } private void pause() { try{ Thread.sleep(500); }catch(Exception e){} } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; private ImageIcon cardBackImage; public GameTablePanel(Dealer dealer, Player player) { setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); cardBackImage = new ImageIcon("images/back.png"); this.dealer = dealer; this.player = player; } public void paintComponent(Graphics g) { super.paintComponent(g); int x = 50; int y = 70; // Add the label "Dealer" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Dealer", x, y - 20); int i = 0; for (Card c : dealer.getCardsOnHand()) { // Display dealer cards if (i == 0) { cardBackImage.paintIcon(this, g, x, y); i++; } else { c.paintIcon(this, g, x, y); } x += 200; } // Display "Deck" label g.drawString("Deck", x, y + 100); // Display player cards x = 50; y = 550; // Add the label "Player" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Player", x, y - 20); for (Card c : player.getCardsOnHand()) { c.paintIcon(this, g, x, y); x += 200; } // Display "Chips on the table:" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Chips on the table:", x - 950, y - 250); } } 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, boolean faceDown) { Card card = deck.dealCard(); //take a card out from the deck if (faceDown) { card.setFaceDown(true); } 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 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.Keyboard; 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: “Game Start The game starts with the dealer shuffles the deck of cards. The dealer will deal (distribute) the cards to the players. The dealer make two passes so that the players and the dealer have two cards each. Two passes means that the dealer must distribute the cards in such a way that, the first card belongs to the player, the second card belongs to the dealer, the third card belongs to the player and the fourth card belows to the dealer. Round 1 The first card of the dealer and player are both hidden, that is face down. The dealer and player can view their own hidden first card. The second card is visible to both the dealer and player. The player with the highest second visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 2 The dealer make one pass. Dealer and player each have 3 cards now. The player with the highest third visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet or choose to quit the current game. Dearler is not allowed to quit the game. If the human player choose to quit at this round, all the chips on the table belongs to the dealer and the current game ends here. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 3 Similar to round 2. Round 4 Similar to round 2 plus the following rule: Each player compares the values of cards hold by other players at the end of each game to determine the winner. The player with the highest accumulate values win the game. The winner gets all the bet on the table. Next Game All the cards on the table are shuffled and placed at the end of the deck. The game will start again unless the player choose to leave the game. Please note that the above game description is a simplified version of the real game and there are also many different versions in different countries. The specifications given in this document are more than sufficient for you to complete this assignment. If you have doubts on the game logic, please feel free to clarify with your tutor. Do take note that the emphasis of this assignment is to implement the game logic using Object-oriented programming."
e855c4bfb54cddd87f42157f679d49c2
{ "intermediate": 0.31380853056907654, "beginner": 0.4907025992870331, "expert": 0.195488840341568 }
7,278
class StreamView(Screen): output = StringProperty() capture = "" def on_enter(self): app = App.get_running_app() self.output = app.data self.capture = cv2.VideoCapture(self.output) # RTSP URL print("print after setting wrong adress") b = Button() b.bind(on_press=lambda instance, button_id="i": gotomainscreen(button_id)) self.add_widget(b) self.image = Image() self.add_widget(self.image) Clock.schedule_interval(self.update, 1.0 / 30.0) # 30 fps def gotomainscreen(x): app = App.get_running_app() app.root.current = "Main" def update(self, dt): ret, frame = self.capture.read() if ret: buf = cv2.flip(frame, 0).tostring() # flip & convert to bytes texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.image.texture = texture def on_leave(self): self.capture.release()
5d76d5b77b0e2f00e13df8458bce31cc
{ "intermediate": 0.35061854124069214, "beginner": 0.47132763266563416, "expert": 0.1780538558959961 }
7,279
Completely revamp this code for a Hugging Face Gradio demo, drastically increasing performance, optimizing the queue, and adding other QoL and major features, like a 'Stop', 'Regenerate' and 'Clear' button. import gradio as gr import os import sys import json import requests MODEL = "gpt-4" API_URL = os.getenv("API_URL") DISABLED = os.getenv("DISABLED") == 'True' OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") NUM_THREADS = int(os.getenv("NUM_THREADS")) print (NUM_THREADS) def exception_handler(exception_type, exception, traceback): print("%s: %s" % (exception_type.__name__, exception)) sys.excepthook = exception_handler sys.tracebacklimit = 0 #https://github.com/gradio-app/gradio/issues/3531#issuecomment-1484029099 def parse_codeblock(text): lines = text.split("\n") for i, line in enumerate(lines): if "
3e415aec74026172ae5b25c22e7eb6b1
{ "intermediate": 0.4223441183567047, "beginner": 0.40129101276397705, "expert": 0.17636483907699585 }
7,280
c# wpf datagrid textbox row
753850fe0aa6d2c77af5380462203ccb
{ "intermediate": 0.3274960219860077, "beginner": 0.33140259981155396, "expert": 0.34110134840011597 }
7,281
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. The basic class structure is as follows: 1. Core: - class Engine - This is the main class that will initialize, run, and shut down other subsystems of the engine (e.g., Window, Renderer, Input, etc.) 2. Window: - class Window - This class will handle window creation, resizing, and destruction using GLFW. It should also handle keyboard and mouse input events. 3. Renderer: - class Renderer - This class will manage Vulkan objects (e.g., instance, device, swapchain, command buffers) and rendering pipelines. - class Shader - To handle shader modules creation and destruction. - class Texture - To handle texture loading and destruction. - class Pipeline - To encapsulate the description and creation of a Vulkan graphics or compute pipeline. 4. Scene: - class Scene - This class will manage the list of objects in the vector, update their transforms, and send them to the Renderer for rendering. - class GameObject - To represent individual objects in the scene, store their transformation matrices, and bind the relevant data like vertices and indices. - class Camera - To store and manage camera properties such as position, rotation, view, and projection matrices. - class Mesh - To handle mesh data (e.g., vertices, indices, etc.) for individual objects. - class Material - To store and manage material properties such as colors, shaders, and textures. 5. Math: - Utilize GLM library to handle vector and matrix math operations. Here is some of the relevant header and source file 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; }; 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(); Terrain terrain(0,10,1,renderer.GetDevice(), renderer.GetPhysicalDevice(), renderer.GetCommandPool(), renderer.GetGraphicsQueue()); terrain.GenerateTerrain(); scene.AddGameObject(terrain.GetTerrainObject()); } 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(); } 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(); private: std::vector<GameObject*> gameObjects; Camera camera; }; Scene.cpp: #include "Scene.h" Scene::Scene() { } Scene::~Scene() { Shutdown(); } void Scene::Initialize() { // Initialize camera and game objects camera.SetPosition(glm::vec3(0.0f, 0.0f, -5.0f)); // Add initial game objects } void Scene::Update(float deltaTime) { // Update game objects and camera for (GameObject* gameObject : gameObjects) { gameObject->Update(deltaTime); } } void Scene::Render(Renderer& renderer) { // Render game objects for (GameObject* gameObject : gameObjects) { gameObject->Render(renderer, camera); } // Submit rendering-related commands to Vulkan queues } void Scene::Shutdown() { // Clean up game objects for (GameObject* gameObject : gameObjects) { delete gameObject; gameObject = nullptr; } gameObjects.clear(); camera.Shutdown(); } void Scene::AddGameObject(GameObject* gameObject) { gameObjects.push_back(gameObject); } Camera& Scene::GetCamera() { return 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(const Mesh& mesh, const Material& material); 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); private: glm::mat4 modelMatrix; glm::vec3 position; glm::vec3 rotation; glm::vec3 scale; Mesh mesh; Material material; bool initialized = false; void UpdateModelMatrix(); }; GameObject.cpp: #include "GameObject.h" #include <glm/gtc/matrix_transform.hpp> GameObject::GameObject() : position(0.0f), rotation(0.0f), scale(1.0f) { } GameObject::~GameObject() { if (initialized) { Shutdown(); } } void GameObject::Initialize(const Mesh& mesh, const Material& material) { this->mesh = mesh; // copy or share mesh data this->material = material; // copy or share material data 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(); 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) 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); } Terrain.h: #pragma once #include "Simplex.h" #include "Mesh.h" #include "Material.h" #include "GameObject.h" class Terrain { public: Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue); ~Terrain(); void GenerateTerrain(); GameObject* GetTerrainObject(); private: void GenerateHeightMap(); void ConvertHeightMapToMeshData(); int seed; int worldSize; float scale; VkDevice* device; VkPhysicalDevice* physicalDevice; VkCommandPool* commandPool; VkQueue* graphicsQueue; SimplexNoise noise; std::vector<std::vector<float>> heightMap; std::vector<Vertex> vertices; std::vector<uint32_t> indices; Mesh terrainMesh; Material terrainMaterial; GameObject terrainObject; }; Terrain.cpp: #include "Terrain.h" Terrain::Terrain(int seed, int worldSize, float scale, VkDevice* device, VkPhysicalDevice* physicalDevice, VkCommandPool* commandPool, VkQueue* graphicsQueue) : seed(seed), worldSize(worldSize), scale(scale), noise(seed), device(device), physicalDevice(physicalDevice), commandPool(commandPool), graphicsQueue(graphicsQueue) { } Terrain::~Terrain() { // Cleanup any resources associated with the Terrain class terrainMesh.Cleanup(); terrainMaterial.Cleanup(); } void Terrain::GenerateHeightMap() { heightMap = std::vector<std::vector<float>>(worldSize, std::vector<float>(worldSize, 0.0f)); for (int x = 0; x < worldSize; ++x) { for (int z = 0; z < worldSize; ++z) { float noiseValue = noise.noise(x * scale, z * scale); heightMap[x][z] = noiseValue; } } } void Terrain::ConvertHeightMapToMeshData() { // … Convert height map to vertices and indices (code from the previous example) } void Terrain::GenerateTerrain() { GenerateHeightMap(); ConvertHeightMapToMeshData(); terrainMesh.Initialize(vertices, indices, *device, *physicalDevice, *commandPool, *graphicsQueue); // Initialize terrainMaterial (shaders, textures, etc.) as needed terrainObject.Initialize(terrainMesh, terrainMaterial); } GameObject* Terrain::GetTerrainObject() { return &terrainObject; } Material.h: #pragma once #include <vulkan/vulkan.h> #include "Texture.h" #include "Shader.h" class Material { public: Material(); ~Material(); void Initialize(const Shader& vertexShader, const Shader& fragmentShader, const Texture& texture, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool); void Cleanup(); VkDescriptorSet GetDescriptorSet() const; VkPipelineLayout GetPipelineLayout() const; private: VkDevice device; Shader vertexShader; Shader fragmentShader; Texture texture; VkDescriptorSet descriptorSet; VkPipelineLayout pipelineLayout; }; 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 Shader& vertexShader, const Shader& fragmentShader, const Texture& texture, VkDevice device, VkDescriptorSetLayout descriptorSetLayout, VkDescriptorPool descriptorPool) { this->device = device; this->vertexShader = vertexShader; // copy or share vertex shader data this->fragmentShader = fragmentShader; // copy or share fragment shader data this->texture = texture; // copy or share texture data // Create descriptor set for the material // … // Create pipeline layout for the material // … } 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; } 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); void Cleanup(); VkImageView GetImageView() const; VkSampler GetSampler() const; 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… }; Texture.cpp: #include "Texture.h" #include "BufferUtils.h" #include <iostream> Texture::Texture() : device(VK_NULL_HANDLE), image(VK_NULL_HANDLE), imageMemory(VK_NULL_HANDLE), imageView(VK_NULL_HANDLE), sampler(VK_NULL_HANDLE) { } Texture::~Texture() { if (initialized) { Cleanup(); } } void Texture::LoadFromFile(const std::string& filename, VkDevice device, VkPhysicalDevice physicalDevice, VkCommandPool commandPool, VkQueue graphicsQueue) { this->device = device; this->physicalDevice = physicalDevice; this->commandPool = commandPool; this->graphicsQueue = graphicsQueue; this->initialized = true; // Load image from file using stb_image int width, height, channels; stbi_uc* pixels = stbi_load(filename.c_str(), &width, &height, &channels, STBI_rgb_alpha); if (!pixels) { throw std::runtime_error("Failed to load texture image!"); } // Calculate the number of mip levels uint32_t mipLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(width, height)))) + 1; // Create a buffer to store the image data VkDeviceSize imageSize = width * height * 4; VkBuffer stagingBuffer; VkDeviceMemory stagingBufferMemory; // Create and fill the buffer // … // Create the staging buffer for transferring image data VkBufferCreateInfo bufferCreateInfo{}; bufferCreateInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; bufferCreateInfo.size = imageSize; bufferCreateInfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; bufferCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if (vkCreateBuffer(device, &bufferCreateInfo, nullptr, &stagingBuffer) != VK_SUCCESS) { throw std::runtime_error("Failed to create staging buffer!"); } VkMemoryRequirements memoryRequirements; vkGetBufferMemoryRequirements(device, stagingBuffer, &memoryRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memoryRequirements.size; allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memoryRequirements.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); if (vkAllocateMemory(device, &allocInfo, nullptr, &stagingBufferMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate staging buffer memory!"); } // Create the staging buffer and staging buffer memory BufferUtils::CreateBuffer(device, physicalDevice, imageSize,VK_BUFFER_USAGE_TRANSFER_SRC_BIT,VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,stagingBuffer, stagingBufferMemory); vkBindBufferMemory(device, stagingBuffer, stagingBufferMemory, 0); // Copy image data to the buffer void* bufferData; vkMapMemory(device, stagingBufferMemory, 0, imageSize, 0, &bufferData); memcpy(bufferData, pixels, static_cast<size_t>(imageSize)); vkUnmapMemory(device, stagingBufferMemory); // Free the stb_image buffer stbi_image_free(pixels); // Create vkImage, copy buffer to image, and create imageView and sampler // … CreateImage(width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); CreateImageView(VK_FORMAT_R8G8B8A8_SRGB, VK_IMAGE_ASPECT_COLOR_BIT, mipLevels); CreateSampler(mipLevels); CopyBufferToImage(stagingBuffer, width, height); // Cleanup the staging buffer and staging buffer memory // … // Destroy the staging buffer and free the staging buffer memory vkDestroyBuffer(device, stagingBuffer, nullptr); vkFreeMemory(device, stagingBufferMemory, nullptr); } void Texture::Cleanup() { vkDestroySampler(device, sampler, nullptr); vkDestroyImageView(device, imageView, nullptr); vkDestroyImage(device, image, nullptr); vkFreeMemory(device, imageMemory, nullptr); this->initialized = false; } VkImageView Texture::GetImageView() const { return imageView; } VkSampler Texture::GetSampler() const { return sampler; } void Texture::CreateImage(uint32_t width, uint32_t height, uint32_t mipLevels, VkSampleCountFlagBits numSamples, VkFormat format, VkImageTiling tiling, VkImageUsageFlags usage, VkMemoryPropertyFlags properties) { VkImageCreateInfo imageInfo{}; imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageInfo.imageType = VK_IMAGE_TYPE_2D; imageInfo.extent.width = width; imageInfo.extent.height = height; imageInfo.extent.depth = 1; imageInfo.mipLevels = mipLevels; imageInfo.arrayLayers = 1; imageInfo.format = format; imageInfo.tiling = tiling; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = usage; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageInfo.samples = numSamples; imageInfo.flags = 0; if (vkCreateImage(device, &imageInfo, nullptr, &image) != VK_SUCCESS) { throw std::runtime_error("Failed to create image!"); } VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements(device, image, &memRequirements); VkMemoryAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; allocInfo.allocationSize = memRequirements.size; allocInfo.memoryTypeIndex = BufferUtils::FindMemoryType(physicalDevice, memRequirements.memoryTypeBits, properties); if (vkAllocateMemory(device, &allocInfo, nullptr, &imageMemory) != VK_SUCCESS) { throw std::runtime_error("Failed to allocate image memory!"); } vkBindImageMemory(device, image, imageMemory, 0); } void Texture::TransitionImageLayout(VkImageLayout oldLayout, VkImageLayout newLayout, uint32_t mipLevels) { // … // Create a one-time-use command buffer and record image layout transition commands // … VkImageMemoryBarrier barrier{}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.oldLayout = oldLayout; barrier.newLayout = newLayout; barrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; barrier.image = image; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.levelCount = mipLevels; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.layerCount = 1; // … } void Texture::CreateImageView(VkFormat format, VkImageAspectFlags aspectFlags, uint32_t mipLevels) { VkImageViewCreateInfo viewInfo{}; viewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; viewInfo.image = image; viewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D; viewInfo.format = format; viewInfo.subresourceRange.aspectMask = aspectFlags; viewInfo.subresourceRange.baseMipLevel = 0; viewInfo.subresourceRange.levelCount = mipLevels; viewInfo.subresourceRange.baseArrayLayer = 0; viewInfo.subresourceRange.layerCount = 1; if (vkCreateImageView(device, &viewInfo, nullptr, &imageView) != VK_SUCCESS) { throw std::runtime_error("Failed to create texture image view!"); } } void Texture::CreateSampler(uint32_t mipLevels) { VkSamplerCreateInfo samplerInfo{}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.mipLodBias = 0.0f; samplerInfo.minLod = 0.0f; samplerInfo.maxLod = static_cast<float>(mipLevels); if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS) { throw std::runtime_error("Failed to create texture sampler!"); } } void Texture::CopyBufferToImage(VkBuffer buffer, uint32_t width, uint32_t height) { // Create a one-time-use command buffer VkCommandBufferAllocateInfo allocInfo{}; allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocInfo.commandPool = commandPool; allocInfo.commandBufferCount = 1; VkCommandBuffer commandBuffer; vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer); VkCommandBufferBeginInfo beginInfo{}; beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; // Record buffer to image copy command in the command buffer vkBeginCommandBuffer(commandBuffer, &beginInfo); VkBufferImageCopy region{}; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset = { 0, 0, 0 }; region.imageExtent = { width, height, 1 }; vkCmdCopyBufferToImage( commandBuffer, buffer, image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region ); // End command buffer recording vkEndCommandBuffer(commandBuffer); // Submit command buffer VkSubmitInfo submitInfo{}; submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &commandBuffer; vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE); vkQueueWaitIdle(graphicsQueue); // Free command buffer vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer); } 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); private: VkDevice device; std::vector<Vertex> vertices; std::vector<uint32_t> indices; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; VkBuffer indexBuffer; VkDeviceMemory indexBufferMemory; }; 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; // 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; } I have a texture image called "texture.png" in "C:\textures\" and shaders "vert.spv" and "frag.spv" sitting in "C:\shaders\". How can I modify the code to use this texture and shaders to render the terrain that is initialized in Engine::Initialize()?
c31709fb43f182ba23043ea45e314677
{ "intermediate": 0.37253791093826294, "beginner": 0.43056100606918335, "expert": 0.1969011276960373 }
7,282
i have an asp.net mvc core project, my domain is mmm.com and it works, but www.mmm.com doesn't work, i applied this code to my web.config : "<rewrite> <rules> <rule name="Redirect to non-www" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{HTTP_HOST}" pattern="^www.villaonline.co$" /> </conditions> <action type="Redirect" url="http://villaonline.co/{R:0}" redirectType="Permanent" /> </rule> </rules> </rewrite>" now mmm.com is not working, solution?
96121b69c5edb6e66babf34562506333
{ "intermediate": 0.5475650429725647, "beginner": 0.2961856424808502, "expert": 0.15624935925006866 }
7,283
I want to create an API using laravel which will do the below jobs, this API will take everything from request and save all its body and also the response body as a document to mongodb collection. this API will also log that request and its response to a file. it would be perfect if we make a file everyday and compress it to a gz file to store all these request daily.
85862012d3814b6a8de48e9904e084c0
{ "intermediate": 0.8547081351280212, "beginner": 0.06339718401432037, "expert": 0.08189474046230316 }
7,284
class StreamView(Screen): output = StringProperty() event = None def on_enter(self): app = App.get_running_app() self.output = app.data #self.capture = cv2.VideoCapture(self.output) # RTSP URL print("print after setting wrong adress") b = Button() b.bind(on_press=lambda instance, button_id="i": gotomainscreen(button_id)) self.add_widget(b) self.image = Image() self.add_widget(self.image) #Clock.schedule_interval(self.update, 1.0 / 30.0) # 30 fps self.event = Clock.schedule_interval(self.update, 1.0 / 30.0) # 30 fps def gotomainscreen(x): app = App.get_running_app() app.root.current = "Main" def update(self, dt): ret, frame = self.capture.read() print("tik tok") if ret: buf = cv2.flip(frame, 0).tostring() # flip & convert to bytes texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') texture.blit_buffer(buf, colorfmt='bgr', bufferfmt='ubyte') self.image.texture = texture def on_leave(self): self.capture.release() self.event.cancel() cv2.destroyAllWindows()
7fb0997c3e269f2664f55293818ed58d
{ "intermediate": 0.32127898931503296, "beginner": 0.534351110458374, "expert": 0.14436990022659302 }
7,285
Optimise this code : // Vérifier l'état actif de l'extension browser.storage.local.get("isActive").then(function (result) { var isExtensionActive = result.isActive; // Récupérez la couleur enregistrée en utilisant l'API browser.storage.local.get() browser.storage.local.get("color").then(function (result) { var color = result.color; if (color) { // Appliquez la couleur au code CSS en utilisant document.documentElement.style document.documentElement.style.setProperty("--antiwoke-highlight-color", color); } }); browser.storage.local.get("hover").then(function (result) { var hover = result.hover; if (hover) { // Appliquez la couleur au code CSS en utilisant document.documentElement.style document.documentElement.style.setProperty("--afficher-hover", hover); } }); browser.storage.local.get("invisible").then(function (result) { var invisible = result.invisible; var elements = document.getElementsByTagName("antiwoke-text"); // Get all <antiwoke> tags if (invisible == "oui") { for (var i = 0; i < elements.length; i++) { elements[i].classList.remove("antiwoke-highlight"); } } else { for (var i = 0; i < elements.length; i++) { elements[i].classList.add("antiwoke-highlight"); } } }); // Exécuter le code uniquement si l'extension est active if (isExtensionActive) { console.log("Extension active"); console.time("Remplacements"); function ajouterNumeroEtRenommerNomsDeGroupes(tableau) { return tableau.map((element, index) => { const patternAvecNumero = new RegExp( element.pattern.source.replace(/\<(\w+)\>/g, `<$1${index}>`) ); const modificationAvecNouveauxNoms = element.modification.replace( /(\$\{match\.groups\.\w+)}/g, `$1${index}}` ); return { ...element, pattern: patternAvecNumero, modification: modificationAvecNouveauxNoms, }; }); } const remplacements = ajouterNumeroEtRenommerNomsDeGroupes(remplacements0); const regex = new RegExp( `${groupeAvantMot}(${remplacements .map((r) => `(${r.pattern.source})`) .join("|")})${groupeApresMot}`, "gmu" ); function remplacer() { const nodes = getTextNodes(document.body); let remplacementsEffectues = false; nodes.forEach((node) => { if ( !node.parentNode.closest("remplacement-text") && !hasAncestorOfType(node, ["STYLE", "SCRIPT"]) ) { const content = node.textContent; let replacedContent = content; let match = regex.exec(content); if (match) { const remplacement = remplacements.find((r) => r.pattern.test(match[0])); const nouveauMot = remplacement.modification.replace( /\$\{match\.groups\.(\w+)\}/g, (m, p1) => match.groups[p1] ); const avant_motLength = match.groups.avant_mot.length; const apres_motLength = match.groups.apres_mot.length; const slicedMatch = apres_motLength === 0 ? match[0] : match[0].slice(0, -apres_motLength); const finalSlicedMatch = avant_motLength === 0 ? slicedMatch : slicedMatch.slice(avant_motLength); replacedContent = replacedContent.replace( match[0], match.groups.avant_mot + "<remplacement-text><woke-text>" + finalSlicedMatch + "</woke-text><antiwoke-text>" + nouveauMot + "</antiwoke-text></remplacement-text>" + match.groups.apres_mot ); remplacementsEffectues = true; } if (replacedContent !== content) { const span = document.createElement("span"); span.innerHTML = replacedContent; node.replaceWith(span); } } }); return remplacementsEffectues; } let remplacementsEffectues = true; while (remplacementsEffectues) { remplacementsEffectues = remplacer(); } function getTextNodes(node) { const textNodes = []; if (node.nodeType === Node.TEXT_NODE) { textNodes.push(node); } else { const children = node.childNodes; for (let i = 0; i < children.length; i++) { textNodes.push(...getTextNodes(children[i])); } } return textNodes; } function hasAncestorOfType(node, types) { if (!node.parentNode) { return false; } else if (types.includes(node.parentNode.nodeName)) { return true; } else { return hasAncestorOfType(node.parentNode, types); } } console.timeEnd("Remplacements"); } else { console.log("Extension désactivée"); } });
f2c2baa2730e626ccbfe03f9af244359
{ "intermediate": 0.2525586485862732, "beginner": 0.5177513957023621, "expert": 0.22968994081020355 }
7,286
pring.config.location not picking log4j2.xml
2a7674eacb83ec0f1c8cfb5c5ff35ec6
{ "intermediate": 0.3494507074356079, "beginner": 0.34086543321609497, "expert": 0.30968382954597473 }
7,287
How to integrate this space to the telegram to send input and get output as a reply to the telegram
a8e085a80f639c1372d2ba2474a3135f
{ "intermediate": 0.3867558538913727, "beginner": 0.19107875227928162, "expert": 0.4221654236316681 }
7,288
Make a code for python for a quiz about Present Simple. I want there to be five questions, each with 4 answers
73612cfc55c8d60d26f77a035fc3bec7
{ "intermediate": 0.33575984835624695, "beginner": 0.45654475688934326, "expert": 0.20769540965557098 }
7,289
This is my current ide code for gui highsum 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.run(); } 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(); } } } import Model.; import Controller.; import View.; import GUIExample.LoginDialog; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; 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); } public void run() { //starts the game! gc.run(); } 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 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; public GameController(Dealer dealer,Player player,ViewController view) { this.dealer = dealer; this.player = player; this.view = view; this.chipsOnTable = 0; } 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, true); this.dealer.dealCardTo(this.dealer, true); } this.dealer.dealCardTo(this.player, false); this.dealer.dealCardTo(this.dealer, false); 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 java.awt.; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.; import Model.; 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”); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); run(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); add(gameTablePanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.SOUTH); add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); pack(); setVisible(true); } public void run() { for (int i = 0; i < 5; i++) { dealer.dealCardTo(dealer); dealer.dealCardTo(player); gameTablePanel.repaint(); pause(); } shufflingLabel.setVisible(false); gameTablePanel.repaint(); } private void pause() { try{ Thread.sleep(500); }catch(Exception e){} } } package GUIExample; import java.awt.; import javax.swing.; import Model.; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; private ImageIcon cardBackImage; public GameTablePanel(Dealer dealer, Player player) { setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); cardBackImage = new ImageIcon(“images/back.png”); this.dealer = dealer; this.player = player; } public void paintComponent(Graphics g) { super.paintComponent(g); int x = 50; int y = 70; // Add the label “Dealer” g.setColor(Color.BLACK); g.setFont(new Font(“Arial”, Font.PLAIN, 18)); g.drawString(“Dealer”, x, y - 20); int i = 0; for (Card c : dealer.getCardsOnHand()) { // Display dealer cards if (i == 0) { cardBackImage.paintIcon(this, g, x, y); i++; } else { c.paintIcon(this, g, x, y); } x += 200; } // Display “Deck” label g.drawString(“Deck”, x, y + 100); // Display player cards x = 50; y = 550; // Add the label “Player” g.setColor(Color.BLACK); g.setFont(new Font(“Arial”, Font.PLAIN, 18)); g.drawString(“Player”, x, y - 20); for (Card c : player.getCardsOnHand()) { c.paintIcon(this, g, x, y); x += 200; } // Display “Chips on the table:” g.setColor(Color.BLACK); g.setFont(new Font(“Arial”, Font.PLAIN, 18)); g.drawString(“Chips on the table:”, x - 950, y - 250); } } 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, boolean faceDown) { Card card = deck.dealCard(); //take a card out from the deck if (faceDown) { card.setFaceDown(true); } 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 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.Keyboard; 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: “Game Start The game starts with the dealer shuffles the deck of cards. The dealer will deal (distribute) the cards to the players. The dealer make two passes so that the players and the dealer have two cards each. Two passes means that the dealer must distribute the cards in such a way that, the first card belongs to the player, the second card belongs to the dealer, the third card belongs to the player and the fourth card belows to the dealer. Round 1 The first card of the dealer and player are both hidden, that is face down. The dealer and player can view their own hidden first card. The second card is visible to both the dealer and player. The player with the highest second visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 2 The dealer make one pass. Dealer and player each have 3 cards now. The player with the highest third visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet or choose to quit the current game. Dearler is not allowed to quit the game. If the human player choose to quit at this round, all the chips on the table belongs to the dealer and the current game ends here. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 3 Similar to round 2. Round 4 Similar to round 2 plus the following rule: Each player compares the values of cards hold by other players at the end of each game to determine the winner. The player with the highest accumulate values win the game. The winner gets all the bet on the table. Next Game All the cards on the table are shuffled and placed at the end of the deck. The game will start again unless the player choose to leave the game. Please note that the above game description is a simplified version of the real game and there are also many different versions in different countries. The specifications given in this document are more than sufficient for you to complete this assignment. If you have doubts on the game logic, please feel free to clarify with your tutor. Do take note that the emphasis of this assignment is to implement the game logic using Object-oriented programming.” Print the codes that have made changes to according to the requirements
626ae781a0fed4aa41de0452282cc456
{ "intermediate": 0.2341250479221344, "beginner": 0.5831007957458496, "expert": 0.1827741116285324 }
7,290
is it possible to integrate sepicific spaces from hugging face to a telegram bot to send inputs and get outputs as a message
998e773efe72cf4ea8bed9f249b27fd4
{ "intermediate": 0.27981695532798767, "beginner": 0.1347300112247467, "expert": 0.5854530334472656 }
7,291
What is event-based communication between a client and a server?
eb66e4d63a2347d2bc69881da499231f
{ "intermediate": 0.2884734869003296, "beginner": 0.24372337758541107, "expert": 0.46780309081077576 }
7,292
python print string until string not equal empty string
06ab589fe82ebe37a09eec57c2ce5922
{ "intermediate": 0.4119440019130707, "beginner": 0.2954324185848236, "expert": 0.2926235795021057 }
7,293
Using only expressjs, simple example of event based communication between client and server
b8d017b1c861ed6f2e41d3df1409ad09
{ "intermediate": 0.43804484605789185, "beginner": 0.29689550399780273, "expert": 0.2650596499443054 }
7,294
Using socket.io and expressjs, simple example of event based communication between client and server, also add middleware using expressjs
8821b6932c514b1fbeb86360444f7cbb
{ "intermediate": 0.6598401069641113, "beginner": 0.1509115844964981, "expert": 0.18924827873706818 }
7,295
can you write me a hello world python script
1b8780827270c9e6b93b986f0903f22c
{ "intermediate": 0.3178059458732605, "beginner": 0.3003872334957123, "expert": 0.3818068206310272 }
7,296
is there a free version to use GPT 3.5 for my telegram bot
9f5d94f16d5679182438493ffb871b84
{ "intermediate": 0.3788239657878876, "beginner": 0.15758638083934784, "expert": 0.4635896384716034 }
7,297
This is my current ide code for gui highsum 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.run(); } 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(); } } } import Model.*; import Controller.*; import View.*; import GUIExample.LoginDialog; public class HighSum { private Dealer dealer; private Player player; private ViewController view; private GameController gc; 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); } public void run() { // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); if (!gc.getPlayerQuitStatus()) { char r = this.view.getPlayerNextGame(); if (r == 'n') { carryOn = false; } } else { 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++) { // Code remains same until here // Check if the player wants to follow or quit char r; if (round == 1) { r = this.view.getPlayerFollowOrNot(this.player, chipsToBet, round); } else { r = this.view.getPlayerFollowOrNot(this.player, chipsToBet, round); if (r == 'q') { playerQuit = true; break; } } } if (playerQuit) { this.view.displayPlayerNameAndLeftOverChips(this.player); this.view.displayPlayerQuit(); } else { // Rest of the code remains same } } 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 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; 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, true); this.dealer.dealCardTo(this.dealer, true); } this.dealer.dealCardTo(this.player, false); this.dealer.dealCardTo(this.dealer, false); 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 java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import Model.*; 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"); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); run(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); add(gameTablePanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.SOUTH); add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); pack(); setVisible(true); } public void run() { for (int i = 0; i < 5; i++) { dealer.dealCardTo(dealer); dealer.dealCardTo(player); gameTablePanel.repaint(); pause(); } shufflingLabel.setVisible(false); gameTablePanel.repaint(); } private void pause() { try{ Thread.sleep(500); }catch(Exception e){} } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; private ImageIcon cardBackImage; public GameTablePanel(Dealer dealer, Player player) { setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); cardBackImage = new ImageIcon("images/back.png"); this.dealer = dealer; this.player = player; } public void paintComponent(Graphics g) { super.paintComponent(g); int x = 50; int y = 70; // Add the label "Dealer" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Dealer", x, y - 20); int i = 0; for (Card c : dealer.getCardsOnHand()) { // Display dealer cards if (i == 0) { cardBackImage.paintIcon(this, g, x, y); i++; } else { c.paintIcon(this, g, x, y); } x += 200; } // Display "Deck" label g.drawString("Deck", x, y + 100); // Display player cards x = 50; y = 550; // Add the label "Player" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Player", x, y - 20); for (Card c : player.getCardsOnHand()) { c.paintIcon(this, g, x, y); x += 200; } // Display "Chips on the table:" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Chips on the table:", x - 950, y - 250); } } 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, boolean faceDown) { Card card = deck.dealCard(); //take a card out from the deck if (faceDown) { card.setFaceDown(true); } 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 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.Keyboard; 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. Page 2 Copyright SCIT, University of Wollongong, 2023 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. Page 3 Copyright SCIT, University of Wollongong, 2023 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." and this is how the game works: "Game Start The game starts with the dealer shuffles the deck of cards. The dealer will deal (distribute) the cards to the players. The dealer make two passes so that the players and the dealer have two cards each. Two passes means that the dealer must distribute the cards in such a way that, the first card belongs to the player, the second card belongs to the dealer, the third card belongs to the player and the fourth card belows to the dealer. Round 1 The first card of the dealer and player are both hidden, that is face down. The dealer and player can view their own hidden first card. The second card is visible to both the dealer and player. The player with the highest second visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 2 The dealer make one pass. Dealer and player each have 3 cards now. The player with the highest third visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet or choose to quit the current game. Dearler is not allowed to quit the game. If the human player choose to quit at this round, all the chips on the table belongs to the dealer and the current game ends here. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 3 Similar to round 2. Round 4 Similar to round 2 plus the following rule: Each player compares the values of cards hold by other players at the end of each game to determine the winner. The player with the highest accumulate values win the game. The winner gets all the bet on the table. Next Game All the cards on the table are shuffled and placed at the end of the deck. The game will start again unless the player choose to leave the game. Please note that the above game description is a simplified version of the real game and there are also many different versions in different countries. The specifications given in this document are more than sufficient for you to complete this assignment. If you have doubts on the game logic, please feel free to clarify with your tutor. Do take note that the emphasis of this assignment is to implement the game logic using Object-oriented programming." Find for errors and make sure the program works according to the game logic and requirements
0ccc5ff2776ba64b71f4b7ecff12aacf
{ "intermediate": 0.2922215461730957, "beginner": 0.5476957559585571, "expert": 0.16008268296718597 }
7,298
Hello, I want to mute a channel through telethon. Can you help me write the code?
e0ea27e59539e7ba5e706e7831af2dbc
{ "intermediate": 0.380113422870636, "beginner": 0.26016736030578613, "expert": 0.35971927642822266 }
7,299
i have canvas that have { DrawConnections(state, viewModel) DrawPackets(viewModel) DrawDevices(state, viewModel) } my function: @Composable fun DrawPackets( viewModel: EmulatorViewModel ) { val pos1 = Offset(0f, 0f) val pos2 = Offset(1000f, 1000f) var circlePosition by remember { mutableStateOf(pos1) } animateOffsetAsState( targetValue = pos2, animationSpec = tween(durationMillis = 10000, easing = LinearEasing) ) { circlePosition = it } Box( Modifier .size(50.dp) .background(Color.White) .offset(circlePosition.x.dp, circlePosition.y.dp) ) } i want to call it from: LaunchedEffect(true) { viewModel.eventFlow.collectLatest { event -> when (event) { is EmulatorViewModel.UiEvent.ShowToast -> { val duration = Toast.LENGTH_SHORT Toast.makeText( context, event.message, duration ).show() } is EmulatorViewModel.UiEvent.AnimatePacket -> { // call it from here } } } } how can i do that if i cant call composables outside composable functionso?
6254c6599a9b60da770da6cdee7e16da
{ "intermediate": 0.4134310781955719, "beginner": 0.3647320568561554, "expert": 0.2218369096517563 }
7,300
This is my current ide code for gui highsum 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.run(); } 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(); } } } import Model.*; import Controller.*; import View.*; import GUIExample.LoginDialog; 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 void run() { // Starts the game! boolean carryOn = true; while (carryOn) { runOneRound(); if (!gc.getPlayerQuitStatus()) { char r = this.view.getPlayerNextGame(); if (r == 'n') { carryOn = false; } } else { 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++) { // Code remains same until here // Check if the player wants to follow or quit char r; if (round == 1) { r = this.view.getPlayerFollowOrNot(this.player, chipsToBet, round); } else { r = this.view.getPlayerFollowOrNot(this.player, chipsToBet, round); if (r == 'q') { playerQuit = true; break; } } } 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 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; 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, true); this.dealer.dealCardTo(this.dealer, true); } this.dealer.dealCardTo(this.player, false); this.dealer.dealCardTo(this.dealer, false); 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 java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; import Model.*; 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"); playButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { shufflingLabel.setVisible(true); run(); } }); quitButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.exit(0); } }); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(playButton); buttonsPanel.add(quitButton); add(gameTablePanel, BorderLayout.CENTER); add(buttonsPanel, BorderLayout.SOUTH); add(shufflingLabel, BorderLayout.NORTH); shufflingLabel.setVisible(false); pack(); setVisible(true); } public void run() { for (int i = 0; i < 5; i++) { dealer.dealCardTo(dealer); dealer.dealCardTo(player); gameTablePanel.repaint(); pause(); } shufflingLabel.setVisible(false); gameTablePanel.repaint(); } private void pause() { try{ Thread.sleep(500); }catch(Exception e){} } } package GUIExample; import java.awt.*; import javax.swing.*; import Model.*; public class GameTablePanel extends JPanel { private Player player; private Dealer dealer; private ImageIcon cardBackImage; public GameTablePanel(Dealer dealer, Player player) { setBackground(Color.GREEN); setPreferredSize(new Dimension(1024, 768)); cardBackImage = new ImageIcon("images/back.png"); this.dealer = dealer; this.player = player; } public void paintComponent(Graphics g) { super.paintComponent(g); int x = 50; int y = 70; // Add the label "Dealer" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Dealer", x, y - 20); int i = 0; for (Card c : dealer.getCardsOnHand()) { // Display dealer cards if (i == 0) { cardBackImage.paintIcon(this, g, x, y); i++; } else { c.paintIcon(this, g, x, y); } x += 200; } // Display "Deck" label g.drawString("Deck", x, y + 100); // Display player cards x = 50; y = 550; // Add the label "Player" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Player", x, y - 20); for (Card c : player.getCardsOnHand()) { c.paintIcon(this, g, x, y); x += 200; } // Display "Chips on the table:" g.setColor(Color.BLACK); g.setFont(new Font("Arial", Font.PLAIN, 18)); g.drawString("Chips on the table:", x - 950, y - 250); } } 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, boolean faceDown) { Card card = deck.dealCard(); //take a card out from the deck if (faceDown) { card.setFaceDown(true); } 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 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.Keyboard; 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. Page 2 Copyright SCIT, University of Wollongong, 2023 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. Page 3 Copyright SCIT, University of Wollongong, 2023 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." These are the game logic and rules to follow: "Game Start The game starts with the dealer shuffles the deck of cards. The dealer will deal (distribute) the cards to the players. The dealer make two passes so that the players and the dealer have two cards each. Two passes means that the dealer must distribute the cards in such a way that, the first card belongs to the player, the second card belongs to the dealer, the third card belongs to the player and the fourth card belows to the dealer. Round 1 The first card of the dealer and player are both hidden, that is face down. The dealer and player can view their own hidden first card. The second card is visible to both the dealer and player. The player with the highest second visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 2 The dealer make one pass. Dealer and player each have 3 cards now. The player with the highest third visible card will make a “call” by stating the amount to bet. The other player will need to place the same amount of bet or choose to quit the current game. Dearler is not allowed to quit the game. If the human player choose to quit at this round, all the chips on the table belongs to the dealer and the current game ends here. Both the bet amount from dealer and player will be placed on the table. The dealer is not allowed to quit the game. Round 3 Similar to round 2. Round 4 Similar to round 2 plus the following rule: Each player compares the values of cards hold by other players at the end of each game to determine the winner. The player with the highest accumulate values win the game. The winner gets all the bet on the table. Next Game All the cards on the table are shuffled and placed at the end of the deck. The game will start again unless the player choose to leave the game. Please note that the above game description is a simplified version of the real game and there are also many different versions in different countries. The specifications given in this document are more than sufficient for you to complete this assignment. If you have doubts on the game logic, please feel free to clarify with your tutor. Do take note that the emphasis of this assignment is to implement the game logic using Object-oriented programming." There are 2 errors in the code: "Description Resource Path Location Type The method dealCardTo(Player, boolean) in the type Dealer is not applicable for the arguments (Dealer) GameTableFrame.java /A3Skeleton/src/GUIExample line 58 Java Problem The method dealCardTo(Player, boolean) in the type Dealer is not applicable for the arguments (Player) GameTableFrame.java /A3Skeleton/src/GUIExample line 59 Java Problem "
f3564f1e0a080dbabecb54dbc5bc171a
{ "intermediate": 0.2949845790863037, "beginner": 0.5130499601364136, "expert": 0.19196540117263794 }
7,301
hello
8ac764503b9622e3e0007a71db7969d1
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
7,302
Create a game where the goal is to guess a random number between 1 and 100 in c#
250eb77c140c6b2529bd68798d2d0daa
{ "intermediate": 0.38131147623062134, "beginner": 0.35393401980400085, "expert": 0.2647545039653778 }
7,303
ok I want the steps to install erpnext ON M1 MAC USING DOCKER AND DOCKER COMPOSER I CREATED IMAGE ON DESKTOPTHAT I WANT ALL ERPNEXT DOCUMENTS TO BE SAVED ON IT IT’S AFPS IMAGE ON DESKTOP CALLED BerkimpireHathaway
1dceea62fea20b2494db9d2ac896a1ea
{ "intermediate": 0.4219444692134857, "beginner": 0.12312186509370804, "expert": 0.45493370294570923 }
7,304
I need to copy candle data from tradingview to txt, is there a way to do that?
e6e7021769a81e8d28ae0abd4ba326c3
{ "intermediate": 0.5976595282554626, "beginner": 0.13040517270565033, "expert": 0.2719353139400482 }
7,305
IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Customers') BEGIN CREATE TABLE Customers ( CustomersID INT PRIMARY KEY NOT NULL, LastName NVARCHAR(30) NOT NULL, FirstName NVARCHAR(30) NOT NULL, City NVARCHAR(15) NULL, Postalcode NVARCHAR(10) NULL, Country NVARCHAR(15) NULL, Phone NVARCHAR(24) NULL ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Orders') BEGIN CREATE TABLE Orders ( OrderID INT PRIMARY KEY NOT NULL, CustomersID INT NULL, Order_date DATETIME NULL, Shipped_date DATETIME NULL, TransportCost INT NULL CONSTRAINT "order_transport" DEFAULT (0), ShipVia INT NULL, FOREIGN KEY (CustomersID) REFERENCES Customers(CustomersID), FOREIGN KEY (ShipVia) REFERENCES Shippers(ShipperID) ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Shippers') BEGIN CREATE TABLE Shippers ( ShipperID INT PRIMARY KEY NOT NULL, CompanyName NVARCHAR(40) NOT NULL, phone NVARCHAR(24) NULL ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Suppliers') BEGIN CREATE TABLE Suppliers ( SupplierID INT PRIMARY KEY NOT NULL, CompanyName NVARCHAR(40) NOT NULL, ContactName NVARCHAR(30) NULL, Address NVARCHAR(60) NULL, City NVARCHAR(15) NULL, Region NVARCHAR(15) NULL, PostalCode NVARCHAR(10) NULL, Phone NVARCHAR(24) NULL ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Supplier_product') BEGIN CREATE TABLE Supplier_product ( SupplierID INT, ProductID INT, PRIMARY KEY (SupplierID, ProductID), FOREIGN KEY (SupplierID) REFERENCES Suppliers(SupplierID), FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Products') BEGIN CREATE TABLE Products ( ProductID INT PRIMARY KEY NOT NULL, ProductName NVARCHAR(40) NOT NULL, CategoryID INT NULL, UnitPrice MONEY NULL CONSTRAINT "Prod_unit_price" DEFAULT (0), UnitsInStock INT NULL CONSTRAINT "Prod_units_stock" DEFAULT(0), Discontinued BIT NOT NULL CONSTRAINT "Prod_discontin" DEFAULT(0), FOREIGN KEY (CategoryID) REFERENCES Categories(CategoryID) ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Categories') BEGIN CREATE TABLE Categories ( CategoryID INT PRIMARY KEY NOT NULL, CategoryName NVARCHAR(15) NOT NULL, TextDescription TEXT NULL, Picture IMAGE NULL ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Order_Details') BEGIN CREATE TABLE Order_Details ( OrderID INT NOT NULL, ProductID INT NOT NULL, PRIMARY KEY (OrderID, ProductID), UnitPrice MONEY NOT NULL CONSTRAINT "Order_unit_price" default (0), Quantity INT NOT NULL CONSTRAINT "Order_quantity" default(1), Discount REAL NOT NULL CONSTRAINT "Order_discount" default(0), FOREIGN KEY (OrderID) REFERENCES Orders(OrderID), FOREIGN KEY (ProductID) REFERENCES Products(ProductID), CONSTRAINT "CK_Discount" CHECK (Discount >= 0 and (Discount <= 1)), CONSTRAINT "CK_Quantity" CHECK (Quantity > 0), CONSTRAINT "CK_UnitPrice" CHECK (UnitPrice >= 0) ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Review') BEGIN CREATE TABLE Review ( ReviewID INT PRIMARY KEY NOT NULL, CustomersID INT NULL, ProductID INT NOT NULL, ReviewText TEXT NOT NULL, Rating INT NOT NULL, CreatedDate DATETIME NULL, FOREIGN KEY (CustomersID) REFERENCES Customers(CustomersID), FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'TicketStatusHistory') BEGIN CREATE TABLE TicketStatusHistory ( TicketStatusHistoryID INT PRIMARY KEY NOT NULL, TicketID INT, TicketStatusID INT, LastUpdate NVARCHAR(100) NOT NULL, FOREIGN KEY (TicketID) REFERENCES Ticket(TicketID), FOREIGN KEY (TicketStatusID) REFERENCES TicketStatus(TicketStatusID) ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Ticket') BEGIN CREATE TABLE Ticket ( TicketID INT PRIMARY KEY NOT NULL, Subject NVARCHAR(75) NOT NULL, Description TEXT NOT NULL, Priority BIT NULL, CreatedDate DATETIME NULL, UpdatedDate DATETIME NULL, AgentID INT NULL, CustomersID INT NOT NULL, FOREIGN KEY (AgentID) REFERENCES Agent(AgentID), FOREIGN KEY (CustomersID) REFERENCES Customers(CustomersID) ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'TicketStatus') BEGIN CREATE TABLE TicketStatus ( TicketStatusID INT PRIMARY KEY NOT NULL, Status NVARCHAR(30) NOT NULL ); END; IF NOT EXISTS (SELECT * FROM sys.tables WHERE name = 'Agent') BEGIN CREATE TABLE Agent ( AgentID INT PRIMARY KEY NOT NULL, FirstName NVARCHAR(30) NOT NULL, LastName NVARCHAR(30) NOT NULL, Email NVARCHAR(50) NULL ); END; FA -MI NISTE UPDATE-URI PE BAZA DE DATE, MAI COMPLEXE
22bf51f219627321d89a7aa64187c310
{ "intermediate": 0.28222769498825073, "beginner": 0.5300795435905457, "expert": 0.18769273161888123 }
7,306
write the program code in JavaFX for the selection of oil analogues
a91f0f2ecf419f58087601ff587f43b1
{ "intermediate": 0.4085196554660797, "beginner": 0.15051913261413574, "expert": 0.4409612715244293 }
7,307
class Favorite(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) updated_at = models.DateTimeField(auto_now= True, blank=True, null=True) class Meta: verbose_name = "Favorite" verbose_name_plural = "Favorites" make a use to not use the same company two time. Django restframework
40387bb8bd1657248e44445dd1db83cc
{ "intermediate": 0.34066078066825867, "beginner": 0.35373586416244507, "expert": 0.30560335516929626 }
7,308
Task 'wrapper' not found in project ':app'.
97c003c5f3d1ba6f7df7a4a24043b568
{ "intermediate": 0.3573134243488312, "beginner": 0.33136290311813354, "expert": 0.3113236129283905 }
7,309
can u walk me through making a django chatapp with css and and default django authentication the app should have 3 pages 1 for authentication the second for account creation and the third for the actual chatapp
c30e21f4f2fca973efd88f0cf12ad268
{ "intermediate": 0.7083434462547302, "beginner": 0.1378992199897766, "expert": 0.15375733375549316 }
7,310
plugins { id 'com.android.application' version '8.0.1' } android { namespace 'com.example.myapp_2' compileSdk 33 defaultConfig { applicationId "com.example.myapp_2" minSdk 25 targetSdk 33 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } buildFeatures { viewBinding true } task wrapper(type: Wrapper){ gradleVersion = '7.4.1' } task prepareKotlinBuildScriptModel { } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } configurations.all { resolutionStrategy { force 'com.google.code.findbugs:jsr305:3.0.2' force 'com.google.guava:guava:27.0.1-android' } } } dependencies { implementation 'androidx.wear.tiles:tiles-material:1.1.0-alpha04' def lifecycle_version = "1.1.1" implementation 'com.google.android.material:material:1.9.0' implementation 'androidx.appcompat:appcompat:1.6.1' implementation 'com.google.android.material:material:1.9.0' implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation 'androidx.recyclerview:recyclerview:1.3.0' implementation 'androidx.cardview:cardview:1.0.0' testImplementation 'junit:junit:4.13.2' androidTestImplementation 'androidx.test.ext:junit:1.1.5' androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1' def room_version = "2.5.1" implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" implementation "androidx.work:work-runtime:2.8.1" implementation "com.makeramen:roundedimageview:2.3.0" } The project is using an incompatible version (AGP 8.0.1) of the Android Gradle plugin. Latest supported version is AGP 7.4.1
718a70ef687ccc4ef79d1cec7cdf7392
{ "intermediate": 0.35494813323020935, "beginner": 0.34715086221694946, "expert": 0.2979010343551636 }
7,311
Extract year from timestamp in SQL
445060dddcff909b8f4d50acfc84c21e
{ "intermediate": 0.4350435733795166, "beginner": 0.26820653676986694, "expert": 0.29674986004829407 }
7,312
create a simple electronics diagram using schemdraw
6176aadd9599786e2055faaff035d93c
{ "intermediate": 0.3814908564090729, "beginner": 0.33692148327827454, "expert": 0.28158771991729736 }
7,313
#include <stdio.h> #include <stdlib.h> typedef enum { BEAR, BIRD, PANDA} AnimalType; typedef enum { ALIVE, DEAD } AnimalStatus; typedef struct { int x; int y; } Location; typedef enum { FEEDING, NESTING, WINTERING } SiteType; typedef struct { /** animal can be DEAD or ALIVE*/ AnimalStatus status; /** animal type, bear, bird, panda*/ AnimalType type; /** its location in 2D site grid*/ Location location; } Animal; /*example usage*/ Animal bird, bear, panda; /** type of Hunter*/ typedef struct { /** points indicate the number of animals, a hunter killed*/ int points; /** its location in the site grid*/ Location location; } Hunter; /** type of a site (a cell in the grid)*/ typedef struct { /** array of pointers to the hunters located at this site*/ Hunter **hunters; /** the number of hunters at this site*/ int nhunters; /** array of pointers to the animals located at this site*/ Animal **animals; /** the number of animals at this site*/ int nanimals; /** the type of site*/ SiteType type; } Site; /** 2D site grid*/ typedef struct { /** number of rows, length at the x-coordinate*/ int xlength; /** number of columns, length at the y-coordinate*/ int ylength; /** the 2d site array*/ Site **sites; } Grid; /* initial grid, empty*/ Grid grid = {0, 0, NULL}; /** * @brief initialize grid with random site types * @param xlength * @param ylength * @return Grid */ Grid initgrid(int xlength, int ylength) { grid.xlength = xlength; grid.ylength = ylength; grid.sites = (Site **)malloc(sizeof(Site *) * xlength); for (int i = 0; i < xlength; i++) { grid.sites[i] = (Site *)malloc(sizeof(Site) * ylength); for (int j = 0; j < ylength; j++) { grid.sites[i][j].animals = NULL; grid.sites[i][j].hunters = NULL; grid.sites[i][j].nhunters = 0; grid.sites[i][j].nanimals = 0; double r = rand() / (double)RAND_MAX; SiteType st; if (r < 0.33) st = WINTERING; else if (r < 0.66) st = FEEDING; else st = NESTING; grid.sites[i][j].type = st; } } return grid; } /** * @brief * */ void deletegrid() { for (int i = 0; i < grid.xlength; i++) { free(grid.sites[i]); } free(grid.sites); grid.sites = NULL; grid.xlength = -1; grid.ylength = -1; } /** * @brief prints the number animals and hunters in each site * of a given grid * @param grid */ void printgrid() { for (int i = 0; i < grid.xlength; i++) { for (int j = 0; j < grid.ylength; j++) { Site *site = &grid.sites[i][j]; int count[3] = {0}; /* do not forget to initialize*/ for (int a = 0; a < site->nanimals; a++) { Animal *animal = site->animals[a]; count[animal->type]++; } printf("|%d-{%d, %d, %d}{%d}|", site->type, count[0], count[1], count[2], site->nhunters); } printf("\n"); } } /** * @brief prints the info of a given site * */ void printsite(Site *site) { int count[3] = {0}; /* do not forget to initialize*/ for (int a = 0; a < site->nanimals; a++) { Animal *animal = site->animals[a]; count[animal->type]++; } printf("|%d-{%d,%d,%d}{%d}|", site->type, count[0], count[1], count[2], site->nhunters); } /* ============================================================= TODO: you need to complete following three functions DO NOT CHANGE ANY OF THE FUNCTION NAME OR TYPES ============================================================= */ /** * @brief it moves a given hunter or animal * randomly in the grid * @param args is an animalarray * @return void* */ void *simulateanimal(void *args) { /*TODO: complete this function: get animal type, check if animal dies, then chose random direction and move make sure to update site.animals then sleep */ return NULL; } /** * @brief simulates the moving of a hunter * * @param args * @return void* */ void *simulatehunter(void *args) { /*TODO: get random position and move, then kill all the animals in this site, increase count, then sleep*/ return NULL; } /** * the main function for the simulation */ int main(int argc, char *argv[]) { /*TODO argv[1] is the number of hunters*/ initgrid(5, 5); /*TODO: init threads for each animal, and hunters, the program should end after 1 second */ printgrid(); deletegrid(); } and thats what they want:Every simulation time unit, if any of these animals are (tr:her bir simülasyon zamanında( threadin bekleyip tekrar devam etmesinde, döngü olarak düşünebilirsiniz, farklı tipteki sitelarda aşağıdaki şekilde davranmaktadırlar:) at the NESTING site, then it populates 1 of its kind at that site and moves to a neighboring random location. (tr:NESTİNG siteda kendi cinsinden bir tane daha hayvan oluşturmaktadır. Yani yeni bir thread oluşturmanız gerekiyor. Ve random komşu lokasyona gitmektedir.) at the WINTERING site, All die with 0.5 probability or live and move to a neighboring random location. (tr:WINTERING siteda tüm hayvanlar 0.5 ihtimalle ölmektedirler. Yada random komşu lokasyona gitmektedirler.) at the FEEDING site, All stay there with 0.8 probability or move to a neighboring random location. (tr:FEEDING siteda tüm hayvanlar 0.8 ihtimalle kalmakta yada random komşu lokasyona gitmektedirler.) (simülasyonda rastgele hareket eden yine avcılar bulunmaktadır. Eğer avcılar bir site'a giderse bu bölgedeki tüm hayvanları öldürmektdirler. Öldürülen hayvan sayısı kendi pointleri olarak toplanmaktadır.) The number of hunters are given at the beginning of the program as a command line argument: ./main 2 creates 2 hunters dont change printgrid function Simulation (main thread) Simulation creates 1 thread for each animal, 1 thread for each hunter. Each thread makes a move then sleeps for 1 millisecond. The simulation ends after 1 second. (tr: main threadde her bir hayvan ve her bir hunter için birer thread oluşturmanız ve bunları rastgele pozisyonlardan başlatmanız gerekiyor. Bu threadler 1milisaniye uyumakta ve sonra rastgele komşu pozisyona yukarıda açıklandığı şekilde hareket etmektedirler.) TO DO LIST: Basically what you need to do is: complete the main function, so that it creates 1 thread for each animal, 1 thread for each hunter (tr: main fonksiyonunu tamamlayarak her bir hunter ve animal için birer thread oluşturmasını sağlayınız.) complete the function void *simulateanimal(void *args); that is run by any of the animal threads (tr: void *simulateanimal(void *args); fonksiyonunu tamamlayarak bir hayvanın hareket etmesini yukarıda açıklandığı şekilde simüle etmesini sağlayınız.) complete the function void *simulatehunter(void *args); that is run by any of the hunter threads. (tr: void *simulatehunter(void *args); fonksiyonunu tamamlayarak bir avcının hareket etmesini yukarıda açıklandığı şekilde simüle etmesini sağlayınız.) Dying of an animal, (tr bir hayvanın ölmesi) if an animal status is made DEAD by itself or by hunters, then its associated thread should free all its resources and terminate its running. Note: You can do this by letting the thread check its status before running/moving. Tr: bir hayvan ya kendisi veya hunter tarafından öldürülebilmektedir. Hunter tarafından öldürülmede her uykudan döndükten sonra durumunu kontrol ederek eğer ölü ise tüm kaynakları serbest bırakarak çalışmasını sonlandırmasını sağlayabilirsiniz.
59763a5addec00288a0e9cd7c6c07c1c
{ "intermediate": 0.41449064016342163, "beginner": 0.43781453371047974, "expert": 0.14769481122493744 }
7,314
Write a tensorflow code for a mathematical neural network for proof derivation based on univalent foundations and using schmidthuber artificial interest
2a660b89a42369f1716938d471458f00
{ "intermediate": 0.07523131370544434, "beginner": 0.05119803175330162, "expert": 0.8735706210136414 }
7,315
How do I Create a game that helps users learn the gender of French words. The game will show a French word that is fetched from a database of words that includes examples of usage and ask the user to select the correct article ("UN" or "UNE", "LE" or "LA" randomly). The user's selection will be checked for correctness and the end of the word will be highlighted in red or green to indicate correctness, if the word does not match any rule from a database table that consists of masculine and feminine endings highlight the whole word. The game will also allow users to click on a word to view its translation and examples of usage. By using react and nestjs
ddca82eeec428ead2cc99a54fecf14c2
{ "intermediate": 0.5135332345962524, "beginner": 0.1383470743894577, "expert": 0.34811973571777344 }
7,316
package main import ( "fmt" "math" "strconv" "strings" "unicode" ) // Define all token types type TokenType int const ( EOF TokenType = iota Number Plus Minus Multiply Divide Power Sqrt LeftParen RightParen ) // Token structure type Token struct { Type TokenType Value string } // Function to check if a rune is a space func isSpace(r rune) bool { return unicode.IsSpace(r) } // Function to check if a rune is a digit func isDigit(r rune) bool { return unicode.IsDigit(r) } // Function to check if a rune is an operator func isOperator(r rune) bool { return strings.ContainsRune("+-*/^", r) } // Function to convert an expression string into tokens func tokenize(expr string) ([]Token, error) { var tokens []Token for len(expr) > 0 { expr = strings.TrimSpace(expr) if len(expr) == 0 { break } var t Token switch { case expr[0] == '+': t = Token{Plus, "+"} expr = expr[1:] case expr[0] == '-': t = Token{Minus, "-"} expr = expr[1:] case expr[0] == '*': t = Token{Multiply, "*"} expr = expr[1:] case expr[0] == '/': t = Token{Divide, "/"} expr = expr[1:] case expr[0] == '(': t = Token{LeftParen, "("} expr = expr[1:] case expr[0] == ')': t = Token{RightParen, ")"} expr = expr[1:] case expr[0] == '^': t = Token{Power, "^"} expr = expr[1:] case strings.HasPrefix(expr, "sqrt"): t = Token{Sqrt, "sqrt"} expr = expr[len("sqrt"):] case isDigit(rune(expr[0])): num := strings.TrimLeftFunc(expr, isDigit) t = Token{Number, expr[:len(expr)-len(num)]} expr = num default: return nil, fmt.Errorf("Неизвестный символ: %c", expr[0]) } tokens = append(tokens, t) } return tokens, nil } // Function to get the precedence of an operator func precedence(op TokenType) int { switch op { case Power: return 4 case Sqrt: return 3 case Multiply, Divide: return 2 case Plus, Minus: return 1 case LeftParen, RightParen: return 0 default: return 0 } } // Function to evaluate an expression given its tokens func eval(tokens []Token) (float64, error) { var stack []float64 var operatorStack []Token for _, t := range tokens { switch t.Type { case Number: value, err := strconv.ParseFloat(t.Value, 64) if err != nil { return 0, err } stack = append(stack, value) case Plus, Minus, Multiply, Divide, Power, Sqrt: for len(operatorStack) > 0 && precedence(t.Type) <= precedence(operatorStack[len(operatorStack)-1].Type) { var op Token op, operatorStack = operatorStack[len(operatorStack)-1], operatorStack[:len(operatorStack)-1] if op.Type == Sqrt { if len(stack) < 1 { return 0, fmt.Errorf("Invalid expression: %s", t.Value) } value := stack[len(stack)-1] if value < 0 { return 0, fmt.Errorf("Cannot take square root of a negative number: %v", value) } stack = stack[:len(stack)-1] stack = append(stack, math.Sqrt(value)) } else { if len(stack) < 2 { return 0, fmt.Errorf("Invalid expression: %s", t.Value) } right, left := stack[len(stack)-1], stack[len(stack)-2] stack = stack[:len(stack)-2] switch op.Type { case Plus: stack = append(stack, left+right) case Minus: stack = append(stack, left-right) case Multiply: stack = append(stack, left*right) case Divide: stack = append(stack, left/right) case Power: stack = append(stack, math.Pow(left, right)) } } } operatorStack = append(operatorStack, t) case LeftParen: operatorStack = append(operatorStack, t) case RightParen: for len(operatorStack) > 0 && operatorStack[len(operatorStack)-1].Type != LeftParen { var op Token op, operatorStack = operatorStack[len(operatorStack)-1], operatorStack[:len(operatorStack)-1] if op.Type == Sqrt { if len(stack) < 1 { return 0, fmt.Errorf("Invalid expression: %s", t.Value) } value := stack[len(stack)-1] if value < 0 { return 0, fmt.Errorf("Cannot take square root of a negative number: %v", value) } stack = stack[:len(stack)-1] stack = append(stack, math.Sqrt(value)) } else { if len(stack) < 2 { return 0, fmt.Errorf("Invalid expression: %s", t.Value) } right, left := stack[len(stack)-1], stack[len(stack)-2] stack = stack[:len(stack)-2] switch op.Type { case Plus: stack = append(stack, left+right) case Minus: stack = append(stack, left-right) case Multiply: stack = append(stack, left*right) case Divide: stack = append(stack, left/right) case Power: stack = append(stack, math.Pow(left, right)) } } } if len(operatorStack) == 0 || operatorStack[len(operatorStack)-1].Type != LeftParen { return 0, fmt.Errorf("Mismatched parentheses") } operatorStack = operatorStack[:len(operatorStack)-1] } } for len(operatorStack) > 0 { var op Token op, operatorStack = operatorStack[len(operatorStack)-1], operatorStack[:len(operatorStack)-1] if op.Type == Sqrt { if len(stack) < 1 { return 0, fmt.Errorf("Invalid expression: %s", op.Value) } value := stack[len(stack)-1] if value < 0 { return 0, fmt.Errorf("Cannot take square root of a negative number: %v", value) } stack = stack[:len(stack)-1] stack = append(stack, math.Sqrt(value)) } else { if len(stack) < 2 { return 0, fmt.Errorf("Invalid expression: %s", op.Value) } right, left := stack[len(stack)-1], stack[len(stack)-2] stack = stack[:len(stack)-2] switch op.Type { case Plus: stack = append(stack, left+right) case Minus: stack = append(stack, left-right) case Multiply: stack = append(stack, left*right) case Divide: stack = append(stack, left/right) case Power: stack = append(stack, math.Pow(left, right)) } } } if len(stack) != 1 { return 0, fmt.Errorf("Invalid expression") } return stack[0], nil } func main() { expr := "sqrt(2-3) + (4 + 1) " tokens, err := tokenize(expr) if err != nil { fmt.Println(err) return } result, err := eval(tokens) if err != nil { fmt.Println(err) return } fmt.Printf("%s = %v\n", expr, result) } перепиши код на rust
efade210e257a58a1289efd7bceb53e9
{ "intermediate": 0.2744925916194916, "beginner": 0.4691505432128906, "expert": 0.2563568949699402 }
7,317
how to list public functions on a linux shared library
6b8c543258785e46ea54f556d2a72272
{ "intermediate": 0.5534265041351318, "beginner": 0.3440101146697998, "expert": 0.10256345570087433 }
7,318
You are a master of python and Kivy, considering that, please make a tutorial for using screens using MDScreenManager
a338fe3fab7dfe4ea88458676cf7aa2e
{ "intermediate": 0.5867375135421753, "beginner": 0.20071808993816376, "expert": 0.21254435181617737 }
7,319
Hello
7f668dbb060ee4166eb4f92074e569f1
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
7,320
how to use global scope varibales on c++
31f195aeb8f08dff7bd9c7e80e9823fc
{ "intermediate": 0.2943788468837738, "beginner": 0.5167787075042725, "expert": 0.18884244561195374 }
7,321
There are functions in TensorFlow that you can use to instruct the model to output an intermediate tensor in the DNN graph list them please
64561e7f82720a4f3c1fe1b56a559f42
{ "intermediate": 0.21899743378162384, "beginner": 0.06427362561225891, "expert": 0.716728925704956 }
7,322
when is a gene
502363e6bcbc6f7cc3acf01520845126
{ "intermediate": 0.32392632961273193, "beginner": 0.4133164584636688, "expert": 0.26275721192359924 }
7,323
Hello there
7867036b8c3bde8f6b77eea95ff2a617
{ "intermediate": 0.32595759630203247, "beginner": 0.25228530168533325, "expert": 0.42175713181495667 }
7,324
What is the meaning of faster horse quote
c86fc3c79930d9c13f6fd21833d59731
{ "intermediate": 0.37132635712623596, "beginner": 0.33288487792015076, "expert": 0.2957887351512909 }
7,325
image_rr = models.FileField(upload_to='media/', null=True, blank=True) ValueError at /company/api/rate_raview/ The 'image_rr' attribute has no file associated with it.
4546a47cf8ef4c5340eaf2852beb3bdc
{ "intermediate": 0.5257493853569031, "beginner": 0.25791648030281067, "expert": 0.21633410453796387 }
7,326
Dragonite @ Leftovers Ability: Multiscale Level: 50 EVs: 252 HP / 252 SpD / 4 Spe Careful Nature - Dragon Claw - Dragon Dance - Heal Bell - Roost Can you build team around this dragonite ?
865d01f2b988d94266c6e4b50f744248
{ "intermediate": 0.33839884400367737, "beginner": 0.24959151446819305, "expert": 0.41200968623161316 }