row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
32,222
|
Voisitko kirjoittaa nämä englanniksi? Minun pitää tehdä tutkimus
|
dc85acc48c016f434176154e9074257d
|
{
"intermediate": 0.3652220070362091,
"beginner": 0.2976287603378296,
"expert": 0.3371492028236389
}
|
32,223
|
make it use tiles instead of random lines:
extends Node2D
var grid_size = Vector2(50, 50) # Change to desired grid size
var cell_size = 10 # Change to the size of each cell in pixels
var grid = []
var update_rate = 0.5 # Seconds
func _ready():
initialize_grid()
update_grid()
var timer = Timer.new()
timer.set_wait_time(update_rate)
timer.set_one_shot(false)
# Create a Callable by referencing the method directly
var callable = Callable(self, "update_grid")
# Use the Callable to connect the signal
timer.connect("timeout", callable)
add_child(timer)
timer.start()
func initialize_grid():
grid = []
for y in range(grid_size.y):
var row = []
for x in range(grid_size.x):
row.append(randi() % 2) # Randomly set initial state to 0 or 1
grid.append(row)
func draw_grid():
_draw()
func _draw():
for y in range(grid_size.y):
for x in range(grid_size.x):
var color = Color(1, 1, 1) if grid[y][x] == 1 else Color(0, 0, 0)
draw_rect(Rect2(Vector2(x, y) * cell_size, Vector2(cell_size, cell_size)), color, false)
func get_cell(x, y):
if x < 0 or x >= grid_size.x or y < 0 or y >= grid_size.y:
return 0
return grid[y][x]
func count_neighbors(x, y):
var count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
count += get_cell(x + i, y + j)
return count
func update_grid():
var new_grid = []
for y in range(grid_size.y):
new_grid.append(grid[y].duplicate())
for y in range(grid_size.y):
for x in range(grid_size.x):
var neighbors = count_neighbors(x, y)
if grid[y][x] == 1 and (neighbors < 2 or neighbors > 3):
new_grid[y][x] = 0 # Cell dies
elif grid[y][x] == 0 and neighbors == 3:
new_grid[y][x] = 1 # Cell becomes alive
grid = new_grid
draw_grid()
|
290cc78d19252af8cef7fec90119b505
|
{
"intermediate": 0.439635694026947,
"beginner": 0.295994371175766,
"expert": 0.2643698751926422
}
|
32,224
|
this is my custom grid class but I am having errors:
#ifndef CUSTOMGRID_H
#define CUSTOMGRID_H
#include <wx/grid.h>
#include <set>
class CustomGrid : public wxGrid
{
public:
CustomGrid(wxWindow* parent, wxWindowID id = wxID_ANY, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = wxWANTS_CHARS, const wxString& name = wxGridNameStr) : wxGrid(parent, id, pos, size, style, name);
virtual ~CustomGrid();
void SetPinnedRow(int row, bool pinned);
protected:
void DrawRowLabel(wxDC& dc, int row) override;
void DrawCell(int row, int col, wxDC& dc, const wxRect& rect, int flags) override;
private:
std::set<int> pinnedRows;
};
#endif // CUSTOMGRID_H
#include "CustomGrid.h"
CustomGrid::~CustomGrid()
{
}
void CustomGrid::SetPinnedRow(int row, bool pinned)
{
if (pinned)
{
pinnedRows.insert(row);
}
else
{
pinnedRows.erase(row);
}
Refresh(); // Redraw the grid with updated pinning
}
void CustomGrid::DrawRowLabel(wxDC& dc, int row)
{
if (pinnedRows.count(row) > 0)
{
dc.SetBrush(wxBrush(wxColour(255, 255, 0))); // Yellow color
dc.SetPen(*wxTRANSPARENT_PEN);
dc.DrawRectangle(wxRect(GetRowLabelSize().x, GetRowTop(row), GetRowLabelSize().GetWidth(), GetRowHeight(row)));
return;
}
wxGrid::DrawRowLabel(dc, row);
}
void CustomGrid::DrawCell(int row, int col,
wxDC& dc, const wxRect& rect, int flags)
{
if (pinnedRows.count(row) > 0)
{
dc.SetBrush(wxBrush(wxColour(255, 255, 0))); // Yellow color
dc.SetPen(*wxTRANSPARENT_PEN);
dc.DrawRectangle(rect);
// Optionally, you can draw additional pinned cell elements here
return;
}
wxGrid::DrawCell(row, col, dc, rect, flags);
}
And the errors are:
- include/CustomGrid.h:16:14: error: ‘void CustomGrid::DrawCell(int, int, wxDC&, const wxRect&, int)’ marked ‘override’, but does not override
- include/CustomGrid.h:10:250: error: expected ‘{’ at end of input
- In member function ‘virtual void CustomGrid::DrawRowLabel(wxDC&, int)’: CustomGrid.cpp:25:9: error: invalid use of incomplete type ‘class wxDC’
- CustomGrid.cpp:25:50: error: invalid use of incomplete type ‘class wxBrush’
- CustomGrid.cpp:26:9: error: invalid use of incomplete type ‘class wxDC’
- CustomGrid.cpp:27:51: error: request for member ‘x’ in ‘((CustomGrid*)this)->CustomGrid::<anonymous>.wxGrid::GetRowLabelSize()’, which is of non-class type ‘int’
- CustomGrid.cpp:27:88: error: request for member ‘GetWidth’ in ‘((CustomGrid*)this)->CustomGrid::<anonymous>.wxGrid::GetRowLabelSize()’, which is of non-class type ‘int’
- CustomGrid.cpp:49:21: error: no matching function for call to ‘CustomGrid::DrawCell(int&, int&, wxDC&, const wxRect&, int&)’
|
3bae787335a9767c82eca872c8638eac
|
{
"intermediate": 0.34991803765296936,
"beginner": 0.38625550270080566,
"expert": 0.263826459646225
}
|
32,225
|
make the generator use the tilemap instead of random lines, got walls and floor tiles:
extends Node2D
var grid_size = Vector2(50, 50) # Change to desired grid size
var cell_size = 10 # Change to the size of each cell in pixels
var grid = []
var update_rate = 0.5 # Seconds
func _ready():
initialize_grid()
update_grid()
var timer = Timer.new()
timer.set_wait_time(update_rate)
timer.set_one_shot(false)
# Create a Callable by referencing the method directly
var callable = Callable(self, "update_grid")
# Use the Callable to connect the signal
timer.connect("timeout", callable)
add_child(timer)
timer.start()
func initialize_grid():
grid = []
for y in range(grid_size.y):
var row = []
for x in range(grid_size.x):
row.append(randi() % 2) # Randomly set initial state to 0 or 1
grid.append(row)
func draw_grid():
_draw()
func _draw():
for y in range(grid_size.y):
for x in range(grid_size.x):
var color = Color(1, 1, 1) if grid[y][x] == 1 else Color(0, 0, 0)
draw_rect(Rect2(Vector2(x, y) * cell_size, Vector2(cell_size, cell_size)), color, false)
func get_cell(x, y):
if x < 0 or x >= grid_size.x or y < 0 or y >= grid_size.y:
return 0
return grid[y][x]
func count_neighbors(x, y):
var count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
count += get_cell(x + i, y + j)
return count
func update_grid():
var new_grid = []
for y in range(grid_size.y):
new_grid.append(grid[y].duplicate())
for y in range(grid_size.y):
for x in range(grid_size.x):
var neighbors = count_neighbors(x, y)
if grid[y][x] == 1 and (neighbors < 2 or neighbors > 3):
new_grid[y][x] = 0 # Cell dies
elif grid[y][x] == 0 and neighbors == 3:
new_grid[y][x] = 1 # Cell becomes alive
grid = new_grid
draw_grid()
|
5764135c35000b9f68d241a824508ecf
|
{
"intermediate": 0.41207355260849,
"beginner": 0.29394084215164185,
"expert": 0.29398560523986816
}
|
32,226
|
i need a code to make a voting model between output between SVM, LST and Bi-LSTM
|
ef3194722e122e5db2056bc87c3b9004
|
{
"intermediate": 0.20245784521102905,
"beginner": 0.056725986301898956,
"expert": 0.7408161759376526
}
|
32,227
|
In the context of LVM 2 caching and Debian GNU/Linux, is it possible to only have writeback caching only be enabled for certain directories or to somehow control when and where writethrough or writeback cache is being used?
|
42a47642d739e5a6a49da3601b2f0950
|
{
"intermediate": 0.33183473348617554,
"beginner": 0.251946359872818,
"expert": 0.4162188768386841
}
|
32,228
|
Assignment 1: Install Linux1. Install Ubuntu Server in your VM by following the instructions in the video: Video Lecture 02 - Installing UbuntuServer in a VM2. Use the following when installing the server:a. Set your username to be your first nameb. Set your hostname to be the first 3 letters of your last name + your student ID (for exampleers20059995)3. Take a screenshot of your Virtual Machine application displaying the login prompt of your VM terminal and saveit as “ScreenShot1.png”a. In Windows use “Snipping Tool” and take a screenshot of your VM Application running your VM usingthe “Windows Snip” mode or other methods to achieve the same result.i.b. If you are a MacOS user, then you can accomplish the same task using “Grab”, or use “Command + Shift+ 4” or “Command + Shift + 4 + Space” shortcut keys.4. Log in to your VM using the username and password you had set earlier during the setup.5. Type and execute the following two commands:echo $USERhostname6. Take a screenshot of your VM terminal showing the above commands and their output and save as“ScreenShot2.png”7. Submit “ScreenShot1.png” and “ScreenShot2.png”Backup the VM (Optional, but recommended)1. Shutdown the Linux VM using the command “sudo shutdown -h now”, or use “sudo poweroff”2. Exit VMware Workstation/VMware Fusion or VirtualBox3. Navigate to the directory where the VM is stored. For VMware Workstation running in Windows, the defaultlocation is under ..\Documents\Virtual Machines, The default location for VirtualBox, “Default machine Folder”can be found under File > Preferences and under the General screen4. Add your Virtual Machine to a Zip Archive. You can back up your zip to another medium such as a USB thumbdrive or another disk for safekeeping.5. You can repeat this process to have a complete backup of your VM every time you make changes, and you aresatisfied with the changes6. You can also take Snapshots and clone your VM. Look at the documentation for your Virtualization softwareHow to restore from Zip ArchiveIf something goes wrong with your VM or you need to restore the VM, or even bring the VM to another computer torun, simply delete the existing directory of your VM files and solve this problem put user name as urmaan and histname as ran20056654 and give the screenshot
|
4641f865e0c2be03c3c279884c5ac1a7
|
{
"intermediate": 0.33569514751434326,
"beginner": 0.3405802845954895,
"expert": 0.32372456789016724
}
|
32,229
|
сделай красивое горизонтальное меню в css
Код:
<div class=“mobile-menu-open-button js_mobile_menu_open_button”><i class=“fas fa-bars”></i></div>
<nav class=“js_wide_menu”>
<i class=“fas fa-times close-mobile-menu js_close_mobile_menu”></i>
<div class=“wrapper-inside”>
<div class=“visible-elements”>
<a class=“links_nav” href=“index.php”>Главная</a>
<a class=“links_nav” href=“index.php”>Поиск</a>
<a class=“links_nav” href=“index.php”>Войти</a>
<a class=“links_nav” href=“corzina.php”>Корзина</a>
</div>
</div>
</nav>
|
302c9730563353db84414b7b2cac62f4
|
{
"intermediate": 0.34868982434272766,
"beginner": 0.3086482584476471,
"expert": 0.34266194701194763
}
|
32,230
|
python2 ktf.console
Traceback (most recent call last):
File "ktf.console", line 9, in <module>
from core.MainListLibrary import *
File "/home/noname/Desktop/KatanaFramework/core/MainListLibrary.py", line 37, in <module>
from Function import Executefunction
File "/home/noname/Desktop/KatanaFramework/core/Function.py", line 11, in <module>
from scapy.all import *
ImportError: No module named scapy.all jak naprawić ten błąd?
|
37aa72cec5aec7e6b34a96fecea662eb
|
{
"intermediate": 0.5498183965682983,
"beginner": 0.30261823534965515,
"expert": 0.1475633680820465
}
|
32,231
|
How can one generate an integer pseudorandomly in Bash (on Debian GNU/Linux)? Be concise.
|
f8858bb07e5dfafb6c62e796afbe49c8
|
{
"intermediate": 0.42541179060935974,
"beginner": 0.20385073125362396,
"expert": 0.3707374632358551
}
|
32,232
|
This is my code:
fn parallel_parse<'a>(s: &'a str) -> Vec<Vec<&'a str>> {
s.par_lines()
.map(|line_result| {
line_result
.map_err(|e| e.into())
.and_then(|line| BedRecord::parse(&s))
})
.collect();
}
fn main() {
let start = std::time::Instant::now();
let whole_file = filename_to_string(
"/home/alejandro/Documents/unam/TOGA_old_versions/x/bed_gencode_tmp/200k.bed",
)
.unwrap();
let wbyl = words_by_line_parallel(&whole_file);
// println!("{:?}", wbyl);
let duration = start.elapsed();
println!("Time: {:?}", duration);
}
fn filename_to_string(s: &str) -> io::Result<String> {
let mut file = File::open(s)?;
let mut s = String::new();
file.read_to_string(&mut s)?;
Ok(s)
}
where BedRecord looks like this:
pub struct BedRecord {
chrom: String,
tx_start: u32,
tx_end: u32,
name: String,
strand: String,
cds_start: u32,
cds_end: u32,
exon_count: u16,
exon_start: Vec<u32>,
exon_end: Vec<u32>,
}
impl BedRecord {
pub fn parse(line: &str) -> Result<BedRecord, &'static str> {
let fields: Vec<&str> = line.split('\t').collect();
let chrom = fields[0];
let tx_start = fields[1].parse::<u32>().unwrap();
let tx_end = fields[2].parse::<u32>().unwrap();
let name = fields[3];
let strand = fields[5];
let cds_start = fields[6].parse::<u32>().unwrap();
let cds_end = fields[7].parse::<u32>().unwrap();
let exon_count = fields[9].parse::<u16>().unwrap();
let mut exon_start = fields[11]
.split(',')
.map(|x| x.parse::<u32>().unwrap())
.collect::<Vec<u32>>();
let mut exon_end = fields[12]
.split(',')
.map(|x| x.parse::<u32>().unwrap())
.collect::<Vec<u32>>();
for i in 0..exon_count as usize {
exon_start[i] += tx_start;
exon_end[i] += tx_start;
}
Ok(BedRecord {
chrom: chrom.to_string(),
tx_start: tx_start,
tx_end: tx_end,
name: name.to_string(),
strand: strand.to_string(),
cds_start: cds_start,
cds_end: cds_end,
exon_count: exon_count,
exon_start: exon_start,
exon_end: exon_end,
})
}
}
The parallel_parse function gives and error and is not well implemented, please fix that. Also check the BedRecord struct and review if that is the fastest way to do that.
|
44f68b284a82563627f7ec78209a1ef8
|
{
"intermediate": 0.30403465032577515,
"beginner": 0.5755499601364136,
"expert": 0.12041543424129486
}
|
32,233
|
Help me fix these errors:
CustomGrid.cpp||In member function ‘virtual void CustomGrid::DrawRowLabel(wxDC&, int)’:|
CustomGrid.cpp|31|error: no matching function for call to ‘CustomGrid::GetRowLabelSize(int&)’|
/usr/local/include/wx-3.1/wx/generic/grid.h|1801|note: candidate: ‘int wxGrid::GetRowLabelSize() const’|
/usr/local/include/wx-3.1/wx/generic/grid.h|1801|note: candidate expects 0 arguments, 1 provided|
CustomGrid.cpp|31|error: no matching function for call to ‘CustomGrid::GetRowLabelSize(int&)’|
/usr/local/include/wx-3.1/wx/generic/grid.h|1801|note: candidate: ‘int wxGrid::GetRowLabelSize() const’|
/usr/local/include/wx-3.1/wx/generic/grid.h|1801|note: candidate expects 0 arguments, 1 provided|
void CustomGrid::DrawRowLabel(wxDC& dc, int row)
{
if (pinnedRows.count(row) > 0)
{
dc.SetBrush(wxBrush(wxColour(255, 255, 0))); // Yellow color
dc.SetPen(*wxTRANSPARENT_PEN);
dc.DrawRectangle(wxRect(wxSize(GetRowLabelSize(row).GetWidth(), GetRowTop(row), GetRowLabelSize(row).GetWidth(), GetRowHeight(row)));
return;
}
wxGrid::DrawRowLabel(dc, row);
}
|
4fee6131375c970bdbd75972249b4ec6
|
{
"intermediate": 0.4228922426700592,
"beginner": 0.3629480004310608,
"expert": 0.21415975689888
}
|
32,234
|
Is there a command in Bash on Debian that gives the device name for a corresponding UUID? Be very concise.
|
1b261ec7b2ac33603598126c6ff594a4
|
{
"intermediate": 0.4674924314022064,
"beginner": 0.23979505896568298,
"expert": 0.292712539434433
}
|
32,235
|
Write a function that receives as parameters
one tuple, one character and one integer
This function should return a tuple similar to
that of the parameter, but in which the
element at the index of the integer is the
character passed as a parameter
(think how you’d do that with a string)
|
c0cd417f9aeaf69805bf33fa0e95bb0b
|
{
"intermediate": 0.3114672899246216,
"beginner": 0.4471363127231598,
"expert": 0.24139638245105743
}
|
32,236
|
C# play sound
|
3caaf338a90d3f34dc14908e3fc1633a
|
{
"intermediate": 0.40023958683013916,
"beginner": 0.4543338119983673,
"expert": 0.14542663097381592
}
|
32,237
|
What are your thoughts on this implementation:
fn main() {
let bedfile =
"/home/alejandro/Documents/unam/TOGA_old_versions/x/bed_gencode_tmp/gencode.v44.bed";
let isoforms =
"/home/alejandro/Documents/unam/TOGA_old_versions/x/bed_gencode_tmp/gencode_isoforms.txt";
let bed = bed_reader(bedfile);
let iso = get_isoforms(isoforms);
let mut track: HashSet<String> = HashSet::new();
for record in bed {
let key = match iso.get(&record.name) {
Some(k) => k,
None => {
println!(
"{} {}",
"Fail:".bright_red().bold(),
"BED file could not be converted. Some isoforms are consistent between files."
);
std::process::exit(1);
}
};
if !track.contains(key) {
track.insert(key.to_string());
to_gtf(todo!());
} else {
to_gtf(todo!());
}
}
}
This needs to be the most efficient and fastest way. Maybe parallelize or SIMD? Take into account that to_gtf function will write to a file
|
85ac86adab955d87457210a7af655b4c
|
{
"intermediate": 0.5565158724784851,
"beginner": 0.27648910880088806,
"expert": 0.1669950932264328
}
|
32,238
|
Is there a bash on Debian command that can convert a device input string or whatever the proper terminology is like /dev/vda1 to /dev/vda?
|
b1148b558be0f5980dedfe1f25b68362
|
{
"intermediate": 0.5671458840370178,
"beginner": 0.20778760313987732,
"expert": 0.22506655752658844
}
|
32,239
|
На js название вывело, а изображение нет: <img src="data:image/jpeg;base64,${product.image}" alt="${product.Nazvanie}">
|
a4ac915bdd05821a270cbd252cdccbd5
|
{
"intermediate": 0.40167009830474854,
"beginner": 0.31406593322753906,
"expert": 0.2842640280723572
}
|
32,240
|
Continue my abruptly-ended previous ChatGPT instance.:
Is there a bash on Debian command that can convert a device input string or whatever the proper terminology is like /dev/vda1 to /dev/vda?
Yes, you can use the basename command to convert a device input string by removing the trailing number or character. Here’s an example:
input=“/dev/vda1”
output=$(basename
|
1dbd47ecd38a906ff62a2db2435c2475
|
{
"intermediate": 0.549963653087616,
"beginner": 0.17124634981155396,
"expert": 0.27879008650779724
}
|
32,241
|
How can I know that a (Bash) script from /etc/initramfs-tools/scripts/init-premount is being run or not (in Debian GNU/Linux)?
|
f27614e5879db8f515178d1320b335b6
|
{
"intermediate": 0.5725057721138,
"beginner": 0.27846968173980713,
"expert": 0.14902456104755402
}
|
32,242
|
Hi! I'm quite new to programming, but I recently had an idea of combining React, Django, and PostGreSQL to create a complex but useful quiz app to help with anatomy bellringers. I'll give you a detailed description of the features I need for the project.
Ok, so I’ll start by explaining the database structure I’m looking for, and then all the front-end features and functionalities. In terms of the database, let me provide a more detailed description on how this is structured, to pair with the information above: In our complex database, I need to have a table to store the user login information. I have a table of questions, which contains the following properties: A question ID, The structure/organ that the question is about, the body region that the question is about, the organ system, the question type (for our case this will always be short answer), the Question Stem/Text, the Correct Answer, and an Explanation for that answer. I also have a table linking my images with their structures in the following manner: Each Image has an ID, and each Image has a bunch of labels from A-Z that map to a structure (for example, in an image, A might be the posterior pituitary and B might be the anterior pituitary). I need a table that will store quizzes as they are formed, which links a quizID with a UserID, storing the quiz information and number of questions. I need a table that will store the Questions that were provided in each quiz, containing QuizQuestionID, QuizID, QuestionID, and Question Position in the quiz. I need a table that will store the Users scores to their past quizzes, containing a SubmissionID, UserID, QuizID, Submission Date, Accuracy, Number of Questions Incorrect, and Number of Questions Correct. I need a table that will store the Users specific answers to their past quizzes, containing a QuizID, SubmissionID, QuizQuestionID, UserAnswer, and if it was correct or not.
Now for front-end.
I need to be able to easily add new images to the database we have. I know react has some libraries like react-image-annotation and libraries for uploading images, so I need the following functionality: A user should be able to upload a labeled image, and using the annotation library, be able to manually put on masks onto the image to cover the labels with the A-Z labels/masks, creating the masked image we would show at a station. For every new label that the user adds, the label should increaes (So the first label should be A, the next B, and so on.) Finally, for every new label that the user adds, there should be a table at the bottom that keeps adding rows, which will automatically fill in the letter used for the label, and ask for an input of the structure name (so when I put my first label, the label itself should say A, and then a table at the bottom would have 2 columns: the label (which would be "A"), and the structure name that the user has to fill out. Adding a new label would put the text B on top of the label on the image, and add a new row in the table with the label "B" asking for the corresponding structure). Clicking submit on this after fully masking should add this entry to the database that connects the images with their structures and labels; specifically, the image-structure database where we would add the image ID, and for every entry in the table that the user filled out with the labels and the structure names, we would add that to the database.
In terms of the quizzes themselves, when a user selects to make a new quiz, they need to be able to select filters that would sort through questions. Specifically, there are 3 filters I am working with: Body Region, Organ System, and Organs. Each of these filters would be in the form of a checkbox - check the box, and only questions with those properties can be asked. Now here's where it gets tricky: Bellringers are typically composed of 10-20 stations, which is formed with an image and 2 associated structures. What does that mean for us? In terms of front-end, when the quiz is generated, we need to have an individual page view for each station. This page view would show an image (I have 2 kinds of images - labeled and masked. During the quiz, we show the masked image, and at the end when the user is checking what they got right/wrong, we show the labeled image), and would have 2 questions (which are short-answer questions, so they need text input). Each station in a bellringer also has a time limit of 1 minute - once that 1-minute is finished, I need that station to autosubmit and to move on to the next station to simulate a real test. Once the test is complete, I need to have a validation system in place that can check the user inputted answer with the correct answer in the database, and thus provide a score for the quiz. Also, there should be a way to view the questions on the quiz, which would have: A labeled image of the station, the user's answer, the correct answer, and an explanation. Why is this important? The logic behind the quiz questioning is as follows (And I'll use an example to make it clear): Users create a new quiz, and filter for specific topics that they are looking to be tested on (let's suppose they want to be tested on the endocrine and reproductive system). Next, we go into our question table and filter only for endocrine and reproductive questions. Out of the remaining questions left, we see which structures are remaining, and with those remaining structures, we filter out our image table to get the list of images (so let's suppose filtering for the endocrine and reproductive leaves us with 20 questions, and the structures associated with those questions are the pituitary and the ovaries. Now I go to my images, and I see only 5 images contain either the pituitary or the ovaries). Now that we have our images that are valid for the quiz, we create our stations: Randomly select 20 images (unless there are less than that, then select the total number of images that we can choose - this can probably be done with a min function like in the example where we only have 5 images). For each image, we have all the labeled structures in those A-Z labels. With those structures, we can go to our question table (remember, this is already filtered to only questions that the user wants) and get a list of potential questions for the structures at that table (so suppose my first image is an image of the brain, so it has the structures pituitary, hypothalamus, and brainstem. I'd take those structures and go back to my filtered question table which only contains endocrine and reproductive questions, and see which questions aligned with my structures. In this case, only questions about the pituitary would be allowed). Finally, I'd randomize 2 of those possible questions at the station, and show those for the user to answer.
In terms of overarching usage, I need to have user login functionality (which means they need to be able to create a username, password, and I need to get the information about when they logged in), and that information can be stored in a database table in PostgreSQL. Once logged in, each user needs to have the ability to do the following: They need to be able to create a new quiz, which would pull questions from the database. They need to be able to see their past quizzes, which would provide a detailed list of past quizzes they took (this information would also be stored in a database). In this list of past quizzes, they need to be able to see the order of the questions, their inputted answers, and the correct answer (which will help with learning). As such, the database will likely need to have a table to host quizzes when they are complete, likely with a Quiz ID, the associated Question IDs, the order the Q's appeared in, and the User answers to each question. In terms of taking the quiz, Do you think you can help me code this?
I’ll also preface this by saying I have no programming experience and I just installed VSCode, so I’ll need a detailed tutorial as well as exact code to use through each step that we go through to build this app in VSCode. Does that sound like a plan? Then we can start first with backend development, then doing the image annotation, then integrating it with front-end and creating the quiz functionalities, and then designing it to look great.
|
e62ea5980fd1d69d744f0239c182e903
|
{
"intermediate": 0.3834565281867981,
"beginner": 0.3108835816383362,
"expert": 0.3056598901748657
}
|
32,243
|
Can you provide an .obj file for the surface of a sphere, divided and separated into three identical non-polar portions?
|
4424a8c30a061fbca945c3d6cfc97dce
|
{
"intermediate": 0.43278348445892334,
"beginner": 0.2674223482608795,
"expert": 0.29979416728019714
}
|
32,244
|
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from flask_login import LoginManager
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = 'fetch.login_post'
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Ln3486160@localhost:5432/RPP_2.3'
app.config['SQLAlchemy_TRACK_MODIFIVATTION'] = False опиши что происходит в коде
|
1fd3d333dafcb5d9413a015131de36b1
|
{
"intermediate": 0.5455795526504517,
"beginner": 0.21290495991706848,
"expert": 0.24151545763015747
}
|
32,245
|
Create table Activity (player_id int, device_id int, event_date date, games_played int)
Truncate table Activity
insert into Activity (player_id, device_id, event_date, games_played) values ('1', '2', '2016-03-01', '5')
insert into Activity (player_id, device_id, event_date, games_played) values ('1', '2', '2016-05-02', '6')
insert into Activity (player_id, device_id, event_date, games_played) values ('2', '3', '2017-06-25', '1')
insert into Activity (player_id, device_id, event_date, games_played) values ('3', '1', '2016-03-02', '0')
insert into Activity (player_id, device_id, event_date, games_played) values ('3', '4', '2018-07-03', '5') find using subqueries in sql
|
0fceb7a7b95384a1e5212ddfb36c1150
|
{
"intermediate": 0.3755728602409363,
"beginner": 0.2862001955509186,
"expert": 0.33822694420814514
}
|
32,246
|
I am running the following code, but I want to add code that lets me know how long it takes to complete: import openpyxl
# Open the input Excel workbook and get the sheet object
input_wb = openpyxl.load_workbook('input.xlsx')
input_sheet = input_wb['Sheet1']
# Get the range of cells containing the prompts
prompts = input_sheet['A1':'A20']
# Create a new Excel workbook and worksheet objects
output_wb = openpyxl.Workbook()
output_sheet = output_wb.active
# Define the range of cells where you want to write the responses
output_range = output_sheet['A1':'A20']
# Loop over the range of cells and write the prompt code
for i, prompt in enumerate(prompts):
# Extract the value from the cell object
prompt_value = prompt[0].value
# Generate the response
response = generator(prompt_value)
print(response[0]["generated_text"])
# Write the response to the current cell
output_range[i][0].value = response[0]["generated_text"]
# Save the output workbook outside the loop
output_wb.save('output.xlsx')
|
24a358ccf3ff04e5d251b564f3d0988b
|
{
"intermediate": 0.31433382630348206,
"beginner": 0.5096892714500427,
"expert": 0.1759769171476364
}
|
32,247
|
I want a script that causes a player to die when they step on it (roblox script)
|
51885570cbd16fb69c63c176c1a9fe0e
|
{
"intermediate": 0.3077515661716461,
"beginner": 0.24509479105472565,
"expert": 0.4471536874771118
}
|
32,248
|
Create table Employee (empId int, name varchar(255), supervisor int, salary int)
Create table Bonus (empId int, bonus int)
Truncate table Employee
insert into Employee (empId, name, supervisor, salary) values ('3', 'Brad', NULL, '4000')
insert into Employee (empId, name, supervisor, salary) values ('1', 'John', '3', '1000')
insert into Employee (empId, name, supervisor, salary) values ('2', 'Dan', '3', '2000')
insert into Employee (empId, name, supervisor, salary) values ('4', 'Thomas', '3', '4000')
Truncate table Bonus
insert into Bonus (empId, bonus) values ('2', '500')
insert into Bonus (empId, bonus) values ('4', '2000')
select * from Employee
select * from Bonus
-- Q2: report name and bonuse amount who's bonus amount is less than $1,000
|
3c11e67704f7508932d2550533e06376
|
{
"intermediate": 0.33657175302505493,
"beginner": 0.29344215989112854,
"expert": 0.36998608708381653
}
|
32,249
|
Define a function sel_sort to implement the straight selection sort on a list. Similar
to the ins_sort on Slide 11, you need to define a local function sel to move the mini-
mum element to the head position. Justify if your implementation is a stable sorting
algorithm.
|
31c4e6ec56d2926cca0cfde46ec56770
|
{
"intermediate": 0.2402002513408661,
"beginner": 0.20071136951446533,
"expert": 0.5590883493423462
}
|
32,250
|
Define a function
balance :: Ord 𝑎 => [𝑎] -> Tree 𝑎
that converts a list of increasingly ordered elements into a balanced search tree. Hint:
first define a function that splits a list into two halves whose length differs by at most
one. use haskell code
|
572553507769fa2b2296225afa4dc68c
|
{
"intermediate": 0.2845548391342163,
"beginner": 0.3501121699810028,
"expert": 0.3653329610824585
}
|
32,251
|
monthly income, monthly expense then based on my savings i want to check how much loan i will get and that loan amount repayment at particular rate of interest and how much my monthly emi will be, please give me kotlin code
|
5fe41032bee874c59c562f3833745dfb
|
{
"intermediate": 0.43577292561531067,
"beginner": 0.28265711665153503,
"expert": 0.2815699875354767
}
|
32,252
|
monthly income, monthly expense then based on my savings i want to check how much loan i will get and that loan amount repayment at particular rate of interest and how much my monthly emi will be, please give me kotlin code
|
04b2aa3f32181de335e4d259c3e7b892
|
{
"intermediate": 0.43577292561531067,
"beginner": 0.28265711665153503,
"expert": 0.2815699875354767
}
|
32,253
|
check this function:
fn find_first_codon(record: &BedRecord) -> Codon {
let mut codon = Codon::new();
let mut exon = 0;
for k in 0..record.get_exon_frames().len() {
if record.get_exon_frames()[k] >= 0 {
exon = k;
break;
} else {
return codon;
}
}
let cds_exon_start = max(record.exon_start()[exon], record.cds_start());
let cds_exon_end = min(record.exon_end()[exon], record.cds_end());
let frame = if record.strand() == "+" {
record.get_exon_frames()[exon]
} else {
(record.get_exon_frames()[exon] + (cds_exon_end - cds_exon_start)) % 3
};
if frame != 0 {
return codon;
}
codon.start = record.cds_start();
codon.end = record.cds_start() + (record.cds_end() - record.cds_start()).min(3);
codon.index = exon as u32;
if codon.end - codon.start < 3 {
exon = exon + 1;
if exon == record.exon_count() as usize {
return codon;
};
let need = 3 - (codon.end - codon.start);
if (record.cds_end() - record.cds_start()) < need {
return codon;
}
codon.start2 = record.cds_start();
codon.end2 = record.cds_start() + need;
}
codon
}
where:
#[derive(Debug, Clone)]
pub struct Codon {
pub start: i32,
pub end: i32,
pub index: i32,
pub start2: i32,
pub end2: i32,
}
impl Codon {
pub fn new() -> Codon {
Codon {
start: 0,
end: 0,
index: 0,
start2: 0,
end2: 0,
}
}
}
and
#[derive(Clone, Debug, PartialEq)]
pub struct BedRecord {
pub chrom: String,
pub tx_start: u32,
tx_end: u32,
name: String,
strand: String,
cds_start: u32,
cds_end: u32,
exon_count: u16,
exon_start: Vec<u32>,
exon_end: Vec<u32>,
}
Review the function find_first_codon() and make all the changes needed to make it faster and more efficient
|
51a4c0ecdab99ddc3841c887e09d8d55
|
{
"intermediate": 0.402569055557251,
"beginner": 0.30460095405578613,
"expert": 0.2928300201892853
}
|
32,254
|
You are an expert Rust programmer. This is the implementation of one of your students:
fn find_first_codon(record: &BedRecord) -> Codon {
let mut codon = Codon::new();
let mut exon = 0;
for k in 0..record.get_exon_frames().len() {
if record.get_exon_frames()[k] >= 0 {
exon = k;
break;
} else {
return codon;
}
}
let cds_exon_start = max(record.exon_start()[exon], record.cds_start());
let cds_exon_end = min(record.exon_end()[exon], record.cds_end());
let frame = if record.strand() == "+" {
record.get_exon_frames()[exon]
} else {
(record.get_exon_frames()[exon] + (cds_exon_end - cds_exon_start)) % 3
};
if frame != 0 {
return codon;
}
codon.start = record.cds_start();
codon.end = record.cds_start() + (record.cds_end() - record.cds_start()).min(3);
codon.index = exon as u32;
if codon.end - codon.start < 3 {
exon = exon + 1;
if exon == record.exon_count() as usize {
return codon;
};
let need = 3 - (codon.end - codon.start);
if (record.cds_end() - record.cds_start()) < need {
return codon;
}
codon.start2 = record.cds_start();
codon.end2 = record.cds_start() + need;
}
codon
}
You gave them this implementation of get_exon_frames():
pub fn get_frames(&self) -> Vec<i16> {
let mut exon_frames: Vec<i16> = vec![-1; self.exon_count as usize];
let mut cds: u32 = 0;
let exon_range = if self.strand == "+" {
(0..(self.exon_count as usize)).collect::<Vec<_>>()
} else {
(0..(self.exon_count as usize)).rev().collect::<Vec<_>>()
};
for exon in exon_range {
let cds_exon_start = max(self.exon_start[exon], self.cds_start);
let cds_exon_end = min(self.exon_end[exon], self.cds_end);
if cds_exon_start < cds_exon_end {
exon_frames[exon] = (cds % 3) as i16;
cds += cds_exon_end - cds_exon_start;
}
}
exon_frames
}
and also gave them this information:
#[derive(Debug)]
pub struct BedRecord {
pub chrom: String,
pub tx_start: u32,
pub tx_end: u32,
pub name: String,
pub strand: String,
pub cds_start: u32,
pub cds_end: u32,
pub exon_count: u16,
pub exon_start: Vec<u32>,
pub exon_end: Vec<u32>,
}
#[derive(Debug, Clone)]
pub struct Codon {
pub start: u32,
pub end: u32,
pub index: u32,
pub start2: u32,
pub end2: u32,
}
impl Codon {
pub fn new() -> Codon {
Codon {
start: 0,
end: 0,
index: 0,
start2: 0,
end2: 0,
}
}
}
Check you student's solution, the goal of this homework was to build the most efficient and fastest way to find the first codon being aware of frames and strands
|
3c0970d255792808553fbee444a88e44
|
{
"intermediate": 0.39766252040863037,
"beginner": 0.3998851776123047,
"expert": 0.20245225727558136
}
|
32,255
|
You are an expert Rust programmer. This is the implementation of one of your students:
fn find_first_codon(record: &BedRecord) -> Codon {
let mut codon = Codon::new();
let mut exon = 0;
for k in 0…record.get_exon_frames().len() {
if record.get_exon_frames()[k] >= 0 {
exon = k;
break;
} else {
return codon;
}
}
let cds_exon_start = max(record.exon_start()[exon], record.cds_start());
let cds_exon_end = min(record.exon_end()[exon], record.cds_end());
let frame = if record.strand() == “+” {
record.get_exon_frames()[exon]
} else {
(record.get_exon_frames()[exon] + (cds_exon_end - cds_exon_start)) % 3
};
if frame != 0 {
return codon;
}
codon.start = record.cds_start();
codon.end = record.cds_start() + (record.cds_end() - record.cds_start()).min(3);
codon.index = exon as u32;
if codon.end - codon.start < 3 {
exon = exon + 1;
if exon == record.exon_count() as usize {
return codon;
};
let need = 3 - (codon.end - codon.start);
if (record.cds_end() - record.cds_start()) < need {
return codon;
}
codon.start2 = record.cds_start();
codon.end2 = record.cds_start() + need;
}
codon
}
You gave them this implementation of get_exon_frames():
pub fn get_frames(&self) -> Vec<i16> {
let mut exon_frames: Vec<i16> = vec![-1; self.exon_count as usize];
let mut cds: u32 = 0;
let exon_range = if self.strand == “+” {
(0…(self.exon_count as usize)).collect::<Vec<>>()
} else {
(0…(self.exon_count as usize)).rev().collect::<Vec<>>()
};
for exon in exon_range {
let cds_exon_start = max(self.exon_start[exon], self.cds_start);
let cds_exon_end = min(self.exon_end[exon], self.cds_end);
if cds_exon_start < cds_exon_end {
exon_frames[exon] = (cds % 3) as i16;
cds += cds_exon_end - cds_exon_start;
}
}
exon_frames
}
and also gave them this information:
#[derive(Debug)]
pub struct BedRecord {
pub chrom: String,
pub tx_start: u32,
pub tx_end: u32,
pub name: String,
pub strand: String,
pub cds_start: u32,
pub cds_end: u32,
pub exon_count: u16,
pub exon_start: Vec<u32>,
pub exon_end: Vec<u32>,
}
#[derive(Debug, Clone)]
pub struct Codon {
pub start: u32,
pub end: u32,
pub index: u32,
pub start2: u32,
pub end2: u32,
}
impl Codon {
pub fn new() -> Codon {
Codon {
start: 0,
end: 0,
index: 0,
start2: 0,
end2: 0,
}
}
}
Check you student’s solution, the goal of this homework was to build the most efficient and fastest way to find the first codon being aware of frames and strands
|
1c3572fd7ae8ef7dded744b66112e1d5
|
{
"intermediate": 0.3602796792984009,
"beginner": 0.35266971588134766,
"expert": 0.2870505452156067
}
|
32,256
|
hello
|
cce298382a62f8eb5f160f4b984c471f
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
32,257
|
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY)
IMAGE_THRESHOLD = 100
def get_coords_by_threshold(
image: np.ndarray, threshold: int = IMAGE_THRESHOLD
) -> tuple:
"""Gets pixel coords with intensity more then 'theshold'."""
coords = np.where(image > threshold)
return coords
def delete_pixels_by_min_threshold(
image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD
) -> np.ndarray:
"""Deletes coords from image and returns this image."""
anti_coords = np.where(image < min_threshold)
image[anti_coords] = 0
return image
def get_neigh_nums_list(
coords: tuple, kernel_size: int = 3
) -> list:
"""
Gets list with number of neighborhoods by kernel.
Returns list like [[x1, y1, N1], [x2, y2, N2]],
Where N - neighborhood's number.
"""
neigh_nums = []
offset = (kernel_size - 1) // 2
for x, y in zip(coords[0], coords[1]):
if x < 0 + offset or x > image.shape[0] - offset:
continue
if y < 0 + offset or y > image.shape[1] - offset:
continue
kernel = image[x-offset:x+offset+1, y-offset:y+offset+1]
step_neigh_num = np.count_nonzero(kernel) - 1
neigh_nums.append([x, y, step_neigh_num])
return neigh_nums
def sort_neight_nums_by_N(neigh_nums: list) -> np.ndarray:
"""
Sort neigh_nums by N parameter.
Removes N=-1, N=0 and sorts by N desc.
"""
np_neigh_nums = np.array(neigh_nums)
np_neigh_nums = np_neigh_nums[
(np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)]
np_neigh_nums = np_neigh_nums[
np.argsort(-np_neigh_nums[:, 2])]
return np_neigh_nums
def get_potential_points_coords(
sorted_niegh_nums: np.ndarray, potential_points_num: int = 200
) -> np.ndarray:
"""
Gets best candidates, potential points coords only.
Returns np.ndarray like [[x1, y1], [x2, y2]].
"""
sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1)
return sorted_neigh_nums[:potential_points_num]
# def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
# """
# Gets best combinations of lines by all points.
# Line y = kx + b.
# Returns np.ndarray like [[k1, b1], [k2, b2]].
# """
# best_lines = []
# best_inliers = []
# iterations_num = 1000
# threshold_distance = 3
# threshold_k = 0.1
# threshold_b = 10
# for i in range(iterations_num):
# sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False)
# sample_points = potential_points[sample_indices]
# sample_x = sample_points[:, 1]
# sample_y = sample_points[:, 0]
# coefficients = np.polyfit(sample_x, sample_y, deg=1)
# distances = np.abs(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1)
# inliers = np.where(distances < threshold_distance)[0]
# is_similar = False
# for line in best_lines:
# diff_k = abs(coefficients[0] - line[0])
# diff_b = abs(coefficients[0] - line[0])
# if diff_k <= threshold_k and diff_b <= threshold_b:
# is_similar = True
# break
# if not is_similar and len(inliers) > len(best_inliers):
# best_lines = [coefficients]
# best_inliers = inliers
# elif not is_similar and len(inliers) == len(best_inliers):
# best_lines.append(coefficients)
# return np.array(best_lines)
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Gets best combinations of lines by all points.
Line y = kx + b.
Returns np.ndarray like [[k1, b1], [k2, b2]].
"""
best_lines = []
num_lines = 0
iterations_num = 1000
threshold_distance = 3
threshold_k = 0.5
threshold_b = 20
while num_lines < 3:
if num_lines == 0:
remaining_points = np.copy(potential_points)
print(f"remaining points: {len(remaining_points)}")
best_inliers = []
best_line = None
for i in range(iterations_num):
if len(remaining_points) < 2:
break
sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False)
sample_points = remaining_points[sample_indices]
sample_x = sample_points[:, 1]
sample_y = sample_points[:, 0]
coefficients = np.polyfit(sample_x, sample_y, deg=1)
distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1)
inliers = np.where(distances < threshold_distance)[0]
is_similar = False
for line in best_lines:
diff_k = abs(coefficients[0] - line[0])
diff_b = abs(coefficients[1] - line[1])
if diff_k <= threshold_k and diff_b <= threshold_b:
is_similar = True
break
if not is_similar and len(inliers) > len(best_inliers):
best_line = coefficients
best_inliers = inliers
if best_line is not None:
best_lines.append(best_line)
buffer = remaining_points
remaining_points = np.delete(remaining_points, best_inliers, axis=0)
if len(remaining_points) < 1:
remaining_points = np.append(remaining_points, buffer[:len(buffer)//2 + 1])
num_lines += 1
return np.array(best_lines)
# def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float:
# """Calculates the angle in degrees between two lines."""
# k1, b1 = line1
# k2, b2 = line2
# angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2)
# angle_deg = np.degrees(angle_rad)
# return angle_deg
# main
coords = get_coords_by_threshold(image)
# image = delete_pixels_by_min_threshold(image)
neigh_nums = get_neigh_nums_list(coords)
sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums)
potential_points = get_potential_points_coords(sorted_neigh_nums)
best_lines = get_best_lines(potential_points)
print(best_lines)
# Visualization
plt.imshow(image, cmap="gray")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.show()
# Plot the lines on the image
for equation in best_lines:
k, b = equation
x = np.arange(0, image.shape[1])
y = k * x + b
plt.imshow(image, cmap="gray")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.plot(x, y, color="green")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.show()
intersection_points = np.array([
np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])),
np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])),
np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]]))
], dtype=np.float32)
print(intersection_points)
Что делать? Видимо, когда не находит достаточное количество potential_points, то вылетает ошибка?
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-5-85e252f97691> in <cell line: 193>()
191 potential_points = get_potential_points_coords(sorted_neigh_nums)
192
--> 193 best_lines = get_best_lines(potential_points)
194 print(best_lines)
195
<ipython-input-5-85e252f97691> in get_best_lines(potential_points)
140 sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False)
141 sample_points = remaining_points[sample_indices]
--> 142 sample_x = sample_points[:, 1]
143 sample_y = sample_points[:, 0]
144 coefficients = np.polyfit(sample_x, sample_y, deg=1)
IndexError: too many indices for array: array is 1-dimensional, but 2 were indexed
Можно ли как-то улучшить алгоритм, чтобы избежать этого
|
7cea54d95ecc8d590fbd13965e4eb146
|
{
"intermediate": 0.27387356758117676,
"beginner": 0.47204846143722534,
"expert": 0.2540779411792755
}
|
32,258
|
review this implementation:
pub fn first_codon(record: &BedRecord) -> Option<Codon> {
let exon_frames = record.get_frames();
record
.exon_start
.iter()
.zip(record.exon_end.iter())
.enumerate()
.find_map(|(mut index, (&start, &end))| {
let mut codon = Codon::new();
let cds_start = max(start, record.cds_start);
let cds_end = min(end, record.cds_end);
if cds_start >= cds_end {
return None;
}
let frame = exon_frames.get(index)?;
let frame = if record.strand == "+" {
*frame
} else {
(*frame + (cds_end - cds_start) as i16) % 3
};
if frame == 0 {
codon.start = cds_start;
codon.end = cds_start + 3;
codon.index = index as u32;
let diff = cds_end - cds_start;
if diff >= 3 {
Some(codon)
} else {
index += 1;
if index >= exon_frames.len() {
Some(codon)
} else {
let need = 3 - diff;
if diff < need {
Some(codon)
} else {
codon.start2 = cds_start;
codon.end2 = cds_start + need;
Some(codon)
}
}
}
} else {
Some(Codon::new())
}
})
}
|
c3a7616bd795a5fc19a4144c528cfa89
|
{
"intermediate": 0.3962685763835907,
"beginner": 0.38816267251968384,
"expert": 0.21556873619556427
}
|
32,259
|
image = cv2.imread("0.0/01.pgm", cv2.COLOR_BGR2GRAY)
IMAGE_THRESHOLD = 100
def get_coords_by_threshold(
image: np.ndarray, threshold: int = IMAGE_THRESHOLD
) -> tuple:
"""Gets pixel coords with intensity more then 'theshold'."""
coords = np.where(image > threshold)
return coords
def delete_pixels_by_min_threshold(
image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD
) -> np.ndarray:
"""Deletes coords from image and returns this image."""
anti_coords = np.where(image < min_threshold)
image[anti_coords] = 0
return image
def get_neigh_nums_list(
coords: tuple, kernel_size: int = 3
) -> list:
"""
Gets list with number of neighborhoods by kernel.
Returns list like [[x1, y1, N1], [x2, y2, N2]],
Where N - neighborhood's number.
"""
neigh_nums = []
offset = (kernel_size - 1) // 2
for x, y in zip(coords[0], coords[1]):
if x < 0 + offset or x > image.shape[0] - offset:
continue
if y < 0 + offset or y > image.shape[1] - offset:
continue
kernel = image[x-offset:x+offset+1, y-offset:y+offset+1]
step_neigh_num = np.count_nonzero(kernel) - 1
neigh_nums.append([x, y, step_neigh_num])
return neigh_nums
def sort_neight_nums_by_N(neigh_nums: list) -> np.ndarray:
"""
Sort neigh_nums by N parameter.
Removes N=-1, N=0 and sorts by N desc.
"""
np_neigh_nums = np.array(neigh_nums)
np_neigh_nums = np_neigh_nums[
(np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)]
np_neigh_nums = np_neigh_nums[
np.argsort(-np_neigh_nums[:, 2])]
return np_neigh_nums
def get_potential_points_coords(
sorted_niegh_nums: np.ndarray, potential_points_num: int = 200
) -> np.ndarray:
"""
Gets best candidates, potential points coords only.
Returns np.ndarray like [[x1, y1], [x2, y2]].
"""
sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1)
return sorted_neigh_nums[:potential_points_num]
# def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
# """
# Gets best combinations of lines by all points.
# Line y = kx + b.
# Returns np.ndarray like [[k1, b1], [k2, b2]].
# """
# best_lines = []
# best_inliers = []
# iterations_num = 1000
# threshold_distance = 3
# threshold_k = 0.1
# threshold_b = 10
# for i in range(iterations_num):
# sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False)
# sample_points = potential_points[sample_indices]
# sample_x = sample_points[:, 1]
# sample_y = sample_points[:, 0]
# coefficients = np.polyfit(sample_x, sample_y, deg=1)
# distances = np.abs(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1)
# inliers = np.where(distances < threshold_distance)[0]
# is_similar = False
# for line in best_lines:
# diff_k = abs(coefficients[0] - line[0])
# diff_b = abs(coefficients[0] - line[0])
# if diff_k <= threshold_k and diff_b <= threshold_b:
# is_similar = True
# break
# if not is_similar and len(inliers) > len(best_inliers):
# best_lines = [coefficients]
# best_inliers = inliers
# elif not is_similar and len(inliers) == len(best_inliers):
# best_lines.append(coefficients)
# return np.array(best_lines)
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Gets best combinations of lines by all points.
Line y = kx + b.
Returns np.ndarray like [[k1, b1], [k2, b2]].
"""
best_lines = []
num_lines = 0
iterations_num = 1000
threshold_distance = 3
threshold_k = 0.5
threshold_b = 20
while num_lines < 3:
if num_lines == 0:
remaining_points = np.copy(potential_points)
print(f"remaining points: {len(remaining_points)}")
best_inliers = []
best_line = None
for i in range(iterations_num):
sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False)
sample_points = remaining_points[sample_indices]
sample_x = sample_points[:, 1]
sample_y = sample_points[:, 0]
coefficients = np.polyfit(sample_x, sample_y, deg=1)
distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1)
inliers = np.where(distances < threshold_distance)[0]
is_similar = False
for line in best_lines:
diff_k = abs(coefficients[0] - line[0])
diff_b = abs(coefficients[1] - line[1])
if diff_k <= threshold_k and diff_b <= threshold_b:
is_similar = True
break
if not is_similar and len(inliers) > len(best_inliers):
best_line = coefficients
best_inliers = inliers
if best_line is not None:
best_lines.append(best_line)
# buffer = remaining_points
remaining_points = np.delete(remaining_points, best_inliers, axis=0)
# if len(remaining_points) < 1:
# remaining_points = np.append(remaining_points, buffer[:len(buffer)//2 + 1])
num_lines += 1
return np.array(best_lines)
# def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float:
# """Calculates the angle in degrees between two lines."""
# k1, b1 = line1
# k2, b2 = line2
# angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2)
# angle_deg = np.degrees(angle_rad)
# return angle_deg
# main
coords = get_coords_by_threshold(image)
# image = delete_pixels_by_min_threshold(image)
neigh_nums = get_neigh_nums_list(coords)
sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums)
potential_points = get_potential_points_coords(sorted_neigh_nums)
best_lines = get_best_lines(potential_points)
print(best_lines)
# Visualization
plt.imshow(image, cmap="gray")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.show()
# Plot the lines on the image
for equation in best_lines:
k, b = equation
x = np.arange(0, image.shape[1])
y = k * x + b
plt.imshow(image, cmap="gray")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.plot(x, y, color="green")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.show()
intersection_points = np.array([
np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])),
np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])),
np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]]))
], dtype=np.float32)
print(intersection_points)
Усиль алгоритм, чтобы он более качественно находил potential_points, то есть точки, которые принадлежат прямым, образующим треугольник на зашумленном изображении
|
7a7d35abbe8a0969eec5c48810341f19
|
{
"intermediate": 0.27387356758117676,
"beginner": 0.47204846143722534,
"expert": 0.2540779411792755
}
|
32,260
|
based on this model:
pub fn first_codon(record: &BedRecord) -> Option<Codon> {
let exon_frames = record.get_frames();
record
.exon_start
.iter()
.zip(record.exon_end.iter())
.enumerate()
.find_map(|(mut index, (&start, &end))| {
let mut codon = Codon::new();
let frame = exon_frames.get(index)?;
let cds_start = max(start, record.cds_start);
let cds_end = min(end, record.cds_end);
let frame = if record.strand == "+" {
*frame
} else {
(*frame + (cds_end - cds_start) as i16) % 3
};
if frame == 0 {
codon.start = cds_start;
codon.end = cds_start + 3;
codon.index = index as u32;
let diff = cds_end - cds_start;
if diff >= 3 {
Some(codon)
} else {
index += 1;
if index >= exon_frames.len() {
Some(codon)
} else {
let need = 3 - diff;
if diff < need {
Some(codon)
} else {
codon.start2 = cds_start;
codon.end2 = cds_start + need;
Some(codon)
}
}
}
} else {
Some(Codon::new())
}
})
}
rewrite the following function:
/// Get the coordinates of the last codon (start/stop).
/// If not in frame, return an empty codon.
fn find_last_codon(record: &BedRecord) -> Codon {
let mut codon = Codon::new();
let mut exon = 0;
for k in (0..record.get_exon_frames().len()).step_by(1).rev() {
if record.get_exon_frames()[k] >= 0 {
exon = k;
break;
} else {
return codon;
}
}
let cds_exon_start = max(record.exon_start()[exon], record.cds_start());
let cds_exon_end = min(record.exon_end()[exon], record.cds_end());
let frame = if record.strand() == "-" {
record.get_exon_frames()[exon]
} else {
(record.get_exon_frames()[exon] + (cds_exon_end - cds_exon_start)) % 3
};
if frame != 0 {
return codon;
}
codon.start = max(record.cds_start(), record.cds_end() - 3);
codon.end = record.cds_end();
codon.index = exon as u32;
if codon.end - codon.start < 3 {
exon = exon + 1;
if exon == record.exon_count() as usize {
return codon;
};
let need = 3 - (codon.end - codon.start);
if (record.cds_end() - record.cds_start()) < need {
return codon;
}
codon.start2 = record.cds_start();
codon.end2 = record.cds_start() + need;
}
codon
}
|
2436aee76ddc2e2ce16f24c6bb84f93c
|
{
"intermediate": 0.32614654302597046,
"beginner": 0.3981665074825287,
"expert": 0.27568694949150085
}
|
32,261
|
explain the purpose, design and usage of c# IUrlHelperFactory class ?
|
7f4b5abd43712eb277b5b5db592825ee
|
{
"intermediate": 0.7082486748695374,
"beginner": 0.20103031396865845,
"expert": 0.09072105586528778
}
|
32,262
|
in asp.net core, i find below code in tag helper class hard to understand, what does it actually do?
|
188059d9461adf927ccfac26bf82925a
|
{
"intermediate": 0.45059317350387573,
"beginner": 0.31499579548835754,
"expert": 0.23441100120544434
}
|
32,263
|
image = cv2.imread("0.6/00.pgm", cv2.COLOR_BGR2GRAY)
IMAGE_THRESHOLD = 100
def get_coords_by_threshold(
image: np.ndarray, threshold: int = IMAGE_THRESHOLD
) -> tuple:
"""Gets pixel coords with intensity more then 'theshold'."""
coords = np.where(image > threshold)
return coords
def delete_pixels_by_min_threshold(
image: np.ndarray, min_threshold: int = IMAGE_THRESHOLD
) -> np.ndarray:
"""Deletes coords from image and returns this image."""
anti_coords = np.where(image < min_threshold)
image[anti_coords] = 0
return image
def get_neigh_nums_list(
coords: tuple, kernel_size: int = 3
) -> list:
"""
Gets list with number of neighborhoods by kernel.
Returns list like [[x1, y1, N1], [x2, y2, N2]],
Where N - neighborhood's number.
"""
neigh_nums = []
offset = (kernel_size - 1) // 2
for x, y in zip(coords[0], coords[1]):
if x < 0 + offset or x > image.shape[0] - offset:
continue
if y < 0 + offset or y > image.shape[1] - offset:
continue
kernel = image[x-offset:x+offset+1, y-offset:y+offset+1]
step_neigh_num = np.count_nonzero(kernel) - 1
neigh_nums.append([x, y, step_neigh_num])
return neigh_nums
def sort_neight_nums_by_N(neigh_nums: list) -> np.ndarray:
"""
Sort neigh_nums by N parameter.
Removes N=-1, N=0 and sorts by N desc.
"""
np_neigh_nums = np.array(neigh_nums)
np_neigh_nums = np_neigh_nums[
(np_neigh_nums[:, 2] != -1) & (np_neigh_nums[:, 2] != 0)]
np_neigh_nums = np_neigh_nums[
np.argsort(-np_neigh_nums[:, 2])]
return np_neigh_nums
def get_potential_points_coords(
sorted_niegh_nums: np.ndarray, potential_points_num: int = 200
) -> np.ndarray:
"""
Gets best candidates, potential points coords only.
Returns np.ndarray like [[x1, y1], [x2, y2]].
"""
sorted_neigh_nums = np.delete(sorted_niegh_nums, 2, axis=1)
return sorted_neigh_nums[:potential_points_num]
# def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
# """
# Gets best combinations of lines by all points.
# Line y = kx + b.
# Returns np.ndarray like [[k1, b1], [k2, b2]].
# """
# best_lines = []
# best_inliers = []
# iterations_num = 1000
# threshold_distance = 3
# threshold_k = 0.1
# threshold_b = 10
# for i in range(iterations_num):
# sample_indices = np.random.choice(potential_points.shape[0], size=3, replace=False)
# sample_points = potential_points[sample_indices]
# sample_x = sample_points[:, 1]
# sample_y = sample_points[:, 0]
# coefficients = np.polyfit(sample_x, sample_y, deg=1)
# distances = np.abs(potential_points[:, 0] - np.matmul(np.vstack((potential_points[:, 1], np.ones_like(potential_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1)
# inliers = np.where(distances < threshold_distance)[0]
# is_similar = False
# for line in best_lines:
# diff_k = abs(coefficients[0] - line[0])
# diff_b = abs(coefficients[0] - line[0])
# if diff_k <= threshold_k and diff_b <= threshold_b:
# is_similar = True
# break
# if not is_similar and len(inliers) > len(best_inliers):
# best_lines = [coefficients]
# best_inliers = inliers
# elif not is_similar and len(inliers) == len(best_inliers):
# best_lines.append(coefficients)
# return np.array(best_lines)
def get_best_lines(potential_points: np.ndarray) -> np.ndarray:
"""
Gets best combinations of lines by all points.
Line y = kx + b.
Returns np.ndarray like [[k1, b1], [k2, b2]].
"""
best_lines = []
num_lines = 0
iterations_num = 1000
threshold_distance = 3
threshold_k = 0.5
threshold_b = 20
while num_lines < 3:
if num_lines == 0:
remaining_points = np.copy(potential_points)
print(f"remaining points: {len(remaining_points)}")
best_inliers = []
best_line = None
for i in range(iterations_num):
sample_indices = np.random.choice(remaining_points.shape[0], size=3, replace=False)
sample_points = remaining_points[sample_indices]
sample_x = sample_points[:, 1]
sample_y = sample_points[:, 0]
coefficients = np.polyfit(sample_x, sample_y, deg=1)
distances = np.abs(remaining_points[:, 0] - np.matmul(np.vstack((remaining_points[:, 1], np.ones_like(remaining_points[:, 1]))).T, coefficients)) / np.sqrt(coefficients[0] ** 2 + 1)
inliers = np.where(distances < threshold_distance)[0]
is_similar = False
for line in best_lines:
diff_k = abs(coefficients[0] - line[0])
diff_b = abs(coefficients[1] - line[1])
if diff_k <= threshold_k and diff_b <= threshold_b:
is_similar = True
break
if not is_similar and len(inliers) > len(best_inliers):
best_line = coefficients
best_inliers = inliers
if best_line is not None:
best_lines.append(best_line)
# buffer = remaining_points
remaining_points = np.delete(remaining_points, best_inliers, axis=0)
# if len(remaining_points) < 1:
# remaining_points = np.append(remaining_points, buffer[:len(buffer)//2 + 1])
num_lines += 1
return np.array(best_lines)
# def angle_between_lines(line1: np.ndarray, line2: np.ndarray) -> float:
# """Calculates the angle in degrees between two lines."""
# k1, b1 = line1
# k2, b2 = line2
# angle_rad = np.arctan2(k2 - k1, 1 + k1 * k2)
# angle_deg = np.degrees(angle_rad)
# return angle_deg
# main
coords = get_coords_by_threshold(image)
# image = delete_pixels_by_min_threshold(image)
neigh_nums = get_neigh_nums_list(coords)
sorted_neigh_nums = sort_neight_nums_by_N(neigh_nums)
potential_points = get_potential_points_coords(sorted_neigh_nums)
best_lines = get_best_lines(potential_points)
print(best_lines)
# Visualization
plt.imshow(image, cmap="gray")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.show()
# Plot the lines on the image
for equation in best_lines:
k, b = equation
x = np.arange(0, image.shape[1])
y = k * x + b
plt.imshow(image, cmap="gray")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.plot(x, y, color="green")
plt.scatter(potential_points[:, 1], potential_points[:, 0], color="red", marker="o")
plt.show()
intersection_points = np.array([
np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[1][0], -1]]), np.array([-best_lines[0][1], -best_lines[1][1]])),
np.linalg.solve(np.array([[best_lines[0][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[0][1], -best_lines[2][1]])),
np.linalg.solve(np.array([[best_lines[1][0], -1], [best_lines[2][0], -1]]), np.array([-best_lines[1][1], -best_lines[2][1]]))
], dtype=np.float32)
print(intersection_points)
Улучши алгоритм, будь то по времени, будь то по качетсву определения точек
|
87591ce08fb9768f9b0493e641f9d563
|
{
"intermediate": 0.27253299951553345,
"beginner": 0.4749148190021515,
"expert": 0.25255218148231506
}
|
32,264
|
Create a full html css js resume page for a junior web developer using bootstrap 5
|
eaf7a2ccea1ed4b6825ef0a4129b7d39
|
{
"intermediate": 0.3556320369243622,
"beginner": 0.32851719856262207,
"expert": 0.31585079431533813
}
|
32,265
|
write a matlab program to accept a number from the user and check if the number even or odd
|
f19d6f64f9bdb44f0151f58293bd49db
|
{
"intermediate": 0.3018113672733307,
"beginner": 0.12462243437767029,
"expert": 0.5735661387443542
}
|
32,266
|
I used this code:
def signal_generator(df):
if df is None or len(df) < 2:
return ''
signal = []
final_signal = []
exit = []
sell_result = 0.0
buy_result = 0.0
mark_price_data = client.ticker_price(symbol=symbol)
mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol)
mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0
# Retrieve depth data
depth_data = client.depth(symbol=symbol)
bids = depth_data['bids']
bid_prices = [float(bid[0]) for bid in bids]
highest_bid_price = max(bid_prices)
lowest_bid_price = min(bid_prices)
b_l = lowest_bid_price > mark_price + (mark_price / 100)
b_h = highest_bid_price > mark_price + ((mark_price / 100) * 2)
asks = depth_data['asks']
ask_prices = [float(ask[0]) for ask in asks]
highest_ask_price = max(ask_prices)
lowest_ask_price = min(ask_prices)
s_l = lowest_ask_price < mark_price - ((mark_price / 100) * 2)
s_h = highest_ask_price < mark_price - (mark_price / 100)
y_qty = round(sum(float(bid[1]) for bid in bids), 0)
l_qty = round(sum(float(ask[1]) for ask in asks), 0)
#Quantity
for bid in bids:
price_buy = float(bid[0])
qty_buy = float(bid[1])
if not price_buy < mark_price + (mark_price / 100):
buy_qty = y_qty - qty_buy
for ask in asks:
price_sell = float(ask[0])
qty_sell = float(ask[1])
if not price_sell > mark_price - (mark_price / 100):
sell_qty = l_qty - qty_sell
# Calculate the threshold for order price deviation
if mark_price_percent > 2:
pth = 7 / 100
elif mark_price_percent < -2:
pth = 7 / 100
else:
pth = 7 / 100
# Subtract quantity if bid price is the same as mark price
for bid in bids:
price_buy = float(bid[0])
qty_buy = float(bid[1])
if price_buy == mark_price:
buy_result = buy_qty - qty_buy
br = buy_result
# Subtract quantity if bid price is the same as mark price
for ask in asks:
price_sell = float(ask[0])
qty_sell = float(ask[1])
if price_sell == mark_price:
sell_result = sell_qty - qty_sell
sr = sell_result
if mark_price_percent > 2:
th = 20000
elif mark_price_percent < -2:
th = 20000
else:
th = 15000
#Main Signal
if (((buy_qty > th) > (sell_qty < th)) and (b_l > mp + pth)):
signal.append('buy')
elif (((sell_qty > th) > (buy_qty < th)) and (s_h < mp - pth)):
signal.append('sell')
else:
signal.append('')
#Signal confirmation
if signal == ['buy'] and not (((br < th) < sell_qty) and (b_l < mp + pth)):
final_signal.append('buy')
elif signal == ['sell'] and not (((sr < th) < buy_qty) and (s_h > mp - pth)):
final_signal.append('sell')
else:
final_signal.append('')
#Exit
if final_signal == ['buy'] and (((br < th) < sell_qty) and (b_h < mp + pth)):
exit.append('buy_exit')
elif final_signal == ['sell'] and (((sr < th) < buy_qty) and (s_l > mp - pth)):
exit.append('sell_exit')
else:
exit.append('')
samerkh = exit and final_signal
return samerkh
But terminal returned me: Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 230, in <module>
signals = signal_generator(df)
^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 138, in signal_generator
buy_result = buy_qty - qty_buy
^^^^^^^
UnboundLocalError: cannot access local variable 'buy_qty' where it is not associated with a value
|
b1ae12271f332fbe9c6815dfbd3387a9
|
{
"intermediate": 0.2767973840236664,
"beginner": 0.46565476059913635,
"expert": 0.2575478255748749
}
|
32,267
|
import cv2
import os
import pickle
import face_recognition
# Загрузка известных лиц
known_faces = pickle.load(open("known_faces.pkl", "rb"))
while True:
# Загрузка изображения
video_capture = cv2.VideoCapture(0)
ret, frame = video_capture.read()
# Поиск лиц на изображении
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
# Инициализация списка для хранения имен лиц на изображении
face_names = []
# Проход по лицам на изображении
for face_encoding in face_encodings:
# Сравнение лица с известными лицами
matches = face_recognition.compare_faces(known_faces["encodings"], face_encoding)
name = " "
# Поиск совпадений
if True in matches:
matched_indexes = [i for (i, b) in enumerate(matches) if b]
counts = {}
# Подсчет совпадений
for i in matched_indexes:
name = known_faces["names"][i]
counts[name] = counts.get(name, 0) + 1
# Получение имени с наибольшим количеством совпадений
name = max(counts, key=counts.get)
face_names.append(name)
# Вывод информации о найденных лицах
for (top, right, bottom, left), name in zip(face_locations, face_names):
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
# Отображение изображения с ограничительными рамками и именами лиц
cv2.imshow("Video", frame)
# Завершение работы при нажатии клавиши ‘q’
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Освобождение ресурсов
video_capture.release()
cv2.destroyAllWindows()
у меня есть программа кооторая распознает лица на вебкамере, но надо сделать так, чтобы в вебкамере было больше fps в это время, придумай как оптимизировать код
|
815360a405692d274cda09379be672b7
|
{
"intermediate": 0.2817300856113434,
"beginner": 0.5050528049468994,
"expert": 0.21321706473827362
}
|
32,268
|
I have this code:
def signal_generator(df):
if df is None or len(df) < 2:
return ''
signal = []
final_signal = []
exit = []
sell_result = 0.0
buy_result = 0.0
mark_price_data = client.ticker_price(symbol=symbol)
mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol)
mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0
# Retrieve depth data
depth_data = client.depth(symbol=symbol)
bids = depth_data['bids']
bid_prices = [float(bid[0]) for bid in bids]
highest_bid_price = max(bid_prices)
lowest_bid_price = min(bid_prices)
b_l = lowest_bid_price > mark_price + (mark_price / 100)
b_h = highest_bid_price > mark_price + ((mark_price / 100) * 2)
asks = depth_data['asks']
ask_prices = [float(ask[0]) for ask in asks]
highest_ask_price = max(ask_prices)
lowest_ask_price = min(ask_prices)
s_l = lowest_ask_price < mark_price - ((mark_price / 100) * 2)
s_h = highest_ask_price < mark_price - (mark_price / 100)
y_qty = round(sum(float(bid[1]) for bid in bids), 0)
l_qty = round(sum(float(ask[1]) for ask in asks), 0)
#Quantity
for bid in bids:
price_buy = float(bid[0])
qty_buy_israel = float(bid[1])
if price_buy > mark_price:
buy_qty = qty_buy_israel
buy_qty = qty_buy_israel
for ask in asks:
price_sell = float(ask[0])
qty_sell_israel = float(ask[1])
if price_sell > mark_price:
sell_qty = qty_sell_israel
sell_qty = qty_sell_israel
# Calculate the threshold for order price deviation
if mark_price_percent > 2:
pth = 7 / 100
elif mark_price_percent < -2:
pth = 7 / 100
else:
pth = 7 / 100
# Subtract quantity if bid price is the same as mark price
for bid in bids:
price_buy = float(bid[0])
qty_buy = float(bid[1])
if price_buy == mark_price:
buy_result = buy_qty - qty_buy
br = buy_result
# Subtract quantity if bid price is the same as mark price
for ask in asks:
price_sell = float(ask[0])
qty_sell = float(ask[1])
if price_sell == mark_price:
sell_result = sell_qty - qty_sell
sr = sell_result
if mark_price_percent > 2:
th = 20000
elif mark_price_percent < -2:
th = 20000
else:
th = 15000
print(buy_qty)
print(sell_qty)
print(b_l)
print(s_h)
print(mark_price + pth)
buy_qty and sell_qty are printing me only one order ,but I need qty of every order
|
85af0ca398e07e7a8e552a01c7ee1885
|
{
"intermediate": 0.3305797874927521,
"beginner": 0.4640094041824341,
"expert": 0.205410897731781
}
|
32,269
|
Question 1
Given in request ids as an array of strings, requests, and an integer k, after all requests are received, find the & most recent requests. Report the answer in order of most recent to least recent,
Example:
Suppose n5, requests [item1", "item2", "item3", "item1", "item 31 and k=3
Starting from the right and moving left, collecting distinct requests, there is "Item3" followed by "item1" Skip the second instance of "item3" and find "item2". The answer is ["item3", "item1", "item2]
Function Description Complete the function getLatestRequests in the editor below.
getLatest Requests takes the following arguments:
str requests/n): the request ids
int &: the number of requests to report
Returns:
strik: the k most recent requests
Constraints:
- 1<k<n<10^5
-requests consists of lowercase characters and digits only (a-z,0-9)
Input Format For Custom Testing:
The first line contains an integer, n the number of elements in requests.
Each of the next n lines contains a string, requests[i].
The next line contains an integer, k
|
fa38d68b2719a81133342a603f23ce29
|
{
"intermediate": 0.3785433769226074,
"beginner": 0.3142085075378418,
"expert": 0.3072480857372284
}
|
32,270
|
Question 1
Given in request ids as an array of strings, requests, and an integer k, after all requests are received, find the & most recent requests. Report the answer in order of most recent to least recent,
Example:
Suppose n5, requests [item1", "item2", "item3", "item1", "item 31 and k=3
Starting from the right and moving left, collecting distinct requests, there is "Item3" followed by "item1" Skip the second instance of "item3" and find "item2". The answer is ["item3", "item1", "item2]
Function Description Complete the function getLatestRequests in the editor below.
getLatest Requests takes the following arguments:
str requests/n): the request ids
int &: the number of requests to report
Returns:
strik: the k most recent requests
Constraints:
- 1<k<n<10^5
-requests consists of lowercase characters and digits only (a-z,0-9)
Input Format For Custom Testing:
The first line contains an integer, n the number of elements in requests.
Each of the next n lines contains a string, requests[i].
The next line contains an integer, k
|
af96f3c8c8b2ff407303a58d99cff1d8
|
{
"intermediate": 0.3785433769226074,
"beginner": 0.3142085075378418,
"expert": 0.3072480857372284
}
|
32,271
|
// Decompiled by AS3 Sorcerer 6.78
// www.buraks.com/as3sorcerer
//forms.MainPanel
package forms
{
import flash.display.Sprite;
import flash.display.Bitmap;
import controls.rangicons.RangIconNormal;
import controls.PlayerInfo;
import controls.ButtonXP;
import flash.events.MouseEvent;
import flash.events.Event;
import alternativa.osgi.service.locale.ILocaleService;
import alternativa.init.Main;
import alternativa.tanks.locale.constants.TextConst;
import flash.utils.Timer;
import flash.events.TimerEvent;
import forms.events.MainButtonBarEvents;
public class MainPanel extends Sprite
{
private static const i:Class = MainPanel_i;
private var crystallsStart:Bitmap = new Bitmap(new i().bitmapData);
public var rangIcon:RangIconNormal = new RangIconNormal();
public var playerInfo:PlayerInfo = new PlayerInfo();
public var buttonBar:ButtonBar;
private var _rang:int;
private var _isTester:Boolean = false;
public var buttonXP:ButtonXP;
public function MainPanel(doubleCrystalls:Boolean=false)
{
this._isTester = this.isTester;
this.buttonBar = new ButtonBar(doubleCrystalls);
this.buttonXP = new ButtonXP();
this.buttonXP.addEventListener(MouseEvent.CLICK, this.buttonBar.listClick);
addEventListener(Event.ADDED_TO_STAGE, this.configUI);
}
public function set rang(value:int):void
{
this._rang = value;
this.playerInfo.rang = value;
this.rangIcon.rang = this._rang;
}
public function get rang():int
{
return (this._rang);
}
private function configUI(e:Event):void
{
this.y = 3;
addChild(this.rangIcon);
addChild(this.playerInfo);
addChild(this.buttonBar);
addChild(this.crystallsStart);
addChild(this.buttonXP);
var localeService:ILocaleService = (Main.osgi.getService(ILocaleService) as ILocaleService);
this.buttonXP.label = localeService.getText(TextConst.MAIN_PANEL_BUTTON_XP);
this.rangIcon.y = -2;
this.rangIcon.x = 2;
removeEventListener(Event.ADDED_TO_STAGE, this.configUI);
this.playerInfo.indicators.changeButton.addEventListener(MouseEvent.CLICK, this.listClick);
this.buttonBar.addButton = this.playerInfo.indicators.changeButton;
stage.addEventListener(Event.RESIZE, this.onResize);
this.onResize(null);
var timer:Timer = new Timer(100, 1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, function (e:TimerEvent):void
{
onResize(null);
});
timer.start();
}
private function listClick(e:MouseEvent):void
{
this.buttonBar.dispatchEvent(new MainButtonBarEvents(1));
}
public function onResize(e:Event):void
{
var minWidth:int = int(Math.max(1000, stage.stageWidth));
this.playerInfo.width = (((minWidth - this.buttonBar.width) - this.buttonXP.width) + 5);
this.buttonXP.x = ((((minWidth - this.buttonBar.width) - this.buttonXP.width) + 5) - 105);
this.playerInfo.indicators.getCrystallSprite().x = (((this.buttonXP.x + this.buttonXP.width) - this.playerInfo.indicators.getCrystallbRight().width) + 6);
this.playerInfo.indicators.getCrystallbRight().x = (this.playerInfo.indicators.getCrystallSprite().x + this.playerInfo.indicators.getCrystallSprite().width);
this.crystallsStart.x = (this.playerInfo.indicators.getCrystallSprite().x + 53);
this.playerInfo.indicators.getCrystallInfo().x = (this.playerInfo.indicators.getCrystallSprite().x - 2);
this.buttonBar.x = ((this.playerInfo.indicators.getCrystallbRight().x + this.playerInfo.indicators.getCrystallbRight().width) + 21);
}
public function hide():void
{
stage.removeEventListener(Event.RESIZE, this.onResize);
}
public function get isTester():Boolean
{
return (this._isTester);
}
public function set isTester(value:Boolean):void
{
this._isTester = value;
this.buttonBar.isTester = this._isTester;
this.buttonBar.draw();
this.onResize(null);
}
public function set doubleCrystalls(value:Boolean):void
{
this.buttonBar.doubleCrystalls = value;
}
}
}//package forms
как убрать кнопку buttonXP и выровнять нормально
|
a526c0217fec3f618a979456e9130976
|
{
"intermediate": 0.31667429208755493,
"beginner": 0.4828342795372009,
"expert": 0.20049139857292175
}
|
32,272
|
Как мне сделать проверку на орфографию при вводе интересов с помощью PySpellChecker? Нужно, чтоб если бот видел орфографическую ошибку, он предлагал ее заменить правильным написанием слова, а вместе с сообщением об этом 2 инлайн кнопки: «Да, изменить» и «Нет, оставить как есть»
import logging
import asyncio
import aiosqlite
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import ReplyKeyboardRemove
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.contrib.fsm_storage.memory import MemoryStorage
API_TOKEN = '6835315645:AAGPyEZKih_bTD7uj4N86_pWxKF73z8F0oc'
ADMIN_ID = 989037374
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
class Form(StatesGroup):
name = State()
faculty = State()
group = State()
about_me = State()
interests = State()
newname = State()
newfaculty = State()
newgroup = State()
newabout_me = State()
newinterests = State()
photo = State()
edit_name = State()
edit_faculty = State()
edit_group = State()
edit_photo = State()
dp.middleware.setup(LoggingMiddleware())
async def init_db():
db = await aiosqlite.connect('users.db')
await db.execute('''CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
username TEXT,
name TEXT,
faculty TEXT,
group_number TEXT,
about_me TEXT,
interests TEXT,
photo_id TEXT)''')
await db.commit()
await db.close()
async def fetch_all_user_ids():
async with aiosqlite.connect('users.db') as db:
cursor = await db.execute("SELECT user_id FROM users")
user_ids = await cursor.fetchall()
return [user_id[0] for user_id in user_ids]
@dp.message_handler(commands=['post'], user_id = ADMIN_ID)
async def handle_broadcast_command(message: types.Message):
broadcast_message = message.get_args()
if not broadcast_message:
await message.reply("Пожалуйста, введите сообщение для рассылки после команды.Например: /post Ваше сообщение здесь.")
return
user_ids = await fetch_all_user_ids()
for user_id in user_ids:
try:
await bot.send_message(user_id, broadcast_message)
except Exception as e:
# You can choose to log the error or silently ignore blocked or invalid user_ids
print(f"Could not send message to {user_id}: {e}")
# Функция для удаления данных пользователя
async def delete_user_data(user_id):
async with aiosqlite.connect('users.db') as db:
await db.execute("DELETE FROM users WHERE user_id =?", (user_id,))
await db.commit()
@dp.message_handler(commands=['delete_me'])
async def confirm_delete_user_data(message: types.Message):
keyboard = InlineKeyboardMarkup().add(InlineKeyboardButton("Удалить мои данные", callback_data ="confirm_delete"))
await message.answer("Вы уверены, что хотите удалить все свои данные?", reply_markup = keyboard)
@dp.callback_query_handler(lambda c: c.data =='confirm_delete')
async def process_callback_button_delete(callback_query: types.CallbackQuery):
user_id = callback_query.from_user.id
await bot.answer_callback_query(callback_query.id)
await delete_user_data(user_id)
await bot.send_message(user_id, "Ваши данные были удалены.")
# Обработчик команды /start
@dp.message_handler(commands='start', state='*')
async def cmd_start(message: types.Message, state: FSMContext):
await init_db()
db = await aiosqlite.connect('users.db')
res = await db.execute(f'''SELECT * FROM users WHERE user_id = {message.from_user.id}''')
res = await res.fetchall()
print(res)
if res == []:
await Form.name.set()
await message.reply("👋 Привет! Я - бот для поиска единомышленников. Давай заполним твою анкету. Для начала, как тебя зовут?")
else:
kb = [
[types.KeyboardButton(text="👨💻 Мой профиль")],
[types.KeyboardButton(text="👁 Смотреть анкеты")]
]
keyboard = types.ReplyKeyboardMarkup(keyboard=kb, resize_keyboard=True)
await message.reply("Добро пожаловать! Воспользуйтесь кнопками ниже, чтобы посмотреть свой профиль или анкеты других пользователей", reply_markup=keyboard)
@dp.message_handler(state=Form.name)
async def process_name(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['name'] = message.text
await Form.next()
await message.reply("Какой у тебя факультет?")
@dp.message_handler(state=Form.faculty)
async def process_faculty(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['faculty'] = message.text
await Form.next()
await message.reply("В какой группе ты учишься?")
@dp.message_handler(state=Form.group)
async def process_faculty(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['group'] = message.text
await Form.next()
await message.reply("Расскажи о себе. Пользователи будут видеть информацию в твоей анкете.")
@dp.message_handler(state=Form.about_me)
async def process_faculty(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['about_me'] = message.text
await Form.next()
await message.reply("Перечисли свои интересы, они должны идти через запятую. (Например: программирование, C++, backend)")
@dp.message_handler(state=Form.interests)
async def process_group(message: types.Message, state: FSMContext):
interests_lower = message.text.lower()
async with state.proxy() as data:
data['interests'] = interests_lower
await Form.photo.set()
await message.reply("Загрузи своё фото", reply = False)
@dp.message_handler(content_types=['photo'], state=Form.photo)
async def process_photo(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['photo'] = message.photo[0].file_id
db = await aiosqlite.connect('users.db')
await db.execute('INSERT INTO users (user_id, username, name, faculty, group_number, about_me, interests, photo_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
(message.from_user.id, message.from_user.username, data['name'], data['faculty'], data['group'],data['about_me'],data['interests'],data['photo']))
await db.commit()
await db.close()
await state.finish()
kb = [
[types.KeyboardButton(text="👨💻 Мой профиль")],
[types.KeyboardButton(text="👁 Смотреть анкеты")]
]
keyboard = types.ReplyKeyboardMarkup(keyboard=kb, resize_keyboard=True)
await message.answer("Спасибо за регистрацию! Воспользуйтесь кнопками ниже, чтобы посмотреть свой профиль или анкеты других пользователей", reply_markup=keyboard)
# Получение данных пользователя из БД
async def get_user_data(user_id):
db = await aiosqlite.connect('users.db')
cursor = await db.execute('SELECT name, faculty, group_number, photo_id FROM users WHERE user_id = ?', (user_id,))
row = await cursor.fetchone()
await cursor.close()
await db.close()
return row
# Обработчик команды /profile
@dp.message_handler(text='👨💻 Мой профиль')
async def cmd_profile(message: types.Message):
user_id = message.from_user.id
user_data = await get_user_data(user_id)
if user_data:
name, faculty, group, about_me, photo_id = user_data
await bot.send_photo(chat_id=message.chat.id, photo=photo_id, caption=f"👨💻 Ваш профиль\n\nИмя: {name}\nФакультет: {faculty}\nГруппа: {group}\nО себе: {about_me}\n\n🛠 Для редактирования профиля воспользуйтесь командами:\n\n/edit_name - изменить имя\n/edit_faculty - изменить факультет\n/edit_group - изменить группу\n/edit_about - изменить информацию о себе\n/edit_interests - изменить интересы\n\n🗑 Если вы хотите удалить свою анкету - используйте команду /delete_me")
else:
await message.reply("Вы еще не зарегистрировались.")
async def get_user_data(user_id):
db = await aiosqlite.connect('users.db')
cursor = await db.execute('SELECT name, faculty, group_number, about_me, photo_id FROM users WHERE user_id = ?', (user_id,))
row = await cursor.fetchone()
await cursor.close()
await db.close()
return row
async def get_users_for_search(current_user_id):
db = await aiosqlite.connect('users.db')
current_user_interests_query = 'SELECT interests FROM users WHERE user_id = ?'
cursor = await db.execute(current_user_interests_query, (current_user_id,))
current_user_interests_row = await cursor.fetchone()
if current_user_interests_row:
current_user_interests = current_user_interests_row[0]
else:
current_user_interests = ''
if not current_user_interests:
matching_users_query = 'SELECT user_id, username, name, faculty, group_number, about_me, interests, photo_id FROM users WHERE 1 = 0'
else:
interests_parts = ["interests LIKE '%{}%'".format(interest.strip()) for interest in current_user_interests.split(',')]
interests_query_part = " OR ".join(interests_parts)
matching_users_query = f"SELECT user_id, username, name, faculty, group_number, about_me, interests, photo_id FROM users WHERE user_id != ? AND ({interests_query_part})"
cursor = await db.execute(matching_users_query, (current_user_id,))
rows = await cursor.fetchall()
await cursor.close()
await db.close()
return rows
@dp.message_handler(text='👁 Смотреть анкеты')
async def cmd_search(message: types.Message):
user_id = message.from_user.id
users = await get_users_for_search(user_id)
if users:
for user in users:
user_id, username, name, faculty, group, about_me, interests, photo_id = user
await bot.send_photo(chat_id=message.chat.id, photo=photo_id, caption=f"Имя: {name}\nФакультет: {faculty}\nГруппа: {group}\nО себе: {about_me}\nИнтересы:{interests}\n\nЕго аккаунт Telegram: @{username}")
else:
await message.reply("Пользователи не найдены. Скорее всего, нет пользователей с интересами, как у вас 😔")
async def update_user_data(user_id, column, data):
async with aiosqlite.connect('users.db') as db:
query = f"UPDATE users SET {column} = ? WHERE user_id = ?"
await db.execute(query, (data, user_id))
await db.commit()
@dp.message_handler(commands=['edit_name'], state='*')
async def prompt_name(message: types.Message):
await Form.newname.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваше новое имя:")
@dp.message_handler(state=Form.newname)
async def update_name(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_name = message.text
await update_user_data(user_id, "name", new_name)
await bot.send_message(message.from_user.id, "Ваше имя обновлено!")
await state.finish()
@dp.message_handler(commands=['edit_faculty'], state='*')
async def prompt_faculty(message: types.Message):
await Form.newfaculty.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваш новый факультет:")
@dp.message_handler(state=Form.newfaculty)
async def update_faculty(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_faculty = message.text
await update_user_data(user_id, "faculty", new_faculty)
await bot.send_message(message.from_user.id, "Ваш факультет обновлен!")
await state.finish()
@dp.message_handler(commands=['edit_group'], state='*')
async def prompt_group(message: types.Message):
await Form.newgroup.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите вашу новую группу:")
@dp.message_handler(state=Form.newgroup)
async def update_group(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_group = message.text
await update_user_data(user_id, "group_number", new_group)
await bot.send_message(message.from_user.id, "Ваша группа обновлена!")
await state.finish()
@dp.message_handler(commands=['edit_about'], state='*')
async def prompt_about(message: types.Message):
await Form.newabout_me.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваше новое описание:")
@dp.message_handler(state=Form.newabout_me)
async def update_about(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_about_me = message.text
await update_user_data(user_id, "about_me", new_about_me)
await bot.send_message(message.from_user.id, "Ваше описание обновлено!")
await state.finish()
@dp.message_handler(commands=['edit_interests'], state='*')
async def prompt_interests(message: types.Message):
await Form.newinterests.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваши интересы через запятую:")
@dp.message_handler(state=Form.newinterests)
async def update_interests(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_interests_lower = message.text.lower()
await update_user_data(user_id, "interests", new_interests_lower)
await bot.send_message(message.from_user.id, "Ваши интересы обновлены!")
await state.finish()
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
|
df01b80243ed824377ff3464d56edd61
|
{
"intermediate": 0.3205738663673401,
"beginner": 0.5738300085067749,
"expert": 0.10559611767530441
}
|
32,273
|
Нужно сделать так, чтобы бот отвечал на любое сообщение, не связанное с его функционалом. Нужно, чтобы он писал «Я не понимаю тебя. Пожалуйста, воспользуйся кнопками или нажми /start
import logging
import asyncio
import aiosqlite
from aiogram import Bot, Dispatcher, executor, types
from aiogram.contrib.middlewares.logging import LoggingMiddleware
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import ReplyKeyboardRemove
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from aiogram.contrib.fsm_storage.memory import MemoryStorage
API_TOKEN = '6835315645:AAGPyEZKih_bTD7uj4N86_pWxKF73z8F0oc'
ADMIN_ID = 989037374
logging.basicConfig(level=logging.INFO)
bot = Bot(token=API_TOKEN)
storage = MemoryStorage()
dp = Dispatcher(bot, storage=storage)
class Form(StatesGroup):
name = State()
faculty = State()
group = State()
about_me = State()
interests = State()
newname = State()
newfaculty = State()
newgroup = State()
newabout_me = State()
newinterests = State()
photo = State()
edit_name = State()
edit_faculty = State()
edit_group = State()
edit_photo = State()
dp.middleware.setup(LoggingMiddleware())
async def init_db():
db = await aiosqlite.connect('users.db')
await db.execute('''CREATE TABLE IF NOT EXISTS users (
user_id INTEGER PRIMARY KEY,
username TEXT,
name TEXT,
faculty TEXT,
group_number TEXT,
about_me TEXT,
interests TEXT,
photo_id TEXT)''')
await db.commit()
await db.close()
async def fetch_all_user_ids():
async with aiosqlite.connect('users.db') as db:
cursor = await db.execute("SELECT user_id FROM users")
user_ids = await cursor.fetchall()
return [user_id[0] for user_id in user_ids]
@dp.message_handler(commands=['post'], user_id = ADMIN_ID)
async def handle_broadcast_command(message: types.Message):
broadcast_message = message.get_args()
if not broadcast_message:
await message.reply("Пожалуйста, введите сообщение для рассылки после команды.Например: /post Ваше сообщение здесь.")
return
user_ids = await fetch_all_user_ids()
for user_id in user_ids:
try:
await bot.send_message(user_id, broadcast_message)
except Exception as e:
# You can choose to log the error or silently ignore blocked or invalid user_ids
print(f"Could not send message to {user_id}: {e}")
# Функция для удаления данных пользователя
async def delete_user_data(user_id):
async with aiosqlite.connect('users.db') as db:
await db.execute("DELETE FROM users WHERE user_id =?", (user_id,))
await db.commit()
@dp.message_handler(commands=['delete_me'])
async def confirm_delete_user_data(message: types.Message):
keyboard = InlineKeyboardMarkup().add(InlineKeyboardButton("Удалить мои данные", callback_data ="confirm_delete"))
await message.answer("Вы уверены, что хотите удалить все свои данные?", reply_markup = keyboard)
@dp.callback_query_handler(lambda c: c.data =='confirm_delete')
async def process_callback_button_delete(callback_query: types.CallbackQuery):
user_id = callback_query.from_user.id
await bot.answer_callback_query(callback_query.id)
await delete_user_data(user_id)
await bot.send_message(user_id, "Ваши данные были удалены.")
# Обработчик команды /start
@dp.message_handler(commands='start', state='*')
async def cmd_start(message: types.Message, state: FSMContext):
await init_db()
db = await aiosqlite.connect('users.db')
res = await db.execute(f'''SELECT * FROM users WHERE user_id = {message.from_user.id}''')
res = await res.fetchall()
print(res)
if res == []:
await Form.name.set()
await message.reply("👋 Привет! Я - бот для поиска единомышленников. Давай заполним твою анкету. Для начала, как тебя зовут?")
else:
kb = [
[types.KeyboardButton(text="👨💻 Мой профиль")],
[types.KeyboardButton(text="👁 Смотреть анкеты")]
]
keyboard = types.ReplyKeyboardMarkup(keyboard=kb, resize_keyboard=True)
await message.reply("Добро пожаловать! Воспользуйтесь кнопками ниже, чтобы посмотреть свой профиль или анкеты других пользователей", reply_markup=keyboard)
@dp.message_handler(state=Form.name)
async def process_name(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['name'] = message.text
await Form.next()
await message.reply("Какой у тебя факультет?")
@dp.message_handler(state=Form.faculty)
async def process_faculty(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['faculty'] = message.text
await Form.next()
await message.reply("В какой группе ты учишься?")
@dp.message_handler(state=Form.group)
async def process_faculty(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['group'] = message.text
await Form.next()
await message.reply("Расскажи о себе. Пользователи будут видеть информацию в твоей анкете.")
@dp.message_handler(state=Form.about_me)
async def process_faculty(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['about_me'] = message.text
await Form.next()
await message.reply("Перечисли свои интересы, они должны идти через запятую. (Например: программирование, C++, backend)")
@dp.message_handler(state=Form.interests)
async def process_group(message: types.Message, state: FSMContext):
interests_lower = message.text.lower()
async with state.proxy() as data:
data['interests'] = interests_lower
await Form.photo.set()
await message.reply("Загрузи своё фото", reply = False)
@dp.message_handler(content_types=['photo'], state=Form.photo)
async def process_photo(message: types.Message, state: FSMContext):
async with state.proxy() as data:
data['photo'] = message.photo[0].file_id
db = await aiosqlite.connect('users.db')
await db.execute('INSERT INTO users (user_id, username, name, faculty, group_number, about_me, interests, photo_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
(message.from_user.id, message.from_user.username, data['name'], data['faculty'], data['group'],data['about_me'],data['interests'],data['photo']))
await db.commit()
await db.close()
await state.finish()
kb = [
[types.KeyboardButton(text="👨💻 Мой профиль")],
[types.KeyboardButton(text="👁 Смотреть анкеты")]
]
keyboard = types.ReplyKeyboardMarkup(keyboard=kb, resize_keyboard=True)
await message.answer("Спасибо за регистрацию! Воспользуйтесь кнопками ниже, чтобы посмотреть свой профиль или анкеты других пользователей", reply_markup=keyboard)
# Получение данных пользователя из БД
async def get_user_data(user_id):
db = await aiosqlite.connect('users.db')
cursor = await db.execute('SELECT name, faculty, group_number, photo_id FROM users WHERE user_id = ?', (user_id,))
row = await cursor.fetchone()
await cursor.close()
await db.close()
return row
# Обработчик команды /profile
@dp.message_handler(text='👨💻 Мой профиль')
async def cmd_profile(message: types.Message):
user_id = message.from_user.id
user_data = await get_user_data(user_id)
if user_data:
name, faculty, group, about_me, photo_id = user_data
await bot.send_photo(chat_id=message.chat.id, photo=photo_id, caption=f"👨💻 Ваш профиль\n\nИмя: {name}\nФакультет: {faculty}\nГруппа: {group}\nО себе: {about_me}\n\n🛠 Для редактирования профиля воспользуйтесь командами:\n\n/edit_name - изменить имя\n/edit_faculty - изменить факультет\n/edit_group - изменить группу\n/edit_about - изменить информацию о себе\n/edit_interests - изменить интересы\n\n🗑 Если вы хотите удалить свою анкету - используйте команду /delete_me")
else:
await message.reply("Вы еще не зарегистрировались.")
async def get_user_data(user_id):
db = await aiosqlite.connect('users.db')
cursor = await db.execute('SELECT name, faculty, group_number, about_me, photo_id FROM users WHERE user_id = ?', (user_id,))
row = await cursor.fetchone()
await cursor.close()
await db.close()
return row
async def get_users_for_search(current_user_id):
db = await aiosqlite.connect('users.db')
current_user_interests_query = 'SELECT interests FROM users WHERE user_id = ?'
cursor = await db.execute(current_user_interests_query, (current_user_id,))
current_user_interests_row = await cursor.fetchone()
if current_user_interests_row:
current_user_interests = current_user_interests_row[0]
else:
current_user_interests = ''
if not current_user_interests:
matching_users_query = 'SELECT user_id, username, name, faculty, group_number, about_me, interests, photo_id FROM users WHERE 1 = 0'
else:
interests_parts = ["interests LIKE '%{}%'".format(interest.strip()) for interest in current_user_interests.split(',')]
interests_query_part = " OR ".join(interests_parts)
matching_users_query = f"SELECT user_id, username, name, faculty, group_number, about_me, interests, photo_id FROM users WHERE user_id != ? AND ({interests_query_part})"
cursor = await db.execute(matching_users_query, (current_user_id,))
rows = await cursor.fetchall()
await cursor.close()
await db.close()
return rows
@dp.message_handler(text='👁 Смотреть анкеты')
async def cmd_search(message: types.Message):
user_id = message.from_user.id
users = await get_users_for_search(user_id)
if users:
for user in users:
user_id, username, name, faculty, group, about_me, interests, photo_id = user
await bot.send_photo(chat_id=message.chat.id, photo=photo_id, caption=f"Имя: {name}\nФакультет: {faculty}\nГруппа: {group}\nО себе: {about_me}\nИнтересы:{interests}\n\nЕго аккаунт Telegram: @{username}")
else:
await message.reply("Пользователи не найдены. Скорее всего, нет пользователей с интересами, как у вас 😔")
async def update_user_data(user_id, column, data):
async with aiosqlite.connect('users.db') as db:
query = f"UPDATE users SET {column} = ? WHERE user_id = ?"
await db.execute(query, (data, user_id))
await db.commit()
@dp.message_handler(commands=['edit_name'], state='*')
async def prompt_name(message: types.Message):
await Form.newname.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваше новое имя:")
@dp.message_handler(state=Form.newname)
async def update_name(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_name = message.text
await update_user_data(user_id, "name", new_name)
await bot.send_message(message.from_user.id, "Ваше имя обновлено!")
await state.finish()
@dp.message_handler(commands=['edit_faculty'], state='*')
async def prompt_faculty(message: types.Message):
await Form.newfaculty.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваш новый факультет:")
@dp.message_handler(state=Form.newfaculty)
async def update_faculty(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_faculty = message.text
await update_user_data(user_id, "faculty", new_faculty)
await bot.send_message(message.from_user.id, "Ваш факультет обновлен!")
await state.finish()
@dp.message_handler(commands=['edit_group'], state='*')
async def prompt_group(message: types.Message):
await Form.newgroup.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите вашу новую группу:")
@dp.message_handler(state=Form.newgroup)
async def update_group(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_group = message.text
await update_user_data(user_id, "group_number", new_group)
await bot.send_message(message.from_user.id, "Ваша группа обновлена!")
await state.finish()
@dp.message_handler(commands=['edit_about'], state='*')
async def prompt_about(message: types.Message):
await Form.newabout_me.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваше новое описание:")
@dp.message_handler(state=Form.newabout_me)
async def update_about(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_about_me = message.text
await update_user_data(user_id, "about_me", new_about_me)
await bot.send_message(message.from_user.id, "Ваше описание обновлено!")
await state.finish()
@dp.message_handler(commands=['edit_interests'], state='*')
async def prompt_interests(message: types.Message):
await Form.newinterests.set()
await bot.send_message(message.from_user.id, "Пожалуйста, введите ваши интересы через запятую:")
@dp.message_handler(state=Form.newinterests)
async def update_interests(message: types.Message, state: FSMContext):
user_id = message.from_user.id
new_interests_lower = message.text.lower()
await update_user_data(user_id, "interests", new_interests_lower)
await bot.send_message(message.from_user.id, "Ваши интересы обновлены!")
await state.finish()
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True)
|
0bfcb63f53cfdd5bf2c5f7a0d085ef2e
|
{
"intermediate": 0.3574736714363098,
"beginner": 0.5369703769683838,
"expert": 0.10555596649646759
}
|
32,274
|
Traceback (most recent call last):
File "C:\Users\Insane\PycharmProjects\ask_dps_spb_bot\main.py", line 48, in <module>
main()
File "C:\Users\Insane\PycharmProjects\ask_dps_spb_bot\main.py", line 37, in main
updater = Updater(TOKEN)
^^^^^^^^^^^^^^
TypeError: Updater.__init__() missing 1 required positional argument: 'update_queue'
Process finished with exit code 1
Как исправить эти ошибки?
|
1c525e30b41d410f1ce7ba011a371fb0
|
{
"intermediate": 0.3520039916038513,
"beginner": 0.2906874716281891,
"expert": 0.357308566570282
}
|
32,275
|
Помоги исправить ошибки компиляции. Код на C++ #include "Intersector.h"
#include "Figure.h"
#include <string>
template <typename T>
static inline bool isCircle(T figure) //static
{
Circle* circle = dynamic_cast(figure1);
if (circle != nullptr) {
return true;
}
else {
return false;
}
}
template <typename T>
static inline bool isTriangle(T figure)
{
Triangle* triangle = dynamic_cast(figure1);
if (triangle != nullptr) {
return true;
}
else {
return false;
}
}
template <typename T>
static inline bool isPolygon(T figure)
{
Polygon* polygon = dynamic_cast(figure1);
if (polygon != nullptr) {
return true;
}
else {
return false;
}
}
template <typename T, typename U>
inline std::string Intersector<T, U>::Intersect(T figure1, U figure2)
{
if (isCircle(figure1) == true && isTriangle(figure2) == true)
{
if (IntersectCircleWithTriangle(figure1, figure2))
return "yes";
else return "no";
}
else if (isCircle(figure1) == true && isCircle(figure2) == true)
{
if (IntersectCircleWithCircle(figure1, figure2))
return "yes";
else return "no";
}
else if (isTriangle(figure1) == true && isCircle(figure2) == true)
{
if (IntersectCircleWithTriangle(figure2, figure1))
return "yes";
else return "no";
}
else if (isTriangle(figure1) == true && isTriangle(figure2) == true)
{
if (IntersectTriangleWithTriangle(figure1, figure2))
return "yes";
else return "no";
}
else if (isPolygon(figure1) == true && isPolygon(figure2) == true)
{
if (IntersectPolygonWithPolygon(figure1, figure2))
{
return "yes";
}
else return "no";
}
else return "no";
}
template <typename T, typename U>
inline bool Intersector<T, U>::IntersectCircleWithTriangle(Circle a, Triangle b)
{
double minX = std::min(std::min(b.getP1().x, b.getP2().x), b.getP3().x);
double maxX = std::max(std::max(b.getP1().x, b.getP2().x), b.getP3().x);
double minY = std::min(std::min(b.getP1().y, b.getP2().y), b.getP3().y);
double maxY = std::max(std::max(b.getP1().y, b.getP2().y), b.getP3().y);
if (a.getCenter().x + a.getRad() < minX || a.getCenter().x - a.getRad() > maxY ||
a.getCenter().y + a.getRad() < minY || a.getCenter().y - a.getRad() > maxY)
{
// Если максимальная проекция круга на оси координат находится полностью вне треугольника,
// то пересечение отсутствует
return false;
}
//Проверяем пересечение круга и ребер треугольника
double distance1 = std::abs((b.getP2().y - b.getP1().y) * a.getCenter().x - (b.getP2().x - b.getP1().x) * a.getCenter().y + b.getP2().x * b.getP1().y - b.getP2().y * b.getP1().x) /
sqrt(pow(b.getP2().y - b.getP1().y, 2) + pow(b.getP2().x - b.getP1().x, 2));
double distance2 = std::abs((b.getP3().y - b.getP2().y) * a.getCenter().x - (b.getP3().x - b.getP2().x) * a.getCenter().y + b.getP3().x * b.getP2().y - b.getP3().y * b.getP2().x) /
sqrt(pow(b.getP3().y - b.getP2().y, 2) + pow(b.getP3().x - b.getP2().x, 2));
double distance3 = std::abs((b.getP1().y - b.getP3().y) * a.getCenter().x - (b.getP1().x - b.getP3().x) * a.getCenter().y + b.getP1().x * b.getP3().y - b.getP1().y * b.getP3().x) /
sqrt(pow(b.getP1().y - b.getP3().y, 2) + pow(b.getP1().x - b.getP3().x, 2));
if (distance1 <= a.getRad() || distance2 <= a.getRad() || distance3 <= a.getRad())
{
// Если расстояние от центра круга до ребра треугольника меньше или равно радиусу круга,
// то пересечение есть
return true;
}
else return false;
}
template <typename T, typename U>
inline bool Intersector<T, U>::IntersectCircleWithCircle(Circle a, Circle b)
{
// Логика проверки пересечения двух кругов
double distance = sqrt(pow(a.getCenter().x - b.getCenter().x, 2) + pow(a.getCenter().y - b.getCenter().y, 2));
//Проверяем пересекаются ли два круга
if (distance <= a.getRad() + b.getRad()) return true;
else return false;
}
template <typename T, typename U>
inline bool Intersector<T, U>::IntersectTriangleWithTriangle(Triangle a, Triangle b)
{
Figure::Point p1 = a.getP1();
Figure::Point p2 = a.getP2();
Figure::Point p3 = a.getP3();
Figure::Point p4 = b.getP1();
Figure::Point p5 = b.getP2();
Figure::Point p6 = b.getP3();
// Проверяем пересечение сторон треугольников
if (CheckEdgeIntersection(a.getP1(), a.getP2(), b.getP1(), b.getP2()) ||
CheckEdgeIntersection(a.getP1(), a.getP2(), b.getP2(), b.getP3()) ||
CheckEdgeIntersection(a.getP1(), a.getP2(), b.getP3(), b.getP1()) ||
CheckEdgeIntersection(a.getP2(), a.getP3(), b.getP1(), b.getP2()) ||
CheckEdgeIntersection(a.getP2(), a.getP3(), b.getP2(), b.getP3()) ||
CheckEdgeIntersection(a.getP2(), a.getP3(), b.getP3(), b.getP1()) ||
CheckEdgeIntersection(a.getP3(), a.getP1(), b.getP1(), b.getP2()) ||
CheckEdgeIntersection(a.getP3(), a.getP1(), b.getP2(), b.getP3()) ||
CheckEdgeIntersection(a.getP3(), a.getP1(), b.getP3(), b.getP1()))
{
return true;
}
else return false;
}
template <typename T, typename U>
inline bool Intersector<T, U>::CheckEdgeIntersection(Figure::Point a, Figure::Point b, Figure::Point c, Figure::Point d)
{
int o1 = CalculateOrientation(a, b, c);
int o2 = CalculateOrientation(a, b, d);
int o3 = CalculateOrientation(c, d, a);
int o4 = CalculateOrientation(c, d, b);
if (o1 != o2 && o3 != o4)
{
return true;
}
return false;
}
template <typename T, typename U>
inline int Intersector<T, U>::CalculateOrientation(Figure::Point p, Figure::Point q, Figure::Point r)
{
int value = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
if (value == 0)
{
return 0; // Коллинеарны
}
else if (value > 0)
{
return 1; // Против часовой стрелки
}
else
{
return -1; // По часовой стрелке
}
}
template <typename T, typename U>
inline bool Intersector<T, U>::IntersectPolygonWithPolygon(Polygon a, Polygon b)
{
vector<Figure::Point> pointsA = new Figures.Point[a.getSize()]; //проверить
pointsA = a.getPoints();
vector<Figure::Point> pointsB = new Figures.Point[b.getSize()];
pointsB = b.getPoints();
int numPointsA = a.getSize();
int numPointsB = b.getSize();
// Проверяем пересечение ребер между многоугольниками
for (int i = 0; i < numPointsA; i++)
{
int nextA = (i + 1) % numPointsA;
for (int j = 0; j < numPointsB; j++)
{
int nextB = (j + 1) % numPointsB;
if (CheckEdgeIntersection(pointsA[i], pointsA[nextA], pointsB[j], pointsB[nextB]))
{
return true;
}
}
}
// Если ребра не пересекаются, проверяем, содержат ли один многоугольник вершины другого
for (int i = 0; i < numPointsA; i++)
{
if (PointInsidePolygon(pointsA[i], pointsB))
{
return true;
}
}
for (int i = 0; i < numPointsB; i++)
{
if (PointInsidePolygon(pointsB[i], pointsA))
{
return true;
}
}
// Если ни одно условие не выполнилось, многоугольники не пересекаются
return false;
}
}
|
1cf56a3a41c56da215fab78522975dcd
|
{
"intermediate": 0.23559676110744476,
"beginner": 0.5613300800323486,
"expert": 0.2030731439590454
}
|
32,276
|
Как исправить ошибку C:\Users\Insane\AppData\Local\Programs\Python\Python312\python.exe C:\Users\Insane\PycharmProjects\ask_dps_spb_bot\main.py
Traceback (most recent call last):
File "C:\Users\Insane\PycharmProjects\ask_dps_spb_bot\main.py", line 2, in <module>
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
ImportError: cannot import name 'Filters' from 'telegram.ext' (C:\Users\Insane\AppData\Local\Programs\Python\Python312\Lib\site-packages\telegram\ext\__init__.py). Did you mean: 'filters'?
|
586fd3b4fe45bd8aea620fe621613b53
|
{
"intermediate": 0.6367368102073669,
"beginner": 0.2130458652973175,
"expert": 0.15021732449531555
}
|
32,277
|
in asp.net core tag helper class, we can see something like "public override void Process(TagHelperContext context, TagHelperOutput output) {}", so what do the parameters in it mean?
|
066ebd94742ea8bfd1b6af235086bdcd
|
{
"intermediate": 0.4559122323989868,
"beginner": 0.4419926702976227,
"expert": 0.10209507495164871
}
|
32,278
|
import cv2
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from PIL import Image, ImageTk
import os
import pickle
import face_recognition
# Загрузка известных лиц
known_faces = pickle.load(open("known_faces.pkl", "rb"))
root = tk.Tk()
root.title("Face Recognition")
# Функция для обработки кнопки "Сделать снимок"
def capture_snapshot():
global video_capture
# Получение текущего кадра видео
ret, frame = video_capture.read()
# Поиск лиц на изображении
face_locations = face_recognition.face_locations(frame)
if len(face_locations) > 0:
# Если на видео есть лицо, сохраняем снимок
# Генерация уникального имени файла на основе времени
now = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"snapshot_{now}.png"
# Сохранение снимка в папку “database”
cv2.imwrite(os.path.join("database", filename), frame)
messagebox.showinfo("Snapshot", "Снимок сохранен")
else:
# Если на видео нет лица, выводим сообщение
messagebox.showinfo("No Face", "На видео нет лица")
# Функция для обработки кнопки "Проверить"
def check_faces():
global video_capture
# Получение текущего кадра видео
ret, frame = video_capture.read()
# Поиск лиц на изображении
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
# Инициализация списка для хранения имен лиц на изображении
face_names = []
# Проход по лицам на изображении
for face_encoding in face_encodings:
# Сравнение лица с известными лицами
matches = face_recognition.compare_faces(known_faces["encodings"], face_encoding)
name = "Unknown"
# Поиск совпадений
if True in matches:
matched_indexes = [i for (i, b) in enumerate(matches) if b]
counts = {}
# Подсчет совпадений
for i in matched_indexes:
name = known_faces["names"][i]
counts[name] = counts.get(name, 0) + 1
# Получение имени с наибольшим количеством совпадений
name = max(counts, key=counts.get)
face_names.append(name)
# Проверка, есть ли человек из базы данных на видео
if any(name != "Unknown" for name in face_names):
messagebox.showinfo("Face Recognition", "На видео есть человек из базы данных")
else:
messagebox.showinfo("Face Recognition", "На видео нет человека из базы данных")
# Инициализация видеокамеры
video_capture = cv2.VideoCapture(0)
# Функция для обновления видео в окне Tkinter
def update_video():
# Получение текущего кадра видео
ret, frame = video_capture.read()
if ret:
# Конвертация цветового пространства BGR в RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Создание изображения Tkinter из массива numpy
img = Image.fromarray(frame_rgb)
imgtk = ImageTk.PhotoImage(image=img)
# Обновление изображения в окне
video_label.imgtk = imgtk
video_label.configure(image=imgtk)
video_label.after(10, update_video)
# Создание окошка для отображения видео
video_label = tk.Label(root)
video_label.pack()
# Создание кнопки "Сделать снимок"
snapshot_button = tk.Button(root, text="Сделать снимок", command=capture_snapshot)
snapshot_button.pack()
# Создание кнопки "Проверить"
check_button = tk.Button(root, text="Проверить", command=check_faces)
check_button.pack()
# Обновление видео в окне
update_video()
# Запуск главного цикла программы
root.mainloop()
# Освобождение ресурсов
video_capture.release()
cv2.destroyAllWindows()
как сделать форму регистрации чтобы была кнопка «новый пользователь» чтобы открывалось дополнительное окно tinker и пользователь мог ввести свое имя и логин и сохранить свое лицо в базу данных, и в базу данных сохранялась картинка с указанным пользователем логином(для логина добавить ограничения соответствующие ограничениям названия файла в windows), а также предложить пользователю ввести пароль, если не получиться распознать лицо пользователя. Пароль и логин и имя сохраняются в файле который хранится также в папке database. (соответсвенно нужно проверять наличия существующего пользователя с таким же логином паролем или лицом)
|
c792fb62770391b17ebc73f1bb6b7161
|
{
"intermediate": 0.35386183857917786,
"beginner": 0.4929375946521759,
"expert": 0.15320058166980743
}
|
32,279
|
c sharp coding for quix application
|
e1e52fd16337a68e42c4ff627a643f28
|
{
"intermediate": 0.3211878538131714,
"beginner": 0.35446950793266296,
"expert": 0.32434260845184326
}
|
32,280
|
from telegram import Update, Bot
from telegram.ext import Updater, CommandHandler, MessageHandler, filters, CallbackContext
import logging
# Введите здесь токен, полученный от BotFather
TOKEN = '6945390760:AAGoty7L52fuz5l--zOuGxqubOw8QD5FAwA'
# Логирование
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
logger = logging.getLogger(name)
# Контрольный вопрос и правильный ответ
CONTROL_QUESTION = "В каком году был основан город Санкт-Петербург?"
CORRECT_ANSWER = "1703"
CHAT_ID = '-1001354338869'
def start(update: Update, _: CallbackContext) -> None:
update.message.reply_text('Привет! Чтобы вступить в закрытый чат, ответьте на контрольный вопрос: ' + CONTROL_QUESTION)
def handle_response(update: Update, context: CallbackContext) -> None:
answer = update.message.text
user_id = update.message.from_user.id
if answer == CORRECT_ANSWER:
bot = context.bot
try:
bot.invite_chat_member(chat_id=CHAT_ID, user_id=user_id)
update.message.reply_text('Ответ верный! Вы были добавлены в закрытый чат.')
except Exception as e:
update.message.reply_text(f'Ошибка при добавлении в чат: {e}')
else:
update.message.reply_text('Неверный ответ. Попробуйте еще раз.')
def main() -> None:
updater = Updater(TOKEN)
dispatcher = updater.dispatcher
dispatcher.add_handler(CommandHandler("start", start))
dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, handle_response))
updater.start_polling()
updater.idle()
if name == 'main':
main()
Возникает ошибка
C:\Users\Insane\AppData\Local\Programs\Python\Python312\python.exe C:\Users\Insane\PycharmProjects\ask_dps_spb_bot\main.py
Traceback (most recent call last):
File "C:\Users\Insane\PycharmProjects\ask_dps_spb_bot\main.py", line 11, in <module>
logger = logging.getLogger(name)
^^^^
NameError: name 'name' is not defined
Process finished with exit code 1
как её исправить?
|
02896858aff4c965ed9460c3f4947c45
|
{
"intermediate": 0.470135360956192,
"beginner": 0.38802236318588257,
"expert": 0.1418423354625702
}
|
32,281
|
write a song abut women empowerment in odia
|
e918d7bb24a12886dcc978390cd56a4c
|
{
"intermediate": 0.42074650526046753,
"beginner": 0.29337039589881897,
"expert": 0.2858831286430359
}
|
32,282
|
import cv2
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from PIL import Image, ImageTk
import os
import pickle
import face_recognition
root = tk.Tk()
root.title("Face Recognition")
def open_registration_form():
registration_window = tk.Toplevel(root)
registration_window.title("Регистрация")
# Функция для обработки нажатия кнопки “Зарегистрироваться”
def register_user():
name = name_entry.get()
username = username_entry.get()
password = password_entry.get()
# Проверка наличия пользователя с таким же логином
if username in known_faces["names"]:
messagebox.showerror("Ошибка", "Пользователь с таким логином уже существует")
return
# Получение текущего кадра видео
ret, frame = video_capture.read()
# Поиск лиц на изображении
face_locations = face_recognition.face_locations(frame)
if len(face_locations) > 0:
# Если на видео есть лицо, сохраняем снимок
# Генерация уникального имени файла на основе времени
now = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"snapshot_{username}_{now}.png"
# Сохранение снимка в папку “database”
cv2.imwrite(os.path.join("database", filename), frame)
messagebox.showinfo("Регистрация", "Пользователь успешно зарегистрирован")
registration_window.destroy()
else:
# Если на видео нет лица, выводим сообщение
messagebox.showinfo("“Ошибка”", "“На видео нет лица”")
# Создание поля для ввода имени пользователя
name_label = tk.Label(registration_window, text="“Имя”")
name_label.pack()
name_entry = tk.Entry(registration_window)
name_entry.pack()
# Создание поля для ввода логина пользователя
username_label = tk.Label(registration_window, text="Логин")
username_label.pack()
username_entry = tk.Entry(registration_window)
username_entry.pack()
# Создание поля для ввода пароля пользователя
password_label = tk.Label(registration_window, text="“Пароль”")
password_label.pack()
password_entry = tk.Entry(registration_window, show="“*”")
password_entry.pack()
# Создание кнопки “Зарегистрироваться”
register_button = tk.Button(registration_window, text="“Зарегистрироваться”", command=register_user)
register_button.pack()
# Функция для обработки кнопки "Сделать снимок"
def capture_snapshot():
global video_capture
# Получение текущего кадра видео
ret, frame = video_capture.read()
# Поиск лиц на изображении
face_locations = face_recognition.face_locations(frame)
if len(face_locations) > 0:
# Если на видео есть лицо, сохраняем снимок
# Генерация уникального имени файла на основе времени
now = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"snapshot_{now}.png"
# Сохранение снимка в папку “database”
cv2.imwrite(os.path.join("database", filename), frame)
messagebox.showinfo("Snapshot", "Снимок сохранен")
else:
# Если на видео нет лица, выводим сообщение
messagebox.showinfo("No Face", "На видео нет лица")
# Функция для обработки кнопки "Проверить"
def check_faces():
global video_capture
# Получение текущего кадра видео
ret, frame = video_capture.read()
# Поиск лиц на изображении
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
# Инициализация списка для хранения имен лиц на изображении
face_names = []
# Проход по лицам на изображении
for face_encoding in face_encodings:
# Сравнение лица с известными лицами
matches = face_recognition.compare_faces(known_faces["encodings"], face_encoding)
name = "Unknown"
# Поиск совпадений
if True in matches:
matched_indexes = [i for (i, b) in enumerate(matches) if b]
counts = {}
# Подсчет совпадений
for i in matched_indexes:
name = known_faces["names"][i]
counts[name] = counts.get(name, 0) + 1
# Получение имени с наибольшим количеством совпадений
name = max(counts, key=counts.get)
face_names.append(name)
# Проверка, есть ли человек из базы данных на видео
if any(name != "Unknown" for name in face_names):
messagebox.showinfo("Face Recognition", "На видео есть человек из базы данных")
else:
messagebox.showinfo("Face Recognition", "На видео нет человека из базы данных")
# Инициализация видеокамеры
video_capture = cv2.VideoCapture(0)
# Функция для обновления видео в окне Tkinter
def update_video():
# Получение текущего кадра видео
ret, frame = video_capture.read()
if ret:
# Конвертация цветового пространства BGR в RGB
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
# Создание изображения Tkinter из массива numpy
img = Image.fromarray(frame_rgb)
imgtk = ImageTk.PhotoImage(image=img)
# Обновление изображения в окне
video_label.imgtk = imgtk
video_label.configure(image=imgtk)
video_label.after(10, update_video)
# Создание окошка для отображения видео
video_label = tk.Label(root)
video_label.pack()
# Создание кнопки "Сделать снимок"
snapshot_button = tk.Button(root, text="Сделать снимок", command=capture_snapshot)
snapshot_button.pack()
# Создание кнопки "Проверить"
check_button = tk.Button(root, text="Проверить", command=check_faces)
check_button.pack()
# Обновление видео в окне
update_video()
# Запуск главного цикла программы
root.mainloop()
# Освобождение ресурсов
video_capture.release()
cv2.destroyAllWindows()
исправь чтобы видео с веб камеры находилось внтри окна и были кнопки которые делали бы снимок видео и добаваляли снимок в папку database
а потом рядом была еще одна кнока которая проверяла есть ли человек из database на видео
сделай в коде так чтобы при нажатии кнопки сохраняющей человека в базу данных, программа перед этим проверяла, если ли на видео лицо, и если есть, то сохраняла снимок
сделай также форму регистрации чтобы была кнопка «новый пользователь» чтобы открывалось дополнительное окно tinker и пользователь мог ввести свое имя и логин и сохранить свое лицо в базу данных, и в базу данных сохранялась картинка с указанным пользователем логином(для логина добавить ограничения соответствующие ограничениям названия файла в windows), а также предложить пользователю ввести пароль, если не получиться распознать лицо пользователя. Пароль и логин и имя сохраняются в файле который хранится также в папке database. (соответсвенно нужно проверять наличия существующего пользователя с таким же логином паролем или лицом)
|
5786c62cb84eea0d8925a837344fe9d8
|
{
"intermediate": 0.3868790864944458,
"beginner": 0.49833473563194275,
"expert": 0.11478617042303085
}
|
32,283
|
quiz game application in c sharp
|
c430024f6b13cc6d8dbfaf402e9e286a
|
{
"intermediate": 0.23126308619976044,
"beginner": 0.4848293662071228,
"expert": 0.28390759229660034
}
|
32,284
|
How to integrate Large Language Models with Knowledge Graphs?
|
a79ca081a8b0f76aad47d61ec56bd107
|
{
"intermediate": 0.2518896162509918,
"beginner": 0.1749449521303177,
"expert": 0.5731654167175293
}
|
32,285
|
Performance is a crucial aspect of any mobile application, especially when preparing for release. A smooth and responsive user experience ensures that your users have a pleasant time interacting with your app.
Same happened with me at work. We are developing our application in react native but to my surprise, it could not handle much stuff going on when compared to the web version.
In this blog post, we'll explore three effective methods to optimize the performance of your React Native application.
1. Utilizing React.memo
One common performance bottleneck in React Native applications is unnecessary re-rendering. Even when no actual changes occur, components might re-render, leading to a sluggish user interface. To address this issue, React provides a useful tool called React.memo.
How to Use React.memo
Wrap your component with React.memo to memoize it, preventing re-renders unless the props change. Here's a quick example:
import React from 'react';
const MyComponent = React.memo(({ data }) => {
// Your component logic here
});
export default MyComponent;
This ensures that the component only re-renders when the props it receives change, significantly improving performance.
2. Leveraging useCallback for Referential Equality
In scenarios where memoization breaks, especially when dealing with functions, the useCallback hook comes to the rescue. When a component relies on referential equality, using useCallback prevents unnecessary re-renders.
How to Use useCallback
import React, { useCallback } from 'react';
const MyComponent = ({ onClick }) => {
const memoizedClick = useCallback(() => {
// Your click handler logic here
}, [/* dependencies */]);
return (
<button onClick={memoizedClick}>Click me</button>
);
};
export default MyComponent;
By specifying dependencies, you ensure that the callback remains referentially equal unless the dependencies change.
3. Optimizing Expensive Functions with useMemo
Another common scenario involves optimizing the performance of expensive functions within components. The useMemo hook helps achieve this by memoizing the result of a function and recalculating it only when the dependencies change.
How to Use useMemo
import React, { useMemo } from 'react';
const MyComponent = ({ data }) => {
const memoizedResult = useMemo(() => {
// Expensive function logic here
return result;
}, [/* dependencies */]);
return (
<div>{memoizedResult}</div>
);
};
export default MyComponent;
By carefully selecting dependencies, you control when the expensive function is recomputed, enhancing overall performance.
Based on these recommendations:
make the changes in the following code to optimize it and avoid unnecessary re-renders
import {AudioSession, useParticipant, useRoom} from '@livekit/react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {createMaterialTopTabNavigator} from '@react-navigation/material-top-tabs';
import axios from 'axios';
import type {LocalParticipant} from 'livekit-client';
import {
DataPacket_Kind,
RemoteParticipant,
Room,
RoomEvent,
TrackPublication,
} from 'livekit-client';
import React, {useEffect, useRef, useState} from 'react';
import {
BackHandler,
Image,
Keyboard,
ScrollView,
TouchableWithoutFeedback,
useWindowDimensions,
View,
} from 'react-native';
import {
ActivityIndicator,
Button,
Card,
Chip,
IconButton,
Menu,
SegmentedButtons,
Text,
TextInput,
} from 'react-native-paper';
import RenderHTML from 'react-native-render-html';
import ADIcon from 'react-native-vector-icons/AntDesign';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import ChatView from '../../components/layout/ChatView';
import ExitDialog from '../../components/layout/ExitDialog';
import ParticipantCard from '../../components/layout/ParticipantCard';
import TopChip from '../../components/layout/TopChip';
import {StageView} from '../../components/StageView';
import RazorpayInit from '../../lib/razorpay';
// @ts-ignore
import {API_URL} from '@env';
import analytics from '@react-native-firebase/analytics';
import swr from 'swr';
import mixpanel, {mixpanelBtnClick} from '../../lib/mixpanel';
import {
widthPercentageToDP as w,
heightPercentageToDP as h,
} from 'react-native-responsive-screen';
import PIPCard from '../../lib/PIPCard';
const fetcher = async (url: string) => {
const token = await AsyncStorage.getItem('token');
return axios
.get(url, {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then(res => res.data)
.catch(err => err.response.data);
};
export default function LiveClass({navigation, route}: any) {
const [showOptions, setShowOptions] = useState(true);
const [message, setMessage] = useState('');
const [messages, setMessages] = useState<any[]>([]);
const [unreadMessages, setUnreadMessages] = useState(0);
const [dialogVisible, setDialogVisible] = useState(false);
const [isScrolling, setIsScrolling] = useState(false);
const [audioMode, setAudioMode] = useState<'speaker' | 'earpiece'>('speaker');
const [page, setPage] = useState(0);
const [loading, setLoading] = useState(false);
const [messageRecipient, setMessageRecipient] = useState<string>('public');
const [expanded, setExpaned] = useState(false);
const [messageLoading, setMessageLoading] = useState(false);
const [isPipModeEnabled, setIsPipModeEnabled] = useState(false);
const [pipModeDelay, setPipModeDelay] = useState(false);
const Tab = createMaterialTopTabNavigator();
const {url, token, masterclassId} = route.params;
const localInputRef = useRef<any>();
const [room] = useState(
() =>
new Room({
adaptiveStream: {pixelDensity: 'screen'},
// publishDefaults: { simulcast: false },
audioCaptureDefaults: {
autoGainControl: true,
echoCancellation: true,
noiseSuppression: true,
},
videoCaptureDefaults: {
facingMode: 'user',
},
publishDefaults: {
simulcast: false,
},
reconnectPolicy: {
nextRetryDelayInMs: (context): number | null => {
if (context.retryCount > 10) {
return null;
}
console.log(
`retrying connection: retries: ${context.retryCount} sec: ${
context.elapsedMs / 1000
} `,
);
return 3000; //retry every 3 seconds
},
},
disconnectOnPageLeave: true,
}),
);
const [isMuteButtonVisible, setIsMuteButtonVisible] = useState(false);
const {
data: masterclassInfo,
error,
isLoading,
mutate,
} = swr(
`fetchMasterclassInfo-${masterclassId}`,
() =>
fetcher(
`${API_URL}/masterclasses/app/masterclass-info?mid=${masterclassId}`,
),
{
refreshInterval: 10000,
},
);
const keyboardDidHideCallback = () => {
localInputRef.current?.blur?.();
};
useEffect(() => {
const keyboardDidHideSubscription = Keyboard.addListener(
'keyboardDidHide',
keyboardDidHideCallback,
);
return () => {
keyboardDidHideSubscription?.remove();
};
}, []);
const {participants} = useRoom(room);
const {cameraPublication, microphonePublication} = useParticipant(
room.localParticipant,
);
function isTrackEnabled(pub?: TrackPublication): boolean {
return !(pub?.isMuted ?? true);
}
type DataSendOptions = {
kind?: DataPacket_Kind;
destination?: string[];
};
const DataTopic = {
CHAT: 'lk-chat-topic',
} as const;
async function sendMessageToClient(
localParticipant: LocalParticipant,
payload: Uint8Array,
topic?: string,
options: DataSendOptions = {},
) {
const {kind, destination} = options;
await localParticipant.publishData(
payload,
kind ?? DataPacket_Kind.RELIABLE,
{
destination,
topic,
},
);
}
async function sendMessage() {
if (!message) {
return;
}
setShowOptions(true);
setMessageLoading(true);
try {
let encoder = new TextEncoder();
const timestamp = Date.now();
const encodedMsg = encoder.encode(JSON.stringify({timestamp, message}));
const adminRecipients = participants.filter(p => {
const metaData = JSON.parse(p.metadata!);
return (
metaData.isAdmin && p.identity !== room.localParticipant.identity
);
});
if (messageRecipient == 'admin') {
await sendMessageToClient(
room.localParticipant,
encodedMsg,
DataTopic.CHAT,
{
kind: DataPacket_Kind.RELIABLE,
destination: adminRecipients.map(p => p.sid),
},
);
setMessages(messages => [
...messages,
{sender: 'You (to admins)', message: message},
]);
} else {
await sendMessageToClient(
room.localParticipant,
encodedMsg,
DataTopic.CHAT,
{
kind: DataPacket_Kind.RELIABLE,
},
);
setMessages(messages => [
...messages,
{sender: 'You', message: message},
]);
}
setMessage('');
} catch (e) {
console.log(e);
} finally {
setMessageLoading(false);
}
}
async function sendLike() {
setMessageLoading(true);
try {
const user = await AsyncStorage.getItem('user').then(
user => JSON.parse(user || '{}')?.data,
);
mixpanelBtnClick({
btnType: 'thumbs_up',
app: masterclassInfo?.data?.masterclass?.title,
user: user,
});
let encoder = new TextEncoder();
const timestamp = Date.now();
const encodedMsg = encoder.encode(
JSON.stringify({timestamp, message: '👍🏻'}),
);
await sendMessageToClient(
room.localParticipant,
encodedMsg,
DataTopic.CHAT,
{
kind: DataPacket_Kind.RELIABLE,
},
);
setMessages(messages => [...messages, {sender: 'You', message: '👍🏻'}]);
setIsScrolling(false);
setUnreadMessages(unreadMessages + 1);
} catch (e) {
console.log(e);
} finally {
setMessageLoading(false);
}
}
useEffect(() => {
AudioSession.selectAudioOutput(audioMode);
}, [audioMode]);
useEffect(() => {
let connect = async () => {
try {
await AudioSession.configureAudio({
android: {
preferredOutputList: [
'bluetooth',
'headset',
'speaker',
'earpiece',
],
audioFocusMode: 'gain',
audioMode: 'normal',
},
});
await AudioSession.startAudioSession();
await room.connect(url, token, {
autoSubscribe: true,
});
} catch (error: any) {
console.log(error);
}
};
connect();
return () => {
room.disconnect();
AudioSession.stopAudioSession();
};
}, [url, token, room]);
useEffect(() => {
if (room.localParticipant.metadata) {
const metadata = JSON.parse(room.localParticipant.metadata);
if (metadata?.isAdmin || metadata?.canSpeak) {
setIsMuteButtonVisible(true);
}
if (!metadata.canSpeak) {
setIsMuteButtonVisible(false);
}
}
}, [room?.localParticipant?.metadata]);
useEffect(() => {
if (room.metadata) {
const pinnedMessages = JSON.parse(room.metadata).pinnedMessages;
}
}, [room.metadata]);
const width = useWindowDimensions().width;
useEffect(() => {
const dataReceived = (
payload: Uint8Array,
participant?: RemoteParticipant,
) => {
//@ts-ignore
let decoder = new TextDecoder('utf-8');
let data = JSON.parse(decoder.decode(payload));
if (data?.type == 'pin') {
return;
}
if (data?.type == 'action') {
if (data?.payload.id == room.localParticipant.identity) {
if (data?.payload?.action == 'mute') {
setIsMuteButtonVisible(false);
room.localParticipant.setMicrophoneEnabled(false);
}
if (data?.payload?.action == 'unmute') {
setIsMuteButtonVisible(true);
}
}
return;
}
setMessages(messages => [
...messages,
{sender: participant?.name ?? 'You', message: data.message},
]);
setUnreadMessages(unreadCnt => unreadCnt + 1);
};
room.on(RoomEvent.DataReceived, dataReceived);
return () => {
room.off(RoomEvent.DataReceived, dataReceived);
};
}, [room]);
useEffect(() => {
const backHandler = BackHandler.addEventListener(
'hardwareBackPress',
() => {
setDialogVisible(true);
return true;
},
);
return () => {
backHandler.remove();
};
}, []);
useEffect(() => {
const timer = setTimeout(() => {
setPage(0);
}, 5000);
return () => clearTimeout(timer);
}, [page]);
useEffect(() => {
if (!isPipModeEnabled) {
setTimeout(() => {
setPipModeDelay(false);
}, 10);
} else {
setPipModeDelay(true);
}
}, [isPipModeEnabled]);
const buttons = masterclassInfo?.data?.bootcamp?.bundleBootcamp
? [
{
value: masterclassInfo?.data?.bootcamp?.id,
label: `Enroll Now - ₹${masterclassInfo?.data?.bootcamp?.discountedPrice?.toLocaleString(
'en-IN',
)}`,
labelStyle: {
color: 'white',
},
},
{
value: masterclassInfo?.data?.bootcamp?.bundleBootcamp?.id,
label: `Enroll Now - ₹${masterclassInfo?.data?.bootcamp?.bundleBootcamp?.discountedPrice?.toLocaleString(
'en-IN',
)}`,
labelStyle: {
color: 'white',
},
},
]
: [
{
value: masterclassInfo?.data?.bootcamp?.id,
label: `Enroll Now - ₹${masterclassInfo?.data?.bootcamp?.discountedPrice?.toLocaleString(
'en-IN',
)}`,
labelStyle: {
color: 'white',
},
style: {
borderWidth: 0,
},
},
];
if (participants.length === 0 || participants.length === 1) {
return (
<View className="h-screen items-center justify-center p-8">
<View className="rounded-xl overflow-hidden">
<View className="w-72 aspect-video items-center justify-center">
<Image
source={require('../../assets/img/loading.gif')}
className="aspect-video w-full h-full object-cover"
/>
</View>
</View>
<Text className="text-black text-xl mt-2 text-center">
You're in waiting room. Wait for the meeting to start.
</Text>
<ExitDialog
exitFn={async () => {
room.disconnect();
const user = await AsyncStorage.getItem('user').then(
user => JSON.parse(user || '{}')?.data,
);
mixpanelBtnClick({
btnType: 'leave_meeting',
app: masterclassInfo?.data?.masterclass?.title,
user: user,
});
analytics().logEvent('leave_meeting', {
title: masterclassInfo?.data?.masterclass?.title,
});
setDialogVisible(false);
navigation.pop();
}}
visible={dialogVisible}
setVisible={setDialogVisible}
title="Leave Meeting"
content="Are you sure you want to leave the meeting?"
/>
</View>
);
}
return (
<PIPCard
isPipModeEnabled={isPipModeEnabled}
setIsPipModeEnabled={setIsPipModeEnabled}
pipComponent={<StageView participants={participants} isPIP={true} />}>
<View className="flex-1 bg-white">
<TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
<>
<TopChip
showDialog={() => setDialogVisible(true)}
audioMode={audioMode}
setAudioMode={setAudioMode}>
{(masterclassInfo?.data?.masterclass?.title.split(
'Masterclass on',
)[1]?.length > 30
? masterclassInfo?.data?.masterclass?.title
.split('Masterclass on')[1]
?.slice(0, 30) + '...'
: masterclassInfo?.data?.masterclass?.title
.split('Masterclass on')[1]
?.slice(0, 30)) ??
masterclassInfo?.data?.masterclass?.title}
</TopChip>
<View className="flex-0 relative w-screen">
{page !== 0 && (
<IconButton
icon={'arrow-left'}
mode="outlined"
className="absolute -left-1 top-6 z-50 bg-white"
iconColor="black"
size={12}
onPress={() => setPage(page - 1)}
/>
)}
<ScrollView horizontal className="flex-row mx-auto">
{pipModeDelay && participants
.slice(3 * page, 3 * (page + 1))
.filter(participant => {
return (
JSON.parse(participant?.metadata ?? '{}')?.isAdmin ||
participant.isLocal
);
})
.map((participant, index) => (
<ParticipantCard
key={index}
participant={participant}
inList
/>
))}
</ScrollView>
{page < Math.floor(participants.length / 3) - 1 && (
<IconButton
mode="outlined"
icon={'arrow-right'}
className="absolute -right-1 top-6 z-50 bg-white"
iconColor="black"
size={12}
onPress={() => setPage(page + 1)}
/>
)}
</View>
<View
className={`w-full relative transition-all duration-500 z-10 h-72 mt-2`}>
<View className="flex-row absolute top-2 px-2 w-full justify-between z-20">
<Chip
icon={() => (
<Icon name="account-outline" size={12} color="red" />
)}
className="bg-white/60 rounded-full w-fit h-6 items-center justify-center"
textStyle={{color: 'black', marginVertical: 0, fontSize: 12}}
compact>
{participants.length * 2}
</Chip>
<Chip
icon={() => <Icon name="record" size={12} color="red" />}
className="bg-white/60 rounded-full w-fit h-6 items-center justify-center"
textStyle={{color: 'black', marginVertical: 0, fontSize: 12}}
compact>
LIVE
</Chip>
</View>
<StageView participants={participants} />
</View>
{masterclassInfo?.data?.metaData?.isEnrollNowButtonVisible ? (
<Tab.Navigator
initialRouteName="Chat"
screenOptions={{
tabBarActiveTintColor: '#000000',
tabBarLabelStyle: {fontSize: 12, textTransform: 'none'},
tabBarIndicatorStyle: {backgroundColor: '#000000'},
}}>
<Tab.Screen
name="Chat"
children={() => (
<ChatView
unreadMessages={unreadMessages}
setUnreadMessages={setUnreadMessages}
messages={messages}
isScrolling={isScrolling}
setIsScrolling={setIsScrolling}
/>
)}
/>
<Tab.Screen
name="Overview"
children={() => (
<ScrollView className="bg-white flex-1 p-4">
<RenderHTML
source={{
html: masterclassInfo?.data?.bootcamp
?.longDescription,
}}
contentWidth={width}
baseStyle={{
color: '#000',
fontSize: 16,
}}
/>
</ScrollView>
)}
/>
<Tab.Screen
name="Curriculum"
children={() => (
<ScrollView className="bg-white flex-1 p-4">
{masterclassInfo?.data?.sessions?.map(
(
session: {
title: string;
description: string;
},
index: React.Key | null | undefined,
) => {
return (
<Card className="bg-white shadow-none" key={index}>
<Card.Title
titleStyle={{color: '#000'}}
title={session.title}
/>
<Card.Content>
<Text className="text-black">
{session.description}
</Text>
</Card.Content>
</Card>
);
},
)}
</ScrollView>
)}
/>
<Tab.Screen
name="Teacher"
children={() => (
<ScrollView className="bg-white flex-1 p-4">
<RenderHTML
source={{
html: masterclassInfo?.data?.teacher?.bio,
}}
contentWidth={width}
baseStyle={{
color: '#000',
fontSize: 16,
}}
/>
</ScrollView>
)}
/>
</Tab.Navigator>
) : (
<>
<ChatView
unreadMessages={unreadMessages}
setUnreadMessages={setUnreadMessages}
messages={messages}
isScrolling={isScrolling}
setIsScrolling={setIsScrolling}
/>
</>
)}
<View
className={`bg-black z-50 ${
masterclassInfo?.data?.metaData?.isEnrollNowButtonVisible
? 'border-2'
: ''
} rounded-t-3xl ${!showOptions ? '-mt-24' : ''}`}>
{masterclassInfo?.data?.metaData?.isEnrollNowButtonVisible && (
<View
style={{
width: width - 4,
}}
className="items-center justify-center mx-auto px-4 pt-4 pb-2 space-y-2">
{!masterclassInfo.data?.metaData?.userPurchasedBootcamp ? (
<SegmentedButtons
value={''}
onValueChange={async value => {
setLoading(true);
const user = await AsyncStorage.getItem('user').then(
user => JSON.parse(user || '{}')?.data,
);
mixpanel.track('payment_initiate', {
app: 'bootcamp purchase',
user: user,
bootcampId: value,
amount:
masterclassInfo?.data?.bootcamp?.id === value
? masterclassInfo?.data?.bootcamp?.discountedPrice
: masterclassInfo?.data?.bootcamp?.bundleBootcamp
?.discountedPrice,
source: 'liveclass',
bootcampName:
masterclassInfo?.data?.bootcamp?.id === value
? masterclassInfo?.data?.bootcamp?.title
: masterclassInfo?.data?.bootcamp?.bundleBootcamp
?.title,
});
RazorpayInit(
{
bootcampId: value,
amount:
masterclassInfo?.data?.bootcamp?.id === value
? masterclassInfo?.data?.bootcamp
?.discountedPrice
: masterclassInfo?.data?.bootcamp
?.bundleBootcamp?.discountedPrice,
others: {
app: 'bootcamp purchase',
source: 'liveclass',
bootcampName:
masterclassInfo?.data?.bootcamp?.id === value
? masterclassInfo?.data?.bootcamp?.title
: masterclassInfo?.data?.bootcamp
?.bundleBootcamp?.title,
},
},
null,
() => {
mutate();
setLoading(false);
},
);
}}
style={{
backgroundColor: '#2C2C8C',
borderRadius: 20,
}}
buttons={buttons}
/>
) : (
<Button
mode="contained"
className="w-full rounded-xl bg-green-500">
<Text className="font-bold text-xl text-white">
🎉 You have enrolled 🎉
</Text>
</Button>
)}
{/* <Text className="text-black">REMAINING SLOTS: 10</Text> */}
</View>
)}
{!showOptions && (
<View
style={{
zIndex: 1000,
}}
className="flex-row items-center mx-4 -my-1">
<Text className="text-white">Send message to</Text>
<Menu
visible={expanded}
onDismiss={() => setExpaned(false)}
contentStyle={{
width: 200,
maxHeight: 200,
backgroundColor: 'white',
}}
// @ts-ignore
className="-mt-8"
anchor={
<Button
mode="text"
compact
className="p-0"
contentStyle={{
flexDirection: 'row-reverse',
}}
onPress={() => setExpaned(true)}
icon={() => (
<ADIcon name="down" size={14} color="black" />
)}>
<Text className="text-red-500 m-0">
{messageRecipient == 'public' ? 'Everyone' : 'Admins'}
</Text>
</Button>
}>
<Menu.Item
titleStyle={{
color: 'black',
}}
leadingIcon={() => (
<Icon name={'account-group'} size={24} color="black" />
)}
onPress={() => {
setMessageRecipient('public');
setExpaned(false);
}}
title="Everyone"
/>
<Menu.Item
titleStyle={{
color: 'black',
}}
leadingIcon={() => (
<Icon name={'account-star'} size={24} color="black" />
)}
onPress={() => {
setMessageRecipient('admin');
setExpaned(false);
}}
title="Admins"
/>
</Menu>
</View>
)}
<View
style={{
width: w(102),
marginHorizontal: -4,
marginBottom: -4,
}}
className={`flex-row items-center justify-center p-1 rounded-b bg-black`}>
{showOptions && (
<>
{isMuteButtonVisible && (
<Button
onPress={async () => {
const user = await AsyncStorage.getItem('user').then(
user => JSON.parse(user!)?.data,
);
mixpanelBtnClick({
btnType:
'mic_' + isTrackEnabled(microphonePublication)
? 'off'
: 'on',
app: masterclassInfo?.data?.masterclass?.title,
user: user,
});
room.localParticipant.setMicrophoneEnabled(
!isTrackEnabled(microphonePublication),
);
}}
labelStyle={{
color: 'white',
}}
icon={() => (
<Icon
name={
isTrackEnabled(microphonePublication)
? 'microphone'
: 'microphone-off'
}
size={24}
color="white"
/>
)}>
{isTrackEnabled(microphonePublication)
? 'Mute'
: 'Unmute'}
</Button>
)}
<Button
onPress={async () => {
const user = await AsyncStorage.getItem('user').then(
user => JSON.parse(user || '{}')?.data,
);
mixpanelBtnClick({
btnType:
'cam_' + isTrackEnabled(cameraPublication)
? 'off'
: 'on',
app: masterclassInfo?.data?.masterclass?.title,
user: user,
});
room.localParticipant.setCameraEnabled(
!isTrackEnabled(cameraPublication),
);
}}
labelStyle={{
color: 'white',
}}
icon={() => (
<Icon
name={
isTrackEnabled(cameraPublication)
? 'video-outline'
: 'video-off-outline'
}
size={24}
color="white"
/>
)}>
{isTrackEnabled(cameraPublication)
? 'Stop Video'
: 'Start Video'}
</Button>
<Button
onPress={async () => {
const user = await AsyncStorage.getItem('user').then(
user => JSON.parse(user || '{}')?.data,
);
mixpanelBtnClick({
btnType: 'chat_open',
app: masterclassInfo?.data?.masterclass?.title,
user: user,
});
setShowOptions(false);
setTimeout(() => {
localInputRef?.current?.focus();
}, 10);
}}
labelStyle={{
color: 'white',
}}
icon={() => (
<Icon name={'chat'} size={24} color="white" />
)}>
Chat
</Button>
{messageLoading ? (
<ActivityIndicator
style={{
height: h(6),
width: h(6),
}}
/>
) : (
<IconButton
onPress={sendLike}
icon={() => (
<ADIcon size={24} name="like1" color="#FFCA28" />
)}
/>
)}
</>
)}
{!showOptions && (
<>
<TextInput
onSubmitEditing={sendMessage}
onBlur={() => setShowOptions(true)}
ref={(ref: any) => {
localInputRef && (localInputRef.current = ref as any);
}}
value={message}
onChangeText={setMessage}
className="flex-1 outline-none border-none bg-transparent"
contentStyle={{
color: 'white',
}}
placeholder={`Write a message for ${
messageRecipient == 'public' ? 'everyone' : 'admins'
}...`}
/>
<View
className={
'rounded-xl mx-2 items-center justify-center w-10 h-10 ' +
(message.length > 0
? 'bg-red-600/90'
: 'bg-transparent')
}>
{messageLoading ? (
<ActivityIndicator />
) : (
<IconButton
onPress={() => {
sendMessage();
setIsScrolling(false);
setUnreadMessages(unreadMessages + 1);
}}
icon={() => (
<Icon name={'send'} size={18} color="white" />
)}
/>
)}
</View>
</>
)}
</View>
</View>
<ExitDialog
exitFn={async () => {
const user = await AsyncStorage.getItem('user').then(
user => JSON.parse(user || '{}')?.data,
);
mixpanelBtnClick({
btnType: 'leave_meeting',
app: masterclassInfo?.data?.masterclass?.title,
user: user,
});
room.disconnect();
analytics().logEvent('leave_meeting', {
title: masterclassInfo?.data?.masterclass?.title,
});
setDialogVisible(false);
navigation.pop();
}}
visible={dialogVisible}
setVisible={setDialogVisible}
title="Leave Meeting"
content="Are you sure you want to leave the meeting?"
/>
</>
</TouchableWithoutFeedback>
</View>
</PIPCard>
);
}
|
d06acbd5e3bf06ca6ad78af8f5b104eb
|
{
"intermediate": 0.345873087644577,
"beginner": 0.3348712921142578,
"expert": 0.3192555904388428
}
|
32,286
|
def load_known_faces(folder_path):
known_faces = []
known_names = []
for name in os.listdir(folder_path):
person_folder = os.path.join(folder_path, name)
if not os.path.isdir(person_folder):
continue
for image_name in os.listdir(person_folder):
image_path = os.path.join(person_folder, image_name)
image = face_recognition.load_image_file(image_path)
image_encoding = face_recognition.face_encodings(image)
if len(image_encoding) > 0:
known_faces.append(image_encoding[0])
known_names.append(name)
return known_faces, known_names как сделать чтобы в список имен сохранялось название картинки которое содержит лицо
|
d936e21d9dd490d54393a502a8a2b8b4
|
{
"intermediate": 0.3884156346321106,
"beginner": 0.25924763083457947,
"expert": 0.35233673453330994
}
|
32,287
|
import cv2
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from PIL import Image, ImageTk
import os
import pickle
import face_recognition
сделай программу которая распознает лица на вебкамере по фотографиям изветных людей, которые хранятся в определенной папке и постоянно пополняются
|
db5701fe7cdc63814b7c7ee262a11aa0
|
{
"intermediate": 0.376330703496933,
"beginner": 0.32692018151283264,
"expert": 0.2967491149902344
}
|
32,288
|
import cv2
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from PIL import Image, ImageTk
import os
import pickle
import face_recognition
def load_known_faces(folder_path):
known_faces = []
known_names = []
for name in os.listdir(folder_path):
person_folder = os.path.join(folder_path, name)
if not os.path.isdir(person_folder):
continue
for image_name in os.listdir(person_folder):
image_path = os.path.join(person_folder, image_name)
image = face_recognition.load_image_file(image_path)
image_encoding = face_recognition.face_encodings(image)
if len(image_encoding) > 0:
known_faces.append(image_encoding[0])
known_names.append(image_name) # Save the image name
known_names.append(name) # Save the person name
return known_faces, known_names
def recognize_faces(camera_id, known_faces, known_names):
video = cv2.VideoCapture(camera_id)
while True:
ret, frame = video.read()
# Определение лиц на кадре
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = " "
# Поиск соответствия лица с известными лицами
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
# Рисуем прямоугольник вокруг лица и название
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, bottom + 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Отображение кадра с распознанными лицами
cv2.imshow("“Face Recognition”", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
# Создание окна для отображения
window = tk.Tk()
window.title("“Face Recognition”")
window.geometry("800x600")
# Загрузка известных лиц
known_faces, known_names = load_known_faces("database")
# Запуск распознавания на веб-камере
recognize_faces(0, known_faces, known_names)
# Запуск главного цикла окна
window.mainloop()
сделай программу которая исправно распознает лица на вебкамере по фотографиям изветных людей, которые хранятся в определенной папке и постоянно пополняются
|
e8e9467c4ed1ffd5c0e84e05edb79c6c
|
{
"intermediate": 0.22640597820281982,
"beginner": 0.5610851645469666,
"expert": 0.21250879764556885
}
|
32,289
|
I'm using a plugin called better terrain and the two tiles are named floor and wall, I wanna use that when creating the generated map:
extends Node2D
var grid_size = Vector2(50, 50) # Change to desired grid size
var cell_size = 10 # Change to the size of each cell in pixels
var grid = []
var update_rate = 0.5 # Seconds
var tilemap # Reference to the TileMap node
var floor_tile_id = 0 # ID of the floor tile in your tileset
var wall_tile_id = 1 # ID of the wall tile in your tileset
func _ready():
tilemap = $Map # Make sure you have a TileMap node as a child and adjust the path accordingly
initialize_grid()
update_grid()
var timer = Timer.new()
timer.set_wait_time(update_rate)
timer.set_one_shot(false)
# Create a Callable by referencing the method directly
var callable = Callable(self, "update_grid")
# Use the Callable to connect the signal
timer.connect("timeout", callable)
add_child(timer)
timer.start()
func initialize_grid():
grid = []
for y in range(grid_size.y):
var row = []
for x in range(grid_size.x):
row.append(randi() % 2) # Randomly set initial state to 0 or 1
grid.append(row)
func draw_grid():
for y in range(grid_size.y):
for x in range(grid_size.x):
# Use the indices of tiles, make sure floor_tile_id and wall_tile_id are integers
var tile_index = wall_tile_id if grid[y][x] == 1 else floor_tile_id
tilemap.set_cell(x, y, tile_index) # Use integer indices here
func get_cell(x, y):
if x < 0 or x >= grid_size.x or y < 0 or y >= grid_size.y:
return 0
return grid[y][x]
func count_neighbors(x, y):
var count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
count += get_cell(x + i, y + j)
return count
func update_grid():
var new_grid = []
for y in range(grid_size.y):
new_grid.append(grid[y].duplicate())
for y in range(grid_size.y):
for x in range(grid_size.x):
var neighbors = count_neighbors(x, y)
if grid[y][x] == 1 and (neighbors < 2 or neighbors > 3):
new_grid[y][x] = 0 # Cell dies, becomes floor
elif grid[y][x] == 0 and neighbors == 3:
new_grid[y][x] = 1 # Cell becomes alive, becomes wall
grid = new_grid
draw_grid()
|
1a8354102627fbd7146c93db2c006401
|
{
"intermediate": 0.34565821290016174,
"beginner": 0.43981707096099854,
"expert": 0.21452473104000092
}
|
32,290
|
from transformers import BertTokenizer, TFBertModel
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import classification_report
# Load Quora dataset
quora_data = pd.read_csv('questions.csv', nrows=6000)
# Select a subset of the dataset for training
#train_data = quora_data.sample(n=80) # Adjust the number of samples based on your requirements
# Get the minimum length between question1 and question2
min_length = min(len(quora_data['question1']), len(quora_data['question2']))
# Adjust the number of samples based on the minimum length
train_data = quora_data.sample(n=min_length)
# Convert the question pairs to list format
question1_list = list(train_data['question1'])
question2_list = list(train_data['question2'])
is_duplicate = list(train_data['is_duplicate'])
# Create DataFrame for the first pair
data1 = pd.DataFrame({'Sentences': question1_list, 'Labels': is_duplicate})
# Create DataFrame for the second pair
data2 = pd.DataFrame({'Sentences': question2_list, 'Labels': is_duplicate})
# Concatenate the two DataFrames
data = pd.concat([data1, data2], ignore_index=True)
# Split data into train and test sets
X_train, X_test, y_train, y_test = train_test_split(data['Sentences'], data['Labels'], test_size=0.2, random_state=42)
# Initialize the TF-IDF vectorizer
vectorizer = TfidfVectorizer()
# Vectorize the sentences in train set
X_train_vectors = vectorizer.fit_transform(X_train)
# Vectorize the sentences in test set
X_test_vectors = vectorizer.transform(X_test)
# Initialize the SVM classifier
svm = SVC()
# Fit the classifier to the training data
svm.fit(X_train_vectors, y_train)
# Predict labels for the test data
y_pred = svm.predict(X_test_vectors)
# Print classification report
print(classification_report(y_test, y_pred))
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, f1_score, recall_score
# Calculate metrics
accuracy = accuracy_score(y_test, y_pred)
cm = confusion_matrix(y_test, y_pred)
precision = precision_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
recall = recall_score(y_test, y_pred)
# Print the results:
print("Accuracy:", accuracy)
print("Confusion Matrix:")
print(cm)
print("Precision:", precision)
print("F1 Score:", f1)
print("Recall:", recall)
save the output the is_duplicated column in an excel file
|
4c7ec79423d6177fa505949f6163e865
|
{
"intermediate": 0.33979347348213196,
"beginner": 0.4478459358215332,
"expert": 0.21236063539981842
}
|
32,291
|
import cv2
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from PIL import Image, ImageTk
import os
import pickle
import face_recognition
def add_new_user(known_faces, known_names):
video = cv2.VideoCapture(0) # Веб-камера
while True:
ret, frame = video.read()
# Определение лиц на кадре
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = "Unknown"
# Проверка, что лицо на видео есть в базе данных
if True in matches:
continue
name = tk.simpledialog.askstring("Новый пользователь", "Введите имя пользователя:")
if name is None:
return
# Создание директории для нового пользователя
person_folder = os.path.join("database", name)
os.makedirs(person_folder, exist_ok=True)
# Сохранение скриншота с лицом
screenshot_name = datetime.now().strftime("%Y%m%d%H%M%S") + ".png"
screenshot_path = os.path.join(person_folder, screenshot_name)
cv2.imwrite(screenshot_path, frame)
# Обновление базы данных
known_faces.append(face_encoding)
known_names.append(name)
messagebox.showinfo("Новый пользователь", "Пользователь успешно добавлен в базу данных.")
return
cv2.imshow("“Face Recognition”", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video.release()
cv2.destroyAllWindows()
def load_known_faces(folder_path):
known_faces = []
known_names = []
for name in os.listdir(folder_path):
person_folder = os.path.join(folder_path, name)
if not os.path.isdir(person_folder):
continue
for image_name in os.listdir(person_folder):
image_path = os.path.join(person_folder, image_name)
image = face_recognition.load_image_file(image_path)
image_encoding = face_recognition.face_encodings(image)
if len(image_encoding) > 0:
known_faces.append(image_encoding[0])
known_names.append(name)
return known_faces, known_names
def recognize_faces(camera_id, known_faces, known_names):
video = cv2.VideoCapture(camera_id)
while True:
ret, frame = video.read()
# Определение лиц на кадре
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = "Unknown"
# Поиск соответствия лица с известными лицами
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
# Рисуем прямоугольник вокруг лица и название
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, bottom + 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Сохранение скриншота при нахождении лица на видео
if name != "Unknown":
now = datetime.now()
timestamp = now.strftime("%Y%m%d%H%M%S")
screenshot_path = os.path.join("database", name, f"{name}_{timestamp}.png")
cv2.imwrite(screenshot_path, frame)
# Отображение кадра с распознанными лицами
cv2.imshow("Face Recognition", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
def add_new_user():
name = messagebox.askstring("New User", "Enter the name of the new user:")
if name:
folder_path = os.path.join("database", name)
os.makedirs(folder_path, exist_ok=True)
messagebox.showinfo("New User", "New user added successfully!")
# Создание окна для отображения
window = tk.Tk()
window.title("“Face Recognition”")
window.geometry("800x600")
# Загрузка известных лиц
known_faces, known_names = load_known_faces("database")
# Кнопка для добавления нового пользователя
add_user_button = tk.Button(window, text="Добавить пользователя", command=lambda: add_new_user(known_faces, known_names))
add_user_button.pack()
# Запуск распознавания на веб-камере
recognize_faces(0, known_faces, known_names)
# Запуск главного цикла окна
window.mainloop()
как уменьшить размер видео внутри окна tkinter чтобы было видно кнопки и остальное окно
|
1cf667a682ad91ea4eb2c48ff5f47d2b
|
{
"intermediate": 0.39294305443763733,
"beginner": 0.4419197142124176,
"expert": 0.16513723134994507
}
|
32,292
|
import cv2
import tkinter as tk
from tkinter import messagebox
from datetime import datetime
from PIL import Image, ImageTk
import os
import pickle
import face_recognition
def add_new_user(known_faces, known_names):
video = cv2.VideoCapture(0) # Веб-камера
while True:
ret, frame = video.read()
# Определение лиц на кадре
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = “Unknown”
# Проверка, что лицо на видео есть в базе данных
if True in matches:
continue
name = tk.simpledialog.askstring(“Новый пользователь”, “Введите имя пользователя:”)
if name is None:
return
# Создание директории для нового пользователя
person_folder = os.path.join(“database”, name)
os.makedirs(person_folder, exist_ok=True)
# Сохранение скриншота с лицом
screenshot_name = datetime.now().strftime(“%Y%m%d%H%M%S”) + “.png”
screenshot_path = os.path.join(person_folder, screenshot_name)
cv2.imwrite(screenshot_path, frame)
# Обновление базы данных
known_faces.append(face_encoding)
known_names.append(name)
messagebox.showinfo(“Новый пользователь”, “Пользователь успешно добавлен в базу данных.”)
return
cv2.imshow(““Face Recognition””, frame)
if cv2.waitKey(1) & 0xFF == ord(‘q’):
break
video.release()
cv2.destroyAllWindows()
def load_known_faces(folder_path):
known_faces = []
known_names = []
for name in os.listdir(folder_path):
person_folder = os.path.join(folder_path, name)
if not os.path.isdir(person_folder):
continue
for image_name in os.listdir(person_folder):
image_path = os.path.join(person_folder, image_name)
image = face_recognition.load_image_file(image_path)
image_encoding = face_recognition.face_encodings(image)
if len(image_encoding) > 0:
known_faces.append(image_encoding[0])
known_names.append(name)
return known_faces, known_names
def recognize_faces(camera_id, known_faces, known_names):
video = cv2.VideoCapture(camera_id)
while True:
ret, frame = video.read()
# Определение лиц на кадре
face_locations = face_recognition.face_locations(frame)
face_encodings = face_recognition.face_encodings(frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
matches = face_recognition.compare_faces(known_faces, face_encoding)
name = “Unknown”
# Поиск соответствия лица с известными лицами
if True in matches:
first_match_index = matches.index(True)
name = known_names[first_match_index]
# Рисуем прямоугольник вокруг лица и название
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, bottom + 20), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
# Сохранение скриншота при нахождении лица на видео
if name != “Unknown”:
now = datetime.now()
timestamp = now.strftime(“%Y%m%d%H%M%S”)
screenshot_path = os.path.join(“database”, name, f"{name}_{timestamp}.png")
cv2.imwrite(screenshot_path, frame)
# Отображение кадра с распознанными лицами
cv2.imshow(“Face Recognition”, frame)
if cv2.waitKey(1) & 0xFF == ord(‘q’):
break
def add_new_user():
name = messagebox.askstring(“New User”, “Enter the name of the new user:”)
if name:
folder_path = os.path.join(“database”, name)
os.makedirs(folder_path, exist_ok=True)
messagebox.showinfo(“New User”, “New user added successfully!”)
# Создание окна для отображения
window = tk.Tk()
window.title(““Face Recognition””)
window.geometry(“800x600”)
# Загрузка известных лиц
known_faces, known_names = load_known_faces(“database”)
# Кнопка для добавления нового пользователя
add_user_button = tk.Button(window, text=“Добавить пользователя”, command=lambda: add_new_user(known_faces, known_names))
add_user_button.pack()
# Запуск распознавания на веб-камере
recognize_faces(0, known_faces, known_names)
# Запуск главного цикла окна
window.mainloop()
как уменьшить размер видео внутри окна tkinter чтобы было видно кнопки и остальное окно с помощью canvas
|
f53c335ffa09b96569f7bb184712ecfa
|
{
"intermediate": 0.35131165385246277,
"beginner": 0.4068478047847748,
"expert": 0.24184052646160126
}
|
32,293
|
Fix this code to print out the Febonacci sequence “ #include <stdio.h>
void main ()
{
long int f1=1,f2=1;
int i;
printf("The febonacci sequence is\n");
for(i=1;i<=20;i++);
{
printf (" %12ld %12ld", f1,f2);
if(1%2==0)printf("\n");
f1=f1+f2;
f2=f2+f1;
}
}”
|
58a9a60deb0ec5b3c181a386adf6e481
|
{
"intermediate": 0.3158767521381378,
"beginner": 0.5616063475608826,
"expert": 0.1225169375538826
}
|
32,294
|
Google sheet, if I want to input in A1, it will automatically display the total of minus in cell A1
|
5e9c5c26e547ab64ff30a3b0b91d7474
|
{
"intermediate": 0.34115472435951233,
"beginner": 0.2306446135044098,
"expert": 0.4282006621360779
}
|
32,295
|
hi
|
b98d6d9600ee74d79d8334f24dd7e969
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
32,296
|
"import os
import numpy as np
import random as rn
import tensorflow as tf
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, LSTM, TimeDistributed, Flatten, Dropout, Conv1D, Bidirectional, ELU
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error, mean_absolute_error
import matplotlib.pyplot as plt
# Set the random seed for reproducibility
seed_value = 42
os.environ['PYTHONHASHSEED'] = str(seed_value)
np.random.seed(seed_value)
rn.seed(seed_value)
tf.random.set_seed(seed_value)
tf.keras.backend.clear_session()
def parse_date(date_string):
return pd.to_datetime(date_string, format='%d/%m/%Y')
df = pd.read_csv('daily2023.csv', parse_dates=['Date'], date_parser=parse_date, index_col='Date')
passenger_count = df['passenger count'].values
def split_sequence(sequence, n_steps):
X, y = list(), list()
for i in range(len(sequence)):
end_ix = i + n_steps
if end_ix > len(sequence) - 1:
break
seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
X.append(seq_x)
y.append(seq_y)
return np.array(X), np.array(y)
def root_mean_squared_error(y_true, y_pred):
return np.sqrt(mean_squared_error(y_true, y_pred))
def mean_absolute_percentage_error(y_true, y_pred):
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
# Fit the scaler on the entire dataset
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(passenger_count.reshape(-1, 1))
train_size = int(len(scaled_data) * 0.6) # 60% of the data
val_size = int(len(scaled_data) * 0.2) # 20% of the data
test_size = len(scaled_data) - train_size - val_size # 20% of the data
scaled_data_train = scaled_data[0:train_size]
scaled_data_val = scaled_data[train_size:train_size+val_size]
scaled_data_test = scaled_data[train_size+val_size:]
# Create the input and target sequences for the train data
n_steps = 35
X_train, y_train = split_sequence(scaled_data_train, n_steps)
X_val, y_val = split_sequence(scaled_data_val, n_steps)
X_test, y_test = split_sequence(scaled_data_test, n_steps)
# Reshape the input data for the training set
n_features = 1
n_seq = 1
X_train = X_train.reshape(X_train.shape[0], n_seq, n_steps, n_features)
X_val = X_val.reshape(X_val.shape[0], n_seq, n_steps, n_features)
X_test = X_test.reshape(X_test.shape[0], n_seq, n_steps, n_features)
initializer=tf.keras.initializers.GlorotNormal(seed=42)
initializer2=tf.keras.initializers.Orthogonal(seed=42)
def create_model():
model = Sequential()
model.add(TimeDistributed(Conv1D(filters=8, kernel_size=3, activation='relu', kernel_initializer=initializer), input_shape=(None, n_steps, n_features)))
model.add(TimeDistributed(Dropout(0.3)))
model.add(TimeDistributed(Flatten()))
model.add(Bidirectional(LSTM(20, activation=ELU(), kernel_initializer=initializer, recurrent_initializer=initializer2, return_sequences=True)))
model.add(Dense(1, kernel_initializer=initializer))
model.compile(optimizer='adam', loss='mse')
return model
model = create_model()
model.summary()
# Fit the model on the training set and evaluate it on the validation set
model.fit(X_train, y_train, validation_data=(X_val, y_val), epochs=150, verbose=1)
# Evaluate the model and make predictions on the training dataset
y_train_pred = model.predict(X_train)
y_train_pred_2d = np.reshape(y_train_pred, (y_train_pred.shape[0]*y_train_pred.shape[1], y_train_pred.shape[2]))
y_train_pred_inverse = scaler.inverse_transform(y_train_pred_2d)
y_train_true_inverse = scaler.inverse_transform(y_train)
# Calculate metrics for the training set
mse = mean_squared_error(y_train_true_inverse, y_train_pred_inverse)
mae = mean_absolute_error(y_train_true_inverse, y_train_pred_inverse)
rmse = root_mean_squared_error(y_train_true_inverse, y_train_pred_inverse)
mape = mean_absolute_percentage_error(y_train_true_inverse, y_train_pred_inverse)
print(f"Training Mean Squared Error: {mse}")
print(f"Training Mean Absolute Error: {mae}")
print(f"Training Root Mean Squared Error: {rmse}")
print(f"Training Mean Absolute Percentage Error: {mape}")
# Plot the forecasting for the training set
plt.plot(y_train_true_inverse, label='True values', color='blue')
plt.plot(y_train_pred_inverse, label='Forecast', color='orange')
plt.legend()
plt.title("Forecast vs True values on training set using CNN LSTM")
plt.show()
# Evaluate the model and make predictions on the validation set
y_val_pred = model.predict(X_val)
y_val_pred_2d = np.reshape(y_val_pred, (y_val_pred.shape[0]*y_val_pred.shape[1], y_val_pred.shape[2]))
y_val_pred_inverse = scaler.inverse_transform(y_val_pred_2d)
y_val_true_inverse = scaler.inverse_transform(y_val)
# Calculate metrics for the validation set
mse = mean_squared_error(y_val_true_inverse, y_val_pred_inverse)
mae = mean_absolute_error(y_val_true_inverse, y_val_pred_inverse)
rmse = root_mean_squared_error(y_val_true_inverse, y_val_pred_inverse)
mape = mean_absolute_percentage_error(y_val_true_inverse, y_val_pred_inverse)
print(f"Validation Mean Squared Error: {mse}")
print(f"Validation Mean Absolute Error: {mae}")
print(f"Validation Root Mean Squared Error: {rmse}")
print(f"Validation Mean Absolute Percentage Error: {mape}")
# Plot the forecasting for the validation set
plt.plot(y_val_true_inverse, label='True values', color='blue')
plt.plot(y_val_pred_inverse, label='Forecast', color='orange')
plt.legend()
plt.title("Forecast vs True values on validation set using CNN LSTM")
plt.show()
# Evaluate the model and make predictions on the test set
y_test_pred = model.predict(X_test)
y_test_pred_2d = np.reshape(y_test_pred, (y_test_pred.shape[0]*y_test_pred.shape[1], y_test_pred.shape[2]))
y_test_pred_inverse = scaler.inverse_transform(y_test_pred_2d)
y_test_true_inverse = scaler.inverse_transform(y_test)
# Calculate metrics for the test set
mse = mean_squared_error(y_test_true_inverse, y_test_pred_inverse)
mae = mean_absolute_error(y_test_true_inverse, y_test_pred_inverse)
rmse = root_mean_squared_error(y_test_true_inverse, y_test_pred_inverse)
mape = mean_absolute_percentage_error(y_test_true_inverse, y_test_pred_inverse)
print(f"Test Mean Squared Error: {mse}")
print(f"Test Mean Absolute Error: {mae}")
print(f"Test Root Mean Squared Error: {rmse}")
print(f"Test Mean Absolute Percentage Error: {mape}")
# Plot the forecasting for the test set
plt.plot(y_test_true_inverse, label='True values', color='blue')
plt.plot(y_test_pred_inverse, label='Forecast', color='orange')
plt.legend()
plt.title("Forecast vs True values on test set using CNN LSTM")
plt.show()
# Get the date indices for train, validation, and test sets
train_dates = df.index[n_steps:train_size]
val_dates = df.index[train_size + n_steps:train_size + val_size]
test_dates = df.index[train_size + val_size + n_steps:]
# Adjust the lengths of the date indices to match the lengths of the prediction arrays
train_dates = train_dates[:len(y_train_pred_inverse)]
val_dates = val_dates[:len(y_val_pred_inverse)]
test_dates = test_dates[:len(y_test_pred_inverse)]
# Plot the original data
plt.figure(figsize=(15, 6))
plt.plot(df.index, passenger_count, label="Original Data", color="#6BD7FF")
# Plot the predictions for the training set
plt.plot(train_dates, y_train_pred_inverse.flatten(), label="Training Set Predictions", color="green")
# Plot the predictions for the validation set
plt.plot(val_dates, y_val_pred_inverse.flatten(), label="Validation Set Predictions", color="purple")
# Plot the predictions for the test set
plt.plot(test_dates, y_test_pred_inverse.flatten(), label="Test Set Predictions", color="orange")
# Customize the plot
plt.xlabel("Date")
plt.ylabel("Passenger Count")
plt.title("Passenger Count Forecast")
plt.legend()
plt.show()"
is this a good implementation of cnn bidirectional lstm for time series forecasting? is it possible to apply attention mechanism?
|
43090baae72a5ec1d8552239928f9fc5
|
{
"intermediate": 0.3971017897129059,
"beginner": 0.24824215471744537,
"expert": 0.3546561002731323
}
|
32,297
|
Hi
|
e34cd5319c3350b5ff895bd44cb9d890
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
32,298
|
Please solve this problem:Suppose there are three genes 𝐺𝑖
, 𝑖 = 1, 2, whose presence are believed to
cause some symptoms 𝑆𝑖
(e.g., the presence of tumors). The doctors cannot directly observe
the genotypes, so they have to assign the treatments based on the symptoms. Now the
doctors want to evaluate the performance of a medicine. The system is modelled as follows:
𝐺1 = 𝑈1
,
𝐺2 = 𝑈2
,
𝐺3 = 𝑈3
,
𝑃𝑟𝑜𝑏(𝑆𝑖 = 1|𝐺𝑗
, 𝑗 = 1, ⋯ , 3) = ℎ(
3
∑
𝑗=1
𝛼𝑖𝑗𝐺𝑗
), 𝑖 = 1, 2,
𝑃 𝑟𝑜𝑏(𝑊 = 1|𝑆𝑖
, 𝑖 = 1, 2) = ℎ(
2
∑
𝑖=1
𝛽𝑖𝑆𝑖
),
𝑌 = 𝛼𝑊 𝑊 +
3
∑
𝑗=1
𝛾𝑗𝐺𝑗
,
where 𝐺𝑗
, 𝑆𝑖
, 𝑊 ∈ {0, 1}, ℎ(𝑥) = exp(−𝑥)/(1 + exp(−𝑥)), and 𝑈𝑖 are independet binary
random variables. 𝐺3
is considered to be the presence of enviromental condition, such as
smoking.
i. Draw the causal for this system (Hint: you can use different types of lines if the figure is
too complex).
ii. Suppose we know that only 𝛼11, 𝛼12, 𝛼22, 𝛽1
, 𝛾2
, 𝛼𝑊 ≠ 0. Draw the causal graph again and
show that the set {𝑆1} and the pair 𝑊 → 𝑌 satisfy the backdoor criterion. Correspondingly,
use the backdoor adjustment to calculate the probability
𝑃 𝑟𝑜𝑏(𝑌 = 𝛼𝑊 |𝑑𝑜(𝑊 = 1)) and 𝑃 𝑟𝑜𝑏(𝑌 = 0|𝑑𝑜(𝑊 = 0)).
Hint: From the system, we have 𝑃 𝑟𝑜𝑏(𝑊 = 1|𝑆𝑖
, 𝐺𝑖
) = ℎ(∑3
𝑗=1 𝛼𝑖𝑗𝐺𝑗
).
iii. Under assumption ii, directly calculate 𝑃𝑟𝑜𝑏(𝑌 = 𝛼𝑊 |𝑑𝑜(𝑊 = 1)) and 𝑃 𝑟𝑜𝑏(𝑌 =
0|𝑑𝑜(𝑊 = 0)). This should coincide with ii.
iv. Suppose the observed data are (𝑊(𝑖), 𝑆(𝑖)
1
, 𝑆(𝑖)
2
, 𝑌 (𝑖)), 𝑖 = 1, 2, ⋯ , 𝑛. Derive valid statistics
for the probabilities
𝑃 𝑟𝑜𝑏(𝑌 = 𝛼𝑊 |𝑑𝑜(𝑊 = 1)) and 𝑃 𝑟𝑜𝑏(𝑌 = 0|𝑑𝑜(𝑊 = 0)).
You do not need to prove the consistency of the estimator. Here suppose the value of 𝛼𝑊 is
known.
|
8e6c4aeb41381c788cf6473100fba561
|
{
"intermediate": 0.2689976692199707,
"beginner": 0.4512259364128113,
"expert": 0.2797764241695404
}
|
32,299
|
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
public class BlockBreakListener implements Listener {
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Material blockMaterial = event.getBlock().getType();
if (blockMaterial.isBlock()) {
String playerName = event.getPlayer().getName();
FileConfiguration config = MiningCore.getPlugin(MiningCore.class).getConfig();
int brokenBlocks = config.getInt(“players.” + playerName, 0);
config.set(“players.” + playerName, brokenBlocks + 1);
MiningCore.getPlugin(MiningCore.class).saveConfig();
}
}
} добавь в этот код чтобы игрок командой /block мог проверить сколько блоков он сломал, скинь код всех классов
|
4550c0e03218c1a01de3d53b1de8e390
|
{
"intermediate": 0.4240448772907257,
"beginner": 0.26157107949256897,
"expert": 0.3143840730190277
}
|
32,300
|
как сделать так чтобы с предметами в меню нельзя было никак взаимодействовать майнкрафт спигот 1.12.2
|
9b0314304c7e76d25a5a21f05a41b0ca
|
{
"intermediate": 0.3287138044834137,
"beginner": 0.24741558730602264,
"expert": 0.42387059330940247
}
|
32,301
|
У меня ругается компилятор на "player.GetCollider()" в строке "platform1.GetCollider().checkCollision(player.GetCollider(), 0.0f);". Причина: ошибка C2664 (невозможно преобразовать Collider в Collider&), “initial value of reference to non-const must be an lvalue”. Тебе хватит этой информации для помощи или нужно ещё что-то показать?
|
40fe9070a5268327e0278d00a7bd1396
|
{
"intermediate": 0.3664931058883667,
"beginner": 0.380980521440506,
"expert": 0.2525264024734497
}
|
32,302
|
I have those constants:
mark_price_data = client.ticker_price(symbol=symbol)
mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol)
mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0
# Retrieve depth data
depth_data = client.depth(symbol=symbol)
bids = depth_data['bids']
bid_prices = [float(bid[0]) for bid in bids]
asks = depth_data['asks']
ask_prices = [float(ask[0]) for ask in asks]
You need to give me system which will print me every bid and ask prices
|
8d05d67fc4e5534747b2cc0c50c613c7
|
{
"intermediate": 0.5991870760917664,
"beginner": 0.15598098933696747,
"expert": 0.24483199417591095
}
|
32,303
|
Implement the breadth-first numbering by simulating lazy evaluation in Python
or Java.
|
6fe306330c9bc17a1b4d714e89dc4293
|
{
"intermediate": 0.31298497319221497,
"beginner": 0.10589912533760071,
"expert": 0.5811159014701843
}
|
32,304
|
give me the speech for the first speaker of proposition side and provide essential arguments and contextualize for the following topic: This house supports the rise of AI companions.
|
a7382e00b4db7417a79f3ef51a7f5e18
|
{
"intermediate": 0.15288886427879333,
"beginner": 0.1273537576198578,
"expert": 0.7197573781013489
}
|
32,305
|
Think about the right-association problem of the grammar, and find out how to solve it. Base you solution on Parser.hs and save it as ParserLeft.hs. Attach your code ParserLeft.hs.
|
7bafa5ada4a3aa36ad91094e478f3337
|
{
"intermediate": 0.3628939688205719,
"beginner": 0.3683558702468872,
"expert": 0.2687501609325409
}
|
32,306
|
Can you please write a python script that will find the longest line in "input.txt" fine, and then print it and it's length in "output.txt" file?
|
144905414438d3438cc08fbe0c14fc2c
|
{
"intermediate": 0.49734994769096375,
"beginner": 0.16268479824066162,
"expert": 0.3399653434753418
}
|
32,307
|
what is migration in elastic cloud storage dell product
|
000560501a754b8dcbcc419120d96f69
|
{
"intermediate": 0.34049898386001587,
"beginner": 0.3417554795742035,
"expert": 0.31774550676345825
}
|
32,308
|
i work on DES algorithm form scratch in python
and i want to function that permute my key and PC_1
how to implement this function?
|
83292d3ad7b77dcd437c94e4c1345eae
|
{
"intermediate": 0.20409724116325378,
"beginner": 0.08332465589046478,
"expert": 0.7125780582427979
}
|
32,309
|
package foleon.miningcore;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import java.io.File;
import java.util.Arrays;
public class StatsCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length < 1) {
sender.sendMessage("Usage: /stats <player>");
return true;
}
String targetPlayerName = args[0];
Player player = (Player) sender;
String playerName = player.getName();
FileConfiguration config = MiningCore.getPlugin(MiningCore.class).getConfig();
int brokenBlocks = config.getInt("players." + playerName, 0);
Player targetPlayer = Bukkit.getPlayer(targetPlayerName);
if (targetPlayer != null) {
Inventory statsMenu = Bukkit.createInventory(null, 9, "Player Stats: " + targetPlayerName);
ItemStack headItem = new ItemStack(Material.SKULL_ITEM);
SkullMeta skullMeta = (SkullMeta) headItem.getItemMeta();
skullMeta.setOwningPlayer(targetPlayer);
skullMeta.setDisplayName(ChatColor.RED + targetPlayerName);
double gold = config.getDouble("gold." + targetPlayer.getUniqueId().toString(), 0.0);
skullMeta.setLore(Arrays.asList(ChatColor.WHITE + "Сломано блоков: " + ChatColor.YELLOW + + brokenBlocks, ChatColor.WHITE + "Золото: " + ChatColor.YELLOW + gold));
headItem.setItemMeta(skullMeta);
statsMenu.setItem(4, headItem);
((Player) sender).openInventory(statsMenu);
} else {
sender.sendMessage("Invalid player specified.");
}
return true;
}
} сделай чтобы в статс писало текущее здоровье игрока и его максимальное здоровье рядом с его ником в названии головы.
|
f800d77a298b2778b6641302067b39a4
|
{
"intermediate": 0.26853129267692566,
"beginner": 0.6231460571289062,
"expert": 0.10832266509532928
}
|
32,310
|
I need to use for loop on all values in a single column in Python Pandas.
|
926f3fb1153b99cfeb7a9fad6069a9a1
|
{
"intermediate": 0.2671869099140167,
"beginner": 0.5475059151649475,
"expert": 0.185307115316391
}
|
32,311
|
<?php
require_once('db.php');
$login=$_POST['login'];
$pas=$_POST['pass'];
$repeatpass=$_POST['repeatpass'];
$email=$_POST['email'];
$sql = "INSERT INTO `users` (login, pass, email) VALUES ('$login', '$pass', '$email')"
$conn -> query($sql);
?> Найди ошибку
|
80e3f309a0ffbc2583f475a645843b2b
|
{
"intermediate": 0.3783729672431946,
"beginner": 0.39305606484413147,
"expert": 0.22857102751731873
}
|
32,312
|
В чем ошибка? <?php
require_once('db.php');
$login=$_POST['login'];
$pass=$_POST['pass'];
$repeatpass=$_POST['repeatpass'];
$email=$_POST['email'];
$sql = "INSERT INTO `users` (login, pass, email) VALUES ('$login', '$pass', '$email')"
$conn -> query($sql);
?>
|
fbc95513f0679ec102939f0db7434b00
|
{
"intermediate": 0.3814326524734497,
"beginner": 0.45541301369667053,
"expert": 0.16315433382987976
}
|
32,313
|
I have this code : # Retrieve depth data
depth_data = client.depth(symbol=symbol)
bids = depth_data['bids']
bid_prices = [float(bid[0]) for bid in bids]
highest_bid_price = max(bid_prices)
lowest_bid_price = min(bid_prices)
b_l = lowest_bid_price > mark_price + (mark_price / 100)
b_h = highest_bid_price
asks = depth_data['asks']
ask_prices = [float(ask[0]) for ask in asks]
highest_ask_price = max(ask_prices)
lowest_ask_price = min(ask_prices)
s_l = lowest_ask_price
s_h = highest_ask_price < mark_price - (mark_price / 100)
Give em ode which will print me all asks price and all bid price
|
db347ae88c2754c09cc44ba049f6bb9b
|
{
"intermediate": 0.438484251499176,
"beginner": 0.22977867722511292,
"expert": 0.33173707127571106
}
|
32,314
|
package foleon.miningcore;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import java.io.File;
import java.util.Arrays;
public class StatsCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length < 1) {
sender.sendMessage(“Usage: /stats <player>”);
return true;
}
String targetPlayerName = args[0];
Player player = (Player) sender;
String playerName = player.getName();
FileConfiguration config = MiningCore.getPlugin(MiningCore.class).getConfig();
int brokenBlocks = config.getInt(“players.” + playerName, 0);
Player targetPlayer = Bukkit.getPlayer(targetPlayerName);
if (targetPlayer != null) {
Inventory statsMenu = Bukkit.createInventory(null, 9, "Player Stats: " + targetPlayerName);
double currentHealth = targetPlayer.getHealth();
double maxHealth = targetPlayer.getMaxHealth();
ItemStack headItem = new ItemStack(Material.SKULL_ITEM);
SkullMeta skullMeta = (SkullMeta) headItem.getItemMeta();
skullMeta.setOwningPlayer(targetPlayer);
skullMeta.setDisplayName(ChatColor.RED + targetPlayerName + " " + currentHealth + “/” + maxHealth + “❤”);
double gold = config.getDouble(“gold.” + targetPlayer.getUniqueId().toString(), 0.0);
skullMeta.setLore(Arrays.asList(ChatColor.WHITE + "Сломано блоков: " + ChatColor.YELLOW + brokenBlocks, ChatColor.WHITE + "Золото: " + ChatColor.YELLOW + gold));
headItem.setItemMeta(skullMeta);
statsMenu.setItem(4, headItem);
((Player) sender).openInventory(statsMenu);
} else {
sender.sendMessage(“Invalid player specified.”);
}
return true;
}
} добавь в этот код чтобы показывало урон игрока который он может нанести. Скинь итоговый код
|
ba53d7ea5c0d5fe9b219c54c1c8fe62f
|
{
"intermediate": 0.36766642332077026,
"beginner": 0.31990930438041687,
"expert": 0.3124242424964905
}
|
32,315
|
Добавь пропуск строки после добавления : private void updateSummaryText() {
TextView summaryText = findViewById(R.id.summary_text);
StringBuilder stringBuilder = new StringBuilder();
// Add checkBox state
if (checkBox.isChecked()) {
stringBuilder.append("com.google.android.material.checkbox.MaterialCheckBox :true");
} else {
stringBuilder.append("com.google.android.material.checkbox.MaterialCheckBox :false");
}
// Add switch state
if (aSwitch.isChecked()) {
stringBuilder.append("com.google.android.material.switchmaterial.SwitchMaterial :true");
} else {
stringBuilder.append("com.google.android.material.switchmaterial.SwitchMaterial :false");
}
// Add toggleButton state
if (toggleButton.isChecked()) {
stringBuilder.append("androidx.appcompat.widget.AppCompatToggleButton :true");
} else {
stringBuilder.append("androidx.appcompat.widget.AppCompatToggleButton :false");
}
if (Cheap.isChecked()) {
stringBuilder.append("com.google.android.material.chip.Chip :true");
} else {
stringBuilder.append("com.google.android.material.chip.Chip :false");
}
|
90fbdc284f1069f699a669cf12af3651
|
{
"intermediate": 0.36334991455078125,
"beginner": 0.3275555372238159,
"expert": 0.30909448862075806
}
|
32,316
|
can you help me create a object detection system that detects from a camera source?
|
269659797fb36777415c9f85d24cee8a
|
{
"intermediate": 0.17361819744110107,
"beginner": 0.09540480375289917,
"expert": 0.7309769988059998
}
|
32,317
|
I used this code:
mark_price_data = client.ticker_price(symbol=symbol)
mp = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
mark_price_data_change = client.ticker_24hr_price_change(symbol=symbol)
mark_price_percent = float(mark_price_data_change['priceChangePercent']) if 'priceChangePercent' in mark_price_data_change else 0.0
# Retrieve depth data
depth_data = client.depth(symbol=symbol)
bids = depth_data['bids']
bid_prices = [float(bid[0]) for bid in bids if float(bid[0]) > mark_price]
asks = depth_data['asks']
ask_prices = [float(ask[0]) for ask in asks if float(ask[0]) < mark_price]
print("buy:", bid_prices)
print("sell:", ask_prices)
print(mark_price)
but terminal returned me: buy: [227.49, 227.48]
sell: []
227.47
It gives me few numbers , I need middle price between them
|
5e2cf07ef97c524b0e81934646604b5e
|
{
"intermediate": 0.388383686542511,
"beginner": 0.343254953622818,
"expert": 0.2683614194393158
}
|
32,318
|
i have a image and there are 5 to 8 symbols (mostly digits) on a white background. write a python script that extracts those symbols and saves them as different images
|
5a6d5f6d8b2eef8ba0d9f08d87c0f971
|
{
"intermediate": 0.36564555764198303,
"beginner": 0.16470742225646973,
"expert": 0.46964699029922485
}
|
32,319
|
how to shift string left
|
3fe8cb55e9e5545b8dcab32d49cbcc2b
|
{
"intermediate": 0.33213022351264954,
"beginner": 0.2726864814758301,
"expert": 0.3951832950115204
}
|
32,320
|
package foleon.miningcore;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.IOException;
import org.bukkit.plugin.Plugin;
public class ExpManager {
private File expFile;
private FileConfiguration expConfig;
public ExpManager() {
expFile = new File(MiningCore.getInstance().getDataFolder(), "exp.yml");
expConfig = YamlConfiguration.loadConfiguration(expFile);
if (!expFile.exists()) {
expConfig.createSection("players");
saveExpConfig();
}
}
public void saveExpConfig() {
try {
expConfig.save(expFile);
} catch (IOException e) {
e.printStackTrace();
}
}
public int getExp(String playerName) {
return expConfig.getInt("players." + playerName, 0);
}
public void setExp(String playerName, int expAmount) {
expConfig.set("players." + playerName, expAmount);
saveExpConfig();
}
public void addExp(String playerName, int expAmount) {
int currentExp = getExp(playerName);
setExp(playerName, currentExp + expAmount);
if (currentExp + expAmount >= 10) {
// При достижении 10 очков опыта - повышение уровня
LevelUp(playerName);
}
}
private void LevelUp(String playerName) {
// Увеличение уровня игрока и обновление опыта
int currentLevel = expConfig.getInt("players." + playerName + ".level", 1);
expConfig.set("players." + playerName + ".level", currentLevel + 1);
setExp(playerName, 0);
saveExpConfig();
// Выполнение дополнительных действий при достижении уровня (например, выдача награды)
// …
}
} добавь в этот код чтобы все игроки зашедшие на сервер добавлялись в exp.yml
|
f26b9e64089bd89e1b7afc1216ace083
|
{
"intermediate": 0.24026721715927124,
"beginner": 0.523759126663208,
"expert": 0.23597364127635956
}
|
32,321
|
i have a image and there are 5 to 8 symbols (mostly digits) on a white background. write a python script that cuts off those symbols and saves them as different images
|
d0b4d528f3155f7269767994709ae0fd
|
{
"intermediate": 0.3572343587875366,
"beginner": 0.1625337153673172,
"expert": 0.4802318513393402
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.