Skip to main content

Posts

Showing posts from September, 2023

Python - Nelder Mead vs fsolve: pH equilibria optimization problem leads to numerical instability in Nelder Mead?

I'm creating a pH equilibrium calculator - starting with initial compositions of certain acids / bases the calculator should come up with the equilibrated concentrations of each component based on physical constants. I've formulated this as a set of equations which need to be solved simultaneously. One key constraint is that H_plus*OH_minus must be 10^-14 , and I've included this in the equations. Code #1: Fsolve. This works, but is sensitive to initial conditions, and I can't put constraints (I need concentrations to be >=0). import numpy as np from scipy.optimize import fsolve def equations(variables, Ka, Kw, initial_concentrations): HA, A_minus, H_plus, OH_minus, ion_Na = variables HA_init, A_minus_init, H_plus_init, OH_minus_init, ion_Na_init = initial_concentrations # Define the equations eq1 = HA + A_minus - HA_init - A_minus_init # Mass balance on acetate eq2 = H_plus + ion_Na - OH_minus - A_minus # charge balance eq3 = H_plus *...

getting "module not found" error when the library is in the anaconda3/envs/projects_env folder

i installed python's schedule library in anaconda, the path is like this: /anaconda3/envs/myprojectenv/schedule my python3 project is in a separate folder, the path is like this: /Desktop/projects/myproject.py when i activate the anaconda3 environment and run my python project, it can't find the schedule library. do the python libraries & packages i install for use in a project need to be in the same directory as that project? because right now i only have it in my anaconda3 environment folder and it can't seem to find it, even with the environment activated. source https://stackoverflow.com/questions/77208273/getting-module-not-found-error-when-the-library-is-in-the-anaconda3-envs-proje

Iterating through

I'm trying to iterate through all of the <ng-template> generated HTML elements and adding event listeners to it and adding/removing classes, but as I'm iterating through the elements it's not letting me grab the actual element. Therefore, I can't grab stuff like classList or innerHTML This is what the console throws: ERROR TypeError: item.classList is undefined Here is my Template Code: <div class="nav-container"> <h2 class="fw-semibold text-center pt-3 logo">bytenotes</h2> <button class="newCat-btn">+ New Category</button> <nav #catItem class="navbar-container"> <h3 *ngFor="let category of categories; first as firstCat" class="catItem" [ngClass]="firstCat ? 'active' : ''" > </h3> </nav> </div> Here is my Component Code: @Component({ selector: 'app-nav', tem...

How to make text field visible based on a specific dropdown list value?

I have a list of option values. Only when a certain option from the value is selected and I would like to show custon_25 text field. I select a specific option like value 2, 5 or 7 then show the text field to enter. Can anyone help please? Thanks $('#select2-results').click('change',function() { if($('value==2').is(':selected')) { $('#custom_25').show(); } else { if($('#custom_25').is(':visible')) { $('#custom_25').hide(); } } }); <div id="editrow-custom_24" class="crm-section editrow_custom_24-section form-item" style="display: block;"> <div class="label" style="display: none;"> <label for="custom_24">Medical Service</label> </div> <div class="edit-value content"> <div class="select2-container crm-select2 crm-form-select select2-allowclear" id="s2i...

The js seems like stop working when I switch to another tab on browser, is a problem?

