Skip to main content

Posts

Showing posts from January, 2022

Equivalent instance property in javascript

In python I can do something like the following to have a property in a class: class Client: def __init__(self, dialect=None, init_conn=False): self.dialect = ... @property def type(self): return self.dialect['name'] Is the equivalent in javascript done with the get prefix, such as with the following? class Client { constructor(dialect, init_conn) { this.dialect = ... }; get type() { return this.dialect.name } } Or, what is the equivalent? Via Active questions tagged javascript - Stack Overflow https://ift.tt/H4UG5yx30

No module named 'pyautogui' when code run from VSCode

I am trying to make a spambot. I am using VS code to edit and run the code but it doesn't work. import time import pyautogui as py running = True time_till_done = int(input("How many times to spam?: ")) spam_speed = float(input("How fast do you want to spam?: ")) what_to_spam = input("What do you want to spam?: ") time.sleep(5) while running: time.sleep(spam_speed) py.typewrite(what_to_spam) py.press("enter") time_till_done = time_till_done - 1 if time_till_done == 0: running = False time.sleep(5) When I run the code i get : PS C:\Users\dante\IdeaProjects\Coding> & c:/Users/dante/IdeaProjects/Coding/venv/Scripts/python.exe "c:/Users/dante/IdeaProjects/Coding/Codes/Making codes/spambots.py" Traceback (most recent call last): File "c:\Users\dante\IdeaProjects\Coding\Codes\Making codes\spambots.py", line 2, in <module> import pyautogui as py ModuleNotFoundError: No module nam

Trying to automate a two step clicker via JavaScript

I'm trying to automate a clicker via JavaScript on Poshmark that clicks the "Share" button, then will follow up with a Modal click that directs where it will be shared to. I have the first step working just fine, which is set up as follows: Editing the HTML to add an ID to this destination via Inspect: //<div data-et-prop-unit_position="0" data-et-prop-listing_id="61f18166e107bb31e89df428" data-et-prop-lister_id="5bfc8b3f1bc870975273b78f" data-et-prop-location="listing_details" data-et-on-name="listing_details" data-et-name="share" data-et-element-type="button" ***id="shareButton"*** class="d--fl ai--c social-action-bar__action social-action-bar__share btn btn--tertiary btn--icon btn--small"><i class="icon share-gray-large btn__icon"></i><span>Share</span></div> Then I run this from the console: var shareButton = document.getElementBy

Python Seaborn placing legend outside with a title

My seaborn plot is working fine. I am having issues in legend. The legend is placed inside the plot bydefault. But when I place it outside, the title goes missing. My code: import seaborn as sns sns.barplot(x='xdata',y='ydata',hue='Rank', data=df, palette='jet_r') plt.gcf().autofmt_xdate() plt.legend(bbox_to_anchor=(1,0.9),loc='upper left') plt.show() Present output: the legend is placed outside but the title is missing. How to solve this? source https://stackoverflow.com/questions/70931643/python-seaborn-placing-legend-outside-with-a-title

Pygame main menu for game

I have four files: main.py, game.py, menu.py and asteroids.py. I have shown the python code for every file apart from the asteroids one which can be found at: https://github.com/araboy24/AsteroidsTut . I watched a tutorial on how to make the game and need to add in a main menu that shows before the game starts. I have tried adding in the code to the different files to see what happens but I can't figure out what I am doing wrong. main.py from game import Game g = Game() while g.running: g.curr_menu.display_menu() g.game_loop() game.py import pygame from menu import * from asteroids import * class Game(): def __init__(self): pygame.init() self.running, self.playing = True, False self.UP_KEY, self.DOWN_KEY, self.START_KEY, self.BACK_KEY = False, False, False, False self.DISPLAY_W, self.DISPLAY_H = 480, 270 self.display = pygame.Surface((self.DISPLAY_W,self.DISPLAY_H)) self.window = pygame.display.set_mode(((self.DIS

Having difficulties building an interactive drag and drop game

