Skip to main content

Posts

Showing posts from September, 2022

Angular open modal doesn't get focused

Within my ts file i open a boostrap modal using the .open command. Then upon pressing the save button another modal gets open and the previous one gets closed. Here the problem is that the first modal recieves focus on itself and the elements inside it BUT second modal doesn't get focus! Here is what is happening: I click a button and i open a modal A In modal A i have some html elements including two buttons to save and close the modal If i click the save button from modal A this modal will get closed and another modal will open This second opened modal doesn't get focus when pressing TAB Here is a stackblitz : StackBlitz Demo How this stackblitz works: If you click the first button is going to open the modal A then clicking save on that modal will open another modal B Inside modal B if you try to tab is going to tab on the elements in the background WHY? I want to give my second modal focus. I tried with Directives and other things that angular suggest bu...

Defining a function that takes specific parameters

I have a computed getter function I created that essentially checked if a scroll bar exists and if it does, a component is moved to adjust for the scroll bar. Here is the code: get scrollTrackOffset() { const rowCount = this.yKeys.length || 0; const totalRowHeight = rowCount * this.rowHeight; return totalRowHeight > this.height ? 15 : 0; } The 'yKeys' for reference is a separate computed getter that always returns an array which will determine if a scroll bar exists or not. My question is that is there a way for me to make const rowCount = this.yKeys.length || 0; const totalRowHeight = rowCount * this.rowHeight; return totalRowHeight > this.height ? 15 : 0; into a reuse-able function where I can input the parameters such as this.height and this.yKeys? Via Active questions tagged javascript - Stack Overflow https://ift.tt/RoE0aZM

Pyton Mysql multy query

How could i do multi query insert to different table into one command in python. When I do it in phpmyadmin that command works without problem but in mysql.connector i couldn't do it. source https://stackoverflow.com/questions/73913632/pyton-mysql-multy-query

Webscrapping with bs4: Type Error - 'NoneType' object is not subscriptable

