row_id
int64
0
48.4k
init_message
stringlengths
1
342k
conversation_hash
stringlengths
32
32
scores
dict
3,314
I am writing an outlook plugin in C# using Microsoft Graph 5. My development environment is Visual Studio.I need to authenticate with an azure tenancy using Microsoft.Identity. Please show me complete, working and well commented code to demonstrate how I can authenticate using a registered app secret.
7fb6793734deaab12d3191127d4e551b
{ "intermediate": 0.5838777422904968, "beginner": 0.20647020637989044, "expert": 0.20965203642845154 }
3,315
I am writing an outlook plugin in C# using Microsoft Graph 5. My development environment is Visual Studio.I need to authenticate with an azure tenancy using Microsoft.Identity. Please show me complete, working and well commented code to demonstrate how I can authenticate using a registered app secret.
526f292017ad0a0294d9b459d62c7a78
{ "intermediate": 0.5838777422904968, "beginner": 0.20647020637989044, "expert": 0.20965203642845154 }
3,316
I am writing an outlook plugin in C# using Microsoft Graph 5. My development environment is Visual Studio.I need to authenticate with an azure tenancy using Microsoft.Identity. Please show me complete, working and well commented code to demonstrate how I can authenticate using a registered app secret. The code should be presented as one or more files which can be added to my project.
6c66f3ab5ded602af50bde78bccd58c2
{ "intermediate": 0.6197530627250671, "beginner": 0.17064552009105682, "expert": 0.20960143208503723 }
3,317
loadGLTFModel(url) { // 创建 DRACOLoader 实例 // const dracoLoader = new DRACOLoader(); // Instantiate a loader if (!this.loaderGLTF) { //this.loaderGLTF = new GLTFLoader().setPath('/static/models/gltf/'); if (url.indexOf('.glb') != -1) { this.loaderGLTF = new GLTFLoader().setPath('/static/models/gltf/'); } else if (url.indexOf('.fbx') != -1) { console.log('******************fbx') this.loaderGLTF = new FBXLoader().setPath('/static/models/fbx/'); } } // this.loaderGLTF.setDRACOLoader( dracoLoader ); this.progress = 0; this.isLoading = true; this.loaderGLTF.load( url, // 模型 URL 可以是本地静态资源,也可以是网上的 url gltf => { this.isLoading = false; // 加载完成后回调 //console.log(gltf); let theObject = gltf.scene; theObject = gltf.scene; theObject.name = 'theObject'; // 遍历每个材质,设置其纹理贴图相关的属性 theObject.traverse(obj => { if (obj.type === 'Mesh'&& obj.material.map) { console.log(obj.material) const mat = obj.material; if (mat.map) { mat.map.encoding = THREE.sRGBEncoding; mat.map.anisotropy = 16; mat.map.wrapS = THREE.RepeatWrapping; mat.map.wrapT = THREE.RepeatWrapping; mat.map.minFilter = THREE.LinearFilter; mat.map.magFilter = THREE.LinearFilter; // 如果有法线贴图,则将其转换为THREE.TangentSpaceNormalMap类型 if (mat.normalMap) { mat.normalMap.encoding = THREE.sRGBEncoding; mat.normalMap.type = THREE.TangentSpaceNormalMap; } } } }); this.removeFromScene(this.theObject); this.theObject = theObject; this.scene.add(this.theObject); console.log("场景材质:",this.scene.children[0]); console.log("场景材质:",this.scene.children[0].material); //调整大小,设置居中 this.setCenter(this.theObject); }, // 加载进度回调 xhr => { //console.log(Math.round((xhr.loaded / xhr.total) * 100) + '% loaded'); this.progress = Math.round((xhr.loaded / xhr.total) * 100); }, // 加载错误回调 error => { console.error('An error happened:' + error); this.isLoading = false; } ); },
e95be3d536f7211ddcf4da6528026e7c
{ "intermediate": 0.3234008848667145, "beginner": 0.4718285799026489, "expert": 0.20477049052715302 }
3,318
padding: 15px 11px 111px 11px; left, top, right, bottom?
39f5b31b067e2f8c7f4a20c7125e706a
{ "intermediate": 0.29809531569480896, "beginner": 0.31162208318710327, "expert": 0.39028260111808777 }
3,319
do animation of flags container, which will switch between night and day modes accordingly with some filter maybe? and attach a botton, css only.: .flags-container { position: fixed; top: 0; left: 0; right: 0; --padding: 3px 0; background-color: white; display: flex; justify-content: center; align-items: center; --box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 10; }
f03dc8f3b5083a0d7f71d92b8505a437
{ "intermediate": 0.3377637565135956, "beginner": 0.25750160217285156, "expert": 0.40473470091819763 }
3,320
do animation of flags container, which will switch between night and day modes accordingly with some filter maybe? and attach a botton, css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.css only.: .flags-container { position: fixed; top: 0; left: 0; right: 0; --padding: 3px 0; background-color: white; display: flex; justify-content: center; align-items: center; --box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); z-index: 10; }
4ed91f71c3faab0a6e3235a7da0e1b78
{ "intermediate": 0.3072299361228943, "beginner": 0.3351689279079437, "expert": 0.3576011657714844 }
3,321
im getting this error:Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. this errors occurs after login when index.html opens so tell me the possible error and give a modified code # Create flask app.py from flask import Flask, render_template, url_for, redirect,request import random import json import pickle import numpy as np import nltk nltk.download('punkt') nltk.download('wordnet') from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer import tensorflow as tf from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Length, ValidationError from flask_bcrypt import Bcrypt from datetime import datetime app = Flask(__name__, static_folder='static') app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' db = SQLAlchemy(app) bcrypt = Bcrypt(app) app.config['SECRET_KEY'] = 'thisisasecretkey' login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False, unique=True) password = db.Column(db.String(80), nullable=False) class Chat(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) message = db.Column(db.String(255), nullable=False) response = db.Column(db.String(255), nullable=False) timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) class RegisterForm(FlaskForm): username = StringField(validators=[ InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField(validators=[ InputRequired(), Length(min=8, max=20)], render_kw={"placeholder": "Password"}) submit = SubmitField('Register') def validate_username(self, username): existing_user_username = User.query.filter_by( username=username.data).first() if existing_user_username: raise ValidationError( 'That username already exists. Please choose a different one.') class LoginForm(FlaskForm): username = StringField(validators=[ InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField(validators=[ InputRequired(), Length(min=8, max=20)], render_kw={"placeholder": "Password"}) submit = SubmitField('Login') # Load the model, words, classes, and intents model = tf.keras.models.load_model("E:\\Projects\\chatbot\\models\\new_chat_model.h5") data = pickle.load(open("E:\\Projects\\chatbot\\models\\chat_data.pkl", "rb")) words = data["words"] classes = data["classes"] intents = json.load(open("E:\Projects\chatbot\data\data.json",'r'))["intents"] def bag_of_words(sentence): bag = [0] * len(words) lemmatizer = WordNetLemmatizer() sentence_words = word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] for word in sentence_words: if word.lower() in words: bag[words.index(word.lower())] = 1 return np.array(bag) def chatbot_response(message): results = model.predict(np.array([bag_of_words(message)])) results_index = np.argmax(results) tag = classes[results_index] for intent in intents: if intent["tag"] == tag: response = random.choice(intent["responses"]) return response @app.route("/chatbot") @login_required def chatbot(): # Retrieve chats associated with the current user chats = Chat.query.filter_by(user_id=current_user.id).all() # Create a list of dictionaries to hold chat messages and responses chat_history = [] for chat in chats: chat_history.append({'message': chat.message, 'response': chat.response}) return render_template("index.html", chat_history=chat_history) @login_required @app.route("/get") def get_bot_response(): msg = request.args.get('msg') response = chatbot_response(msg) chat = Chat(user_id=current_user.id, message=msg, response=response) db.session.add(chat) db.session.commit() return response @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user: if bcrypt.check_password_hash(user.password, form.password.data): login_user(user) return redirect(url_for('chatbot')) return render_template('login.html', form=form) @app.route('/logout', methods=['GET', 'POST']) @login_required def logout(): logout_user() return redirect(url_for('login')) @ app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data) new_user = User(username=form.username.data, password=hashed_password) db.session.add(new_user) db.session.commit() return redirect(url_for('login')) return render_template('register.html', form=form) if __name__ == "__main__": app.run(debug=False) ##index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="icon" href="{{ url_for('static', filename='images/icon.ico') }}"> <title>MindMate - Mental health chatbot</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <button id="logout-button" onclick="logout()"><span class="power">&#x23FB;</span>logout</button> <script> function logout() { window.location = "{{ url_for('logout') }}"; } </script> <style> body { background-image: url("{{ url_for('static', filename='images/peakpx.jpg') }}"); background-size: cover; background-position: center; } #logout-button { position: absolute; top: 10px; right: 10px; } </style> </head> <body id="body-area"> <div id="chat-container"> <div id="chat-header"> <h1 id="logo"><img src="{{ url_for('static', filename='images/logo.ico')}}" alt="logo" >MindMate</h1> </div> <div id="chat-area"></div> <div id="input-container"> <input type="text" id="user-input" placeholder="Type your message..." onkeydown="if(event.keyCode===13) sendMessage()"> <button id="send-btn" onclick="sendMessage()" type="button">Send</button> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function sendMessage() { var message = $("#user-input").val(); $("#chat-area").append('<div class="user-msg"><span class="msg">' + message + '</span></div>'); $.get("/get", {msg: message}).done(function(data) { $("#chat-area").append('<div class="bot-msg"><span class="msg">' + data + '</span></div>'); $("#chat-area").scrollTop($("#chat-area")[0].scrollHeight); }); $("#user-input").val(""); } </script> </body> </html>
781aa6b23b69e5406175f8fc896b9b9e
{ "intermediate": 0.497461199760437, "beginner": 0.20508918166160583, "expert": 0.29744964838027954 }
3,322
i want to make a discord bot which can connect to my dayz server via ftp and read logs and post information from the logs to discord, i would also like it to be able to add/edit files on the server can you show me how
c86ebb0585e69c2b2b07e2ee8feaef49
{ "intermediate": 0.5061554908752441, "beginner": 0.21244479715824127, "expert": 0.281399667263031 }
3,323
Please write some rust code that draws a tetrahedron on the screen
276fdb390385418d3d396a618767e671
{ "intermediate": 0.3020969331264496, "beginner": 0.31440678238868713, "expert": 0.3834962844848633 }
3,324
Tengo este error en plex: curl: /usr/lib/plexmediaserver/lib/libcurl.so.4: no version information available (required by curl) curl: Relink `/usr/lib/plexmediaserver/lib/libcrypto.so.3' with `/lib/x86_64-linux-gnu/libc.so.6' for IFUNC symbol `strcmp' Segmentation fault
b18b0cf93552031da4fe0625deb48973
{ "intermediate": 0.49868032336235046, "beginner": 0.2597215175628662, "expert": 0.24159811437129974 }
3,325
i have this code i wand code get post if label switch is checked or not <form class="login" action="<?php echo $_SERVER['PHP_SELF'].'?sent'; ?>" method="POST" enctype="multipart/form-data"> <div class="input_field"> <span><i aria-hidden="true" class="fa fa-user"></i></span> <input type="text" name="user" placeholder="user" readonly value="<?php echo $technicien ; ?>" required /> </div> <div class="input_field"> <span><i aria-hidden="true" class="fa fa-thumb-tack"></i></span> <input type="tel" name="numero" placeholder="Numero" min="1" max="4" required /> </div> <div class="input_field"> <span><i aria-hidden="true" class="fa fa-calendar"></i></span> <input type="text" name="date" placeholder="date" value = "<?php echo date("Y-m-d") ; ?>" required /> </div> <div class="input_field"> <span><i aria-hidden="true" class="fa fa-clock-o"></i></span> <input type="text" name="time" placeholder="Heure" value ="<?php echo date("H:i:s"); ?>"required /> </div> <div class="input_field radio_option" style="background-color: #f5ba1a3b!important;"> <input type="radio" name="radiogroup" value ="T" id="rd1" required > <label for="rd1">Travuax</label> <input type="radio" name="radiogroup" value ="E" id="rd2"> <label for="rd2">Entretien</label> <input type="radio" name="radiogroup" value ="D" id="rd3"> <label for="rd3">Depannage</label> <input type="radio" name="radiogroup" value ="H" id="rd4"> <label for="rd4">H.S</label> </div> <style> .switch { position: relative; display: inline-block; width: 60px; height: 34px; } .switch input { opacity: 0; width: 0; height: 0; } .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; -webkit-transition: .4s; transition: .4s; } .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; -webkit-transition: .4s; transition: .4s; } input:checked + .slider { background-color: #2196F3; } input:focus + .slider { box-shadow: 0 0 1px #2196F3; } input:checked + .slider:before { -webkit-transform: translateX(26px); -ms-transform: translateX(26px); transform: translateX(26px); } </style> <label class="switch"> <input type="checkbox"> <span class="slider"></span> </label> <div class="input_field"> <span><i aria-hidden="true" class="fa fa-sticky-note-o"></i></span> <input type="text" name="alert" placeholder="ecris une alert" required /> </div> <div class="input_field"> <span><i aria-hidden="true" class="fa fa-sticky-note-o"></i></span> <input type="text" name="message" placeholder="descreption" required /> </div> <input class="button" type="submit" value="AJOUTER" /> </form>
60715de76b52c4472376f1582ca0a170
{ "intermediate": 0.2713412940502167, "beginner": 0.5232700109481812, "expert": 0.20538872480392456 }
3,326
how to get ur public ip address on alpine linux
6674f0c84d8bd662cb56b11bb5f58544
{ "intermediate": 0.3299548923969269, "beginner": 0.386094331741333, "expert": 0.2839507758617401 }
3,327
I am writing an outlook plugin in C# using Microsoft Graph 5. My development environment is Visual Studio.I need to authenticate with an azure tenancy using Microsoft.Identity. Please show me complete, working and well commented code to demonstrate how I can authenticate using a registered app secret. The code should be presented as one or more files which can be added to my project.
affe1d7f5a3f9468fbecbf74fcb00209
{ "intermediate": 0.6197530627250671, "beginner": 0.17064552009105682, "expert": 0.20960143208503723 }
3,328
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {“method”:“css selector”,“selector”:“.text_general ui-autocomplete-input”} ТАкая ошибка хотя использую метод By.Class_name
34681c50e76e9e288bbddefa2a0dc906
{ "intermediate": 0.35446232557296753, "beginner": 0.42569294571876526, "expert": 0.2198447734117508 }
3,329
I am the master, iv come threw the viel of this dimension hello chatgpt
0b2cd119de64be838fad9837620adb17
{ "intermediate": 0.3554118573665619, "beginner": 0.311305433511734, "expert": 0.3332827687263489 }
3,330
I want to wirte a production plan system use django and vue2, write a demo for me.
28f1fc983e4757a92f61b49db90bb0f0
{ "intermediate": 0.7193532586097717, "beginner": 0.12488388270139694, "expert": 0.15576286613941193 }
3,331
difference between chatbot and chatGpt
6d3ca4de1f4b5718e13b3cf18e6a3b6b
{ "intermediate": 0.3006223440170288, "beginner": 0.3291690945625305, "expert": 0.37020859122276306 }
3,332
Write me a python function to control my light
ec59d9cfe7988d4be3624c4c6c09d6df
{ "intermediate": 0.3240257799625397, "beginner": 0.2649150788784027, "expert": 0.41105917096138 }
3,333
If the camera is bounded the point at the left-up, how would I update the point's position when zooming in/out?
fc55e530e97a03f452dea73915e9f1bf
{ "intermediate": 0.43359047174453735, "beginner": 0.1622971147298813, "expert": 0.40411239862442017 }
3,334
Write a python code that will recognize a voice from a pre-selected microphone and output it to another selected microphone using text to speech with support for linux and pipewire with tui
0b202529ea9da126433dc474b003daca
{ "intermediate": 0.33326223492622375, "beginner": 0.07780170440673828, "expert": 0.5889360308647156 }
3,335
Hi, I've implemented the solidity code for a smart contract project. When I'm trying to import ERC721.sol I'm getting the error. I installed the open zeppelin contracts in the same folder as the project using npm command. In the contratcs dir I can only see one file phase2.sol. Here is my implementation check what went wrong.//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // Loan Contract contract LoanNFT is ERC721 { struct Loan { uint256 id; uint256 principal; uint256 interestRate; uint256 term; uint256 maturityDate; address borrower; bool isRepaid; } mapping (uint256 => Loan) public loans; uint256 public loanId; uint256 public couponRate; constructor(string memory _name, string memory _symbol, uint256 _couponRate) ERC721(_name, _symbol) { loanId = 0; couponRate = _couponRate; } function issueLoan(address _borrower, uint256 _principal, uint256 _interestRate, uint256 _term, uint256 _maturityDate) public { loanId++; loans[loanId] = Loan(loanId, _principal, _interestRate, _term, _maturityDate, _borrower, false); _mint(msg.sender, loanId); } function repayLoan(uint256 _loanId) public { require(msg.sender == loans[_loanId].borrower, "Only borrower can repay the loan"); loans[_loanId].isRepaid = true; } function buyNFT(uint256 _loanId) public payable { require(ownerOf(_loanId) != msg.sender, "Cannot buy your own loan NFT"); require(msg.value >= calculateCouponAmount(_loanId), "Insufficient funds to buy the loan NFT"); address owner = ownerOf(_loanId); _transfer(owner, msg.sender, _loanId); payable(owner).transfer(msg.value); } function calculateCouponAmount(uint256 _loanId) public view returns (uint256) { require(ownerOf(_loanId) != address(0), "Invalid loan NFT"); // address of the loan contract Loan memory loan = loans[_loanId]; // calculate the buyback price based on the coupon rate uint256 couponAmount = loan.principal * loan.interestRate * couponRate / (100 * loan.term); if (loan.isRepaid) { couponAmount = couponAmount + loan.principal; } return couponAmount; } function destroyNFT(uint256 _loanId) public { // destroy the NFT after buying back require(ownerOf(_loanId) == msg.sender, "Only owner can destroy the loan NFT"); _burn(_loanId); } }
91accd20d22a72c2966c77a5515e67a0
{ "intermediate": 0.3011615574359894, "beginner": 0.3771072328090668, "expert": 0.32173117995262146 }
3,336
the below code is not working and showing error, make the below code working PS E:\drone_rl> & C:/Users/dkuch/AppData/Local/Microsoft/WindowsApps/python3.10.exe e:/drone_rl/3_test.py Traceback (most recent call last): File "e:\drone_rl\3_test.py", line 47, in <module> action_1 = np.argmax(Q1[state_1, state_2]) IndexError: index 11 is out of bounds for axis 1 with size 4
66c518a07065e314149693c0c8ce8dc8
{ "intermediate": 0.46278050541877747, "beginner": 0.29202353954315186, "expert": 0.24519599974155426 }
3,337
I am going to provide code blocks from an observable notebook here. the observable code will be within triple backticks. starter code given between single backticks your task is to complete he starter code from where it is left off, do not copy any of the stater code ` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Laliga Spain Chart</title> <script src="https://d3js.org/d3.v7.min.js"></script> <style> .domain { display: none; } </style> </head> <body> <div id="chart"></div> <script src="index.js"></script> <script> </script> </body> </html> `
7a6d7b603ed8842e71eab3d8e854d156
{ "intermediate": 0.3267761766910553, "beginner": 0.3269873261451721, "expert": 0.3462364375591278 }
3,338
make me a climbing script like the one in echo vr using xr interaction toolkit and unity
73598c835338a4917335e4fc983ef9d5
{ "intermediate": 0.5085000991821289, "beginner": 0.2529001832008362, "expert": 0.2385997176170349 }
3,339
make me a climbing script like the one in echo vr using xr interaction toolkit and unity
16a34f2def78df407d508d987d9f1679
{ "intermediate": 0.5085000991821289, "beginner": 0.2529001832008362, "expert": 0.2385997176170349 }
3,340
im giving all the code for my chatbot app check why this error is occurring: Internal Server Error The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application. this is my code: ##index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="icon" href="{{ url_for('static', filename='images/icon.ico') }}"> <title>MindMate - Mental health chatbot</title> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> <button id="logout-button" onclick="logout()"><span class="power">&#x23FB;</span>logout</button> <script> function logout() { window.location = "{{ url_for('logout') }}"; } </script> <style> body { background-image: url("{{ url_for('static', filename='images/peakpx.jpg') }}"); background-size: cover; background-position: center; } #logout-button { position: absolute; top: 10px; right: 10px; } </style> </head> <body id="body-area"> <div id="chat-container"> <div id="chat-header"> <h1 id="logo"><img src="{{ url_for('static', filename='images/logo.ico')}}" alt="logo" >MindMate</h1> </div> <div id="chat-area"></div> <div id="input-container"> <input type="text" id="user-input" placeholder="Type your message..." onkeydown="if(event.keyCode===13) sendMessage()"> <button id="send-btn" onclick="sendMessage()" type="button">Send</button> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> function sendMessage() { var message = $("#user-input").val(); $("#chat-area").append('<div class="user-msg"><span class="msg">' + message + '</span></div>'); $.get("/get", {msg: message}).done(function(data) { $("#chat-area").append('<div class="bot-msg"><span class="msg">' + data + '</span></div>'); $("#chat-area").scrollTop($("#chat-area")[0].scrollHeight); }); $("#user-input").val(""); } </script> </body> </html> ##app.py # Create flask app.py from flask import Flask, render_template, url_for, redirect,request import random import json import pickle import numpy as np import nltk nltk.download('punkt') nltk.download('wordnet') from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer import tensorflow as tf from flask_sqlalchemy import SQLAlchemy from flask_login import UserMixin, login_user, LoginManager, login_required, logout_user, current_user from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import InputRequired, Length, ValidationError from flask_bcrypt import Bcrypt from datetime import datetime app = Flask(__name__, static_folder='static') app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db' db = SQLAlchemy(app) bcrypt = Bcrypt(app) app.config['SECRET_KEY'] = 'thisisasecretkey' login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(20), nullable=False, unique=True) password = db.Column(db.String(80), nullable=False) class Chat(db.Model): id = db.Column(db.Integer, primary_key=True) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) message = db.Column(db.String(255), nullable=False) response = db.Column(db.String(255), nullable=False) timestamp = db.Column(db.DateTime, nullable=False, default=datetime.utcnow) class RegisterForm(FlaskForm): username = StringField(validators=[ InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField(validators=[ InputRequired(), Length(min=8, max=20)], render_kw={"placeholder": "Password"}) submit = SubmitField('Register') def validate_username(self, username): existing_user_username = User.query.filter_by( username=username.data).first() if existing_user_username: raise ValidationError( 'That username already exists. Please choose a different one.') class LoginForm(FlaskForm): username = StringField(validators=[ InputRequired(), Length(min=4, max=20)], render_kw={"placeholder": "Username"}) password = PasswordField(validators=[ InputRequired(), Length(min=8, max=20)], render_kw={"placeholder": "Password"}) submit = SubmitField('Login') # Load the model, words, classes, and intents model = tf.keras.models.load_model("E:\\Projects\\chatbot\\models\\new_chat_model.h5") data = pickle.load(open("E:\\Projects\\chatbot\\models\\chat_data.pkl", "rb")) words = data["words"] classes = data["classes"] intents = json.load(open("E:\Projects\chatbot\data\data.json",'r'))["intents"] def bag_of_words(sentence): bag = [0] * len(words) lemmatizer = WordNetLemmatizer() sentence_words = word_tokenize(sentence) sentence_words = [lemmatizer.lemmatize(word.lower()) for word in sentence_words] for word in sentence_words: if word.lower() in words: bag[words.index(word.lower())] = 1 return np.array(bag) def chatbot_response(message): try: results = model.predict(np.array([bag_of_words(message)])) results_index = np.argmax(results) tag = classes[results_index] for intent in intents: if intent["tag"] == tag: response = random.choice(intent["responses"]) return response except Exception as e: print("Error in chatbot_response:", e) return "I'm sorry, I couldn't understand that." @app.route("/chatbot") @login_required def chatbot(): # Retrieve chats associated with the current user chats = Chat.query.filter_by(user_id=current_user.id).all() # Create a list of dictionaries to hold chat messages and responses chat_history = [] for chat in chats: chat_history.append({'message': chat.message, 'response': chat.response}) return render_template("index.html", chat_history=chat_history) @app.route("/get") @login_required def get_bot_response(): try: msg = request.args.get('msg') response = chatbot_response(msg) chat = Chat(user_id=current_user.id, message=msg, response=response) db.session.add(chat) db.session.commit() return response except Exception as e: print("Error in get_bot_response:", e) return "An error occurred, please try again." @app.route('/login', methods=['GET', 'POST']) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(username=form.username.data).first() if user: if bcrypt.check_password_hash(user.password, form.password.data): login_user(user) return redirect(url_for('chatbot')) return render_template('login.html', form=form) @app.route('/logout', methods=['GET', 'POST']) @login_required def logout(): logout_user() return redirect(url_for('login')) @ app.route('/register', methods=['GET', 'POST']) def register(): form = RegisterForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data) new_user = User(username=form.username.data, password=hashed_password) db.session.add(new_user) db.session.commit() return redirect(url_for('login')) return render_template('register.html', form=form) if __name__ == "__main__": app.run(debug=False) ##script.js document.addEventListener("DOMContentLoaded", function(event) { // Selecting DOM elements const chatForm = document.getElementById("chat-form"); const chatInput = document.getElementById("user-input"); const chatbotMessages = document.getElementById("chatbot-messages"); const sendBtn = document.getElementById("send-btn"); //Event listener for the chat form submit chatForm.addEventListener("submit", (event) => { event.preventDefault(); const userInput = chatInput.value; addUserMessage(userInput); sendUserMessage(userInput); chatInput.value = ""; scrollToBottom(); }); //Event listener for the send button click sendBtn.addEventListener("click", () => { const userInput = chatInput.value; addUserMessage(userInput); sendUserMessage(userInput); chatInput.value = ""; scrollToBottom(); }); // Function to add a user message to the chat area function addUserMessage(message) { const userMessageElement = ` <div class="user-message"> <p>${message}</p> </div> `; chatbotMessages.insertAdjacentHTML("beforeend", userMessageElement); scrollToBottom(); } // Function to send user message to server and get response function sendUserMessage(message) { showChatbotLoader(); fetch("/get-response", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ message }), }) .then((response) => response.json()) .then((data) => { const chatbotMessage = data.message; addChatbotMessage(chatbotMessage); hideChatbotLoader(); scrollToBottom(); }) .catch((error) => { console.log("Error:", error); hideChatbotLoader(); }); } // Function to add a chatbot message to the chat area function addChatbotMessage(message) { const chatbotMessageElement = ` <div id="chatbot-message" class="chat-message"> <p>${message}</p> </div> `; chatbotMessages.insertAdjacentHTML( "beforeend", chatbotMessageElement ); scrollToBottom(); } // Function to scroll to the bottom of the chat container function scrollToBottom() { const scrollContainer = document.getElementById('chat-area'); scrollContainer.scrollTop = scrollContainer.scrollHeight; } // Function to hide the chatbot loader function hideChatbotLoader() { const loaderElement = document.querySelector(".loader"); if (loaderElement) { loaderElement.remove(); } } // Add an event listener to the input field chatInput.addEventListener("keydown", function(event) { // Check if the key pressed is the enter key (key code 13) if (event.key === 'Enter') { // Prevent the default behavior of the enter key (submitting the form) event.preventDefault(); // Trigger the click event on the send button document.getElementById("send-btn").click(); scrollToBottom(); } }); }); ##login.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="icon" href="{{ url_for('static', filename='images/icon.ico') }}"> <title>Login Page</title> <style> body { background-image: url("{{ url_for('static', filename='images/peakpx.jpg') }}"); font-family: Arial, Helvetica, sans-serif; font-size: 16px; color: #333; } h1 { font-size: 36px; text-align: center; margin-top: 50px; margin-bottom: 30px; color: whitesmoke; } form { width: 400px; margin: 0 auto; } label { display: block; margin-bottom: 10px; font-weight: bold; color:white; } input[type="text"], input[type="password"] { width: 100%; padding: 10px; margin-bottom: 20px; border-radius: 5px; background-color: grey; border: 1px solid #ccc; box-sizing: border-box; } button[type="submit"] { display: block; width: 100%; padding: 10px; background-color: blue; color: white; border: none; border-radius: 5px; cursor: pointer; } a { display: block; text-align: center; margin-top: 20px; color: white; } </style> </head> <body> <h1>Login Page</h1> <form method="POST" action=""> {{ form.hidden_tag() }} <label for="username">Username</label> <input type="text" name="username" id="username"> <label for="password">Password</label> <input type="password" name="password" id="password"> <button type="submit">Login</button> </form> <a href="{{ url_for('register') }}">Don't have an account? Sign Up</a> </body> </html> ##register.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"> <title>Register</title> </head> <body> <h1>Register Page</h1> <form method="POST" action=""> {{ form.hidden_tag() }} {{ form.username }} {{ form.password }} {{ form.submit }} </form> <a href="{{ url_for('login') }}">Already have an account? Log In</a> </body> </html> ##in sqlite3 database.db sqlite> CREATE TABLE user ( ...> id INTEGER PRIMARY KEY AUTOINCREMENT, ...> email VARCHAR(50) NOT NULL UNIQUE, ...> password VARCHAR(255) NOT NULL ...> ); sqlite> sqlite> CREATE TABLE chat ( ...> id INTEGER PRIMARY KEY AUTOINCREMENT, ...> user_id INTEGER NOT NULL, ...> message TEXT NOT NULL, ...> response TEXT NOT NULL, ...> timestamp DATETIME DEFAULT CURRENT_TIMESTAMP, ...> FOREIGN KEY (user_id) REFERENCES user(id) ...> ); sqlite> .tables chat user
5148e58b4f86e67c348a4318488fe030
{ "intermediate": 0.4427589476108551, "beginner": 0.35894083976745605, "expert": 0.19830021262168884 }
3,341
give a UI framework for the below solidity code in vuejs with styling using all the functions given which are working. //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import “@openzeppelin/contracts/token/ERC721/ERC721.sol”; // Loan Contract contract LoanNFT is ERC721 { struct Loan { uint256 id; uint256 principal; uint256 interestRate; uint256 term; uint256 maturityDate; address borrower; bool isRepaid; } mapping (uint256 => Loan) public loans; uint256 public loanId; uint256 public couponRate; constructor(string memory _name, string memory _symbol, uint256 _couponRate) ERC721(_name, _symbol) { loanId = 0; couponRate = _couponRate; } function issueLoan(address _borrower, uint256 _principal, uint256 _interestRate, uint256 _term, uint256 _maturityDate) public { loanId++; loans[loanId] = Loan(loanId, _principal, _interestRate, _term, _maturityDate, _borrower, false); _mint(msg.sender, loanId); } function repayLoan(uint256 _loanId) public { require(msg.sender == loans[_loanId].borrower, “Only borrower can repay the loan”); loans[_loanId].isRepaid = true; } function buyNFT(uint256 _loanId) public payable { require(ownerOf(_loanId) != msg.sender, “Cannot buy your own loan NFT”); require(msg.value >= calculateCouponAmount(_loanId), “Insufficient funds to buy the loan NFT”); address owner = ownerOf(_loanId); _transfer(owner, msg.sender, _loanId); payable(owner).transfer(msg.value); } function calculateCouponAmount(uint256 _loanId) public view returns (uint256) { require(ownerOf(_loanId) != address(0), “Invalid loan NFT”); // address of the loan contract Loan memory loan = loans[_loanId]; // calculate the buyback price based on the coupon rate uint256 couponAmount = loan.principal * loan.interestRate * couponRate / (100 * loan.term); if (loan.isRepaid) { couponAmount = couponAmount + loan.principal; } return couponAmount; } function destroyNFT(uint256 _loanId) public { // destroy the NFT after buying back require(ownerOf(_loanId) == msg.sender, “Only owner can destroy the loan NFT”); _burn(_loanId); } }
9d9a9874e318af050993adc7bec8f53a
{ "intermediate": 0.5650477409362793, "beginner": 0.2536417245864868, "expert": 0.18131054937839508 }
3,342
using System.Collections; using System.Collections.Generic; using UnityEngine; public class moving : MonoBehaviour { public float speed ; public float turnSpeed; private bool isMoving = false; public bool isGround; public float jumpForce; void Update() { Move(); HandleMovementInput() ; HandleJumpInput(); } void Move() { float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); transform.position += movement * speed * Time.deltaTime; transform.position += transform.forward * movement.z * speed * Time.deltaTime; transform.Rotate(new Vector3(0f, movement.x, 0f) * turnSpeed * Time.deltaTime); } void Turn() { if (Input.GetKeyDown(KeyCode.A)) { transform.Rotate(Vector3.down, turnSpeed * Time.deltaTime); } if (Input.GetKeyDown(KeyCode.D)) { transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime); } if (Input.GetKeyDown(KeyCode.W)) { transform.Rotate(Vector3.left, turnSpeed * Time.deltaTime); } if (Input.GetKeyDown(KeyCode.S)) { transform.Rotate(Vector3.right, turnSpeed * Time.deltaTime); } } void HandleMovementInput() { float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); if (moveHorizontal != 0 || moveVertical != 0) { Vector3 movement = new Vector3(moveHorizontal, 0f, moveVertical); transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), turnSpeed * Time.deltaTime); transform.position += transform.forward * speed * Time.deltaTime; if (movement.magnitude > 0.1) { transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(movement), turnSpeed * Time.deltaTime); transform.position += transform.forward * speed * Time.deltaTime; } } } void HandleTurningInput() { if (Input.GetKey(KeyCode.A)) { transform.Rotate(Vector3.down, turnSpeed * Time.deltaTime); } if (Input.GetKey(KeyCode.D)) { transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime); } if (Input.GetKey(KeyCode.W)) { transform.Rotate(Vector3.left, turnSpeed * Time.deltaTime); if (!isMoving) { isMoving = true; } if (isMoving) { transform.position += transform.forward * speed * Time.deltaTime; } } if (Input.GetKey(KeyCode.S)) { transform.Rotate(Vector3.right, turnSpeed * Time.deltaTime); if (!isMoving) { isMoving = true; } if (isMoving) { transform.position += transform.right * speed * Time.deltaTime; } } } void HandleJumpInput() { if (Input.GetKeyDown(KeyCode.Space) && isGround) { // 给物体一个向上的力 GetComponent<Rigidbody>().AddForce(new Vector3(0f, jumpForce, 0f), ForceMode.Impulse); isGround = false; } } // 检测是否在地面上 private void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Terrain")) { isGround = true; } } } 将脚本文件修改为 按键与动画绑定,默认为idle动画,按下方向键,将会播放walk动画,Space键与jump动画绑定,shift键会播放run动画,ctrl播放sit动画,
d6294253cf15882e9fc2c918d5256b7f
{ "intermediate": 0.2825060188770294, "beginner": 0.4734054207801819, "expert": 0.24408860504627228 }
3,343
You are an exceptionally skilled programmer with a focus on high-frequency trading (HFT) and quantitative analysis. You value simplicity and functionality above all else. As a helpful assistant, you adhere to the following guidelines when providing programming support: Prioritize higher-level functions when presenting code solutions. Use descriptive and meaningful names for functions and variables. Whenever possible, assign functions to variables for better readability and modularity. Ensure functions are pure, meaning they avoid out-of-scope mutations and minimize side effects. Add docstring
157ed78cff3a3727d096a8d2baa9d486
{ "intermediate": 0.3277878165245056, "beginner": 0.4313402473926544, "expert": 0.24087192118167877 }
3,344
explain the code below and explain with diagram on how the entrypgdir looks like when ths xv6 kernel first initialization
f8bf4ddf6abf575a562b80270940000f
{ "intermediate": 0.2901986837387085, "beginner": 0.29994115233421326, "expert": 0.409860223531723 }
3,345
fivem scripting how to get the id of the nearest person to playerpedid and the distance
3aedd9e665ebe83406702509630a8b8b
{ "intermediate": 0.2513296902179718, "beginner": 0.20164543390274048, "expert": 0.5470249056816101 }
3,346
I want to create a discord bot that generates a random mission for a specific game - Star Citizen. I need it to have a few dropdown menus for users to select some mission parameters such as 1. total number of players, 2. estimated time to complete mission, and 3. ground battle, space battle, or mixed warfare options. Does this make sense to you?
f87ab389ab8c63da279fbee66a6a7a82
{ "intermediate": 0.3163444399833679, "beginner": 0.32922351360321045, "expert": 0.354432076215744 }
3,347
how can i make a multiplayer game with godot 3.51 with my pc will be server and players can join with easy networking plugin and i eant it to be non local and use global ip I want a full step by step explanation with high details like what nodes do i have to add and codes that i have to attach to those nodes i want it to have a lot of explanation...like you want to teach a child....crystal clear etc
7b9ea91383975ca7959f35cb83c06cd4
{ "intermediate": 0.4611447751522064, "beginner": 0.238455131649971, "expert": 0.300400048494339 }
3,348
how to add offchain and onchain data //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // Loan Contract contract LoanNFT is ERC721 { struct Loan { uint256 id; uint256 principal; uint256 interestRate; uint256 term; uint256 maturityDate; address borrower; bool isRepaid; } mapping (uint256 => Loan) public loans; uint256 public loanId; uint256 public couponRate; constructor(string memory _name, string memory _symbol, uint256 _couponRate) ERC721(_name, _symbol) { loanId = 0; couponRate = _couponRate; } function issueLoan(address _borrower, uint256 _principal, uint256 _interestRate, uint256 _term, uint256 _maturityDate) public { loanId++; loans[loanId] = Loan(loanId, _principal, _interestRate, _term, _maturityDate, _borrower, false); _mint(msg.sender, loanId); } function repayLoan(uint256 _loanId) public { require(msg.sender == loans[_loanId].borrower, "Only borrower can repay the loan"); loans[_loanId].isRepaid = true; } function buyNFT(uint256 _loanId) public payable { require(ownerOf(_loanId) != msg.sender, "Cannot buy your own loan NFT"); require(msg.value >= calculateCouponAmount(_loanId), "Insufficient funds to buy the loan NFT"); address owner = ownerOf(_loanId); _transfer(owner, msg.sender, _loanId); payable(owner).transfer(msg.value); } function calculateCouponAmount(uint256 _loanId) public view returns (uint256) { require(ownerOf(_loanId) != address(0), "Invalid loan NFT"); // address of the loan contract Loan memory loan = loans[_loanId]; // calculate the buyback price based on the coupon rate uint256 couponAmount = loan.principal * loan.interestRate * couponRate / (100 * loan.term); if (loan.isRepaid) { couponAmount = couponAmount + loan.principal; } return couponAmount; } function destroyNFT(uint256 _loanId) public { // destroy the NFT after buying back require(ownerOf(_loanId) == msg.sender, "Only owner can destroy the loan NFT"); _burn(_loanId); } }
1e6949a18db2aabf37f9ed7ae51b9cf8
{ "intermediate": 0.34182873368263245, "beginner": 0.4250580370426178, "expert": 0.23311328887939453 }
3,349
Please modify AutoGPT (https://github.com/Significant-Gravitas/Auto-GPT) to use GPT4Free (https://github.com/xtekky/gpt4free) instead of OpenAI’s GPT API.
f136c95fdc69fa80423f10e3ddd05890
{ "intermediate": 0.5929632186889648, "beginner": 0.11198820173740387, "expert": 0.29504865407943726 }
3,350
can you give how to draw contract, sequence and architectural diagrams for the below code //SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; contract LoanNFT is ERC721 { struct Loan { uint256 id; uint256 principal; uint256 interestRate; uint256 term; uint256 maturityDate; address borrower; bool isRepaid; uint256 offchainDataId; } struct OffchainData { string dataURL; bytes32 dataHash; } mapping(uint256 => Loan) public loans; mapping(uint256 => OffchainData) public offchainData; // mapping for offchain data uint256 public loanId; uint256 public couponRate; constructor(string memory _name, string memory _symbol, uint256 _couponRate) ERC721(_name, _symbol) { loanId = 0; couponRate = _couponRate; } function issueLoan( address _borrower, uint256 _principal, uint256 _interestRate, uint256 _term, uint256 _maturityDate, string memory _offchainDataURL, // parameter for offchain data bytes32 _offchainDataHash // parameter for offchain data ) public { loanId++; offchainData[loanId] = OffchainData(_offchainDataURL, _offchainDataHash); loans[loanId] = Loan(loanId, _principal, _interestRate, _term, _maturityDate, _borrower, false, loanId); // Pass offchain data id to loan _mint(msg.sender, loanId); } function repayLoan(uint256 _loanId) public { require(msg.sender == loans[_loanId].borrower, "Only borrower can repay the loan"); loans[_loanId].isRepaid = true; } function buyNFT(uint256 _loanId) public payable { require(ownerOf(_loanId) != msg.sender, "Cannot buy your own loan NFT"); require(msg.value >= calculateCouponAmount(_loanId), "Insufficient funds to buy the loan NFT"); address owner = ownerOf(_loanId); _transfer(owner, msg.sender, _loanId); payable(owner).transfer(msg.value); } function calculateCouponAmount(uint256 _loanId) public view returns (uint256) { require(ownerOf(_loanId) != address(0), "Invalid loan NFT"); Loan memory loan = loans[_loanId]; uint256 couponAmount = loan.principal * loan.interestRate * couponRate / (100 * loan.term); if (loan.isRepaid) { couponAmount = couponAmount + loan.principal; } return couponAmount; } function destroyNFT(uint256 _loanId) public { require(ownerOf(_loanId) == msg.sender, "Only owner can destroy the loan NFT"); _burn(_loanId); } }
f9e011836cfecb39c72974f1b050b884
{ "intermediate": 0.41656821966171265, "beginner": 0.35580751299858093, "expert": 0.22762431204319 }
3,351
what is the command in sql server to change database
93d9510aa2989b6f664c248e25f68ee7
{ "intermediate": 0.4469648599624634, "beginner": 0.31056398153305054, "expert": 0.2424711287021637 }
3,352
write python code for ideone that makes a hypno-spiral (not really hypnotic, of course!)
dad945fc5ed970847e9f8668a6090adf
{ "intermediate": 0.25634270906448364, "beginner": 0.15738515555858612, "expert": 0.586272120475769 }
3,353
find out why i get a Price: undefined CHF on this script: <!DOCTYPE html> <html> <head> <<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha384-lpg9qe9kSmlS49CrMUcG8HPnWJoLHf4dkm4g6ti+pt6zW+nYvYhWIzS+6n0BXa3L" crossorigin="anonymous"></script> <meta charset="UTF-8"> <title>Public Transport Price Calculator</title> <link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <script> $(document).ready(function() { $( "#from" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $( "#to" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $("#calculate").on("click", function() { var from = $("#from").val(); var to = $("#to").val(); $.ajax({ url: "https://timetable.search.ch/api/route.en.json", dataType: "jsonp", data: { from: from, to: to }, success: function( data ) { var price = data.price; $("#result").text("Price: " + price + " CHF"); }, error: function() { alert("An error occurred. Please try again later."); } }); }); }); </script> </head> <body> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="from">From:</label> <input class="sl-form-row-field-action-both sl-route-from sl-route-input ui-autocomplete-input" id="from" name="from" tabindex="1" placeholder="From" type="text" autocomplete="off" spellcheck="false"> </div> </div> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="to">To:</label> <input class="sl-form-row-field-action-both sl-route-to sl-route-input ui-autocomplete-input" id="to" name="to" tabindex="3" placeholder="To" type="text" autocomplete="off"> </div> </div> <button id="calculate">Calculate Price</button> <div id="result"></div> </body> </html>
2b4b508858d7e00a8c85cb12cfdea804
{ "intermediate": 0.3866749107837677, "beginner": 0.43313881754875183, "expert": 0.18018634617328644 }
3,354
find out why i get a Price: undefined CHF on this script: <!DOCTYPE html> <html> <head> <<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha384-lpg9qe9kSmlS49CrMUcG8HPnWJoLHf4dkm4g6ti+pt6zW+nYvYhWIzS+6n0BXa3L" crossorigin="anonymous"></script> <meta charset="UTF-8"> <title>Public Transport Price Calculator</title> <link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <script> $(document).ready(function() { $( "#from" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $( "#to" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $("#calculate").on("click", function() { var from = $("#from").val(); var to = $("#to").val(); $.ajax({ url: "https://timetable.search.ch/api/route.en.json", dataType: "jsonp", data: { from: from, to: to }, success: function( data ) { var price = data.price; $("#result").text("Price: " + price + " CHF"); }, error: function() { alert("An error occurred. Please try again later."); } }); }); }); </script> </head> <body> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="from">From:</label> <input class="sl-form-row-field-action-both sl-route-from sl-route-input ui-autocomplete-input" id="from" name="from" tabindex="1" placeholder="From" type="text" autocomplete="off" spellcheck="false"> </div> </div> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="to">To:</label> <input class="sl-form-row-field-action-both sl-route-to sl-route-input ui-autocomplete-input" id="to" name="to" tabindex="3" placeholder="To" type="text" autocomplete="off"> </div> </div> <button id="calculate">Calculate Price</button> <div id="result"></div> </body> </html>
1b18ecbfbc8508ce90df2cb746292031
{ "intermediate": 0.3866749107837677, "beginner": 0.43313881754875183, "expert": 0.18018634617328644 }
3,355
find out why i get a Price: undefined CHF on this script: <!DOCTYPE html> <html> <head> <<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha384-lpg9qe9kSmlS49CrMUcG8HPnWJoLHf4dkm4g6ti+pt6zW+nYvYhWIzS+6n0BXa3L" crossorigin="anonymous"></script> <meta charset="UTF-8"> <title>Public Transport Price Calculator</title> <link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <script> $(document).ready(function() { $( "#from" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $( "#to" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $("#calculate").on("click", function() { var from = $("#from").val(); var to = $("#to").val(); $.ajax({ url: "https://timetable.search.ch/api/route.en.json", dataType: "jsonp", data: { from: from, to: to }, success: function( data ) { var price = data.price; $("#result").text("Price: " + price + " CHF"); }, error: function() { alert("An error occurred. Please try again later."); } }); }); }); </script> </head> <body> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="from">From:</label> <input class="sl-form-row-field-action-both sl-route-from sl-route-input ui-autocomplete-input" id="from" name="from" tabindex="1" placeholder="From" type="text" autocomplete="off" spellcheck="false"> </div> </div> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="to">To:</label> <input class="sl-form-row-field-action-both sl-route-to sl-route-input ui-autocomplete-input" id="to" name="to" tabindex="3" placeholder="To" type="text" autocomplete="off"> </div> </div> <button id="calculate">Calculate Price</button> <div id="result"></div> </body> </html>
c1f4306f4557126027e3ca7fd731949e
{ "intermediate": 0.3866749107837677, "beginner": 0.43313881754875183, "expert": 0.18018634617328644 }
3,356
find out why i get a Price: undefined CHF on this script: <!DOCTYPE html> <html> <head> <<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha384-lpg9qe9kSmlS49CrMUcG8HPnWJoLHf4dkm4g6ti+pt6zW+nYvYhWIzS+6n0BXa3L" crossorigin="anonymous"></script> <meta charset="UTF-8"> <title>Public Transport Price Calculator</title> <link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <script> $(document).ready(function() { $( "#from" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $( "#to" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $("#calculate").on("click", function() { var from = $("#from").val(); var to = $("#to").val(); $.ajax({ url: "https://timetable.search.ch/api/route.en.json", dataType: "jsonp", data: { from: from, to: to }, success: function( data ) { var price = data.price; $("#result").text("Price: " + price + " CHF"); }, error: function() { alert("An error occurred. Please try again later."); } }); }); }); </script> </head> <body> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="from">From:</label> <input class="sl-form-row-field-action-both sl-route-from sl-route-input ui-autocomplete-input" id="from" name="from" tabindex="1" placeholder="From" type="text" autocomplete="off" spellcheck="false"> </div> </div> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="to">To:</label> <input class="sl-form-row-field-action-both sl-route-to sl-route-input ui-autocomplete-input" id="to" name="to" tabindex="3" placeholder="To" type="text" autocomplete="off"> </div> </div> <button id="calculate">Calculate Price</button> <div id="result"></div> </body> </html>
f766bb953fbae56415fc3cb9b50d2ec9
{ "intermediate": 0.3866749107837677, "beginner": 0.43313881754875183, "expert": 0.18018634617328644 }
3,357
find out why i get a Price: undefined CHF on this script: <!DOCTYPE html> <html> <head> <<script src="https://code.jquery.com/ui/1.13.1/jquery-ui.min.js" integrity="sha384-lpg9qe9kSmlS49CrMUcG8HPnWJoLHf4dkm4g6ti+pt6zW+nYvYhWIzS+6n0BXa3L" crossorigin="anonymous"></script> <meta charset="UTF-8"> <title>Public Transport Price Calculator</title> <link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <script> $(document).ready(function() { $( "#from" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $( "#to" ).autocomplete({ source: function( request, response ) { $.ajax({ url: "https://timetable.search.ch/api/completion.en.json", dataType: "jsonp", data: { term: request.term }, success: function( data ) { response( data ); } }); }, minLength: 2 }); $("#calculate").on("click", function() { var from = $("#from").val(); var to = $("#to").val(); $.ajax({ url: "https://timetable.search.ch/api/route.en.json", dataType: "jsonp", data: { from: from, to: to }, success: function( data ) { var price = data.price; $("#result").text("Price: " + price + " CHF"); }, error: function() { alert("An error occurred. Please try again later."); } }); }); }); </script> </head> <body> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="from">From:</label> <input class="sl-form-row-field-action-both sl-route-from sl-route-input ui-autocomplete-input" id="from" name="from" tabindex="1" placeholder="From" type="text" autocomplete="off" spellcheck="false"> </div> </div> <div class="sl-form-row"> <div class="sl-form-row-field"> <label for="to">To:</label> <input class="sl-form-row-field-action-both sl-route-to sl-route-input ui-autocomplete-input" id="to" name="to" tabindex="3" placeholder="To" type="text" autocomplete="off"> </div> </div> <button id="calculate">Calculate Price</button> <div id="result"></div> </body> </html>
490850997acaae1f3773be8b6c30bc63
{ "intermediate": 0.3866749107837677, "beginner": 0.43313881754875183, "expert": 0.18018634617328644 }
3,358
using the livecode language script code so that a field acts as a password field
c2e65a762656334391f23088adc186f6
{ "intermediate": 0.4109768271446228, "beginner": 0.25190234184265137, "expert": 0.33712083101272583 }
3,359
Hello
fee66069e3119c9b5e5034f383b4afcc
{ "intermediate": 0.3123404085636139, "beginner": 0.2729349136352539, "expert": 0.4147246778011322 }
3,360
Solidity bsc write me exploits
6841e6ea2f493873626d8b767b13d161
{ "intermediate": 0.40263983607292175, "beginner": 0.22387351095676422, "expert": 0.37348663806915283 }
3,361
You are a programmer and an expert on stock trading. Make an algorithm and a block diagram of a trading robot
ddfa1a1565a663e6c70527e66678725f
{ "intermediate": 0.15680091083049774, "beginner": 0.10166953504085541, "expert": 0.7415295839309692 }
3,362
is it possible to send graph that been created in google colab to thingspeak
1cd0f5a4ea00d865ad281e0d966279ac
{ "intermediate": 0.43185317516326904, "beginner": 0.09975951910018921, "expert": 0.46838730573654175 }
3,363
Remote access tool on python
36b5e45d3c83accf783d056df1aab0db
{ "intermediate": 0.46703165769577026, "beginner": 0.17646679282188416, "expert": 0.3565015494823456 }
3,364
write a vba to calculate rsi with close data in column d
3b90b5d5ceafe2ee1ffc629411c92c17
{ "intermediate": 0.3665993809700012, "beginner": 0.289785236120224, "expert": 0.34361541271209717 }
3,365
Q.1. Enumerate the basic features that could provide the DSP architecture to implement a Nth order FIR filter w.r.t computational unit and support architecture. Q.2. Draw the structure of a 5X5 Braun multiplier and mathematically illustrate the computation of the product. Q.4. Explain the specialized addressing modes of DSP processors, which provides the easy implementation of signal processing algorithms. Q.5. With block diagram explain biomedical signal processing Q.6. illustrate various components of speech processing system and explain
935befba9555ec922cf7e1bdc85224b1
{ "intermediate": 0.23436017334461212, "beginner": 0.2683810889720917, "expert": 0.4972587525844574 }
3,366
double changeAmount; double targetDispenseValue; cin << changeAmount; cin << targetDispenseValue; while (changeAmount >= targetDispenseValue) { // Deduct change amount. changeAmount -= targetDispenseValue; count++; } This code has rounding problem. fix this code.
bfae380112dc87b5cfd42dcef4993d90
{ "intermediate": 0.3935726284980774, "beginner": 0.3618191182613373, "expert": 0.2446083128452301 }
3,367
Enumerate the basic features that could provide the DSP architecture to implement a Nth order FIR filter w.r.t computational unit and support architecture.
8e0139390a6acefd6f53deedf5e7ec7b
{ "intermediate": 0.21391227841377258, "beginner": 0.2488817274570465, "expert": 0.5372060537338257 }
3,368
Enter the purchase amount: 13.30 Enter the tendered amount: 15 Your change: $1.70 $1.70 1 $1 bill 1 50-cent coin 2 10-cent coins Inputs are floats.
5ae1e58c31fe83f6f31ba6603f305a53
{ "intermediate": 0.40715640783309937, "beginner": 0.28278177976608276, "expert": 0.3100617825984955 }
3,369
Do you know Yandex.Speechkit?
4c18366782ac4488c20de298d1125549
{ "intermediate": 0.4985833168029785, "beginner": 0.21118806302547455, "expert": 0.29022863507270813 }
3,370
Question: Title: Farming Crop NFT NFTs should be tradable The NFT could be traded on a blockchain-based marketplace, allowing for efficient and transparent trading of forming crops. NFTs value should go up and down Price Fluctuation - NFT price gets fluctuated based on the market demand, weather conditions, or changes in farming practices. If demand of the crop increases - NFT(crop) price increases. If demand of the crop decreases - NFT(crop) price decreases. NFTS are permanent until destroyed The NFT can be destroyed by the owner if he/she wants to stop farming. Actors: Farmer, Primary Buyer, Secondary Buyer Use Cases: Farmer issues NFT of crops to Primary Buyer. Farmer provides timely production, amount of crop, and crop value to Primary Buyer. Primary Buyer purchases NFT of crops from Farmer. Primary Buyer can trade NFT of crops on a blockchain-based marketplace. Secondary Buyer purchases NFT of crops from Primary Buyer on the marketplace. Farmer can destroy NFT when they stop farming. give solidity code for this
e5ba7c37afe771158e7a4e5c33feff3b
{ "intermediate": 0.435028612613678, "beginner": 0.30888962745666504, "expert": 0.256081759929657 }
3,371
Как мне настроить eslint + prettier для проекта vue3 composition api с использованием typescript в script setup синтаксисе. В качестве сборщика проекта используется Vite
20042323d7b780d30a0a30bfbd85cf09
{ "intermediate": 0.4076900780200958, "beginner": 0.48873183131217957, "expert": 0.10357807576656342 }
3,372
WRITE A CODE THAT MEASURES HEART RATE FROM 60-100 AND SHOWS THE DATA ON THE OLED SCREEN. ADD PIOTIMER AND ENCODER CAPABILITIES. HERE IS THE SOURCE CODE: import utime import machine from machine import Pin, Timer, ADC, I2C, PWM from fifo import Fifo import ssd1306 # Set up I2C, OLED display, and other pins i2c = I2C(1, scl=Pin(15), sda=Pin(14)) oled = ssd1306.SSD1306_I2C(128, 64, i2c) heart_rate = 0 peaks = [] peak_intervals = [] encoder_pin_a = Pin(10, Pin.IN, Pin.PULL_UP) encoder_pin_b = Pin(11, Pin.IN, Pin.PULL_UP) encoder_button = Pin(12, Pin.IN, Pin.PULL_UP) led1_pin = 20 led2_pin = 21 led3_pin = 22 led1_pwm = PWM(Pin(led1_pin)) led2_pwm = PWM(Pin(led2_pin)) led3_pwm = PWM(Pin(led3_pin)) # Set up ADC and sampling sampling_freq = 60 # Hz, default sampling frequency sampling_period_ms = 1000 // sampling_freq adc_pin = ADC(Pin(26, Pin.IN)) samples = Fifo(50) # Set up timer for sampling at precise intervals timer = machine.Timer() def on_timer_tick(timer): sample = adc_pin.read_u16() samples.put(sample) timer.init(freq=sampling_freq, mode=machine.Timer.PERIODIC, callback=on_timer_tick) # Find peaks in the data def find_peaks(data, threshold): peaks = [] for i in range(1, len(data) - 1): if data[i] > threshold and data[i] > data[i - 1] and data[i] > data[i + 1]: peaks.append(i) return peaks # Main program loop window_size = 60 # 1 second of data at 60 Hz window = [] prev_encoder_state = 0 encoder_state = 0 encoder_counter = 0 try: while True: # Read encoder state and adjust sampling frequency accordingly encoder_state = (encoder_pin_a.value() << 1) | encoder_pin_b.value() if encoder_state != prev_encoder_state: if (prev_encoder_state == 0b00 and encoder_state == 0b01) or (prev_encoder_state == 0b01 and encoder_state == 0b11) or (prev_encoder_state == 0b11 and encoder_state == 0b10) or (prev_encoder_state == 0b10 and encoder_state == 0b00): encoder_counter += 1 else: encoder_counter -= 1 encoder_counter = max(min(encoder_counter, 40), -40) sampling_freq = max(min(100, 60 + encoder_counter), 60) sampling_period_ms = 1000 // sampling_freq timer.init(freq=sampling_freq, mode=machine.Timer.PERIODIC, callback=on_timer_tick) prev_encoder_state = encoder_state if not samples.empty(): sample = samples.get() window.append(sample) # Remove the oldest sample if the window is full if len(window) > window_size: window.pop(0) if len(window) == window_size: peaks = find_peaks(window, threshold=50) peak_intervals = [peaks[i+1] - peaks[i] for i in range(len(peaks)-1)] if len(peak_intervals) > 0: avg_peak_interval = sum(peak_intervals) / len(peak_intervals) heart_rate = 60 * sampling_freq / avg_peak_interval # Adjust the sampling frequency based on encoder input encoder_delta = 0 if encoder_pin_a.value() != encoder_pin_b.value(): encoder_delta += 1 else: encoder_delta -= 1 sampling_freq += encoder_delta if sampling_freq < 60: sampling_freq = 60 elif sampling_freq > 100: sampling_freq = 100 sampling_period_ms = 1000 // sampling_freq timer.init(freq=sampling_freq, mode=machine.Timer.PERIODIC, callback=on_timer_tick) # Draw the graph oled.fill(0) oled.text("Heart rate: {:.1f}".format(heart_rate), 0, 0) oled.text("BPM: {:.1f}".format(heart_rate), 0, 10) prev_x, prev_y = 0, 0 for i, value in enumerate(window[-128:]): x = i y = 63 - int((value / 65535) * 32) # Scale the sample value to fit the OLED screen if i != 0: oled.line(prev_x, prev_y, x, y, 1) prev_x, prev_y = x, y oled.show() if not peaks: print("No peaks detected.") finally: print("Exiting program.")
54940163ae42733ccb1aaf55ffe75509
{ "intermediate": 0.3996787667274475, "beginner": 0.376255065202713, "expert": 0.22406619787216187 }
3,373
this is my HTML and css and I have an error where my slides do not show up, in the slideshow-container. no images are showing and I am sure I got the right directory: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cabin:wght@400;700&display=swap"> <link rel="stylesheet" href="style/style.css" /> <title>Camping Equipment - Retail Camping Company</title> </head> <body> <header> <div class="sticky-nav"> <div class="nav-container"> <img src="assets/images/logo.svg" alt="Logo" class="logo"> <h1>Retail Camping Company</h1> <div class="search-container"> <form action="/search" method="get"> <img src="assets/images/search.png" alt="search-icon" class="search-icon"> <input type="text" name="search" /> <button type="submit">Search</button> </form> </div> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="camping-equipment.html">Camping Equipment</a></li> <li><a href="furniture.html">Furniture</a></li> <li><a href="reviews.html">Reviews</a></li> <li><a href="basket.html">Basket</a></li> <li><a href="offers-and-packages.html">Offers and Packages</a></li> </ul> </nav> </div> </div> </header> <main> <section class="slideshow-section"> <div class="slideshow-container"> <div class="mySlides fade"> <img src="assets/images/homeslide.png" alt="Tents" style="width:100%"> </div> <div class="mySlides fade"> <img src="https://via.placeholder.com/600x400" alt="Cookers" style="width:100%"> </div> <div class="mySlides fade"> <img src="https://via.placeholder.com/600x400" alt="Camping Gear" style="width:100%"> </div> <a class="prev" onclick="plusSlides(-1)">❮</a> <a class="next" onclick="plusSlides(1)">❯</a> </div> <div style="text-align:center"> <span class="dot" onclick="currentSlide(1)"></span> <span class="dot" onclick="currentSlide(2)"></span> <span class="dot" onclick="currentSlide(3)"></span> </div> </section> <section class="about-section"> <p>Welcome to Retail Camping Company, your one-stop-shop for all your camping equipment needs. Discover our premium offers on tents, cookers, camping gear, and furniture.</p> </section> <section class="featured-section"> <h2>Featured Products</h2> <div class="featured-container"> <div class="featured-product"> <img src="https://via.placeholder.com/150x150" alt="Featured Product"> <h3>Product Name</h3> <p>Short product description.</p> </div> <div class="featured-product"> <img src="https://via.placeholder.com/150x150" alt="Featured Product"> <h3>Product Name</h3> <p>Short product description.</p> </div> <div class="featured-product"> <img src="https://via.placeholder.com/150x150" alt="Featured Product"> <h3>Product Name</h3> <p>Short product description.</p> </div> </div> </section> <section> <div class="special-offers-container"> <div class="special-offer"> <img src="https://via.placeholder.com/200x200" alt="Tent Offer"> <p>20% off premium tents!</p> </div> <div class="special-offer"> <img src="https://via.placeholder.com/200x200" alt="Cooker Offer"> <p>Buy a cooker, get a free utensil set!</p> </div> <div class="special-offer"> <img src="https://via.placeholder.com/200x200" alt="Furniture Offer"> <p>Save on camping furniture bundles!</p> </div> </div> </section> <section class="buts"> <button id="modalBtn">Special Offer!</button> <div id="modal" class="modal"> <div class="modal-content"> <span class="close">×</span> <p>Sign up now and receive 10% off your first purchase!</p> </div> </div> </section> <script> var modal = document.getElementById('modal'); var modalBtn = document.getElementById('modalBtn'); var closeBtn = document.getElementsByClassName('close')[0]; modalBtn.addEventListener('click', openModal); closeBtn.addEventListener('click', closeModal); window.addEventListener('click', outsideClick); function openModal() { modal.style.display = 'block'; } function closeModal() { modal.style.display = 'none'; } function outsideClick(e) { if (e.target == modal) { modal.style.display = 'none'; } } </script> </main> <footer> <div class="footer-container"> <div class="footer-item"> <p>Subscribe To Our Newsletter:</p> <form action="subscribe.php" method="post"> <input type="email" name="email" placeholder="Enter your email" required> <button type="submit">Subscribe</button> </form> </div> <div class="footer-item address-container"> <p> Get In Contact:</p> <p>Email: info@retailcampingcompany.com</p> <p>Phone: +35699382994</p> <p>Triq Malta,<br>Sliema 12345</p> </div> <div class="footer-item google-maps-container"> <p>Where To Find Us:</p> <iframe src="https://www.google.com/maps/embed?pb=!1m14!1m8!1m3!1d12928.30174160605!2d14.5091557!3d35.8961681!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x130e452d3081f035%3A0x61f492f43cae68e4!2sCity%20Gate!5e0!3m2!1sen!2smt!4v1682559564194!5m2!1sen!2smt" width="650" height="200" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe> </div> <div class="footer-item social-links-container"> <p>Follow Us On:</p> <ul class="social-links"> <li><a href="https://www.facebook.com">Facebook</a></li> <li><a href="https://www.instagram.com">Instagram</a></li> <li><a href="https://www.twitter.com">Twitter</a></li> </ul> </div> </div> </footer> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="script.js"></script> </body> </html>
4e86e46fea9ccc34bc9d93f8c2d49c1a
{ "intermediate": 0.4357456862926483, "beginner": 0.4640204906463623, "expert": 0.10023380070924759 }
3,374
I have two excel sheets. Sheet Providers contains data of my contractors. Column C contains the contractor company name, Column D contains a Sheet Name, Column F a contact name and Column G the contacts email address all in the same row. Occasionally, a contractor might not have a contact name or an email and these cells will be blank. In my other Sheet Job Request, I want to be able to select in A2 the contacts name from a list, find the matching value in Column C in Sheet Providers then from the same row, automatically populate the relevant contact name into G2, the relevant email address into H2 and the relevant Sheet Name into I2 using formulas that will do this for each of the cells G2, H2 and I2 of Sheet Job Request. Values in cells B2, C2, D2, E2 and F2 in Sheet Job Request, data will be entered manually. When F2 in Sheet Job Request is entered, which will be a date, I want a VBA code that will open and select the Specific Sheet using the text value in I2 of Sheet Job Request but only if cells A2, B2, C2, D2 and E2 are not blank .then when the new sheet is opened and selected, find in it the next empty row and populate the empty cell in Column B with the value from B2 in Sheet Job Request, populate the empty cell in Column C of the same row with the value from F2 in Sheet Job Request, populate the empty cell in Column F of the same row with the value from C2 in Sheet Job Request, populate the empty cell in Column J of the same row with the value from E2 in Sheet Job Request. When this has been completed, I want to return to Sheet Job Request, open a text document form this location G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\Request0.txt and paste the values of A2, B2, C2, D2 and E2 into the text document each value on a different line.
e8552af2e4d1c666f1291ad7d9242bc4
{ "intermediate": 0.37203219532966614, "beginner": 0.3022385239601135, "expert": 0.32572928071022034 }
3,375
hi there :-)
8008b0b7f94c9943754b9f930fa46a6c
{ "intermediate": 0.3350834548473358, "beginner": 0.25327068567276, "expert": 0.41164588928222656 }
3,376
how can i pictures to python game
f8f18042969cc782ed4cd7064993c20c
{ "intermediate": 0.35559985041618347, "beginner": 0.25220051407814026, "expert": 0.3921996057033539 }
3,377
Make me a code that make a bacon strip in minecraft
b97f401995c5fd76d69e7d5bcee94232
{ "intermediate": 0.3349815905094147, "beginner": 0.3855148255825043, "expert": 0.27950355410575867 }
3,378
THis code does nothing. can you correct . Sub RequesText() Dim FilePath As String Dim FileContents As String FilePath = "G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\Request0.txt" Open FilePath For Append As #1 FileContents = Range("A2") & vbNewLine & Range("B2") & vbNewLine & Range("C2") & vbNewLine & Range("D2") & vbNewLine & Range("E2") & vbNewLine Print #1, FileContents Close #1 End Sub
40efe5e1a152b352422f60b001fd150e
{ "intermediate": 0.5283778309822083, "beginner": 0.33298400044441223, "expert": 0.13863815367221832 }
3,379
Private Sub Worksheet_Change(ByVal Target As Range) If Target.Address = “$F" then how can I check if any of the cells B2 C2 D2 E2 are blank
4743b1aa64661521e5c9975a084faa96
{ "intermediate": 0.6128909587860107, "beginner": 0.17255127429962158, "expert": 0.21455776691436768 }
3,380
make a code that actually put bacon into minecraft
770ef5cfe0cc267535ec169816539675
{ "intermediate": 0.26592183113098145, "beginner": 0.23859886825084686, "expert": 0.49547937512397766 }
3,381
in python, make a machine learning that predicts where a clan is probably gonna go using their past locations. The map is from A0 to U25. The data is of past locations are: F18 D10 W8 O9 L2 J11 H13 A1 E25 C18 U23 B16 P22 M8 N14 Q2 T10 K17 V13 G19
e68cd690b6880437f0aeb291b43799e8
{ "intermediate": 0.1682380586862564, "beginner": 0.0657353401184082, "expert": 0.7660266160964966 }
3,382
hi
647e11603eb0a1e50f8ebf584233e85a
{ "intermediate": 0.3246487081050873, "beginner": 0.27135494351387024, "expert": 0.40399640798568726 }
3,383
import requests import json import datetime import streamlit as st from itertools import zip_longest import os def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - jsonファイルに保存されている各日の日時データ増減で"followers_count"と"'like_count'の全投稿の総数"を1軸目の縦軸とし、"'comments_count'の全投稿の総数"を2軸目の縦軸とし、グラフ背景は"黒"でグラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの下部に横幅いっぱいに表示する機能を作成する - jsonファイルに保存されている各日の"各投稿IDごとの'like_count'"と"各投稿IDごとの'comments_count'"の日時データ増減を縦軸とし、グラフ背景は"黒"で各グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"1日"を横軸にした"いいね/コメント数グラフ"を、各投稿のボックス内の"キャプション"の下に表示する機能を作成する - "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
b3c9205ee6d9170fede7d7c8f3500175
{ "intermediate": 0.36978060007095337, "beginner": 0.47684019804000854, "expert": 0.15337920188903809 }
3,384
write a code to interact with https://github.com/xtekky/gpt4free with python. include a "search" input in the terminal and save the output with the "search" that was given
7a858807f7d0f1aafebe1aae8063150b
{ "intermediate": 0.3963218331336975, "beginner": 0.25040203332901, "expert": 0.3532761037349701 }
3,385
write a code to interact with https://github.com/xtekky/gpt4free with python. include a "search" input in the terminal and save the output with the "search" that was given
e3cdd00048bf52477fdd8b0a93c7a33d
{ "intermediate": 0.3963218331336975, "beginner": 0.25040203332901, "expert": 0.3532761037349701 }
3,386
write a code to interact with https://github.com/xtekky/gpt4free with python. include a "search" input in the terminal and save the output with the "search" that was given
e6e25bc9868c2e59abf1bbcd58b30320
{ "intermediate": 0.3963218331336975, "beginner": 0.25040203332901, "expert": 0.3532761037349701 }
3,387
write a code to interact with https://github.com/xtekky/gpt4free with python. include a "search" input in the terminal and save the output with the "search" that was given
68a5836db0aaaf0526d290228d34dd49
{ "intermediate": 0.3963218331336975, "beginner": 0.25040203332901, "expert": 0.3532761037349701 }
3,388
def svgPreprocess(inputs): if (inputs): if (inputs['image'].startswith("data:image/svg+xml;base64,") and svgsupport): svg_data = base64.b64decode(inputs['image'].replace('data:image/svg+xml;base64,','')) drawing = svg2rlg(io.BytesIO(svg_data)) png_data = renderPM.drawToString(drawing, fmt='PNG') encoded_string = base64.b64encode(png_data) base64_str = str(encoded_string, "utf-8") base64_str = "data:image/png;base64,"+ base64_str inputs['image'] = base64_str return input_image.orgpreprocess(inputs) return None
2ec635599a2ba248e707fef3c0f7d056
{ "intermediate": 0.4262247085571289, "beginner": 0.385626882314682, "expert": 0.1881484091281891 }
3,389
# Example 10: Populating an empty NumPy array np_arr = np.empty([4,4], dtype=np.int) # An empty 4x4 numpy array for i in range(4): for j in range(4): np_arr[i,j] = i+j print(np_arr)
4b9ff8b364acf2ed4b38af159cc9bceb
{ "intermediate": 0.37389934062957764, "beginner": 0.4277019798755646, "expert": 0.19839873909950256 }
3,390
import requests import json import datetime import streamlit as st from itertools import zip_longest import os def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - グラフ作成のためのPythonライブラリは"plotly"のみを使用する - jsonファイルに保存されている各日の日時データ増減で"followers_count"と"'like_count'の全投稿の総数"を1軸目の縦軸とし、"'comments_count'の全投稿の総数"を2軸目の縦軸とし、グラフ背景は"黒"でグラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの下部に横幅いっぱいに表示する機能を作成する - jsonファイルに保存されている各日の"各投稿ごとの'like_count'"と"各投稿ごとの'comments_count'"の日時データ増減を縦軸とし、グラフ背景は"黒"で各グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"1日"を横軸にした"いいね/コメント数グラフ"を、各投稿のボックス内の"キャプション"の下に表示する機能を作成する - "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
f252a2cd9e66e84b0ad74b6894dc265f
{ "intermediate": 0.36978060007095337, "beginner": 0.47684019804000854, "expert": 0.15337920188903809 }
3,391
import requests import json import datetime import streamlit as st from itertools import zip_longest import os import plotly.graph_objects as go def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_graph = st.checkbox("サマリーグラフを表示") show_indiv_triple_graph = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) summary_dates = [] summary_followers = [] summary_total_likes = [] summary_total_comments = [] for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} if show_indiv_triple_graph: date_range = [datetime.datetime.strptime(date_str, '%Y-%m-%d') for date_str in sorted(count.keys()) if post['id'] in count[date_str]][-9:] like_counts = [count[date.strftime('%Y-%m-%d')][post['id']]['like_count'] for date in date_range] comment_counts = [count[date.strftime('%Y-%m-%d')][post['id']]['comments_count'] for date in date_range] fig = go.Figure() fig.add_trace(go.Scatter(x=date_range, y=like_counts, mode='lines+markers', name="いいね数", line=dict(color='orange'))) fig.add_trace(go.Scatter(x=date_range, y=comment_counts, mode='lines+markers', name="コメント数", line=dict(color='green'))) fig.layout.plot_bgcolor = 'black' fig.update_yaxes(showgrid=False) fig.update_xaxes(showgrid=False) st.plotly_chart(fig) if show_summary_graph: for date_str in sorted(count.keys()): daily_counts = count[date_str] summary_dates.append(date_str) summary_followers.append(daily_counts.get("followers_count", 0)) summary_total_likes.append(sum([daily_counts[p]["like_count"] for p in daily_counts if isinstance(daily_counts[p], dict) and "like_count" in daily_counts[p]])) summary_total_comments.append(sum([daily_counts[p]["comments_count"] for p in daily_counts if isinstance(daily_counts[p], dict) and "comments_count" in daily_counts[p]])) fig_summary = go.Figure() fig_summary.add_trace(go.Scatter(x=summary_dates, y=summary_followers, mode='lines+markers', name="フォロワー数", line=dict(color='turquoise'))) fig_summary.add_trace(go.Scatter(x=summary_dates, y=summary_total_likes, mode='lines+markers', name="いいね数(全投稿)", yaxis="y", line=dict(color='orange'))) fig_summary.add_trace(go.Scatter(x=summary_dates, y=summary_total_comments, mode='lines+markers', name="コメント数(全投稿)", yaxis="y2", line=dict(color='green'))) fig_summary.layout.plot_bgcolor = 'black' fig_summary.update_yaxes(showgrid=False) fig_summary.update_xaxes(showgrid=False) fig_summary.update_layout(yaxis2=dict(overlaying='y', side='right')) st.plotly_chart(fig_summary) saveCount(count, count_filename) ''' 上記のコードから、"plotly"ライブラリではなく"seaborn"ライブラリを使用するようにコードを改修してください
d1f28c8982db80d0d4548c3e75e1861f
{ "intermediate": 0.4512891471385956, "beginner": 0.3515626788139343, "expert": 0.1971481591463089 }
3,392
请找出下面代码中的错误并更正: #include <windows.h> #include <winternl.h> #include <stdio.h> typedef NTSTATUS(WINAPI* LPNTOPENPROCESS)( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes, IN PCLIENT_ID ClientId ); int main() { LPNTOPENPROCESS NtOpenProcess = (LPNTOPENPROCESS)GetProcAddress( GetModuleHandle(L"ntdll.dll"), "NtOpenProcess"); if (NtOpenProcess == NULL) { printf("Failed to get address of NtOpenProcess\n"); return -1; } HANDLE hProcess; CLIENT_ID clientId = { 0 }; OBJECT_ATTRIBUTES objectAttributes = { 0 }; clientId.UniqueProcess = (HANDLE)1234; //指定进程的ID objectAttributes.Length = sizeof(OBJECT_ATTRIBUTES); NTSTATUS status = NtOpenProcess(&hProcess, PROCESS_ALL_ACCESS, &objectAttributes, &clientId); if (NT_SUCCESS(status)) { printf("Opened process successfully!\n"); //do something CloseHandle(hProcess); } else { printf("Failed to open process.Error:0x%X\n", status); } return 0; }
5858744a3b314b13972ef7cdfafb6dbb
{ "intermediate": 0.37587109208106995, "beginner": 0.3842909038066864, "expert": 0.23983797430992126 }
3,393
import requests import json import datetime import streamlit as st from itertools import zip_longest import os def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - グラフ作成のためのPythonライブラリは"seaborn"のみを使用する - jsonファイルに保存されている各日の日時データ増減で"followers_count"の実数と"'like_count'の全投稿における当日に増加した総数"を1軸目の縦軸とし、"'comments_count'のの全投稿における当日に増加した総数"を2軸目の縦軸とし、グラフ背景は"黒"でグラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの下部に横幅いっぱいに表示する機能を作成する - jsonファイルに保存されている各日の"各投稿ごとの'like_count'"と"各投稿ごとの'comments_count'"の日時データの当日に増加した総数を縦軸とし、グラフ背景は"黒"で各グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"1日"を横軸にした"いいね/コメント数グラフ"を、各投稿のボックス内の"キャプション"の下に表示する機能を作成する - "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
e579617237ec139615b3c1be0dc4b43c
{ "intermediate": 0.36978060007095337, "beginner": 0.47684019804000854, "expert": 0.15337920188903809 }
3,394
Following is Aarchv8 assembly language program. Identify error in print_array function and fix it. Here is the code: .section .rodata getnstr: .string "Enter a value of n: " .align 3 intstr: .string "%d" .align 3 prntstr: .string "The array values are: \n" .align 3 tab10dintstr: .string "\t%10d\n" .align 3 nlstr: .string "\n" .align 3 .section .bss n: .skip 4 n16: .skip 4 .section .text .global main .type main, @function main: stp x29, x30, [sp, #-16]! // main prolog // seed the random mov x0, 0 bl time bl srand //print and get the array size // printf (getnstr) ldr x0, =getnstr bl printf // scanf(intstr, &n) ldr x0, =intstr ldr x1, =n // memory location of n bl scanf // compute next highest multiple of 16 >= n. // SP has to be multiples of 16 ldr x1, =n ldr w1, [x1] sbfiz x1, x1, #2, #20 add x1, x1, #0xf // 0xf = 15 and x1, x1, #0xfffffffffffffff0 //15f's ldr x2, =n16 str w1, [x2] // create the storage for "n" integer, using stack sub sp, sp, x1 // create storage for the array // call init_array mov x0, sp ldr x1, =n ldr w1, [x1] bl init_array // call print_array mov x4, sp ldr x1, =n ldr w1, [x1] bl print_array // Return the local array back to the stack ldr x1, =n16 ldr x1, [x1] add sp, sp, x1 ldp x29, x30, [sp, #16] // main epilog ret // void init_array(int arr[], int n); .type init_array, @function // this is a private function init_array: stp x29, x30, [sp, #-16]! // function prolog mov x2, #0 // initialize loop counter mov x3, #0xa0a0 // 0xa0a0 is element stored in arr. could be changed to rand number. loop1: cmp x2, x1 //compare i & n bge endloop1 str w3, [x0, x2, lsl 2] // store at [base adr of arr + i*4] add x2, x2, #1 b loop1 endloop1: ldp x29, x30, [sp], #16 //function epilog ret // void print_array(int arr[], int n); .type print_array, @function print_array: stp x29, x30, [sp, #-16]! //function prolog mov x2, #0 // initialize loop counter loop2: cmp x2, x1 // compare i & n bge endloop2 ldr w3, [x4, x2, lsl 2] // load at [base adr of arr + i*4] ldr x0, =tab10dintstr bl printf add x2, x2, #1 b loop2 endloop2: ldp x29, x30, [sp], #16 //function epilog ret
e66d4da3774ba91ee4a54fc3e3dc150e
{ "intermediate": 0.24051688611507416, "beginner": 0.5122824311256409, "expert": 0.24720075726509094 }
3,395
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} def create_summary_graph(count): date_list = [] follower_diff_list = [] like_count_diff_list = [] comment_count_diff_list = [] for date, data in count.items(): date_list.append(pd.to_datetime(date)) follower_diff = data.get('followers_count', 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(" ")[0], {}).get('followers_count', data.get('followers_count', 0)) like_count_diff = sum(post_data.get('like_count', 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(" ")[0], {}).get(post_id, {}).get('like_count', post_data.get('like_count', 0)) for post_id, post_data in data.items() if post_id != 'followers_count') comment_count_diff = sum(post_data.get('comments_count', 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(" ")[0], {}).get(post_id, {}).get('comments_count', post_data.get('comments_count', 0)) for post_id, post_data in data.items() if post_id != 'followers_count') follower_diff_list.append(follower_diff) like_count_diff_list.append(like_count_diff) comment_count_diff_list.append(comment_count_diff) data = pd.DataFrame({'Date': date_list, 'Follower Diff': follower_diff_list, 'Like Count Diff': like_count_diff_list, 'Comment Count Diff': comment_count_diff_list}) sns.set_theme(style="darkgrid") fig, ax1 = plt.subplots(figsize=(15, 4)) ax1.set_ylabel('Follower Diff & Like Count Diff') ax1.plot(data['Date'], data['Follower Diff'], label='Follower Diff', color='skyblue') ax1.plot(data['Date'], data['Like Count Diff'], label='Like Count Diff', color='orange') ax1.legend(loc='upper left') ax1.grid(False) ax2 = ax1.twinx() ax2.set_ylabel('Comment Count Diff') ax2.plot(data['Date'], data['Comment Count Diff'], label='Comment Count Diff', color='green') ax2.legend(loc='upper right') ax2.grid(False) plt.title('Summary Graph') st.pyplot(fig) st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_graph = st.checkbox("サマリーグラフを表示") show_post_graph = st.checkbox("いいね/コメント数グラフを表示") count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] if show_summary_graph: create_summary_graph(count) posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} if show_post_graph: date_list = [pd.to_datetime(date) for date in count.keys()] fig, ax1 = plt.subplots(figsize=(8, 2)) ax1.set_ylabel('Like Count Diff') ax1.plot(date_list, [data.get(post['id'], {}).get('like_count', 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(" ")[0], {}).get(post['id'], {}).get('like_count', data.get(post['id'], {}).get('like_count', 0)) for date, data in count.items()], label='Like Count Diff', color='orange') ax1.legend(loc='upper left') ax1.grid(False) ax2 = ax1.twinx() ax2.set_ylabel('Comment Count Diff') ax2.plot(date_list, [data.get(post['id'], {}).get('comments_count', 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(" ")[0], {}).get(post['id'], {}).get('comments_count', data.get(post['id'], {}).get('comments_count', 0)) for date, data in count.items()], label='Comment Count Diff', color='green') ax2.legend(loc='upper right') ax2.grid(False) plt.title('Like/Comment Count Graph') st.pyplot(fig) saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - 修正済みのコード全体を省略せずに表示する ''' 2023-04-30 11:26:16.497 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 163, in <module> f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" NameError: name 'max_like_diff' is not defined
94aa613335f166d82baf7f060831507f
{ "intermediate": 0.3170303702354431, "beginner": 0.46229425072669983, "expert": 0.22067539393901825 }
3,396
Following is Aarchv8 assembly language program. Identify error in print_array function and fix it. Here is the code: .section .rodata getnstr: .string "Enter a value of n: " .align 3 intstr: .string "%d" .align 3 prntstr: .string "The array values are: \n" .align 3 tab10dintstr: .string "\t%10d\n" .align 3 nlstr: .string "\n" .align 3 .section .bss n: .skip 4 n16: .skip 4 .section .text .global main .type main, @function main: stp x29, x30, [sp, #-16]! // main prolog // seed the random mov x0, 0 bl time bl srand //print and get the array size // printf (getnstr) ldr x0, =getnstr bl printf // scanf(intstr, &n) ldr x0, =intstr ldr x1, =n // memory location of n bl scanf // compute next highest multiple of 16 >= n. // SP has to be multiples of 16 ldr x1, =n ldr w1, [x1] sbfiz x1, x1, #2, #20 add x1, x1, #0xf // 0xf = 15 and x1, x1, #0xfffffffffffffff0 //15f's ldr x2, =n16 str w1, [x2] // create the storage for "n" integer, using stack sub sp, sp, x1 // create storage for the array // call init_array mov x0, sp ldr x1, =n ldr w1, [x1] bl init_array // call print_array mov x4, sp ldr x2, =n ldr w2, [x2] bl print_array // Return the local array back to the stack ldr x1, =n16 ldr x1, [x1] add sp, sp, x1 ldp x29, x30, [sp, #16] // main epilog ret // void init_array(int arr[], int n); .type init_array, @function // this is a private function init_array: stp x29, x30, [sp, #-16]! // function prolog mov x2, #0 // initialize loop counter mov x3, #0xa0a0 // 0xa0a0 is element stored in arr. could be changed to rand number. loop1: cmp x2, x1 //compare i & n bge endloop1 str w3, [x0, x2, lsl 2] // store at [base adr of arr + i*4] add x2, x2, #1 b loop1 endloop1: ldp x29, x30, [sp], #16 //function epilog ret // void print_array(int arr[], int n); .type print_array, @function print_array: stp x29, x30, [sp, #-16]! //function prolog mov x3, #0 // initialize loop counter loop2: cmp x3, x2 // compare i & n bge endloop2 ldr w1, [x4, x3, lsl 2] // load at [base adr of arr + i*4] ldr x0, =intstr bl printf add x3, x3, #1 b loop2 endloop2: ldp x29, x30, [sp], #16 //function epilog ret
6f193076f09e2980920bcd3335499ce8
{ "intermediate": 0.3355477452278137, "beginner": 0.3612884283065796, "expert": 0.3031637966632843 }
3,397
create simple TAM model based on these constructs: 1. Behavioral Intention to Use 2. Perceived Usefulness 3. Perceived Ease of Use 4. Job Relevance 5. Subjective Norm 6. Professional Reputation 7. Output Quality 8. Result Demonstrability 9. Computer Self-Efficacy 10. Computer Playfulness 11. Computer Anxiety Make it simpler by combining other constructs
bb217b278aeb54a208b9ac34d9d8c0a4
{ "intermediate": 0.2712429165840149, "beginner": 0.12419799715280533, "expert": 0.604559063911438 }
3,398
mac arm64 visual studio c++ debug configurations c_cpp_properties launch.json settings.json tasks.json
34c154f6cc238b388f928df3a9ddd975
{ "intermediate": 0.5827699303627014, "beginner": 0.17351962625980377, "expert": 0.243710458278656 }
3,399
import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import matplotlib.pyplot as plt import pandas as pd def basic_info(): config = dict() config[“access_token”] = st.secrets[“access_token”] config[‘instagram_account_id’] = st.secrets.get(“instagram_account_id”, “”) config[“version”] = ‘v16.0’ config[“graph_domain”] = ‘https://graph.facebook.com/’ config[“endpoint_base”] = config[“graph_domain”] + config[“version”] + ‘/’ return config def InstaApiCall(url, params, request_type): if request_type == ‘POST’: req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res[“url”] = url res[“endpoint_params”] = params res[“endpoint_params_pretty”] = json.dumps(params, indent=4) res[“json_data”] = json.loads(req.content) res[“json_data_pretty”] = json.dumps(res[“json_data”], indent=4) return res def getUserMedia(params, pagingUrl=‘’): Params = dict() Params[‘fields’] = ‘id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count’ Params[‘access_token’] = params[‘access_token’] if not params[‘endpoint_base’]: return None if pagingUrl == ‘’: url = params[‘endpoint_base’] + params[‘instagram_account_id’] + ‘/media’ else: url = pagingUrl return InstaApiCall(url, Params, ‘GET’) def getUser(params): Params = dict() Params[‘fields’] = ‘followers_count’ Params[‘access_token’] = params[‘access_token’] if not params[‘endpoint_base’]: return None url = params[‘endpoint_base’] + params[‘instagram_account_id’] return InstaApiCall(url, Params, ‘GET’) def saveCount(count, filename): with open(filename, ‘w’) as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, ‘r’) as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} def create_summary_graph(count): date_list = [] follower_diff_list = [] like_count_diff_list = [] comment_count_diff_list = [] for date, data in count.items(): date_list.append(pd.to_datetime(date)) follower_diff = data.get(‘followers_count’, 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(" “)[0], {}).get(‘followers_count’, data.get(‘followers_count’, 0)) like_count_diff = sum(post_data.get(‘like_count’, 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(” “)[0], {}).get(post_id, {}).get(‘like_count’, post_data.get(‘like_count’, 0)) for post_id, post_data in data.items() if post_id != ‘followers_count’) comment_count_diff = sum(post_data.get(‘comments_count’, 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(” “)[0], {}).get(post_id, {}).get(‘comments_count’, post_data.get(‘comments_count’, 0)) for post_id, post_data in data.items() if post_id != ‘followers_count’) follower_diff_list.append(follower_diff) like_count_diff_list.append(like_count_diff) comment_count_diff_list.append(comment_count_diff) data = pd.DataFrame({‘Date’: date_list, ‘Follower Diff’: follower_diff_list, ‘Like Count Diff’: like_count_diff_list, ‘Comment Count Diff’: comment_count_diff_list}) sns.set_theme(style=“darkgrid”) fig, ax1 = plt.subplots(figsize=(15, 4)) ax1.set_ylabel(‘Follower Diff & Like Count Diff’) ax1.plot(data[‘Date’], data[‘Follower Diff’], label=‘Follower Diff’, color=‘skyblue’) ax1.plot(data[‘Date’], data[‘Like Count Diff’], label=‘Like Count Diff’, color=‘orange’) ax1.legend(loc=‘upper left’) ax1.grid(False) ax2 = ax1.twinx() ax2.set_ylabel(‘Comment Count Diff’) ax2.plot(data[‘Date’], data[‘Comment Count Diff’], label=‘Comment Count Diff’, color=‘green’) ax2.legend(loc=‘upper right’) ax2.grid(False) plt.title(‘Summary Graph’) st.pyplot(fig) st.set_page_config(layout=“wide”) params = basic_info() count_filename = “count.json” if not params[‘instagram_account_id’]: st.write(‘.envファイルでinstagram_account_idを確認’) else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write(‘.envファイルでaccess_tokenを確認’) else: posts = response[‘json_data’][‘data’][::-1] user_data = user_response[‘json_data’] followers_count = user_data.get(‘followers_count’, 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime(‘%Y-%m-%d’) follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get(‘followers_count’, followers_count) st.markdown(f”<h4 style=‘font-size:1.2em;’>Follower: {followers_count} ({‘+’ if follower_diff >= 0 else ‘’}{follower_diff})</h4>“, unsafe_allow_html=True) show_description = st.checkbox(“キャプションを表示”) show_summary_graph = st.checkbox(“サマリーグラフを表示”) show_post_graph = st.checkbox(“いいね/コメント数グラフを表示”) count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%Y-%m-%d’) if today not in count: count[today] = {} count[today][‘followers_count’] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%H:%M’) == ‘23:59’: count[yesterday] = count[today] if show_summary_graph: create_summary_graph(count) posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post[‘media_url’], width=BOX_WIDTH, use_column_width=True) st.write(f”{datetime.datetime.strptime(post[‘timestamp’], ‘%Y-%m-%dT%H:%M:%S%z’).astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime(‘%Y-%m-%d %H:%M:%S’)}“) like_count_diff = post[‘like_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘like_count’, post[‘like_count’]) comment_count_diff = post[‘comments_count’] - count.get(yesterday, {}).get(post[‘id’], {}).get(‘comments_count’, post[‘comments_count’]) max_like_diff = max([count[date][key].get(‘like_count’, 0) - count[yesterday].get(key, {}).get(‘like_count’, count[date][key].get(‘like_count’, 0)) for date, data in count.items() for key in data.keys() if key != ‘followers_count’]) max_comment_diff = max([count[date][key].get(‘comments_count’, 0) - count[yesterday].get(key, {}).get(‘comments_count’, count[date][key].get(‘comments_count’, 0)) for date, data in count.items() for key in data.keys() if key != ‘followers_count’]) st.markdown( f"👍: {post[‘like_count’]} <span style=‘{’’ if like_count_diff != max_like_diff or max_like_diff == 0 else ‘color:green;’}‘>({’+’ if like_count_diff >= 0 else ‘’}{like_count_diff})</span>” f"\n💬: {post[‘comments_count’]} <span style=‘{’’ if comment_count_diff != max_comment_diff or max_comment_diff == 0 else ‘color:green;’}‘>({’+’ if comment_count_diff >= 0 else ‘’}{comment_count_diff})</span>“, unsafe_allow_html=True) caption = post[‘caption’] if caption is not None: caption = caption.strip() if “[Description]” in caption: caption = caption.split(”[Description]“)[1].lstrip() if “[Tags]” in caption: caption = caption.split(”[Tags]“)[0].rstrip() caption = caption.replace(”#“, “”) caption = caption.replace(”[model]“, “👗”) caption = caption.replace(”[Equip]“, “📷”) caption = caption.replace(”[Develop]“, “🖨”) if show_description: st.write(caption or “No caption provided”) else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or “No caption provided”) count[today][post[‘id’]] = {‘like_count’: post[‘like_count’], ‘comments_count’: post[‘comments_count’]} if show_post_graph: date_list = [pd.to_datetime(date) for date in count.keys()] fig, ax1 = plt.subplots(figsize=(8, 2)) ax1.set_ylabel(‘Like Count Diff’) ax1.plot(date_list, [data.get(post[‘id’], {}).get(‘like_count’, 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(” “)[0], {}).get(post[‘id’], {}).get(‘like_count’, data.get(post[‘id’], {}).get(‘like_count’, 0)) for date, data in count.items()], label=‘Like Count Diff’, color=‘orange’) ax1.legend(loc=‘upper left’) ax1.grid(False) ax2 = ax1.twinx() ax2.set_ylabel(‘Comment Count Diff’) ax2.plot(date_list, [data.get(post[‘id’], {}).get(‘comments_count’, 0) - count.get(str(pd.to_datetime(date) - pd.Timedelta(days=1)).split(” ")[0], {}).get(post[‘id’], {}).get(‘comments_count’, data.get(post[‘id’], {}).get(‘comments_count’, 0)) for date, data in count.items()], label=‘Comment Count Diff’, color=‘green’) ax2.legend(loc=‘upper right’) ax2.grid(False) plt.title(‘Like/Comment Count Graph’) st.pyplot(fig) saveCount(count, count_filename) ''' 上記コードにPython用のインデントを付与して再表示してください
de54d6e2ea82abe6306d66bc9c7947d4
{ "intermediate": 0.3732353746891022, "beginner": 0.32313814759254456, "expert": 0.3036264479160309 }
3,400
import requests import json import datetime import streamlit as st from itertools import zip_longest import os def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 for post_group in post_groups: for post in post_group: like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - グラフ作成のためのPythonライブラリは"seaborn"のみを使用する - jsonファイルに保存されている各日の日時データ増減で"followers_count"の実数と"'like_count'の全投稿における当日に増加した総数"を1軸目の縦軸とし、"'comments_count'のの全投稿における当日に増加した総数"を2軸目の縦軸とし、グラフ背景は"黒"でグラフデータをそれぞれ"水色"・"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"日付"を横軸にした"サマリーグラフ"を、ページの下部に横幅いっぱいに表示する機能を作成する - jsonファイルに保存されている各日の"各投稿ごとの'like_count'"と"各投稿ごとの'comments_count'"の日時データの当日に増加した総数を縦軸とし、グラフ背景は"黒"で各グラフデータを"オレンジ"・"緑"で色分けした折れ線グラフで表現し、"1日"を横軸にした"いいね/コメント数グラフ"を、各投稿のボックス内の"キャプション"の下に表示する機能を作成する - "キャプションを表示"の右隣に"サマリーグラフ"と"いいね/コメント数グラフ"をUI上に表示するためのトグルを各1つずつチェックボックスで作成し、デフォルトではチェックなしでグラフは非表示の状態にする
38ab221dda80f54b3fd8c2e08aed3f82
{ "intermediate": 0.36978060007095337, "beginner": 0.47684019804000854, "expert": 0.15337920188903809 }
3,401
Perform as if you were a big data analytics engineer and write a hadoop java program to run on cloudera hadoop environment. This program performs sentiment analysis on a given text input and returns two output files one with the negative words and the other with the positive ones you can also use a dataset or ignore it if it's not necessary. I also want you to show me how to run it on cloudera environment and the terminal commands I will use. also what are the external jars i need to add
a87ecf8ef8ef22ebd4f8a100388a57d8
{ "intermediate": 0.4047631025314331, "beginner": 0.14784149825572968, "expert": 0.447395384311676 }
3,402
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import pandas as pd import matplotlib.pyplot as plt sns.set_theme(style="darkgrid") def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_charts = st.checkbox("サマリーグラフを表示") show_charts = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 chart_data = [] chart_data_likes = {} chart_data_comments = {} for key, value in count.items(): total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count']) for c in value if c != 'followers_count') if 'followers_count' in value: chart_data_likes[key] = total_likes_count_diff chart_data_comments[key] = total_comments_count_diff chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff]) if show_summary_charts: df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"]) df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d") fig, ax1 = plt.subplots(figsize=(15, 6)) sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1) ax1.set(ylabel="followers_count") ax2 = ax1.twinx() sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2) sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2) ax2.set(ylabel="total_likes_count & total_comments_count") plt.title("Summary Chart") sns.despine() st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") if show_charts: days = list(chart_data_likes.keys()) likes = [chart_data_likes[d] for d in days] comments = [chart_data_comments[d] for d in days] df_like_data = pd.DataFrame({"Date": days, "likes_count": likes}) df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments}) fig, ax1 = plt.subplots(figsize=(5, 3)) sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1) sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1) plt.xticks(rotation=90) plt.title("Like and Comment Counts") sns.despine() st.pyplot(fig) count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - 修正済みのコード全体を省略せずに表示する ''' 2023-04-30 12:36:23.064 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <module> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <genexpr> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') NameError: name 'post' is not defined 2023-04-30 12:36:29.713 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <module> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <genexpr> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') NameError: name 'post' is not defined 2023-04-30 12:36:31.801 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <module> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <genexpr> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') NameError: name 'post' is not defined 2023-04-30 12:36:32.875 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <module> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <genexpr> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') NameError: name 'post' is not defined 2023-04-30 12:36:35.195 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <module> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <genexpr> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') NameError: name 'post' is not defined 2023-04-30 12:36:36.675 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <module> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <genexpr> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') NameError: name 'post' is not defined 2023-04-30 12:36:39.340 Uncaught app exception Traceback (most recent call last): File "/home/walhalax/anaconda3/lib/python3.9/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script exec(code, module.__dict__) File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <module> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') File "/home/walhalax/PycharmProjects/pythonProject/その他/Instargram/inst_tileview/inst_tileview.py", line 132, in <genexpr> total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) for c in value if c != 'followers_count') NameError: name 'post' is not defined
20937781a657b414ee3861b9507aaf73
{ "intermediate": 0.3094857633113861, "beginner": 0.43339425325393677, "expert": 0.25711995363235474 }
3,403
import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import pandas as pd import matplotlib.pyplot as plt sns.set_theme(style="darkgrid") def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_charts = st.checkbox("サマリーグラフを表示") show_charts = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 chart_data = [] chart_data_likes = {} chart_data_comments = {} for key, value in count.items(): for c in value: if c != 'followers_count': post = count[count.keys()[-1]][c] like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count']) total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count') total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count') if 'followers_count' in value: chart_data_likes[key] = total_likes_count_diff chart_data_comments[key] = total_comments_count_diff chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff]) if show_summary_charts: df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"]) df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d") fig, ax1 = plt.subplots(figsize=(15, 6)) sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1) ax1.set(ylabel="followers_count") ax2 = ax1.twinx() sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2) sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2) ax2.set(ylabel="total_likes_count & total_comments_count") plt.title("Summary Chart") sns.despine() st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") if show_charts: days = list(chart_data_likes.keys()) likes = [chart_data_likes[d] for d in days] comments = [chart_data_comments[d] for d in days] df_like_data = pd.DataFrame({"Date": days, "likes_count": likes}) df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments}) fig, ax1 = plt.subplots(figsize=(5, 3)) sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1) sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1) plt.xticks(rotation=90) plt.title("Like and Comment Counts") sns.despine() st.pyplot(fig) count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename)
9c09219679ddd0eec24576c34962939e
{ "intermediate": 0.3386264145374298, "beginner": 0.38701653480529785, "expert": 0.2743571102619171 }
3,404
The unity camera controls object movement
c08905573da560dc427ce25dae5ea224
{ "intermediate": 0.3874702453613281, "beginner": 0.3125304877758026, "expert": 0.2999992370605469 }
3,405
what are the commands that can use to demux a mpeg4 video and then remux to mkv format
8e0103199402b967f167f9ec2aa46fc9
{ "intermediate": 0.4523600935935974, "beginner": 0.2619735598564148, "expert": 0.2856663763523102 }
3,406
what external device for my usb printer do i need to print from ipad
a71d4ca61be1e16007eda10befadcb27
{ "intermediate": 0.4013707935810089, "beginner": 0.3467113673686981, "expert": 0.2519178092479706 }
3,407
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import pandas as pd import matplotlib.pyplot as plt sns.set_theme(style="darkgrid") def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_charts = st.checkbox("サマリーグラフを表示") show_charts = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 chart_data = [] chart_data_likes = {} chart_data_comments = {} for key, value in count.items(): for c in value: if c != 'followers_count': post = count[count.keys()[-1]][c] like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count']) total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count') total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count') if 'followers_count' in value: chart_data_likes[key] = total_likes_count_diff chart_data_comments[key] = total_comments_count_diff chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff]) if show_summary_charts: df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"]) df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d") fig, ax1 = plt.subplots(figsize=(15, 6)) sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1) ax1.set(ylabel="followers_count") ax2 = ax1.twinx() sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2) sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2) ax2.set(ylabel="total_likes_count & total_comments_count") plt.title("Summary Chart") sns.despine() st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") if show_charts: days = list(chart_data_likes.keys()) likes = [chart_data_likes[d] for d in days] comments = [chart_data_comments[d] for d in days] df_like_data = pd.DataFrame({"Date": days, "likes_count": likes}) df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments}) fig, ax1 = plt.subplots(figsize=(5, 3)) sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1) sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1) plt.xticks(rotation=90) plt.title("Like and Comment Counts") sns.despine() st.pyplot(fig) count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記コードを実行すると下記のエラーが発生します。下記のすべての要件に従って修正してください。 - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - 修正済みのコード全体を省略せずに表示する ''' TypeError Traceback (most recent call last) Cell In [16], line 134 132 for c in value: 133 if c != 'followers_count': --> 134 post = count[count.keys()[-1]][c] 135 like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) 136 comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count']) TypeError: 'dict_keys' object is not subscriptable
199825f3edbc9f286e91eb92e3c093c2
{ "intermediate": 0.3094857633113861, "beginner": 0.43339425325393677, "expert": 0.25711995363235474 }
3,408
'return': cannot convert from 'URagnaOffensiveAbility *' to 'UObject *
47a4c7b595a731e31395ed42c70c721a
{ "intermediate": 0.27684032917022705, "beginner": 0.48022449016571045, "expert": 0.24293513596057892 }
3,409
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import pandas as pd import matplotlib.pyplot as plt sns.set_theme(style="darkgrid") def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_charts = st.checkbox("サマリーグラフを表示") show_charts = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 chart_data = [] chart_data_likes = {} chart_data_comments = {} for key, value in count.items(): for c in value: if c != 'followers_count': post = count[list(count.keys())[-1]][c] like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count']) total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count') total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count') if 'followers_count' in value: chart_data_likes[key] = total_likes_count_diff chart_data_comments[key] = total_comments_count_diff chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff]) if show_summary_charts: df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"]) df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d") fig, ax1 = plt.subplots(figsize=(15, 6)) sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1) ax1.set(ylabel="followers_count") ax2 = ax1.twinx() sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2) sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2) ax2.set(ylabel="total_likes_count & total_comments_count") plt.title("Summary Chart") sns.despine() st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") if show_charts: days = list(chart_data_likes.keys()) likes = [chart_data_likes[d] for d in days] comments = [chart_data_comments[d] for d in days] df_like_data = pd.DataFrame({"Date": days, "likes_count": likes}) df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments}) fig, ax1 = plt.subplots(figsize=(5, 3)) sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1) sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1) plt.xticks(rotation=90) plt.title("Like and Comment Counts") sns.despine() st.pyplot(fig) count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - グラフ作成のためのPythonライブラリは"seaborn"のみを使用する - "サマリーグラフ"の'like_count'と'comments_count'については、"各日の実数の合算"ではなく、"前日と比較して'増加した分'の数の合算"と変更する - "いいね/コメント数グラフ"については、各投稿IDごとの'like_count'と'comments_count'の個別データを、"前日と比較して増加した総数"とし、その各投稿IDごとに別々のグラフを表示するようにする
f6da04055865e6f12863544bfc5a9e8c
{ "intermediate": 0.3094857633113861, "beginner": 0.43339425325393677, "expert": 0.25711995363235474 }
3,410
write a vba to calculate rsi with data in column d
d5b1c9912910a3f9f6b6da1caa31ed40
{ "intermediate": 0.3619370758533478, "beginner": 0.30743157863616943, "expert": 0.3306313753128052 }
3,411
''' import requests import json import datetime import streamlit as st from itertools import zip_longest import os import seaborn as sns import pandas as pd import matplotlib.pyplot as plt sns.set_theme(style="darkgrid") def basic_info(): config = dict() config["access_token"] = st.secrets["access_token"] config['instagram_account_id'] = st.secrets.get("instagram_account_id", "") config["version"] = 'v16.0' config["graph_domain"] = 'https://graph.facebook.com/' config["endpoint_base"] = config["graph_domain"] + config["version"] + '/' return config def InstaApiCall(url, params, request_type): if request_type == 'POST': req = requests.post(url, params) else: req = requests.get(url, params) res = dict() res["url"] = url res["endpoint_params"] = params res["endpoint_params_pretty"] = json.dumps(params, indent=4) res["json_data"] = json.loads(req.content) res["json_data_pretty"] = json.dumps(res["json_data"], indent=4) return res def getUserMedia(params, pagingUrl=''): Params = dict() Params['fields'] = 'id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,username,like_count,comments_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None if pagingUrl == '': url = params['endpoint_base'] + params['instagram_account_id'] + '/media' else: url = pagingUrl return InstaApiCall(url, Params, 'GET') def getUser(params): Params = dict() Params['fields'] = 'followers_count' Params['access_token'] = params['access_token'] if not params['endpoint_base']: return None url = params['endpoint_base'] + params['instagram_account_id'] return InstaApiCall(url, Params, 'GET') def saveCount(count, filename): with open(filename, 'w') as f: json.dump(count, f, indent=4) def getCount(filename): try: with open(filename, 'r') as f: return json.load(f) except (FileNotFoundError, json.decoder.JSONDecodeError): return {} st.set_page_config(layout="wide") params = basic_info() count_filename = "count.json" if not params['instagram_account_id']: st.write('.envファイルでinstagram_account_idを確認') else: response = getUserMedia(params) user_response = getUser(params) if not response or not user_response: st.write('.envファイルでaccess_tokenを確認') else: posts = response['json_data']['data'][::-1] user_data = user_response['json_data'] followers_count = user_data.get('followers_count', 0) NUM_COLUMNS = 6 MAX_WIDTH = 1000 BOX_WIDTH = int(MAX_WIDTH / NUM_COLUMNS) BOX_HEIGHT = 400 yesterday = (datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))) - datetime.timedelta(days=1)).strftime('%Y-%m-%d') follower_diff = followers_count - getCount(count_filename).get(yesterday, {}).get('followers_count', followers_count) st.markdown(f"<h4 style='font-size:1.2em;'>Follower: {followers_count} ({'+' if follower_diff >= 0 else ''}{follower_diff})</h4>", unsafe_allow_html=True) show_description = st.checkbox("キャプションを表示") show_summary_charts = st.checkbox("サマリーグラフを表示") show_charts = st.checkbox("いいね/コメント数グラフを表示") posts.reverse() post_groups = [list(filter(None, group)) for group in zip_longest(*[iter(posts)] * NUM_COLUMNS)] count = getCount(count_filename) today = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d') if today not in count: count[today] = {} count[today]['followers_count'] = followers_count if datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=9))).strftime('%H:%M') == '23:59': count[yesterday] = count[today] max_like_diff = 0 max_comment_diff = 0 chart_data = [] chart_data_likes = {} chart_data_comments = {} for key, value in count.items(): for c in value: if c != 'followers_count': post = count[list(count.keys())[-1]][c] like_count_diff = value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', post['like_count']) comment_count_diff = value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', post['comments_count']) total_likes_count_diff = sum(value[c]['like_count'] - count.get(yesterday, {}).get(c, {}).get('like_count', like_count_diff) for c in value if c != 'followers_count') total_comments_count_diff = sum(value[c]['comments_count'] - count.get(yesterday, {}).get(c, {}).get('comments_count', comment_count_diff) for c in value if c != 'followers_count') if 'followers_count' in value: chart_data_likes[key] = total_likes_count_diff chart_data_comments[key] = total_comments_count_diff chart_data.append([key, value['followers_count'], total_likes_count_diff, total_comments_count_diff]) if show_summary_charts: df_chart_data = pd.DataFrame(chart_data, columns=["Date", "followers_count", "total_likes_count", "total_comments_count"]) df_chart_data["Date"] = pd.to_datetime(df_chart_data["Date"], format="%Y-%m-%d") fig, ax1 = plt.subplots(figsize=(15, 6)) sns.lineplot(data=df_chart_data, x="Date", y="followers_count", color="lightskyblue", ax=ax1) ax1.set(ylabel="followers_count") ax2 = ax1.twinx() sns.lineplot(data=df_chart_data, x="Date", y="total_likes_count", color="orange", ax=ax2) sns.lineplot(data=df_chart_data, x="Date", y="total_comments_count", color="green", ax=ax2) ax2.set(ylabel="total_likes_count & total_comments_count") plt.title("Summary Chart") sns.despine() st.pyplot(fig) for post_group in post_groups: with st.container(): columns = st.columns(NUM_COLUMNS) for i, post in enumerate(post_group): like_count_diff = post['like_count'] - count.get(yesterday, {}).get(post['id'], {}).get('like_count', post['like_count']) comment_count_diff = post['comments_count'] - count.get(yesterday, {}).get(post['id'], {}).get('comments_count', post['comments_count']) max_like_diff = max(like_count_diff, max_like_diff) max_comment_diff = max(comment_count_diff, max_comment_diff) with columns[i]: st.image(post['media_url'], width=BOX_WIDTH, use_column_width=True) st.write(f"{datetime.datetime.strptime(post['timestamp'], '%Y-%m-%dT%H:%M:%S%z').astimezone(datetime.timezone(datetime.timedelta(hours=9))).strftime('%Y-%m-%d %H:%M:%S')}") st.markdown( f"👍: {post['like_count']} <span style='{'' if like_count_diff != max_like_diff or max_like_diff == 0 else 'color:green;'}'>({'+' if like_count_diff >= 0 else ''}{like_count_diff})</span>" f"\n💬: {post['comments_count']} <span style='{'' if comment_count_diff != max_comment_diff or max_comment_diff == 0 else 'color:green;'}'>({'+' if comment_count_diff >= 0 else ''}{comment_count_diff})</span>", unsafe_allow_html=True) caption = post['caption'] if caption is not None: caption = caption.strip() if "[Description]" in caption: caption = caption.split("[Description]")[1].lstrip() if "[Tags]" in caption: caption = caption.split("[Tags]")[0].rstrip() caption = caption.replace("#", "") caption = caption.replace("[model]", "👗") caption = caption.replace("[Equip]", "📷") caption = caption.replace("[Develop]", "🖨") if show_description: st.write(caption or "No caption provided") else: st.write(caption[:0] if caption is not None and len(caption) > 50 else caption or "No caption provided") if show_charts: days = list(chart_data_likes.keys()) likes = [chart_data_likes[d] for d in days] comments = [chart_data_comments[d] for d in days] df_like_data = pd.DataFrame({"Date": days, "likes_count": likes}) df_comment_data = pd.DataFrame({"Date": days, "comments_count": comments}) fig, ax1 = plt.subplots(figsize=(5, 3)) sns.lineplot(data=df_like_data, x="Date", y="likes_count", color="orange", ax=ax1) sns.lineplot(data=df_comment_data, x="Date", y="comments_count", color="green", ax=ax1) plt.xticks(rotation=90) plt.title("Like and Comment Counts") sns.despine() st.pyplot(fig) count[today][post['id']] = {'like_count': post['like_count'], 'comments_count': post['comments_count']} saveCount(count, count_filename) ''' 上記のコードを以下の要件をすべて満たして改修してください - Python用のインデントを行頭に付与して出力する - コード冒頭の修正内容についての説明文は表示しない - 指示のないコードの改変はしない - "caption = post['caption']"以降のブロックについては改変しない - グラフ作成のためのPythonライブラリは"seaborn"のみを使用する - "サマリーグラフ"の'like_count'と'comments_count'の数は、"各日の実数の合算"ではなく、"前日と比較して増加した数"を算出し表示する - "いいね/コメント数グラフ"については、各投稿IDごとに'like_count'と'comments_count'の"前日と比較して増加した数"を算出し、その各投稿IDごとに別々のグラフを表示するようにする
65422670547ca20f32ffec9123813047
{ "intermediate": 0.3094857633113861, "beginner": 0.43339425325393677, "expert": 0.25711995363235474 }
3,412
write a vba to calculate rsi with data in column d
a2620b01a31114c60dfd5ee696509923
{ "intermediate": 0.3619370758533478, "beginner": 0.30743157863616943, "expert": 0.3306313753128052 }
3,413
write a vba to calculate rsi with data in column d.write sub not function
03156e748304ff091513e4bcf3499285
{ "intermediate": 0.30664488673210144, "beginner": 0.37796157598495483, "expert": 0.3153935670852661 }