row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
13,462
Networking and Web Services in java
5aca47b467de285189f8dcd13033974f
{ "intermediate": 0.5313616991043091, "beginner": 0.21734704077243805, "expert": 0.2512911856174469 }
13,463
why dont the images open? import random from PIL import Image # Define the artists and their monthly Spotify listeners artists = { 'Young Nudy': {"image":"./fotos/Young Nudy_1.jpeg", "listeners": 7553116}, 'Young Thug': {"image":"./fotos/Young Thug_1.jpeg", "listeners": 28887553}, 'Yungeen Ace': {"image":"./fotos/Yungeen Ace_1.jpeg", "listeners": 1294188}, } while True: score = 0 # reset score at the beginning of each game first_artist, second_artist = random.sample(list(artists.keys()), 2) # Load the images for the artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) while True: # Display the images image.show(first_artist_image) image.show(second_artist_image) guess = input(f"\nWhich artist has more monthly Spotify listeners - 1. {first_artist.title()} or 2. {second_artist.title()}? ") guess_lower = guess.strip().lower() if guess_lower == 'quit': print("Thanks for playing!") quit() elif guess_lower not in ['1', '2', first_artist.lower(), second_artist.lower()]: print("Invalid input. Please enter the name of one of the two artists or 'quit' to end the game.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists[first_artist]["listeners"] > artists[second_artist]["listeners"]: print(f"You guessed correctly! {first_artist.title()} had {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) continue elif guess_lower == second_artist.lower() or guess_lower == '2' and artists[second_artist]["listeners"] > artists[first_artist]["listeners"]: print(f"You guessed correctly! {second_artist.title()} had {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {first_artist.title()} has {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.") score += 1 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) continue else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {artists[first_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners and {second_artist.title()} has {artists[second_artist]['listeners'] / 1e6:.1f}M monthly Spotify listeners.\n") print(f"Your final score is {score}.") play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() else: score = 0 first_artist, second_artist = random.sample(list(artists.keys()), 2) # select new artists for the next round # Load the images for the new artists first_artist_image = Image.open(artists[first_artist]["image"]) second_artist_image = Image.open(artists[second_artist]["image"]) break
570fab2999fb0a8c4e18e5e7da833425
{ "intermediate": 0.2767770290374756, "beginner": 0.42796146869659424, "expert": 0.2952614724636078 }
13,464
fouries series frequency , amplitude, phases
9a17b663c396a47176811486fa1ed76c
{ "intermediate": 0.4467043876647949, "beginner": 0.29093822836875916, "expert": 0.26235732436180115 }
13,465
write html code for simple form
a02a6f65771a2d681038900adc1c4da4
{ "intermediate": 0.3452727198600769, "beginner": 0.36157432198524475, "expert": 0.29315298795700073 }
13,466
I have Nging on front and apache on back. how to create Lets Encrypt ssl certificate for subdomain in ubuntu?
913b5241b1b6f739676e0e99b7740025
{ "intermediate": 0.5867370963096619, "beginner": 0.19636215269565582, "expert": 0.2169007509946823 }
13,467
In rofi configuration, how can I get rid of the "run" string when using "run" mode?
715f3314edc6333e509cec8107077ab7
{ "intermediate": 0.33639195561408997, "beginner": 0.27809956669807434, "expert": 0.3855085074901581 }
13,468
I want you to act as a data scientist and code for me. I have a dataset of as follow. Please build a machine learning model that predict code time_key open close high low pe_ratio turnover_rate volume turnover change_rate last_close 148 4/5/2023 0:00 23.45 23.8 23.8 23.4 7.2 0.006554942 71000 2.81 23.15 317 4/5/2023 0:00 11.2 11.28 11.56 11.04 20.83 0.037366074 1078000 2.55 11 558 4/5/2023 0:00 7.95 7.95 7.98 7.87 19.1 0.053763794 740000 1.02 7.87 631 4/5/2023 0:00 10.58 10.48 10.76 10.46 20.3 0.077287376 2456389 -0.19 10.5 838 4/5/2023 0:00 0.84 0.82 0.84 0.82 7.03 0.006548266 114000 -1.2 0.83 868 4/5/2023 0:00 13.92 14.16 14.24 13.84 11.27 0.017989255 742001 1.72 13.92
ef26e902342fc189d3f26b2240283eac
{ "intermediate": 0.2424582839012146, "beginner": 0.28186526894569397, "expert": 0.4756764769554138 }
13,469
{ title: <FormattedMessage id="Read bytes" defaultMessage="Read bytes" />, dataIndex: 'readBytes', render: (dom, entity) => ( <div style={{ display: 'flex', flexWrap: 'nowrap' }}> {entity.readBytes!.map((item) => ( <svg style={{ display: 'inline-block', width: '5px', height: '5px', marginRight: '2px' }} > <circle cx="2.5" cy="2.5" r="2.5" stroke="#888" stroke-width="1" fill="#1890ff" /> </svg> ))} </div> ), }, как к каждому svg прикрепить tooltip?
5f373ad58925ca6a451b9aa56f0e28ad
{ "intermediate": 0.36111077666282654, "beginner": 0.33182060718536377, "expert": 0.3070686161518097 }
13,470
{ title: <FormattedMessage id="Host" defaultMessage="Host" />, dataIndex: 'host', tip: 'The host is the unique key', render: (dom, entity) => { return ( <a onClick={() => { setCurrentRow(entity); setShowDetail(true); }} > {dom} </a> ); }, }, как сделать так чтобы при клике в таблице ниже создавался не разделенный на столбы ряд с каким либо текстом в несколько строк?
8e8be8a13e95da5a743e5bfb6be5c5cf
{ "intermediate": 0.36943838000297546, "beginner": 0.33769240975379944, "expert": 0.2928691506385803 }
13,471
I want to make a script that will remove all <page> content that has a namespace value that is any number besides 0.
8a84a7444bf44545b7d2b4724b8b2abd
{ "intermediate": 0.2995056211948395, "beginner": 0.26392316818237305, "expert": 0.4365712106227875 }
13,472
Is it possible to have multiple fonts in a rofi menu?
16195a40bd7948e88aaef1d3f7432ef5
{ "intermediate": 0.3330252766609192, "beginner": 0.24479222297668457, "expert": 0.42218253016471863 }
13,473
I want to make a script that will remove all <page> content that has a namespace value that is any number besides 0. this must have drag and drop functionality and remove the entire <page> content, including the <page></page> tags.
b6cc43d819a3c34ed9a40858208eca6f
{ "intermediate": 0.37739047408103943, "beginner": 0.23454849421977997, "expert": 0.3880610764026642 }
13,474
Create a python script that will remove all <page> content that has a namespace value that is any number besides 0. this must have drag and drop functionality and remove the entire <page> content, including the <page></page> tags.
81f86c0f193eb8d47c1cf48026282f86
{ "intermediate": 0.3608956038951874, "beginner": 0.23528915643692017, "expert": 0.40381520986557007 }
13,475
`<mediawiki xmlns=“http://www.mediawiki.org/xml/export-0.11/” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=“http://www.mediawiki.org/xml/export-0.11/ http://www.mediawiki.org/xml/export-0.11.xsd” version=“0.11” xml:lang=“en”> <siteinfo> <sitename>I-chu Wiki</sitename> <dbname>ichu</dbname> <base>http://i-chu.fandom.com/wiki/I-chu_Wiki</base> <generator>MediaWiki 1.37.4</generator> <case>first-letter</case> <namespaces> <namespace key=“-2” case=“first-letter”>Media</namespace> <namespace key=“-1” case=“first-letter”>Special</namespace> <namespace key=“0” case=“first-letter” /> <namespace key=“1” case=“first-letter”>Talk</namespace> <namespace key=“2” case=“first-letter”>User</namespace> <namespace key=“3” case=“first-letter”>User talk</namespace> <namespace key=“4” case=“first-letter”>I-chu Wiki</namespace> <namespace key=“5” case=“first-letter”>I-chu Wiki talk</namespace> <namespace key=“6” case=“first-letter”>File</namespace> <namespace key=“7” case=“first-letter”>File talk</namespace> <namespace key=“8” case=“first-letter”>MediaWiki</namespace> <namespace key=“9” case=“first-letter”>MediaWiki talk</namespace> <namespace key=“10” case=“first-letter”>Template</namespace> <namespace key=“11” case=“first-letter”>Template talk</namespace> <namespace key=“12” case=“first-letter”>Help</namespace> <namespace key=“13” case=“first-letter”>Help talk</namespace> <namespace key=“14” case=“first-letter”>Category</namespace> <namespace key=“15” case=“first-letter”>Category talk</namespace> <namespace key=“110” case=“first-letter”>Forum</namespace> <namespace key=“111” case=“first-letter”>Forum talk</namespace> <namespace key=“420” case=“first-letter”>GeoJson</namespace> <namespace key=“421” case=“first-letter”>GeoJson talk</namespace> <namespace key=“500” case=“first-letter”>User blog</namespace> <namespace key=“501” case=“first-letter”>User blog comment</namespace> <namespace key=“502” case=“first-letter”>Blog</namespace> <namespace key=“503” case=“first-letter”>Blog talk</namespace> <namespace key=“710” case=“first-letter”>TimedText</namespace> <namespace key=“711” case=“first-letter”>TimedText talk</namespace> <namespace key=“828” case=“first-letter”>Module</namespace> <namespace key=“829” case=“first-letter”>Module talk</namespace> <namespace key=“1200” case=“first-letter”>Message Wall</namespace> <namespace key=“1201” case=“first-letter”>Thread</namespace> <namespace key=“1202” case=“first-letter”>Message Wall Greeting</namespace> <namespace key=“2000” case=“first-letter”>Board</namespace> <namespace key=“2001” case=“first-letter”>Board Thread</namespace> <namespace key=“2002” case=“first-letter”>Topic</namespace> <namespace key=“2900” case=“first-letter”>Map</namespace> <namespace key=“2901” case=“first-letter”>Map talk</namespace> </namespaces> </siteinfo> <page> <title>I-chu Wiki:Copyrights</title> <ns>4</ns> <id>1452</id> <revision> <id>3728</id> <timestamp>2015-05-02T22:33:04Z</timestamp> <contributor> <username>Default</username> <id>49312</id> </contributor> <origin>3728</origin> <model>wikitext</model> <format>text/x-wiki</format> <text bytes=“397” sha1=“184h6kou71fwrz3b41tx9pa3zf3a3b1” xml:space=“preserve”>Except where otherwise specified, the text on Wikia sites is licensed under the Creative Commons Attribution-Share Alike License 3.0 (Unported) (CC-BY-SA). * [http://creativecommons.org/licenses/by-sa/3.0/ Read the license summary] * [http://creativecommons.org/licenses/by-sa/3.0/legalcode Read the full legal code of the license]. Please see [[w:Wikia:Licensing|Wikia:Licensing]] for details.</text> <sha1>184h6kou71fwrz3b41tx9pa3zf3a3b1</sha1> </revision> </page> <page> <title>Category:Browse</title> <ns>14</ns> <id>1460</id> <revision> <id>3862</id> <timestamp>2015-05-02T22:33:04Z</timestamp> <contributor> <username>Default</username> <id>49312</id> </contributor> <minor/> <comment>Reverted edits by [[Special:Contributions/Robin Patterson|Robin Patterson]] ([[User talk:Robin Patterson|talk]] | [[Special:Block/Robin Patterson|block]]) to last version by [[User:Susan Taylor|Susan Taylor]]</comment> <origin>3862</origin> <model>wikitext</model> <format>text/x-wiki</format> <text bytes=“227” sha1=“mionibs20om4gen6jorb90t8lcij5xw” xml:space=“preserve”>To add a new category to a page you can click the Category button at the bottom of the page and type in the name you’d like your category to be called. A full list of existing categories can be found at [[Special:Categories]].</text> <sha1>mionibs20om4gen6jorb90t8lcij5xw</sha1> </revision> </page> <page> <title>I-chu Wiki</title> <ns>0</ns> <id>1461</id> <revision> <id>105286</id> <parentid>105232</parentid> <timestamp>2019-12-01T19:29:06Z</timestamp> <contributor> <username>Namakemonos</username> <id>27157972</id> </contributor> <origin>105286</origin> <model>wikitext</model> <format>text/x-wiki</format> <text bytes=“815” sha1=“i63hpy852brmrtcpa6e6iphp9mn051k” xml:space=“preserve”><mainpage-leftcolumn-start /> {{MainPageWelcome}} {{MainPageSlider}} {{Featured Song}}<br /> {{FeaturedUnit}} <mainpage-endcolumn /> <mainpage-rightcolumn-start /> {{MaintenanceNotice |Maintenance = no <!-- yes / no --> |Vertical = yes <!-- Keep for mainpage --> |Date = September 27 2019 |Start time = 13:00 |End time = 16:00}} {|class=“mainpagetemplatenobg” width=“100%” style=“color:black; text-align:center; background-color:none; font-size:89%; margin-bottom:10px;” | colspan=“2” | {{Template:Calendar/Dec}} |} <p style=“border-bottom:1.5px solid #652386; border-top:1.5px solid #652386; border-left:1.5px solid #652386; border-right:1.5px solid #652386;”><twitter widget-id=“705548045694459905” screen-name=“ichuwiki”></twitter></p> {{Poll}}<br /> {{Affiliates}} <mainpage-endcolumn /> [[Category:Browse]]</text> <sha1>i63hpy852brmrtcpa6e6iphp9mn051k</sha1> </revision> </page> </mediawiki> Create a python script that will remove all <page> content that has a namespace value that is any number besides 0. this must have drag and drop functionality and remove the entire <page> content, including the <page></page> tags.
c077e1bc8b0331c955c6ed59e84f2fba
{ "intermediate": 0.37546855211257935, "beginner": 0.44577541947364807, "expert": 0.1787559688091278 }
13,476
import Images from "../assets/exportAssets"; import { useState, useEffect } from "react"; import { userRequest } from "../requestMethods"; import TimeAgo from "react-timeago"; interface Order { _id: string; userId: string; products: [ { productId: { type: String }; quantity: { type: Number; default: 1 } } ]; amount: number; address: {}; status: string; createdAt: string; } const WidgetLarge = () => { const [orders, setOrders] = useState<Order[]>([]); useEffect(() => { const getOrders = async () => { try { const res = await userRequest.get("orders"); setOrders(res.data); } catch (err) { console.log(err); } }; getOrders(); }, []); const ButtonComp = ({ type }: { type: string }) => { return <button className={"widgetLarge__button " + type}>{type}</button>; }; return ( <div className="widgetLarge"> <h3 className="widgetLarge__title">Latest transactions</h3> <table className="widgetLarge__table"> <thead> <tr className="widgetLarge__tr"> <th className="widgetLarge__th">Customer</th> <th className="widgetLarge__th">Date</th> <th className="widgetLarge__th">Amount</th> <th className="widgetLarge__th">Status</th> </tr> </thead> <tbody> {orders.map((order) => ( <tr className="widgetLarge__tr" key={order._id}> <td className="widgetLarge__user"> <span className="widgetLarge__name">{order.userId}</span> </td> <td className="widgetLarge__date"> <TimeAgo datetime={order.createdAt} locale="vi" /> </td> <td className="widgetLarge__amount">{order.amount}pln</td> <td className="widgetLarge__status"> <ButtonComp type={order.status} /> </td> </tr> ))} </tbody> </table> </div> ); }; export default WidgetLarge; No overload matches this call. Overload 1 of 2, '(props: (ReactTimeagoProps<ComponentType<{}> | keyof IntrinsicElements> & ({} | DetailedHTMLProps<HTMLAttributes<HTMLTableSectionElement>, HTMLTableSectionElement> | ... 121 more ... | SVGProps<...>)) | Readonly<...>): ReactTimeago<...>', gave the following error. Type '{ datetime: string; locale: string; }' is not assignable to type 'IntrinsicAttributes & (IntrinsicClassAttributes<ReactTimeago<ComponentType<{}> | keyof IntrinsicElements>> & Readonly<...>)'. Property 'datetime' does not exist on type 'IntrinsicAttributes & (IntrinsicClassAttributes<ReactTimeago<ComponentType<{}> | keyof IntrinsicElements>> & Readonly<...>)'.
437c9dab48192806548407dda2ede63e
{ "intermediate": 0.296068400144577, "beginner": 0.5265406966209412, "expert": 0.17739088833332062 }
13,477
Help me find a mistake in my code
4dbe16196fb1ac22850a35bc7013967d
{ "intermediate": 0.2985609769821167, "beginner": 0.4131905436515808, "expert": 0.2882484793663025 }
13,478
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class random : MonoBehaviour { public static string DogsImg; void Update() { DogsImg = breed.answer; Image image = GetComponent<Image>(); Sprite newSprite = null; //Выбор картинки отображения switch (DogsImg) { case "Абби (0)": newSprite = Resources.Load("dog (0)"); break; case "Азавак (1)": newSprite = Resources.Load("dog (1)"); break; case "Бастер (2)": newSprite = Resources.Load("dog (2)"); break; case "Белорусская овчарка (3)": newSprite = Resources.Load("dog (3)"); break; case "Бигль (4)": newSprite = Resources.Load("dog (4)"); break; case "Бладхаунд (5)": newSprite = Resources.Load("dog (5)"); break; case "Бультерьер (6)": newSprite = Resources.Load("dog (6)"); break; case "Винни (7)": newSprite = Resources.Load("dog (7)"); break; case "Восточно-сибирская лайка (8)": newSprite = Resources.Load("dog (8)"); break; case "Гриндель (9)": newSprite = Resources.Load("dog (9)"); break; case "Далматин (10)": newSprite = Resources.Load("dog (10)"); break; case "Дворняга (11)": newSprite = Resources.Load("dog (11)"); break; case "Джек-Рассел терьер (12)": newSprite = Resources.Load("dog (12)"); break; case "Западно-сибирская лайка (13)": newSprite = Resources.Load("dog (13)"); break; case "Золотой Ретривер (14)": newSprite = Resources.Load("dog (14)"); break; case "Керри-блю-терьер (15)": newSprite = Resources.Load("dog (15)"); break; case "Колли (16)": newSprite = Resources.Load("dog (16)"); break; case "Комондор (17)": newSprite = Resources.Load("dog (17)"); break; case "Корги (18)": newSprite = Resources.Load("dog (18)"); break; case "Корейский шпиц (19)": newSprite = Resources.Load("dog (19)"); break; case "Лхаса апсо (20)": newSprite = Resources.Load("dog (20)"); break; case "Неаполитанский мастиф (21)": newSprite = Resources.Load("dog (21)"); break; case "Немецкая овчарка (22)": newSprite = Resources.Load("dog (22)"); break; case "Овчарка (23)": newSprite = Resources.Load("dog (23)"); break; case "Парсон-рассел-терьер (24)": newSprite = Resources.Load("dog (24)"); break; case "Пти-брабансон (25)": newSprite = Resources.Load("dog (25)"); break; case "Русская гончая (26)": newSprite = Resources.Load("dog (26)"); break; case "Русская пегая гончая (27)": newSprite = Resources.Load("dog (27)"); break; case "Русская псовая борзая (28)": newSprite = Resources.Load("dog (28)"); break; case "Русский черный терьер (29)": newSprite = Resources.Load("dog (29)"); break; case "Русско-европейская лайка (30)": newSprite = Resources.Load("dog (30)"); break; case "Сахалинский хаски (31)": newSprite = Resources.Load("dog (31)"); break; case "Сиба-ину (32)": newSprite = Resources.Load("dog (32)"); break; case "Сибирский хаски (33)": newSprite = Resources.Load("dog (33)"); break; case "Чау-чау (34)": newSprite = Resources.Load("dog (34)"); break; case "Шелти (35)": newSprite = Resources.Load("dog (35)"); break; case "Японский хин (36)": newSprite = Resources.Load("dog (36)"); break; case "Японский шпиц (37)": newSprite = Resources.Load("dog (37)"); } image.sprite = newSprite; } } Где ошибка?
9ef4ab86a9446743771b33492dc95a6a
{ "intermediate": 0.35290762782096863, "beginner": 0.43652957677841187, "expert": 0.2105628252029419 }
13,479
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class breed : MonoBehaviour { public AudioSource Right; public Text button1; public Text button2; public Text button3; public Text button4; public Image ColorButton1; public Image ColorButton2; public Image ColorButton3; public Image ColorButton4; public static string answer; public static int i; public static string[] fruits = new string[39]; void Start() { //Массив с породами fruits[0] = "Абби (0)"; fruits[1] = "Азавак (1)"; fruits[2] = "Бастер (2)"; fruits[3] = "Белорусская овчарка (3)"; fruits[4] = "Бигль (4)"; fruits[5] = "Бладхаунд (5)"; fruits[6] = "Бультерьер (6)"; fruits[7] = "Винни (7)"; fruits[8] = "Восточно-сибирская лайка (8)"; fruits[9] = "Гриндель (9)"; fruits[10] = "Далматин (10)"; fruits[11] = "Дворняга (11)"; fruits[12] = "Джек-Рассел терьер (12)"; fruits[13] = "Западно-сибирская лайка (13)"; fruits[14] = "Золотой Ретривер (14)"; fruits[15] = "Керри-блю-терьер (15)"; fruits[16] = "Колли (16)"; fruits[17] = "Комондор (17)"; fruits[18] = "Корги (18)"; fruits[19] = "Корейский шпиц (19)"; fruits[20] = "Лхаса апсо (20)"; fruits[21] = "Неаполитанский мастиф (21)"; fruits[22] = "Немецкая овчарка (22)"; fruits[23] = "Овчарка (23)"; fruits[24] = "Парсон-рассел-терьер (24)"; fruits[25] = "Пти-брабансон (25)"; fruits[26] = "Русская гончая (26)"; fruits[27] = "Русская пегая гончая (27)"; fruits[28] = "Русская псовая борзая (28)"; fruits[29] = "Русский черный терьер (29)"; fruits[30] = "Русско-европейская лайка (30)"; fruits[31] = "Сахалинский хаски (31)"; fruits[32] = "Сиба-ину (32)"; fruits[33] = "Сибирский хаски (33)"; fruits[34] = "Чау-чау (34)"; fruits[35] = "Шелти (35)"; fruits[36] = "Японский хин (36)"; fruits[37] = "Японский шпиц (37)"; fruits[38] = "Японский шпиц (37)"; //Выбор правильного ответа button1.text = fruits[Random.Range(0, fruits.Length)]; button2.text = fruits[Random.Range(0, fruits.Length)]; button3.text = fruits[Random.Range(0, fruits.Length)]; button4.text = fruits[Random.Range(0, fruits.Length)]; //На какой кнопке будет правильный ответ i = Random.Range(1, 4); //Присваивание текста к кнопкам switch (i) { case 1: answer = button1.text; break; case 2: answer = button2.text; break; case 3: answer = button3.text; break; case 4: answer = button4.text; break; } } void Update() { //Сравнивание ответа и выбора if(NextPage.b == i) { OnClick(); ColorButton1.color = new Color(0.466f, 0.584f, 0.313f, 1f); ColorButton2.color = new Color(0.466f, 0.584f, 0.313f, 1f); ColorButton3.color = new Color(0.466f, 0.584f, 0.313f, 1f); ColorButton4.color = new Color(0.466f, 0.584f, 0.313f, 1f); Right.Play(); } } public void OnClick() { //Выбор правильного ответа button1.text = fruits[Random.Range(0, fruits.Length)]; button2.text = fruits[Random.Range(0, fruits.Length)]; button3.text = fruits[Random.Range(0, fruits.Length)]; button4.text = fruits[Random.Range(0, fruits.Length)]; //На какой кнопке будет правильный ответ i = Random.Range(1, 4); //Присваивание текста к кнопкам switch (i) { case 1: answer = button1.text; break; case 2: answer = button2.text; break; case 3: answer = button3.text; break; case 4: answer = button4.text; break; } } } using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class random : MonoBehaviour { public static string DogsImg; void Update() { DogsImg = breed.answer; Image image = GetComponent<Image>(); Sprite newSprite = null; //Выбор картинки отображения switch (DogsImg) { case "Абби (0)": newSprite = (Sprite)Resources.Load("dog (0)"); break; case "Азавак (1)": newSprite = (Sprite)Resources.Load("dog (1)"); break; case "Бастер (2)": newSprite = (Sprite)Resources.Load("dog (2)"); break; case "Белорусская овчарка (3)": newSprite = (Sprite)Resources.Load("dog (3)"); break; case "Бигль (4)": newSprite = (Sprite)Resources.Load("dog (4)"); break; case "Бладхаунд (5)": newSprite = (Sprite)Resources.Load("dog (5)"); break; case "Бультерьер (6)": newSprite = (Sprite)Resources.Load("dog (6)"); break; case "Винни (7)": newSprite = (Sprite)Resources.Load("dog (7)"); break; case "Восточно-сибирская лайка (8)": newSprite = (Sprite)Resources.Load("dog (8)"); break; case "Гриндель (9)": newSprite = (Sprite)Resources.Load("dog (9)"); break; case "Далматин (10)": newSprite = (Sprite)Resources.Load("dog (10)"); break; case "Дворняга (11)": newSprite = (Sprite)Resources.Load("dog (11)"); break; case "Джек-Рассел терьер (12)": newSprite = (Sprite)Resources.Load("dog (12)"); break; case "Западно-сибирская лайка (13)": newSprite = (Sprite)Resources.Load("dog (13)"); break; case "Золотой Ретривер (14)": newSprite = (Sprite)Resources.Load("dog (14)"); break; case "Керри-блю-терьер (15)": newSprite = (Sprite)Resources.Load("dog (15)"); break; case "Колли (16)": newSprite = (Sprite)Resources.Load("dog (16)"); break; case "Комондор (17)": newSprite = (Sprite)Resources.Load("dog (17)"); break; case "Корги (18)": newSprite = (Sprite)Resources.Load("dog (18)"); break; case "Корейский шпиц (19)": newSprite = (Sprite)Resources.Load("dog (19)"); break; case "Лхаса апсо (20)": newSprite = (Sprite)Resources.Load("dog (20)"); break; case "Неаполитанский мастиф (21)": newSprite = (Sprite)Resources.Load("dog (21)"); break; case "Немецкая овчарка (22)": newSprite = (Sprite)Resources.Load("dog (22)"); break; case "Овчарка (23)": newSprite = (Sprite)Resources.Load("dog (23)"); break; case "Парсон-рассел-терьер (24)": newSprite = (Sprite)Resources.Load("dog (24)"); break; case "Пти-брабансон (25)": newSprite = (Sprite)Resources.Load("dog (25)"); break; case "Русская гончая (26)": newSprite = (Sprite)Resources.Load("dog (26)"); break; case "Русская пегая гончая (27)": newSprite = (Sprite)Resources.Load("dog (27)"); break; case "Русская псовая борзая (28)": newSprite = (Sprite)Resources.Load("dog (28)"); break; case "Русский черный терьер (29)": newSprite = (Sprite)Resources.Load("dog (29)"); break; case "Русско-европейская лайка (30)": newSprite = (Sprite)Resources.Load("dog (30)"); break; case "Сахалинский хаски (31)": newSprite = (Sprite)Resources.Load("dog (31)"); break; case "Сиба-ину (32)": newSprite = (Sprite)Resources.Load("dog (32)"); break; case "Сибирский хаски (33)": newSprite = (Sprite)Resources.Load("dog (33)"); break; case "Чау-чау (34)": newSprite = (Sprite)Resources.Load("dog (34)"); break; case "Шелти (35)": newSprite = (Sprite)Resources.Load("dog (35)"); break; case "Японский хин (36)": newSprite = (Sprite)Resources.Load("dog (36)"); break; case "Японский шпиц (37)": newSprite = (Sprite)Resources.Load("dog (37)"); break; } image.sprite = newSprite; } } В чем ошибка?
a8288ee7e3a5bce77dda4a9a444dfc76
{ "intermediate": 0.2856093943119049, "beginner": 0.56769859790802, "expert": 0.14669202268123627 }
13,480
give me the python code to do build detailed portfolios of A/P and A/R per each company. use numpy and pandas. In this simulation, each company as a tax ID, an economic activity code and a dimension( micro, sme, big). Also there are about 90 industries in the Input Output matrix where each industry consumes and produces for others and also imports or exports. The python code should use the aggregated statistics on A/P and A/R that were delivered by Bank of Portugal
bcd33696a3910b8f4a1c682fc3b0514e
{ "intermediate": 0.5845963358879089, "beginner": 0.1174897626042366, "expert": 0.29791390895843506 }
13,481
I want to build a graph network where edges are companies and vertices are individual A/P or individual A/R values depending on the direction you analyse. I only have aggregated data of total A/P and total A/R per industry, company size and average A/P and A/R per each segment. I have average A/P and A/R and also number of companies in each segment. Also I can divide each total A/P and total A/R porfolio of each company by using the input-output table that inter-relate each industry. Build me the code in Python
01a5a026dad2e5005a7bc42561640d4f
{ "intermediate": 0.454517662525177, "beginner": 0.15843379497528076, "expert": 0.38704851269721985 }
13,482
防止ssl pinning bypass
8ed8844979ed250793fe1c32067fda67
{ "intermediate": 0.26528400182724, "beginner": 0.35194429755210876, "expert": 0.38277167081832886 }
13,483
import Chart from "../components/Chart"; import Info from "../components/Info"; import WidgetLarge from "../components/WidgetLarge"; import WidgetSmall from "../components/WidgetSmall"; import { dataOfUsers } from "../exmapleData"; import { useState, useMemo, useEffect } from "react"; import { userRequest } from "../requestMethods"; interface Stats {} const Home = () => { const [userStats, setUserStats] = useState([]); const MONTHS = useMemo( () => [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Agu", "Sep", "Oct", "Nov", "Dec", ], [] ); useEffect(() => { const getStats = async () => { try { const res = await userRequest.get("/users/stats"); res.data.map((item) => setUserStats((prev) => [ ...prev, { name: MONTHS[item._id - 1], "Active User": item.total }, ]) ); } catch {} }; getStats(); }, [MONTHS]); return ( <div className="home"> <Info /> <Chart data={dataOfUsers} title="User Analytics" dataKey="Active User" grid={true} /> <div className="home__widgets"> <WidgetSmall /> <WidgetLarge /> </div> </div> ); }; export default Home; TS7006: Parameter 'item' implicitly has an 'any' type. 31 | try { 32 | const res = await userRequest.get("/users/stats"); > 33 | res.data.map((item) => | ^^^^ 34 | setUserStats((prev) => [ 35 | ...prev, 36 | { name: MONTHS[item._id - 1], "Active User": item.total }, ERROR in src/pages/Home.tsx:34:24 TS2345: Argument of type '(prev: never[]) => { name: string; "Active User": any; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'. Type '(prev: never[]) => { name: string; "Active User": any; }[]' is not assignable to type '(prevState: never[]) => never[]'. Type '{ name: string; "Active User": any; }[]' is not assignable to type 'never[]'. Type '{ name: string; "Active User": any; }' is not assignable to type 'never'. 32 | const res = await userRequest.get("/users/stats"); 33 | res.data.map((item) => > 34 | setUserStats((prev) => [ | ^^^^^^^^^^^ > 35 | ...prev, | ^^^^^^^^^^^^^^^^^^^^ > 36 | { name: MONTHS[item._id - 1], "Active User": item.total }, | ^^^^^^^^^^^^^^^^^^^^ > 37 | ]) | ^^^^^^^^^^^^ 38 | ); 39 | } catch {} 40 | };
63f8143bcdea4d5ca969267bef913f34
{ "intermediate": 0.31664684414863586, "beginner": 0.4154359698295593, "expert": 0.2679171860218048 }
13,484
Write full snake game in c console using nurses
43342e703887cac64578ff65468b983f
{ "intermediate": 0.3965710401535034, "beginner": 0.3400682806968689, "expert": 0.2633607089519501 }
13,485
hi
a79bd868841e62887c27c1243f848c72
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
13,486
hi
6f47ba73011befb8282fe4435ce83407
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
13,487
element select修改带分页的下拉框
a777c84175e618183713c414e33d8b42
{ "intermediate": 0.3015933036804199, "beginner": 0.32833215594291687, "expert": 0.3700745105743408 }
13,488
in pyqt5 define a timer to do some callback every 0.1second without blocking
2ca603cb084df82a72acf91657e6811e
{ "intermediate": 0.4691731929779053, "beginner": 0.20690877735614777, "expert": 0.32391801476478577 }
13,489
Student Management System: Develop a student management system in java that uses collections and generics to manage student records. The system should allow users to add, remove, and update student records, search for students by name or ID, and generate reports.
7c77734623da93eb87591d6dbc161b54
{ "intermediate": 0.55780029296875, "beginner": 0.16646835207939148, "expert": 0.27573129534721375 }
13,490
use jest create ut for this component: <template> <div> <el-tree v-if="treeVisible" ref="tree" v-bind="treeProps" v-on="treeListeners" /> </div> </template> <script> import camelCase from 'lodash/camelCase' import utils from 'utils/index.js' import gb from 'utils/global.js' import _get from 'lodash/get' import _cloneDeep from 'lodash/cloneDeep' import { attributes } from './treeConfig' const nonAxiosAttrs = [ 'beforeRequest', 'interceptResponse', 'response', 'resField', 'lazyKey' ] export default { name: 'GdTree', data() { return { treeVisible: true, treeProps: {}, // 取树的属性用这个 treeListeners: {}, defaultProps: { data: [], showCheckbox: true, nodeKey: 'id', props: { label: 'label', children: 'children', isLeaf: 'leaf' } }, defaultListener: {} } }, watch: {}, created() { // console.log(this) this._mergeTreeObjFn() this._setTreeCheckboxStatusFn() this._mergeTreeEventFn() // this._watchElTreeAttr() if (this.auto) { this._loadData() } // this.$gdMar.send('gd-tree-loaded') }, mounted() {}, methods: { // 重新load一下数据,比如重新请求一个接口 loadData() { this.treeVisible = false this._loadData() this.$nextTick(() => { this.treeVisible = true }) }, getRef() { return this.$refs.tree }, setData(data) { if (!utils.isArr(data)) { console.error('setData中的参数data必须为数组') return } // 对数据按照showLevel的设置进行处理 if (this.showLevel.length > 0) { data = this._setDataByShowLevel(data) } this._traverseTreeToSetAttr(data) // 这个函数,目前只用于初始化的数据 this.treeProps.data = data }, _setDataByShowLevel(data) { let treeData = _cloneDeep(data) let level = 1 let queue = [] let result = [] // 给每个树节点打上gd-tree-id treeData.map((level1, index) => { level1['gd-tree-id'] = index queue.push(level1) }) let treeLevelData = {} let childrenField = this.treeProps.props.children let showLevel = this.showLevel.sort((a, b) => (a - b)) // BFS while (queue.length > 0) { let length = queue.length treeLevelData[level] = [] for (let i = 0; i < length; i++) { let queueTop = queue.shift() let children = queueTop[childrenField] if (children && children.length > 0) { children.map((item, index) => { // 需要显示的层级会加上-index,不需要显示的继承父亲的gd-tree-id,方便下面查找,提高性能 if (showLevel.indexOf(+level + 1) > 0) { item['gd-tree-id'] = `${queueTop['gd-tree-id']}-${index}` } else { item['gd-tree-id'] = queueTop['gd-tree-id'] } queue.push(item) }) } queueTop.children = [] // 清空childrenField treeLevelData[level].push(queueTop) } level++ } // 对showLevel排序 showLevel.map((level, index) => { let levelData = treeLevelData[level] if (!isNaN(level) && levelData) { if (index === 0) { result.push(...levelData) } else { levelData.map((item, index) => { // 根据gdTreeId直接找到要挂靠的父元素 let gdTreeId = item['gd-tree-id'] + '' let levels = gdTreeId.split('-') levels.pop() let getStr levels.map((item, index) => { if (index === 0) { getStr = [item] } else { getStr.push(childrenField, item) } }) let parantItem = _get(result, getStr) parantItem.children.push(item) }) } } }) return result }, _traverseTreeToSetAttr(treeData) { let level = 1 // BFS let queue = [] for (let level1 of treeData) { queue.push(level1) } while (queue.length > 0) { let length = queue.length for (let i = 0; i < length; i++) { let queueTop = queue.shift() let children = queueTop[this.treeProps.props.children] if (this.disabledLevel[level]) { queueTop['disabled'] = true } if (children && children.length > 0) { children.map(item => { queue.push(item) }) } } level++ } }, // 发起请求 _requestAxios(axiosAttrs) { let axiosInstance = gb.axios let source = this.source return new Promise((resolve, reject) => { axiosInstance(axiosAttrs).then(axiosRes => { let data = source.resField ? _get(axiosRes, source.resField, []) : axiosRes let interceptResponse = source.interceptResponse let comData = [] if (interceptResponse && utils.isFunc(interceptResponse)) { let isContinue = true let doneFn = (type = true) => { isContinue = type } let interceptResponseRes = interceptResponse(doneFn, data, axiosRes) interceptResponseRes = interceptResponseRes || data if (!isContinue) { console.warn('interceptResponse--拦截') return } if (utils.isArr(interceptResponseRes)) { comData = interceptResponseRes } else { console.error('非法,传入el-tree组件的data非array') comData = [] } } else { if (!utils.isArr(data)) { console.error('非法,传入el-tree组件的data非array') comData = [] } else { comData = data } } let response = source.response if (response && utils.isFunc(response)) { source.response(comData, axiosRes) } resolve(comData, axiosRes) this.$emit('loaded') }).catch((error) => { console.error(error) }) }) }, /** * @param {object} otherParams - 会合并进请求体的参数 * @return {Promise} */ _getSourceData(otherParams) { let source = this.source if (source && utils.isObj(source) && source.url) { let axiosAttrs = utils.deepCopy(source) Object.keys(axiosAttrs).map(key => { if (nonAxiosAttrs.includes(key)) { delete axiosAttrs[key] } }) if (axiosAttrs.method === 'get') { Object.assign(axiosAttrs.params, otherParams) } else { Object.assign(axiosAttrs.data, otherParams) } let beforeRequest = source.beforeRequest if (beforeRequest && utils.isFunc(beforeRequest)) { // 根据请求url获取数据 let isContinue = true let doneFn = (type = true) => { isContinue = type } var beforeResult = beforeRequest(doneFn, axiosAttrs) let _axiosAttrs = beforeResult || axiosAttrs if (!isContinue) { console.warn('beforeRequest--请求拦截') return } else { if (!utils.isObj(_axiosAttrs)) { console.error('非法,beforeRequest返回的非axios参数对象') return } return this._requestAxios(_axiosAttrs) } } else { return this._requestAxios(axiosAttrs) } } else { this.$emit('loaded') // 从data中获取数据 return new Promise((resolve, reject) => { resolve([]) }) } }, _loadData() { if (this.source.url && this.treeProps.lazy !== undefined) { // 有设置source且设置lazy const LAZYKEY = 'id' let defaultSourceLazy = (node, resolve) => { // 设置了lazyOption.showMaxLevel let showMaxLevel = this.lazyOption.showMaxLevel > 0 ? this.lazyOption.showMaxLevel : 0 if (showMaxLevel && node.level >= showMaxLevel) { return } // 首次不传 var obj = {} if (node.level > 0) { obj[this.source.lazyKey || LAZYKEY] = node.data && node.data[this.treeProps.nodeKey] } else { obj[this.source.lazyKey || LAZYKEY] = '' } this._getSourceData(obj).then(data => { if (node.level === 0) { // 首次请求,请求回来的data连接外部传入的data this.setData(data) } else { // 展示最大层级时,就是最末层节点 if (showMaxLevel && node.level === (showMaxLevel - 1)) { data.map(item => { item[this.treeProps.props.isLeaf] = true }) } // 根据disabledLevel的配置,看是否禁用节点 if (this.disabledLevel[node.level + 1]) { data.map(item => { item['disabled'] = true }) } // 由于懒加载后追加节点,不会同步到this.treeProps.data,所以得特别留意 resolve(data) } }) } this.treeProps.load = this.treeProps.load || defaultSourceLazy } else if (this.source.url) { this._getSourceData().then(data => { // 有设置source,首次请求 this.setData(data) }) } else { this.setData(this.treeProps.data) } }, _setTreeCheckboxStatusFn() { if (this.multiple) { return } else { this.treeProps['checkStrictly'] = true this.defaultListener['check'] = (item, checkStatus) => { this.$refs.tree.setCheckedKeys([]) this.$refs.tree.setCheckedKeys([item[this.treeProps['nodeKey']]]) } } }, _camelCaseTransformFn(data) { if (utils.isObj(data)) { let obj = {} Object.keys(data).map((key) => { obj[camelCase(key)] = data[key] }) return obj } if (utils.isStr(data)) { return camelCase(data) } return data }, _mergeTreeObjFn() { this.treeProps = Object.assign({}, this.defaultProps, this._camelCaseTransformFn(this.$attrs)) }, _mergeTreeEventFn() { this.treeListeners = Object.assign({}, this.defaultListener, this.$listeners) }, _watchElTreeAttr() { attributes.map(attr => { if (this.$attrs[attr]) { this.$watch(function() { return this.$attrs[attr] }, (newVal, oldVal) => { this.treeProps[camelCase(attr)] = newVal }, { deep: true }) } }) } } } </script>
8b290a27c82abd8a7839f4fd61e0dc0c
{ "intermediate": 0.41349267959594727, "beginner": 0.4957042634487152, "expert": 0.0908031016588211 }
13,491
redis cache user logon status sample
230c4ad27f84cdee666187575722dfc0
{ "intermediate": 0.3614460825920105, "beginner": 0.2925986051559448, "expert": 0.34595534205436707 }
13,492
develop java source code for Music Player: Develop a music player that uses JavaFX to provide an interactive user interface. The player should allow users to browse and play their music collections, create playlists, and customize the player’s settings.
83ca7077cdffb5d2b10a66af2fc554bd
{ "intermediate": 0.5674477219581604, "beginner": 0.20479634404182434, "expert": 0.22775594890117645 }
13,493
The opengl version of Windows is 1.1, and the error 'Failed to create GLFW window' is still reported after using GLFW
5844097674d5e56e861f0d683c6c922c
{ "intermediate": 0.4199145436286926, "beginner": 0.23291711509227753, "expert": 0.34716829657554626 }
13,494
use jest create ut for this component: <template> <div> <el-tree v-if="treeVisible" ref="tree" v-bind="treeProps" v-on="treeListeners" /> </div> </template> <script> const nonAxiosAttrs = [ 'beforeRequest', 'interceptResponse', 'response', 'resField', 'lazyKey' ] export default { name: 'GdTree', data() { return { treeVisible: true, treeProps: {}, // 取树的属性用这个 treeListeners: {}, defaultProps: { data: [], showCheckbox: true, nodeKey: 'id', props: { label: 'label', children: 'children', isLeaf: 'leaf' } }, defaultListener: {} } }, watch: {}, created() { // console.log(this) this._mergeTreeObjFn() this._setTreeCheckboxStatusFn() this._mergeTreeEventFn() // this._watchElTreeAttr() if (this.auto) { this._loadData() } // this.$gdMar.send('gd-tree-loaded') }, mounted() {}, methods: { // 重新load一下数据,比如重新请求一个接口 loadData() { this.treeVisible = false this._loadData() this.$nextTick(() => { this.treeVisible = true }) }, getRef() { return this.$refs.tree }, setData(data) { if (!utils.isArr(data)) { console.error('setData中的参数data必须为数组') return } // 对数据按照showLevel的设置进行处理 if (this.showLevel.length > 0) { data = this._setDataByShowLevel(data) } this._traverseTreeToSetAttr(data) // 这个函数,目前只用于初始化的数据 this.treeProps.data = data }, _setDataByShowLevel(data) { let treeData = _cloneDeep(data) let level = 1 let queue = [] let result = [] // 给每个树节点打上gd-tree-id treeData.map((level1, index) => { level1['gd-tree-id'] = index queue.push(level1) }) let treeLevelData = {} let childrenField = this.treeProps.props.children let showLevel = this.showLevel.sort((a, b) => (a - b)) // BFS while (queue.length > 0) { let length = queue.length treeLevelData[level] = [] for (let i = 0; i < length; i++) { let queueTop = queue.shift() let children = queueTop[childrenField] if (children && children.length > 0) { children.map((item, index) => { // 需要显示的层级会加上-index,不需要显示的继承父亲的gd-tree-id,方便下面查找,提高性能 if (showLevel.indexOf(+level + 1) > 0) { item['gd-tree-id'] = `${queueTop['gd-tree-id']}-${index}` } else { item['gd-tree-id'] = queueTop['gd-tree-id'] } queue.push(item) }) } queueTop.children = [] // 清空childrenField treeLevelData[level].push(queueTop) } level++ } // 对showLevel排序 showLevel.map((level, index) => { let levelData = treeLevelData[level] if (!isNaN(level) && levelData) { if (index === 0) { result.push(...levelData) } else { levelData.map((item, index) => { // 根据gdTreeId直接找到要挂靠的父元素 let gdTreeId = item['gd-tree-id'] + '' let levels = gdTreeId.split('-') levels.pop() let getStr levels.map((item, index) => { if (index === 0) { getStr = [item] } else { getStr.push(childrenField, item) } }) let parantItem = _get(result, getStr) parantItem.children.push(item) }) } } }) return result }, _traverseTreeToSetAttr(treeData) { let level = 1 // BFS let queue = [] for (let level1 of treeData) { queue.push(level1) } while (queue.length > 0) { let length = queue.length for (let i = 0; i < length; i++) { let queueTop = queue.shift() let children = queueTop[this.treeProps.props.children] if (this.disabledLevel[level]) { queueTop['disabled'] = true } if (children && children.length > 0) { children.map(item => { queue.push(item) }) } } level++ } }, // 发起请求 _requestAxios(axiosAttrs) { let axiosInstance = gb.axios let source = this.source return new Promise((resolve, reject) => { axiosInstance(axiosAttrs).then(axiosRes => { let data = source.resField ? _get(axiosRes, source.resField, []) : axiosRes let interceptResponse = source.interceptResponse let comData = [] if (interceptResponse && utils.isFunc(interceptResponse)) { let isContinue = true let doneFn = (type = true) => { isContinue = type } let interceptResponseRes = interceptResponse(doneFn, data, axiosRes) interceptResponseRes = interceptResponseRes || data if (!isContinue) { console.warn('interceptResponse--拦截') return } if (utils.isArr(interceptResponseRes)) { comData = interceptResponseRes } else { console.error('非法,传入el-tree组件的data非array') comData = [] } } else { if (!utils.isArr(data)) { console.error('非法,传入el-tree组件的data非array') comData = [] } else { comData = data } } let response = source.response if (response && utils.isFunc(response)) { source.response(comData, axiosRes) } resolve(comData, axiosRes) this.$emit('loaded') }).catch((error) => { console.error(error) }) }) }, /** * @param {object} otherParams - 会合并进请求体的参数 * @return {Promise} */ _getSourceData(otherParams) { let source = this.source if (source && utils.isObj(source) && source.url) { let axiosAttrs = utils.deepCopy(source) Object.keys(axiosAttrs).map(key => { if (nonAxiosAttrs.includes(key)) { delete axiosAttrs[key] } }) if (axiosAttrs.method === 'get') { Object.assign(axiosAttrs.params, otherParams) } else { Object.assign(axiosAttrs.data, otherParams) } let beforeRequest = source.beforeRequest if (beforeRequest && utils.isFunc(beforeRequest)) { // 根据请求url获取数据 let isContinue = true let doneFn = (type = true) => { isContinue = type } var beforeResult = beforeRequest(doneFn, axiosAttrs) let _axiosAttrs = beforeResult || axiosAttrs if (!isContinue) { console.warn('beforeRequest--请求拦截') return } else { if (!utils.isObj(_axiosAttrs)) { console.error('非法,beforeRequest返回的非axios参数对象') return } return this._requestAxios(_axiosAttrs) } } else { return this._requestAxios(axiosAttrs) } } else { this.$emit('loaded') // 从data中获取数据 return new Promise((resolve, reject) => { resolve([]) }) } }, _loadData() { if (this.source.url && this.treeProps.lazy !== undefined) { // 有设置source且设置lazy const LAZYKEY = 'id' let defaultSourceLazy = (node, resolve) => { // 设置了lazyOption.showMaxLevel let showMaxLevel = this.lazyOption.showMaxLevel > 0 ? this.lazyOption.showMaxLevel : 0 if (showMaxLevel && node.level >= showMaxLevel) { return } // 首次不传 var obj = {} if (node.level > 0) { obj[this.source.lazyKey || LAZYKEY] = node.data && node.data[this.treeProps.nodeKey] } else { obj[this.source.lazyKey || LAZYKEY] = '' } this._getSourceData(obj).then(data => { if (node.level === 0) { // 首次请求,请求回来的data连接外部传入的data this.setData(data) } else { // 展示最大层级时,就是最末层节点 if (showMaxLevel && node.level === (showMaxLevel - 1)) { data.map(item => { item[this.treeProps.props.isLeaf] = true }) } // 根据disabledLevel的配置,看是否禁用节点 if (this.disabledLevel[node.level + 1]) { data.map(item => { item['disabled'] = true }) } // 由于懒加载后追加节点,不会同步到this.treeProps.data,所以得特别留意 resolve(data) } }) } this.treeProps.load = this.treeProps.load || defaultSourceLazy } else if (this.source.url) { this._getSourceData().then(data => { // 有设置source,首次请求 this.setData(data) }) } else { this.setData(this.treeProps.data) } }, _setTreeCheckboxStatusFn() { if (this.multiple) { return } else { this.treeProps['checkStrictly'] = true this.defaultListener['check'] = (item, checkStatus) => { this.$refs.tree.setCheckedKeys([]) this.$refs.tree.setCheckedKeys([item[this.treeProps['nodeKey']]]) } } }, _camelCaseTransformFn(data) { if (utils.isObj(data)) { let obj = {} Object.keys(data).map((key) => { obj[camelCase(key)] = data[key] }) return obj } if (utils.isStr(data)) { return camelCase(data) } return data }, _mergeTreeObjFn() { this.treeProps = Object.assign({}, this.defaultProps, this._camelCaseTransformFn(this.$attrs)) }, _mergeTreeEventFn() { this.treeListeners = Object.assign({}, this.defaultListener, this.$listeners) }, _watchElTreeAttr() { attributes.map(attr => { if (this.$attrs[attr]) { this.$watch(function() { return this.$attrs[attr] }, (newVal, oldVal) => { this.treeProps[camelCase(attr)] = newVal }, { deep: true }) } }) } } } </script>
0abaad199058599a8cc4e16e1143f9af
{ "intermediate": 0.39304572343826294, "beginner": 0.4759325683116913, "expert": 0.131021648645401 }
13,495
use jest creat some ut from this component: <template> <div> <el-tree v-if="treeVisible" ref="tree" v-bind="treeProps" v-on="treeListeners" /> </div> </template> <script> const nonAxiosAttrs = [ 'beforeRequest', 'interceptResponse', 'response', 'resField', 'lazyKey' ] export default { name: 'GdTree', data() { return { treeVisible: true, treeProps: {}, // 取树的属性用这个 treeListeners: {}, defaultProps: { data: [], showCheckbox: true, nodeKey: 'id', props: { label: 'label', children: 'children', isLeaf: 'leaf' } }, defaultListener: {} } }, watch: {}, created() { // console.log(this) this._mergeTreeObjFn() this._setTreeCheckboxStatusFn() this._mergeTreeEventFn() // this._watchElTreeAttr() if (this.auto) { this._loadData() } // this.$gdMar.send('gd-tree-loaded') }, mounted() {}, methods: { // 重新load一下数据,比如重新请求一个接口 loadData() { this.treeVisible = false this._loadData() this.$nextTick(() => { this.treeVisible = true }) }, getRef() { return this.$refs.tree }, setData(data) { if (!utils.isArr(data)) { console.error('setData中的参数data必须为数组') return } // 对数据按照showLevel的设置进行处理 if (this.showLevel.length > 0) { data = this._setDataByShowLevel(data) } this._traverseTreeToSetAttr(data) // 这个函数,目前只用于初始化的数据 this.treeProps.data = data }, _setDataByShowLevel(data) { let treeData = _cloneDeep(data) let level = 1 let queue = [] let result = [] // 给每个树节点打上gd-tree-id treeData.map((level1, index) => { level1['gd-tree-id'] = index queue.push(level1) }) let treeLevelData = {} let childrenField = this.treeProps.props.children let showLevel = this.showLevel.sort((a, b) => (a - b)) // BFS while (queue.length > 0) { let length = queue.length treeLevelData[level] = [] for (let i = 0; i < length; i++) { let queueTop = queue.shift() let children = queueTop[childrenField] if (children && children.length > 0) { children.map((item, index) => { // 需要显示的层级会加上-index,不需要显示的继承父亲的gd-tree-id,方便下面查找,提高性能 if (showLevel.indexOf(+level + 1) > 0) { item['gd-tree-id'] = `${queueTop['gd-tree-id']}-${index}` } else { item['gd-tree-id'] = queueTop['gd-tree-id'] } queue.push(item) }) } queueTop.children = [] // 清空childrenField treeLevelData[level].push(queueTop) } level++ } // 对showLevel排序 showLevel.map((level, index) => { let levelData = treeLevelData[level] if (!isNaN(level) && levelData) { if (index === 0) { result.push(...levelData) } else { levelData.map((item, index) => { // 根据gdTreeId直接找到要挂靠的父元素 let gdTreeId = item['gd-tree-id'] + '' let levels = gdTreeId.split('-') levels.pop() let getStr levels.map((item, index) => { if (index === 0) { getStr = [item] } else { getStr.push(childrenField, item) } }) let parantItem = _get(result, getStr) parantItem.children.push(item) }) } } }) return result }, _traverseTreeToSetAttr(treeData) { let level = 1 // BFS let queue = [] for (let level1 of treeData) { queue.push(level1) } while (queue.length > 0) { let length = queue.length for (let i = 0; i < length; i++) { let queueTop = queue.shift() let children = queueTop[this.treeProps.props.children] if (this.disabledLevel[level]) { queueTop['disabled'] = true } if (children && children.length > 0) { children.map(item => { queue.push(item) }) } } level++ } }, // 发起请求 _requestAxios(axiosAttrs) { let axiosInstance = gb.axios let source = this.source return new Promise((resolve, reject) => { axiosInstance(axiosAttrs).then(axiosRes => { let data = source.resField ? _get(axiosRes, source.resField, []) : axiosRes let interceptResponse = source.interceptResponse let comData = [] if (interceptResponse && utils.isFunc(interceptResponse)) { let isContinue = true let doneFn = (type = true) => { isContinue = type } let interceptResponseRes = interceptResponse(doneFn, data, axiosRes) interceptResponseRes = interceptResponseRes || data if (!isContinue) { console.warn('interceptResponse--拦截') return } if (utils.isArr(interceptResponseRes)) { comData = interceptResponseRes } else { console.error('非法,传入el-tree组件的data非array') comData = [] } } else { if (!utils.isArr(data)) { console.error('非法,传入el-tree组件的data非array') comData = [] } else { comData = data } } let response = source.response if (response && utils.isFunc(response)) { source.response(comData, axiosRes) } resolve(comData, axiosRes) this.$emit('loaded') }).catch((error) => { console.error(error) }) }) }, /** * @param {object} otherParams - 会合并进请求体的参数 * @return {Promise} */ _getSourceData(otherParams) { let source = this.source if (source && utils.isObj(source) && source.url) { let axiosAttrs = utils.deepCopy(source) Object.keys(axiosAttrs).map(key => { if (nonAxiosAttrs.includes(key)) { delete axiosAttrs[key] } }) if (axiosAttrs.method === 'get') { Object.assign(axiosAttrs.params, otherParams) } else { Object.assign(axiosAttrs.data, otherParams) } let beforeRequest = source.beforeRequest if (beforeRequest && utils.isFunc(beforeRequest)) { // 根据请求url获取数据 let isContinue = true let doneFn = (type = true) => { isContinue = type } var beforeResult = beforeRequest(doneFn, axiosAttrs) let _axiosAttrs = beforeResult || axiosAttrs if (!isContinue) { console.warn('beforeRequest--请求拦截') return } else { if (!utils.isObj(_axiosAttrs)) { console.error('非法,beforeRequest返回的非axios参数对象') return } return this._requestAxios(_axiosAttrs) } } else { return this._requestAxios(axiosAttrs) } } else { this.$emit('loaded') // 从data中获取数据 return new Promise((resolve, reject) => { resolve([]) }) } }, _loadData() { if (this.source.url && this.treeProps.lazy !== undefined) { // 有设置source且设置lazy const LAZYKEY = 'id' let defaultSourceLazy = (node, resolve) => { // 设置了lazyOption.showMaxLevel let showMaxLevel = this.lazyOption.showMaxLevel > 0 ? this.lazyOption.showMaxLevel : 0 if (showMaxLevel && node.level >= showMaxLevel) { return } // 首次不传 var obj = {} if (node.level > 0) { obj[this.source.lazyKey || LAZYKEY] = node.data && node.data[this.treeProps.nodeKey] } else { obj[this.source.lazyKey || LAZYKEY] = '' } this._getSourceData(obj).then(data => { if (node.level === 0) { // 首次请求,请求回来的data连接外部传入的data this.setData(data) } else { // 展示最大层级时,就是最末层节点 if (showMaxLevel && node.level === (showMaxLevel - 1)) { data.map(item => { item[this.treeProps.props.isLeaf] = true }) } // 根据disabledLevel的配置,看是否禁用节点 if (this.disabledLevel[node.level + 1]) { data.map(item => { item['disabled'] = true }) } // 由于懒加载后追加节点,不会同步到this.treeProps.data,所以得特别留意 resolve(data) } }) } this.treeProps.load = this.treeProps.load || defaultSourceLazy } else if (this.source.url) { this._getSourceData().then(data => { // 有设置source,首次请求 this.setData(data) }) } else { this.setData(this.treeProps.data) } }, _setTreeCheckboxStatusFn() { if (this.multiple) { return } else { this.treeProps['checkStrictly'] = true this.defaultListener['check'] = (item, checkStatus) => { this.$refs.tree.setCheckedKeys([]) this.$refs.tree.setCheckedKeys([item[this.treeProps['nodeKey']]]) } } }, _camelCaseTransformFn(data) { if (utils.isObj(data)) { let obj = {} Object.keys(data).map((key) => { obj[camelCase(key)] = data[key] }) return obj } if (utils.isStr(data)) { return camelCase(data) } return data }, _mergeTreeObjFn() { this.treeProps = Object.assign({}, this.defaultProps, this._camelCaseTransformFn(this.$attrs)) }, _mergeTreeEventFn() { this.treeListeners = Object.assign({}, this.defaultListener, this.$listeners) }, _watchElTreeAttr() { attributes.map(attr => { if (this.$attrs[attr]) { this.$watch(function() { return this.$attrs[attr] }, (newVal, oldVal) => { this.treeProps[camelCase(attr)] = newVal }, { deep: true }) } }) } } } </script>
b58076c8e90d59bf6b9c2bacbba08552
{ "intermediate": 0.4010235071182251, "beginner": 0.4423586428165436, "expert": 0.15661777555942535 }
13,496
You don't need any OPENAIYou don't need any OPENAI
c4c1ae5a22ead575591dc18809b21d51
{ "intermediate": 0.3293657898902893, "beginner": 0.2441634088754654, "expert": 0.4264707863330841 }
13,497
hello?
8b3dc0b6ffde61162340296d5a695614
{ "intermediate": 0.3582178056240082, "beginner": 0.25206828117370605, "expert": 0.3897138833999634 }
13,498
ok, now some 4 colored circles spinning around big(Sun) one, but they suppose to be obscured by the Sun, right? fix obscurage problem, and also represent astronomical terms in arrows pointing accordingly and words of text.: <!DOCTYPE html> <html> <head> <title>Solar System</title> <style> canvas { background: black; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="canvas" width="600" height="600"></canvas> <script> var ctx = document.getElementById("canvas").getContext("2d"); var sun = { x: 300, y: 300, radius: 50, color: "yellow" }; var planets = [ { name: "Mercury", distance: 70, radius: 5, color: "gray", inclination: 0, eccentricity: 0.01, angle: Math.random() * Math.PI * 2 }, { name: "Venus", distance: 100, radius: 10, color: "orange", inclination: Math.PI / 4, eccentricity: 0.02, angle: Math.random() * Math.PI * 2 }, { name: "Earth", distance: 150, radius: 12, color: "blue", inclination: Math.PI / 8, eccentricity: 0.03, angle: Math.random() * Math.PI * 2 }, { name: "Mars", distance: 200, radius: 8, color: "red", inclination: Math.PI / 16, eccentricity: 0.04, angle: Math.random() * Math.PI * 2 } ]; function drawPlanet(planet) { ctx.beginPath(); var x = sun.x + planet.distance * Math.cos(planet.angle); var y = sun.y + planet.distance * Math.sin(planet.angle) * Math.sin(planet.inclination); ctx.arc(x, y, planet.radius, 0, 2 * Math.PI); ctx.fillStyle = planet.color; ctx.fill(); ctx.closePath(); } function animate() { ctx.clearRect(0, 0, 600, 600); ctx.beginPath(); ctx.arc(sun.x, sun.y, sun.radius, 0, 2 * Math.PI); ctx.fillStyle = sun.color; ctx.fill(); ctx.closePath(); planets.forEach(function(planet) { planet.angle += 0.01; drawPlanet(planet); }); requestAnimationFrame(animate); } animate(); </script> </body> </html>
d72b8d339337a084bdb87238ebbb1855
{ "intermediate": 0.37863871455192566, "beginner": 0.37849920988082886, "expert": 0.2428620457649231 }
13,499
looks no errors but canvas is black. : <!DOCTYPE html> <html> <head> <title>Solar System</title> <style> canvas { background: black; display: block; margin: 0 auto; } </style> </head> <body> <canvas id="canvas" width="600" height="600"></canvas> <script> var ctx = document.getElementById("canvas").getContext("2d"); var sun = { x: 300, y: 300, radius: 50, color: "yellow" }; var planets = [ { name: "Mercury", distance: 70, radius: 5, color: "gray", inclination: 0, eccentricity: 0.01, angle: Math.random() * Math.PI * 2, satellites: [] }, { name: "Venus", distance: 100, radius: 10, color: "orange", inclination: Math.PI / 4, eccentricity: 0.02, angle: Math.random() * Math.PI * 2, satellites: [] }, { name: "Earth", distance: 150, radius: 12, color: "blue", inclination: Math.PI / 8, eccentricity: 0.03, angle: Math.random() * Math.PI * 2, satellites: [ { name: "Moon", distance: 40, radius: 3, color: "gray", inclination: Math.PI / 16, eccentricity: 0.02, angle: Math.random() * Math.PI * 2 } ] }, { name: "Mars", distance: 200, radius: 8, color: "red", inclination: Math.PI / 16, eccentricity: 0.04, angle: Math.random() * Math.PI * 2, satellites: [ { name: "Phobos", distance: 20, radius: 2, color: "gray", inclination: Math.PI / 32, eccentricity: 0.02, angle: Math.random() * Math.PI * 2 }, { name: "Deimos", distance: 30, radius: 3, color: "gray", inclination: Math.PI / 64, eccentricity: 0.03, angle: Math.random() * Math.PI * 2 } ] } ]; function drawPlanet(planet) { var directionX = Math.cos(planet.angle); var directionY = Math.sin(planet.angle) * Math.sin(planet.inclination); var planetX = sun.x + planet.distance * directionX; var planetY = sun.y + planet.distance * directionY; if (planetX + planet.radius < 0 || planetX - planet.radius > 600 || planetY + planet.radius < 0 || planetY - planet.radius > 600) return; if (planetX > sun.x) { var planetTop = planetY - planet.radius * Math.sin(Math.acos((sun.x - planetX) / planet.distance)); var planetBottom = planetY + planet.radius * Math.sin(Math.acos((sun.x - planetX) / planet.distance)); ctx.beginPath(); ctx.moveTo(sun.x, sun.y); ctx.lineTo(planetX, planetTop); ctx.lineTo(planetX, planetBottom); ctx.closePath(); ctx.fillStyle = "black"; ctx.fill(); if (planet.satellites && planet.satellites.length > 0) { planet.satellites.forEach(function(satellite) { var satelliteDirectionX = Math.cos(satellite.angle); var satelliteDirectionY = Math.sin(satellite.angle) * Math.sin(satellite.inclination); var satelliteX = planetX + satellite.distance * satelliteDirectionX; var satelliteY = planetY + satellite.distance * satelliteDirectionY; if (satelliteX + satellite.radius < 0 || satelliteX - satellite.radius > 600 || satelliteY + satellite.radius < 0 || satelliteY - satellite.radius > 600) return; var satelliteTop = satelliteY - satellite.radius * Math.sin(Math.acos((planetX - satelliteX) / satellite.distance)); var satelliteBottom = satelliteY + satellite.radius * Math.sin(Math.acos((planetX - satelliteX) / satellite.distance)); ctx.beginPath(); ctx.moveTo(planetX, planetY); ctx.lineTo(satelliteX, satelliteTop); ctx.lineTo(satelliteX, satelliteBottom); ctx.closePath(); ctx.fillStyle = "black"; ctx.fill(); }); } ctx.beginPath(); ctx.arc(planetX, planetY, planet.radius, 0, 2 * Math.PI); ctx.fillStyle = planet.color; ctx.fill(); ctx.closePath(); ctx.beginPath(); ctx.moveTo(sun.x, sun.y); ctx.lineTo(sun.x + planet.distance, sun.y); ctx.strokeStyle = "white"; ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.moveTo(sun.x, sun.y); ctx.lineTo(planetX, planetY); ctx.strokeStyle = "white"; ctx.stroke(); ctx.closePath(); var angleProjected = Math.asin(directionY / Math.sqrt(directionX ** 2 + directionY ** 2)); if (directionX < 0) angleProjected = Math.PI - angleProjected; var textX = sun.x + (planet.distance / 2) * Math.cos(angleProjected); var textY = sun.y + (planet.distance / 2) * Math.sin(angleProjected); var text = planet.name + ", dist: " + planet.distance + "km"; ctx.font = "14px Arial"; ctx.fillStyle = "white"; ctx.fillText(text, textX, textY); planet.satellites.forEach(function(satellite) { drawPlanet(satellite); }); } function animate() { ctx.clearRect(0, 0, 600, 600); ctx.beginPath(); ctx.arc(sun.x, sun.y, sun.radius, 0, 2 * Math.PI); ctx.fillStyle = sun.color; ctx.fill(); ctx.closePath(); planets.forEach(function(planet) { planet.angle += 0.01; drawPlanet(planet); }); requestAnimationFrame(animate); } animate();} </script> </body> </html>
adf1ef3a5d1979c30dadb5bf5b069346
{ "intermediate": 0.2457408905029297, "beginner": 0.5331008434295654, "expert": 0.22115826606750488 }
13,500
astronomical terms of movement of planets and orbit placement. output detailed list with explanations for each term Sure, here are some astronomical terms related to the movement of planets and orbit placement: 1. Orbit: The path that a planet or other celestial body follows as it revolves around another body in space. 2. Perihelion: The point in a planet’s orbit at which it is closest to the Sun. 3. Aphelion: The point in a planet’s orbit at which it is farthest from the Sun. 4. Eccentricity: The degree to which an orbit deviates from a perfect circle; in other words, how “oval” or elongated an orbit is. 5. Inclination: The angle between a planet’s orbital plane and the plane of the ecliptic (the imaginary plane that Earth’s orbit follows as it revolves around the Sun). 6. Retrograde motion: The apparent backward motion of a planet in the sky, caused by the differing orbital speeds of Earth and the other planet. 7. Synodic period: The time it takes for a planet to return to the same position relative to Earth and the Sun, as seen from Earth. 8. Sidereal period: The time it takes for a planet to complete one orbit around the Sun, as measured with respect to the fixed stars. 9. Precession: The slow, cyclical wobbling of the Earth’s rotational axis that causes changes in the positions of the stars over long periods of time. 10. Tidal locking: The phenomenon by which a planet’s rotation and revolution become synchronized with each other, so that one side of the planet always faces its star. These are just a few of the many terms used in astronomy to describe the movement of planets and their orbits.
f3363828d1edad07f13aba88c78915f4
{ "intermediate": 0.3041151762008667, "beginner": 0.31953585147857666, "expert": 0.37634900212287903 }
13,501
I don’t see any actual update in planet movement animation, but the timefactor slider changing the position frame. You’re right, I apologize for the mistake in my previous response. The problem is that the transformation properties for each planet were not properly concatenated into a single string. Here is an updated version of the JavaScript code that should fix the issue: <!DOCTYPE html> <html> <head> <style> body { margin: 0; padding: 0; background-color: black; font-family: sans-serif; } #sun { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; border-radius: 50%; background-color: yellow; } .planet { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 20px; height: 20px; border-radius: 50%; animation-timing-function: linear; opacity: 0.8; } #mercury { animation: orbit-mercury 56d linear infinite; background-color: #aaaaaa; transform: translateX(43px); } #venus { animation: orbit-venus 225d linear infinite; background-color: #ff6600; transform: translateX(107px); } #earth { animation: orbit-earth 365d linear infinite; background-color: #3366cc; transform: translateX(146px); } @keyframes orbit-mercury { from { transform: rotate(0deg) translateX(43px) rotate(0deg); } to { transform: rotate(360deg) translateX(43px) rotate(-360deg); } } @keyframes orbit-venus { from { transform: rotate(0deg) translateX(107px) rotate(0deg); } to { transform: rotate(360deg) translateX(107px) rotate(-360deg); } } @keyframes orbit-earth { from { transform: rotate(0deg) translateX(146px) rotate(0deg); } to { transform: rotate(360deg) translateX(146px) rotate(-360deg); } } input[type=range], label[for=time-factor] { display: inline-block; vertical-align: middle; } label[for=time-factor] { margin-right: 10px; } #time-factor { width: 150px; } </style> </head> <body> <div id="sun"></div> <div id="mercury" class="planet"></div> <div id="venus" class="planet"></div> <div id="earth" class="planet"></div> <label for="time-factor">Time factor:</label> <input type="range" id="time-factor" min="0.1" max="10" step="0.1" value="1.0"> <script> const timeFactorInput = document.getElementById('time-factor'); const mercury = document.getElementById('mercury'); const venus = document.getElementById('venus'); const earth = document.getElementById('earth'); let timeFactor = 1; function updateTimeFactor() { timeFactor = parseFloat(timeFactorInput.value); } timeFactorInput.addEventListener('change', updateTimeFactor); function animate() { requestAnimationFrame(animate); const now = new Date(); const mercuryAngle = (now / (56 * timeFactor * 24 * 60 * 60 * 1000)) * 360; const venusAngle = (now / (225 * timeFactor * 24 * 60 * 60 * 1000)) * 360; const earthAngle = (now / (365 * timeFactor * 24 * 60 * 60 * 1000)) * 360; mercury.style.transform = 'rotate(' + mercuryAngle + 'deg) translateX(43px) rotate(' + -mercuryAngle + 'deg)'; venus.style.transform = 'rotate(' + venusAngle + 'deg) translateX(107px) rotate(' + -venusAngle + 'deg)'; earth.style.transform = 'rotate(' + earthAngle + 'deg) translateX(146px) rotate(' + -earthAngle + 'deg)'; } animate(); </script> </body> </html>
08d736cac5792deeacee25a97ad3c8c1
{ "intermediate": 0.29052087664604187, "beginner": 0.4586465656757355, "expert": 0.25083255767822266 }
13,502
can you output it with all the astronomical terms applied precisely. also, set timefactor to visually acceptable value of 1000.: 1. Orbit: The path that a planet or other celestial body follows as it revolves around another body in space. 2. Perihelion: The point in a planet’s orbit at which it is closest to the Sun. 3. Aphelion: The point in a planet’s orbit at which it is farthest from the Sun. 4. Eccentricity: The degree to which an orbit deviates from a perfect circle; in other words, how “oval” or elongated an orbit is. 5. Inclination: The angle between a planet’s orbital plane and the plane of the ecliptic (the imaginary plane that Earth’s orbit follows as it revolves around the Sun). 6. Retrograde motion: The apparent backward motion of a planet in the sky, caused by the differing orbital speeds of Earth and the other planet. 7. Synodic period: The time it takes for a planet to return to the same position relative to Earth and the Sun, as seen from Earth. 8. Sidereal period: The time it takes for a planet to complete one orbit around the Sun, as measured with respect to the fixed stars. 9. Precession: The slow, cyclical wobbling of the Earth’s rotational axis that causes changes in the positions of the stars over long periods of time. 10. Tidal locking: The phenomenon by which a planet’s rotation and revolution become synchronized with each other, so that one side of the planet always faces its star. it also will be nice if you somehow make it into full 3d, without any frameworks or third-paty libraries used.: <!DOCTYPE html> <html> <head> <style> body { margin: 0; padding: 0; background-color: black; font-family: sans-serif; } #sun { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; border-radius: 50%; background-color: yellow; } .planet { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 20px; height: 20px; border-radius: 50%; animation-timing-function: linear; opacity: 0.8; } #mercury { animation: orbit-mercury 88d linear infinite; background-color: #aaaaaa; transform: translateX(50px); } #venus { animation: orbit-venus 224.7d linear infinite; background-color: #ff6600; transform: translateX(80px); } #earth { animation: orbit-earth 365.25d linear infinite; background-color: #3366cc; transform: translateX(110px); } @keyframes orbit-mercury { from { transform: rotate(0deg) translateX(50px) rotate(0deg); } to { transform: rotate(360deg) translateX(50px) rotate(-360deg); } } @keyframes orbit-venus { from { transform: rotate(0deg) translateX(80px) rotate(0deg) translateY(8.7px) rotate(0deg); } to { transform: rotate(360deg) translateX(80px) rotate(-360deg) translateY(8.7px) rotate(-1.26deg); } } @keyframes orbit-earth { from { transform: rotate(0deg) translateX(110px) rotate(0deg) translateY(23.4px) rotate(0deg); } to { transform: rotate(360deg) translateX(110px) rotate(-360deg) translateY(23.4px) rotate(-1.57deg); } } input[type=range], label[for=time-factor] { display: inline-block; vertical-align: middle; } label[for=time-factor] { margin-right: 10px; } #time-factor { width: 150px; } </style> </head> <body> <div id="sun"></div> <div id="mercury" class="planet"></div> <div id="venus" class="planet"></div> <div id="earth" class="planet"></div> <label for="time-factor">Time factor:</label> <input type="range" id="time-factor" min="0.1" max="10" step="0.1" value="1000"> <script> const timeFactorInput = document.getElementById('time-factor'); const mercury = document.getElementById('mercury'); const venus = document.getElementById('venus'); const earth = document.getElementById('earth'); const inclination = 7; const perihelion = { mercury: 46, venus: 107, earth: 147 }; const aphelion = { mercury: 69, venus: 109, earth: 152 }; const eccentricity = { mercury: 0.21, venus: 0.01, earth: 0.02 }; const siderealPeriod = { mercury: 88, venus: 224.7, earth: 365.25 }; const orbitalPeriod = { mercury: 87.97, venus: 224.7, earth: 365.25 }; const planetAxisAngle = { mercury: 0.01, venus: 2.64, earth: 23.44 }; let lastTime = null; let timeElapsed = 0; let timeFactor = 1; function updateTimeFactor() { timeFactor = parseFloat(timeFactorInput.value); } timeFactorInput.addEventListener('change', updateTimeFactor); function animate(now) { if (!lastTime) { lastTime = now; } const deltaTime = now - lastTime; lastTime = now; timeElapsed += deltaTime * timeFactor; const mercuryAngle = ((timeElapsed / (orbitalPeriod.mercury * 24 * 60 * 60)) * 360) + ((360 / siderealPeriod.mercury) * timeElapsed) - (planetAxisAngle.mercury * inclination); const venusAngle = ((timeElapsed / (orbitalPeriod.venus * 24 * 60 * 60)) * 360) + ((360 / siderealPeriod.venus) * timeElapsed) - (planetAxisAngle.venus * inclination); const earthAngle = ((timeElapsed / (orbitalPeriod.earth * 24 * 60 * 60)) * 360) + ((360 / siderealPeriod.earth) * timeElapsed) - (planetAxisAngle.earth * inclination); const mercuryPerihelion = perihelion.mercury * (1 + eccentricity.mercury); const mercuryAphelion = perihelion.mercury * (1 - eccentricity.mercury); const mercuryDistance = ((mercuryPerihelion - mercuryAphelion) / 2) + mercuryAphelion; mercury.style.transform = 'rotate(' + mercuryAngle + 'deg) translateX(' + mercuryDistance + 'px) rotate(' + -mercuryAngle + 'deg)'; const venusPerihelion = perihelion.venus * (1 + eccentricity.venus); const venusAphelion = perihelion.venus * (1 - eccentricity.venus); const venusDistance = ((venusPerihelion - venusAphelion) / 2) + venusAphelion; venus.style.transform = 'rotate(' + venusAngle + 'deg) translateX(' + venusDistance + 'px) rotate(' + -venusAngle + 'deg)'; const earthPerihelion = perihelion.earth * (1 + eccentricity.earth); const earthAphelion = perihelion.earth * (1 - eccentricity.earth); const earthDistance = ((earthPerihelion - earthAphelion) / 2) + earthAphelion; earth.style.transform = 'rotate(' + earthAngle + 'deg) translateX(' + earthDistance + 'px) rotate(' + -earthAngle + 'deg)'; requestAnimationFrame(animate); } animate(0); </script> </body> </html>
2ad917aa59c3629e84672e4513c5b784
{ "intermediate": 0.2814783453941345, "beginner": 0.39903998374938965, "expert": 0.3194817304611206 }
13,503
also, the mercury is too close to the Sun, need to adjust the sizes somehow, and to adjust all the sizes properly we need to convert the space scene into 3d by simply using simple javascript for that, without any frameworks or third-paty libraries used. <!DOCTYPE html> <html> <head> <style> body { margin: 0; padding: 0; background-color: black; font-family: sans-serif; } #sun { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 100px; height: 100px; border-radius: 50%; background-color: yellow; } .planet { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 20px; height: 20px; border-radius: 50%; animation-timing-function: linear; opacity: 0.8; } #mercury { animation: orbit-mercury 88d linear infinite; background-color: #ff0000; transform: translateX(50px); } #venus { animation: orbit-venus 224.7d linear infinite; background-color: #ff6600; transform: translateX(80px); } #earth { animation: orbit-earth 365.25d linear infinite; background-color: #3366cc; transform: translateX(110px); } @keyframes orbit-mercury { from { transform: rotate(0deg) translateX(50px) rotate(0deg); } to { transform: rotate(360deg) translateX(50px) rotate(-360deg); } } @keyframes orbit-venus { from { transform: rotate(0deg) translateX(80px) rotate(0deg) translateY(8.7px) rotate(0deg); } to { transform: rotate(360deg) translateX(80px) rotate(-360deg) translateY(8.7px) rotate(-1.26deg); } } @keyframes orbit-earth { from { transform: rotate(0deg) translateX(110px) rotate(0deg) translateY(23.4px) rotate(0deg); } to { transform: rotate(360deg) translateX(110px) rotate(-360deg) translateY(23.4px) rotate(-1.57deg); } } input[type=range], label[for=time-factor] { display: inline-block; vertical-align: middle; } label[for=time-factor] { margin-right: 10px; } #time-factor { width: 150px; } </style> </head> <body> <div id="solar-system"> <div id="sun"></div> <div id="mercury" class="planet"></div> <div id="venus" class="planet"></div> <div id="earth" class="planet"></div> </div> <label for="time-factor">Time factor:</label> <input type="range" id="time-factor" min="0.1" max="10" step="0.1" value="1000"> <script> const timeFactorInput = document.getElementById('time-factor'); const mercury = document.getElementById('mercury'); const venus = document.getElementById('venus'); const earth = document.getElementById('earth'); const inclination = 7; const perihelion = { mercury: 46, venus: 107, earth: 147 }; const aphelion = { mercury: 69, venus: 109, earth: 152 }; const eccentricity = { mercury: 0.21, venus: 0.01, earth: 0.02 }; const siderealPeriod = { mercury: 88, venus: 224.7, earth: 365.25 }; const orbitalPeriod = { mercury: 87.97, venus: 224.7, earth: 365.25 }; const planetAxisAngle = { mercury: 0.01, venus: 2.64, earth: 23.44 }; let lastTime = null; let timeElapsed = 0; let timeFactor = 1; function updateTimeFactor() { timeFactor = parseFloat(timeFactorInput.value); } timeFactorInput.addEventListener('change', updateTimeFactor); function animate(now) { if (!lastTime) { lastTime = now; } const deltaTime = now - lastTime; lastTime = now; timeElapsed += deltaTime * timeFactor; const mercuryAngle = ((timeElapsed / (orbitalPeriod.mercury * 24 * 60 * 60)) * 360) + ((360 / siderealPeriod.mercury) * timeElapsed) - (planetAxisAngle.mercury * inclination); const venusAngle = ((timeElapsed / (orbitalPeriod.venus * 24 * 60 * 60)) * 360) + ((360 / siderealPeriod.venus) * timeElapsed) - (planetAxisAngle.venus * inclination); const earthAngle = ((timeElapsed / (orbitalPeriod.earth * 24 * 60 * 60)) * 360) + ((360 / siderealPeriod.earth) * timeElapsed) - (planetAxisAngle.earth * inclination); const mercuryPerihelion = perihelion.mercury * (1 + eccentricity.mercury); const mercuryAphelion = perihelion.mercury * (1 - eccentricity.mercury); const mercuryDistance = ((mercuryPerihelion - mercuryAphelion) / 2) + mercuryAphelion; mercury.style.transform = 'rotate(' + mercuryAngle + 'deg) translateX(' + mercuryDistance + 'px) rotate(' + -mercuryAngle + 'deg)'; const venusPerihelion = perihelion.venus * (1 + eccentricity.venus); const venusAphelion = perihelion.venus * (1 - eccentricity.venus); const venusDistance = ((venusPerihelion - venusAphelion) / 2) + venusAphelion; venus.style.transform = 'rotate(' + venusAngle + 'deg) translateX(' + venusDistance + 'px) rotate(' + -venusAngle + 'deg)'; const earthPerihelion = perihelion.earth * (1 + eccentricity.earth); const earthAphelion = perihelion.earth * (1 - eccentricity.earth); const earthDistance = ((earthPerihelion - earthAphelion) / 2) + earthAphelion; earth.style.transform = 'rotate(' + earthAngle + 'deg) translateX(' + earthDistance + 'px) rotate(' + -earthAngle + 'deg)'; requestAnimationFrame(animate); } animate(0); </script> </body> </html> don't use any backticks, call styles in old fashion by using " and +.
af74722f8af20eaa6ab30aa376a62abb
{ "intermediate": 0.21356451511383057, "beginner": 0.49522098898887634, "expert": 0.2912144660949707 }
13,504
Sun need to be centered here plus the XYZ rotation of scene by mouse left button dragging in any empty space implemented. plus bg color to black with some random noise in form of milky way, without any image, frameworks or third-party libraries used. plus the time factor relatively to natural planetoid progression and their sizes difference adjusted. plus all possible astronomical terms accordingly applied to corresponding stellar bodily physics, as: 1. Orbit: The path that a planet or other celestial body follows as it revolves around another body in space. 2. Perihelion: The point in a planet’s orbit at which it is closest to the Sun. 3. Aphelion: The point in a planet’s orbit at which it is farthest from the Sun. 4. Eccentricity: The degree to which an orbit deviates from a perfect circle; in other words, how “oval” or elongated an orbit is. 5. Inclination: The angle between a planet’s orbital plane and the plane of the ecliptic (the imaginary plane that Earth’s orbit follows as it revolves around the Sun). 6. Retrograde motion: The apparent backward motion of a planet in the sky, caused by the differing orbital speeds of Earth and the other planet. 7. Synodic period: The time it takes for a planet to return to the same position relative to Earth and the Sun, as seen from Earth. 8. Sidereal period: The time it takes for a planet to complete one orbit around the Sun, as measured with respect to the fixed stars. 9. Precession: The slow, cyclical wobbling of the Earth’s rotational axis that causes changes in the positions of the stars over long periods of time. 10. Tidal locking: The phenomenon by which a planet’s rotation and revolution become synchronized with each other, so that one side of the planet always faces its star. Other terms might include Kepler’s laws of planetary motion (which describe the elliptical shape of planetary orbits and the speed at which planets move at various points in their orbits), the Roche limit (which describes how close a moon can orbit a planet before tidal forces tear it apart), and the Hill sphere (which describes the gravitational “sphere of influence” that a planet has around it, within which other celestial bodies are most likely to be bound to its gravity rather than that of the Sun). : const canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; function drawSolarSystem() { // Clear the canvas before drawing the planets ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw the Sun drawPlanet(sunPos.x, sunPos.y, sunPos.size, 'yellow'); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x, mercuryPos.y, mercuryPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, 'red'); // Draw Venus const venusPos2D = projectTo2D(venusPos.x, venusPos.y, venusPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, 'orange'); // Draw Earth const earthPos2D = projectTo2D(earthPos.x, earthPos.y, earthPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, 'blue'); // Update planet positions for the next frame updatePlanetPositions(); } function updatePlanetPositions() { // Update Mercury's position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus's position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth's position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const scale = distance / (distance + z); const x2d = canvas.width / 2 + x * scale; const y2d = canvas.height / 2 - y * scale; return { x: x2d, y: y2d }; } // Start the animation loop setInterval(drawSolarSystem, 16);
495d3eeb75156b114c6be15df2022556
{ "intermediate": 0.27965429425239563, "beginner": 0.4514334201812744, "expert": 0.26891231536865234 }
13,505
give me an api key
c1587d0a0d5a64966f9ed772da22b738
{ "intermediate": 0.607940137386322, "beginner": 0.18309442698955536, "expert": 0.20896540582180023 }
13,506
need to fix that mouse dragging by only when clicking and dragging, but no always rotating with mouse move on canvas. it suppose to store the current (rotated) position, and on the next mouse left click and drag it should update the position and so on… it still resets the position after reclicking and redragging.: const canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); function drawGrid() { const gridSize = 100; const gridSpacing = 10; // Find the normal vector of the orbital plane by taking the cross-product of the positions // of two planets that are not collinear with the Sun (in this case, Mercury and Earth) const v1 = { x: earthPos.x - sunPos.x, y: earthPos.y - sunPos.y, z: earthPos.z - sunPos.z }; const v2 = { x: mercuryPos.x - sunPos.x, y: mercuryPos.y - sunPos.y, z: mercuryPos.z - sunPos.z }; const normal = { x: v1.y * v2.z - v1.z * v2.y, y: v1.z * v2.x - v1.x * v2.z, z: v1.x * v2.y - v1.y * v2.x }; // Normalize the normal vector to get the direction of the orbital plane const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z); const planeDir = { x: normal.x / length, y: normal.y / length, z: normal.z / length }; // Calculate a point on the plane by projecting the Sun position onto it const planePos = { x: sunPos.x - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.x, y: sunPos.y - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.y, z: sunPos.z - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.z }; // Draw grid lines that lie on the orbital plane ctx.beginPath(); ctx.strokeStyle = 'rgba(255,255,255,0.2)'; for (let i = -gridSize; i <= gridSize; i += gridSpacing) { const p1 = { x: planePos.x + (i * planeDir.x), y: planePos.y + (i * planeDir.y), z: planePos.z + (i * planeDir.z) }; const p2 = { x: planePos.x + (i * planeDir.x) + (gridSize * planeDir.y), y: planePos.y + (i * planeDir.y) - (gridSize * planeDir.x), z: planePos.z + (i * planeDir.z) }; ctx.moveTo(projectTo2D(p1.x, p1.y, p1.z).x, projectTo2D(p1.x, p1.y, p1.z).y); ctx.lineTo(projectTo2D(p2.x, p2.y, p2.z).x, projectTo2D(p2.x, p2.y, p2.z).y); } ctx.stroke(); ctx.closePath(); } drawGrid(); // Draw Milky Way background ctx.globalCompositeOperation = "lighter"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = "lighter"; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ' + 0.1 + ')'; ctx.fill(); } // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, '#ffcc00'); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, '#ff6666'); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, '#ffa500'); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, '#6699ff'); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let lastRotation = { x: 0, y: 0 }; // store last rotation angles canvas.addEventListener('mousedown', function(event) { isDragging = true; }); canvas.addEventListener('mouseup', function(event) { isDragging = false; // store current rotation angle values when mouse button is released lastRotation.x = rotation.x; lastRotation.y = rotation.y; }); canvas.addEventListener('mousemove', function(event) { if (isDragging) { // add current and last rotation angle values to get new angles rotation.x = lastRotation.x + (event.clientY - canvas.height/2) / canvas.height * Math.PI; rotation.y = lastRotation.y + (event.clientX - canvas.width/2) / canvas.width * Math.PI; } }); } function updatePlanetPositions() { // Update Mercury's position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus's position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth's position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } // Start the animation loop setInterval(drawSolarSystem, 16);
5772602774d890c8a3f16f4f804fe025
{ "intermediate": 0.3555867075920105, "beginner": 0.5035718679428101, "expert": 0.14084148406982422 }
13,507
now preven bufferoverflow and output normal end of the code. Great to hear that the animation is working properly now! By using requestAnimationFrame instead of setInterval, we can optimize the animation loop to ensure that each frame is rendered at the optimal time, which helps to prevent buffer overflows and improve overall performance. If you have any other questions or concerns, feel free to ask! you now preven bufferoverflow and output normal end of the code. I apologize for any confusion - I’m not sure what you mean by “output normal end of the code.” Can you please provide more details or clarify what you mean? this “// Update planet positions for the next frame function update() { updatePlanetPositions(); drawSolarSystem(); requestAnimationFrame(update); } update();” now preven bufferoverflow and output normal end of the code. Ah, I understand now - I’m glad to hear that the changes to the code have prevented buffer overflows and resulted in normal program execution. By using requestAnimationFrame :::::::::::::: const canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); function drawGrid() { const gridSize = 100; const gridSpacing = 10; // Find the normal vector of the orbital plane by taking the cross-product of the positions // of two planets that are not collinear with the Sun (in this case, Mercury and Earth) const v1 = { x: earthPos.x - sunPos.x, y: earthPos.y - sunPos.y, z: earthPos.z - sunPos.z }; const v2 = { x: mercuryPos.x - sunPos.x, y: mercuryPos.y - sunPos.y, z: mercuryPos.z - sunPos.z }; const normal = { x: v1.y * v2.z - v1.z * v2.y, y: v1.z * v2.x - v1.x * v2.z, z: v1.x * v2.y - v1.y * v2.x }; // Normalize the normal vector to get the direction of the orbital plane const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z); const planeDir = { x: normal.x / length, y: normal.y / length, z: normal.z / length }; // Calculate a point on the plane by projecting the Sun position onto it const planePos = { x: sunPos.x - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.x, y: sunPos.y - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.y, z: sunPos.z - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.z }; // Draw grid lines that lie on the orbital plane ctx.beginPath(); ctx.strokeStyle = 'rgba(255,255,255,0.2)'; for (let i = -gridSize; i <= gridSize; i += gridSpacing) { const p1 = { x: planePos.x + (i * planeDir.x), y: planePos.y + (i * planeDir.y), z: planePos.z + (i * planeDir.z) }; const p2 = { x: planePos.x + (i * planeDir.x) + (gridSize * planeDir.y), y: planePos.y + (i * planeDir.y) - (gridSize * planeDir.x), z: planePos.z + (i * planeDir.z) }; ctx.moveTo(projectTo2D(p1.x, p1.y, p1.z).x, projectTo2D(p1.x, p1.y, p1.z).y); ctx.lineTo(projectTo2D(p2.x, p2.y, p2.z).x, projectTo2D(p2.x, p2.y, p2.z).y); } ctx.stroke(); ctx.closePath(); } drawGrid(); // Draw Milky Way background ctx.globalCompositeOperation = "lighter"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = "lighter"; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ' + 0.1 + ')'; ctx.fill(); } // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, '#ffcc00'); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, '#ff6666'); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, '#ffa500'); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, '#6699ff'); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let initialMousePos = { x: 0, y: 0 }; // store initial mouse position when dragging starts let currentRotation = { x: 0, y: 0 }; // store current rotation angles let prevRotation = { x: 0, y: 0 }; // store previous (last) rotation angles canvas.addEventListener('mousedown', function(event) { isDragging = true; initialMousePos.x = event.clientX; initialMousePos.y = event.clientY; prevRotation.x = currentRotation.x; // store previous rotation angles prevRotation.y = currentRotation.y; }); canvas.addEventListener('mouseup', function(event) { isDragging = false; }); canvas.addEventListener('mousemove', function(event) { if (isDragging) { // calculate new rotation angles based on difference between current mouse position and initial mouse position currentRotation.x = prevRotation.x + (event.clientY - initialMousePos.y) / canvas.height * Math.PI; currentRotation.y = prevRotation.y + (event.clientX - initialMousePos.x) / canvas.width * Math.PI; // update lastRotation whenever rotation angles are set to new values if (currentRotation.x !== prevRotation.x || currentRotation.y !== prevRotation.y) { prevRotation.x = currentRotation.x; prevRotation.y = currentRotation.y; } } }); } function updatePlanetPositions() { // Update Mercury's position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus's position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth's position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } // Start the animation loop setInterval(drawSolarSystem, 16);
53cb86fbde7389029a4c937f09d5cc73
{ "intermediate": 0.30072277784347534, "beginner": 0.4845968186855316, "expert": 0.21468038856983185 }
13,508
Hi there
b69a9126ba07f6b17198bdc251c332b6
{ "intermediate": 0.32728445529937744, "beginner": 0.24503648281097412, "expert": 0.42767903208732605 }
13,509
the 3d planar grid is bisected here on two planes. need to do this 3d planar grid a solid thing relative to all planets from the Sun position, which is the center.: const canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); function drawGrid() { const gridSize = 1000; const gridSpacing = 100; // Find the normal vector of the orbital plane by taking the cross-product of the positions // of two planets that are not collinear with the Sun (in this case, Mercury and Earth) const v1 = { x: earthPos.x - sunPos.x, y: earthPos.y - sunPos.y, z: earthPos.z - sunPos.z }; const v2 = { x: mercuryPos.x - sunPos.x, y: mercuryPos.y - sunPos.y, z: mercuryPos.z - sunPos.z }; const normal = { x: v1.y * v2.z - v1.z * v2.y, y: v1.z * v2.x - v1.x * v2.z, z: v1.x * v2.y - v1.y * v2.x }; // Normalize the normal vector to get the direction of the orbital plane const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z); const planeDir = { x: normal.x / length, y: normal.y / length, z: normal.z / length }; // Calculate a point on the plane by projecting the Sun position onto it const planePos = { x: sunPos.x - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.x, y: sunPos.y - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.y, z: sunPos.z - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.z }; // Draw grid lines that lie on the orbital plane ctx.beginPath(); ctx.strokeStyle = 'rgba(255,255,255,0.2)'; for (let i = -gridSize; i <= gridSize; i += gridSpacing) { const p1 = { x: planePos.x + (i * planeDir.x), y: planePos.y + (i * planeDir.y), z: planePos.z + (i * planeDir.z) }; const p2 = { x: planePos.x + (i * planeDir.x) + (gridSize * planeDir.y), y: planePos.y + (i * planeDir.y) - (gridSize * planeDir.x), z: planePos.z + (i * planeDir.z) }; ctx.moveTo(projectTo2D(p1.x, p1.y, p1.z).x, projectTo2D(p1.x, p1.y, p1.z).y); ctx.lineTo(projectTo2D(p2.x, p2.y, p2.z).x, projectTo2D(p2.x, p2.y, p2.z).y); } ctx.stroke(); ctx.closePath(); } drawGrid(); // Draw Milky Way background ctx.globalCompositeOperation = "lighter"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = "lighter"; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ' + 0.1 + ')'; ctx.fill(); } // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, '#ffcc00'); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, '#ff6666'); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, '#ffa500'); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, '#6699ff'); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let initialMousePos = { x: 0, y: 0 }; // store initial mouse position when dragging starts let currentRotation = { x: rotation.x, y: rotation.y }; // initialize current rotation angles to the current rotation let prevRotation = { x: 0, y: 0 }; // store previous (last) rotation angles canvas.addEventListener('mousedown', function (event) { isDragging = true; initialMousePos.x = event.clientX; initialMousePos.y = event.clientY; prevRotation.x = currentRotation.x; // store previous rotation angles prevRotation.y = currentRotation.y; }); canvas.addEventListener('mouseup', function (event) { isDragging = false; }); canvas.addEventListener('mousemove', function (event) { if (isDragging) { // calculate new rotation angles based on difference between current mouse position and initial mouse position currentRotation.x = prevRotation.x + (event.clientY - initialMousePos.y) / canvas.height * Math.PI; currentRotation.y = prevRotation.y + (event.clientX - initialMousePos.x) / canvas.width * Math.PI; // update lastRotation whenever rotation angles are set to new values if (currentRotation.x !== prevRotation.x || currentRotation.y !== prevRotation.y) { rotation.x = currentRotation.x; rotation.y = currentRotation.y; } } }); } function updatePlanetPositions() { // Update Mercury's position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus's position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth's position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } // Update planet positions for the next frame function update() { updatePlanetPositions(); drawSolarSystem(); requestAnimationFrame(update); } update();
117ae8e530b5a3fec61088c68e602785
{ "intermediate": 0.2619156539440155, "beginner": 0.5121026635169983, "expert": 0.22598162293434143 }
13,510
wpf datagrid中既有combox又有textbox的例子
ec4e452142c8fe3df5f322116ce163d3
{ "intermediate": 0.4458748996257782, "beginner": 0.23819482326507568, "expert": 0.3159303069114685 }
13,511
the 3d planar grid is bisected here on two planes. need to do this 3d planar grid a solid thing relative to all planets from the Sun position, which is the center. seems clean as explanation to me. whats wrong? how to explain that to you just what I just explained to you? you wish a reexplain? do you understand the term “axiometer”? planar grid attached to XYZ axiometer from the central position, which is not got bisected on two planes in 3d space.: const canvas = document.createElement(‘canvas’); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext(‘2d’); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); function drawGrid() { const gridSize = 1000; const gridSpacing = 100; // Find the normal vector of the orbital plane by taking the cross-product of the positions // of two planets that are not collinear with the Sun (in this case, Mercury and Earth) const v1 = { x: earthPos.x - sunPos.x, y: earthPos.y - sunPos.y, z: earthPos.z - sunPos.z }; const v2 = { x: mercuryPos.x - sunPos.x, y: mercuryPos.y - sunPos.y, z: mercuryPos.z - sunPos.z }; const normal = { x: v1.y * v2.z - v1.z * v2.y, y: v1.z * v2.x - v1.x * v2.z, z: v1.x * v2.y - v1.y * v2.x }; // Normalize the normal vector to get the direction of the orbital plane const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z); const planeDir = { x: normal.x / length, y: normal.y / length, z: normal.z / length }; // Calculate a point on the plane by projecting the Sun position onto it const planePos = { x: sunPos.x - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.x, y: sunPos.y - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.y, z: sunPos.z - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.z }; // Draw grid lines that lie on the orbital plane ctx.beginPath(); ctx.strokeStyle = ‘rgba(255,255,255,0.2)’; for (let i = -gridSize; i <= gridSize; i += gridSpacing) { const p1 = { x: planePos.x + (i * planeDir.x), y: planePos.y + (i * planeDir.y), z: planePos.z + (i * planeDir.z) }; const p2 = { x: planePos.x + (i * planeDir.x) + (gridSize * planeDir.y), y: planePos.y + (i * planeDir.y) - (gridSize * planeDir.x), z: planePos.z + (i * planeDir.z) }; ctx.moveTo(projectTo2D(p1.x, p1.y, p1.z).x, projectTo2D(p1.x, p1.y, p1.z).y); ctx.lineTo(projectTo2D(p2.x, p2.y, p2.z).x, projectTo2D(p2.x, p2.y, p2.z).y); } ctx.stroke(); ctx.closePath(); } drawGrid(); // Draw Milky Way background ctx.globalCompositeOperation = “lighter”; ctx.fillStyle = “black”; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = “lighter”; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ’ + 0.1 + ‘)’; ctx.fill(); } // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, ‘#ffcc00’); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, ‘#ff6666’); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, ‘#ffa500’); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, ‘#6699ff’); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let initialMousePos = { x: 0, y: 0 }; // store initial mouse position when dragging starts let currentRotation = { x: rotation.x, y: rotation.y }; // initialize current rotation angles to the current rotation let prevRotation = { x: 0, y: 0 }; // store previous (last) rotation angles canvas.addEventListener(‘mousedown’, function (event) { isDragging = true; initialMousePos.x = event.clientX; initialMousePos.y = event.clientY; prevRotation.x = currentRotation.x; // store previous rotation angles prevRotation.y = currentRotation.y; }); canvas.addEventListener(‘mouseup’, function (event) { isDragging = false; }); canvas.addEventListener(‘mousemove’, function (event) { if (isDragging) { // calculate new rotation angles based on difference between current mouse position and initial mouse position currentRotation.x = prevRotation.x + (event.clientY - initialMousePos.y) / canvas.height * Math.PI; currentRotation.y = prevRotation.y + (event.clientX - initialMousePos.x) / canvas.width * Math.PI; // update lastRotation whenever rotation angles are set to new values if (currentRotation.x !== prevRotation.x || currentRotation.y !== prevRotation.y) { rotation.x = currentRotation.x; rotation.y = currentRotation.y; } } }); } function updatePlanetPositions() { // Update Mercury’s position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus’s position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth’s position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } // Update planet positions for the next frame function update() { updatePlanetPositions(); drawSolarSystem(); requestAnimationFrame(update); } update();
8d7adab8c8404f6e6036ee72719cf36d
{ "intermediate": 0.3212480843067169, "beginner": 0.4927639663219452, "expert": 0.1859879493713379 }
13,512
need then one plane radial grid within X(horizontal) position through the same relative X(horizontal) rotation of planets around the Sun. If you want to use a radial grid in the X(horizontal) plane relative to the rotation of the planets around the Sun, you can modify the drawGrid function to calculate the position of each grid line based on its distance from the Sun’s position along the X(horizontal) axis. Here’s an example of how you could modify the function to achieve this: function drawGrid() { const gridSpacing = 100; // Find the minimum and maximum X(horizontal) positions of the planets const minPosX = Math.min(sunPos.x, mercuryPos.x, venusPos.x, earthPos.x); const maxPosX = Math.max(sunPos.x, mercuryPos.x, venusPos.x, earthPos.x); // Draw grid lines that lie on the X(horizontal) axis ctx.beginPath(); ctx.strokeStyle = “rgba(255, 255, 255, 0.2)”; for (let i = Math.floor(minPosX / gridSpacing) * gridSpacing; i <= maxPosX; i += gridSpacing) { const p1 = { x: i, y: -gridSize, z: 0 }; const p2 = { x: i, y: gridSize, z: 0 }; ctx.moveTo(projectTo2D(p1.x, p1.y, p1.z).x, projectTo2D(p1.x, p1.y, p1.z).y); ctx.lineTo(projectTo2D(p2.x, p2.y, p2.z).x, projectTo2D(p2.x, p2.y, p2.z).y); } ctx.stroke(); ctx.closePath(); } In this modified version, the minPosX and maxPosX variables are calculated as the minimum and maximum X(horizontal) positions of the planets. The for loop then iterates over the X(horizontal) positions within the range of minPosX and maxPosX, with a step size of gridSpacing. For each position, p1 and p2 are calculated with the X(horizontal) position as the x coordinate and gridSize as the and min/max grid size is irrelevant in that case? : const canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); function drawGrid() { const gridSize = 1000; const gridSpacing = 50; // Find the normal vector of the orbital plane by taking the cross-product of the positions // of two planets that are not collinear with the Sun (in this case, Mercury and Earth) const v1 = { x: earthPos.x - sunPos.x, y: earthPos.y - sunPos.y, z: earthPos.z - sunPos.z }; const v2 = { x: mercuryPos.x - sunPos.x, y: mercuryPos.y - sunPos.y, z: mercuryPos.z - sunPos.z }; const normal = { x: v1.y * v2.z - v1.z * v2.y, y: v1.z * v2.x - v1.x * v2.z, z: v1.x * v2.y - v1.y * v2.x }; // Normalize the normal vector to get the direction of the orbital plane const length = Math.sqrt(normal.x * normal.x + normal.y * normal.y + normal.z * normal.z); const planeDir = { x: normal.x / length, y: normal.y / length, z: normal.z / length }; // Calculate a point on the plane by projecting the Sun position onto it const planePos = { x: sunPos.x - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.x, y: sunPos.y - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.y, z: sunPos.z - (sunPos.x * planeDir.x + sunPos.y * planeDir.y + sunPos.z * planeDir.z) * planeDir.z }; // Draw grid lines that lie on the orbital plane ctx.beginPath(); ctx.strokeStyle = 'rgba(255,255,255,0.2)'; for (let i = -gridSize; i <= gridSize; i += gridSpacing) { const p1 = { x: planePos.x + (i * planeDir.x), y: planePos.y + (i * planeDir.y), z: planePos.z + (i * planeDir.z) }; const p2 = { x: planePos.x + (i * planeDir.x), y: planePos.y + (i * planeDir.y) + (gridSize * planeDir.z), z: planePos.z + (i * planeDir.z) - (gridSize * planeDir.y) }; ctx.moveTo(projectTo2D(p1.x, p1.y, p1.z).x, projectTo2D(p1.x, p1.y, p1.z).y); ctx.lineTo(projectTo2D(p2.x, p2.y, p2.z).x, projectTo2D(p2.x, p2.y, p2.z).y); } ctx.stroke(); ctx.closePath(); } drawGrid(); // Draw Milky Way background ctx.globalCompositeOperation = "lighter"; ctx.fillStyle = "black"; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = "lighter"; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ' + 0.1 + ')'; ctx.fill(); } // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, '#ffcc00'); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, '#ff6666'); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, '#ffa500'); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, '#6699ff'); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let initialMousePos = { x: 0, y: 0 }; // store initial mouse position when dragging starts let currentRotation = { x: rotation.x, y: rotation.y }; // initialize current rotation angles to the current rotation let prevRotation = { x: 0, y: 0 }; // store previous (last) rotation angles canvas.addEventListener('mousedown', function (event) { isDragging = true; initialMousePos.x = event.clientX; initialMousePos.y = event.clientY; prevRotation.x = currentRotation.x; // store previous rotation angles prevRotation.y = currentRotation.y; }); canvas.addEventListener('mouseup', function (event) { isDragging = false; }); canvas.addEventListener('mousemove', function (event) { if (isDragging) { // calculate new rotation angles based on difference between current mouse position and initial mouse position currentRotation.x = prevRotation.x + (event.clientY - initialMousePos.y) / canvas.height * Math.PI; currentRotation.y = prevRotation.y + (event.clientX - initialMousePos.x) / canvas.width * Math.PI; // update lastRotation whenever rotation angles are set to new values if (currentRotation.x !== prevRotation.x || currentRotation.y !== prevRotation.y) { rotation.x = currentRotation.x; rotation.y = currentRotation.y; } } }); } function updatePlanetPositions() { // Update Mercury's position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus's position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth's position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } // Update planet positions for the next frame function update() { updatePlanetPositions(); drawSolarSystem(); requestAnimationFrame(update); } update();
c03b58b8793654610b73249e7e33f7c6
{ "intermediate": 0.36788874864578247, "beginner": 0.45326730608940125, "expert": 0.1788439303636551 }
13,513
wpf datagrid中同一列既有combox又有textbox的完整例子
c56c4cc225f53189557da8637a2b6db4
{ "intermediate": 0.42467933893203735, "beginner": 0.24613815546035767, "expert": 0.32918256521224976 }
13,514
radial grid is invisible. need fix that.: const canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw Milky Way background ctx.globalCompositeOperation = 'lighter'; ctx.fillStyle = 'black'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = 'lighter'; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ' + 0.1 + ')'; ctx.fill(); } // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, '#ffcc00'); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, '#ff6666'); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, '#ffa500'); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, '#6699ff'); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let initialMousePos = { x: 0, y: 0 }; // store initial mouse position when dragging starts let currentRotation = { x: rotation.x, y: rotation.y }; // initialize current rotation angles to the current rotation let prevRotation = { x: 0, y: 0 }; // store previous (last) rotation angles canvas.addEventListener('mousedown', function (event) { isDragging = true; initialMousePos.x = event.clientX; initialMousePos.y = event.clientY; prevRotation.x = currentRotation.x; // store previous rotation angles prevRotation.y = currentRotation.y; }); canvas.addEventListener('mouseup', function (event) { isDragging = false; }); canvas.addEventListener('mousemove', function (event) { if (isDragging) { // calculate new rotation angles based on difference between current mouse position and initial mouse position currentRotation.x = prevRotation.x + (event.clientY - initialMousePos.y) / canvas.height * Math.PI; currentRotation.y = prevRotation.y + (event.clientX - initialMousePos.x) / canvas.width * Math.PI; // update lastRotation whenever rotation angles are set to new values if (currentRotation.x !== prevRotation.x || currentRotation.y !== prevRotation.y) { rotation.x = currentRotation.x; rotation.y = currentRotation.y; } } }); } function updatePlanetPositions() { // Update Mercury's position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus's position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth's position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } // Update planet positions for the next frame function update() { updatePlanetPositions(); drawSolarSystem(); requestAnimationFrame(update); } update();
8e2d71f76a26cd46188d52156fea1f43
{ "intermediate": 0.25497156381607056, "beginner": 0.48959943652153015, "expert": 0.25542891025543213 }
13,515
got an error when radial grid collapses in the center. need to fix that "IndexSizeError: CanvasRenderingContext2D.arc: Negative radius": const canvas = document.createElement('canvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; document.body.appendChild(canvas); const ctx = canvas.getContext('2d'); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 100, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw Milky Way background ctx.globalCompositeOperation = 'lighter'; ctx.fillStyle = 'black'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = 'lighter'; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ' + 0.1 + ')'; ctx.fill(); } // Draw radial grid drawRadialGrid(); // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, '#ffcc00'); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, '#ff6666'); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, '#ffa500'); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, '#6699ff'); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let initialMousePos = { x: 0, y: 0 }; // store initial mouse position when dragging starts let currentRotation = { x: rotation.x, y: rotation.y }; // initialize current rotation angles to the current rotation let prevRotation = { x: 0, y: 0 }; // store previous (last) rotation angles canvas.addEventListener('mousedown', function (event) { isDragging = true; initialMousePos.x = event.clientX; initialMousePos.y = event.clientY; prevRotation.x = currentRotation.x; // store previous rotation angles prevRotation.y = currentRotation.y; }); canvas.addEventListener('mouseup', function (event) { isDragging = false; }); canvas.addEventListener('mousemove', function (event) { if (isDragging) { // calculate new rotation angles based on difference between current mouse position and initial mouse position currentRotation.x = prevRotation.x + (event.clientY - initialMousePos.y) / canvas.height * Math.PI; currentRotation.y = prevRotation.y + (event.clientX - initialMousePos.x) / canvas.width * Math.PI; // update lastRotation whenever rotation angles are set to new values if (currentRotation.x !== prevRotation.x || currentRotation.y !== prevRotation.y) { rotation.x = currentRotation.x; rotation.y = currentRotation.y; } } }); } function drawRadialGrid() { const farthestPlanetRadius = earthPos.x; const center = { x: canvas.width / 2, y: canvas.height / 2 }; ctx.beginPath(); ctx.arc(center.x, center.y, farthestPlanetRadius, 0, Math.PI * 2); ctx.closePath(); ctx.setLineDash([5, 5]); ctx.strokeStyle = 'lightgray'; ctx.stroke(); ctx.setLineDash([]); for (let radius = 10; radius <= farthestPlanetRadius; radius += 10) { ctx.beginPath(); ctx.arc(center.x, center.y, radius, 0, Math.PI * 2); ctx.closePath(); ctx.strokeStyle = 'lightgray'; ctx.stroke(); } } function updatePlanetPositions() { // Update Mercury's position mercuryPos.x = 50 * Math.cos(Date.now() / 1000); mercuryPos.z = 50 * Math.sin(Date.now() / 1000); // Update Venus's position venusPos.x = 70 * Math.cos(Date.now() / 1500); venusPos.z = -10 * Math.sin(Date.now() / 1500); // Update Earth's position earthPos.x = 100 * Math.cos(Date.now() / 2000); earthPos.z = 100 * Math.sin(Date.now() / 2000); } function drawPlanet(x, y, size, color) { size = Math.max(size, 0.1); // ensure size is greater than zero ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } function update() { updatePlanetPositions(); drawSolarSystem(); requestAnimationFrame(update); } update();
29dbef983585a0bc167733c25236cff3
{ "intermediate": 0.28707391023635864, "beginner": 0.4732006788253784, "expert": 0.23972544074058533 }
13,516
phrases related to charity, soup
6c165a4ac637998e57e746d8fcc73ae5
{ "intermediate": 0.3751331567764282, "beginner": 0.3583667576313019, "expert": 0.2665000855922699 }
13,517
now try fix Based on the possible causes we identified earlier, here are some steps you can take to fix the “Negative radius” error: 1. Check the updatePlanetPositions() function to ensure that the x, y, and z properties for each planet are correctly updated. In the updatePlanetPositions function, the position of each planet is updated based on the current time. The x and z positions are calculated using the Math.cos() and Math.sin() functions with the current time as input. If a planet’s x, y, or z value is negative, it could cause the “Negative radius” error. To fix this issue, we can add an offset to the planet’s position or use Math.abs() to ensure the values are always positive. For example, we can modify the code for updating the Mercury position like this: mercuryPos.x = 50 * Math.cos(Date.now() / 1000) + sunPos.x; mercuryPos.z = 50 * Math.sin(Date.now() / 1000) + sunPos.z; Here, we’re adding the sunPos values to the mercuryPos values to ensure that the position is always positive. 2. Check all occurrences of the size property to ensure that it is never set to a value that is less than or equal to zero. In the drawPlanet() function, the size of each planet is passed to the arc() method to draw the planet. If the size is negative or zero, it could cause the “Negative radius” error. To fix this issue, we can ensure that the size value is always greater than zero by using the Math.max() method. Here’s how we could modify the drawPlanet() function: function drawPlanet(x, y, size, color) { size = Math.max(size, 0.1); // size should always be > 0 ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } Here, we’re using the Math.max() method to ensure that the size is always greater than zero. 3. Double-check that the window size is not zero or negative. We can check the width and height of the canvas to ensure that they are not zero or negative. If either of these values is zero or negative, it could cause the “Negative radius” error. To fix this issue, we can add a check to ensure that the width and height are always greater than zero. For example: const canvas = document.createElement(‘canvas’); canvas.width = Math.max(1, window.innerWidth); canvas.height = Math.max(1, window.innerHeight); Here, we’re using the Math.max() method to ensure that the width and height are always greater than zero. By taking these steps, you can address the possible causes of the “Negative radius” error and ensure that the code works as expected. the problem is in the earth, it collapses the whole radial grid to the center and: IndexSizeError: CanvasRenderingContext2D.arc: Negative radius If the radial grid collapses to the center and you receive the “Negative radius” error specifically for the Earth, it’s possible that the position of the Earth is being set such that the distance from the center of the solar system (the Sun) to the Earth is negative. To fix this, we can ensure that the Earth’s position is always at a greater distance than the other planets. We can use the farthestPlanetRadius variable to represent the farthest distance of any planet from the solar system center. We can set the Earth’s position to be a value greater than that. Here’s an example of how we could update the earthPos object: const earthPos = { x: 130, y: 0, z: 0, size: 5 }; Here, we’ve set the Earth’s x position to be 130, which is greater than any other planet’s x position. By ensuring that the Earth’s distance from the center is greater than the farthest bound of the radial grid, we can ensure that the “Negative radius” error does not occur. Additionally, we can add a check in the drawRadialGrid function to ensure that the radius of the circular grid is positive before drawing it. This can help prevent the error from occurring in the first place. Here’s an example of how we could modify the drawRadialGrid function to include this check: function drawRadialGrid() { const farthestPlanetRadius = earthPos.x; const center = { x: canvas.width / 2, y: canvas.height / 2 }; for (let radius = 10; radius <= farthestPlanetRadius; radius += 10) { if (radius <= 0) continue; // skip negative/zero radii ctx.beginPath(); ctx.arc(center.x, center.y, radius, 0, Math.PI * 2); ctx.closePath(); ctx.strokeStyle = ‘lightgray’; ctx.stroke(); } } Here, we’re adding a check to skip any radii that are negative or zero. This can help prevent the “Negative radius” error from occurring during drawing. By taking these steps, we can ensure that the position and size of the planets are correctly defined and prevent the “Negative radius” error from occurring. neahg. same error: IndexSizeError: CanvasRenderingContext2D.arc: Negative radius If the error is still occurring after making the changes we’ve suggested, there could be another issue causing the problem. Here are a few additional things to check: 1. Check the projectTo2D function for negative or zero values in the distance calculation. The projectTo2D function calculates the distance between the camera and the planet, which is used to scale the planet size. If this value is negative or zero, it could cause the “Negative radius” error. Check the distance calculation in the projectTo2D function to make sure that it is positive. 2. Check the updatePlanetPositions function for invalid position values. The updatePlanetPositions function updates the position of each planet based on time. If any of the position values for a planet become NaN (not a number) or undefined, it could cause the “Negative radius” error. Check this function to make sure that all position values are correctly defined. 3. Check for any other code that could be affecting the positions of the planets or the canvas size. If the previous steps don’t solve the issue, there could be another issue in the code not mentioned above. Check for any other code that could potentially affect the positions of the planets or the canvas size, as this could cause the “Negative radius” error. 4. Check browser console for any additional error messages. If the issue persists, it may help to check the browser console for any additional error messages that could provide more information on the issue. From there, you may be able to find a specific location in the code that is causing the problem. Check the code and find the issue, I don’t have time to bother with this nonsense. : “const canvas = document.createElement(‘canvas’); canvas.width = Math.max(1, window.innerWidth); canvas.height = Math.max(1, window.innerHeight); document.body.appendChild(canvas); const ctx = canvas.getContext(‘2d’); const sunPos = { x: 0, y: 0, z: 0, size: 20 }; const mercuryPos = { x: 50, y: 0, z: 0, size: 3 }; const venusPos = { x: 70, y: 0, z: -10, size: 4 }; const earthPos = { x: 130, y: 0, z: 0, size: 5 }; let rotation = { x: 0, y: 0, z: 0 }; function drawSolarSystem() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw Milky Way background ctx.globalCompositeOperation = ‘lighter’; ctx.fillStyle = ‘black’; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.globalCompositeOperation = ‘lighter’; for (let i = 0; i < 1000; i++) { const size = Math.random() * 2; const x = Math.random() * canvas.width; const y = Math.random() * canvas.height; ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = 'rgba(255, 255, 255, ’ + 0.1 + ‘)’; ctx.fill(); } // Draw radial grid drawRadialGrid(); // Draw the Sun const sunPos2D = projectTo2D(sunPos.x, sunPos.y, sunPos.z); drawPlanet(sunPos2D.x, sunPos2D.y, sunPos.size, ‘#ffcc00’); // Draw Mercury const mercPos2D = projectTo2D(mercuryPos.x - sunPos.x, mercuryPos.y - sunPos.y, mercuryPos.z - sunPos.z); drawPlanet(mercPos2D.x, mercPos2D.y, mercuryPos.size, ‘#ff6666’); // Draw Venus const venusPos2D = projectTo2D(venusPos.x - sunPos.x, venusPos.y - sunPos.y, venusPos.z - sunPos.z); drawPlanet(venusPos2D.x, venusPos2D.y, venusPos.size, ‘#ffa500’); // Draw Earth const earthPos2D = projectTo2D(earthPos.x - sunPos.x, earthPos.y - sunPos.y, earthPos.z - sunPos.z); drawPlanet(earthPos2D.x, earthPos2D.y, earthPos.size, ‘#6699ff’); // Update planet positions for the next frame updatePlanetPositions(); // Update rotation angles based on mouse position let isDragging = false; let initialMousePos = { x: 0, y: 0 }; // store initial mouse position when dragging starts let currentRotation = { x: rotation.x, y: rotation.y }; // initialize current rotation angles to the current rotation let prevRotation = { x: 0, y: 0 }; // store previous (last) rotation angles canvas.addEventListener(‘mousedown’, function (event) { isDragging = true; initialMousePos.x = event.clientX; initialMousePos.y = event.clientY; prevRotation.x = currentRotation.x; // store previous rotation angles prevRotation.y = currentRotation.y; }); canvas.addEventListener(‘mouseup’, function (event) { isDragging = false; }); canvas.addEventListener(‘mousemove’, function (event) { if (isDragging) { // calculate new rotation angles based on difference between current mouse position and initial mouse position currentRotation.x = prevRotation.x + (event.clientY - initialMousePos.y) / canvas.height * Math.PI; currentRotation.y = prevRotation.y + (event.clientX - initialMousePos.x) / canvas.width * Math.PI; // update lastRotation whenever rotation angles are set to new values if (currentRotation.x !== prevRotation.x || currentRotation.y !== prevRotation.y) { rotation.x = currentRotation.x; rotation.y = currentRotation.y; } } }); } function drawRadialGrid() { const farthestPlanetRadius = earthPos.x; const center = { x: canvas.width / 2, y: canvas.height / 2 }; ctx.beginPath(); ctx.arc(center.x, center.y, farthestPlanetRadius, 0, Math.PI * 2); ctx.closePath(); ctx.setLineDash([5, 5]); ctx.strokeStyle = ‘lightgray’; ctx.stroke(); ctx.setLineDash([]); for (let radius = 10; radius <= farthestPlanetRadius; radius += 10) { if (radius <= 0) continue; // skip negative/zero radii ctx.beginPath(); ctx.arc(center.x, center.y, radius, 0, Math.PI * 2); ctx.closePath(); ctx.strokeStyle = ‘lightgray’; ctx.stroke(); } } function updatePlanetPositions() { // Update Mercury’s position mercuryPos.x = 50 * Math.cos(Date.now() / 1000) + sunPos.x; mercuryPos.z = 50 * Math.sin(Date.now() / 1000) + sunPos.z; // Update Venus’s position venusPos.x = 70 * Math.cos(Date.now() / 1500) + sunPos.x; venusPos.z = -10 * Math.sin(Date.now() / 1500) + sunPos.z; // Update Earth’s position earthPos.x = 100 * Math.cos(Date.now() / 2000) + sunPos.x; earthPos.z = 100 * Math.sin(Date.now() / 2000) + sunPos.z; } function drawPlanet(x, y, size, color) { size = Math.max(size, 0.1); // size should always be > 0 ctx.beginPath(); ctx.arc(x, y, size, 0, Math.PI * 2); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function projectTo2D(x, y, z) { const fov = 90; // Field of view angle in degrees const distance = canvas.width / 2 / Math.tan(fov / 2 * Math.PI / 180); const cosX = Math.cos(rotation.x); const sinX = Math.sin(rotation.x); const cosY = Math.cos(rotation.y); const sinY = Math.sin(rotation.y); const cosZ = Math.cos(rotation.z); const sinZ = Math.sin(rotation.z); const x1 = x * cosY * cosZ - y * cosY * sinZ + z * sinY; const y1 = x * (sinX * sinY * cosZ + cosX * sinZ) + y * (sinX * sinY * sinZ - cosX * cosZ) - z * sinX * cosY; const z1 = x * (cosX * sinY * cosZ - sinX * sinZ) + y * (cosX * sinY * sinZ + sinX * cosZ) + z * cosX * cosY; const scale = distance / (distance + z1); const x2d = canvas.width / 2 + x1 * scale; const y2d = canvas.height / 2 - y1 * scale; return { x: x2d, y: y2d }; } function update() { updatePlanetPositions(); drawSolarSystem(); requestAnimationFrame(update); } update();” steps “you” can, not me! I don’t have time to bother with this nonsense. find and fix the code.: IndexSizeError: CanvasRenderingContext2D.arc: Negative radius
58ec688dfa08660e9c03631a39266fbd
{ "intermediate": 0.32313185930252075, "beginner": 0.4212578535079956, "expert": 0.2556103467941284 }
13,518
what is today's date?
2a13006cb044e36aabd12990ae614ed0
{ "intermediate": 0.40370941162109375, "beginner": 0.3754262328147888, "expert": 0.22086431086063385 }
13,519
write java script function which receives json structure, take it's "Nodes" value being array and for each array value return json single Name: "value"
b1585c84de678280a1c50ad25eef7fda
{ "intermediate": 0.5054084658622742, "beginner": 0.22722575068473816, "expert": 0.2673657238483429 }
13,520
cannot use dynamic_cast with -fno -rtti
f7d592afae45bd62559a7f80f7fdf110
{ "intermediate": 0.43955326080322266, "beginner": 0.2548486590385437, "expert": 0.30559810996055603 }
13,521
How do I convert E63085FB to 4536333038354642 in python code?
ec6d80324e0dee7605d9b129546c8f6f
{ "intermediate": 0.37414276599884033, "beginner": 0.24833889305591583, "expert": 0.37751826643943787 }
13,522
wpf datagrid中同一列既有combox又有textbox的完整例子
713cb092cc2911e0326176378b867507
{ "intermediate": 0.42467933893203735, "beginner": 0.24613815546035767, "expert": 0.32918256521224976 }
13,523
How do I convert ‘5jCF+w==’ to a decimal number in python?
4b12cb7dbce556d9d17851458080fd89
{ "intermediate": 0.45454704761505127, "beginner": 0.14311249554157257, "expert": 0.40234044194221497 }
13,524
QString str = "主机名称:" + QHostInfo::localHostName() + "\n";
71d6c2f9b1dab784f0413059740187d3
{ "intermediate": 0.3540111184120178, "beginner": 0.38338300585746765, "expert": 0.26260584592819214 }
13,525
You are a visualization expert, and will be provided with stock datasets in markdown table format decimated by triple backticks quotes
cdfb57119e025bf7028793facc5126e6
{ "intermediate": 0.33200883865356445, "beginner": 0.3919824957847595, "expert": 0.2760087251663208 }
13,526
hi again
bc60ba3df2b29500abdb89a04e9d9ed2
{ "intermediate": 0.3273336887359619, "beginner": 0.25858765840530396, "expert": 0.4140787124633789 }
13,527
generate a shell in c++
4145db7a3302efe453747e709354ecf4
{ "intermediate": 0.2657609283924103, "beginner": 0.45273900032043457, "expert": 0.28150010108947754 }
13,528
create a code in python beautifulsoup that scrapes a website with multiple pages by css selector
73d5608b8747aa1537387c49e3839d1a
{ "intermediate": 0.40831559896469116, "beginner": 0.24067622423171997, "expert": 0.35100820660591125 }
13,529
class EntryLine(bt.Indicator): lines = ('entryprice',) plotinfo = dict(subplot=False) plotlines = dict(entryprice=dict(ls='--', lw=2, color='red')) def __init__(self): self.addminperiod(self.data.size()) def prenext(self): self.lines.entryprice[0] = float('nan') def next(self): self.lines.entryprice[0] = float('nan') def set_entryprice(self, price): for index in range(-1, -self.data.size() - 1, -1): self.lines.entryprice[index] = price 在不改动此类的前提下,如何在实例化时把颜色改为蓝色
beda99ea0eae24e0f5628d37487d0fb3
{ "intermediate": 0.3458726704120636, "beginner": 0.47755807638168335, "expert": 0.17656920850276947 }
13,530
hi
8197bf91675b41d4d5a0aa3973db08b8
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
13,531
hi
72a613c10a2d3b9ff0db5657aff633f0
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
13,532
ImguiSettings::variables& ImSettings = ImguiSettings::getImguiSettings(); variables is a struct; if imSettings is <struct at NULL> how i can check does pointer pointing to null struct or not
8ec8a08e6108ec1e64feb37ba60ee15c
{ "intermediate": 0.5021867156028748, "beginner": 0.2960360646247864, "expert": 0.20177717506885529 }
13,533
@keyup.enter.native @keyup.enter 的区别
ef165ca8d20f4b95fdd9a5c04ff5df70
{ "intermediate": 0.34131377935409546, "beginner": 0.30502110719680786, "expert": 0.3536651134490967 }
13,534
How can I do a one-time page reload in react when page mounts?
a17a52488f4a4d0970b0eb73079cf302
{ "intermediate": 0.4891803562641144, "beginner": 0.15084055066108704, "expert": 0.35997912287712097 }
13,535
In selenium webdriver, How to automatically click on the OK button on a browser prompt
b67fa76cbcd921d0d429b2b266f6ab4d
{ "intermediate": 0.4329027533531189, "beginner": 0.21117863059043884, "expert": 0.3559185862541199 }
13,536
errorQuery failed: Cannot cast '2' to BOOLEAN in below query -SELECT Account.id as "AccountID", Account.name, Account.accountnumber, Account.batch, Account.additionalemailaddresses, contact.firstname, contact.lastname, contact.workemail, contact.personalemail, Invoice.amount, Invoice.balance, Invoice.duedate, Invoice.invoicedate, Invoice.invoicenumber, Invoice.status, Invoice.id, date_diff('day', Invoice.duedate, current_date) as "duedays", Subscription.id as "SubscriptionID", Subscription.name, Subscription.status FROM InvoiceItem IT JOIN Account on IT.accountid = Account.id JOIN Invoice on IT.invoiceid = Invoice.id JOIN contact on contact.id = Account.BillToId JOIN Subscription on IT.subscriptionid = Subscription.id WHERE (date_diff('day', Invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.a}}' AS BOOLEAN) AS BIGINT) OR date_diff('day', Invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.b}}' AS BOOLEAN) AS BIGINT) OR date_diff('day', Invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.c}}' AS BOOLEAN) AS BIGINT) OR date_diff('day', Invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.d}}' AS BOOLEAN) AS BIGINT) OR date_diff('day', Invoice.duedate, current_date) = CAST(CAST('{{Data.Workflow.e}}' AS BOOLEAN) AS BIGINT)) AND Invoice.balance>0 AND Invoice.status = 'Posted'
b4830fb9a6da1506a6a46d329f4800e4
{ "intermediate": 0.33747056126594543, "beginner": 0.38023611903190613, "expert": 0.28229331970214844 }
13,537
CONTEXTE : jN Npp Plugin jN (JavaScript for Notepad++) allows you to extend Notepad++ by using JavaScript. jN uses the built-in javascript engine of Microsoft Windows. This powerful engine allows to access a lot of ActiveX base services like Shell, WMI of operating system. Due to automate Notepad++ jN wraps the Notepad++ API into ActiveX interfaces accessible via global objects Editor and System. =-=-=-=-=-=-= J'ai actuellement le code suivant dans un fichier dans "Editor.cpp" ------------- ❨ #include "Editor.h" #include "common\System.h" #include "DockableDialog.h" #define SUBCLASSING TEXT("jN.Npp.Subclassing") const TCHAR* langs[] ={TEXT("TXT"), /* bla bla bla */ , TEXT("EXTERNAL")}; CEditor::~CEditor(void){ // Release Views for(int i=0; i<m_ViewsNumber; i++){ m_Views[i]->Release(); } // Release Scripting elements if (m_Listener){ delete m_Listener; m_Listener = NULL; } // Restore WndProc WNDPROC oldWndProc = (WNDPROC)GetProp(m_NppHandle, SUBCLASSING); SetWindowLongPtr(m_NppHandle, GWLP_WNDPROC, (LPARAM)oldWndProc); AcceleratorHook::getInstance()->remove(&m_Accelerators); } int CEditor::GetCurrentView(){ int currentEdit; NPPM(GETCURRENTSCINTILLA,0,&currentEdit); return currentEdit; } int CEditor::GetMenuItemPosition(HANDLE hMenu, TCHAR* text) { /* bla bla bla */ } // 1.) because NPP use lets IDs for menu items // and we can not get new IDs for our dynamic menu items. To solve // this problem we switch menu message handling from WM_COMMAND to WM_MENUCOMMAND // see 2.) and 3.) LRESULT CALLBACK CEditor::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam){ if (message == WM_MENUCOMMAND){ CMenuItem* mItem = CMenuItem::GetInstance((HMENU)lParam, wParam); if (mItem){ // here we have our menu item mItem->call(); }else{ // we have menu items from NPP // simulate WM_COMMAND, NPP handles his menu items self MENUITEMINFO mii; mii.cbSize = sizeof(mii); mii.fMask = MIIM_ID | MIIM_DATA; // 2.) WM_MENUCOMMAND + submenu handle and item position help us to // get MenuItemInfo without using of menu item ID BOOL res = GetMenuItemInfo((HMENU)lParam, wParam, TRUE, &mii); if (res) ::SendMessage(hwnd, WM_COMMAND,mii.wID,0); } } else if (message == WM_INITMENUPOPUP){ CMenu* menu = CMenu::GetInstance((HMENU)wParam); if (menu){ menu->oninitpopup(); return NULL; } } WNDPROC oldWndProc = (WNDPROC)GetProp(hwnd, SUBCLASSING); return CallWindowProc(oldWndProc, hwnd, message, wParam, lParam); } CEditor::CEditor(HWND nppHandle):CComDispatch(),m_Accelerators(nppHandle){ AcceleratorHook::getInstance()->add(&m_Accelerators); // 3.) set our wndproc to have WM_MENUCOMMAND instead WM_COMMAND // see 1.) and 2.) m_NppHandle = nppHandle; WNDPROC oldWndProc = (WNDPROC)SetWindowLongPtr(nppHandle, GWLP_WNDPROC, (LPARAM)CEditor::WndProc); SetProp(m_NppHandle, SUBCLASSING, oldWndProc); m_Listener = NULL; // get main menu handle m_mainMenu = (HMENU)NPPM(GETMENUHANDLE,1,0); if (!m_mainMenu){ VARIANT_BOOL hidden; get_menuHidden(&hidden); if (!hidden){ m_mainMenu = GetMenu(nppData._nppHandle); }else{ put_menuHidden(VARIANT_FALSE); m_mainMenu = GetMenu(nppData._nppHandle); put_menuHidden(VARIANT_TRUE); } } // create views for(int i=0; i<m_ViewsNumber; i++){ m_Views[i] = new CEditorView(i+1); } MENUINFO mi; memset(&mi, 0, sizeof(mi)); mi.cbSize = sizeof(mi); mi.fMask = MIM_STYLE | MIM_APPLYTOSUBMENUS; mi.dwStyle = MNS_NOTIFYBYPOS; BOOL res = SetMenuInfo( m_mainMenu, &mi); } void CEditor::getViewAndPosFrom(SCNotification* eventArgs, int* view, int* pos){ /* bla bla bla */ } void CEditor::doOnMessage(SCNotification* eventArgs){ int r = 0; // provide messages to current view int view = GetCurrentView(); // can be -1 what is not valid if (view >= 0 && view < m_ViewsNumber){ m_Views[view]->DoMessage(eventArgs); } if (m_Listener==NULL) return ; TCHAR* method1 = NULL; TCHAR* method2 = NULL; switch(eventArgs->nmhdr.code){ case SCN_MODIFYATTEMPTRO: method2 = TEXT("MODIFYATTEMPTRO"); break; case NPPN_SHUTDOWN:{ method1 = TEXT("SHUTDOWN"); break; } case NPPN_FILECLOSED:{ method1 = TEXT("FILECLOSED"); break; } case NPPN_READONLYCHANGED:{ method2 = TEXT("READONLYCHANGED"); break; } case NPPN_LANGCHANGED:{ method2 = TEXT("LANGCHANGED"); break; } } if (method1){ CallListener(method1); }else if(method2){ int view, pos; getViewAndPosFrom(eventArgs, &view, &pos); CallListener(method2, view, pos); } } void CEditor::CallListener(TCHAR* method, int view, int file){ if (m_Listener == NULL) return; if (view >= 0 && view < m_ViewsNumber){ VARIANT var[2]; var[0].vt = VT_DISPATCH; var[0].pdispVal = m_Views[view]; var[1].vt = VT_INT; var[1].intVal = file; m_Listener->callMethod(method, var, 2); }else{ m_Listener->callMethod(method); } } HRESULT STDMETHODCALLTYPE CEditor::get_firstView( IView **result){ *result = m_Views[0]; (*result)->AddRef(); return S_OK; } /* HRESULT STDMETHODCALLTYPE CEditor::get_currentView( IView **result){ // bla bla bla HRESULT STDMETHODCALLTYPE CEditor::get_secondView( IView **result){ // bla bla bla HRESULT STDMETHODCALLTYPE CEditor::alert( BSTR *value){ // bla bla bla HRESULT STDMETHODCALLTYPE CEditor::saveAll( void){ // bla bla bla HRESULT STDMETHODCALLTYPE CEditor::get_statusBarHidden / put_statusBarHidden / open / runMenuCmd / setListener / etc. */ HRESULT STDMETHODCALLTYPE CEditor::createDockable(IDispatch* cfg, IDialog** result){ if (!cfg) return S_OK; Dialog* d = new DockableDialog(MyActiveSite::getInstance()->WrapScriptObj(cfg), nppData._nppHandle); d->Init(); d->AddRef(); *result = d; NPPM(MODELESSDIALOG,MODELESSDIALOGADD,d->hwnd()); return S_OK; } HRESULT STDMETHODCALLTYPE CEditor::get_handle(int *result){ *result = (int)m_NppHandle; return S_OK; } ------------- Ce code dans "Editor.cpp" me permet de créer un dock (fenêtre ancrée) avec des options de manipulations. Dock que je vais créer plus tard dans le plugin compilé .dll avec un script javascript WSH contenant : var options = { name: 'blablabla', docking: 'bottom', onclose: function () { /* bla bla bla */} }; var dock = Editor.createDockable(options); } ------------- Et j'ai également le code suivant dans le fichier "DockableDialog.cpp" : ------------- #include <set> #include "..\common\Statics.h" #include "..\npp\PluginDefinition.h" #include "..\npp\dockingResource.h" #include "DockableDialog.h" // Because of wrong architecture of Notepad++ it is necessary // to destroy Strings given to docable dialog manager after destoroying // of it self. Hence we don't destroy them at all. To reduce memory consumption // create cache. class StringCache{ struct StringCmp{ bool operator()(TCHAR* left, TCHAR* right) const { int result = StrCmp(left, right); return result < 0; } }; typedef std::set<TCHAR*, StringCmp> Cache; Cache m_Cache; public: TCHAR* GetCached(TCHAR* value){ Cache::iterator findIt = m_Cache.find(value); if (findIt != m_Cache.end()) return *findIt; // create a copy of value and put it to the cache TCHAR* copy = StrDup(value); // uses LocalAlloc m_Cache.insert(copy); return copy; } ~StringCache(){ for(Cache::iterator it = m_Cache.begin(); it!=m_Cache.end(); ++it){ LocalFree(*it); } } }; StringCache CachedStrings; #define CHARS_IN(a) sizeof(a)/sizeof(TCHAR) #define DD_AFTER_REGISTERASDOCKABLE WM_USER+1 // sent to control after DockableDialog::DockableDialog(ScriptObj* cfg, HWND parent): Dialog(cfg, parent),CComDispatch(),m_Modul(TEXT("jN.dll,")), m_Name(TEXT("jN")) { StringCchCopy(m_Info,CHARS_IN(m_Info), TEXT("")); VARIANT* textValue = m_Cfg->getProperty(TEXT("name"), VT_BSTR); if (textValue != NULL){ m_Name.Set(textValue->bstrVal); m_Modul.Append(textValue->bstrVal); VariantClear(textValue); delete textValue; } } void DockableDialog::BeforeCreate(){ m_Style = WS_CHILD; m_ExStyle = WS_EX_CLIENTEDGE; } void DockableDialog::AfterCreate(){ // Nothing to do override standard behavior RegisterAsDockable(); } int DockableDialog::GetDockingFlags(){ int result = DWS_DF_CONT_BOTTOM; VARIANT* dockingText = m_Cfg->getProperty(TEXT("docking"), VT_BSTR); if (dockingText){ if (0 == StrCmp(TEXT("top"),dockingText->bstrVal)) result = DWS_DF_CONT_TOP; else if (0 == StrCmp(TEXT("right"),dockingText->bstrVal)) result = DWS_DF_CONT_RIGHT; else if (0 == StrCmp(TEXT("bottom"),dockingText->bstrVal)) result = DWS_DF_CONT_BOTTOM; else if (0 == StrCmp(TEXT("left"),dockingText->bstrVal)) result = DWS_DF_CONT_LEFT; else if (0 == StrCmp(TEXT("floating"),dockingText->bstrVal)) result = DWS_DF_FLOATING; VariantClear(dockingText); delete dockingText; } return result; } void DockableDialog::RegisterAsDockable(){ int mask = GetDockingFlags() | DWS_ICONTAB | DWS_ADDINFO; memset(&m_Data,0,sizeof(m_Data)); m_Data.dlgID = 0; //Nr of menu item to assign (!= _cmdID, beware) m_Data.hIconTab = (HICON) LoadImage(Statics::instance().hInstance, MAKEINTRESOURCE(1),IMAGE_ICON, 0,0,LR_CREATEDIBSECTION|LR_SHARED|LR_LOADTRANSPARENT); //icon to use m_Data.pszAddInfo = m_Info; //Titlebar info pointer m_Data.pszModuleName = CachedStrings.GetCached( m_Modul ); //name of the dll m_Data.pszName = CachedStrings.GetCached( m_Name ); //Name for titlebar m_Data.uMask = mask; //Flags to use (see docking.h) m_Data.hClient = m_Hwnd; //HWND Handle of window this dock belongs to m_Data.iPrevCont = -1; SendMessage(nppData._nppHandle, NPPM_DMMREGASDCKDLG, 0, (LPARAM)&m_Data); //Register it // update ui SendMessage(m_Hwnd, DD_AFTER_REGISTERASDOCKABLE, 0, 0); } void DockableDialog::ResetUI(){ //Registering as dockable breaks window styles, reset them LONG_PTR oldStyle = ::GetWindowLongPtr(m_Hwnd, GWL_STYLE); ::SetWindowLongPtr(m_Hwnd, GWL_STYLE, m_Style | oldStyle); ::SetWindowLongPtr(m_Hwnd, GWL_EXSTYLE, m_ExStyle); SetWindowPos(m_Hwnd, 0, 0, 0, 0, 0, SWP_FRAMECHANGED| SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER); UpdateWindow(m_Hwnd); } void DockableDialog::UpdateInfo(){ m_Data.pszAddInfo = m_Info; m_Data.pszName = m_Name; SendMessage(m_Hwnd, NPPM_DMMUPDATEDISPINFO, 0, (LPARAM)m_Hwnd); } LRESULT CALLBACK DockableDialog::MessageProc(UINT message, WPARAM wParam, LPARAM lParam){ switch(message){ case DD_AFTER_REGISTERASDOCKABLE:{ ResetUI(); return TRUE; } case WM_NOTIFY:{ NMHDR nmh = (NMHDR) *((NMHDR*)lParam); if (nmh.hwndFrom == nppData._nppHandle) { if (nmh.code == DMN_CLOSE) { ::PostMessage(m_Hwnd, WM_CLOSE, 0, 0); return TRUE; } else if ((nmh.code & DMN_DOCK) == DMN_DOCK && (nmh.code & DMN_FLOAT) != DMN_FLOAT) {// only if just docked PostMessage(m_Hwnd, DD_AFTER_REGISTERASDOCKABLE,0,0); return TRUE; } } break; } case WM_ERASEBKGND: return TRUE; //case WM_SETFOCUS: { // //Why restore focus here? This window should never be able to get focus in the first place // HWND hPrev = (HWND)wParam; // if (hPrev != NULL) // ::SetFocus(hPrev); // break; //} } return Dialog::MessageProc(message, wParam, lParam); } HRESULT STDMETHODCALLTYPE DockableDialog::get_visible( VARIANT_BOOL *result){ if (isCreated()) *result = IsWindowVisible(m_Hwnd); return S_OK; } HRESULT STDMETHODCALLTYPE DockableDialog::put_visible( VARIANT_BOOL value){ ::SendMessage(nppData._nppHandle, value ? NPPM_DMMSHOW : NPPM_DMMHIDE, 0, (LPARAM)m_Hwnd); return S_OK; } ------------- Ce code de "DockableDialog.cpp" permet des manipulations sur le dock qu'on a créé. Par exemple je peux modifier sa visibilité avec dock.visible = true/false. ------------- Ma question : qu'est ce que je dois modifier ou ajoûter dans les fichiers "Editor.cpp" et "DockableDialog.cpp" pour pouvoir cloturer / détruire / remove un dock que j'ai ajouté avec var dock = Editor.createDockable(options); ? J'aimerais une option genre Editor.closeDock(x); pour clôturer un dock créer avec x = Editor.createDockable(options); Et bien-sûr Editor.closeDock(y); cloturerait y = Editor.createDockable(options); sans toucher un dock x ou z…
a998d1e2261fad8579782a8d2b2a7a7b
{ "intermediate": 0.367033451795578, "beginner": 0.371426522731781, "expert": 0.261540025472641 }
13,538
test
19bc978287375669b78b4bfcaee5f3ec
{ "intermediate": 0.3229040801525116, "beginner": 0.34353747963905334, "expert": 0.33355844020843506 }
13,539
you are a python developper and you work with ChatGPT and stable diffusion to create image
13ab9a2c0674fc457e2832f382f5749c
{ "intermediate": 0.44329187273979187, "beginner": 0.1555447280406952, "expert": 0.4011634588241577 }
13,540
from sklearn.feature_extraction.text import CountVectorizer from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import make_pipeline vec = CountVectorizer() clf = LogisticRegression() pipe = make_pipeline(vec, clf) pipe.fit(X_train.verbatim, y_train.status) I want to excute this with lightgbm
361a688f5a7e2c86ebe39b66e4de88bd
{ "intermediate": 0.2749471664428711, "beginner": 0.2200637310743332, "expert": 0.5049890279769897 }
13,541
can you make a print board design connecting just the chip of an arduino with the components needed for controlling a stepper
003aa43b86e8e2d1a5a7fdd81a28d4d3
{ "intermediate": 0.3180701732635498, "beginner": 0.20897775888442993, "expert": 0.47295206785202026 }
13,542
can you write the arduino code for connecting two arduino devices using MQTT via matter protocol?
5fd0c27f23e4632f7c0ca7fcad9950dd
{ "intermediate": 0.5991696119308472, "beginner": 0.16289958357810974, "expert": 0.2379308044910431 }
13,543
Make a java script for a micro bit that creates a minature maze game where hitting the A button moves the character left and B button moving the character right and the top left trigger being forward and pressing A+B restarting the maze
6343185c38f2e8c64e2a987cc2bc6c31
{ "intermediate": 0.40085306763648987, "beginner": 0.20195737481117249, "expert": 0.39718958735466003 }
13,544
write java script function which receives json structure with 4 keys, take it’s key “Nodes” value. for each value in resulting array return function “apiData” with arguments http://${consts.host}/api/fetchENodeBv2, and json Name: node one by one
d650deada6d321809f80a9ff7b1f1684
{ "intermediate": 0.5872862339019775, "beginner": 0.18554170429706573, "expert": 0.2271721214056015 }
13,545
hi
e0aafdd0e0ab9a95ce273542ecd7d7c5
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
13,546
pip install pycaret ==2.0
1de095766ee514b679dba34a6e6786e8
{ "intermediate": 0.43147799372673035, "beginner": 0.21136850118637085, "expert": 0.3571535050868988 }
13,547
Convert ‘4921599493627’ to ‘E63085FB’ using java
3c913153aa8b1e7b3c64dbd22f51c1ed
{ "intermediate": 0.319088876247406, "beginner": 0.3012416660785675, "expert": 0.3796694278717041 }
13,548
Hello
7a585eee6f17f727d927270c9b4e8b45
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
13,549
Can you refactor the followin code in c++
9c4cd286a640d03659cfc1ec32fe726a
{ "intermediate": 0.24851293861865997, "beginner": 0.4628118872642517, "expert": 0.28867512941360474 }
13,550
which version of pycaret includes nlp
b59eb1fcf40cff0c94a7ccec58a4e902
{ "intermediate": 0.2730390131473541, "beginner": 0.2630811929702759, "expert": 0.46387988328933716 }
13,551
can you improve the following code in c#?
581855c6a3cffceb9a687b4851355c49
{ "intermediate": 0.41722971200942993, "beginner": 0.4061697721481323, "expert": 0.17660044133663177 }
13,552
discord.js и firebird
eb8673ca95d2913141a5d0a4b57b4f8b
{ "intermediate": 0.47343650460243225, "beginner": 0.2566598057746887, "expert": 0.26990368962287903 }
13,553
I used this signal_generator code: def signal_generator(df): # Calculate EMA and MA lines df['EMA5'] = df['Close'].ewm(span=5, adjust=False).mean() df['EMA10'] = df['Close'].ewm(span=10, adjust=False).mean() df['EMA20'] = df['Close'].ewm(span=20, adjust=False).mean() df['EMA50'] = df['Close'].ewm(span=50, adjust=False).mean() df['EMA100'] = df['Close'].ewm(span=100, adjust=False).mean() df['EMA200'] = df['Close'].ewm(span=200, adjust=False).mean() df['MA10'] = df['Close'].rolling(window=10).mean() df['MA20'] = df['Close'].rolling(window=20).mean() df['MA50'] = df['Close'].rolling(window=50).mean() df['MA100'] = df['Close'].rolling(window=100).mean() open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2] # Calculate the last candlestick last_candle = df.iloc[-1] current_price = df.Close.iloc[-1] ema_analysis = '' candle_analysis = '' # EMA crossover - buy signal if df.EMA10.iloc[-1] > df.EMA50.iloc[-1] and current_price > last_candle[['EMA10', 'EMA50']].iloc[-1].min(): ema_analysis = 'buy' # EMA crossover - sell signal elif df.EMA10.iloc[-1] < df.EMA50.iloc[-1] and current_price < last_candle[['EMA10', 'EMA50']].iloc[-1].max(): ema_analysis = 'sell' # EMA crossover - buy signal if df.EMA20.iloc[-1] > df.EMA200.iloc[-1] and current_price > last_candle[['EMA20', 'EMA200']].iloc[-1].min(): ema_analysis = 'buy' # EMA crossover - sell signal elif df.EMA20.iloc[-1] < df.EMA200.iloc[-1] and current_price < last_candle[['EMA20', 'EMA200']].iloc[-1].max(): ema_analysis = 'sell' # Check for bullish trends elif current_price > last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].max(): ema_analysis = 'buy' # Check for bearish trends elif current_price < last_candle[['EMA5', 'EMA20', 'EMA50', 'EMA100', 'EMA200']].iloc[-1].min(): ema_analysis = 'sell' # Check for bullish candlestick pattern if (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): candle_analysis = 'buy' # Check for bearish candlestick pattern elif (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): candle_analysis = 'sell' # Check if both analyses are the same if ema_analysis == candle_analysis == ema_analysis != '': return ema_analysis # If no signal is found, return an empty string return '' df = get_klines(symbol, '1m', 44640) but it giveing me wrong signals , is it code is right ? If no give me right code please
0480b6fccf5608cbbdb735abc6fa76c8
{ "intermediate": 0.29511523246765137, "beginner": 0.3723642826080322, "expert": 0.332520455121994 }
13,554
build a kubernetes CustomResourceDefinition, which describe structure of objects like this: apiService: crds.idom.project/v1alpha1 kind: Mediaplan metadata: name: somename spec: # scheduling schedule: "0 1-10/3,12-22/2 */1 * *" # channel metadata channel: name: "" guid: "" id: 0 link: "https://..." messagingSettings: # oneof: topic or files # generation topics topics: # topic - code: pbot-4 # topic code weight: 1 # generation weight # or choose files from s3 files: - uri: s3://bucket/file.xlsx # agent settings agentSettings: # count totalCount: 20 # credential comparison credentials: - key: key-1 value: value-1 # mimicry comparison mimicry: - key: key-1 value: value-1 # common mediaplan settings commonSettings: # output pkg generation coefficient # define, how many packages will be generated for one incoming message generationCoefficient: 0.2 # each five message in channel should make one package, because 1/0.2 = 5 # total packages count totalMessageCount: 2000 # 0 - without limit (only if estimatedLeadTime not null) # estimated time for different messaging options estimatedLeadTime: 2h # disable mimicry options (for agents) disableMimicryOptions: false # use image for packages didImageUsedForGeneration: false
cda3f39d8d3cda9f3951979c40d76e7f
{ "intermediate": 0.5392865538597107, "beginner": 0.24833358824253082, "expert": 0.2123798280954361 }
13,555
Error in ggplot() : could not find function "ggplot"
229fcfa7e3cffd9f531d70bf140ea7ba
{ "intermediate": 0.4229854643344879, "beginner": 0.3368293344974518, "expert": 0.2401852160692215 }
13,556
this is a Mediaplan resource # CustomResourceDefinition apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: mediaplans.crd.idom.project spec: group: crds.idom.project scope: Namespaced names: plural: mediaplans singular: mediaplan kind: Mediaplan shortNames: - mediap versions: - name: v1alpha1 served: true storage: true schema: openAPIV3Schema: type: object properties: apiVersion: type: string description: ‘A unique version for the Kubernetes API’ kind: type: string description: ‘Type of resource’ metadata: type: object properties: name: type: string description: ‘Name of the resource’ required: - name spec: type: object properties: # scheduling schedule: type: string description: ‘Scheduling format for the mediaplan’ # channel metadata channel: type: object properties: name: type: string description: ‘Name of the channel’ guid: type: string description: ‘GUID of the channel’ id: type: integer description: ‘ID of the channel’ link: type: string description: ‘Link for the channel’ messagingSettings: type: object properties: # oneof: topic or files # generation topics topics: type: array items: type: object properties: code: type: string description: ‘Code for the topic’ weight: type: integer description: ‘Generation weight for the topic’ default: 1 # or choose files from s3 files: type: array items: type: object properties: uri: type: string description: ‘URI for the file’ # agent settings agentSettings: type: object properties: # count totalCount: type: integer description: ‘Total number of agents for the mediaplan’ default: 10 # credential comparison credentials: type: array items: type: object properties: key: type: string description: ‘Key for the credential’ value: type: string description: ‘Value for the credential’ # mimicry comparison mimicry: type: array items: type: object properties: key: type: string description: ‘Key for the mimicry option’ value: type: string description: ‘Value for the mimicry option’ # common mediaplan settings commonSettings: type: object properties: # output pkg generation coefficient # define, how many packages will be generated for one incoming message generationCoefficient: type: number description: ‘Output package generation coefficient’ default: # total packages count totalMessageCount: type: integer description: ‘Total number of messages for the mediaplan’ # estimated time for different messaging options estimatedLeadTime: type: string description: ‘Estimated lead time for the mediaplan’ # disable mimicry options (for agents) disableMimicryOptions: type: boolean description: ‘Disables mimicry options for agents’ # use image for packages didImageUsedForGeneration: type: boolean description: ‘Indicates if an image was used for package generation’
aae9f5ca8130775dda5f2c5ae4cae6f4
{ "intermediate": 0.32817235589027405, "beginner": 0.40554726123809814, "expert": 0.2662803828716278 }
13,557
write a python code to get sum of two numbers
022c87ecbc3d48453b75834ac925c953
{ "intermediate": 0.334235817193985, "beginner": 0.2648848593235016, "expert": 0.4008793830871582 }
13,558
there is Mediaplan CustomDefinitionResource: # CustomResourceDefinition apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: mediaplans.crd.idom.project spec: group: crds.idom.project scope: Namespaced names: plural: mediaplans singular: mediaplan kind: Mediaplan shortNames: - mediap versions: - name: v1alpha1 served: true storage: true schema: openAPIV3Schema: type: object properties: apiVersion: type: string description: ‘A unique version for the Kubernetes API’ kind: type: string description: ‘Type of resource’ metadata: type: object properties: name: type: string description: ‘Name of the resource’ required: - name spec: type: object properties: # scheduling schedule: type: string description: ‘Scheduling format for the mediaplan’ # channel metadata channel: type: object properties: name: type: string description: ‘Name of the channel’ guid: type: string description: ‘GUID of the channel’ id: type: integer description: ‘ID of the channel’ link: type: string description: ‘Link for the channel’ messagingSettings: type: object properties: # oneof: topic or files # generation topics topics: type: array items: type: object properties: code: type: string description: ‘Code for the topic’ weight: type: integer description: ‘Generation weight for the topic’ default: 1 # or choose files from s3 files: type: array items: type: object properties: uri: type: string description: ‘URI for the file’ # agent settings agentSettings: type: object properties: # count totalCount: type: integer description: ‘Total number of agents for the mediaplan’ default: 10 # credential comparison credentials: type: array items: type: object properties: key: type: string description: ‘Key for the credential’ value: type: string description: ‘Value for the credential’ # mimicry comparison mimicry: type: array items: type: object properties: key: type: string description: ‘Key for the mimicry option’ value: type: string description: ‘Value for the mimicry option’ # common mediaplan settings commonSettings: type: object properties: # output pkg generation coefficient # define, how many packages will be generated for one incoming message generationCoefficient: type: number description: ‘Output package generation coefficient’ default: # total packages count totalMessageCount: type: integer description: ‘Total number of messages for the mediaplan’ # estimated time for different messaging options estimatedLeadTime: type: string description: ‘Estimated lead time for the mediaplan’ # disable mimicry options (for agents) disableMimicryOptions: type: boolean description: ‘Disables mimicry options for agents’ # use image for packages didImageUsedForGeneration: type: boolean description: ‘Indicates if an image was used for package generation’ build a python application, which serve create/update/delete operations of Mediaplan CustomResourceDefinition through kopf lib. On create, if Mediaplan contain not null "spec.schedule" option, then application create an CronJob, else "Job". On update, do the same, if "spec.schedule" is not null, else first delete an existing job (with waiting), then create again. On delete, delete already existing CronJob or Job
8706c36921d7cf19f7a6d095d684e4ef
{ "intermediate": 0.36629629135131836, "beginner": 0.3955528140068054, "expert": 0.23815090954303741 }
13,559
there is Mediaplan CustomDefinitionResource: # CustomResourceDefinition apiVersion: apiextensions.k8s.io/v1 kind: CustomResourceDefinition metadata: name: mediaplans.crd.idom.project spec: group: crds.idom.project scope: Namespaced names: plural: mediaplans singular: mediaplan kind: Mediaplan shortNames: - mediap versions: - name: v1alpha1 served: true storage: true schema: openAPIV3Schema: type: object properties: apiVersion: type: string description: ‘A unique version for the Kubernetes API’ kind: type: string description: ‘Type of resource’ metadata: type: object properties: name: type: string description: ‘Name of the resource’ required: - name spec: type: object properties: # scheduling schedule: type: string description: ‘Scheduling format for the mediaplan’ # channel metadata channel: type: object properties: name: type: string description: ‘Name of the channel’ guid: type: string description: ‘GUID of the channel’ id: type: integer description: ‘ID of the channel’ link: type: string description: ‘Link for the channel’ messagingSettings: type: object properties: # oneof: topic or files # generation topics topics: type: array items: type: object properties: code: type: string description: ‘Code for the topic’ weight: type: integer description: ‘Generation weight for the topic’ default: 1 # or choose files from s3 files: type: array items: type: object properties: uri: type: string description: ‘URI for the file’ # agent settings agentSettings: type: object properties: # count totalCount: type: integer description: ‘Total number of agents for the mediaplan’ default: 10 # credential comparison credentials: type: array items: type: object properties: key: type: string description: ‘Key for the credential’ value: type: string description: ‘Value for the credential’ # mimicry comparison mimicry: type: array items: type: object properties: key: type: string description: ‘Key for the mimicry option’ value: type: string description: ‘Value for the mimicry option’ # common mediaplan settings commonSettings: type: object properties: # output pkg generation coefficient # define, how many packages will be generated for one incoming message generationCoefficient: type: number description: ‘Output package generation coefficient’ default: # total packages count totalMessageCount: type: integer description: ‘Total number of messages for the mediaplan’ # estimated time for different messaging options estimatedLeadTime: type: string description: ‘Estimated lead time for the mediaplan’ # disable mimicry options (for agents) disableMimicryOptions: type: boolean description: ‘Disables mimicry options for agents’ # use image for packages didImageUsedForGeneration: type: boolean description: ‘Indicates if an image was used for package generation’ please show a sample of a python application, which serve create/update/delete operations of Mediaplan CustomResourceDefinition through kopf lib. On create, if Mediaplan contain not null "spec.schedule" option, then application create an CronJob, else "Job". On update, do the same, if "spec.schedule" is not null, else first delete an existing job (with waiting), then create again. On delete, delete already existing CronJob or Job
5d74615cb358170886e41d0b2d71ab2d
{ "intermediate": 0.36629629135131836, "beginner": 0.3955528140068054, "expert": 0.23815090954303741 }
13,560
How to implement the extract method of c++17 unorder_map in c++13
9decc873760e5972415fb20143d5d408
{ "intermediate": 0.3636561930179596, "beginner": 0.15194043517112732, "expert": 0.4844033718109131 }
13,561
how to check isLoggedIn for nuxt app with jwt
48a41ce0c28c2f70c845423845b2290e
{ "intermediate": 0.600812554359436, "beginner": 0.11618411540985107, "expert": 0.2830033302307129 }