I am trying to extract "video" from the url and print how many there are in the console. But I get this Error: TypeError: 'NoneType' object is not subscriptable Here is my code: import requests from bs4 import BeautifulSoup Web_url = "https://watch.plex.tv/show/hannibal/season/1/episode/9" r = requests.get(Web_url) soup = BeautifulSoup(r.content, 'html.parser') video_tags = soup.find_all("video") print("Total", len(video_tags), "videos found") if len(video_tags) !=0: for video_tag in video_tags: video_url = video_tag.find("a")['href'] print(video_url)``` source https://stackoverflow.com/questions/73913131/webscrapping-with-bs4-type-error-nonetype-object-is-not-subscriptable

Using Javascript Vue and having problems linking tabs so that when user clicks tab button they are directed to new page. Do I need to use router

This is in sidebar.vue tab: <script> export default { name: 'SidebarMenu', props: { //! Menu settings isMenuOpen: { type: Boolean, default: true, }, menuTitle: { type: String, default: '', }, menuLogo: { type: String, default: '', }, menuIcon: { type: String, default: 'bx-planet', }, isPaddingLeft: { type: Boolean, default: true, }, menuOpenedPaddingLeftBody: { type: String, default: '250px' }, menuClosedPaddingLeftBody: { type: String, default: '78px' }, //! Menu items menuItems: { type: Array, default: () => [ { link: 'Home.vue', name: 'Home', tooltip: 'Home', icon: 'bx-grid-alt', }, ...

Python rounding does not work because of scientific number

Very simple, I want to round my 'base_price' and 'entry' with the precision, here 0.00001. It doesn't work because it converts it to a scientific number. How do I do this; I have been stuck for 1 hour. Some post says to use output="{:.9f}".format(num) but it adds some zero after the last 1. It work with precision = str(0.0001) but start from 4 zeros after the dot, it change to scientific numbers and digit = precision[::-1].find('.') doesn't work with scientific numbers. precision = str(0.00001) #5 decimals after the dot print(precision) base_price=0.0314858333 entry=0.031525 digit = precision[::-1].find('.') entry_price = float(round(float(entry), digit)) base_price = float(round(float(base_price), digit)) print(entry_price,base_price) Expected result: base_price=0.03148 #5 decimals after the dot entry=0.03152 #5 decimals after the dot source https://stackoverflow.com/questions/73901048/python-rounding-does-not-work-because-...

Why is onAudioProcess returning the buffer over and over?

I feel like theres a very simple mistake here, I just cannot figure it out. Basically I am trying to record my voice and then store the chunks in an array as they come in. Heres the code: const audioBuffers = [] var audioCtx = new AudioContext() navigator.mediaDevices.getUserMedia({ audio: true }) .then(stream => { var input = audioCtx.createMediaStreamSource(stream) var processor = audioCtx.processAudio() //processAudio created below var outputNode = audioCtx.destination input.connect(processor) processor.connect(outputNode) }); setTimeout(function(){ audioCtx.close() console.log(audioBuffers) }, 3000) AudioContext.prototype.processAudio = function () { //reduce volume of output function edit(input, output){ for(var i = 0; i < output.length; i++){ output[i] = input[i] / 2 } return output ...

How to replace rel value double quotes from string without having access to the HMTL?

I have an issue with a string that has double quotes (") when I get it from the backend I get it like this <span class="parsed-qr-field" rel="{ "id": 123, "sign": "45tgrl:" }"></span> and then I have to send it through an API to another machine which renders what I'm sending So when they try to print the HTML is giving issues due to the double quotes ". Is there a way of replacing the rel attribute value in the string for this rel="{ &quot;id&quot;: 123, &quot;sign&quot;: &quot;45tgrl:&quot; }" as when we do it manually like that it works We can not do the replaces statically as the rel values changes per every request I have already tried to do things like: _this._page += Template.TemplateHTML.replace(/"/g, '\\"') Or var doc = new DOMParser().parseFromString(Template.TemplateHTML, "text/html"); doc.querySelector('span[rel]').rel = do...

How to use async function in keypress.delegate event

I need to pass an asynchronous function to a keypress event in my html So far without an asynchronous function, my function must return true so that I can write to my input field otherwise I'm stuck Here is my html <input type="text" class="form-control" keypress.delegate="onEnterKeyPressedAsync($event)" value.bind="newItem[valueField] & validateForm" check-field="field:SCHEMA.USER_MAIL;format:alphanum;is-required.bind:true;" maxlength="255"> Here is my typescript file public async onEnterKeyPressedAsync($event : any) : Promise<boolean> { if ($event.which === 13 && this.items.length > 0) { const isValid = await this.addItemFormValidVM.validateAsync(); if (this.saveAsync && isValid) { this.saveAsync({newItem : this.newItem}); this.newItem = this._initializeNewItem(); this.fieldIsVisible = false; this.addItemFormValidVM.clear(); } } return true; } My func...

Should spread operator behave differently in asynchronous conditions?

I am trying to replace an instance of hardcoding in a web application with 2 very similar API calls, as I don't have time to rewrite a whole new procedure and endpoint to handle the same functionality right now. I am able to get the data from the 2 individual calls fine with Promise.all . But the template for this page (it is using handlebars ) is expecting a single object to loop through and display the options in a drop down. I have been trying to use spread operators to bring the contents of the results together with no duplicates, and it does work as expected if I mock it up synchronously in the console, but in practice the results get nested into another object as if it were an array. This is the code actually running: Promise.all([ this.isUsers = GetUsersByRole("Inside Sales", app.user.id), this.asmUsers = GetUsersByRole("Area Sales Managers", app.user.id) ]).then((is, asm) => { // is and asm contain the correct data here,...

Im trying to add an onClick function on the button so if the user clicks Yes, it removes the two buttons then add two new inputs field react js

this is the first code with the buttons elements import React, { useState } from "react"; import "./button.css"; function Button1() { return ( <div className="buttons"> <button>yes</button> <button>No</button> </div> ); } export default Button1; while this is where the button component is called and rendered, i think this is where the logic will happen import React from "react"; import styled from "styled-components"; import Button1 from "./button/Button1"; import Button2 from "./button/Button2"; import Button3 from "./button/Button3"; import CardContent from "./CardContent"; function RightBody() { return ( <Card> <SmallCircle /> <Div> <CardContent number={"1."} title={"Course of study in school:"} /> <CardContent number={"2."} title={...

React js project on GitHub pages not showing

I published my React project to GitHub pages and while I can see the favicon and main page title the actual project page is blank (nothing shows). I tried most fixes I could find but nothing worked. This is my App.JS: import {BrowserRouter} from "react-router-dom"; import Pages from "./pages/Pages"; import 'bootstrap/dist/css/bootstrap.min.css'; function App() { return ( <div className="App"> <BrowserRouter> <Pages/> </BrowserRouter> </div> ); } export default App; and this is my Page routes: import React from "react"; import { Route, Routes } from "react-router-dom"; import MainPage from "../components/MainPage"; import SpaceProFigGridDetails from "../components/SpaceProFigGridDetails"; import SpaceProMain from "../components/SpaceProMain"; import SpaceProSpaceGDetails from "../components/SpaceProSpace...

How to clone/duplicate a TensorFlow Probability neural network model

I have a TensorFlow Probability model that is built similar to models described in this YouTube Video . I'm using python==3.8.11 tensorflow==2.10.0 tensorflow-probability==0.18.0 Here's the code to build the model: def posterior_mean_field(kernel_size: int, bias_size: int, dtype: Any) -> tf.keras.Model: n = kernel_size + bias_size c = np.log(np.expm1(1.)) return tf.keras.Sequential([ tfp.layers.VariableLayer(2 * n, dtype=dtype), tfp.layers.DistributionLambda(lambda t: tfd.Independent(tfd.Normal(loc=t[..., :n], scale=1e-5 + tf.nn.softplus(c + t[..., n:])), reinterpreted_batch_ndims=1)), ]) def prior_trainable(kernel_size: int, bias_size: int, dtype: Any) -> tf.keras.Model: n = kernel_size + bias_size return tf.keras.Sequential([ tfp.layers.VariableLayer(n, dtype=dtype), ...

Do I need to specify data_vars when I import multi-band images with xarray / rasterio

I am new to xarray/rioxarray (more familiar with rasterio) so apologies if my question is naïve. I am trying to merge two overlapping datasets (two images with many bands). They seem to open fine (I can visualize them) but when I try to merge them I get this error: "AttributeError: 'DataArray' object has no attribute 'data_vars'" here is my code: path = 'path' file1 = 'file.dat' cube1 = xr.open_dataarray(path+file1,engine='rasterio') file2 = 'file.dat' cube2 = xr.open_dataarray(path+file2,engine='rasterio') ds = [ cube1, cube2, ] merged = merge_datasets(ds) cube 1 attributes Do I need to specify data_vars when I import them? would that be a dictionary of bands? source https://stackoverflow.com/questions/73886773/do-i-need-to-specify-data-vars-when-i-import-multi-band-images-with-xarray-ras

iOS - HTML img not rendering fully

I am loading an image in the page as a background, it works everywhere except on IOS devices. In the network tab, the image has been fully delivered. The amount of bytes transferred is the expected amount. when I refresh the page it doesnt even help. what I noticed is when I turn off the display and turn back on image shows fully. Via Active questions tagged javascript - Stack Overflow https://ift.tt/zkwfZmh

xlsxwriter format currency - problem with cents quantity

i have no problem in formatting columns as currency, i did with this function: def style_excel_currency(writer): wb = writer.book ws = writer.sheets['Fatture'] money_fmt = wb.add_format({'num_format': '€#.###,##0'}) ws.set_column('A:A', 10, money_fmt) if __name__=='__main__': filename='attempt.xlsx' with pd.ExcelWriter(filename) as writer: df.to_excel(writer, sheet_name='Fatture', index=False, engine='openpyxl') style_excel_currency(writer) The issue is that some very low number get rendered weirdly in excel. For example numbers in the hundreds or thousands of euros works well: it fails to format correctly number in the cents area: ( 0,06 and 0,66) I don't get if something is wrong with my formatting. Example datasets: df = pd.DataFrame(data={'col1':[100,101,200,0.06,0.66]}) Thanks source https://stackoverflow.com/qu...

Compare data in source sheet with target sheet and copy missing rows to target sheet with Google Apps Script

Source sheet has 8 columns and target sheet has 9 columns (note first 8 columns are the same, the 9th column is used to set a url link once it has been mailed out). I don't want the target sheet to be sorted. The url link has to be on the appropriate row it pertains to. This is the code I am working with so far. It does pull and compare the data, but it keeps adding a blank row at the beginning and after each run. I can't figure out why it does that? function addNewStudents() { let ss = SpreadsheetApp.getActiveSpreadsheet() let source = ss.getSheetByName('Accepted Students') let sourceValues = source.getRange(2, 1, source.getLastRow(), 8).getValues().filter(String) //sourceValues.shift() //Logger.log(sourceValues) let targetSheet = ss.getSheetByName('Confirmation Letters') let targetValues = targetSheet.getRange(2, 1, targetSheet.getLastRow(), 8).getValues().filter(String) //console.log(targetValues) let diff = targetValues.showDif(sourc...

Methods and data value doesn't access to keydown listenner Vue js

i have this code in my mounted function : mounted () { document.addEventListener('keydown', function (e) { switch (e.keyCode) { case 37 : alert(this.indexPictures) break } }) } My data value: data: function () { return { indexPictures: this.index, } }, My result : undifined I don't know why but i can't get value in data function and this is the same problem, from methods access. My result : is not a function Do you have any ideas ? thanks for you help :) Via Active questions tagged javascript - Stack Overflow https://ift.tt/m7Z9o1i

Module not found: Error: You attempted to import /firebase/app which falls outside of the project src/ directory

I had it working on a different project before and going off that as a reference but I still get this same error. My utils folder is inside the src directory. Can not seem to find out whats going on. Directory image import { initializeApp } from '/firebase/app' import { getAuth, signInWithRedirect, signInWithPopUp, GoogleAuthProvider } from '/firebase/auth' // Your web app's Firebase configuration const firebaseConfig = { // api keys // }; // Initialize Firebase const firebaseApp = initializeApp(firebaseConfig); const provider = new GoogleAuthProvider() provider.setCustomParameters({ prompt: 'select_account' }) export const auth = getAuth() export const signInWithGooglePopUp = () => signInWithPopUp(auth, provider) // Sign-in component // import { signInWithGooglePopUp } from "../../utils/firebase/firebase.utils"; const SignIn = () => { const logGoogleUser = async () => { const response = await signInWithGooglePopUp...

How I make my function in a rock, pepper, scissors game wait for a button press in Javascript?

So I have this code(I added the whole JS code but the part I want help is in the function game) that simply runs 5 rounds of a game of rock, papper, scissors with a press of a button in my html file. The thing is that each round I want the function to wait for a button click of any of the three buttons (rock, papper or scissors) I will appriciate any help, thank you and have a nice day! let rock = "Rock"; let papper = "Papper"; let scissors = "Scissors"; let wins = 0; let playerSelection; const btnrock = document.getElementById('btn1'); const btnpapper = document.getElementById('btn2'); const btnscissors = document.getElementById('btn3'); const btnplay = document.getElementById('game') function getPlayerChoice() { btnrock.addEventListener('click', () => { playerSelection = rock; return playerSelection; }); btnpapper.addEventListener('click', () => { playerSelection = ...

Read csv file with multiple columns and plot data using matplotlib

Is there an easy way to read a csv file and plot an undefined(csv file changes) number of columns using pandas, matplotlib, and pyqt5? I'm a super beginner to programming so any help would be awesome! I've tried finding articles online to help, but I'm very lost. The plot I'm trying to create has an x-axis based on time with the format '%d-%m-%Y %H:%M:%S.%f' located in column 0 of the csv file and the y-axis changes depending on the column heading starting with column 1. Example: Timestamp, O63ME, O63MT, 011KT, etc... 11/06/2020 11:04:00.196, 34, 24, 11, etc... 14/06/2020 11:04:00.449, 114, 29, 3.84, etc... This is what I have so far: from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT as Navi from matplotlib.figure import Figure import matplotlib.pyplot as plt import pandas as pd class MyCanvas(FigureCanvasQTAgg): def __init__(self,pa...

Showing current/dynmaic url in react tab

Simple problem which I cannot seem to find the answer to. Currently I have built a website with react and when a user opens a new tab it shows the same favicon, image and hard coded title on every tab. I simply wish to do as stackoverflow, and may other web pages and dynamically show the page title in the tab. My current index.html in the react app just has the hard-coded title. Does anyone know how to change this to show the current web url ? Thanks! <title>My Website </title> Via Active questions tagged javascript - Stack Overflow https://ift.tt/m7Z9o1i

Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before.while react version 18 upgrade

I have 3 index.js files in my project and I was upgrading the react version to 18. Before the changes it was somehow like this. src/index.js ... ReactDoM.render( <React.StrictMode> <App /> </React.StrictMode> ) ... src/pages/home export const HomePage = props => { const { appData } = props const ShowGroupTiles = Boolean(appData.pagecontextdata?.find(data => data.contentType === "catalogBrowseGroupTiles")) const ShowProductTiles = Boolean(appData.pagecontextdata?.find(data => data.contentType === "catalogBrowseProducts")) const groupTiles = () => { document.addEventListener("DOMContentLoaded", function(event) { ReactDOM.render(<CatalogBrowseGroupTiles appData={appData} />, document.getElementById('group-tiles')); }) } const productTiles = () => { document.addEventListener("DOMContentLoaded", function(event) {...

Excel and Python, need assistance [duplicate]

I am currently working on a code in which the user inputs a pdf file with data and converts that data to an excel file, however, I am trying to use that same code to generate whatever data but that new data will appear in the same excel file as a new sheet. For example: User inputs: Data1.pdf Converts to excel file name: Report.xlsx Sheet1 = Data1 User inputs: Data2.pdf Converts to excel file name: Report.xlsx Sheet2 = Data2 . . . and so on... I am currently using df.to_excel(filetype_xlsx,sheet_name = "DATA1", index=False) If anyone can help me with this would be greatly appreciated! source https://stackoverflow.com/questions/73858219/excel-and-python-need-assistance

Here is the problem discription: print(snake_array[0].x) AttributeError: 'list' object has no attribute 'x' . I cannot find the mistake

class Test: def __init__(self, x, y, dir): self.x = x self.y = y self.dir = dir def snake_init(snake_array): snake_array.append([Test(300, 300, "RIGHT")]) snake_array.append([Test(301, 300, "RIGHT")]) snake_array.append([Test(302, 300, "RIGHT")]) print(snake_array[0].x) snake_array = [] snake_init(snake_array) source https://stackoverflow.com/questions/73859470/here-is-the-problem-discription-printsnake-array0-x-attributeerror-list

How can I take a screenshot with JavaScript? [closed]

I am trying to take a screenshot in the browser with JavaScript in an extension. Then I need to save it to a variable, which needs to be done without user interaction (possibly only for the first time when installing the extension). The screenshot needs to include everything on the page as is, meaning no HTML re-rendering (YouTube videos as they are, for instance). Via Active questions tagged javascript - Stack Overflow https://ift.tt/qdi0tcr

Does anyone know how I can store those in localStorage?

const tr = document.createElement("tr"); const td = document.createElement("td"); table.appendChild(tr); td.innerText = "" + new Date().toLocaleDateString("de-Ch"); tr.appendChild(td); const td2 = document.createElement("td"); td2.innerText = object.text; tr.appendChild(td2); const td3 = document.createElement("td"); if (object.amount > 0){ td3.style.color = "rgb(4, 209, 4)"; td3.innerText = "+"; } else{ td3.style.color = "red"; } td3.innerText += object.amount; tr.appendChild(td3); const td4 = document.createElement("td"); td4.style.color = saldo < 0 ? "red" : "black"; td4.innerText = saldo.toFixed(2); tr.appendChild(td4); Basically this code gets ran when I submit a form and it adds a tr and td's to a table which I already have as elementById. My question is, does anyone know how I could store the values, that I input, as localStorage, so ...

Why when I have only 1 export default in the file, it still doesn't export?

I don't get why I keep receiving an error like this: Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data import React, { useEffect } from 'react'; import Tmdb from './Tmdb'; export default () => { useEffect(() => { const loadAll = async () => { // Pegar a Lista Total let list = await Tmdb.getHomeList(); console.log(list); } loadAll(); }, []); return ( <div> Hello World! </div> ); } Via Active questions tagged javascript - Stack Overflow https://ift.tt/x9p2GDY

XMLHTTPREQUEST Keeps Returning Empty Line When I Send A Request

I am trying to make a login function where it filters through the rest api. The API itself works on localhost and when I enter the local host address(http://localhost:3000/config/username) myself in a browser it works completely fine, but when I try to access it via XMLHTTPREQUEST it keeps returning an empty line. I have tried many things, but it either returns undefined, null, a CORS error, or just doesn't do anything at all. My Javascript Code Is: async function getLogin(){ console.log('------') let usernameElement = document.querySelector('#username') let passwordElement = document.querySelector('#password') const url = `http://localhost:3000/config/${usernameElement.value}` try { const request = new XMLHttpRequest() request.open("GET", url, true); let jsonResponse; request.send() request.onload = function(){ jsonResponse = request.response }; alert(request.response) } catch(err){ alert(err) ...

