Skip to main content

Posts

Showing posts from December, 2023

Using pycord and tkinter together returning error

RuntimeWarning: coroutine 'send' was never awaited self.tk.mainloop(n) RuntimeWarning: Enable tracemalloc to get the object allocation traceback I keep getting the above error on my pycord code. I can't figure out why and have looked at multiple discussions. Here is the code. root = Tk() frm = ttk.Frame(root, padding=10) frm.grid() server = StringVar() channel = StringVar() text = StringVar() e1 = Entry(frm, textvariable=server) e1.grid(column=0, row=0) e1.insert(0, 'Server') e2 = Entry(frm, textvariable=channel) e2.grid(column=0, row=1) e2.insert(0, 'Channel') e3 = Entry(frm, textvariable=text) e3.grid(column=0, row=2) e3.insert(0, 'Text') async def send(): for guild in bot.guilds: if guild.name == server.get(): for channel1 in guild.channels: if channel1.name == channel.get(): await channel1.send(text) ttk.Button(frm, text="Send", command=send).grid(column=0, row=4) def run...

Are timing requirements in webRtc between calling setRemoteDescription and addIceCandidate?

I have implemented webrtc in 2 browsers that physically work on one local machine (one browser I will call as "local", another - "remote"). The browser - Firefox 112.0.1, TURN, STUN servers are not used. All strings (offer, answer, ice candidates) are transferred from one to another browser manually (slow transfer - via copy and paste). "Remote" gets an offer from the "local" and processes it by rtc2_RegisterRemoteOffer (see code below). This function creates answer of the "remote". Then: (1) the negotiationneeded event fired on the "remote", (2) because of (1) "remote" creates offer and generates it's own ice candidates (up to here neither "local" nor "remote" ice candidates I didn't transfer to each other). (3) Then after few seconds on the "remote" iceconnectionstate fired with the status failed . The questions are: What may be a reason of iceconnectionstate gets faile...

Form is returning null without any reason [closed]

thanks to give me your time. I actually coding a login page but i can't write form.addEventListener() When i console.log(form) it return null and i don't know why For the js side : const form = document.getElementById("form"); console.log(form) form.addEventListener('submit', (event) => { event.preventDefault console.log(event) console.log(form) }) For the html side : [...] <form id="form"> <label for="email"> Entrez votre Email : </label> <input id="email" type="email" name="email" placeholder="Email ..." required> <label for="mdp"> Entrez votre Mot de Passe : </label> <input type="password" name="password" id="mdp" placeholder="Mot De Passe ..." required> <input type="submit" name="envoyer" id=...

React Native npx create-react-app Problem

My PowerShell(Terminal) Warn, i don't used npm install or any one just tried npx create-react-app NKE command: PS C:\Users\berk.BERK-PC\React Native> npx create-react-app NKE npm WARN using --force Recommended protections disabled. npm WARN using --force Recommended protections disabled. npm ERR! code ENOENT npm ERR! syscall lstat npm ERR! path C:\Users\berk.BERK-PC\React Native\'~ npm ERR! errno -4058 npm ERR! enoent ENOENT: no such file or directory, lstat 'C:\Users\berk.BERK-PC\React Native\'~' npm ERR! enoent This is related to npm not being able to find a file. npm ERR! enoent npm ERR! A complete log of this run can be found in: C:\Users\berk.BERK-PC\AppData\Local\npm-cache\_logs\2023-12-28T21_08_04_536Z-debug-0.log PS C:\Users\berk.BERK-PC\React Native> The Loc File: 0 verbose cli C:\Program Files\nodejs\node.e...

Queenbee evaluation function for Hex

I created an alpha-beta cutoff search agent for Hex that uses the Queen Bee evaluation function, but I cannot get the function to work properly and need help. The evaluation function is described in section 3.2 of this paper. The function is simple and the explanation is quick to read through. I have provided my implementation below and have a couple questions: The function seems to work fine for smaller board sizes, but it cannot be completed quickly for larger boards. What can I do to speed up this calculation? There is definitely a simple fix for this, but this function is difficult for me to debug and test because there are many recursive calls that I need to walk through. Is there a way to skip all the recursive calls and jump back to the original caller in VS Code? def qb_distance(state, qb): def qb_distance_left(pos, d, v, qb_list): r, c = pos[0], pos[1] if c == 0: #if the current position is on the left edge of the board, return d return ...

