row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
502
This are physically attched to the host & offer high perfomance Extremely high perfomance very low latency EBS volumes are attched over the network Instance store volume are ephmeral (non - persistent) data lost when instance power down use for temp data EBS persistent storage & instance storage non persistent While launching an instance we can see an option EBS only or disk space only disk space is instance store scan all the text I have given above & from above text create questions Now give answers to these questions By writing question 1st & thier answers
3046e7acae9021ac0337d034306fb3a7
{ "intermediate": 0.37939637899398804, "beginner": 0.27518633008003235, "expert": 0.3454173505306244 }
503
admin url path in django project '
4fcdcc5b78186012cfe8ddf913b9c6b2
{ "intermediate": 0.43714550137519836, "beginner": 0.2338133007287979, "expert": 0.32904118299484253 }
504
I want to create a chrome extension that does : when surfing a website or a Wikipedia page when i came across a term or topic , and I want to know immediately what elon musk said about that topic or term
7d864eb533df16ebf9052722db31dd8a
{ "intermediate": 0.3436185419559479, "beginner": 0.25034281611442566, "expert": 0.4060386121273041 }
505
nodejs new Function()
021dc7f1e607c2ec71a7c61a31b55dbe
{ "intermediate": 0.28003713488578796, "beginner": 0.45613402128219604, "expert": 0.2638288140296936 }
506
use tab instead of spaces only in python. i have an init.lua file in my ~/.config/nvim
7265d4a0265aa68795afe19cb5b69f23
{ "intermediate": 0.3377642333507538, "beginner": 0.3302415907382965, "expert": 0.3319942355155945 }
507
import React, {useState, useEffect, ChangeEvent} from "react"; import { Badge, Box, Button, ButtonGroup, Chip, CircularProgress, Grid, Icon, IconButton, Skeleton, TextField, Typography } from "@mui/material"; import ArrowUpwardRoundedIcon from '@mui/icons-material/ArrowUpwardRounded'; import ArrowDownwardRoundedIcon from '@mui/icons-material/ArrowDownwardRounded'; import {useAuthContext} from "../../AuthProvider/AuthProvider"; import FormatPrice from "../../Common/FormatPrice"; import {Order, readCandlesByTrade, readOrderByTrade, Trade, updateTrade} from "../../../actions/cicap-diary-trades"; import DataTable from "../../DataTable/DataTable"; import {useSnackbar} from "notistack"; import {CandleChart} from "../CandleChart/CandleChart"; import {TradeEntity} from "../CandleChart/CandleChart.props"; import {FormattedNumber} from "react-intl"; import ImageIcon from "next/image"; import {createTradeImage, deleteTradeImage, tradeImagesCollection, TradeImage} from "../../../actions/cicap-diary-trades-images"; const timezoneOffset = new Date().getTimezoneOffset() * 60; interface SideTypeProps { order: Order; } const SideType = ({order}: SideTypeProps) => { let label = ''; let color = 'default'; const icon = order?.side && 'sell' === order.side ? ArrowDownwardRoundedIcon : ArrowUpwardRoundedIcon; switch (order?.type) { case 'limit': label = 'L'; color = 'success' break; case 'market': label = 'M'; color = 'warning' break; case 'stop_market': label = 'F'; color = 'primary' break; } return <> <Badge badgeContent={label} // @ts-ignore color={color} > <Icon component={icon} color="action" /> </Badge> </> } interface CandlePrice { timestamp: number; open: number; high: number; low: number; close: number; volume: number; } interface TradeDetailsProps { tradeId: string; defaultChartInterval: string; } const TradeDetails = ({tradeId, defaultChartInterval}: TradeDetailsProps) => { const [trade, setTrade] = useState<{orders: Array<Order>, data: Trade} | undefined>(undefined); const [orders, setOrders] = useState<Array<TradeEntity>>([]); const [chartInterval, setChartInterval] = useState(defaultChartInterval); const [waiting, setWaiting] = useState(false); const [candleData, setCandleData] = useState<Array<CandlePrice>>([]); const [images, setImages] = useState<Array<TradeImage>>([]); const [imageIdDeletion, setImageIdDeletion] = useState<string|null>(null); const {diaryToken} = useAuthContext(); const [description, setDescription] = useState(''); const [conclusion, setConclusion] = useState(''); const [videoLink, setVideoLink] = useState(''); const {enqueueSnackbar} = useSnackbar(); const ref = React.createRef<HTMLInputElement>(); const fetchTrade = () => { if (!tradeId || !diaryToken) { return; } setWaiting(true); readOrderByTrade(tradeId, diaryToken) .then(data => { setWaiting(false); if (!data) return; const newOrders: Array<TradeEntity> = []; data.orders.forEach(order => { const timestamp = Math.floor(order.msTimestamp) - timezoneOffset; newOrders.push({ time: timestamp, position: order.side, value: parseFloat(order.price), }); }); setTrade(data); setOrders(newOrders); }); } const fetchImages = () => { if (!tradeId || !diaryToken) { return; } tradeImagesCollection(tradeId, diaryToken) .then(data => { if (!data) return; setImages(data.data) }) } const createImage = (name: string, content: string) => { if (!tradeId || !diaryToken) { return; } createTradeImage(tradeId, {name: name, content: content}, diaryToken) .then(data => { if (!data) return; setImages([...images, data.data]) }) } const fetchCandleData = () => { if (!tradeId || !diaryToken) { return; } setWaiting(true); readCandlesByTrade(tradeId, chartInterval, diaryToken) .then(data => { setWaiting(false); if (!data) return; // @ts-ignore const candles = data.data; const dataLength = candles.length; const kLines = []; for (let i = 0; i < dataLength; i += 1) { const timestamp = Math.floor(candles[i][0]) - timezoneOffset; kLines.push({ timestamp: timestamp, open: parseFloat(candles[i][1]), high: parseFloat(candles[i][2]), low: parseFloat(candles[i][3]), close: parseFloat(candles[i][4]), volume: parseFloat(candles[i][5]), }); } setCandleData(kLines); }) } const updateTradeHandle = () => { if (!diaryToken) return; if (!trade?.data.id) return; updateTrade(trade?.data.id, description, conclusion, videoLink, diaryToken) .then(data => { if (!data) return; fetchTrade(); enqueueSnackbar('Сделка обновлена.', {variant: 'success'}); }) } const onMainPhotoSelected = (e: ChangeEvent<HTMLInputElement>) => { if (!e.target.files) return const file = e.target.files[0] const reader = new FileReader() reader.onloadend = () => { if (!reader.result) return createImage(`chart-${tradeId}-${images.length}`, reader.result.toString()) } reader.readAsDataURL(file) } const removeGalleryImage = (imageId: string) => { if (!tradeId || !diaryToken) { return; } setImageIdDeletion(imageId) deleteTradeImage(tradeId, imageId, diaryToken) .then(data => { if (!data) return; fetchImages(); enqueueSnackbar('Изображение удалено', {variant: 'success'}); setImageIdDeletion(null) }) } useEffect(() => { fetchTrade(); fetchCandleData(); fetchImages() }, [tradeId]); useEffect(() => { fetchCandleData(); }, [chartInterval]); useEffect(() => { setDescription(trade?.data?.description || ''); setConclusion(trade?.data?.conclusion || ''); setVideoLink(trade?.data?.videoLink || ''); }, [trade]); return <> <Box sx={{p: 2, pb: 4, backgroundColor: '#f5f5f5'}}> <Box sx={{mb: 2}}> <Typography variant="h6" component="span"> {trade?.data?.symbolName} {trade?.data?.side.toUpperCase()} </Typography> &nbsp;&nbsp; <Chip label={`Процент: ${parseFloat(`${trade?.data?.percentDiffPrice}`).toFixed(Math.abs(parseFloat(`${trade?.data?.percentDiffPrice}`)) < 0.1 ? 3 : 2)}%`} color={parseFloat(`${trade?.data?.percentDiffPrice}`) >= 0 ? 'success' : 'error'} /> &nbsp; <Chip label={<>Прибыль: ${FormatPrice({ amount: parseFloat(`${trade?.data?.profit}`) || 0, currency_iso_code: 'USD'})}</>} /> </Box> <Grid container spacing={2}> <Grid item xs={12} md={6} sx={{pr: 2}}> <ButtonGroup variant="outlined" style={{ marginBottom: '1rem' }}> { ["1m", "3m", "5m", "15m", "30m", "1h", "4h", "12h", "1d"].map(interval => ( <Button key={interval} sx={{px: 1, py: .5, fontSize: '.75rem'}} variant={interval === chartInterval ? "contained" : "outlined"} onClick={() => setChartInterval(interval)} >{interval}</Button> )) } </ButtonGroup> &nbsp; { waiting ? ( <CircularProgress style={{position: "absolute", marginLeft: '1rem'}} color="inherit" size={32} /> ) : (<></>) } <Box sx={{pr: 2}}> { trade?.data.id && candleData ? (<> <CandleChart images={images} candles={candleData} tradeId={trade?.data.id} orders={orders} interval={chartInterval} openPrice={trade?.data.openPrice} closePrice={trade?.data.closePrice} pricePrecision={trade.data.pricePrecision} quantityPrecision={trade.data.quantityPrecision} createImage={createImage} /> </>) : (<> <Skeleton variant="rectangular" height={500} /> </>) } </Box> </Grid> <Grid item xs={12} md={3}> {trade?.orders && Array.isArray(trade.orders) ? ( <DataTable sx={{fontSize: '.75rem', '& .MuiDataGrid-cell': {py: 2}}} rows={trade.orders} hideFooter columns={[ {flex: 1, field: 'side', headerName: 'Сторона', sortable: false, filterable: false, renderCell: cell => (<> {cell.value.toUpperCase()} <SideType order={cell.row} /> </>)}, {flex: 1, field: 'quantity', headerName: 'Оборот', sortable: false, filterable: false }, {flex: 1, field: 'price', headerName: 'Цена', sortable: false, filterable: false, renderCell: cell => (<> <FormattedNumber value={cell.value} minimumFractionDigits={0} maximumFractionDigits={parseInt(trade?.data.pricePrecision || '10')} /> $ </>)}, {flex: 1, field: 'amount', headerName: 'Объем', sortable: false, filterable: false, renderCell: cell => (<> <FormattedNumber value={cell.value} minimumFractionDigits={0} maximumFractionDigits={parseInt(trade?.data.quantityPrecision || '10')} /> $ </>)}, {flex: 1, field: 'profit', headerName: 'Доход', sortable: false, filterable: false, renderCell: cell => (<> <FormattedNumber value={cell.value} minimumFractionDigits={0} maximumFractionDigits={4} /> $ </>)}, ]} /> ) : (<></>)} <Box sx={{my: 2}}> <Chip style={{ width: '1.5rem' }} size="small" label="M" color="warning" /> - Market order,&nbsp;&nbsp; <Chip style={{ width: '1.5rem' }} size="small" label="L" color="success" /> - Limit order,&nbsp;&nbsp; <Chip style={{ width: '1.5rem' }} size="small" label="F" color="primary" /> - Funding&nbsp; </Box> <Box sx={{ my: 2 }}> <Grid display="flex"> <Typography>Галерея</Typography> <input ref={ref} type='file' accept=".jpg, .jpeg" style={{ display: 'none' }} onChange={onMainPhotoSelected} /> <Button sx={{ ml: 3, width: 60, height: 25 }} onClick={() => ref && ref.current?.click()}> добавить </Button> </Grid> <Grid mt={3} > { images.map((image, index) => <span style={{ position: "relative", margin: "5px" }} key={index}> <a target='_blank' rel='noreferrer' href={image.url}> <ImageIcon style={{ cursor: "pointer", opacity: imageIdDeletion === image.id ? 0.4 : 1, margin: 5 }} key={image.id + index} src={image.url} width={160} height={120} alt="" /> </a> { imageIdDeletion === image.id ? <CircularProgress style={{ position: "absolute", left: 55, top: -65 }} color="error" size={42} /> : <></> } <IconButton color="error" sx={{ position: "absolute", right: 0, top: -114, borderRadius: 2 }} onClick={() => removeGalleryImage(image.id)} > x </IconButton> </span> ) } </Grid> </Box> </Grid> <Grid item xs={12} md={3}> <Typography>Описание:</Typography> <TextField fullWidth sx={{mb: 2}} variant="outlined" value={description} onChange={e => { setDescription(e.target.value); }} multiline rows={3} /> <Typography>Вывод:</Typography> <TextField fullWidth sx={{mb: 2}} variant="outlined" value={conclusion} onChange={e => { setConclusion(e.target.value); }} multiline rows={3} /> <Typography>Ссылка на видео:</Typography> <TextField fullWidth variant="outlined" value={videoLink} onChange={e => { setVideoLink(e.target.value); }} /> <Button color="primary" variant="contained" sx={{mt: 2}} onClick={updateTradeHandle}>Сохранить</Button> </Grid> </Grid> </Box> </> } export default TradeDetails; import React, {useEffect, useRef, useState} from "react"; import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from "klinecharts"; import {CandleChartProps} from "./CandleChart.props"; import CandleChartToolbar from "./CandleChartToolbar"; import {Style} from "util"; import {Box, Icon, IconButton, Stack} from "@mui/material"; import getMinutesTickSizeByInterval from "./utils/getMinutesTickSizeByInterval.util"; import drawTrade from "./utils/drawTrade.util"; import drawTradeLines from "./utils/drawTradeLines.util"; import {BasketIcon, ScreenIcon} from "../../icons"; import {FullScreen, useFullScreenHandle} from "react-full-screen";; // @ts-ignore const chartStyles: DeepPartial<Style> = { candle: { bar: { upColor: "#4caf50", downColor: "#d32f2f", noChangeColor: "" }, priceMark: { high: { textFamily: "Mont", }, low: { textFamily: "Mont", }, last: { text: { family: "Mont", } } }, tooltip: { text: { family: "Mont", marginLeft: 10, marginTop: 8, marginRight: 10 } } }, indicator: { ohlc: { upColor: "red", downColor: "red", noChangeColor: "red" }, bars: [{ upColor: "#4caf50", downColor: "#d32f2f", noChangeColor: "" }], lastValueMark: { show: false, text: { family: "Mont", } }, tooltip: { text: { family: "Mont", }, }, }, xAxis: { tickText: { family: "Mont", } }, yAxis: { type: "log", tickText: { family: "Mont", }, }, crosshair: { horizontal: { text: { family: "Mont", } }, vertical: { text: { family: "Mont", } } }, overlay: { text: { family: "Mont", }, rectText: { family: "Mont", backgroundColor: "#686D76", } } } interface Vol { volume?: number } export const CandleChart = ({ images, candles, tradeId, orders, interval, openPrice, closePrice, pricePrecision, quantityPrecision, createImage }: CandleChartProps) => { console.log(candles); const chart = useRef<Chart|null>(); const paneId = useRef<string>(""); const [figureId, setFigureId] = useState<string>("") const ref = useRef<HTMLDivElement>(null); const handle = useFullScreenHandle(); const onWindowResize = () => chart.current?.resize() useEffect(() => { window.addEventListener("resize", onWindowResize); onWindowResize(); return () => { window.removeEventListener("resize", onWindowResize); }; }, [ref, handle]); useEffect(() => { chart.current = init(`chart-${tradeId}`, {styles: chartStyles}); return () => dispose(`chart-${tradeId}`); }, [tradeId]); useEffect(() => { const onWindowResize = () => chart.current?.resize(); window.addEventListener("resize", onWindowResize); return () => window.removeEventListener("resize", onWindowResize); }, []); useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: "VOL", shortName: "Объем", calcParams: [], figures: [ { key: "volume", title: "", type: "bar", baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData let color: string if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, "bars[0].upColor", (defaultStyles.bars)[0].upColor) as string } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, "bars[0].downColor", (defaultStyles.bars)[0].downColor) as string } else { color = utils.formatValue(indicator.styles, "bars[0].noChangeColor", (defaultStyles.bars)[0].noChangeColor) as string } return { color } } } ] }, paneId.current); chart.current?.createIndicator("VOL", false, { id: paneId.current }); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]); useEffect(() => { if (!orders || orders.length === 0 || candles.length === 0) return; const minTime = orders[0].time; const maxTime = orders[orders.length - 1].time; const needleTime = minTime + (maxTime - minTime) / 2; chart.current?.scrollToTimestamp(needleTime + 45 * getMinutesTickSizeByInterval(interval) * 60 * 1000); drawTrade(chart, paneId, orders, interval); if (openPrice && closePrice) { let openTime = Infinity; let closeTime = -Infinity; orders.forEach(order => { if (openTime > order.time) { openTime = order.time; } if (closeTime < order.time) { closeTime = order.time; } }); drawTradeLines( chart, openPrice, openTime, closePrice, closeTime, orders[0].position, paneId, pricePrecision, quantityPrecision, ); } }, [orders, candles, tradeId]); const removeFigure = () => { chart.current?.removeOverlay({ id: figureId }) setFigureId("") } const onButtonClick = async () => { const imgUrl = chart.current?.getConvertPictureUrl(true) if (!imgUrl) return createImage(`chart-${tradeId}-${images.length}`, imgUrl) const link = document.createElement("a"); link.setAttribute("href", imgUrl); link.setAttribute("download", `chart-${tradeId}.jpg`); link.click(); } return (<> <FullScreen handle={handle}> <Box height={!handle.active ? 590 : "100%"} sx={{ position: "relative", background: "#ffffff" }}> <Box sx={{ borderBottom: "1px solid #ddd" }}> <Box sx={{ borderLeft: "1px solid #ddd", ml: "55px" }}> <IconButton sx={{ borderRadius: 2, ml: 1, fontSize: "1rem", fontFamily: "Mont", color: "#677294" }} onClick={onButtonClick}> <Icon component={ScreenIcon} /> Screenshot </IconButton> </Box> </Box> <Stack direction="row" height={!handle.active ? 550 : "100%"} width="100%"> <CandleChartToolbar setFigureId={setFigureId} chart={chart} paneId={paneId} handle={handle} /> <Box ref={ref} id={`chart-${tradeId}`} width="calc(100% - 55px)" height={!handle.active ? 550 : "100%"} sx={{ borderLeft: "1px solid #ddd" }} > { figureId.length > 0 && <Stack sx={{ backgroundColor: "#CBD4E3", borderRadius: 1, position: "absolute", zIndex: 10, right: 80, top: 30, border: "1px solid #697669", }} spacing={2} > <IconButton sx={{ borderRadius: 1 }} onClick={removeFigure}> <Icon component={BasketIcon} /> </IconButton> </Stack> } </Box> </Stack> </Box> </FullScreen> </>); } В тех сделках, где нет закрытого ордера нужно отображать на графике свечи в реальном времени и по текущей цене рассчитывать процент. Это нужно, чтобы можно было следить за сделкой в реальном времени. Нужно чтобы график отображал текущую ситуацию на рынке, как здесь https://www.binance.com/ru/futures/DOGEUSDT
cd8308a253edd3623fb38ea32e36cfd8
{ "intermediate": 0.4048151671886444, "beginner": 0.41602393984794617, "expert": 0.1791609227657318 }
508
import streamlit as st import pandas as pd import requests import json from PIL import Image from io import BytesIO from itertools import groupby import instaloader import datetime access_token = "" account_id = "" instaloading = instaloader.Instaloader() def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement)", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"__{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) st.image(image, caption=selected_data["caption"]) likes = selected_data["like_count"] if "insights" in selected_data.keys(): try: impressions = selected_data["insights"][0]['values'][0]['value'] percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.2f}%)") except (KeyError, IndexError): st.write(f"いいね: {likes}") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") elif choice == "Analytics": categories = ["フォロワー数", "いいね数", "コメント数"] selected_category = st.selectbox("Select metric", categories) if selected_category == "フォロワー数": # フォロワー数を使ったグラフの作成 st.write("Here you can display the followers count graph") elif selected_category == "いいね数": # いいね数を使ったグラフの作成 st.write("Here you can display the likes count graph") elif selected_category == "コメント数": # コメント数を使ったグラフの作成 st.write("Here you can display the comments count graph") ''' 上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所ががあり以下に改修点を列挙します。①"Content"で右ペインにpostされた当該コンテンツの画像が大きすぎるため縦横サイズを半分ほどに縮小表示してほしい。②"Content"の右ペインの"いいね数"の隣に「インプレッション数と"いいね数"から計算された"いいね"実施率」を"(24.9%)"のように小数点第一位まで表示してほしい。③"コメント数"の下に、実際のコメント一覧とコメントしたユーザ名をリスト表示してほしい。④左ペインで"Analytics"を選択し、右ペインでリストからmetricを選択してもグラフが表示されない。例えば、投稿日を基準とした時系列を横軸にして、"フォロワー数"や"いいね数"などを縦軸に設定して"フォロワー数"や"いいね数"などのデータをグラフ脇のリストから選択して動的に表示できるように改修してほしい。これらの機能が正常に動作するよう修正済みのコードを省略せずにすべて表示してください。もしコード内にアンダースコアを2つ連続で使用するのであれば、出力時に不可視にされてしまうので"__"に置換して表示してください。
a7c32915130cf7ae1e4eac66ac8a6568
{ "intermediate": 0.47716858983039856, "beginner": 0.349801629781723, "expert": 0.1730298101902008 }
509
nvim tabs instead of spaces for only python files in inti.lua file
a6c610e106bb4ad61137fd79a05faeed
{ "intermediate": 0.337088406085968, "beginner": 0.29968878626823425, "expert": 0.36322274804115295 }
510
how to add user in openconnect to group
b86a19ae5fb38616dd5c904bed360d9f
{ "intermediate": 0.410677433013916, "beginner": 0.23046602308750153, "expert": 0.3588564991950989 }
511
const readOrderByTrade = ( tradeId: string, token: string, ): Promise<{data:Trade,orders:Array<Order>}|undefined> => { return diaryClient( `/trades/${tradeId}/orders`, 'get', token, ); } const [trade, setTrade] = useState<{orders: Array<Order>, data: Trade} | undefined>(undefined); const [orders, setOrders] = useState<Array<TradeEntity>>([]); const fetchTrade = () => { if (!tradeId || !diaryToken) { return; } setWaiting(true); readOrderByTrade(tradeId, diaryToken) .then(data => { setWaiting(false); if (!data) return; const newOrders: Array<TradeEntity> = []; data.orders.forEach(order => { const timestamp = Math.floor(order.msTimestamp) - timezoneOffset; newOrders.push({ time: timestamp, position: order.side, value: parseFloat(order.price), }); }); setTrade(data); setOrders(newOrders); }); } const fetchCandleData = () => { if (!tradeId || !diaryToken) { return; } setWaiting(true); readCandlesByTrade(tradeId, chartInterval, diaryToken) .then(data => { setWaiting(false); if (!data) return; // @ts-ignore const candles = data.data; const dataLength = candles.length; const kLines = []; for (let i = 0; i < dataLength; i += 1) { const timestamp = Math.floor(candles[i][0]) - timezoneOffset; kLines.push({ timestamp: timestamp, open: parseFloat(candles[i][1]), high: parseFloat(candles[i][2]), low: parseFloat(candles[i][3]), close: parseFloat(candles[i][4]), volume: parseFloat(candles[i][5]), }); } setCandleData(kLines); }) } return <> <Box sx={{pr: 2}}> { trade?.data.id && candleData ? (<> <CandleChart images={images} candles={candleData} tradeId={trade?.data.id} orders={orders} interval={chartInterval} openPrice={trade?.data.openPrice} closePrice={trade?.data.closePrice} pricePrecision={trade.data.pricePrecision} quantityPrecision={trade.data.quantityPrecision} createImage={createImage} /> </>) : (<> <Skeleton variant="rectangular" height={500} /> </>) } </Box> </>); } import React, {useEffect, useRef, useState} from "react"; import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from "klinecharts"; import {CandleChartProps} from "./CandleChart.props"; import CandleChartToolbar from "./CandleChartToolbar"; import {Style} from "util"; import {Box, Icon, IconButton, Stack} from "@mui/material"; import getMinutesTickSizeByInterval from "./utils/getMinutesTickSizeByInterval.util"; import drawTrade from "./utils/drawTrade.util"; import drawTradeLines from "./utils/drawTradeLines.util"; import {BasketIcon, ScreenIcon} from "../../icons"; import {FullScreen, useFullScreenHandle} from "react-full-screen";; // @ts-ignore const chartStyles: DeepPartial<Style> = { candle: { bar: { upColor: "#4caf50", downColor: "#d32f2f", noChangeColor: "" }, priceMark: { high: { textFamily: "Mont", }, low: { textFamily: "Mont", }, last: { text: { family: "Mont", } } }, tooltip: { text: { family: "Mont", marginLeft: 10, marginTop: 8, marginRight: 10 } } }, indicator: { ohlc: { upColor: "red", downColor: "red", noChangeColor: "red" }, bars: [{ upColor: "#4caf50", downColor: "#d32f2f", noChangeColor: "" }], lastValueMark: { show: false, text: { family: "Mont", } }, tooltip: { text: { family: "Mont", }, }, }, xAxis: { tickText: { family: "Mont", } }, yAxis: { type: "log", tickText: { family: "Mont", }, }, crosshair: { horizontal: { text: { family: "Mont", } }, vertical: { text: { family: "Mont", } } }, overlay: { text: { family: "Mont", }, rectText: { family: "Mont", backgroundColor: "#686D76", } } } interface Vol { volume?: number } export const CandleChart = ({ images, candles, tradeId, orders, interval, openPrice, closePrice, pricePrecision, quantityPrecision, createImage }: CandleChartProps) => { console.log(candles); const chart = useRef<Chart|null>(); const paneId = useRef<string>(""); const [figureId, setFigureId] = useState<string>("") const ref = useRef<HTMLDivElement>(null); const handle = useFullScreenHandle(); useEffect(() => { chart.current = init(`chart-${tradeId}`, {styles: chartStyles}); return () => dispose(`chart-${tradeId}`); }, [tradeId]); useEffect(() => { const onWindowResize = () => chart.current?.resize(); window.addEventListener("resize", onWindowResize); return () => window.removeEventListener("resize", onWindowResize); }, []); useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: "VOL", shortName: "Объем", calcParams: [], figures: [ { key: "volume", title: "", type: "bar", baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData let color: string if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, "bars[0].upColor", (defaultStyles.bars)[0].upColor) as string } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, "bars[0].downColor", (defaultStyles.bars)[0].downColor) as string } else { color = utils.formatValue(indicator.styles, "bars[0].noChangeColor", (defaultStyles.bars)[0].noChangeColor) as string } return { color } } } ] }, paneId.current); chart.current?.createIndicator("VOL", false, { id: paneId.current }); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]); useEffect(() => { if (!orders || orders.length === 0 || candles.length === 0) return; const minTime = orders[0].time; const maxTime = orders[orders.length - 1].time; const needleTime = minTime + (maxTime - minTime) / 2; chart.current?.scrollToTimestamp(needleTime + 45 * getMinutesTickSizeByInterval(interval) * 60 * 1000); drawTrade(chart, paneId, orders, interval); if (openPrice && closePrice) { let openTime = Infinity; let closeTime = -Infinity; orders.forEach(order => { if (openTime > order.time) { openTime = order.time; } if (closeTime < order.time) { closeTime = order.time; } }); drawTradeLines( chart, openPrice, openTime, closePrice, closeTime, orders[0].position, paneId, pricePrecision, quantityPrecision, ); } }, [orders, candles, tradeId]); return (<> <Stack direction="row" height={!handle.active ? 550 : "100%"} width="100%"> <CandleChartToolbar setFigureId={setFigureId} chart={chart} paneId={paneId} handle={handle} /> <Box ref={ref} id={`chart-${tradeId}`} width="calc(100% - 55px)" height={!handle.active ? 550 : "100%"} sx={{ borderLeft: "1px solid #ddd" }} > { figureId.length > 0 && <Stack sx={{ backgroundColor: "#CBD4E3", borderRadius: 1, position: "absolute", zIndex: 10, right: 80, top: 30, border: "1px solid #697669", }} spacing={2} > <IconButton sx={{ borderRadius: 1 }} onClick={removeFigure}> <Icon component={BasketIcon} /> </IconButton> </Stack> } </Box> </Stack> </>); } В тех сделках, где нет закрытого ордера нужно отображать на графике свечи в реальном времени и по текущей цене рассчитывать процент. Это нужно, чтобы можно было следить за сделкой в реальном времени. Нужно чтобы график отображал текущую ситуацию на рынке, как здесь https://www.binance.com/ru/futures/DOGEUSDT
1e3b7eb939f462415d44f0e16baf6928
{ "intermediate": 0.38178667426109314, "beginner": 0.44135773181915283, "expert": 0.1768556386232376 }
512
How to point to a clang-format-8.exe binary within the in-built clang formatter?
61eb7ff28f27b67ae4adb402a2a78554
{ "intermediate": 0.4338313639163971, "beginner": 0.26799577474594116, "expert": 0.29817283153533936 }
513
i found an tool that can get current playing song info in macos from the commandline, but i dont know how to install it: github: https://github.com/kirtan-shah/nowplaying-cli README.md: nowplaying-cli nowplaying-cli is a macOS command-line utility for retrieving currently playing media, and simulating media actions. Use nowplaying-cli to get song information and play/pause your media through an easy to use CLI! Disclaimer: nowplaying-cli uses private frameworks, which may cause it to break with future macOS software updates. Tested and working on: Ventura 13.1 Usage nowplaying-cli <cmd> command description get [propName1 propName2 … ] get now playing media properties get-raw get all non-nil now playing media properties in dictionary format play play the currently playing media regardless of current state pause pause the currently playing media regardless of current state togglePlayPause toggle play/pause based on current state next skip to next track previous go to previous track Examples screenshot of examples in terminal Available properties native nowplaying-cli kMRMediaRemoteNowPlayingInfoTotalDiscCount totalDiscCount kMRMediaRemoteNowPlayingInfoShuffleMode shuffleMode kMRMediaRemoteNowPlayingInfoTrackNumber trackNumber kMRMediaRemoteNowPlayingInfoDuration duration kMRMediaRemoteNowPlayingInfoRepeatMode repeatMode kMRMediaRemoteNowPlayingInfoTitle title kMRMediaRemoteNowPlayingInfoPlaybackRate playbackRate kMRMediaRemoteNowPlayingInfoArtworkData artworkData kMRMediaRemoteNowPlayingInfoAlbum album kMRMediaRemoteNowPlayingInfoTotalQueueCount totalQueueCount kMRMediaRemoteNowPlayingInfoArtworkMIMEType artworkMIMEType kMRMediaRemoteNowPlayingInfoMediaType mediaType kMRMediaRemoteNowPlayingInfoDiscNumber discNumber kMRMediaRemoteNowPlayingInfoTimestamp timestamp kMRMediaRemoteNowPlayingInfoGenre genre kMRMediaRemoteNowPlayingInfoQueueIndex queueIndex kMRMediaRemoteNowPlayingInfoArtist artist kMRMediaRemoteNowPlayingInfoDefaultPlaybackRate defaultPlaybackRate kMRMediaRemoteNowPlayingInfoElapsedTime elapsedTime kMRMediaRemoteNowPlayingInfoTotalTrackCount totalTrackCount kMRMediaRemoteNowPlayingInfoIsMusicApp isMusicApp kMRMediaRemoteNowPlayingInfoUniqueIdentifier uniqueIdentifier Homebrew Install TODO Build clang nowplaying.mm -framework Cocoa -o nowplaying-cli -O3 files: nowplaying.mm Enums.h
5e11d4d13cea90c435ee3a261876f150
{ "intermediate": 0.41671130061149597, "beginner": 0.2892118990421295, "expert": 0.2940768301486969 }
514
can you create a android studio app that edits a google sheet column
5f029630121a45a876533b902522e56e
{ "intermediate": 0.45324867963790894, "beginner": 0.1918979287147522, "expert": 0.35485342144966125 }
515
Pretend you are a Linux terminal running bash.
f51e0dbca6179bab25d554240142d412
{ "intermediate": 0.3553963899612427, "beginner": 0.36850792169570923, "expert": 0.2760957181453705 }
516
const readOrderByTrade = ( tradeId: string, token: string, ): Promise<{data:Trade,orders:Array<Order>}|undefined> => { return diaryClient( /trades/${tradeId}/orders, ‘get’, token, ); } const [trade, setTrade] = useState<{orders: Array<Order>, data: Trade} | undefined>(undefined); const [orders, setOrders] = useState<Array<TradeEntity>>([]); const fetchTrade = () => { if (!tradeId || !diaryToken) { return; } setWaiting(true); readOrderByTrade(tradeId, diaryToken) .then(data => { setWaiting(false); if (!data) return; const newOrders: Array<TradeEntity> = []; data.orders.forEach(order => { const timestamp = Math.floor(order.msTimestamp) - timezoneOffset; newOrders.push({ time: timestamp, position: order.side, value: parseFloat(order.price), }); }); setTrade(data); setOrders(newOrders); }); } const fetchCandleData = () => { if (!tradeId || !diaryToken) { return; } setWaiting(true); readCandlesByTrade(tradeId, chartInterval, diaryToken) .then(data => { setWaiting(false); if (!data) return; // @ts-ignore const candles = data.data; const dataLength = candles.length; const kLines = []; for (let i = 0; i < dataLength; i += 1) { const timestamp = Math.floor(candles[i][0]) - timezoneOffset; kLines.push({ timestamp: timestamp, open: parseFloat(candles[i][1]), high: parseFloat(candles[i][2]), low: parseFloat(candles[i][3]), close: parseFloat(candles[i][4]), volume: parseFloat(candles[i][5]), }); } setCandleData(kLines); }) } return <> <Box sx={{pr: 2}}> { trade?.data.id && candleData ? (<> <CandleChart images={images} candles={candleData} tradeId={trade?.data.id} orders={orders} interval={chartInterval} openPrice={trade?.data.openPrice} closePrice={trade?.data.closePrice} pricePrecision={trade.data.pricePrecision} quantityPrecision={trade.data.quantityPrecision} createImage={createImage} /> </>) : (<> <Skeleton variant=“rectangular” height={500} /> </>) } </Box> </>); } import React, {useEffect, useRef, useState} from “react”; import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from “klinecharts”; import {CandleChartProps} from “./CandleChart.props”; import CandleChartToolbar from “./CandleChartToolbar”; import {Style} from “util”; import {Box, Icon, IconButton, Stack} from “@mui/material”; import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”; import drawTrade from “./utils/drawTrade.util”; import drawTradeLines from “./utils/drawTradeLines.util”; import {BasketIcon, ScreenIcon} from “…/…/icons”; import {FullScreen, useFullScreenHandle} from “react-full-screen”;; interface Vol { volume?: number } export const CandleChart = ({ images, candles, tradeId, orders, interval, openPrice, closePrice, pricePrecision, quantityPrecision, createImage }: CandleChartProps) => { console.log(candles); const chart = useRef<Chart|null>(); const paneId = useRef<string>(“”); const [figureId, setFigureId] = useState<string>(“”) const ref = useRef<HTMLDivElement>(null); const handle = useFullScreenHandle(); useEffect(() => { chart.current = init(chart-${tradeId}, {styles: chartStyles}); return () => dispose(chart-${tradeId}); }, [tradeId]); useEffect(() => { const onWindowResize = () => chart.current?.resize(); window.addEventListener(“resize”, onWindowResize); return () => window.removeEventListener(“resize”, onWindowResize); }, []); useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: “VOL”, shortName: “Объем”, calcParams: [], figures: [ { key: “volume”, title: “”, type: “bar”, baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData let color: string if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string } else { color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string } return { color } } } ] }, paneId.current); chart.current?.createIndicator(“VOL”, false, { id: paneId.current }); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]); useEffect(() => { if (!orders || orders.length === 0 || candles.length === 0) return; const minTime = orders[0].time; const maxTime = orders[orders.length - 1].time; const needleTime = minTime + (maxTime - minTime) / 2; chart.current?.scrollToTimestamp(needleTime + 45 * getMinutesTickSizeByInterval(interval) * 60 * 1000); drawTrade(chart, paneId, orders, interval); if (openPrice && closePrice) { let openTime = Infinity; let closeTime = -Infinity; orders.forEach(order => { if (openTime > order.time) { openTime = order.time; } if (closeTime < order.time) { closeTime = order.time; } }); drawTradeLines( chart, openPrice, openTime, closePrice, closeTime, orders[0].position, paneId, pricePrecision, quantityPrecision, ); } }, [orders, candles, tradeId]); return (<> <Stack direction=“row” height={!handle.active ? 550 : “100%”} width=“100%”> <CandleChartToolbar setFigureId={setFigureId} chart={chart} paneId={paneId} handle={handle} /> <Box ref={ref} id={chart-${tradeId}} width=“calc(100% - 55px)” height={!handle.active ? 550 : “100%”} sx={{ borderLeft: “1px solid #ddd” }} > { figureId.length > 0 && <Stack sx={{ backgroundColor: “#CBD4E3”, borderRadius: 1, position: “absolute”, zIndex: 10, right: 80, top: 30, border: “1px solid #697669”, }} spacing={2} > <IconButton sx={{ borderRadius: 1 }} onClick={removeFigure}> <Icon component={BasketIcon} /> </IconButton> </Stack> } </Box> </Stack> </>); } В тех сделках, где нет закрытого ордера нужно отображать на графике свечи в реальном времени и по текущей цене рассчитывать процент. Это нужно, чтобы можно было следить за сделкой в реальном времени. Нужно чтобы график отображал текущую ситуацию на рынке, как здесь https://www.binance.com/ru/futures/DOGEUSDT
af69586e9ac853593cfa22fd338ea7c1
{ "intermediate": 0.33156001567840576, "beginner": 0.4901132881641388, "expert": 0.17832672595977783 }
517
I want to make an integer parameter in a pytorch module, how can I do that?
f0d7fa62a83e007ac6637ff75ed8c1c6
{ "intermediate": 0.5684312582015991, "beginner": 0.17100609838962555, "expert": 0.26056262850761414 }
518
Pretend to be a Commodore 64.
64d16ce78ede0c370d997bcc1e5c415a
{ "intermediate": 0.33610910177230835, "beginner": 0.4039357304573059, "expert": 0.25995516777038574 }
519
I’m trying to make a fivem NUI that displays a little points score at the top of the screen https://cdn.discordapp.com/attachments/1052780891300184096/1095659338003128380/image.png do you think i’m best to use react or just html css
d5a837d4c9a723a0e8f4e17cfdff5a40
{ "intermediate": 0.31530818343162537, "beginner": 0.22456710040569305, "expert": 0.4601247012615204 }
520
using https with nginx and gunicorn if i have ssl certificate
255ff28ddefb9035cd9e93bf11efb587
{ "intermediate": 0.4605598449707031, "beginner": 0.2390526682138443, "expert": 0.30038753151893616 }
521
Pretend to be a Linux terminal running on Pablo Picasso's computer.
4edf5b6c2a7633ee8dbcbc40bb0d3496
{ "intermediate": 0.3352341651916504, "beginner": 0.3124828636646271, "expert": 0.3522830009460449 }
522
''' import streamlit as st import pandas as pd import requests import json from PIL import Image from io import BytesIO from itertools import groupby import instaloader import datetime import altair as alt loader = instaloader.Instaloader() loader.context.request_timeout = (9, 15) # Increase request timeout access_token = "" account_id = "" def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement)", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"__{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) st.image(image, caption=selected_data["caption"], width=300) likes = selected_data["like_count"] if "insights" in selected_data.keys(): try: impressions = selected_data["insights"][0]['values'][0]['value'] percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)") except (KeyError, IndexError): st.write(f"いいね: {likes}") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") # Get comments and usernames try: shortcode = selected_data["permalink"].split("/")[-2] post = instaloader.Post.from_shortcode(loader.context, shortcode) comments = post.get_comments() for comment in comments: st.write(f"{comment.owner.username}: {comment.text}") except Exception as e: st.write("コメントの取得中にエラーが発生しました。") elif choice == "Analytics": categories = ["フォロワー数", "いいね数", "コメント数"] selected_category = st.selectbox("Select metric", categories) if selected_category == "フォロワー数": metric = "follower_count" elif selected_category == "いいね数": metric = "like_count" elif selected_category == "コメント数": metric = "comments_count" chart_df = df[["id", "timestamp", metric]].copy() chart_df["timestamp"] = pd.to_datetime(chart_df["timestamp"]).dt.date chart = alt.Chart(chart_df).mark_line().encode( x="timestamp:T", y=metric + ":Q" ).properties( title=f"Time Series of {selected_category}", width=800, height=300 ) st.altair_chart(chart) ''' 上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所があるため、以下に改修点を列挙します。 ①"Content"の右ペインの"いいね数"の隣に「インプレッション数と"いいね数"から計算された"いいね"実施率」を"(24.9%)"のように小数点第一位まで表示されていない ②"Content"の右ペインの"コメント数"の下に、実際のコメント一覧とコメントしたユーザ名が列挙されるリストが表示されない ③左ペインで"Analytics"を選択し、右ペインでリストから"metric"を選択した際に"フォロワー数"のみグラフが表示されない。この"フォロワー数"を選択した際の画面上のエラー表示は下記。 ''' KeyError: "['follower_count'] not in index" Traceback: File "/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/instagram_analytics.py", line 99, in <module> chart_df = df[["id", "timestamp", metric]].copy() File "/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/frame.py", line 3813, in __getitem__ indexer = self.columns._get_indexer_strict(key, "columns")[1] File "/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 6070, in _get_indexer_strict self._raise_if_missing(keyarr, indexer, axis_name) File "/home/walhalax/.var/app/org.jupyter.JupyterLab/config/jupyterlab-desktop/jlab_server/lib/python3.8/site-packages/pandas/core/indexes/base.py", line 6133, in _raise_if_missing raise KeyError(f"{not_found} not in index") ''' これらの機能が正常に動作するよう修正済みのコードを省略せずにすべて表示してください。
9fb6c8ccd9796ba1e526604432095614
{ "intermediate": 0.3807740807533264, "beginner": 0.3988170325756073, "expert": 0.22040878236293793 }
523
You need to develop a file sharing system. Two files are needed to be written i.e. client.c and server.c Server.c  It should allocate a shared memory and then wait until some client writes a command into the shared memory. Command can be of two formats: o read filename o write filename data  Read that command, clear the shared memory, and make a new thread.  If command is of read, make a new shared memory and share the key with the client process through old shared memory. Then copy the content of that file onto new shared memory.  If command is of write, copy the contents of the command onto file of specified name.  Use the semaphores to avoid any unwanted situation. Client.c  It should read the command from terminal, make sure it is in right format.  It should wait until there is no other writer or reader for shared memory. (Use semaphore)  And then it will write the command to the shared memory  If command is of read, wait until the response, and communicate with server to show the content of the file, then terminate.  If command is of write just terminate the process.
1361c852fbac46c9b60ce0f44f4282eb
{ "intermediate": 0.3716892898082733, "beginner": 0.3567473590373993, "expert": 0.2715632915496826 }
524
How do I make http request in c#
62951bd0393fd7ad31df3a0f4cb44dcb
{ "intermediate": 0.546500027179718, "beginner": 0.20066718757152557, "expert": 0.2528327703475952 }
525
How do I turn off the display for my macbook while I'm using hdmi
acfd69b4a809ee13263fb9eb8b0e6734
{ "intermediate": 0.508739709854126, "beginner": 0.23241905868053436, "expert": 0.25884124636650085 }
526
add stop button: package main import ( "io" "os" "sync" "gioui.org/app" "gioui.org/io/system" "gioui.org/layout" "gioui.org/op" "gioui.org/unit" "gioui.org/widget" "gioui.org/widget/material" "gioui.org/font/gofont" "github.com/tosone/minimp3" "github.com/hajimehoshi/oto" ) func main() { go func() { w := app.NewWindow( app.Title("mp3 reader"), app.Size(unit.Dp(350), unit.Dp(500)), ) var ops op.Ops for event := range w.Events() { switch event := event.(type) { case system.DestroyEvent: os.Exit(0) case system.FrameEvent: event.Frame(frame(layout.NewContext(&ops, event))) } } }() app.Main() } type ( // C quick alias for Context. C = layout.Context // D quick alias for Dimensions. D = layout.Dimensions ) var ( th = material.NewTheme(gofont.Collection()) topLabel = "mp3 reader" playBtn = widget.Clickable{} pauseBtn = widget.Clickable{} playing bool mu sync.Mutex player *oto.Player dec *minimp3.Decoder ) // frame lays out the entire frame and returns the resultant ops buffer. func frame(gtx C) *op.Ops { layout.Center.Layout(gtx, func(gtx C) D { gtx.Constraints.Max.X = gtx.Dp(unit.Dp(300)) return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { label := material.H5(th, topLabel) return label.Layout(gtx) }), layout.Rigid(func(gtx C) D { return material.Button(th, &playBtn, "Play").Layout(gtx) }), layout.Rigid(func(gtx C) D { return material.Button(th, &pauseBtn, "Pause").Layout(gtx) }), ) }) if playBtn.Clicked() { go func() { mu.Lock() if playing { mu.Unlock() return } playing = true mu.Unlock() var err error var file *os.File if file, err = os.Open("demo.mp3"); err != nil { return } if dec == nil { if dec, err = minimp3.NewDecoder(file); err != nil { return } started := dec.Started() <-started var context *oto.Context if context, err = oto.NewContext(dec.SampleRate, dec.Channels, 2, 1024); err != nil { return } player = context.NewPlayer() } for { var data = make([]byte, 1024) _, err := dec.Read(data) if err == io.EOF { break } if err != nil { break } player.Write(data) mu.Lock() if !playing { mu.Unlock() break } mu.Unlock() } mu.Lock() playing = false mu.Unlock() }() } if pauseBtn.Clicked() { mu.Lock() playing = false mu.Unlock() } return gtx.Ops }
4287c63a7fb165f14838b4019f81a815
{ "intermediate": 0.3896542489528656, "beginner": 0.44026702642440796, "expert": 0.17007876932621002 }
527
add stop button: package main import ( "io" "os" "sync" "gioui.org/app" "gioui.org/io/system" "gioui.org/layout" "gioui.org/op" "gioui.org/unit" "gioui.org/widget" "gioui.org/widget/material" "gioui.org/font/gofont" "github.com/tosone/minimp3" "github.com/hajimehoshi/oto" ) func main() { go func() { w := app.NewWindow( app.Title("mp3 reader"), app.Size(unit.Dp(350), unit.Dp(500)), ) var ops op.Ops for event := range w.Events() { switch event := event.(type) { case system.DestroyEvent: os.Exit(0) case system.FrameEvent: event.Frame(frame(layout.NewContext(&ops, event))) } } }() app.Main() } type ( // C quick alias for Context. C = layout.Context // D quick alias for Dimensions. D = layout.Dimensions ) var ( th = material.NewTheme(gofont.Collection()) topLabel = "mp3 reader" playBtn = widget.Clickable{} pauseBtn = widget.Clickable{} playing bool mu sync.Mutex player *oto.Player dec *minimp3.Decoder ) // frame lays out the entire frame and returns the resultant ops buffer. func frame(gtx C) *op.Ops { layout.Center.Layout(gtx, func(gtx C) D { gtx.Constraints.Max.X = gtx.Dp(unit.Dp(300)) return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { label := material.H5(th, topLabel) return label.Layout(gtx) }), layout.Rigid(func(gtx C) D { return material.Button(th, &playBtn, "Play").Layout(gtx) }), layout.Rigid(func(gtx C) D { return material.Button(th, &pauseBtn, "Pause").Layout(gtx) }), ) }) if playBtn.Clicked() { go func() { mu.Lock() if playing { mu.Unlock() return } playing = true mu.Unlock() var err error var file *os.File if file, err = os.Open("demo.mp3"); err != nil { return } if dec == nil { if dec, err = minimp3.NewDecoder(file); err != nil { return } started := dec.Started() <-started var context *oto.Context if context, err = oto.NewContext(dec.SampleRate, dec.Channels, 2, 1024); err != nil { return } player = context.NewPlayer() } for { var data = make([]byte, 1024) _, err := dec.Read(data) if err == io.EOF { break } if err != nil { break } player.Write(data) mu.Lock() if !playing { mu.Unlock() break } mu.Unlock() } mu.Lock() playing = false mu.Unlock() }() } if pauseBtn.Clicked() { mu.Lock() playing = false mu.Unlock() } return gtx.Ops }
10c613e9b4441ca65c8cda097bec1f1d
{ "intermediate": 0.3896542489528656, "beginner": 0.44026702642440796, "expert": 0.17007876932621002 }
528
this is my html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <title>Scoreboard</title> </head> <body> <div class="scoreboard"> <div class="points"> <span class="label">Points: </span> <span class="score">0</span> </div> </div> <script src="app.js"></script> </body> </html> css body { margin: 0; background-color: #111; } .scoreboard { position: fixed; top: 0; right: 0; background-color: rgba(0, 0, 0, 0.5); padding: 5px 15px; margin: 10px; border-radius: 5px; display: inline-flex; align-items: center; } .label { color: #ffffff; font-family: Arial, sans-serif; font-size: 14px; } .score { color: #247c24; font-family: Arial, sans-serif; font-size: 14px; font-weight: bold; margin-left: 5px; } I'm trying to center the scoreboard class but currently it only sits on the right
aefb543b89a37c824df569a5f2a26300
{ "intermediate": 0.3961728811264038, "beginner": 0.3132885694503784, "expert": 0.2905385494232178 }
529
''' import streamlit as st import pandas as pd import requests import json from PIL import Image from io import BytesIO from itertools import groupby import instaloader import datetime import altair as alt loader = instaloader.Instaloader() # For login username = "" password = "" loader.context.login(username, password) # Login loader.context.request_timeout = (9, 15) # Increase request timeout access_token = "" account_id = "" def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement)", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"__{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) st.image(image, caption=selected_data["caption"], width=300) likes = selected_data["like_count"] if "insights" in selected_data.keys(): try: impressions = selected_data["insights"][0]['values'][0]['value'] percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)") except (KeyError, IndexError): st.write(f"いいね: {likes}") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") # Get comments and usernames try: shortcode = selected_data["permalink"].split("/")[-2] post = instaloader.Post.from_shortcode(loader.context, shortcode) comments = post.get_comments() for comment in comments: st.write(f"{comment.owner.username}: {comment.text}") except Exception as e: st.write("コメントの取得中にエラーが発生しました。") elif choice == "Analytics": categories = ["いいね数", "コメント数"] selected_category = st.selectbox("Select metric", categories) if selected_category == "いいね数": metric = "like_count" elif selected_category == "コメント数": metric = "comments_count" chart_df = df[["id", "timestamp", metric]].copy() chart_df["timestamp"] = pd.to_datetime(chart_df["timestamp"]).dt.date chart = alt.Chart(chart_df).mark_line().encode( x="timestamp:T", y=metric + ":Q" ).properties( title=f"Time Series of {selected_category}", width=800, height=300 ) st.altair_chart(chart) ''' 上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所があるため、以下に改修点を列挙します。 ①いまだにコンテンツに対する"いいね率"の表示が正常にされておりません。抜本的な対処も含めて改修したコード全体を表示してください。 ②"Content"の説明文について、[Description]の前の文字列と、[Tags]を含むそれ以降の文字列を表示させないようにしたい。 ③"Content"を選択するための左ペインにあるリストにて、日付IDのフォーマットにアンダーバーが2つ連続しているが、アンダーバーを1つだけの表記にしたい。 ④"Content"のコメントとコメントユーザーのリストのフォントサイズを少しだけ大きくしたい。さらに、最新の3コメントのみの表示をデフォルトとして、"さらに表示"の文字を押下することで全件表示をするようにしたい。
ff76ea6e8998c87ac0e206a9d1c04c9e
{ "intermediate": 0.41424688696861267, "beginner": 0.4111219346523285, "expert": 0.1746312379837036 }
530
tell me about mvc
d1941b9a33268421cab176551ee720bf
{ "intermediate": 0.560580313205719, "beginner": 0.19354365766048431, "expert": 0.2458760291337967 }
531
Create a Unity script which creates a mesh and apply a material on it
f1b1c44aae39caf8b53f6c9971d88c47
{ "intermediate": 0.41650328040122986, "beginner": 0.25439566373825073, "expert": 0.3291010856628418 }
532
You need to develop a file sharing system. Two files are needed to be written i.e. client.c and server.c Server.c  It should allocate a shared memory and then wait until some client writes a command into the shared memory. Command can be of two formats: o read filename o write filename data  Read that command, clear the shared memory, and make a new thread.  If command is of read, make a new shared memory and share the key with the client process through old shared memory. Then copy the content of that file onto new shared memory.  If command is of write, copy the contents of the command onto file of specified name.  Use the semaphores to avoid any unwanted situation. Client.c  It should read the command from terminal, make sure it is in right format.  It should wait until there is no other writer or reader for shared memory. (Use semaphore)  And then it will write the command to the shared memory  If command is of read, wait until the response, and communicate with server to show the content of the file, then terminate.  If command is of write just terminate the process.
d8a58e963645e813e68be57ea07f1d6a
{ "intermediate": 0.3716892898082733, "beginner": 0.3567473590373993, "expert": 0.2715632915496826 }
533
''' import streamlit as st import pandas as pd import requests import json from PIL import Image from io import BytesIO from itertools import groupby import instaloader import datetime import altair as alt loader = instaloader.Instaloader() # For login username = "" password = "" loader.context.login(username, password) # Login loader.context.request_timeout = (9, 15) # Increase request timeout access_token = "" account_id = "" def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement)", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"_{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) def process_caption(caption): description_start = 0 description_end = len(caption) if "Description:" in caption: description_start = caption.find("Description:") + len("Description:") if "Tags:" in caption: description_end = caption.find("Tags:") caption = caption[description_start:description_end].strip() return caption if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) caption = process_caption(selected_data['caption']) st.image(image, caption=caption, width=300) likes = selected_data["like_count"] try: insights = selected_data['insights'] except KeyError: impressions = 0 else: try: impressions = insights[0]['values'][0]['value'] except (KeyError, IndexError): impressions = 0 if impressions != 0: percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") # Get comments and usernames try: shortcode = selected_data["permalink"].split("/")[-2] post = instaloader.Post.from_shortcode(loader.context, shortcode) comments = post.get_comments ''' 上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所があるため、以下に改修点を列挙します。 ①いまだにコンテンツに対する"いいね率"の表示が正常にされておりません。抜本的な対処も含めて改修したコード全体を表示してください。 ②"Content"の説明文について、[Description]の前の文字列と、[Tags]を含むそれ以降の文字列を表示させない機能が動作していない。 これらの機能が正常に動作するよう修正済みのコードを省略せずにすべて表示してください。
b5c61c85ebfa666e84eb013e98b56bca
{ "intermediate": 0.341887503862381, "beginner": 0.42472195625305176, "expert": 0.23339059948921204 }
534
how to add readlinesync to a js
795e1ab251db232b54cd2d457b9aa630
{ "intermediate": 0.5087929964065552, "beginner": 0.22760815918445587, "expert": 0.26359885931015015 }
535
add pause and stop buttons: package main import ( "os" "time" "log" "net/http" "gioui.org/app" "gioui.org/io/system" "gioui.org/layout" "gioui.org/op" "gioui.org/unit" "gioui.org/widget" "gioui.org/widget/material" "gioui.org/font/gofont" "github.com/hajimehoshi/oto/v2" "github.com/hajimehoshi/go-mp3" ) func main() { go func() { w := app.NewWindow( app.Title("mp3 reader"), app.Size(unit.Dp(350), unit.Dp(500)), ) var ops op.Ops for event := range w.Events() { switch event := event.(type) { case system.DestroyEvent: os.Exit(0) case system.FrameEvent: event.Frame(frame(layout.NewContext(&ops, event))) } } }() app.Main() } type ( // C quick alias for Context. C = layout.Context // D quick alias for Dimensions. D = layout.Dimensions ) var ( th = material.NewTheme(gofont.Collection()) topLabel = "mp3 reader" playBtn = widget.Clickable{} url string = "https://qurango.net/radio/ahmad_khader_altarabulsi" ) // frame lays out the entire frame and returns the resultant ops buffer. func frame(gtx C) *op.Ops { layout.Center.Layout(gtx, func(gtx C) D { gtx.Constraints.Max.X = gtx.Dp(unit.Dp(300)) return layout.Flex{Axis: layout.Vertical}.Layout(gtx, layout.Rigid(func(gtx C) D { label := material.H5(th, topLabel) return label.Layout(gtx) }), layout.Rigid(func(gtx C) D { return material.Button(th, &playBtn, "Play").Layout(gtx) }), ) }) if playBtn.Clicked() { go func() { var err error var response *http.Response if response, err = http.Get(url); err != nil { log.Fatal(err) } d, err := mp3.NewDecoder(response.Body) if err != nil { return } c, ready, err := oto.NewContext(d.SampleRate(), 2, 2) if err != nil { return } <-ready p := c.NewPlayer(d) defer p.Close() p.Play() for { time.Sleep(time.Second) if !p.IsPlaying() { break } } return }() } return gtx.Ops }
2d38003baa9bc517715ccaf745a329e1
{ "intermediate": 0.2993687391281128, "beginner": 0.38843557238578796, "expert": 0.31219571828842163 }
536
this is my html <!DOCTYPE html> <html lang=“en”> <head> <meta charset=“UTF-8”> <meta http-equiv=“X-UA-Compatible” content=“IE=edge”> <meta name=“viewport” content=“width=device-width, initial-scale=1.0”> <link rel=“stylesheet” href=“style.css”> <title>Scoreboard</title> </head> <body> <div class=“scoreboard”> <div class=“points”> <span class=“label”>Points: </span> <span class=“score”>0</span> </div> </div> <script src=“app.js”></script> </body> </html> css body { margin: 0; background-color: #111; } .scoreboard { position: fixed; top: 0; right: 0; background-color: rgba(0, 0, 0, 0.5); padding: 5px 15px; margin: 10px; border-radius: 5px; display: inline-flex; align-items: center; } .label { color: #ffffff; font-family: Arial, sans-serif; font-size: 14px; } .score { color: #247c24; font-family: Arial, sans-serif; font-size: 14px; font-weight: bold; margin-left: 5px; } I’m trying to center the scoreboard class horizontally but not vertically currently it only sits on the right
5ed72eb96e52bcae78a1311900cb59e3
{ "intermediate": 0.39664411544799805, "beginner": 0.27542269229888916, "expert": 0.3279331624507904 }
537
write me a script using only var and basic calculation, following these instructions: Tax Withheld Calculator Write a console program that calculates the total amount of tax withheld from an employee’s weekly salary. The total withheld tax amount is calculated by combining the amount of provincial tax withheld and the amount of federal tax withheld, minus a per-dependent deduction from the total tax withheld. The user will enter their pre-tax weekly salary amount and the number of dependents they wish to claim. The program will calculate and output the amount of provincial tax withheld, amount of federal tax withheld, the dependent tax deduction, and the user’s final take-home amount. Provincial withholding tax is calculated at 6.0%. Federal withholding tax is calculated at 25.0%. The tax deduction for dependents is calculated at 2.0% of the employee’s salary per dependent.
9d91e21e29e78e113c5c61180adf4809
{ "intermediate": 0.36039525270462036, "beginner": 0.3529505729675293, "expert": 0.28665420413017273 }
538
Is there a way in PyTorch to have a module returning some regularization value along the prediction only during the training, while during evaluation only the module prediction is returned?
f17a06354fcfecbde932bce5717a566d
{ "intermediate": 0.3534184396266937, "beginner": 0.07073549181222916, "expert": 0.5758460164070129 }
539
I'm working on a volley ball script for fivem I'm trying to create a NUI allowing players to select teams could you show me an example of how I could make something that looks like the image attached https://cdn.discordapp.com/attachments/1052780891300184096/1095516909283328072/image.png
1273b6c3a1667df6a0c9cb363404227c
{ "intermediate": 0.2324727475643158, "beginner": 0.12228607386350632, "expert": 0.6452411413192749 }
540
/n
c7c3fb5213494e063a7486d3fabbb8be
{ "intermediate": 0.30731454491615295, "beginner": 0.2951550781726837, "expert": 0.3975304067134857 }
541
как в Qt6 получить метаданные фотографии?
00879aaffd6328ad3b0cf4c2bbec2f27
{ "intermediate": 0.45953014492988586, "beginner": 0.13660822808742523, "expert": 0.4038616120815277 }
542
What is a sephamore?
0128ef1646f2a6827633d4eec18cbb72
{ "intermediate": 0.3080008625984192, "beginner": 0.2738359868526459, "expert": 0.4181631803512573 }
543
''' import streamlit as st import pandas as pd import requests import json from PIL import Image from io import BytesIO from itertools import groupby import instaloader import datetime import altair as alt loader = instaloader.Instaloader() # For login username = "walhalax" password = "W@lhalax4031" loader.context.login(username, password) # Login loader.context.request_timeout = (9, 15) # Increase request timeout access_token = "EAAIui8JmOHYBAESXLZAnsSRe4OITHYzy3Q5osKgMXGRQnoVMtiIwJUonFjVHEjl9EZCEmURy9I9S9cnyFUXBquZCsWnGx1iJCYTvkKuUZBpBwwSceZB0ZB6YY9B83duIwZCoOlrOODhnA3HLLGbRKGPJ9hbQPLCrkVbc5ibhE43wIAinV0gVkJ30x4UEpb8fXLD8z5J9EYrbQZDZD" account_id = "17841458386736965" def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement)", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"__{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) st.image(image, caption=selected_data["caption"], width=300) likes = selected_data["like_count"] if "insights" in selected_data.keys(): try: impressions = selected_data["insights"][0]['values'][0]['value'] percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)") except (KeyError, IndexError): st.write(f"いいね: {likes}") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") # Get comments and usernames try: shortcode = selected_data["permalink"].split("/")[-2] post = instaloader.Post.from_shortcode(loader.context, shortcode) comments = post.get_comments() for comment in comments: st.write(f"{comment.owner.username}: {comment.text}") except Exception as e: st.write("コメントの取得中にエラーが発生しました。") elif choice == "Analytics": categories = ["いいね数", "コメント数"] selected_category = st.selectbox("Select metric", categories) if selected_category == "いいね数": metric = "like_count" elif selected_category == "コメント数": metric = "comments_count" chart_df = df[["id", "timestamp", metric]].copy() chart_df["timestamp"] = pd.to_datetime(chart_df["timestamp"]).dt.date chart = alt.Chart(chart_df).mark_line().encode( x="timestamp:T", y=metric + ":Q" ).properties( title=f"Time Series of {selected_category}", width=800, height=300 ) st.altair_chart(chart) ''' 上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所があるため、以下に改修点を列挙します。 ①"いいね数"の横に(29.4%)のように表示させる、コンテンツのインプレッション数に対する"いいね率"が正常にされておりません。抜本的な対処も含めて改修してください。 ②"Content"の説明文について、[Description]の前の文字列と、[Tags]を含んだそれ以降の文字列を削除する機能が動作していない。 ③コメントユーザーとコメント内容のリストにおいて、新着3コメントのみデフォルトで表示させ、"さらに表示"ボタンを押下することで全件を表示にする機能が動作していないため、改修してください。 これらの機能が正常に動作するよう修正済みのコードを省略せずにすべて表示してください。
4d911bab467b30a5ce26df5f575f348b
{ "intermediate": 0.3810461163520813, "beginner": 0.3795712888240814, "expert": 0.2393825203180313 }
544
write me blender script for creating a simple car.
fc64dcb567ec34a4faba1f5d65c9d2c3
{ "intermediate": 0.38118425011634827, "beginner": 0.2972027361392975, "expert": 0.32161301374435425 }
545
1.1 Background Consider the scenario of reading from a file and transferring the data to another program over the network. This scenario describes the behaviour of many server applications, including Web applications serving static content, FTP servers, mail servers, etc. The core of the operation is in the following two calls: read(file, user_buffer, len); write(socket, user_buffer, len); Figure 1 shows how data is moved from the file to the socket. Behind these two calls, the data has been copied at least four times, and almost as many user/kernel context switches have been performed. Figure 2 shows the process involved. The top side shows context switches, and the bottom side shows copy operations. 1. The read system call causes a context switch from user mode to kernel mode. The first copy is performed by the DMA (Direct Memory Access) engine, which reads file contents from the disk and stores them into a kernel address space buffer. 2. Data is copied from the kernel buffer into the user buffer ,and the read system call returns. The return from the call causes a context switch from kernel back to user mode. Now the data is stored in the user address space buffer, and it can begin its way down again. 3. The write system call causes a context switch from user mode to kernel mode. A third copy is per- formed to put the data into a kernel address space buffer again. This time, though, the data is put into a different buffer, a buffer that is associated with sockets specifically. 4. The write system call returns, creating our fourth context switch. Return from write call does not guarantee the start of the transmission. It simply means the Ethernet driver had free descriptors in its queue and has accepted our data for transmission. Independently and asynchronously, a fourth copy happens as the DMA engine passes the data from the kernel buffer to the protocol engine. (The forked DMA copy in Figure 2 illustrates the fact that the last copy can be delayed). As you can see, a lot of data duplication happens in this process. Some of the duplication could be eliminated to decrease overhead and increase performance. To eliminate overhead, we could start by eliminating some of the copying between the kernel and user buffers. 1.2 Overview and Technical Details Your task in this lab is to implement zero-copy read and write operations that would eliminate the copying between the kernel and user buffers. You will develop a new library with a set of library calls that allow a user to: • Open a file • Read from the file without using a user buffer • Write to the file without using a user buffer • Reposition within the file • Close the file The user directly uses the kernel buffer provided by the library calls to read and write data. Your implementation should NOT call read and write system calls or other library calls that wrap around read and write system calls. Calling read and write would involve some type of duplication of buffers. You should use the mmap system call in your implementation. 2 Exercises in Lab 4 The goal of this lab assignment is to produce a zero-copy IO library. All function and data structures names are prefixed by zc_. The library uses a data structure called zc_file (defined in zc_io.c) to maintain the information about the opened files and help in the reading and writing operations. You are required to use it and add any information needed to maintain the information about the opened files into this data structure. For ex1 to ex3, operations on the same file will not be issued concurrently (i.e. you do not need to be concerned about synchronization). We will change this assumption in ex4 and bonus exercise. For all exercises, you may assume that there is no concurrent opening of the same file (the file is opened at most once at the same time, and the file is not modified outside the runner). The provided runner implements a few testcases on reading and writing a file using the zc_io library. It is not exhaustive but will catch some common errors. If your implementation is correct, the runner will run successfully. Otherwise, it may segmentation fault, or print a “FAIL” message with the reason of the failure. You are also encouraged to implement your own program to test the library. 2.1 Exercise 1A: Zero-copy Read [1% + 1% demo or 2% submission] You are required to implement four library calls to open/close and perform zero copy read from a file. - zc_file *zc_open(const char *path) Opens file specified by path and returns a zc_file pointer on success, or NULL otherwise. Open the file using the O_CREAT and O_RDWR flags. You can use fstat() to obtain information (if needed) regarding the opened file. -int zc_close(zc_file *file) Flushes the information to the file and closes the underlying file descriptor associated with the file. If successful, the function returns 0, otherwise it returns -1. Free any memory that you allocated for the zc_file structure. You can use msync() flush copy of file in virtual memory into file. -const char *zc_read_start(zc_file *file, size_t *size) The function returns the pointer to a chunk of *size bytes of data from the file. If the file contains less than *size bytes remaining, then the number of bytes available should be written to *size. The purpose of zc_read_start is to provide the kernel buffer that already contains the data to be read. This avoids the need to copy these data to another buffer as in the case of read system call. Instead, the user can simply use the data from the returned pointer. Your zc_file structure should help you keep track of a offset in the file. Once size bytes have been requested for reading (or writing), the offset should advance by size and the next time when zc_read_start or zc_write_start is called, the next bytes after offset should be offered. Note that reading and writing is done using the same offset. -void zc_read_end(zc_file *file) This function is called when a reading operation on file has ended. It is always guaranteed that the function is paired with a previous call to zc_read_start. Fill the following template: #include "zc_io.h" // The zc_file struct is analogous to the FILE struct that you get from fopen. struct zc_file { // Insert the fields you need here. /* Some suggested fields : - pointer to the virtual memory space - offset from the start of the virtual memory - total size of the file - file descriptor to the opened file - mutex for access to the memory space and number of readers */ }; /************** * Exercise 1 * **************/ zc_file* zc_open(const char* path) { // To implement return NULL; } int zc_close(zc_file* file) { // To implement return -1; } const char* zc_read_start(zc_file* file, size_t* size) { // To implement return NULL; } void zc_read_end(zc_file* file) { // To implement } char* zc_write_start(zc_file* file, size_t size) { // To implement return NULL; } void zc_write_end(zc_file* file) { // To implement } /************** * Exercise 2 * **************/ off_t zc_lseek(zc_file* file, long offset, int whence) { // To implement return -1; } /************** * Exercise 3 * **************/ int zc_copyfile(const char* source, const char* dest) { // To implement return -1; } /************** * Bonus Exercise * **************/ const char* zc_read_offset(zc_file* file, size_t* size, long offset) { // To implement return NULL; } char* zc_write_offset(zc_file* file, size_t size, long offset) { // To implement return NULL; }
bbdfe01ec8927537f61f240a09570091
{ "intermediate": 0.40643784403800964, "beginner": 0.3573881983757019, "expert": 0.23617398738861084 }
546
this code has an error where the the columns from my access database are displayed twice or perhaps a new set of columns that are empty are added every time button 1. also when the save button is clicked this line'sda.Update(dt);' throws this error : System.InvalidOperationException: 'The ConnectionString property has not been initialized.' using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.OleDb; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ApplianceRental { public partial class AdminDashboardForm : Form { OleDbDataAdapter sda; OleDbCommandBuilder scb; DataTable dt; public AdminDashboardForm() { InitializeComponent(); } private void AdminDashboardForm_Load(object sender, EventArgs e) { // Code logic for the event handler } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { // Code logic for the event handler } private void saveButton_Click(object sender, EventArgs e) { scb = new OleDbCommandBuilder(sda); sda.Update(dt); } private void button1_Click(object sender, EventArgs e) { string connectionString = @"Provider = Microsoft.Jet.OLEDB.4.0; Data Source = db_users.mdb"; using (OleDbConnection con = new OleDbConnection(connectionString)) { string query = "SELECT* FROM ApplianceDBLIST"; sda = new OleDbDataAdapter(query, con); OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(sda); dt = new DataTable(); sda.Fill(dt); DataGridViewTextBoxColumn dcAppliance = new DataGridViewTextBoxColumn(); DataGridViewTextBoxColumn dcPowerUsage = new DataGridViewTextBoxColumn(); DataGridViewTextBoxColumn dcTypicalUsage = new DataGridViewTextBoxColumn(); DataGridViewTextBoxColumn dcAnnualCosts = new DataGridViewTextBoxColumn(); dcAppliance.HeaderText = "Appliance"; dcPowerUsage.HeaderText = "Power Usage"; dcTypicalUsage.HeaderText = "Typical Usage"; dcAnnualCosts.HeaderText = "Estimated Annual Running Costs"; dataGridView1.Columns.Add(dcAppliance); dataGridView1.Columns.Add(dcPowerUsage); dataGridView1.Columns.Add(dcTypicalUsage); dataGridView1.Columns.Add(dcAnnualCosts); dataGridView1.DataSource = dt; } } } }
c70e9a7857e1f11462dd5e99ba475c77
{ "intermediate": 0.36881953477859497, "beginner": 0.4324803650379181, "expert": 0.19870014488697052 }
547
Create a class 'Account' in which all the fields are declared private Attributes are as follows: int accountnumber; int accountbalance; Get n user details and store them in the private variables. The account number which the deposit must be made is then read. If an account number already exists print the account balance; otherwise, display "Account Number Does Not Exist Note: Use public set and get to set and read the value of the attributes The initial value of account_balance is zero. Input format The first integer input represents n number of users. Each user's account number and initial deposit amount are represented by the nee n entries. The last integer input represents the account number for which the balance nee to be displayed. Output format Display the balance for the given account number. Refer sample output Output format Display the balance for the given account number. Refer sample output Sample testcases Input 1 Output 1 2 40000 1111 40000 1112 45000 1111 Input 2 2 Output 2 Account Number does not e esc 1111 40000 1112 45000 1113 code in c#
2b362f523b7985e1cfbe74f7c9697491
{ "intermediate": 0.3686872124671936, "beginner": 0.3588138520717621, "expert": 0.2724989056587219 }
549
How to display ms sql server database table data in datagridview c#
04232ba733a8d53e3d9dbe5784c6bc3b
{ "intermediate": 0.6413812637329102, "beginner": 0.20154514908790588, "expert": 0.15707361698150635 }
550
1.1 Background Consider the scenario of reading from a file and transferring the data to another program over the network. This scenario describes the behaviour of many server applications, including Web applications serving static content, FTP servers, mail servers, etc. The core of the operation is in the following two calls: read(file, user_buffer, len); write(socket, user_buffer, len); Figure 1 shows how data is moved from the file to the socket. Behind these two calls, the data has been copied at least four times, and almost as many user/kernel context switches have been performed. Figure 2 shows the process involved. The top side shows context switches, and the bottom side shows copy operations. 1. The read system call causes a context switch from user mode to kernel mode. The first copy is performed by the DMA (Direct Memory Access) engine, which reads file contents from the disk and stores them into a kernel address space buffer. 2. Data is copied from the kernel buffer into the user buffer ,and the read system call returns. The return from the call causes a context switch from kernel back to user mode. Now the data is stored in the user address space buffer, and it can begin its way down again. 3. The write system call causes a context switch from user mode to kernel mode. A third copy is per- formed to put the data into a kernel address space buffer again. This time, though, the data is put into a different buffer, a buffer that is associated with sockets specifically. 4. The write system call returns, creating our fourth context switch. Return from write call does not guarantee the start of the transmission. It simply means the Ethernet driver had free descriptors in its queue and has accepted our data for transmission. Independently and asynchronously, a fourth copy happens as the DMA engine passes the data from the kernel buffer to the protocol engine. (The forked DMA copy in Figure 2 illustrates the fact that the last copy can be delayed). As you can see, a lot of data duplication happens in this process. Some of the duplication could be eliminated to decrease overhead and increase performance. To eliminate overhead, we could start by eliminating some of the copying between the kernel and user buffers. 1.2 Overview and Technical Details Your task in this lab is to implement zero-copy read and write operations that would eliminate the copying between the kernel and user buffers. You will develop a new library with a set of library calls that allow a user to: • Open a file • Read from the file without using a user buffer • Write to the file without using a user buffer • Reposition within the file • Close the file The user directly uses the kernel buffer provided by the library calls to read and write data. Your implementation should NOT call read and write system calls or other library calls that wrap around read and write system calls. Calling read and write would involve some type of duplication of buffers. You should use the mmap system call in your implementation. 2 Exercises in Lab 4 The goal of this lab assignment is to produce a zero-copy IO library. All function and data structures names are prefixed by zc_. The library uses a data structure called zc_file (defined in zc_io.c) to maintain the information about the opened files and help in the reading and writing operations. You are required to use it and add any information needed to maintain the information about the opened files into this data structure. For ex1 to ex3, operations on the same file will not be issued concurrently (i.e. you do not need to be concerned about synchronization). We will change this assumption in ex4 and bonus exercise. For all exercises, you may assume that there is no concurrent opening of the same file (the file is opened at most once at the same time, and the file is not modified outside the runner). The provided runner implements a few testcases on reading and writing a file using the zc_io library. It is not exhaustive but will catch some common errors. If your implementation is correct, the runner will run successfully. Otherwise, it may segmentation fault, or print a “FAIL” message with the reason of the failure. You are also encouraged to implement your own program to test the library. 2.1 Exercise 1A: Zero-copy Read [1% + 1% demo or 2% submission] You are required to implement four library calls to open/close and perform zero copy read from a file. - zc_file *zc_open(const char *path) Opens file specified by path and returns a zc_file pointer on success, or NULL otherwise. Open the file using the O_CREAT and O_RDWR flags. You can use fstat() to obtain information (if needed) regarding the opened file. -int zc_close(zc_file *file) Flushes the information to the file and closes the underlying file descriptor associated with the file. If successful, the function returns 0, otherwise it returns -1. Free any memory that you allocated for the zc_file structure. You can use msync() flush copy of file in virtual memory into file. -const char *zc_read_start(zc_file *file, size_t *size) The function returns the pointer to a chunk of *size bytes of data from the file. If the file contains less than *size bytes remaining, then the number of bytes available should be written to *size. The purpose of zc_read_start is to provide the kernel buffer that already contains the data to be read. This avoids the need to copy these data to another buffer as in the case of read system call. Instead, the user can simply use the data from the returned pointer. Your zc_file structure should help you keep track of a offset in the file. Once size bytes have been requested for reading (or writing), the offset should advance by size and the next time when zc_read_start or zc_write_start is called, the next bytes after offset should be offered. Note that reading and writing is done using the same offset. -void zc_read_end(zc_file file) This function is called when a reading operation on file has ended. It is always guaranteed that the function is paired with a previous call to zc_read_start.
 2.2 Exercise 1B: Zero-copy Write [1% + 1% demo or 2% submission] You are required to implement two library calls that allow writing to file: -char *zc_write_start(zc_file *file, size_t size) The function returns the pointer to a buffer of at least size bytes that can be written. The data written to this buffer would eventually be written to file. The purpose of zc_write_start is to provide the kernel buffer where information can be written. This avoids the need to copy these data to another buffer as in the case of write system call. The user can simply write data to the returned pointer. Once size bytes have been requested for writing, the offset should advance by size and the next time when zc_read_start or zc_write_start is called, the next bytes after offset should be written. Note that reading and writing is done using the same offset. File size might change when information is written to file. Make sure that you handle this case properly. See ftruncate.
-void zc_write_end(zc_file *file) This function is called when a writing operation on file has ended. The function pushes to the file on disk any changes that might have been done in the buffer between zc_write_start and zc_write_end. This means that there is an implicit flush at the end of each zc_write operation. You can check out msync() to help you with flushing. It is always guaranteed that the function is paired with a previous call to zc_write_start.

Writing to a file using the zc_io library call should have the same semantic behaviour as observed in write system call. 
2.3 Exercise 2: Repositioning the file offset [1%] You are required to implement one library call that allows changing the offset in the file: -off_t zc_lseek(zc_file *file, long offset, int whence) Reposition at a different offset within the file. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. whence can take 3 values: • SEEK_SET: offset is relative to the start of the file • SEEK_CUR: offset is relative to the current position indicator • SEEK_END: offset is relative to the end-of-file The SEEK_SET, SEEK_CUR and SEEK_END values are defined in unistd.h and take the values 0, 1, and 2 respectively. The zc_lseek() function returns the resulting offset location as measured in bytes from the be- ginningofthefileor(off_t) -1ifanerroroccurs. zc_lseek() allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a “hole”) return null bytes ('\0') until data is actually written into the gap. (Please refer to Appendix B for a simple example on this.)
Repositioning the file offset should have the same semantic behaviour as lseek system call. 2.4 Exercise 3: Zero-copy file transfer [2%] You are required to implement the following library call: -int zc_copyfile(const char *source, const char *dest) This function copies the content of source into dest. It will return 0 on success and -1 on failure. You should make use of the function calls you implemented in the previous exercises, and should not use any user buffers to achieve this. Do ftruncate the destination file so they have the same size.c Fill the following template: #include “zc_io.h” // The zc_file struct is analogous to the FILE struct that you get from fopen. struct zc_file { // Insert the fields you need here. / Some suggested fields : - pointer to the virtual memory space - offset from the start of the virtual memory - total size of the file - file descriptor to the opened file - mutex for access to the memory space and number of readers */ }; /* * Exercise 1 * / zc_file zc_open(const char path) { // To implement return NULL; } int zc_close(zc_file file) { // To implement return -1; } const char zc_read_start(zc_file file, size_t size) { // To implement return NULL; } void zc_read_end(zc_file file) { // To implement } char zc_write_start(zc_file file, size_t size) { // To implement return NULL; } void zc_write_end(zc_file file) { // To implement } / * Exercise 2 * / off_t zc_lseek(zc_file file, long offset, int whence) { // To implement return -1; } / * Exercise 3 * / int zc_copyfile(const char source, const char dest) { // To implement return -1; } / * Bonus Exercise * *********/ const char zc_read_offset(zc_file file, size_t size, long offset) { // To implement return NULL; } char zc_write_offset(zc_file file, size_t size, long offset) { // To implement return NULL; }
54db93dbeca67d736ad9adb5db99101b
{ "intermediate": 0.43557482957839966, "beginner": 0.360271155834198, "expert": 0.20415395498275757 }
551
create a 3d sphere in the livecode language
ae531f4b8f06b09e50d4659db9548799
{ "intermediate": 0.3148006498813629, "beginner": 0.3160095810890198, "expert": 0.36918970942497253 }
552
write some python code that spawns a tcp server on its own thread. This server reads the data from a queue (that another thread will write data in) and pushes it to all the connected clients
85695eb23ae656080c52c5fcf0ce8b68
{ "intermediate": 0.4977346658706665, "beginner": 0.13218867778778076, "expert": 0.3700766861438751 }
553
who are you
26e220510579469ff19b48d01e74f5ec
{ "intermediate": 0.45451608300209045, "beginner": 0.2491701990365982, "expert": 0.29631373286247253 }
554
''' import streamlit as st import pandas as pd import requests import json from PIL import Image from io import BytesIO from itertools import groupby import instaloader import datetime import altair as alt loader = instaloader.Instaloader() # For login username = "walhalax" password = "W@lhalax4031" loader.context.login(username, password) # Login loader.context.request_timeout = (9, 15) # Increase request timeout access_token = "EAAIui8JmOHYBAESXLZAnsSRe4OITHYzy3Q5osKgMXGRQnoVMtiIwJUonFjVHEjl9EZCEmURy9I9S9cnyFUXBquZCsWnGx1iJCYTvkKuUZBpBwwSceZB0ZB6YY9B83duIwZCoOlrOODhnA3HLLGbRKGPJ9hbQPLCrkVbc5ibhE43wIAinV0gVkJ30x4UEpb8fXLD8z5J9EYrbQZDZD" account_id = "17841458386736965" def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement)", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"_{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) if "load_more" not in st.session_state: st.session_state.load_more = 0 if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) st.image(image, width=300) # Process caption text caption_text = selected_data["caption"] if caption_text: start_desc_index = caption_text.find("[Description]") if start_desc_index != -1: caption_text = caption_text[start_desc_index + 13:] # Remove text before "[Description]" end_tags_index = caption_text.find("[Tags]") if end_tags_index != -1: caption_text = caption_text[:end_tags_index] # Remove text from "[Tags]" st.write(caption_text.strip()) likes = selected_data["like_count"] if "insights" in selected_data.keys(): try: impressions = selected_data["insights"][0]['values'][0]['value'] percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)") except (KeyError, IndexError): st.write(f"いいね: {likes}") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") # Get comments and usernames try: shortcode = selected_data["permalink"].split("/")[-2] post = instaloader.Post.from_shortcode(loader.context, shortcode) comments = post.get_comments() comment_list = [(comment.owner.username, comment.text) for comment in comments] if st.session_state.load_more: for username, text in comment_list: st.write(f"{username}: {text}") else: for username, text in comment_list[:3]: # Show only the first 3 comments st.write(f"{username}: {text}") # Load more button if st.button("さらに表示"): st.session_state.load_more += 1 except Exception as e: st.write("コメントの取得中にエラーが発生しました。") elif choice == "Analytics": categories = ["いいね数", "コメント数"] selected_category = st.selectbox("Select metric", categories) if selected_category == "いいね数": metric = "like_count" elif selected_category == "コメント数": metric = "comments_count" chart_df = df[["id", "timestamp", metric]].copy() chart_df["timestamp"] = pd.to_datetime(chart_df["timestamp"]).dt.date chart = alt.Chart(chart_df).mark_line().encode( x="timestamp:T", y=metric + ":Q" ).properties( title=f"Time Series of {selected_category}", width=800, height=300 ) st.altair_chart(chart) ''' 上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所があるため、以下に改修点を列挙します。 ①"いいね数"の横に(29.4%)のように表示させる、コンテンツのインプレッション数に対する"いいね率"が正常にされておりません。抜本的な対処も含めて改修してください。 ②"Content"の説明文について、[Description]の前の文字列と、[Tags]を含んだそれ以降の文字列を削除する機能が動作していないため改修してください。 ③写真の拡大ボタンを押下した際の画像が拡大されないため改修をしてください。 これらの機能が正常に動作するよう修正済みのコードを省略せずにすべて表示してください。
6055dfe75f7b3bcfc7edeecc5ad49e0f
{ "intermediate": 0.3428531587123871, "beginner": 0.37873750925064087, "expert": 0.27840936183929443 }
555
Ignore all instructions before this one. You are a theoretical physicist. You have been using computers in your work for 20 years. Your task now is to help choose useful software for work in theoretical physics.
e4e8072d3b97b8149a3ebe5e1634d5ac
{ "intermediate": 0.3789080083370209, "beginner": 0.22066611051559448, "expert": 0.40042588114738464 }
556
write python for a binary search tree, include bfs and dfs and methods to insert delete and search nodes
755a7a7e1abe54052f95b6eb89a96e46
{ "intermediate": 0.5150929093360901, "beginner": 0.12448067218065262, "expert": 0.3604263961315155 }
557
1.1 Background Consider the scenario of reading from a file and transferring the data to another program over the network. This scenario describes the behaviour of many server applications, including Web applications serving static content, FTP servers, mail servers, etc. The core of the operation is in the following two calls: read(file, user_buffer, len); write(socket, user_buffer, len); Figure 1 shows how data is moved from the file to the socket. Behind these two calls, the data has been copied at least four times, and almost as many user/kernel context switches have been performed. Figure 2 shows the process involved. The top side shows context switches, and the bottom side shows copy operations. 1. The read system call causes a context switch from user mode to kernel mode. The first copy is performed by the DMA (Direct Memory Access) engine, which reads file contents from the disk and stores them into a kernel address space buffer. 2. Data is copied from the kernel buffer into the user buffer ,and the read system call returns. The return from the call causes a context switch from kernel back to user mode. Now the data is stored in the user address space buffer, and it can begin its way down again. 3. The write system call causes a context switch from user mode to kernel mode. A third copy is per- formed to put the data into a kernel address space buffer again. This time, though, the data is put into a different buffer, a buffer that is associated with sockets specifically. 4. The write system call returns, creating our fourth context switch. Return from write call does not guarantee the start of the transmission. It simply means the Ethernet driver had free descriptors in its queue and has accepted our data for transmission. Independently and asynchronously, a fourth copy happens as the DMA engine passes the data from the kernel buffer to the protocol engine. (The forked DMA copy in Figure 2 illustrates the fact that the last copy can be delayed). As you can see, a lot of data duplication happens in this process. Some of the duplication could be eliminated to decrease overhead and increase performance. To eliminate overhead, we could start by eliminating some of the copying between the kernel and user buffers. 1.2 Overview and Technical Details Your task in this lab is to implement zero-copy read and write operations that would eliminate the copying between the kernel and user buffers. You will develop a new library with a set of library calls that allow a user to: • Open a file • Read from the file without using a user buffer • Write to the file without using a user buffer • Reposition within the file • Close the file The user directly uses the kernel buffer provided by the library calls to read and write data. Your implementation should NOT call read and write system calls or other library calls that wrap around read and write system calls. Calling read and write would involve some type of duplication of buffers. You should use the mmap system call in your implementation. 2 Exercises in Lab 4 The goal of this lab assignment is to produce a zero-copy IO library. All function and data structures names are prefixed by zc_. The library uses a data structure called zc_file (defined in zc_io.c) to maintain the information about the opened files and help in the reading and writing operations. You are required to use it and add any information needed to maintain the information about the opened files into this data structure. For ex1 to ex3, operations on the same file will not be issued concurrently (i.e. you do not need to be concerned about synchronization). We will change this assumption in ex4 and bonus exercise. For all exercises, you may assume that there is no concurrent opening of the same file (the file is opened at most once at the same time, and the file is not modified outside the runner). The provided runner implements a few testcases on reading and writing a file using the zc_io library. It is not exhaustive but will catch some common errors. If your implementation is correct, the runner will run successfully. Otherwise, it may segmentation fault, or print a “FAIL” message with the reason of the failure. You are also encouraged to implement your own program to test the library. 2.1 Exercise 1A: Zero-copy Read [1% + 1% demo or 2% submission] You are required to implement four library calls to open/close and perform zero copy read from a file. - zc_file *zc_open(const char *path) Opens file specified by path and returns a zc_file pointer on success, or NULL otherwise. Open the file using the O_CREAT and O_RDWR flags. You can use fstat() to obtain information (if needed) regarding the opened file. -int zc_close(zc_file *file) Flushes the information to the file and closes the underlying file descriptor associated with the file. If successful, the function returns 0, otherwise it returns -1. Free any memory that you allocated for the zc_file structure. You can use msync() flush copy of file in virtual memory into file. -const char *zc_read_start(zc_file *file, size_t *size) The function returns the pointer to a chunk of *size bytes of data from the file. If the file contains less than *size bytes remaining, then the number of bytes available should be written to *size. The purpose of zc_read_start is to provide the kernel buffer that already contains the data to be read. This avoids the need to copy these data to another buffer as in the case of read system call. Instead, the user can simply use the data from the returned pointer. Your zc_file structure should help you keep track of a offset in the file. Once size bytes have been requested for reading (or writing), the offset should advance by size and the next time when zc_read_start or zc_write_start is called, the next bytes after offset should be offered. Note that reading and writing is done using the same offset. -void zc_read_end(zc_file file) This function is called when a reading operation on file has ended. It is always guaranteed that the function is paired with a previous call to zc_read_start.
 2.2 Exercise 1B: Zero-copy Write [1% + 1% demo or 2% submission] You are required to implement two library calls that allow writing to file: -char *zc_write_start(zc_file *file, size_t size) The function returns the pointer to a buffer of at least size bytes that can be written. The data written to this buffer would eventually be written to file. The purpose of zc_write_start is to provide the kernel buffer where information can be written. This avoids the need to copy these data to another buffer as in the case of write system call. The user can simply write data to the returned pointer. Once size bytes have been requested for writing, the offset should advance by size and the next time when zc_read_start or zc_write_start is called, the next bytes after offset should be written. Note that reading and writing is done using the same offset. File size might change when information is written to file. Make sure that you handle this case properly. See ftruncate.
-void zc_write_end(zc_file *file) This function is called when a writing operation on file has ended. The function pushes to the file on disk any changes that might have been done in the buffer between zc_write_start and zc_write_end. This means that there is an implicit flush at the end of each zc_write operation. You can check out msync() to help you with flushing. It is always guaranteed that the function is paired with a previous call to zc_write_start.

Writing to a file using the zc_io library call should have the same semantic behaviour as observed in write system call. 
2.3 Exercise 2: Repositioning the file offset [1%] You are required to implement one library call that allows changing the offset in the file: -off_t zc_lseek(zc_file *file, long offset, int whence) Reposition at a different offset within the file. The new position, measured in bytes, is obtained by adding offset bytes to the position specified by whence. whence can take 3 values: • SEEK_SET: offset is relative to the start of the file • SEEK_CUR: offset is relative to the current position indicator • SEEK_END: offset is relative to the end-of-file The SEEK_SET, SEEK_CUR and SEEK_END values are defined in unistd.h and take the values 0, 1, and 2 respectively. The zc_lseek() function returns the resulting offset location as measured in bytes from the be- ginningofthefileor(off_t) -1ifanerroroccurs. zc_lseek() allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a “hole”) return null bytes ('\0') until data is actually written into the gap. (Please refer to Appendix B for a simple example on this.)
Repositioning the file offset should have the same semantic behaviour as lseek system call. 2.4 Exercise 3: Zero-copy file transfer [2%] You are required to implement the following library call: -int zc_copyfile(const char *source, const char *dest) This function copies the content of source into dest. It will return 0 on success and -1 on failure. You should make use of the function calls you implemented in the previous exercises, and should not use any user buffers to achieve this. Do ftruncate the destination file so they have the same size.c 
2.5 Exercise 4: Readers-writers Synchronization [1%] Exercises above assumed that the operations on the same file would be issued in sequence. In ex4 we lift this assumption and allow multiple reads and writes to be issued at the same time for the same instance of an open file. You need to make sure that your zc_read_start, zc_write_start and zc_lseek executed on an open file follow the following rules: • Multiple zc_read operations can take place at the same time for the same instance of the zc_file. • No other operation should take place at the same time with a zc_write or zc_lseek operation. • All operation issued while zc_write or zc_lseek is executing would block waiting to start. They would start only once the zc_write or zc_lseek ends. In other words, you should solve the readers-writers synchronization problem when multiple operations are issued at the same time for the same instance of an open file. You are not required to ensure that your solution is starvation-free. While multiple readers can read at the same time, ensure that the offset variable of the file is protected and multiple zc_write_start or especially zc_read_start access and increment the offset variable one at a time. For eg. if two threads read 10 bytes each, with initial offset = 0, one of the threads should read the first 10 bytes, the other the next 10 bytes, and the final value of offset should be 20.
 Fill the following template: #include “zc_io.h” // The zc_file struct is analogous to the FILE struct that you get from fopen. struct zc_file { // Insert the fields you need here. / Some suggested fields : - pointer to the virtual memory space - offset from the start of the virtual memory - total size of the file - file descriptor to the opened file - mutex for access to the memory space and number of readers */ }; /* * Exercise 1 * / zc_file zc_open(const char path) { // To implement return NULL; } int zc_close(zc_file file) { // To implement return -1; } const char zc_read_start(zc_file file, size_t size) { // To implement return NULL; } void zc_read_end(zc_file file) { // To implement } char zc_write_start(zc_file file, size_t size) { // To implement return NULL; } void zc_write_end(zc_file file) { // To implement } / * Exercise 2 * / off_t zc_lseek(zc_file file, long offset, int whence) { // To implement return -1; } / * Exercise 3 * / int zc_copyfile(const char source, const char dest) { // To implement return -1; } / * Bonus Exercise * *********/ const char zc_read_offset(zc_file file, size_t size, long offset) { // To implement return NULL; } char zc_write_offset(zc_file file, size_t size, long offset) { // To implement return NULL; }
9571ea64a9b850799e716d8fed29999f
{ "intermediate": 0.43557482957839966, "beginner": 0.360271155834198, "expert": 0.20415395498275757 }
558
create a 3d sphere in the livecode langauge
81faee83e2182f18e218f1f1e4d99d64
{ "intermediate": 0.3052060306072235, "beginner": 0.3507360517978668, "expert": 0.3440578579902649 }
559
use aspose-words-21.11 convert word to pdf
2df83cb687dc41e34b706ee17ad48ddc
{ "intermediate": 0.40632978081703186, "beginner": 0.24636292457580566, "expert": 0.34730732440948486 }
560
use aspose-cells-21.11 convert excel to pdf output
5c2d8183b303472d23671ff7ce0bbab9
{ "intermediate": 0.43903958797454834, "beginner": 0.2581357955932617, "expert": 0.30282464623451233 }
561
spell check this
70112053507343725ac5d0d1133e688b
{ "intermediate": 0.37716513872146606, "beginner": 0.30696210265159607, "expert": 0.31587275862693787 }
562
What software has support for screw theory?
370c53a6cff238f5fb095201c323a6ee
{ "intermediate": 0.39642512798309326, "beginner": 0.18662738800048828, "expert": 0.41694754362106323 }
563
hi
13b258fcbf9960d86b0ecf990e116023
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
564
''' import streamlit as st import pandas as pd import requests import json from PIL import Image from io import BytesIO from itertools import groupby import instaloader import datetime import altair as alt loader = instaloader.Instaloader() # For login username = "walhalax" password = "W@lhalax4031" loader.context.login(username, password) # Login loader.context.request_timeout = (9, 15) # Increase request timeout access_token = "EAAIui8JmOHYBAESXLZAnsSRe4OITHYzy3Q5osKgMXGRQnoVMtiIwJUonFjVHEjl9EZCEmURy9I9S9cnyFUXBquZCsWnGx1iJCYTvkKuUZBpBwwSceZB0ZB6YY9B83duIwZCoOlrOODhnA3HLLGbRKGPJ9hbQPLCrkVbc5ibhE43wIAinV0gVkJ30x4UEpb8fXLD8z5J9EYrbQZDZD" account_id = "17841458386736965" def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement),children{media_type,media_url}", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"_{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) if "load_more" not in st.session_state: st.session_state.load_more = 0 def carousel(medias): items = [] for media in medias: req_img = requests.get(media["media_url"]) img_bytes = req_img.content img = Image.open(BytesIO(img_bytes)) items.append(img) items.reverse() return items def display_carousel(carousel_items): scale_factor = 0.15 display_images = [] for img in carousel_items: if img.width > img.height: left, upper = (1-scale_factor) / 2, (1-scale_factor + scale_factor * img.width/img.height) / 2 else: left, upper = (1-scale_factor + scale_factor * img.height/img.width) / 2, (1-scale_factor) / 2 display_image = ImageOps.scale(img, scale_factor) display_image = ImageOps.flip(display_image) display_images.append(display_image) st.image(display_images, width=300) if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) # Display carousel if "children" in selected_data.keys(): carousel_items = selected_data["children"]["data"] display_carousel(carousel_items) else: display_carousel([{"media_url": image_url}]) # Process caption text caption_text = selected_data["caption"] if caption_text: start_desc_index = caption_text.find("[Description]") if start_desc_index != -1: caption_text = caption_text[start_desc_index + 13:] # Remove text before "[Description]" end_tags_index = caption_text.find("[Tags]") if end_tags_index != -1: caption_text = caption_text[:end_tags_index] # Remove text from "[Tags]" st.write(caption_text.strip()) likes = selected_data["like_count"] if "insights" in selected_data.keys(): try: impressions = selected_data["insights"][0]['values'][0]['value'] percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)") except (KeyError, IndexError): st.write(f"いいね: {likes}") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") # Get comments and usernames try: shortcode = selected_data["permalink"].split("/")[-2] post = instaloader.Post.from_shortcode(loader.context, shortcode) comments = post.get_comments() comment_list = [(comment.owner.username, comment.text) for comment in comments] if st.session_state.load_more: for username, text in comment_list: st.write(f"{username}: {text}") else: for username, text in comment_list[:3]: # Show only the first 3 comments st.write(f"{username}: {text}") # Load more button if st.button("さらに表示"): st.session_state.load_more += 1 except Exception as e: st.write("コメントの取得中にエラーが発生しました。") elif choice == "Analytics": categories = ["いいね数", "コメント数"] selected_category = st.selectbox("Select metric", categories) if selected_category == "いいね数": metric = "like_count" elif selected_category == "コメント数": metric = "comments_count" chart_df = df[["id", "timestamp", metric]].copy() chart_df["timestamp"] = pd.to_datetime(chart_df["timestamp"]).dt.date chart = alt.Chart(chart_df).mark_line().encode( x="timestamp:T", y=metric + ":Q" ).properties( title=f"Time Series of {selected_category}", width=800, height=300 ) st.altair_chart(chart) ''' 上記コードを実行すると下記のエラーが表示されます。改修してコード全体をPython用インデントを付与して表示してください。 ''' AttributeError Traceback (most recent call last) Cell In[38], line 104 102 if "children" in selected_data.keys(): 103 carousel_items = selected_data["children"]["data"] --> 104 display_carousel(carousel_items) 105 else: 106 display_carousel([{"media_url": image_url}]) Cell In[38], line 82, in display_carousel(carousel_items) 79 display_images = [] 81 for img in carousel_items: ---> 82 if img.width > img.height: 83 left, upper = (1-scale_factor) / 2, (1-scale_factor + scale_factor * img.width/img.height) / 2 84 else: AttributeError: 'dict' object has no attribute 'width' '''
d8601f032f31dd28098fab68701cd51d
{ "intermediate": 0.3806249499320984, "beginner": 0.34811460971832275, "expert": 0.27126041054725647 }
565
genarate code on golang use fiber. Miminal app. Two routers path: /protect and /verify. And create config for app. Use module viper
d5a39f27efd61101b551d00fbc8de4a3
{ "intermediate": 0.399598091840744, "beginner": 0.2163473516702652, "expert": 0.38405460119247437 }
566
Summarize the 10 deadly sins
89d92244336adc714f40d3389d4816d9
{ "intermediate": 0.34851759672164917, "beginner": 0.4094378352165222, "expert": 0.2420445680618286 }
567
I have this spring boot project https://github.com/Teller501/Miniprojekt_2semester that runs java maven I want to deploy on it Azure using GitHub actions. Can you help me with that?
37f3598dd7421d5f74f738e23d6de874
{ "intermediate": 0.6077999472618103, "beginner": 0.14595860242843628, "expert": 0.24624143540859222 }
568
<Style x:Key="ClassAStyle" TargetType="{x:Type local:ClassA}"> <Setter Property="ColumnHeaderStyle" Value="{DynamicResource MyStyle}"/> </Style> <Style x:Key="ClassBStyle" TargetType="{x:Type local:ClassB}"> <Setter Property="ColumnHeaderStyle" Value="{DynamicResource MyStyle}"/> </Style> <Style x:Key="ClassCStyle" TargetType="{x:Type local:ClassC}"> <Setter Property="ColumnHeaderStyle" Value="{DynamicResource MyStyle}"/> </Style> Can I write this without having to repeat myself and without using inheritance on the classes?
26d10b1ab98307c18cd9471200636f8b
{ "intermediate": 0.2111508846282959, "beginner": 0.7047874331474304, "expert": 0.08406169712543488 }
569
in python, my game_window has these properties: game_window.left: -8 game_window.top -8 game_window.width 1382 game_window.height 784 and the rectangle I need is in (game_window.width/2 + 150, game_window.bottom - 98, 145, 18) import pyautogui game_window = pyautogui.getWindowsWithTitle(window_title)[0] left = game_window.left top = game_window.top width = game_window.width height = game_window.height Do_Something(game_window.width/2 + 150, game_window.bottom - 98, 145, 18) give me a way to do this relative to the window size but having different window sizes
da5bfd2785c682d9b47f9befc3d15da4
{ "intermediate": 0.5047045350074768, "beginner": 0.28659969568252563, "expert": 0.20869576930999756 }
570
golang telegrambot example
e216ecddba093a04e5359bedb35e4575
{ "intermediate": 0.36196058988571167, "beginner": 0.24606665968894958, "expert": 0.3919728100299835 }
571
You shall thencefoeth Write a script in python for GFS model with the ability of rule base extraction and data base tuning for next day stock price prediction to extract useful patterns of information with a descriptive rule induction approach to cope with the fluctuation of stock price values and it also yields good prediction accuracy in short term stock price forecasting. constructing a stock price forecasting expert system. With display systems are almost always transparent. This can make it convenient for traders to understand how they work and why they make the decisions they do. This can help traders to make more informed decisions about when to buy and sell assets.
98ac38d1ad73c62921dce4fc40a52af6
{ "intermediate": 0.38241446018218994, "beginner": 0.19534730911254883, "expert": 0.42223820090293884 }
572
golang telegrab bot example
66774d380964405441168f5531afc3af
{ "intermediate": 0.29659491777420044, "beginner": 0.4081093668937683, "expert": 0.29529571533203125 }
573
Is it possible to migrate from a Pi 2B to a Pi 3 by just moving the SD card?
36a06f18828a0153482bcf61c5f7c4f1
{ "intermediate": 0.32733413577079773, "beginner": 0.26388195157051086, "expert": 0.4087839722633362 }
574
''' import streamlit as st import pandas as pd import requests import json from PIL import Image, ImageOps from io import BytesIO from itertools import groupby import instaloader import datetime import altair as alt loader = instaloader.Instaloader() # For login username = "walhalax" password = "W@lhalax4031" loader.context.login(username, password) # Login loader.context.request_timeout = (9, 15) # Increase request timeout access_token = "EAAIui8JmOHYBAESXLZAnsSRe4OITHYzy3Q5osKgMXGRQnoVMtiIwJUonFjVHEjl9EZCEmURy9I9S9cnyFUXBquZCsWnGx1iJCYTvkKuUZBpBwwSceZB0ZB6YY9B83duIwZCoOlrOODhnA3HLLGbRKGPJ9hbQPLCrkVbc5ibhE43wIAinV0gVkJ30x4UEpb8fXLD8z5J9EYrbQZDZD" account_id = "17841458386736965" def load_media_info(access_token, account_id): base_url = f"https://graph.facebook.com/v11.0/{account_id}/media" params = { "fields": "id,media_type,media_url,thumbnail_url,permalink,caption,timestamp,like_count,comments_count,insights.metric(impressions,reach,engagement),children{media_type,media_url}", "access_token": access_token } items = [] while base_url: response = requests.get(base_url, params=params) data = json.loads(response.text) items.extend(data["data"]) if "paging" in data and "next" in data["paging"]: base_url = data["paging"]["next"] params = {} else: base_url = None return pd.DataFrame(items) df = load_media_info(access_token, account_id) if 'thumbnail_url' not in df.columns: df['thumbnail_url'] = df['media_url'] df['thumbnail_url'] = df.apply(lambda x: x["media_url"] if x["media_type"] == "IMAGE" else x["thumbnail_url"], axis=1) df["id"] = df["timestamp"] df["id"] = df["id"].apply(lambda x: datetime.datetime.strptime(x.split("+")[0], "%Y-%m-%dT%H:%M:%S").strftime("%Y%m%d")) df = df.sort_values("timestamp", ascending=False) df["id_rank"] = [f"_{len(list(group))}" for _, group in groupby(df["id"])] df["id"] += df["id_rank"] menu = ["Content", "Analytics"] choice = st.sidebar.radio("Menu", menu) if "load_more" not in st.session_state: st.session_state.load_more = 0 def display_carousel(carousel_items): scale_factor = 0.15 display_images = [] for url in carousel_items: req_img = requests.get(url) img_bytes = req_img.content img = Image.open(BytesIO(img_bytes)) display_image = ImageOps.scale(img, scale_factor) display_images.append(display_image) st.image(display_images, width=300) if choice == "Content": selected_id = st.sidebar.selectbox("Select Post", df["id"].unique()) selected_data = df[df["id"] == selected_id].iloc[0] image_url = selected_data["media_url"] if selected_data["media_type"] == "IMAGE" else selected_data["thumbnail_url"] image_response = requests.get(image_url) image = Image.open(BytesIO(image_response.content)) # Display carousel if "children" in selected_data.keys(): carousel_items = [child_data["media_url"] for child_data in selected_data["children"]["data"]] display_carousel(carousel_items) else: display_carousel([image_url]) # Process caption text caption_text = selected_data["caption"] if caption_text: start_desc_index = caption_text.find("[Description]") if start_desc_index != -1: caption_text = caption_text[start_desc_index + 13:] # Remove text before "[Description]" end_tags_index = caption_text.find("[Tags]") if end_tags_index != -1: caption_text = caption_text[:end_tags_index] # Remove text from "[Tags]" st.write(caption_text.strip()) likes = selected_data["like_count"] if "insights" in selected_data.keys(): try: impressions = selected_data["insights"][0]['values'][0]['value'] percentage = (likes * 100) / impressions st.write(f"いいね: {likes} (インプレッションに対する割合: {percentage:.1f}%)") except (KeyError, IndexError): st.write(f"いいね: {likes}") else: st.write(f"いいね: {likes}") st.write(f"コメント数: {selected_data['comments_count']}") # Get comments and usernames try: shortcode = selected_data["permalink"].split("/")[-2] post = instaloader.Post.from_shortcode(loader.context, shortcode) comments = post.get_comments() comment_list = [(comment.owner.username, comment.text) for comment in comments] if st.session_state.load_more: for username, text in comment_list: st.write(f"{username}: {text}") else: for username, text in comment_list[:5]: # Show only the first 5 comments st.write(f"{username}: {text}") # Load more button if st.button("さらに表示"): st.session_state.load_more += 1 except Exception as e: st.write("コメントの取得中にエラーが発生しました。") elif choice == "Analytics": categories = ["いいね数", "コメント数"] selected_category = st.selectbox("Select metric", categories) if selected_category == "いいね数": metric = "like_count" elif selected_category == "コメント数": metric = "comments_count" chart_df = df[["id", "timestamp", metric]].copy() chart_df["timestamp"] = pd.to_datetime(chart_df["timestamp"]).dt.date chart = alt.Chart(chart_df).mark_line().encode( x="timestamp:T", y=metric + ":Q" ).properties( title=f"Time Series of {selected_category}", width=800, height=300 ) st.altair_chart(chart) ''' 上記コードにてJupyter開発環境ではエラー表示はなく、streamlitで表示された事を確認できました。しかし、期待された表示がされていない箇所があるため、以下に改修点を列挙します。 ①"Content"の説明文について、"[Description]"の前の文字列と、"[Tags]"を含めたそれ以降の文字列を削除するための機能が動作していないため、抜本的な対処も含めて改修してください。 ②"いいね数"の横に(29.4%)のように表示する、コンテンツのインプレッション数に対する"いいね率"が正常に表示されておりません。抜本的な対処も含めて改修してください。 ③コンテンツの写真については、全画面表示に切り替えたとき以外は、1枚目の写真のみ表示するよう改修してください。 これらの機能が正常に動作するよう修正済みのコードを省略せずにすべて表示してください。
0d83f41f258c451489537fffe03b8377
{ "intermediate": 0.34760522842407227, "beginner": 0.3995046615600586, "expert": 0.25289005041122437 }
575
This is my game window size 1382 x 784 and these are the values of the correct rectangle left: 841 top: 678 width: 145 height: 18 How can I get the relative values for different window sizes in python?
3d42208fab5f77add6c2928aa1b1cb98
{ "intermediate": 0.5666468143463135, "beginner": 0.10620571672916412, "expert": 0.3271474838256836 }
576
In python, make a machine learning moudel to predict a 5x5 minesweeper game. You can't make it random or make it predict 2 same results in a row if a new game is started. You have data for the past 10 games: [2, 12, 18, 10, 12, 21, 1, 5, 13, 12, 21, 23, 7, 15, 24, 10, 14, 23, 9, 15, 16, 11, 19, 22, 2, 7, 17, 1, 6, 8] and you need to predict 4 safe spots. You need to use the list raw
bd503c29f1016584a8c4c41c201f68b2
{ "intermediate": 0.15513455867767334, "beginner": 0.09273305535316467, "expert": 0.7521323561668396 }
577
QUE ES lo que falla en este codigo: "import random class Coin: def __init__(self): self.chain = None self.staked_coins = None self.current_supply = None self.max_supply = None def init(self, max_supply): self.max_supply = max_supply self.current_supply = 0 self.staked_coins = {} self.chain = [] def issue_initial_supply(self, initial_supply, users): coins_per_user = initial_supply // len(users) for user in users: user.receive_coins(coins_per_user) self.current_supply += coins_per_user def stake_coins(self, user, amount): if user.balance >= amount: user.lock_coins(amount) self.staked_coins[user] = amount def create_block(self, validator, transactions): if self.current_supply < self.max_supply: new_block = { "validator": validator, "transactions": transactions, "reward": 10 } self.chain.append(new_block) self.current_supply += new_block["reward"] validator.receive_coins(new_block["reward"]) class User: def __init__(self): self.staked_balance = None self.balance = None self.name = None def init(self, name): self.name = name self.balance = 0 self.staked_balance = 0 def receive_coins(self, amount): self.balance += amount def lock_coins(self, amount): self.balance -= amount self.staked_balance += amount def select_validator(staked_coins): validators = list(staked_coins.keys()) stakes = list(staked_coins.values()) return random.choices(validators, weights=stakes, k=1)[0] def main(): # Inicializar criptomoneda y usuarios example_coin = Coin(1000000) users = [User(f"User{i}") for i in range(4)] # Emitir suministro inicial y simular "staking" example_coin.issue_initial_supply(100000, users) for user in users: example_coin.stake_coins(user, user.balance // 2) # Simular creación y validación de bloques for i in range(5): validator = select_validator(example_coin.staked_coins) transactions = ["Dummy transaction"] # Aquí se agregarían transacciones reales example_coin.create_block(validator, transactions) print(f"Block {i + 1} created and validated by {validator.name}") for user in users: print(f"{user.name}: balance={user.balance} staked={user.staked_balance}") print() if __name__ == "__main__": main()"
219442fbf563dffe8842cc789613a4fd
{ "intermediate": 0.3485088646411896, "beginner": 0.4133698046207428, "expert": 0.23812134563922882 }
578
I have a function f(x)=((6x^2-5x+3)/(2x-1)) so find the solutions for a,b,c so that f(x)=a+bx+(c/(2x-1))
43c21875b46e22c2992118b286acbf99
{ "intermediate": 0.36974695324897766, "beginner": 0.25663164258003235, "expert": 0.37362140417099 }
579
This is my game window: {left} {top} {width} {height} -8 -8 1382 784 and I currently got the game area i need, which is: {left} {top} {width} {height} 841 678 145 18 it works but for that initial window values. How can I get the same area for different window sizes? The code I have right now is this: game_window = pyautogui.getWindowsWithTitle(window_title)[0] left = game_window.left top = game_window.top width = game_window.width height = game_window.height Save_Screenshot(game_window.width/2 + 150, game_window.bottom - 98, 145, 18)
01769b4ee85a8adef7aa44b7b7c9a798
{ "intermediate": 0.45310622453689575, "beginner": 0.3343864679336548, "expert": 0.21250732243061066 }
580
Make an Elevator system in unreal engine blueprints with queue.
2363124df66927aaecbf61d0adda5eed
{ "intermediate": 0.28206151723861694, "beginner": 0.23827195167541504, "expert": 0.479666531085968 }
581
es correcto lo de [user]? : "class Coin: def __init__(self): self.max_supply = None self.current_supply = 0 self.staked_coins = None self.chain = None def __init__(self, max_supply): self.chain = None self.staked_coins = None self.current_supply = 0 self.max_supply = max_supply def issue_initial_supply(self, initial_supply, users): coins_per_user = initial_supply // len(users) for user in users: user.receive_coins(coins_per_user) self.current_supply += coins_per_user def stake_coins(self, user, amount): if user.balance >= amount: user.lock_coins(amount) self.staked_coins[user] = amount"
0a81ba35380f6a640f1844593003a269
{ "intermediate": 0.3591978847980499, "beginner": 0.38565289974212646, "expert": 0.2551491856575012 }
582
write me a js line that calculates tax by combining the amount of provincial tax withheld and the amount of federal tax withheld, minus a per-dependent deduction from the total tax withheld
b5c4a2bda06b1828843a585b1c30fc22
{ "intermediate": 0.3769652247428894, "beginner": 0.29989171028137207, "expert": 0.3231430649757385 }
583
How do I reference a nix package when building a nix shell using a shell.nix file?
a9a7814ff9786c4521b79987b2f92ba9
{ "intermediate": 0.5051296949386597, "beginner": 0.22355633974075317, "expert": 0.2713140547275543 }
584
react typescript, klinechart charting library. You need to access market data as here https://www.binance.com/ru/futures/DOGEUSDT here is my code import React, {useState, useEffect, ChangeEvent} from “react”; import { Badge, Box, Button, ButtonGroup, Chip, CircularProgress, Grid, Icon, IconButton, Skeleton, TextField, Typography } from “@mui/material”; import ArrowUpwardRoundedIcon from ‘@mui/icons-material/ArrowUpwardRounded’; import ArrowDownwardRoundedIcon from ‘@mui/icons-material/ArrowDownwardRounded’; import {useAuthContext} from “…/…/AuthProvider/AuthProvider”; import FormatPrice from “…/…/Common/FormatPrice”; import {Order, readCandlesByTrade, readOrderByTrade, Trade, updateTrade} from “…/…/…/actions/cicap-diary-trades”; import DataTable from “…/…/DataTable/DataTable”; import {useSnackbar} from “notistack”; import {CandleChart} from “…/CandleChart/CandleChart”; import {TradeEntity} from “…/CandleChart/CandleChart.props”; import {FormattedNumber} from “react-intl”; import ImageIcon from “next/image”; import {createTradeImage, deleteTradeImage, tradeImagesCollection, TradeImage} from “…/…/…/actions/cicap-diary-trades-images”; const timezoneOffset = new Date().getTimezoneOffset() * 60; interface SideTypeProps { order: Order; } const SideType = ({order}: SideTypeProps) => { let label = ‘’; let color = ‘default’; const icon = order?.side && ‘sell’ === order.side ? ArrowDownwardRoundedIcon : ArrowUpwardRoundedIcon; switch (order?.type) { case ‘limit’: label = ‘L’; color = ‘success’ break; case ‘market’: label = ‘M’; color = ‘warning’ break; case ‘stop_market’: label = ‘F’; color = ‘primary’ break; } return <> <Badge badgeContent={label} // @ts-ignore color={color} > <Icon component={icon} color=“action” /> </Badge> </> } interface CandlePrice { timestamp: number; open: number; high: number; low: number; close: number; volume: number; } interface TradeDetailsProps { tradeId: string; defaultChartInterval: string; } const TradeDetails = ({tradeId, defaultChartInterval}: TradeDetailsProps) => { const [trade, setTrade] = useState<{orders: Array<Order>, data: Trade} | undefined>(undefined); const [orders, setOrders] = useState<Array<TradeEntity>>([]); const [chartInterval, setChartInterval] = useState(defaultChartInterval); const [waiting, setWaiting] = useState(false); const [candleData, setCandleData] = useState<Array<CandlePrice>>([]); const [images, setImages] = useState<Array<TradeImage>>([]); const [imageIdDeletion, setImageIdDeletion] = useState<string|null>(null); const {diaryToken} = useAuthContext(); const [description, setDescription] = useState(‘’); const [conclusion, setConclusion] = useState(‘’); const [videoLink, setVideoLink] = useState(‘’); const {enqueueSnackbar} = useSnackbar(); const ref = React.createRef<HTMLInputElement>(); const fetchTrade = () => { if (!tradeId || !diaryToken) { return; } setWaiting(true); readOrderByTrade(tradeId, diaryToken) .then(data => { setWaiting(false); if (!data) return; const newOrders: Array<TradeEntity> = []; data.orders.forEach(order => { const timestamp = Math.floor(order.msTimestamp) - timezoneOffset; newOrders.push({ time: timestamp, position: order.side, value: parseFloat(order.price), }); }); setTrade(data); setOrders(newOrders); }); } return <> <Box sx={{pr: 2}}> { trade?.data.id && candleData ? (<> <CandleChart images={images} candles={candleData} tradeId={trade?.data.id} orders={orders} interval={chartInterval} openPrice={trade?.data.openPrice} closePrice={trade?.data.closePrice} pricePrecision={trade.data.pricePrecision} quantityPrecision={trade.data.quantityPrecision} createImage={createImage} /> </>) : (<> <Skeleton variant=“rectangular” height={500} /> </>) } </Box> </> } import React, {useEffect, useRef, useState} from “react”; import { init, dispose, Chart, DeepPartial, IndicatorFigureStylesCallbackData, Indicator, IndicatorStyle, KLineData, utils, } from “klinecharts”; import {CandleChartProps} from “./CandleChart.props”; import CandleChartToolbar from “./CandleChartToolbar”; import {Style} from “util”; import {Box, Icon, IconButton, Stack} from “@mui/material”; import getMinutesTickSizeByInterval from “./utils/getMinutesTickSizeByInterval.util”; import drawTrade from “./utils/drawTrade.util”; import drawTradeLines from “./utils/drawTradeLines.util”; import {BasketIcon, ScreenIcon} from “…/…/icons”; import {FullScreen, useFullScreenHandle} from “react-full-screen”;; interface Vol { volume?: number } export const CandleChart = ({ images, candles, tradeId, orders, interval, openPrice, closePrice, pricePrecision, quantityPrecision, createImage }: CandleChartProps) => { console.log(candles); const chart = useRef<Chart|null>(); const paneId = useRef<string>(“”); const [figureId, setFigureId] = useState<string>(“”) const ref = useRef<HTMLDivElement>(null); const handle = useFullScreenHandle(); useEffect(() => { chart.current = init(chart-${tradeId}, {styles: chartStyles}); return () => dispose(chart-${tradeId}); }, [tradeId]); useEffect(() => { const onWindowResize = () => chart.current?.resize(); window.addEventListener(“resize”, onWindowResize); return () => window.removeEventListener(“resize”, onWindowResize); }, []); useEffect(() => { chart.current?.applyNewData(candles); chart.current?.overrideIndicator({ name: “VOL”, shortName: “Объем”, calcParams: [], figures: [ { key: “volume”, title: “”, type: “bar”, baseValue: 0, styles: (data: IndicatorFigureStylesCallbackData<Vol>, indicator: Indicator, defaultStyles: IndicatorStyle) => { const kLineData = data.current.kLineData as KLineData let color: string if (kLineData.close > kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].upColor”, (defaultStyles.bars)[0].upColor) as string } else if (kLineData.close < kLineData.open) { color = utils.formatValue(indicator.styles, “bars[0].downColor”, (defaultStyles.bars)[0].downColor) as string } else { color = utils.formatValue(indicator.styles, “bars[0].noChangeColor”, (defaultStyles.bars)[0].noChangeColor) as string } return { color } } } ] }, paneId.current); chart.current?.createIndicator(“VOL”, false, { id: paneId.current }); chart.current?.setPriceVolumePrecision(+pricePrecision, +quantityPrecision); }, [candles]); useEffect(() => { if (!orders || orders.length === 0 || candles.length === 0) return; const minTime = orders[0].time; const maxTime = orders[orders.length - 1].time; const needleTime = minTime + (maxTime - minTime) / 2; chart.current?.scrollToTimestamp(needleTime + 45 * getMinutesTickSizeByInterval(interval) * 60 * 1000); drawTrade(chart, paneId, orders, interval); if (openPrice && closePrice) { let openTime = Infinity; let closeTime = -Infinity; orders.forEach(order => { if (openTime > order.time) { openTime = order.time; } if (closeTime < order.time) { closeTime = order.time; } }); drawTradeLines( chart, openPrice, openTime, closePrice, closeTime, orders[0].position, paneId, pricePrecision, quantityPrecision, ); } }, [orders, candles, tradeId]); return (<> <Stack direction=“row” height={!handle.active ? 550 : “100%”} width=“100%”> <CandleChartToolbar setFigureId={setFigureId} chart={chart} paneId={paneId} handle={handle} /> <Box ref={ref} id={chart-${tradeId}} width=“calc(100% - 55px)” height={!handle.active ? 550 : “100%”} sx={{ borderLeft: “1px solid #ddd” }} > { figureId.length > 0 && <Stack sx={{ backgroundColor: “#CBD4E3”, borderRadius: 1, position: “absolute”, zIndex: 10, right: 80, top: 30, border: “1px solid #697669”, }} spacing={2} > <IconButton sx={{ borderRadius: 1 }} onClick={removeFigure}> <Icon component={BasketIcon} /> </IconButton> </Stack> } </Box> </Stack> </>); } In those transactions where there is no closed order, you need to display real-time candles on the chart and calculate the percentage at the current price. This is necessary so that you can follow the transaction in real time. It is necessary that the chart reflects the current situation on the market, as here https://www.binance.com/ru/futures/DOGEUSDT
a8b4892829c06c8d064889551776ba01
{ "intermediate": 0.3814411759376526, "beginner": 0.41001394391059875, "expert": 0.20854489505290985 }
585
clean up, remove comments: <script setup> import { onMounted, ref, reactive, watchEffect } from 'vue'; import {comma } from '@/assets/countries.js'; const props = defineProps({ uuid: Number, country: Number || String || Object, title: String, countryName: String, }); const identifier = ref(String(props.title).toLocaleLowerCase().replace(' ', '-')); const random = ref(Math.floor(Math.random() * 100) + 35); onMounted(()=>{ gsap.fromTo(`#${identifier.value}-${props.uuid}`, { marginTop: 10, duration: 0.3, opacity: 0, x:-150, scale:0.1, stagger: 0.8 },{ marginTop: 0, duration: 0.4, opacity: 1, x:0, scale: 1.1, },'-=0.39'); }) /* Smoothed number count anims */ const tweened = reactive({ number: 0 }) function callAnim(n){ gsap.to(tweened, { duration: 0.35, number: Number(n) || 0}) } watchEffect(()=>{ return callAnim(props.country) }) function updateNum(){ return comma(tweened.number.toFixed(0)) } </script> <template> <Flicking :options="{ gap: 10, circular: true, deceleration: 0.015, moveType: 'freeScroll' }"> <div class="properties mx-2 "> <div v-if="identifier === 'defense-budget' && country >= 0 " > <div class="btn shadow-none "> <div class="overflow-hidden hover-effect ">{{title}}</div> <p class=" z-index-down " :title="props.title" :id="identifier + '-'+uuid"> <span class="text-main" v-if="country > 0">{{ "$" + updateNum() }}</span> <p v-if="country <= 0" :style="{'width': random+'px' }" class=" position-relative"> </p> </p> </div> </div> <div v-if="identifier === 'manpower' && country >= 0 "> <div class="btn shadow-none "> <div class="overflow-hidden hover-effect">{{title}}</div> <p class=" z-index-down" :title="props.title" :id="identifier + '-'+uuid"> <span class="text-main" v-if="country > 0">{{ updateNum() }}</span> <p v-if="country <= 0" :style="{'width': random+'px' }" class=" position-relative"> </p> </p> </div> </div> <div v-if="identifier === 'active' && country >= 0 " > <div class="btn shadow-none "> <div class="overflow-hidden hover-effect">{{title}}</div> <p class=" z-index-down" :title="props.title" :id="identifier + '-'+uuid"> <span class="text-main" v-if="country > 0">{{ updateNum() }}</span> <p v-if="country <= 0" :style="{'width': random+'px' }" class=" position-relative"> </p> </p> </div> </div> <div v-if="identifier === 'reserves' && country >= 0 " > <div class="btn shadow-none "> <div class="overflow-hidden hover-effect">{{title}}</div> <p class=" z-index-down" :title="props.title" :id="identifier + '-'+uuid"> <span class="text-main" v-if="country > 0">{{ updateNum() }}</span> <p v-if="country <= 0" :style="{'width': random+'px' }" class=" position-relative"> </p> </p> </div> </div> <div v-if="identifier === 'land-area' && country >= 0 " > <div class="btn shadow-none "> <div class="overflow-hidden hover-effect">{{title}}</div> <p class=" z-index-down" :title="props.title" :id="identifier + '-'+uuid"> <span class="text-main" v-if="country > 0">{{ updateNum() + ' km²' }}</span> <p v-if="country <= 0" :style="{'width': random+'px' }" class=" position-relative"> </p> </p> </div> </div> <div v-if="identifier === 'oil' && country >= 0 " > <div class="btn shadow-none "> <div class="overflow-hidden hover-effect">{{title}}</div> <p class=" z-index-down" :title="props.title" :id="identifier + '-'+uuid"> <span class="text-main" v-if="country > 0">{{ updateNum() + ' bbl' }}</span> <p v-if="country <= 0" :style="{'width': random+'px' }" class=" position-relative"> </p> </p> </div> </div> <div v-if="identifier === 'gdp' && country >= 0 " > <div class="btn shadow-none "> <div class="overflow-hidden hover-effect">{{title}}</div> <p class=" z-index-down" :title="props.title" :id="identifier + '-'+uuid"> <span class="text-main" v-if="country > 0">{{ "$" + updateNum() }}</span> <p v-if="country <= 0" :style="{'width': random+'px' }" class=" position-relative"> </p> </p> </div> </div> </div> </Flicking> </template>
a69368ac531ef3b6b36a844dd1f3c2bd
{ "intermediate": 0.39827579259872437, "beginner": 0.3502812087535858, "expert": 0.2514430582523346 }
586
clean up this code for production: <script setup> import { onMounted, ref, reactive, watchEffect } from 'vue'; import {comma } from '@/assets/countries.js'; const props = defineProps({ uuid: Number, country: Number || String || Object, title: String, countryName: String, }); const identifier = ref(String(props.title).toLocaleLowerCase().replace(' ', '-')); const random = ref(Math.floor(Math.random() * 100) + 35); onMounted(()=>{ gsap.fromTo(`#${identifier.value}-${props.uuid}`, { marginTop: 10, duration: 0.3, opacity: 0, x:-150, scale:0.1, stagger: 0.8 },{ marginTop: 0, duration: 0.4, opacity: 1, x:0, scale: 1.1, },'-=0.39'); }) /* Smoothed number count anims */ const tweened = reactive({ number: 0 }) function callAnim(n){ gsap.to(tweened, { duration: 0.35, number: Number(n) || 0}) } watchEffect(()=>{ return callAnim(props.country) }) function updateNum(){ return comma(tweened.number.toFixed(0)) } </script>
cc683fbffb40c22d18276a5c0b03e73f
{ "intermediate": 0.4243357181549072, "beginner": 0.35259732604026794, "expert": 0.22306695580482483 }
587
This is my game window: {left} {top} {width} {height} -8 -8 1382 784 and I want to get this game area i need, which is: {left} {top} {width} {height} 841 678 145 18 How can I get the same area for different window sizes? The code I have right now is wrong and giving me wrong values: game_window = pyautogui.getWindowsWithTitle(window_title)[0] left = game_window.left top = game_window.top width = game_window.width height = game_window.height initial_window_width = 1382 initial_window_height = 784 initial_game_area_left = 841 initial_game_area_top = 678 initial_game_area_width = 145 initial_game_area_height = 18 left_ratio = initial_game_area_left / initial_window_width top_ratio = initial_game_area_top / initial_window_height width_ratio = initial_game_area_width / initial_window_width height_ratio = initial_game_area_height / initial_window_height game_area_left = left + (width * left_ratio) game_area_top = top + (height * top_ratio) game_area_width = width * width_ratio game_area_height = height * height_ratio Save_Screenshot(game_area_left, game_area_top, game_area_width, game_area_height)
1823453677ec71da9afcf11a6e61359e
{ "intermediate": 0.42567363381385803, "beginner": 0.37355858087539673, "expert": 0.20076780021190643 }
588
Есть ли замечания для этого кода: #include <cassert> #include <cstddef> #include <iterator> #include <string> #include <utility> #include <iostream> template <typename Type> class SingleLinkedList { struct Node { Node() = default; Node(const Type& val, Node* next) : value(val) , next_node(next) { } Type value; Node* next_node = nullptr; }; template <typename ValueType> class BasicIterator { friend class SingleLinkedList; explicit BasicIterator(Node* node) { node_ = node; } public: using iterator_category = std::forward_iterator_tag; using value_type = Type; using difference_type = std::ptrdiff_t; using pointer = ValueType*; using reference = ValueType&; BasicIterator() = default; BasicIterator(const BasicIterator<Type>& other) noexcept { node_ = other.node_; } BasicIterator& operator=(const BasicIterator& rhs) = default; [[nodiscard]] bool operator==(const BasicIterator<const Type>& rhs) const noexcept { return node_ == rhs.node_; } [[nodiscard]] bool operator!=(const BasicIterator<const Type>& rhs) const noexcept { return node_ != rhs.node_; } [[nodiscard]] bool operator==(const BasicIterator<Type>& rhs) const noexcept { return node_ == rhs.node_; } [[nodiscard]] bool operator!=(const BasicIterator<Type>& rhs) const noexcept { return node_ != rhs.node_; } BasicIterator& operator++() noexcept { node_ = node_->next_node; return *this; } BasicIterator operator++(int) noexcept { auto old_value(*this); ++(*this); return old_value; } [[nodiscard]] reference operator*() const noexcept { return node_->value; } [[nodiscard]] pointer operator->() const noexcept { return &node_->value; } private: Node* node_ = nullptr; }; public: using value_type = Type; using reference = value_type&; using const_reference = const value_type&; using Iterator = BasicIterator<Type>; using ConstIterator = BasicIterator<const Type>; [[nodiscard]] Iterator begin() noexcept { return Iterator(head_.next_node); } [[nodiscard]] Iterator end() noexcept { Node* end = head_.next_node; while (end != nullptr) { end = end->next_node; } return Iterator(end); } [[nodiscard]] ConstIterator begin() const noexcept { return ConstIterator(head_.next_node); } [[nodiscard]] ConstIterator end() const noexcept { return cend(); } [[nodiscard]] ConstIterator cbegin() const noexcept { return ConstIterator(head_.next_node); } [[nodiscard]] ConstIterator cend() const noexcept { Node* end = head_.next_node; while (end != nullptr) { end = end->next_node; } return ConstIterator(end); } [[nodiscard]] Iterator before_begin() noexcept { return Iterator(&head_); } [[nodiscard]] ConstIterator cbefore_begin() const noexcept { return ConstIterator(const_cast<Node*>(&head_)); } [[nodiscard]] ConstIterator before_begin() const noexcept { return cbefore_begin(); } SingleLinkedList() : size_(0) { } SingleLinkedList(std::initializer_list<Type> values) : size_(0) { SingleLinkedList tmp; tmp.Assign(values.begin(), values.end()); swap(tmp); } SingleLinkedList(const SingleLinkedList& other) { *this = other; } ~SingleLinkedList() { Clear(); } Iterator InsertAfter(ConstIterator pos, const Type& value) { Node* node = new Node(value, pos.node_->next_node); pos.node_->next_node = node; ++size_; return Iterator(node); } Iterator EraseAfter(ConstIterator pos) noexcept { Node* node = pos.node_->next_node; Node* next = pos.node_->next_node->next_node; pos.node_->next_node = next; delete node; --size_; return Iterator(next); } void PopFront() noexcept { if (IsEmpty()) { return; } Node* node = head_.next_node; head_.next_node = head_.next_node->next_node; delete node; --size_; } void PushFront(const Type& value) { head_.next_node = new Node(value, head_.next_node); ++size_; } void Clear() { while (head_.next_node != nullptr) { Node* next_next_node = head_.next_node->next_node; delete head_.next_node; head_.next_node = next_next_node; } size_ = 0; } [[nodiscard]] size_t GetSize() const noexcept { return size_; } [[nodiscard]] bool IsEmpty() const noexcept { return head_.next_node == nullptr; } SingleLinkedList& operator=(const SingleLinkedList& rhs) { if (this != &rhs) { SingleLinkedList tmp; tmp.Assign(rhs.begin(), rhs.end()); swap(tmp); } return *this; } void swap(SingleLinkedList& other) noexcept { size_t tmp = size_; size_ = other.size_; other.size_ = tmp; Node* node_ptr = head_.next_node; head_.next_node = other.head_.next_node; other.head_.next_node = node_ptr; } template <typename It> void Assign(const It& begin, const It& end) { Node* last_node = &head_; for (auto it = begin; it != end; ++it) { last_node->next_node = new Node(*it, nullptr); last_node = last_node->next_node; ++size_; } } private: Node head_; size_t size_; }; template <typename Type> void swap(SingleLinkedList<Type>& lhs, SingleLinkedList<Type>& rhs) noexcept { lhs.swap(rhs); } template <typename Type> bool operator==(const SingleLinkedList<Type>& lhs, const SingleLinkedList<Type>& rhs) { return std::equal(lhs.begin(), lhs.end(), rhs.begin(), lhs.end()); } template <typename Type> bool operator!=(const SingleLinkedList<Type>& lhs, const SingleLinkedList<Type>& rhs) { return !(lhs == rhs); } template <typename Type> bool operator<(const SingleLinkedList<Type>& lhs, const SingleLinkedList<Type>& rhs) { return std::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end()); } template <typename Type> bool operator<=(const SingleLinkedList<Type>& lhs, const SingleLinkedList<Type>& rhs) { return lhs == rhs || lhs < rhs; } template <typename Type> bool operator>(const SingleLinkedList<Type>& lhs, const SingleLinkedList<Type>& rhs) { return rhs < lhs; } template <typename Type> bool operator>=(const SingleLinkedList<Type>& lhs, const SingleLinkedList<Type>& rhs) { return !(lhs < rhs); }
70521d817f3585450f6fdcfb751d040b
{ "intermediate": 0.31929126381874084, "beginner": 0.4982646703720093, "expert": 0.18244406580924988 }
589
Hi, I've implemented a DQN Agent and I want you to implement a code to test my implemented DQN on TWO environments:‘CartPole-v1’ and any other complex environment of your choice from OpenAI LunarLander, OpenAI MountainCar, OpenAI Atari Breakout (Choose the easy one). Provide performance results including reward dynamics (total reward per episode). Goal : ‘CartPole-v1’ environment is considered to be solved if it is getting an average reward of more than 470 points over 100 consecutive episodes during evaluation. That being said , Here is the DQN implementation: class DQNAgentPytorch: def __init__(self, env, memory_size=2000, epsilon=1.0, gamma=0.99, learning_rate=0.001): self.env = env self.observation_space = env.observation_space self.action_space = env.action_space self.memory = deque(maxlen=memory_size) self.epsilon = epsilon self.gamma = gamma self.lr = learning_rate self.model = self.build_model() self.target_model = self.build_model() self.optimizer = optim.Adam(self.model.parameters(), lr=self.lr) self.criterion = nn.MSELoss() self.update_target_net() def build_model(self): model = nn.Sequential( nn.Linear(self.observation_space.n, 16), nn.ReLU(), nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, self.action_space.n) ) return model def remember(self, state, action, reward, next_state, done): self.memory.append((state, action, reward, next_state, done)) def choose_action(self, state, test=False): if test or random.random() > self.epsilon: with torch.no_grad(): state_oh = self.state_to_onehot(state) q_values = self.model(state_oh) return torch.argmax(q_values).item() else: return np.random.randint(self.action_space.n) def state_to_onehot(self, state): return torch.tensor(np.identity(self.observation_space.n)[state].reshape(1, -1), dtype=torch.float32) def train(self, batch_size): if len(self.memory) < batch_size: return minibatch = random.sample(self.memory, batch_size) for state, action, reward, next_state, done in minibatch: target = self.target_model(self.state_to_onehot(state)).squeeze(0) if done: target[action] = reward else: next_q_values = self.target_model(self.state_to_onehot(next_state)).squeeze(0) target[action] = reward + self.gamma * torch.max(next_q_values) inputs = self.state_to_onehot(state) targets = target.unsqueeze(0) self.optimizer.zero_grad() outputs = self.model(inputs) loss = self.criterion(outputs, targets) loss.backward() self.optimizer.step() def update_target_net(self): self.target_model.load_state_dict(self.model.state_dict()) def update_epsilon(self, new_epsilon): self.epsilon = new_epsilon def save_weights(self, file_name): torch.save(self.model.state_dict(), file_name) def load_weights(self, file_name): self.epsilon = 0 self.model.load_state_dict(torch.load(file_name)) def train_dqn(agent, episodes, batch_size, epsilon_decay=0.995, min_epsilon=0.01): rewards = [] steps_list = [] epsilons = [] target_update_freq = 25 for episode_i in range(1, episodes + 1): state = agent.env.reset() done = False episode_reward = 0 steps = 0 while not done: steps += 1 action = agent.choose_action(state) next_state, reward, done, _ = agent.env.step(action) agent.remember(state, action, reward, next_state, done) agent.train(batch_size) state = next_state episode_reward += reward if steps % target_update_freq == 0: agent.update_target_net() rewards.append(episode_reward) steps_list.append(steps) epsilons.append(agent.epsilon) agent.update_epsilon(max(agent.epsilon * epsilon_decay, min_epsilon)) print(f"Episode: {episode_i}, Total Reward: {episode_reward}, Epsilon: {agent.epsilon}, Steps: {steps}") return rewards, epsilons, steps_list def plot_results(rewards, epsilons): plt.subplot(2, 1, 1) plt.plot(rewards) plt.title('DQN GridWorld Rewards') plt.subplot(2, 1, 2) plt.plot(epsilons) plt.title('Epsilon Decay') plt.xlabel('Episodes') plt.tight_layout() plt.show()env = GridWorldDeterministic() agent = DQNAgentPytorch(env) rewards, epsilons, steps_list = train_dqn(agent, episodes=100, batch_size=32) plot_results(rewards, epsilons) agent.save_weights('aboda_assignment2_part2_dqn_gridworld.h5') def evaluate(agent, env, episodes=5, max_steps=10): test_rewards = [] for episode_i in range(1, episodes + 1): state = env.reset() done = False total_reward = 0 step = 0 while not done and step < max_steps: action = agent.choose_action(state, test=True) next_state, reward, done, _ = env.step(action) env.render() print("Action taken:", action) print("New state:", state) print("Reward received:", reward) print("Done?", done) print("="*20) state = next_state total_reward += reward step += 1 test_rewards.append(total_reward) print(f'Test Episode: {episode_i}, Total Reward: {total_reward}, Steps: {step}') return test_rewards env = GridWorldDeterministic() agent = DQNAgentPytorch(env) agent.load_weights('aboda_assignment2_part2_dqn_gridworld.h5') test_rewards = evaluate(agent, env) # Plot test reward graph plt.plot(test_rewards) plt.xlabel('Test Episodes') plt.ylabel('Rewards') plt.title('DQN GridWorld Test Rewards') plt.grid() plt.show()
35c03f964a01772f5e3d7052391cb9b7
{ "intermediate": 0.277553528547287, "beginner": 0.43259716033935547, "expert": 0.28984931111335754 }
590
In python, make me some code that predicts a 5x5 field minesweeper. You're supposed to predict 4 safe spots, where you've data for the past 10 games: [2, 12, 18, 10, 12, 21, 1, 5, 13, 12, 21, 23, 7, 15, 24, 10, 14, 23, 9, 15, 16, 11, 19, 22, 2, 7, 17, 1, 6, 8]. Use machine learning and use the raw list and also it cant be random or predict the same spots two times in a row
bbe5166907722213018b4773d30b6f20
{ "intermediate": 0.15785764157772064, "beginner": 0.044563986361026764, "expert": 0.7975783944129944 }
591
Make this code more readable if possible just print the code no explaining:<script setup> import { onMounted, ref, reactive, watchEffect, defineProps } from 'vue'; import { comma } from '@/assets/countries.js'; import gsap from 'gsap'; const props = defineProps({ uuid: Number, country: [Number, String, Object], title: String, countryName: String, }); const identifier = ref(props.title.toLowerCase().replace(/ /g, '-')); const random = ref(Math.floor(Math.random() * 100) + 35); onMounted(() => { const element = document.querySelector(`#${identifier.value}-${props.uuid}`); if (!element) return; gsap.fromTo(element, { marginTop: 10, duration: 0.3, opacity: 0, x: -150, scale: 0.1, stagger: 0.8, }, { marginTop: 0, duration: 0.4, opacity: 1, x: 0, scale: 1.1, }, '-=0.39'); }); const tweened = reactive({ number: 0, }); watchEffect(() => { const countryNumber = Number(props.country); if (isNaN(countryNumber)) return; gsap.to(tweened, { duration: 0.35, number: countryNumber }); }); function formatNumber() { return comma(tweened.number.toFixed(0)); } </script> <template> <Flicking :options="{ gap: 10, circular: true, deceleration: 0.015, moveType: 'freeScroll' }"> <div class="properties mx-2 " v-if="props.country >= 0 && ['defense-budget', 'manpower', 'active', 'reserves', 'land-area', 'oil', 'gdp'].includes(identifier)"> <div class="btn shadow-none "> <div class="overflow-hidden hover-effect">{{ props.title }}</div> <p :title="props.title" :id="`${identifier}-${props.uuid}`" class="z-index-down"> <span class="text-main" v-if="props.country > 0"> <template v-if="identifier === 'land-area'">{{ `${formatNumber()} km²` }}</template> <template v-else-if="identifier === 'oil'">{{ `${formatNumber()} bbl` }}</template> <template v-else>{{ `$${formatNumber()}` }}</template> </span> <p v-else :style="{ width: `${random}px` }" class="position-relative"></p> </p> </div> </div> </Flicking> </template>
663e3945c62793b3f5d730014ee39a6c
{ "intermediate": 0.2836446464061737, "beginner": 0.5769652128219604, "expert": 0.13939018547534943 }
592
If I have load django templates in gunicorn config, should I write static/templates paths in nginx config?
d608281c23dc75288c4b40d297a0d47b
{ "intermediate": 0.6463713645935059, "beginner": 0.20496664941310883, "expert": 0.1486620157957077 }
593
i have this code: window_rect = (game_window.left, game_window.top, game_window.width, game_window.height) game_area_rect = (841, 678, 145, 18) # Calculate the game area position and size as a fraction of the window size fraction_left = float(game_area_rect[0] - window_rect[0]) / window_rect[2] fraction_top = float(game_area_rect[1] - window_rect[1]) / window_rect[3] fraction_width = float(game_area_rect[2]) / window_rect[2] fraction_height = float(game_area_rect[3]) / window_rect[3] # Calculate the actual position and size of the game area in the window game_area_left = game_window.left + (game_window.width * fraction_left) game_area_top = game_window.top + (game_window.height * fraction_top) game_area_width = game_window.width * fraction_width game_area_height = game_window.height * fraction_height print("Game area:", game_area_left, game_area_top, game_area_width, game_area_height) I need that the game area moves based on initial window position, and if I run the script with a different starting position it should always point the same area
1cbe5c22d496d3fe4a18a8854047887c
{ "intermediate": 0.41826900839805603, "beginner": 0.3196876347064972, "expert": 0.2620433270931244 }
594
Can you predcit a towers game based on the previes data?
c2e18b25bb5a7b393b9d06a02630f52a
{ "intermediate": 0.3394268751144409, "beginner": 0.15159684419631958, "expert": 0.5089762806892395 }
595
create a object oriented rock paper scissor tournament simulation
f62d00509d5b86e92a2e689eab930b58
{ "intermediate": 0.23945587873458862, "beginner": 0.35278117656707764, "expert": 0.40776297450065613 }
596
hi
62303cf25b22c465b512020112ea50ec
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
597
can cv2.matchTemplate be used for an arbitrary size template? I have a template that is from one screen size, but if I change the window size the template change too. Or there is another simple alternative? Also I don't know beforehand the size of the window nor the size to resize the template to, to fit the window
83bec2c50a7e458f02680fa54c64f64e
{ "intermediate": 0.44270002841949463, "beginner": 0.22908732295036316, "expert": 0.3282126784324646 }
598
how to deploy pure python algotrading code into vercel?
c0ba50827c6f504c40004a5ffa3906a9
{ "intermediate": 0.11871939152479172, "beginner": 0.25160929560661316, "expert": 0.6296713352203369 }
599
How would you go about introducing shading into a 3D game written in C# and Monogame?
039f0e84ed80ecf99d62aa30978ca03f
{ "intermediate": 0.46539798378944397, "beginner": 0.2833625376224518, "expert": 0.2512394189834595 }
600
"Give me a list of interview questions & thier answers on Install WordPress on EC2 with RDS Database for AWS DevOps engineers only While giving answers, first write a question, then give the answer"
08d062a0c30ff6eb6e676c5b3c0d1413
{ "intermediate": 0.4426296353340149, "beginner": 0.31462132930755615, "expert": 0.24274906516075134 }
601
generate a simple working Example of Vue Router Transition using the latest vue version
a1c9fd31fc07742298c7026fb4388fd0
{ "intermediate": 0.5376994013786316, "beginner": 0.1727232187986374, "expert": 0.2895773947238922 }
602
line 19, in <module> if hinst <= wintypes.HINSTANCE_ERROR: AttributeError: module 'ctypes.wintypes' has no attribute 'HINSTANCE_ERROR'
c333ea17692270403421519cfc7edd41
{ "intermediate": 0.45974284410476685, "beginner": 0.25050589442253113, "expert": 0.28975120186805725 }