I made a clock. I realized that when I switch another tab and came back after a while the clock stop behind current time. I found something named web workers, is it related to this?? Same senteces, don't read. I made a clock. I realized that when I switch another tab and came back after a while the clock stop behind current time. I found something named web workers, is it related to this?? I expected the code work anytime but it didn't. The code: let numbers = document.getElementsByClassName('number'); let numbersLength = numbers.length-1; let numberContainer = document.querySelectorAll('.number > div'); let minute = document.querySelector('#minute'); let hour = document.querySelector('#hour'); let second = document.querySelector('#second'); let startSecond = new Date().getSeconds()*6; let startHour = new Date().getHours()*30; let startMinute = new Date().getMinutes()*6; setInterval(increaseSecond, 1000); function readyHour() {...

Table Jquery Horizontal Scroll on Click

I have a table with overflow scroll and I'd like the user to be able to click a button to scroll the table as well. Please see fiddle below for my code. Any help on where i'm going wrong would be greatly appreciated. I have a fiddle here Via Active questions tagged javascript - Stack Overflow https://ift.tt/hzQUbVL

How to live video stream using node API (Read file with chunk logic)

I want to make a live video streaming API and send the video buffer chunk data to an HTML. I am using rtsp URL. The chunk logic does not work. The video only plays for 5 seconds then stops. index.js file const express = require('express'); const ffmpeg = require('fluent-ffmpeg'); const fs = require('fs'); const path = require('path'); const app = express(); const port = 3000; app.get('/', (req, res) => { res.sendFile(__dirname + "/index.html"); }); const rtspUrl = 'rtsp://zephyr.rtsp.stream/movie?streamKey=64fd08123635440e7adc17ba31de2036'; const chunkDuration = 5; // Duration of each chunk in seconds app.get('/video', (req, res) => { const outputDirectory = path.join(__dirname, 'chunks'); if (!fs.existsSync(outputDirectory)) { fs.mkdirSync(outputDirectory); } const startTime = new Date().getTime(); const outputFileName = `chunk_${startTime}.mp4`; const outputFilePath = path.join(...

Why does the tooltip show up on the wrong point in Plotly.js scatter plot?

I posted this question over at the Plotly community here: https://community.plotly.com/t/why-does-the-tooltip-show-on-the-wrong-point-in-scatter-plot/78835 . I'm posting it again here to get more responses. I have a scatter plot. When I hover over the points, the tooltips that show the values show up on the wrong point: Is this a bug in Plotly? Is there any way to fix it? Thank you. Via Active questions tagged javascript - Stack Overflow https://ift.tt/MfyX2kE

Trouble with vector arrays in p5.js

I am trying to create a 2-dimensional array of vectors using p5.js I generate the 2D vector array in setup() using nested For loops, and print the vector value to the console within the same nested loops. Starting with a 2D array of 2x2 elements, I want the vectors to take their values from the array index (so, for example: vector[0][0] has value (0,0) and vector[1][1] has value (1,1). This all works correctly in setup(), and the first line on the console is: 0 0 _class {x: 0, y: 0, z: 0, constructor: Object} But when I access this 2D array in the draw() function and print the vectors to console, the first line is: 0 0 _class {x: 1, y: 0, z: 0, constructor: Object} let xV = 2 let yV = 2 let vectorP = [2,2] function setup() { for (var i = 0; i < xV; i++) { for (var j = 0; j < yV; j++) { vectorP[i,j] = new p5.Vector(i,j); console.log(i,j,vectorP[i,j]); } } } function draw() { console.log ("draw") for (var i = 0; i < xV; i++) { for (var j...

QT6 how to automatic adjust button location and widgets layout

I am quite new to QT and I want to add QPushButton in each new widget on the same place (top right side for example) , but I am having an issue in that , the button appears randomly everywhere and break the layout as well. I am pasting part of my code as below: self.method_container = QWidget() self.method_layout = QHBoxLayout() method_delete_button = QPushButton() method_delete_button.setObjectName(f"{self._NodeItem__id}") method_delete_button.setIcon(QIcon(':/Panematic/Icons/Delete.png')) method_delete_button.setStyleSheet(Path("Panematic/Ui/UI.qss").read_text()) method_delete_button.setAutoFillBackground(True) method_delete_button.clicked.connect(lambda: deleteButtonClick(self, method_delete_button)) self.method_layout.addWidget(method_delete_button) self.method_container.setLayout(self.method_layout) self.proxy = QGraphicsProxyWidget() self.proxy.setWidget(s...

How do I rotate one image that is on top of a second background image?

VSCode ================================ -- index.html code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport", content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="image.css"> </head> <body> <div id="canvasContainer"> <canvas id="canvas" width="900" height="520"></canvas> </div> <script src="image.js"></script> </body> </html> ================================ -- image.js code: const cCanvas = document.getElementById('canvas'); cCanvas.width = 600; cCanvas.height = 300; const cContext = cCanvas.getContext('2d'); const cBackgroundImage = new Image(); const cBackgroundWidth = cCanvas.width; let lBackgroundHeight; const cCarImage = new Image(); const...

Moving two rectangles with transition

Using the following code, I can move two rectangles together with a transition, but after moving the two rectangles together, one of the rectangles moves from bottom to top again. <script> var rectangles = document.getElementsByClassName("rectangle"); for (var i = 0; i < rectangles.length; i++) { var rectangle = rectangles[i]; var upButton = rectangle.getElementsByClassName("up")[0]; var downButton = rectangle.getElementsByClassName("down")[0]; upButton.addEventListener("click", function() { moveFile(this.parentNode, "up"); }); downButton.addEventListener("click", function() { moveFile(this.parentNode, "down"); }); } function moveFile(currentRectangle, direction) { var siblingRectangle = direction === "up" ? currentRectangle.previousElementSibling : currentRectangle.nextElementSibling; if (siblingRectangle) { currentRectangle.classList.add(direction === "up...

MUI primary theme color changing in production AWS Amplify

I am creating a nextjs 13 app router project using material UI. i have designed the theme using createTheme but the primary color sort of dulls down on its own when uploading on AWS AMPLIFY. the changes look fine locally but not on cloud. Dependencies i am using in the current project: { "@emotion/react": "^11.11.1", "@emotion/styled": "^11.11.0", "@fontsource/roboto": "^5.0.8", "@mui/icons-material": "^5.14.3", "@mui/material": "^5.14.3", "@types/node": "20.4.8", "@types/react": "18.2.18", "@types/react-dom": "18.2.7", "ag-grid-community": "^30.1.0", "ag-grid-react": "^30.1.0", "eslint": "8.46.0", "eslint-config-next": "13.4.12", "faker": "^5.5.3", "millify...

SVG arg fadeout/gradient effect

I'm trying to create doughnut visualization using d3 with fadeout/gradient effect for each arc like this: I've tried to add 'filter: drop-shadow(0 0 10px color)' but it doesn't give me this effect, also, it spread on both sides. So I moved to use two pies Outer solid color Inner with (hopefully) the fade out effect I know in gradient I can make solid, then fade out but since I don't have a clear path to success, I split to two pies I've tried to use both linearGradient & radialGradient on the second pie which seems like a step in a good direction, but the gradient effect changes as the arcs angles are different: For the simplicity, currently I created a gradient filter for just one color as I'm not sure this is the solution for my problem... I've added a snippet to help the helpers :) const colors = ['red','green','purple','blue','orange','teal'] const data = [10,12,33,112,22,4]; const...

How to play audio from decoded base64 string with ElevenLabs Streaming Websocket Typescript

I am attempting to use the ElevenLabs API and Websockets to stream audio to the browser. response.audio does return a generated partial MP3 audio chunk encoded as a base64 string, but I am stuck on trying to properly decode and play it. This is my current attempt: Main notes: The API does return a response of base64 string successfully I keep receiving the error on Chrome: Uncaught (in promise) DOMException: Failed to load because no supported source was found. My blob url returns a 404 error Here is my code: "use client"; import React, { useRef, useState } from 'react'; const StreamingAudioTest: React.FC = () => { const [isPlaying, setIsPlaying] = useState(false); const audioRef = useRef<HTMLAudioElement | null>(null); const handlePlayButtonClick = () => { const voiceId = "<voice-id>"; const model = 'eleven_monolingual_v1'; const wsUrl = `wss://api.elevenlabs.io/v1/text-to-speech/${voiceId}/stream-i...

Read basePath in Next.js AppRouter

How can I read basePath in Next.js 13 when I use AppRouter ? We can get it by reading router.basePath from useRouter of PageRouter by importing `import { useRouter } from 'next/router' I cannot find any way to read it when I use AppRouter import { useRouter } from 'next/navigation' has no basePath Via Active questions tagged javascript - Stack Overflow https://ift.tt/t9AZyWC

How to show only the Duplicate values from a List in Python [duplicate]

I'm a beginner with Python. Let me show you my code below and I'll describe my problem. random_list=['a','b','c','b','d','m','n','n'] duplicates=[] for value in random_list: if random_list.count(value) > 1: if value is not duplicates: duplicates. Append(value) print(duplicates) Below is what happens when I run the code. [] ['b'] ['b'] ['b', 'b'] ['b', 'b'] ['b', 'b'] ['b', 'b', 'n'] ['b', 'b', 'n', 'n' The problem is that it shows me the duplicates however, it shows them too many times. How do I tell Python that I only want to show the duplicates once? Example: ['b','n']. Please note, I'm not trying to eliminate the duplicates in my list, I'm trying to show them. I've put tried different c...

External scripts in tag manager within a single page app built with React aren't working properly

We have a single page app built with react that also uses GTM to load external scripts like Google Analytics 4, Microsoft Clarity, etc. For some reason none of the external scripts are functioning unless using tag assistant or preview mode in GTM. The 3 external scripts we have are: -Pardot's Tracking Script -Zoominfo's Tracking Script -Microsoft Clarity's Tracking Script All three of these are in Custom HTML GTM tags triggered by the "All Pages" trigger. I do not see these scripts loading in DevTools and no activity is logged in each of these services unless in GTM preview mode. I've also tried loading these scripts via the following triggers with no change: -Window Loaded -Dom Ready I know that GTM is loading correctly because we have several GA4 event tags that fire on several different triggers. The only issue seems to be loading external scripts. Could this be something related to React? My searches don't return anything relevant. Via Active qu...

Why can't I run a controller through AJAX code? [closed]

I have the following form in a modal: <div class="modal fade" id="absenceModal" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-md" role="document"> <form role="form" method="post" id="formAbsence"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title"><b>Absence</b></h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <div class="form-row"> <div class="col-md-5 mb-3"> <input class="form-control" type="text" name="d...

In React Application API data is displaying but when refreshing page it's showing error

I am learning coding from last 4months. I got strucked here.. I am creating a food delivery App. Here i want to display Restaurant Name and menu list in UI.. it's ok its worked but when i am refreshing the page it's showing error. I used react useState and useeffect hook to render This is my code When i am refreshing page it's showing error Api Data is Displayed Via Active questions tagged javascript - Stack Overflow https://ift.tt/bvVHIE5

Common function to check if JSON attribute is undefined [duplicate]

I need to findout if the JSON variable is undefined or not. Below is the snippet of code. var file = JSON.parse(getvar("fileJSON")); console.log(JSON.stringify(file)); // set required variables setvar("a",file.a); setvar("b",file.b); setvar("c",file.c); setvar("d",file.d); setvar("e",file.e); setvar("f",file.f); Below check works fine. But instead of repeating for each variable, Can you please suggest common function in javascript to acheive this check "if(typeof file.a!== 'undefined')". Please suggest if(typeof file.a!== 'undefined') setvar("a",file.a); if(typeof file.b!== 'undefined') setvar("b",file.b); Below function dint work : setvar("a",checkNull(file.a)); function checkNull(var) { if(typeof var !== 'undefined'){ return var; } } Via Active questions tagged javascript - Stack Overflow https...

How to get user response from a native java module on react native?

I am launching a native intent from Java and I need to catch if the user saves or cancel a configuration made before inside the java code so I could send back the corresponding response to my React Native module. I am running the native intent ACTION_WIFI_ADD_NETWORKS but I don't know how to catch if the user press the save or cancel button in this code. my module code: public class MyConnection extends ReactContextBaseJavaModule { private Context reactContext; public MYConnection(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; reactContext.startActivityForResult(intent, REQUEST_CODE); this.connectivityManager = (ConnectivityManager)reactContext.getSystemService(reactContext.CONNECTIVITY_SERVICE); } @Override public String getName() { return "AndroidConnection"; } @ReactMethod public void connect(String ssid,String userName, String passWord, ...

Problems with dissolved shapefiles in Google Earth Engine

I created a single dissolved polygon shapefile out of a set of smaller polygons in ArcGIS and imported it into Google Earth Engine using geemap (Python API). I wanted to extract values from every pixel in the dissolved shapefile using the ee.Image.sampleRegions function. However, upon closer inspection, it appears that the function only sampled one of the smaller polygons, even though I imported it as a single shapefile. When I show it on the map and select it, it seems like it should be working as a single polygon. Does anyone know why this could be? It is a large area (about 20,000 hectares), if that matters. source https://stackoverflow.com/questions/77137380/problems-with-dissolved-shapefiles-in-google-earth-engine

Circos plotting the CCA results

I run CCA on a set of variables and got 4 components significant after fdr correction. Each components got top vars extracted by thresholding the cca weight at 0.2 and now I wanted to plot the components and top vars in each fc and sc as seen bellow of the code: import os import networkx as nx import numpy as np import pandas as pd from sklearn.cross_decomposition import CCA from scipy.stats import percentileofscore from statsmodels.stats.multitest import multipletests from sklearn.utils import resample from nxviz import CircosPlot import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler #Set seed np.random.seed(123) # Load data def load_data(file_name): return pd.read_csv(file_name) # Canonical Correlation Analysis def calculate_canonical_loadings(X, Y): cca = CCA(n_components=69, max_iter=5000) cca.fit(X, Y) X_c, Y_c = cca.transform(X, Y) return np.corrcoef(X_c.T, Y_c.T)[:X_c.shape[1], X_c.shape[1]:], cca # Bootstrap for CCA coefficie...

How to detect strikethrough text from docx tables?

I'm using python-docx to parse some tables to dictionaries. However, some of those tables contain strikethrough text. This text needs to be excluded. I have already found how to detect strike-through through text in paragraphs or how to apply strike-through text myself , but nowhere can I find how to check for strikethrough text in tables. As far as I can tell from the documentation, neither the Table object nor the cells have a "Run" object, which is something that Paragraphs have that contain style data. Without the Run object, there's no style data. source https://stackoverflow.com/questions/77128728/how-to-detect-strikethrough-text-from-docx-tables

How to return arraobject if the particular property exists in nested array object using javascript;

How to check the particular property exists in nested array object using javascript; In the below arrobj , if value property is empty, remove and return the array of object If all object property value is empty, return []; using javascript. var arrobj = [ { id: 1, task: [ {tid:1, value:[]}, {tid:2, value:[12,13]} ] }, { id: 2, task: [ {tid:4, value:[14,15]} ] } ] Tried var valueExists = arrobj.filter(e=>e.tasks.filter(i =>i.value.length > 0); Expected Output: [ { id: 1, task: [ {tid:2, value:[12,13]} ] }, { id: 2, task: [ {tid:4, value:[14,15]} ] } ] Via Active questions tagged javascript - Stack Overflow https://ift.tt/zN8KLeJ

Prevent Link from activating on click on card icon in React

I have a card wrapped in a Link from the react-router-dom@v5 . Inside the Link is a div for the card and the div is positioned relatively. Inside the card div is an icon positioned absolutely to the card that when clicked should change background color. The problem now is that clicking on the icon also clicks the Link which I don't want. I tried to use e.preventDefault() but it also stops all subsequent events from firing again properly as I want to be able to flip the background color of the icon any time I click on it. I tried e.stopPropagation() and e.nativeEvent.stopImmediatePropagation but they don't seem to work. I have also gone through several SO answers but none seem to fix my problem. function handleFavClick(event) { event.stopPropagation(); console.log(event); } <Link to={`/movies/${movie.id}`} key={movie.id}> <div className="card" key={movie.id} > <img src="/heart-ico...

In an update form how can i display old value and make it editable?

i have a array called students, it stores name, age and phone number, i already have the functionality of the add fuction: const [students, setStudents] = useState([]); const [name, setName] = useState(""); const [age, setAge] = useState(""); const [phoneNumber, setPhoneNumber] = useState(""); And i have already have the update functionality" const [updatedName, setupdatedName] = useState(""); const [updatedAge, setupdatedAge] = useState(""); const [updatedPhoneNumber, setupdatedPhoneNumber] = useState(""); const updateStudent = () => { if (updatedName.trim() === "" || updatedAge.trim() === "") { showAlert("Name and Age are required fields."); return; } if (!/^[a-zA-Z\s]+$/.test(updatedName.trim())) { showAlert("Name must contain only letters and spaces."); return; } const ageValue = parseInt(updatedAge); if (isNa...

python git push function works only on windows

Using the git module,this code works fine on windows def actionGitPush(self,message_label,dir): repo = git.Repo(dir ) origin_url = repo.remotes.origin.url #print(repo) repo.remotes.origin.push(refspec='master:master') message_label.append('Git Push to ' + origin_url ) message_label.append('==========') but it gives this error on ubuntu. Traceback (most recent call last): File "/media/vbk/MAsTOCK/_PROJECT/_utils/scripts/python/devmgmt/devmgmt.py", line 234, in actionGitPush repo.remotes.origin.push(refspec='master:master') File "/home/vbk/.local/lib/python3.9/site-packages/git/remote.py", line 1118, in push return self._get_push_info(proc, progress, kill_after_timeout=kill_after_timeout) File "/home/vbk/.local/lib/python3.9/site-packages/git/remote.py", line 927, in _get_push_info proc.wait(stderr=stderr_text) File "/home/vbk/.local/lib/python3.9/sit...

why is the 3D model not rendering on my webpage?

I used chatgpt to generate the code for three js I also did 'npm install three' still the 3D model is not rendering i want my 3d model to render on my page.js , located in the app folder directly i think the code inside ModelViewer.js import { GLTFLoader } from 'three/addons/loaders/GLTFLoader'; is somehow wrong because when I write three/, it shows me src, build and examples folders, there is no such thing as addons when I am writing import { GLTFLoader } from 'three', it is telling me (loader is not a constructor)(line 27 in ModelViewer.js) what do I do? Via Active questions tagged javascript - Stack Overflow https://ift.tt/uRgO1As

XPath expression to select children of parent in xpath (that works in javascript and in c#)

TLDR: I want to write an xpath expression to select all (at any level) children of parent node using both '..' and 'parent::', that will work in c# and javascript/typescript. I am limited to xsd 1.0. I do not want to use preceding-sibling axis. My xml looks like <tns:s03.q01 id="s03.q01" text="Select the specific issues encountered (please select all that apply) and indicate the corresponding MBAs" description="" isAnsewerRequired="true" type="Question"> <tns:choices> <tns:multiChoiceAssert condition="count(parent::tns:choices/*[@value='true']) = 0" message="'{$locator}\Choices' must have atleast one choice selected." relevantNodeLocator="string(../../@id)" /> <tns:s03.q01.c01 value="true" id="s03.q01.c01" text="Bias" description="" type="Choice"> <tns:selectMBA...

Google Analytics react-ga4 returning a 204 but event not tracking

I am trying to log events using react-ga4 . After firing an event I get a response. Headers: Request URL: https://www.google-analytics.com/g/collect?.... Request Method:POST Status Code:204 Remote Address:142.... Referrer Policy: strict-origin-when-cross-origin Request Payload: en=header_about_us_click&_ee=1&ep.category=button&ep.action=click&_et=2929 en=page_view&_ee=1&_et=2&dp=%2Fwho-we-are&dt=About%20Us&dl=https%3A%2F%2Fwww.paragonwebdevelopment.com%2Fwho-we-are The request payload seems to be correct. However it doesn't seem like my events are tracking correctly. Via Active questions tagged javascript - Stack Overflow https://ift.tt/roJdaCS

Using viewtransition for dark mode in astro

I am trying to implement the new viewtransition, in my project in astro, the problem is I have found documentation on how to fix the dark mode issue when chaging routes, but I am using a little different code and because of that it does not work, my code: // Get the theme toggle input const themeToggle: HTMLInputElement = document.querySelector( '.theme-switch input[type="checkbox"]' ); // Get the current theme from local storage const currentTheme = localStorage.getItem("theme"); // If the current local storage item can be found if (currentTheme) { // Set the body data-theme attribute to match the local storage item document.documentElement.setAttribute("data-theme", currentTheme); // If the current theme is dark, check the theme toggle if (currentTheme === "dark") { themeToggle.checked = true; } } // Function that will switch the theme based on the if the theme toggle is checked or ...

Inconsistent Elasticsearch scores with async python client

I'm consuming an elastic search cluster with 3 nodes and keep receiving consistent results for only a very short period of time despite having defined the preference parameter. I found the following litterature and I could not really understand what am I missing: Different Elasticsearch results for the same query Different results for same query in Elasticsearch Cluster Difference in results between "preference" and "search_type" on _search in Elasticsearch Elasticsearch Scoring Inconsistency I'm looking for recommendations on how to address this issue or aspects I might be missing as it starts to be annoying once we start using pagination. My client is defined as following: es_client = AsyncElasticsearch( hosts=[3 nodes], ... sniff_timeout=10, sniffer_timeout=60, sniff_on_connection_fail=True, max_retries=5, retry_on_timeout=True, request_timeout=30, ) and I execute my search as...

Using vue js components when using it from cdn

I'm trying to use the ButtonCounter component as an example ( https://vuejs.org/guide/essentials/component-basics.html#defining-a-component ), but I just can't make it work. I use vue js 3 from a CDN. I have the ButtonCounter.js file: export default { data() { return { count: 0 } }, template: ` <button @click="count++"> You clicked me times. </button>` } Then I have the main js file with vue: import ButtonCounter from './ButtonCounter.js' const app = Vue.createApp({ components: { ButtonCounter }, data() { return { aaa: [] } }, methods: { ... } } }) app.mount('#app') And finally I have the html where I link vue js from a cdn, and I specify the following inside the body: <ButtonCounter /> But I can't see the button. What am I doing wrong? Via Active questions tagged javascript - Stack Overflow https://ift.tt/Op4tv9N

Displaying different images with raspberry in Python using PIR sensor

sorry in advance for any dumb mistakes, I'm a very beginner programmer and am trying to help my friend with his project (he doesn't know how to code). We are trying to make the program display one picture or the other, depending on the reading on the PIR sensor. If the reading is LOW, image A is shown. If the reading is HIGH, image B is shown. For this, we are using the pygame library and the display function. The issue is: we cannot make the program alternate between pictures. At first we were using the PIL library, but we found that it lacked a way to close the image windows in a simple manner, and the program kept creating new windows everytime the sensor did a reading. So we opted for the pygame, as it has an option to exit the display function. At our first attempt, the program would only read the first if, that is, the LOW input. So I modified it as a way to try and make that every time the sensor changed readings (from LOW to HIGH and vice versa) it would first close...

What the state of the art way to build LSTM data: data_generator or tf.data.Dataset.window?

I always did my own code to format my data (3D, normalize...) for my LSTM models. Now I have to work with bigger dataset and need to ingess many csv files. What is the best way to make all the work fast and memory efficiency. Tensorflow suggest a data generator and finaly convert data set to data.dataset and I found guy doing thing like this : WINDOW_SIZE = 72 BATCH_SIZE = 32 dataset = ( tf.data.Dataset.from_tensor_slices(dataset_train) .window(WINDOW_SIZE, shift=1) .flat_map(lambda seq: seq.batch(WINDOW_SIZE)) .map(lambda seq_and_label: (seq_and_label[:,:-1], seq_and_label[-1:,-1])) .batch(BATCH_SIZE) ) I realy want to learn the best way, my goal is to use my code in production and learn in the futur more about Mlops. Thank for your help and if you have good explained exemple to set up 3d lstm data.dataset, I take all suggestion source https://stackoverflow.com/questions/77084220/what-the-state-of-the-art-way-to-build-lstm-data-data-generator-or-tf-data-data...

OpenAI Gymnasium vectorized approach works slower than non-vectorized

I'm getting started with OpenAI Gymnasium . My task is to speed-up trajectory generation. So to create N trajectories, I want to use a single parallel multi-env instead of running the same env N times with resets. I found the vector module of Gym and tried to use it. But for me it doesn't speed up the generation, moreover it's sometimes slower. Here's sample code: Vectorized n_envs = 100 vec_envs = gym.vector.make("CartPole-v0", render_mode="rgb_array", num_envs=n_envs) vec_envs.reset() n_actions = vec_envs.action_space[0].n %%time t_steps = 1000 for iter_idx in range(t_steps): actions_batch = np.random.randint(low=0, high=n_actions, size=(n_envs,)) new_s, r, terminated, truncated, info = vec_envs.step(actions_batch) Here %%time gives me: CPU times: total: 5.8 s Wall time: 6.84 s Non Vectorized env = gym.make("CartPole-v0", render_mode="rgb_array") env.reset() n_actions = env.action_space.n %%time t_steps = 100...

How to extract linkedin companies URL from linkedin search using python

I'm trying to scrap company's profile URL from a LinkedIn search but I got "not found". Every things worked well in my code here it is: import requests import csv import time import numpy from bs4 import BeautifulSoup from time import sleep from selenium import webdriver import pandas as pd from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys import time import re # Read the keywords from a file with open("keywords.txt", "r") as file: keywords = file.read().splitlines() # Define the User-Agent header edgedriver_path = '/path/to/edgedriver' options = webdriver.EdgeOptions() options.add_argument("--start-maximized") driver = webdriver.Edge(options=options, executable_path=edgedriver_path) driver.implicitly_wait(10) driver.get('https://www.linkedin.com/login') email_input = driver.find_element(By.ID, 'username') password_input = driver.find_element(By.ID, 'passwor...

Override exported variable in file within __mocks__ folder in jest

I have a __mocks__ folder with a file called example.ts in it File Content (shortened for simplicity) export let token: string | null = "exampleString"; I have a test file where I use this variable in all the test cases. There is one in particular where I want to override the value of this variable to be null Approaches tried: Use a proxy to try to intercept the variable when the function to be tested is called (no success, variable still set to exampleString Use jest.spyOn to try and override the variable, still no success Used jest.unmock('../../modules/__mocks__/example'); to try and use the real implementation of the file but no success Has anyone got an idea on how to successfully override the value of the variable for a single test case? Thanks Via Active questions tagged javascript - Stack Overflow https://ift.tt/zv5wiGK

Problem with ElevenLabs API with working API ke

Screenshot from Visual Studio So I'm building a smart assistant on a bigger project, and everything but elevenlabs works just fine. This is a small test file I made to try to understand what's going on. Let me provide some more information: yes, I already tried with playsound and failed yes, I already tried with pydub and failed yes, I've already tried with pygame and failed yes, the audio on my pc is not muted yes, the API key is working (I know that cause everytime I run the program the remaining characters available in my elevenlabs account go down) yes, I tried to use "generate_play_audio" instead of "audio" and failed. I don't really know what the prroblem is, also because I am kinda new to python and APIs. Any help would be appreciated, thanks in advance! I tried everything i listed above, but nothing seems to work. Is it because python is using the wrong speaker? I don't know... Is it because all of the methods I tried to play the sound ...

Python Matplotlib plt.imshow crashes kernel in an unknown way when plotting images

When I run the following code (which runs fine on Google Colab) my kernel crashes from torchvision import datasets from torchvision.transforms import ToTensor import torch.nn as nn import torch.nn as cnn train_dataset = datasets.MNIST( root = 'datasets', train = True, transform = ToTensor(), download = True, ) test_dataset = datasets.MNIST( root = 'datasets', train = False, transform = ToTensor() ) print(train_dataset) print(test_dataset) print(train_dataset.data.size()) print(test_dataset.data.size()) import matplotlib.pyplot as plot plot.figure(1) plot.imshow(train_dataset.data[0], cmap='gray') plot.title('%i' % train_dataset.targets[0]) plot.show() The very undescriptive error message i get is the following: (This is the click here link shown in the screenshot-image above) However if I run the following code a one or more cells above the previous code works without crashing the kernel. What is really d...

onesignal send push to user like FCM

I'm sending pushes with OneSignal in React Native app. I'm new with it, but have some experience with Google FCM. I'd like to make the same architecture solution like FCM. Init -> OneSignal.initialize("CODE") ; Get device token -> I did not find any SDK API to get it. Place token into database and link it with userid in my database. Get token from database when action triggered and send push by token. Please, help with 2 (get token API) and 4 statement (send push by Token API). Via Active questions tagged javascript - Stack Overflow https://ift.tt/JpQn1Sl

Nestjs: files with details in them?

I'm using nestjs, and Im trying to upload multiple files. Each file can also contain sound (which is also a file). This is how it looks on postman. Request and this is how the request looks like. uploadedfiles This is what the code looks like: @ApiConsumes('multipart/form-data') @ApiMultiFile() @Serialize(MemoryGetOneResponseDto) @UseInterceptors(AnyFilesInterceptor()) async create( @CurrentUser() user: EUser, @UploadedFiles() files: Express.Multer.File[], @Request() req, // @Body() dto: DTO ) { console.log(files); I'm trying to link the files with sounds somehow, probably something like this: [ { fieldname: 'files', originalname: 'image.jpeg', encoding: '7bit', mimetype: 'image/jpeg', buffer: <Buffer>, size: 100064, sounds: { fieldname: 'files[0][sounds]', originalname: 'sound.mp3', encoding: '7...