row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
11,852
|
transcription for "https://www.youtube.com/watch?v=_qDML_BCju8"
|
6103dd33f30d78bd3c0e47ebc61abc29
|
{
"intermediate": 0.29304972290992737,
"beginner": 0.27008432149887085,
"expert": 0.43686604499816895
}
|
11,853
|
write a code that do a gui and display photos that located in a folder called storage while using google colab
|
bb167fa730e00127f34a42158a2f154d
|
{
"intermediate": 0.5165177583694458,
"beginner": 0.14932577311992645,
"expert": 0.33415648341178894
}
|
11,854
|
Modify the antd tabs style to look like the antd card component in react
|
7f145ba3b98a6adb4d73617f399d37cd
|
{
"intermediate": 0.41063350439071655,
"beginner": 0.2696385979652405,
"expert": 0.31972789764404297
}
|
11,855
|
import re
import requests
import difflib
API_KEY = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS"
BASE_URL = "https://api.bscscan.com/api"
similarity_threshold = 0.5
def get_contract_source_code(address):
params = {
"module": "contract",
"action": "getsourcecode",
"address": address,
"apiKey": API_KEY
}
response = requests.get(BASE_URL, params=params)
data = response.json()
if data["status"] == "1":
source_code = data["result"][0]["SourceCode"]
return remove_comments(source_code)
else:
return None
def remove_comments(code):
cleaned_code = re.sub(r"//.", "", code) # Remove single-line comments
cleaned_code = re.sub(r" *", "", code) # Remove single-line comments
cleaned_code = re.sub(r" / *[\s\S]? */ ", "", cleaned_code) # Remove multiline comments
cleaned_code = re.sub(r" *[\s\S] * ? * / ", "", cleaned_code) # Remove multiline comments starting with *
cleaned_code = re.sub(r"\n + ", "\n", cleaned_code) # Remove any extra line breaks
return cleaned_code.strip()
lines = code.split('\n')
lines_without_comments = []
is_multiline_comment = False
for line in lines:
single_line_comment = re.sub(r"//.", "", line)
match = re.findall(r" /* | */ ", single_line_comment)
if not match:
if not is_multiline_comment:
lines_without_comments.append(single_line_comment)
elif match:
if is_multiline_comment and "/" in match:
is_multiline_comment = False
pos = single_line_comment.index(" / ") + 2
single_line_comment = single_line_comment[pos:]
lines_without_comments.append(single_line_comment)
elif not is_multiline_comment and "/" in match:
is_multiline_comment = True
single_line_comment = single_line_comment[: single_line_comment.index(" / * ")]
lines_without_comments.append(single_line_comment)
cleaned_code = "\n".join(lines_without_comments)
return cleaned_code
def jaccard_similarity(str1, str2):
a = set(str1.split())
b = set(str2.split())
c = a.intersection(b)
return float(len(c)) / (len(a) + len(b) - len(c))
def find_similar_contracts(reference_addresses, candidate_addresses):
reference_source_codes = {}
for reference_address in reference_addresses:
source_code = get_contract_source_code(reference_address)
if source_code is not None:
reference_source_codes[reference_address] = source_code
if not reference_source_codes:
print("No source code found for reference contracts")
return []
similar_contracts = {}
for address in candidate_addresses:
candidate_source_code = get_contract_source_code(address)
if candidate_source_code is not None:
for reference_address, reference_source_code in reference_source_codes.items():
similarity = jaccard_similarity(candidate_source_code, reference_source_code)
if similarity >= similarity_threshold:
if reference_address not in similar_contracts:
similar_contracts[reference_address] = [(address, similarity)]
else:
similar_contracts[reference_address].append((address, similarity))
return similar_contracts
def print_code_difference(reference_code, candidate_code):
reference_lines = reference_code.splitlines()
candidate_lines = candidate_code.splitlines()
diff = difflib.unified_diff(reference_lines, candidate_lines)
for line in diff:
print(line)
if __name__ == "__main__":
reference_addresses = ["0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb"]
candidate_addresses = ["0xd481997fbe2D7C7f9E651e5f2450AcbC38Eed750"]
similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses)
print("Contracts with similar source code (ignoring comments):")
for reference_address, similar_addresses in similar_contracts.items():
reference_code = get_contract_source_code(reference_address)
print(f"Reference contract: {reference_address}")
for address, similarity in similar_addresses:
candidate_code = get_contract_source_code(address)
print(f"Similar contract: {address} with a similarity of {similarity:.2f}")
if similarity < 1.0:
print("Code differences:")
print_code_difference(reference_code, candidate_code)
print("\n")
The code above does not remove all comments that are in the source code of the contract.
Comments in code begin with the following characters
//
this is a single-line comment and the characters after it should not be taken into account when comparing
/*
*/
this is a multi-line comment. All characters between them do not need to be taken into account when comparing
/**
*/
this is also a multi-line comment. All characters between them do not need to be taken into account when comparing
Inside a multiline comment, comments start with the * character. All characters after * also do not need to be taken into account when comparing
Write full code
|
ef5c11849f0b2c837a44b445a268f5bf
|
{
"intermediate": 0.38675186038017273,
"beginner": 0.35349562764167786,
"expert": 0.2597525119781494
}
|
11,856
|
Hello
|
2fa9d297f3efed6b8dadbef85c3a3646
|
{
"intermediate": 0.3123404085636139,
"beginner": 0.2729349136352539,
"expert": 0.4147246778011322
}
|
11,857
|
Considere o tutorial em https://geth.ethereum.org/docs/getting-started para solucionar esse erro:
WARN [06-13|14:21:47.789] Failed to open wallet url=extapi://\\.\pipe\clef.ipc err="operation not supported on external signers"
|
58b4e338242acb2f502a8464008b45e3
|
{
"intermediate": 0.4203273057937622,
"beginner": 0.2015584260225296,
"expert": 0.378114253282547
}
|
11,858
|
I have 3 tables. I need atrr in Customer with Customer objects. Here my tables: class Customer(Base):
__tablename__ = 'customer'
name: Mapped[str] = mapped_column(String(32), unique=True, nullable=False)
noservice_date: Mapped[date | None] = mapped_column(Date, default=None)
class CustomerObject(Base):
__tablename__ = 'customer_obj'
name: Mapped[str] = mapped_column(String(100), unique=True, nullable=False)
address: Mapped[str] = mapped_column(String(100), nullable=False)
phone_numbers: Mapped[str] = mapped_column(String(100), nullable=False)
schedule: Mapped[list] = mapped_column(ARRAY(Time, dimensions=2))
area_int: Mapped[int] = mapped_column(Integer, nullable=False)
trade_area_int: Mapped[int] = mapped_column(Integer, nullable=False)
slab_height_int: Mapped[int] = mapped_column(SmallInteger, nullable=False)
ceiling_height_int: Mapped[int] = mapped_column(SmallInteger, nullable=False)
service_end_date: Mapped[date | None] = mapped_column(Date, default=None)
class CustomerCustomerObject(Base):
__tablename__ = 'customer_customer_obj'
customer_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('customer.id'), nullable=False)
customer_obj_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('customer_obj.id'), nullable=False)
city_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('city.id'), nullable=False)
ceiling_type_id: Mapped[uuid.UUID] = mapped_column(ForeignKey('ceiling_type.id'), nullable=False)
|
b6c52e9952a897e2afd42fd596e5039a
|
{
"intermediate": 0.3959505259990692,
"beginner": 0.32286304235458374,
"expert": 0.28118643164634705
}
|
11,859
|
i wanna place button at the bottom of the imgui window, keep in mind that imgui window working separately from main window
|
f7bdcf17d8358d6763a3194cd14cc185
|
{
"intermediate": 0.42980286478996277,
"beginner": 0.21107880771160126,
"expert": 0.35911837220191956
}
|
11,860
|
how to stream a response back from openai
|
d3bf9c87382e25b96356d28da6b59fe6
|
{
"intermediate": 0.3666038513183594,
"beginner": 0.10473707318305969,
"expert": 0.5286590456962585
}
|
11,861
|
template <typename T>
void loadFromJson(const nlohmann::json& j, const std::string& key, T& var)
{
if ( j.contains(key) && j[key].is<T>())
{
var = j[key].get<T>();
}
}
this gives an error c2760
rewrite snippet to fix those error.
keep function as is. don't use try-catch blocks
|
d96b814c2f2e936464ae26ab5cb55c6d
|
{
"intermediate": 0.3256601095199585,
"beginner": 0.49034184217453003,
"expert": 0.18399804830551147
}
|
11,862
|
How to create a MLP ANN in matlab?
|
75d9da895eb63cb051854bfc416f5a5e
|
{
"intermediate": 0.08364877104759216,
"beginner": 0.03771798312664032,
"expert": 0.8786332607269287
}
|
11,863
|
Is feed forward ANN different with Back progration ANN in matlab??
|
a6efc2cce0d1d1d6f1fa6848c3a44614
|
{
"intermediate": 0.10745852440595627,
"beginner": 0.05187680944800377,
"expert": 0.8406646251678467
}
|
11,864
|
How to extract data from nav_msgs/Odometry topic of ros package?
|
7dad8510ee8fb989082b015fc03234cd
|
{
"intermediate": 0.531925618648529,
"beginner": 0.11366342753171921,
"expert": 0.35441091656684875
}
|
11,865
|
how to check if
There is a record in the database that simultaneously has the same fields "Object name", "City", "Street" python ans sqlalchemy
|
6bda3726d7b9ec2e4ec3efdfa9d466f3
|
{
"intermediate": 0.4845138192176819,
"beginner": 0.2212120145559311,
"expert": 0.2942741811275482
}
|
11,866
|
Оптимизируй код:
using DiplomWPFnetFramework.Classes;
using DiplomWPFnetFramework.DataBase;
using DiplomWPFnetFramework.Windows.BufferWindows;
using DiplomWPFnetFramework.Windows.DocumentTemplatesWindows;
using System;
using System.Collections.Generic;
using System.Data.Entity.Migrations;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace DiplomWPFnetFramework.Pages.MainInteractionsPages
{
/// <summary>
/// Логика взаимодействия для DocumentViewingPage.xaml
/// </summary>
public partial class DocumentViewingPage : Page
{
Window parentWindow = null;
public DocumentViewingPage()
{
InitializeComponent();
LoadContent();
}
public void LoadContent()
{
SystemContext.PageForLoadContent = this;
using (var db = new test123Entities1())
{
DocumentsViewGrid.Children.Clear();
List<Items> items = null;
try
{
if (SystemContext.isFromFolder)
{
if (SystemContext.isFromHiddenFiles)
{
items = (from i in db.Items
where i.UserId == SystemContext.User.Id && i.IType != "Folder" && (i.FolderId == null || i.FolderId == SystemContext.Item.Id) && i.IsHidden == 1
orderby i.IPriority descending, i.DateCreation
select i).ToList<Items>();
addNewImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/CheckMarkImage.png"));
addNewImage.Stretch = Stretch.Uniform;
}
else
{
items = (from i in db.Items
where i.UserId == SystemContext.User.Id && i.IType != "Folder" && (i.FolderId == null || i.FolderId == SystemContext.Item.Id) && i.IsHidden == 0
orderby i.IPriority descending, i.DateCreation
select i).ToList<Items>();
addNewImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/CheckMarkImage.png"));
addNewImage.Stretch = Stretch.Uniform;
}
}
else if (SystemContext.isFromHiddenFiles)
{
items = (from i in db.Items
where i.UserId == SystemContext.User.Id && i.FolderId == null && i.IsHidden == 1
orderby i.IPriority descending, i.DateCreation
select i).ToList<Items>();
if (!SystemContext.isDocumentNeedToShow)
items.RemoveAll(d => d.IType == "Passport" || d.IType == "INN" || d.IType == "SNILS" || d.IType == "Polis");
if (!SystemContext.isCreditCardNeedToShow)
items.RemoveAll(cc => cc.IType == "CreditCard");
if (!SystemContext.isCollectionNeedToShow)
items.RemoveAll(c => c.IType == "Collection");
if (!SystemContext.isFolderNeedToShow)
items.RemoveAll(f => f.IType == "Folder");
}
else
{
items = (from i in db.Items
where i.UserId == SystemContext.User.Id && i.FolderId == null && i.IsHidden == 0
orderby i.IPriority descending, i.DateCreation
select i).ToList<Items>();
if (!SystemContext.isDocumentNeedToShow)
items.RemoveAll(d => d.IType == "Passport" || d.IType == "INN" || d.IType == "SNILS" || d.IType == "Polis");
if (!SystemContext.isCreditCardNeedToShow)
items.RemoveAll(cc => cc.IType == "CreditCard");
if (!SystemContext.isCollectionNeedToShow)
items.RemoveAll(c => c.IType == "Collection");
if (!SystemContext.isFolderNeedToShow)
items.RemoveAll(f => f.IType == "Folder");
}
}
catch
{
MessageBox.Show("Ошибка при загрузке документов");
return;
}
foreach (var item in items)
AddNewDocument(item);
}
}
private BitmapSource ByteArrayToImage(byte[] buffer)
{
using (var stream = new MemoryStream(buffer))
{
return BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
}
}
private void AddNewDocument(Items item)
{
var borderPanel = new Border() { BorderBrush = Brushes.LightGray, BorderThickness = new Thickness(2), Style = (Style)DocumentsViewGrid.Resources["ContentBorderStyle"], Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#8a8eab")) };
var mainGrid = new Grid() { Name = "mainGrid", Resources = (ResourceDictionary)DocumentsViewGrid.Resources["CornerRadiusSetter"] };
var bottomDarkeningBorder = new Border() { Style = (Style)DocumentsViewGrid.Resources["BottomBorderProperties"] };
var contextMenu = (ContextMenu)this.FindResource("MyContextMenu");
ImageBrush imageBrush = new ImageBrush();
Image image = new Image() { Resources = (ResourceDictionary)DocumentsViewGrid.Resources["CornerRadiusSetter"] };
if (item.IImage != null && item.IImage.ToString() != "")
image.Source = ByteArrayToImage(item.IImage);
else
{
switch (item.IType)
{
case "Passport":
image.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/RussianPassportPlug.png"));
imageBrush.Stretch = Stretch.Uniform;
break;
case "INN":
image.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/RussianINNPlug.jpg"));
imageBrush.Stretch = Stretch.Uniform;
break;
case "SNILS":
image.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/RussianSNILSPlug.jpg"));
imageBrush.Stretch = Stretch.Uniform;
break;
case "CreditCard":
image.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/CreditCardPlugImage.png"));
imageBrush.Stretch = Stretch.UniformToFill;
break;
case "Polis":
image.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/RussianPolisPlug.png"));
imageBrush.Stretch = Stretch.UniformToFill;
break;
case "Folder":
break;
case "Collection":
break;
default:
image.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/DocumentPlugImage.png"));
imageBrush.Stretch = Stretch.UniformToFill;
break;
}
}
imageBrush.ImageSource = image.Source;
mainGrid.Background = imageBrush;
bottomDarkeningBorder.VerticalAlignment = VerticalAlignment.Bottom;
TextBlock itemName = new TextBlock() { Text = item.Title, Style = (Style)DocumentsViewGrid.Resources["DocumentTextBlockPropeties"] };
borderPanel.Tag = item;
contextMenu.Tag = item;
bottomDarkeningBorder.Tag = item;
itemName.Tag = item;
borderPanel.MouseLeftButtonUp += ChangeItemButton_Click;
if (SystemContext.isFromFolder == false)
borderPanel.ContextMenu = contextMenu;
bottomDarkeningBorder.MouseLeftButtonUp += ChangeTitleNameButton_Click;
itemName.MouseLeftButtonUp += ChangeTitleNameButton_Click;
Image LockImage = new Image() { Name = "LockImage", VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 5, 0, 0), Height = 25, Width = 25 };
LockImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/LockImage.png"));
mainGrid.Children.Add(LockImage);
if (item.IPriority == 0)
LockImage.Visibility = Visibility.Hidden;
if (SystemContext.isFromFolder)
{
Image unselectedImage = new Image() { Name = "unselectedImage", VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 5, 5, 0), Height = 25, Width = 25 };
Image selectedImage = new Image() { Name = "selectedImage", VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Right, Margin = new Thickness(0, 5, 5, 0), Height = 25, Width = 25 };
unselectedImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/unselected_circle.png"));
selectedImage.Source = new BitmapImage(new Uri("pack://application:,,,/Resources/selected_circle.png"));
mainGrid.Children.Add(unselectedImage);
mainGrid.Children.Add(selectedImage);
if (item.IsSelected == 1)
unselectedImage.Visibility = Visibility.Hidden;
else
selectedImage.Visibility = Visibility.Hidden;
}
mainGrid.Children.Add(bottomDarkeningBorder);
mainGrid.Children.Add(itemName);
borderPanel.Child = mainGrid;
DocumentsViewGrid.Children.Add(borderPanel);
}
private void AddInFolder(Items item)
{
using (var db = new test123Entities1())
{
if (item.FolderId == null && item.IsSelected == 1)
{
item.FolderId = SystemContext.Folder.Id;
db.Items.AddOrUpdate(item);
}
else if (item.FolderId != null && item.IsSelected == 0)
{
item.FolderId = null;
db.Items.AddOrUpdate(item);
}
db.SaveChanges();
}
}
private void ChangeItemButton_Click(object sender, MouseButtonEventArgs e)
{
if (SystemContext.isChangeTitleName)
{
SystemContext.isChangeTitleName = false;
return;
}
parentWindow = Window.GetWindow(this);
using (var db = new test123Entities1())
{
if (SystemContext.isFromFolder)
{
SystemContext.SelectedItem = (sender as Border).Tag as Items;
Items item;
item = SystemContext.SelectedItem;
Grid grid = (sender as Border).Child as Grid;
Image selectedImage = grid.Children.OfType<Image>().FirstOrDefault(si => si.Name == "selectedImage");
Image unselectedImage = grid.Children.OfType<Image>().FirstOrDefault(si => si.Name == "unselectedImage");
if (item.IsSelected == 1)
{
selectedImage.Visibility = Visibility.Hidden;
unselectedImage.Visibility = Visibility.Visible;
item.IsSelected = 0;
}
else
{
selectedImage.Visibility = Visibility.Visible;
unselectedImage.Visibility = Visibility.Hidden;
item.IsSelected = 1;
}
db.Items.AddOrUpdate(item);
db.SaveChanges();
return;
}
else
{
SystemContext.Item = (sender as Border).Tag as Items;
SystemContext.isChange = true;
SystemContext.PageForLoadContent = this;
switch (SystemContext.Item?.IType)
{
case "Passport":
var passportWindow = new PassportWindow();
passportWindow.Closed += Window_Closed;
passportWindow.ShowDialog();
break;
case "INN":
var innWindow = new InnWindow();
innWindow.Closed += Window_Closed;
innWindow.ShowDialog();
break;
case "SNILS":
var snilsWindow = new SnilsWindow();
snilsWindow.Closed += Window_Closed;
snilsWindow.ShowDialog();
break;
case "Polis":
var polisWindow = new PolisWindow();
polisWindow.Closed += Window_Closed;
polisWindow.ShowDialog();
break;
case "Photo":
var photoWindow = new PhotoWindow();
photoWindow.Closed += Window_Closed;
photoWindow.ShowDialog();
break;
case "CreditCard":
var creditCardWindow = new CreditCardWindow();
creditCardWindow.Closed += Window_Closed;
creditCardWindow.ShowDialog();
break;
case "Folder":
SystemContext.Folder = SystemContext.Item;
Frame openFolderPageFrame = parentWindow.FindName("openPageFrame") as Frame;
FolderContentPage folderContentPage = new FolderContentPage();
openFolderPageFrame.Content = folderContentPage;
break;
case "Collection":
Frame openCollectionPageFrame = parentWindow.FindName("openPageFrame") as Frame;
CollectionContentPage collectionContentPage = new CollectionContentPage();
openCollectionPageFrame.Content = collectionContentPage;
break;
default:
MessageBox.Show("Ошибка при открытии документа");
break;
}
}
SystemContext.isFromFolder = false;
}
}
private void ChangeTitleNameButton_Click(object sender, MouseButtonEventArgs e)
{
if (SystemContext.isFromFolder)
return;
if (sender is TextBlock)
SystemContext.Item = (sender as TextBlock).Tag as Items;
else
SystemContext.Item = (sender as Border).Tag as Items;
SystemContext.isChangeTitleName = true;
ChangeItemTitleNameWindow changeItemTitleNameWindow = new ChangeItemTitleNameWindow();
changeItemTitleNameWindow.Closed += Window_Closed;
changeItemTitleNameWindow.ShowDialog();
}
private void addNewDocumentButton_Click(object sender, RoutedEventArgs e)
{
if (SystemContext.isFromFolder)
{
using (var db = new test123Entities1())
{
List<Items> items = null;
try
{
items = (from i in db.Items
where i.UserId == SystemContext.User.Id
select i).ToList<Items>();
}
catch
{
MessageBox.Show("Ошибка при иницианлизации выбранных документов");
return;
}
foreach (var item in items)
AddInFolder(item);
}
parentWindow = Window.GetWindow(this);
Frame openFolderPageFrame = parentWindow.FindName("openPageFrame") as Frame;
FolderContentPage folderContentPage = new FolderContentPage();
openFolderPageFrame.Content = folderContentPage;
SystemContext.isFromFolder = false;
return;
}
SystemContext.PageForLoadContent = this;
addNewDocumentBufferWindow addNewDocumentBufferWindow = new addNewDocumentBufferWindow();
addNewDocumentBufferWindow.ShowDialog();
}
private void MenuItemLock_Click(object sender, RoutedEventArgs e)
{
Border border = (Border)((ContextMenu)(sender as MenuItem).Parent).PlacementTarget;
Grid grid = border.Child as Grid;
SystemContext.Item = border.Tag as Items;
Items item;
item = SystemContext.Item;
Image LockImage = grid.Children.OfType<Image>().FirstOrDefault(li => li.Name == "LockImage");
using (var db = new test123Entities1())
{
if (item.IPriority == 1)
{
LockImage.Visibility = Visibility.Hidden;
item.IPriority = 0;
}
else
{
LockImage.Visibility = Visibility.Visible;
item.IPriority = 1;
}
db.Items.AddOrUpdate(item);
db.SaveChanges();
}
LoadContent();
}
private void MenuItemHide_Click(object sender, RoutedEventArgs e)
{
Border border = (Border)((ContextMenu)(sender as MenuItem).Parent).PlacementTarget;
SystemContext.Item = border.Tag as Items;
Items item;
item = SystemContext.Item;
using (var db = new test123Entities1())
{
if (SystemContext.isFromHiddenFiles)
{
if (item.IType == "Folder")
{
List<Items> itemsInFolder = (from i in db.Items
where i.UserId == SystemContext.User.Id && i.FolderId == item.Id
select i).ToList<Items>();
foreach (var itemInFodler in itemsInFolder)
{
itemInFodler.IsHidden = 0;
}
}
item.IsHidden = 0;
}
else
{
if (item.IType == "Folder")
{
List<Items> itemsInFolder = (from i in db.Items
where i.UserId == SystemContext.User.Id && i.FolderId == item.Id
select i).ToList<Items>();
foreach (var itemInFodler in itemsInFolder)
{
itemInFodler.IsHidden = 1;
}
}
item.IsHidden = 1;
}
db.Items.AddOrUpdate(item);
db.SaveChanges();
}
LoadContent();
}
private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
{
Border border = (Border)((ContextMenu)(sender as MenuItem).Parent).PlacementTarget;
SystemContext.Item = border.Tag as Items;
Items item = new Items();
item = SystemContext.Item;
using (var db = new test123Entities1())
{
if (item.IType == "Folder")
{
List<Items> itemsInFolder = (from i in db.Items
where i.UserId == SystemContext.User.Id && i.FolderId == item.Id
select i).ToList<Items>();
foreach(var itemInFodler in itemsInFolder)
{
db.Entry(itemInFodler).State = System.Data.Entity.EntityState.Deleted;
}
}
else if (item.IType == "Collection")
{
List<Photo> photoesInCollecion = (from p in db.Photo
where p.CollectionID == SystemContext.Item.Id
select p).ToList<Photo>();
foreach (var photoInCollecion in photoesInCollecion)
{
db.Entry(photoInCollecion).State = System.Data.Entity.EntityState.Deleted;
}
}
db.Entry(item).State = System.Data.Entity.EntityState.Deleted;
db.SaveChanges();
}
LoadContent();
}
private void Window_Closed(object sender, EventArgs e)
{
LoadContent();
}
}
}
|
e4ca7646d72946194b05801960247e27
|
{
"intermediate": 0.4311530590057373,
"beginner": 0.46480709314346313,
"expert": 0.10403983294963837
}
|
11,867
|
I am doing a c# unit testing using MSTest
it doesn’t give me an error now but it doesn’t delete the element, I tried this inside the unit test method:
DataGrid dataGrid = new DataGrid();
dataGrid.SelectionUnit = DataGridSelectionUnit.CellOrRowHeader;
ObservableCollection<ItemDatagridItems> testCollection = new ObservableCollection<ItemDatagridItems>
{
new ItemDatagridItems(1, 1, "a", "desc a", 1.0, 100.0),
new ItemDatagridItems(2, 2, "b", "desc b", 2.0, 200.0),
new ItemDatagridItems(3, 3, "c", "desc c", 3.0, 300.0),
};
dataGrid.ItemsSource = testCollection;
DataGridTextColumn column = new DataGridTextColumn();
dataGrid.Columns.Add(column);
dataGrid.SelectedCells.Add(new DataGridCellInfo(testCollection[1], column));
System.Diagnostics.Debug.WriteLine(dataGrid.SelectedCells[0].Item.ToString());
if (dataGrid.SelectedCells[0].Item is ItemDatagridItems item)
{
testCollection.Remove(item);
System.Diagnostics.Debug.WriteLine(“removed”);
}
and the output was this:
{DependencyProperty.UnsetValue}
But the element wasn’t removed.
Why this element wasn't removed?
|
d55499fe2a08ba279d1e4720a071bd12
|
{
"intermediate": 0.6994169354438782,
"beginner": 0.22398991882801056,
"expert": 0.07659316807985306
}
|
11,868
|
I am trying to plot a density contour in plotly and I want the values below a specific densitiy not to be colored, but the values above the threshold to be colored. How do I do that?
|
9b81edc656084e8e5ba8ba37471b138d
|
{
"intermediate": 0.4004185199737549,
"beginner": 0.22767271101474762,
"expert": 0.3719088137149811
}
|
11,869
|
Hello could you make a driver in selenium python, then open google chrome
|
58e1c96fe3260ff054b70880314e5215
|
{
"intermediate": 0.43108469247817993,
"beginner": 0.12454675137996674,
"expert": 0.44436854124069214
}
|
11,870
|
can you make this somehow dispaly the curve once generated? maybe even a feature to generate new ones in the click of a button and display them? i want to find the perfect settings.
import numpy as np
import csv
# Configuration
start_point = np.array([1000, 201]) # Starting point (a)
end_point = np.array([1700, 700]) # Ending point (b)
num_control_points = 5 # Number of control points
offset_range = 500 # Maximum offset range for control points
screen_dimensions = (1920, 1080) # Screen dimensions (default: 1080p)
num_selected_points = 15 # Number of points to select from the curve
def bezier_curve(control_points, num_points):
t = np.linspace(0, 1, num_points)
n = len(control_points) - 1
curve = np.zeros((num_points, 2))
for i in range(num_points):
for j in range(n + 1):
curve[i] += (
control_points[j]
* np.math.comb(n, j)
* (1 - t[i]) ** (n - j)
* t[i] ** j
)
return curve
def generate_random_control_points(start, end, num_control_points, offset_range):
line = np.linspace(start, end, num_control_points + 2)
control_points = []
for point in line[1:-1]:
offset = np.random.uniform(-offset_range, offset_range, size=2)
control_points.append(point + offset)
return np.array(control_points)
# Generate random control points
control_points = generate_random_control_points(start_point, end_point, num_control_points, offset_range)
# Generate the Bézier curve
num_points = 100
curve = bezier_curve(np.vstack((start_point, control_points, end_point)), num_points)
# Apply screen boundary constraints
screen_width, screen_height = screen_dimensions
curve[:, 0] = np.clip(curve[:, 0], 0, screen_width)
curve[:, 1] = np.clip(curve[:, 1], 0, screen_height)
# Select a subset of points from the curve
selected_indices = np.linspace(0, len(curve) - 1, num_selected_points, dtype=int)
selected_points = curve[selected_indices]
# Convert motion data to CSV-formatted string
csv_string = ''
csv_string += '\n'.join([f'{row[0]},{row[1]}' for row in selected_points])
# Print the CSV-formatted string
print(csv_string)
|
ac3f0ad55467b0df4de0ee952138f49b
|
{
"intermediate": 0.22693876922130585,
"beginner": 0.6722306609153748,
"expert": 0.10083058476448059
}
|
11,871
|
import {
LineStyle,
Timeline,
TrendingUp,
PersonOutline,
Inventory,
Paid,
Assessment,
MailOutline,
Forum,
Message,
Work,
ReportGmailerrorred,
} from "@mui/icons-material";
import { Link } from "react-router-dom";
const Sidebar = () => {
const menuItems = [
{
title: "Dashboard",
items: [
{ label: "Home", icon: LineStyle, active: true },
{ label: "Analytics", icon: Timeline },
{ label: "Sales", icon: TrendingUp },
],
},
{
title: "Quick Menu",
items: [
{ label: "Users", icon: PersonOutline, link: "/user" },
{ label: "Products", icon: Inventory },
{ label: "Transactions", icon: Paid },
{ label: "Report", icon: Assessment },
],
},
{
title: "Notifications",
items: [
{ label: "Mail", icon: MailOutline },
{ label: "Feedback", icon: Forum },
{ label: "Message", icon: Message },
],
},
{
title: "Staff",
items: [
{ label: "Manage", icon: Work },
{ label: "Analytics", icon: Timeline },
{ label: "Report", icon: ReportGmailerrorred },
],
},
];
return (
<div className="sidebar">
<div className="sidebarContainer">
{menuItems.map((menuItem, index) => (
<div className="sidebarContainer__menu" key={index}>
<h3 className="sidebarContainer__title">{menuItem.title}</h3>
<ul className="sidebarContainer__list">
{menuItem.items.map((item, i) => (
<li
className={`sidebarContainer__listItem ${
item.active ? "active" : ""
}`}
>
<Link to={item.link !== undefined ? item.link : ""} key={i}>
<item.icon className="sidebarContainer__listIcon" />
{item.label}{" "}
</Link>
</li>
))}
</ul>
</div>
))}
</div>
</div>
);
};
export default Sidebar;
Property 'active' does not exist on type '{ label: string; icon: OverridableComponent<SvgIconTypeMap<{}, "svg">> & { muiName: string; }; active: boolean; } | { label: string; icon: OverridableComponent<...> & { ...; }; active?: undefined; } | { ...; } | { ...; }'.
Property 'active' does not exist on type '{ label: string; icon: OverridableComponent<SvgIconTypeMap<{}, "svg">> & { muiName: string; }; link: string; }'.ts(2339)
Property 'link' does not exist on type '{ label: string; icon: OverridableComponent<SvgIconTypeMap<{}, "svg">> & { muiName: string; }; active: boolean; } | { label: string; icon: OverridableComponent<...> & { ...; }; active?: undefined; } | { ...; } | { ...; }'.
Property 'link' does not exist on type '{ label: string; icon: OverridableComponent<SvgIconTypeMap<{}, "svg">> & { muiName: string; }; active: boolean; }'.ts(2339)
|
55833f71b6e22ab17bfd41941156e39c
|
{
"intermediate": 0.29868724942207336,
"beginner": 0.5078723430633545,
"expert": 0.19344034790992737
}
|
11,872
|
I would like to write a VBA code to comlplete this process:
I have two sheets named 'Reminders' and 'Events' within the same workbook.
In the 'Reminders' sheet the following columns are entered as follows with each row pertaining to a specific data entry.
Column D - contains text summaries of reminders
Column E - contains text detailed info of reminders
Column F - contains date entries for the reminders
Column G - contains text entries of Contractor Codes
Column H - contains formula generated Contrator Names
In the 'Events' sheet the following columns are entered as follows with each row pertaining to a specific data entry.
Column B - contains date entries for the events
Column C - contains text detailed info of events
Column D - contains text Notes of events
In the 'Reminders' sheet, I would like to click on a cell and make the row my target to copy.
Cells in the same row of column E, column F and column H will be the primary values required.
The last empty row in sheet 'Events' must then recive the values from sheet 'Reminders' in this order.
last empty cell in sheet 'Events' column B will recieve the value of cell value of column F from my target row in sheet 'Reminders'
The same row cell in sheet 'Events' column C will recieve the value of cell value of column E from my target row in sheet 'Reminders'
The same row cell in sheet 'Events' column D will recieve the value of cell value of column H from my target row in sheet 'Reminders'
|
d33cf34cae3a1b3bb1746aaa5557bbdb
|
{
"intermediate": 0.4294598698616028,
"beginner": 0.3124927878379822,
"expert": 0.2580473721027374
}
|
11,873
|
make unit testing using mstest in c# of this code
public static List<T> GetControls<T>(Window w, int count, string name)
{
List<T> controls = new List<T>();
for (int i = 1; i <= count; i++)
{
controls.Add((T)w.FindName($"{name}{i:D2}"));
}
return controls;
}
|
3c4993fe13ba080057a68e78f3483aef
|
{
"intermediate": 0.4763583242893219,
"beginner": 0.3179328143596649,
"expert": 0.20570887625217438
}
|
11,874
|
in dao.js
exports.pageContent = (pageid) => {
return new Promise((resolve, reject) => {
const sql = `
SELECT
title AS title,
authorId AS authorId,
publishDate AS publishDate
blocks AS blocks
FROM
pages
WHERE
id=?`;
db.get(sql, [pageid], (err, row) => { //db.get returns only the first element matching the query
if (err) {
reject(err);
return;
}
if (row == undefined) {
resolve({ error404: "Page not found." }); //Page not found
}
else {
const objBlocks = JSON.parse(row.blocks);
const info = { title: row.title, authorId: row.authorId, publishDate: dayjs(row.publishDate), blocks: objBlocks};
resolve(info);
}
});
});
};
the table pages has a column called blocks. the content of the field linked to id=10 is [{"blockType":"Header","content":"Brasilh3333"},{"blockType":"Image","content":"http://localhost:3000/images/brasil.jpg"}]
is this function right?
|
01536b09bbc763c9a02afe03807021f8
|
{
"intermediate": 0.48708635568618774,
"beginner": 0.3396475911140442,
"expert": 0.17326605319976807
}
|
11,875
|
I wrote this unit test but it gave me the error actual value is 3 instead of 0, it should be 0 as I send name as "a". What could be the problem?
[TestMethod]
public void TestGetControls()
{
Window window = new Window();
int count = 3;
List<Button> expected = new List<Button>();
for (int i = 0; i < count; i++)
{
Button button = new Button();
button.Name = $"Button{i}";
expected.Add(button);
}
StackPanel panel = new StackPanel();
foreach (Button button in expected)
{
panel.Children.Add(button);
}
window.Content = panel;
List<Button> buttons = Collections.GetControls<Button>(window, count, "a");
Assert.AreEqual(0, buttons.Count);
}
public static List<T> GetControls<T>(Window w, int count, string name)
{
List<T> controls = new List<T>();
for (int i = 1; i <= count; i++)
{
controls.Add((T)w.FindName($"{name}{i:D2}"));
}
return controls;
}
|
534dd13e462112c708d695a4ce6e2341
|
{
"intermediate": 0.43501293659210205,
"beginner": 0.35703277587890625,
"expert": 0.2079542577266693
}
|
11,876
|
import {
LineStyle,
Timeline,
TrendingUp,
PersonOutline,
Inventory,
Paid,
Assessment,
MailOutline,
Forum,
Message,
Work,
ReportGmailerrorred,
} from "@mui/icons-material";
import { Link } from "react-router-dom";
const Sidebar = () => {
const menuItems = [
{
title: "Dashboard",
items: [
{ label: "Home", icon: LineStyle, active: true },
{ label: "Analytics", icon: Timeline },
{ label: "Sales", icon: TrendingUp },
],
},
{
title: "Quick Menu",
items: [
{ label: "Users", icon: PersonOutline, link: "./users" },
{ label: "Products", icon: Inventory },
{ label: "Transactions", icon: Paid },
{ label: "Report", icon: Assessment },
],
},
{
title: "Notifications",
items: [
{ label: "Mail", icon: MailOutline },
{ label: "Feedback", icon: Forum },
{ label: "Message", icon: Message },
],
},
{
title: "Staff",
items: [
{ label: "Manage", icon: Work },
{ label: "Analytics", icon: Timeline },
{ label: "Report", icon: ReportGmailerrorred },
],
},
];
return (
<div className="sidebar">
<div className="sidebarContainer">
{menuItems.map((menuItem, index) => (
<div className="sidebarContainer__menu" key={index}>
<h3 className="sidebarContainer__title">{menuItem.title}</h3>
<ul className="sidebarContainer__list">
{menuItem.items.map((item, i) =>
item.link ? (
<Link to={item.link}>
<li
className={`sidebarContainer__listItem ${
item.active !== undefined ? "active" : ""
}`}
key={i}
>
<item.icon className="sidebarContainer__listIcon" />
{item.label}
</li>
</Link>
) : (
<li
className={`sidebarContainer__listItem ${
item.active !== undefined ? "active" : ""
}`}
key={i}
>
<item.icon className="sidebarContainer__listIcon" />
{item.label}
</li>
)
)}
</ul>
</div>
))}
</div>
</div>
);
};
export default Sidebar;
correct this code beceuse
Property 'link' does not exist on type '{ label: string; icon: OverridableComponent<SvgIconTypeMap<{}, "svg">> & { muiName: string; }; active: boolean; } | { label: string; icon: OverridableComponent<...> & { ...; }; active?: undefined; } | { ...; } | { ...; }'.
Property 'link' does not exist on type '{ label: string; icon: OverridableComponent<SvgIconTypeMap<{}, "svg">> & { muiName: string; }; active: boolean; }'.ts(2339)
|
227fd03da763c4a6535a5d408ab0c430
|
{
"intermediate": 0.31135737895965576,
"beginner": 0.5133899450302124,
"expert": 0.17525264620780945
}
|
11,877
|
I want you to create a text adventure game where you describe the scene and I am given options of what to do. I want this game to be programed in html CSS and JavaScript so that it can be played on a browser. Please give the entire code
This game will have 3 rooms for now
Writing notes for game
I will start at 18 years old mentally I am 18 years old physically I Weigh 155 lbs I have a height of 5' 9" my name is Erik
Please keep the story as pg. as possible while preserving the previous parts
In the top right hand corner I want these stats displayed at all times
Name: Erik
Age (physical): Var PAge
Age (mental): Var MAge
Height: Var Height in cm Weight: Var weight in lbs
Inventory: (multiple variables using an array) (also allow me to do all actions with items from my inventory here for example being able to drink or drop potions or being able to equip equipment into a slot )
Mental traits: (multiple variables using an array)
Physical traits: (multiple variables using an array)
Clothing: (current clothing not sure how to track)
HP: (Page * 3) + (equipment modifiers)
Defence: (Page * 0.5) + (equipment modifiers)
Attack: (Page * 1.5) + (equipment modifiers)
Head equipment slot: hat
Chest equipment slot: short sleave short
Leg equipment slot: jeans
Feet equipment slot: shoes
In the top left hand corner I want all of these listed.
The description of the room
The description and names of any interactive items (also the ability to use those items from here)
make the code so I can make consumable items, storage boxes and rooms like this and then update the items to work within the new system also make the physical age regression potion work and keep as much other functionality as possible
const daycareroom = {
name: “daycare”
class: room
north: elementary class room
south: wall
east: playroom
west: wall
interactive items: storage box (daycare)
description: this is the room you spawn in please explore the two other rooms in this test
};
const classroom= {
name: “classroom”
class: room
north: wall
south: daycare
east: wall
west: wall
interactive items: N/A
description: this is the classroom
};
Const playroom= {
Name: “playroom”
North: wall
South: wall
East: wall
West: daycare
Interactive items: N/A
Description: a normal play room
};
const mentalAgePotion = {
name: "Mental Age Regression Potion",
class: "Consumable",
type: "1 use",
effect when used : "-1 var MAge",
description: "A potion that regresses the drinker's mental age.",
};
Const BattleArmor (chest) = {
name: "Battle Armor",
class: "Equipment",
type: "chest",
effect when worn: "-1 var PAge +5 var Attack",
description: "A Armor that while wearing will reduce the wearers age by 1 year but give +5 atk",
};
Please create the code so that storage box can be accessed from the corresponding room in the location allowing you to see it inventory when open and not being able to see its inventory when closed using this code. This code needs to work with anything that is class: storage keep in mind some rooms will have multiple storage boxes and others will have none also make it so when when there is a storage box within the room a button will appear
Const StorageBox(Daycare)= {
Name: storage box (daycare)
Class: storage
Inverntory: [Mental Age Regression Potion, Battle Armor ],
Location: daycare
Description for room (open) : There is a cute open playful box in the corner
Description for room (closed): There is a cute closed playful box in the corner
};
Const StorageBox(playroom)= {
Name: storage box (playroom)
Class: storage
Inventory: [empty]
Location: playroom
Description for room (open): an open empty box
Description for room (closed): a closed box
};
I also want to be able to spawn creatures with this format
Const testMonster(classroom)={
Name: bottle monster
Stats : { HP=20: Attack = 5: defence = 5:}
Attacks: {
Attack 1: {
name: bottle slam
Effect: (-1) – (Attack stat)
Targets: player
Description: in this attack the bottle rams into the player
}
Attack 2: {
name: bottle rush
Effect: (-1) – (Attack stat)
Targets: player
Description: the bottle rushes at the player hitting there guts
}
}
Location: classroom
Spawn conditions: first time only
}
|
0613d811ab3841dd62f8cdc5f82dd0e7
|
{
"intermediate": 0.36691245436668396,
"beginner": 0.36253443360328674,
"expert": 0.2705530822277069
}
|
11,878
|
create antd tabs in react that each tab has a gray check, if all the form items in the tab are filled the check will be green, the tabs are inside a form component
|
ab9e38468af0f12a9dc3e2dd98ba2105
|
{
"intermediate": 0.3671697974205017,
"beginner": 0.15104487538337708,
"expert": 0.4817853271961212
}
|
11,879
|
in bash how would I add a password and If I typed it I want it to show like ****
|
be23b7829bc0e073b6a98e6ed716c862
|
{
"intermediate": 0.43718940019607544,
"beginner": 0.22949449717998505,
"expert": 0.33331605792045593
}
|
11,880
|
I got this error :
System.InvalidOperationException: No NameScope found for register Name 'Button01'.
From this code:
Window window = new Window();
int count = 3;
List<Button> expected = new List<Button>();
for (int i = 1; i <= count; i++)
{
Button button = new Button();
button.Name = $"Button{i:D2}";
window.RegisterName(button.Name, button);
expected.Add(button);
}
StackPanel panel = new StackPanel();
foreach (Button button in expected)
{
panel.Children.Add(button);
}
window.Content = panel;
|
653263d84ad081d2605c48029c62f969
|
{
"intermediate": 0.3711680769920349,
"beginner": 0.3505263924598694,
"expert": 0.2783055305480957
}
|
11,881
|
Quiero saber como realizar una query bidireccional en neo4j usando match colocando un parametro de busqueda concreto ejemplo:
match match (a:Account {id: '70003448'})-[r:HAS_TRANSFERED]->(a2:Account) RETURN a,r,a2
|
3ff67dfc26f5f78a8b165fdacfc4b610
|
{
"intermediate": 0.4913221299648285,
"beginner": 0.11479856073856354,
"expert": 0.39387935400009155
}
|
11,882
|
hi
|
58941bf7ee99985b69ce49f5037e0f00
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
11,883
|
Write code that will remove all commented lines in the code.
Comments in code begin with the following characters
//
this is a one line comment. A line starting with these characters must be removed from their code
/*
*/
this is a multi-line comment. The lines between these characters must be removed from the code.
/**
*/
this is also a multi-line comment. The lines between these characters must be removed from the code.
|
843817955a3505c718b13b928ab23373
|
{
"intermediate": 0.373452365398407,
"beginner": 0.22577354311943054,
"expert": 0.40077415108680725
}
|
11,884
|
make unit testings in c# and MSTEST for the next code:
public static List<T> GetControls<T>(Window w, int count, string name)
{
List<T> controls = new List<T>();
for (int i = 1; i <= count; i++)
{
controls.Add((T)w.FindName($"{name}{i:D2}"));
}
return controls;
}
|
3444b2138b16d9e8da1a847032dd6401
|
{
"intermediate": 0.5054234266281128,
"beginner": 0.3029111325740814,
"expert": 0.1916653960943222
}
|
11,885
|
create an antd button in react that moves me to the next antd tabl, I have 5 tabs and each one will have this button except the last one
|
efc025c6336a5f62b3ba569dec3d6ccf
|
{
"intermediate": 0.45781439542770386,
"beginner": 0.13065218925476074,
"expert": 0.4115334153175354
}
|
11,886
|
i wanna set a date in java and set in a class
|
42ee56af7dd88f8747774148db9ec756
|
{
"intermediate": 0.3699568510055542,
"beginner": 0.4881804287433624,
"expert": 0.14186275005340576
}
|
11,887
|
fix this error File "D:\Pfa\projet f_nf_flask\app.py", line 134, in gen
cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 255), 2)
cv2.error: OpenCV(4.7.0) :-1: error: (-5:Bad argument) in function 'rectangle'
> Overload resolution failed:
> - img is not a numpy array, neither a scalar
> - Expected Ptr<cv::UMat> for argument 'img'
> - img is not a numpy array, neither a scalar
> - Expected Ptr<cv::UMat> for argument 'img'
in this code
# from flask import Flask, render_template, Response
# import cv2
# import numpy as np
# from keras.models import load_model
# from waitress import serve
# import tensorflow as tf
# import imutils
# model = load_model('models\Xrchi1')
# face_cascade = cv2.CascadeClassifier('cascade\haarcascade_frontalface_default.xml')
# prototxt = 'cascade\deploy.prototxt'
# model1 = 'cascade\modeldetect.caffemodel'
# net = cv2.dnn.readNetFromCaffe(prototxt, model1)
# app = Flask(__name__)
# @app.route('/')
# def index():
# return render_template('index.html')
# def detect_faces(frame):
# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# return faces
# def gen():
# cap = cv2.VideoCapture(1)
# while True:
# ret, frame = cap.read()
# if not ret:
# continue
# faces = detect_faces(frame)
# for (x, y, w, h) in faces:
# face = frame[y:y+h, x:x+w]
# face = cv2.resize(face, (84, 119))
# face = tf.expand_dims(face, axis=0)
# face = tf.cast(face, tf.float32)
# face /= 255.0
# prediction = model.predict(face)
# prediction = (prediction < 0.35)
# color = (0, 0, 255) if prediction == False else (0, 255, 0)
# label = "No-Focus" if prediction == False else "Focus"
# cv2.rectangle(frame, (x, y), (x+w, y+h), color, 2)
# cv2.putText(frame, label, (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
# _, jpeg = cv2.imencode('.jpg', frame)
# frame = jpeg.tobytes()
# yield (b'--frame\r\n'
# b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
# cap.release()
# cv2.destroyAllWindows()
# @app.route('/video_feed')
# def video_feed():
# return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')
# if __name__ == '__main__':
# app.run(host='0.0.0.0', port=8080)
from flask import Flask, render_template, Response
import cv2
import numpy as np
from keras.models import load_model
from waitress import serve
import tensorflow as tf
import imutils
#import matplotlib.pyplot as plt
model = load_model('models\Xrchi1')
face_cascade=cv2.CascadeClassifier('cascade\haarcascade_frontalface_default.xml')
prototxt = 'cascade\deploy.prototxt'
model1 = 'cascade\modeldetect.caffemodel'
net = cv2.dnn.readNetFromCaffe(prototxt, model1)
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
def gen():
# Accéder à la webcam
cap = cv2.VideoCapture(0)
#width = 1000
#height = 900
# Set the scale factors
#cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
#cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
while True:
ret, frame = cap.read()
print(ret)
if not ret:
continue
scale_percent = 120 # Zoom factor (increase to zoom in, decrease to zoom out)
width = int((frame.shape[1] * scale_percent / 100)-180)
height = int((frame.shape[0] * scale_percent / 100)-150)
frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_LINEAR)
#frame = cv2.resize(frame, (frame.shape[1]-100, frame.shape[0]-90))
#frame = imutils.resize(frame, width=300, height=300)
#frame=np.resize(frame,(400,400,3))
#print(frame.shape, face.shape)
(h, w) = frame.shape[:2]
#print(h,w)
blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
net.setInput(blob)
detections = net.forward()
confidence = detections[0, 0, 0, 2]
for i in range(0, detections.shape[2]):
# extract the confidence (i.e., probability) associated with the prediction
confidence = detections[0, 0, i, 2]
# filter out weak detections by ensuring the `confidence` is
# greater than the minimum confidence threshold
if confidence > 0.5:
# compute the (x, y)-coordinates of the bounding box for the object
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# draw the bounding box of the face along with the associated probability
text = "{:.2f}%".format(confidence * 100)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 255, 255), 2)
face = frame[startY:endY, startX:endX]
#print(face)
print("face=",face.shape)
face=np.resize(frame,(1,119,84,3))
face=tf.data.Dataset.from_tensor_slices(face).batch(1)
print(face)
prediction = model.predict(face)
print(prediction)
prediction=(prediction<0.4)
#print(prediction)
#print(prediction==[False])
color = (0, 0, 255) if prediction == False else (0, 255, 0)
label = "Fraud" if prediction == False else "Non-Fraud"
cv2.putText(frame, label, (startX, startY-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
_, jpeg = cv2.imencode('.jpg', frame)
frame = jpeg.tobytes()
#print(type(frame))
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
cap.release()
cv2.destroyAllWindows()
@app.route('/video_feed')
def video_feed():
return Response(gen(),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '_main_':
app.run( host='0.0.0.0', port=8080)
|
61ee933ae5b90e4286e1b35de194048a
|
{
"intermediate": 0.4428677260875702,
"beginner": 0.36046484112739563,
"expert": 0.19666747748851776
}
|
11,888
|
I need to collect daily income twice , i need to open my metamask from my computer and then i need to click some buttons in order. I want to automate this task daily based on time . Security is also important for me , how can i do this on my computer ? I use macbook
|
a75545b5a6f3931a44840d7a56d73bac
|
{
"intermediate": 0.4337193965911865,
"beginner": 0.2852509319782257,
"expert": 0.28102967143058777
}
|
11,889
|
Create a python program that will graph in real time how many messages per minute in a Twitch chat
|
c2d04a1e40f4cb1fb38ee7c40ac78306
|
{
"intermediate": 0.36672845482826233,
"beginner": 0.10851360857486725,
"expert": 0.5247579216957092
}
|
11,890
|
C:\Users\AshotxXx\PycharmProjects\ByteCodes\MatchBytesCodeSimilar\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 79, in <module>
similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 43, in find_similar_contracts
source_code = get_contract_source_code(reference_address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 23, in get_contract_source_code
return remove_comments(source_code)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 29, in remove_comments
for line in source_code.readlines():
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'readlines'
Process finished with exit code 1
|
75b6dc07cf8fd21873df42364bee5268
|
{
"intermediate": 0.43359869718551636,
"beginner": 0.2956855297088623,
"expert": 0.27071577310562134
}
|
11,891
|
i'm trying to add an radar from my angular app hosted on http://localhost:4200 the backend is many microservices connected to a getaway on http://localhost:8888/ so i got the next error : Access to XMLHttpRequest at 'http://localhost:8888/RADAR-SERVER/radars' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.:
get method works fine
|
e75919c0f998a17d4224f2ef59d994d7
|
{
"intermediate": 0.4032634198665619,
"beginner": 0.37468379735946655,
"expert": 0.22205278277397156
}
|
11,892
|
type ChartProps = {
title: string;
data: { name: string; "Active User": number |'sales': number}[];
dataKey: string;
grid: boolean;
};
make data generic
|
bd814de920b32459d1bc31b7c522f128
|
{
"intermediate": 0.4374147355556488,
"beginner": 0.26498866081237793,
"expert": 0.29759663343429565
}
|
11,893
|
import re
import requests
import difflib
API_KEY = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS"
BASE_URL = "https://api.bscscan.com/api"
similarity_threshold = 0.5
def get_contract_source_code(address):
params = {
"module": "contract",
"action": "getsourcecode",
"address": address,
"apiKey": API_KEY
}
response = requests.get(BASE_URL, params=params)
data = response.json()
if data["status"] == "1":
source_code = data["result"][0]["SourceCode"]
return remove_comments(source_code)
else:
return None
def remove_comments(source_code):
clean_code = ""
for line in source_code.splitlines():
if line.startswith(__prefix='//'):
line = line[:line.index("//")].rstrip(" ")
clean_code += line
return clean_code
def jaccard_similarity(str1, str2):
a = set(str1.split())
b = set(str2.split())
c = a.intersection(b)
return float(len(c)) / (len(a) + len(b) - len(c))
def find_similar_contracts(reference_addresses, candidate_addresses):
reference_source_codes = {}
for reference_address in reference_addresses:
source_code = get_contract_source_code(reference_address)
if source_code is not None:
reference_source_codes[reference_address] = source_code
if not reference_source_codes:
print("No source code found for reference contracts")
return []
similar_contracts = {}
for address in candidate_addresses:
candidate_source_code = get_contract_source_code(address)
if candidate_source_code is not None:
for reference_address, reference_source_code in reference_source_codes.items():
similarity = jaccard_similarity(candidate_source_code, reference_source_code)
if similarity >= similarity_threshold:
if reference_address not in similar_contracts:
similar_contracts[reference_address] = [(address, similarity)]
else:
similar_contracts[reference_address].append((address, similarity))
return similar_contracts
def print_code_difference(reference_code, candidate_code):
reference_lines = reference_code.splitlines()
candidate_lines = candidate_code.splitlines()
diff = difflib.unified_diff(reference_lines, candidate_lines)
for line in diff:
print(line)
if __name__ == "__main__":
reference_addresses = ["0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb"]
candidate_addresses = ["0x4401E60E39F7d3F8D5021F113306AF1759a6c168"]
similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses)
print("Contracts with similar source code (ignoring comments):")
for reference_address, similar_addresses in similar_contracts.items():
reference_code = get_contract_source_code(reference_address)
print(f"Reference contract: {reference_address}")
for address, similarity in similar_addresses:
candidate_code = get_contract_source_code(address)
print(f"Similar contract: {address} with a similarity of {similarity:.2f}")
if similarity < 1.0:
print("Code differences:")
print_code_difference(reference_code, candidate_code)
print("\n")
The code above gives an error
C:\Users\AshotxXx\PycharmProjects\ByteCodes\MatchBytesCodeSimilar\venv\Scripts\python.exe C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py
Traceback (most recent call last):
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 82, in <module>
similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 46, in find_similar_contracts
source_code = get_contract_source_code(reference_address)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 23, in get_contract_source_code
return remove_comments(source_code)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\AshotxXx\PycharmProjects\ByteCodes\CodeDifferences\main.py", line 31, in remove_comments
if line.startswith(__prefix='//'):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: str.startswith() takes no keyword arguments
Process finished with exit code 1
Fix it. Use startswith
|
b329f4a717928a6532cf8090c62bc232
|
{
"intermediate": 0.2991412878036499,
"beginner": 0.4512068033218384,
"expert": 0.24965187907218933
}
|
11,894
|
hi!
|
f51a5ba64827526fe451b543e844d308
|
{
"intermediate": 0.32477712631225586,
"beginner": 0.26637697219848633,
"expert": 0.4088459014892578
}
|
11,895
|
can you take a look at this link https://drive.google.com/file/d/17m0rz0EhkpazFPeMvUi99Ea6En8kp1z3/view?usp=sharing
|
0b6e822d5123432b63c796e94948f3a6
|
{
"intermediate": 0.27230116724967957,
"beginner": 0.20516587793827057,
"expert": 0.5225329995155334
}
|
11,896
|
It is well known that the application of nitrogen (i.e., fertilizer) to corn increases crop yield. However, an optimization between the applied amount of fertilizer and the corn crop yield should be performed to increase the annual revenue. Accordingly, the below observations are collected from the field.
Nitrogen (ton/hectare) (X) Corn Crop Yield (ton/hectare) (Y)
0 5.1
0.36 7.6
0.46 6.4
0.6 7.8
0.73 9.0
0.75 9.5
0.87 11.3
1.01 12.7
1.12 9.5
1.18 12.7
Based on this data and by using 5 significant digits (e.g., 0.0012345 and 1.2345),
(6 %) a) Find mean, median, standard deviation, variance, interquartile range, and coefficient of variation of both nitrogen and corn crop yield.
(5 %) b) Find the covariance and correlation coefficient between nitrogen and corn crop yield.
(5 %) c) Find and draw a scatter plot of corn crop yield (y-axis) and nitrogen (x-axis).
(10 %) d) Find linear regression parameters, where corn crop yield is being predicted (Y) via nitrogen (X)
(6 %) e) Find confidence intervals of both regression parameters at 95% confidence level.
|
a6eae8c4bdb22fdc7365aaff433da74c
|
{
"intermediate": 0.37854519486427307,
"beginner": 0.44633063673973083,
"expert": 0.1751241683959961
}
|
11,897
|
this is my angular header for my app how can i make it horizontal at the top instead of vertical : <nav class="navbar navbar-dark navbar-theme-primary px-4 col-12 d-lg-none">
<a class="navbar-brand me-lg-5" [routerLink]="['']"><img class="navbar-brand-dark" src="assets/img/logo.png" alt="logo"> <img class="navbar-brand-light" src="assets/img/dark.svg" alt="Rich logo"></a>
<div class="d-flex align-items-center"><button class="navbar-toggler d-lg-none collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button></div>
</nav>
<nav id="sidebarMenu" class="sidebar d-lg-block bg-gray-800 text-white collapse" data-simplebar>
<div class="sidebar-inner px-4 pt-3">
<div class="user-card d-flex d-md-none align-items-center justify-content-between justify-content-md-center pb-4">
<div class="d-flex align-items-center">
<div class="avatar-lg me-4"></div>
<div class="d-block">
<h2 class="h5 mb-3">Welcome</h2>
<a [routerLink]="['/sign-in']" class="btn btn-secondary btn-sm d-inline-flex align-items-center">
<svg class="icon icon-xxs me-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
</svg>
Sign Out
</a>
</div>
</div>
<div class="collapse-close d-md-none">
<a href="#sidebarMenu" data-bs-toggle="collapse" data-bs-target="#sidebarMenu" aria-controls="sidebarMenu" aria-expanded="true" aria-label="Toggle navigation">
<svg class="icon icon-xs" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd"></path>
</svg>
</a>
</div>
</div>
<ul class="nav flex-column pt-3 pt-md-0">
<li class="nav-item"><a class="nav-link d-flex align-items-center"><span class="sidebar-icon"><img src="assets/img/logo.png" height="20" width="20" alt="Logo"> </span><span class="mt-1 ms-1 sidebar-text"><b>E-RADAR</b></span></a></li>
<li class="nav-item" *ngIf="authService.hasRole('ADMIN')">
<a routerLink="vehicles" class="nav-link" *ngIf="authService.hasRole('ADMIN')">
<span class="sidebar-icon">
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0,0,256,256"
style="fill:#000000;">
<g fill="#9ca3af" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><g transform="scale(8.53333,8.53333)"><path d="M26.206,12.559l-2.058,-5.88c-0.561,-1.602 -2.079,-2.679 -3.777,-2.679h-10.742c-1.698,0 -3.216,1.077 -3.776,2.678l-2.058,5.88c-1.099,0.723 -1.795,1.972 -1.795,3.346v7.096c0,1.105 0.895,2 2,2c1.105,0 2,-0.895 2,-2v-1.261c0,0 5.281,0.261 9,0.261c3.719,0 9,-0.261 9,-0.261v1.261c0,1.105 0.895,2 2,2c1.105,0 2,-0.895 2,-2v-7.096c0,-1.374 -0.697,-2.623 -1.794,-3.345zM6.595,10.613l1.146,-3.274c0.281,-0.802 1.038,-1.339 1.888,-1.339h10.742c0.85,0 1.607,0.537 1.888,1.339l1.146,3.274c0.18,0.515 -0.249,1.034 -0.788,0.947c-1.961,-0.317 -4.482,-0.56 -7.617,-0.56c-3.135,0 -5.656,0.243 -7.617,0.56c-0.539,0.087 -0.968,-0.432 -0.788,-0.947zM6.5,18c-0.828,0 -1.5,-0.672 -1.5,-1.5c0,-0.828 0.672,-1.5 1.5,-1.5c0.828,0 1.5,0.672 1.5,1.5c0,0.828 -0.672,1.5 -1.5,1.5zM18,17h-6c-0.552,0 -1,-0.448 -1,-1c0,-0.552 0.448,-1 1,-1h6c0.552,0 1,0.448 1,1c0,0.552 -0.448,1 -1,1zM23.5,18c-0.828,0 -1.5,-0.672 -1.5,-1.5c0,-0.828 0.672,-1.5 1.5,-1.5c0.828,0 1.5,0.672 1.5,1.5c0,0.828 -0.672,1.5 -1.5,1.5z"></path></g></g>
</svg>
</span>
<span class="sidebar-text">Vehicles</span>
</a>
</li>
<li class="nav-item" *ngIf="authService.hasRole('ADMIN')">
<a routerLink="radars" class="nav-link">
<span class="sidebar-icon">
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0,0,256,256"
style="fill:#000000;">
<g fill="#9ca3af" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><g transform="scale(5.12,5.12)"><path d="M25,3c-12.13281,0 -22,9.86719 -22,22c0,12.13281 9.86719,22 22,22c12.13281,0 22,-9.86719 22,-22c0,-5.70703 -2.17578,-10.89844 -5.75,-14.8125l-4.28125,4.25c2.49219,2.82031 4.03125,6.51172 4.03125,10.5625c0,7.69141 -5.59375,14.28906 -13.09375,15.65625c-0.30469,1.33594 -1.48047,2.34375 -2.90625,2.34375c-1.41797,0 -2.59375,-0.98828 -2.90625,-2.3125c-7.49609,-1.33203 -13.09375,-7.96484 -13.09375,-15.6875c0,-2.60156 0.57813,-4.99609 1.6875,-7.125c-0.41797,-0.51562 -0.6875,-1.16016 -0.6875,-1.875c0,-1.65234 1.34766,-3 3,-3c0.41797,0 0.82422,0.09375 1.1875,0.25c2.96484,-2.73047 6.78125,-4.25 10.8125,-4.25c4.05078,0 7.74219,1.53906 10.5625,4.03125l4.25,-4.28125c-3.91406,-3.57422 -9.10547,-5.75 -14.8125,-5.75zM25,11c-3.53125,0 -6.73828,1.26563 -9.34375,3.625c0.21875,0.41797 0.34375,0.87109 0.34375,1.375c0,1.65234 -1.34766,3 -3,3c-0.20312,0 -0.40234,-0.02344 -0.59375,-0.0625c-0.91797,1.80859 -1.40625,3.83984 -1.40625,6.0625c0,6.71094 4.82422,12.47266 11.3125,13.6875c0.48828,-0.99609 1.50391,-1.6875 2.6875,-1.6875c1.17578,0 2.19531,0.69922 2.6875,1.6875c6.5,-1.24219 11.3125,-7 11.3125,-13.6875c0,-3.5 -1.30469,-6.69922 -3.4375,-9.15625l-2.8125,2.84375c1.41016,1.72266 2.25,3.91406 2.25,6.3125c0,1.67969 -0.42187,3.26563 -1.15625,4.65625c0.09375,0.26563 0.15625,0.54688 0.15625,0.84375c0,1.38281 -1.11719,2.5 -2.5,2.5c-0.15625,0 -0.32031,-0.03516 -0.46875,-0.0625c-1.67969,1.27734 -3.76172,2.0625 -6.03125,2.0625c-5.51562,0 -10,-4.48437 -10,-10c0,-5.51562 4.48438,-10 10,-10c2.39844,0 4.58984,0.83984 6.3125,2.25l2.84375,-2.8125c-2.45703,-2.13281 -5.65625,-3.4375 -9.15625,-3.4375zM13,15c-0.55078,0 -1,0.44922 -1,1c0,0.55078 0.44922,1 1,1c0.55078,0 1,-0.44922 1,-1c0,-0.55078 -0.44922,-1 -1,-1zM25,17c-4.41016,0 -8,3.58984 -8,8c0,4.41016 3.58984,8 8,8c1.59766,0 3.09375,-0.47266 4.34375,-1.28125c-0.20312,-0.36328 -0.34375,-0.77344 -0.34375,-1.21875c0,-1.38281 1.11719,-2.5 2.5,-2.5c0.30078,0 0.57813,0.0625 0.84375,0.15625c0.41797,-0.96875 0.65625,-2.03516 0.65625,-3.15625c0,-1.84766 -0.63281,-3.55078 -1.6875,-4.90625l-4.375,4.40625c0.04297,0.16406 0.0625,0.32031 0.0625,0.5c0,1.10547 -0.89453,2 -2,2c-1.10547,0 -2,-0.89453 -2,-2c0,-1.10547 0.89453,-2 2,-2c0.21875,0 0.42969,0.03125 0.625,0.09375l4.28125,-4.40625c-1.35547,-1.05469 -3.05859,-1.6875 -4.90625,-1.6875zM25,39c-0.55078,0 -1,0.44922 -1,1c0,0.55078 0.44922,1 1,1c0.55078,0 1,-0.44922 1,-1c0,-0.55078 -0.44922,-1 -1,-1z"></path></g></g>
</svg>
</span>
<span class="sidebar-text">Radars</span>
</a>
</li>
<li class="nav-item">
<a routerLink="infractions" class="nav-link">
<span class="sidebar-icon">
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="20" height="20" viewBox="0,0,256,256"
style="fill:#000000;">
<g fill="#9ca3af" fill-rule="nonzero" stroke="none" stroke-width="1" stroke-linecap="butt" stroke-linejoin="miter" stroke-miterlimit="10" stroke-dasharray="" stroke-dashoffset="0" font-family="none" font-weight="none" font-size="none" text-anchor="none" style="mix-blend-mode: normal"><g transform="scale(4,4)"><path d="M10,4.76172v54.23828h2h2h36h2h2v-54.23437l-6.00586,3l-4.00781,-2.00195l-3.99805,2l-4,-2l-3.99805,2l-4,-2l-3.99805,2l-4,-2l-3.99805,2zM19.99219,10.23633l4,2l3.99805,-2l4,2l3.99805,-2l4,2l4,-2l4.00586,1.99805l2.00586,-1v43.76563h-36v-43.76172l1.99414,0.99805zM21,16c-1.657,0 -3,1.343 -3,3c0,1.657 1.343,3 3,3c1.657,0 3,-1.343 3,-3c0,-1.657 -1.343,-3 -3,-3zM28,17v4h18v-4zM21,24c-1.657,0 -3,1.343 -3,3c0,1.657 1.343,3 3,3c1.657,0 3,-1.343 3,-3c0,-1.657 -1.343,-3 -3,-3zM28,25v4h11v-4zM21,32c-1.657,0 -3,1.343 -3,3c0,1.657 1.343,3 3,3c1.657,0 3,-1.343 3,-3c0,-1.657 -1.343,-3 -3,-3zM28,33v4h15v-4zM42.13281,40v0.99609c-1.297,0.236 -2.34961,1.10372 -2.34961,2.51172c0,1.929 1.758,2.46566 2.875,3.09766c0.891,0.507 1.5,0.8107 1.5,1.4707c0,0.743 -0.45536,1.22461 -1.44336,1.22461c-0.868,0 -1.69514,-0.36895 -2.36914,-0.87695l-0.6875,1.7168c0.674,0.503 1.60261,0.8163 2.47461,0.9043v0.95508h1.38477v-0.98242c1.546,-0.235 2.48242,-1.14575 2.48242,-2.84375c0,-1.542 -1.14064,-2.38244 -2.80664,-3.27344c-1.048,-0.567 -1.66602,-0.86603 -1.66602,-1.45703c0,-0.429 0.55161,-0.70703 1.34961,-0.70703c0.937,0 1.55517,0.22281 2.20117,0.75781l0.51172,-1.81445c-0.581,-0.438 -1.28327,-0.65452 -2.07227,-0.72852v-0.95117zM18,46v4h15v-4z"></path></g></g>
</svg>
</span>
<span class="sidebar-text">Infractions</span>
</a>
</li>
</ul>
</div>
</nav>
|
bf9f40be909c1cf8dc0880155353d66d
|
{
"intermediate": 0.3086481988430023,
"beginner": 0.39397868514060974,
"expert": 0.29737308621406555
}
|
11,898
|
write a short email to get a quotation from a trading company X
|
02cbe0b42d960f64669bac3e01fa7635
|
{
"intermediate": 0.3425738215446472,
"beginner": 0.31055521965026855,
"expert": 0.34687095880508423
}
|
11,899
|
OOP C++: Chúng ta sẽ mô phỏng một thành phố bị zombie tấn công trên mặt phẳng hai chiều, mỗi đối tượng trong không gian có các thông tin: ID, type (1 – 3), toạ độ x, toạ độ y.
Quân lính (type = 1): có thêm thông tin là cấp, tương đương số lượng zombie có thể tiêu dượt / lượt và khoảng cách tấn công. Quân lính tự động tấn công zombie gần nhất. Quân lính bị zombie tiếp cận sẽ biến thành zombie mới, có tốc độ di chuyển = 1.
Dân thường (type = 2): có thêm thông tin tốc độ di chuyển s và tầm nhìn v, dân thường tự động chạy khỏi zombie gần nhất, nếu phát hiện có zombie trong tầm nhìn v. Nếu không có zombie, dân thường đứng yên. Dân thường khi biến thành zombie mới có tốc độ di chuyển như cũ.
Zombie (type = 3): có thêm thông tin tốc độ di chuyển s, tự động di chuyển vào dân thường / quân lính gần nhất. Nếu không còn quân lính / dân thường nào, Zombie đứng yên. Zombie khi tiếp cận quân lính / dân thường sẽ biến quân lính / dân thường thành zombie trong lượt kế.
Quy tắc di chuyển: quân lính luôn đứng yên, dân thường và zombie có thể đi chéo hoặc đi thẳng. Zombie luôn ưu tiên hướng di chuyển làm sao cho rút ngắn khoảng cách nhất, dân thường di chuyển ngược hướng với hướng đi của Zombie gần nhất.
Trong một lượt, dân thường di chuyển => zombie di chuyển => quân lính tấn công.
Áp dụng kế thừa, đa hình để mô phỏng quá trình lây lan dịch bệnh.
B1. Nhập vào số lượng cá thể n, số lượt m và nhập thông tin n cá thể trên n dòng
[n] [m]
[ID] [Type] [Toạ độ x] [Toạ độ y] [Thông tin thêm nếu có]
B2. In ra toạ độ các zombie tại lượt m, sắp xếp theo hoàng độ và tung độ, không cần thông tin ID.
[Toạ độ x] [Toạ độ y]
image
Input Format
int int
[int int int int]
Constraints
n, m >= 0
Output Format
[int int int]
Sample Input 0
7 5
1 1 3 3 1
2 1 2 5 1
3 1 3 6 1
4 2 5 5 1 1
5 3 6 3 1
5 3 6 4 1
5 3 7 4 1
Explanation 0
https://youtu.be/ATTNUMTCERI
Sample Input 1
10 5
1 1 3 3 1
2 1 2 5 1
3 1 3 6 1
4 2 6 5 1 1
5 3 2 1 1
6 3 3 1 1
7 3 6 3 1
7 3 6 4 1
7 3 6 5 1
7 3 6 6 1
Sample Output 1
2 5
2 5
2 6
2 6
2 6
2 6
2 6
|
58a1ff1ace9013c53470f7fa0ba3883d
|
{
"intermediate": 0.22884871065616608,
"beginner": 0.6107500791549683,
"expert": 0.16040119528770447
}
|
11,900
|
import os
def new_directory(directory, filename):
# Before creating a new directory, check to see if it already exists
if os.path.isdir(directory) == False:
___
# Create the new file inside of the new directory
os.chdir(___)
with open (___) as file:
pass
# Return the list of files in the new directory
return ___
print(new_directory("PythonPrograms", "script.py"))
|
fa3a77b5f22a8b898714dca7a9547316
|
{
"intermediate": 0.36265483498573303,
"beginner": 0.411594420671463,
"expert": 0.22575077414512634
}
|
11,901
|
mysql Incorrect datetime value: '6/13/2023 5:34:38 PM' for column 'createtime' at row 1
|
401e17055577106a024a8562f3b0fc8a
|
{
"intermediate": 0.36338576674461365,
"beginner": 0.27049189805984497,
"expert": 0.366122305393219
}
|
11,902
|
OOP C++: Chúng ta sẽ mô phỏng một thành phố bị zombie tấn công trên mặt phẳng hai chiều, mỗi đối tượng trong không gian có các thông tin: ID, type (1 – 3), toạ độ x, toạ độ y.
Quân lính (type = 1): có thêm thông tin là cấp, tương đương số lượng zombie có thể tiêu dượt / lượt và khoảng cách tấn công. Quân lính tự động tấn công zombie gần nhất. Quân lính bị zombie tiếp cận sẽ biến thành zombie mới, có tốc độ di chuyển = 1.
Dân thường (type = 2): có thêm thông tin tốc độ di chuyển s và tầm nhìn v, dân thường tự động chạy khỏi zombie gần nhất, nếu phát hiện có zombie trong tầm nhìn v. Nếu không có zombie, dân thường đứng yên. Dân thường khi biến thành zombie mới có tốc độ di chuyển như cũ.
Zombie (type = 3): có thêm thông tin tốc độ di chuyển s, tự động di chuyển vào dân thường / quân lính gần nhất. Nếu không còn quân lính / dân thường nào, Zombie đứng yên. Zombie khi tiếp cận quân lính / dân thường sẽ biến quân lính / dân thường thành zombie trong lượt kế. Zombie ưu tiên tấn công quân lính cấp cao hơn và dân thường có tốc độ di chuyển thấp hơn.
Quy tắc di chuyển: quân lính luôn đứng yên, dân thường và zombie có thể đi chéo hoặc đi thẳng. Zombie luôn ưu tiên hướng di chuyển làm sao cho rút ngắn khoảng cách nhất, dân thường di chuyển ngược hướng với hướng đi của Zombie gần nhất.
Trong một lượt, dân thường di chuyển => zombie di chuyển => quân lính tấn công.
Áp dụng kế thừa, đa hình để mô phỏng quá trình lây lan dịch bệnh.
B1. Nhập vào số lượng cá thể n, số lượt m và nhập thông tin n cá thể trên n dòng
[n] [m]
[ID] [Type] [Toạ độ x] [Toạ độ y] [Thông tin thêm nếu có]
B2. In ra toạ độ các zombie tại lượt m, sắp xếp theo hoàng độ và tung độ, không cần thông tin ID.
[Toạ độ x] [Toạ độ y]
image
Input Format
int int
[int int int int]
Constraints
n, m >= 0
Output Format
[int int int]
Sample Input 0
7 5
1 1 3 3 1
2 1 2 5 1
3 1 3 6 1
4 2 5 5 1 1
5 3 6 3 1
5 3 6 4 1
5 3 7 4 1
Explanation 0
https://youtu.be/ATTNUMTCERI
Sample Input 1
10 5
1 1 3 3 1
2 1 2 5 1
3 1 3 6 1
4 2 6 5 1 1
5 3 2 1 1
6 3 3 1 1
7 3 6 3 1
7 3 6 4 1
7 3 6 5 1
7 3 6 6 1
Sample Output 1
2 5
2 5
2 6
2 6
2 6
2 6
2 6
|
adb709c358df6524f313eecd795b77aa
|
{
"intermediate": 0.11469557136297226,
"beginner": 0.7338246703147888,
"expert": 0.1514797806739807
}
|
11,903
|
import os
import datetime
def file_date(filename):
# Create the file in the current directory
with open (filename,"w") asfile:
pass
timestamp = os.path.getmtime(filename)
# Convert the timestamp into a readable format, then into a string
___
# Return just the date portion
# Hint: how many characters are in “yyyy-mm-dd”?
return ("{___}".format(___))
print(file_date("newfile.txt"))
# Should be today's date in the format of yyyy-mm-dd
|
dfdfa2e98d6ec0f942dc937170ff6fed
|
{
"intermediate": 0.42720428109169006,
"beginner": 0.34273892641067505,
"expert": 0.23005680739879608
}
|
11,904
|
how to get border line segments of multi polygon 's union by python
|
08313a943915c463fd9fc06941a68c1a
|
{
"intermediate": 0.24598559737205505,
"beginner": 0.17960110306739807,
"expert": 0.5744132399559021
}
|
11,905
|
ensure only required ports must be open in linux server hardening
|
8b5b973d43099eedb92e095bf7d4b68b
|
{
"intermediate": 0.312395304441452,
"beginner": 0.2810732126235962,
"expert": 0.4065314531326294
}
|
11,906
|
使用down_interruptible实现单线程阻塞读取驱动 C代码
|
264387793ceb02ef2b6d2042aaf88817
|
{
"intermediate": 0.27261117100715637,
"beginner": 0.3780859708786011,
"expert": 0.34930288791656494
}
|
11,907
|
Write a research paper on Machine Learning-Based Classification of Breast Cancer Subtypes using Open-Source Data: Enhancing Precision and Personalized Treatment Decisions , include the source of the data and also give the code to replicate the result in google colab
|
c0437a713485ac253e83edd58b3ee509
|
{
"intermediate": 0.06730938702821732,
"beginner": 0.03690531477332115,
"expert": 0.8957852721214294
}
|
11,908
|
Write a method that can process each line of code
|
89f31fbd00e79802127731e31e22fa4e
|
{
"intermediate": 0.3833833932876587,
"beginner": 0.19148172438144684,
"expert": 0.4251348376274109
}
|
11,909
|
Hi I'm getting this error : Exception has occurred: TypeError: globalObject.eval is not a function and the line of code is globalObject.eval("(async function* () {});").prototype BTW I'm using node.js
|
1bf2668767f5643f2aace4e4d79a3c0b
|
{
"intermediate": 0.4697202742099762,
"beginner": 0.3405989408493042,
"expert": 0.18968074023723602
}
|
11,910
|
check if a string contrains certain sub string in the middle in python
|
fcc5e778ca0dbb5076ff5a71ba3c7c95
|
{
"intermediate": 0.4820055365562439,
"beginner": 0.2002721130847931,
"expert": 0.31772229075431824
}
|
11,911
|
give me a String search python program
|
92d70a53ac499b132b9bbca189639513
|
{
"intermediate": 0.3963727653026581,
"beginner": 0.23580646514892578,
"expert": 0.36782076954841614
}
|
11,912
|
I will give you a code , you have to change one structure ....
in the code there was written vgg16 , you have use lstm insteed of vgg16 and all others things will be same
here is the code -
"
here is the code modify it -
"#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 16 15:16:08 2020
@author: kalpita
"""
#matplotlib inline
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from torchvision import transforms, datasets
import torchvision.datasets as datasets
import torchvision.models as models
import os
My_dir = os.listdir('/media/nibaran/New Volume/Jaya/deep_learning_LineData')
print(My_dir)
print(len(My_dir))
num_epochs = len(My_dir)
for epoch in range(num_epochs):
print(My_dir[epoch])
Ptrain = os.path.join('/media/nibaran/New Volume/Jaya/deep_learning_LineData' + '/' + My_dir[epoch] + '/' + 'train'+ '/')
print(Ptrain)
PATH = os.path.join('/media/nibaran/New Volume/Jaya/line_result/Train_WTTest' + My_dir[epoch] +'.pth' )
Ptest = os.path.join('/media/nibaran/New Volume/Jaya/deep_learning_LineData' + '/' + My_dir[epoch] + '/' + 'test' + '/')
print(Ptest)
PATH1 = os.path.join('/media/nibaran/New Volume/Jaya/line_result/ModelTest' + My_dir[epoch] +'.pth' )
# Load data
apply_transform = transforms.Compose([transforms.RandomResizedCrop(224),transforms.RandomHorizontalFlip(), transforms.ToTensor()])
BatchSize = 1 # change according to system specs
#trainset = datasets.MNIST(root='./MNIST', train=True, download=True, transform=apply_transform)
#train_path='/media/nibaran/New Volume/Jaya/nEW_rUN/bangla_data_deep/86/train/'
trainset=datasets.ImageFolder(Ptrain, transform=apply_transform)
trainLoader = torch.utils.data.DataLoader(trainset, batch_size=BatchSize,
shuffle=True, num_workers=1) # Creating dataloader
# Validation set with random rotations in the range [-90,90]
#testset = datasets.MNIST(root='./MNIST', train=False, download=True, transform=apply_transform)
#test_path='/media/nibaran/New Volume/Jaya/nEW_rUN/bangla_data_deep/86/test/'
testset=datasets.ImageFolder(Ptest, transform=apply_transform)
testLoader = torch.utils.data.DataLoader(testset, batch_size=BatchSize,
shuffle=False, num_workers=1) # Creating dataloader
# Size of train and test datasets
print('No. of samples in train set: '+str(len(trainLoader.dataset)))
print('No. of samples in test set: '+str(len(testLoader.dataset)))
Notrain = len(trainLoader.dataset)
Notest = len(testLoader.dataset)
#Define model architecture
use_gpu = torch.cuda.is_available()
net = models.vgg16(pretrained=True)
net.classifier._modules['6'] = nn.Linear(4096, 2)
print(net)
if use_gpu:
print('GPU is avaialble!')
net = net.cuda()
# train model
criterion = nn.CrossEntropyLoss()
learning_rate = 0.0001
num_epochs = 100
train_loss = []
train_acc = []
for epoch in range(num_epochs):
running_loss = 0.0
running_corr = 0
for i,data in enumerate(trainLoader):
inputs,labels = data
if use_gpu:
inputs, labels = inputs.cuda(),labels.cuda()
# Initializing model gradients to zero
net.zero_grad()
# Data feed-forward through the network
outputs = net(inputs)
# Predicted class is the one with maximum probability
preds = torch.argmax(outputs,dim=1)
# Finding the loss
loss = criterion(outputs, labels)
# Accumulating the loss for each batch
running_loss += loss
# Accumulate number of correct predictions
running_corr += torch.sum(preds==labels)
totalLoss = running_loss/(i+1)
# Calculating gradients
totalLoss.backward()
# Updating the model parameters
for f in net.parameters():
f.data.sub_(f.grad.data * learning_rate)
epoch_loss = running_loss.item()/(i+1) #Total loss for one epoch
epoch_acc = running_corr.item()/Notrain
train_loss.append(epoch_loss) #Saving the loss over epochs for plotting the graph
train_acc.append(epoch_acc) #Saving the accuracy over epochs for plotting the graph
print('Epoch {:.0f}/{:.0f} : Training loss: {:.4f} | Training Accuracy: {:.4f}'.format(epoch+1,num_epochs,epoch_loss,epoch_acc*100))
fig = plt.figure(figsize=[15,5])
plt.subplot(121)
plt.plot(range(num_epochs),train_loss,'r-',label='Loss')
plt.legend(loc='upper right')
plt.xlabel('Epochs')
plt.ylabel('Training')
plt.subplot(122)
plt.plot(range(num_epochs),train_acc,'g-',label='Accuracy')
plt.legend(loc='upper right')
plt.xlabel('Epochs')
plt.ylabel('Training')
#Evaluation of trained model
correct_pred = 0
for data in testLoader:
inputs,labels = data
if use_gpu:
inputs, labels = inputs.cuda(),labels.cuda()
# Feedforward train data batch through model
output = net(inputs)
# Predicted class is the one with maximum probability
preds = torch.argmax(output,dim=1)
correct_pred += torch.sum(preds==labels)
test_accuracy = correct_pred.item()/Notest
print('Testing accuracy = ',test_accuracy*100)
# Save Model
#PATH = os.path.join('/media/nibaran/New Volume/Jaya/nEW_rUN/Results/Resut_test' + )
#PATH = '/media/nibaran/New Volume/Jaya/nEW_rUN/Results/bangla_data_deepR/Train_WTTest_86w.pt'
#PATH1 = '/media/nibaran/New Volume/Jaya/nEW_rUN/Results/bangla_data_deepR/ModelTest_86w.pt'
torch.save(net.state_dict(), PATH)
torch.save(net, PATH1)
"
"
|
689dcc6f01e11fee33bbc6717cb25759
|
{
"intermediate": 0.3407505452632904,
"beginner": 0.3561304807662964,
"expert": 0.3031189739704132
}
|
11,913
|
write me Bubble sort python program
|
0542baf666672db4bb9931b002bd9541
|
{
"intermediate": 0.2768382728099823,
"beginner": 0.28245529532432556,
"expert": 0.44070640206336975
}
|
11,914
|
hi\
|
f64cc19b6dbb5df08ad90d644eeecbed
|
{
"intermediate": 0.3229372203350067,
"beginner": 0.28523269295692444,
"expert": 0.39183008670806885
}
|
11,915
|
write a good prompt for chat gpt for the task below.
|
de3b7a49a6606688cea7ccd1df228fae
|
{
"intermediate": 0.31139785051345825,
"beginner": 0.31245699524879456,
"expert": 0.3761451542377472
}
|
11,916
|
what is δ(f) the Dirac delta function?
|
875a514049b427ebe3efe48a3246aa5b
|
{
"intermediate": 0.2883661687374115,
"beginner": 0.36258238554000854,
"expert": 0.34905147552490234
}
|
11,917
|
Could you create a jms consumer client with weblogic from rabbitmq c#
|
2ceccf38d0a25c465671e46b0afa379c
|
{
"intermediate": 0.5376381278038025,
"beginner": 0.1785183548927307,
"expert": 0.2838435471057892
}
|
11,918
|
[eslint] Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc.js': Cannot find module '@typescript-eslint/parser'
Require stack:
- D:\R-Vision\AT\rpoint-ui\.eslintrc.js
как решить
|
57576eec1c655e4be0346194019334c8
|
{
"intermediate": 0.567496120929718,
"beginner": 0.22341114282608032,
"expert": 0.20909270644187927
}
|
11,919
|
write me a Graphs python program
|
7c62040bc744e0d5de74c1481b9f9c60
|
{
"intermediate": 0.3102431893348694,
"beginner": 0.1337345540523529,
"expert": 0.5560221672058105
}
|
11,920
|
<vxe-column field="khxh__c" min-width="120" title="客户型号"></vxe-column>
<vxe-column field=“main_field” min-width=“100” title=“mzgcpck”></vxe-column> 我需要将mzgcpck改成可以修改的文本框
|
b06d73313c9255ee39ae920f5e143f13
|
{
"intermediate": 0.2651312053203583,
"beginner": 0.30320340394973755,
"expert": 0.43166548013687134
}
|
11,921
|
there is no uniform called: kernelSize
|
7232a20cca50dedd7d2dc0bbe6564d16
|
{
"intermediate": 0.46122702956199646,
"beginner": 0.32756203413009644,
"expert": 0.2112109363079071
}
|
11,922
|
intoresponse seaorm DbErr for axum Response
|
f8d97a7885015a0f57954e3a4367ce68
|
{
"intermediate": 0.40311259031295776,
"beginner": 0.26682257652282715,
"expert": 0.3300648033618927
}
|
11,923
|
in python, how to translate chinese into english
|
6fff24533b770e4f9db703bffec2d108
|
{
"intermediate": 0.2972399592399597,
"beginner": 0.3435485363006592,
"expert": 0.3592114746570587
}
|
11,924
|
class Tasks(db.Model):
tablename = ‘tasks’
searchable = [‘task’, ‘id’] # these fields will be indexed by whoosh
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
url = db.Column(db.String(120), comment=“ЧПУ задачи в адресе (транслитом)”)
task = db.Column(db.Text, comment=‘Условие задачи’)
answer = db.Column(db.Text, comment=‘Ответ’)
status = db.Column(db.Boolean, default=0, comment=‘Статус: опубликована/неактивна (по умолчанию нет)’)
created_t = db.Column(db.DateTime, comment=‘Дата и время создания’)
level = db.Column(db.SmallInteger, default=1, comment=‘Уровень сложности: 1,2 … (по умолчанию 1 уровень)’)
# связи
topics = db.relationship(‘Topics’,
secondary=tasks_topics,
back_populates=“tasks”)
есть вот такой класс. Я попытался сделать полнотекстовый поиск с помощью whoosh
schema = Schema(id=ID(stored=True), task=TEXT(stored=True), answer=TEXT(stored=True))
index_dir = 'tasks_index'
if not os.path.exists(index_dir):
os.mkdir(index_dir)
ix = create_in(index_dir, schema)
ix = open_dir(index_dir)
writer = ix.writer()
all_tasks = Tasks.query.all()
for task in all_tasks:
writer.add_document(id=str(task.id), task=task.task, answer=task.answer)
writer.commit()
with ix.searcher() as searcher:
query = QueryParser('task', ix.schema).parse('решить')
results = searcher.search(query)
print(results) line 573, in <module>
writer.add_document(id=str(task.id), task=task.task, answer=task.answer) raise IndexingError("This writer is closed")
whoosh.writing.IndexingError: This writer is closed. Как это исправить?
|
98bbee81a9a9f2bc8df6127b6165f752
|
{
"intermediate": 0.37885966897010803,
"beginner": 0.17954882979393005,
"expert": 0.4415914714336395
}
|
11,925
|
write me a Kruskal algorithm python program
|
ee421b14cc3306a7c414e593e8b12404
|
{
"intermediate": 0.08075575530529022,
"beginner": 0.06949586421251297,
"expert": 0.849748432636261
}
|
11,926
|
write me Hash table python program
|
5271cbe86467731e663bf80654e65f81
|
{
"intermediate": 0.29556989669799805,
"beginner": 0.2111256867647171,
"expert": 0.49330446124076843
}
|
11,927
|
Максимально оптимизируй этот код, что бы он работал очень быстро, и перепеши мне готовый вариант
|
c2f62b711b640003880d70a22c5dcabc
|
{
"intermediate": 0.3073136508464813,
"beginner": 0.27829912304878235,
"expert": 0.4143872559070587
}
|
11,928
|
i want to make MEV bot
|
350618d28c7d613ebeef7e86e9d6106a
|
{
"intermediate": 0.23844027519226074,
"beginner": 0.19017061591148376,
"expert": 0.5713890790939331
}
|
11,929
|
i have flutter project and i want to make the apk download silently with every update i tried some solutions but i faced the following error Execution failed for task ':app:processReleaseResources'.
A failure occurred while executing com.android.build.gradle.internal.res.LinkApplicationAndroidResourcesTask$TaskAction
Android resource linking failed
|
96db995f5c617585208b2997412e4f3a
|
{
"intermediate": 0.5229689478874207,
"beginner": 0.26457446813583374,
"expert": 0.212456613779068
}
|
11,930
|
write me Line chart data structure python program
|
70b2b176077aac7a8ed4df51860231a4
|
{
"intermediate": 0.4273437261581421,
"beginner": 0.23899208009243011,
"expert": 0.3336641490459442
}
|
11,931
|
Can you create an HTML website with a custom background image and a centered list of 4 items?
|
512716128c1526edf7decb78f8c1a826
|
{
"intermediate": 0.40366989374160767,
"beginner": 0.3264499306678772,
"expert": 0.2698802053928375
}
|
11,932
|
Мой сайт своего рода доска объявлений - социальная сеть для для музыкантов, которые ищут других музыкантов. Блок с недавно зарегистрированными пользователями выглядит лишним, либо я неправильно это реализовал. Мне нужно придумать, какой блок вставить, следующий после полей поиска
index:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0" name="viewport">
<meta content="ie=edge" http-equiv="X-UA-Compatible">
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:400,500,700" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<link href="/css/main.css" rel="stylesheet">
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="/jquery-ui/themes/base/all.css" rel="stylesheet">
<title>Home</title>
</head>
<body>
<header class="header">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="/">
<img src="/img/logo.png" alt="My Musician Site">
</a>
<button aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler" data-target="#navbarNav" data-toggle="collapse" type="button">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link" href="#find-musicians">Find Musicians</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/register"><i class="fa fa-user-plus" aria-hidden="true"></i> Register</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/login"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="hero">
<div class="container">
<h1 class="hero-title">Find the Perfect Musician for Your Band or Project</h1>
<p class="hero-subtitle">Join our community today and connect with talented musicians from around the world.</p>
<a class="btn btn-primary btn-lg" href="/register">Register Now</a>
</div>
</div>
</header>
<main class="main">
<section class="section section-search" id="find-musicians">
<div class="container">
<h2 class="section-title"><i class="fa fa-search" aria-hidden="true"></i> Find Musicians</h2>
<form class="form-search" action="/search" method="get">
<div class="form-group">
<label for="role"><i class="fa fa-users" aria-hidden="true"></i> Role:</label>
<select class="form-control" id="role" name="role">
<option value="">All</option>
<option value="Band">Band</option>
<option value="Artist">Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Search by genre:</label>
<select class="form-control" id="genre" name="genre">
<option value="">All</option>
</select>
</div>
<div class="form-group">
<label for="city"><i class="fa fa-map-marker" aria-hidden="true"></i> Location:</label>
<input id="city" name="city" type="text" class="form-control" autocomplete="on" value="<%= city %>" data-value="">
</div>
<button class="btn btn-primary" type="submit"><i class="fa fa-search" aria-hidden="true"></i> Search</button>
</form>
</div>
</section>
<!-- последние зарегистрированные пользователи -->
<section class="musicians">
<div class="container">
<h2>Find Musicians</h2>
<div class="row">
<% musicians.forEach(function(musician) { %>
<div class="col-lg-4 col-md-6 col-sm-12">
<div class="musician-card">
<div class="musician-info">
<h3><%= musician.name %></h3>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<p><strong>Location:</strong> <%= musician.location %></p>
</div>
<div class="musician-link">
<a href="/musicians/<%= musician.id %>">View profile</a>
</div>
</div>
</div>
<% }); %>
</div>
</div>
</section>
<!-- end -->
</main>
<footer class="footer">
<div class="container">
<p class="text-center mb-0">My Musician Site © 2023</p>
</div>
</footer>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script>
$("#city").autocomplete({
source: '/autocomplete/cities',
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#city");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
</script>
<script>
const genres = ["Rock", "Pop", "Jazz", "Blues", "Country"];
const genreSelect = document.querySelector("#genre");
genres.forEach((genre) => {
const option = document.createElement("option");
option.value = genre;
option.text = genre;
genreSelect.appendChild(option);
});
</script>
</body>
</html>
css:
.musician-info {
display: inline-block;
margin-left: 10px;
vertical-align: top;
}
.name {
font-weight: bold;
font-size: 1.2em;
}
.genre {
display: block;
font-size: 0.9em;
color: #666;
}
ul li a img {
max-width: 200px;
height: 200px;
object-fit: cover;
}
/* Normalize CSS */
body {
margin: 0;
font-family: 'Roboto', sans-serif;
font-size: 16px;
line-height: 1.5;
}
/* Header */
.header {
background-color: #fff;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}
.navbar-brand img {
height: 50px;
}
/* Hero */
.hero {
background-image: url('/img/hero.jpg');
background-size: cover;
background-position: center;
color: #fff;
padding: 100px 0;
}
.hero-title {
font-size: 48px;
margin-bottom: 20px;
}
.hero-subtitle {
font-size: 24px;
margin-bottom: 40px;
}
.hero .btn-primary {
background-color: #ffc107;
border-color: #ffc107;
}
.hero .btn-primary:hover {
background-color: #ffca2c;
border-color: #ffca2c;
}
/* Search */
.section-search {
background-color: #f8f9fa;
padding: 80px 0;
}
.section-title {
font-size: 36px;
margin-bottom: 40px;
text-align: center;
}
.form-search {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
max-width: 800px;
margin: 0 auto;
position: relative; /* add this */
}
.form-search .btn-primary {
position: relative; /* add this */
right: 0; /* add this */
top: 100%; /* add this */
margin-top: 20px; /* add this */
margin-left: 10px;
}
.form-group {
margin: 10px;
}
.form-group select {
margin-top: 10px;
}
.form-group label {
margin-bottom: 5px;
display: block;
}
.form-control {
border-radius: 0;
}
.btn-primary {
background-color: #ffc107;
border-color: #ffc107;
}
.btn-primary:hover {
background-color: #ffca2c;
border-color: #ffca2c;
}
/* Results */
.section-results {
padding: 80px 0;
text-align: center;
}
/* Footer */
.footer {
background-color: #212529;
color: #fff;
padding: 20px 0;
}
.footer p {
margin-bottom: 0;
font-size: 14px;
}
.footer a {
color: #fff;
}
.footer a:hover {
color: #ffc107;
}
/* последние зарегистрированные пользователи */
.musician-card {
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
margin-bottom: 30px;
overflow: hidden;
}
.musician-info {
padding: 20px;
}
.musician-info h3 {
margin-top: 0;
}
.musician-info p {
margin-bottom: 10px;
}
.musician-link {
background-color: #f2f2f2;
padding: 15px;
text-align: center;
}
.musician-link a {
color: #333;
display: inline-block;
font-size: 16px;
text-decoration: none;
}
|
d5980c3307749753e72d3277381d941e
|
{
"intermediate": 0.29628196358680725,
"beginner": 0.4901341497898102,
"expert": 0.21358387172222137
}
|
11,933
|
Lock down boot partition to Read only mode in linux
|
dce765c47c489d674756987777c8cf2e
|
{
"intermediate": 0.3799862265586853,
"beginner": 0.21598514914512634,
"expert": 0.40402859449386597
}
|
11,934
|
How to use AWS CLI to delete SiteWise Portal forcebly
|
ca4d5680ac31c45d735eb1509761026a
|
{
"intermediate": 0.357416570186615,
"beginner": 0.33641302585601807,
"expert": 0.30617040395736694
}
|
11,935
|
Can you create a bare minimum basic HTML website?
|
3b2bb0be89d1d6f21165b613f4e40cea
|
{
"intermediate": 0.3910761773586273,
"beginner": 0.341968297958374,
"expert": 0.26695555448532104
}
|
11,936
|
tasks_topics = db.Table(‘tasks_topics’,
db.Column(‘task_id’, db.Integer, db.ForeignKey(‘tasks.id’)),
db.Column(‘topics_id’, db.Integer, db.ForeignKey(‘topics.id’))
)
class Tasks(db.Model):
tablename = ‘tasks’
searchable = [‘task’, ‘id’] # these fields will be indexed by whoosh
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
url = db.Column(db.String(120), comment=“ЧПУ задачи в адресе (транслитом)”)
task = db.Column(db.Text, comment=‘Условие задачи’)
answer = db.Column(db.Text, comment=‘Ответ’)
status = db.Column(db.Boolean, default=0, comment=‘Статус: опубликована/неактивна (по умолчанию нет)’)
created_t = db.Column(db.DateTime, comment=‘Дата и время создания’)
level = db.Column(db.SmallInteger, default=1, comment=‘Уровень сложности: 1,2 … (по умолчанию 1 уровень)’)
# связи
topics = db.relationship(‘Topics’,
secondary=tasks_topics,
back_populates=“tasks”)
class Topics(db.Model):
tablename = ‘topics’
searchable = [‘name’]
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(140), comment=“Уникальное название темы(подтемы)”)
parent = db.Column(db.Integer, default=0, comment=“ID родительской темы(если есть)”)
# связи
tasks = db.relationship(‘Tasks’,
secondary=tasks_topics,
back_populates=“topics”)
schema = Schema(id=ID(stored=True),
task=TEXT(stored=True),
answer=TEXT(stored=True),
topics_name = TEXT(stored=True))
index_dir = 'tasks_index'
if not os.path.exists(index_dir):
os.mkdir(index_dir)
ix = create_in(index_dir, schema)
else:
ix = open_dir(index_dir)
with ix.searcher() as searcher:
query = QueryParser('task','topics_name', ix.schema).parse('Умножение и деление')
results = searcher.search(query, limit=None)
print(results)
for hit in results:
print(hit)
with ix.writer() as writer:
all_tasks = Tasks.query.options(subqueryload(Tasks.topics)).all()
for task in all_tasks:
topics_name = ""
for top in task.topics:
topics_name.join(top.name)
writer.add_document(id=str(task.id), task=task.task, answer=task.answer,topics_name = topics_name)
writer.commit()
AttributeError: 'TEXT' object has no attribute 'taggers' line 575, in <module>
query = QueryParser('task','topics_name', ix.schema).parse('Умножение и деление')
|
14dbd310a3f891ffdb584852a93494c4
|
{
"intermediate": 0.32967305183410645,
"beginner": 0.5426135063171387,
"expert": 0.12771347165107727
}
|
11,937
|
Нужно добавить возможность заливать зарегистрированному пользователю свою фонотеку (музыку). Одним из условий должно быть прикрепление картинки 200x200 к любой из песен. Кроме того, должна быть возможность загружать и отображать песни целыми альбомами. Фонотека/дискография должна отображаться в профиле у музыканта в profile.ejs. Название альбомов и так далее будет храниться в json файле. Мне нужно более-менее простое решение. Вот код:
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'music', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'music' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
});
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users WHERE city LIKE ?",
[searchString + '%'],
(error, results, fields) => {
if (error) {
console.error("Ошибка выполнения запроса: ", error);
res.status(500).send("Ошибка выполнения запроса");
} else {
const cities = results.map(row => row.city);
res.json(cities);
}
}
);
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
res.render("profile", { musician: musician, city:'', query:'', role:'' });
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].id);
} else {
res.render("login", { error: "Invalid login or password" });
}
}
}
);
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.post("/profile/:id/edit", requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Popper.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200">
</div>
<div class="col-md-8">
<h1><%= musician.name %></h1>
<p><strong>Role:</strong> <%= musician.role %></p>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<% if (musician.role === 'Artist' && musician.instrument) { %>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<% } %>
<p><strong>Location:</strong> <%= musician.city %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (musician.soundcloud) { %>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
</div>
<% } %>
<% if (musician.soundcloud1) { %>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
</div>
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button>
<div id="edit-profile-modal" class="modal fade">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Profile</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control">
</div>
<div class="form-group">
<label for="role">Role:</label>
<select id="role" name="role" class="form-control">
<option value="">Select a role</option>
<option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option>
<option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Genre:</label>
<select id="genre" name="genre" class="form-control">
<option value="">Select a genre</option>
<option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option>
<option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option>
<option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option>
<option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option>
<option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option>
<option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option>
</select>
</div>
<% if (musician.role === 'Artist') { %>
<div class="form-group">
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control">
</div>
<% } %>
<div class="form-group">
<label for="city">Location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control">
</div>
<div class="form-group">
<label for="bio">Bio:</label>
<textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea>
</div>
<div class="form-group">
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file">
</div>
<div class="form-group">
<label for="soundcloud">Soundcloud Track:</label>
<input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control">
</div>
<div class="form-group">
<label for="soundcloud1">Soundcloud Track 2:</label>
<input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
<style>
.ui-autocomplete {
z-index: 9999;
}
</style>
</body>
</html>
|
8d26c4013c9bc3925e5f3e21749fde2c
|
{
"intermediate": 0.30458641052246094,
"beginner": 0.5436923503875732,
"expert": 0.15172120928764343
}
|
11,938
|
<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="16.0007" cy="16.0007" r="14" stroke="#40484F" stroke-width="1.33333"/>
<rect x="7.33268" y="11.3346" width="17.3333" height="9.33333" rx="0.666667" stroke="#40484F" stroke-width="1.33333"/>
<circle cx="11.9987" cy="16.0007" r="2" stroke="#40484F" stroke-width="1.33333"/>
<line x1="16.6667" y1="18.3333" x2="22" y2="18.3333" stroke="#40484F" stroke-width="1.33333" stroke-linecap="round"/>
<line x1="16.6667" y1="16.3333" x2="22" y2="16.3333" stroke="#40484F" stroke-width="1.33333" stroke-linecap="round"/>
<line x1="16.6667" y1="14.3333" x2="22" y2="14.3333" stroke="#40484F" stroke-width="1.33333" stroke-linecap="round"/>
</svg>
svg иконка не меняет цвет
|
4c26cc86463b2a5cfa95a0d1a7e97b61
|
{
"intermediate": 0.35320132970809937,
"beginner": 0.31113430857658386,
"expert": 0.335664302110672
}
|
11,939
|
const entities = require('@jetbrains/youtrack-scripting-api/entities');
exports.rule = entities.Issue.onChange({
title: 'Copy subsystem from parent task when issue is linked as a subtask',
guard: (ctx) => {
return
},
action: (ctx) => {
const issue = ctx.issue;
const safeSetSubsystem = function (subtask) {
if (subtask.project && !subtask.project.isArchived) {
if (subtask.project.key === issue.project.key || subtask.project.findFieldByName(ctx.Subsystem.name)) {
if (!subtask.fields.Subsystem) {
const value = subtask.project.findFieldByName(ctx.Subsystem.name).findValueByName(issue.fields.Subsystem.name);
if (value) {
subtask.fields.Subsystem = value;
}
}
}
}
};
issue.links['parent for'].added.forEach(safeSetSubsystem);
},
requirements: {
Subsystem: {
type: entities.EnumField.fieldType
},
SubtaskOf: {
type: entities.IssueLinkPrototype,
name: 'Subtask',
outward: 'parent for',
inward: 'subtask of'
}
}
}); напиши условие срабатывания скрипта. Должен срабатывать если задача становиться подзадачей для другой задачи
|
3da0e2cce9225b81ebb7834201e8392d
|
{
"intermediate": 0.5769392251968384,
"beginner": 0.23986953496932983,
"expert": 0.1831912398338318
}
|
11,940
|
Give me some very complicated terraform code with using for_each, count, toset, lookup and few others functions
|
8f5dd30f55c0f66a26df92069d685fdd
|
{
"intermediate": 0.37485820055007935,
"beginner": 0.40881797671318054,
"expert": 0.2163238525390625
}
|
11,941
|
ReferenceError: C:\Users\Ilya\Downloads\my-musician-network\views\profile.ejs:259
257| const cityInput = document.querySelector("#edit-profile-modal input[name='city']");
258|
>> 259| queryInput.value = "<%= query %>";
260| roleInput.value = "<%= role %>";
261| cityInput.value = cityInput.getAttribute('data-value');
262|
query is not defined
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Popper.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200">
</div>
<div class="col-md-8">
<h1><%= musician.name %></h1>
<p><strong>Role:</strong> <%= musician.role %></p>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<% if (musician.role === 'Artist' && musician.instrument) { %>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<% } %>
<p><strong>Location:</strong> <%= musician.city %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (musician.soundcloud) { %>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
</div>
<% } %>
<% if (musician.soundcloud1) { %>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
</div>
<!-- загрузка музла -->
<div>
<h2>Tracks:</h2>
<ul>
<% tracks.forEach(track => { %>
<li>
<%= track.title %> (<%= track.album_title || "No Album" %>)
<audio controls>
<source src="/tracks/<%= track.filename %>" type="audio/mpeg">
</audio>
<img src="/img/<%= track.image_filename || 'default-track-image.jpg' %>" alt="<%= track.title %>" width="200" height="200">
</li>
<% }); %>
</ul>
</div>
<div>
<h2>Upload a new track:</h2>
<form action="/profile/<%= musician.id %>/upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="track">Track file:</label>
<input type="file" id="track" name="track" accept="audio/" class="form-control-file" required>
</div>
<div class="form-group">
<label for="title">Track title:</label>
<input type="text" id="title" name="title" class="form-control" required>
</div>
<div class="form-group">
<label for="albumTitle">Album title:</label>
<input type="text" id="albumTitle" name="albumTitle" class="form-control">
</div>
<div class="form-group">
<label for="image">Track image:</label>
<input type="file" id="image" name="image" accept="image/" class="form-control-file">
</div>
<button type="submit" class="btn btn-primary">Upload Track</button>
</form>
</div>
<!-- конец -->
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button>
<div id="edit-profile-modal" class="modal fade">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Profile</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control">
</div>
<div class="form-group">
<label for="role">Role:</label>
<select id="role" name="role" class="form-control">
<option value="">Select a role</option>
<option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option>
<option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Genre:</label>
<select id="genre" name="genre" class="form-control">
<option value="">Select a genre</option>
<option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option>
<option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option>
<option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option>
<option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option>
<option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option>
<option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option>
</select>
</div>
<% if (musician.role === 'Artist') { %>
<div class="form-group">
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control">
</div>
<% } %>
<div class="form-group">
<label for="city">Location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control">
</div>
<div class="form-group">
<label for="bio">Bio:</label>
<textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea>
</div>
<div class="form-group">
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file">
</div>
<div class="form-group">
<label for="soundcloud">Soundcloud Track:</label>
<input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control">
</div>
<div class="form-group">
<label for="soundcloud1">Soundcloud Track 2:</label>
<input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
//скрыть плеер, если ссылка не внесена
const song1Input = document.getElementById("soundcloud");
const song2Input = document.getElementById("soundcloud1");
const player1 = document.getElementsByTagName('iframe')[0];
const player2 = document.getElementsByTagName('iframe')[1];
let songs = {
song: "",
song1: ""
}
function hidePlayer(player) {
player.src = "";
player.style.display = "none";
}
function updateSongs() {
songs.song = song1Input.value.trim();
songs.song1 = song2Input.value.trim();
}
function updatePlayers() {
if (songs.song !== "") {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (songs.song1 !== "") {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
song1Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
song2Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
updateSongs();
updatePlayers();
//Валидация ссылок с soundcloud
function updatePlayers() {
if (isValidSoundcloudUrl(songs.song)) {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (isValidSoundcloudUrl(songs.song1)) {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
function isValidSoundcloudUrl(url) {
const regex = /^https?:\/\/(soundcloud\.com|snd\.sc)\/(.*)$/;
return regex.test(url);
}
</script>
<script>
$("input[name='city']").autocomplete({
source: '/autocomplete/cities',
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#edit-profile-modal input[name='city']");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
</script>
<style>
.ui-autocomplete {
z-index: 9999;
}
</style>
</body>
</html>
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'music', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'music' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
});
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users WHERE city LIKE ?",
[searchString + '%'],
(error, results, fields) => {
if (error) {
console.error("Ошибка выполнения запроса: ", error);
res.status(500).send("Ошибка выполнения запроса");
} else {
const cities = results.map(row => row.city);
res.json(cities);
}
}
);
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks });
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].id);
} else {
res.render("login", { error: "Invalid login or password" });
}
}
}
);
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.post("/profile/:id/edit", requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const albumTitle = req.body.albumTitle || '';
const track = {
musician_id: musicianId,
title,
albumTitle,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
|
909a87584a4ca5fa015378b3b112d168
|
{
"intermediate": 0.3776165246963501,
"beginner": 0.5056113600730896,
"expert": 0.11677215993404388
}
|
11,942
|
import re
import requests
import difflib
API_KEY = "CXTB4IUT31N836G93ZI3YQBEWBQEGGH5QS"
BASE_URL = "https://api.bscscan.com/api"
similarity_threshold = 0.01
def get_contract_source_code(address):
params = {
"module": "contract",
"action": "getsourcecode",
"address": address,
"apiKey": API_KEY
}
response = requests.get(BASE_URL, params=params)
data = response.json()
if data["status"] == "1":
source_code = data["result"][0]["SourceCode"]
return source_code
else:
return None
def jaccard_similarity(str1, str2):
a = set(str1.split())
b = set(str2.split())
c = a.intersection(b)
return float(len(c)) / (len(a) + len(b) - len(c))
def find_similar_contracts(reference_addresses, candidate_addresses):
reference_source_codes = {}
for reference_address in reference_addresses:
source_code = get_contract_source_code(reference_address)
if source_code is not None:
reference_source_codes[reference_address] = source_code
if not reference_source_codes:
print("No source code found for reference contracts")
return []
similar_contracts = {}
for address in candidate_addresses:
candidate_source_code = get_contract_source_code(address)
if candidate_source_code is not None:
for reference_address, reference_source_code in reference_source_codes.items():
similarity = jaccard_similarity(candidate_source_code, reference_source_code)
if similarity >= similarity_threshold:
if reference_address not in similar_contracts:
similar_contracts[reference_address] = [(address, similarity)]
else:
similar_contracts[reference_address].append((address, similarity))
return similar_contracts
def print_code_difference(reference_code, candidate_code):
reference_lines = reference_code.splitlines()
candidate_lines = candidate_code.splitlines()
diff = difflib.unified_diff(reference_lines, candidate_lines)
for line in diff:
print(line)
if __name__ == "__main__":
reference_addresses = ["0x445645eC7c2E66A28e50fbCF11AAa666290Cd5bb"]
candidate_addresses = ["0x4401E60E39F7d3F8D5021F113306AF1759a6c168"]
similar_contracts = find_similar_contracts(reference_addresses, candidate_addresses)
print("Contracts with similar source code (ignoring comments):")
for reference_address, similar_addresses in similar_contracts.items():
reference_code = get_contract_source_code(reference_address)
for address, similarity in similar_addresses:
print(f"Reference contract: {reference_address}")
candidate_code = get_contract_source_code(address)
print(f"Similar contract: {address} with a similarity of {similarity:.2f}")
if similarity < 1.0:
print("Code differences:")
print_code_difference(reference_code, candidate_code)
print("\n")
Complete the code above so that it outputs the codes of each of the codes to a text file
|
aca39e637da2304f9c0c795205e992c7
|
{
"intermediate": 0.36535459756851196,
"beginner": 0.36562785506248474,
"expert": 0.26901760697364807
}
|
11,943
|
import React from 'react';
import { yupResolver } from '@hookform/resolvers/yup';
import { Grid } from '@material-ui/core';
import cx from 'classnames';
import { isAfter, isBefore, isEqual, isValid } from 'date-fns';
import { Controller, useForm } from 'react-hook-form';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import * as Yup from 'yup';
import { Button, DateTimePicker, Select, TextField } from 'components/common';
import { idOptions, mspmFunctionOptions } from 'constants/ActivityLog';
import {
DATE_FORMAT_WITH_SECONDS,
MAX_DATE,
MIN_DATE,
} from 'constants/manualActions';
import { routePaths } from 'constants/Routes';
import { noSpaces } from 'constants/Validations';
import { useFlagsContext } from 'contexts/FlagsContext';
import { MSPMFunction } from 'models/ActivityLog';
import { ActivityLogSearchFormValues } from 'models/ActivityLogSearchForm';
import { BranchStatus } from 'models/BranchStatus';
import { SetActivityLogSearchFormValues } from 'models/Context';
import { getQueryParams, setQueryParams } from 'utils/ActivityLog';
import './ActivitySearchForm.scss';
export interface ActivitySearchFormProps {
searchStatus: BranchStatus;
selectedSearchValues: ActivityLogSearchFormValues;
setSelectedSearchValues: SetActivityLogSearchFormValues;
}
export const ActivitySearchForm: React.FC<ActivitySearchFormProps> = ({
searchStatus,
selectedSearchValues,
setSelectedSearchValues,
}) => {
const { t } = useTranslation();
const navigate = useNavigate();
const {
control,
handleSubmit,
watch,
setValue,
formState: { errors, isValid: isFormValid },
clearErrors,
} = useForm({
resolver: yupResolver(
Yup.object().shape({
startTime: Yup.date().required(),
endTime: Yup.date().required(),
username: Yup.string(),
idType: Yup.string(),
id: Yup.string().matches(
noSpaces,
t('validations.cannotContainSpaces'),
),
action: Yup.string(),
}),
),
mode: 'onChange',
});
const { flags } = useFlagsContext();
const mspmFunctionOptionsWithFlag = [...mspmFunctionOptions];
if (!flags.BLOCK_SETTLEMENT_FLAG) {
mspmFunctionOptionsWithFlag.push({
label: 'Block Settlement',
value: MSPMFunction.BLOCK_SETTLEMENT,
});
}
if (!flags.SPORTEX_ID_FLAG) {
mspmFunctionOptionsWithFlag.push({
label: 'Sportex ID re-map',
value: MSPMFunction.SPORTEX_REMAPPING,
});
}
const startTimeWatch = watch('startTime');
const endTimeWatch = watch('endTime');
const idTypeWatch = watch('idType');
const loading = searchStatus === BranchStatus.LOADING;
const onSubmit = (data: ActivityLogSearchFormValues) => {
setSelectedSearchValues(data);
const params = setQueryParams(data);
navigate(`${routePaths.activityLog.resultsPath}?${getQueryParams(params)}`);
};
React.useEffect(() => {
setValue('startTime', selectedSearchValues.startTime);
setValue('endTime', selectedSearchValues.endTime);
}, [setValue, selectedSearchValues]);
return (
<form
className="activity-search-form form"
data-testid="activity-search-form"
onSubmit={handleSubmit(onSubmit)}
>
<Grid container spacing={2}>
<Grid item xs={3} style={{ minWidth: '16rem' }}>
<Controller
name="startTime"
control={control}
defaultValue={selectedSearchValues.startTime}
render={({ onChange, value, name }) => (
<DateTimePicker
label={t('form.from')}
name={name}
testId="activity-search-form-from-date"
onChange={onChange}
value={value}
maxDate={endTimeWatch ?? MAX_DATE}
format={DATE_FORMAT_WITH_SECONDS}
maxDateMessage={t('validations.fromMaxMessage')}
variant="dialog"
placeholder={t(
'components.activitySearchForm.dateTimePlaceholder',
)}
/>
)}
/>
</Grid>
<Grid item xs={3} style={{ minWidth: '16rem' }}>
<Controller
name="endTime"
control={control}
defaultValue={selectedSearchValues.endTime}
render={({ onChange, value, name }) => (
<DateTimePicker
label={t('form.to')}
name={name}
testId="activity-search-form-to-date"
onChange={onChange}
format={DATE_FORMAT_WITH_SECONDS}
value={value}
minDate={startTimeWatch ?? MIN_DATE}
minDateMessage={t('validations.toMinMessage')}
variant="dialog"
placeholder={t(
'components.activitySearchForm.dateTimePlaceholder',
)}
/>
)}
/>
</Grid>
<Grid item xs style={{ flex: '1 0 auto' }}>
<Controller
name="username"
control={control}
defaultValue={selectedSearchValues.username}
render={({ onChange, value, name }) => (
<TextField
optional
testId="activity-search-form-username"
placeholder={t(
'components.activitySearchForm.usernamePlaceholder',
)}
label={t('components.activitySearchForm.usernameLabel')}
value={value}
name={name}
onChange={onChange}
/>
)}
/>
</Grid>
<Grid item xs={3} style={{ minWidth: '16rem' }}>
<Controller
name="idType"
control={control}
defaultValue={selectedSearchValues.idType}
render={({ onChange, value, name }) => (
<Select
optional
testId="activity-search-form-id-type"
placeholder={t('form.idTypePlaceholder')}
label={t('form.idTypeLabel')}
onChange={(event) => {
if (event.target.value === '') {
setValue('id', '');
clearErrors('id');
}
onChange(event.target.value);
}}
value={value}
name={name}
options={idOptions}
/>
)}
/>
</Grid>
<Grid item xs={3} style={{ minWidth: '16rem' }}>
<Controller
name="id"
control={control}
defaultValue={selectedSearchValues.id}
render={({ onChange, value, name }) => (
<div className="activity-search-form__id">
<TextField
testId="activity-search-form-id"
placeholder={t('form.idPlaceholder')}
onChange={onChange}
value={value}
className={cx({
disabled: !idTypeWatch,
})}
name={name}
disabled={!idTypeWatch}
error={!!errors.id}
helperText={errors.id?.message}
label={t('form.idLabel')}
optional
/>
</div>
)}
/>
</Grid>
<Grid item xs style={{ flex: '1 0 auto' }}>
<Controller
name="action"
control={control}
defaultValue={selectedSearchValues.action}
render={({ onChange, value, name }) => (
<Select
aria-label={`activity-search-form-mspm-function-${name}`}
testId="activity-search-form-mspm-function"
onChange={onChange}
name={name}
value={value}
options={mspmFunctionOptionsWithFlag}
placeholder={t(
'components.activitySearchForm.mspmFunctionPlaceholder',
)}
label={t('components.activitySearchForm.mspmFunctionLabel')}
optional
/>
)}
/>
</Grid>
<Grid item xs={12}>
<Button
testId="activity-search-form-submit-button"
className="activity-search-form__submit-button"
buttonColor="positive"
type="submit"
disabled={
!isValid(startTimeWatch) ||
!isValid(endTimeWatch) ||
(!isBefore(startTimeWatch, endTimeWatch) &&
!isEqual(startTimeWatch, endTimeWatch)) ||
isBefore(startTimeWatch, new Date(MIN_DATE)) ||
isAfter(endTimeWatch, new Date(MAX_DATE)) ||
loading ||
(!isFormValid && !!idTypeWatch)
}
loading={loading}
>
{t('common.cta.submit')}
</Button>
</Grid>
</Grid>
</form>
);
}; how best to use yup so that I don't have to do this disabled={
!isValid(startTimeWatch) ||
!isValid(endTimeWatch) ||
(!isBefore(startTimeWatch, endTimeWatch) &&
!isEqual(startTimeWatch, endTimeWatch)) ||
isBefore(startTimeWatch, new Date(MIN_DATE)) ||
isAfter(endTimeWatch, new Date(MAX_DATE)) ||
loading ||
(!isFormValid && !!idTypeWatch)
}
|
09d9cde2a01c038195030c9d54e26218
|
{
"intermediate": 0.4470211863517761,
"beginner": 0.3496851325035095,
"expert": 0.20329374074935913
}
|
11,944
|
schema = Schema(id=ID(stored=True),
task=TEXT(stored=True),
answer=TEXT(stored=True),
topics_name = TEXT(stored=True))
index_dir = ‘tasks_index’
if not os.path.exists(index_dir):
os.mkdir(index_dir)
ix = create_in(index_dir, schema)
else:
ix = open_dir(index_dir)
with ix.searcher() as searcher:
query = QueryParser(‘topics_name’, ix.schema).parse(‘Деление’)
results = searcher.search(query, limit=None)
print(results)
for hit in results:
print(hit) В этом коде проблем не возникает как и если мы поменяем query = QueryParser(‘task’, ix.schema).parse(‘Деление’) . Однако query = QueryParser(‘task’,‘topics_name’, ix.schema).parse(‘Деление’) выдает ошибку AttributeError: ‘TEXT’ object has no attribute ‘taggers’. Как это исправить?
|
334e9cc479a3b2731bda0f9b04734f7f
|
{
"intermediate": 0.49247121810913086,
"beginner": 0.29307976365089417,
"expert": 0.2144489735364914
}
|
11,945
|
Когда я загружаю .mp3 файл, изображение альбома, и жму upload track - ничего не происходит, происходит редирект на страницу профиля с модального окна, в базе данных трека нет. вот полный код:
profile.ejs:
<!DOCTYPE html>
<html>
<head>
<title><%= musician.name %> - Musician Profile</title>
<link rel="stylesheet" href="/jquery-ui/themes/base/all.css" />
<script src="/jquery/dist/jquery.min.js"></script>
<script src="/jquery-ui/dist/jquery-ui.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- Popper.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-3">
<img src="/img/<%= musician.thumbnail || 'avatar.jpg' %>" alt="<%= musician.name %>" width="200" height="200">
</div>
<div class="col-md-8">
<h1><%= musician.name %></h1>
<p><strong>Role:</strong> <%= musician.role %></p>
<p><strong>Genre:</strong> <%= musician.genre %></p>
<% if (musician.role === 'Artist' && musician.instrument) { %>
<p><strong>Instrument:</strong> <%= musician.instrument %></p>
<% } %>
<p><strong>Location:</strong> <%= musician.city %></p>
<p><strong>Bio:</strong> <%= musician.bio %></p>
<% if (musician.soundcloud) { %>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
</div>
<% } %>
<% if (musician.soundcloud1) { %>
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="https://w.soundcloud.com/player/?url=<%= musician.soundcloud1 %>&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true"></iframe>
</div>
<!-- загрузка музла -->
<!-- конец -->
<% } %>
<% if (userLoggedIn && username === musician.name) { %>
<button type="button" class="btn btn-primary mt-3 mb-3" data-toggle="modal" data-target="#edit-profile-modal">Edit Profile</button>
<div id="edit-profile-modal" class="modal fade">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Profile</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<form action="/profile/<%= musician.id %>/edit" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="<%= musician.name %>" class="form-control">
</div>
<div class="form-group">
<label for="role">Role:</label>
<select id="role" name="role" class="form-control">
<option value="">Select a role</option>
<option value="Band" <%= musician.role === 'Band' ? 'selected' : '' %>>Band</option>
<option value="Artist" <%= musician.role === 'Artist' ? 'selected' : '' %>>Artist</option>
</select>
</div>
<div class="form-group">
<label for="genre">Genre:</label>
<select id="genre" name="genre" class="form-control">
<option value="">Select a genre</option>
<option value="Rock" <%= musician.genre === 'Rock' ? 'selected' : '' %>>Rock</option>
<option value="Pop" <%= musician.genre === 'Pop' ? 'selected' : '' %>>Pop</option>
<option value="Hip-hop" <%= musician.genre === 'Hip-hop' ? 'selected' : '' %>>Hip-hop</option>
<option value="Jazz" <%= musician.genre === 'Jazz' ? 'selected' : '' %>>Jazz</option>
<option value="Electronic" <%= musician.genre === 'Electronic' ? 'selected' : '' %>>Electronic</option>
<option value="Classical" <%= musician.genre === 'Classical' ? 'selected' : '' %>>Classical</option>
</select>
</div>
<% if (musician.role === 'Artist') { %>
<div class="form-group">
<label for="instrument">Instrument:</label>
<input type="text" id="instrument" name="instrument" value="<%= musician.instrument || '' %>" class="form-control">
</div>
<% } %>
<div class="form-group">
<label for="city">Location:</label>
<input id="city" name="city" type="text" autocomplete="on" value="<%= city %>" data-value="" class="form-control">
</div>
<div class="form-group">
<label for="bio">Bio:</label>
<textarea id="bio" name="bio" class="form-control"><%= musician.bio %></textarea>
</div>
<div class="form-group">
<label for="thumbnail">Thumbnail:</label>
<input type="file" id="thumbnail" name="thumbnail" accept="image/*" class="form-control-file">
</div>
<!-- загрузка музла -->
<div>
<h2>Tracks:</h2>
<ul>
<% tracks.forEach(track => { %>
<li>
<%= track.title %> (<%= track.album_title || "No Album" %>)
<audio controls>
<source src="/tracks/<%= track.filename %>" type="audio/mpeg">
</audio>
<img src="/img/<%= track.image_filename || 'default-track-image.jpg' %>" alt="<%= track.title %>" width="200" height="200">
</li>
<% }); %>
</ul>
</div>
<div>
<h2>Upload a new track:</h2>
<form action="/profile/<%= musician.id %>/upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="track">Track file:</label>
<input type="file" id="track" name="track" accept="audio/" class="form-control-file" required>
</div>
<div class="form-group">
<label for="title">Track title:</label>
<input type="text" id="title" name="title" class="form-control" required>
</div>
<div class="form-group">
<label for="albumTitle">Album title:</label>
<input type="text" id="albumTitle" name="albumTitle" class="form-control">
</div>
<div class="form-group">
<label for="image">Track image:</label>
<input type="file" id="image" name="image" accept="image/" class="form-control-file">
</div>
<button type="submit" class="btn btn-primary">Upload Track</button>
</form>
</div>
<!-- конец -->
<div class="form-group">
<label for="soundcloud">Soundcloud Track:</label>
<input type="text" id="soundcloud" name="soundcloud" value="<%= musician.soundcloud || '' %>" class="form-control">
</div>
<div class="form-group">
<label for="soundcloud1">Soundcloud Track 2:</label>
<input type="text" id="soundcloud1" name="soundcloud1" value="<%= musician.soundcloud1 || '' %>" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save Changes</button>
</form>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
<script>
const modal = document.getElementById("edit-profile-modal");
const btn = document.getElementsByTagName("a")[0];
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
//скрыть плеер, если ссылка не внесена
const song1Input = document.getElementById("soundcloud");
const song2Input = document.getElementById("soundcloud1");
const player1 = document.getElementsByTagName('iframe')[0];
const player2 = document.getElementsByTagName('iframe')[1];
let songs = {
song: "",
song1: ""
}
function hidePlayer(player) {
player.src = "";
player.style.display = "none";
}
function updateSongs() {
songs.song = song1Input.value.trim();
songs.song1 = song2Input.value.trim();
}
function updatePlayers() {
if (songs.song !== "") {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (songs.song1 !== "") {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
song1Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
song2Input.addEventListener("input", function() {
updateSongs();
updatePlayers();
});
updateSongs();
updatePlayers();
//Валидация ссылок с soundcloud
function updatePlayers() {
if (isValidSoundcloudUrl(songs.song)) {
player1.src = `https://w.soundcloud.com/player/?url=${songs.song}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player1.style.display = "block";
} else {
hidePlayer(player1);
}
if (isValidSoundcloudUrl(songs.song1)) {
player2.src = `https://w.soundcloud.com/player/?url=${songs.song1}&color=%23ff5500&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&show_teaser=true&visual=true`;
player2.style.display = "block";
} else {
hidePlayer(player2);
}
}
function isValidSoundcloudUrl(url) {
const regex = /^https?:\/\/(soundcloud\.com|snd\.sc)\/(.*)$/;
return regex.test(url);
}
</script>
<script>
$("input[name='city']").autocomplete({
source: '/autocomplete/cities',
minLength: 1,
});
const queryInput = document.querySelector("#query");
const roleInput = document.querySelector("#role");
const cityInput = document.querySelector("#edit-profile-modal input[name='city']");
queryInput.value = "<%= query %>";
roleInput.value = "<%= role %>";
cityInput.value = cityInput.getAttribute('data-value');
const query = queryInput.value;
const role = roleInput.value;
const city = cityInput.value;
</script>
<style>
.ui-autocomplete {
z-index: 9999;
}
</style>
</body>
</html>
app.js:
const express = require("express");
const fs = require("fs");
const session = require("express-session");
const fileUpload = require("express-fileupload");
const app = express();
const fuzzball = require("fuzzball");
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'music', // замените на свой логин
password: 'password', // замените на свой пароль
database: 'music' // замените на свою базу данных
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ', err);
} else {
console.log('Подключение к базе данных успешно');
}
});
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(fileUpload());
app.use(session({
secret: "mysecretkey",
resave: false,
saveUninitialized: false
}));
const citiesAndRegions = JSON.parse(fs.readFileSync("./db/russia.json", "utf8"));
connection.query("CREATE TABLE IF NOT EXISTS tracks (id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY, musician_id int(11) NOT NULL, title varchar(255) NOT NULL, album_title varchar(255), filename varchar(255) NOT NULL, image_filename varchar(255), uploaded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)", (err, result) => {
if(err) throw err;
});
//const predefinedGenres = ['Rock', 'Pop', 'Jazz', 'Hip Hop', 'Electronic', 'Blues'];
// Функция для получения последних музыкантов, зарегистрированных музыкантов
function getLastNRegisteredMusicians(N, callback) {
connection.query("SELECT * FROM users ORDER BY id DESC LIMIT ?", [N], (err, result) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
//функция для получения песен музыканта по id
function getMusicianTracks(musicianId, callback) {
connection.query("SELECT * FROM tracks WHERE musician_id=?", [musicianId], (err, result) => {
if (err) {
console.error("Ошибка при получении песен музыканта с id ${musicianId}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result);
}
});
}
function getMusicians(callback) {
connection.query("SELECT * FROM users", (err, result) => {
if (err) {
console.error("Ошибка при получении списка музыкантов: ", err);
return callback(err);
} else {
return callback(null, result);
}
});
}
// Функция для получения музыканта по id
function getMusicianById(id, callback) {
connection.query("SELECT * FROM users WHERE id=?", [id], (err, result) => {
if (err) {
console.error("Ошибка при получении музыканта с id ${id}: ", err);
return typeof callback === 'function' && callback(err);
} else {
return typeof callback === 'function' && callback(null, result[0]);
}
});
}
function requireLogin(req, res, next) {
if (req.session.musicianId) {
next();
} else {
res.redirect("/login");
}
}
//функция поиска
function search(query = '', role = '', city = '', genre = '', callback) {
let results = [];
// Формируем запрос на выборку с базы данных в зависимости от переданных параметров поиска
let queryStr = "SELECT * FROM users WHERE (name LIKE ? OR genre LIKE ?)";
let queryParams = ['%' + query + '%', '%' + query + '%'];
if (role !== '') {
queryStr += " AND role = ?";
queryParams.push(role);
}
if (city !== '') {
queryStr += " AND city = ?";
queryParams.push(city);
}
if (genre !== '') {
queryStr += " AND genre = ?";
queryParams.push(genre);
}
// Выполняем запрос к базе данных
connection.query(queryStr, queryParams, (err, resultsDB) => {
if (err) {
console.error("Ошибка при выполнении запроса: ", err);
return callback(err);
}
else {
// Формируем список музыкантов на основе результата запроса
results = resultsDB.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
// Удаляем дубликаты из списка
results = results.filter((result, index, self) =>
index === self.findIndex(r => (
r.name === result.name && r.genre === result.genre && r.city === result.city
))
);
// Сортируем по score (у словарей scoreA и scoreB значения по умолчанию равны 0, так что сортировка по алфавиту)
results.sort((a, b) => {
let scoreA = 0;
let scoreB = 0;
if (a.name.toLowerCase().includes(query)) {
scoreA++;
}
if (a.genre.toLowerCase().includes(query)) {
scoreA++;
}
if (b.name.toLowerCase().includes(query)) {
scoreB++;
}
if (b.genre.toLowerCase().includes(query)) {
scoreB++;
}
// Сортировка по score (убывающая)
return scoreB - scoreA;
});
// Вызываем callback-функцию с результатами поиска
return callback(null, results);
}
});
}
app.use((req, res, next) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении current user: ", err);
} else {
res.locals.musician = musician;
res.locals.userLoggedIn = true;
res.locals.username = musician.name;
}
});
} else {
res.locals.userLoggedIn = false;
}
next();
});
app.get("/", (req, res) => {
getLastNRegisteredMusicians(5, (err, lastRegisteredMusicians) => {
if (err) {
console.error("Ошибка при получении последних зарегистрированных музыкантов: ", err);
res.status(500).send("Ошибка получения данных");
} else {
res.render("index", { musicians: lastRegisteredMusicians, query:'',city:'',role:'',genre:'' });
}
});
});
app.get("/autocomplete/cities", async (req, res) => {
const searchString = req.query.term;
connection.query(
"SELECT DISTINCT city FROM users WHERE city LIKE ?",
[searchString + '%'],
(error, results, fields) => {
if (error) {
console.error("Ошибка выполнения запроса: ", error);
res.status(500).send("Ошибка выполнения запроса");
} else {
const cities = results.map(row => row.city);
res.json(cities);
}
}
);
});
app.get("/register", (req, res) => {
if (req.session.musicianId) {
const musician = getMusicianById(req.session.musicianId);
res.redirect("/profile/" + musician.id);
} else {
res.render("register", { citiesAndRegions, city:'', query:'',role:'' });
}
});
app.post("/register", (req, res) => {
if (req.session.musicianId) {
getMusicianById(req.session.musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
} else {
res.redirect("/profile/" + musician.id);
}
});
} else {
// Проверка на уникальность логина
connection.query("SELECT * FROM users WHERE login=?", [req.body.login], (err, result) => {
if (err) {
console.error("Ошибка при проверке логина: ", err);
res.status(500).send("Ошибка при регистрации");
} else {
if (result.length > 0) {
res.render("register", { error: "This login is already taken", citiesAndRegions, city:'', query:'', role:'' });
} else {
const newMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
password: req.body.password,
role: req.body.role,
city: req.body.city,
login: req.body.login,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + file.name;
file.mv("./public/img/" + filename);
newMusician.thumbnail = filename;
}
connection.query("INSERT INTO users SET ?", newMusician, (err, result) => {
if (err) {
console.error("Ошибка при регистрации нового музыканта: ", err);
res.status(500).send("Ошибка регистрации");
} else {
req.session.musicianId = result.insertId;
res.redirect("/profile/" + result.insertId);
}
});
}
}
});
}
});
app.get("/profile/:id", (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
getMusicianTracks(musician.id, (err, tracks) => {
if(err) {
console.error("Ошибка при получении треков для профиля: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
res.render("profile", { musician: musician, tracks: tracks, query:'', role:'', city:''});
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.get("/login", (req, res) => {
res.render("login");
});
app.post("/login", (req, res) => {
connection.query("SELECT * FROM users WHERE login=? AND password=?", [req.body.login, req.body.password], (err, result) => {
if (err) {
console.error("Ошибка при входе: ", err);
res.status(500).send("Ошибка при входе");
} else {
if (result.length > 0) {
req.session.musicianId = result[0].id;
res.redirect("/profile/" + result[0].id);
} else {
res.render("login", { error: "Invalid login or password" });
}
}
}
);
});
app.get("/logout", (req, res) => {
req.session.destroy();
res.redirect("/");
});
app.get('/search', (req, res) => {
let query = req.query.query || '';
const role = req.query.role || '';
const city = req.query.city || '';
const genre = req.query.genre || '';
if (query || role || city || genre) {
search(query, role, city, genre, (err, musicians) => {
if (err) {
res.status(500).send("Ошибка при выполнении поиска");
} else {
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
} else {
// Use the getMusicians function instead of reading from musicians.json
getMusicians((err, musiciansList) => {
if (err) {
res.status(500).send("Ошибка при получении списка музыкантов");
} else {
const musicians = musiciansList.map(musician => {
return {
name: musician.name,
genre: musician.genre,
originalName: musician.name,
profileLink: `/profile/${musician.id}`,
thumbnail: musician.thumbnail,
soundcloud: musician.soundcloud,
role: musician.role,
city: musician.city
};
});
app.locals.JSON = JSON;
res.render('search', { musicians, query, role, city, genre, citiesAndRegions});
}
});
}
});
app.get("/profile/:id/edit", requireLogin, (req, res) => {
getMusicianById(parseInt(req.params.id), (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
if (req.session.musicianId === musician.id) { // Check if the logged-in user is the owner of the profile
res.render("edit-profile", { musician: musician });
} else {
res.status(403).send("Access denied");
}
} else {
res.status(404).send("Musician not found");
}
}
});
});
app.post("/profile/:id/edit", requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
getMusicianById(musicianId, (err, musician) => {
if (err) {
console.error("Ошибка при получении музыканта: ", err);
res.status(500).send("Ошибка при получении данных");
} else {
if (musician) {
const updatedMusician = {
name: req.body.name,
genre: req.body.genre,
instrument: req.body.instrument,
soundcloud: req.body.soundcloud,
soundcloud1: req.body.soundcloud1,
city: req.body.city,
role: req.body.role,
bio: req.body.bio,
};
if (req.files && req.files.thumbnail) {
const file = req.files.thumbnail;
const filename = "musician_" + musicianId + "_" + file.name;
file.mv("./public/img/" + filename);
updatedMusician.thumbnail = filename;
}
connection.query("UPDATE users SET ? WHERE id=?", [updatedMusician, musicianId], (err, result) => {
if (err) {
console.error("Ошибка при обновлении профиля музыканта: ", err);
res.status(500).send("Ошибка при обновлении профиля");
} else {
res.redirect("/profile/" + musicianId);
}
});
} else {
res.status(404).send("Musician not found");
}
}
});
});
//загрузка музыки и изображений к музыке
app.post("/profile/:id/upload", requireLogin, (req, res) => {
const musicianId = parseInt(req.params.id);
if (!req.files) {
res.status(400).send("No files were uploaded.");
return;
}
const trackFile = req.files.track;
if (!trackFile) {
res.status(400).send("No track file was uploaded.");
return;
}
const trackFilename = "track_" + musicianId + "" + trackFile.name;
trackFile.mv("./public/tracks/" + trackFilename);
const title = req.body.title;
const albumTitle = req.body.albumTitle || '';
const track = {
musician_id: musicianId,
title,
albumTitle,
filename: trackFilename,
};
if (req.files.image) {
const imageFile = req.files.image;
const imageFilename = "image" + musicianId + "_" + imageFile.name;
imageFile.mv("./public/img/" + imageFilename);
track.image_filename = imageFilename;
}
connection.query("INSERT INTO tracks SET ?", track, (err, result) => {
if (err) {
console.error("Ошибка при добавлении трека: ", err);
res.status(500).send("Ошибка при добавлении трека");
} else {
res.redirect("/profile/" + musicianId);
}
});
});
function isValidSoundCloudUrl(url) {
return url.startsWith('https://soundcloud.com/');
}
app.listen(3000, () => {
console.log("Server started on port 3000");
});
|
286c0acd033ba42b90b8e9d2fa95b166
|
{
"intermediate": 0.3055392801761627,
"beginner": 0.4503134787082672,
"expert": 0.24414725601673126
}
|
11,946
|
I have an arduino and im trying to implement stepper driver with interrupt. For that i code stepper motor class in stepper.h file and for running many stepper motor at the same time from interrupt routine i wanted to declare global volatile stepper array. What is the best practise to do that
|
80c4c2b75180d16eaec4b09312f009c8
|
{
"intermediate": 0.4730437994003296,
"beginner": 0.2618076801300049,
"expert": 0.26514849066734314
}
|
11,947
|
How to realize private and public routes in React applications?
|
012891f80262fa435e7b5fe39809392f
|
{
"intermediate": 0.325651079416275,
"beginner": 0.22007356584072113,
"expert": 0.4542753994464874
}
|
11,948
|
what is the fastest way to find prime number in c++ i want input for length prime to find for example if i want 3 length will only find random prime number with 3 length
let's work this out in a step by step way to be sure we have the right answer let's work this out in a step by step way to be sure we have the right answer.
|
57a022a35530ab04f10f74e985728926
|
{
"intermediate": 0.3883732855319977,
"beginner": 0.10686998069286346,
"expert": 0.5047567486763
}
|
11,949
|
what is the cmd command for viewing the AD groups I belong to
|
9f8acdc70c7f5652cd963ac1c16b3a5a
|
{
"intermediate": 0.32553038001060486,
"beginner": 0.32942482829093933,
"expert": 0.3450447916984558
}
|
11,950
|
While the img is loading, showing the loading gif
|
d3b8a036da4b0fbf28b3c9a2db3e0136
|
{
"intermediate": 0.36566248536109924,
"beginner": 0.2759069800376892,
"expert": 0.35843053460121155
}
|
11,951
|
let image1;
let image2;
let image3;
let image4;
let overlayImage;
let currentImageIndex = 0;
let falling = false;
let broken = false;
let overlayY = 0;
let oriPostionX=0;
let oriPostionY=0;
let px= 0;
let py =0;
function preload() {
// 加载图片
image1 = loadImage('loudao.jpg'); //楼道
image2 = loadImage('fangjian4.jpg');//第四个房间
image3 = loadImage('datu4.jpg'); // 放大的窗户
pingzi = loadImage('pingzi.png'); // 瓶子的图片
image4 = loadImage('kaichuang.jpg');
smashSound = loadSound('glass_smash.mp3');
oriPostionX=windowWidth/2 +200;
oriPostionY=windowHeight/2 +100;
px=oriPostionX;
py=oriPostionY;//这里是原先的位置,<<<<<
acc=0;
}
function setup() {
createCanvas(windowWidth,windowHeight);
}
function draw() {
// 根据当前图片索引绘制对应的图像
if (currentImageIndex === 0) {
background(0);
imageMode(CENTER);
image(image1, windowWidth/2, windowHeight/2);
imageMode(CORNER);
} else if (currentImageIndex === 1) {
background(10, 24, 37);
imageMode(CENTER);
image(image2, windowWidth/2, windowHeight/2);
imageMode(CORNER);
}
else if(currentImageIndex == 2){
// 在画面中心绘制第三张图片,并将尺寸扩大1.5倍
background(10, 24, 37);
imageMode(CENTER);
image(image3, windowWidth/2, windowHeight/2);
imageMode(CORNER);
}
if(currentImageIndex ==2 && falling) {
imageMode(CENTER);
if(broken==false){
image(pingzi,px,py);
py+=acc*0.1;
acc++; //<<<<acc代表加速度
if(abs(py-windowHeight*7/8)<20){ //<<<<<<<<<<<<当py的坐标临近窗口高度7/8的时候触发事件
smashSound.play();
broken = true;
}
}else{
image(pingzi,px,py);
}
imageMode(CORNER);
}
}
function keyPressed() {
if (key === 'd' || key === 'D') {
currentImageIndex = (currentImageIndex + 1) % 3; // 切换图片索引
if(broken){
falling=false;
broken=false;
px=oriPostionX;
py=oriPostionY;//这里是原先的位置,<<<<<
acc=0;
}
}
if (key === 'q' || key === 'Q') {
falling = true;
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
// 在打碎玻璃后,播放照片image4
function mouseClicked() {
let mic = new p5.AudioIn();
mic.start();
mic.getLevel(function(level) {
console.log(level);
if (level > 0.3) { // 判断声音强度,如果大于0.3就播放第四张图片
imageMode(CENTER);
background(255);
image(image4,windowWidth/2, windowHeight/2);
imageMode(CORNER);
smashSound.stop();
}
});
}让后面代码完善能正常运行,后面声呗部分完善
|
fb86fd6187443807a763cdadb3583847
|
{
"intermediate": 0.2892606556415558,
"beginner": 0.3916129469871521,
"expert": 0.3191264271736145
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.