How do I access Vite configuration from code?

Inside vite.config.ts , I have: export default defineConfig({ base: '', plugins: [react()], server: { open: true, port: 3000, }, }); Is it possible to access these values, especially the port number, from code? Or perhaps it's better to set these through easily accessible environment variables instead? Via Active questions tagged javascript - Stack Overflow https://ift.tt/DV5wcv7

DiscordJS DiscordAPIError[50013]

I want to send a message to a channel here is my index.js const json = require('./jsonEdit.js'); const discordBot = require('./discordBot.js') const youtubeAPI = require('./youtubeAPI.js') const server = require('./httpServer.js') let intervalId = 0 let link = '' const main = async () => { var config = json.readJsonFile('./config.json'); try { result = await json.updateData('./config.json', await youtubeAPI.getChannelIDByUrl(config.YOUTUBE_CHANNEL_LINK)); config = result.config } catch (error) { console.error('Error updating config:', error); config = null } if(config == null) { return } await discordBot.start(json) await server.start(json) intervalId = setInterval(() => aprilFool(json), 1000); // Check every second, adjust as needed process(json) setInterval(() => process(json), config.INTERVAL); } main() async function process(json) { let res = await youtubeA...

Pytorch parameters are not updating

This seems to be a common question for folks who start using pytorch and I guess this one is my version of it. Is it clear to a more experienced pytorch user why my params are not updating as my code loops? import torch import numpy as np np.random.seed(10) def optimize(final_shares: torch.Tensor, target_weight, prices, loss_func=None): final_shares = final_shares.clamp(0.) mv = torch.multiply(final_shares, prices) w = torch.div(mv, torch.sum(mv)) print(w) return loss_func(w, target_weight) def main(): position_count = 16 cash_buffer = .001 starting_shares = torch.tensor(np.random.uniform(low=1, high=50, size=position_count), dtype=torch.float64) prices = torch.tensor(np.random.uniform(low=1, high=100, size=position_count), dtype=torch.float64) prices[-1] = 1. x_param = torch.nn.Parameter(starting_shares, requires_grad=True) target_weights = ((1 - cash_buffer) / (position_count - 1)) target_weights_vec = [target_weights] * (p...

How to Share a Leaflet Map Instance Across Multiple Vue 2 Components?

Background: I'm building a web application using Vue 2 and Leaflet. I'm trying to share a single Leaflet map instance across multiple components in my application. Issue: I'm looking for a way to create a Leaflet map instance in one place and access and use it across multiple components in the entire application. Code Example: This is a method I have tried, but I don't know if this way of writing is appropriate. Maybe there is a better way: App.vue provide() { return { parent: this }; }, mounted() { this.map = L.map('map',{}) } components inject: ["parent"] Is there a more appropriate way? Via Active questions tagged javascript - Stack Overflow https://ift.tt/aVhrA5x

How to do only page segmentation / layout detection with Tesseract (mode --psm 2)?

I would like to use page segmentation from Tesseract without running the OCR, as I have my own custom OCR model, and it takes to long to run page segmentation AND OCR. I tried using the --psm 2 mode in command line mode of Tesseract , and in pytesseract , and it didn't work as promised. I'm working in Linux, and am coding in Python 3.10. I currently use the tesseract-ocr-api from layoutparser Documentation . The code looks like the following: import layoutparser as lp ocr_agent = lp.TesseractAgent() res = ocr_agent.detect(img_path, return_response=True) layout_info = res['data'] The layout_info then is a pd.DataFrame and contains Layout information on the level of blocks, paragraph, lines and words and also the OCR output. The problem is that this is very slow; on my machine it takes 7s per image and I actually don't need the OCR. Hence, I want page segmentation (also sometimes called layout detection) only. According to the Tesseract ( Documentation ), th...

error: tf.compat.v1.app.run() while running model_main_tf2.py object detection

I have a problem with running this command in Terminal: python model_main_tf2.py --model_dir=C:\\models\\my_ssd_resnet50_v1_fpn --pipeline_config_path=\\models\\my_ssd_resnet50_v1_fpn\\pipeline.config The first error I receive is tf.compat.v1.app.run() . tfrecord are generated, I created the label_map.pbtxt . Python 3.9.9 Tensorflow 2.10.1 source https://stackoverflow.com/questions/77706092/error-tf-compat-v1-app-run-while-running-model-main-tf2-py-object-detection

ttkbootstrap.tableview.Tableview rowheight doesn't work for data rows

Cannot set the row height of ttkbootstrap.tableview.Tablewview data rows. I can change the heading but not the data rows. import ttkbootstrap as ttk from ttkbootstrap.tableview import Tableview from ttkbootstrap.constants import * app = ttk.Window() style = app.style **style.configure('Treeview.Heading', rowheight=80, font=(None, 18)) style.configure('Treeview', rowheight=80, font=(None, 18))** coldata = [{"text": "LNum", "stretch": False}, "CompanyName", {"text": "UserCount", "stretch": False}, ] rowdata = [('A123', 'IzzyCo', 12), ('A136', 'Kimdee Inc.', 45), ('A158', 'Farmadding Co.', 36)] dt = Tableview( master=app, coldata=coldata, rowdata=rowdata, paginated=True, searchable=True ) dt.pack(fill=BOTH, expand=YES, padx=10, pady=10) dt.load_table_data() app.mainloop() I expect the data row height to increase in height but it doe...

Anyone can help me on this discord bot command error

I'm doing a discord bot, at first it's just an XP bot, the problem is related with the output on the server, when i write the command in the chat commands. When i do a mencion for me or for another users, the bot do not response, ithis the same thing if i mention he or not mention anyone follow de code bellow import discord from discord.ext import commands import json import os intents = discord.Intents.default() intents.messages = True intents.guilds = True intents.guild_messages = True bot = commands.Bot(command_prefix=commands.when_mentioned_or("!"), intents=intents) xp_channel_id = 1186457318850838539 # Altere para o ID real do canal config_file = "config.json" # Verifica se o arquivo JSON jĆ” existe e carrega os dados if os.path.exists(config_file): with open(config_file, "r") as f: config = json.load(f) else: config = {"XP": {}} def save_config(): with open(config_file, "w") as f: json.dump(confi...

csv to html table ( header mapping | django)

I'm currently working on a Django project where users can upload a CSV file with headers in different languages. My goal is to allow users to map these headers to the corresponding fields in my database model. For example : Fields in the database: (first name, last name, age, country) User CSV header : (pays, prenom, nom, age) In this scenario, the user has provided all the necessary fields but in French and in a different order. After the user clicks the upload button, my plan is to load the CSV file into a table or another format that allows them to easily map the fields in the CSV file to the columns in my database. Thank you in advance. Tried using Pandas, but it just shows the CSV file as a table. No idea how to make the table header editable. Via Active questions tagged javascript - Stack Overflow https://ift.tt/JzPBnYy

Absolute vs. Relative File Path (Python)

Is it better to use a relative or absolute file path in Python, in both a situational setting and for best practice? I know what both of them do, and I'm wondering if, for example, always using an absolute file path is better practice than using a relative file path, or if it depends. And if it is a situational thing, when should you use one or the other? source https://stackoverflow.com/questions/77695077/absolute-vs-relative-file-path-python

Batch update entity property in pyautocad

I am making a pyqt widget tool which should operate with data in AutoCAD. Basically it allow user to select color and fill it in selected hatch objects in AutoCAD. It actually can be done directly in AutoCAD but sometimes it's time consuming task to open custom palette and manually select color. My current tool is based on pyautocad and pyqt modules. This is how it looks like: While widget is opened, user can select hatches and then select type in widget and then press Fill type button and finally we got repainted hatches. This is how it looks like in Python code: red, green, blue = 146, 32, 6 acad = Autocad() # initializing AutoCAD connection list_to_upd = [] curr_sset = acad.doc.PickfirstSelectionSet # get a list of selected entities new_color = None for obj in curr_sset: if obj.ObjectName == 'AcDbHatch': # check if entity is hatch type if not new_color: tcolor = obj.TrueColor tcolor.SetRGB(red, green, blue) new_colo...

How to solve Tabula error reading pdf to pandas?

Help. I am having the following error in reading pdf files using tabula: Error importing jpype dependencies. Fallback to subprocess. No module named 'jpype' Error from tabula-java: The operation couldn’t be completed. Unable to locate a Java Runtime. Please visit http://www.java.com for information on installing Java. i'm using a macbook with the following code: from tabula import read_pdf for file in glob.glob(os.path.join(link_scrape['pdfs'],'*.pdf')): try: df = read_pdf(file,pages='all') except Exception as e: print(e) break how do i resolve this? source https://stackoverflow.com/questions/77691801/how-to-solve-tabula-error-reading-pdf-to-pandas

Python interface for openEMS software not installing

I am trying to install an open source Maxwell's equations solver known as OpenEMS. To run that software the python interface for two things within it are required to be manually installed through terminal-CSXCAD and openEMS. To do that I have to go into the python directory within both CSXCAD and the openems directory in terminal and run the command pip install --user . . However it is not happening every time I try. When I try to run it within the CSXCAD python directory it says the following, python setup.py bdist_wheel did not run succesfully And when I try to install the python interface for openems I get the following errors, python setup.py egg_info did not run succesfully I searched up the problems that were coming such as python setup.py egg info did not run successfully for the CSXCAD python interface and python setup.py bdist_wheel did not run successfully. I even tried upgrading pip and setuptools but nothing is working source https://stackoverflow.com/questions...

FID and custom feature extractor

I would like to use a custom feature extractor to calculate FID according to https://lightning.ai/docs/torchmetrics/stable/image/frechet_inception_distance.html I can use nn.Module for feature What is wrong with the following code? import torch _ = torch.manual_seed(123) from torchmetrics.image.fid import FrechetInceptionDistance from torchvision.models import inception_v3 net = inception_v3() checkpoint = torch.load('checkpoint.pt') net.load_state_dict(checkpoint['state_dict']) net.eval() fid = FrechetInceptionDistance(feature=net) # generate two slightly overlapping image intensity distributions imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8) imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8) fid.update(imgs_dist1, real=True) fid.update(imgs_dist2, real=False) result = fid.compute() print(result) Traceback (most recent call last): File "foo.py", line 12, in <module> fid = FrechetInce...

Unable to resolve KeyError: "Index 'slice(None, None, None)' is not valid for indexed component 'MindtPy_utils.objective_value'"

import pandas as pd import random as r import numpy as np import glpk from pyomo.environ import * from amplpy import AMPL def pyblock(pyp, pytau, pyr, pys): M = ConcreteModel() M.m = Set(initialize = list(range(int(len(pyp))))) M.e = Set(initialize = list(range(int(len(pyr))))) M.s = Set(initialize = list(range(int(pys)))) M.r = Param(M.e, initialize = pyr) M.tau = Param(M.m, initialize = pytau) M.p = Param(M.m, M.e, M.s, initialize = 0) M.n = Var(M.m, M.e, M.s, domain=NonNegativeIntegers, initialize=0) def obj(M): return sum(-log(1-prod((1-pyp[i,j,k])**(M.n[i,j,k]) for j in M.e for k in M.s)) for i in M.m) M.obj=Objective(rule=obj, sense=minimize) def fire_rate(M, j, k): return sum(M.n[i,j,k] for i in M.m) <= M.r[j] M.fire_rate=Constraint(M.e, M.s, rule = fire_rate) opt = SolverFactory('mindtpy') results = opt.solve( M, mip_solver = 'cplex', nlp_solver = 'ipopt', tee=True ) # ...

session.execute with multiple databases

I want to execute raw sql on separate databases through sqlalchemy sessions. My session/engine is configured as follows: db1Base = declarative_base() db2Base = declarative_base() DB_ENGINES['db1'] = create_engine(db1_postgres_url, **connection_args) DB_ENGINES['db2'] = create_engine(db2_postgres_url, **connection_args) session_factory = sessionmaker(autocommit=False, autoflush=False, twophase=True) session_factory.configure(binds={db1Base: DB_ENGINES['db1'], db2Base: DB_ENGINES['db2']}) Session = scoped_session(session_factory) When I do session.query(Model) , sqlalchemy is able to figure out which engine to use depending on which base the model inherits from. But if I instead use session.execute(text(query), params) i'll get the error UnboundExecutionError: Could not locate a bind configured on SQL expression or this Session. Because sqlalchemy cannot figure out which engine to use. Is there a way to explicitly or implicitly specify which engine...

Simple Diffusion Model with Checkerboard Data

I have been trying to build a simple diffusion model with checker board data which is made from dots (x, y). So it is 2d data. def get_noise_level(step, total_steps, max_noise_level=1.0): # Define the mean and standard deviation for the Gaussian distribution mean = total_steps / 2 std_dev = total_steps / 4 # This can be adjusted based on desired spread # Calculate the Gaussian noise level gaussian_noise_level = np.exp(-((step - mean) ** 2) / (2 * std_dev ** 2)) # Scale the noise level to be between 0 and max_noise_level return gaussian_noise_level * max_noise_level Above is my func. to get the noise level # Model definition class DiffusionModel(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(2, 128) self.fc2 = nn.Linear(128, 128) self.fc3 = nn.Linear(128, 2) def forward(self, x): x = torch.relu(self.fc1(x)) x = torch.relu(self.fc2(x)) return self.fc3(x) Above is m...

RuntimeError: Given groups=1, weight of size [64, 64, 5, 5, 5], expected input[1, 16, 64, 8, 8] to have 64 channels, but got 16 channels instead

Hello i use pytorch to make a CNN with Cirfar data. And I got this error. class Net(nn.Module): def init (self): super(Net, self). init () self.conv1 = nn.Conv2d( in_channels = 3, out_channels = 32, kernel_size = 5, stride = 1, padding = 2 ) self.conv2 = nn.Conv2d( in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2 ) self.conv3 = nn.Conv3d( in_channels=64, out_channels=64, kernel_size=5, stride=1, padding=2 ) self.pool = nn.MaxPool2d(2,2) self.fc1 = nn.Linear(1024, 0) self.fc2 = nn.Linear(0, 1024) self.fc3 = nn.Linear(1024, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) print('x_shape:',x.shape) x = self.pool(F.relu(self.conv3(x))) x = torch.flatten(x, 1) # flatten all dimensions except batch x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return (x) model = Net() count_parameters(model) model.to(device) criterion = nn.CrossEntropyLoss() optimizer = opti...

Struggling with some first steps(unluckily i didn't manage to find out the solution on my own) [closed]

enter image description here [WinError 2] The system cannot find the file specified [cmd: ['py', '-m', 'py_compile', 'C:\Users\Administrator\Desktop\python\hello_world.py']] [dir: C:\Users\Administrator\Desktop\python] [path: C:\Program Files (x86)\VMware\VMware Workstation\bin;C:\Program Files\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\PC Connectivity Solution;C:\app\Administrator\product\12.1.0\client;C:\app\Administrator\product\12.1.0\client\bin;C:\app\Administrator\product\12.1.0\client_1;C:\app\Administrator\product\12.1.0\client_1\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0;C:\WINDOWS\System32\OpenSSH;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE;c:\Pro...

Tkinter (or CustomTkinter) scrollbar transparency

I want to hide scrollbar in CTkScrollableFrame, or at least make it transparent. Anticipating your question, I need to be able to scroll my frame with mouse wheel, so I don't need to see the scroll button. Is there any way to do it? I just read wiki for both Ctk and Tkinter, and didn't find the answer. source https://stackoverflow.com/questions/77671526/tkinter-or-customtkinter-scrollbar-transparency

Flask blueprints with SQLAlchemy for APIs -- what can I do to simplify?

I am designing an app that has a database, a CRUD web interface to manage its content, and exposing a REST API to be called by an external UI written in React. I am using native Flask Blueprints, SQLAlchemy, along with Marshmallow for API serialization. The way I have structured Blueprints, based on what I learned from the Flask docs, seems unnecessarily complicated: app.py -> __init__.py . create_app() registers blueprints "factory" Flask pattern each blueprint imports from a routes module register_blueprint specifies two blueprints one for HTML, another for API as each has a different url_prefix each routes module __init__.py imports Blueprint, then creates the blueprint instances for html and api, then imports the actual routes for the module (e.g. from routes.user import routes ) each routes implementation imports the blueprints created in the module imports the SQLAlchemy model and Marshmallow schema creates the code for the routes, and decora...

onClick(props.function()) Causes Function Calls repetedly [duplicate]

I am trying to display different things depending if a element is clicked or not in a navbar, in body.main App.js content: const [showCatContent, setShowCatContent] = useState(false); const toggleCatContent = () => { setShowCatContent(!showCatContent); }; console.log(showCatContent) return ( <html><head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <script defer src="theme.js"></script> <link rel="stylesheet" href="style.css" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400,700&display=swap" rel="stylesheet" /> </head> <body> <Navbar toggleCatContent={toggleCatContent} /> <body> <Navbar toggleCatContent={toggleCatContent} /> <main> {showCatContent ? ( <p>This is my cat ahahhahahah...

CS50P Issue - Little Professor "displays EEE when answer is incorrect" and "shows solution after 3 incorrect attempts"

I'm brand new to programming taking the CS50P course. In the Little Professor assignment in Pset4 I am passing all the Check50 tests except the last two. Running my code manually yields all the expected results per the problem sample video. I am guessing that I have some type of operations order that gives the right result but check50 is not interpreting it as needed. Here is my code: import random def main(): score = 0 level = get_level() for _ in range(10): x, y, correct_answer = generate_problem(level) user_attempts = 0 while user_attempts < 3: print(f"{x} + {y} = ", end="") user_answer = get_user_input() if user_answer == correct_answer: score += 1 break else: user_attempts += 1 print("EEE") if user_attempts == 3: print(f"{x} + {y} = {correct_answer}") print(...

How do I access to the logs generated from training a model with tensorboard?

now That we cannot upload the logs to tensorboard dev I cannot transform the information from the logs to DataFrame as easily as before. So I wante to ask if anyone knows how to extract the data stored in the train and test logs programatically, that is, without using: tensorboard --logdir=path_to_logs in the console command. I cannot do anything if first I cannot understand how I can unpack the data stores in the logs. source https://stackoverflow.com/questions/77644842/how-do-i-access-to-the-logs-generated-from-training-a-model-with-tensorboard

how to automatically kill sessions on postgres db in python django, before django tests recreate the db

django recreates our postgres test database on start, however in some cases there are sessions open. I can kill the sessions with SELECT 'SELECT pg_terminate_backend(' || pg_terminate_backend(pg_stat_activity.pid) || ');' FROM pg_stat_activity WHERE pg_stat_activity.datname = 'MY_DBNAME' AND pg_stat_activity.pid <> pg_backend_pid(); but currently, I do that manually as needed from SquirrelSQL. How can this be done automatically before django recreates the DB (very early in the test setup process). THis is needed because otherwise the delete DB fails due to connected sessions. source https://stackoverflow.com/questions/77645214/how-to-automatically-kill-sessions-on-postgres-db-in-python-django-before-djang

FileUpload Widget Issue in VS Code .ipynb: 'Upload(6)' Displayed, but data Length Returns 0

I was trying to upload a file using widget.FileUpload() and print the image out. But after uploading 6 images and trying to run the last line in a new cell it returned an error, saying "IndexError: list index out of range" btn_upload = widgets.FileUpload() btn_upload img = PILImage.create(btn_upload.data[-1]) I then tried the line print("Number of uploaded files:", len(btn_upload.data)) expecting "6" as that is the number of files I uploaded, it returned 0 instead. source https://stackoverflow.com/questions/77643801/fileupload-widget-issue-in-vs-code-ipynb-upload6-displayed-but-data-lengt

How to check if each values in array exist in database

Simply, I am working on a project and I faced a case and want to know if I am implementing it correctly. I expect the client to send an array of IDs, and I need to check if each value in the array exists or not in the database. If any value does not exist, I will send a response with an error. Otherwise, I will proceed with the next actions. I have implemented the idea in the following way: let result = null; for (let i = 0; i < listIds.length; i++) { const existCheck = await branchModel.exists({ _id: listIds[i] }) != null ? true : false; if (existCheck == false) { result = false; } } if (result != false) { result = true; } return result; } However, I think this approach may impact performance if the array is very long, and I am not sure if calling the database multiple times in the same API is healthy and not expensive. Is there a method in Mongoose to achieve the same idea? Soluation : let result = false; let unique = [...new Set(listIds)]; co...

Electron Squirrel Auto Updater The remote server returned an error: (308) Permanent Redirect

I was trying to make an auto-updater for my electron app and used Hazel as the update server, but when I tried this and tested it, following every step on the electron guide , It would always give me these errors in the Squirrel-CheckForUpdate.log file: [10/12/23 11:54:19] info: FileDownloader: Downloading url: https://cbsh-updater.vercel.app//update/win32/1.0.2/releases?id=bellschedoverlay&localversion=1.0.2&arch=amd64 [10/12/23 11:54:19] warn: IEnableLogger: Failed to download url: https://cbsh-updater.vercel.app//update/win32/1.0.2/releases?id=bellschedoverlay&localversion=1.0.2&arch=amd64: System.Net.WebException: The remote server returned an error: (308) Permanent Redirect. [10/12/23 11:54:19] info: CheckForUpdateImpl: Download resulted in WebException (returning blank release list): System.Net.WebException: The remote server returned an error: (308) Permanent Redirect. [10/12/23 11:54:19] fatal: Finished with unhandled exception: System.AggregateException: O...

I want to remap my mouse side btns to keyboards btns using Tampermonkey Javascript

// ==UserScript== // @name Mouse Button Remapper // @namespace http://tampermonkey.net/ // @version 0.1 // @description Remap mouse side buttons to keyboard buttons // @author You // @match *://*/* // @grant none // ==/UserScript== (function() { 'use strict'; // Map mouse button IDs to keyboard key codes const buttonMappings = { 3: 'P', // Change this to the desired key code 4: 'O' // Change this to the desired key code // Add more mappings as needed }; // Add event listener for mouse button press window.addEventListener('mousedown', function(event) { const buttonId = event.button; if (buttonMappings[buttonId]) { // Simulate keydown event for the mapped key const keyEvent = new KeyboardEvent('keydown', {'key': buttonMappings[buttonId]}); document.dispatchEvent(keyEvent); } }); // Add ...

Hero slider with wide image and animations on it to work with mobile

I'm working on side project and the client want from me to create hero for full screen and should be scrollable horizontally, you can click on the image and swipe from left to right and from right to left. So from beginning, I have a huge image 5000px x 2000px and eg. on full hd monitor I need to show the image center and user can swipe in horizontal to see the rest of the content. Should be responsive also for the mobile that height of the hero will be always 100vh and width of that image will calculate proportionally. here is the video how it should look like: https://drive.google.com/file/d/14V0CEuWvapHBxI5ZQ1tc33IiYMDWZJdZ/view?usp=sharing also is another challenge, that animations should be in this slider, got sequence from Designer to animate, and I need to put that animation in absolute position, for example fire animation. there is a figma to play with desktop version: https://www.figma.com/proto/87RAbQap8Yeekp0oEsHnti/Dogin-Hood-Prototype?page-id=314%3A163&type=d...

javascript not showing right message at right momernt

wrote a code to handlhandle the type of messatge i should get, I am looping over the table's all trs and finding the conditions to match Here are my conditions: if all rows have data-mode="success" and data-pure="yes", it means the code is correct and its a success: if any row has data-mode='success" and data-pure="no", it means, it is a warning, if any row has data-mode="error", it means its an error and the message is danger I have the following code but it is always returning me 1, if there is a third condition, function checkTableData() { var allTables = $('#tableBody'); var highestValue = -1; for (var i = 0; i < allTables.length; i++) { var table = allTables[i]; var trs = $(table).find('tr'); for (var j = 0; j < trs.length; j++) { var tr = trs[j]; var d...

TypeError: 'options' is an invalid keyword argument for Connection() What do i do? [closed]

if im doing anything wrong then im sorry its my first time using stack overflow and python. Im trying to setup FCMS for the game Elite Dangerous Because i want to modify stuff and upgrade it a bit And keep Getting an error wich from what i read is probably from sqlalchmy: Traceback (most recent call last): File "<frozen runpy>", line 198, in _run_module_as_main File "<frozen runpy>", line 88, in _run_code File "C:\Users\mmuch\Desktop\FCMS-master\FCMS\env\Scripts\initialize_FCMS_db.exe\__main__.py", line 7, in <module> File "C:\Users\mmuch\Desktop\FCMS-master\FCMS\FCMS\scripts\initialize_db.py", line 34, in main with env['request'].tm: File "C:\Users\mmuch\Desktop\FCMS-master\FCMS\env\Lib\site-packages\transaction\_manager.py", line 142, in __exit__ self.commit() File "C:\Users\mmuch\Desktop\FCMS-master\FCMS\env\Lib\site-packages\transaction\_manager.py", line 133, in commit r...

How to get identification number and exam code from the image with OpenCV [closed]

I'm new to OpenCV and I have a photo like this, how can I get the registration number and exam code in the upper right corner of the photo? And further, how can i draw green background for the selected answer ? The photo right below here. Image url How can i get that, thanks for any help. source https://stackoverflow.com/questions/77623699/how-to-get-identification-number-and-exam-code-from-the-image-with-opencv

Potential Recommendations for a Computer Science Bachelor's Degree final project

I have a friend who will be finishing his Computer Science bachelor's degree next semestre, and he's trying to think what he could do for his final project. He plans to use Python as his main language, with potential frameworks like Kivy and/or Django. He's also considering using real data from his university if given permission for his project. So far he hasn't gotten any luck comming up with project ideas that can apply something computer science related such as AI or simulation. He also needs to make sure that it isn't exclusively an information system project (like if the project is just a simple dashboard or a normal website that won't do much). If anyone can offer any recommendations for what could be a good computer science final project for my friend i'd be very grateful. source https://stackoverflow.com/questions/77623696/potential-recommendations-for-a-computer-science-bachelors-degree-final-project

Programmatically generating box UVW maps

I'm need to programmatically generate box UVW maps in 3D-models, similar to how UVW Map -> Box works in 3ds Max. Example with default UV Example with box UV, what I'm after I've tried javascript-based solutions such as this or this , but it seems to give various results depending on if the mesh/geometry is merged or if it already has any built in UV. Or it has different directions . Applying box UV-map via Blender or 3ds Max to the same 3D-model always gives perfect results though. Best case scenario would be a command line tool, similar to how gltf-pipeline works: generate-box-map -i model.gltf -type box -size 50 I've found tools/projects such as PyMeshLab , Meshmatic , or running a Blender instance and attempting to do it via python, but I couldn't find a solution. Perhaps there's a native/easier way of doing this? Via Active questions tagged javascript - Stack Overflow https://ift.tt/dhNjQMu

How can I create dynamically HTML pages for each data?

I need to create html pages for multiple datas. I searched, then I found this document.getElementById("div-1").appendChild(container); datas.forEach(function (data) { var rptContainer = document.querySelector('.container').cloneNode(true); rptContainer .querySelector('.customer-no').textContent = data.customerNo; rptContainer .querySelector('.customer-name').textContent =data.customerName; document.getElementById("div-1").appendChild(rptContainer); }); It creates pages according to the number of data, but all the pages contain the information of the most recent data. How can I create pages according to each data (customer)? Via Active questions tagged javascript - Stack Overflow https://ift.tt/dhNjQMu

popup displays and dissapears immediately after button is clicked

I want to make a popup for my project so I decided to follow a w3schools tutorial but I'm running into a problem. When I click the button to show the modal it appears and immediately disappears. var btn = document.getElementById("btn"); btn.onclick = function() { modal.style.display = "block"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } <div class="modal" id="myModal"> <div class="container"> <div class="input-container"> <h1>Search Product</h1> <input type="text" name="search" id="search" placeholder="Search"> <div class="results-container"> <table aria-label=""> <thead> <tr> <th id="number">No.</th> <th id="prod...

I'm getting this weird red color texts in my react code

I'm getting this weird red color text in my vscode, the code runs on my localhost(local machine), and also "npm run build" works. But when I try to host it on Vercel it doesn't work. enter image description here . This is my code enter image description here . The weird text appears everywhere in my code, I don't understand whats happening. enter image description here I'm trying to host my code that's working on my local machine on vercel and its not working Via Active questions tagged javascript - Stack Overflow https://ift.tt/dhNjQMu

Calculating time between high state

In python I want calculations of high / low states of a signal in chunks of a given size ( samples_to_process ). The two required calculations are number index between rising edges ( length_between_high_states ) and number of index's the signal is high for ( high_state_length ). The calculations must be stateful across chunnks. Lets take a small reproduceable example: data = np.array([0,1,1,0,1,1,1,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,1,0,0]) If this array is read 8 items at a time, the first iteration is high_state_length = 2 length_between_high_states = 4 then high_state_length = 3 length_between_high_states = 9 I believe I have the correct logic to read in the first state of the array and signal changes, but subsequent state changes in the signal and carrying the state across chunks are not yet implemented: import numpy as np #total array size = 25 data = np.array([0,1,1,0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,1,1,1,1,0,0]) #size ...

Ajax from DataTable is not working in .net 6

I dont get any errors in the console. And the breakpoint in the method of the controller is never called. (sorry for my bad english). The problem is that the method is never called from the ajax. Please help. Html: <!-- Modal --> <div id="modal-inclusion" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h2 class="modal-title text-center" id="exampleModalCenterTitle">Solicitar inclusiĆ³n</h2> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="mod...