row_id int64 0 48.4k | init_message stringlengths 1 342k | conversation_hash stringlengths 32 32 | scores dict |
|---|---|---|---|
19,994 | import sys
import __main__
import sys, time, os
import numpy as np
import math
import os
from subprocess import call
# calculates the rotation matrix necessary to rotate the aligned dipole moment
# difference to the z-matrix coordinate system
def rotationMatrixFrom(vec1, vec2):
# normalized dipole vectors
normVec1 = vec1/np.linalg.norm(vec1)
normVec2 = vec2/np.linalg.norm(vec2)
a, b = normVec1.reshape(3), normVec2.reshape(3)
# cross dot (cross) and sin
v = np.cross(a, b)
c = np.dot(a, b)
s = np.linalg.norm(v)
# rotation matrix calculation from cartesian to z-matrix
kmat = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
rotation_matrix = np.eye(3) + kmat + kmat.dot(kmat) * ((1 - c) / (s ** 2))
return rotation_matrix
# uses the aligned cartesian sp results to find the difference in dipole moment between ts and int
def calculateDipoleDifference(tsLocation, intLocation, tsLocZ, intLocZ):
#reads int and ts dipole moments
file1 = open(intLocation, 'r')
intLine = file1.readlines()[0].strip().split()
intDipoleCart = [float(intLine[1]), float(intLine[3]), float(intLine[5])]
file1.close()
file2 = open(tsLocation, 'r')
tsLine = file2.readlines()[0].strip().split()
tsDipoleCart = [float(tsLine[1]), float(tsLine[3]), float(tsLine[5])]
file2.close()
file3 = open(intLocZ, 'r')
intLineZ = file3.readlines()[0].strip().split()
intDipoleZmat = [float(intLineZ[1]), float(intLineZ[3]), float(intLineZ[5])]
file3.close()
file4 = open(tsLocZ, 'r')
tsLineZ = file4.readlines()[0].strip().split()
tsDipoleZmat = [float(tsLineZ[1]), float(tsLineZ[3]), float(tsLineZ[5])]
file4.close()
allTheDipoleVectors = [intDipoleCart, tsDipoleCart, intDipoleZmat, tsDipoleZmat]
oneOfThemIsNothing = False
for theIndVects in allTheDipoleVectors:
sumOfZeros = 0
for eachCart in theIndVects:
if eachCart == 0.0:
sumOfZeros += 1
if sumOfZeros == 3:
oneOfThemIsNothing = True
if oneOfThemIsNothing == False :
# calculates the dipole difference in cartesian and z-matrix system and saves it to a file
diffDipoleCart = [tsDipoleCart[0]-intDipoleCart[0], tsDipoleCart[1]-intDipoleCart[1], tsDipoleCart[2]-intDipoleCart[2]]
# finds matrix to rotate cartesian dipole to z matrix
tsCartToZmat = rotationMatrixFrom(tsDipoleCart, tsDipoleZmat)
intCartToZmat = rotationMatrixFrom(intDipoleCart, intDipoleZmat)
fieldStrengths = [[str(25),-0.0025],[str(50),-0.0050],[str(75),-0.0075],[str(100),-0.01]]
dipoleSummary = open("dipoleSummary.txt", 'a')
dipoleSummary.write("Int Dipole Moment (Cartesian Coordinates) \n")
dipoleSummary.write(str(intDipoleCart) + "\n")
dipoleSummary.write( "||int dipole|| = " + str(np.linalg.norm(intDipoleCart))+" \n")
dipoleSummary.write(" \n")
dipoleSummary.write("TS Dipole Moment (Cartesian Coordinates): \n")
dipoleSummary.write(str(tsDipoleCart) + "\n")
dipoleSummary.write( "||ts dipole|| = " + str(np.linalg.norm(tsDipoleCart)) + " \n")
dipoleSummary.write(" \n")
dipoleSummary.write("TS-Int Dipole Difference (Cartesian Coordinates): \n")
dipoleSummary.write(str(diffDipoleCart) + "\n")
dipoleSummary.write( "||dipole diff|| = " + str(np.linalg.norm(diffDipoleCart)) + " \n")
dipoleSummary.close()
# Scales the dipole difference vector magnitude so that the applied electric field can be incrimented by those magnitudes
for magnitude in fieldStrengths:
tsDipoleDiffereceZmatN = magnitude[1]*tsCartToZmat.dot(diffDipoleCart/np.linalg.norm(diffDipoleCart))
tsDipoleDiffereceZmatStrN = str(tsDipoleDiffereceZmatN[0]) + " " + str(tsDipoleDiffereceZmatN[1]) + " " + str(tsDipoleDiffereceZmatN[2]) + " "
intDipoleDifferenceZmatN = magnitude[1]*intCartToZmat.dot(diffDipoleCart/np.linalg.norm(diffDipoleCart))
intDipoleDifferenceZmatStrN = str(intDipoleDifferenceZmatN[0]) + " " + str(intDipoleDifferenceZmatN[1]) + " " + str(intDipoleDifferenceZmatN[2]) + " "
tsZmatN = open("ts_N" + magnitude[0] + ".txt", 'w')
tsZmatN.write(tsDipoleDiffereceZmatStrN)
tsZmatN.close()
intZmatN = open("int_N" + magnitude[0] + ".txt", 'w')
intZmatN.write(intDipoleDifferenceZmatStrN)
intZmatN.close()
rc = call("./countinueProcesses.sh")
else :
rc = call("./stopDueToZero.sh")
calculateDipoleDifference(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])请详细解释一下代码 | 947441f04f4eeda7351f201c2913251e | {
"intermediate": 0.36590486764907837,
"beginner": 0.33158501982688904,
"expert": 0.3025100529193878
} |
19,995 | how to learn io_uring | 9b16185d9db634e3aea4b15e3539217c | {
"intermediate": 0.42948129773139954,
"beginner": 0.4104290306568146,
"expert": 0.1600896567106247
} |
19,996 | how to loop mp4 video in WPF c# | efe4ff63b2f5aa95d23b8c15b918cbbc | {
"intermediate": 0.3307875692844391,
"beginner": 0.47678425908088684,
"expert": 0.19242815673351288
} |
19,997 | Power BI: Need to get the file created date for the import excel file | aed3072ba290211dd0546d35dbee8bf2 | {
"intermediate": 0.3477069139480591,
"beginner": 0.22735102474689484,
"expert": 0.4249420166015625
} |
19,998 | <!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.cdnfonts.com/css/tetris" rel="stylesheet">
<link rel="stylesheet" href="index.css"/>
<title>3</title>
</head>
<body>
<div class="tetris">
<h1 class="title">Tetris</h1>
<div>score: <span id="score">0</span></div>
<canvas width="270" height="400" id="field" class="field"></canvas>
<button id="start" class="button">Start</button>
<button id="rotate" class="joystick">
<img src="rotate.svg" />
</button>
<button id="top" class="joystick">
<img src="arrow-top.svg" />
</button>
<button id="bottom" class="joystick">
<img src="arrow-bottom.svg" />
</button>
<button id="left" class="joystick">
<img src="arrow-left.svg" />
</button>
<button id="right" class="joystick">
<img src="arrow-right.svg" />
</button>
</div>
<script type="module" src="./js/main.js"></script>
</body>
</htm>
напиши логику игры в тетрис на js для этого html используя функции | a0660be4a45d4b3699adfe20c474233a | {
"intermediate": 0.37856972217559814,
"beginner": 0.3512970805168152,
"expert": 0.2701331675052643
} |
19,999 | INFO: HHH10001008: Cleaning up connection pool [jdbc:sqlite:database.sqlite]
java.lang.NullPointerException | d6e7b077807f922d0dc3eb8f9574964c | {
"intermediate": 0.4054681062698364,
"beginner": 0.34413501620292664,
"expert": 0.2503969371318817
} |
20,000 | org.hibernate.AssertionFailure: non-transient entity has a null id | 7fc5ae16cd312e50f8c403177ef6a6f2 | {
"intermediate": 0.45176219940185547,
"beginner": 0.199919655919075,
"expert": 0.34831809997558594
} |
20,001 | use jsonlint to validate json array? | 2e3d3d2dd9903b473acf310e40e0d2ad | {
"intermediate": 0.6223907470703125,
"beginner": 0.15346020460128784,
"expert": 0.22414904832839966
} |
20,002 | I am not sure but when I invoke cmake I get the following error message:
No implementation of use_package. Create yours. Package "boost" with
version "1.80.0" for target "ForeignLanguageConversionRoutines" is ignored!
what does it mean? | 4e10e1023663bc56ea8fbee632da884a | {
"intermediate": 0.6046692728996277,
"beginner": 0.19150026142597198,
"expert": 0.20383042097091675
} |
20,003 | Power BI: Where do i find the creation date for the imported Excel | 281080cd2551a8ce6c305b7f163145d3 | {
"intermediate": 0.39313802123069763,
"beginner": 0.2027546763420105,
"expert": 0.40410730242729187
} |
20,004 | hi | 0c211f9991df4cc34cd7c8d90d050ec0 | {
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
} |
20,005 | Power BI: I have two external Excel files, Once is called current and other previous. I need to track their Date/Time last uploaded. Next time when i change the sources of Current and Previous, Previous should show the prior date/time | 7f96ab5e6e288cc70c7cf3ad3f336794 | {
"intermediate": 0.35082513093948364,
"beginner": 0.2017250508069992,
"expert": 0.44744983315467834
} |
20,006 | how i can add tag = BIRTH_PLACE in in storied procedure=SSS on sql ? | 7438e0baf5c495f6f8fa219bd143d5c2 | {
"intermediate": 0.42799854278564453,
"beginner": 0.25805917382240295,
"expert": 0.3139423131942749
} |
20,007 | I want a VBA code that will do the following.
When I select a value from a list in A1,
In all sheets in my workbook that have a name with only three letters,
find the matching value in column B, then
for each match, copy the row B:J
to sheet 'CTasks' B:J starting from row two.
For each match found, I also want the sheet name where the match is found to be written to column K in sheet CTasks. | 53887c4b148f0fb90505942b43801459 | {
"intermediate": 0.4638110101222992,
"beginner": 0.16680817306041718,
"expert": 0.36938080191612244
} |
20,008 | I have a collection of images of a player charracter from a game doing certain animations.
please make a python program that looks for the charracter on the screen based on all the images in the folder | b263f8a881e34f9750dadcad784d8dd2 | {
"intermediate": 0.4286089837551117,
"beginner": 0.20346474647521973,
"expert": 0.3679262697696686
} |
20,009 | Good morning. Could you give me an example of speech for programmer interview? | 76b32288987f9f2e8700097389d94ca6 | {
"intermediate": 0.3365841209888458,
"beginner": 0.312944233417511,
"expert": 0.3504716455936432
} |
20,010 | I want a VBA code that will do the following.
When I click on a cell in the range B2:L101,
the entrie row within the range will highlight Yellow | bcd5128688c3629e3fdbaf0b68671777 | {
"intermediate": 0.2855241894721985,
"beginner": 0.37039974331855774,
"expert": 0.3440760672092438
} |
20,011 | why is my code just showing me a black window with what seems to be randomly colores pixels on the top and bottom?
I want it to take screenshots of my screen and check for the images in the folder and then draw a box and print out the location.
import cv2
import numpy as np
import os
def find_character(character_images_folder):
# Load character images from folder
character_images = []
character_sizes = []
for filename in os.listdir(character_images_folder):
if filename.endswith(".png") or filename.endswith(".jpg"):
image_path = os.path.join(character_images_folder, filename)
image = cv2.imread(image_path)
character_images.append(image)
character_sizes.append(image.shape[:2])
# Initialize video capture
capture = cv2.VideoCapture(0)
while True:
# Read frame from camera
ret, frame = capture.read()
# Loop through each character image
for character_img, character_size in zip(character_images, character_sizes):
character_height, character_width = character_size
# Find character in the frame
result = cv2.matchTemplate(frame, character_img, cv2.TM_CCORR_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# Set a threshold for character detection
threshold = 0.8
# If character is found
if max_val >= threshold:
print("Detected Charracter")
# Draw rectangle around the character
top_left = max_loc
bottom_right = (top_left[0] + character_width, top_left[1] + character_height)
cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 3)
cv2.putText(frame, "Character Detected", (top_left[0], top_left[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# Display the frame
cv2.imshow("Character Detection", frame)
# Press "q" to exit
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# Release the video capture
capture.release()
cv2.destroyAllWindows()
# Provide the path to the character images folder
character_images_folder = "./images/character"
# Call the function to find the character on the screen
find_character(character_images_folder) | 6e4f46de35edde7755362f2e28fbf857 | {
"intermediate": 0.35789933800697327,
"beginner": 0.502708911895752,
"expert": 0.13939169049263
} |
20,012 | How to set value on Polars slice? | 0f0380d98f02bffd93775e00a4135cf1 | {
"intermediate": 0.28015437722206116,
"beginner": 0.16196657717227936,
"expert": 0.5578790903091431
} |
20,013 | change the place holder of input dynamically from url when changes angular | f9e776ed8a6f4e6cb6675002cc2a31bb | {
"intermediate": 0.447648286819458,
"beginner": 0.19436290860176086,
"expert": 0.35798877477645874
} |
20,014 | find the center between the top left and bottom right coordinates and click there with the mouse using pyautogui.
import cv2
import numpy as np
import os
import pyautogui
import time
def find_character(character_images_folder):
# Load character images from folder
character_images = []
character_sizes = []
for filename in os.listdir(character_images_folder):
if filename.endswith(".png") or filename.endswith(".jpg"):
image_path = os.path.join(character_images_folder, filename)
image = cv2.imread(image_path)
character_images.append(image)
character_sizes.append(image.shape[:2])
time.sleep(2)
for i in range(5):
# Capture screenshot of the screen
screen = pyautogui.screenshot()
frame = np.array(screen)
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
# Loop through each character image
for character_img, character_size in zip(character_images, character_sizes):
character_height, character_width = character_size
# Find character in the frame
result = cv2.matchTemplate(frame, character_img, cv2.TM_CCORR_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
# Set a threshold for character detection
threshold = 0.965
# If character is found
if max_val >= threshold:
# Draw rectangle around the character
top_left = max_loc
bottom_right = (top_left[0] + character_width, top_left[1] + character_height)
print("Detected Character: ", str(top_left), " / ", str(bottom_right))
cv2.rectangle(frame, top_left, bottom_right, (0, 255, 0), 2)
cv2.putText(frame, "Character: " + str(max_val), (top_left[0], top_left[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
# Display the frame
cv2.imshow("Character Detection", frame)
#time.sleep(0.1)
# Press "q" to exit
if cv2.waitKey(1) & 0xFF == ord("q"):
break
# Provide the path to the character images folder
character_images_folder = "./images/character"
# Call the function to find the character on the screen
find_character(character_images_folder) | 42c08f8a25e59e948a1ae0002338fd08 | {
"intermediate": 0.38594070076942444,
"beginner": 0.4652141034603119,
"expert": 0.14884518086910248
} |
20,015 | root@bf7f8e5914fa:/var/www/html# service apache2 reload
Reloading Apache httpd web server: apache2 failed!
The apache2 configtest failed. Not doing anything. ... (warning).
Output of config test was:
AH00526: Syntax error on line 31 of /etc/apache2/sites-enabled/default-ssl.conf:
SSLCertificateFile: file '/etc/ssl/certs/ssl-cert-snakeoil.pem' does not exist or is empty
Action 'configtest' failed.
The Apache error log may have more information. | 2763989585f67c7d65097991c262066e | {
"intermediate": 0.4267519414424896,
"beginner": 0.31076130270957947,
"expert": 0.2624867558479309
} |
20,016 | Hi. Please write docker-compose.yml for Astro and Strapi in one monorepo. | ff9dbea18ff120e0901bc723b70f81e4 | {
"intermediate": 0.5353297591209412,
"beginner": 0.2026551514863968,
"expert": 0.26201507449150085
} |
20,017 | конвертируй конфигурацию cisco BGP под Nikrotik Router os 7.11 BGPlogin as: newciscoedge Keyboard-interactive authentication prompts from server: | Password: End of keyboard-interactive prompts from server Access denied Keyboard-interactive authentication prompts from server: | Password: End of keyboard-interactive prompts from server Access denied Keyboard-interactive authentication prompts from server: | Password: End of keyboard-interactive prompts from server EDGE01# EDGE01# EDGE01#sh EDGE01#show run EDGE01#show running-config Building configuration… Current configuration : 4866 bytes ! version 15.5 service timestamps debug datetime msec service timestamps log datetime localtime service password-encryption no service dhcp no platform punt-keepalive disable-kernel-core ! hostname EDGE01 ! boot-start-marker boot-end-marker ! ! vrf definition Mgmt-intf ! address-family ipv4 exit-address-family ! address-family ipv6 exit-address-family ! ! aaa new-model ! ! aaa authentication login default local aaa authorization exec default local ! ! ! ! ! aaa session-id common clock timezone GMT 3 0 ! ! ! ! ! ! ! ! ! no ip bootp server ip domain name msccbronka.ru ip name-server 8.8.8.8 ! ! ! login block-for 120 attempts 5 within 60 login on-failure log login on-success log ! ! ! ! ! ! ! subscriber templating vtp mode transparent multilink bundle-name authenticated ! ! ! ! license udi pid ISR4431/K9 sn FOC20102Q01 ! spanning-tree extend system-id no spanning-tree vlan 1200 ! username newciscoedge privilege 15 password 7 151D020A003F737D1B170C314A030F5453040A0A737E39 ! redundancy mode none ! ! vlan internal allocation policy ascending no cdp run ! ! ! ! ! ! ! ! ! interface Loopback0 ip address 93.188.203.5 255.255.255.255 ! interface GigabitEthernet0/0/0 description LINKTOEDGE02 ip address 93.188.203.1 255.255.255.252 no ip redirects no ip proxy-arp negotiation auto no cdp enable no mop enabled ! interface GigabitEthernet0/0/1 no ip address no ip redirects no ip proxy-arp negotiation auto no cdp enable no mop enabled ! interface GigabitEthernet0/0/2 description LINKTOOBIT ip address 217.79.15.198 255.255.255.252 no ip redirects no ip proxy-arp negotiation auto no cdp enable no mop enabled ! interface GigabitEthernet0/0/3 description LINKTOCUST no ip address no ip redirects no ip proxy-arp negotiation auto no cdp enable no mop enabled ! interface GigabitEthernet0/0/3.770 description LINKLOCALMAN encapsulation dot1Q 770 ip address 10.99.99.1 255.255.255.0 no ip redirects no ip proxy-arp no cdp enable ! interface GigabitEthernet0/0/3.771 description LINKTOCHECKPOINT encapsulation dot1Q 771 ip address 93.188.201.2 255.255.255.224 no ip redirects no ip proxy-arp standby 201 ip 93.188.201.1 standby 201 priority 105 standby 201 preempt no cdp enable ! interface GigabitEthernet0/0/3.772 description LINKTOMISC encapsulation dot1Q 772 ip address 93.188.201.34 255.255.255.224 no ip redirects no ip proxy-arp standby 202 ip 93.188.201.33 standby 202 priority 105 standby 202 preempt no cdp enable ! interface GigabitEthernet0/0/3.773 description LINKTOBK encapsulation dot1Q 773 ip address 93.188.202.2 255.255.255.240 no ip redirects no ip proxy-arp standby 203 ip 93.188.202.1 standby 203 priority 105 standby 203 preempt no cdp enable ! interface GigabitEthernet0 vrf forwarding Mgmt-intf no ip address negotiation auto ! interface Vlan1 no ip address ! router bgp 207258 bgp log-neighbor-changes bgp dampening network 93.188.200.0 mask 255.255.252.0 neighbor 93.188.203.6 remote-as 207258 neighbor 93.188.203.6 description iBGP - TO EDGE02 neighbor 93.188.203.6 update-source Loopback0 neighbor 93.188.203.6 version 4 neighbor 93.188.203.6 next-hop-self neighbor 93.188.203.6 send-community neighbor 93.188.203.6 soft-reconfiguration inbound neighbor 217.79.15.197 remote-as 8492 neighbor 217.79.15.197 description BGP to - OBIT neighbor 217.79.15.197 version 4 neighbor 217.79.15.197 send-community neighbor 217.79.15.197 soft-reconfiguration inbound neighbor 217.79.15.197 prefix-list BOGONS in neighbor 217.79.15.197 prefix-list ANNOUNCE out ! ip forward-protocol nd no ip http server no ip http secure-server ip route 93.188.200.0 255.255.252.0 Null0 200 ip route 93.188.201.64 255.255.255.224 93.188.201.43 110 ip route 93.188.203.6 255.255.255.255 93.188.203.2 ! ! ! ! ip prefix-list ANNOUNCE description Our External Netblocks ip prefix-list ANNOUNCE seq 10 permit 93.188.200.0/22 ! ip prefix-list BOGONS description Bad Routes to Block In ip prefix-list BOGONS seq 10 deny 0.0.0.0/8 le 32 ip prefix-list BOGONS seq 15 deny 10.0.0.0/8 le 32 ip prefix-list BOGONS seq 20 deny 127.0.0.0/8 le 32 ip prefix-list BOGONS seq 25 deny 172.16.0.0/12 le 32 ip prefix-list BOGONS seq 30 deny 192.0.2.0/24 le 32 ip prefix-list BOGONS seq 35 deny 192.168.0.0/16 le 32 ip prefix-list BOGONS seq 40 deny 224.0.0.0/3 le 32 ip prefix-list BOGONS seq 1000 deny 93.188.200.0/22 le 32 ip prefix-list BOGONS seq 9999 permit 0.0.0.0/0 le 27 access-list 99 permit 93.188.203.2 access-list 99 permit 93.188.201.4 access-list 99 permit 93.188.203.4 access-list 99 permit 185.17.84.14 ! snmp-server community bronkaro RO 99 ! ! ! ! control-plane ! ! line con 0 stopbits 1 line aux 0 stopbits 1 line vty 0 4 access-class 99 in transport input ssh line vty 5 15 access-class 99 in transport preferred none transport input ssh ! ! end | e9be93ed941134d75075aca6a18d14fb | {
"intermediate": 0.406839519739151,
"beginner": 0.35736727714538574,
"expert": 0.23579317331314087
} |
20,018 | write me telegram bot code for beauty studio, connected to calendars and feedback | 75fad6d718db888c2f17d28251323f1b | {
"intermediate": 0.4680972993373871,
"beginner": 0.210623636841774,
"expert": 0.32127901911735535
} |
20,019 | У меня есть игра на юнити, как сделать чтобы на гем можно было нажимать только после выполнения полной анимации(SwapGemsSmoothly) using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Unity.VisualScripting;
using UnityEngine;
public class Gem : MonoBehaviour
{
[SerializeField] private SceneController controller;
private int _id;
public int id => _id;
// private static Gem _firstGem;
// private static Gem _secondGem;
private int _orderNum;
public int orderNum
{
get => _orderNum;
set => _orderNum = value;
}
// //Создания массива, состоящего из массивов нелегальных пар(которые не могут менятся друг с другом(так как не являются соседями)
// private int[][] illegalPairs = new int[3][];
public void Awake()
{
controller = FindObjectOfType<SceneController>();
}
// public void OnMouseDown()
// {
// // GetComponent<SpriteRenderer>().color = Color.black;
// if (_firstGem == null)
// {
// _firstGem = this;
// GetComponent<SpriteRenderer>().color = Color.gray;
//
// Debug.Log($"Order num: {_firstGem._orderNum}");
// Debug.Log($"Order id: {_firstGem.id}");
//
//
// }
//
// else
// {
// _secondGem = this;
// SwapGems(_firstGem, _secondGem);
//
// _firstGem.GetComponent<SpriteRenderer>().color = Color.white;
//
// _firstGem = null;
// _secondGem = null;
//
//
//
// }
// }
public void OnMouseDown()
{
controller.ClickOnGem(this);
Debug.Log($"Click! id: {this.id}, orderNum: {this.orderNum}");
Debug.Log(controller.IsGameWon());
}
public void SetGem(int startPosition, Sprite image)
{
_id = startPosition;
_orderNum = startPosition;
GetComponent<SpriteRenderer>().sprite = image;
}
// private void SwapGems(Gem gem1, Gem gem2)
// {
// if (gem1.id == 15 || gem2.id == 15)
// {
// if (Math.Abs(_firstGem.orderNum - _secondGem.orderNum) == 1 ||
// Math.Abs(_firstGem.orderNum - _secondGem.orderNum) == 4)
// {
// int[] orderNumArray = { _firstGem.orderNum, _secondGem.orderNum };
// Array.Sort(orderNumArray);
//
// if (!illegalPairs.Any(pair => pair.SequenceEqual(orderNumArray)))
// {
// SwapGemsWithOrder(gem1, gem2);
// // Vector3 firstPos = gem1.transform.position;
// // Vector2 secondPos = gem2.transform.position;
// //
// //
// // int tempOrderNum = _firstGem.orderNum;
// // int secondTilePrevOrderNum = _secondGem.orderNum;
// //
// //
// // gem1.transform.position = secondPos;
// // gem2.transform.position = firstPos;
// //
// // // Обновить значения orderNum после переставления gems
// // _firstGem.orderNum = secondTilePrevOrderNum;
// // _secondGem.orderNum = tempOrderNum;
//
// }
//
// }
//
// }
// }
//
// public void SwapGemsWithOrder(Gem firstGem, Gem secondGem)
// {
// Vector3 firstPos = firstGem.transform.position;
// Vector2 secondPos = secondGem.transform.position;
//
// int tempOrderNum = _firstGem.orderNum;
// int secondTilePrevOrderNum = _secondGem.orderNum;
//
// firstGem.transform.position = secondPos;
// secondGem.transform.position = firstPos;
//
// // Обновить значения orderNum после переставления gems
// _firstGem.orderNum = secondTilePrevOrderNum;
// _secondGem.orderNum = tempOrderNum;
// }
//
// // public bool IsGameWon(Gem[] gems)
// // {
// // return gems.All(gem => gem.id == gem.orderNum);
// // }
}using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Unity.VisualScripting;
using UnityEngine;
using Random = UnityEngine.Random;
public class ShuffleScript : MonoBehaviour
{
[SerializeField] private SceneController controller;
[SerializeField] private float delay;
[SerializeField] private int numOfIterations;
private Gem[] _gems;
private readonly Dictionary<int, int[]> _puzzleGraph = new Dictionary<int, int[]>();
public void Start()
{
_gems = controller.GetGemsArray();
FillPuzzleGraph();
}
private void OnMouseDown()
{
// Debug.Log((GetGemById(15, _gems).id));
// Debug.Log($"Соседи 15: {string.Join(" ", _puzzleGraph[15])} ");
// Debug.Log($"16-ая ячейка: orderNum:{_gems[15].orderNum} / id:{_gems[15].id}");
Debug.Log($"Id: {_gems[15].id}\n" +
$"OrderNum: {_gems[15].orderNum}");
StartCoroutine(ShuffleGemsWithDelay(delay, numOfIterations));
Debug.Log(controller.IsGameWon());
}
private void ShuffleGems()
{
Gem gem16 = _gems[15];
int gemCurrentOrder = gem16.orderNum;
//Находим соседние клетки, после чего выбираем случайную соседнюю клетку
int[] gemNeighbors = _puzzleGraph[gemCurrentOrder];
int randomOrder = Random.Range(0, gemNeighbors.Length);
int randomNeighborOrder = gemNeighbors[randomOrder];
Gem randomGem = GetGemByOrder(randomNeighborOrder);
// Debug.Log($"Random Neighbor: {randomNeighbor}");
Vector3 firstPos = gem16.transform.position;
Vector2 secondPos = randomGem.transform.position;
int tempOrderNum = gem16.orderNum;
int secondTilePrevOrderNum = randomGem.orderNum;
gem16.transform.position = secondPos;
randomGem.transform.position = firstPos;
// Обновить значения orderNum после перестановки gems
gem16.orderNum = secondTilePrevOrderNum;
randomGem.orderNum = tempOrderNum;
// Debug.Log($"Черный гем id: {gem16.id}\n " +
// $"orderNum: {gem16.orderNum}\n" +
// $"id: {_gems[15].id}" +
// $"orderNum {_gems[15].orderNum}"
//
// );
}
private IEnumerator ShuffleGemsWithDelay(float delayNum, int num)
{
// yield return new WaitForSeconds(delay);
for (int i = 0; i < num; i++)
{
ShuffleGems();
yield return new WaitForSeconds(delayNum);
}
}
private Gem GetGemByOrder(int orderNum)
{
Gem gemWithOrder = _gems.FirstOrDefault(gem => gem.orderNum == orderNum);
return gemWithOrder;
}
//Функция, для заполнения словаря.
void FillPuzzleGraph()
{
_puzzleGraph.Add(0, new[] { 1, 4 });
_puzzleGraph.Add(1, new[] { 0, 2, 5 });
_puzzleGraph.Add(2, new[] { 1, 3, 6 });
_puzzleGraph.Add(3, new[] { 2, 7 });
_puzzleGraph.Add(4, new[] { 0, 5, 8 });
_puzzleGraph.Add(5, new[] { 1, 4, 6, 9 });
_puzzleGraph.Add(6, new[] { 2, 5, 7, 10 });
_puzzleGraph.Add(7, new[] { 3, 6, 11 });
_puzzleGraph.Add(8, new[] { 4, 9, 12 });
_puzzleGraph.Add(9, new[] { 5, 8, 10, 13 });
_puzzleGraph.Add(10, new[] { 6, 9, 11, 14 });
_puzzleGraph.Add(11, new[] { 7, 10, 15 });
_puzzleGraph.Add(12, new[] { 8, 13 });
_puzzleGraph.Add(13, new[] { 9, 12, 14 });
_puzzleGraph.Add(14, new[] { 10, 13, 15 });
_puzzleGraph.Add(15, new[] { 11, 14 });
}
}using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class SceneController : MonoBehaviour
{
public const int GridRows = 4;
public const int GridCols = 4;
public const float OffsetX = 2f;
public const float OffsetY = 2.5f;
[SerializeField] private Gem originalGem;
[SerializeField] private Sprite[] images;
private int GemNum = 0;
private Gem _firstGem;
private Gem _secondGem;
private Gem _emptyGem;
private Gem[] _gems; // Поле класса для хранения массива гемов
//Создания массива, состоящего из массивов нелегальных пар(которые не могут менятся друг с другом(так как не являются соседями)
private int[][] illegalPairs = new int[3][];
public Gem[] GemsArray
{
get => _gems;
set => _gems = value;
}
private void Awake()
{
//Заполнение массива нелегальных пар
illegalPairs[0] = new int[] { 3, 4 };
illegalPairs[1] = new int[] { 7, 8 };
illegalPairs[2] = new int[] { 11, 12 };
Vector3 startPos = originalGem.transform.position;
_gems = new Gem[GridRows * GridCols]; // Инициализируем массив гемов
for (int i = 0; i < GridRows; i++)
{
for (int j = 0; j < GridCols; j++)
{
// Gem gem;
Gem gem = Instantiate(originalGem) as Gem;
gem.SetGem(GemNum, images[GemNum]);
// gem = Instantiate(originalGem) as Gem;
float posX = (OffsetX * j) + startPos.x;
float posY = -(OffsetY * i) + startPos.y;
gem.transform.position = new Vector3(posX, posY, startPos.z);
_gems[(i * GridCols) + j] = gem; // Добавляем гем в массив
GemNum++;
}
}
_emptyGem = _gems[15];
}
// public Gem[] GetGemsArray()
// {
// Gem[] gems = FindObjectsOfType<Gem>();
// return gems;
//
// // foreach (Gem gem in gems)
// // {
// // if (gem.id == targetId)
// // {
// // return gem;
// // }
// // }
// //
// // return null; // Объект с указанным id не найден
// }
// public void ClickOnGem(Gem gem)
// {
// if (_firstGem == null)
// {
// _firstGem = gem;
//
// Debug.Log("1st if");
//
// // _firstGem.GetComponent<SpriteRenderer>().color = Color.gray;
// }
// else
// {
// _secondGem = gem;
// SwapGems(_firstGem, _secondGem);
//
// // _firstGem.GetComponent<SpriteRenderer>().color = Color.white;
//
// _firstGem = null;
// _secondGem = null;
//
// Debug.Log("2st if");
// }
// }
public void ClickOnGem(Gem gem)
{
if (Math.Abs(gem.orderNum - _emptyGem.orderNum) == 1 ||
Math.Abs(gem.orderNum - _emptyGem.orderNum) == 4)
{
int[] orderNumArray = { gem.orderNum, _emptyGem.orderNum };
Array.Sort(orderNumArray);
if (!illegalPairs.Any(pair => pair.SequenceEqual(orderNumArray)))
{
// SwapGemsWithOrder(gem, _emptyGem);
StartCoroutine(SwapGemsSmoothly(gem, _emptyGem));
}
}
}
// private void SwapGems(Gem gem1, Gem gem2)
// {
// // if (gem1.id == 15 || gem2.id == 15)
// // {
// if (Math.Abs(_firstGem.orderNum - _secondGem.orderNum) == 1 ||
// Math.Abs(_firstGem.orderNum - _secondGem.orderNum) == 4)
// {
// int[] orderNumArray = { _firstGem.orderNum, _secondGem.orderNum };
// Array.Sort(orderNumArray);
//
// if (!illegalPairs.Any(pair => pair.SequenceEqual(orderNumArray)))
// {
// SwapGemsWithOrder(gem1, gem2);
// }
// }
//
// // }
// }
public void SwapGemsWithOrder(Gem firstGem, Gem secondGem)
{
Vector3 firstPos = firstGem.transform.position;
Vector2 secondPos = secondGem.transform.position;
int tempOrderNum = firstGem.orderNum;
int secondTilePrevOrderNum = secondGem.orderNum;
firstGem.transform.position = secondPos;
secondGem.transform.position = firstPos;
// Обновить значения orderNum после переставления gems
firstGem.orderNum = secondTilePrevOrderNum;
secondGem.orderNum = tempOrderNum;
}
IEnumerator SwapGemsSmoothly(Gem firstGem, Gem secondGem)
{
Vector3 initialPosition1 = firstGem.transform.position;
Vector3 initialPosition2 = secondGem.transform.position;
Vector3 targetPosition1 = secondGem.transform.position;
Vector3 targetPosition2 = firstGem.transform.position;
int tempOrderNum = firstGem.orderNum;
int secondTilePrevOrderNum = secondGem.orderNum;
float duration = 0.5f; // Время, которое займет анимация (можете настроить под свои предпочтения)
float elapsedTime = 0f;
while (elapsedTime < duration)
{
firstGem.transform.position = Vector3.Lerp(initialPosition1, targetPosition1, elapsedTime / duration);
secondGem.transform.position = Vector3.Lerp(initialPosition2, targetPosition2, elapsedTime / duration);
elapsedTime += Time.deltaTime;
yield return null;
}
// Убедитесь, что обе позиции точно установлены на конечные значения, чтобы избежать погрешностей.
firstGem.transform.position = targetPosition1;
secondGem.transform.position = targetPosition2;
// Обновить значения orderNum после переставления gems
firstGem.orderNum = secondTilePrevOrderNum;
secondGem.orderNum = tempOrderNum;
}
public Gem[] GetGemsArray()
{
return _gems; // Возвращаем сохраненный массив гемов
}
public bool IsGameWon()
{
return _gems.All(gem => gem.id == gem.orderNum);
}
} | 5fe7fe8b8ed7577776b7f972305f9c3d | {
"intermediate": 0.39581167697906494,
"beginner": 0.48618876934051514,
"expert": 0.11799956113100052
} |
20,020 | Hi do you know Ann search in Amazon OpenSearch service | f01bcb671a342be0bd71263bfa9403ec | {
"intermediate": 0.25232675671577454,
"beginner": 0.34631699323654175,
"expert": 0.40135622024536133
} |
20,021 | i do i convert: [[{'summary_text': " Taylor Knight asks Maristela, Rogelio P CPO USN, CG57, about how to access technical manuals and documentations . The old system (TDMIS) originally allowed you to access . But now that it's disabled, correct? Are these publications solely housed in TDMIS?"}],
[{'summary_text': '
to just the text | 552a7f812c20f39711fe19406a256ed7 | {
"intermediate": 0.28186357021331787,
"beginner": 0.3032267987728119,
"expert": 0.414909690618515
} |
20,022 | Can you please amend the VBA code below to do the following:
In the same folder location, open in the background the woorkbook 'Service Providers History'.
Search all sheets that have three letters in the woorkbook 'Service Providers History'
and write the results to the sheet HTasks in the workbook 'Service Providers'
then close the workbook 'Service Providers History' without any notifications.
Sub FindAndCopyHRows()
Dim selectedValue As String
Dim ws As Worksheet
Dim hTasksWs As Worksheet
Dim lastRow As Long, pasteRow As Long
' Get the selected value from cell A1
selectedValue = Range("A1").Value
' Set the "CTasks" worksheet as the destination for copied rows
Set cTasksWs = ThisWorkbook.Worksheets("HTasks")
' Clear the previous data in CTasks worksheet
cTasksWs.Range("B2:J" & hTasksWs.Cells(Rows.Count, "B").End(xlUp).Row).Clear
cTasksWs.Range("K2:K" & hTasksWs.Cells(Rows.Count, "K").End(xlUp).Row).Clear
' Loop through all sheets in the workbook
For Each ws In ThisWorkbook.Worksheets
' Check if the sheet name has only three letters
If Len(ws.Name) = 3 Then
' Find the matching value in column B
lastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
For i = 2 To lastRow
If ws.Cells(i, "B").Value = selectedValue Then
' Copy the row B:J to CTasks sheet
pasteRow = hTasksWs.Cells(hTasksWs.Rows.Count, "B").End(xlUp).Row + 1
ws.Range("B" & i & ":J" & i).Copy Destination:=hTasksWs.Range("B" & pasteRow & ":J" & pasteRow)
' Write the sheet name to column K in CTasks sheet
hTasksWs.Cells(pasteRow, "K").Value = ws.Name
End If
Next i
End If
Next ws
hTasksWs.Range("L2:L101").Calculate
hTasksWs.Range("N1:X1").Copy Range("B1:L1")
End Sub | 95a80db3a13bfe9480eb426ed5689102 | {
"intermediate": 0.35745006799697876,
"beginner": 0.35569480061531067,
"expert": 0.2868551015853882
} |
20,023 | I am trying to delete a merge request merged incorrectly in Gitlab. I already reverted the changes in Git by force pushing but in gitlab's interface it shows the merge request closed and I can't delete it.
I used the following command in a powershell:
curl --request DELETE --header "PRIVATE-TOKEN: MY_PRIVATE_TOKEN" "https://gitlab.com/api/v4/projects/NAME_OF_MY_PROJECT/merge_requests/165"
and it gave me this error output:
Invoke-WebRequest : No se encuentra ningún parámetro de posición que acepte el argumento 'DELETE'.
En línea: 1 Carácter: 1
+ curl --request DELETE --header "PRIVATE-TOKEN: ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Why is this error? is there an alternative to this? how to delete it correctly? | 356a9fc08d35434ef6597a040bf0fcb2 | {
"intermediate": 0.6321747899055481,
"beginner": 0.21027526259422302,
"expert": 0.1575498878955841
} |
20,024 | I have DAG in first.py:
with DAG(
default_args={
'owner': CONFIG['dag_owner'],
'retries': CONFIG['dag_retries'],
'retry_delay': CONFIG['dag_retry_delay']
},
dag_id = 'Weather_ETL',
description='Download archive data for Moscow Weather',
start_date=datetime(2023, 9, 1),
schedule_interval='0 1/3 * * *',
catchup=False
) as dag:
Weather_etl = DockerOperator(
task_id="weather_etl",
image="weather-etl:latest",
command="python main.py",
docker_url='unix://var/run/docker.sock',
mount_tmp_dir = False,
auto_remove=True,
xcom_all=True
)
and main.py that placed in docker container:
def main():
kotlin
Copy code
file_path = extract()
data = transform(file_path)
# If new data is found, add to DB
if data.shape[0] > 0:
load(data)
new_rows_found = True
else:
new_rows_found = False
first.py and main.py are different files
i need to save new_rows_found to xcom of airflow | a5b7d989b842e9acadf86fed01e28824 | {
"intermediate": 0.5198624134063721,
"beginner": 0.22428347170352936,
"expert": 0.25585412979125977
} |
20,025 | how to save a plot in matlab | e934de50bd0a2e817b0aa1b965da557f | {
"intermediate": 0.17309065163135529,
"beginner": 0.09502637386322021,
"expert": 0.7318829894065857
} |
20,026 | [Inject]
private readonly IItemCatalogService itemCatalogService;
private static readonly ILog Logger = LogManager.GetLogger(typeof(InventoryGridService));
public bool HasFreeSpace(GameEntity inventoryItemEntity, GameEntity addedItemEntity)
{
if (!addedItemEntity.hasItem)
{
Logger.Info("Entity id: " + addedItemEntity.id.Value + " has not ItemComponent");
return false;
}
if (!inventoryItemEntity.hasInventoryGrid)
{
Logger.Info("Entity id: " + inventoryItemEntity.id.Value + " has not InventoryGridComponent");
return false;
}
itemCatalogService.TryGetItemConfig(addedItemEntity.item.UID, out IInventoryItemConfig inventoryItemConfig);
bool r = false;
foreach (int[,] grid in inventoryItemEntity.inventoryGrid.Value)
{
Debug.Log("inventoryItemConfig.InventorySize: " + inventoryItemConfig.InventorySize);
var posOnGrid = FindSpaceForObjectAnyDirection(grid, inventoryItemConfig.InventorySize, addedItemEntity.isInventoryRotated);
Debug.Log("1 posOnGrid: " + posOnGrid);
if (posOnGrid == null)
{
r = false;
}
if (posOnGrid != null)
{
return true;
}
}
return r;
}
private static Vector2Int RotateItem(Vector2Int itemSize) {
(itemSize.x, itemSize.y) = (itemSize.y, itemSize.x);
return itemSize;
}
private Vector2Int? FindSpaceForObjectAnyDirection(int[,] simpleGrid, Vector2Int inventoryItemToInsert, bool isRotated)
{
var posOnGrid = FindSpaceForObject(simpleGrid, inventoryItemToInsert);
Debug.Log("2 posOnGrid: " + posOnGrid);
if (posOnGrid != null) return posOnGrid;
var lastRotateState = isRotated;
inventoryItemToInsert = RotateItem(inventoryItemToInsert);
Debug.Log("was rotate");
posOnGrid = FindSpaceForObject(simpleGrid, inventoryItemToInsert);
if (posOnGrid == null && lastRotateState != isRotated)
{
inventoryItemToInsert = RotateItem(inventoryItemToInsert);
}
return posOnGrid;
}
private Vector2Int? FindSpaceForObject(int[,] simpleGrid, Vector2Int itemToInsert)
{
int width = simpleGrid.GetLength(0);
int height = simpleGrid.GetLength(1);
Debug.Log("height: " + height);
Debug.Log("width: " + width);
var normalizedHeight = height - itemToInsert.y + 1;
var normalizedWidth = width - itemToInsert.x + 1;
for (var y = 0; y < normalizedHeight; y++)
{
for (var x = 0; x < normalizedWidth; x++)
{
if (OverlapCheck(simpleGrid, x, y, itemToInsert.x, itemToInsert.y))
{
return new Vector2Int(x, y);
}
}
}
return null;
}
private bool OverlapCheck(int[,] simpleGrid, int posX, int posY, int itemWidth, int itemHeight)
{
for (var x = 0; x < itemWidth; x++)
{
for (var y = 0; y < itemHeight; y++)
{
var inventoryItem = GetItem(simpleGrid, posX + x, posY + y);
if (inventoryItem == null) continue;
return false;
}
}
return true;
}
private static int? GetItem(int[,] simpleGrid, int x, int y)
{
try
{
return simpleGrid[x, y];
}
catch (IndexOutOfRangeException)
{
return null;
}
catch (NullReferenceException)
{
Logger.Error("InventoryItemsSlot not initialized, maybe you change something in the Editor and the reference turns null.");
return null;
}
}
Среди этих методов я вызываю только метод HasFreeSpace. Смысл этого кода такой, что я просто ищу есть ли свободное место в инвентаре. В инвентаре может быть несколько сеток(grids). Но у меня не всё работает корректно. Посмотри, может быть где-то здесь есть логическая ошибка. | 8dad284693aaa22f5e49b2cd19d79e7c | {
"intermediate": 0.26091569662094116,
"beginner": 0.5212029814720154,
"expert": 0.21788136661052704
} |
20,027 | Can you give me a list of data sets that were used to train you? | 79cfc1bef1398447618db2b7bbf1da23 | {
"intermediate": 0.23827064037322998,
"beginner": 0.15506505966186523,
"expert": 0.60666424036026
} |
20,028 | I have a list in B2 that has names of worksheets in my workbook.
Can you write me a VBA code that will go to the sheet when I select an item from the list | 6eb6e81d573a4e7e697bec8c9525841c | {
"intermediate": 0.39118966460227966,
"beginner": 0.33427757024765015,
"expert": 0.2745327651500702
} |
20,029 | Write a program using Euler's method simulating a bouncing ball that is confined to vertical motion. For the if-condition that identifies when the ball hits the wall or goes past the wall, modify the calculation by adding a linear interpolation. To do this, first assume the same equation of motion that would occur if the floor was not present. Then calculate the velocity that the ball will have just before the collision at 𝑦 = 0 using linear interpolation of a velocity
versus height. | bb9d99cc4c0eb14aad3f217e312fcdbe | {
"intermediate": 0.2738693654537201,
"beginner": 0.15077029168605804,
"expert": 0.5753603577613831
} |
20,030 | How do I check if String is a number in Kotlin? | 8ef38b3eb0c361442178b04828668816 | {
"intermediate": 0.7124415040016174,
"beginner": 0.13507169485092163,
"expert": 0.15248680114746094
} |
20,031 | I’m a complete beginner, can you explain the fundamentals of manipulating 3d objects in Codea? | 17c6c3a83475520046392edda3b1bd0e | {
"intermediate": 0.4187858998775482,
"beginner": 0.3430006802082062,
"expert": 0.2382134199142456
} |
20,032 | I want you to write a VBA code for a power point presentation about the Fault Finding Techniques. you are to fill in all the text with your own knowledge. | 10f393b5c989a5b8d4ac9ee7d8009757 | {
"intermediate": 0.23685647547245026,
"beginner": 0.4385208785533905,
"expert": 0.32462260127067566
} |
20,033 | Pretend you're making a video game. You want your player to be stopped by a wall, but instead he runs right through it. What component have you forgotten to add to the wall? | 382990a30f928ad54e232a61a257823c | {
"intermediate": 0.3333197236061096,
"beginner": 0.3335817754268646,
"expert": 0.33309847116470337
} |
20,034 | How to fix this code in python?
max_legent = 24
validate_key = 2877
simbol_key = {
'A': -90,
'B': 51,
'C': 40,
'D': -23,
'E': 59,
'R': -14,
'G': 69,
'H': 46,
'K': 75,
'J': -10,
'L': 60,
'Z': 26,
'V': 84,
'Y': 29 }
numbers_only = [
2,
5,
6,
7,
12,
13,
14,
18,
20,
23]
if len(a) != max_legent:
return False
count_key = 0
i = 0
i1 = 0
i2 = 0
i3 = 2
for x1 in a:
if x1.isnumeric():
if i not in numbers_only:
print('is not numeric or not in numbers only')
return False
count_key = count_key + round(int(x1) * i3)
elif x1 not in simbol_key:
print('x1 is not in numbers only')
return False
if i in numbers_only:
print('i is not in numbers only')
count_key = count_key + round(simbol_key[x1] * i3)
print(count_key)
i = i + 1
if i1 == 4:
i1 = 0
i2 = i2 + 1
i1 = i1 + 1
i3 = i3 + 1
if count_key == validate_key:
return True | 8bf5e4ea9430effbdeefb5d1230efc7b | {
"intermediate": 0.3453912138938904,
"beginner": 0.4436335861682892,
"expert": 0.21097522974014282
} |
20,035 | Write key generator in python from this code:
max_legent = 24
validate_key = 2877
simbol_key = {
'A': -90,
'B': 51,
'C': 40,
'D': -23,
'E': 59,
'R': -14,
'G': 69,
'H': 46,
'K': 75,
'J': -10,
'L': 60,
'Z': 26,
'V': 84,
'Y': 29
}
def get_value_from_symbol(s):
if s == 'A':
return -90
elif s == 'B':
return 51
elif s == 'C':
return 40
elif s == 'D':
return -23
elif s == 'E':
return 59
elif s == 'R':
return -14
elif s == 'G':
return 69
elif s == 'H':
return 46
elif s == 'K':
return 75
elif s == 'J':
return -10
elif s == 'L':
return 60
elif s == 'Z':
return 26
elif s == 'V':
return 84
elif s == 'Y':
return 29
else:
return 0
def key_check(a):
if len(a) != max_legent:
return False
count_key = 0
i1 = 0
i3 = 2
for x1 in a:
if x1.isnumeric():
print('x1 is ', x1)
count_key += round(int(x1) * i3)
print('count_key = ', str(count_key))
elif x1 not in simbol_key: #never be triggered
return False
count_key += round(get_value_from_symbol(x1) * i3)
i3 += 1
print('count_key = ', str(count_key))
print('i3 = ', str(i3))
if count_key == validate_key:
return True
return False | ca743c17b437d6c983f25da06af0df0d | {
"intermediate": 0.3766469657421112,
"beginner": 0.4079338610172272,
"expert": 0.21541914343833923
} |
20,036 | hello | 576ba4b223a6f3ee6eddc61e9814fe0c | {
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
} |
20,037 | <div v-html="'<p>Paragraph</p> {{ SourceId }}'"></div> | 38c10f9f22fcd7cfb641943d2616984a | {
"intermediate": 0.34365314245224,
"beginner": 0.25030210614204407,
"expert": 0.4060448110103607
} |
20,038 | Similar to this 'Interior.Color = RGB(255, 255, 0) ' Yellow', what is the VBA for Black and what is the VBA for Red | c52c9bde429306c0946838135e98158f | {
"intermediate": 0.4138723313808441,
"beginner": 0.3085826337337494,
"expert": 0.2775449752807617
} |
20,039 | Write me an abstract about decision tree and implementing them in python. | b3739a6fd25d070d24a8b991af8845f2 | {
"intermediate": 0.11211039125919342,
"beginner": 0.08945257216691971,
"expert": 0.7984369993209839
} |
20,040 | Have input files, previous and current.
Need to get their creation dates displayed.
Each time both file change, need to have their updated dates.
How ever there is challenge to get the Metadata, what are the other options to track both files date/time. | 5106e5791a1cdbf8591203eb0edfa2a9 | {
"intermediate": 0.493781715631485,
"beginner": 0.2526533007621765,
"expert": 0.2535650432109833
} |
20,041 | let cup: {[key: number]: CupItem} = {};
let history: CupHistory = {
ask: {},
bid: {},
};
let isSubscribed = false;
let pair = "";
let aggregation = 10;
let publisherTimeoutInMs = 40;
let publisherIntervalId: any = null;
let wsConnection: WebSocket|null = null;
let bestBidPrice = 0;
let bestAskPrice = 0;
let pricePrecision = 1;
let priceStep = 1;
let quantityPrecision = 1;
let maxVolume = 1;
let fixedMaxVolume = 0;
let volumeIsFixed = false;
let volumeAsDollars = false;
let cameras: {[key: string]: number} = {};
let cameraStep = 4;
let cameraIsBlocked = false;
let unblockCameraTimerId: any = null;
let port: MessagePort|null = null;
let rowsCount: number = 60;
let quantityDivider = 1;
let priceDivider = 1;
let diffModifier = 2;
let cameraGoToCenter = false;
const connectToWs = (callback: () => void) => {
if (wsConnection) {
callback();
return;
}
wsConnection = new WebSocket(`${process.env.NEXT_PUBLIC_RUST_WS_SERVER}`);
wsConnection.onopen = () => {
if (null !== wsConnection) {
callback();
}
};
wsConnection.onmessage = async(message: MessageEvent) => {
if (!message.data) return;
const data = JSON.parse(message.data);
if (!data?.commands || data.commands.length === 0) return;
const exchangeInitial = data?.commands?.find((item: any) => "ExchangeInitial" in item);
const update = data.commands.find((item: any) => "undefined" !== typeof item.Update);
if (exchangeInitial) {
cup = exchangeInitial.ExchangeInitial.rows;
pricePrecision = exchangeInitial.ExchangeInitial.params.pricePrecision;
priceStep = exchangeInitial.ExchangeInitial.params.priceStep;
quantityPrecision = exchangeInitial.ExchangeInitial.params.quantityPrecision;
quantityDivider = Math.pow(10, quantityPrecision);
priceDivider = Math.pow(10, pricePrecision);
}
if (update) {
const futuresUpdate = update.Update.find((item: any) => item?.pair?.substring(0, 2) === "FT");
if (pair === futuresUpdate.pair.substring(3)) {
bestBidPrice = futuresUpdate.spread.bid;
bestAskPrice = futuresUpdate.spread.ask;
if (cameras[pair] === 0) {
cameras[pair] = bestBidPrice;
}
Object.keys(futuresUpdate.history.ask)
// @ts-ignore
.forEach((key: number) => {
history.ask[key] = futuresUpdate.history.ask[key];
});
Object.keys(futuresUpdate.history.bid)
// @ts-ignore
.forEach((key: number) => {
history.bid[key] = futuresUpdate.history.bid[key];
});
Object
.keys(futuresUpdate.rows)
// @ts-ignore
.forEach((key: number) => {
cup[key] = futuresUpdate.rows[key];
});
}
}
};
};
const publish = () => {
if (!isSubscribed) return;
if (!cameras[pair]) {
cameras[pair] = 0;
}
const zoomedTickSize = priceStep * aggregation;
const centerCupPosition = parseInt((Math.ceil(bestAskPrice / zoomedTickSize) * zoomedTickSize).toFixed(0));
const rows: {[key: number]: CupItem} = {};
const historyRows: CupHistory = {ask: {}, bid: {}};
const timeModifier = parseInt((publisherTimeoutInMs / 40).toFixed(0));
diffModifier = Math.max(
diffModifier,
parseInt(((Math.abs(centerCupPosition - cameras[pair]) / zoomedTickSize) / (rowsCount / 2)).toFixed(0))
);
const cameraTopLime = centerCupPosition + rowsCount * .3 * zoomedTickSize;
const cameraBottomLine = centerCupPosition - rowsCount * .3 * zoomedTickSize;
const cameraIsVisible = cameras[pair] < cameraTopLime && cameras[pair] > cameraBottomLine;
if (!cameraIsVisible && cameras[pair] !== 0 && !cameraIsBlocked) {
cameraGoToCenter = true;
}
if (cameraGoToCenter) {
cameras[pair] = cameras[pair] > centerCupPosition
? Math.max(centerCupPosition, cameras[pair] - zoomedTickSize * timeModifier * diffModifier)
: Math.min(centerCupPosition, cameras[pair] + zoomedTickSize * timeModifier * diffModifier);
if (cameras[pair] === centerCupPosition) {
cameraGoToCenter = false;
}
} else {
diffModifier = 2;
}
const startMicroPrice = cameras[pair] + rowsCount / 2 * zoomedTickSize - zoomedTickSize;
for (let index = 0; index <= rowsCount; index++) {
const microPrice = startMicroPrice - index * zoomedTickSize;
if (microPrice < 0) continue;
rows[microPrice] = cup[microPrice] || {};
const bid = rows[microPrice]?.bid;
const ask = rows[microPrice]?.ask;
maxVolume = volumeAsDollars
? Math.max(maxVolume, (ask || bid || 0) / quantityDivider * (microPrice / priceDivider))
: Math.max(maxVolume, (ask || bid || 0) / quantityDivider);
}
const startHistoryMicroPrice = bestAskPrice + 10 * zoomedTickSize - zoomedTickSize;
for (let index = 0; index < 20; index++) {
const historyMicroPrice = startHistoryMicroPrice - index * zoomedTickSize;
if (historyMicroPrice < 0) continue;
if (index <= 10) {
historyRows.ask[historyMicroPrice] = history.ask[historyMicroPrice];
} else {
historyRows.bid[historyMicroPrice] = history.bid[historyMicroPrice];
}
}
port?.postMessage({type: "set_camera", value: cameras[pair]});
postMessage({
type: "update_cup",
cup: rows,
history: historyRows,
camera: cameras[pair],
aggregation,
bestBidPrice,
bestAskPrice,
pricePrecision,
priceStep,
quantityPrecision,
rowsCount,
maxVolume: volumeIsFixed
? fixedMaxVolume
: maxVolume,
volumeAsDollars,
});
};
const publisherStart = () => {
if (publisherIntervalId) {
clearInterval(publisherIntervalId);
}
publisherIntervalId = setInterval(publish, publisherTimeoutInMs);
};
const publisherStop = () => {
if (publisherIntervalId) {
clearInterval(publisherIntervalId);
}
};
if (data && data?.type === "subscribe") {
pair = data.pair;
aggregation = data.zoom;
isSubscribed = true;
cameras[pair] = 0;
maxVolume = 0;
cup = {};
publisherStart();
if (wsConnection?.readyState === 3) {
wsConnection = null;
}
connectToWs(() => {
if (null === wsConnection) return;
wsConnection.send(JSON.stringify({
"commands": [
{
commandType: "SUBSCRIBE_SYMBOL",
exchange: `FT:${pair}`,
aggregation: aggregation,
},
],
}));
});
}
придумай как можно оптимизировать | 2fe85103617b1ba9411c1835ce30fe25 | {
"intermediate": 0.30421197414398193,
"beginner": 0.5189691185951233,
"expert": 0.17681893706321716
} |
20,042 | give me html div imply in desktop an image on the left side and text on the right text and on the mobile screen the image on the top and text on the below the image: | f3a7678a5195ab1a16ee24ce146c63f0 | {
"intermediate": 0.38859128952026367,
"beginner": 0.3136252760887146,
"expert": 0.29778340458869934
} |
20,043 | How to write gui for hex editor in java | c0106d0172834c381d6eef709a19e350 | {
"intermediate": 0.38988637924194336,
"beginner": 0.4102753698825836,
"expert": 0.1998382955789566
} |
20,044 | On Firejail (in Debian), how does one undo the private-dev in a profile file in a local file? | ed1c0c2d8717a4c6691a8894913819f3 | {
"intermediate": 0.6003645658493042,
"beginner": 0.19267131388187408,
"expert": 0.20696412026882172
} |
20,045 | how to use multiple servers in json file for swagger openapi 3.0.3 | 22ca0740f4ea9a3d5a2cdb51c279469c | {
"intermediate": 0.6428746581077576,
"beginner": 0.14994415640830994,
"expert": 0.2071811705827713
} |
20,046 | How do I get all keys from inside the array in JS
var a ={'a':[{'b':'b'},{'c':'b'},{'d':'b'}]} | 9002db7724d74d3854489ab9abda74f3 | {
"intermediate": 0.6366996765136719,
"beginner": 0.16102612018585205,
"expert": 0.20227424800395966
} |
20,047 | const marginForOrders = 40;
const cupDrawer = {
clear: (ctx: CanvasRenderingContext2D, size: CanvasSize) => {
ctx.clearRect(0, 0, size.width, size.height);
},
draw: (
ctx: CanvasRenderingContext2D,
size: CanvasSize,
dpiScale: number,
bestBidPrice: number,
bestAskPrice: number,
maxVolume: number,
pricePrecision: number,
quantityPrecision: number,
priceStep: number,
zoom: number,
rowCount: number,
camera: number,
cellHeight: number,
zoomedBestMicroPrice: any,
darkMode: boolean,
volumeAsDollars: boolean,
cup: {[key: number]: CupItem},
history: CupHistory,
positions: Record<string, AccountPosition>,
openOrders: Record<string, AccountOpenOrder>,
symbol: string,
) => {
const zoomedTickSize = priceStep * zoom;
const startMicroPrice = camera + rowCount / 2 * zoomedTickSize - zoomedTickSize;
const quantityDivider = Math.pow(10, quantityPrecision);
const priceDivider = Math.pow(10, pricePrecision);
const fullWidthAsMarginForOrders = size.width - (marginForOrders * dpiScale);
for (let index = 0; index <= rowCount; index++) {
const microPrice = startMicroPrice - index * zoomedTickSize;
if (microPrice < 0) continue;
const item = cup[microPrice] || {};
let side = "undefined" !== typeof item?.bid
? "bid"
: "undefined" !== typeof item?.ask ? "ask" : "";
if ("" === side || (!item?.bid && !item.ask)) {
side = (microPrice >= (zoomedBestMicroPrice?.buy || zoomedBestMicroPrice?.sell || 0) ? "ask" : "bid");
}
const historyItemAsk = history.ask[microPrice] || {};
const historyItemBid = history.bid[microPrice] || {};
let historyItem: CupHistoryItem;
side === "ask"
? historyItem = historyItemAsk
: historyItem = historyItemBid;
const yPosition = cellHeight * index;
const quantity = volumeAsDollars
? ((side === "bid" ? item?.bid || 0 : item?.ask || 0) / quantityDivider) * (microPrice / priceDivider)
: (side === "bid" ? item?.bid || 0 : item?.ask || 0) / quantityDivider;
const isBestPrice = cupTools.isBestPrice(
side,
microPrice,
zoomedBestMicroPrice,
);
if ((microPrice / zoomedTickSize) % 5 === 0) {
ctx.beginPath();
ctx.strokeStyle = darkMode ? "#232425" : "#dddedf";
ctx.lineWidth = Math.max(1, dpiScale);
ctx.moveTo((marginForOrders * dpiScale), yPosition);
ctx.lineTo(size.width, yPosition);
ctx.stroke();
}
if (Object.keys(historyItem).length !== 0) {
cupDrawer.drawHistoryTcks(
ctx,
historyItem.tcks,
cupTools.microPriceToReal(microPrice, pricePrecision),
quantity,
side,
maxVolume,
isBestPrice,
yPosition,
cellHeight,
fullWidthAsMarginForOrders,
dpiScale,
quantityDivider,
darkMode
);
}
cupDrawer.drawCell(
ctx,
quantity,
side,
maxVolume,
isBestPrice,
yPosition,
cellHeight,
fullWidthAsMarginForOrders,
dpiScale,
darkMode
);
if (isBestPrice) {
cupDrawer.drawFill(
ctx,
quantity,
side,
maxVolume,
yPosition,
cellHeight,
fullWidthAsMarginForOrders,
dpiScale,
darkMode
);
}
cupDrawer.drawPrice(
ctx,
cupTools.microPriceToReal(microPrice, pricePrecision),
side,
isBestPrice,
yPosition,
cellHeight,
fullWidthAsMarginForOrders,
dpiScale,
darkMode
);
cupDrawer.drawQuantity(
ctx,
cupTools.abbreviateNumber(quantity),
side,
isBestPrice,
yPosition,
cellHeight,
fullWidthAsMarginForOrders,
dpiScale,
darkMode
);
}
if(openOrders) {
let filteredOrders = Object.values(openOrders).filter(o => o.symbol === symbol);
if(filteredOrders.length > 0) {
filteredOrders.forEach(order => {
return cupDrawer.drawOpenOrder(
ctx,
order,
Object.keys(cup),
priceDivider,
cellHeight,
dpiScale,
darkMode
);
});
}
}
if(positions && positions[symbol]) {
const position = positions[symbol];
cupDrawer.drawPosition(
ctx,
position,
priceDivider,
Object.keys(cup),
bestBidPrice,
bestAskPrice,
cellHeight,
size,
dpiScale,
darkMode
);
}
},
нужно оптимизировать код, сделай это, оптимизируй | ac99ff03b7fc591b3468670313df0412 | {
"intermediate": 0.34152379631996155,
"beginner": 0.3638863265514374,
"expert": 0.29458996653556824
} |
20,048 | would need to test post in rest api with real time data | 4271db581db835bef41deed9404be901 | {
"intermediate": 0.6814343333244324,
"beginner": 0.09676677733659744,
"expert": 0.221798837184906
} |
20,049 | IndexError: list index out of range | 1035d20e79acc3118e9bbe86d1ca73fc | {
"intermediate": 0.38017213344573975,
"beginner": 0.2803376615047455,
"expert": 0.33949014544487
} |
20,050 | привет у меня в Unity есть боты я бы хотел чтобы они получили 5 случайных, удаленных друг от друга точек на 100 юнитов на NavMesh и ходили в зацикленном виде по ним | 379de312def0a4e7dcf97497fedf6a51 | {
"intermediate": 0.41297483444213867,
"beginner": 0.22176826000213623,
"expert": 0.3652569651603699
} |
20,051 | When I used Python's plot function to draw a scatter plot of hundreds of thousands of points, the image was saved in EPS format, but the display speed was slow when opened. Is there any way to accelerate it | e3767317714347f4c3b7692141a9af3a | {
"intermediate": 0.580837607383728,
"beginner": 0.09313421696424484,
"expert": 0.32602816820144653
} |
20,052 | closed_inq is adf. when column inquiry_id value is 13 i want to modify the column searchable | 5a10779ea1e336278211a462e2a4e5ea | {
"intermediate": 0.3507436513900757,
"beginner": 0.2510690689086914,
"expert": 0.3981872797012329
} |
20,053 | Write a piece of code in C to output a 12KHz PWM signal using an EPS32 chip | a67555c55b843d99c27e1b0c6c78ab54 | {
"intermediate": 0.22688281536102295,
"beginner": 0.1597069799900055,
"expert": 0.613410234451294
} |
20,054 | in python i have a df. if column a is 13 i want columb be to be changed to 'yay' | 7350a480d67d2d6eef2bcf2763ed7d7c | {
"intermediate": 0.3718291223049164,
"beginner": 0.28239706158638,
"expert": 0.345773845911026
} |
20,055 | hello, how to convert telephone from "+12345" to "1(23) 45" using javascript | 3601191fdf4105718b06d938214f44f1 | {
"intermediate": 0.38047462701797485,
"beginner": 0.4041643440723419,
"expert": 0.21536101400852203
} |
20,056 | #include <iostream>
#include <math.h>
#include <algorithm>
using namespace std;
bool prime(int n)
{
for(int i=2;i<=sqrt(n);i++)
if(n%i==0)
return false;
return true;
}
int main()
{
string s;
cin>>s;
int x,y;
sort(s.begin(),s.end());
x=stoi(s);
reverse(s.begin(),s.end());
y=stoi(s);
if (prime(x) && prime(y))
cout<<"yes"<<endl;
else
cout <<"no"<<endl; в чём ошибка программы?
return 0;
} | 0906e3c4d4cb8f99c18569b7b1e727fa | {
"intermediate": 0.2155306339263916,
"beginner": 0.45433536171913147,
"expert": 0.3301340341567993
} |
20,057 | int compareRent(const void *a, const void *b) //比较租金
{
Venue *venueA = (Venue *)a;
Venue *venueB = (Venue *)b;
if(venueA->rent < venueB->rent) {
return -1;
} else if(venueA->rent > venueB->rent) {
return 1;
} else {
return 0;
}
}
void sortByRent(Venue venues[3][99], int numVenues[3]) //根据租金排序所有场地
{
system("cls");
int num = 0;
int i;
for (i = 0; i < 3; i++)
{
qsort(venues[0], numVenues[i], sizeof(Venue), compareRent);
}
int j = 0;
int m, n;
for(i=0;i<3;i++)
{
for(j = 0; j <numVenues[i]; j++)
{
printf("所在地区:%s\n", venues[i][j].area);
printf("场馆名:%s\n", venues[i][j].name_stadium);
printf("ID:%s\n", venues[i][j].id);
printf("场地名:%s\n", venues[i][j].name_venue);
printf("运动类型:%s\n", venues[i][j].sport_type);
printf("简述:%s\n", venues[i][j].description);
printf("年龄限制:%d ~ %d\n", venues[i][j].age_limit_min, venues[i][j].age_limit_max);
printf("租金:%.2f\n", venues[i][j].rent);
printf("\n\n");
}
}
}
这个函数在排序租金方面的存在问题,请问问题是什么? | a29920c32c8dd0f735a2789904078cab | {
"intermediate": 0.24252496659755707,
"beginner": 0.4779757559299469,
"expert": 0.27949926257133484
} |
20,058 | Define a function called password_gen(num) that takes an integer number num and produces a valid
password of length num. A valid password must
Be created at random
Have a length between 8 and 16 (both inclusive)
Consist of the following elements:
1. at least one lowercase letter
2. at least one uppercase letter
3. at least one number between 0 and 9 (both inclusive)
4. at least one special character in _$!? (they are underscore, dollar sign, exclamation
mark, and question mark)
Instructions
There is no additional requirement on the validity of the password.
If the argument value is not an integer number between 8 and 16, the function should produce
a warning message (see examples 1, 3, 6).
You may define and call other functions as part of password_gen(num).
Hint: The string module may come in handy. Import it and explore its methods. | 1fc0c85eedc2e6633112a7787be5d253 | {
"intermediate": 0.31046736240386963,
"beginner": 0.32456204295158386,
"expert": 0.3649706542491913
} |
20,059 | with Ilo version 5, how can I get the options send and set by the DHCP ipv6 ? | 94aefa23407f10672f4e99031c892fdd | {
"intermediate": 0.5594990849494934,
"beginner": 0.22581042349338531,
"expert": 0.2146904319524765
} |
20,060 | Привет помоги с рефакторингом
namespace Pedestrian
{
[RequireComponent(typeof(Animator))]
[RequireComponent(typeof(NavMeshAgent))]
public class PedestrianCharacter : MonoBehaviour
{
private List<Vector3> pointsPath = new List<Vector3>();
private CreatorPathBot creatorPath;
private Animator animator;
private NavMeshAgent navMeshAgent;
private Vector2 velocity;
private Vector2 smoothDeltaPosition;
private int currentTargetIndex;
private Coroutine coroutine;
public NavMeshAgent Agent { get => navMeshAgent; }
public void Ini()
{
animator = GetComponent<Animator>();
navMeshAgent = GetComponent<NavMeshAgent>();
animator.applyRootMotion = true;
navMeshAgent.updatePosition = false;
navMeshAgent.updateRotation = true;
creatorPath = new CreatorPathBot();
pointsPath.AddRange(creatorPath.GetPathBot());
if (coroutine == null)
{
coroutine = StartCoroutine(MoveToPoints());
}
}
private void OnAnimatorMove()
{
var rootPosition = animator.rootPosition;
rootPosition.y = navMeshAgent.nextPosition.y;
transform.position = rootPosition;
navMeshAgent.nextPosition = rootPosition;
}
private void Update()
{
UpdateAnimator();
navMeshAgent.SetDestination(pointsPath[currentTargetIndex]);
}
private void UpdateAnimator()
{
var woridDeltaPosition = navMeshAgent.nextPosition - transform.position;
woridDeltaPosition.y = 0;
var deltaX = Vector3.Dot(transform.right, woridDeltaPosition);
var deltaY = Vector3.Dot(transform.forward, woridDeltaPosition);
var deltaPosition = new Vector2(deltaX,deltaY);
var smooth = Mathf.Min(1, Time.deltaTime / 0.1f);
smoothDeltaPosition = Vector2.Lerp(smoothDeltaPosition,deltaPosition,smooth);
velocity = smoothDeltaPosition / Time.deltaTime;
if (navMeshAgent.remainingDistance <= navMeshAgent.stoppingDistance)
{
velocity = Vector2.Lerp(
Vector2.zero,
velocity,
navMeshAgent.remainingDistance / navMeshAgent.stoppingDistance);
}
var shouldMove = velocity.magnitude > 0.5f
&& navMeshAgent.remainingDistance > navMeshAgent.stoppingDistance;
animator.SetFloat("speedPercent", velocity.magnitude);
animator.SetBool("Move", shouldMove);
var deltaMagnitude = woridDeltaPosition.magnitude;
if (deltaMagnitude> navMeshAgent.radius/2f)
{
transform.position = Vector3.Lerp(animator.rootPosition, navMeshAgent.nextPosition,smooth);
}
}
private IEnumerator MoveToPoints()
{
while(true)
{
yield return new WaitForSeconds(1f);
if (Vector3.SqrMagnitude(transform.position - new Vector3(pointsPath[currentTargetIndex].x, 0, pointsPath[currentTargetIndex].z)) < 1)
{
currentTargetIndex = (currentTargetIndex + 1) % pointsPath.Count;
navMeshAgent.SetDestination(pointsPath[currentTargetIndex]);
}
}
}
}
} | bd70fccb4f7ef6e50a044ebe8a25af09 | {
"intermediate": 0.26672983169555664,
"beginner": 0.5652329325675964,
"expert": 0.16803723573684692
} |
20,061 | Write a program to crawl the questions and solutions on leetcode and save them to the local D drive in the form of Markdown text. Create a front-end page, enter filter conditions, and start crawling questions. | 070923d3f92b0c554fb9c664b222fa1a | {
"intermediate": 0.238073468208313,
"beginner": 0.380896657705307,
"expert": 0.3810299038887024
} |
20,062 | Hello, how do I create my own webserver in c#? | 2f1bf55f9ceebd6626da7c9823496bce | {
"intermediate": 0.6440362334251404,
"beginner": 0.17917311191558838,
"expert": 0.17679063975811005
} |
20,063 | create a graph usuing Matplotlib in python showing these counties [China, Russia, USA] with these variables [24,10,34] | 90ee18a3ec266339e5e9c9e4896d5b51 | {
"intermediate": 0.4244188666343689,
"beginner": 0.27459943294525146,
"expert": 0.300981730222702
} |
20,064 | HttpListener server = new HttpListener(); // this is the http server
server.Prefixes.Add("http://localhost:8080/");
server.Start(); // and start the server
Console.WriteLine("Server started...");
while (true)
{
HttpListenerContext context = server.GetContext();
HttpListenerResponse response = context.Response;
Console.WriteLine("URL: {0}", context.Request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", context.Request.RawUrl);
byte[] buffer = System.IO.File.ReadAllBytes("index.html");
response.ContentLength64 = buffer.Length;
Stream st = response.OutputStream;
st.Write(buffer, 0, buffer.Length);
context.Response.Close();
}
i have this code, but it only returns me html page without css and js, which is used in my html file, how do I make it work so when I load the page, all css styles and scripts work? | d9770b5959117cde1b5f5e7d326eaa7f | {
"intermediate": 0.5558764338493347,
"beginner": 0.28016555309295654,
"expert": 0.16395798325538635
} |
20,065 | c# how to use httplistener prefixes add? why is there URI requiered? | 598625e29f8bc17cec04e47ca4dfb887 | {
"intermediate": 0.6253696084022522,
"beginner": 0.20939938724040985,
"expert": 0.16523100435733795
} |
20,066 | {state.currentMarker.image_url.split(",").length > 1 ?
<Carousel >
{state.currentMarker.image_url.split(",").map((value, index) => (
<Carousel.Item sx={style}>
<img
className="d-block w-100"
src={value}
alt={value}
height="400"
/>
</Carousel.Item>
))}
</Carousel>
: null} in lên anh giúp tôi chữ tcmap.vn để khỏi người khác lấy ảnh | a2002624ad4634a83adb8e4e5737be12 | {
"intermediate": 0.32237115502357483,
"beginner": 0.49179160594940186,
"expert": 0.18583723902702332
} |
20,067 | import telebot
from telebot import types
TOKEN = '6668161332:AAGoDic9hlPdLWsob0M3xPH-wOz8ngFOPK0'
bot = telebot.TeleBot(TOKEN)
zaproses = 10
@bot.message_handler(commands=['start'])
def menu(message):
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton("Профиль", callback_data='profile'))
bot.send_message(message.chat.id, '<b>Привет!</b>', parse_mode='html', reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def handle_query(call):
global zaproses
if call.data == 'profile':
markup2 = types.InlineKeyboardMarkup()
markup2.add(types.InlineKeyboardButton("Меню", callback_data='menu'))
bot.send_message(call.message.chat.id, f'Это ваш профиль, ваш ID: {call.from_user.id}<br><br>У вас {zaproses} Запросов<br><br>Вы КРУт', parse_mode='html', reply_markup=markup2)
elif call.data == 'menu':
menu(call.message)
bot.polling(none_stop=True)
как сделать чтобы бот писал в Профиле количество запросов (zaproses, переменная такая) | 145ca3f13d03971d859b6ee57eea3afb | {
"intermediate": 0.340828001499176,
"beginner": 0.3676615357398987,
"expert": 0.29151055216789246
} |
20,068 | import telebot
from telebot import types
TOKEN = ‘6668161332:AAGoDic9hlPdLWsob0M3xPH-wOz8ngFOPK0’
bot = telebot.TeleBot(TOKEN)
zaproses = 10
@bot.message_handler(commands=[‘start’])
def menu(message):
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton(“Профиль”, callback_data=‘profile’))
bot.send_message(message.chat.id, ‘<b>Привет!</b>’, parse_mode=‘html’, reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def handle_query(call):
global zaproses
if call.data == ‘profile’:
markup2 = types.InlineKeyboardMarkup()
markup2.add(types.InlineKeyboardButton(“Меню”, callback_data=‘menu’))
bot.send_message(call.message.chat.id, f’Это ваш профиль, ваш ID: {call.from_user.id}<br><br>У вас {zaproses} Запросов<br><br>Вы КРУт’, parse_mode=‘html’, reply_markup=markup2)
elif call.data == ‘menu’:
menu(call.message)
bot.polling(none_stop=True)
как сделать чтобы бот писал в Профиле количество валюты zaproses (zaproses, переменная такая) | e2d071136c0c0e6ac81af3682ac9838d | {
"intermediate": 0.3473365604877472,
"beginner": 0.3354611396789551,
"expert": 0.31720229983329773
} |
20,069 | i have an error in the folowing code, can you find it? :
[gcode_macro BED_MESH]
gcode:
{% set svv = printer.save_variables.variables %}
{% set sheet_name = svv.build_sheet installed %}
{% set filament_installed_t0 = svv.filament_installed_t0 %}
{% set sheet_key = (svv["build_sheet installed"] | string) %}
{% set sheet = (svv[sheet_key] | default(None)) %}
{% set extruders = [] %}
{% for name in printer %}
{% if name.startswith("extruder") %}
{% set _ = extruders.append(name) %}
{% endif %}
{% endfor %}
{% set num_tools = (extruders | count) %}
{% if num_tools == 0 %}
{action_respond_info("No Extruders found in this printer!")}
{% elif num_tools == 1 %}
{% set filament_key = (svv["filament_installed_t0"] | default(None)) %}
{% set filament = (None if filament_key == None else svv[filament_key]) %}
{% if filament == None %}
{action_respond_info("No Filament Set")}
{% else %}
{action_respond_info("Filament: %s - %.0fC/%.0fC" % (filament.name, filament.extruder, filament.bed))}
{% endif %}
{% if sheet %}
{action_respond_info("Greating bed mesh for build sheet: %s" % (sheet.name))}
G28
M117 Heating bed...
M190 S{filament.bed}}
TEMPERATURE_WAIT SENSOR=heater_bed MINIMUM={filament.bed}
M117 Bed calibrate...
G28 Z
M117 Bed mesh...
BED_MESH_CALIBRATE
G0 X1 Y115 Z50 F10000
BED_MESH_PROFILE save={sheet_name}
BED_MESH_PROFILE load={sheet_name}
{% else %}
{action_respond_info("No buildplate selected, using default for mesh") }
BED_MESH_PROFILE save=default
BED_MESH_PROFILE load=default
{% endif %} | c1a37a5d4b64543b347e54b416a08048 | {
"intermediate": 0.38744866847991943,
"beginner": 0.2861032783985138,
"expert": 0.32644811272621155
} |
20,070 | У меня есть такой метод на Unity. Он удаляет прошлое положение на сетке. Сам метод работает хорошо, но я только что добавил условие что если предмет в сетке перевернули, то он из вертикального положения переходит в горизонтальное. Проблема в том что во время вращения удаление из прошлой позиции работает плохо. Подумай очень сильно и глубоко проанализируй код и найди ошибку.
public bool RemoveFromGrid(GameEntity inventoryItemEntity, GameEntity pickupItemEntity)
{
if (!pickupItemEntity.hasItem)
{
Logger.Info("Entity id: " + pickupItemEntity.id.Value + " has not ItemComponent");
return false;
}
if (!inventoryItemEntity.hasInventoryGrid)
{
Logger.Info("Entity id: " + inventoryItemEntity.id.Value + " has not InventoryGridComponent");
return false;
}
itemCatalogService.TryGetItemConfig(pickupItemEntity.item.UID, out IInventoryItemConfig pickupInventoryItemConfig);
Vector2Int pickupItemEntitySize = pickupInventoryItemConfig.InventorySize;
if (pickupItemEntity.isInventoryRotated)
{
pickupItemEntitySize = RotateItem(pickupItemEntitySize);
}
Vector2Int onGridPosition = pickupItemEntity.inventoryGridPosition.Position;
int onGridIndex = pickupItemEntity.inventoryGridPosition.IndexGrid;
int[,] grid = inventoryItemEntity.inventoryGrid.Value[onGridIndex];
for (int ix = 0; ix < pickupItemEntitySize.x; ix++)
{
for (int iy = 0; iy < pickupItemEntitySize.y; iy++)
{
grid[onGridPosition.x + ix, onGridPosition.y + iy] = -1;
}
}
return true;
} | 0ef0db4c39d38ef632610069e859f476 | {
"intermediate": 0.31539633870124817,
"beginner": 0.4154385030269623,
"expert": 0.26916518807411194
} |
20,071 | import telebot
from telebot import types
TOKEN = '6668161332:AAGoDic9hlPdLWsob0M3xPH-wOz8ngFOPK0'
bot = telebot.TeleBot(TOKEN)
zaproses = 10
subscribe = "Нет подписки"
@bot.message_handler(commands=['start'])
def menu(message):
markup = types.InlineKeyboardMarkup()
markup.add(types.InlineKeyboardButton("Профиль", callback_data='menu'))
bot.send_message(message.chat.id, '<b>Меню\nВыберите пункт.</b>', parse_mode='html', reply_markup=markup)
@bot.callback_query_handler(func=lambda call: True)
def shop(call):
shopback = types.InlineKeyboardMarkup()
shopback.add(types.InlineKeyboardButton("", callback_data='menu'))
bot.send_message(call.message.chat.id, '<b>Магазин:\nТекст 1:\n</b> 100 RUB \n Текст 2:\n</b> 250 RUB\nТекст 3:\n</b> 400 RUB \n Текст 4:\n</b> 500 RUB', parse_mode='html', reply_markup=shopback)
@bot.callback_query_handler(func=lambda call: True)
def handle_query(call):
global zaproses
global subscribe
if call.data == 'profile':
markupadds = types.InlineKeyboardMarkup()
menub = types.InlineKeyboardButton("🔙 Назад", callback_data='menu')
shopb = types.InlineKeyboardButton("💷 Пополнить 💷", callback_data='shop')
markupadds.add(menub, shopb)
bot.send_message(call.message.chat.id, f'Это ваш профиль,\nваш ID: {call.from_user.id}\nУ вас: {zaproses} Запросов\nВаши подписки: {subscribe}', parse_mode='html', reply_markup=markupadds)
elif call.data == 'menu':
menu(call.message)
bot.polling(none_stop=True) <br> <br> бот выдает следующую ошибку <br> "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Scripts\python.exe" "C:\Users\Dell alienware\PycharmProjects\BotTG\main.py"
2023-09-14 19:27:16,332 (__init__.py:1083 MainThread) ERROR - TeleBot: "Threaded polling exception: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: can't parse entities: Unexpected end tag at byte offset 64"
2023-09-14 19:27:16,333 (__init__.py:1085 MainThread) ERROR - TeleBot: "Exception traceback:
Traceback (most recent call last):
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\__init__.py", line 1074, in __threaded_polling
self.worker_pool.raise_exceptions()
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\util.py", line 147, in raise_exceptions
raise self.exception_info
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\util.py", line 90, in run
task(*args, **kwargs)
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\__init__.py", line 6788, in _run_middlewares_and_handler
result = handler['function'](message)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell alienware\PycharmProjects\BotTG\main.py", line 21, in shop
bot.send_message(call.message.chat.id, '<b>Магазин:\nТекст 1:\n</b> 100 RUB \n Текст 2:\n</b> 250 RUB\nТекст 3:\n</b> 400 RUB \n Текст 4:\n</b> 500 RUB', parse_mode='html', reply_markup=shopback)
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\__init__.py", line 1549, in send_message
apihelper.send_message(
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\apihelper.py", line 264, in send_message
return _make_request(token, method_url, params=payload, method='post')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\apihelper.py", line 162, in _make_request
json_result = _check_result(method_name, result)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Dell alienware\PycharmProjects\BotTG\venv\Lib\site-packages\telebot\apihelper.py", line 189, in _check_result
raise ApiTelegramException(method_name, result, result_json)
telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: can't parse entities: Unexpected end tag at byte offset 64
" | 60a599de653664f1f7793ab9f2f63a8c | {
"intermediate": 0.3842610716819763,
"beginner": 0.4481489956378937,
"expert": 0.16758988797664642
} |
20,072 | Сообщение 2714, уровень 16, состояние 6, строка 2
В базе данных уже существует объект с именем "#IOUT". исправь ошибку в скрипте IF OBJECT_ID('#IOUT') IS NOT NULL DROP TABLE #IOUT
select I.MNEMOCODE INTO #IOUT from INVOICE_OUT I
where I.DATE>CONVERT(DATETIME,'2023-08-30',121)
DECLARE @DOC VARCHAR(50)
WHILE EXISTS (SELECT 1 FROM #IOUT)
BEGIN
SET @DOC = (SELECT TOP 1 MNEMOCODE FROM #IOUT)
DELETE FROM KIZ_MOVE WHERE ID_KIZ_ITEM_GLOBAL IN (SELECT ID_KIZ_ITEM_GLOBAL FROM KIZ_ITEM WHERE ID_KIZ_DOC_GLOBAL IN (SELECT ID_KIZ_DOC_GLOBAL FROM KIZ_DOC WHERE DOC_NUM = @DOC))
DELETE FROM KIZ_ITEM WHERE ID_KIZ_DOC_GLOBAL IN
(SELECT ID_KIZ_DOC_GLOBAL FROM KIZ_DOC WHERE DOC_NUM = @DOC)
DELETE FROM KIZ_DOC WHERE DOC_NUM = @DOC
DELETE FROM #IOUT WHERE MNEMOCODE = @DOC
END | 2f8cba3f7bf8bfcfafa6c8ab7ae542fc | {
"intermediate": 0.4207238256931305,
"beginner": 0.33002379536628723,
"expert": 0.24925237894058228
} |
20,073 | can you wright me an acknowledgment letter of PhD thesis? | 5d133c90d4d02ab530b8baad212535d6 | {
"intermediate": 0.31314826011657715,
"beginner": 0.26029345393180847,
"expert": 0.4265582859516144
} |
20,074 | In the VBA code below, how can I add the the Target.Offset(0, -3).Value to the MsgBox so that it reads;
"PO details copied to Word Document" & vbNewLine &
"Please Add PO: (Target.Offset(0, -3).Value) into Comment Cell"
If Target.Cells.CountLarge > 1 Then Exit Sub 'only one cell at a time
If Not Intersect(Target, Range("J2:J2001")) Is Nothing And Target.Value = "NOTIFY CONTRACTOR" Then 'Check for J2:J2001
If Target.Row > 1 Then
'USED TO OPEN WORD DOC FOR TASK REQUEST - DO NOT DELETE
'Module9.sheetJobRequestActive = True 'THIS SET THE GLOBAL VARIABLE TO - TRUE - because the code checks for TRUE the code runs
'If Not Module9.sheetJobRequestActive Then Exit Sub ' if TRUE it allows the module to run
Dim wordApp As Object
Dim doc As Object
Dim WshShell As Object
Set wordApp = CreateObject("Word.Application")
Set doc = wordApp.Documents.Open("G:\Shared drives\Swan School Site Premises\PREMISES MANAGEMENT\SERVICE PROVIDERS\zzzz ServProvDocs\POissued.docm")
wordApp.Visible = True
doc.Activate
Set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate wordApp.Caption
Application.Wait (Now + TimeValue("0:00:03"))
Dim wsjrw As Worksheet
Dim wscfw As Worksheet
Dim activeRow As Long
Set wsjrw = Worksheets("PORDER")
activeRow = ActiveCell.Row
Set wscfw = Worksheets(Cells(activeRow, 11).Value)
Cells(activeRow, 12).Value = "Sent"
Cells(activeRow, 10).Calculate
wscfw.Activate
MsgBox ("PO details copied to Word Documnet" & vbNewLine & "" & vbNewLine & "Please Add PO:123 number into Comment Cell" & vbNewLine & "" & vbNewLine & "Comments Can Also Be Added")
End If
End If | b25c1eff5de2e43649c68383ac1ed48c | {
"intermediate": 0.46545344591140747,
"beginner": 0.36891379952430725,
"expert": 0.1656326949596405
} |
20,075 | here my code:
import pandas as pd
from matplotlib import pyplot as plt
name = ['Всех акций\n MOEX', 'Топ 50\nпо капитализации', 'Топ 10\n по капитализации','Доллара']
price = [200, 140, 80, 30]
bars_color = ['pink','pink','pink','pink']
# Figure Size
fig, ax = plt.subplots(figsize=(16, 9))
# Add x, y gridlines
ax.grid(visible=True, color='grey',
linestyle='-.', linewidth=0.5,
alpha=0.2, zorder=0)
# Horizontal Bar Plot
ax.barh(name, price,color=bars_color, alpha=1.0, zorder=1)
# Remove axes splines
for s in ['top', 'bottom', 'left', 'right']:
ax.spines[s].set_visible(False)
# Remove x, y Ticks
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
# Add padding between axes and labels
ax.xaxis.set_tick_params(pad=2)
ax.yaxis.set_tick_params(pad=5)
# Show top values
ax.invert_yaxis()
# # Add annotation to bars
for i in ax.patches:
plt.text(i.get_width() + 2, i.get_y() + 0.5,
'+'+ str(round(i.get_width(), 2)) + '%',
fontsize=30, #fontweight='bold',
color='green')
# Add Plot Title
ax.set_title('Return YTD',
loc='left', fontweight='bold', fontsize=66, color=(0.37,0.15, 0.19))
# Set size of the country names
plt.tick_params(axis='y', labelsize=15)
plt.subplots_adjust(left=0.168, bottom=0.387, right=0.789, top=0.789, wspace=0.364, hspace=None)
# Show Plot
plt.show()
why are gridlines above the bars? | 4520f7b0ae5d09b27f88059678ffb621 | {
"intermediate": 0.5156360268592834,
"beginner": 0.2657911777496338,
"expert": 0.21857279539108276
} |
20,076 | (I agree with Dr. T, that we will still need mechanics to work on the flying cars and the skills required to maintain them. This can be seen even today with our current newer cars, when it comes to tuning a new car, a lot of programming is required in order to tweak the fuel/air mixture and the timing of the engine, it is not as simple as getting a wrench or screwdriver to tune a car anymore. As things have become more sophisticated, people must learn new skills in order to continue making progress, and this wouldn't be any different with flying cars, we would still need people to work on the physical engines themselves, but also to tweak with the computers inside the engine.
I think that technology and the future of the workforce will certainly change, as technology becomes more sophisticated, certain professions will become obsolete, and others will increase in demand. I believe that the programming experience that we are gaining will help us in the future to help with this transition, as technology starts to advance, there will still be a need for people to monitor these programs when errors arise. One area that has become affected by the progression of technology is Data Science, as machine learning has become more advanced and AI is becoming more sophisticated, the utilization of AI is growing more and more. This however is not a bad thing, this allows people to do more in a smaller amount of time, leading to projects getting completed in a shorter time frame. ) Respond to this post | 4ff557ac6af9fb8782cb190e55dc1647 | {
"intermediate": 0.3083018660545349,
"beginner": 0.25265535712242126,
"expert": 0.43904274702072144
} |
20,077 | Write a console application for the following.
*· Scenario:
Complete the following C++ program by including the definition for the function named weeklyPay that returns weekly pay.
The function has the formal parameter hours to pass the value of the number of hours worked in a week and the formal, parameter rate to pass the value of the hourly rate, the name should be passed as a third parameter, the fourth parameter of type (int, where 1=”full-time”, 2=”part-time”).
Additional specifications
*Output a dollar sign in from to each weekly pay
*Set precision to 2 decimal places
*Assume 12% FIT rate where hourly rate is less than $15, and 15% otherwise (FIT applies to taxable income) //Unit 5 Point of Clarification below
*Assume full 6.2% Social Security rate
*Assume 1.45% Medicare Rate
*If and only if a full time employee, Assume $17.00 for dental (pre-tax) //See Unit 5 Point of Clarification below
*If and only if a full time employee, Assume $77.00 employee (pre-tax) contribution toward retirement //Unit 5 Point of Clarification below
*Assume overtime pay a 2 times time's regular rate beyond 40 clockedHours for fulltime employees only
*Output to the screen the employees name IN-ALL-CAPS using the appropriate Java built-in function, weekly pay in $, and whether or not he/she is a full time or parttime employee.
*Highlight the employee’s name in color, and leave the rest of the text in black/white. (IDE Permitting) | 0a1ddace37db41dd1e0cc4ae363a2c65 | {
"intermediate": 0.3745974004268646,
"beginner": 0.35984429717063904,
"expert": 0.2655583322048187
} |
20,078 | i'm trying to make a sort of demo casino website, not with real money but just for testing probabilities with fake money.
What language should I make the back end in?
the part responsible for actually calculating your wins, generating random numbers, etc.
I am currently learning c++, am good at python, meh at javascript/nodejs, and starting to forget go.
what do you think I should choose? | 79c9da8e1c4174d338f63811516afd3c | {
"intermediate": 0.3479257822036743,
"beginner": 0.4367077946662903,
"expert": 0.21536648273468018
} |
20,079 | in python I have a list and I want you to count how many each entry appears in the list and neatly print them out.
import random
class Limbo:
def get_multiplier(seed):
random.seed(seed)
num = random.randint(1,6)
return num
limbo = Limbo
multipliers = []
for i in range(500000):
multipliers.append(limbo.get_multiplier(random.random()))
print(multipliers) | db339f51b30c8e574b0b561fa2db3637 | {
"intermediate": 0.3285912573337555,
"beginner": 0.4835584759712219,
"expert": 0.1878502517938614
} |
20,080 | create a project with html, css and javascript, create a web calculator | d350b072dc3186cecae5301f2db76662 | {
"intermediate": 0.4887027442455292,
"beginner": 0.23433901369571686,
"expert": 0.2769581973552704
} |
20,081 | Create me an HTML code with excellent edges that contains an image attachment tool and a captcha tool | 1e567ec5d2ce64204acd9d5898a806e1 | {
"intermediate": 0.49515870213508606,
"beginner": 0.17443162202835083,
"expert": 0.3304097056388855
} |
20,082 | act as a react native developer and build a react native component that receives an array of urls and based on this array it creates rows of 4 images per row, this images should be rounded and tappable. | 90749d53e56f0a18bbe8701da54192fd | {
"intermediate": 0.5320687294006348,
"beginner": 0.18807142972946167,
"expert": 0.27985984086990356
} |
20,083 | in kdenlive when changing audio sample rate after done rendering my video file has stuttering in it how to fix | 84ba48083aa91838b31bc42fa78fe143 | {
"intermediate": 0.4395918548107147,
"beginner": 0.21390247344970703,
"expert": 0.34650567173957825
} |
20,084 | I want you to act as a scientific Chinese-English translator, I will provide you with some paragraphs in one language and your task is to accurately and academically translate the paragraphs only into the other language. Do not repeat the original provided paragraphs after translation. You should use artificial itntelligence tools, such as natural language processing, and rhetorical knowledge and experience about effective writing techniques to reply. I will give you my paragraphs as follows. | 89aa01add51974482e596ea66487d5f9 | {
"intermediate": 0.2976062595844269,
"beginner": 0.26592522859573364,
"expert": 0.43646854162216187
} |
20,085 | Read from the text file “pi_million_digits.txt”, which includes the first million digits of pi. Write
a program to find out all six-digit consecutive numbers (such as 123456, 345678, and 789012) in
pi. Store these numbers as strings in a list called sixdigit. | e8172f409962131e60077d2a066ccf78 | {
"intermediate": 0.38313543796539307,
"beginner": 0.2583509385585785,
"expert": 0.35851359367370605
} |
20,086 | give me a python code for car race game | 453d09f34bae3c2ce20ba9086a234eb0 | {
"intermediate": 0.382202684879303,
"beginner": 0.24410051107406616,
"expert": 0.37369680404663086
} |
20,087 | 下面是修改后的代码,使用connect函数将UDP套接字连接到固定的IP地址和端口:
#include <sys/epoll.h>
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
int main() {
// 创建UDP套接字
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1) {
std::cerr << “Failed to create socket” << std::endl;
return 1;
}
// 将UDP套接字连接到固定的IP地址和端口
struct sockaddr_in serverAddr{};
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(2000);
serverAddr.sin_addr.s_addr = inet_addr(“192.178.111.1”);
if (connect(sockfd, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) == -1) {
std::cerr << “Failed to connect socket” << std::endl;
close(sockfd);
return 1;
}
// 创建epoll实例
int epollfd = epoll_create(1);
if (epollfd == -1) {
std::cerr << “Failed to create epoll instance” << std::endl;
close(sockfd);
return 1;
}
// 添加套接字到epoll
struct epoll_event ev{};
ev.events = EPOLLIN | EPOLLOUT; // 监听可读和可写事件
ev.data.fd = sockfd;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, sockfd, &ev) == -1) {
std::cerr << “Failed to add socket to epoll” << std::endl;
close(epollfd);
close(sockfd);
return 1;
}
while (true) {
// 等待事件发生
struct epoll_event events[1];
int numEvents = epoll_wait(epollfd, events, 1, -1);
if (numEvents == -1) {
std::cerr << “Error in epoll_wait” << std::endl;
break;
}
// 检查每个返回的事件
for (int i = 0; i < numEvents; ++i) {
int fd = events[i].data.fd;
if (events[i].events & EPOLLIN) {
// 套接字可读,接收数据
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
ssize_t bytesRead = recv(fd, buffer, sizeof(buffer) - 1, 0);
if (bytesRead == -1) {
std::cerr << “Failed to receive data” << std::endl;
break;
}
std::cout << "Received data: " << buffer << std::endl;
}
if (events[i].events & EPOLLOUT) {
// 套接字可写,发送数据
std::string sendData = “Hello, server!”;
ssize_t bytesSent = send(fd, sendData.c_str(), sendData.size(), 0);
if (bytesSent == -1) {
std::cerr << “Failed to send data” << std::endl;
break;
}
std::cout << "Sent data: " << sendData << std::endl;
// 取消对可写事件的监视
struct epoll_event modEv{};
modEv.events = EPOLLIN;
modEv.data.fd = fd;
if (epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &modEv) == -1) {
std::cerr << “Failed to modify epoll event” << std::endl;
break;
}
}
}
}
// 关闭套接字和epoll实例
close(epollfd);
close(sockfd);
return 0;
}
在代码中,添加了以下几行来连接到固定的IP地址和端口:
// 将UDP套接字连接到固定的IP地址和端口
struct sockaddr_in serverAddr{};
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(2000);
serverAddr.sin_addr.s_addr = inet_addr(“192.178.111.1”);
if (connect(sockfd, (struct sockaddr *) &serverAddr, sizeof(serverAddr)) == -1) {
std::cerr << “Failed to connect socket” << std::endl;
close(sockfd);
return 1;
}
这样,UDP套接字便会发送和接收数据到指定的IP地址(192.178.111.1)和端口(2000)了。请注意,UDP是无连接的协议,所以对于UDP套接字,connect函数实际上只会设置一个默认的目标地址,但并不实际建立连接。
以上你是上次给我的代码,我想给成server地址为INADDR_ANY,client的IP地址(192.178.111.1)和端口(2000) | f90726017e5cf21fdd36aceb25f2a2d5 | {
"intermediate": 0.328229695558548,
"beginner": 0.4616497755050659,
"expert": 0.2101205438375473
} |
20,088 | Read from the text file “pi_million_digits.txt”, which includes the first million digits of pi. Write
a program to find out all six-digit consecutive numbers (such as 123456, 345678, and 789012) in
pi. Store these numbers as strings in a list called sixdigit.
In two separate cells, execute the following codes and show your outputs. | f6260c7e45bb4d60e11ab619c191193f | {
"intermediate": 0.38111382722854614,
"beginner": 0.2544637620449066,
"expert": 0.36442238092422485
} |
20,089 | write me a VBA code for a PowerPoint presentation about Emotional intelligence effects in higher education. only 10 slides mentioning accredited references. | deaff11ebd251af26aefb970af6bdc45 | {
"intermediate": 0.17906679213047028,
"beginner": 0.6075865626335144,
"expert": 0.2133466601371765
} |
20,090 | Hi - in R Shiny one can make boxes in a dashboard like this (https://rstudio.github.io/shinydashboard/structure.html):
box(
title = "Histogram", status = "primary", solidHeader = TRUE,
collapsible = TRUE,
plotOutput("plot3", height = 250)
),
box(
title = "Inputs", status = "warning", solidHeader = TRUE,
"Box content here", br(), "More box content",
sliderInput("slider", "Slider input:", 1, 100, 50),
textInput("text", "Text input:")
)
Do you know what the equivalent code is in Python? | 6dcc32ed1cae1ad9f290f815b6fa0385 | {
"intermediate": 0.39700576663017273,
"beginner": 0.4748415946960449,
"expert": 0.12815259397029877
} |
20,091 | how to make a dictionary values sorted in python | bcc9d5bd3f60e8a97566a8167807cf3c | {
"intermediate": 0.31727829575538635,
"beginner": 0.182490274310112,
"expert": 0.5002313852310181
} |
20,092 | In Java are primitive fields instantiated to a default value, but a primitive variable in a method is not? If it's not instantiated to a default value, what value does it have? Null or what? | b159f8e7f30c05fa6585a63df6638086 | {
"intermediate": 0.5981848239898682,
"beginner": 0.242447167634964,
"expert": 0.15936796367168427
} |
20,093 | package com.mycompany.myapp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class ClientCode {
public static void main(String[] args) throws Exception {
// Transaction tx = null;
try/*( Session session = HibernateUtil.getSessionFactory().openSession() )*/ {
// tx = session.beginTransaction();
// FOR APPLE
Food apple = new Apple(8.9);
FoodDao.getInstance().save(apple);
// // FOR BREAD LOAF
ShippingForm shippingForm = new ShippingForm(123.45, 45.123, LocalDateTime.now(), false);
BreadSlice breadSlice1 = new BreadSlice(0.2, 420.0, LocalDateTime.now().plusMinutes(1), false);
BreadSlice breadSlice2 = new BreadSlice(0.8, 1680.0, LocalDateTime.now().plusMinutes(2), false);
List<BreadSlice> breadSlices = new ArrayList<>(2);
breadSlices.add(breadSlice1);
breadSlices.add(breadSlice2);
//
Food breadLoaf = new BreadLoaf("Bready bread", shippingForm, breadSlices);
FoodDao.getInstance().save(breadLoaf);
// // DISPLAY ALL FOOD
List<Food> foods = FoodDao.getInstance().loadAllData(Food.class);
System.out.println("All of the ITransactionSets: " + foods);
// tx.commit();
} catch (Exception e) {
// tx.rollback();
e.printStackTrace();
}
}
}
package com.mycompany.myapp;
import jakarta.persistence.Basic;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
@Entity
@Table(name = "apples")
public class Apple implements Food, Serializable {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
private final UUID uuid;
private final double price;
@Basic
private LocalDateTime timestamp;
public Apple() {
this(0.0, LocalDateTime.now());
}
public Apple(double transactionAmount) {
this(transactionAmount, LocalDateTime.now());
}
public Apple(LocalDateTime timestamp) {
this(0.0, timestamp);
}
public Apple(double transactionAmount, LocalDateTime timestamp) {
this.uuid = UUID.randomUUID();
this.price = transactionAmount;
this.timestamp = timestamp;
}
public double getPrice() {
return this.price;
}
@Override
public UUID getUuid() {
return this.uuid;
}
public String getTimestamp() {
return timestamp.toString();
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = LocalDateTime.parse(timestamp);
}
}
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.mycompany.myapp;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class FoodDao {
private static FoodDao transactionSetDao = null;
private FoodDao() {}
public static FoodDao getInstance() {
if(transactionSetDao == null) {
transactionSetDao = new FoodDao();
}
return transactionSetDao;
}
public void save(Food food) {
Transaction tx = null;
try( Session session = HibernateUtil.getSessionFactory().openSession() ) {
tx = session.beginTransaction();
session.merge(food);
tx.commit();
}
}
public <T> List<T> loadAllData(Class<T> type) {
Transaction tx = null;
try( Session session = HibernateUtil.getSessionFactory().openSession() ) {
tx = session.beginTransaction();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<T> criteria = builder.createQuery(type);
criteria.from(type);
List<T> data = session.createQuery(criteria).getResultList();
tx.commit();
return data;
}
}
}
FoodDao.getInstance().save(apple); seems to be causing the NullPointerException, but why?
What must I change for the problem to be resolved? Be elaborate for the syntactic parts of your answer, but concise for the explanations. | 7ae59c7c13903baeb6fe858b8481bf83 | {
"intermediate": 0.3679266571998596,
"beginner": 0.45118314027786255,
"expert": 0.18089015781879425
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.