row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
2,607
|
i got this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1948, in __call__
return self.func(*args)
^^^^^^^^^^^^^^^^
File "C:\Users\user\Videos\clipboard4.py", line 147, in toggle_log_translations
options_menu.entryconfig("Disable", label="Enable")
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 3425, in entryconfigure
return self._configure(('entryconfigure', index), cnf, kw)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\tkinter\__init__.py", line 1692, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: bad menu entry index "Disable"
from this code:
def toggle_log_translations():
global log_translations, translation_logfile
value = not log_translations
save_settings("log_translations", value)
if value:
options_menu.entryconfig("Enable", label="Disable")
else:
options_menu.entryconfig("Disable", label="Enable")
# Create a function to set the log file name
def set_translation_logfile():
global translation_logfile
translation_logfile = filedialog.asksaveasfilename(initialdir=os.getcwd(),
title="Set Translation Log File",
defaultextension=".txt",
filetypes=(("Text files", ".txt"), ("All files", ".")))
if translation_logfile:
save_settings("translation_logfile", translation_logfile)
log_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Log", menu=log_menu)
log_menu.add_command(label="Enable" if not log_translations else "Disable", command=toggle_log_translations)
log_menu.add_command(label="Set Translation Log File", command=set_translation_logfile)
|
747c7e5817ca1e72f828267aa72e831f
|
{
"intermediate": 0.4004319906234741,
"beginner": 0.4124123454093933,
"expert": 0.18715563416481018
}
|
2,608
|
create me an image warp function that will be like this: "def warp_perspective(img, H, reverse=False):" reverse means reversing the homography matrix
|
065fd5d25c5d23ca4910c092ec39c31b
|
{
"intermediate": 0.3559712767601013,
"beginner": 0.2825087308883667,
"expert": 0.3615199625492096
}
|
2,609
|
MaterialApp listen on screen size change
|
47c2efe8d8cbd57bd1f10202eafb8518
|
{
"intermediate": 0.36915838718414307,
"beginner": 0.3120265305042267,
"expert": 0.318815141916275
}
|
2,610
|
Fix the code. (The DrawCircle part.)
namespace bresenhamCircle
{
public partial class Form1 : Form
{
private int x1, y1, x2, y2;
public Form1()
{
InitializeComponent();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
if (x1 != 0 && y1 != 0)
{
x2 = (int)((MouseEventArgs)e).X;
y2 = (int)((MouseEventArgs)e).Y;
DrawCircle(x1, y1, x2, y2);
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
}
else
{
x1 = (int)((MouseEventArgs)e).X;
y1 = (int)((MouseEventArgs)e).Y;
}
}
private void DrawCircle(int x1, int y1, int x2, int y2)
{
pictureBox1.Image = (Image)new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(pictureBox1.Image);
int r = 0; //radius ???
int x = x1;
int y = y1;
x = -r; // ???
y = 0; //???
int F = 1 - r;
int delFs = 3;
int delFd = 5 - 2 * r;
while (x + y < 0)
{
g.FillRectangle(Brushes.Black, x, y, 1, 1);
if (F > 0)
{
//Диагональное смещение.
F += delFd;
x++;
y++;
delFs += 2;
delFd += 4;
}
else
{
//Вертикальное смешение.
F += delFs;
y++;
delFs += 2;
delFd += 2;
}
}
}
}
}
|
dcb57f417d5128e616f7699b2dfd2258
|
{
"intermediate": 0.3795546889305115,
"beginner": 0.38886862993240356,
"expert": 0.23157666623592377
}
|
2,611
|
#include <iostream>
#include <vector>
class Node {
public:
int key;
Node* left;
Node* right;
Node(int key) : key(key), left(nullptr), right(nullptr) {}
};
class BST {
private:
Node* root;
Node* insert(Node* node, int key) {
if (node == nullptr) {
return new Node(key);
}
if (key < node->key) {
node->left = insert(node->left, key);
} else {
node->right = insert(node->right, key);
}
return node;
}
void inorderTraversal(Node* node) {
if (node == nullptr) {
return;
}
inorderTraversal(node->left);
std::cout << node->key << " ";
inorderTraversal(node->right);
}
public:
BST() : root(nullptr) {}
void insert(int key) {
root = insert(root, key);
}
void inorderTraversal() {
inorderTraversal(root);
std::cout << std::endl;
}
};
void bstFromSelectionSort(const std::vector<int>& data, BST& bst) {
std::vector<bool> visited(data.size(), false);
for (size_t i = 0; i < data.size(); i++) {
int minIndex = -1;
for (size_t j = 0; j < data.size(); j++) {
if (!visited[j] && (minIndex == -1 || data[j] < data[minIndex])) {
minIndex = j;
}
}
visited[minIndex] = true;
bst.insert(data[minIndex]);
}
}
int main() {
std::vector<int> data = {5, 3, 8, 1, 7, 2, 9};
// Create a BST using the modified Selection Sort
BST bst;
bstFromSelectionSort(data, bst);
// Output the data in the BST using inorder traversal
bst.inorderTraversal();
return 0;
} write a code to calculate the running time in this code
|
06e4a84af33c994434378b8b34a9ebce
|
{
"intermediate": 0.31563475728034973,
"beginner": 0.39689838886260986,
"expert": 0.2874668836593628
}
|
2,612
|
hi
|
42295b4b3303bbc5e85934cf170e0aea
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
2,613
|
how to resolve TypeError: set_api_key() missing 1 required positional argument: 'self' error in intrinio_sdk?
|
b8f12de350fffabd1415d73b38294d2e
|
{
"intermediate": 0.7642909288406372,
"beginner": 0.11072429269552231,
"expert": 0.1249847412109375
}
|
2,614
|
using unity cloud service I want to make something where a user types in the name of his ranch and then that gets saved onto the unity cloud. This popup should only happen if the user hasn't played before/doesn't have a save
|
ca3058136efd4412234753f9f3831092
|
{
"intermediate": 0.4053255021572113,
"beginner": 0.24176786839962006,
"expert": 0.3529066741466522
}
|
2,615
|
website keeps reloading every 2 sec after adding pwa in quasar app
|
33b5bd96b55aaa73d44aba14f858fbe0
|
{
"intermediate": 0.30893760919570923,
"beginner": 0.3458925783634186,
"expert": 0.3451698422431946
}
|
2,616
|
i want to use ts-morph to traverse two sourcefiles, get the AST and compare each node to see if the node name and node text are same with each other. can you give me the nodejs script?
|
2de03d1c148f6c69c15ad0c85d91ab6e
|
{
"intermediate": 0.5458654165267944,
"beginner": 0.18122585117816925,
"expert": 0.27290868759155273
}
|
2,617
|
ok I have made an image warping function, please check it for errors: "def warp_perspective(img, H, reverse=False):
# Apply homography matrix to the source image corners
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
corners = np.array([[0, 0, 1], [h, 0, 1], [0, w, 1], [h, w, 1]])
transformed_corners = np.dot(H, corners.T).T
transformed_corners /= transformed_corners[:, 2].reshape((-1, 1))
print(img.shape)
# Compute the bounding box of the transformed corners and
# define the target_shape as the (height, width) of the bounding box
min_x, min_y, max_x, max_y = 0, 0, 0, 0
min_x = min(min_x, transformed_corners[:, 1].min())
min_y = min(min_y, transformed_corners[:, 0].min())
max_x = max(max_x, transformed_corners[:, 1].max())
max_y = max(max_y, transformed_corners[:, 0].max())
target_shape = (int(np.round(max_y - min_y)), int(np.round(max_x - min_x)))
h, w = target_shape
print("a", target_shape)
target_coordinates = np.zeros((h,w,img.shape[2]))
center = np.array(target_shape)//2
center_source = np.dot(np.linalg.inv(H), [center[0],center[1],1])
source_center = np.array(img.shape)//2
shift = center_source - source_center
for y in range(h):
for x in range(w):
source = np.dot(np.linalg.inv(H), [y,x,1])
s_y = int(np.floor(source[0])-shift[0])
s_x = int(np.floor(source[1])-shift[1])
if 0 <= s_y < img.shape[0] and 0 <= s_x < img.shape[1]:
target_coordinates[y,x] = img[s_y, s_x]
print("done")
warped_image = target_coordinates
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image"
|
3064499ab71b8d5ff7e3fd6b002af633
|
{
"intermediate": 0.2878974378108978,
"beginner": 0.3997175395488739,
"expert": 0.31238508224487305
}
|
2,618
|
вот код
{
'value': {
'va': function(og) {
var Nv = Ng;
return {
'index': og[Nv(gc_1c4.J)] + 0x3
};
},
'vb': function(og) {
var l0 = Ng;
return {
'index': 0x0 - og[l0(gc_1c5.J)]
};
},
'vc': function(og) {
var l1 = Ng;
return {
'index': 0xa - og[l1(gc_1c6.J)]
};
},
'vd': function(og) {
var l2 = Ng;
return {
'index': 0x3 * og[l2(gc_1c7.J)]
};
}
},
'key': {
'ka': function(og) {
var l3 = Ng;
return og[l3(gc_1c8.J)];
},
'kb': function(og) {
var l4 = Ng;
return [og[l4(gc_1c9.J)]];
},
'kc': function(og) {
var l5 = Ng;
return {
'guess': og[l5(gc_1cJ.J)]
};
}
}
}
что тебе нужно, чтобы составить алгоритм генерации guess на python?
я имею ввиду какие параметры кода тебе недостают для этой задачи
|
4f92eecdca754031bd94863507e07000
|
{
"intermediate": 0.3366899788379669,
"beginner": 0.5013511776924133,
"expert": 0.16195887327194214
}
|
2,619
|
def randn(*args):
cnum = np.random.randn(*args) + <br/> np.random.randn(*args) * 1j
return cnum.astype(np.csingle)
left = randn(M, N)
can u change this code into C language
|
c55d38ad13d4dfcb042685bbeca32250
|
{
"intermediate": 0.316834956407547,
"beginner": 0.5155333280563354,
"expert": 0.16763170063495636
}
|
2,620
|
how can I load a project from the source files by using ts-morph and traverse each node of its AST
|
55db489c67c5980c8fc3fe3b87b2ae0c
|
{
"intermediate": 0.3544355034828186,
"beginner": 0.3360441327095032,
"expert": 0.30952027440071106
}
|
2,621
|
Android Studio CPU Profiling mode Sample C++Function Recording failed to stop
|
c1837cb66d6cc95da957c5475b3e78bb
|
{
"intermediate": 0.4038653075695038,
"beginner": 0.34300777316093445,
"expert": 0.25312691926956177
}
|
2,622
|
jetpack compose firebase email verification via mail
|
0ca72705930eb24ba1913f91f5334a1e
|
{
"intermediate": 0.44787201285362244,
"beginner": 0.20652134716510773,
"expert": 0.34560662508010864
}
|
2,624
|
Can you improve performance of this function. Do not use anything other than NumPy of course: "def warp_perspective(img, H, reverse=False):
# Apply homography matrix to the source image corners
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
corners = np.array([[0, 0, 1], [0, w, 1], [h, 0, 1], [h, w, 1]])
transformed_corners = np.dot(H, corners.T).T
transformed_corners /= transformed_corners[:, 2].reshape((-1, 1))
print(img.shape)
# Compute the bounding box of the transformed corners and
# define the target_shape as the (height, width) of the bounding box
min_x, min_y, max_x, max_y = np.inf, np.inf, -np.inf, -np.inf
min_x = min(min_x, transformed_corners[:, 1].min())
min_y = min(min_y, transformed_corners[:, 0].min())
max_x = max(max_x, transformed_corners[:, 1].max())
max_y = max(max_y, transformed_corners[:, 0].max())
target_shape = (int(np.round(max_y - min_y)), int(np.round(max_x - min_x)))
h, w = target_shape
print(“a”, target_shape)
target_coordinates = np.zeros((h, w, img.shape[2]))
center = np.array(target_shape) // 2
center_source = np.dot(np.linalg.inv(H), [center[0], center[1], 1])
source_center = np.array(img.shape) // 2
shift = center_source - source_center
for y in range(h):
for x in range(w):
source = np.dot(np.linalg.inv(H), [y, x, 1])
s_y = int(np.floor(source[1]) - shift[1])
s_x = int(np.floor(source[0]) - shift[0])
if 0 <= s_y < img.shape[0] and 0 <= s_x < img.shape[1]:
target_coordinates[y, x] = img[s_y, s_x]
print(“done”)
warped_image = target_coordinates
display_image(img)
display_image(warped_image)
print(warped_image.shape)
return warped_image"
|
d82f54bb762e42e585e9c848ace6db94
|
{
"intermediate": 0.36628392338752747,
"beginner": 0.34627535939216614,
"expert": 0.2874407470226288
}
|
2,625
|
https://huggingface.co/spaces/yuntian-deng/ChatGPT
|
f099cb92f3adef9706c28b39b6f66087
|
{
"intermediate": 0.34223473072052,
"beginner": 0.2823311388492584,
"expert": 0.3754340708255768
}
|
2,626
|
i need to write a code in mt4 by mql4 that show me price pivot in eur/usd chart .
|
bdb065e983ecd4e835b13c0bf4cdb885
|
{
"intermediate": 0.6831198930740356,
"beginner": 0.09404654055833817,
"expert": 0.222833514213562
}
|
2,627
|
given that this is my HTML and CSS
Implement a cool line hover effect in the navigation bar within the header
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Cabin:wght@400;700&display=swap">
<link rel="stylesheet" href="style/style.css" />
<title>Camping Equipment - Retail Camping Company</title>
</head>
<body>
<header>
<div class="sticky-nav">
<div class="nav-container">
<img src="assets/images/logo.svg" alt="Logo" class="logo">
<h1>Retail Camping Company</h1>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="camping-equipment.html">Camping Equipment</a></li>
<li><a href="furniture.html">Furniture</a></li>
<li><a href="reviews.html">Reviews</a></li>
<li><a href="basket.html">Basket</a></li>
<li><a href="offers-and-packages.html">Offers and Packages</a></li>
</ul>
</nav>
</div>
</div>
</header>
<!-- Home Page -->
<main>
<section class="slideshow-section">
<!-- Insert slide show here -->
<div class="slideshow-container">
<div class="mySlides fade">
<img src="https://via.placeholder.com/600x400" alt="Tents" style="width:100%">
</div>
<div class="mySlides fade">
<img src="https://via.placeholder.com/600x400" alt="Cookers" style="width:100%">
</div>
<div class="mySlides fade">
<img src="https://via.placeholder.com/600x400" alt="Camping Gear" style="width:100%">
</div>
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
<div style="text-align:center">
<span class="dot" onclick="currentSlide(1)"></span>
<span class="dot" onclick="currentSlide(2)"></span>
<span class="dot" onclick="currentSlide(3)"></span>
</div>
</section>
<section class="about-section">
<p>Welcome to Retail Camping Company, your one-stop-shop for all your camping equipment needs. Discover our premium offers on tents, cookers, camping gear, and furniture.</p>
</section>
<section class="featured-section">
<h2>Featured Products</h2>
<div class="featured-container">
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
<div class="featured-product">
<img src="https://via.placeholder.com/150x150" alt="Featured Product">
<h3>Product Name</h3>
<p>Short product description.</p>
</div>
</div>
</section>
<section>
<!-- Display special offers and relevant images -->
<div class="special-offers-container">
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Tent Offer">
<p>20% off premium tents!</p>
</div>
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Cooker Offer">
<p>Buy a cooker, get a free utensil set!</p>
</div>
<div class="special-offer">
<img src="https://via.placeholder.com/200x200" alt="Furniture Offer">
<p>Save on camping furniture bundles!</p>
</div>
</div>
</section>
<section class="buts">
<!-- Modal pop-up window content here -->
<button id="modalBtn">Special Offer!</button>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Sign up now and receive 10% off your first purchase!</p>
</div>
</div>
</section>
<script>
// Get modal element
var modal = document.getElementById('modal');
// Get open model button
var modalBtn = document.getElementById('modalBtn');
// Get close button
var closeBtn = document.getElementsByClassName('close')[0];
// Listen for open click
modalBtn.addEventListener('click', openModal);
// Listen for close click
closeBtn.addEventListener('click', closeModal);
// Listen for outside click
window.addEventListener('click', outsideClick);
// Function to open modal
function openModal() {
modal.style.display = 'block';
}
// Function to close modal
function closeModal() {
modal.style.display = 'none';
}
// Function to close modal if outside click
function outsideClick(e) {
if (e.target == modal) {
modal.style.display = 'none';
}
}
</script>
</main>
<footer>
<div class="footer-container">
<div class="footer-item">
<p>Contact Us:</p>
<ul class="social-links">
<li><a href="https://www.facebook.com">Facebook</a></li>
<li><a href="https://www.instagram.com">Instagram</a></li>
<li><a href="https://www.twitter.com">Twitter</a></li>
</ul>
</div>
<div class="footer-item">
<p>Where to find us: </p>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3843.534694025997!2d14.508501137353216!3d35.89765941458404!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x130e452d3081f035%3A0x61f492f43cae68e4!2sCity Gate!5e0!3m2!1sen!2smt!4v1682213255989!5m2!1sen!2smt" width="600" height="200" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>
<div class="footer-item">
<p>Subscribe to our newsletter:</p>
<form action="subscribe.php" method="post">
<input type="email" name="email" placeholder="Enter your email" required>
<button type="submit">Subscribe</button>
</form>
</div>
</div>
</footer>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
CSS:
html, body, h1, h2, h3, h4, p, a, ul, li, div, main, header, section, footer, img {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font-family: inherit;
vertical-align: baseline;
box-sizing: border-box;
}
body {
font-family: "Cabin", sans-serif;
line-height: 1.5;
color: #333;
width: 100%;
margin: 0;
padding: 0;
min-height: 100vh;
flex-direction: column;
display: flex;
background-image: url("../assets/images/cover.jpg");
background-size: cover;
}
header {
background: #00000000;
padding: 0.5rem 2rem;
text-align: center;
color: #32612D;
font-size: 1.2rem;
}
main{
flex-grow: 1;
}
.sticky-nav {
position: -webkit-sticky;
position: sticky;
top: 0;
z-index: 1000;
}
.nav-container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.logo {
width: 50px;
height: auto;
margin-right: 1rem;
}
h1 {
flex-grow: 1;
text-align: left;
}
nav ul {
display: inline
list-style: none;
}
nav ul li {
display: inline;
margin-left: 1rem;
}
nav ul li a {
text-decoration: none;
color: #32612D;
}
nav ul li a:hover {
color: #000000;
}
@media screen and (max-width: 768px) {
.nav-container {
flex-direction: column;
}
h1 {
margin-bottom: 1rem;
}
}
nav ul li a {
position: relative;
}
nav ul li a::after {
content: ‘’;
position: absolute;
bottom: 0;
left: 0;
width: 100%;
height: 2px;
background-color: #000;
transform: scaleX(0);
transition: transform 0.3s;
}
nav ul li a:hover::after {
transform: scaleX(1);
}
.slideshow-container {
width: 100%;
position: relative;
margin: 1rem 0;
}
.mySlides {
display: none;
}
.mySlides img {
width: 100%;
height: auto;
}
/* Slideshow navigation */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 16px;
color: #32612D;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
}
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev:hover, .next:hover {
background-color: rgba(255,255,255,0.8);
}
.dot {
cursor: pointer;
height: 15px;
width: 15px;
margin: 0 2px;
background-color: #bbb;
border-radius: 50%;
display: inline-block;
transition: background-color 0.6s ease;
}
.dot:hover {
background-color: #717171;
}
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
.about-section {
padding: 1rem;
text-align: center;
margin: 1rem 0;
}
.featured-section {
padding: 1rem;
text-align: center;
margin: 1rem 0;
}
.featured-section h2 {
font-size: 1.5rem;
margin-bottom: 1rem;
}
.featured-container {
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
margin: 1rem 0;
}
.featured-product {
width: 150px;
padding: 1rem;
background-color: #ADC3AB;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
margin: 0.5rem;
}
.featured-product:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
transform: translateY(-5px);
}
.featured-product img {
width: 100%;
height: auto;
margin-bottom: 1rem;
border-radius: 5px;
}
.special-offers-container {
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
margin: 1rem 0;
}
.special-offer {
width: 200px;
padding: 1rem;
text-align: center;
margin: 1rem;
background-color: #ADC3AB;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
}
.special-offer:hover {
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2);
transform: translateY(-5px);
}
.special-offer img {
width: 100%;
height: auto;
margin-bottom: 0.5rem;
border-radius: 5px;
}
.modal {
display: none;
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
overflow: auto;
align-items: center;
}
.modal-content {
background-color: #fefefe;
padding: 2rem;
margin: 10% auto;
width: 30%;
min-width: 300px;
max-width: 80%;
text-align: center;
border-radius: 5px;
box-shadow: 0 1px 8px rgba(0, 0, 0, 0.1);
}
.buts {
text-align: center;
}
.close {
display: block;
text-align: right;
font-size: 2rem;
color: #333;
cursor: pointer;
}
footer {
background: #32612D;
padding: 1rem;
text-align: center;
margin-top: auto;
}
.footer-container {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
}
.footer-item {
margin: 1rem 2rem;
}
footer p {
color: #fff;
margin-bottom: 1rem;
}
footer ul {
list-style: none;
}
footer ul li {
display: inline;
margin: 0.5rem;
}
footer ul li a {
text-decoration: none;
color: #fff;
}
@media screen and (max-width: 768px) {
.special-offers-container {
flex-direction: column;
}
}
@media screen and (max-width: 480px) {
h1 {
display: block;
margin-bottom: 1rem;
}
}
.footer-item iframe {
width: 100%;
height: 200px;
}
.footer-item form {
display: inline-flex;
align-items: center;
}
.footer-item input[type="email"] {
padding: 0.5rem;
border: none;
border-radius: 5px;
margin-right: 0.5rem;
}
.footer-item button {
background-color: #ADC3AB;
color: #32612D;
padding: 0.5rem;
border: none;
border-radius: 5px;
cursor: pointer;
}
.footer-item button:hover {
background-color: #32612D;
color: #fff;
}
|
caba5e79ff9c5d509b379dd5db079376
|
{
"intermediate": 0.43323928117752075,
"beginner": 0.40643540024757385,
"expert": 0.1603253036737442
}
|
2,628
|
sqlalchemy with filter with int with like
|
6a115bdc4fa028c5bab1d49de23822db
|
{
"intermediate": 0.22798104584217072,
"beginner": 0.33482757210731506,
"expert": 0.4371913969516754
}
|
2,629
|
详细分析下述代码,并用mermaid代码给出详细的流程图// FileManager.cpp: implementation of the CFileManager class.
//
//////////////////////////////////////////////////////////////////////
#include "FileManager.h"
typedef struct
{
DWORD dwSizeHigh;
DWORD dwSizeLow;
}FILESIZE;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFileManager::CFileManager(CClientSocket *pClient, int h):CManager(pClient)
{
m_nTransferMode = TRANSFER_MODE_NORMAL;
// 发送驱动器列表, 开始进行文件管理,建立新线程
SendDriveList();
}
CFileManager::~CFileManager()
{
m_UploadList.clear();
}
VOID CFileManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
{
switch (lpBuffer[0])
{
case COMMAND_LIST_FILES:// 获取文件列表
SendFilesList((char *)lpBuffer + 1);
break;
case COMMAND_DELETE_FILE:// 删除文件
DeleteFile((char *)lpBuffer + 1);
SendToken(TOKEN_DELETE_FINISH);
break;
case COMMAND_DELETE_DIRECTORY:// 删除文件
DeleteDirectory((char *)lpBuffer + 1);
SendToken(TOKEN_DELETE_FINISH);
break;
case COMMAND_DOWN_FILES: // 上传文件
UploadToRemote(lpBuffer + 1);
break;
case COMMAND_CONTINUE: // 上传文件
SendFileData(lpBuffer + 1);
break;
case COMMAND_CREATE_FOLDER:
CreateFolder(lpBuffer + 1);
break;
case COMMAND_RENAME_FILE:
Rename(lpBuffer + 1);
break;
case COMMAND_STOP:
StopTransfer();
break;
case COMMAND_SET_TRANSFER_MODE:
SetTransferMode(lpBuffer + 1);
break;
case COMMAND_FILE_SIZE:
CreateLocalRecvFile(lpBuffer + 1);
break;
case COMMAND_FILE_DATA:
WriteLocalRecvFile(lpBuffer + 1, nSize -1);
break;
case COMMAND_OPEN_FILE_SHOW:
OpenFile((char *)lpBuffer + 1, SW_SHOW);
break;
case COMMAND_OPEN_FILE_HIDE:
OpenFile((char *)lpBuffer + 1, SW_HIDE);
break;
default:
break;
}
}
bool CFileManager::MakeSureDirectoryPathExists(LPCTSTR pszDirPath)
{
LPTSTR p, pszDirCopy;
DWORD dwAttributes;
// Make a copy of the string for editing.
__try
{
pszDirCopy = (LPTSTR)malloc(sizeof(TCHAR) * (lstrlen(pszDirPath) + 1));
if(pszDirCopy == NULL)
return FALSE;
lstrcpy(pszDirCopy, pszDirPath);
p = pszDirCopy;
// If the second character in the path is "\", then this is a UNC
// path, and we should skip forward until we reach the 2nd \ in the path.
if((*p == TEXT('\\')) && (*(p+1) == TEXT('\\')))
{
p++; // Skip over the first \ in the name.
p++; // Skip over the second \ in the name.
// Skip until we hit the first "\" (\\Server\).
while(*p && *p != TEXT('\\'))
{
p = CharNext(p);
}
// Advance over it.
if(*p)
{
p++;
}
// Skip until we hit the second "\" (\\Server\Share\).
while(*p && *p != TEXT('\\'))
{
p = CharNext(p);
}
// Advance over it also.
if(*p)
{
p++;
}
}
else if(*(p+1) == TEXT(':')) // Not a UNC. See if it's <drive>:
{
p++;
p++;
// If it exists, skip over the root specifier
if(*p && (*p == TEXT('\\')))
{
p++;
}
}
while(*p)
{
if(*p == TEXT('\\'))
{
*p = TEXT('\0');
dwAttributes = GetFileAttributes(pszDirCopy);
// Nothing exists with this name. Try to make the directory name and error if unable to.
if(dwAttributes == 0xffffffff)
{
if(!CreateDirectory(pszDirCopy, NULL))
{
if(GetLastError() != ERROR_ALREADY_EXISTS)
{
free(pszDirCopy);
return FALSE;
}
}
}
else
{
if((dwAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
{
// Something exists with this name, but it's not a directory... Error
free(pszDirCopy);
return FALSE;
}
}
*p = TEXT('\\');
}
p = CharNext(p);
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
free(pszDirCopy);
return FALSE;
}
free(pszDirCopy);
return TRUE;
}
bool CFileManager::OpenFile(LPCTSTR lpFile, INT nShowCmd)
{
char lpSubKey[500];
HKEY hKey;
char strTemp[MAX_PATH];
LONG nSize = sizeof(strTemp);
char *lpstrCat = NULL;
memset(strTemp, 0, sizeof(strTemp));
const char *lpExt = strrchr(lpFile, '.');
if (!lpExt)
return false;
if (RegOpenKeyEx(HKEY_CLASSES_ROOT, lpExt, 0L, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
return false;
RegQueryValue(hKey, NULL, strTemp, &nSize);
RegCloseKey(hKey);
memset(lpSubKey, 0, sizeof(lpSubKey));
wsprintf(lpSubKey, "%s\\shell\\open\\command", strTemp);
if (RegOpenKeyEx(HKEY_CLASSES_ROOT, lpSubKey, 0L, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
return false;
memset(strTemp, 0, sizeof(strTemp));
nSize = sizeof(strTemp);
RegQueryValue(hKey, NULL, strTemp, &nSize);
RegCloseKey(hKey);
lpstrCat = strstr(strTemp, "\"%1");
if (lpstrCat == NULL)
lpstrCat = strstr(strTemp, "%1");
if (lpstrCat == NULL)
{
lstrcat(strTemp, " ");
lstrcat(strTemp, lpFile);
}
else
lstrcpy(lpstrCat, lpFile);
STARTUPINFO si = {0};
PROCESS_INFORMATION pi;
si.cb = sizeof si;
if (nShowCmd != SW_HIDE)
si.lpDesktop = "WinSta0\\Default";
CreateProcess(NULL, strTemp, NULL, NULL, false, 0, NULL, NULL, &si, &pi);
return true;
}
UINT CFileManager::SendDriveList()
{
char DriveString[256];
// 前一个字节为令牌,后面的52字节为驱动器跟相关属性
BYTE DriveList[1024];
char FileSystem[MAX_PATH];
char *pDrive = NULL;
DriveList[0] = TOKEN_DRIVE_LIST; // 驱动器列表
GetLogicalDriveStrings(sizeof(DriveString), DriveString);
pDrive = DriveString;
unsigned __int64 HDAmount = 0;
unsigned __int64 HDFreeSpace = 0;
unsigned long AmntMB = 0; // 总大小
unsigned long FreeMB = 0; // 剩余空间
DWORD dwOffset = 1;
for (; *pDrive != '\0'; pDrive += lstrlen(pDrive) + 1)
{
memset(FileSystem, 0, sizeof(FileSystem));
// 得到文件系统信息及大小
GetVolumeInformation(pDrive, NULL, 0, NULL, NULL, NULL, FileSystem, MAX_PATH);
SHFILEINFO sfi;
SHGetFileInfo(pDrive, FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(SHFILEINFO), SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES);
int nTypeNameLen = lstrlen(sfi.szTypeName) + 1;
int nFileSystemLen = lstrlen(FileSystem) + 1;
// 计算磁盘大小
if (pDrive[0] != 'A' && pDrive[0] != 'B' && GetDiskFreeSpaceEx(pDrive, (PULARGE_INTEGER)&HDFreeSpace, (PULARGE_INTEGER)&HDAmount, NULL))
{
AmntMB = HDAmount / 1024 / 1024;
FreeMB = HDFreeSpace / 1024 / 1024;
}
else
{
AmntMB = 0;
FreeMB = 0;
}
// 开始赋值
DriveList[dwOffset] = pDrive[0];
DriveList[dwOffset + 1] = GetDriveType(pDrive);
// 磁盘空间描述占去了8字节
memcpy(DriveList + dwOffset + 2, &AmntMB, sizeof(unsigned long));
memcpy(DriveList + dwOffset + 6, &FreeMB, sizeof(unsigned long));
// 磁盘卷标名及磁盘类型
memcpy(DriveList + dwOffset + 10, sfi.szTypeName, nTypeNameLen);
memcpy(DriveList + dwOffset + 10 + nTypeNameLen, FileSystem, nFileSystemLen);
dwOffset += 10 + nTypeNameLen + nFileSystemLen;
}
return Send((LPBYTE)DriveList, dwOffset);
}
UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
{
// 重置传输方式
m_nTransferMode = TRANSFER_MODE_NORMAL;
UINT nRet = 0;
char strPath[MAX_PATH];
char *pszFileName = NULL;
LPBYTE lpList = NULL;
HANDLE hFile;
DWORD dwOffset = 0; // 位移指针
int nLen = 0;
DWORD nBufferSize = 1024 * 10; // 先分配10K的缓冲区
WIN32_FIND_DATA FindFileData;
lpList = (BYTE *)LocalAlloc(LPTR, nBufferSize);
wsprintf(strPath, "%s\\*.*", lpszDirectory);
hFile = FindFirstFile(strPath, &FindFileData);
if (hFile == INVALID_HANDLE_VALUE)
{
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
}
*lpList = TOKEN_FILE_LIST;
// 1 为数据包头部所占字节,最后赋值
dwOffset = 1;
/*
文件属性 1
文件名 strlen(filename) + 1 ('\0')
文件大小 4
*/
do
{
// 动态扩展缓冲区
if (dwOffset > (nBufferSize - MAX_PATH * 2))
{
nBufferSize += MAX_PATH * 2;
lpList = (BYTE *)LocalReAlloc(lpList, nBufferSize, LMEM_ZEROINIT|LMEM_MOVEABLE);
}
pszFileName = FindFileData.cFileName;
if (strcmp(pszFileName, ".") == 0 || strcmp(pszFileName, "..") == 0)
continue;
// 文件属性 1 字节
*(lpList + dwOffset) = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
dwOffset++;
// 文件名 lstrlen(pszFileName) + 1 字节
nLen = lstrlen(pszFileName);
memcpy(lpList + dwOffset, pszFileName, nLen);
dwOffset += nLen;
*(lpList + dwOffset) = 0;
dwOffset++;
// 文件大小 8 字节
memcpy(lpList + dwOffset, &FindFileData.nFileSizeHigh, sizeof(DWORD));
memcpy(lpList + dwOffset + 4, &FindFileData.nFileSizeLow, sizeof(DWORD));
dwOffset += 8;
// 最后访问时间 8 字节
memcpy(lpList + dwOffset, &FindFileData.ftLastWriteTime, sizeof(FILETIME));
dwOffset += 8;
} while(FindNextFile(hFile, &FindFileData));
nRet = Send(lpList, dwOffset);
LocalFree(lpList);
FindClose(hFile);
return nRet;
}
bool CFileManager::DeleteDirectory(LPCTSTR lpszDirectory)
{
WIN32_FIND_DATA wfd;
char lpszFilter[MAX_PATH];
wsprintf(lpszFilter, "%s\\*.*", lpszDirectory);
HANDLE hFind = FindFirstFile(lpszFilter, &wfd);
if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
return FALSE;
do
{
if (wfd.cFileName[0] != '.')
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
char strDirectory[MAX_PATH];
wsprintf(strDirectory, "%s\\%s", lpszDirectory, wfd.cFileName);
DeleteDirectory(strDirectory);
}
else
{
char strFile[MAX_PATH];
wsprintf(strFile, "%s\\%s", lpszDirectory, wfd.cFileName);
DeleteFile(strFile);
}
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind); // 关闭查找句柄
if(!RemoveDirectory(lpszDirectory))
{
return FALSE;
}
return true;
}
UINT CFileManager::SendFileSize(LPCTSTR lpszFileName)
{
UINT nRet = 0;
DWORD dwSizeHigh;
DWORD dwSizeLow;
// 1 字节token, 8字节大小, 文件名称, '\0'
HANDLE hFile;
// 保存当前正在操作的文件名
memset(m_strCurrentProcessFileName, 0, sizeof(m_strCurrentProcessFileName));
strcpy(m_strCurrentProcessFileName, lpszFileName);
hFile = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
return FALSE;
dwSizeLow = GetFileSize(hFile, &dwSizeHigh);
CloseHandle(hFile);
// 构造数据包,发送文件长度
int nPacketSize = lstrlen(lpszFileName) + 10;
BYTE *bPacket = (BYTE *)LocalAlloc(LPTR, nPacketSize);
memset(bPacket, 0, nPacketSize);
bPacket[0] = TOKEN_FILE_SIZE;
FILESIZE *pFileSize = (FILESIZE *)(bPacket + 1);
pFileSize->dwSizeHigh = dwSizeHigh;
pFileSize->dwSizeLow = dwSizeLow;
memcpy(bPacket + 9, lpszFileName, lstrlen(lpszFileName) + 1);
nRet = Send(bPacket, nPacketSize);
LocalFree(bPacket);
return nRet;
}
UINT CFileManager::SendFileData(LPBYTE lpBuffer)
{
UINT nRet = 0;
FILESIZE *pFileSize;
char *lpFileName;
pFileSize = (FILESIZE *)lpBuffer;
lpFileName = m_strCurrentProcessFileName;
// 远程跳过,传送下一个
if (pFileSize->dwSizeLow == -1)
{
UploadNext();
return 0;
}
HANDLE hFile;
hFile = CreateFile(lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
return -1;
SetFilePointer(hFile, pFileSize->dwSizeLow, (long *)&(pFileSize->dwSizeHigh), FILE_BEGIN);
int nHeadLength = 9; // 1 + 4 + 4数据包头部大小
DWORD nNumberOfBytesToRead = MAX_SEND_BUFFER - nHeadLength;
DWORD nNumberOfBytesRead = 0;
LPBYTE lpPacket = (LPBYTE)LocalAlloc(LPTR, MAX_SEND_BUFFER);
// Token, 大小,偏移,文件名,数据
lpPacket[0] = TOKEN_FILE_DATA;
memcpy(lpPacket + 1, pFileSize, sizeof(FILESIZE));
ReadFile(hFile, lpPacket + nHeadLength, nNumberOfBytesToRead, &nNumberOfBytesRead, NULL);
CloseHandle(hFile);
if (nNumberOfBytesRead > 0)
{
int nPacketSize = nNumberOfBytesRead + nHeadLength;
nRet = Send(lpPacket, nPacketSize);
}
else
{
UploadNext();
}
LocalFree(lpPacket);
return nRet;
}
// 传送下一个文件
void CFileManager::UploadNext()
{
list <string>::iterator it = m_UploadList.begin();
// 删除一个任务
m_UploadList.erase(it);
// 还有上传任务
if(m_UploadList.empty())
{
SendToken(TOKEN_TRANSFER_FINISH);
}
else
{
// 上传下一个
it = m_UploadList.begin();
SendFileSize((*it).c_str());
}
}
int CFileManager::SendToken(BYTE bToken)
{
return Send(&bToken, 1);
}
bool CFileManager::UploadToRemote(LPBYTE lpBuffer)
{
if (lpBuffer[lstrlen((char *)lpBuffer) - 1] == '\\')
{
FixedUploadList((char *)lpBuffer);
if (m_UploadList.empty())
{
StopTransfer();
return true;
}
}
else
{
m_UploadList.push_back((char *)lpBuffer);
}
list <string>::iterator it = m_UploadList.begin();
// 发送第一个文件
SendFileSize((*it).c_str());
return true;
}
bool CFileManager::FixedUploadList(LPCTSTR lpPathName)
{
WIN32_FIND_DATA wfd;
char lpszFilter[MAX_PATH];
char *lpszSlash = NULL;
memset(lpszFilter, 0, sizeof(lpszFilter));
if (lpPathName[lstrlen(lpPathName) - 1] != '\\')
lpszSlash = "\\";
else
lpszSlash = "";
wsprintf(lpszFilter, "%s%s*.*", lpPathName, lpszSlash);
HANDLE hFind = FindFirstFile(lpszFilter, &wfd);
if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
return false;
do
{
if (wfd.cFileName[0] != '.')
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
char strDirectory[MAX_PATH];
wsprintf(strDirectory, "%s%s%s", lpPathName, lpszSlash, wfd.cFileName);
FixedUploadList(strDirectory);
}
else
{
char strFile[MAX_PATH];
wsprintf(strFile, "%s%s%s", lpPathName, lpszSlash, wfd.cFileName);
m_UploadList.push_back(strFile);
}
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind); // 关闭查找句柄
return true;
}
void CFileManager::StopTransfer()
{
if (!m_UploadList.empty())
m_UploadList.clear();
SendToken(TOKEN_TRANSFER_FINISH);
}
void CFileManager::CreateLocalRecvFile(LPBYTE lpBuffer)
{
FILESIZE *pFileSize = (FILESIZE *)lpBuffer;
// 保存当前正在操作的文件名
memset(m_strCurrentProcessFileName, 0, sizeof(m_strCurrentProcessFileName));
strcpy(m_strCurrentProcessFileName, (char *)lpBuffer + 8);
// 保存文件长度
m_nCurrentProcessFileLength = (pFileSize->dwSizeHigh * (MAXDWORD + long long(1))) + pFileSize->dwSizeLow;
// 创建多层目录
MakeSureDirectoryPathExists(m_strCurrentProcessFileName);
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(m_strCurrentProcessFileName, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE
&& m_nTransferMode != TRANSFER_MODE_OVERWRITE_ALL
&& m_nTransferMode != TRANSFER_MODE_ADDITION_ALL
&& m_nTransferMode != TRANSFER_MODE_JUMP_ALL
)
{
SendToken(TOKEN_GET_TRANSFER_MODE);
}
else
{
GetFileData();
}
FindClose(hFind);
}
void CFileManager::GetFileData()
{
int nTransferMode;
switch (m_nTransferMode)
{
case TRANSFER_MODE_OVERWRITE_ALL:
nTransferMode = TRANSFER_MODE_OVERWRITE;
break;
case TRANSFER_MODE_ADDITION_ALL:
nTransferMode = TRANSFER_MODE_ADDITION;
break;
case TRANSFER_MODE_JUMP_ALL:
nTransferMode = TRANSFER_MODE_JUMP;
break;
default:
nTransferMode = m_nTransferMode;
}
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(m_strCurrentProcessFileName, &FindFileData);
// 1字节Token,四字节偏移高四位,四字节偏移低四位
BYTE bToken[9];
DWORD dwCreationDisposition; // 文件打开方式
memset(bToken, 0, sizeof(bToken));
bToken[0] = TOKEN_DATA_CONTINUE;
// 文件已经存在
if (hFind != INVALID_HANDLE_VALUE)
{
// 提示点什么
// 如果是续传
if (nTransferMode == TRANSFER_MODE_ADDITION)
{
memcpy(bToken + 1, &FindFileData.nFileSizeHigh, 4);
memcpy(bToken + 5, &FindFileData.nFileSizeLow, 4);
dwCreationDisposition = OPEN_EXISTING;
}
// 覆盖
else if (nTransferMode == TRANSFER_MODE_OVERWRITE)
{
// 偏移置0
memset(bToken + 1, 0, 8);
// 重新创建
dwCreationDisposition = CREATE_ALWAYS;
}
// 传送下一个
else if (nTransferMode == TRANSFER_MODE_JUMP)
{
DWORD dwOffset = -1;
memcpy(bToken + 5, &dwOffset, 4);
dwCreationDisposition = OPEN_EXISTING;
}
}
else
{
// 偏移置0
memset(bToken + 1, 0, 8);
// 重新创建
dwCreationDisposition = CREATE_ALWAYS;
}
FindClose(hFind);
HANDLE hFile =
CreateFile
(
m_strCurrentProcessFileName,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
dwCreationDisposition,
FILE_ATTRIBUTE_NORMAL,
0
);
// 需要错误处理
if (hFile == INVALID_HANDLE_VALUE)
{
m_nCurrentProcessFileLength = 0;
return;
}
CloseHandle(hFile);
Send(bToken, sizeof(bToken));
}
void CFileManager::WriteLocalRecvFile(LPBYTE lpBuffer, UINT nSize)
{
// 传输完毕
BYTE *pData;
DWORD dwBytesToWrite;
DWORD dwBytesWrite;
int nHeadLength = 9; // 1 + 4 + 4 数据包头部大小,为固定的9
FILESIZE *pFileSize;
// 得到数据的偏移
pData = lpBuffer + 8;
pFileSize = (FILESIZE *)lpBuffer;
// 得到数据在文件中的偏移
LONG dwOffsetHigh = pFileSize->dwSizeHigh;
LONG dwOffsetLow = pFileSize->dwSizeLow;
dwBytesToWrite = nSize - 8;
HANDLE hFile =
CreateFile
(
m_strCurrentProcessFileName,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0
);
SetFilePointer(hFile, dwOffsetLow, &dwOffsetHigh, FILE_BEGIN);
int nRet = 0;
// 写入文件
nRet = WriteFile
(
hFile,
pData,
dwBytesToWrite,
&dwBytesWrite,
NULL
);
CloseHandle(hFile);
// 为了比较,计数器递增
BYTE bToken[9];
bToken[0] = TOKEN_DATA_CONTINUE;
dwOffsetLow += dwBytesWrite;
memcpy(bToken + 1, &dwOffsetHigh, sizeof(dwOffsetHigh));
memcpy(bToken + 5, &dwOffsetLow, sizeof(dwOffsetLow));
Send(bToken, sizeof(bToken));
}
void CFileManager::SetTransferMode(LPBYTE lpBuffer)
{
memcpy(&m_nTransferMode, lpBuffer, sizeof(m_nTransferMode));
GetFileData();
}
void CFileManager::CreateFolder(LPBYTE lpBuffer)
{
MakeSureDirectoryPathExists((char *)lpBuffer);
SendToken(TOKEN_CREATEFOLDER_FINISH);
}
void CFileManager::Rename(LPBYTE lpBuffer)
{
LPCTSTR lpExistingFileName = (char *)lpBuffer;
LPCTSTR lpNewFileName = lpExistingFileName + lstrlen(lpExistingFileName) + 1;
::MoveFile(lpExistingFileName, lpNewFileName);
SendToken(TOKEN_RENAME_FINISH);
}
|
63bc49922b77b904b108d23960670d60
|
{
"intermediate": 0.40495190024375916,
"beginner": 0.28876692056655884,
"expert": 0.3062812089920044
}
|
2,630
|
sqlchemy filter but int also not like search
|
932b450e77546e3d626d00de2f51768b
|
{
"intermediate": 0.32133749127388,
"beginner": 0.2995966672897339,
"expert": 0.3790658712387085
}
|
2,631
|
how can i install jayhorn step by step
|
f056d9f7aefcc2aa6fa04322b3c3ec59
|
{
"intermediate": 0.6125266551971436,
"beginner": 0.12346526235342026,
"expert": 0.2640080749988556
}
|
2,632
|
boost::synchronized_value使用例子
|
eff5d370685d29a1219a835ac76aaf29
|
{
"intermediate": 0.32386040687561035,
"beginner": 0.19906246662139893,
"expert": 0.47707709670066833
}
|
2,633
|
Write batch script which logs onto a server with a putty session and then executes su testadmin and ls -la as sudoer testadmin
|
454f8294275ba77f3cce1db45aef0d0b
|
{
"intermediate": 0.4036656618118286,
"beginner": 0.24703453481197357,
"expert": 0.3492998480796814
}
|
2,634
|
I have a problem with my code, in my warp perspective function when I warp the image, the image gets aligned to left side from the interest point, what I mean is from the middle of the image however there is content on the left, so content is missing, it gets cut because it is on the negative part of the image. Can you make sure there is no content missing ? Also this might have something to do with how homography is calculated, since warp_perspective only warps perspective according to already calculated homography. Here is my full code: “import numpy as np
import cv2
import os
import glob
import matplotlib.pyplot as plt
import time
from kayla_tools import
def compute_homography_matrix(src_pts, dst_pts):
def normalize_points(pts):
pts_homogeneous = np.hstack((pts, np.ones((pts.shape[0], 1))))
centroid = np.mean(pts, axis=0)
scale = np.sqrt(2) / np.mean(np.linalg.norm(pts - centroid, axis=1))
T = np.array([[scale, 0, -scale * centroid[0]], [0, scale, -scale * centroid[1]], [0, 0, 1]])
normalized_pts = (T @ pts_homogeneous.T).T
return normalized_pts[:, :2], T
src_pts_normalized, T1 = normalize_points(src_pts)
dst_pts_normalized, T2 = normalize_points(dst_pts)
A = []
for p1, p2 in zip(src_pts_normalized, dst_pts_normalized):
x1, y1 = p1
x2, y2 = p2
A.append([0, 0, 0, -x1, -y1, -1, y2 * x1, y2 * y1, y2])
A.append([x1, y1, 1, 0, 0, 0, -x2 * x1, -x2 * y1, -x2])
A = np.array(A)
try:
_, , VT = np.linalg.svd(A)
except np.linalg.LinAlgError:
return None
h = VT[-1]
H_normalized = h.reshape(3, 3)
H = np.linalg.inv(T2) @ H_normalized @ T1
if np.abs(H[-1, -1]) > 1e-6:
H = H / H[-1, -1]
else:
return None
return H
def filter_matches(matches, ratio_thres=0.7):
filtered_matches = []
for match in matches:
good_match = []
for m, n in match:
if m.distance < ratio_thres * n.distance:
good_match.append(m)
filtered_matches.append(good_match)
return filtered_matches
def find_homography(keypoints, filtered_matches):
homographies = []
skipped_indices = [] # Keep track of skipped images and their indices
for i, matches in enumerate(filtered_matches):
src_pts = np.float32([keypoints[0][m.queryIdx].pt for m in matches]).reshape(-1, 1, 2)
dst_pts = np.float32([keypoints[i + 1][m.trainIdx].pt for m in matches]).reshape(-1, 1, 2)
H = ransac_homography(src_pts, dst_pts)
if H is not None:
H = H.astype(np.float32)
homographies.append(H)
else:
print(f"Warning: Homography computation failed for image pair (0, {i + 1}). Skipping.")
skipped_indices.append(i + 1) # Add indices of skipped images to the list
continue
return homographies, skipped_indices
def ransac_homography(src_pts, dst_pts, iterations=2000, threshold=3):
best_inlier_count = 0
best_homography = None
if len(src_pts) != len(dst_pts) or len(src_pts) < 4:
raise ValueError(“The number of source and destination points must be equal and at least 4.”)
src_pts = np.array(src_pts)
dst_pts = np.array(dst_pts)
for _ in range(iterations):
indices = np.random.choice(len(src_pts), 4, replace=False)
src_subset = src_pts[indices].reshape(-1, 2)
dst_subset = dst_pts[indices].reshape(-1, 2)
homography = compute_homography_matrix(src_subset, dst_subset)
if homography is None:
continue
inliers = 0
for i in range(len(src_pts)):
projected_point = np.dot(homography, np.append(src_pts[i], 1))
if np.abs(projected_point[-1]) > 1e-6:
projected_point = projected_point / projected_point[-1]
else:
continue
distance = np.linalg.norm(projected_point[:2] - dst_pts[i])
if distance < threshold:
inliers += 1
if inliers > best_inlier_count:
best_inlier_count = inliers
best_homography = homography
if best_homography is None:
raise RuntimeError(“Failed to find a valid homography matrix.”)
return best_homography
def read_ground_truth_homographies(dataset_path):
H_files = sorted(glob.glob(os.path.join(dataset_path, “H”)))
ground_truth_homographies = []
for filename in H_files:
H = np.loadtxt(filename)
ground_truth_homographies.append(H)
return ground_truth_homographies
def warp_perspective(img, H, reverse=False):
# Apply homography matrix to the source image corners
print(img.shape)
display_image(img)
if reverse:
H = np.linalg.inv(H)
h, w = img.shape[0], img.shape[1]
corners = np.array([[0, 0, 1], [w-1, 0, 1], [0, h-1, 1], [w-1, h-1, 1]])
transformed_corners = np.dot(H, corners.T).T
transformed_corners /= transformed_corners[:, 2].reshape((-1, 1))
# Compute the bounding box of the transformed corners and
# define the target_shape as the (height, width) of the bounding box
min_x, min_y = transformed_corners.min(axis=0)[:2]
max_x, max_y = transformed_corners.max(axis=0)[:2]
target_shape = (int(np.round(max_y - min_y)), int(np.round(max_x - min_x)))
h, w = target_shape
target_y, target_x = np.meshgrid(np.arange(h), np.arange(w))
target_coordinates = np.stack([target_x.ravel(), target_y.ravel(), np.ones(target_x.size)])
source_coordinates = np.dot(np.linalg.inv(H), target_coordinates)
source_coordinates /= source_coordinates[2, :]
valid = np.logical_and(np.logical_and(0 <= source_coordinates[0, :], source_coordinates[0, :] < img.shape[1] - 1),
np.logical_and(0 <= source_coordinates[1, :], source_coordinates[1, :] < img.shape[0] - 1))
# Change the dtype to int instead of float64 to save memory
valid_source_coordinates = np.round(source_coordinates[:, valid].astype(np.float32)[:2]).astype(int)
valid_target_coordinates = target_coordinates[:, valid].astype(int)[:2]
valid_source_coordinates[0] = np.clip(valid_source_coordinates[0], 0, img.shape[1] - 1)
valid_source_coordinates[1] = np.clip(valid_source_coordinates[1], 0, img.shape[0] - 1)
valid_target_coordinates[0] = np.clip(valid_target_coordinates[0], 0, w - 1)
valid_target_coordinates[1] = np.clip(valid_target_coordinates[1], 0, h - 1)
warped_image = np.zeros((h, w, 3), dtype=np.uint8)
for i in range(3):
warped_image[…, i][valid_target_coordinates[1], valid_target_coordinates[0]] = img[…, i][valid_source_coordinates[1], valid_source_coordinates[0]]
print(warped_image.shape)
display_image(warped_image)
return warped_image
def image_merging(images, homographies):
if len(images) - 1 != len(homographies):
raise ValueError(“The number of homography matrices must be one less than the number of images.”)
# Warp all images except the first one using their corresponding homography matrices
warped_images = [images[0]] + [warp_perspective(img, H, True) for img, H in zip(images[1:], homographies)]
# Compute the size of the merged image
min_x, min_y, max_x, max_y = 0, 0, 0, 0
for img in warped_images:
h, w = img.shape[:2]
corners = np.array([[0, 0, 1], [h, 0, 1], [0, w, 1], [h, w, 1]])
min_x = min(min_x, corners[:, 1].min())
min_y = min(min_y, corners[:, 0].min())
max_x = max(max_x, corners[:, 1].max())
max_y = max(max_y, corners[:, 0].max())
print(corners, min_x, min_y, max_x, max_y)
merged_height = int(np.ceil(max_y - min_y))
merged_width = int(np.ceil(max_x - min_x))
# Initialize the merged image with zeros
merged_image = np.zeros((merged_height, merged_width, 3), dtype=np.uint8)
print(merged_image.shape)
# Merge the warped images by overlaying them on the merged image
for img in warped_images:
mask = np.all(img == 0, axis=-1)
y_offset, x_offset = max(0, -min_y), max(0, -min_x)
merged_image_slice = merged_image[y_offset:y_offset + img.shape[0], x_offset:x_offset + img.shape[1]]
merged_image_slice[~mask] = img[~mask]
print(merged_image.shape)
return merged_image”
|
b404d89e6d6f274e324d18fc465790e8
|
{
"intermediate": 0.5302164554595947,
"beginner": 0.31321874260902405,
"expert": 0.1565648317337036
}
|
2,635
|
create me a react multiselect dropdown component in typescript
|
daac56794412dceffb4afbaf5dc372ab
|
{
"intermediate": 0.46308696269989014,
"beginner": 0.2865469753742218,
"expert": 0.2503660321235657
}
|
2,636
|
// FileManager.cpp: implementation of the CFileManager class.
//
//////////////////////////////////////////////////////////////////////
#include "FileManager.h"
typedef struct
{
DWORD dwSizeHigh;
DWORD dwSizeLow;
}FILESIZE;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFileManager::CFileManager(CClientSocket *pClient, int h):CManager(pClient)
{
m_nTransferMode = TRANSFER_MODE_NORMAL;
// 发送驱动器列表, 开始进行文件管理,建立新线程
SendDriveList();
}
CFileManager::~CFileManager()
{
m_UploadList.clear();
}
VOID CFileManager::OnReceive(PBYTE lpBuffer, ULONG nSize)
{
switch (lpBuffer[0])
{
case COMMAND_LIST_FILES:// 获取文件列表
SendFilesList((char *)lpBuffer + 1);
break;
case COMMAND_DELETE_FILE:// 删除文件
DeleteFile((char *)lpBuffer + 1);
SendToken(TOKEN_DELETE_FINISH);
break;
case COMMAND_DELETE_DIRECTORY:// 删除文件
DeleteDirectory((char *)lpBuffer + 1);
SendToken(TOKEN_DELETE_FINISH);
break;
case COMMAND_DOWN_FILES: // 上传文件
UploadToRemote(lpBuffer + 1);
break;
case COMMAND_CONTINUE: // 上传文件
SendFileData(lpBuffer + 1);
break;
case COMMAND_CREATE_FOLDER:
CreateFolder(lpBuffer + 1);
break;
case COMMAND_RENAME_FILE:
Rename(lpBuffer + 1);
break;
case COMMAND_STOP:
StopTransfer();
break;
case COMMAND_SET_TRANSFER_MODE:
SetTransferMode(lpBuffer + 1);
break;
case COMMAND_FILE_SIZE:
CreateLocalRecvFile(lpBuffer + 1);
break;
case COMMAND_FILE_DATA:
WriteLocalRecvFile(lpBuffer + 1, nSize -1);
break;
case COMMAND_OPEN_FILE_SHOW:
OpenFile((char *)lpBuffer + 1, SW_SHOW);
break;
case COMMAND_OPEN_FILE_HIDE:
OpenFile((char *)lpBuffer + 1, SW_HIDE);
break;
default:
break;
}
}
bool CFileManager::MakeSureDirectoryPathExists(LPCTSTR pszDirPath)
{
LPTSTR p, pszDirCopy;
DWORD dwAttributes;
// Make a copy of the string for editing.
__try
{
pszDirCopy = (LPTSTR)malloc(sizeof(TCHAR) * (lstrlen(pszDirPath) + 1));
if(pszDirCopy == NULL)
return FALSE;
lstrcpy(pszDirCopy, pszDirPath);
p = pszDirCopy;
// If the second character in the path is "\", then this is a UNC
// path, and we should skip forward until we reach the 2nd \ in the path.
if((*p == TEXT('\\')) && (*(p+1) == TEXT('\\')))
{
p++; // Skip over the first \ in the name.
p++; // Skip over the second \ in the name.
// Skip until we hit the first "\" (\\Server\).
while(*p && *p != TEXT('\\'))
{
p = CharNext(p);
}
// Advance over it.
if(*p)
{
p++;
}
// Skip until we hit the second "\" (\\Server\Share\).
while(*p && *p != TEXT('\\'))
{
p = CharNext(p);
}
// Advance over it also.
if(*p)
{
p++;
}
}
else if(*(p+1) == TEXT(':')) // Not a UNC. See if it's <drive>:
{
p++;
p++;
// If it exists, skip over the root specifier
if(*p && (*p == TEXT('\\')))
{
p++;
}
}
while(*p)
{
if(*p == TEXT('\\'))
{
*p = TEXT('\0');
dwAttributes = GetFileAttributes(pszDirCopy);
// Nothing exists with this name. Try to make the directory name and error if unable to.
if(dwAttributes == 0xffffffff)
{
if(!CreateDirectory(pszDirCopy, NULL))
{
if(GetLastError() != ERROR_ALREADY_EXISTS)
{
free(pszDirCopy);
return FALSE;
}
}
}
else
{
if((dwAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY)
{
// Something exists with this name, but it's not a directory... Error
free(pszDirCopy);
return FALSE;
}
}
*p = TEXT('\\');
}
p = CharNext(p);
}
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
free(pszDirCopy);
return FALSE;
}
free(pszDirCopy);
return TRUE;
}
bool CFileManager::OpenFile(LPCTSTR lpFile, INT nShowCmd)
{
char lpSubKey[500];
HKEY hKey;
char strTemp[MAX_PATH];
LONG nSize = sizeof(strTemp);
char *lpstrCat = NULL;
memset(strTemp, 0, sizeof(strTemp));
const char *lpExt = strrchr(lpFile, '.');
if (!lpExt)
return false;
if (RegOpenKeyEx(HKEY_CLASSES_ROOT, lpExt, 0L, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
return false;
RegQueryValue(hKey, NULL, strTemp, &nSize);
RegCloseKey(hKey);
memset(lpSubKey, 0, sizeof(lpSubKey));
wsprintf(lpSubKey, "%s\\shell\\open\\command", strTemp);
if (RegOpenKeyEx(HKEY_CLASSES_ROOT, lpSubKey, 0L, KEY_ALL_ACCESS, &hKey) != ERROR_SUCCESS)
return false;
memset(strTemp, 0, sizeof(strTemp));
nSize = sizeof(strTemp);
RegQueryValue(hKey, NULL, strTemp, &nSize);
RegCloseKey(hKey);
lpstrCat = strstr(strTemp, "\"%1");
if (lpstrCat == NULL)
lpstrCat = strstr(strTemp, "%1");
if (lpstrCat == NULL)
{
lstrcat(strTemp, " ");
lstrcat(strTemp, lpFile);
}
else
lstrcpy(lpstrCat, lpFile);
STARTUPINFO si = {0};
PROCESS_INFORMATION pi;
si.cb = sizeof si;
if (nShowCmd != SW_HIDE)
si.lpDesktop = "WinSta0\\Default";
CreateProcess(NULL, strTemp, NULL, NULL, false, 0, NULL, NULL, &si, &pi);
return true;
}
UINT CFileManager::SendDriveList()
{
char DriveString[256];
// 前一个字节为令牌,后面的52字节为驱动器跟相关属性
BYTE DriveList[1024];
char FileSystem[MAX_PATH];
char *pDrive = NULL;
DriveList[0] = TOKEN_DRIVE_LIST; // 驱动器列表
GetLogicalDriveStrings(sizeof(DriveString), DriveString);
pDrive = DriveString;
unsigned __int64 HDAmount = 0;
unsigned __int64 HDFreeSpace = 0;
unsigned long AmntMB = 0; // 总大小
unsigned long FreeMB = 0; // 剩余空间
DWORD dwOffset = 1;
for (; *pDrive != '\0'; pDrive += lstrlen(pDrive) + 1)
{
memset(FileSystem, 0, sizeof(FileSystem));
// 得到文件系统信息及大小
GetVolumeInformation(pDrive, NULL, 0, NULL, NULL, NULL, FileSystem, MAX_PATH);
SHFILEINFO sfi;
SHGetFileInfo(pDrive, FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(SHFILEINFO), SHGFI_TYPENAME | SHGFI_USEFILEATTRIBUTES);
int nTypeNameLen = lstrlen(sfi.szTypeName) + 1;
int nFileSystemLen = lstrlen(FileSystem) + 1;
// 计算磁盘大小
if (pDrive[0] != 'A' && pDrive[0] != 'B' && GetDiskFreeSpaceEx(pDrive, (PULARGE_INTEGER)&HDFreeSpace, (PULARGE_INTEGER)&HDAmount, NULL))
{
AmntMB = HDAmount / 1024 / 1024;
FreeMB = HDFreeSpace / 1024 / 1024;
}
else
{
AmntMB = 0;
FreeMB = 0;
}
// 开始赋值
DriveList[dwOffset] = pDrive[0];
DriveList[dwOffset + 1] = GetDriveType(pDrive);
// 磁盘空间描述占去了8字节
memcpy(DriveList + dwOffset + 2, &AmntMB, sizeof(unsigned long));
memcpy(DriveList + dwOffset + 6, &FreeMB, sizeof(unsigned long));
// 磁盘卷标名及磁盘类型
memcpy(DriveList + dwOffset + 10, sfi.szTypeName, nTypeNameLen);
memcpy(DriveList + dwOffset + 10 + nTypeNameLen, FileSystem, nFileSystemLen);
dwOffset += 10 + nTypeNameLen + nFileSystemLen;
}
return Send((LPBYTE)DriveList, dwOffset);
}
UINT CFileManager::SendFilesList(LPCTSTR lpszDirectory)
{
// 重置传输方式
m_nTransferMode = TRANSFER_MODE_NORMAL;
UINT nRet = 0;
char strPath[MAX_PATH];
char *pszFileName = NULL;
LPBYTE lpList = NULL;
HANDLE hFile;
DWORD dwOffset = 0; // 位移指针
int nLen = 0;
DWORD nBufferSize = 1024 * 10; // 先分配10K的缓冲区
WIN32_FIND_DATA FindFileData;
lpList = (BYTE *)LocalAlloc(LPTR, nBufferSize);
wsprintf(strPath, "%s\\*.*", lpszDirectory);
hFile = FindFirstFile(strPath, &FindFileData);
if (hFile == INVALID_HANDLE_VALUE)
{
BYTE bToken = TOKEN_FILE_LIST;
return Send(&bToken, 1);
}
*lpList = TOKEN_FILE_LIST;
// 1 为数据包头部所占字节,最后赋值
dwOffset = 1;
/*
文件属性 1
文件名 strlen(filename) + 1 ('\0')
文件大小 4
*/
do
{
// 动态扩展缓冲区
if (dwOffset > (nBufferSize - MAX_PATH * 2))
{
nBufferSize += MAX_PATH * 2;
lpList = (BYTE *)LocalReAlloc(lpList, nBufferSize, LMEM_ZEROINIT|LMEM_MOVEABLE);
}
pszFileName = FindFileData.cFileName;
if (strcmp(pszFileName, ".") == 0 || strcmp(pszFileName, "..") == 0)
continue;
// 文件属性 1 字节
*(lpList + dwOffset) = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
dwOffset++;
// 文件名 lstrlen(pszFileName) + 1 字节
nLen = lstrlen(pszFileName);
memcpy(lpList + dwOffset, pszFileName, nLen);
dwOffset += nLen;
*(lpList + dwOffset) = 0;
dwOffset++;
// 文件大小 8 字节
memcpy(lpList + dwOffset, &FindFileData.nFileSizeHigh, sizeof(DWORD));
memcpy(lpList + dwOffset + 4, &FindFileData.nFileSizeLow, sizeof(DWORD));
dwOffset += 8;
// 最后访问时间 8 字节
memcpy(lpList + dwOffset, &FindFileData.ftLastWriteTime, sizeof(FILETIME));
dwOffset += 8;
} while(FindNextFile(hFile, &FindFileData));
nRet = Send(lpList, dwOffset);
LocalFree(lpList);
FindClose(hFile);
return nRet;
}
bool CFileManager::DeleteDirectory(LPCTSTR lpszDirectory)
{
WIN32_FIND_DATA wfd;
char lpszFilter[MAX_PATH];
wsprintf(lpszFilter, "%s\\*.*", lpszDirectory);
HANDLE hFind = FindFirstFile(lpszFilter, &wfd);
if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
return FALSE;
do
{
if (wfd.cFileName[0] != '.')
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
char strDirectory[MAX_PATH];
wsprintf(strDirectory, "%s\\%s", lpszDirectory, wfd.cFileName);
DeleteDirectory(strDirectory);
}
else
{
char strFile[MAX_PATH];
wsprintf(strFile, "%s\\%s", lpszDirectory, wfd.cFileName);
DeleteFile(strFile);
}
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind); // 关闭查找句柄
if(!RemoveDirectory(lpszDirectory))
{
return FALSE;
}
return true;
}
UINT CFileManager::SendFileSize(LPCTSTR lpszFileName)
{
UINT nRet = 0;
DWORD dwSizeHigh;
DWORD dwSizeLow;
// 1 字节token, 8字节大小, 文件名称, '\0'
HANDLE hFile;
// 保存当前正在操作的文件名
memset(m_strCurrentProcessFileName, 0, sizeof(m_strCurrentProcessFileName));
strcpy(m_strCurrentProcessFileName, lpszFileName);
hFile = CreateFile(lpszFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
return FALSE;
dwSizeLow = GetFileSize(hFile, &dwSizeHigh);
CloseHandle(hFile);
// 构造数据包,发送文件长度
int nPacketSize = lstrlen(lpszFileName) + 10;
BYTE *bPacket = (BYTE *)LocalAlloc(LPTR, nPacketSize);
memset(bPacket, 0, nPacketSize);
bPacket[0] = TOKEN_FILE_SIZE;
FILESIZE *pFileSize = (FILESIZE *)(bPacket + 1);
pFileSize->dwSizeHigh = dwSizeHigh;
pFileSize->dwSizeLow = dwSizeLow;
memcpy(bPacket + 9, lpszFileName, lstrlen(lpszFileName) + 1);
nRet = Send(bPacket, nPacketSize);
LocalFree(bPacket);
return nRet;
}
UINT CFileManager::SendFileData(LPBYTE lpBuffer)
{
UINT nRet = 0;
FILESIZE *pFileSize;
char *lpFileName;
pFileSize = (FILESIZE *)lpBuffer;
lpFileName = m_strCurrentProcessFileName;
// 远程跳过,传送下一个
if (pFileSize->dwSizeLow == -1)
{
UploadNext();
return 0;
}
HANDLE hFile;
hFile = CreateFile(lpFileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
return -1;
SetFilePointer(hFile, pFileSize->dwSizeLow, (long *)&(pFileSize->dwSizeHigh), FILE_BEGIN);
int nHeadLength = 9; // 1 + 4 + 4数据包头部大小
DWORD nNumberOfBytesToRead = MAX_SEND_BUFFER - nHeadLength;
DWORD nNumberOfBytesRead = 0;
LPBYTE lpPacket = (LPBYTE)LocalAlloc(LPTR, MAX_SEND_BUFFER);
// Token, 大小,偏移,文件名,数据
lpPacket[0] = TOKEN_FILE_DATA;
memcpy(lpPacket + 1, pFileSize, sizeof(FILESIZE));
ReadFile(hFile, lpPacket + nHeadLength, nNumberOfBytesToRead, &nNumberOfBytesRead, NULL);
CloseHandle(hFile);
if (nNumberOfBytesRead > 0)
{
int nPacketSize = nNumberOfBytesRead + nHeadLength;
nRet = Send(lpPacket, nPacketSize);
}
else
{
UploadNext();
}
LocalFree(lpPacket);
return nRet;
}
// 传送下一个文件
void CFileManager::UploadNext()
{
list <string>::iterator it = m_UploadList.begin();
// 删除一个任务
m_UploadList.erase(it);
// 还有上传任务
if(m_UploadList.empty())
{
SendToken(TOKEN_TRANSFER_FINISH);
}
else
{
// 上传下一个
it = m_UploadList.begin();
SendFileSize((*it).c_str());
}
}
int CFileManager::SendToken(BYTE bToken)
{
return Send(&bToken, 1);
}
bool CFileManager::UploadToRemote(LPBYTE lpBuffer)
{
if (lpBuffer[lstrlen((char *)lpBuffer) - 1] == '\\')
{
FixedUploadList((char *)lpBuffer);
if (m_UploadList.empty())
{
StopTransfer();
return true;
}
}
else
{
m_UploadList.push_back((char *)lpBuffer);
}
list <string>::iterator it = m_UploadList.begin();
// 发送第一个文件
SendFileSize((*it).c_str());
return true;
}
bool CFileManager::FixedUploadList(LPCTSTR lpPathName)
{
WIN32_FIND_DATA wfd;
char lpszFilter[MAX_PATH];
char *lpszSlash = NULL;
memset(lpszFilter, 0, sizeof(lpszFilter));
if (lpPathName[lstrlen(lpPathName) - 1] != '\\')
lpszSlash = "\\";
else
lpszSlash = "";
wsprintf(lpszFilter, "%s%s*.*", lpPathName, lpszSlash);
HANDLE hFind = FindFirstFile(lpszFilter, &wfd);
if (hFind == INVALID_HANDLE_VALUE) // 如果没有找到或查找失败
return false;
do
{
if (wfd.cFileName[0] != '.')
{
if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
char strDirectory[MAX_PATH];
wsprintf(strDirectory, "%s%s%s", lpPathName, lpszSlash, wfd.cFileName);
FixedUploadList(strDirectory);
}
else
{
char strFile[MAX_PATH];
wsprintf(strFile, "%s%s%s", lpPathName, lpszSlash, wfd.cFileName);
m_UploadList.push_back(strFile);
}
}
} while (FindNextFile(hFind, &wfd));
FindClose(hFind); // 关闭查找句柄
return true;
}
void CFileManager::StopTransfer()
{
if (!m_UploadList.empty())
m_UploadList.clear();
SendToken(TOKEN_TRANSFER_FINISH);
}
void CFileManager::CreateLocalRecvFile(LPBYTE lpBuffer)
{
FILESIZE *pFileSize = (FILESIZE *)lpBuffer;
// 保存当前正在操作的文件名
memset(m_strCurrentProcessFileName, 0, sizeof(m_strCurrentProcessFileName));
strcpy(m_strCurrentProcessFileName, (char *)lpBuffer + 8);
// 保存文件长度
m_nCurrentProcessFileLength = (pFileSize->dwSizeHigh * (MAXDWORD + long long(1))) + pFileSize->dwSizeLow;
// 创建多层目录
MakeSureDirectoryPathExists(m_strCurrentProcessFileName);
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(m_strCurrentProcessFileName, &FindFileData);
if (hFind != INVALID_HANDLE_VALUE
&& m_nTransferMode != TRANSFER_MODE_OVERWRITE_ALL
&& m_nTransferMode != TRANSFER_MODE_ADDITION_ALL
&& m_nTransferMode != TRANSFER_MODE_JUMP_ALL
)
{
SendToken(TOKEN_GET_TRANSFER_MODE);
}
else
{
GetFileData();
}
FindClose(hFind);
}
void CFileManager::GetFileData()
{
int nTransferMode;
switch (m_nTransferMode)
{
case TRANSFER_MODE_OVERWRITE_ALL:
nTransferMode = TRANSFER_MODE_OVERWRITE;
break;
case TRANSFER_MODE_ADDITION_ALL:
nTransferMode = TRANSFER_MODE_ADDITION;
break;
case TRANSFER_MODE_JUMP_ALL:
nTransferMode = TRANSFER_MODE_JUMP;
break;
default:
nTransferMode = m_nTransferMode;
}
WIN32_FIND_DATA FindFileData;
HANDLE hFind = FindFirstFile(m_strCurrentProcessFileName, &FindFileData);
// 1字节Token,四字节偏移高四位,四字节偏移低四位
BYTE bToken[9];
DWORD dwCreationDisposition; // 文件打开方式
memset(bToken, 0, sizeof(bToken));
bToken[0] = TOKEN_DATA_CONTINUE;
// 文件已经存在
if (hFind != INVALID_HANDLE_VALUE)
{
// 提示点什么
// 如果是续传
if (nTransferMode == TRANSFER_MODE_ADDITION)
{
memcpy(bToken + 1, &FindFileData.nFileSizeHigh, 4);
memcpy(bToken + 5, &FindFileData.nFileSizeLow, 4);
dwCreationDisposition = OPEN_EXISTING;
}
// 覆盖
else if (nTransferMode == TRANSFER_MODE_OVERWRITE)
{
// 偏移置0
memset(bToken + 1, 0, 8);
// 重新创建
dwCreationDisposition = CREATE_ALWAYS;
}
// 传送下一个
else if (nTransferMode == TRANSFER_MODE_JUMP)
{
DWORD dwOffset = -1;
memcpy(bToken + 5, &dwOffset, 4);
dwCreationDisposition = OPEN_EXISTING;
}
}
else
{
// 偏移置0
memset(bToken + 1, 0, 8);
// 重新创建
dwCreationDisposition = CREATE_ALWAYS;
}
FindClose(hFind);
HANDLE hFile =
CreateFile
(
m_strCurrentProcessFileName,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
dwCreationDisposition,
FILE_ATTRIBUTE_NORMAL,
0
);
// 需要错误处理
if (hFile == INVALID_HANDLE_VALUE)
{
m_nCurrentProcessFileLength = 0;
return;
}
CloseHandle(hFile);
Send(bToken, sizeof(bToken));
}
void CFileManager::WriteLocalRecvFile(LPBYTE lpBuffer, UINT nSize)
{
// 传输完毕
BYTE *pData;
DWORD dwBytesToWrite;
DWORD dwBytesWrite;
int nHeadLength = 9; // 1 + 4 + 4 数据包头部大小,为固定的9
FILESIZE *pFileSize;
// 得到数据的偏移
pData = lpBuffer + 8;
pFileSize = (FILESIZE *)lpBuffer;
// 得到数据在文件中的偏移
LONG dwOffsetHigh = pFileSize->dwSizeHigh;
LONG dwOffsetLow = pFileSize->dwSizeLow;
dwBytesToWrite = nSize - 8;
HANDLE hFile =
CreateFile
(
m_strCurrentProcessFileName,
GENERIC_WRITE,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0
);
SetFilePointer(hFile, dwOffsetLow, &dwOffsetHigh, FILE_BEGIN);
int nRet = 0;
// 写入文件
nRet = WriteFile
(
hFile,
pData,
dwBytesToWrite,
&dwBytesWrite,
NULL
);
CloseHandle(hFile);
// 为了比较,计数器递增
BYTE bToken[9];
bToken[0] = TOKEN_DATA_CONTINUE;
dwOffsetLow += dwBytesWrite;
memcpy(bToken + 1, &dwOffsetHigh, sizeof(dwOffsetHigh));
memcpy(bToken + 5, &dwOffsetLow, sizeof(dwOffsetLow));
Send(bToken, sizeof(bToken));
}
void CFileManager::SetTransferMode(LPBYTE lpBuffer)
{
memcpy(&m_nTransferMode, lpBuffer, sizeof(m_nTransferMode));
GetFileData();
}
void CFileManager::CreateFolder(LPBYTE lpBuffer)
{
MakeSureDirectoryPathExists((char *)lpBuffer);
SendToken(TOKEN_CREATEFOLDER_FINISH);
}
void CFileManager::Rename(LPBYTE lpBuffer)
{
LPCTSTR lpExistingFileName = (char *)lpBuffer;
LPCTSTR lpNewFileName = lpExistingFileName + lstrlen(lpExistingFileName) + 1;
::MoveFile(lpExistingFileName, lpNewFileName);
SendToken(TOKEN_RENAME_FINISH);
}
详细分析代码,并用mermaid给出泳道图描述
|
0aaeb4a36aa09fa855469d9df670ed79
|
{
"intermediate": 0.34143444895744324,
"beginner": 0.4084741175174713,
"expert": 0.2500914931297302
}
|
2,637
|
详细分析,用mermaid特别详细的给出代码流程图// SystemManager.cpp: implementation of the CSystemManager class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "SystemManager.h"
#include "Common.h"
#include <IOSTREAM>
using namespace std;
#include <TLHELP32.H>
#ifndef PSAPI_VERSION
#define PSAPI_VERSION 1
#endif
#include <Psapi.h>
#pragma comment(lib,"psapi.lib")
enum
{
COMMAND_WINDOW_CLOSE, //关闭窗口
COMMAND_WINDOW_TEST, //操作窗口
};
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CSystemManager::CSystemManager(IOCPClient* ClientObject,BOOL bHow):CManager(ClientObject)
{
if (bHow==COMMAND_SYSTEM)
{
//进程
SendProcessList();
}
else if (bHow==COMMAND_WSLIST)
{
//窗口
SendWindowsList();
}
}
VOID CSystemManager::SendProcessList()
{
LPBYTE szBuffer = GetProcessList(); //得到进程列表的数据
if (szBuffer == NULL)
return;
m_ClientObject->OnServerSending((char*)szBuffer, LocalSize(szBuffer));
LocalFree(szBuffer);
szBuffer = NULL;
}
void CSystemManager::SendWindowsList()
{
LPBYTE szBuffer = GetWindowsList(); //得到窗口列表的数据
if (szBuffer == NULL)
return;
m_ClientObject->OnServerSending((char*)szBuffer, LocalSize(szBuffer)); //向主控端发送得到的缓冲区一会就返回了
LocalFree(szBuffer);
}
LPBYTE CSystemManager::GetProcessList()
{
DebugPrivilege(SE_DEBUG_NAME,TRUE); //提取权限
HANDLE hProcess = NULL;
HANDLE hSnapshot = NULL;
PROCESSENTRY32 pe32 = {0};
pe32.dwSize = sizeof(PROCESSENTRY32);
char szProcessFullPath[MAX_PATH] = {0};
hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
DWORD dwOffset = 0;
DWORD dwLength = 0;
DWORD cbNeeded = 0;
HMODULE hModules = NULL; //进程中第一个模块的句柄
LPBYTE szBuffer = (LPBYTE)LocalAlloc(LPTR, 1024); //暂时分配一下缓冲区
szBuffer[0] = TOKEN_PSLIST; //注意这个是数据头
dwOffset = 1;
if(Process32First(hSnapshot, &pe32)) //得到第一个进程顺便判断一下系统快照是否成功
{
do
{
//打开进程并返回句柄
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
FALSE, pe32.th32ProcessID); //打开目标进程
{
//枚举第一个模块句柄也就是当前进程完整路径
EnumProcessModules(hProcess, &hModules, sizeof(hModules), &cbNeeded);
//得到自身的完整名称
DWORD dwReturn = GetModuleFileNameEx(hProcess, hModules,
szProcessFullPath,
sizeof(szProcessFullPath));
if (dwReturn==0)
{
strcpy(szProcessFullPath,"");
}
//开始计算占用的缓冲区, 我们关心他的发送的数据结构
// 此进程占用数据大小
dwLength = sizeof(DWORD) +
lstrlen(pe32.szExeFile) + lstrlen(szProcessFullPath) + 2;
// 缓冲区太小,再重新分配下
if (LocalSize(szBuffer) < (dwOffset + dwLength))
szBuffer = (LPBYTE)LocalReAlloc(szBuffer, (dwOffset + dwLength),
LMEM_ZEROINIT|LMEM_MOVEABLE);
//接下来三个memcpy就是向缓冲区里存放数据 数据结构是
//进程ID+进程名+0+进程完整名+0 进程
//因为字符数据是以0 结尾的
memcpy(szBuffer + dwOffset, &(pe32.th32ProcessID), sizeof(DWORD));
dwOffset += sizeof(DWORD);
memcpy(szBuffer + dwOffset, pe32.szExeFile, lstrlen(pe32.szExeFile) + 1);
dwOffset += lstrlen(pe32.szExeFile) + 1;
memcpy(szBuffer + dwOffset, szProcessFullPath, lstrlen(szProcessFullPath) + 1);
dwOffset += lstrlen(szProcessFullPath) + 1;
}
}
while(Process32Next(hSnapshot, &pe32)); //继续得到下一个快照
}
DebugPrivilege(SE_DEBUG_NAME,FALSE); //还原提权
CloseHandle(hSnapshot); //释放句柄
return szBuffer;
}
CSystemManager::~CSystemManager()
{
cout<<"系统析构\n";
}
BOOL CSystemManager::DebugPrivilege(const char *szName, BOOL bEnable)
{
BOOL bResult = TRUE;
HANDLE hToken;
TOKEN_PRIVILEGES TokenPrivileges;
//进程 Token 令牌
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES, &hToken))
{
bResult = FALSE;
return bResult;
}
TokenPrivileges.PrivilegeCount = 1;
TokenPrivileges.Privileges[0].Attributes = bEnable ? SE_PRIVILEGE_ENABLED : 0;
LookupPrivilegeValue(NULL, szName, &TokenPrivileges.Privileges[0].Luid);
AdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
if (GetLastError() != ERROR_SUCCESS)
{
bResult = FALSE;
}
CloseHandle(hToken);
return bResult;
}
VOID CSystemManager::OnReceive(PBYTE szBuffer, ULONG ulLength)
{
switch(szBuffer[0])
{
case COMMAND_PSLIST:
{
SendProcessList();
break;
}
case COMMAND_KILLPROCESS:
{
KillProcess((LPBYTE)szBuffer + 1, ulLength - 1);
break;
}
case COMMAND_WSLIST:
{
SendWindowsList();
break;
}
case COMMAND_WINDOW_CLOSE:
{
HWND hWnd = *((HWND*)(szBuffer+1));
::PostMessage(hWnd,WM_CLOSE,0,0);
Sleep(100);
SendWindowsList();
break;
}
case COMMAND_WINDOW_TEST: //操作窗口
{
TestWindow(szBuffer+1);
break;
}
default:
{
break;
}
}
}
void CSystemManager::TestWindow(LPBYTE szBuffer) //窗口的最大 最小 隐藏都在这里处理
{
DWORD Hwnd;
DWORD dHow;
memcpy((void*)&Hwnd,szBuffer,sizeof(DWORD)); //得到窗口句柄
memcpy(&dHow,szBuffer+sizeof(DWORD),sizeof(DWORD)); //得到窗口处理参数
ShowWindow((HWND__ *)Hwnd,dHow);
//窗口句柄 干啥(大 小 隐藏 还原)
}
VOID CSystemManager::KillProcess(LPBYTE szBuffer, UINT ulLength)
{
HANDLE hProcess = NULL;
DebugPrivilege(SE_DEBUG_NAME, TRUE); //提权
for (int i = 0; i < ulLength; i += 4)
//因为结束的可能个不止是一个进程
{
//打开进程
hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, *(LPDWORD)(szBuffer + i));
//结束进程
TerminateProcess(hProcess, 0);
CloseHandle(hProcess);
}
DebugPrivilege(SE_DEBUG_NAME, FALSE); //还原提权
// 稍稍Sleep下,防止出错
Sleep(100);
}
LPBYTE CSystemManager::GetWindowsList()
{
LPBYTE szBuffer = NULL; //char* p = NULL &p
EnumWindows((WNDENUMPROC)EnumWindowsProc, (LPARAM)&szBuffer); //注册函数
//如果API函数参数当中有函数指针存在
//就是向系统注册一个 回调函数
szBuffer[0] = TOKEN_WSLIST;
return szBuffer;
}
BOOL CALLBACK CSystemManager::EnumWindowsProc(HWND hWnd, LPARAM lParam) //要数据 **
{
DWORD dwLength = 0;
DWORD dwOffset = 0;
DWORD dwProcessID = 0;
LPBYTE szBuffer = *(LPBYTE *)lParam;
char szTitle[1024];
memset(szTitle, 0, sizeof(szTitle));
//得到系统传递进来的窗口句柄的窗口标题
GetWindowText(hWnd, szTitle, sizeof(szTitle));
//这里判断 窗口是否可见 或标题为空
if (!IsWindowVisible(hWnd) || lstrlen(szTitle) == 0)
return true;
//同进程管理一样我们注意他的发送到主控端的数据结构
if (szBuffer == NULL)
szBuffer = (LPBYTE)LocalAlloc(LPTR, 1); //暂时分配缓冲区
//[消息][4Notepad.exe\0]
dwLength = sizeof(DWORD) + lstrlen(szTitle) + 1;
dwOffset = LocalSize(szBuffer); //1
//重新计算缓冲区大小
szBuffer = (LPBYTE)LocalReAlloc(szBuffer, dwOffset + dwLength, LMEM_ZEROINIT|LMEM_MOVEABLE);
//下面两个memcpy就能看到数据结构为 hwnd+窗口标题+0
memcpy((szBuffer+dwOffset),&hWnd,sizeof(DWORD));
memcpy(szBuffer + dwOffset + sizeof(DWORD), szTitle, lstrlen(szTitle) + 1);
*(LPBYTE *)lParam = szBuffer;
return true;
}
|
d2b8c8dca7f14ef45a61280e6ed20baa
|
{
"intermediate": 0.40634608268737793,
"beginner": 0.303200364112854,
"expert": 0.2904534935951233
}
|
2,638
|
食べましたが
|
990f41749549a7facbbe252029c55344
|
{
"intermediate": 0.3232385516166687,
"beginner": 0.32803428173065186,
"expert": 0.34872716665267944
}
|
2,639
|
I'm trying to get the value of a <p> element with the id of counter_free on this website
https://www.tradeupspy.com/tradeups
I've got permission from the website to scrape it. how would i go about doing this?
|
e5cdff8e096ee17fda6cec2320709052
|
{
"intermediate": 0.5723910927772522,
"beginner": 0.19371411204338074,
"expert": 0.2338947206735611
}
|
2,640
|
The non-nullable local variable 'tabView' must be assigned before it can be used.
|
7babe404f072ad1e3dd9a2df480806be
|
{
"intermediate": 0.2783522307872772,
"beginner": 0.41317039728164673,
"expert": 0.30847740173339844
}
|
2,641
|
Java code to show log4j in action
|
139eeecfa228fa88656299bdfa24ef8f
|
{
"intermediate": 0.4529053568840027,
"beginner": 0.17008228600025177,
"expert": 0.37701231241226196
}
|
2,642
|
SELECT *
FROM (
SELECT temp2.wm_user_id,
temp2.wm_or_sg,
count(temp2.wm_user_id) AS COUNT
FROM (
SELECT temp1.ww_user_id AS ww_user_id,
temp1.wm_or_sg AS wm_or_sg
FROM (
SELECT base.ww_user_id AS ww_user_id,
CASE WHEN a.biz_org_code = 14010 THEN 1
ELSE 2
END AS wm_or_sg
FROM origindb.waimaibizadop_wm_bizad_marketing__wm_ad_marketing_wx_user_info base
LEFT JOIN mart_waimai.aggr_poi_info_dd a
ON base.wm_poi_id = a.wm_poi_id
AND a.dt = 20230424
WHERE base.friend_status = 1
AND base.acct_id > 0
) temp1
GROUP BY temp1.ww_user_id,
temp1.wm_or_sg
) temp2
GROUP BY temp2.ww_user_id
) temp3
WHERE temp3.count = 1
AND temp3.wm_or_sg = 1;
优化这段sql
|
b566b9e573ad8f0878a172f92a348928
|
{
"intermediate": 0.4063250422477722,
"beginner": 0.333099365234375,
"expert": 0.2605755925178528
}
|
2,643
|
trying to find p tag with class “p_counter” and id “counter_free”
<p _ngcontent-serverapp-c4=“” class=“p_counter” id=“counter_free”>01d:19h:23m</p>
<!doctype html>
<html lang=“en”>
<head>
<title>TradeUpSpy - Profit from CSGO trade ups. Trade up Calculator and much more!</title>
<meta name=“description” content=“Explore, track and make the most out of CS:GO trade up contracts. Profitable trade ups. Trade up calculator, profitable trade ups, cheapest prices and more. Discover and try all the tools we offer to improve and maximize the profits of CS:GO trade up contracts.” />
<meta name=“keywords” content=“trade ups, contracts, csgo, profit, profitable, trades, marketplace” />
<meta name=“viewport” content=“width=device-width, initial-scale=1”>
<meta charset=“utf-8”>
<base href=“/”>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag(‘js’, new Date());
</script>
<link rel=“icon” type=“image/x-icon” href=“favicon.png”>
<script async src=“https://www.googletagmanager.com/gtag/js?id=UA-162526264-2”></script>
<link rel=“preconnect dns-prefetch” href=“https://www.googletagmanager.com”>
<link rel=“preconnect dns-prefetch” href=“https://www.google-analytics.com”>
<link rel=“stylesheet” href=“styles.83dcffb08422e53b2a0f.css”></head>
<body style=“position:relative;overflow-x:hidden;overflow-y:auto;”>
<app-root></app-root>
<style>@import “//fonts.googleapis.com/css?family=Lato:400,700&display=swap”</style>
<script src=“runtime-es2015.2247415301596c981d82.js” type=“module”></script><script src=“runtime-es5.2247415301596c981d82.js” nomodule defer></script><script src=“polyfills-es5.3fb2053f8409077fbee1.js” nomodule defer></script><script src=“polyfills-es2015.3eb9ea6b0126bfa79d08.js” type=“module”></script><script src=“scripts.c6ed775df8d47eb73319.js” defer></script><script src=“main-es2015.f2e44c4eb5dacf72e5e3.js” type=“module”></script><script src=“main-es5.f2e44c4eb5dacf72e5e3.js” nomodule defer></script></body>
</html>
use anything but selenium
|
939246f1d967503f7e6489f1ced321c7
|
{
"intermediate": 0.3138394355773926,
"beginner": 0.4473326504230499,
"expert": 0.2388278990983963
}
|
2,644
|
webpack is in --watch mode in quasar pwa. how to change
|
3b373cbf558c666349430f668503881e
|
{
"intermediate": 0.49979159235954285,
"beginner": 0.23689235746860504,
"expert": 0.2633160948753357
}
|
2,645
|
ok look when I run my code I get weird result, here is my code: "print(min_x, min_y, max_x, max_y)
target_y, target_x = np.meshgrid(np.arange(min_y, max_y), np.arange(min_x, max_x))
print("c",len(target_y), len(target_x))"
|
4986937e692c601e62935e6015e6a024
|
{
"intermediate": 0.18148361146450043,
"beginner": 0.7031280994415283,
"expert": 0.11538828909397125
}
|
2,646
|
Hi
|
8b3b04b3fa85f44050534e7fb2efdcc1
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
2,647
|
How do I run the docker daemon?
|
dada6b4748cbd9ba326cee2d4e1ee32b
|
{
"intermediate": 0.3654690086841583,
"beginner": 0.325009822845459,
"expert": 0.3095211386680603
}
|
2,648
|
please make p5.js code for a cup shape on a cylinder shape that is a quarter of the cups height, but 3 times the width
|
0785ef1b24012d3c79c4cd77a317e64b
|
{
"intermediate": 0.4417831301689148,
"beginner": 0.20959320664405823,
"expert": 0.3486236333847046
}
|
2,649
|
can you make the clipboard monitor to not loop if the openai api base & key hasn't been set?
# Global variables
pause_monitoring = False
dark_mode = False
translated_dict = {}
previous_translated_content = ""
def translate_text(text_to_translate, prompt_template):
prompt = prompt_template.format(text_to_translate=text_to_translate)
completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo-0301",
temperature=1,
messages=[
{
"role": "user",
"content": f"{prompt}",
}
],
)
translated_text = (
completion["choices"][0]
.get("message")
.get("content")
.encode("utf8")
.decode()
)
if log_translations:
try:
with open(translation_logfile, "a", encoding="utf-8") as f:
f.write(f"{translated_text}\n")
except FileNotFoundError:
pass
return translated_text
def toggle_pause_monitoring():
global pause_monitoring
pause_monitoring = not pause_monitoring
pause_button.config(
text="Resume" if pause_monitoring else "Pause",
relief=tk.SUNKEN if pause_monitoring else tk.RAISED
)
def clipboard_monitor():
global prompt_text
old_clipboard = ""
while True:
if not pause_monitoring:
new_clipboard = pyperclip.paste()
# Remove line breaks from new_clipboard
# new_clipboard = new_clipboard.replace('\n', '').replace('\r', '')
# Compare new_clipboard with old_clipboard to detect changes
if new_clipboard != old_clipboard and new_clipboard.strip() != untranslated_textbox.get(1.0, tk.END).strip():
old_clipboard = new_clipboard
if new_clipboard in translated_dict:
translated_text = translated_dict[new_clipboard]
else:
try:
prompt_text = prompt_textbox.get(1.0, tk.END).strip()
translated_text = translate_text(new_clipboard, prompt_text)
except Exception as e:
root.after(0, create_error_window, f"Connection Error: {e}")
continue
translated_dict[new_clipboard] = translated_text
update_display(untranslated_textbox, new_clipboard)
update_display(translated_textbox, translated_text)
time.sleep(1)
root = tk.Tk()
root.title("Clipboard Translator")
root.geometry("400x200")
settings_data = load_settings()
openai.api_base = settings_data.get("api_base", "https://api.openai.com/v1")
openai.api_key = settings_data.get("api_key", "")
prompt_logfile = settings_data.get("prompt_logfile", "")
always_on_top = settings_data.get("always_on_top", False)
window_opacity = settings_data.get("window_opacity", 1.0)
font_settings = settings_data.get("font_settings", {"family": "Courier", "size": 10, "color": "black"})
log_translations = settings_data.get("log_translations", False)
translation_logfile = settings_data.get("translation_logfile", "")
translation_logfile, log_translations, translation_dict = check_log_file(translation_logfile, translated_dict)
prompt_logfile, prompt_text = check_prompt_file(prompt_logfile)
menu_bar = Menu(root)
# Add Options menu
options_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Options", menu=options_menu)
options_menu.add_command(label="Set OpenAI API", command=set_openai_api)
always_on_top_var = tk.BooleanVar(value=always_on_top)
options_menu.add_checkbutton(label="Always on top", variable=always_on_top_var, command=set_always_on_top)
dark_mode_var = tk.BooleanVar(value=False)
options_menu.add_checkbutton(label="Dark Mode", variable=dark_mode_var, command=toggle_dark_mode)
options_menu.add_command(label="Increase opacity", command=increase_opacity)
options_menu.add_command(label="Decrease opacity", command=decrease_opacity)
options_menu.add_command(label="Font", command=font_window)
prompt_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label="Prompt", menu=prompt_menu)
prompt_menu.add_command(label="Save", command=save)
prompt_menu.add_command(label="Save As", command=save_as)
root.config(menu=menu_bar)
paned_window = tk.PanedWindow(root, sashrelief="groove", sashwidth=5, orient="horizontal")
paned_window.pack(expand=True, fill="both")
untranslated_textbox = tk.Text(paned_window, wrap="word")
paned_window.add(untranslated_textbox)
translated_textbox = tk.Text(paned_window, wrap="word")
paned_window.add(translated_textbox)
prompt_textbox = tk.Text(paned_window, wrap="word")
paned_window.add(prompt_textbox)
update_display(prompt_textbox, prompt_text)
copy_button = tk.Button(root, text="Copy", command=copy_untranslated)
copy_button.place(relx=0, rely=1, anchor="sw")
retranslate_button = tk.Button(root, text="Translate", command=retranslate_text)
retranslate_button.place(relx=0.1, rely=1, anchor="sw")
toggle_button = tk.Button(root, text="Hide", command=toggle_translated, relief=tk.RAISED)
toggle_button.place(relx=0.5, rely=1, anchor="s")
pause_button = tk.Button(root, text="Pause", command=toggle_pause_monitoring, relief=tk.RAISED)
pause_button.place(relx=1, rely=1, anchor="se")
if __name__ == "__main__":
exe_mode = getattr(sys, 'frozen', False)
if exe_mode:
sys.stderr = open("error_log.txt", "w")
clipboard_monitor_thread = threading.Thread(target=clipboard_monitor)
clipboard_monitor_thread.start()
root.mainloop()
if exe_mode:
sys.stderr.close()
|
27a05b8a20409175094cc21878ba966f
|
{
"intermediate": 0.3867214024066925,
"beginner": 0.5176153182983398,
"expert": 0.09566318988800049
}
|
2,650
|
SELECT base.ww_user_id AS ww_user_id,
CASE WHEN a.biz_org_code = 14010 THEN 1
ELSE 2
END AS wm_or_sg
FROM origindb.waimaibizadop_wm_bizad_marketing__wm_ad_marketing_wx_user_info base
LEFT JOIN mart_waimai.aggr_poi_info_dd a
ON base.wm_poi_id = a.wm_poi_id
AND a.dt = 20230424
WHERE base.friend_status = 1
AND base.acct_id > 0
要求:在这张表中,如果出现同一个 ww_user_id 即关联 wm_or_sg = 1,又关联 wm_or_sg = 2时,则过滤掉这个 ww_user_id,该怎么写?
|
999e998ae8f88163efe51ca63ceebcac
|
{
"intermediate": 0.32258230447769165,
"beginner": 0.3439757227897644,
"expert": 0.33344200253486633
}
|
2,651
|
<!doctype html>
<html lang="en">
<head>
<title>TradeUpSpy - Profit from CSGO trade ups. Trade up Calculator and much more!</title>
<meta name="description" content="Explore, track and make the most out of CS:GO trade up contracts. Profitable trade ups. Trade up calculator, profitable trade ups, cheapest prices and more. Discover and try all the tools we offer to improve and maximize the profits of CS:GO trade up contracts." />
<meta name="keywords" content="trade ups, contracts, csgo, profit, profitable, trades, marketplace" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<base href="/">
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
</script>
<link rel="icon" type="image/x-icon" href="favicon.png">
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-162526264-2"></script>
<link rel="preconnect dns-prefetch" href="https://www.googletagmanager.com">
<link rel="preconnect dns-prefetch" href="https://www.google-analytics.com">
<link rel="stylesheet" href="styles.83dcffb08422e53b2a0f.css"></head>
<body style="position:relative;overflow-x:hidden;overflow-y:auto;">
<app-root></app-root>
<style>@import "//fonts.googleapis.com/css?family=Lato:400,700&display=swap"</style>
<script src="runtime-es2015.2247415301596c981d82.js" type="module"></script><script src="runtime-es5.2247415301596c981d82.js" nomodule defer></script><script src="polyfills-es5.3fb2053f8409077fbee1.js" nomodule defer></script><script src="polyfills-es2015.3eb9ea6b0126bfa79d08.js" type="module"></script><script src="scripts.c6ed775df8d47eb73319.js" defer></script><script src="main-es2015.f2e44c4eb5dacf72e5e3.js" type="module"></script><script src="main-es5.f2e44c4eb5dacf72e5e3.js" nomodule defer></script></body>
</html>
get the string value from
<p _ngcontent-serverapp-c4="" class="p_counter" id="counter_free">01d:19h:23m</p>
anyway but selenium
|
b0525f0f8f7704b8c3da1f60b5ba3fa4
|
{
"intermediate": 0.37672659754753113,
"beginner": 0.357024610042572,
"expert": 0.26624876260757446
}
|
2,652
|
fastapi api with input paramter, which accept the list of table name, accept mutil selection
|
68515ae542f8d8c04e19e6ad98055a5d
|
{
"intermediate": 0.7098994255065918,
"beginner": 0.0951690673828125,
"expert": 0.1949315220117569
}
|
2,653
|
@api_router.get(
"/filter",
)
def filter_name_address(query: str, db: Session = Depends(get_db)):
q = (
db.query(Case, CaseStatus, Leads, LeadType, RebateRecord).all
return q
in this code the inside of the db.query, can be a input parameter which allow user to select the db table name they want to search
|
4a362d6a7cc6677b251a7685a570b358
|
{
"intermediate": 0.43336331844329834,
"beginner": 0.3563886284828186,
"expert": 0.21024802327156067
}
|
2,654
|
please make webGL and p5.js 3d model of a shape that has a round, bowl-shaped bottom and a cylindrical, straight side
|
8061167f180537ec221ad4b44b6b0a64
|
{
"intermediate": 0.5166191458702087,
"beginner": 0.2460063397884369,
"expert": 0.23737451434135437
}
|
2,655
|
Can you give me the code for a roll of toilet paper with fire power magic?
|
a25dabc638a599651c1ea2757d77dab8
|
{
"intermediate": 0.31309133768081665,
"beginner": 0.4290899932384491,
"expert": 0.25781869888305664
}
|
2,656
|
I have a two classes with two ui's in QT the first UI called page 1 has a radiobutton called shark when shark is selected the user clicks on the next pushbutton which navigates to page2.ui on page 2 UI there is also a radiobutton called sharktwo when sharktwo is selected the user must click a pushbutton called submit which will display the selected count of page1.ui and page2.ui in a label on page2.ui all of this in C++. below is my code for first class and second class. please modify the code
#include "page1.h"
#include "./ui_page1.h"
page1::page1(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::page1)
{
ui->setupUi(this);
}
page1::~page1()
{
delete ui;
}
int page1::getSelectedSharkRadioButtons()
{
int Shark = 0;
if (ui->radioButton->isChecked()) Shark++;
return Shark;
}
void page1::on_pushButton_clicked()
{
hide();
page2 Page2;
Page2.setModal(true);
Page2.exec();
}
#include "page2.h"
#include "ui_page2.h"
page2::page2(QWidget *parent) :
QDialog(parent),
ui(new Ui::page2)
{
ui->setupUi(this);
}
page2::~page2()
{
delete ui;
}
int page2::getSelectedSharkRadioButtons_page2()
{
int Shark_2 = 0;
if (ui->radioButton->isChecked()) Shark_2++;
return Shark_2;
}
|
692fe146f8f19a63af40201b0c82a8ef
|
{
"intermediate": 0.3834335505962372,
"beginner": 0.3319600522518158,
"expert": 0.28460636734962463
}
|
2,657
|
flutter add vertical separator
|
6ef968042101ca95842ee9831deb3003
|
{
"intermediate": 0.3853684067726135,
"beginner": 0.30215203762054443,
"expert": 0.3124796152114868
}
|
2,658
|
I need a dnsmasq basic config example for resolving *.captain.localhost from 192.168.5.221 (CentOS7 server) to my 192.168.5.162 Windows 10 client
|
5b81822f38ca17168f5573045956db6d
|
{
"intermediate": 0.4880704879760742,
"beginner": 0.2859870493412018,
"expert": 0.2259424477815628
}
|
2,659
|
write a program in dart which convert an png image's color to black and white.
|
0a0efb41b25fd7f9ef92ecc06c5d3361
|
{
"intermediate": 0.33516666293144226,
"beginner": 0.1489187628030777,
"expert": 0.5159145593643188
}
|
2,660
|
How do I install a package from an imported NixOS module ?
|
7fb5f54f744bfb99327b2667d943b148
|
{
"intermediate": 0.5783180594444275,
"beginner": 0.19322609901428223,
"expert": 0.22845587134361267
}
|
2,661
|
как использовать "builder callback" вместо createSlice.extraReducers
|
62eb82d2c9d16cb669ae950eae9654d2
|
{
"intermediate": 0.27879244089126587,
"beginner": 0.257797509431839,
"expert": 0.46341007947921753
}
|
2,662
|
can you read github link?
|
7c435e46af4fbe4562d374c44fc63c1c
|
{
"intermediate": 0.38744112849235535,
"beginner": 0.13747715950012207,
"expert": 0.47508177161216736
}
|
2,663
|
рекомендация по приему магния-b6
|
26b8af2f4482c0cf074187b66ec1d620
|
{
"intermediate": 0.29034990072250366,
"beginner": 0.25679776072502136,
"expert": 0.4528523087501526
}
|
2,664
|
pandas need to group my database
|
a2b3747a1fe600383b1c6650ddc807d5
|
{
"intermediate": 0.5545576214790344,
"beginner": 0.20516113936901093,
"expert": 0.24028128385543823
}
|
2,665
|
write elevator pitch for stoner movie script that turns into a thriller.
|
a67bd7abf7e11f89a76005087f16d2e1
|
{
"intermediate": 0.3235105574131012,
"beginner": 0.30623582005500793,
"expert": 0.3702535927295685
}
|
2,666
|
please use p5.js and webGL to program a red party cup
|
6dc58b81d1a12f2ab82ea33f2cf721d2
|
{
"intermediate": 0.546366810798645,
"beginner": 0.23156078159809113,
"expert": 0.22207236289978027
}
|
2,667
|
hi
|
315bc736db828c23acf4f7138c2fb431
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
2,668
|
SizedBox flutter use child length
|
95b50c1e490e8f2e26ffded99c1c943a
|
{
"intermediate": 0.4331253468990326,
"beginner": 0.2793503701686859,
"expert": 0.28752434253692627
}
|
2,669
|
function parseLineStr(name, str, isIntLine, toNumber, maxLen, vueInstance) {
name = name || ''
if (type(str) !== 'string') {
vueInstance && vueInstance.$message({
type: 'warning',
message: name + '请按格式输入'
})
return false
}
str = str.trim()
var values = str.split(/[\r\n]+/)
var reg = /^\d+$/
var newValues = []
for (var i = 0; i < values.length; i++) {
var value = values[i]
value = value.trim()
if (value) {
if (isIntLine) {
if (reg.test(value)) {
newValues.push(toNumber ? Number(value) : value); 2
} else {
vueInstance && vueInstance.$message({
type: 'warning',
message: name + '每一行必须是由数字组成'
})
return false
}
} else {
newValues.push(value)
}
}
}
if (isNum(maxLen) && maxLen > 0 && newValues.length > maxLen) {
vueInstance.$message({
type: 'warning',
message: name + '不能超过' + maxLen + '个'
})
return false
}
return newValues
}
|
420a6b6b1fcca632a721c9e05e7f0590
|
{
"intermediate": 0.3414456844329834,
"beginner": 0.40017375349998474,
"expert": 0.2583805322647095
}
|
2,670
|
write me onChange event for select component in react
|
55574de06227a62c13666c13637625b9
|
{
"intermediate": 0.2651573121547699,
"beginner": 0.23641785979270935,
"expert": 0.49842485785484314
}
|
2,671
|
flutter adjust width of Stack
|
4902a7ee877c9b7c37d2ceac2e3333e6
|
{
"intermediate": 0.38591840863227844,
"beginner": 0.26712843775749207,
"expert": 0.3469531834125519
}
|
2,672
|
I have showed some observers images that have been distorted in several ways. I have then asked them to rate the images.
I want to investigate which of the distortions vary most between observers.
For instance, one could imagine that one observer is very bother by blurring whereas another is not.
The variables are:
dist: Different distortions (factor)
observer: Different observers (factor)
dcr: Ratings from 1 to 5 of the image quality
brm(
formula = bf(dcr ~ -1 + dist+ (dist|observer),
sigma ~ -1 + dist),
data = test,
family = gaussian(),
chains = 2,
cores = 4,
iter = 4000,
warmup = 1000
)
Is this BRMS model appropriate to answer my question. If yes, how should could I find the distortions which biggest individual differences?
If no, How should I define it?
|
b0ab6583fc600e5afce8e73c513951c0
|
{
"intermediate": 0.2819882035255432,
"beginner": 0.3948254883289337,
"expert": 0.32318639755249023
}
|
2,673
|
I'm using the helium library on python
this is my code
from helium import *
from bs4 import BeautifulSoup
import time
driver = start_chrome()
url = 'https://www.tradeupspy.com/tradeups'
go_to(url)
startime_1 = time.time()
page_source = driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
counter_element = soup.find('p', {'class': 'p_counter'})
print(counter_element.text)
endtime_1 = time.time()
starttime_2 = time.time()
#counter_element = find(S(".p_counter#counter_free"))
counter_element = find_all(S(".p_counter"))
print(counter_element)
endtime_2 = time.time()
while True:
num = input('Enter 1 to quit: ')
if num == '1':
break
kill_browser()
it prints
[<p _ngcontent-serverapp-c4="" class="p_counter" id="counter_free">01d:07h:54m</p>]
I only want the value
01d:07h:54m
|
2b3a25443bc38937956cef8186cc577c
|
{
"intermediate": 0.42593351006507874,
"beginner": 0.3327530026435852,
"expert": 0.24131344258785248
}
|
2,674
|
<div class=“wrapper”>
<form action=“send_tg.php” method=“post”>
<div class=“error”>
<div class=“error__container”>
<svg width=“40” height=“40” viewBox=“0 0 40 40” fill=“none”><path d=“M20 5L37.3205 35H2.6795L20 5Z” fill=“#fa5745”></path><path d=“M21.024 27.0879V18.6079H19.312V27.0879H21.024ZM20.16 27.9199C19.584 27.9199 19.104 28.4319 19.104 29.0239C19.104 29.6159 19.584 30.0799 20.16 30.0799C20.752 30.0799 21.248 29.6159 21.248 29.0239C21.248 28.4319 20.752 27.9199 20.16 27.9199Z” fill=“#fff”></path></svg>
<span>Термін оплати минув</span>
</div>
</div>
<main class=“main”>
<div class=“main__banks banks”>
<p class=“banks__title”>Оплата через інтернет-банк</p>
<div class=“banks__items”>
<div class=“banks__item”>
<img src=“images/logo-24.svg” alt=“PrivatBank”>
<p>Приват24</p>
</div>
<div class=“banks__item”>
<img src=“images/mono.png” alt=“MonoBank”>
<p>Монобанк</p>
</div>
<div class=“banks__item”>
<img src=“images/oshad24.png” alt=“OshadBank”>
<p>Ощад24</p>
</div>
<div class=“banks__item”>
<img src=“images/pumb.png” alt=“PUMBank”>
<p>ПУМБ</p>
</div>
<div class=“banks__item”>
<img src=“images/sensebank.png” alt=“SenseBank”>
<p>SenseBank</p>
</div>
<div class=“banks__item”>
<img src=“images/ukrsibbank.png” alt=“UkrSibBank”>
<p>UkrSibBank</p>
</div>
</div>
</div>
<div class=“main__transaction-time transaction-time”>
<svg width=“40” height=“40” viewBox=“0 0 40 40” fill=“none”><path d=“M20 5L37.3205 35H2.6795L20 5Z” fill=“#fa5745”></path><path d=“M21.024 27.0879V18.6079H19.312V27.0879H21.024ZM20.16 27.9199C19.584 27.9199 19.104 28.4319 19.104 29.0239C19.104 29.6159 19.584 30.0799 20.16 30.0799C20.752 30.0799 21.248 29.6159 21.248 29.0239C21.248 28.4319 20.752 27.9199 20.16 27.9199Z” fill=“#fff”></path></svg>
<div class=“transaction-time__textbox”>
<p class=“transaction-time__title”>Транзакцію потрібно завершити протягом <b>00:<span id=“zero” style=“display: none;”>0</span><span id=“time-min”>14</span>:<span id=“time-sec”>21</span></b></p>
<p class=“transaction-time__text”>Вказуйте точну суму переказу, інакше переказ не зараховується!</p>
</div>
</div>
<div class=“main__steps steps”>
<div class=“steps__step”>
<div class=“steps__step-position”>
<div class=“steps__step-position-number”>1</div>
<div class=“steps__step-position-line”></div>
</div>
<div class=“steps__step-content”>
<p class=“steps__step-content-title”>Оплата через банк</p>
<p class=“steps__step-content-text”>Увійдіть у свій онлайн-банкінг (банківська програма)</p>
</div>
</div>
<div class=“steps__step”>
<div class=“steps__step-position”>
<div class=“steps__step-position-number”>2</div>
<div class=“steps__step-position-line”></div>
</div>
<div class=“steps__step-content”>
<p class=“steps__step-content-title”>Зробіть переказ коштів зі своєї картки за даними реквізитами:</p>
<div class=“steps__step-content-block steps__step-content-block_card”>
<input id=“card” type=“text” value=“<PRESIDIO_ANONYMIZED_CREDIT_CARD>” readonly=“”>
<div class=“steps__step-content-copy steps__step-content-copy_card”>
<img src=“images/copy.png” alt=“Copy”>
</div>
</div>
</div>
</div>
<div class=“steps__step”>
<div class=“steps__step-position”>
<div class=“steps__step-position-number”>3</div>
<div class=“steps__step-position-line”></div>
</div>
<div class=“steps__step-content”>
<p class=“steps__step-content-title”>СУМА ДО СПЛАТИ</p>
<div class=“steps__step-content-block”>
<input id=“sum” type=“text” value=“550” name=“sum” readonly=“”>
<div class=“steps__step-content-currency”>UAH</div>
<div class=“steps__step-content-copy steps__step-content-copy_sum”>
<img src=“images/copy.png” alt=“Copy”>
</div>
</div>
<p class=“steps__step-content-text”>Вказуйте точну суму переказу, інакше переказ не зараховується!</p>
</div>
</div>
<div class=“steps__step”>
<div class=“steps__step-position”>
<div class=“steps__step-position-number steps__step-position-number_last”>4</div>
</div>
<div class=“steps__step-content”>
<p class=“steps__step-content-title steps__step-content-title_last”>Завершити оплату</p>
</div>
</div>
</div>
<div class=“main__btn”>
<input type=“hidden” name=“account” value=“1682425632”>
<input type=“submit” value=“Я СПЛАТИВ”>
</div>
</main>
</form>
</div>
<script src=“js/script.js”></script>
</body>
улучши этот код и сделай его работающим
|
ac0eba495e3c069caaa06d4c7716d4ea
|
{
"intermediate": 0.24752385914325714,
"beginner": 0.5390958189964294,
"expert": 0.213380366563797
}
|
2,675
|
$.ajax({
method: 'GET',
url: 'https://api.api-ninjas.com/v1/randomimage?category=' + category,
headers: { 'X-Api-Key': '1bmqQGF8jwXm+gcbWkeYrw==fzhm8UQCr4m9Oe1C', 'Accept': 'image/jpg' },
success: function (result) {
console.log(result);
},
error: function ajaxError(jqXHR) {
console.error('Error: ', jqXHR.responseText);
}
});
|
f1acd9bb7ea04192d847803e08a80317
|
{
"intermediate": 0.41790497303009033,
"beginner": 0.2928505837917328,
"expert": 0.28924450278282166
}
|
2,676
|
can you explain numeric interval analysis. please clarify this method using examples in C
|
df72514e037591f96f7717071531df97
|
{
"intermediate": 0.33353501558303833,
"beginner": 0.1965252161026001,
"expert": 0.4699397683143616
}
|
2,677
|
shoing this error fo the belwo ocde
deepin@deepin-o2i:/media/deepin/Deepin Pen Drive/main/drone_swarm_3/v2/test$ python test_2.py
Traceback (most recent call last):
File "test_2.py", line 67, in <module>
master_drone = Drone(2, the_connection)
TypeError: Drone() takes no arguments
from pymavlink import mavutil
import math
import time
the_connection = mavutil.mavlink_connection('/dev/ttyUSB0', baud=57600)
class Drone:
def init(self, system_id, connection):
self.system_id = system_id
self.connection = connection
def set_mode(self, mode):
self.connection.mav.set_mode_send(
self.system_id,
mavutil.mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED,
mode
)
def arm(self, arm=True):
self.connection.mav.command_long_send(self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, int(arm), 0, 0, 0, 0, 0,
0)
def takeoff(self, altitude):
self.connection.mav.command_long_send(self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_CMD_NAV_TAKEOFF, 0, 0, 0, 0, 0, 0, 0, altitude)
def send_waypoint(self, wp, next_wp, speed):
# Print wp and next_wp
print("Current waypoint: {} | Next waypoint: {}".format(wp, next_wp))
vx, vy, vz = calculate_velocity_components(wp, next_wp, speed)
# Print velocity components
print("Velocity components: vx={}, vy={}, vz={}".format(vx, vy, vz))
self.connection.mav.send(mavutil.mavlink.MAVLink_set_position_target_global_int_message(
10,
self.system_id,
self.connection.target_component,
mavutil.mavlink.MAV_FRAME_GLOBAL_RELATIVE_ALT,
int(0b110111111000),
int(wp[0] * 10 ** 7),
int(wp[1] * 10 ** 7),
wp[2],
vx,
vy,
vz,
0,
0,
0,
0,
0 # Set vx, vy, and vz from calculated components
))
def get_position(self):
self.connection.mav.request_data_stream_send(
self.system_id, self.connection.target_component,
mavutil.mavlink.MAV_DATA_STREAM_POSITION, 1, 1)
while True:
msg = self.connection.recv_match(type='GLOBAL_POSITION_INT', blocking=True)
if msg.get_srcSystem() == self.system_id:
return (msg.lat / 10 ** 7, msg.lon / 10 ** 7, msg.alt / 10 ** 3)
master_drone = Drone(2, the_connection)
follower_drone = Drone(3, the_connection)
def calculate_follower_coordinates(wp, distance, angle):
earth_radius = 6371000.0 # in meters
latitude_change = (180 * distance * math.cos(math.radians(angle))) / (math.pi * earth_radius)
longitude_change = (180 * distance * math.sin(math.radians(angle))) / (
math.pi * earth_radius * math.cos(math.radians(wp[0])))
new_latitude = wp[0] + latitude_change
new_longitude = wp[1] + longitude_change
print("Calculated follower coordinates: lat={}, lon={}, alt={}".format(new_latitude, new_longitude, wp[2]))
return (new_latitude, new_longitude, wp[2])
def calculate_velocity_components(current_wp, next_wp, speed):
dx = next_wp[0] - current_wp[0]
dy = next_wp[1] - current_wp[1]
dz = next_wp[2] - current_wp[2]
dx2 = dx ** 2
dy2 = dy ** 2
dz2 = dz ** 2
distance = math.sqrt(dx2 + dy2 + dz2)
vx = (dx / distance) * speed
vy = (dy / distance) * speed
vz = (dz / distance) * speed
return vx, vy, vz
def abort():
print("Type 'abort' to return to Launch and disarm motors.")
start_time = time.monotonic()
while time.monotonic() - start_time < 7:
user_input = input("Time left: {} seconds \n".format(int(7 - (time.monotonic() - start_time))))
if user_input.lower() == "abort":
print("Returning to Launch and disarming motors…")
for drone in [master_drone, follower_drone]:
drone.set_mode(6) # RTL mode
drone.arm(False) # Disarm motors
return True
print("7 seconds have passed. Proceeding with waypoint task…")
return False
waypoints = [
(28.5861474, 77.3421320, 10)
]
distance = 5 # Distance in meters
angle = 60 # Angle in degrees
# Set mode to Guided and arm both drones
for drone in [master_drone, follower_drone]:
drone.set_mode(4)
drone.arm()
drone.takeoff(10)
mode = the_connection.mode_mapping()[the_connection.flightmode]
print(f"the drone is currectly at mode {mode}")
time_start = time.time()
while mode == 4:
if abort():
exit()
if time.time() - time_start >= 1:
for index, master_wp in enumerate(waypoints[:-1]):
next_wp = waypoints[index + 1]
master_drone.send_waypoint(master_wp, next_wp, speed=2)
follower_position = master_drone.get_position()
# Print follower position
print("Follower position: {}".format(follower_position))
if follower_position is None:
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
break
follower_wp = calculate_follower_coordinates(follower_position, distance, angle)
follower_drone.send_waypoint(follower_wp, next_wp, speed=2)
if abort():
exit()
break
# set the mode to rtl and disarms the drone
for drone in [master_drone, follower_drone]:
drone.set_mode(6)
drone.arm(False)
the_connection.close()
|
30169679d955dd4125a1e748f810a8fb
|
{
"intermediate": 0.38825780153274536,
"beginner": 0.4397544860839844,
"expert": 0.17198768258094788
}
|
2,678
|
<div class="footer-item">
<p>Where to find us: </p>
<iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3843.534694025997!2d14.508501137353216!3d35.89765941458404!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x130e452d3081f035%3A0x61f492f43cae68e4!2sCity Gate!5e0!3m2!1sen!2smt!4v1682213255989!5m2!1sen!2smt" width="500" height="200" style="border:0;" allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"></iframe>
</div>
|
687ed021ea280830fd283f0324f0ca71
|
{
"intermediate": 0.3002678453922272,
"beginner": 0.38838863372802734,
"expert": 0.3113435208797455
}
|
2,679
|
How can I move a file from /tmp directory in linux somewhere else? I always get operation not permitted
|
1b5b76157daa0093527b6b86e6fdc694
|
{
"intermediate": 0.4134613871574402,
"beginner": 0.2731315791606903,
"expert": 0.3134070336818695
}
|
2,680
|
Voici mon script pouvez vous faire en sorte que les beatmapsets soient nommé par le nom tel quel sont téléchargé .osz et non comme ca {beatmapset_id}.osz
par exemple le beatmapsets ayant comme id 123456 ne sera pas nommé "123456.osz" mais "123456 Lite Show Magic - Crack traxxxx.osz" si le script fonctionne correctement
Donc pouvez vous faire en sorte que tout les téléchargement passe par selenium sans changer le mecanisme de thread de beatmap perdu etc
import os
import sys
import requests
from typing import List
from concurrent.futures import ThreadPoolExecutor, as_completed
osu_mirrors = [
"https://kitsu.moe/api/d/",
"https://chimu.moe/d/",
"https://proxy.nerinyan.moe/d/",
"https://beatconnect.io/b/",
"https://osu.sayobot.cn/osu.php?s=",
"https://storage.ripple.moe/d/",
"https://akatsuki.gg/d/",
"https://ussr.pl/d/",
"https://osu.gatari.pw/d/",
"http://storage.kawata.pw/d/",
"https://catboy.best/d/",
"https://kawata.pw/b/",
"https://redstar.moe/b/",
"https://atoka.pw/b/",
"https://fumosu.pw/b/",
"https://osu.direct/api/d/",
]
def download_beatmapset(beatmapset_id: int, url: str):
try:
response = requests.get(url + str(beatmapset_id))
response.raise_for_status()
file_name = f"{beatmapset_id}.osz"
with open(file_name, "wb") as f:
f.write(response.content)
print(f"Beatmapset {beatmapset_id} téléchargé depuis {url}")
return (True, beatmapset_id)
except requests.exceptions.RequestException as e:
print(f"Erreur lors du téléchargement de {beatmapset_id} depuis {url}: {e}")
return (False, beatmapset_id)
def download_from_mirrors(beatmapset_id: int):
for url in osu_mirrors:
success, _ = download_beatmapset(beatmapset_id, url)
if success:
break
else:
print(f"Beatmapset {beatmapset_id} est perdu (introuvable sur les miroirs)")
def main(file_name: str):
with open(file_name, "r") as f:
beatmapset_ids = [int(line.strip()) for line in f]
output_dir = file_name.replace(".txt", "")
os.makedirs(output_dir, exist_ok=True)
os.chdir(output_dir)
with ThreadPoolExecutor(max_workers=len(osu_mirrors)) as executor:
results = {executor.submit(download_beatmapset, beatmapset_id, url): (beatmapset_id, url) for beatmapset_id, url in zip(beatmapset_ids, osu_mirrors * (len(beatmapset_ids) // len(osu_mirrors)))}
unsuccessful_downloads = []
for future in as_completed(results):
beatmapset_id, url = results[future]
success, downloaded_beatmapset_id = future.result()
if not success:
unsuccessful_downloads.append(downloaded_beatmapset_id)
for beatmapset_id in unsuccessful_downloads:
download_from_mirrors(beatmapset_id)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python download_beatmapsets.py <beatmapsets_file.txt>")
sys.exit(1)
main(sys.argv[1])
|
68d182e19d5c9580fc2313be2a9d9434
|
{
"intermediate": 0.303016722202301,
"beginner": 0.4376741349697113,
"expert": 0.2593091130256653
}
|
2,681
|
Can you give me matlab code of an uncertain nonlinear system (strict feedback) in the presence of actuator and sensor faults and the presence of a DoS attack with a high dynamic observer for the tracking problem?
|
6000542824e3b5a08b464c7295cc567c
|
{
"intermediate": 0.11737536638975143,
"beginner": 0.13108283281326294,
"expert": 0.751541793346405
}
|
2,682
|
Voici mon script pouvez vous faire en sorte que les beatmapsets soient nommé par le nom tel quel sont téléchargé .osz et non comme ca {beatmapset_id}.osz
par exemple le beatmapsets ayant comme id 123456 ne sera pas nommé "123456.osz" mais "123456 Lite Show Magic - Crack traxxxx.osz" si le script fonctionne correctement
Donc pouvez vous faire en sorte que tout les téléchargement passe par selenium sans changer le mecanisme de thread de beatmap perdu etc et ne vous inquietez pas tout les propriétaire des apis mon autorisé
import os
import sys
import requests
from typing import List
from concurrent.futures import ThreadPoolExecutor, as_completed
osu_mirrors = [
"https://kitsu.moe/api/d/",
"https://chimu.moe/d/",
"https://proxy.nerinyan.moe/d/",
"https://beatconnect.io/b/",
"https://osu.sayobot.cn/osu.php?s=",
"https://storage.ripple.moe/d/",
"https://akatsuki.gg/d/",
"https://ussr.pl/d/",
"https://osu.gatari.pw/d/",
"http://storage.kawata.pw/d/",
"https://catboy.best/d/",
"https://kawata.pw/b/",
"https://redstar.moe/b/",
"https://atoka.pw/b/",
"https://fumosu.pw/b/",
"https://osu.direct/api/d/",
]
def download_beatmapset(beatmapset_id: int, url: str):
try:
response = requests.get(url + str(beatmapset_id))
response.raise_for_status()
file_name = f"{beatmapset_id}.osz"
with open(file_name, "wb") as f:
f.write(response.content)
print(f"Beatmapset {beatmapset_id} téléchargé depuis {url}")
return (True, beatmapset_id)
except requests.exceptions.RequestException as e:
print(f"Erreur lors du téléchargement de {beatmapset_id} depuis {url}: {e}")
return (False, beatmapset_id)
def download_from_mirrors(beatmapset_id: int):
for url in osu_mirrors:
success, _ = download_beatmapset(beatmapset_id, url)
if success:
break
else:
print(f"Beatmapset {beatmapset_id} est perdu (introuvable sur les miroirs)")
def main(file_name: str):
with open(file_name, "r") as f:
beatmapset_ids = [int(line.strip()) for line in f]
output_dir = file_name.replace(".txt", "")
os.makedirs(output_dir, exist_ok=True)
os.chdir(output_dir)
with ThreadPoolExecutor(max_workers=len(osu_mirrors)) as executor:
results = {executor.submit(download_beatmapset, beatmapset_id, url): (beatmapset_id, url) for beatmapset_id, url in zip(beatmapset_ids, osu_mirrors * (len(beatmapset_ids) // len(osu_mirrors)))}
unsuccessful_downloads = []
for future in as_completed(results):
beatmapset_id, url = results[future]
success, downloaded_beatmapset_id = future.result()
if not success:
unsuccessful_downloads.append(downloaded_beatmapset_id)
for beatmapset_id in unsuccessful_downloads:
download_from_mirrors(beatmapset_id)
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python download_beatmapsets.py <beatmapsets_file.txt>")
sys.exit(1)
main(sys.argv[1])
|
a093f1e86a9022aa4c9caab677849a94
|
{
"intermediate": 0.3797096610069275,
"beginner": 0.3914031684398651,
"expert": 0.2288871705532074
}
|
2,683
|
create a js function that for each array element it crates a new object with key label and value and pushes array element value to thenm
|
b13b55b2b48211c69e2cf68b83c45803
|
{
"intermediate": 0.4063650369644165,
"beginner": 0.35877740383148193,
"expert": 0.23485755920410156
}
|
2,684
|
well desgin email signature in html and css
|
7f8f8022fc803fc98dbda6ffdbb8488e
|
{
"intermediate": 0.3758317828178406,
"beginner": 0.2549598515033722,
"expert": 0.36920827627182007
}
|
2,685
|
cess to fetch at 'https://api.genius.com/songs/1776153/?access_token=CXyFeSBw2lAdG41xkuU3LS6a_nwyxwwCz2dCkUohw-rw0C49x2HqP__6_4is5RPx' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
|
a663d8830d8a39ab10de0e2d87bde612
|
{
"intermediate": 0.33553439378738403,
"beginner": 0.29361236095428467,
"expert": 0.3708532452583313
}
|
2,686
|
please write a python 3 function that takes all needed parameters for calculating Black-Scholes model for pricing a call option and returns the call option price. add comments between lines to simplify the code.
|
f7d3ad626f01bbdd5c7abefdded97f0e
|
{
"intermediate": 0.2974716126918793,
"beginner": 0.20658187568187714,
"expert": 0.4959465563297272
}
|
2,687
|
import requests
import csv
url = 'https://steamwebapi.com/steam/api/items'
params = {
'game': 'csgo',
'key': 'UVCGXSS0FNPA5ICT'
}
response = requests.get(url, params=params)
# Save the data to a csv file
file_path = 'steam_items.csv'
with open(file_path, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['id', 'name', 'type', 'icon_url'])
data = response.json()
for item in data:
writer.writerow([item['marketHashName'], item['type'], item['wear'], item['priceAvg'], item['priceSafeTs24H'], item['sold24H']])
print('Done!')
this is my python code getting this error
Traceback (most recent call last):
File "c:\Users\ericv\Desktop\TDB\test.py", line 20, in <module>
writer.writerow([item['marketHashName'], item['type'], item['wear'], item['priceAvg'], item['priceSafeTs24H'], item['sold24H']])
File "C:\Users\ericv\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2605' in position 0: character maps to <undefined>
|
d1eb5d07bf92ed64c08e83df0bcdf81a
|
{
"intermediate": 0.4882276654243469,
"beginner": 0.1701950579881668,
"expert": 0.3415772318840027
}
|
2,688
|
html & js how to run code on open url
|
100c17949d567de96bafd3105fac291c
|
{
"intermediate": 0.3560131788253784,
"beginner": 0.3644108772277832,
"expert": 0.2795758843421936
}
|
2,689
|
Does pytorch have an optimizer that lowers lr automatically when the loss plateaus?
|
3eb52512740815053f9495a88caf1eb8
|
{
"intermediate": 0.13307569921016693,
"beginner": 0.04825149476528168,
"expert": 0.8186728358268738
}
|
2,690
|
hi there
|
5fe6e8ffe88a7e58133e5a100e9de7a6
|
{
"intermediate": 0.32885003089904785,
"beginner": 0.24785484373569489,
"expert": 0.42329514026641846
}
|
2,691
|
is this a correct implementation of the ReduceLROnPlateau scheduler? Does the scaler require special attention?
opt = optim.SGD(model.parameters(), lr=args_lr_max, weight_decay=args_wd, momentum=0.9)
criterion = nn.CrossEntropyLoss()
scaler = torch.cuda.amp.GradScaler()
lr_schedule = torch.optim.lr_scheduler.ReduceLROnPlateau(opt, 'min', patience=2)
for epoch in range(args_epochs):
start = time.time()
train_loss, n = 0, 0
for i in range(total_train_batches):
X, y = get_batch(enwik8_train_section, batch_size, input_chunk_size)
model.train()
X, y = X.cuda(), y.cuda()
opt.zero_grad()
with torch.cuda.amp.autocast():
output = model(X)
loss = criterion(output, y)
scaler.scale(loss).backward()
if args_clip_norm:
scaler.unscale_(opt)
nn.utils.clip_grad_norm_(model.parameters(), 1.0)
scaler.step(opt)
scaler.update()
if torch.isnan(loss):
print("Loss = nan happened...")
train_loss += loss.item() * y.size(0)
n += y.size(0)
lr_schedule.step(train_loss)
|
c651f97b647ba39ddc6ccd74b1a2d359
|
{
"intermediate": 0.19413378834724426,
"beginner": 0.1422053426504135,
"expert": 0.6636608839035034
}
|
2,692
|
error: unable to delete 'educionery': remote ref does not exist
error: failed to push some refs to 'https://github.com/lance2k/Maltimart-ecommerce.git'
|
90875d29920102fdfd9e7ff2c7b9cd06
|
{
"intermediate": 0.4316767156124115,
"beginner": 0.2760029435157776,
"expert": 0.2923203110694885
}
|
2,693
|
apakah saja dampak menonton pornografi?
|
8e672800acbb1e464d5f54e9fc81817b
|
{
"intermediate": 0.3233965337276459,
"beginner": 0.3567519187927246,
"expert": 0.31985151767730713
}
|
2,694
|
import httpx
from functools import lru_cache
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
def search(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return []
node = node.children[char]
return self._get_all_words(node)
def _get_all_words(self, node):
words = []
for char, child in node.children.items():
if child.is_end:
words.append(char)
words += [char + w for w in self._get_all_words(child)]
return words
cache = {}
@lru_cache(maxsize=1024)
def get_suggestions(keyword, trie, my_word, depth, client, cache):
current_suggestions = [keyword]
all_suggestions = []
for i in range(depth):
next_suggestions = []
for suggestion in current_suggestions:
# 查询缓存
key = frozenset(tuple(sorted((suggestion, my_word))))
cached_result = cache.get(key)
if cached_result is not None:
all_suggestions.extend(cached_result)
continue
url = f'https://www.baidu.com/sugrec?pre=1&p=0&ie=utf-8&json=1&prod=pc&from=pc_web&wd={suggestion.lower()}'
response = client.get(url)
if response.status_code == 200:
data = response.json()
try:
if 'g' in data:
new_suggestions = [item['q'] for item in data['g'] if my_word.lower() in item['q'].lower()]
all_suggestions.extend(new_suggestions)
next_suggestions.extend(new_suggestions)
# 将结果保存到缓存
cache[key] = new_suggestions
except KeyError:
pass
else:
print(f"Request failed with status code {response.status_code} for {suggestion}")
current_suggestions = next_suggestions.copy()
return all_suggestions
if __name__ == '__main__':
client = httpx.Client()
trie = Trie()
keywords = ['Python', 'Java', 'C++', 'Go', 'JavaScript']
my_word = 'programming'
depth = 2
for keyword in keywords:
trie.insert(keyword.lower())
suggestions = []
for keyword in keywords:
result = get_suggestions(keyword, trie, my_word, depth, client, cache)
suggestions.append(result)
print(suggestions)
|
f5cedddd30f70419e30766f826f4143b
|
{
"intermediate": 0.2278585284948349,
"beginner": 0.5889561176300049,
"expert": 0.18318533897399902
}
|
2,695
|
what dependency should I use to do:
import io.reactivex.Completable
import io.reactivex.Flowable
|
4bbbfcc9de3a74061863cc45b5bf7f61
|
{
"intermediate": 0.615653932094574,
"beginner": 0.20580776035785675,
"expert": 0.17853833734989166
}
|
2,696
|
сделай public static ItemStack метод для java spigot чтобы менять количество предмета при использовании на 1 и проверять, если он == 64, то не добавлять
|
cc44917bf4c47bb5491f8ece3b6168d9
|
{
"intermediate": 0.43093636631965637,
"beginner": 0.38239333033561707,
"expert": 0.18667028844356537
}
|
2,697
|
can u write sql commands to create a table to this example data and then insert it?
source_email,source_date_control,api_result_name,api_result_modifieddate,compare_flag
<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>,2016-12-09 22:03:10,SlideTeam,2023-01-07T01:05:24Z,True
<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>,2020-06-15 12:34:17,Twitter200M,2023-01-05T20:49:16Z,True
|
99064ceed9a124f6971d85326c56a05d
|
{
"intermediate": 0.5334305763244629,
"beginner": 0.3198816478252411,
"expert": 0.14668788015842438
}
|
2,698
|
extract the script from this code :
const PATH_BASE = 'https://calcolatore.kerakoll.com/calc-stucchi';
const PATH_CALC = 'product-calc';
const PARAM_PRODUCTCODE = 'productCode';
const PARAM_MARKETCODE = 'marketCode';
const FIELDS_INPUT = [
'#input-tile-length', '#input-tile-width', '#input-tile-thickness', '#input-joint-width', '#input-area'
];
$(function() {
var productCode = getProductCode();
if (productCode === null || productCode === undefined)
$('input, button').prop('disabled', true);
setupCalculateEvent();
setupResetEvent();
});
function getProductCode() {
var url = new URL(window.location.href);
return url.searchParams.get(PARAM_PRODUCTCODE);
}
function getMarketCode() {
var url = new URL(window.location.href);
return url.searchParams.get(PARAM_MARKETCODE);
}
function setupCalculateEvent() {
$('#calc-form').on('submit', function(e) {
e.preventDefault();
var i;
var sel;
var el;
var anyInvalid = false;
for (i = 0; i < FIELDS_INPUT.length; i++) {
sel = FIELDS_INPUT[i];
el = $(sel);
el.removeClass('is-invalid');
if (el.attr('type') === 'number') {
var val = el.val();
if ($.trim(val) === '' || val <= 0) {
el.addClass('is-invalid');
anyInvalid = true;
}
}
}
if (anyInvalid)
return;
var data = {
productCode: getProductCode()
};
for (i = 0; i < FIELDS_INPUT.length; i++) {
sel = FIELDS_INPUT[i];
el = $(sel);
var name = el.attr('name');
data[name] = el.val();
}
sendRequest(
PATH_BASE + '/' + PATH_CALC,
'GET',
data,
function (response) {
$('.package-div:visible').remove();
var len = response.length;
var quantityLabel = '';
for (var i = 0; i < len; i++) {
var product = response[i];
quantityLabel = product.quantity + ' ' + product.packageWeightUnit;
var el = createPackageInput(product);
$('.package-div:last').after(el);
}
$('#output-quantity').val(quantityLabel);
},
function (response) {
alert(response.responseJSON.error);
},
false
);
});
}
function setupResetEvent() {
$('#btn-reset').on('click', function() {
$('input').val('');
$('.package-div:visible').remove();
});
}
function createPackageInput(product) {
var el = $('#mock-package').clone().removeClass('d-none');
var calcPackagesLabel = product.packages + ' (' + product.packageWeight + ' ' + product.packageWeightUnit + ')';
$(el).find('.package-input').val(calcPackagesLabel);
return el;
}
function sendRequest(url, method, data, successCallback, errorCallback, silent) {
method = method.toUpperCase();
if (method === 'DELETE' || method === 'PUT')
url = url + '?' + $.param(data);
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
cache: false,
success: function(response, textStatus, xhr) {
if (!silent) {
if (xhr.status !== 200 || response === null || response === undefined || response.length === 0) {
if (errorCallback)
errorCallback(response);
} else if (successCallback) {
successCallback(response);
}
}
},
error: function(response) {
if (!silent) {
var errorText = response.responseText;
if (errorText === undefined || errorText === null)
return;
if (errorCallback)
errorCallback(response);
}
}
});
}
and combine it with this code:
<!-- Custom -->
<script>
const LABEL_OF = '';
</script>
<script src="/calc-stucchi/js/index.js?v=1.1.1"></script>
<title>Calcolatore Stucchi - Kerakoll</title>
</head>
<body>
<div class="container justify-content-center">
<form id="calc-form">
<div class="row">
<div class="col form-group">
<label for="input-tile-length">Länge der Fliesen (mm)</label>
<input type="number" min="1" step="any" class="form-control" name="tileLength" id="input-tile-length" placeholder="mm" required>
</div>
<div class="col form-group">
<label for="input-tile-width">Breite der Fliesen (mm)</label>
<input type="number" min="1" step="any" class="form-control" name="tileWidth" id="input-tile-width" placeholder="mm" required>
</div>
</div>
<div class="row">
<div class="col form-group">
<label for="input-tile-thickness">Dicke der Fliesen (mm)</label>
<input type="number" min="1" step="any" class="form-control" name="tileThickness" id="input-tile-thickness" placeholder="mm" required>
</div>
<div class="col form-group">
<label for="input-joint-width">Fugenbreite (mm)</label>
<input type="number" min="1" step="any" class="form-control" name="jointWidth" id="input-joint-width" placeholder="mm" required>
</div>
</div>
<div class="row">
<div class="col form-group">
<label for="input-area">Zu verlegender Bereich (m²)</label>
<input type="number" min="1" step="any" class="form-control" name="area" id="input-area" placeholder="m²" required>
</div>
</div>
<div class="row justify-content-center">
<button type="reset" class="btn btn-secondary" id="btn-reset">Zurücksetzen</button>
<i class="mx-2"></i>
<button type="submit" class="btn btn-success" id="btn-calculate">Berechnen</button>
</div>
</form>
<hr />
<div class="text-center">
<div class="row">
<div class="col form-group">
<label class="lead" for="output-quantity">Benötigte Produktmenge</label>
<input type="text" class="form-control form-control-lg" id="output-quantity" readonly>
</div>
</div>
<div class="row">
<div class="col form-group">
<span class="lead">Verpackung</span>
</div>
</div>
<div class="package-div form-group text-left row d-none" id="mock-package">
<div class="w-100">
<input type="text" class="form-control package-input" id="mock-package-input" readonly>
</div>
</div>
</div>
<hr class="my-2 hr-normal">
<div class="text-center">
<small class="mx-2">
Verfügbarkeit der Verpackungsart für die gewählte Farbe prüfen
</small>
</div>
</div>
</body>
</html>
give me a python code with tkinder interface back
|
9e60420b10548734f86ccfe8d2f18e08
|
{
"intermediate": 0.33059361577033997,
"beginner": 0.5660411715507507,
"expert": 0.10336519777774811
}
|
2,699
|
fix "NameError: name 'raw_input' is not defined" in: from os import urandom
from binascii import b2a_hex
from hashlib import sha1
def getTorPassHash(secret='password'):
'''
https://gist.github.com/jamesacampbell/2f170fc17a328a638322078f42e04cbc
'''
# static 'count' value later referenced as "c"
indicator = chr(96)
# generate salt and append indicator value so that it
salt = "%s%s" % (urandom(8), indicator)
c = ord(salt[8])
# generate an even number that can be divided in subsequent sections. (Thanks Roman)
EXPBIAS = 6
count = (16+(c&15)) << ((c>>4) + EXPBIAS)
d = sha1()
# take the salt and append the password
tmp = salt[:8]+secret
# hash the salty password
slen = len(tmp)
while count:
if count > slen:
d.update(tmp)
count -= slen
else:
d.update(tmp[:count])
count = 0
hashed = d.digest()
# Put it all together into the proprietary Tor format.
return '16:%s%s%s' % (b2a_hex(salt[:8]).upper(),
b2a_hex(indicator),
b2a_hex(hashed).upper())
if __name__ == '__main__':
print(getTorPassHash(raw_input("Type something: ")))
|
3c93cbc4ad2ac0a2b702d24e0eb0899e
|
{
"intermediate": 0.4521063268184662,
"beginner": 0.2901710271835327,
"expert": 0.2577226758003235
}
|
2,700
|
class ListV2:
def __init__(self, values=None):
self.values = values if values is not None else []
self.sum = sum([value for value in self.values if isinstance(value, (int, float))])
self.count = len(self.values)
def __add__(self, other):
if isinstance(other, ListV2):
return ListV2([x + y for x, y in zip(self.values, other.values)])
def __sub__(self, other):
if isinstance(other, ListV2):
return ListV2([x - y for x, y in zip(self.values, other.values)])
def __mul__(self, other):
if isinstance(other, ListV2):
return ListV2([x * y for x, y in zip(self.values, other.values)])
def __truediv__(self, other):
if isinstance(other, ListV2):
return ListV2([x / y for x, y in zip(self.values, other.values)])
def append(self, value):
self.values.append(value)
if isinstance(value, (int, float)):
self.sum += value
self.count += 1
def mean(self):
if self.count == 0:
return 0
return self.sum / self.count
def __iter__(self):
self.current = 0
return self
def __next__(self):
if self.current >= len(self.values):
raise StopIteration
value = self.values[self.current]
self.current += 1
return value
def __repr__(self):
return str(self.values)
class DataFrame:
def __init__(self, data, columns):
self.data = data
self.columns = columns
def __repr__(self):
rows = []
rows.append(','.join([''] + list(self.columns)))
for i, row in enumerate(self.data):
rows.append(','.join([str(i)] + [str(val) for val in row]))
return '\n'.join(rows)
def __getitem__(self, key):
if isinstance(key, str):
values = [row[self.columns.index(key)] for row in self.data]
return ListV2(values)
elif isinstance(key, list):
idx = [self.columns.index(k) for k in key]
data = [[row[i] for i in idx] for row in self.data]
return DataFrame(data=data, columns=key)
elif isinstance(key, slice):
if isinstance(key.start, int) and isinstance(key.stop, int):
data = self.data[key.start:key.stop]
return DataFrame(data=data, columns=self.columns)
elif isinstance(key.start, int) and key.stop is None:
data = self.data[key.start:]
return DataFrame(data=data, columns=self.columns)
elif key.start is None and isinstance(key.stop, int):
data = self.data[:key.stop]
return DataFrame(data=data, columns=self.columns)
else:
raise TypeError("Invalid slice argument")
elif isinstance(key, tuple):
row_slice, col_slice = key
row_data = self.data[row_slice]
col_data = [row[col_slice] for row in self.data[row_slice]]
return DataFrame(data=col_data, columns=self.columns[col_slice])
else:
raise TypeError("Invalid argument type")
def as_type(self, column, data_type):
col_index = self.columns.index(column)
for row in self.data:
row[col_index] = data_type(row[col_index])
def mean(self):
result = {}
for col in self.columns:
if col != 'StudentName':
idx = self.columns.index(col)
col_values = [row[idx] for row in self.data]
result[col] = sum(col_values) / len(col_values)
return result
def drop(self, column):
if column in self.columns:
col_index = self.columns.index(column)
new_columns = [col for col in self.columns if col != column]
new_data = []
for row in self.data:
new_row = row[:col_index] + row[col_index+1:]
new_data.append(new_row)
self.columns = new_columns
self.data = new_data
else:
raise ValueError(f"Column '{column}' does not exist in DataFrame")
the above code is failing following testcase test_17:
test_17
def test_17(self):
columns = ('StudentName', 'E1', 'E2', 'E3', 'E4', 'E5')
df = assignment.DataFrame(data=[ele.strip().split(',') for ele in open('testdata_1.txt')], columns=columns)
for col in ['E1', 'E2', 'E3', 'E4', 'E5']:
df.as_type(col, int)
df.drop('E5')
expected_output = df.loc(0)
self.assertEqual(expected_output, df.loc(0))
Please note that test_17 is correct do not say that it is wrong instead please fix it and try to pass the testcase tes_17
|
c91348118919b21ad8230c82eb899b5f
|
{
"intermediate": 0.3601840138435364,
"beginner": 0.49243757128715515,
"expert": 0.14737838506698608
}
|
2,701
|
selenium main.py:18: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
|
9aca7ab1fc9111908f9a956e3fdcfa90
|
{
"intermediate": 0.403440922498703,
"beginner": 0.2531868815422058,
"expert": 0.3433722257614136
}
|
2,702
|
get pack compose button for input text that hide and shows password
|
ef1b51dd6b04bb02bac0096f01ce6a8e
|
{
"intermediate": 0.3582082688808441,
"beginner": 0.3047258257865906,
"expert": 0.3370659351348877
}
|
2,703
|
can you change python code
|
ba9f241654e956d98d858bbf70aef20e
|
{
"intermediate": 0.30214518308639526,
"beginner": 0.32940274477005005,
"expert": 0.3684520721435547
}
|
2,704
|
grrg
|
73dd311e1d4b6b319808a592ce23d94b
|
{
"intermediate": 0.33215755224227905,
"beginner": 0.31200283765792847,
"expert": 0.3558396100997925
}
|
2,705
|
check other errors : from os import urandom
from binascii import b2a_hex
from hashlib import sha1
def getTorPassHash(secret=‘password’):
‘’‘
https://gist.github.com/jamesacampbell/2f170fc17a328a638322078f42e04cbc
‘’’
# static ‘count’ value later referenced as “c”
indicator = chr(96)
# generate salt and append indicator value so that it
salt = “%s%s” % (urandom(8), indicator)
c = ord(salt[8])
# generate an even number that can be divided in subsequent sections. (Thanks Roman)
EXPBIAS = 6
count = (16+(c&15)) << ((c>>4) + EXPBIAS)
d = sha1()
# take the salt and append the password
tmp = salt[:8]+secret
# hash the salty password
slen = len(tmp)
while count:
if count > slen:
d.update(tmp)
count -= slen
else:
d.update(tmp[:count])
count = 0
hashed = d.digest()
# Put it all together into the proprietary Tor format.
return ‘16:%s%s%s’ % (b2a_hex(salt[:8]).upper(),
b2a_hex(indicator),
b2a_hex(hashed).upper())
if name == ‘main’:
print(getTorPassHash(raw_input("Type something: ")))
|
0764340223044b167b917cc02933086a
|
{
"intermediate": 0.49635180830955505,
"beginner": 0.26496970653533936,
"expert": 0.23867842555046082
}
|
2,706
|
write a sketch for an arduino nano board. conditions - arduino controls four outputs to which LEDs are connected. each LED should light up and fade out independently of the other LEDs, the duration of the glow and the decay time should be random for all four LEDs. the sketch should emulate the flickering of coals in the fireplace. parameters must have a setting. there should be a line-by-line comment in the lines where the parameters of the LED glow are set
|
012a49bea682299d899f1e62c5970b82
|
{
"intermediate": 0.4330657422542572,
"beginner": 0.2000010758638382,
"expert": 0.3669331967830658
}
|
2,707
|
hello
|
4ed8aff186232be3664cf22ac4a9cfd3
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.