How can I convert jQuery ajax to fetch?

This was my jQuery code before. Now I want to change it to fetch. function fetch(){ jQuery.ajax({ url: '<?php echo admin_url('admin-ajax.php'); ?>', type: 'post', data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() }, success: function(data) { jQuery('#datafetch').html( data ); } }); } I have changed the code to this now but I am getting bad request 400 status code document.querySelector('#keyword').addEventListener('keyup',()=>{ let data = { action: 'data_fetch', keyword: document.querySelector("#keyword").value }; let url = "<?php echo admin_url('admin-ajax.php'); ?>"; fetch(url, { method: 'POST', // or 'PUT' headers: { 'Content-Type': 'application/json', }, body: JSON.st...

How to display a given number of records from an array into a ListGroup?

I'm using React-Bootstrap to create a dashboard. It has a ListGroup that displays user details taken from the users array. I need to know how to display only a given number of ListGroup.Items (eg: 5 list items out of 10) instead of displaying all the records from the array. For now, my ListGroup displays the entire array of user records. Users.js export const Users = () => { const users = [ { id: "1", img: "https://cdn-icons-png.flaticon.com/512/3135/3135715.png", firstname: "Rangana", lastname: "Cruise", organization: "Company", role: "Admin", }, ... { id: "10", img: "https://cdn-icons-png.flaticon.com/512/3135/3135715.png", firstname: "James", lastname: "Bond", organization: "Company", role: "Admin", }, ]; return ( <div className="bg"...

Python initialize a dictionary with condition values

When I initialize the check_dict , will all the values(condition) be calculated(become boolean values), if yes will it be not efficient if I put conditon be dictionary's value, is there any better way to do it? def checker(fruit: str, number: int) -> bool: check_dict = { "apple": True if number > 3 else False, "banana": True if number < 2 else False, "watermelon": True if number > 10 else False } res = check_dict.get(fruit, None) if res: return res ans = checker(fruit="apple", number=4) print(ans) source https://stackoverflow.com/questions/73847475/python-initialize-a-dictionary-with-condition-values

I need a clarification of targeting an element from the markup

I am following a class online and the tutor target a <button> document in which I don't really understand how he did it because he used a document.querySelector to target the parent and that's all. <div class="row"> <form id="task-form" action="index.php"> <div class="input-field col s12"> <input type="text" name="task" id="task" value=""> <label for="task">New Task</label> </div> </div> <button id="add" class="btn">Add</button> </form> he then wrote : document.querySelector('form').addEventListener('submit', function(event) { /* ... */ }) to me what I understand is that the querySelector will only select the firstChild in this case. Via Active questions tagged javascript - Stack Overflow https://ift.tt/x9p2GDY

Trying to input counts that are float values into histogram with set bins

I have this set of data here that I am trying to create a histogram for: | cos_low | cos_up | E_low | E_up | diff_cross | |-1 |-0.9 |105 |162.9 |21.7861 | |-1 |-0.9 |162.9 |220.8 |41.0181 | |-1 |-0.9 |220.8 |278.7 |38.4258 | |-1 |-0.9 |278.7 |336.6 |23.33 | |-1 |-0.9 |336.6 |394.5 |7.47169 | |-1 |-0.9 |394.5 |452.4 |1.41047 | |-1 |-0.9 |452.4 |510.3 |0.190604 | |-1 |-0.9 |510.3 |568.2 |0.0381209 | |-1 |-0.9 |568.2 |626.1 |0 | |-1 |-0.9 |626.1 |684 |0 | (There is no header in the original text file) This is just a portion of the full set of data I have but the format is the same. It contains the bin edges for the angle and energy. The energy bin goes from 105 to 3000 with 50 bins. I am trying to put the diff_cross values as the counts for each energy bin into a histogram but I can't get it to plot. I've tried the code for d...

I'm trying to build a database for phone contacts in python but i still get this error when using sqlite3

import sqlite3 connection = sqlite3.connect("ContactsDatabase.db") cursor = connection.cursor() cursor.execute( "Create table ContactsDatabase (contact_name text, contact_adress text, contact_phone_number integer, contact_email text)") class Contact_Book: contact_name = str(input("Contact Name: ")).capitalize() contact_adress = input("Contact Adress: ").capitalize() contact_phone_number = int(input("Contact Phone Number: ")) contact_email = input("Contact Email Adress: ") def name(self): self.name = Contact_Book.contact_name return self.name def adress(self): self.adress = Contact_Book.contact_adress return self.adress def phone_number(self): self.phone_number = Contact_Book.contact_phone_number return self.phone_number def email(self): self.email = Contact_Book.contact_email return self.email def contact_list(self)...

Am I reinventing the wheel with this MobX / React pattern I made up?

I started putting controller-like (e.g. cancelSelection()) functions in their own files (e.g. cancelSelection.js). These functions typically read and write to a variety of MobX stores. Stores are stored on the window and are abstracted behind a "getContext" function I invented. The React jsx calls these functions. e.g. // cancelSelection.js import {getContext} from "./context" export function cancelSelection() { const { rootStore: { selectionStore, toolbarStore } } = getContext(); selectionStore.clear(); toolbarStore.setTool(CURSOR); } // App.jsx import { cancelSelection } from "./cancelSelection" <button onClick={() => cancelSelection()}>Cancel Selection</button> Pros the test code can read them via the getContext() function. it's easy to find the orchestrator I need in VS Code with Cmd+P 'cancelSel...' keeps the jsx file smaller Cons ...? Via Active questions tagged javascript - Stack Overflow https://ift.tt/HE...

pattern number, javascript, loop

I am trying to print this pattern using javascript. but I need to enter by the user the following: for example: enter a starting number: 2 insert a final number: 5 enter the jump :2 so far i try this, let beginGetal = Number(prompt("Geef een begingetal in:")); let eindGetal = Number(prompt("Geef een eindgetal in:")); let sprong = Number(prompt("Geef een sprong in:")); let string = ""; let count = beginGetal; for (let i = 1; i <=eindGetal; i++) { for (let j = 1; j <= i; j++) { string += count +"," ; count++; } string += "\n"; } console.log(string); >2 >3,4,5, >6,7,8,9,10, >11,12,13,14,15,16,17, >18,19,20,21,22,23,24,25,26 like this Via Active questions tagged javascript - Stack Overflow https://ift.tt/HEF1bm4

Chrome Extension: How to get object from DB when searching by value?

Im trying to create a chrome extension, and have encountered an annoying problem. I have this function, where I add an object to my indexedDB if the urlKeyValue of that object, does not already exist in the database. If the urlKeyValue does exist in the DB, i want to get the object in the DB that contains that value. This is where my problem begins. On line 184 - 188, i try to get the object by searching by the `urlKeyValue, but when I try to print the object, i get undefined . Question: How to get an object from IndexedDB by a value? This is how my objects are structured: { message: "insert", payload: [ { urlKeyValue: "", url: { [userId]: { [time]: { msg: form_data.get("message"), }, }, }, }, ], } My Function where it all happens: function insert_records(records, when) { if (db) { const insert_transaction = db.transaction(["r...

ConversationHandler not moving to the next state

I have the following ConversationHandler conv_handler = ConversationHandler( entry_points=[CommandHandler('entry' entry)], states={ ONE: [MessageHandler(filters.TEXT, one)], TWO: [MessageHandler(filters.TEXT, two)], THREE: [CallbackQueryHandler(three)], FOUR: [CallbackQueryHandler(four)] }, fallbacks=[CommandHandler(Commands.CANCEL.value, cancel)], ) I defined the states keys as follows: ONE, TWO, THREE, FOUR = range(4) Entry function: async def entry(update: Update, context: ContextTypes) -> int: await update.message.reply_text("bla") return ONE ONE function: async def one(update: Update, context: ContextTypes) -> int: x = update.message.text await update.message.reply_text("yes. bla.") context.user_data["x"] = x return TWO TWO function: async def two(update: Update, context: ContextTypes) -> int: await update.message.re...

Azure storage CORS settings for video element

I'm creating panorama tour with some additional content (videos,...) with three js and react. My videos are stored on private azure storage, where I generate SAS token for certain video files. When I try to play video from gui it works with CORS well : <video id={uid} autoPlay controls controlsList="nodownload"> <source style= src={videoPath} type={"video/mp4"}/> </video> //this one is working videoPath in this case is on www.mystorage.azurelink.net , not on my origin. But when I create video element dynamically per view: const videosRoot = document.getElementById("videosroot") const video: HTMLVideoElement = document.createElement("video") video.id = `video-${this.uid}` video.crossOrigin = "anonymous" video.playsInline = true video.muted = true video.style.display = "none" const source = docume...

Retrieve and send a Postico bytea image

I have an app which uses AWS Lambda functions to store images in a AWS PostgreSQL RDS as bytea file types. The app is written in javascript and allows users to upload an image (typically small). <input className={style.buttonInputImage} id="logo-file-upload" type="file" name="myLogo" accept="image/*" onChange={onLogoChange} /> Currently I am not concerned about what format the images are in, although if it makes storage and retrieval easier I could add restrictions. I am using python to query my database and post and retrieve these files. INSERT INTO images (logo, background_image, uuid) VALUES ('{0}','{1}','{2}') ON CONFLICT (uuid) DO UPDATE SET logo='{0}', background_image='{1}';".format(data['logo'], data['background_image'], data['id']); and when I want to retrieve the images: "SELECT logo, background_image FROM clients AS c JOIN images AS i ON ...

How to prevent form submission if only one out of two paired inputs is filled out

I have a pair of inputs. I have no problem with a user leaving the both of them blank. But what I need is a way to force the user to fill the second input field if he decides to fill the first input field and vice versa(or prevent form submission in the event of that). Here are my input elements: <input name="cas[]" id="ca"> <input name="exams[]" id="exam"> <button type="submit" id="submit">Submit</submit> I would also appreciate if there is also an implementation for multiple input pairs. Via Active questions tagged javascript - Stack Overflow https://ift.tt/qfys7Th

javascript press key function

I want to add my javascript a key press function because my script run automaticaly I want it when i press a specific key it will run and stop The JS will not run / run automaticaly until i press "a" When I press "a" it will run; When I press "e" it will stop. Can you add it to my javascript, Thanks. here is the code bellow: var currentpos = 0, alt = 1, curpos1 = 0, curpos2 = -1 function initialize() { startit() } function scrollwindow() { if (document.all) temp = document.body.scrollTop else temp = window.pageYOffset if (alt == 0) alt = 1 else alt = 0 if (alt == 0) curpos1 = temp else curpos2 = temp if (curpos1 != curpos2) { if (document.all) currentpos = document.body.scrollTop + 1 else currentpos = window.pageYOffset + 1 window.scroll(0, currentpos) } else { currentpos = 0 window.scroll(0, currentpos) } } function startit() { setInterval("scrollwindow(...

Change Body background Color On Scroll Using Locomotive Scroll

I'm trying to have the background of each section change when you scroll through (using locomotive-scroll) and i used this response which works up to a point, but doesn't change back when i move to the previous section. Any idea how to get this effect thanks. Here is a link to the website I saw that does it beautifully Example Use https://stackoverflow.com/a/66184996/14719899 <div class="body locomotive-scroll" data-scroll-container> <div data-scroll-section> <section id="landing-page" data-scroll data-scroll-repeat data-scroll-call="pageColor" data-scroll-id="data-scroll-landing-page" data-scroll-id="black"> some content </section> <div> <div data-scroll-section> <section id="landing-page" data-scroll data-scroll-repeat data-scroll-call="pageColor" data-scroll-id="data-scroll-landing-page" data-scroll-id="white"> some content ...

blender 3.2? - How to hide object in new window

Blender - How to hide object only in this new window which i creat create a button in blender VIEW_3D_UI and if i click the button in UI they create a new window if the new window appear on the screen then i select the object and press the key = any. thay hide the object only in this window which i creat. not in whole blender only in this newly window Code: import bpy render = bpy.context.scene.render render.resolution_x = 640 render.resolution_y = 480 render.resolution_percentage = 100 prefs = bpy.context.preferences prefs.view.render_display_type = "WINDOW" bpy.ops.render.view_show("INVOKE_DEFAULT") area = bpy.context.window_manager.windows[-1].screen.areas[0] area.type = "VIEW_3D" sorry for my bad english source https://stackoverflow.com/questions/73774868/blender-3-2-how-to-hide-object-in-new-window

Why is 'this' different when a function is invoked in a callback vs when invoked regularly ex.) showThis(); [duplicate]

enter image description here ui.title.addEventListener('click', ui.showThis) ui.title.addEventListener('click', () => { ui.showThis(); }) I have a keyup event on an input field in my application that calls a function in my UI Controller module showThis(){ console.log(this); } which logs the value of this when the input field is clicked. enter image description here Why is it that the value of 'this' is different when the function is called within a callback function on the event listener vs. when the function is itself passed as the callback? Via Active questions tagged javascript - Stack Overflow https://ift.tt/htNsJ70

Empty body as response from server

I have a basic python server like this: from http.server import HTTPServer, BaseHTTPRequestHandler import json class ServerHandler(BaseHTTPRequestHandler): def do_POST(self): print("got post") content_len = int(self.headers.get('Content-Length')) print(content_len) post_body = json.loads(self.rfile.read(content_len)) self.send_response(200) self.send_header('Content-type',"application/json") self.end_headers() self.wfile.write(b'{"message":"General Kenobi"}') server= HTTPServer(('',6000),ServerHandler) server.serve_forever() print("server started...") and I'm sending my post request from godot (gdscript) like this: tool extends HTTPRequest export (bool) var send_req_btn = false setget send_req func send_req(val): if(val): # Create an HTTP request node and connect its completion signal. var body = to_json({...

Bounding HTML Tooltip inside listener

I am visualizing data using d3.js . Within the visualization, I have built a HTML tooltip. I have overlaid a svg rect to listen to the desired mouseevents before it can generate the tooltip. It has been good so far. However, I desire the tooltip to adjust its position in a way so that it always stays inside the listening rect . But I can't seem to find a way to do that. The code is below const data = [{ x: 1, y: .03 }, { x: 2, y: .04 }, { x: 3, y: .06 }, { x: 4, y: .09 }, { x: 5, y: .13 }, { x: 6, y: .18 }, { x: 7, y: .25 }, { x: 8, y: .33 }, { x: 9, y: .45 }, { x: 10, y: .59 }, { x: 11, y: .76 }, { x: 12, y: .97 }, { x: 13, y: 1.22 }, { x: 14, y: 1.52 }, { x: 15, y: 1.85 }, { x: 16, y: 2.24 }, { x: 17, y: 2.66 }, { x: 18, y: 3.13 }, { x: 19, y: 3.63 }, { x: 20, y: 4.16 }, { x: 21, y: 4.71 }, { x: 22, y: 5.27 }, { x: 23, y: 5.83 }, { x: 24, y: 6.38 }, { x: 25, y: 6.91 }, { x: 26, y: 7.4 }, { x: 27, y: 7.85 }, { x: 28, y: 8.25 }, { x: 29, y: 8.59 }, { x: 30, y: 8.86 }, { x: 31...

How to communicate between typescript decorators

To learn more about decorators I would like to create a decorator which caches the output of a function, something like this class BarFoo { @Cahced() doComplexCalc(@CahcedParamIgnore() a, b, c) { } } DEMO The @Cached decorator caches the response from doComplexCalc based on the values from a , b and c . As you can see in the example, I would also like to be able to ignore one or more method arguments. My question is, what would be the best way for the @CahcedParamIgnore decorator to inform the @Cached decorator about which arguments to ignore? Via Active questions tagged javascript - Stack Overflow https://ift.tt/htNsJ70

Create new in JS

i want to create new table row as text <tr> after every third table data <td> from user input. It have to be like this: <table border="3" align="center" style="width: 100%;"> <tr> <td><a href="link"><img src="link"></td> <td><a href="lin"><img src="link"></td> <td><a href="link"><img src="link"></td> </tr> <tr> <td><a href="link"><img src="link"></td> <td><a href="lin"><img src="link"></td> <td><a href="link"><img src="link"></td> </tr> </table> My code: <script type="text/javascript"> let x = 0; const data = Array(); document.getElementById('btn').addEventListener("click", fun); ...