I have spent days and hours trying to figure this out and have gone through so many different coding techniques, but I'm not well-versed in javascript so I'm having a lot of trouble. My goal is to create a type of drag-and-drop interaction. Think collage maker, or room designer, or outfit builder. Something where there are organized draggable elements (preferably in clickable dropdowns but scrollboxes will work). The viewer can drag elements freely to design. I've been able to successfully create drag and drop items inside a scroll box, but haven't been able to drag them outside. I've tried the clone helper but with no success. They either clone, then disappear on drop, or they shrink in size when I pick them up. Or the drag option is gone completely. This is a project I'm so excited about and am getting so frustrated. So any guidance is greatly appreciated! I'm sharing a link to a photo that describes what my overall vision is, along with coding I'm c

check substring in string [duplicate]

I have this dataframe ind inc xx cc number one one number two one NaN one So what i'm going to do df['ind inc'] = df3.apply(lambda x:str(x.'ind inc')+str(x.['xx cc']) if str(x.['xx cc']) in str(x.'ind inc') else x.['ind inc'], axis=1) And this code doesn't work. But if I change columns name on 1 word this will work. For example A B number one one number two one NaN one df['B'] = df3.apply(lambda x:str(x.A)+str(x.B) if str(x.B) in str(x.A) else x.A, axis=1) So my question is how to work with first dataframe where column name have more then 1 word? source https://stackoverflow.com/questions/70918439/check-substring-in-string

Can i use textContent in JS for adding to element numbers?

I'm trying to make program that every time i click a button a numbers is being added to to a html element. I'm trying to do it using textContent like the code below, but every time the element "gets" the number, instead of doing the calculation and show the sum, its just adding the number as Like, instead doing that: score: 2+4 >> score:6 score: 6+1 >> score:7 its doing that: score:241 this is the code: HTML: <div id="player1score"> <h2>score: <span id="sumscore1">0</span></h2> <p id="player1dice">-</p> </div> JS: function render() { let randomNumber = random() sumscore1.textContent+= randomNumber } Maybe textContent cant gets numbers and attribute the numbers as string? Via Active questions tagged javascript - Stack Overflow https://ift.tt/lxXsT3U7w

How to get the exact BBox for svg

I am trying to figure out why getBBox() for tspan element of a svg does not return the dimension. To demonstrate this with an example, if I run BBox on both tsp1 and rect1 , it returns the correct dimension for rect1 but not for tsp1 var tsp = document.getElementById('tsp1'); var tspBBox = tsp.getBBox(); var rect = document.getElementById('rect1'); var rectBBox = rect.getBBox(); console.log(tspBBox); console.log(rectBBox); <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720"> <text class="t1" id="t1" font-size="20" font-family="PT Mono" text-decoration="underline"> <tspan class="tsp1" id="tsp1" x="10.23" y="135.05">Abc ef ghi</tspan> </text> <rect class="rect1" id="rect1" x="9.23" y="112.73368530273439&q

Changing status of parent/children on the basis of boolean value

