row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
1,606
import “…/styles/globals.css” import type {AppProps} from “next/app” import Layout from “…/components/Layout/Layout”; import {AuthProvider} from “…/components/AuthProvider/AuthProvider”; import {SnackbarProvider} from “notistack”; import {AdapterDayjs} from “@mui/x-date-pickers/AdapterDayjs”; import {LocalizationProvider} from “@mui/x-date-pickers”; import {ruRU} from “@mui/material/locale”; import {SnackbarUtilsConfigurator} from “…/components/SnackbarUtilsConfigurator/SnackbarUtilsConfigurator”; import {CartProvider} from “…/components/CartProvider/CartProvider”; import dayjs from “dayjs”; import ru from “dayjs/locale/ru”; import utc from “dayjs/plugin/utc”; import Head from “next/head”; import “…/public/css/input-mono.woff2.css”; import “…/public/css/mont.woff2.css”; import {NotificationProvider} from “…/components/NotificationProvider/NotificationProvider”; import {IntlProvider} from “react-intl”; import ReferralProvider from “…/components/ReferralProvider/ReferralProvider”; import DemoCodeProvider from “…/components/DemoCodeProvider/DemoCodeProvider”; import Script from “next/script”; import {useRouter} from “next/router”; import {ApiKeyProvider} from “…/providers/ApiKeyProvider/ApiKeyProvider”; import {useEffect} from “react”; dayjs.locale(ru); dayjs.extend(utc); function MyApp({ Component, pageProps }: AppProps) { const router = useRouter(); const { isFallback, events } = useRouter(); const googleTranslateElementInit = () => { // @ts-ignore new window.google.translate.TranslateElement({ pageLanguage: “ru” }, “google_translate_element”); } useEffect(() => { const id = “google-translate-script”; const addScript = () => { const s = document.createElement(“script”); s.setAttribute(“src”, “//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit”); s.setAttribute(“id”, id); const q = document.getElementById(id); if (!q) { document.body.appendChild(s); // @ts-ignore window.googleTranslateElementInit = googleTranslateElementInit; } } const removeScript = () => { const q = document.getElementById(id); if (q) q.remove(); const w = document.getElementById(“google_translate_element”); if (w) w.innerHTML = “”; } isFallback || addScript(); events.on(“routeChangeStart”, removeScript); events.on(“routeChangeComplete”, addScript); document.cookie = “=googtrans”; return () => { events.off(“routeChangeStart”, removeScript); events.off(“routeChangeComplete”, addScript); }; }, []); const routeParts = router.route.split(“/”); const hideAmoCrm = Array.isArray(routeParts) && routeParts.length >= 3 && “cabinet” === routeParts[1] && [“trading”, “algo-trading”].includes(routeParts[2]); return ( <> <Head> <meta name=“viewport” content=“minimum-scale=1, initial-scale=1, width=device-width” key=“viewport-meta” /> { hideAmoCrm ? (<style id=“hide-amo-button”>.amo-button {{display: none !important}}</style>) : (<></>) } </Head> <IntlProvider locale=“ru”> <AuthProvider> <ApiKeyProvider> <CartProvider> <NotificationProvider> <ReferralProvider> <DemoCodeProvider> <LocalizationProvider adapterLocale={ruRU} dateAdapter={AdapterDayjs}> <SnackbarProvider className=“snackbar-styles” anchorOrigin={{ vertical: “bottom”, horizontal: “right” }} maxSnack={4}> <SnackbarUtilsConfigurator /> <Layout> <Component {…pageProps} /> </Layout> </SnackbarProvider> </LocalizationProvider> </DemoCodeProvider> </ReferralProvider> </NotificationProvider> </CartProvider> </ApiKeyProvider> </AuthProvider> </IntlProvider> <Script id=“amo-chat” strategy=“afterInteractive” dangerouslySetInnerHTML={{ __html: <br/> (function(a,m,o,c,r,m){a[m]={id:"364435",hash:"beafc0edab607fa31241320b7af9026be29401f0634595fbf1660c11303896cf",locale:"ru",inline:false,setMeta:function(p){this.params=(this.params||[]).concat([p])}};a[o]=a[o]||function(){(a[o].q=a[o].q||[]).push(arguments)};var d=a.document,s=d.createElement("script");s.async=true;s.id=m+"_script";s.src="https://gso.amocrm.ru/js/button.js?1669713416";d.head&&d.head.appendChild(s)}(window,0,"amoSocialButton",0,0,"amo_social_button"));<br/> }} /> </> ) } export default MyApp import {LayoutProps} from “./Layout.props”; import {createTheme, ThemeProvider} from “@mui/material/styles”; import { AppBar, Badge, Box, Button, Container, CssBaseline, Dialog, DialogContent, DialogTitle, Divider, Drawer, Grid, Icon, IconButton, Link as MLink, List, ListItem, ListItemAvatar, ListItemButton, ListItemIcon, ListItemText, Popover, responsiveFontSizes, Stack, Toolbar, Typography, } from “@mui/material”; import {useRouter} from “next/router”; import {RouteGuard} from “…/RouteGuard/RouteGuard”; import {useAuthContext} from “…/AuthProvider/AuthProvider”; import {Fragment, MouseEventHandler, useEffect, useState} from “react”; import MenuIcon from “@mui/icons-material/Menu”; import { CameraAlt, NotificationsRounded, ShoppingBagRounded, Telegram, Twitter, YouTube } from “@mui/icons-material”; import {sideMenu} from “./_side.menu”; import {mobileMenu} from “./_mobile.menu”; import Link from “next/link”; import {CicapLogo, DiscordIcon, DzenIcon, FakeFacebookIcon, VkIcon} from “…/icons”; import {useCartContext} from “…/CartProvider/CartProvider”; import Script from “next/script”; import BinanceLive from “…/BinanceLive/BinanceLive”; import Image from “next/image”; import {useNotificationContext} from “…/NotificationProvider/NotificationProvider”; import dayjs from “dayjs”; import {Notification, notificationSetAsRead, notificationUnreadCollection} from “…/…/actions/notification”; import NotificationBlock from “…/NotificationBlock/NotificationBlock”; import NotificationAvatar from “…/NotificationAvatar/NotificationAvatar”; import {useDemoCodeContext} from “…/DemoCodeProvider/DemoCodeProvider”; import {checkDemoCode} from “…/…/actions/demo-code”; import PermIdentityIcon from “@mui/icons-material/PermIdentity”; import LanguageSwitcher from “…/LanguageSwitcher/LanguageSwitcher”; declare module “@mui/material/Alert” { interface AlertPropsColorOverrides { black: true; white: true; green: true; discordInvite: true; } } declare module “@mui/material/Button” { interface ButtonPropsColorOverrides { black: true; white: true; green: true; discordInvite: true; } } declare module “@mui/material/Radio” { interface RadioPropsColorOverrides { black: true; white: true; green: true; } } declare module “@mui/material/Checkbox” { interface CheckboxPropsColorOverrides { black: true; white: true; green: true; } } declare module “@mui/material/styles” { interface Palette { black: Palette[“primary”]; white: Palette[“primary”]; green: Palette[“primary”]; discordInvite: Palette[“primary”]; } interface PaletteOptions { black: PaletteOptions[“primary”]; white: PaletteOptions[“primary”]; green: PaletteOptions[“primary”]; discordInvite: PaletteOptions[“primary”]; } interface PaletteColor { black?: string; white?: string; green?: string; discordInvite?: string; } } let theme = createTheme({ palette: { primary: { main: “#cb0000”, }, secondary: { main: “#0d0d0d”, }, success: { main: “#30C23A”, contrastText: “#ffffff”, }, error: { main: “#D73A3A”, contrastText: “#ffffff”, }, white: { main: “#ffffff”, contrastText: “#000000” }, black: { main: “#000000”, contrastText: “#ffffff”, }, green: { main: “#286d43”, contrastText: “#ffffff”, }, discordInvite: { main: “#e74c3c”, contrastText: “#ffffff”, } }, components: { MuiButton: { styleOverrides: { root: { textTransform: “none”, fontSize: “1rem”, paddingTop: “.5rem”, paddingBottom: “.5rem”, paddingLeft: “2.75rem”, paddingRight: “2.75rem”, borderRadius: “.5rem”, boxShadow: “none” } } }, MuiTypography: { styleOverrides: { gutterBottom: { marginBottom: “1rem”, } } }, MuiChip: { styleOverrides: { root: { borderRadius: “3px”, height: “18px”, }, label: { paddingLeft: “4px”, paddingRight: “4px” } } } }, typography: { fontSize: 14, fontFamily: [ “Mont”, “-apple-system”, “BlinkMacSystemFont”, “Segoe UI”, “Roboto”, “Helvetica Neue”, “Arial”, “sans-serif”, “Apple Color Emoji”, “Segoe UI Emoji”, “Segoe UI Symbol”, ].join(“,”), body1: { lineHeight: 1.618, }, h1: { fontWeight: 800, fontSize: “3.7rem”, lineHeight: 1.25, letterSpacing: “0em”, }, h2: { fontSize: “3rem”, fontWeight: 800, lineHeight: 1.25, letterSpacing: “0em”, }, h3: { fontSize: “2.2rem”, fontWeight: 800, lineHeight: 1.25, }, h4: { fontSize: “1.8rem”, fontWeight: 800, lineHeight: 1.25, letterSpacing: “0em”, }, h5: { fontWeight: 800, lineHeight: 1.25, }, h6: { fontWeight: 800, lineHeight: 1.25, letterSpacing: “0em”, }, }, shape: { borderRadius: 6, }, }); theme = responsiveFontSizes(theme, { breakpoints: [“xs”, “md”], variants: [“h1”, “h2”, “h3”, “h4”, “h5”, “h6”, “subtitle1”, “subtitle2”, “body1”, “body2”, “button”, “caption”, “overline”], }); export default function Layout({children}: LayoutProps) { const [drawerWidth, setDrawerWidth] = useState(60); const [mobileMenuOpen, setMobileMenuOpen] = useState(false); const [asUser, setAsUser] = useState<string|null>(null); const router = useRouter(); const {user, bearer} = useAuthContext(); const {carts} = useCartContext(); const {notifications, setNotifications} = useNotificationContext(); const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null); const [open, setOpen] = useState(false); const [notification, setNotification] = useState<Notification|undefined>(undefined); const [notificationsCount, setNotificationsCount] = useState(0); const [showSocial, setShowSocial] = useState(false); const [showed, setShowed] = useState(false); const [showDemoModal, setShowDemoModal] = useState(false); const {demoCode, setDemoCode} = useDemoCodeContext(); const handleClick: MouseEventHandler = event => { // @ts-ignore setAnchorEl(event.currentTarget); setOpen(true); }; const handleClose = () => { setAnchorEl(null); setOpen(false); }; const hideNotification = (notification_id: number) => { notificationSetAsRead(notification_id, bearer) .then(data => { if (!data) return; notificationUnreadCollection(bearer) .then(data => { if (!data) return; setNotifications(data.data); }) }) } useEffect(() => { if (“undefined” !== typeof window) { setAsUser(window.localStorage.getItem(“as_user”)); } }) useEffect(() => { if (notificationsCount < notifications.length && notifications.length > 0) { setNotification(notifications[0]); } setNotificationsCount(notifications.length); }, [notifications]); useEffect(() => { document.addEventListener(“mouseout”, (event) => { // @ts-ignore const from = event.relatedTarget || event?.toElement; if ( (!from || from.nodeName == “HTML”) && event.clientY <= 100 ) { setShowSocial(true); } }); }, []); useEffect(() => { if (undefined === demoCode || “undefined” === demoCode) { return; } checkDemoCode(demoCode) .then(data => { if (!data) { return; } if (!data.result) { window.localStorage.removeItem(“demo_code”); return; } setShowDemoModal(true); }); }, [demoCode]); interface ActiveLink { href: string children: string } const ActiveLink = ({ href, children }: ActiveLink) => { const router = useRouter(); const isActive = router.pathname === href; return ( <Typography sx={{ fontWeight: isActive ? 400 : 200 }}> <Link href={href}>{children}</Link> </Typography> ); } return ( <ThemeProvider theme={theme}> { null !== asUser ? ( <Box sx={{ position: “fixed”, left: 0, right: 0, bottom: 0, height: “40px”, lineHeight: “40px”, zIndex: 10, textAlign: “center”, backgroundColor: theme => theme.palette.primary.main, color: theme => theme.palette.primary.contrastText, }} > Вы авторизованы под пользователем с ID {asUser} <button style={{ marginLeft: “7px”, cursor: “pointer”, border: “1px solid #fff”, color: “#f00”, background: “white”, fontWeight: “bold”, borderRadius: “3px”}} onClick={() => { window.localStorage.removeItem(“as_user”); window.location.reload() }} > Выйти </button> </Box> ) : (<></>) } <RouteGuard> { “/_error” === router.pathname ? children : ( <> <Box sx={{ display: “flex”, background: “#f5f5f5” }}> <CssBaseline /> <AppBar position=“fixed” sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }} color=“secondary”> <Toolbar> <Box sx={{display: “flex”,width: “100%”,}}> <Grid sx={{display: “flex”, width: “100%”, flexDirection: “row”, alignItems: “center”, ml: {xs: 0, md: -2}, pr: {xs: 0, md: 3}}}> <Stack direction=“row” className=“header-menu” alignItems=“center” justifyContent=“center” spacing={2} sx={{display: {xs: “none”, md: “flex”}, whiteSpace: “nowrap”}}> <Typography width={130} > <Link href=“/”> <MLink href=“/” className=“logo”> <Icon component={CicapLogo} sx={{transform: {xs: “none”, md: “translateX(-12px)”}}} /> </MLink> </Link> </Typography> <ActiveLink href=“/shop”>Курсы</ActiveLink> <ActiveLink href=“/about”>О компании</ActiveLink> <ActiveLink href=“/subscriptions”>Подписки</ActiveLink> <ActiveLink href=“/soft”>Софт</ActiveLink> <ActiveLink href=“/faq”>FAQ</ActiveLink> <ActiveLink href=“/contacts”>Контакты</ActiveLink> { user && ( <Badge badgeContent={user.courses_count} color=“primary” sx={{display: {xs: “none”, md: “none”, lg: “block”}}}> <Typography sx={{fontWeight: 200}}> <Link href=“/cabinet/learning”>Мои курсы</Link> </Typography> </Badge> ) } </Stack> <Box sx={{ flex: 3, display: “flex”, alignItems: “center”, justifyContent: “end” }}> <LanguageSwitcher /> </Box> <Box sx={{ flex: 1, display: “flex”, alignItems: “center”, justifyContent: “end” }}> { bearer && notifications.length > 0 && ( <> <Button sx={{px: “0”, color: “#fff”}} onClick={handleClick}> <Badge badgeContent={notifications.length > 9 ? “9+” : notifications.length} color=“primary” > <NotificationsRounded /> </Badge> </Button> <Popover open={open} anchorEl={anchorEl} onClose={handleClose} anchorOrigin={{ vertical: “bottom”, horizontal: “right”, }} sx={{transform: {md: “translateX(-250px)”}}} > <List sx={{width: “500px”, maxWidth: “80vw”}}> { notifications.map((notification, index) => ( <Fragment key={index}> <ListItem> <ListItemAvatar> <NotificationAvatar notification={notification} /> </ListItemAvatar> <ListItemText primary={notification.title} primaryTypographyProps={{ sx: {lineHeight: 1.3, cursor: “pointer”}, onClick: () => { setNotification(notification) } }} secondary={<> <Typography fontSize=“small” sx={{opacity: .75}}>{dayjs(notification.created_at).format(“DD MMM, HH:mm”)}</Typography> { !notification.read && ( <Button variant=“outlined” sx={{px: “12px !important”, mt: 1, py: “0 !important”, fontSize: “12px”}} onClick={e => { e.preventDefault(); hideNotification(notification.id); }} > Скрыть </Button> ) } </>} /> </ListItem> <Divider /> </Fragment> )) } <ListItem> <Link href={“/cabinet/notifications”}> <MLink href={“/cabinet/notifications”} onClick={() => {setOpen(false)}}>Все уведомления</MLink> </Link> </ListItem> </List> </Popover> </> ) } { bearer && notifications.length === 0 ? ( <Link href={“/cabinet/notifications”}> <IconButton size=“large” color=“inherit” href=“/cabinet/notifications” sx={{p: 0, mr: 2}} > <NotificationsRounded /> </IconButton> </Link> ) : (<></>) } <Link href={“/cart”}> { carts.length > 0 ? ( <Badge badgeContent={carts.length} color=“primary”> <IconButton size=“large” color=“inherit” href=“/cart” sx={{p: 0, mr: 2}} > <ShoppingBagRounded /> </IconButton> </Badge> ) : ( <IconButton size=“large” color=“inherit” href=“/cart” sx={{p: 0}} > <ShoppingBagRounded /> </IconButton> ) } </Link> { bearer ? ( <Link href=“/cabinet”> <IconButton size=“large” color=“inherit” sx={{p: 0}} > <PermIdentityIcon sx={{mr: 0.5}} /> <Typography fontWeight={300} pt={0.5} > {user?.name} </Typography> </IconButton> </Link> ) : ( <> <Link href=“/login”> <Button size=“small” href=“/login” sx={{whiteSpace: “nowrap”, borderRadius: “6px”, lineHeight: 1.25, px: 2, height: “38px”, mr: 1, ml: 2, display: {xs: “none”, md: “block”}}} // @ts-ignore color=“white” variant=“outlined” >Вход</Button> </Link> <Link href=“/registration”> <Button size=“small” sx={{whiteSpace: “nowrap”, borderRadius: “6px”, lineHeight: 1.25, px: 2, height: “38px”, display: {xs: “none”, md: “block”}}} // @ts-ignore color=“white” variant=“contained” >Регистрация</Button> </Link> </> ) } <IconButton size=“large” edge=“start” color=“inherit” aria-label=“menu” sx={{ ml: 2, mr: -7, mt: 1, display: {xs: “none”, md: “block”} }} onClick={() => { setDrawerWidth(drawerWidth === 60 ? 250 : 60) }} > <MenuIcon /> </IconButton> <IconButton size=“large” edge=“start” color=“inherit” aria-label=“menu” sx={{ ml: 2, display: {xs: “block”, md: “none”}, lineHeight: 0 }} onClick={() => setMobileMenuOpen(!mobileMenuOpen)} > <MenuIcon /> </IconButton> </Box> </Grid> </Box> </Toolbar> </AppBar> <Drawer anchor=“right” variant=“permanent” sx={{ display: {xs: “none”, md: “flex”}, width: drawerWidth, flexShrink: 2, [& .MuiDrawer-paper]: { width: drawerWidth, boxSizing: “border-box”, background: “#0d0d0d”, color: “#fff”, }, }} onMouseOver={() => { setDrawerWidth(250) }} onMouseOut={() => { setDrawerWidth(60) }} > <Toolbar sx={{backgroundColor: “#0d0d0d”, color: “#fff”}} /> <Stack direction=“column” alignItems=“flex-start” justifyContent=“space-between” sx={{ overflowX: “hidden”, backgroundColor: “#0d0d0d”, color: “#fff”, height: “100vh”, }} > { sideMenu.map((group, index) => ( <Box key={index}> <List> { group.map(({ label, url, icon }) => ( <ListItem key={label} disablePadding sx={{ width: “300px”, }}> <Link href={url}> <ListItemButton sx={{[“&:hover”]: {background: “rgba(255,255,255,.2)”, lineHeight: “36px”}}}> <ListItemIcon sx={{color: “#fff”, minWidth: drawerWidth > 60 ? “48px” : “32px”, height: “36px”, pt: .5}}> <Icon component={icon} /> </ListItemIcon> { drawerWidth > 60 ? ( <ListItemText primary={label} /> ) : (<></>) } </ListItemButton> </Link> </ListItem> )) } </List> <Divider /> </Box> )) } </Stack> </Drawer> </Box> </RouteGuard> </ThemeProvider> ); } import React, { useState } from 'react'; import { Box, IconButton, Menu, MenuItem } from '@mui/material'; import TranslateIcon from '@mui/icons-material/Translate'; interface Language { value: string; label: string; } const LanguageSwitcher: React.FC = () => { const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null); // const [selectedLanguage, setSelectedLanguage] = useState<Language | null>(null); const languages: Language[] = [ { value: '', label: 'Русский' }, { value: '/ru/en', label: 'English' }, ]; const handleLanguageClick = (event: React.MouseEvent<HTMLButtonElement>) => { setAnchorEl(event.currentTarget); }; const handleLanguageClose = (language: Language) => { setAnchorEl(null); // setSelectedLanguage(language); setCookie(language.value); }; const setCookie = (cookieValue: string) => { document.cookie = `googtrans=${cookieValue}`; window.location.reload(); }; return ( <div> <Box> <div> <IconButton onClick={handleLanguageClick} size="large" color="inherit"> <TranslateIcon /> </IconButton> </div> <div> <Menu anchorEl={anchorEl} open={Boolean(anchorEl)} onClose={() => setAnchorEl(null)} > <div> {languages.map((language) => ( <MenuItem key={language.value} onClick={() => handleLanguageClose(language)}> <div> {language.label} </div> </MenuItem> ))} </div> </Menu> </div> </Box> </div> ); }; export default LanguageSwitcher; NotFoundError : Failed to execute ‘insertBefore’ on ‘Node’: The node before which the new node is to be inserted is not a child of this node. переключаюсь в компоненте, когда использую гугл переводчик в проекте и показывает такую ошибку. как исправить? next react. Когда язык на сайте переводен на английский с помощью встроенного переводчика, то показывает такую ошибку
b29a985e8edcc796b7266451649086c4
{ "intermediate": 0.3082906901836395, "beginner": 0.4757518172264099, "expert": 0.2159574329853058 }
1,607
I'm working on a fivem script I am currently using this code to check if both teams have players in them is there a more optimal way? local teams = {['A']= 0, ['B']= 0} Citizen.CreateThread(function() while true do print(teams['A']) print(teams['B']) if teams['A'] ~= 0 and teams['B'] ~= 0 then print('triggered') end Citizen.Wait(1500) end end)
594063668e3ff13d6f8ab922d52c0a24
{ "intermediate": 0.27787473797798157, "beginner": 0.5520448684692383, "expert": 0.17008037865161896 }
1,608
Write c# code for Autocad 2022 .net api to get a block name from user then for each block create a new layout and set viewport zoom in layout to that block extends.
bfbee2d4471efa0a0e007d93a60b7451
{ "intermediate": 0.616516649723053, "beginner": 0.13325235247612, "expert": 0.25023096799850464 }
1,609
Hi there. Yesterday, I came to you with a following prompt: "Hello! Let’s have a TS training session. I know the basics of JS and I am trying to learn TS as well. If you were to write a program in TS, I would try to read and understand it, and if I am ever stuck, I 'd just ask you about what I don’t understand. Can you do that? If you do, please write a somewhat short (10-40 lines long) program for me to analyze. If you can, please make this program neither too basic or too complicated. Also, please do not explain what does it do and don’t add any comments. We’re pretending that this is a someone else’s code that we need to analyze, and someone else’s code would most likely not have comments and we’d have no one to explain the code to us. We did this exercise a few times already, so please do not use the following examples: Simple Person class with Greetings method; Simple shopping cart program" (end of prompt quote) You were able to come up with a program, but we didn't have enough time to break it down. Can I copy the program you suggested here so I can analyze it in this new chat?
e41afd818dcf9fb107b600fc15317f94
{ "intermediate": 0.340166300535202, "beginner": 0.44976696372032166, "expert": 0.21006673574447632 }
1,610
we are going to develop a project with dataset of satellite images before and after an earthquake. We are going to use Yolov8. The thing is I can not understand how we are going to use both the before image and after image of disaster. Yolov8 is object detection model so it gets trained on only a type of image. I really don't know what we are going to predict given this dataset ? May be the probability of destruction ? If so how are we going to train Yolov8 models. Can you help me, please give detailed explanation I am really confused.
08af3b261d0285e2e9f99fd238ef4687
{ "intermediate": 0.2624177038669586, "beginner": 0.09386909008026123, "expert": 0.6437132358551025 }
1,611
explain "static void" in CSharp
4f5befe50438639208f6e88ec9380d4d
{ "intermediate": 0.2883082926273346, "beginner": 0.4805986285209656, "expert": 0.23109298944473267 }
1,612
I’m working on a rust program. Why should the id variable have an option, such as : pub id: option<AccountId> Here is the code: use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Account { pub id: option<AccountId>, pub email: String, pub password: String, } #[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct AccountId(pub i32); #[derive(Deserialize, Serialize, Debug, Clone)] pub struct NewAccount { pub email: String, pub password: String, }
bd401f0f3a9be4f0e2918a372d97fc24
{ "intermediate": 0.42930638790130615, "beginner": 0.4865124821662903, "expert": 0.08418115973472595 }
1,613
J'ai ce script en roblox lua pour envoyer des sorts mais j'ai un problème de précision si le joueur clique au sol à 100m de sa position par exemple le sort s'arrêteras sur le sol 50m avant quel est le moyen pour adapter la vitesse à laquelle le projectile descende de façon à attérir au sol à 100m local function spellProjectile(player,spellId,mouseHit) local startTime = os.clock() local spellSettings = spellsModule.List[spellId] local character = player.Character local humanoidRootPart = character.HumanoidRootPart if eventsCooldown:CheckRemote(player,tostring(spellSettings.Name)) == false then return end local wandTool for i,v in pairs (player.Character:GetChildren()) do if v:GetAttribute("Wand") then wandTool = v end end local colorSequence = ColorSequence.new{ ColorSequenceKeypoint.new(0, spellSettings.Color), ColorSequenceKeypoint.new(1, spellSettings.Color) } local mousePosition = Vector3.new(mouseHit.Position.X,mouseHit.Position.Y,mouseHit.Position.Z) wandTool.Handle.Cast:Play() wandTool.Handle.Attachment.spellFire.Color = colorSequence wandTool.Handle.Attachment.Sparks.Color = colorSequence wandTool.Handle.Attachment.spellFire.Enabled = true wandTool.Handle.Attachment.Sparks.Enabled = true delay(.1,function() wandTool.Handle.Attachment.spellFire.Enabled = false wandTool.Handle.Attachment.Sparks.Enabled = false end) --shakeEvent:FireClient(player,) shakeEvent:FireClient(player,"Bump",0.1) --wandTool.Handle.Attachment.spellFire:Emit(800) local spellProjectile = game.ReplicatedStorage.ProjectileNew:Clone() --projectile:Clone() spellProjectile.Player.Value = player.Name spellProjectile.Parent = workspace.Projectiles spellProjectile.CFrame = CFrame.new(character.HumanoidRootPart.Position,mousePosition) spellProjectile.projectileLoop.Volume = 0.3 spellProjectile.spellGlow.Range = 0 spellProjectile.Trail1.Color = colorSequence spellProjectile.Trail2.Color = colorSequence spellProjectile.Trail3.Color = colorSequence spellProjectile.Main.Color = colorSequence spellProjectile.Particles.Hit.Color = colorSequence spellProjectile.Particles.Sparks.Color = colorSequence spellProjectile.Particles.Spiral.Color = colorSequence spellProjectile.Particles.Water.Color = colorSequence spellProjectile.Particles.Wind.Color = colorSequence local bodyGyro = Instance.new("BodyGyro", player.Character.HumanoidRootPart) bodyGyro.Name = "FaceTargetBodyGyro" bodyGyro.MaxTorque = Vector3.new(10000, 10000, 10000) bodyGyro.P = 8000 bodyGyro.D = 0 local targetDirection = (mousePosition - humanoidRootPart.Position).unit local targetCFrame = CFrame.lookAt(humanoidRootPart.Position, humanoidRootPart.Position + targetDirection) bodyGyro.CFrame = targetCFrame game:GetService("Debris"):AddItem(bodyGyro,.45) spellProjectile.CFrame = CFrame.new(humanoidRootPart.Position,mousePosition) spellProjectile.spellGlow.Color = spellSettings.Color spellProjectile.IsActive.Value = true spellProjectile.SpellId.Value = spellId --localLightningEvent:FireAllClients(true,spellId,spellProjectile) --local direction = mouseHit.LookVector - spellProjectile.a1.Position --local cframe = CFrame.new(spellProjectile.a1.Position, spellProjectile.a1.Position + direction) * CFrame.new(0, 0, spellSettings.BoltProperties.LengthBetweenAttachment) --spellProjectile.a2.CFrame = cframe local connection = {} local ignoreList = {} for i,v in pairs (player.Character:GetDescendants()) do if v:GetAttribute("Wand") then for a,b in pairs (v:GetChildren()) do if b:IsA("Part") or b:IsA("MeshPart") then table.insert(ignoreList,b) end end elseif v:IsA("Part") or v:IsA("MeshPart") or v:IsA("BasePart") then table.insert(ignoreList,v) end end table.insert(ignoreList,spellProjectile) local raycastParams = RaycastParams.new() raycastParams.FilterType = Enum.RaycastFilterType.Blacklist raycastParams.FilterDescendantsInstances = ignoreList local direct = (mousePosition - spellProjectile.Position).Unit task.spawn(function() while spellProjectile.IsActive.Value == true do task.wait() local part = squareRay(spellProjectile,raycastParams,2) if part then if part.Name ~= "projectile" then spellProjectile.IsActive.Value = false for i,v in pairs (connection) do v:Disconnect() end tweenService:Create(spellProjectile.projectileLoop,tweenQuint,{Volume = 0}):Play() for i,v in pairs (spellProjectile:GetDescendants()) do if v:IsA("ParticleEmitter") then v:Destroy() end end if spellProjectile:FindFirstChild("spellGlow") then spellProjectile.spellGlow:Destroy() end if part.Name == "Shield" and not spellSettings.Heal then if part.Parent.PrimaryPart.Transparency < 1 then spellProjectile:Destroy() part.Parent.PrimaryPart.Attachment.Flare:Emit(3) part.Parent.PrimaryPart.Attachment.Sparkle:Emit(3) part.Parent.PrimaryPart.Attachment.Wave:Emit(3) part.Parent.PrimaryPart.counterSpell:Play() return end end spellProjectile.hitSound.SoundId = spellSettings.hitSound spellProjectile.hitSound:Play() local lightningExplo = game.ReplicatedStorage.Lightning:Clone() lightningExplo.Parent = workspace lightningExplo.Glow.Color = colorSequence lightningExplo.Lightning.Color = colorSequence lightningExplo.Position = spellProjectile.Position delay(.3,function() for i,v in pairs (lightningExplo:GetChildren()) do if v:IsA("ParticleEmitter") then v.Enabled = false end end end) delay(2,function() spellProjectile:Destroy() lightningExplo:Destroy() end) callBack(player,part,spellId,spellProjectile) return end end if os.clock() - startTime >= 3 then for i,v in pairs (connection) do v:Disconnect() end spellProjectile:Destroy() return end end end) connection[#connection+1] = runService.Heartbeat:Connect(function(dt) spellProjectile.CFrame = CFrame.new(spellProjectile.Position) + direct * dt * spellSettings.Speed --spellProjectile.CFrame = CFrame.new(spellProjectile.Position) + mouseHit.LookVector * dt * spellSettings.Speed for i,v in pairs (workspace.Projectiles:GetChildren()) do if v ~= spellProjectile and v.Player.Value ~= player.Name then if (v.Position - spellProjectile.Position).magnitude <= 5 then if v.IsActive.Value ~= false and spellProjectile.IsActive.Value ~= false then if (game.Players:FindFirstChild(v.Player.Value).Character.HumanoidRootPart.Position - player.Character.PrimaryPart.Position).magnitude <= 85 then spellProjectile.IsActive.Value = false v.IsActive.Value = false for i,v in pairs (connection) do v:Disconnect() end spellProjectile.spellGlow:Destroy() v.spellGlow:Destroy() tweenService:Create(spellProjectile.projectileLoop,tweenQuint,{Volume = 0}):Play() tweenService:Create(v.projectileLoop,tweenQuint,{Volume = 0}):Play() clash(v,spellProjectile) return end end end end end end) end
9f3dea43f957ca8efeb920432cdb7547
{ "intermediate": 0.27522602677345276, "beginner": 0.4943029284477234, "expert": 0.23047101497650146 }
1,614
How do make my nginx webserver hosted on linux accept https requests?
83bf0a24094e650f52d240334d80d83f
{ "intermediate": 0.4379075765609741, "beginner": 0.33904707431793213, "expert": 0.22304536402225494 }
1,615
I'm working on a fivem script -- Server event to add players to team RegisterServerEvent("main-volleyball:server:setteam") AddEventHandler("main-volleyball:server:setteam", function(team) print('hello') print(team) for k,v in pairs(teams) do print(k) print(v) if k == team then teams[k] = source print(teams[k]) end end end) I want to make it so if the team they are trying to join already has a person it returns a msg to client saying team is full
32db837f1594bda51e9d07f6473e549e
{ "intermediate": 0.3026992082595825, "beginner": 0.4600088596343994, "expert": 0.23729196190834045 }
1,616
const inputStyles = ` .MuiInputBase-root .MuiOutlinedInput-root .MuiInputBase-colorPrimary .MuiInputBase-formControl .css-1ns4pi7-MuiInputBase-root {height: 100px}`; when i render this there is BRs in my code, why is this?
bad77738a19242b58c7a8abc1cb28de5
{ "intermediate": 0.54719078540802, "beginner": 0.22852201759815216, "expert": 0.22428715229034424 }
1,617
what changes should i make so the player can type or the name of the artist or the numbers 1 or 2, the rappers shouldt have their own numbers. You dont need to change the code import random artists_listeners = { '$NOT': 7781046, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: 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 != first_artist.lower() and guess_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() and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break elif guess_lower == second_artist.lower() and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.")
b17152a341c7568203308e69e75e7d2f
{ "intermediate": 0.3987133800983429, "beginner": 0.42564260959625244, "expert": 0.17564398050308228 }
1,618
import random artists_listeners = { 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: 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 != first_artist.lower() and guess_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() and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break elif guess_lower == second_artist.lower() and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}." can you change it so that the player can give both the name of the artist or the number 1 or 2, not every artist should have their own number
a0e272e54980dfcb9a8f2a1e62933bef
{ "intermediate": 0.38378655910491943, "beginner": 0.3521905541419983, "expert": 0.26402291655540466 }
1,619
hello
8e3214306127b9f6e5a101c97e89c778
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
1,620
fivem lua is there a way to play an animation for only a certain amount of frames?
476a79f8faaf606ac7cfcc3adf966616
{ "intermediate": 0.30401211977005005, "beginner": 0.17978166043758392, "expert": 0.5162062048912048 }
1,621
Could you please invent and describe a programming language which code is easy to understand for a non-programmer, yet general and competent enough to be used in any setting that a present programming language is used today? Please also provide an example of some code of this programming language.
1db21996f798d558eda8cf45e8ee0464
{ "intermediate": 0.333621084690094, "beginner": 0.3246226906776428, "expert": 0.3417561948299408 }
1,622
.MuiInputBase-root.MuiOutlinedInput-root.MuiInputBase-colorPrimary.MuiInputBase-formControl.css-1ns4pi7-MuiInputBase-root-MuiOutlinedInput-root { height: 100px; } can you put this css on multiple lines
2bb04db03d46f7ab981dd2be91a61ea4
{ "intermediate": 0.486397922039032, "beginner": 0.3086400330066681, "expert": 0.20496200025081635 }
1,623
Write a program in C which shows difference between pthread_attr_setschedpolicy and sched_setscheduler
95e7ab4dc7bddf7842d6038ef65e4ced
{ "intermediate": 0.46355631947517395, "beginner": 0.12175267189741135, "expert": 0.4146910309791565 }
1,624
давайте напишем наш градиентный спуск. Напомним, что формула для одной итерации градиентного спуска выглядит следующим образом: $$ w^t = w^{t-1} - \eta \nabla_{w} Q(w^{t-1}, X, y) $$ Где $w^t$ — значение вектора весов на $t$-ой итерации, а $\eta$ — параметр learning rate, отвечающий за размер шага. Реализуйте функцию gradient_descent Функция должна принимать на вход начальное значение весов линейной модели w_init, матрицу объектов-признаков X, вектор правильных ответов y, объект функции потерь loss, размер шага lr и количество итераций n_iterations. Функция должна реализовывать цикл, в котором происходит шаг градиентного спуска (градиенты берутся из loss посредством вызова метода calc_grad) по формуле выше и возвращать траекторию спуска (список из новых значений весов на каждом шаге) def gradient_descent( w_init: np.ndarray, X: np.ndarray, y: np.ndarray, loss: BaseLoss, lr: float, n_iterations: int = 100000, ) -> List[np.ndarray]: """ Функция градиентного спуска :param w_init: np.ndarray размера (n_feratures,) -- начальное значение вектора весов :param X: np.ndarray размера (n_objects, n_features) -- матрица объекты-признаки :param y: np.ndarray размера (n_objects,) -- вектор правильных ответов :param loss: Объект подкласса BaseLoss, который умеет считать градиенты при помощи loss.calc_grad(X, y, w) :param lr: float -- параметр величины шага, на который нужно домножать градиент :param n_iterations: int -- сколько итераций делать :return: Список из n_iterations объектов np.ndarray размера (n_features,) -- история весов на каждом шаге """ #Your code here
f60d4303773d85e3d04528e9b472d434
{ "intermediate": 0.16762341558933258, "beginner": 0.658359169960022, "expert": 0.17401738464832306 }
1,625
export const getStaticProps: GetStaticProps<{ customers: any[] }> = async ( ctx ) => { fetch("http://localhost:3000/api/customers") .then((res) => res.json()) .then((res) => console.log("response ========================================> ", res.customers) ); return { props: { customers: [], // customers: response.customers, // products: response.data, }, }; }; error - unhandledRejection: Error [FetchError]: invalid json response body at http://localhost:3000/api/customers reason: Unexpected token < in JSON at position 0 at D:\Fastaccount\TESTTASKS\shtrafovnet\node_modules\next\dist\compiled\node-fetch\index.js:1:51220 at processTicksAndRejections (node:internal/process/task_queues:96:5) { digest: undefined }
e48d863d174db96701c152e2a1ddc0bb
{ "intermediate": 0.44640666246414185, "beginner": 0.32973843812942505, "expert": 0.2238549143075943 }
1,626
import { useTranslation } from 'react-i18next'; import styled from '@emotion/styled'; import { useTheme } from '@mui/material'; import { MouseEventHandler, PieTooltipProps, ResponsivePie } from '@nivo/pie'; import { formatCurrency, formatValue } from 'app/utils/numbers'; import { useLocale } from 'app/features/Localisation'; const LegendContainer = styled('div', { shouldForwardProp: (prop) => !['pointColor'].includes(prop), })<{ pointColor: string }>` width: 250px; @media only screen and (max-width: 550px) { width: 215px; } display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 15px; border-radius: 4px; font-size: 14px; ${({ theme }) => ` box-shadow: ${theme.shadows[3]}; background-color: ${theme.palette.background.paper}; `} div.label { font-weight: 700; padding-bottom: ${({ theme }) => theme.spacing(3)}; ::after { height: 18px; width: 18px; content: ' '; position: absolute; display: inline; margin: auto; margin-left: 12px; border-radius: 50px; background-color: ${({ pointColor }) => pointColor}; box-shadow: 0 0 0 2px rgb(230, 230, 230), 0 0 0 3px rgb(160, 160, 160); } } div.values { display: flex; flex-direction: column; justify-content: center; align-items: center; gap: ${({ theme }) => theme.spacing(1)}; } `; export type NivoPieChartData = { id: string; label: string; value?: number; quantity: number; color?: string; }; const ChartTooltip = ({ datum, }: PieTooltipProps<NivoPieChartData>): JSX.Element => { const { t } = useTranslation(['common', 'journals']); const { locale } = useLocale(); return ( <LegendContainer pointColor={datum.color}> <div className="label">{datum.label}</div> <div className="values"> {datum.data.value ? ( <span> {t('journals:hub-view.pie-chart.tooltip.value', { value: t('common:display.value.currency', { symbol: locale.currency.symbol, value: formatCurrency(datum.data.value, locale.type), }), })} </span> ) : null} <span> {t('journals:hub-view.pie-chart.tooltip.quantity', { value: datum.data.quantity, })} </span> </div> </LegendContainer> ); }; export const NivoPieChart = ({ data, displayValue, onClick, }: { data: NivoPieChartData[]; displayValue: 'value' | 'quantity'; onClick: MouseEventHandler<NivoPieChartData, SVGPathElement>; }): JSX.Element => { const theme = useTheme(); const { locale } = useLocale(); const { t } = useTranslation(['common', 'journals']); return ( <ResponsivePie activeOuterRadiusOffset={8} arcLinkLabel={({ label, value }) => `${label} (${ displayValue === 'value' ? t('common:display.value.currency', { symbol: locale.currency.symbol, value: formatCurrency(value, locale.type), }) : formatValue(value, locale.type) })` } value={displayValue} arcLinkLabelsColor={{ from: 'color' }} arcLinkLabelsDiagonalLength={6} arcLinkLabelsOffset={6} arcLinkLabelsSkipAngle={13} arcLinkLabelsStraightLength={6} arcLinkLabelsTextColor={{ theme: 'labels.text.fill' }} arcLinkLabelsThickness={2} colors={{ scheme: 'category10' }} cornerRadius={10} data={data} enableArcLabels={false} innerRadius={0.25} margin={{ top: 25, right: 50, bottom: 50, left: 50 }} padAngle={2} sortByValue theme={theme.nivo} tooltip={ChartTooltip} onClick={onClick} /> ); }; please analyse this ReactJS code and find any clear mistakes
caff855b642778af2672ef6687a65670
{ "intermediate": 0.40241262316703796, "beginner": 0.5032023191452026, "expert": 0.09438506513834 }
1,627
import random artists_listeners = { '$NOT': 7781046, 'Young Nudy': 7553116, 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: 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 != first_artist.lower() and guess_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() and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break elif guess_lower == second_artist.lower() and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.") how can i change it so you can choose between different genres of music to play the game, for example the game explains what genres you can pick and then it only asks questions of artitsts in that genre, do i need to make a different set of data ? You dont need to correct the code
ba1985f840e31c08f802edd1f5a00c92
{ "intermediate": 0.44318467378616333, "beginner": 0.3152441680431366, "expert": 0.2415710985660553 }
1,628
import { useTranslation } from 'react-i18next'; import styled from '@emotion/styled'; import { useTheme } from '@mui/material'; import { MouseEventHandler, PieTooltipProps, ResponsivePie } from '@nivo/pie'; import { formatCurrency, formatValue } from 'app/utils/numbers'; import { useLocale } from 'app/features/Localisation'; const LegendContainer = styled('div', { shouldForwardProp: (prop) => !['pointColor'].includes(prop), })<{ pointColor: string }>` width: 250px; @media only screen and (max-width: 550px) { width: 215px; } display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 15px; border-radius: 4px; font-size: 14px; ${({ theme }) => ` box-shadow: ${theme.shadows[3]}; background-color: ${theme.palette.background.paper}; `} div.label { font-weight: 700; padding-bottom: ${({ theme }) => theme.spacing(3)}; ::after { height: 18px; width: 18px; content: ' '; position: absolute; display: inline; margin: auto; margin-left: 12px; border-radius: 50px; background-color: ${({ pointColor }) => pointColor}; box-shadow: 0 0 0 2px rgb(230, 230, 230), 0 0 0 3px rgb(160, 160, 160); } } div.values { display: flex; flex-direction: column; justify-content: center; align-items: center; gap: ${({ theme }) => theme.spacing(1)}; } `; export type NivoPieChartData = { id: string; label: string; value?: number; quantity: number; color?: string; }; const ChartTooltip = ({ datum, }: PieTooltipProps<NivoPieChartData>): JSX.Element => { const { t } = useTranslation(['common', 'journals']); const { locale } = useLocale(); return ( <LegendContainer pointColor={datum.color}> <div className="label">{datum.label}</div> <div className="values"> {datum.data.value ? ( <span> {t('journals:hub-view.pie-chart.tooltip.value', { value: t('common:display.value.currency', { symbol: locale.currency.symbol, value: formatCurrency(datum.data.value, locale.type), }), })} </span> ) : null} <span> {t('journals:hub-view.pie-chart.tooltip.quantity', { value: datum.data.quantity, })} </span> </div> </LegendContainer> ); }; export const NivoPieChart = ({ data, displayValue, onClick, }: { data: NivoPieChartData[]; displayValue: 'value' | 'quantity'; onClick: MouseEventHandler<NivoPieChartData, SVGPathElement>; }): JSX.Element => { const theme = useTheme(); const { locale } = useLocale(); const { t } = useTranslation(['common', 'journals']); return ( <ResponsivePie activeOuterRadiusOffset={8} arcLinkLabel={({ label, value }) => `${label} (${ displayValue === 'value' ? t('common:display.value.currency', { symbol: locale.currency.symbol, value: formatCurrency(value, locale.type), }) : formatValue(value, locale.type) })` } value={displayValue} arcLinkLabelsColor={{ from: 'color' }} arcLinkLabelsDiagonalLength={6} arcLinkLabelsOffset={6} arcLinkLabelsSkipAngle={13} arcLinkLabelsStraightLength={6} arcLinkLabelsTextColor={{ theme: 'labels.text.fill' }} arcLinkLabelsThickness={2} colors={{ scheme: 'category10' }} cornerRadius={10} data={data} enableArcLabels={false} innerRadius={0.25} margin={{ top: 25, right: 50, bottom: 50, left: 50 }} padAngle={2} sortByValue theme={theme.nivo} tooltip={ChartTooltip} onClick={onClick} /> ); }; Could you give me some tips on how to improve my code structure and please give me information about my code and not another example
eb150578a6e4e6bbcf10df859c805880
{ "intermediate": 0.40241262316703796, "beginner": 0.5032023191452026, "expert": 0.09438506513834 }
1,629
def plot_gd(w_list: Iterable, X: np.ndarray, y: np.ndarray, loss: BaseLoss, lr: float): """ Функция для отрисовки траектории градиентного спуска :param w_list: Список из объектов np.ndarray размера (n_features,) -- история весов на каждом шаге :param X: np.ndarray размера (n_objects, n_features) -- матрица объекты-признаки :param y: np.ndarray размера (n_objects,) -- вектор правильных ответов :param loss: Объект подкласса BaseLoss, который умеет считать лосс при помощи loss.calc_loss(X, y, w) :param lr: Коэффициент learning rate """ w_list = np.array(w_list) meshgrid_space = np.linspace(-2, 2, 100) A, B = np.meshgrid(meshgrid_space, meshgrid_space) levels = np.empty_like(A) for i in range(A.shape[0]): for j in range(A.shape[1]): w_tmp = np.array([A[i, j], B[i, j]]) levels[i, j] = loss.calc_loss(X, y, w_tmp) plt.figure(figsize=(15, 6)) plt.title(f"{lr}") plt.xlabel(r"$w_1$") plt.ylabel(r"$w_2$") plt.xlim(w_list[:, 0].min() - 0.1, w_list[:, 0].max() + 0.1) plt.ylim(w_list[:, 1].min() - 0.1, w_list[:, 1].max() + 0.1) plt.gca().set_aspect('equal') # visualize the level set CS = plt.contour( A, B, levels, levels=np.logspace(0, 1, num=20), cmap=plt.cm.rainbow_r ) CB = plt.colorbar(CS, shrink=0.8, extend="both") # visualize trajectory plt.scatter(w_list[:, 0], w_list[:, 1]) plt.plot(w_list[:, 0], w_list[:, 1]) def stochastic_gradient_descent( w_init: np.ndarray, X: np.ndarray, y: np.ndarray, loss: BaseLoss, lr: float, batch_size: int, n_iterations: int = 1000, ) -> List[np.ndarray]: """ Функция градиентного спуска :param w_init: np.ndarray размера (n_feratures,) -- начальное значение вектора весов :param X: np.ndarray размера (n_objects, n_features) -- матрица объекты-признаки :param y: np.ndarray размера (n_objects,) -- вектор правильных ответов :param loss: Объект подкласса BaseLoss, который умеет считать градиенты при помощи loss.calc_grad(X, y, w) :param lr: float -- параметр величины шага, на который нужно домножать градиент :param batch_size: int -- размер подвыборки, которую нужно семплировать на каждом шаге :param n_iterations: int -- сколько итераций делать :return: Список из n_iterations объектов np.ndarray размера (n_features,) -- история весов на каждом шаге """ w_history = [w_init] w = w_init.copy() for iteration in range(n_iterations): batch_indices = np.random.choice(X.shape[0], size=batch_size, replace=False) X_batch = X[batch_indices] y_batch = y[batch_indices] gradient = loss.calc_grad(X_batch, y_batch, w) w = w - lr * gradient w_history.append(w) return w_history При помощи функций stochastic_gradient_descent и plot_gd нарисуйте траекторию градиентного спуска для разных значений длины шага (параметра lr) и размера подвыборки (параметра batch_size). Используйте не менее четырёх разных значений для lr и batch_size. Сделайте и опишите свои выводы о том, как параметры lr и batch_size влияют на поведение стохастического градиентного спуска. Как отличается поведение стохастического градиентного спуска от обычного? Обратите внимание, что в нашем датасете всего 300 объектов, так что batch_size больше этого числа не будет иметь смысла.
3442815e26ab746b0ae285b97b29910f
{ "intermediate": 0.3748631477355957, "beginner": 0.40538111329078674, "expert": 0.21975572407245636 }
1,630
import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class HighSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("HighSum GAME"); System.out.println("================================================================================"); // Login system String username = ""; while (true) { System.out.print("Enter your username: "); username = input.nextLine(); System.out.print("Enter your password: "); String password = input.nextLine(); if (password.equals("password")) { System.out.println(username + ", You have 100 chips"); break; } else { System.out.println("Incorrect username or password. Please try again."); } } // Set initial chips to 100 int chips = 100; System.out.println("--------------------------------------------------------------------------------"); System.out.println("Game starts - Dealer shuffles deck."); System.out.println("--------------------------------------------------------------------------------"); int roundNumber = 1; while (true) { // Create deck of cards ArrayList<Card> deck = new ArrayList<Card>(); String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"}; String[] ranks = {"Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"}; for (String suit : suits) { for (String rank : ranks) { deck.add(new Card(suit, rank)); } } // Shuffle deck Collections.shuffle(deck); // Deal cards to players ArrayList<Card> playerHand = new ArrayList<Card>(); ArrayList<Card> dealerHand = new ArrayList<Card>(); playerHand.add(deck.get(0)); playerHand.add(deck.get(2)); dealerHand.add(deck.get(1)); dealerHand.add(deck.get(3)); // Print players' hands System.out.println("Dealer dealing cards - ROUND " + roundNumber); System.out.println("--------------------------------------------------------------------------------"); System.out.println("Dealer"); System.out.println("<HIDDEN CARD> " + dealerHand.get(1)); System.out.println(username); System.out.println(playerHand.get(0) + " " + playerHand.get(1)); System.out.println("Value: " + (playerHand.get(0).getValue() + playerHand.get(1).getValue())); // Determine highest visible card and get the bet int bet = 0; if (playerHand.get(1).getValue() > dealerHand.get(1).getValue()) { System.out.print("Player call, state bet: "); bet = input.nextInt(); } else { System.out.println("Dealer call, state bet: "); bet = (int) (Math.random() * (chips / 2) + 1); System.out.println(bet); } // Update chips chips -= bet; System.out.println(username + ", You are left with " + chips + " chips"); System.out.println("Bet on table : " + (bet * 2)); System.out.println("================================================================================"); roundNumber++; } } } change the code for the rounds so that the display is in this format "Dealer <HIDDEN CARD> <Club 6> "User" <Diamond Ace> <Spade 6> Value: 7" Starting round deals 2 card to each the dealer and the player but the dealer have 1 hidden card. Next round onwards showing the additional card given in this format with the game logic still in place: "Dealer <HIDDEN CARD> <Club 6> <Diamond 9> "user" <Diamond Ace> <Spade 6> <Heart 7> Value:14 Dealer call, state bet: 10 Do you want to follow? [Y/N]: Y"
a5615fa1a0cd5d7453b952bec50c3d34
{ "intermediate": 0.25479772686958313, "beginner": 0.6186787486076355, "expert": 0.1265234649181366 }
1,631
for python, what does os.path do
2b37fd151431760b492db78dc5482b39
{ "intermediate": 0.34767061471939087, "beginner": 0.4476573169231415, "expert": 0.20467206835746765 }
1,632
Ok, working with single database is pretty simple, what if you have 2 or more storages? It might be not only databases, but external REST CRUD services or message queues. And it is possible that one of that external storage have no option to rollback or made revers changes. What is possible approaches here? As an example you might refer to next:
70beec617349d858ceaed1430e80dd57
{ "intermediate": 0.5385211110115051, "beginner": 0.20059747993946075, "expert": 0.2608814835548401 }
1,633
Please explain what the following Scheme code does. (define (pow a) (cond ((= a 0) 1) ((= a 1) 1) ((+ (pow (- a 1)) (pow (- a 2))))))
6ba2d3298ff8a3990fc17129844ddd51
{ "intermediate": 0.19188344478607178, "beginner": 0.6555534601211548, "expert": 0.15256313979625702 }
1,634
ORA-01555: snapshot too old: rollback segment number with name "" too small
275299b97b6efd5ca795d4d0bcdcafe3
{ "intermediate": 0.33644020557403564, "beginner": 0.34326446056365967, "expert": 0.3202953338623047 }
1,635
can you convert this github actions file into a bash script that works within another Github actions file as a step and be able to pull github secrets too? name: Update website content on: push: branches: - dev - stg - prod # Triggers if there is any change in static_website directory paths: - 'static_website/**' permissions: id-token: write contents: read jobs: build: runs-on: ubuntu-latest steps: - name: checkout out current code using public action uses: actions/checkout@v3 - name: Set env variable for branch id: env_var_step run: | if [[ "${{ github.ref_name }}" == "dev" ]]; then echo "NAMESPACE=dev" >> $GITHUB_OUTPUT elif [[ "${{ github.ref_name }}" == "stg" ]]; then echo "NAMESPACE=stg" >> $GITHUB_OUTPUT elif [[ "${{ github.ref_name }}" == "prod" ]]; then echo "NAMESPACE=prod" >> $GITHUB_OUTPUT # elif [[ "${{ github.ref_name }}" == "test_ci_cd" ]]; # then # echo "I am inside test_ci_cd" # echo "NAMESPACE=stg" >> $GITHUB_OUTPUT fi - name: Export AWS credentials for AWS CLI setup id: aws_creds run: | if [[ ${{ steps.env_var_step.outputs.NAMESPACE }} == "dev" ]]; then echo "role_arn=${{ secrets.DEV_GITHUB_MDL_CLOUD_SERVERLESS_ROLE }}" >> $GITHUB_OUTPUT elif [[ ${{ steps.env_var_step.outputs.NAMESPACE }} == "stg" ]]; then echo "role_arn=${{ secrets.STG_GITHUB_MDL_CLOUD_SERVERLESS_ROLE }}" >> $GITHUB_OUTPUT elif [[ ${{ steps.env_var_step.outputs.NAMESPACE }} == "prod" ]]; then echo "role_arn=${{ secrets.PROD_GITHUB_MDL_CLOUD_SERVERLESS_ROLE }}" >> $GITHUB_OUTPUT elif [[ ${{ steps.env_var_step.outputs.NAMESPACE }} == "sandbox" ]]; then echo "role_arn=${{ secrets.SANDBOX_GITHUB_MDL_CLOUD_SERVERLESS_ROLE }}" >> $GITHUB_OUTPUT fi - name: Configure AWS Credentials uses: aws-actions/configure-aws-credentials@v1 with: role-to-assume: ${{ steps.aws_creds.outputs.role_arn }} role-session-name: OIDCSession aws-region: ${{ secrets.AWS_REGION }} - name: Upload latest changes to S3 bucket run: | echo ${{ steps.env_var_step.outputs.NAMESPACE }} bucket_list=$(aws s3 ls | awk '{print $3}') for bucket in $bucket_list; do if [[ "$bucket" == *"${{ secrets.PROJECT_NAME }}-${{ steps.env_var_step.outputs.NAMESPACE }}"* ]]; then if [[ "$bucket" != *"logs" ]]; then aws s3 sync static_website/ s3://$bucket --delete fi fi done - name: Create Cloudfront invalidation to pick name changes run: | distributions=$(aws cloudfront list-distributions | jq -r '.DistributionList.Items[] | .AliasICPRecordals[].CNAME') if [[ ${{ steps.env_var_step.outputs.NAMESPACE }} == "dev" ]]; then for item in $distributions; do if [[ "$item" == "${{ secrets.PROJECT_NAME }}.dev.deployer.mckinsey.com" ]]; then id=$(aws cloudfront list-distributions | jq -r '.DistributionList.Items[] | select(.AliasICPRecordals[].CNAME == "'$item'") | .Id') invalidation_id=$(aws cloudfront create-invalidation --distribution-id $id --paths "/*" | jq -r '.Invalidation.Id') aws cloudfront wait invalidation-completed --distribution-id $id --id $invalidation_id fi done elif [[ ${{ steps.env_var_step.outputs.NAMESPACE }} == "stg" ]]; then for item in $distributions; do if [[ "$item" == "${{ secrets.PROJECT_NAME }}.stg.deployer.mckinsey.com" ]]; then id=$(aws cloudfront list-distributions | jq -r '.DistributionList.Items[] | select(.AliasICPRecordals[].CNAME == "'$item'") | .Id') invalidation_id=$(aws cloudfront create-invalidation --distribution-id $id --paths "/*" | jq -r '.Invalidation.Id') aws cloudfront wait invalidation-completed --distribution-id $id --id $invalidation_id fi done elif [[ ${{ steps.env_var_step.outputs.NAMESPACE }} == "prod" ]]; then for item in $distributions; do if [[ "$item" == "${{ secrets.PROJECT_NAME }}.deployer.mckinsey.com" ]]; then id=$(aws cloudfront list-distributions | jq -r '.DistributionList.Items[] | select(.AliasICPRecordals[].CNAME == "'$item'") | .Id') invalidation_id=$(aws cloudfront create-invalidation --distribution-id $id --paths "/*" | jq -r '.Invalidation.Id') aws cloudfront wait invalidation-completed --distribution-id $id --id $invalidation_id fi done fi
6f1a2f490001aa492769257505a9dd7e
{ "intermediate": 0.3003617227077484, "beginner": 0.5830199122428894, "expert": 0.11661834269762039 }
1,636
I have a person bounding box, i want to extract the countours of the person, a polygon, inside the bounding box using opencv
b6ec1bca40212da3caf1d50aa46db561
{ "intermediate": 0.40305471420288086, "beginner": 0.12805862724781036, "expert": 0.46888667345046997 }
1,637
Write a program in C, which shows diffrence between pthread_attr_setschedpolicy and sched_setscheduler
cd13dc512997323e390b4e4c74f3af7c
{ "intermediate": 0.3746289312839508, "beginner": 0.15621864795684814, "expert": 0.46915245056152344 }
1,638
write full java code for a simple shoot em up game similar to touhou
269dcdc1c742fbc9e368e5f4c887fd77
{ "intermediate": 0.3765752613544464, "beginner": 0.42062443494796753, "expert": 0.20280024409294128 }
1,639
import random artists_listeners = { '$NOT': 7781046, '21 Savage': 60358167, '9lokknine': 1680245, 'A Boogie Wit Da Hoodie': 18379137, 'Ayo & Teo': 1818645, 'Bhad Bhabie': 1915352, 'Blueface': 4890312, 'Bobby Shmurda': 2523069, 'Cardi B': 30319082, 'Central Cee': 22520846, 'Chief Keef': 9541580, 'Coi Leray': 28619269, 'DaBaby': 30353214, 'DDG': 4422588, 'Denzel Curry': 7555420, 'Desiigner': 5586908, 'Don Toliver': 27055150, 'Dusty Locane': 3213566, 'Est Gee': 5916299, 'Famous Dex': 2768895, 'Fivio Foreign': 9378678, 'Fredo Bang': 1311960, 'Future': 47165975, 'Gazo': 5342471, 'GloRilla': 6273110, 'Gunna': 23998763, 'Hotboii': 1816019, 'Iann Dior': 14092651, 'J. Cole': 36626203, 'JayDaYoungan': 1415050, 'Juice WRLD': 31818659, 'Key Glock': 10397097, 'King Von': 7608559, 'Kodak Black': 24267064, 'Latto': 10943008, 'Lil Baby': 30600740, 'Lil Durk': 20244848, 'Lil Keed': 2288807, 'Lil Loaded': 2130890, 'Lil Mabu': 2886517, 'Lil Mosey': 8260285, 'Lil Peep': 15028635, 'Lil Pump': 7530070, 'Lil Skies': 4895628, 'Lil Tecca': 13070702, 'Lil Tjay': 19119581, 'Lil Uzi Vert': 3538351, 'Lil Wayne': 32506473, 'Lil Xan': 2590180, 'Lil Yachty': 11932163, 'Machine Gun Kelly': 13883363, 'Megan Thee Stallion': 23815306, 'Moneybagg Yo': 11361158, 'NLE Choppa': 17472472, 'NoCap': 1030289, 'Offset': 15069868, 'Playboi Carti': 16406109, 'PnB Rock': 5127907, 'Polo G': 24374576, 'Pooh Shiesty': 4833055, 'Pop Smoke': 24438919, 'Quando Rondo': 1511549, 'Quavo': 15944317, 'Rod Wave': 8037875, 'Roddy Ricch': 22317355, 'Russ Millions': 6089378, 'Ski Mask The Slump God': 9417485, 'Sleepy Hallow': 8794484, 'Smokepurpp': 2377384, 'Soulja Boy': 10269586, 'SpottemGottem': 1421927, 'Takeoff': 9756119, 'Tay-K': 4449331, 'Tee Grizzley': 4052375, 'Travis Scott': 46625716, 'Trippie Redd': 19120728, 'Waka Flocka Flame': 5679474, 'XXXTENTACION': 35627974, 'YBN Nahmir': 4361289, 'YK Osiris': 1686619, 'YNW Melly': 8782917, 'YounBoy Never Broke Again': 18212921, 'Young M.A': 2274306, 'Young Nudy': 7553116, 'Young Thug': 28887553, 'Yungeen Ace': 1294188, } keys = list(artists_listeners.keys()) score = 0 while True: first_artist = random.choice(keys) second_artist = random.choice(keys) while first_artist == second_artist: second_artist = random.choice(keys) while True: 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, or enter 1 or 2 to make a guess.") elif guess_lower == first_artist.lower() or guess_lower == '1' and artists_listeners[first_artist] > artists_listeners[second_artist]: print(f"You guessed correctly! {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break elif guess_lower == second_artist.lower() or guess_lower == '2' and artists_listeners[second_artist] > artists_listeners[first_artist]: print(f"You guessed correctly! {second_artist.title()} had {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners and {first_artist.title()} has {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners.") score += 1 break else: print(f"\nSorry, you guessed incorrectly. {first_artist.title()} had {int(artists_listeners[first_artist] / 1e6):,}M monthly Spotify listeners and {second_artist.title()} has {int(artists_listeners[second_artist] / 1e6):,}M monthly Spotify listeners.\n") score = 0 play_again = input("Would you like to play again? (y/n) ") if play_again.lower() == 'n': print("Thanks for playing!") quit() print(f"\nYour score is {score}.") how to change the code so the answer reveals one decimal in the listeners number for example : .. had 20,1M listeners you dont need to correct the whole code
b931a4645d80fc841dddff2b5beaf7d5
{ "intermediate": 0.3797962963581085, "beginner": 0.2852279245853424, "expert": 0.3349757194519043 }
1,640
karaf print all bubdles
c3678d311b14a57d66396c9d7cd13af8
{ "intermediate": 0.44275614619255066, "beginner": 0.17359699308872223, "expert": 0.3836468458175659 }
1,641
Write me a simple website for a chinese teacher
89bd8626f8a65ad71a0679990345bcfb
{ "intermediate": 0.28423869609832764, "beginner": 0.39025962352752686, "expert": 0.3255016505718231 }
1,642
Hey ChatGPT! Could you please give me a list (in a code block) of 25 extremely obscure and experimental games inspired by Syd Mead?
0c1a2c3dbc0aa3085e7a87438cce8552
{ "intermediate": 0.39251694083213806, "beginner": 0.3647521436214447, "expert": 0.24273094534873962 }
1,643
make this script use 2captcha import os import random import string from rich.console import Console from rich.prompt import IntPrompt from playwright.sync_api import sync_playwright console = Console() def generate_password(length=20): alphabet = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(alphabet) for _ in range(length)) def generate_nickname(): try: with open('nicknames.txt', 'r') as file: words = [line.strip() for line in file.readlines()] return random.choice(words) + str(random.randint(10000, 999999)) except FileNotFoundError: console.log('[bold red]Error:[/] nicknames.txt file not found!') console.print('[bold]Press enter to exit...[/]') console.input() exit() def clear(): # Clears the console screen and adds the name at the beginning os.system('cls' if os.name == 'nt' else 'clear') console.rule('[bold red]Roblox Account Generator[/]') def registration(): with sync_playwright() as pw: nickname = generate_nickname() password = generate_password() browser = pw.firefox.launch(headless=False) # * Don't try to use chromium browsers because they got detected by roblox as bot. context = browser.new_context() page = context.new_page() page.set_viewport_size({"width": 640, "height": 480}) page.route('https://apis.roblox.com/universal-app-configuration/v1/behaviors/cookie-policy/content', lambda route: route.abort()) # Blocks cookies banner page.goto('https://www.roblox.com') page.locator('//*[@id="MonthDropdown"]').select_option('January') page.locator('//*[@id="DayDropdown"]').select_option('01') page.locator('//*[@id="YearDropdown"]').select_option('1999') while True: # Checks username valid with page.expect_response('https://auth.roblox.com/v1/usernames/validate') as username_validate: page.locator('//*[@id="signup-username"]').fill(nickname) if username_validate.value.json().get('code') == 0: break else: nickname = generate_nickname() page.locator('//*[@id="signup-password"]').fill(password) page.locator('//*[@id="MaleButton"]').click() with page.expect_response('https://auth.roblox.com/v2/signup') as signup_validate: page.locator('//*[@id="signup-button"]').click(timeout=0) if signup_validate.value.status == 429: browser.close() console.log('[bold red]Error:[/] too many requests! Try to change your IP (you can use VPN, preferably paid)') console.print('[bold]Press enter to continue...[/]') console.input() return None else: with page.expect_response('https://client-api.arkoselabs.com/fc/gt2/public_key/**') as signup_validate: pass if signup_validate.value.ok: page.wait_for_url('https://www.roblox.com/home?nu=true', timeout=0) else: browser.close() console.log('[bold red]Error:[/] Unknown error! Try to change your IP (you can use VPN, preferably paid)') console.print('[bold]Press enter to continue...[/]') console.input() return None with open('cookies.txt', 'a') as file: cookies = context.cookies() roblosecurity_cookie = next((cookie for cookie in cookies if cookie['name'] == '.ROBLOSECURITY'),None) # Finds .ROBLOSECURITY cookies if roblosecurity_cookie: roblos_data_value = roblosecurity_cookie['value'] file.write(f'{roblos_data_value}\n') with open('accounts.txt', 'a') as file: file.write(f'{nickname}:{password}\n') console.log('[bold green]Account generated successfully[/]', ':white_check_mark:') browser.close() return None def main(): try: clear() amount = IntPrompt.ask('Enter how many accounts to generate') clear() for _ in range(amount): with console.status('Generating...', spinner='line'): registration() except BaseException: pass if __name__ == '__main__': main()
651e86532755e104ab875917077833ed
{ "intermediate": 0.3547446131706238, "beginner": 0.3470029830932617, "expert": 0.2982523739337921 }
1,644
What it means? : building 'talib._ta_lib' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for TA-Lib Failed to build TA-Lib ERROR: Could not build wheels for TA-Lib, which is required to install pyproject.toml-based project
94c517ddeb0acc980f51dd7e418e1951
{ "intermediate": 0.5787332057952881, "beginner": 0.20783290266990662, "expert": 0.2134338766336441 }
1,645
can you add 2captcha in this script import os import random import string from rich.console import Console from rich.prompt import IntPrompt from playwright.sync_api import sync_playwright console = Console() def generate_password(length=20): alphabet = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(alphabet) for _ in range(length)) def generate_nickname(): # Generates a random nickname by combining a word from the file with a random number try: with open('nicknames.txt', 'r') as file: words = [line.strip() for line in file.readlines()] return random.choice(words) + str(random.randint(10000, 999999)) except FileNotFoundError: console.log('[bold red]Error:[/] nicknames.txt file not found!') console.print('[bold]Press enter to exit...[/]') console.input() exit() def clear(): # Clears the console screen and adds the name at the beginning os.system('cls' if os.name == 'nt' else 'clear') console.rule('[bold red]Roblox Account Generator[/]') def registration(): with sync_playwright() as pw: nickname = generate_nickname() password = generate_password() browser = pw.firefox.launch(headless=False) # * Don't try to use chromium browsers because they got detected by roblox as bot. context = browser.new_context() page = context.new_page() page.set_viewport_size({"width": 640, "height": 480}) page.route('https://apis.roblox.com/universal-app-configuration/v1/behaviors/cookie-policy/content', lambda route: route.abort()) # Blocks cookies banner page.goto('https://www.roblox.com') page.locator('//*[@id="MonthDropdown"]').select_option('January') page.locator('//*[@id="DayDropdown"]').select_option('01') page.locator('//*[@id="YearDropdown"]').select_option('1999') while True: # Checks username valid with page.expect_response('https://auth.roblox.com/v1/usernames/validate') as username_validate: page.locator('//*[@id="signup-username"]').fill(nickname) if username_validate.value.json().get('code') == 0: break else: nickname = generate_nickname() page.locator('//*[@id="signup-password"]').fill(password) page.locator('//*[@id="MaleButton"]').click() with page.expect_response('https://auth.roblox.com/v2/signup') as signup_validate: page.locator('//*[@id="signup-button"]').click(timeout=0) if signup_validate.value.status == 429: browser.close() console.log('[bold red]Error:[/] too many requests! Try to change your IP (you can use VPN, preferably paid)') console.print('[bold]Press enter to continue...[/]') console.input() return None else: with page.expect_response('https://client-api.arkoselabs.com/fc/gt2/public_key/**') as signup_validate: pass if signup_validate.value.ok: page.wait_for_url('https://www.roblox.com/home?nu=true', timeout=0) else: browser.close() console.log('[bold red]Error:[/] Unknown error! Try to change your IP (you can use VPN, preferably paid)') console.print('[bold]Press enter to continue...[/]') console.input() return None with open('cookies.txt', 'a') as file: cookies = context.cookies() roblosecurity_cookie = next((cookie for cookie in cookies if cookie['name'] == '.ROBLOSECURITY'),None) # Finds .ROBLOSECURITY cookies if roblosecurity_cookie: roblos_data_value = roblosecurity_cookie['value'] file.write(f'{roblos_data_value}\n') with open('accounts.txt', 'a') as file: file.write(f'{nickname}:{password}\n') console.log('[bold green]Account generated successfully[/]', ':white_check_mark:') browser.close() return None def main(): try: clear() amount = IntPrompt.ask('Enter how many accounts to generate') clear() for _ in range(amount): with console.status('Generating...', spinner='line'): registration() except BaseException: pass if __name__ == '__main__': main()
0de60de362d7a0ecd854f419c804df42
{ "intermediate": 0.33607569336891174, "beginner": 0.49527886509895325, "expert": 0.16864539682865143 }
1,646
make this script work with 2captcha also make it solve funcaptcha import os import random import string from rich.console import Console from rich.prompt import IntPrompt from playwright.sync_api import sync_playwright console = Console() def generate_password(length=20): alphabet = string.ascii_letters + string.digits + string.punctuation return ''.join(random.choice(alphabet) for _ in range(length)) def generate_nickname(): # Generates a random nickname by combining a word from the file with a random number try: with open('nicknames.txt', 'r') as file: words = [line.strip() for line in file.readlines()] return random.choice(words) + str(random.randint(10000, 999999)) except FileNotFoundError: console.log('[bold red]Error:[/] nicknames.txt file not found!') console.print('[bold]Press enter to exit...[/]') console.input() exit() def clear(): # Clears the console screen and adds the name at the beginning os.system('cls' if os.name == 'nt' else 'clear') console.rule('[bold red]Roblox Account Generator[/]') def registration(): with sync_playwright() as pw: nickname = generate_nickname() password = generate_password() browser = pw.firefox.launch(headless=False) # * Don't try to use chromium browsers because they got detected by roblox as bot. context = browser.new_context() page = context.new_page() page.set_viewport_size({"width": 640, "height": 480}) page.route('https://apis.roblox.com/universal-app-configuration/v1/behaviors/cookie-policy/content', lambda route: route.abort()) # Blocks cookies banner page.goto('https://www.roblox.com') page.locator('//*[@id="MonthDropdown"]').select_option('January') page.locator('//*[@id="DayDropdown"]').select_option('01') page.locator('//*[@id="YearDropdown"]').select_option('1999') while True: # Checks username valid with page.expect_response('https://auth.roblox.com/v1/usernames/validate') as username_validate: page.locator('//*[@id="signup-username"]').fill(nickname) if username_validate.value.json().get('code') == 0: break else: nickname = generate_nickname() page.locator('//*[@id="signup-password"]').fill(password) page.locator('//*[@id="MaleButton"]').click() with page.expect_response('https://auth.roblox.com/v2/signup') as signup_validate: page.locator('//*[@id="signup-button"]').click(timeout=0) if signup_validate.value.status == 429: browser.close() console.log('[bold red]Error:[/] too many requests! Try to change your IP (you can use VPN, preferably paid)') console.print('[bold]Press enter to continue...[/]') console.input() return None else: with page.expect_response('https://client-api.arkoselabs.com/fc/gt2/public_key/**') as signup_validate: pass if signup_validate.value.ok: page.wait_for_url('https://www.roblox.com/home?nu=true', timeout=0) else: browser.close() console.log('[bold red]Error:[/] Unknown error! Try to change your IP (you can use VPN, preferably paid)') console.print('[bold]Press enter to continue...[/]') console.input() return None with open('cookies.txt', 'a') as file: cookies = context.cookies() roblosecurity_cookie = next((cookie for cookie in cookies if cookie['name'] == '.ROBLOSECURITY'),None) # Finds .ROBLOSECURITY cookies if roblosecurity_cookie: roblos_data_value = roblosecurity_cookie['value'] file.write(f'{roblos_data_value}\n') with open('accounts.txt', 'a') as file: file.write(f'{nickname}:{password}\n') console.log('[bold green]Account generated successfully[/]', ':white_check_mark:') browser.close() return None def main(): try: clear() amount = IntPrompt.ask('Enter how many accounts to generate') clear() for _ in range(amount): with console.status('Generating...', spinner='line'): registration() except BaseException: pass if __name__ == '__main__': main()
8b4a24bc11fd4201e73bb52474bc74ea
{ "intermediate": 0.28018730878829956, "beginner": 0.41962265968322754, "expert": 0.3001900017261505 }
1,647
after it clicks signup button the browser closing and script stopping work without any error in terminal import os import random import string from rich.console import Console from rich.prompt import IntPrompt from playwright.sync_api import sync_playwright from captcha_solver import CaptchaSolver console = Console() def generate_password(length=20): alphabet = string.ascii_letters + string.digits + string.punctuation return "".join(random.choice(alphabet) for _ in range(length)) def generate_nickname(): # Generates a random nickname by combining a word from the file with a random number try: with open("nicknames.txt", "r") as file: words = [line.strip() for line in file.readlines()] return random.choice(words) + str(random.randint(10000, 999999)) except FileNotFoundError: console.log("[bold red]Error:[/] nicknames.txt file not found!") console.print("[bold]Press enter to exit…[/]") console.input() exit() def clear(): # Clears the console screen and adds the name at the beginning os.system("cls" if os.name == "nt" else "clear") console.rule("[bold red]Roblox Account Generator[/]") def registration(): with sync_playwright() as pw: nickname = generate_nickname() password = generate_password() browser = pw.firefox.launch( headless=False ) # * Don’t try to use chromium browsers because they got detected by roblox as bot. context = browser.new_context() page = context.new_page() page.set_viewport_size({"width": 640, "height": 480}) page.route( "https://apis.roblox.com/universal-app-configuration/v1/behaviors/cookie-policy/content", lambda route: route.abort(), ) # Blocks cookies banner page.goto("https://www.roblox.com") page.locator('//*[@id="MonthDropdown"]').select_option("January") page.locator('//*[@id="DayDropdown"]').select_option("01") page.locator('//*[@id="YearDropdown"]').select_option("1999") while True: # Checks username valid with page.expect_response( "https://auth.roblox.com/v1/usernames/validate" ) as username_validate: page.locator('//*[@id="signup-username"]').fill(nickname) if username_validate.value.json().get("code") == 0: break else: nickname = generate_nickname() page.locator('//*[@id="signup-password"]').fill(password) page.locator('//*[@id="MaleButton"]').click() with page.expect_response( "https://auth.roblox.com/v2/signup" ) as signup_validate: page.click('//*[@id="signup-button"]', timeout=0) if signup_validate.value.status == 429: browser.close() console.log( "[bold red]Error:[/] too many requests! Try to change your IP (you can use VPN, preferably paid)" ) console.print("[bold]Press enter to continue…[/]") console.input() return None else: with page.expect_target_changed() as target_info: pass if page.url == "https://www.roblox.com/home?nu=true": with open("cookies.txt", "a") as file: cookies = context.cookies() roblosecurity_cookie = next( ( cookie for cookie in cookies if cookie["name"] == ".ROBLOSECURITY" ), None, ) # Finds .ROBLOSECURITY cookies if roblosecurity_cookie: roblos_data_value = roblosecurity_cookie["value"] file.write(f"{roblos_data_value}\n") else: # Solve funcaptcha solver = CaptchaSolver('twocaptcha', api_key="fb2df99ad7f7cdd933767005dbc18466") while True: # Get the challenge URL and the session ID challenge_url = page.locator('//[@id="FunCaptcha"]/@data-payload-url')[0] session_id = page.locator('//[@id="FunCaptcha"]/@data-session-id')[0] # Solve the challenge using 2captcha captcha_response = solver.solve_captcha(challenge_url) if not captcha_response.get("code"): # Get the s, sig, and api_server keys from the 2captcha API response s = captcha_response["solution"]["s"] sig = captcha_response["solution"]["sig"] api_server = captcha_response["api_server"] # Pass the s, sig, and api_server keys to the page and submit the form page.set_extra_headers({"x-fcapi-session-id": session_id}) page.set_extra_headers({"x-fcapi-s-token": s}) page.set_extra_headers({"x-fcapi-sig": sig}) page.route( "https://client-api.arkoselabs.com/fc/gt2/public_key/", lambda route: route.abort(), ) page.click('//[@id="signup-button"]', timeout=0) with open("accounts.txt", "a") as file: file.write(f"{nickname}:{password}\n") console.log( "[bold green]Account generated successfully[/]", ":white_check_mark:" ) break else: console.log(f'[bold red]Error:[/] {captcha_response.get("message")}') nickname = generate_nickname() browser.close() console.log( "[bold green]Account generated successfully[/]", ":white_check_mark:" ) return None def main(): try: clear() amount = IntPrompt.ask("Enter how many accounts to generate") clear() for _ in range(amount): with console.status("Generating...", spinner="line"): registration() except BaseException: pass if __name__ == "__main__": main()
27cb16a39b3a122ca6446ad8dafd8f78
{ "intermediate": 0.39842474460601807, "beginner": 0.4637066125869751, "expert": 0.13786858320236206 }
1,648
Can you provide an example of a MC68000 assembly code program with commented lines that implements a 2-layer neural network?
30c1b6ae4abc5da4bfbb7908d2b62311
{ "intermediate": 0.1160382553935051, "beginner": 0.10717329382896423, "expert": 0.7767884731292725 }
1,649
In groups of 5-6 students, you are required to design and implement a database to address the requirements of a scenario provided by your tutor. Note that you will be grouped with other students in the same seminar session. As the scenario contains only a brief outline of a business case study, you will need to state any business rules and assumptions that you have made in order to fill any gaps or to address any ambiguities when putting together your database design. All the required tables need to be implemented using Oracle APEX. SUBMISSION A: Group Project Report Each group member needs to submit a copy of their group’s report using the ‘ISDB Group Project’ submission link set up on Blackboard. Any group member who fails to submit a copy will be awarded zero marks. Any report that is submitted late will capped at 40%. The report must use the assignment report template provided, containing the following elements, in this order: 1. A header page which includes the name and ID of your team members and the username and password of the APEX account(s) containing your group’s implemented tables and reports/queries. 2. A list of any assumptions/clarifications you have made that have affected the design of your database. 3. An ER diagram (using ‘Crow’s foot’ notation) providing the final design of your database, which shows entities, attributes, primary and foreign keys, and named relationships. 4. Entity specification forms documenting all your entities (using the template provided). 5. The SQL scripts you used to create your tables (including all constraints) which should match your entity specification forms. 6. A list of the SQL scripts (INSERT INTO ..commands) used to insert test data into each of your tables, annotated to show that there is sufficient breadth and volume of data to adequately test your queries/reports (see below). 2 7. 8 functional requirements generating reports/output that effectively demonstrate the scope and functionality of the system, and for each: a) the SQL script used to implement the requirement, and b) a screenshot of the run query and output it produces. The queries you choose should critical queries illustrating the breadth and potential of the implemented database, as well as your mastery of SQL. Each script should be numbered and saved in your database. 8. A brief overview of the database features you would implement to ensure your data is adequately secured. 9. A suggestion for one other database technology/information system that you think might benefit the company, either now or in the future, providing a rationale for this. 10. Evidence to show effective and timely project management using Scrum, the contribution of each member to the project, namely attendance at team meetings held in (and outside) your seminar sessions, sprint backlogs, tasks uploaded to the group’s file Blackboard area and SQL scripts saved in members’ APEX account(s). Case study for Information Systems and Databases – February 2023 South London University’s Computing school wishes to set up a database to manage its external speaker and placements processes. This is all part of developing links with local businesses and giving students the opportunity to get some industry experience. At present, individual members of the teaching team organise guest lectures, but this is all done in a rather random fashion. They might use their personal contacts or meet an interesting speaker at an external event and invite him/her to give a lecture or run a workshop for their students. If the speaker agrees, then the lecturer will contact the timetabling unit to arrange a suitable date, time and room for the lecture and then announce details of the event through the Blackboard announcement system. With the increasing emphasis on giving students ‘real world’ experiences, more and more of these events are being run and the school wishes to make the most of the contacts they have and which topics these contacts have expressed an interest in talking about. Unfortunately, these contacts and speakers are not stored centrally, which leads to problems, for example: • There have been occasions where multiple guest lectures have been arranged in one week for a particular cohort of students, as each of the teaching staff concerned had no idea of the other lecturers’ arrangements. • A number of guest lectures were arranged on the same topic, thereby duplicating the content of a previous lecture. • Staff have independently invited speakers from the same company. • Staff members have contacted an organisation to ask if it would consider offering placement/workshop/ guest lecture etc, to find that the contact has already been approached and has turned down the request - so is annoyed that he/she is being targeted again. • Staff members wanted to re-run specific guest lectures in a subsequent year for a new cohort of students, but the staff member who had arranged the original lecture had left the university without leaving details of the contact. • Students have turned up to the staff room wanting to know where a lecture was being held. etc.. etc.. The school is very keen to set up a database as it feels that if everything is centrally stored it will be able eradicate such problems and to use the contacts to greater advantage, for example to see if a speaker (or someone within their organisation) would be interested in providing placements/job experience or live projects for students, as well as guest lectures. The Head of School hopes that a sensible timetable can be put together showing the guest lectures for the whole of a semester which students and teaching staff could access. He would also like to monitor attendance at each of the lectures/workshops and also to collect any positive or negative feedback from students to see how popular the talk has been, which might indicate whether to re-run a particular talk the following year. 5 The Head of Computing has suggested that, with a new system, teaching staff could put in requests for a guest lecture on a particular topic, and the system administrator might then be able to suggest a suitable external speaker for that topic from information held in the database. A small number of companies are already supplying ‘live’ projects to the department and the Head of School hopes that a lot more can be found. The details of these also need to be stored centrally, together with the member of staff who is running the live project. At present nobody knows who is doing what. The marketing manager for the school would also like to know about these live projects and their outcomes – if completed successfully, they could raise some good publicity for the university. The new system should have some mechanism for informing the marketing manager that the project has completed so that timely publicity materials can be produced. The Head of School would also like there to be a designated staff member for each organisation, responsible for nurturing and developing links with the organisation. Anyone wishing to contact a company would need to liaise with the designated staff contact person. Members of staff should have easy access to this information. The system should also be able to store a history of the contacts made with each company and the reason for that contact, which teaching staff could refer to. The placement officer for the school also wants to maintain a database of placement or job experience opportunities provided by organisations, and which students have been successful in getting these placements, so that these students could be invited to talk to the student cohort on their return from placement – again this is all part of getting students ready for the world of work. School administrators will also benefit from this as currently they often unaware of which students are doing placements. The new system will be able to clearly show which students are on placement and who their designated supervisor is at their placement company (which may be different for each student). The Head of School and administrator think that useful reports could be generated from the proposed database, for example to show how the school is interacting with businesses and the local community, which lecturer has made the most effort at developing links with industry (and who hasn’t bothered at all…), and many other outputs. All in all, the current system is a mess and you have been called in to sort it out. The above description is just a basic outline of some of the issues and problems. You can make any sensible assumptions to fill in any gaps. Good luck!
5f2dded89dd4f293497a3ad31fd09a02
{ "intermediate": 0.40573132038116455, "beginner": 0.41075167059898376, "expert": 0.18351702392101288 }
1,650
This is my current code for a card game. Edit the code in java so it can be used in an IDE software. Edit it so that the program looks something like this when played: “HighSum GAME ================================================================================ IcePeak, You have 100 chips -------------------------------------------------------------------------------- Game starts - Dealer shuffles deck. -------------------------------------------------------------------------------- Dealer dealing cards - ROUND 1 -------------------------------------------------------------------------------- Dealer <HIDDEN CARD> <Club 6> IcePeak <Diamond Ace> <Spade 6> Value:7 Player call, state bet: 10 IcePeak, You are left with 90 chips Bet on table : 20 -------------------------------------------------------------------------------- Dealer dealing cards - ROUND 2 -------------------------------------------------------------------------------- Dealer <HIDDEN CARD> <Club 6> <Diamond 9> IcePeak <Diamond Ace> <Spade 6> <Heart 7> Value:14 Dealer call, state bet: 10 Do you want to follow? [Y/N]: Y IcePeak, You are left with 80 chips Bet on table : 40 -------------------------------------------------------------------------------- Dealer dealing cards - ROUND 3 -------------------------------------------------------------------------------- Dealer <HIDDEN CARD> <Club 6> <Diamond 9> <Heart Ace> IcePeak <Diamond Ace> <Spade 6> <Heart 7> <Spade 9> Value:23 Page 4 Copyright SCIT, University of Wollongong, 2023 Do you want to [C]all or [Q]uit?: C Player call, state bet: 10 You are left with 70 chips Bet on table : 60 -------------------------------------------------------------------------------- Dealer dealing cards - ROUND 4 -------------------------------------------------------------------------------- Dealer <HIDDEN CARD> <Club 6> <Diamond 9> <Heart Ace> <Spade 2> IcePeak <Diamond Ace> <Spade 6> <Heart 7> <Spade 9> <Heart King> Value : 33 Do you want to [C]all or [Q]uit?: C Player call, state bet: 10 You are left with 60 chips Bet on table : 80 -------------------------------------------------------------------------------- Game End - Dealer reveal hidden cards -------------------------------------------------------------------------------- Dealer <Spade Ace> <Club 6> <Diamond 9> <Heart Ace> <Spade 2> Value : 19 IcePeak <Diamond Ace> <Spade 6> <Heart 7> <Spade 9> <Heart King> Value : 33 IcePeak Wins IcePeak, You have 140 chips Dealer shuffles used cards and place behind the deck. -------------------------------------------------------------------------------- Next Game? (Y/N) > Y” import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class HighSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(“HighSum GAME”); System.out.println(“================================================================================”); // Login system String username = “”; while (true) { System.out.print(“Enter your username: “); username = input.nextLine(); System.out.print(“Enter your password: “); String password = input.nextLine(); if (password.equals(“password”)) { System.out.println(username + “, You have 100 chips”); break; } else { System.out.println(“Incorrect username or password. Please try again.”); } } // Set initial chips to 100 int chips = 100; System.out.println(”--------------------------------------------------------------------------------”); System.out.println(“Game starts - Dealer shuffles deck.”); System.out.println(”--------------------------------------------------------------------------------”); int roundNumber = 1; while (true) { // Create deck of cards ArrayList<Card> deck = new ArrayList<Card>(); String[] suits = {“Hearts”, “Diamonds”, “Clubs”, “Spades”}; String[] ranks = {“Ace”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “Jack”, “Queen”, “King”}; for (String suit : suits) { for (String rank : ranks) { deck.add(new Card(suit, rank)); } } // Shuffle deck Collections.shuffle(deck); // Deal cards to players ArrayList<Card> playerHand = new ArrayList<Card>(); ArrayList<Card> dealerHand = new ArrayList<Card>(); playerHand.add(deck.get(0)); playerHand.add(deck.get(2)); dealerHand.add(deck.get(1)); dealerHand.add(deck.get(3)); // Print players’ hands System.out.println(“Dealer dealing cards - ROUND " + roundNumber); System.out.println(”--------------------------------------------------------------------------------“); System.out.println(“Dealer”); System.out.println(”<HIDDEN CARD> " + dealerHand.get(1)); System.out.println(username); System.out.println(playerHand.get(0) + " " + playerHand.get(1)); System.out.println("Value: " + (playerHand.get(0).getValue() + playerHand.get(1).getValue())); // Determine highest visible card and get the bet int bet = 0; if (playerHand.get(1).getValue() > dealerHand.get(1).getValue()) { System.out.print("Player call, state bet: "); bet = input.nextInt(); } else { System.out.println("Dealer call, state bet: “); bet = (int) (Math.random() * (chips / 2) + 1); System.out.println(bet); } // Update chips chips -= bet; System.out.println(username + “, You are left with " + chips + " chips”); System.out.println(“Bet on table : " + (bet * 2)); System.out.println(”================================================================================”); roundNumber++; } } } class Card { private String suit; private String rank; public Card(String suit, String rank) { this.suit = suit; this.rank = rank; } public String getSuit() { return suit; } public String getRank() { return rank; } public int getValue() { if (rank.equals(“Ace”)) { return 14; } else if (rank.equals(“King”)) { return 13; } else if (rank.equals(“Queen”)) { return 12; } else if (rank.equals(“Jack”)) { return 11; } else { return Integer.parseInt(rank); } } public String toString() { return rank + " of " + suit; } }
83270697cb85001f78137a37d82baef6
{ "intermediate": 0.3196535110473633, "beginner": 0.3635358512401581, "expert": 0.31681063771247864 }
1,651
Can you make some ASCII-art please?
3680e595edcddaaac634885c49b902c7
{ "intermediate": 0.41723397374153137, "beginner": 0.3355010449886322, "expert": 0.24726496636867523 }
1,652
In python, use machine learning to predict a 5x5 minesweeper game. You've data for the past 30 games and you need to predict x amount safe spots the user inputs, and you need to predict 3 possible mine locations. You got data for the past 30 games in a list, and each number presents an old bomb location. Your goal is to make this as accurate as possible and make it like really really accurate. Use deep learning for this. The data is: [4, 5, 6, 1, 7, 23, 3, 4, 6, 5, 11, 18, 3, 15, 22, 4, 9, 18, 4, 14, 24, 6, 9, 23, 8, 14, 18, 2, 5, 20, 2, 3, 15, 1, 6, 23, 2, 12, 18, 6, 13, 19, 6, 20, 23, 4, 11, 21, 3, 7, 8, 1, 6, 8, 17, 18, 20, 3, 8, 23, 14, 16, 17, 1, 22, 23, 1, 4, 8, 5, 8, 24, 13, 15, 17, 1, 5, 10, 7, 8, 9, 14, 18, 19, 9, 11, 17, 4, 6, 7]
30d392f889a7cd01f5e475852b79fe23
{ "intermediate": 0.15120835602283478, "beginner": 0.05466587468981743, "expert": 0.7941257953643799 }
1,653
Implement a task planning algorithm in python that creates a daily schedule based on priority and estimated completion time.
ba8714083cd857f36984c322c80efd73
{ "intermediate": 0.15346919000148773, "beginner": 0.0674540102481842, "expert": 0.7790768146514893 }
1,654
In python, use Monte-Carlo Tree Search (MCTS) to predict a 5x5 minesweeper game. You've data for the past 30 games and you need to predict x amount safe spots the user inputs, and you need to predict 3 possible mine locations. You got data for the past 30 games in a list, and each number presents an old bomb location. Your goal is to make this as accurate as possible and make it like really really accurate. The data is: [4, 5, 6, 1, 7, 23, 3, 4, 6, 5, 11, 18, 3, 15, 22, 4, 9, 18, 4, 14, 24, 6, 9, 23, 8, 14, 18, 2, 5, 20, 2, 3, 15, 1, 6, 23, 2, 12, 18, 6, 13, 19, 6, 20, 23, 4, 11, 21, 3, 7, 8, 1, 6, 8, 17, 18, 20, 3, 8, 23, 14, 16, 17, 1, 22, 23, 1, 4, 8, 5, 8, 24, 13, 15, 17, 1, 5, 10, 7, 8, 9, 14, 18, 19, 9, 11, 17, 4, 6, 7]
28bacaf1c8652cd3067a19fcdc927e80
{ "intermediate": 0.3158876895904541, "beginner": 0.14080753922462463, "expert": 0.5433048009872437 }
1,655
Develope for a match-3 game in unity c# the Chain Reaction Algorithm – This algorithm is responsible for triggering chain reactions when the matches are made. It involves detecting whether a match creates a new match by shifting the game pieces around.
4631a0bd2897911ffde3aa57c5084e16
{ "intermediate": 0.24308869242668152, "beginner": 0.07989419996738434, "expert": 0.6770171523094177 }
1,656
Develope for a match-3 game in unity c# the Chain Reaction Algorithm – This algorithm is responsible for triggering chain reactions when the matches are made. It involves detecting whether a match creates a new match by shifting the game pieces around.
a5e5420edfd44b9c0eb0f44a63b91c77
{ "intermediate": 0.24308869242668152, "beginner": 0.07989419996738434, "expert": 0.6770171523094177 }
1,657
Can you make some ASCII-art please?
ef2ccb07a296488a531df82647753162
{ "intermediate": 0.41723397374153137, "beginner": 0.3355010449886322, "expert": 0.24726496636867523 }
1,658
Fix the code by it's only showing 0 and not counting up to 5000 <template> <div> <span ref="countupElement">0</span> </div> </template> <script setup> import { ref, onMounted } from 'vue'; import { CountUp } from 'countup.js'; // Define a ref to hold the countup instance const countUpInstance = ref(null); onMounted(() => { // Get the DOM element to be animated using a ref const countupElement = refCountupElement.value; // Define the options for CountUp const options = { startVal: 0, // Starting value endVal: 1000, // Ending value duration: 2.5, // Animation duration in seconds /* Other options can be specified here, such as decimal places, formatting, easing functions, etc. */ }; // Create a new CountUp instance countUpInstance.value = new CountUp(countupElement, options.startVal, options.endVal, 0, options.duration, options); // Start the count-up animation countUpInstance.value.start(); }); // Expose the ref to the countup element const refCountupElement = ref(null); </script>
5a7ab9fb0ab8d1e3c45d283378e3b6ad
{ "intermediate": 0.48341649770736694, "beginner": 0.33405956625938416, "expert": 0.1825239211320877 }
1,659
Could you make a line drawing of a house but instead of drawing it, create a number of line-statements like this line(100,100,150,125) that forms the shape of a house?
b6634235a1927bc0cfa4871c8121069e
{ "intermediate": 0.36347976326942444, "beginner": 0.19645726680755615, "expert": 0.44006291031837463 }
1,660
In this problem, you are working in chemical sales, selling a compound that is used to make batteries. This compound requires a couple of ingredients, which has been stored in structure array "ingredients". You have also been storing some of your past compound orders in anothe rstructure array "orders", but you realize you never noted down how much of each ingredient you use. It is your task to dtermine whether you can solve for the amount of ingredients used for each order, and return the solution, if you can. "ingredients" is a structure array the following information (table) in each of its fields:  field                                 value price                     cost of buying this ingredient mass                     mass of this ingredient The structure array will contain "N" ingredients elements, all of which are used together to create a singular compound (e.g. if there are 2 elements in "ingredients", then they are used together to create 1 chemical compund) "order" contains information (table) about some orders you had for this chemical compound:  field                                value weight                  total mass of the order cost                      total cost of fulfilling the order This structure array contains 1 order for the compound created from combining all the ingredients. With the information you are given, construct a system with the following form: Ax=b where "x" is the amount of each ingredient that you used in the orders. You will try to solve for "x" in this problem. First, you must analyze the system to see what type of solution you will get. There are 3 possibilities: 'Unique', 'Infinite', and 'None'. Once you have determined this, assign this to "num_solutions", and proceed with solving the solution. Notice that "A\b" will still return some value for infinite and no solutions. Tips you have to use: "rref()" cannot be used in the solution in matlab. You are given the following code just fill it in:  function [num_solutions,solution] = analyzeSales(ingredients, order)         end
a4207a7dbf4a1755e503a1a9fd940971
{ "intermediate": 0.42286330461502075, "beginner": 0.24715806543827057, "expert": 0.32997867465019226 }
1,661
Find the subset sum using backtracking. S= {1, 3, 4, 5}, sum=8. Find the possible subsets of 'S' that sum to 'sum'.
301b0bdd07c2af6a4f496e1986704e79
{ "intermediate": 0.3045580983161926, "beginner": 0.2006109654903412, "expert": 0.4948309659957886 }
1,662
"import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class HighSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(“HighSum GAME”); System.out.println(“================================================================================”); // Login system String username = “”; while (true) { System.out.print(“Enter your username: “); username = input.nextLine(); System.out.print(“Enter your password: “); String password = input.nextLine(); if (password.equals(“password”)) { System.out.println(); System.out.println(“HighSum GAME”); System.out.println(”================================================================================”); System.out.println(username + “, You have 100 chips”); break; } else { System.out.println(“Incorrect username or password. Please try again.”); } } // Set initial chips to 100 int chips = 100; boolean keepPlaying = true; while (keepPlaying) { System.out.println(”--------------------------------------------------------------------------------”); System.out.println(“Game starts - Dealer shuffles deck.”); System.out.println(“--------------------------------------------------------------------------------”); chips = playRound(username, chips, input); System.out.println(“--------------------------------------------------------------------------------”); System.out.print(“Next Game? (Y/N) > “); String nextGame = input.next(); keepPlaying = nextGame.equalsIgnoreCase(“Y”); if (keepPlaying) { chips = 100; } } input.close(); } static int playRound(String username, int chips, Scanner input) { int roundNumber = 1; int currentBet = 0; boolean quit = false; // Create and shuffle deck ArrayList<Card> deck = new ArrayList<Card>(); String[] suits = {“Hearts”, “Diamonds”, “Clubs”, “Spades”}; String[] ranks = {“Ace”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “Jack”, “Queen”, “King”}; for (String suit : suits) { for (String rank : ranks) { deck.add(new Card(suit, rank)); } } Collections.shuffle(deck); // Deal cards to players ArrayList<Card> playerHand = new ArrayList<Card>(); ArrayList<Card> dealerHand = new ArrayList<Card>(); while (roundNumber <= 4 && !quit) { System.out.println(“Dealer dealing cards - ROUND " + roundNumber); System.out.println(”--------------------------------------------------------------------------------”); // Add cards playerHand.add(deck.remove(0)); dealerHand.add(deck.remove(0)); // Print players’ hands System.out.println(“Dealer”); if (roundNumber == 1) { System.out.print(”<HIDDEN CARD> “); } else { System.out.print(”<" + dealerHand.get(0) + “> “); } for (int i = 1; i < dealerHand.size(); i++) { System.out.print(”<” + dealerHand.get(i) + “> “); } System.out.println(); System.out.println(username); for (Card card : playerHand) { System.out.print(”<” + card + "> "); } System.out.println(); System.out.println("Value: " + playerHand.stream().mapToInt(Card::getValue).sum()); // Bet boolean playerHasHigherCard = playerHand.get(playerHand.size() - 1).getValue() > dealerHand.get(dealerHand.size() - 1).getValue(); if ((roundNumber == 1 && playerHasHigherCard) || roundNumber > 1) { if (roundNumber == 1) { System.out.print("Do you want to follow? [Y/N]: "); String follow = input.next(); if (follow.equalsIgnoreCase(“Y”)) { System.out.print("Player call, state bet: "); currentBet = input.nextInt(); if (currentBet > 10) { System.out.println(“Maximum Bet is 10 chips”); currentBet = 10; } } else { quit = true; } } else { System.out.print(“Do you want to [C]all or [Q]uit?: “); String callOrQuit = input.next(); if (callOrQuit.equalsIgnoreCase(“Q”)) { quit = true; } } } else if (roundNumber == 1) { System.out.print(“Dealer call, state bet: “); currentBet = (int) (Math.random() * (chips / 2) + 1); if (currentBet > 10) { currentBet = 10; } System.out.println(currentBet); } if (quit) { chips -= currentBet; System.out.println(username + “, You are left with " + chips + " chips”); System.out.println(“Bet on table : " + (currentBet * 2)); System.out.println(“Dealer Wins”); return chips; } chips -= currentBet; System.out.println(username + “, You are left with " + chips + " chips”); System.out.println(“Bet on table : " + (currentBet * 2 * roundNumber)); System.out.println(”--------------------------------------------------------------------------------”); roundNumber++; } if (!quit) { System.out.println(“Game End - Dealer reveal hidden cards”); System.out.println(”--------------------------------------------------------------------------------”); // Reveal dealer’s hand System.out.println(“Dealer”); for (Card card : dealerHand) { System.out.print(”<” + card + “> “); } System.out.println(); System.out.println(“Value : " + dealerHand.stream().mapToInt(Card::getValue).sum()); // Compare player and dealer values int playerValue = playerHand.stream().mapToInt(Card::getValue).sum(); int dealerValue = dealerHand.stream().mapToInt(Card::getValue).sum(); if (playerValue > dealerValue) { System.out.println(username + " Wins”); chips += (currentBet * 2 * (roundNumber - 1)); } else { System.out.println(“Dealer Wins”); } System.out.println(username + “, You have " + chips + " chips”); System.out.println(“Dealer shuffles used cards and place behind the deck.”); System.out.println(”--------------------------------------------------------------------------------”); } return chips; } } class Card { private String suit; private String rank; public Card(String suit, String rank) { this.suit = suit; this.rank = rank; } public String getSuit() { return suit; } public String getRank() { return rank; } public int getValue() { if (rank.equals(“Ace”)) { return 14; } else if (rank.equals(“King”)) { return 13; } else if (rank.equals(“Queen”)) { return 12; } else if (rank.equals(“Jack”)) { return 11; } else { return Integer.parseInt(rank); } } public String toString() { return rank + " of " + suit; } } for round 1 “Do you want to follow? [Y/N]:” is not needed. Display current amount bet by player or dealer depending whose most recent card is bigger by displaying “Dealer/Player call, state bet:”. Ask for betting input after player calls if the player’s most recent card is bigger than the dealer. Remove max bet. Chips bet cannot be negative. If chips are insufficient, notify the player and display message “Chips insufficient” and let the player enter bet again. import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class HighSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(“HighSum GAME”); System.out.println(“================================================================================”); // Login system String username = “”; while (true) { System.out.print(“Enter your username: “); username = input.nextLine(); System.out.print(“Enter your password: “); String password = input.nextLine(); if (password.equals(“password”)) { System.out.println(); System.out.println(“HighSum GAME”); System.out.println(”================================================================================”); System.out.println(username + “, You have 100 chips”); break; } else { System.out.println(“Incorrect username or password. Please try again.”); } } // Set initial chips to 100 int chips = 100; boolean keepPlaying = true; while (keepPlaying) { System.out.println(”--------------------------------------------------------------------------------”); System.out.println(“Game starts - Dealer shuffles deck.”); System.out.println(“--------------------------------------------------------------------------------”); chips = playRound(username, chips, input); System.out.println(“--------------------------------------------------------------------------------”); System.out.print(“Next Game? (Y/N) > “); String nextGame = input.next(); keepPlaying = nextGame.equalsIgnoreCase(“Y”); if (keepPlaying) { chips = 100; } } input.close(); } static int playRound(String username, int chips, Scanner input) { int roundNumber = 1; int currentBet = 0; boolean quit = false; // Create and shuffle deck ArrayList<Card> deck = new ArrayList<Card>(); String[] suits = {“Hearts”, “Diamonds”, “Clubs”, “Spades”}; String[] ranks = {“Ace”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “Jack”, “Queen”, “King”}; for (String suit : suits) { for (String rank : ranks) { deck.add(new Card(suit, rank)); } } Collections.shuffle(deck); // Deal cards to players ArrayList<Card> playerHand = new ArrayList<Card>(); ArrayList<Card> dealerHand = new ArrayList<Card>(); while (roundNumber <= 4 && !quit) { System.out.println(“Dealer dealing cards - ROUND " + roundNumber); System.out.println(”--------------------------------------------------------------------------------”); // Add cards playerHand.add(deck.remove(0)); dealerHand.add(deck.remove(0)); // Print players’ hands System.out.println(“Dealer”); if (roundNumber == 1) { System.out.print(”<HIDDEN CARD> “); } else { System.out.print(”<" + dealerHand.get(0) + “> “); } for (int i = 1; i < dealerHand.size(); i++) { System.out.print(”<” + dealerHand.get(i) + “> “); } System.out.println(); System.out.println(username); for (Card card : playerHand) { System.out.print(”<” + card + "> "); } System.out.println(); System.out.println("Value: " + playerHand.stream().mapToInt(Card::getValue).sum()); // Bet boolean playerHasHigherCard = playerHand.get(playerHand.size() - 1).getValue() > dealerHand.get(dealerHand.size() - 1).getValue(); if (roundNumber == 1) { if (playerHasHigherCard) { System.out.print("Player call, state bet: "); while (true) { currentBet = input.nextInt(); if (currentBet > chips) { System.out.println(“Chips insufficient”); System.out.print("Player call, state bet: "); } else if (currentBet < 0) { System.out.println(“Chips cannot be negative”); System.out.print("Player call, state bet: "); } else { break; } } } else { System.out.print(“Dealer call, state bet: “); currentBet = (int) (Math.random() * (chips / 2) + 1); System.out.println(currentBet); } } else { System.out.print(“Do you want to [C]all or [Q]uit?: “); String callOrQuit = input.next(); if (callOrQuit.equalsIgnoreCase(“Q”)) { quit = true; } } if (quit) { chips -= currentBet; System.out.println(username + “, You are left with " + chips + " chips”); System.out.println(“Bet on table : " + (currentBet * 2)); System.out.println(“Dealer Wins”); return chips; } chips -= currentBet; System.out.println(username + “, You are left with " + chips + " chips”); System.out.println(“Bet on table : " + (currentBet * 2 * roundNumber)); System.out.println(”--------------------------------------------------------------------------------”); roundNumber++; } if (!quit) { System.out.println(“Game End - Dealer reveal hidden cards”); System.out.println(”--------------------------------------------------------------------------------”); // Reveal dealer’s hand System.out.println(“Dealer”); for (Card card : dealerHand) { System.out.print(”<” + card + “> “); } System.out.println(); System.out.println(“Value : " + dealerHand.stream().mapToInt(Card::getValue).sum()); // Compare player and dealer values int playerValue = playerHand.stream().mapToInt(Card::getValue).sum(); int dealerValue = dealerHand.stream().mapToInt(Card::getValue).sum(); if (playerValue > dealerValue) { System.out.println(username + " Wins”); chips += (currentBet * 2 * (roundNumber - 1)); } else { System.out.println(“Dealer Wins”); } System.out.println(username + “, You have " + chips + " chips”); System.out.println(“Dealer shuffles used cards and place behind the deck.”); System.out.println(”--------------------------------------------------------------------------------”); } return chips; } } class Card { private String suit; private String rank; public Card(String suit, String rank) { this.suit = suit; this.rank = rank; } public String getSuit() { return suit; } public String getRank() { return rank; } public int getValue() { if (rank.equals(“Ace”)) { return 14; } else if (rank.equals(“King”)) { return 13; } else if (rank.equals(“Queen”)) { return 12; } else if (rank.equals(“Jack”)) { return 11; } else { return Integer.parseInt(rank); } } public String toString() { return rank + " of " + suit; } } add state bet to each round and allow player to bet after calling if their card is bigger than dealer’s. Round 1 starts with 2 cards, only 1 of the dealer’s card is Hidden, player’s card is shown as normal. import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class HighSum { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println(“HighSum GAME”); System.out.println(“================================================================================”); // Login system String username = “”; while (true) { System.out.print(“Enter your username: “); username = input.nextLine(); System.out.print(“Enter your password: “); String password = input.nextLine(); if (password.equals(“password”)) { System.out.println(); System.out.println(“HighSum GAME”); System.out.println(”================================================================================”); System.out.println(username + “, You have 100 chips”); break; } else { System.out.println(“Incorrect username or password. Please try again.”); } } // Set initial chips to 100 int chips = 100; boolean keepPlaying = true; while (keepPlaying) { System.out.println(”--------------------------------------------------------------------------------”); System.out.println(“Game starts - Dealer shuffles deck.”); System.out.println(“--------------------------------------------------------------------------------”); chips = playRound(username, chips, input); System.out.println(“--------------------------------------------------------------------------------”); System.out.print(“Next Game? (Y/N) > “); String nextGame = input.next(); keepPlaying = nextGame.equalsIgnoreCase(“Y”); if (keepPlaying) { chips = 100; } } input.close(); } static int playRound(String username, int chips, Scanner input) { int roundNumber = 1; int currentBet = 0; boolean quit = false; // Create and shuffle deck ArrayList<Card> deck = new ArrayList<Card>(); String[] suits = {“Hearts”, “Diamonds”, “Clubs”, “Spades”}; String[] ranks = {“Ace”, “2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “Jack”, “Queen”, “King”}; for (String suit : suits) { for (String rank : ranks) { deck.add(new Card(suit, rank)); } } Collections.shuffle(deck); // Deal cards to players ArrayList<Card> playerHand = new ArrayList<Card>(); ArrayList<Card> dealerHand = new ArrayList<Card>(); // Initial deal: 2 cards for each player playerHand.add(deck.remove(0)); dealerHand.add(deck.remove(0)); playerHand.add(deck.remove(0)); dealerHand.add(deck.remove(0)); while (roundNumber <= 4 && !quit) { System.out.println(“Dealer dealing cards - ROUND " + roundNumber); System.out.println(”--------------------------------------------------------------------------------”); if (roundNumber > 1) { // Add cards playerHand.add(deck.remove(0)); dealerHand.add(deck.remove(0)); } // Print players’ hands System.out.println(“Dealer”); if (roundNumber == 1) { System.out.print(”<HIDDEN CARD> “); System.out.print(”<" + dealerHand.get(1) + “> “); } else { for (Card card : dealerHand) { System.out.print(”<” + card + “> “); } } System.out.println(); System.out.println(username); for (Card card : playerHand) { System.out.print(”<” + card + "> "); } System.out.println(); System.out.println("Value: " + playerHand.stream().mapToInt(Card::getValue).sum()); // Bet boolean playerHasHigherCard = playerHand.get(playerHand.size() - 1).getValue() > dealerHand.get(dealerHand.size() - 1).getValue(); if (playerHasHigherCard) { System.out.print("Player call, state bet: "); while (true) { currentBet = input.nextInt(); if (currentBet > chips) { System.out.println(“Chips insufficient”); System.out.print("Player call, state bet: "); } else if (currentBet < 0) { System.out.println(“Chips cannot be negative”); System.out.print("Player call, state bet: "); } else { break; } } } else { System.out.print(“Dealer call, state bet: “); currentBet = (int) (Math.random() * (chips / 2) + 1); System.out.println(currentBet); } System.out.print(“Do you want to [C]all or [Q]uit?: “); String callOrQuit = input.next(); if (callOrQuit.equalsIgnoreCase(“Q”)) { quit = true; } if (quit) { chips -= currentBet; System.out.println(username + “, You are left with " + chips + " chips”); System.out.println(“Bet on table : " + (currentBet * 2)); System.out.println(“Dealer Wins”); return chips; } chips -= currentBet; System.out.println(username + “, You are left with " + chips + " chips”); System.out.println(“Bet on table : " + (currentBet * 2 * roundNumber)); System.out.println(”--------------------------------------------------------------------------------”); roundNumber++; } if (!quit) { System.out.println(“Game End - Dealer reveal hidden cards”); System.out.println(”--------------------------------------------------------------------------------”); // Reveal dealer’s hand System.out.println(“Dealer”); for (Card card : dealerHand) { System.out.print(”<” + card + “> “); } System.out.println(); System.out.println(“Value : " + dealerHand.stream().mapToInt(Card::getValue).sum()); // Compare player and dealer values int playerValue = playerHand.stream().mapToInt(Card::getValue).sum(); int dealerValue = dealerHand.stream().mapToInt(Card::getValue).sum(); if (playerValue > dealerValue) { System.out.println(username + " Wins”); chips += (currentBet * 2 * (roundNumber - 1)); } else { System.out.println(“Dealer Wins”); } System.out.println(username + “, You have " + chips + " chips”); System.out.println(“Dealer shuffles used cards and place behind the deck.”); System.out.println(”--------------------------------------------------------------------------------”); } return chips; } } class Card { private String suit; private String rank; public Card(String suit, String rank) { this.suit = suit; this.rank = rank; } public String getSuit() { return suit; } public String getRank() { return rank; } public int getValue() { if (rank.equals(“Ace”)) { return 14; } else if (rank.equals(“King”)) { return 13; } else if (rank.equals(“Queen”)) { return 12; } else if (rank.equals(“Jack”)) { return 11; } else { return Integer.parseInt(rank); } } public String toString() { return rank + " of " + suit; } }" Ask player to call or quit before asking state bet. Dealer same as player in the whole game cannot spend past 100 chips in bets. Dealer's hidden card is hidden during the game and is only revealed after round 4 when the game ends.
05d08edde770971a19b44cbffc99f86d
{ "intermediate": 0.2904307246208191, "beginner": 0.47403258085250854, "expert": 0.23553673923015594 }
1,663
In this problem, we are going to obtain the best fit regression model by comparing non-linear model with linear models of varying order using least-squares criterion.  Linear model: y=(a_m)x^m+(a_m-1)x^(m-1)+a1x+a0 Non-linear model: y=ce^bx For the function "regression", there are three inputs: "xval", y_val", and "m", which is the maximum order of the linear model. You need to find the best model among linear models (of different orders from 1 to "m") and non-linear model based on the least value of "RMSE", which is defined as:  RMSE=sqrt(1/n*summation i=1 ((y^i)-yi)^2) where (y^i) is the estimation of of y. For example: if 2nd order linear model is the best fit (having the least value of RMSE) then the output variable "best_fit" = 'linear-2'.You have to describe different models in the structure array "details" and plot both models along with the given data to visualize the best fit model. For better understanding, see the given test case. Tips you have to use: Your function should work on any set of data in the appropriate format. For the non-linear model, the relationship between "x" and "y" can be linearized by taking the logarithmic on both sides: logy=logc+bx. But "details(2).coefs" must contain the values of "b" and "c" respectively. For the "coefs" field in case of linear models, arrange the coefficients of each models such that the coefficients of higher order terms should come first.You can use "sprintf()" function. Test case:  xval = 1:5; yval = exp(xval); m = 2; [fig, best_fit, details] = regression(xval, yval, m) fig =  Figure (1) with properties:  Number: 1 Name: ' ' Color: [0.9400 0.9400 0.9400] Position: [488 342 560 420] Units 'pixels' best_fit =  "non-linear" details =  1x2 struct array with fields:  model  order coefs RMSE details(1) ans =  struct with fields:  model: 'linear' order: [1 2] coefs: {2x1 cell} RMSE: [25.0243 7.3614] details(2) ans =  struct with fields:  model: 'non-linear' order: 'n/a' coefs: [1.0000 1] RMSE: 7.2292e-16  details(1).coefs ans =  2x1 cell array {[33.8599  -54.9388]} {[14.2932  -51.8992  45.1135]} You are given the following code in matlab just fill it in:  function [fig, best_fit, details] = regression(xval, yval, m)   % Linear model % Non-linear model   % RMSE comparison   fig = figure;   xvals = linspace(min(xval),max(xval),50); % use this array to predict y for plotting % follow the order: raw data, linear-1, linear-2, ...., linear-m, non-linear axis([min(xval) max(xval) min(yval) max(yval)]) % axis limits end
8590165934d8ac25b9de7e318cfef01d
{ "intermediate": 0.18907047808170319, "beginner": 0.6860057711601257, "expert": 0.12492378056049347 }
1,664
How can I add inertia to character movement in Unity using C#?
db57e692b00a476a275ca9dfe9a4d17b
{ "intermediate": 0.6132129430770874, "beginner": 0.19616548717021942, "expert": 0.19062158465385437 }
1,665
can you teach me to code?
f7a7c14e781643bc5e4e6ac23582b260
{ "intermediate": 0.2747616469860077, "beginner": 0.30260714888572693, "expert": 0.422631174325943 }
1,666
make the following changes to this HTML and CSS files: remove the title from every html page instead make the header format be Logo(left side)------Title Page (in the centre)--------navigation bar(left) make the changes so that they look equally spaced, also make sure you change the fact that in the header navigation bar is a row under the title also this is where you can find my logo it is in svg C:\Users\Kaddra52\Desktop\DDW\assets\images\logo.svg index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style/style.css" /> <title>Camping Equipment - Retail Camping Company</title> </head> <body> <header> <h1>Retail Camping Company</h1> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="camping-equipment.html">Camping Equipment</a></li> <li><a href="furniture.html">Furniture</a></li> <li><a href="reviews.html">Reviews</a></li> <li><a href="basket.html">Basket</a></li> <li><a href="offers-and-packages.html">Offers and Packages</a></li> </ul> </nav> </header> <!-- Camping Equipment Page --> <main> <section> <h2>Camping Equipment</h2> <div class="catalog"> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Camping Tent"> <h3>Camping Tent</h3> <p>$199.99</p> <button>Add to Basket</button> </div> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Camping Cooker"> <h3>Camping Cooker</h3> <p>$49.99</p> <button>Add to Basket</button> </div> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Camping Lantern"> <h3>Camping Lantern</h3> <p>$29.99</p> <button>Add to Basket</button> </div> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Sleeping Bag"> <h3>Sleeping Bag</h3> <p>$89.99</p> <button>Add to Basket</button> </div> </div> </section> </main> <footer> <p>Follow us on social media:</p> <ul> <li><a href="https://www.facebook.com">Facebook</a></li> <li><a href="https://www.instagram.com">Instagram</a></li> <li><a href="https://www.twitter.com">Twitter</a></li> </ul> </footer> </body> </html> camping-equipment.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style/style.css" /> <title>Camping Equipment - Retail Camping Company</title> </head> <body> <header> <h1>Retail Camping Company</h1> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="camping-equipment.html">Camping Equipment</a></li> <li><a href="furniture.html">Furniture</a></li> <li><a href="reviews.html">Reviews</a></li> <li><a href="basket.html">Basket</a></li> <li><a href="offers-and-packages.html">Offers and Packages</a></li> </ul> </nav> </header> <!-- Camping Equipment Page --> <main> <section> <h2>Camping Equipment</h2> <div class="catalog"> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Camping Tent"> <h3>Camping Tent</h3> <p>$199.99</p> <button>Add to Basket</button> </div> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Camping Cooker"> <h3>Camping Cooker</h3> <p>$49.99</p> <button>Add to Basket</button> </div> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Camping Lantern"> <h3>Camping Lantern</h3> <p>$29.99</p> <button>Add to Basket</button> </div> <!-- Sample catalog item --> <div class="catalog-item"> <img src="https://via.placeholder.com/200x200" alt="Sleeping Bag"> <h3>Sleeping Bag</h3> <p>$89.99</p> <button>Add to Basket</button> </div> </div> </section> </main> <footer> <p>Follow us on social media:</p> <ul> <li><a href="https://www.facebook.com">Facebook</a></li> <li><a href="https://www.instagram.com">Instagram</a></li> <li><a href="https://www.twitter.com">Twitter</a></li> </ul> </footer> </body> </html> CSS: html, body, h1, h2, h3, h4, p, a, ul, li, div, main, header, section, footer, img { margin: 0; padding: 0; border: 0; font-size: 100%; font-family: inherit; vertical-align: baseline; box-sizing: border-box; } body { font-family: Arial, sans-serif; line-height: 1.5; background: #f1f1f1; color: #333; width: 100%; margin: 0; padding: 0; min-height: 100vh; flex-direction: column; display: flex; } header { background: #32612D; padding: 0.5rem 2rem; } main{ flex-grow: 1; } h1 { color: #fff; margin-right: 2rem; } .nav-container { display: flex; justify-content: flex-end; align-items: center; } nav ul { display: inline; list-style: none; } nav ul li { display: inline; margin-left: 1rem; } nav ul li a { text-decoration: none; color: #fff; } nav ul li a:hover { color: #b3b3b3; } .slideshow-container { width: 100%; position: relative; margin: 1rem 0; } .mySlides { display: none; } .mySlides img { width: 100%; height: auto; } .special-offers-container { display: flex; justify-content: space-around; align-items: center; flex-wrap: wrap; margin: 1rem 0; } .special-offer { width: 200px; padding: 1rem; text-align: center; margin: 1rem; background-color: #ADC3AB; border-radius: 5px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; } .special-offer:hover { box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); transform: translateY(-5px); } .special-offer img { width: 100%; height: auto; margin-bottom: 0.5rem; border-radius: 5px; } .modal { display: none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1; overflow: auto; } .modal-content { background-color: #fefefe; padding: 2rem; margin: 10% auto; width: 30%; min-width: 300px; max-width: 80%; text-align: center; border-radius: 5px; box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); } .close { display: block; text-align: right; font-size: 2rem; color: #333; cursor: pointer; } footer { position: relative; bottom: 0px; background: #32612D; padding: 1rem; text-align: center; margin-top: auto; } footer p { color: #fff; margin-bottom: 1rem; } footer ul { list-style: none; } footer ul li { display: inline; margin: 0.5rem; } footer ul li a { text-decoration: none; color: #fff; } @media screen and (max-width: 768px) { .special-offers-container { flex-direction: column; } } @media screen and (max-width: 480px) { header { text-align: center; } h1 { display: block; margin-bottom: 1rem; } } .catalog { display: flex; flex-wrap: wrap; justify-content: center; margin: 2rem 0; } .catalog-item { width: 200px; padding: 1rem; margin: 1rem; background-color: #ADC3AB; border-radius: 5px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); text-align: center; } .catalog-item:hover { box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); } .catalog-item img { width: 100%; height: auto; margin-bottom: 0.5rem; border-radius: 5px; } .catalog-item h3 { margin-bottom: 0.5rem; } .catalog-item p { margin-bottom: 0.5rem; } .catalog-item button { background-color: #32612D; color: #fff; padding: 0.5rem; border: none; border-radius: 5px; cursor: pointer; } .catalog-item button:hover { background-color: #ADC3AB; }
db20ebbe30135399550ab2e841c3be0d
{ "intermediate": 0.3001039922237396, "beginner": 0.37746790051460266, "expert": 0.3224281072616577 }
1,667
In this problem, we are going to obtain the best fit regression model by comparing non-linear model with linear models of varying order using least-squares criterion.  Linear model: y=(a_m)x^m+(a_m-1)x^(m-1)+a1x+a0 Non-linear model: y=ce^bx For the function "regression", there are three inputs: "xval", y_val", and "m", which is the maximum order of the linear model. You need to find the best model among linear models (of different orders from 1 to "m") and non-linear model based on the least value of "RMSE", which is defined as:  RMSE=sqrt(1/n*summation i=1 ((y^i)-yi)^2) where (y^i) is the estimation of of y. For example: if 2nd order linear model is the best fit (having the least value of RMSE) then the output variable "best_fit" = 'linear-2'.You have to describe different models in the structure array "details" and plot both models along with the given data to visualize the best fit model. For better understanding, see the given test case. Tips you have to use: Your function should work on any set of data in the appropriate format. For the non-linear model, the relationship between "x" and "y" can be linearized by taking the logarithmic on both sides: logy=logc+bx. But "details(2).coefs" must contain the values of "b" and "c" respectively. For the "coefs" field in case of linear models, arrange the coefficients of each models such that the coefficients of higher order terms should come first.You can use "sprintf()" function. Test case:  xval = 1:5; yval = exp(xval); m = 2; [fig, best_fit, details] = regression(xval, yval, m) fig =  Figure (1) with properties:  Number: 1 Name: ' ' Color: [0.9400 0.9400 0.9400] Position: [488 342 560 420] Units 'pixels' best_fit =  "non-linear" details =  1x2 struct array with fields:  model  order coefs RMSE details(1) ans =  struct with fields:  model: 'linear' order: [1 2] coefs: {2x1 cell} RMSE: [25.0243 7.3614] details(2) ans =  struct with fields:  model: 'non-linear' order: 'n/a' coefs: [1.0000 1] RMSE: 7.2292e-16  details(1).coefs ans =  2x1 cell array {[33.8599  -54.9388]} {[14.2932  -51.8992  45.1135]} You are given the following code in matlab just fill it in:  function [fig, best_fit, details] = regression(xval, yval, m)   % Linear model % Non-linear model   % RMSE comparison   fig = figure;   xvals = linspace(min(xval),max(xval),50); % use this array to predict y for plotting % follow the order: raw data, linear-1, linear-2, ...., linear-m, non-linear axis([min(xval) max(xval) min(yval) max(yval)]) % axis limits end  Here is the code I will use to call my function: xval = 1:5; yval = exp(xval); m=2; [fig, best_fit, details] = regression(xval, yval, m)
bf4be116651ebc90967442ca6a0c7939
{ "intermediate": 0.3285256028175354, "beginner": 0.4781613349914551, "expert": 0.19331315159797668 }
1,668
using Turings reaction diffusion model create a mathematical model for human population growth, where the reaction is population and the diffusion is information. When population increases then information increases then population increases. If population is approaching the carrying capacity then information increase causes slowing down of population increase
ac619f5f7b901e99dcb4e0dcaee522e3
{ "intermediate": 0.3915286958217621, "beginner": 0.2481931447982788, "expert": 0.3602781593799591 }
1,669
Hey
74de727ee90f575dacff8fe6d2eb0d32
{ "intermediate": 0.3360580503940582, "beginner": 0.274208664894104, "expert": 0.38973328471183777 }
1,670
Make a corporate compliance themed rap
7121386da7b0aaf0832722a7861854ab
{ "intermediate": 0.2882617115974426, "beginner": 0.45330432057380676, "expert": 0.2584339678287506 }
1,671
in this css, my background image is not appearing can you fix it given that this is the full directory of where it is C:\Users\Kaddra52\Desktop\DDW\assets\images\cover.jpg my css: html, body, h1, h2, h3, h4, p, a, ul, li, div, main, header, section, footer, img { margin: 0; padding: 0; border: 0; font-size: 100%; font-family: inherit; vertical-align: baseline; box-sizing: border-box; } body { font-family: 'Cabin', sans-serif; line-height: 1.5; color: #333; width: 100%; margin: 0; padding: 0; min-height: 100vh; flex-direction: column; display: flex; background-image: ("assets/images/cover.jpg"); background-size: cover; } header { background: #FFFFFF; padding: 0.5rem 2rem; text-align: center; color: #32612D; } main{ flex-grow: 1; } .nav-container { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; } .logo { width: 50px; height: auto; margin-right: 1rem; } h1 { flex-grow: 1; text-align: center; } nav ul { display: inline; list-style: none; } nav ul li { display: inline; margin-left: 1rem; } nav ul li a { text-decoration: none; color: #32612D; } nav ul li a:hover { color: #000000; } @media screen and (max-width: 768px) { .nav-container { flex-direction: column; } h1 { margin-bottom: 1rem; } } .slideshow-container { width: 100%; position: relative; margin: 1rem 0; } .mySlides { display: none; } .mySlides img { width: 100%; height: auto; } .special-offers-container { display: flex; justify-content: space-around; align-items: center; flex-wrap: wrap; margin: 1rem 0; } .special-offer { width: 200px; padding: 1rem; text-align: center; margin: 1rem; background-color: #ADC3AB; border-radius: 5px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; } .special-offer:hover { box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); transform: translateY(-5px); } .special-offer img { width: 100%; height: auto; margin-bottom: 0.5rem; border-radius: 5px; } .modal { display: none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1; overflow: auto; } .modal-content { background-color: #fefefe; padding: 2rem; margin: 10% auto; width: 30%; min-width: 300px; max-width: 80%; text-align: center; border-radius: 5px; box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); } .close { display: block; text-align: right; font-size: 2rem; color: #333; cursor: pointer; } footer { position: relative; bottom: 0px; background: #32612D; padding: 1rem; text-align: center; margin-top: auto; } footer p { color: #fff; margin-bottom: 1rem; } footer ul { list-style: none; } footer ul li { display: inline; margin: 0.5rem; } footer ul li a { text-decoration: none; color: #fff; } @media screen and (max-width: 768px) { .special-offers-container { flex-direction: column; } } @media screen and (max-width: 480px) { h1 { display: block; margin-bottom: 1rem; } } .catalog { display: flex; flex-wrap: wrap; justify-content: center; margin: 2rem 0; } .catalog-item { width: 200px; padding: 1rem; margin: 1rem; background-color: #ADC3AB; border-radius: 5px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); text-align: center; } .catalog-item:hover { box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); } .catalog-item img { width: 100%; height: auto; margin-bottom: 0.5rem; border-radius: 5px; } .catalog-item h3 { margin-bottom: 0.5rem; } .catalog-item p { margin-bottom: 0.5rem; } .catalog-item button { background-color: #32612D; color: #fff; padding: 0.5rem; border: none; border-radius: 5px; cursor: pointer; } .catalog-item button:hover { background-color: #ADC3AB; }
f3fa430a26c12f58bcc21ba39e6e1f06
{ "intermediate": 0.36069256067276, "beginner": 0.3817954659461975, "expert": 0.2575119435787201 }
1,672
given this is my html code and css instead of having the page name in the top right corner I want the logo in the top left corner. the logo is in assets/image.svg rewrite both html and css with the changes html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="style/style.css"> <title>RCC Home</title> </head> <body> <header> <h1><strong><div class = "title">Home</div></strong></h1> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="camping-equipment.html">Camping Equipment</a></li> <li><a href="furniture.html">Furniture</a></li> <li><a href="offers.html">Offers and Packages</a></li> <li><a href="reviews.html">Reviews</a></li> <li><a href="basket.html">Basket</a></li> </ul> </nav> </header> <br> <div class="container"> <div class="modal"> <form> <h2>Sign up for our newsletter</h2> <label>Name:</label> <input type="text" id="name"> <label>Email:</label> <input type="email" id="email"> <button type="submit" id="subscribe">Subscribe</button> </form> </div> <div class="image"> </div> </div> <footer> <ul> <li><a href="#">About Us</a></li> <li><a href="#">Contact Us</a></li> <li><a href="#">Privacy Policy</a></li> <li><a href="#">Terms and Conditions</a></li> </ul> <div class = "rights"> <p>&copy; RCC 2023. All rights reserved.</p> </div> <div class="social-media"> <a href="#"><img src="assets/fb.png" alt="Facebook"></a> <a href="#"><img src="assets/twitter.png" alt="Twitter"></a> <a href="#"><img src="assets/instagram.png" alt="Instagram"></a> </div> </div> </footer> </body> </html> css: * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: Arial, sans-serif; font-size: 16px; line-height: 1.5; background-color: #f5f5f5; display: flex; flex-direction: column; min-height: 100vh; } h1 { font-size: 36px; margin-bottom: 10px; } nav ul { display: flex; list-style: none; justify-content: center; margin-top: 20px; margin-bottom: 20px; } nav li { margin-right: 10px; } nav a { color: #555; text-decoration: none; padding: 10px; border-radius: 5px; } nav a:hover { background-color: #555; color: #fff; } #subscribe { background-color: #000; color: white; padding: 10px; cursor: pointer; } #news h3 { margin-bottom: 10px; } #news label { display: block; margin-bottom: 5px; } #news input { padding: 5px; border-radius: 5px; border: 1px solid #ddd; margin-bottom: 10px; } #news button { background-color: #000; color: #fff; border: none; padding: 10px; border-radius: 5px; cursor: pointer; } #news button:hover { background-color: #333; } #pic { background-image: url('assets/camping.jpeg'); height: 400px; background-size: cover; background-position: center; } .social-media { margin-bottom: 10px; } .social-media a { display: inline-block; margin-right: 10px; } .social-media img { height: 50px; } .rights { margin-top: 20px; text-align: center; } header { background-color: #1d1d1d; color: #fff; display: flex; justify-content: space-between; padding: 20px; } h1, h2, h3, h4, h5, h6 { margin: 0; } nav ul { display: flex; list-style: none; margin: 0; padding: 0; } nav ul li { margin-right: 20px; } nav ul li:last-child { margin-right: 0; } nav ul li a { color: #fff; text-decoration: none; } main { padding: 50px; flex-grow: 1; } .catalogue { display: grid; grid-template-columns: repeat(4, 1fr); gap: 30px; margin-top: 30px; } .product { border: 1px solid #ccc; padding: 20px; text-align: center; } .product h3 { margin-bottom: 10px; } .product p { color: #999; margin-bottom: 20px; } .product button { background-color: #000; border: none; color: #fff; padding: 10px 20px; cursor: pointer; } .product button:hover { background-color: #333; } footer { background-color: #1d1d1d; color: #fff; padding: 20px; display: flex; justify-content: space-between; align-items: center; margin-top: auto; } footer ul { display: flex; list-style: none; margin: 0; padding: 0; text-decoration: underline; } footer ul li { margin-right: 20px; } footer ul li:last-child { margin-right: 0; } footer ul li a { color: #fff; text-decoration: none; } .social-media { display: flex; justify-content: center; } .social-media img { margin: 0 10px; } .rights { text-align: center; } .search-container { display: flex; justify-content: center; margin-bottom: 30px; } .search-container input[type="text"] { padding: 10px; border: none; border-radius: 5px; margin-right: 10px; } .search-container button[type="submit"] { background-color: #1d1d1d; border: none; color: #fff; padding: 10px 20px; border-radius: 5px; transition: background-color 0.3s ease-in-out; } .search-container button[type="submit"]:hover { background-color: #000; } .search-container :hover{ cursor: pointer; } #name { padding: 5px; border-radius: 2px; } #email { padding: 5px; border-radius: 2px; } .offerscatalogue { display: grid; grid-template-columns: repeat(3, 1fr); gap: 30px; margin-top: 30px; margin-left: 5px; margin-right: 5px; } textarea { resize: none; } form { text-align: center; } main { text-align: center; } span{ font-weight: bold; }
be7b5cbc519ffb1dc51940cd08bbe50f
{ "intermediate": 0.3084753453731537, "beginner": 0.4768390953540802, "expert": 0.21468551456928253 }
1,673
given that this is my css and html, add a small hover animation that quickly draws a line under what is being hovered over in the navigation bard: HTML: <!DOCTYPE html> <html lang=:"en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cabin:wght@400;700&display=swap"> <link rel="stylesheet" href="style/style.css" /> <title>Camping Equipment - Retail Camping Company</title> </head> <body> <header> <div class="nav-container"> <img src="C:/Users/Kaddra52/Desktop/DDW/assets/images/logo.svg" alt="Logo" class="logo"> <h1>Retail Camping Company</h1> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="camping-equipment.html">Camping Equipment</a></li> <li><a href="furniture.html">Furniture</a></li> <li><a href="reviews.html">Reviews</a></li> <li><a href="basket.html">Basket</a></li> <li><a href="offers-and-packages.html">Offers and Packages</a></li> </ul> </nav> </div> </header> <!-- Home Page --> <main> <section> <!-- Insert slide show here --> <div class="slideshow-container"> <div class="mySlides"> <img src="https://via.placeholder.com/600x400" alt="Tents" style="width:100%"> </div> <div class="mySlides"> <img src="https://via.placeholder.com/600x400" alt="Cookers" style="width:100%"> </div> <div class="mySlides"> <img src="https://via.placeholder.com/600x400" alt="Camping Gear" style="width:100%"> </div> </div> </section> <section> <!-- Display special offers and relevant images --> <div class="special-offers-container"> <div class="special-offer"> <img src="https://via.placeholder.com/200x200" alt="Tent Offer"> <p>20% off premium tents!</p> </div> <div class="special-offer"> <img src="https://via.placeholder.com/200x200" alt="Cooker Offer"> <p>Buy a cooker, get a free utensil set!</p> </div> <div class="special-offer"> <img src="https://via.placeholder.com/200x200" alt="Furniture Offer"> <p>Save on camping furniture bundles!</p> </div> </div> </section> <section class="buts"> <!-- Modal pop-up window content here --> <button id="modalBtn">Special Offer!</button> <div id="modal" class="modal"> <div class="modal-content"> <span class="close">×</span> <p>Sign up now and receive 10% off your first purchase!</p> </div> </div> </section> </main> <footer> <p>Follow us on social media:</p> <ul> <li><a href="https://www.facebook.com">Facebook</a></li> <li><a href="https://www.instagram.com">Instagram</a></li> <li><a href="https://www.twitter.com">Twitter</a></li> </ul> </footer> <script> // Get modal element var modal = document.getElementById('modal'); // Get open model button var modalBtn = document.getElementById('modalBtn'); // Get close button var closeBtn = document.getElementsByClassName('close')[0]; // Listen for open click modalBtn.addEventListener('click', openModal); // Listen for close click closeBtn.addEventListener('click', closeModal); // Listen for outside click window.addEventListener('click', outsideClick); // Function to open modal function openModal() { modal.style.display = 'block'; } // Function to close modal function closeModal() { modal.style.display = 'none'; } // Function to close modal if outside click function outsideClick(e) { if (e.target == modal) { modal.style.display = 'none'; } } </script> </body> </html> CSS: html, body, h1, h2, h3, h4, p, a, ul, li, div, main, header, section, footer, img { margin: 0; padding: 0; border: 0; font-size: 100%; font-family: inherit; vertical-align: baseline; box-sizing: border-box; } body { font-family: 'Cabin', sans-serif; line-height: 1.5; color: #333; width: 100%; margin: 0; padding: 0; min-height: 100vh; flex-direction: column; display: flex; background-image: url("../assets/images/cover.jpg"); background-size: cover; } header { background: #00000000; padding: 0.5rem 2rem; text-align: center; color: #32612D; font-size: 1.2rem; } main{ flex-grow: 1; } .nav-container { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; } .logo { width: 50px; height: auto; margin-right: 1rem; } h1 { flex-grow: 1; text-align: left; } nav ul { display: inline; list-style: none; } nav ul li { display: inline; margin-left: 1rem; } nav ul li a { text-decoration: none; color: #32612D; } nav ul li a:hover { color: #000000; } @media screen and (max-width: 768px) { .nav-container { flex-direction: column; } h1 { margin-bottom: 1rem; } } .slideshow-container { width: 100%; position: relative; margin: 1rem 0; } .mySlides { display: none; } .mySlides img { width: 100%; height: auto; } .special-offers-container { display: flex; justify-content: space-around; align-items: center; flex-wrap: wrap; margin: 1rem 0; } .special-offer { width: 200px; padding: 1rem; text-align: center; margin: 1rem; background-color: #ADC3AB; border-radius: 5px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); transition: all 0.3s ease; } .special-offer:hover { box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); transform: translateY(-5px); } .special-offer img { width: 100%; height: auto; margin-bottom: 0.5rem; border-radius: 5px; } .modal { display: none; position: fixed; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1; overflow: auto; align-items: center; } .modal-content { background-color: #fefefe; padding: 2rem; margin: 10% auto; width: 30%; min-width: 300px; max-width: 80%; text-align: center; border-radius: 5px; box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1); } .buts{ text-align: center; } .close { display: block; text-align: right; font-size: 2rem; color: #333; cursor: pointer; } footer { position: relative; bottom: 0px; background: #32612D; padding: 1rem; text-align: center; margin-top: auto; } footer p { color: #fff; margin-bottom: 1rem; } footer ul { list-style: none; } footer ul li { display: inline; margin: 0.5rem; } footer ul li a { text-decoration: none; color: #fff; } @media screen and (max-width: 768px) { .special-offers-container { flex-direction: column; } } @media screen and (max-width: 480px) { h1 { display: block; margin-bottom: 1rem; } } .catalog { display: flex; flex-wrap: wrap; justify-content: center; margin: 2rem 0; } .catalog-item { width: 200px; padding: 1rem; margin: 1rem; background-color: #ADC3AB; border-radius: 5px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); text-align: center; } .catalog-item:hover { box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); } .catalog-item img { width: 100%; height: auto; margin-bottom: 0.5rem; border-radius: 5px; } .catalog-item h3 { margin-bottom: 0.5rem; } .catalog-item p { margin-bottom: 0.5rem; } .catalog-item button { background-color: #32612D; color: #fff; padding: 0.5rem; border: none; border-radius: 5px; cursor: pointer; } .catalog-item button:hover { background-color: #ADC3AB; }
2fba792582cd5f0d63540932e40a3744
{ "intermediate": 0.38470685482025146, "beginner": 0.3608283996582031, "expert": 0.254464715719223 }
1,674
Hello
4ddc0259438f56e115b08b5b4954f497
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
1,675
how to install jikanpy
515d6035a9d8eab97ff64c04ef607c73
{ "intermediate": 0.4770071506500244, "beginner": 0.1564178168773651, "expert": 0.3665750324726105 }
1,676
hello
d2d7ef02a8b01acf5daf3d42793bd33a
{ "intermediate": 0.32064199447631836, "beginner": 0.28176039457321167, "expert": 0.39759764075279236 }
1,677
在不同的A和B的组合中,最好的组合并不一致。
873be9752388d4699f2526338303be07
{ "intermediate": 0.3001605272293091, "beginner": 0.4045884311199188, "expert": 0.2952510416507721 }
1,678
Deliverables You will upload to Canvas a single .zip file, titled LastNameFirstInit_Lab8.zip, containing two separate files: 1) LastNameFirstInit_Lab8.m will contain your ABM3 code in response to Task 1, and 2) LastNameFirstInit_Lab8.pdf will contain your lab report in response to Task 2. Terminology State Variables In a dynamical system (such as an Initial Value Problem), the dependent variables are also called the state variables. e.g., in Problem 5 of HW #9, x and v (or ẋ) are the state variables. These variables are often put into an array, which is called the state array. While the independent variable (usually time, for us) is not technically considered a state variable, we are primarily interested in the system state as a function of time. In our case, we will insert the independent variable as the first value in the state array and call it the augmented state array. Mode Shapes and Natural Frequencies Consider the vibration system below. As a two degree of freedom system, it has two natural frequencies and two mode shapes. If the two masses are both displaced to the left (by the correct distances) and released, they will each undergo perfect sinusoidal motion. Both will oscillate at the same frequency – called the first natural frequency. The first mode shape is a normalized vector representing respective signed amplitudes of their oscillations. The second mode shape and second natural frequency occur when the two masses are released after being displaced (by the correct distances) in opposite directions. In this case, the values in the mode shapes will have different signs, because the masses are moving in opposite directions. Task #1 Write a single function script to perform the Third Order Adams-Bashforth-Moulton algorithm on a system of ordinary differential equations (IVP). The program must be able to handle any number of differential equations (an IVP with any number of state variables). Your function m-file will receive through its header the following problem parameters (in this exact order): a. a cell array containing the function handles of the equations describing the time derivatives of the several state variables b. the initial augmented state-array – a numerical row array containing the needed starting values of the independent variable and the several state variables (in the same order as the function handles in the cell array from the first input argument) c. the step size to be used, and d. the number of steps to take Function Output Your file should not return anything to the calling program. Instead, it should i. print to screen (the command window) the final state of the system, including t, and ii. plot a trace for each of the dependent variables as a function of time. Plot each trace on a separate graph. To facilitate plotting, store the results of all time steps in the augmented state-array a. each row represents the system at a different point in time b. column 1 contains the time, and each other column contains the temporal history of a particular state variable Store only the final result of each time step, not the predicted or non-converged corrected values. Title each plot ‘Var1’, ‘Var2’, etc. Try help plot and help title in the MATLAB command window to learn more about plotting. num2str will also be useful for creating the labels themselves. Hints for your Function Script Handling a System of Un-predetermined Size Technical Because you will not know in advance the order of the IVP your function will be asked to solve, some of the system parameters will need to be passed in as arrays, rather than as scalars. The step size and number of steps will still be scalars, but there will be an un-predetermined number of state variables, each of which will have an associated starting value and derivative expression. The starting value of each state variable is a scalar, so the collection of them can be stored in a normal array. On the other hand, your function script must be passed a separate function handle for the equation for the time derivative of each state variable. To store function handles, we must use a cell array. So then, you must be able to evaluate a function handle stored in a cell array. We did this in Lab #4, but I cover it again later in this document. NOTE: Because your augmented state array will include time as the first value, the function stored in the nth index of the cell array is actually the derivative of the state variable in the (n+1)th index of the augmented state array. Metaphysical To figure out how to structure your code to deal with any size system, consult HW#9 and the notes from lab. In the HW, we performed RK3 on a 2nd order system. We can call the state variables x and v, and we can call their slopes (time derivatives) k and m, respectively. Feel free to write out and logically group the steps you took to solve the system for one timestep. Now, imagine we have 3 or 4 state variables each with their own slopes. Again, write out and logically group the steps you took to solve the system of equations. What changed about the process? Did the number of groups increase? Did the number of steps within particular groups increase? Now, we need to replace the RK4 algorithm steps with the ABM4 algorithm steps. Pay careful attention to the following differences: a. the predictor and its modifier are performed once per time step, the corrector and its modifier are repeated until convergence each time step b. the is no modifier on the predictor in the first time step c. when performing the modifier steps, you use only non-modified values d. when you check for convergence you compare only modified values Function handles with unknown number of inputs If you remember doing this for Modified Secant on a system of equations, then you may skip this section. Up to now, you’ve probably only used function handles for equations that had a predetermined number of inputs. For this program, each derivative equation may be a function of the independent variable and any or all of the state variables. This is only a problem because you don’t know now (as you’re writing the function script) how many or which of the state variables will appear in each of the derivative equations. Fortunately, MATLAB allows us to put arrays into the equation function evaluation. For example, if I define a function handle: d1_by_dt = @(t,a) a(1) * a(3) / (2 + t); when you ask MATLAB to evaluate the mathematical expression, MATLAB will expect to receive a scalar as the 1st argument, and an array of at least three terms as the 2nd argument. It will use the first and third terms in the array, along with the scalar, to evaluate the expression. The augmented state array passed into the function already has t as the first value, so let’s just stick with that. Then our example equation becomes: d1_by_dt = @(a) a(2) * a(4) / (2 + a(1)); You, of course, will have no prior knowledge of which state variables are used in each derivative expression. Therefore, for each derivative evaluation, you will need to submit an array containing the correct values of the dependent variable and all of the state variables, in the same order as the initial values in the passed-in augmented state array. When grading your code, it will be my responsibility to ensure that all of the derivative equations use the correct variables. Function handles in cell arrays The function handles of the derivative expressions of the several state variables will be passed to your function script in a cell array. The syntax for evaluating a function handle that is stored in a cell array is as follows: value = array_name{n}(input1, input2, ... , inputQ) • array_name is the name of the cell array in which the handles are stored • n is the index into the cell array, in which is stored the expression for (d/dt)y n • input1 thru inputQ are the inputs to the mathematical expression represented by the function handle – in our case that will simply be the augmented state array Please note that those are braces around the index ‘n’ and parentheses around the arguments. The ABM4 process To calculate the predicted value of each state variable, you are going to perform very similar math: n+1 ^0y k = n y k + h((55/24)g^k n - (59/24)g^k n-1 + (37/24)g^k n-2 - (3/8)g^k n-3) where the k superscript on each g term matches the state variable number (the k subscript on each y term). Take advantage of how MATALB deals with vectors to simplify the process of calculating the predictor for all the state variable and each subsequent corrector for all the state variables. Create an array that holds the g m evaluations for all of the state variables. You will have 3 or 4 of these, one for each timestep. Then you can ... temp_state = current_state + (h / 2) * slopes_array Test your program The spring-mass system from the Terminology section has been reproduced here. Neglecting friction, the equations of motion of this system are: ẍ1 = (-(k1+k2)x1 + k2x2)/m1 ẍ2 = (-(k2+k3)x2 + k2x1)/m2 where x1 and x2 are measured from the static equilibrium locations of the respective masses. To handle the 2nd order nature of the time derivatives, we must include additional state variables v1 and v2. If we arrange the state variables in the order x1, v1, x2, v2, the augmented state array becomes t, x1, v1, x2, v2, and the corresponding differential equations becomes: dx1/dt = g1(a) = a(3) dv1/dt = g2(a) = (-(k1+k2)a(2) + k2a(4))/m1 dx2/dt = g3(a) = a(5) dv2/dt = g4(a) = (-(k2+k3)a(4) + k2a(2))/m2 Remember, a(1) is time, which does not appear in our equations of motion. Create a main script (program) that performs the following tasks: iii. define the system parameters (masses and spring stiffnesses) iv. define the IVP functions above and store them in a cell array v. set the initial condition of the augmented state array (time and all four state variables) vi. call your RK4 function script Set the system parameters to m1 = m2 = 1(kg) and k1 = k2 = k3 = 13.16(N/m). Set the initial conditions to t = 0, x1(0) = 0.01(m), v1(0) = 0, x2(0) = -0.01(m), and v2(0) = 0. Call your RK4 function script with a time step of 0.001 seconds and 2000 time steps. Inspect the plots of x1 and x2. They should be mirrored sinusoidal functions with amplitudes of 0.01 and frequencies of 1Hz (2π rad/sec). Analyze Your Custom Vibration System You are going to customize the parameters of the spring mass system based upon your student ID number. Consider digits 4-5 as a two digit number X. Let digits 6-7 be a two digit number Y. If either X or Y are zero, pretend that they are 35. Task #2: Apply Your Program You will use your function to analyze a customized version of the vibration system depicted on the previous page. The system will be customized based on the last four digits of your student ID. Your goal will be to determine the second natural frequency and corresponding mode shape. For more details, refer to the Terminology section of this document. Set the system parameters to m1 = 1(kg), m2 = (0.75-(X/200))(kg), k1 = k2 = 13.16(N/m), and k3 = (13.66+(Y/200))(N/m). Set the initial conditions to t = 0, x1(0) = -0.01(m), v1(0) = 0, and v2(0) = 0. Please note that the initial value of x1 is negative. Now, find the second natural frequency and second mode shape of your system by running your RK4 function multiple times, with different initial values for x2. I think the correct value should be > 0.01. When you find the correct value of x2(0) each mass should demonstrate smooth sinusoidal motion. Inspect your table of state variables to determine the period of the oscillation. The period is the time between consecutive maximum displacements. The frequency in Hz is the inverse of the period. The mode shape is the vector [x1(0); x2(0)] scaled to have a Euclidean norm of unity (1). Include in your Lab Report the following: • the last four digits of your student ID number • the values you used for X and Y • the second natural frequency, in Hz, of your customized spring-mass system • the normalized second mode shape of your customized spring-mass system • plots of x1 and x2 as functions of time for two seconds Provide the natural frequency and mode shape values to 5 significant figures. Here is the RK4 chunk that is supposed to go on the top of the code for the function: % In the code below: % % g is cell array containing the various dy/dt functions % % s_a is the augmented state array. It starts out as a row vector. It is % passed in with the starting values of t and each state variable, in the % same order as the function handles in the g cell array. It will % eventually contain all of the values of t and the state variables over % time. % % h is the step size N = length(g); slopes = zeros(4,N) for iter = 1:2 state = s_a(iter,:); for c = 1:N slopes(1,c) = g{c}(state); end state = s_a(iter,:) + (h/2)*[1, slopes(1,:)]; for c = 1:N slopes(2,c) = g{c}(state); end state = s_a(iter,:) + (h/2)*[1, slopes(2,:)]; for c = 1:N slopes(3,c) = g{c}(state); end state = s_a(iter,:) + h*[1, slopes(3,:)]; for c = 1:N slopes(4,c) = g{c}(state); end RK = (slopes(1,:) + 2*slopes(2,:) + 2*slopes(3,:) + slopes(4,:)) / 6; s_a(iter+1,:) = s_a(iter,:) + h*[1, RK] end When this chunk is done, we should have three rows in the augmented state array, corresponding to our first three time points. It shouldn't be changed in any way while making the function script.
77a5f92acc498ecf1afe4d8348c3c7d4
{ "intermediate": 0.3902553617954254, "beginner": 0.3665621280670166, "expert": 0.2431824505329132 }
1,679
In an oncology clinical trial, how to predict the survival time for remaining patients who are still alive based on data observed up to date, taking into below considerations? 1. baseline characteristics of the patients who are still alive, like age and gender 2. the death hazard varies over time so that it should be estimated piecewise 3. avarage estimated time of death from 10000 simulations
1829051e76ee28b2fb2f8077ba68caea
{ "intermediate": 0.28661322593688965, "beginner": 0.3761037588119507, "expert": 0.33728304505348206 }
1,680
#include "roll_polling.h" #include <thread> #include <vector> namespace mediakit { #define ErrorL std::cerr #define InfoL std::cerr #define WarnL std::cerr int RollPollingWorker::Start(const std::string input, const std::string output) { av_log_set_level(AV_LOG_INFO); std::lock_guard<std::mutex> lock(mutex_); source_ctx_ = OpenInputFile(input); if (!source_ctx_) { ErrorL << "open input file [" << input << "] failed"; return -1; } if (OpenOutputFile(output) < 0) { ErrorL << "open output file [" << output << "] failed"; return -1; } filter_ctx_ = InitFilter(source_ctx_->codec_ctx_, ocodec_ctx_); if (!filter_ctx_) { ErrorL << "output file " << output << " init filter failed"; return -1; } output_ = output; state_ = kRunning; std::cerr << "start roll polling task [" << output_ << "] successed \n"; return 0; } int RollPollingWorker::Stop() { state_ = kStoped; return 0; } int RollPollingWorker::UpdateInput(const std::string input) { std::string prefix = Prefix(); if (kRunning != state_) { ErrorL << prefix << " is not running"; return -1; } if (input == source_ctx_->filename_) { InfoL << prefix << " input file [" << input << " is same with preview input"; return 0; } std::shared_ptr<SourceContext> source_ctx = OpenInputFile(input); if (!source_ctx) { ErrorL << prefix << " open input file [" << input << "] failed"; return -1; } std::shared_ptr<FilterContext> filter_ctx = InitFilter(source_ctx->codec_ctx_, ocodec_ctx_); if (!filter_ctx) { ErrorL << prefix << " init filter failed"; return -1; } std::lock_guard<std::mutex> lock(mutex_); source_ctx_ = source_ctx; filter_ctx_ = filter_ctx; need_idr_ = true; InfoL << "update input file " << input << " successed \n"; return 0; } void RollPollingWorker::Runnable() { std::string prefix = Prefix(); AVPacket* pkt = av_packet_alloc(); while (kRunning == state_) { std::lock_guard<std::mutex> lock(mutex_); SourceContext* source = source_ctx_.get(); FilterContext* filter = filter_ctx_.get(); int ret = av_read_frame(source->fmt_ctx_, pkt); if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } // only process video stream if (pkt->stream_index != source->vid_stream_idx_) continue; if (filter_ctx_) { ret = avcodec_send_packet(source->codec_ctx_, pkt); if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } while (ret >= 0) { ret = avcodec_receive_frame(source->codec_ctx_, source->decoded_frame_); if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } FilterFrame(filter, source->decoded_frame_); av_frame_unref(source->decoded_frame_); } } else { //av_packet_rescale_ts(pkt, // source->fmt_ctx_->streams[pkt->stream_index]->time_base, // ofmt_ctx_->streams[0]->time_base); // only video stream pkt->stream_index = 0; pkt->pts = pkt->dts = (frame_cnt_++) * 40; pkt->duration = 0; pkt->pos = -1; ret = av_interleaved_write_frame(ofmt_ctx_, pkt); } av_packet_unref(pkt); //std::cerr << "write video packet size = " << pkt->size << " result = " << ret << " \n"; if (ret < 0) { ErrorL << prefix << " write packet to output file failed \n"; //break; } } av_write_trailer(ofmt_ctx_); av_packet_free(&pkt); avcodec_free_context(&ocodec_ctx_); if (ofmt_ctx_ && !(ofmt_ctx_->oformat->flags & AVFMT_NOFILE)) avio_closep(&ofmt_ctx_->pb); avformat_free_context(ofmt_ctx_); state_ = kStoped; InfoL << "roll polling task finished"; } std::shared_ptr<RollPollingWorker::SourceContext> RollPollingWorker::OpenInputFile(const std::string filename) { std::shared_ptr<SourceContext> source_ctx = std::make_shared<SourceContext>(); int ret = avformat_open_input(&source_ctx->fmt_ctx_, filename.c_str(), 0, nullptr); if (ret < 0) { ErrorL << "failed to open input file [" << filename << "]"; return nullptr; } ret = avformat_find_stream_info(source_ctx->fmt_ctx_, 0); if (ret < 0) { ErrorL << "Fail to find input stream information in [" << filename << "]"; return nullptr; } AVCodec* dec = nullptr; ret = av_find_best_stream(source_ctx->fmt_ctx_, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0); if (ret < 0) { ErrorL << "Fail to av_find_best_stream in [" << filename << "]"; return nullptr; } source_ctx->vid_stream_idx_ = ret; source_ctx->codec_ctx_ = avcodec_alloc_context3(dec); if (!source_ctx->codec_ctx_) { ErrorL << "Fail to avcodec_alloc_context3 in [" << filename << "]"; return nullptr; } int vid_stream_idx = source_ctx->vid_stream_idx_; avcodec_parameters_to_context(source_ctx->codec_ctx_, source_ctx->fmt_ctx_->streams[vid_stream_idx]->codecpar); // very important source_ctx->codec_ctx_->framerate = av_guess_frame_rate(source_ctx->fmt_ctx_, source_ctx->fmt_ctx_->streams[vid_stream_idx], nullptr); ret = avcodec_open2(source_ctx->codec_ctx_, dec, NULL); if (ret < 0) { ErrorL << "Fail to avcodec_open2 in [" << filename << "]"; return nullptr; } source_ctx->decoded_frame_ = av_frame_alloc(); return source_ctx; } int RollPollingWorker::OpenOutputFile(const std::string filename) { avformat_alloc_output_context2(&ofmt_ctx_, nullptr, "flv", filename.c_str()); if (!ofmt_ctx_) { ErrorL << "failed to open output file [" << filename << "]"; return -1; } const AVCodec* enc = avcodec_find_encoder(AV_CODEC_ID_H264); if (!enc) { ErrorL << "cannot find H.264 encoder"; return -1; } ocodec_ctx_ = avcodec_alloc_context3(enc); if (!ocodec_ctx_) { ErrorL << "failed to allocate H.264 encoder context"; return -1; } ocodec_ctx_->height = source_ctx_->codec_ctx_->height; ocodec_ctx_->width = source_ctx_->codec_ctx_->width; ocodec_ctx_->sample_aspect_ratio = source_ctx_->codec_ctx_->sample_aspect_ratio; ocodec_ctx_->pix_fmt = source_ctx_->codec_ctx_->pix_fmt; ocodec_ctx_->time_base = av_inv_q(source_ctx_->codec_ctx_->framerate); AVDictionary* enc_opts = nullptr; av_dict_set(&enc_opts, "x264-params", "crf=23:bframes=0", 0); if (avcodec_open2(ocodec_ctx_, enc, &enc_opts) < 0) { ErrorL << "Cannot open video encoder"; return -1; } AVStream* out_stream = avformat_new_stream(ofmt_ctx_, nullptr); if (!out_stream) { ErrorL << "Fail to avformat_new_stream, filename " << filename << " \n"; return -1; } if (avcodec_parameters_from_context(out_stream->codecpar, ocodec_ctx_) < 0) { ErrorL << "Failed to copy encoder parameters to output"; return -1; } out_stream->time_base = ocodec_ctx_->time_base; if (avio_open(&ofmt_ctx_->pb, filename.c_str(), AVIO_FLAG_WRITE) < 0) { ErrorL << "Could not open output file " << filename << "\n"; return -1; } AVDictionary* opts = nullptr; av_dict_set(&opts, "flvflags", "no_duration_filesize+no_metadata", 0); return avformat_write_header(ofmt_ctx_, &opts); } std::shared_ptr<RollPollingWorker::FilterContext> RollPollingWorker::InitFilter( AVCodecContext* icodec_ctx, AVCodecContext* ocodec_ctx) { std::shared_ptr<FilterContext> filter_ctx = std::make_shared<FilterContext>(); filter_ctx->filter_graph_ = avfilter_graph_alloc(); filter_ctx->filter_frame_ = av_frame_alloc(); char args[512]; snprintf(args, sizeof(args), "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d", icodec_ctx->width, icodec_ctx->height, icodec_ctx->pix_fmt, icodec_ctx->time_base.num, icodec_ctx->time_base.den, icodec_ctx->sample_aspect_ratio.num, icodec_ctx->sample_aspect_ratio.den); const AVFilter* buffersrc = avfilter_get_by_name("buffer"); int ret = avfilter_graph_create_filter(&filter_ctx->buffersrc_ctx_, buffersrc, "in", args, nullptr, filter_ctx->filter_graph_); if (ret < 0) { ErrorL << "Cannot create buffer source"; return nullptr; } const AVFilter* buffersink = avfilter_get_by_name("buffersink"); ret = avfilter_graph_create_filter(&filter_ctx->buffersink_ctx_, buffersink, "out", nullptr, nullptr, filter_ctx->filter_graph_); if (ret < 0) { ErrorL << "Cannot create buffer sink"; return nullptr; } ret = av_opt_set_bin(filter_ctx->buffersink_ctx_, "pix_fmts", (uint8_t*)&ocodec_ctx_->pix_fmt, sizeof(ocodec_ctx_->pix_fmt), AV_OPT_SEARCH_CHILDREN); if (ret < 0) { ErrorL << "Cannot set output pixel format"; return nullptr; } AVFilterInOut* outputs = avfilter_inout_alloc();; outputs->name = av_strdup("in"); outputs->filter_ctx = filter_ctx->buffersrc_ctx_; outputs->pad_idx = 0; outputs->next = nullptr; AVFilterInOut *inputs = avfilter_inout_alloc(); inputs->name = av_strdup("out"); inputs->filter_ctx = filter_ctx->buffersink_ctx_; inputs->pad_idx = 0; inputs->next = NULL; std::string filter_spec = "[in]scale=" + std::to_string(kWidth) + ":" + std::to_string(kHeight) + "[out]"; do { ret = avfilter_graph_parse_ptr(filter_ctx->filter_graph_, filter_spec.c_str(), &inputs, &outputs, nullptr); if (ret < 0) { ErrorL << "avfilter graph parse failed"; break; } ret = avfilter_graph_config(filter_ctx->filter_graph_, nullptr); if (ret < 0) { ErrorL << "avfilter graph config failed"; break; } } while (0); avfilter_inout_free(&inputs); avfilter_inout_free(&outputs); return ret < 0 ? nullptr : filter_ctx; } int RollPollingWorker::FilterFrame(FilterContext* filter, AVFrame* frame) { int ret = av_buffersrc_add_frame_flags(filter->buffersrc_ctx_, frame, 0); if (ret < 0) { ErrorL << "Error while feeding the filtergraph \n"; return ret; } while (1) { ret = av_buffersink_get_frame(filter->buffersink_ctx_, filter->filter_frame_); if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } filter->filter_frame_->pict_type = AV_PICTURE_TYPE_NONE; if (need_idr_) { filter->filter_frame_->pict_type = AV_PICTURE_TYPE_I; need_idr_ = false; } ret = EncodeFrame(filter->filter_frame_); av_frame_unref(filter->filter_frame_); if (ret < 0) break; } return ret; } int RollPollingWorker::EncodeFrame(AVFrame* frame) { if (avcodec_send_frame(ocodec_ctx_, frame) < 0) return -1; AVPacket* enc_pkt = av_packet_alloc(); int ret = 0; while (ret >= 0) { ret = avcodec_receive_packet(ocodec_ctx_, enc_pkt); if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } enc_pkt->stream_index = 0; enc_pkt->pts = enc_pkt->dts = (frame_cnt_++) * 40; enc_pkt->duration = 0; enc_pkt->pos = -1; //std::cerr << "muxing frame: pts " << enc_pkt->pts << " duration " << enc_pkt->duration << "\n"; ret = av_interleaved_write_frame(ofmt_ctx_, enc_pkt); av_packet_unref(enc_pkt); if (ret < 0) { ErrorL << Prefix() << " write packet to output file failed \n"; break; } } av_packet_free(&enc_pkt); return ret; } int RollPollingWorkerPool::StartWorker(const std::string input, const std::string output) { std::shared_ptr<RollPollingWorker> worker = std::make_shared<RollPollingWorker>(); if (!worker->Start(input, output)) { return -1; } std::weak_ptr<RollPollingWorker> weak_worker = worker; auto task = [weak_worker](int64_t unused){ auto worker = weak_worker.lock(); if (worker) worker->Runnable(); }; std::lock_guard<std::mutex> lock(mutex_); worker_list_[output] = worker; return 0; } int RollPollingWorkerPool::StopWorker(const std::string url) { std::lock_guard<std::mutex> lock(mutex_); auto it = worker_list_.find(url); return it != worker_list_.end() ? it->second->Stop() : -1; } int RollPollingWorkerPool::PollingStart(const std::vector<std::string> inputsurl, const std::string outputurl) { std::vector<std::string> inputs = inputsurl ; // for (int i = 1; i < (argc - 1); i++) // inputs.push_back(argv[i]); // std::string output = argv[argc - 1]; std::string output = outputurl; mediakit::RollPollingWorker worker; if (worker.Start(inputs[0], output) < 0) return -1; auto f = [&](){ worker.Runnable(); }; std::thread task(f); task.detach(); size_t idx = 1; while (worker.IsRunning()) { std::this_thread::sleep_for(std::chrono::milliseconds(10000)); if (idx >= 4) break; if (inputs.size() > 1) { std::string tmp = inputs[idx % inputs.size()]; std::cerr << "change input file to [" << tmp << "\n"; worker.UpdateInput(tmp); idx++; } } worker.Stop(); //task.join(); return 0; } }每一行都加上中文注释,帮助我理解
822d21a208c4697c186a44ef19b1afa3
{ "intermediate": 0.4294775128364563, "beginner": 0.34500470757484436, "expert": 0.22551777958869934 }
1,681
我本地有在 script.rand.utils目录下有个文件叫noise.py,我在script.aa 目录下的test.py文件去使用noise.py中的函数,我在test.py中from script。rand.util import noise as noise_lib 提示expected type union got noise.py instead
897738931cfd419c4a3e2b4a60424596
{ "intermediate": 0.3562190532684326, "beginner": 0.3436369299888611, "expert": 0.3001439869403839 }
1,682
Deliverables You will upload to Canvas a single .zip file, titled LastNameFirstInit_Lab8.zip, containing two separate files: 1) LastNameFirstInit_Lab8.m will contain your ABM4 code in response to Task 1, and 2) LastNameFirstInit_Lab8.pdf will contain your lab report in response to Task 2. Terminology State Variables In a dynamical system (such as an Initial Value Problem), the dependent variables are also called the state variables. e.g., in Problem 5 of HW #9, x and v (or ẋ) are the state variables. These variables are often put into an array, which is called the state array. While the independent variable (usually time, for us) is not technically considered a state variable, we are primarily interested in the system state as a function of time. In our case, we will insert the independent variable as the first value in the state array and call it the augmented state array. Mode Shapes and Natural Frequencies Consider the vibration system below. As a two degree of freedom system, it has two natural frequencies and two mode shapes. If the two masses are both displaced to the left (by the correct distances) and released, they will each undergo perfect sinusoidal motion. Both will oscillate at the same frequency – called the first natural frequency. The first mode shape is a normalized vector representing respective signed amplitudes of their oscillations. The second mode shape and second natural frequency occur when the two masses are released after being displaced (by the correct distances) in opposite directions. In this case, the values in the mode shapes will have different signs, because the masses are moving in opposite directions. Task #1 Write a single function script to perform the Fourth Order Adams-Bashforth-Moulton algorithm on a system of ordinary differential equations (IVP). The program must be able to handle any number of differential equations (an IVP with any number of state variables). Your function m-file will receive through its header the following problem parameters (in this exact order): a. a cell array containing the function handles of the equations describing the time derivatives of the several state variables b. the initial augmented state-array – a numerical row array containing the needed starting values of the independent variable and the several state variables (in the same order as the function handles in the cell array from the first input argument) c. the step size to be used, and d. the number of steps to take Function Output Your file should not return anything to the calling program. Instead, it should i. print to screen (the command window) the final state of the system, including t, and ii. plot a trace for each of the dependent variables as a function of time. Plot each trace on a separate graph. To facilitate plotting, store the results of all time steps in the augmented state-array a. each row represents the system at a different point in time b. column 1 contains the time, and each other column contains the temporal history of a particular state variable Store only the final result of each time step, not the predicted or non-converged corrected values. Title each plot ‘Var1’, ‘Var2’, etc. Try help plot and help title in the MATLAB command window to learn more about plotting. num2str will also be useful for creating the labels themselves. Hints for your Function Script Handling a System of Un-predetermined Size Technical Because you will not know in advance the order of the IVP your function will be asked to solve, some of the system parameters will need to be passed in as arrays, rather than as scalars. The step size and number of steps will still be scalars, but there will be an un-predetermined number of state variables, each of which will have an associated starting value and derivative expression. The starting value of each state variable is a scalar, so the collection of them can be stored in a normal array. On the other hand, your function script must be passed a separate function handle for the equation for the time derivative of each state variable. To store function handles, we must use a cell array. So then, you must be able to evaluate a function handle stored in a cell array. We did this in Lab #4, but I cover it again later in this document. NOTE: Because your augmented state array will include time as the first value, the function stored in the nth index of the cell array is actually the derivative of the state variable in the (n+1)th index of the augmented state array. Metaphysical To figure out how to structure your code to deal with any size system, consult HW#9 and the notes from lab. In the HW, we performed RK3 on a 2nd order system. We can call the state variables x and v, and we can call their slopes (time derivatives) k and m, respectively. Feel free to write out and logically group the steps you took to solve the system for one timestep. Now, imagine we have 3 or 4 state variables each with their own slopes. Again, write out and logically group the steps you took to solve the system of equations. What changed about the process? Did the number of groups increase? Did the number of steps within particular groups increase? Now, we need to replace the RK4 algorithm steps with the ABM4 algorithm steps. Pay careful attention to the following differences: a. the predictor and its modifier are performed once per time step, the corrector and its modifier are repeated until convergence each time step b. the is no modifier on the predictor in the first time step c. when performing the modifier steps, you use only non-modified values d. when you check for convergence you compare only modified values Function handles with unknown number of inputs If you remember doing this for Modified Secant on a system of equations, then you may skip this section. Up to now, you’ve probably only used function handles for equations that had a predetermined number of inputs. For this program, each derivative equation may be a function of the independent variable and any or all of the state variables. This is only a problem because you don’t know now (as you’re writing the function script) how many or which of the state variables will appear in each of the derivative equations. Fortunately, MATLAB allows us to put arrays into the equation function evaluation. For example, if I define a function handle: d1_by_dt = @(t,a) a(1) * a(3) / (2 + t); when you ask MATLAB to evaluate the mathematical expression, MATLAB will expect to receive a scalar as the 1st argument, and an array of at least three terms as the 2nd argument. It will use the first and third terms in the array, along with the scalar, to evaluate the expression. The augmented state array passed into the function already has t as the first value, so let’s just stick with that. Then our example equation becomes: d1_by_dt = @(a) a(2) * a(4) / (2 + a(1)); You, of course, will have no prior knowledge of which state variables are used in each derivative expression. Therefore, for each derivative evaluation, you will need to submit an array containing the correct values of the dependent variable and all of the state variables, in the same order as the initial values in the passed-in augmented state array. When grading your code, it will be my responsibility to ensure that all of the derivative equations use the correct variables. Function handles in cell arrays The function handles of the derivative expressions of the several state variables will be passed to your function script in a cell array. The syntax for evaluating a function handle that is stored in a cell array is as follows: value = array_name{n}(input1, input2, ... , inputQ) • array_name is the name of the cell array in which the handles are stored • n is the index into the cell array, in which is stored the expression for (d/dt)y n • input1 thru inputQ are the inputs to the mathematical expression represented by the function handle – in our case that will simply be the augmented state array Please note that those are braces around the index ‘n’ and parentheses around the arguments. The ABM4 process To calculate the predicted value of each state variable, you are going to perform very similar math: n+1 ^0y k = n y k + h((55/24)g^k n - (59/24)g^k n-1 + (37/24)g^k n-2 - (3/8)g^k n-3) where the k superscript on each g term matches the state variable number (the k subscript on each y term). Take advantage of how MATALB deals with vectors to simplify the process of calculating the predictor for all the state variable and each subsequent corrector for all the state variables. Create an array that holds the g m evaluations for all of the state variables. You will have 3 or 4 of these, one for each timestep. Then you can ... temp_state = current_state + (h / 2) * slopes_array Test your program The spring-mass system from the Terminology section has been reproduced here. Neglecting friction, the equations of motion of this system are: ẍ1 = (-(k1+k2)x1 + k2x2)/m1 ẍ2 = (-(k2+k3)x2 + k2x1)/m2 where x1 and x2 are measured from the static equilibrium locations of the respective masses. To handle the 2nd order nature of the time derivatives, we must include additional state variables v1 and v2. If we arrange the state variables in the order x1, v1, x2, v2, the augmented state array becomes t, x1, v1, x2, v2, and the corresponding differential equations becomes: dx1/dt = g1(a) = a(3) dv1/dt = g2(a) = (-(k1+k2)a(2) + k2a(4))/m1 dx2/dt = g3(a) = a(5) dv2/dt = g4(a) = (-(k2+k3)a(4) + k2a(2))/m2 Remember, a(1) is time, which does not appear in our equations of motion. Create a main script (program) that performs the following tasks: iii. define the system parameters (masses and spring stiffnesses) iv. define the IVP functions above and store them in a cell array v. set the initial condition of the augmented state array (time and all four state variables) vi. call your RK4 function script Set the system parameters to m1 = m2 = 1(kg) and k1 = k2 = k3 = 13.16(N/m). Set the initial conditions to t = 0, x1(0) = 0.01(m), v1(0) = 0, x2(0) = -0.01(m), and v2(0) = 0. Call your RK4 function script with a time step of 0.001 seconds and 2000 time steps. Inspect the plots of x1 and x2. They should be mirrored sinusoidal functions with amplitudes of 0.01 and frequencies of 1Hz (2π rad/sec). Analyze Your Custom Vibration System You are going to customize the parameters of the spring mass system based upon your student ID number. Consider digits 4-5 as a two digit number X. Let digits 6-7 be a two digit number Y. If either X or Y are zero, pretend that they are 35. Task #2: Apply Your Program You will use your function to analyze a customized version of the vibration system depicted on the previous page. The system will be customized based on the last four digits of your student ID. Your goal will be to determine the second natural frequency and corresponding mode shape. For more details, refer to the Terminology section of this document. Set the system parameters to m1 = 1(kg), m2 = (0.75-(X/200))(kg), k1 = k2 = 13.16(N/m), and k3 = (13.66+(Y/200))(N/m). Set the initial conditions to t = 0, x1(0) = -0.01(m), v1(0) = 0, and v2(0) = 0. Please note that the initial value of x1 is negative. Now, find the second natural frequency and second mode shape of your system by running your RK4 function multiple times, with different initial values for x2. I think the correct value should be > 0.01. When you find the correct value of x2(0) each mass should demonstrate smooth sinusoidal motion. Inspect your table of state variables to determine the period of the oscillation. The period is the time between consecutive maximum displacements. The frequency in Hz is the inverse of the period. The mode shape is the vector [x1(0); x2(0)] scaled to have a Euclidean norm of unity (1). Include in your Lab Report the following: • the last four digits of your student ID number • the values you used for X and Y • the second natural frequency, in Hz, of your customized spring-mass system • the normalized second mode shape of your customized spring-mass system • plots of x1 and x2 as functions of time for two seconds Provide the natural frequency and mode shape values to 5 significant figures. Here is the RK4 chunk that is supposed to go on the top of the code for the function: % In the code below: % % g is cell array containing the various dy/dt functions % % s_a is the augmented state array. It starts out as a row vector. It is % passed in with the starting values of t and each state variable, in the % same order as the function handles in the g cell array. It will % eventually contain all of the values of t and the state variables over % time. % % h is the step size N = length(g); slopes = zeros(4,N) for iter = 1:2 state = s_a(iter,:); for c = 1:N slopes(1,c) = g{c}(state); end state = s_a(iter,:) + (h/2)*[1, slopes(1,:)]; for c = 1:N slopes(2,c) = g{c}(state); end state = s_a(iter,:) + (h/2)*[1, slopes(2,:)]; for c = 1:N slopes(3,c) = g{c}(state); end state = s_a(iter,:) + h*[1, slopes(3,:)]; for c = 1:N slopes(4,c) = g{c}(state); end RK = (slopes(1,:) + 2*slopes(2,:) + 2*slopes(3,:) + slopes(4,:)) / 6; s_a(iter+1,:) = s_a(iter,:) + h*[1, RK] end When this chunk is done, we should have three rows in the augmented state array, corresponding to our first three time points. It shouldn't be changed in any way while making the function script.
d9d6d579b31d657269074d9b98ad9352
{ "intermediate": 0.38896793127059937, "beginner": 0.3662795126438141, "expert": 0.24475248157978058 }
1,683
I'm working on a fivem script where when you aim your gun in a car your character leans out of the vehicle
c91599d5be2d59b605342c28d19bd3be
{ "intermediate": 0.3151758909225464, "beginner": 0.27144283056259155, "expert": 0.41338127851486206 }
1,684
flutter Don't use web-only libraries outside Flutter web plugin packages.
f13b197052cf3256395dc52a058f7390
{ "intermediate": 0.8018684983253479, "beginner": 0.09851450473070145, "expert": 0.09961705654859543 }
1,685
I'm working on a fivem script How could i create a server callback rather then having to trigger an event to send information to the client and trigger one to return it
a6729d23bf16d416b726ed6068d9871d
{ "intermediate": 0.5796369314193726, "beginner": 0.17193575203418732, "expert": 0.2484273463487625 }
1,686
Hi
cc75acaecbfd3f29c1f72dfc1b2f3b2e
{ "intermediate": 0.33010533452033997, "beginner": 0.26984941959381104, "expert": 0.400045245885849 }
1,687
#include “roll_polling.h” #include <thread> #include <vector> namespace mediakit { #define ErrorL std::cerr #define InfoL std::cerr #define WarnL std::cerr //开启一个RollPollingWorker任务 int RollPollingWorker::Start(const std::string input, const std::string output) { av_log_set_level(AV_LOG_INFO); std::lock_guard<std::mutex> lock(mutex_); source_ctx_ = OpenInputFile(input); if (!source_ctx_) { ErrorL << “open input file [” << input << “] failed”; return -1; } if (OpenOutputFile(output) < 0) { ErrorL << “open output file [” << output << “] failed”; return -1; } filter_ctx_ = InitFilter(source_ctx_->codec_ctx_, ocodec_ctx_);//初始过滤器 if (!filter_ctx_) { ErrorL << “output file " << output << " init filter failed”; return -1; } output_ = output; state_ = kRunning;//设置状态为运行中 std::cerr << “start roll polling task [” << output_ << “] successed \n”; return 0; } int RollPollingWorker::Stop() { state_ = kStoped;//设置状态为停止 return 0; } int RollPollingWorker::UpdateInput(const std::string input) { std::string prefix = Prefix();//获取当前任务 if (kRunning != state_) { ErrorL << prefix << " is not running"; return -1; } if (input == source_ctx_->filename_) { InfoL << prefix << " input file [" << input << " is same with preview input"; return 0; } std::shared_ptr<SourceContext> source_ctx = OpenInputFile(input); if (!source_ctx) { ErrorL << prefix << " open input file [" << input << “] failed”; return -1; } std::shared_ptr<FilterContext> filter_ctx = InitFilter(source_ctx->codec_ctx_, ocodec_ctx_); if (!filter_ctx) { ErrorL << prefix << " init filter failed"; return -1; } std::lock_guard<std::mutex> lock(mutex_); source_ctx_ = source_ctx;//更新输入源上下文 filter_ctx_ = filter_ctx;//更新过滤器上下文 need_idr_ = true;//需要IDR帧 InfoL << “update input file " << input << " successed \n”; return 0; } void RollPollingWorker::Runnable() { std::string prefix = Prefix(); AVPacket* pkt = av_packet_alloc();//分配AVPacket while (kRunning == state_) {//当任务处于运行状态时 std::lock_guard<std::mutex> lock(mutex_); SourceContext* source = source_ctx_.get();//获取输入源上下文 FilterContext* filter = filter_ctx_.get(); //获取过滤器上下文 int ret = av_read_frame(source->fmt_ctx_, pkt);//读取帧 if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } // only process video stream 只处理视频流 if (pkt->stream_index != source->vid_stream_idx_) continue; if (filter_ctx_) {//如果存在过滤器上下文 ret = avcodec_send_packet(source->codec_ctx_, pkt); //将数据包发送到解码器 if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } while (ret >= 0) { ret = avcodec_receive_frame(source->codec_ctx_, source->decoded_frame_);//接收解码后的帧 if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } FilterFrame(filter, source->decoded_frame_);//过滤帧 av_frame_unref(source->decoded_frame_); //取消引用帧 } } else { //av_packet_rescale_ts(pkt, // source->fmt_ctx_->streams[pkt->stream_index]->time_base, // ofmt_ctx_->streams[0]->time_base); // only video stream pkt->stream_index = 0; pkt->pts = pkt->dts = (frame_cnt_++) * 40; pkt->duration = 0; pkt->pos = -1; ret = av_interleaved_write_frame(ofmt_ctx_, pkt);//将数据包写入输出文件 } av_packet_unref(pkt);//取消引用数据包 //std::cerr << “write video packet size = " << pkt->size << " result = " << ret << " \n”; if (ret < 0) { ErrorL << prefix << " write packet to output file failed \n"; //break; } } av_write_trailer(ofmt_ctx_);//写入文件尾部 av_packet_free(&pkt); //释放数据包 avcodec_free_context(&ocodec_ctx_);//释放编码器上下文 if (ofmt_ctx_ && !(ofmt_ctx_->oformat->flags & AVFMT_NOFILE))//如果输出格式上下文存在且不是没有文件标志 avio_closep(&ofmt_ctx_->pb); //关闭输出文件 avformat_free_context(ofmt_ctx_); //释放输出格式上下文 state_ = kStoped;//设置状态为停止 InfoL << “roll polling task finished”; } std::shared_ptr<RollPollingWorker::SourceContext> RollPollingWorker::OpenInputFile(const std::string filename) { std::shared_ptr<SourceContext> source_ctx = std::make_shared<SourceContext>(); int ret = avformat_open_input(&source_ctx->fmt_ctx_, filename.c_str(), 0, nullptr);//打开输入文件 if (ret < 0) { ErrorL << “failed to open input file [” << filename << “]”; return nullptr; } ret = avformat_find_stream_info(source_ctx->fmt_ctx_, 0);//找到输入文件的流信息 if (ret < 0) { ErrorL << “Fail to find input stream information in [” << filename << “]”; return nullptr; } AVCodec* dec = nullptr; ret = av_find_best_stream(source_ctx->fmt_ctx_, AVMEDIA_TYPE_VIDEO, -1, -1, &dec, 0);//查找视频流 if (ret < 0) { ErrorL << “Fail to av_find_best_stream in [” << filename << “]”; return nullptr; } source_ctx->vid_stream_idx_ = ret;//设置视频流索引 source_ctx->codec_ctx_ = avcodec_alloc_context3(dec); //分配解码器上下文 if (!source_ctx->codec_ctx_) { ErrorL << “Fail to avcodec_alloc_context3 in [” << filename << “]”; return nullptr; } int vid_stream_idx = source_ctx->vid_stream_idx_; //将参数传递给解码器上下文 avcodec_parameters_to_context(source_ctx->codec_ctx_, source_ctx->fmt_ctx_->streams[vid_stream_idx]->codecpar); // very important source_ctx->codec_ctx_->framerate = av_guess_frame_rate(source_ctx->fmt_ctx_, source_ctx->fmt_ctx_->streams[vid_stream_idx], nullptr); ret = avcodec_open2(source_ctx->codec_ctx_, dec, NULL);//打开解码器 if (ret < 0) { ErrorL << “Fail to avcodec_open2 in [” << filename << “]”; return nullptr; } source_ctx->decoded_frame_ = av_frame_alloc();//分配帧 return source_ctx; } int RollPollingWorker::OpenOutputFile(const std::string filename) { avformat_alloc_output_context2(&ofmt_ctx_, nullptr, “flv”, filename.c_str()); //分配输出格式上下文 if (!ofmt_ctx_) { ErrorL << “failed to open output file [” << filename << “]”; return -1; } const AVCodec* enc = avcodec_find_encoder(AV_CODEC_ID_H264);//查找H.264编码器 if (!enc) { ErrorL << “cannot find H.264 encoder”; return -1; } ocodec_ctx_ = avcodec_alloc_context3(enc);//分配H.264编码器上下文 if (!ocodec_ctx_) { ErrorL << “failed to allocate H.264 encoder context”; return -1; } ocodec_ctx_->height = source_ctx_->codec_ctx_->height;//设置编码器上下文的宽高和像素格式 ocodec_ctx_->width = source_ctx_->codec_ctx_->width; ocodec_ctx_->sample_aspect_ratio = source_ctx_->codec_ctx_->sample_aspect_ratio; ocodec_ctx_->pix_fmt = source_ctx_->codec_ctx_->pix_fmt; ocodec_ctx_->time_base = av_inv_q(source_ctx_->codec_ctx_->framerate);//设置编码器上下文的时间基准 AVDictionary* enc_opts = nullptr; av_dict_set(&enc_opts, “x264-params”, “crf=23:bframes=0”, 0); if (avcodec_open2(ocodec_ctx_, enc, &enc_opts) < 0) { ErrorL << “Cannot open video encoder”; return -1; } AVStream* out_stream = avformat_new_stream(ofmt_ctx_, nullptr); if (!out_stream) { ErrorL << “Fail to avformat_new_stream, filename " << filename << " \n”; return -1; } if (avcodec_parameters_from_context(out_stream->codecpar, ocodec_ctx_) < 0) { ErrorL << “Failed to copy encoder parameters to output”; return -1; } out_stream->time_base = ocodec_ctx_->time_base; if (avio_open(&ofmt_ctx_->pb, filename.c_str(), AVIO_FLAG_WRITE) < 0) { ErrorL << "Could not open output file " << filename << “\n”; return -1; } AVDictionary* opts = nullptr; av_dict_set(&opts, “flvflags”, “no_duration_filesize+no_metadata”, 0); return avformat_write_header(ofmt_ctx_, &opts); } std::shared_ptr<RollPollingWorker::FilterContext> RollPollingWorker::InitFilter( AVCodecContext* icodec_ctx, AVCodecContext* ocodec_ctx) { std::shared_ptr<FilterContext> filter_ctx = std::make_shared<FilterContext>(); filter_ctx->filter_graph_ = avfilter_graph_alloc(); filter_ctx->filter_frame_ = av_frame_alloc(); char args[512]; snprintf(args, sizeof(args), “video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d”, icodec_ctx->width, icodec_ctx->height, icodec_ctx->pix_fmt, icodec_ctx->time_base.num, icodec_ctx->time_base.den, icodec_ctx->sample_aspect_ratio.num, icodec_ctx->sample_aspect_ratio.den); const AVFilter* buffersrc = avfilter_get_by_name(“buffer”); int ret = avfilter_graph_create_filter(&filter_ctx->buffersrc_ctx_, buffersrc, “in”, args, nullptr, filter_ctx->filter_graph_); if (ret < 0) { ErrorL << “Cannot create buffer source”; return nullptr; } const AVFilter* buffersink = avfilter_get_by_name(“buffersink”); ret = avfilter_graph_create_filter(&filter_ctx->buffersink_ctx_, buffersink, “out”, nullptr, nullptr, filter_ctx->filter_graph_); if (ret < 0) { ErrorL << “Cannot create buffer sink”; return nullptr; } ret = av_opt_set_bin(filter_ctx->buffersink_ctx_, “pix_fmts”, (uint8_t*)&ocodec_ctx_->pix_fmt, sizeof(ocodec_ctx_->pix_fmt), AV_OPT_SEARCH_CHILDREN); if (ret < 0) { ErrorL << “Cannot set output pixel format”; return nullptr; } AVFilterInOut* outputs = avfilter_inout_alloc();; outputs->name = av_strdup(“in”); outputs->filter_ctx = filter_ctx->buffersrc_ctx_; outputs->pad_idx = 0; outputs->next = nullptr; AVFilterInOut inputs = avfilter_inout_alloc(); inputs->name = av_strdup(“out”); inputs->filter_ctx = filter_ctx->buffersink_ctx_; inputs->pad_idx = 0; inputs->next = NULL; std::string filter_spec = “[in]scale=” + std::to_string(kWidth) + “:” + std::to_string(kHeight) + “[out]”; do { ret = avfilter_graph_parse_ptr(filter_ctx->filter_graph_, filter_spec.c_str(), &inputs, &outputs, nullptr); if (ret < 0) { ErrorL << “avfilter graph parse failed”; break; } ret = avfilter_graph_config(filter_ctx->filter_graph_, nullptr); if (ret < 0) { ErrorL << “avfilter graph config failed”; break; } } while (0); avfilter_inout_free(&inputs); avfilter_inout_free(&outputs); return ret < 0 ? nullptr : filter_ctx; } int RollPollingWorker::FilterFrame(FilterContext filter, AVFrame* frame) { int ret = av_buffersrc_add_frame_flags(filter->buffersrc_ctx_, frame, 0); if (ret < 0) { ErrorL << “Error while feeding the filtergraph \n”; return ret; } while (1) { ret = av_buffersink_get_frame(filter->buffersink_ctx_, filter->filter_frame_); if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } filter->filter_frame_->pict_type = AV_PICTURE_TYPE_NONE; if (need_idr_) { filter->filter_frame_->pict_type = AV_PICTURE_TYPE_I; need_idr_ = false; } ret = EncodeFrame(filter->filter_frame_); av_frame_unref(filter->filter_frame_); if (ret < 0) break; } return ret; } int RollPollingWorker::EncodeFrame(AVFrame* frame) { if (avcodec_send_frame(ocodec_ctx_, frame) < 0) return -1; AVPacket* enc_pkt = av_packet_alloc(); int ret = 0; while (ret >= 0) { ret = avcodec_receive_packet(ocodec_ctx_, enc_pkt); if (ret < 0) { if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) ret = 0; break; } enc_pkt->stream_index = 0; enc_pkt->pts = enc_pkt->dts = (frame_cnt_++) * 40; enc_pkt->duration = 0; enc_pkt->pos = -1; //std::cerr << “muxing frame: pts " << enc_pkt->pts << " duration " << enc_pkt->duration << “\n”; ret = av_interleaved_write_frame(ofmt_ctx_, enc_pkt); av_packet_unref(enc_pkt); if (ret < 0) { ErrorL << Prefix() << " write packet to output file failed \n”; break; } } av_packet_free(&enc_pkt); return ret; } int RollPollingWorkerPool::StartWorker(const std::string input, const std::string output) { std::shared_ptr<RollPollingWorker> worker = std::make_shared<RollPollingWorker>(); if (!worker->Start(input, output)) { return -1; } std::weak_ptr<RollPollingWorker> weak_worker = worker; auto task = [weak_worker](int64_t unused){ auto worker = weak_worker.lock(); if (worker) worker->Runnable(); }; std::lock_guard<std::mutex> lock(mutex_); worker_list_[output] = worker; return 0; } int RollPollingWorkerPool::StopWorker(const std::string url) { std::lock_guard<std::mutex> lock(mutex_); auto it = worker_list_.find(url); return it != worker_list_.end() ? it->second->Stop() : -1; } int RollPollingWorkerPool::PollingStart(const std::vector<std::string> inputsurl, const std::string outputurl) { std::vector<std::string> inputs = inputsurl ; // for (int i = 1; i < (argc - 1); i++) // inputs.push_back(argv[i]); // std::string output = argv[argc - 1]; std::string output = outputurl; mediakit::RollPollingWorker worker; if (worker.Start(inputs[0], output) < 0) return -1; auto f = &{ worker.Runnable(); }; std::thread task(f); task.detach(); size_t idx = 1; while (worker.IsRunning()) { std::this_thread::sleep_for(std::chrono::milliseconds(10000)); if (idx >= 4) break; if (inputs.size() > 1) { std::string tmp = inputs[idx % inputs.size()]; std::cerr << “change input file to [” << tmp << “\n”; worker.UpdateInput(tmp); idx++; } } worker.Stop(); //task.join(); return 0; } } 代码的每一行都加上中文注释。
be3dc457988c4089f7f49078ab254277
{ "intermediate": 0.3615835905075073, "beginner": 0.4444482922554016, "expert": 0.19396813213825226 }
1,688
Give me example of code written in open processing that will identify rectangles and squares in an image
4efc992d9abd9d2b782889ee61362ff2
{ "intermediate": 0.3454929292201996, "beginner": 0.0661056861281395, "expert": 0.5884013772010803 }
1,689
i want to create a cmake system
b3cc2e0f06b4c94558dc1346fc996a92
{ "intermediate": 0.3217736482620239, "beginner": 0.169736847281456, "expert": 0.5084894895553589 }
1,690
//test let gameStorageServiceStub: SinonStubbedInstance<GameStorageService>; let socketManagerServiceStub: SinonStubbedInstance<SocketManager>; let sandbox: SinonSandbox; let expressApp: Express.Application; beforeEach(async () => { sandbox = createSandbox(); gameStorageServiceStub = createStubInstance(GameStorageService); socketManagerServiceStub = createStubInstance(SocketManager); const app = Container.get(Application); Object.defineProperty(app['gamesController'], 'gameStorageService', { value: gameStorageServiceStub }); Object.defineProperty(app['gamesController'], 'socketManagerService', { value: socketManagerServiceStub }); expressApp = app.app; }); //games controller : this.router.post('/saveGame', async (req: Request, res: Response) => { this.gameStorageService.storeGameImages(receivedNameForm.gameId, buffer1, buffer2); const newGameToAdd: GameData = { }; this.gameStorageService .storeGameResult(newGameToAdd) .then(() => { // we need to send a socket to refresh the game list this.socketManagerService.sendRefreshAvailableGames(); res.status(StatusCodes.CREATED).send({ body: receivedNameForm.gameName }); }) .catch((error: Error) => { res.status(StatusCodes.NOT_FOUND).send(error.message); }); }); //error : 1) GamesController "before each" hook for "fetchGame should catch error": TypeError: Cannot redefine property: socketManagerService Fix the error
d00807f1a8e2b4c0c1d4e924dc0ce334
{ "intermediate": 0.4372236132621765, "beginner": 0.3303406238555908, "expert": 0.23243579268455505 }
1,691
How do I implement dragging a window using its client area
8056984da69966e80536a19ee9802eb8
{ "intermediate": 0.47403809428215027, "beginner": 0.20538091659545898, "expert": 0.32058095932006836 }
1,692
Acting as a professional chatgpt user and coder, write me a 5000 word how-to book that teaches new users how to use chatgpt in ebook publishing format.
bfd9e79d034f48c2bc904f95d07d54f0
{ "intermediate": 0.45640087127685547, "beginner": 0.31497952342033386, "expert": 0.22861960530281067 }
1,693
I partially understand the primal-dual relationship, but I still can't see how two problems (primal and dual) connected together, how one problem transformated naturally into another problem such that one equation tune specific part in another equation. Help me please
fa589cc0e3797f64403684bd8a25fe1e
{ "intermediate": 0.35381171107292175, "beginner": 0.30405789613723755, "expert": 0.3421304523944855 }
1,694
what is the chemical formula of dental plastic for prothetics
29bce683318c5caec26a230a5fa5466d
{ "intermediate": 0.3706340193748474, "beginner": 0.3075135350227356, "expert": 0.3218524754047394 }
1,695
any good tool for automatic generating subtitle for my video recording?
e1b8d4bafb81a4b8e82a7d95a811c7d4
{ "intermediate": 0.34973618388175964, "beginner": 0.2222001850605011, "expert": 0.42806360125541687 }
1,696
android compose 调用 view
facc370a90c216a6f6cc8d934c0f1a30
{ "intermediate": 0.4218185245990753, "beginner": 0.26792001724243164, "expert": 0.3102615177631378 }
1,697
how to create a tool in ArcMap, the input is a polyline shp and the function is create 8 fields in its attribute table, namely start point Longitude, start point Latitude, start point Timbalai X, start point Timbalai Y, end point Longitude, end point Latitude, end point Timbalai X, end point Timbalai Y, and fill them with the info. note that the latitude and longitude should be in decimal degree format
a33bd3e339b26cfcdb7891675367c0a6
{ "intermediate": 0.561252236366272, "beginner": 0.2047058492898941, "expert": 0.23404191434383392 }
1,698
fivem lua I'm working on a fruit picking script but can't find the right animation
039472018958960a0360b750bcef0fad
{ "intermediate": 0.34023281931877136, "beginner": 0.35613125562667847, "expert": 0.30363592505455017 }
1,699
fivem lua is there a way to slow down an animation but also control how far through the animation is played
97e2b258d863e741381bb82dec6e9714
{ "intermediate": 0.28337469696998596, "beginner": 0.19357888400554657, "expert": 0.5230464339256287 }
1,700
I’m working on a fivem volleyball script what gta 5 animation looks like this? https://cdn.discordapp.com/attachments/1052780891300184096/1098469494197850224/image.png
a258e8bc46259668580148eac928b5af
{ "intermediate": 0.1810625195503235, "beginner": 0.2193119078874588, "expert": 0.5996255874633789 }
1,701
Tell me about Wesley Pichardo the man born in the bronx who's 24 years old
c67a0558b783928e1b0c13c8e0e986f9
{ "intermediate": 0.36184826493263245, "beginner": 0.2834428548812866, "expert": 0.3547089099884033 }
1,702
fivem lua is it possible to smooth an animation so it doesn't look so choppy?
41e9be8c47d07f292ba147ab5625964f
{ "intermediate": 0.2857421934604645, "beginner": 0.24187006056308746, "expert": 0.47238773107528687 }
1,703
what is the best thread concept in java to distribute tasks to gpu shaders ? give example code
1937a0d6d186397c66422db961ab4376
{ "intermediate": 0.5599464178085327, "beginner": 0.10535559803247452, "expert": 0.3346979320049286 }
1,704
explain cmake include vs cmake macro, i feel they are almost the same
986cf5a3ac86de7f48a1b9e9a47223eb
{ "intermediate": 0.5004602670669556, "beginner": 0.2553906738758087, "expert": 0.24414904415607452 }
1,705
.net core中使用minio的方法
3b4231c07bcff5f0dff25e821999326f
{ "intermediate": 0.34658539295196533, "beginner": 0.23214343190193176, "expert": 0.4212711453437805 }