I have a array as follows: [ { data: { name: "Cloud", size: "20mb", type: "Folder", DisplayStatus: 1, }, children: [ { data: { id: 1, name: "backup-1.zip", size: "10mb", type: "Zip", isDisplayStatus: 1, }, }, { data: { id: 2, name: "backup-2.zip", size: "10mb", type: "Zip", isDisplayStatus: 1, }, }, ], }, { data: { name: "Desktop", size: "150kb", type: "Folder", DisplayStatus: 0, }, children: [ { data: { id: 3, name: "note-meeting.txt", size: "50kb", type: "Text", isDisplayStatus: 0, }, }, { data: { id:

Splitting image of handwriting sentence into each phrase?

I would like to split the linked image into each phrase. However, I struggle to get the segmentation to work. I would like to split the sentence so I get multiple images, the splicing should be where there are large whitespaces. I tried using findContours in cv2, but I could not get it to work. Could I get any help on this? Thanks. Specifically, I am not sure how to find the white spaces. For instance in the image below, there should be a cut between "1 - 3/4'' Corp Stop" and "45' of 3/4'' Copper." source https://stackoverflow.com/questions/70909623/splitting-image-of-handwriting-sentence-into-each-phrase

Button drops after adding a character to its inner text [duplicate]

I have 3 buttons in a row. When I click on a button, it will add a 'O' to the innerText of the button. However, after adding the 'O' the button drop about half way down while other buttons still on the same position. However, when all the buttons have 'O', they all move back to the correct position. How do I fix this? Thank you <!DOCTYPE html> <html lang="en"> <head> <title>Document</title> <script> window.addEventListener("DOMContentLoaded", () => { const gameSpace = document.querySelector('.game-space'); const buttons = gameSpace.querySelectorAll('button'); buttons.forEach(button => button.addEventListener('click', () => button.innerText = 'O')); }) </script> <style> .game-space button { font-size: 2rem; min-width: 100px; min-height: 100p

Unsure how to add 'else' after my existing if statement without changing program [duplicate]

Have an If-Statement but no 'else' after 'if'. Is the 'else' part necessary? i don't want to change the program (which is supposed to randomise 3 die 50 times and count how many matches there were) unless I need to. Mainly focused on 'else' after if statement #Program 2# #create a Yatzhee dice program# import random print("--------------------") print("Yatzhee dice program") print("--------------------") print("") print("Welcome to the Yatzhee Dice Program") print("In this program the dice will get rolled 50 times and at the end we tell you how many matches you got.") print("") # before loop # rolls = 50 total_matches = 0 # --- loop --- for i in range(rolls): #randomise 50 times# die1 = random.randint(1, 6) die2 = random.randint(1, 6)#chooses a number from 1 to 6# die3 = random.randint(1, 6) print(die1, "|", die2, "|", die3) if die1 ==

Javascript / React - Question about .focus() behaviour

I've just created a small search bar component that appears/disappear when clicking on an icon. It hides and shows (changes opacity and width) with a nice animation based on if the input is focused or not. Here is the code that works perfectly: const SearchBar = () => { const inputRef = useRef(); const [isSearchBarOpen, setIsSearchBarOpen] = useState(false); const handleClick = () => { if (!isSearchBarOpen) { setIsSearchBarOpen(true); inputRef.current.focus(); } else { inputRef.current.blur(); setIsSearchBarOpen(false); } }; return ( <div className="search-container"> <input type="text" placeholder="Search content" className="searchbar-input" ref={inputRef} /> <BiSearch className="search-icon" size="2.5rem" color="#fff" onClick={handleClick} /> &

Numpy indexing: all rows where column value is in a list that is different for each row

I have a program that looks like so: bar = { 1245896421: { 1, 2, 3, 4 }, 2598732155: { 31, 32, 33, 34 }, 4876552519: { 11, 12, 13, 14 }, } # This emulates a previous step in the process, which yields batches of about # 1 million rows. Can't do it all at once due to memory constraints batch_generator = ( np.random.randint(0, 999999999999, size=(100, 5), dtype=np.int64) for i in range(1000000) ) for foo in batch_generator: ## This is an example of what foo looks like: #foo = np.array([ # [ 1, 2, 3, 1245896421, 4 ], # [ 5, 6, 7, 2598732155, 8 ], # [ 9, 10, 11, 4876552519, 12 ], # [ 13, 14, 15, 4876552519, 16 ], # [ 17, 18, 19, 1245896421, 20 ], #]) baz = np.array([ row for row in foo if row[1] in bar[row[3]] ]) What I'm trying to do is to find all rows of foo where the value of the second column is in the set of bar at the index corresponding to foo 's fourth

Recursive dictionary searching

I'm trying to make a function that would take nested array (dict/list in any order) and a key name as arguments and return all values of that key in a list. my_key = "Items" my_dict = [{'z': 0, 'x': 0, 'y': 0, 'Items': [{'Slot': 1, 'id': 'minecraft:rail', 'Count': 1}, {'Slot': 2, 'id': 'minecraft:white_shulker_box', 'tag': {'BlockEntityTag': {'id': 'minecraft:shulker_box', 'Items': [{'Slot': 0, 'Count': 1, 'tag': {'Items': [{'id': 'minecraft:amethyst_shard', 'Count': 1}]}, 'id': 'minecraft:bundle'}]}}, 'Count': 1}]}] def recursive_lookup(data, key): if isinstance(data, list): for i in data: recursive_lookup(i, key) elif isinstance(data, dict): for i, v in data.items(): if i == key: print(f'{v = }&#

How to change the Boostrap 4 Accordion card header color when active

I am trying to change the header color to my $primary color and the text color to white when the tab is active. When the tab is not opened I want it to be my $unactive color for the tab and the font color to be my $primary color. Any help would be great. I am using scss to make it so the site doesnt look like every other bootstrap site. //app.scss // override all variables first $primary: #fff; $tertiary: goldenrod; $secondary: #003e7a; $unactiveTab: #ebf2fa; $theme-color: ( "tertiary": $tertiary, "unactiveTab": #ebf2fa, ); .jumbotron { background: url('https://www.wctc.edu/_site-images/it-web-and-software-developer-bl.jpg') no-repeat; background-size: cover; height:460px; width: 100%; font-weight: bold; text-align: center; } .nav-pills{ background-color: $secondary; color: $primary; } .card-header{ color: $secondary; } .nav-pills.active{ background-color: $secondary; } .card-header .btn[aria-expanded=true] { color: $primar

What is the best solution to pick up value from rigth column based on range in left column?

What is the best solution to pick up value from rigth column based on range in left column? What is best not to use heavy loops: numpy array, pandas series, dict, list. Data itself in Dataframe and ranges are bigger that in the example. And not only one value it could be a row with many values. There is an Excel file that shows the tariffs for transportation depending on various conditions. Tariffs change quarterly, in this file. Old data is overwritten. Therefore, the format must be left for automatic loading into Dataframe. It is necessary to select the desired line with the tariff depending on the distance. For example For 74 km I should pick up 6955,00 if condition 1. source https://stackoverflow.com/questions/70896761/what-is-the-best-solution-to-pick-up-value-from-rigth-column-based-on-range-in-l

Puppeteer & Chromium using large CPU?

I have a nodejs script running on my Macbook 24/7, and every 20 minutes or so it runs Puppeteer to parse the contents of a website. Every two days, the fan gets very loud, and I see Chromium is using lots of CPU and RAM. Is there someway I can fix this? This is the code I am running: const options = { args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage', '--disable-accelerated-2d-canvas', '--no-first-run', '--no-zygote', '--single-process', '--disable-gpu' ], headless: true } const browser = await puppeteer.launch(options); const page = await browser.newPage(); await page.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) C

Using JavaScript count the number of elements equal to or higher than the index in a loop

I'm working on a JavaScript function that can create an authors- H-Index. H-Index is the highest number of publication an author has written with just as many citations in other articles. I have let array = [0,0,0,1,1,2,3,3,5,6,6,7,20,20,20] This is the number of citied articles in ascending order I need to loop the array until the index is more that the count of the items equal to or higher than the index Such as for (let i = 1; i < array.length; i++){ count all items that are above i (0's get skipped) if there are more than i then loop to next i if not exit with i - 1 console.log(i) } What I'm looking for is 6 with an efficient loop. Thanks for the help I've played with map and filtered inside the loop but I can't seem to get the correct syntax Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Deleting elements from lists in a dictionary, Python

I have a dictionary with certain keys and lists of couples as elements. I want to perform the following operation: remove every element (couple) from all the lists for which its second element (or first, doesn't really matter) fulfills a certain condition. I tried with a very simple piece of code to do that, but I did not succeed and I in fact noticed a specific behavior: removing an element form a list let's the list's elements for loop skip the following element, for some reason (or at least this is what it looks like to me). This is a very simple example: # random dictionary a = {'a': [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7]], 'b': [[2, 1], [2, 2], [2, 3], [2, 4], [2, 5], [2, 6], [2, 7]]} def f(d): # keys in the dicitonary for key in list(d): # elements inthe list for elem in d[key]: # if the second element of the couple # satisfies a certain criterion...

How to hold shift and use arrow keys in Cypress

I have an issue when using the Cypress type() command in the way I want. My objective I want to be able to select and delete text in a textfield. I want this done via holding the shift key, pressing the right arrow key multiple times and then pressing the delete key. My attempt //hold shift and use right arrow cy.type('{shift}{rightarrow}'.repeat(10)); //press delete cy.type('{del}'); Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

my decoration sometimes appears just outside the triangle

It seems that my decoration sometimes appears just outside the triangle... How can I fix this? import random n = int(input('enter n: ')) x = 1 for i in range(n): if i == 0: count = 0 else: count = random.randint(0, x) print(' ' * (n - i), '*' * count, end = '') if i == 0: print('&', end = '') else: print('o', end = '') print('*' * (x - count - 1)) x += 2 What do I get for value n = 10: & ***o *o*** o****** ******o** *********o* *************o *****o********* *************o*** ******************o source https://stackoverflow.com/questions/70883922/my-decoration-sometimes-appears-just-outside-the-triangle

Mapping Airline Domiciles

I'm in the middle of creating a leaflet map that shows the location of airline pilot domicile locations. I have a JSON file of all airports, and can easily make a .csv of all airlines and domiciles. What is the best way of listing variables or arrays, in order to be able to filter based on airline, flying category (major, regional, cargo, training), or state? I need to allow a user to select a state, or airline, and see only the pilot bases offered in those options. Ideally, I'd like to pull these from a separately-managed .csv, but any way for a non-coder to easily update would be just fine. Here is the group of overlays I have so far. <script> var overlays = { 'Legacy': legacy, 'Major': major, 'Regional': regional, 'Cargo': cargo, 'EMS': ems, 'Military': military, 'Pilot Training': pilotTraining }; //This line ADDS the control layer

planeGeometry turned into a sphere

I feel like my logic isnt too awful here. I am trying to convert a planeGeometry into a sphere using its UV coordinates as latitude and longitude. Essentially here is the logic: convert uv coordinates to lat/long respectively change lat/long over to radians convert to x,y,z catesian coordinates heres the code for the vertex shader im trying out: varying vec2 vUv; #define PI 3.14159265359 void main() { vUv = uv; float lat = (uv.x - 0.5) * 90.0; float lon = abs((uv.y - 0.5) * 180.0); float latRad = lat * (PI / 180.0); float lonRad = lon * (PI / 180.0); float x = sin(latRad) * sin(lonRad); float y = cos(latRad); float z = cos(latRad) * sin(lonRad); gl_Position = projectionMatrix * modelViewMatrix * vec4(x,y,z, 0.5); } Any advice is appreciated, I feel like I am just missing something small with the logic but I believe in the masses. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2

How to manually start and stop a thread running blocking code within a Python asyncio event loop?

I have an app that runs in asyncio loop. I wish to start a thread which will execute a piece of blocking code: def run(self)->bool: self._running = True while self._running: #MOVE FORWORD / BACKWORDS if kb.is_pressed('x'): self.move_car("forward") elif kb.is_pressed('w'): self.move_car("backward") return True until I decide to stop it and manually set the self._running = False by calling: def stop(self): self._running = False These are both methods of a class controlling the whole operation of a raspberry pi robot-car I made. I want this to run on a separate thread so that my main application can still listen to my input and stop the thread while the other thread is running in this while loop you can see above. How can I achieve that? Note For sending the start and stop signal I use http requests but this does not affect t

Leaflet delete element from sidebar

I have an application that saves center coordination of Leaflet map with save button to sidebar. I want to click any coordinate and delete with a keyboard button in the sidebar. Code snippet that controls the sidebar: function createSidebarElements(layer) { const el = `<div class="sidebar-el" data-marker="${layer._leaflet_id}">${layer .getLatLng() .toString()}</div>`; const temp = document.createElement("div"); temp.innerHTML = el.trim(); const htmlEl = temp.firstChild; L.DomEvent.on(htmlEl, "dblclick", zoomToMarker); sidebar.insertAdjacentElement("beforeend", htmlEl); } function zoomToMarker(e) { const clickedEl = e.target; const markerId = clickedEl.getAttribute("data-marker"); const marker = fg.getLayer(markerId); const getLatLong = marker.getLatLng(); marker.addTo(map); marker.bindPopup(getLatLong.toString()).openPopup(); map.panTo(getLatLong); } Full script.js: let co

I can't find a table using bs4, and I found an alternative using `re`, but I'm not sure how to get the information I need

I wanted to create a dictionary where I would pull the holdings as the key along with the Weight(%) as the value. But when I try to use soup.find('table', {'id' : 'etf_holding_table'}) to access the table, nothing shows up. I saw some posts saying that it might be inside a comment and tried to copy a few ways things were done there, but I wasn't able to do so successfully. I ended up finding someone's response to a way to pull ticker information using re , but I can't seem to find any good resources explaining what his code was doing. Here is the post I copied code from to get the ticker . import requests import re keys = ['ARKK'] headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0"} url = 'https://www.zacks.com/funds/etf/ARKK/holding' with requests.Session() as req: req.headers.update(headers) for key in keys: r = req.get(url.

Having trouble trying to get my bot to schedule a message. There are no errors, I am just not getting the desired output

I am trying to create a discord bot where you can schedule a message to be sent at a certain time. I have got my bot to work all the way until the bot ask "Please send the message you would like to schedule". Once the bot ask that and the user does not respond, the bot does not do anything after that. I suspect the code is not sending the information to the mongodb database or the collector is not actually collecting anything, however I do not know why. Can someone please tell me what could be going wrong, I appreciate the help const momentTimeZones = require('moment-timezone') const { MessageCollector } = require('discord.js') const scheduledSchema = require('../models/scheduled-schema') module.exports = { requiredPermissions: ['ADMINISTRATOR'], expectedArgs: '<Channel tag> <YYYY/MM/DD> <HH:MM> <"AM" or "PM"> <Timezone>', minArgs: 5, maxArgs: 5, init: (client) =>

How to set second litepicker startDate based on first litepicker startDate selection

Hey my fellow Stackoverflowers, I am working with litepicker.js and ran into a snag that I am hoping one of you can help me figure out. I have built out two separate litepickers and am successfully populating todays date on the first and tomorrows date in the second. (these are also successfully being accepted as the minDate for both) What I have not been able to figure out is how to set the minDate for the second litepicker to one day after the selected startDate of the first litepicker. You can see where I am at in this codepen https://codepen.io/DigitalDesigner/pen/oNGRWzV HTML Code: <form> <input id="start-date" class="form-control start-date"> / <input id="end-date" class="form-control end-date"> </form> Javascript: <script> let current = new Date(); let tomorrow = new Date(current.getTime() + 86400000); // + 1 day in ms tomorrow.toLocaleDateString(); // Add litepicker calendar to stay dates const s

Is there a way to prevent getting photos randomly on Firebase Storage?

I have some folders on Firebase Storage. Every folder includes 1_org_zoom.jpg file. I can get those photos, but not in the right array order. I want to get those photos in an order like the photo below, but photos are shown randomly. I tried for loop and forEach, but didn't work. Is there any way to get these photos in an order? useEffect(() => { /* for(let i = 0; i<products.length; i++){ const imgRef = ref(storage, imgFolderRef[i]); console.log(imgRef); getDownloadURL(imgRef) .then((url) => { console.log(url); }) } */ /* imgFolderRef.forEach((imgFolder) => { console.log(imgFolder); getDownloadURL(ref(storage, imgFolder)) .then((url) => { setExArr((oldArr) => [...oldArr, url]) }) }) }, [products]); */ Array name is imgFolderRef. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Why aren't Vue prop changes triggering reactivity in my bundled component?

I've been troubleshooting this issue for a while now and I'm running out of ideas. I hope some fresh eyes can give me a better perspective. In short: I have several computed properties in a component that are not reacting to changes in props only after bundling . Before bundling, the computed properties work exactly as expected. Here's the relevant bits of code. For context, this is part of a paginated data table component. setup(props) { props = reactive(props); const isNextDisabled = computed(() => props.index + props.pageSize >= props.totalSize const rangeUpperBound = computed(() => { let upperBound = props.index + props.pageSize; if (upperBound > props.totalSize) { upperBound = props.totalSize; } return upperBound; }); return { isNextDisabled, upperBound, } } I'm using Storybook.js to develop this component as part of a library. I'm also trying to simulate

How to get plus minus to update button text

I have been trying to get a plus minus button integrated into my number input. I have been able to update the field between the buttons with the new value however am trying to get that value to populate a second area (specifically a button) If I select the number input and click up or down arrows both the input and the button text are successfully updating, I am just stuck on mingling the two together. How do I get the button to load the value of the number field after clicking the plus and minus buttons? var adultModal = document.getElementById("adultModal"); var adultBtn = document.getElementById("guests"); var adultSpan = document.getElementsByClassName("adultClose")[0]; adultBtn.onclick = function() { adultModal.style.display = "block"; } adultSpan.onclick = function() { adultModal.style.display = "none"; } window.onclick = function(event) { if (event.target == adultModal) { adultModal.style.display = "none&quo

How to display docx files in frontend React.js?

I'm trying to display docx files as i receive them from backend side, I use react-file-viewer and wanted to install the latest version but it give me an error, instead i installed Version 0.5.0, everything going well but i got those warnings : (Accessing PropTypes via the main React package is deprecated, and will be removed in React v16.0. Use the latest available v15.* prop-types package from npm instead. For info on usage, compatibility, migration and more, see prop-types-docs ) and also this one : (lowPriorityWarning.js:37 Warning: Accessing createClass via the main React package is deprecated, and will be removed in React v16.0. Use a plain JavaScript class instead. If you're not yet ready to migrate, create-react-class v15.* is available on npm as a temporary, drop-in replacement. For more info see react-create-class ) this is in frontend : import React from 'react' import FileViewer from "react-file-viewer"; export default function FilesCard({ fil

Get date-time value instead of default dd/mm/yyyy --:-- -- on Edit

I have created a bootstrap Modal from which I am taking Debt information, now on debt creation, I don't have a problem with dd/mm/yyyy --:-- -- as default (I can remove it using JS and put a placeholder) but when I edit the debt entry, i want to display the values entered instead.. Debt Entry Editing of debt where I want date values like other fields <!-- edit Debt date --> <div class="form-group"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-calendar"><span style="font-size:1.2em;">Debt Date</span></i></span> <input class="form-control input-lg" type="datetime-local" id="editDebtDate" name="editDebtDate" required> </div> </div> <!-- edit Return date --> <div class="form-group&qu

Code for saving google extension data to local storage doesn't work. What is wrong?

I have created a chrome extension that changes the background of the page from light to dark and vice versa. But when the page refreshes, it doesnt "keep" the state of the button so the user needs to change it every time the page refreshes. However, I got some help here from stackoverflow but can't get the code to work. I would like someone to point out what is wrong in my code and why. popup.js (async function () { // Read data from chrome local storage asynchronously const readLocalStorage = async (key) => { return new Promise((resolve, reject) => { chrome.storage.local.get([key], function (result) { if (result[key] === undefined) { resolve(undefined); } else { resolve(result[key]); } }); }); }; // Set data in chrome local storage const setLocalStorage = (key, value) => { chrome.storage.sync.set({ [key]: value }, () => {}); }; const changeState = () => { if (!

FullCalendar: show timed events like all-day events in stacked presentation?

In day view, FullCalendar renders floated boxes that are very hard to read for events with a start time. The all-day events stack quite cleanly. Is there a way to make timed events simply stack as well? I've tried all manner of CSS and JS hacks, and can't quite get there. Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How do I spread an object (class instance properties) to the parent's super constructor?

How can I spread a class properties to the parent's super constructor? ActionLog is a base class, it's instantiated in a method inside ActionRequestAccess ActionRequestAccess.ts export class ActionRequestAccess extends ActionLog { constructor(public actionLog: ActionLog, public customerId: string) { super( actionLog.id, // Want to get rid of these assignments <<< and switch to something like: ...actionLog actionLog.type, actionLog.date, actionLog.address, actionLog.location ); } static override fromMap(map: any) { if (!map) { return null; } const baseMap = super.fromMap(map); if (!baseMap) { return null; } return new ActionRequestAccess(baseMap, map['customerId'] ?? null); } } ActionLog.ts import { ActionType } from '../../enums'; export class ActionLog { constructor( public id: string, public type: ActionType, public date: Date, public address: st

How can I run a Qt app in Raspberry pi from CLI instead of Desktop?

I am trying to run a PyQt5 GUI script on Raspberry Pi from CLI as shown in this tutorial: Raspberry Pi - Autostart Application with Splash Screen . The program auto-starts when booted to Desktop, but doesn't run when booted to CLI. In the above tutorial it is shown that it should! Although, when I try to run it manually and write this command: python main.py following error is shown: qt.qpa.xcb: could not connect to display qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "" even though it was found. This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem. Available platform plugins are: eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, xcb. Aborted I tried using export DISPLAY=:1.0 and export DISPLAY=:0.0 but got same error. Currently I am using rc.local file to auto-start the script I also used other auto-start methods, but got same problem Thanks

How to select a set of pandas rows, where the sum of each column is approximately the same or around a given number?

Suppose there is a dataframe of mxn like: a b c d 0 19 13 14 19 1 13 6 6 10 2 2 16 12 26 3 8 2 9 27 4 16 6 10 22 5 6 14 14 26 6 18 8 8 22 7 8 11 7 18 8 16 12 12 23 9 14 19 5 11 How to randomly select a number of rows, that the sum of each column is approximately the same or around a given number? Edit: As pointed out in the comment, it may be very hard to find a solution in case the standard deviation among columns is high, so it can be only an approximation rather than a fixel solution. source https://stackoverflow.com/questions/70839882/how-to-select-a-set-of-pandas-rows-where-the-sum-of-each-column-is-approximatel

How to cast a string into an array using Yup

So whenever I receive a string I want to store it as an array. But I've got no luck so far, i tried to do with cast and with transform. I just need some clarity to get the things going. Is transform and cast the same thing? How to cast a string into an array using Yup? const schema = yup.object().shape({ types: yup .array('type must be an array.') .of( yup .string('the array must contains only strings.') .transform(value => typeof value === 'string' || myVar instanceof 'string' ? [value] : value, ) .matches(/(writer|artist)/, null), ) .min(1, 'Need to provide at least one type') .max(2, 'Can not provide more than two types'), name: yup .string('name must be a string.')

Flask: call loop AJAX post when click on a button

In my Flask App, when i click on the "Play" button, I want to display in the DOM some information processed by the server every 4 seconds for 'n' times. With "sync" AJAX POST it works, but isn't the best practice (freeze UI). Is there a better way to do that ? Thanks in Advance Here is an Example Flask.py @app.route("/play", methods=['GET', 'POST']) def play(): time.sleep(4) # Do something data_to_client = {} return json.dumps(data_to_client) Ajax POST var i=0; do{ i+=1; $.ajax({ type: "POST", url: "/play", contentType: "application/json", async: false, // method to change data: JSON.stringify(data_to_server), success: function(data_from_server){ // Every loop changes something in the DOM } }); } while(i<=5) HTML <div class="col-md-auto p-3 border-top border-bottom"> <input type="submit" id="play" name="pla

What is the best way to grab first URL segment from Vue.js hash mode?

I have this URL generated by my vue.js app http://localhost:8080/#/url-groups I need to access url-groups I've tried const firstSegment = new URL(window.location.href).pathname.split('/#/') I kept getting '/' I've also tried : const firstSegment = new URL(window.location.href).pathname.split('#'); console.log(firstSegment); VM21687:1 ['/'] const firstSegment = new URL(window.location.href).pathname.split('/#/'); console.log(firstSegment); VM21719:1 ['/'] const firstSegment = new URL(window.location.href).pathname.split('/'); console.log(firstSegment); VM21751:1 (2) ['', ''] Can someone pls correct me ? Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to add a tags input functionality in rails form or how to add array to input field?

I am building a form wjere I want to add the usser to add tags in the form. I have completed the functionality but from the front-end only and things got complex to handle. I am using Ruby on Rails in backend and html css js jqurey in frontend So far the user can add the tags in the way I want but I didn't find any way of sending the tags as an array in the form. Is there any way of sending array with forms in input or in rails forms or something else? As I said, i don't know how to send array with form so I am converting that array to string to store it in input field and then back to array using split with comma to print it on form. But user can add , in input and I don't want to Split the string with that comma so thats not the good way of using string! If you have any tutorial or link where I can find out how to send that in backend then I will be thankful to you... Thanks Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

Store an image locally in React Server Side Rendering App

I have a React Server Side Rendering App. There's a performance issue when images are to be displayed on the page. For an image to be displayed, there's a network call for the image from the server and then it's displayed on screen. For larger images, it takes a while to load the image which is very evident. Is there a way once the request is made to the server and the image is received as response to have the image stored locally and use the locally stored image when needed again without making a network request. I couldn't find any good resource to help me through this one, it would be of great help if you could help me with this one or even point me to a reference! Via Active questions tagged javascript - Stack Overflow https://ift.tt/2FdjaAW

How to debug unknown html + js: How to trace what .js is modding html for a specific class?

I am maintaining a web site that does some magic behavior (well, it adds a few characters that are not in the html) to elements tagged: class="popupover-host" I can't find this referenced in the css, and so far don't see it referenced in any .js In the browser, it is pre rendered, and examining the element shows me the fully processed text (e.g. the text that is in the source html PLUS the added characters). I feel like I need to watch the browser process the html, but have not done this before. The question boils down to this (I think): Static html + css can be figured out "by hand" by mapping the "class" tags in the html to the relevant css. We know the browser bolts the two together at render time. Add js to the picture, and it gets... harder to figure out how the final html was created. And with nested css... it is also hard to figure out. Question: So, how do I watch the browser bolt it all together? For example, if I know the &q