Skip to main content

Posts

Showing posts from December, 2022

FuelSDK: use get() to pull salesforce items into a dataframe

I'm attempting to use Salesforce FuelSDK to pull audit items (i.e. click events, unsub events, bounce events, etc.) from our client's Marketing Cloud. I'm sure this is down to my inexperience with APIs, but although I'm able to get a success code from "get()", I'm not sure how to pull the actual content. The end goal is to pull each event type into its own dataframe. Here's what I have so far: import FuelSDK import ET_Client import pandas as pd import requests # In[2]: #define local variables clientid= 'client_id_code_here' clientsecret='client_secret_code_here' subdomain = 'mcx1k2thcht5qzdsm6962p8ln2c8' auth_base_url = f'https://{subdomain}.auth.marketingcloudapis.com/' rest_url = f'https://{subdomain}.rest.marketingcloudapis.com/' soap_url=f'https://{subdomain}.soap.marketingcloudapis.com/' # In[3]: #Passing config as a parameter to ET_Client constructor: myClient = FuelSDK.ET_Cli

How to check the front end before deployment in Elastic Beanstalk

I am building a web app using Python+Flask back-end and I want to deploy on Elastic Beanstalk with Pipelines and Github. I am trying to understand how to create a testing/pre-prod stage where I can see the front-end result before deployment. All resources I have found talk either about source+deploy stages in Pipelines or at most with some build stage for unit tests etc. But what about actually seeing the result on the browser? How can I see that before hitting (manually probably) the Approve/deploy button? Any help would be appreciated, doesn't have to be the full solution, a pointer to web/youtube video should also work. Thanks! source https://stackoverflow.com/questions/74971951/how-to-check-the-front-end-before-deployment-in-elastic-beanstalk

Phaser 3 physics group with circle

I'm fairly new to Phaser, and am following this tutorial: https://www.codecaptain.io/blog/game-development/shooting-bullets-phaser-3-using-arcade-physics-groups/696 Except, that instead of the Laser being a Sprite , I just want it to be a simple circle, so I tried the following; export class Laser extends Phaser.Physics.Arcade.Body { constructor(scene: Phaser.Scene, x: number, y: number) { const c = new Phaser.GameObjects.Ellipse(scene, x, y, 25, 25, 0x00ff00); super(scene.physics.world, c); } } This just throws the following error Uncaught TypeError: child.addToDisplayList is not a function . Am I missing something fairly fundamental here? I can only seem to be able to use Phaser.Physics.Arcade.Sprite or Phaser.Physics.Arcade.Image . Is it not possible to just have a physics object that consist of multiple rectangles or circles? Via Active questions tagged javascript - Stack Overflow https://ift.tt/gYJHezQ

How can I read from this file and turn it to a dictionary?

I've tried several methods to read from this file and turn it to a dictionary but I'm having a lot of errors I've tried the following method but it did not work I got not enough values unpack . d = {} with open("file.txt") as f: for line in f: (key, val) = line.split() d[int(key)] = val I want to read and convert it to this: {123: ['Ahmed Rashed', 'a', '1000.0'], 456: ['Noof Khaled', 'c', '0.0'], 777: ['Ali Mahmood', 'a', '4500.0']} source https://stackoverflow.com/questions/74971504/how-can-i-read-from-this-file-and-turn-it-to-a-dictionary

Assigning object to array adds many nulls

I try to assign an object to an array by key but it ends up with many nulls inside besides the actual object. First of all, I output data to an HTML data-* attribute with PHP: <div id="" data-my-obj=""></div> Then I read the data object and the id with jQuery, and I assign the the object to an empty array with the id as the key (I get the id somewhere else above this piece of code): let arr = []; let myObj = $(`#${id}`).data(`myObj`); console.log(JSON.stringify(myObj)) // outputs {"data": "some_data"} correctly if (arr[id] === undefined) { arr[id] = []; // in case it was not initialized before } arr[id] = myObj; But when I console log the arr using console.log(JSON.stringify(arr)) it shows me the following: [null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, {"data": "some_data"}] I manag

Slide Toggle on link click, but keep link clickable to page

I have a "dot" navigation on a site that has one link with a submenu. Originally, I had a simple JQ function that would slideToggle() the submenu on hover but that was causing some 'bouncing' issues. So, I reverted it back to click() function. $("#troy-dot-nav li.menu-item-81 > a").click(function(e){ e.preventDefault(); $(this).siblings('.sub-menu').slideToggle('800'); }); In doing so, I need to add the preventDefault() so the submenu would open up on click, but disable the link. Turns out, I need to keep the link on that active to navigate to that top-level page, but can't seem to figure out the best way to go about allowing the submenu to open (on click or hover; without bouncing) and keep the menu link active. HTML for Menu <div class="menu-primary-container"> <ul id="troy-dot-nav" class="menu reverse-dots"> <li class="..."><a href="...">Abou

Variable Sites in Alignment using Python

from Bio import AlignIO from Bio.Seq import Seq from Bio.Align import MultipleSeqAlignment from Bio.SeqRecord import SeqRecord counter = 0 Sitesofvariation = [] for i in range(0,len(alig[0])): s = alig[:,i] if s == len(s) * s[0]: counter += 1 Sitesofvariation.append(i+1) Will this work to help me find the sites of variation in my genome alignment? source https://stackoverflow.com/questions/74965637/variable-sites-in-alignment-using-python

How can I reduce the length of my conditionals in my JavaScript?

let getSlotList = []; if ( res.data.hasOwnProperty('alley') && res.data.hasOwnProperty('booked') && res.data.hasOwnProperty('reminder') ) { getSlotList = [ ...res.data.alley, ...res.data.booked, ...res.data.reminder, ]; } else if ( res.data.hasOwnProperty('alley') && res.data.hasOwnProperty('booked') ) { getSlotList = [...res.data.alley, ...res.data.booked]; } else if ( res.data.hasOwnProperty('booked') && res.data.hasOwnProperty('reminder') ) { getSlotList = [...res.data.reminder, ...res.data.booked]; } else if ( res.data.hasOwnProperty('alley') && res.data.hasOwnProperty('reminder') ) { getSlotList = [...res.data.alley, ...res.data.booked]; } else if (res.data.hasOwnProperty('alley')) { getSlotList = [...res.data.alley

Getting the current git hash of a library from an Airflow Worker

I have a library mylib that I want to get the current git hash for logging purposes when I run an Airflow Worker via the PythonOperator , I know several methods to get the latest git hash , the main issue is I don't know where the directory will be and I'll likely be running it out of directory . The workers themselves can all vary (docker, ec2, gke, kubenetes) but the source python library mylib would always be installed via a pip install git+https://${GITHUB_TOKEN}@github.com/user/mylib.git@{version} command. Is there a generic way I can get the git hash for mylib on any Airflow worker since the directory where mylib is installed will change across my Airflow Workers? source https://stackoverflow.com/questions/74954628/getting-the-current-git-hash-of-a-library-from-an-airflow-worker

Firebase Two-Factor Authentication with Typescript: Error (auth/argument-error)

I have followed the code from the official docs . When you scroll down to the full code, it has two things that make problems. First of all, this seems weird: const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth); const auth = getAuth(); They define auth after using it for recaptchaVerifier . But that seems like a typo, so I just switched these two lines. But I cannot resolve the second issue. Their code is in JavaScript, my code is in TypeScript. They use undefined as an argument in the definition of recaptchaVerifier : const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undefined, auth); The second argument of the constructor is undefined . Since TypeScript does not allow that, I tried many things, for example these: const undef: any = undefined; const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container-id', undef, auth); const recaptchaVerifier = new RecaptchaVerifier('recapt

Arguments for Node child_process "spawn()"

Using child_process (spawn) to open a new BASH terminal and execute the commands in each file. I want to add all of my .sh files, that I'm going to spawn, into a folder to clean up my project directory. PROBLEM: I can't figure out how to change the directory the scripts run from, and the docs are a little to heavy for me at this point. SIMPLE TEST EXAMPLE, WITH MY FIRST TWO FILES FOR CONNECTING (each .sh file would be in the project folder): const { spawn } = require('node:child_process'); const bat = spawn('cmd.exe', ['/c', 'connect.sh']); /* <connect.sh> // 1st .sh file #!/usr/bin/env bash //to make it bash HTTP_PORT=3002 P2P_PORT=5002 PEERS=ws://localhost:5001 npm run dev <connect1.sh> // 2nd .sh file #!/usr/bin/env bash //to make it bash HTTP_PORT=3003 P2P_PORT=5003 PEERS=ws://localhost:5002,ws://localhost:5001 npm run dev */ I have 9 of these files to connect up to 10 peers. And I

Why does web3py transtactions not work in my code?

from web3 import Web3 import requests *i have also connect to a node provider before this function. def buy_coin_token(): from_acc = str(input("Sender acc:")) private_key = str(input("Senders private key:")) to_acc = str(input("Receiver acc/contract address:")) amount_to_send = input("Amount to send:") gas = int(input("Gas:")) gas_price = int(input("Gas price:")) nonce = w3.eth.getTransactionCount(from_acc) tx = { 'nonce': nonce, 'to': to_acc, 'value': amount_to_send, 'gas': gas, 'gasPrice': gas_price } signed_tx = w3.eth.account.signTransaction(tx, private_key) tx_hash = w3.eth.sendRawTransaction(signed_tx.rawTransaction) print("Your transactions has is "+(tx_hash)) I am trying to make a transaction on the bsc and i keep bumping into the same error: TypeError: Transaction had invalid

How to generate text from Python DataFrame

How do I generate a string of text based on data in a pandas dataframe? for i in FLEDefendantsTbl: doc.add_paragraph('At all times material hereto, ' + FLEDefendantsTbl['Name'] + ' was a Florida corporation that regularly transacted business in ' + CaseInfoTbl['County'] + ' County, Florida.') I keep getting this error: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). I've already filtered exactly the table of data I want. I just need this text to be generated for each row of the filtered data. How do I do this? source https://stackoverflow.com/questions/74956063/how-to-generate-text-from-python-dataframe

How can I use javascript to create a div with elements inside of it?

I would like to create the following structure: <div> <label>Label:</label> <p>This text should be right beside the label</p> </div> So the results would look something like: Label: Here is the text I have tried doing using the following: label_element = document.createElement('label') p_element = document.createElement('p') label_node = document.createTextNode('text') p_node = document.createTextNode('text2') label_element.appendChild(p_element) document.getElementById('anchor').appendChild('label_element') The above returns: Label: Here is the text How can I make them together? An alternative for me would be to concate strings into one, but what if I want to have an input field right beside the label field? Via Active questions tagged javascript - Stack Overflow https://ift.tt/ru1Y7Xw

Can't upgrade geopandas

I looked at the documentation for geopandas. https://geopandas.org/en/v0.4.0/install.html Apparent, this is how you install geopandas: conda install -c conda-forge geopandas I tried that and I'm getting version .9, but the newest version seems to be .12, but I can't seem to upgrade my version of geopandas. Also, when I try to run this: geopandas.sjoin_nearest I'm getting this error: AttributeError: module 'geopandas' has no attribute 'sjoin_nearest' Has anyone experienced this? Is there some kind of work-around? source https://stackoverflow.com/questions/74954959/cant-upgrade-geopandas

add more fields to the filter function Angular

Tengo una funcion filter que le digo que me traiga los registerBy y al momento de implementarla en el html funciona, pero claro solo con ese campo, y yo quiero agregar mas campos a ese filtro, pero no se como se puede hacer. quiero agregar 2 campos mas a ese filtrado. aqui esta el código de TS y HTML: TS private _filter(value: string): string[] { const filterValue = value.toLowerCase(); this.data.registerBy = filterValue this.rest.get('/history?where={"registerBy":{"contains":"' + this.data.registerBy + '"}}' + "&skip=" + this.skip + "&limit=" + this.limit + "&sort=id DESC") .subscribe((result: any) => { this.currentHistory = result }) return this.currentHistory } HTML <div class="filter" fxLayoutAlign="end"> <mat-form-field appearance="legacy"> <mat-label> <mat-icon>search</mat-icon> Busc

setTimeout triggers too late in MIDI.js

I'm using MIDI.js to play a MIDI file with several musical instruments. Why are the following things executed too late ? First notes of the song. Like all notes, they are scheduled via start() of an AudioBufferSourceNode here . MIDI program change events . They are scheduled via setTimeout here . Their "lateness" is even worse than that of the first notes. When I stop the song and start it again, there are no problems anymore, but the delay values are very similar. So the delay values are probably not the cause of the problem. (I use the latest official branch (named "abcjs") because the "master" branch is older and has more problems with such MIDI files.) Via Active questions tagged javascript - Stack Overflow https://ift.tt/ru1Y7Xw

PySpark least or greatest with dynamic columns

I need to give a dynamic parameter to greatest in pyspark but it seems it doesn't accept that, column_names=['c_'+str(x) for x in range(800)] train_df=spark.read.parquet(train_path).select(column_names).withColumn('max_values',least(col_names)) So what is the way to do this without using RDDs and just dataframes source https://stackoverflow.com/questions/74945288/pyspark-least-or-greatest-with-dynamic-columns

Is Any Of My CSS Or Javascript Crashing The Mobile Version of Google Chrome?

I'm a beginner in coding with HTML, CSS, and Javascript, and have created a simple website with a responsive menu. It works well on every browser except for the mobile (ios) version of Google Chrome. What's happening is that after viewing a few pages if I try to click on a link and navigate to another page it will constantly show that it's loading that page and nothing happens, it stays on the current page. After that, it's as if the site freezes and I have trouble navigating to any previous page I've viewed. I've seen that some people are having difficulty with the mobile version of Google Chrome based upon certain code (CSS and/or Javascript) and wondered if that is what may be causing my website not to open properly on it. If anyone has any knowledge as to what may be causing my website not to load properly I'd appreciate you sharing your knowledge with me. Thank you. HTML/MENU: <!DOCTYPE html> <html lang="ja"> <head>

sprites are not removed from the screen

enter image description here I am writing a game. After death, I can restart the game. But the sprites of old enemies are not removed even after what I wrote in the code: enter image description here . New enemies just spawn and old just stop. mobs.empty() mobs.add() mobs arent removed from screen source https://stackoverflow.com/questions/74944517/sprites-are-not-removed-from-the-screen

I get "undefined" when I use return;

I get a snapshot value that if I console.log it works but I when I return the value I get "undefined". I tried changing variable and changing the return values and using await and async . async function GetElements(element, place) { firebase.database().ref().child(place).orderByChild("uid").equalTo(element).once('value', (snapshot) => { snapshot.forEach(function(childSnapshot) { Holder = childSnapshot.val(); }); }, (errorObject) => { console.log("User does not exist"); document.cookie = "uid=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT"; window.location.replace("login.html"); }); return Holder; } async function Test() { var bob = await GetElements("POkHi19eyZTfdeYECVpZByeVv2R2", "users/"); console.log(bob) } Test() Via Active questions tagged javascript - Stack Overflow https://ift.tt/ICsoGYX

Data transformation for conditional multicolour line matplotlib

This question has been asked around but I could not adapt any of the previous answers and I am looking for help. I have the following df: myf = {'A': {0: 0.118905, 1: 0.116909, 2: 0.114422, 3: 0.111605, 4: 0.108002, 5: 0.103467, 6: 0.0982083, 7: 0.0938204, 8: 0.090206, 9: 0.0871905, 10: 0.084656, 11: 0.08252, 12: 0.0807242, 13: 0.0792274, 14: 0.0780016, 15: 0.0770298, 16: 0.0763054, 17: 0.0758326, 18: 0.0756302, 19: 0.075625, 20: 0.075625}, 'B': {0: 0.13157894736842105, 1: 0.12597030386740332, 2: 0.12036337209302327, 3: 0.1147584355828221, 4: 0.10915584415584415, 5: 0.10355603448275864, 6: 0.09795955882352941, 7: 0.09236712598425198, 8: 0.08677966101694914, 9: 0.08119839449541284, 10: 0.07562500000000003, 11: 0.07006181318681318, 12: 0.06451219512195122, 13: 0.05898116438356164, 14: 0.053476562500000005, 15: 0.04801136363636364, 16: 0.042608695652173914, 17: 0.0373141891891892, 18: 0.03223214285714286, 19: 0.02766447368421054, 20: 0.025000000000000022}, 'x': {0

Problem with solving exquations of TransposedConv2D for finding its parameters

Regarding the answer posted here , When I want to use the equations for obtaining the values of the parameters of the transposed convolution, I face some problems. For example, I have a tensor with the size of [16,256,16,160,160] and I want to upsample that to the size of [16,256,16,224,224]. Based on the equation of the transposed convolution, when, for solving the equations for the height, I select stride+2 and I want to find the k (kernel size), I have the following equation that the kernel size will have a large and also negative value. 224 = (160 - 2)x (2) + 1x(k - 1) + 1 What is wrong with my calculations and how I can find the parameters. source https://stackoverflow.com/questions/74898431/problem-with-solving-exquations-of-transposedconv2d-for-finding-its-parameters

Switching from mqtts protocol to wss in nodeJS

I can connect to my MQTT broker, using mqtts protocol like this: mqtt = require('mqtt') let options = { host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud', port: 8883, path: '/mqtt', clientId: 'mqttx_2d803d2743', protocol: 'mqtts', username: 'light29', password: 'Mqtt29@!', cleanSession: true, } // initialize the MQTT client let client = mqtt.connect(options); // setup the callbacks client.on('connect', function () { console.log('Connected'); }); client.on('error', function (error) { console.log(error); }); client.on('message', function (topic, message) { // called each time a message is received console.log('Received message:', topic, message.toString()); }); // subscribe to topic 'my/test/topic' client.subscribe('mytest'); // publish message 'Hello' to topic 'my/test/topic' client.publish(&#

What alternative can I use for event.unicode?

I've just started out coding in python, and I was playing around with text boxes, when I got an error (AttributeError: 'Event' object has no attribute 'unicode'). From what I've found on a few forums, this error is because I use Python 3, but I couldn't find anywhere an alternative I could use. for event in pygame.event.get(): # quit if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if input_rect.collidepoint(event.pos): active = True else: active = False if event.type == pygame.KEYDOWN: # Check for backspace if event.key == pygame.K_BACKSPACE: user_text = user_text[:-1] else: user_text += event.unicode # here is where I recieve the error The exact error is: user_text += event.unicode ^^^^^^^^^^

How to use Hyperband to tune for single or multiple LSTM layers?

The logic is that if one LSTM layer is added then its return sequence must be False, whereas if two LSTM layers are to be added the first one should have return sequence equal to True. I'm trying to do this by using parent_values but it does not work, so far I have something like this: use_two_lstm_layers = hp.Boolean("use_two_lstm_layers") return_sequences = hp.Choice("return_sequences", ['True', 'False'], parent_values=True) model.add(keras.layers.Bidirectional(tf.keras.layers.LSTM(units=hp.Int('units', min_value=8, max_value=64, step=8), return_sequences=return_sequences))) model.add(keras.layers.Dropout(rate=hp.Float('dp', min_value=0.1, max_value=0.8, step=0.1))) if use_two_lstm_layers: model.add(keras.layers.Bidirectional(tf.keras.layers.LSTM(units=hp.Int('units2', min_value=8, max_value=256, step=8)))) model.add(keras.layers.Dropout(rate=hp.Float('dp2', min_value=0.1, max_value=0.8, step=0.1

Error Message Uncaught TypeError: Cannot read properties of undefined

Does anybody know why I get this error? I want to pass the setCookie function to ParseUserCookie but I get an error "Uncaught TypeError: Cannot read properties of undefined (reading 'setCookie')" function TicTacToe(){ const [cookie, setCookie] = useState(null); <button onClick={() => handleMultiplayerClick(setCookie)}> ..... } const handleMultiplayerClick = (props) => { promptUserCookie(); let cookie = parseUserCookie(props.setCookie); //Cannot read properties ... } Uncaught TypeError: Cannot read properties of undefined (reading 'setCookie') Via Active questions tagged javascript - Stack Overflow https://ift.tt/Jk789W3

React variable not changing within recursive function after i change it in another function

I have two functions in react. One is a recursive function which will repeatedly call itself after finishing the main operations based on whether a flag variable is true or false. I have a button which calls a toggle function to switch the flag variable between true and false. If it is false i want to stop the recursion and when i click the button again, the variable will switch to true and runs the recursuve function. The problem i have is the variable is updated within the toggle function but not in the recursive function therefore the recursive function cant be stopped. I have tried many ways including usestate for the flag variable, set timeout and clear interval also didnt work (recursive function kept on running). Please help me out, let me know if you need the specific code Via Active questions tagged javascript - Stack Overflow https://ift.tt/Jk789W3

Why is the while loop not working, python [closed]

The question is probably stupid, but I can't catch the error in my thoughts. I need to find the least common multiple. I know algorithms for solving this problem, but I wanted to experiment: a = int(input()) b = int(input()) if a > b: i = a while i % a != 0 and i % b != 0 and i < a * b: i += 1 print(i) else: i = b while i % a != 0 and i % b != 0 and i < a * b: i += 1 print(i) However, the numbers I enter do not go through the while loop, i is output as I assigned it. Help, please, to understand where I am stupid. source https://stackoverflow.com/questions/74923498/why-is-the-while-loop-not-working-python

How should I plot healpix binning

I was plotting celestial sphere with equal area binning. My first intention was making a binning based on the basic calculus knowledge which I learned from 1st year University calculus class. Following is what I made. import numpy as np import matplotlib.pyplot as plt def Drawpixel(lm,lM,bm,bM,co,w): l0=[lm,lM] b0=[bM,bM] l1=[lm,lM] b1=[bm,bm] l2=[lm,lm] b2=[bm,bM] l3=[lM,lM] b3=[bm,bM] plt.plot(l0,b0,c=co,linewidth=w) plt.plot(l1,b1,c=co,linewidth=w) plt.plot(l2,b2,c=co,linewidth=w) plt.plot(l3,b3,c=co,linewidth=w) def Paint(lm,lM,bm,bM,co): l=[lm,lM] b1=[bM,bM] b2=[bm,bm] plt.fill_between(l,b1,b2,color=co) plt.subplot(111,projection="aitoff") plt.title("Equal Binning", fontsize = 30) co='k' w=1 for i in range(16): bM=np.pi/2-np.arccos((8-i)/8) bm=np.pi/2-np.arccos((7-i)/8) for j in range(32): lm=(j-16)/16*np.pi*-1 lM=(j-15)/16*np.pi*-1 Drawpixel(lm,

how can I alter this code to remove javascript error message when correct value is entered in text field [duplicate]

This script enables a submit button only if numbers are entered into the text field. onkeyup if the field is empty or non-numeric values are used the button remains disabled and an error message is displayed. All works ok, but when numeric values are entered and the button is enabled, the error message is still visible. I am searching for a method to clear the error message as the numeric values are entered in the text box. I would be very grateful for any pointers. html <input type="text" id="numberTest" /> <button id="button" class="formButton" type="submit">Click Me</button> <div id="error"></div> javascript var formButton = document.getElementById("button"); formButton.disabled = true; var myInput = document.getElementById("numberTest"); const errorElement =document.getElementById('error'); myInput.onkeyup = function() { let message = []; var numberTes

How to architect passing data from a server to express routes without a database?

I am running a node.js application which upon startup uses fetch to call an external api (not owned by me) to grab data on a list of devices I own. Once I have this gotten this data from the fetch call I initialise an express server which is located in another file 'server.js' which itself requires an express Router defined in a subfolder 'routes' and mounted on the route '/api'. My question is, the data I initially fetch (which is a javascript object) can be modified by the express server I run, through post requests, and is periodically saved to disk by the primary application. Since the system I am running this on can't handle a database I just use a simple method of saving the data with the fs module. What is the best way to architect the flow of data so that the main process which starts the express server can both view and modify the data in the javascript object as well as the post and get routes of the express router being able to have the same pr

Struggling to get the data from useDocument to display with vue.js and Firestore

I'm trying to get a single record from Firestore to display in Vue.js. I'm using VueFire and the guide here . <script setup> import { initializeApp } from 'firebase/app' import { getFirestore , doc } from "firebase/firestore"; import { useDocument } from 'vuefire' const firebaseConfig = {...}; // Initialize Firebase const firebaseApp = initializeApp(firebaseConfig); const analytics = getAnalytics(firebaseApp); const db = getFirestore(firebaseApp); const place = useDocument(doc(db, "data", "key")); console.log(place) </script> <template> </template> The data logged is RefImpl {__v_isShallow: false, dep: undefined, __v_isRef: true, _rawValue : {title: 'I am a title', however when it gets to the template there is an error Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'title') Via Active questions tagged javascript - Stack Overflow https://ift.tt

How can i convert html entities in my twitter bot?

i'm a begginer programmer and i'm having troubles with my twitter bot. The idea of the bot is tweet an daily verse of bible everyday, and that's what I got so far: import tweepy import requests api = tweepy.Client( consumer_key='', consumer_secret='', access_token='-', access_token_secret='', ) response = requests.get("https://www.biblegateway.com/votd/get/?format=json&version=NVI-PT") verse_of_the_day = response.json()["votd"]["text"] try: tweet=api.create_tweet(text=("Aqui está o versículo do dia: \n") + verse_of_the_day) print(tweet) except: print("something is wrong") the problem is that some characters appear as HTML entity and not as the "character itself" and what I hope is to fix these characters that are in html entity source https://stackoverflow.com/questions/74915764/how-can-i-convert-html-entities-in-my-twitter-bot

How to recognize "@" with optical text recognition in python?

Since there are different ways of writing the sign "@", the python package of optical text recognition seems to have a hard time how to recognize it such as this package . Are there any known python package that can identify the various forms of "@" sign? source https://stackoverflow.com/questions/74915828/how-to-recognize-with-optical-text-recognition-in-python

Phyton: graph from csv filtered by pandas shows no graph

I would like to create a graph on filtered data from a csv. A graph is created but without content. Here is the code and the result: code cell 1 # var 4 graph xs = [] ys = [] name = "Anna" gender = "F" state = "CA" # 4 reading csv file import pandas as pd # reading csv file dataFrame = pd.read_csv("../Kursmaterialien/data/names.csv") #print("DataFrame...\n",dataFrame) # select rows containing text dataFrame = dataFrame[(dataFrame['Name'] == name)&dataFrame['State'].str.contains(state)&dataFrame['Gender'].str.contains(gender)] #print("\nFetching rows with text ...\n",dataFrame) print(dataFrame) # append var with value xs.append(list(dataFrame['Year'])) ys.append(list(dataFrame['Count'])) #xs.append(list(map(str,dataFrame['Year']))) #ys.append(list(map(str,dataFrame['Count']))) print(xs) print(ys) result cell 1 enter image description here code cel

How do you detect directional arrow keypresses in JavaScript? [duplicate]

I'm trying to detect keypresses on the left and right arrow keys. Here is my current code (nothing gets printed): this.addEventListener('keypress', event => { if (event.key == "ArrowLeft") { console.log("Left key"); } else if (event.key == "ArrowRight") { console.log("Right key"); } }); I've tried console.log(event.key) and pressing the directional arrow buttons as well, but again, nothing gets printed. Via Active questions tagged javascript - Stack Overflow https://ift.tt/1KpsiEP

Error with BrowserRouter in ReactJS: react.development.js:209 Warning: Invalid hook call. Hooks can only be called

I set up my react app like this so far: index.js : import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import {BrowserRouter, Routes, Route} from 'react-router-dom'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <BrowserRouter> <Route path="/" exact component={App} /> </BrowserRouter> ); App.js : import './App.css'; import {useState, useEffect} from 'react'; function App() { const [drinks, setDrinks] = useState([]); const fetchData = async () => { const response = await fetch('https://www.thecocktaildb.com/api/json/v1/1/list.php?c=list'); const jsondata = await response.json(); console.log(jsondata.drinks); setDrinks(jsondata.drinks); } useEffect(() => { fetchData(); }, []) return ( <div className="App"> &

Creating a Plane of best fit from points

Is there a way to make a plane of best fit using matplotlib? I'm trying to get a smooth curved plane, but I'm unsure on how to do so. My points are arranged as shown in the following image: They are quite smooth, except for a few exceptions, which are mostly clear. My current code is: from mpl_toolkits import mplot3d import matplotlib.pyplot as plt from sklearn import linear_model plt.style.use('seaborn-poster') x = np.array([12.5, 10, 9.5, 7.5, 6]) y = np.array([30, 45, 50, 55, 60, 65]) z = np.array([ [62.13, 55.41, 54.49, 46.46, 42.13], [67.11, 59.43, 56.39, 52.64, 41.89], [82.89, 61.13, 57.30, 50.75, 43.02], [73.31, 60.57, 57.17, 52.64, 41.73], [78.11, 62.92, 63.40, 58.08, 48.69], [83.96, 65.19, 60.22, 53.57, 44.22] ]) X, Y = np.meshgrid(x, y) Z = z x1, y1, z1 = X.flatten(), Y.flatten(), Z.flatten() X_data = np.array([x1, y1]).reshape((-1, 2)) Y_data = z1 reg = linear_model.LinearRegression().fit(X_data, Y_data) a1, a2, c = float(reg

access localhost with smartphone and get no response from the server

website works via localhost on pc access with smartphone to localhost via ip too (I receive html, css and js for client) when I click the button, a "hi" is also added but function "search()" is not executed but when I enter the url http://localhost:3000/users I get the "hi1" What do i have to do to make this work? Client Side const button = document.querySelector("button"); button.addEventListener("click", () => { document.getElementById("imageDiv").innerHTML = "Hi";//this work search();//this not work }); async function search(){ await fetch("http://localhost:3000/users") .then(response => response.json()) .then(response => { var image; image = JSON.parse(JSON.stringify(Object.assign({},response))); document.getElementById("imageDiv").innerHTML = response; })}; Server Side const express = require('express'); const

How to add GCP bucket to the Firestore with Python SDK?

I am trying to upload the file to the custom Google Cloud Storage bucket with a Flutter web app. final _storage = FirebaseStorage.instanceFor(bucket: bucketName); Reference documentRef = _storage.ref().child(filename); await documentRef.putData(await data); The code works fine for a default bucket but fails with a new custom GCP bucket. Error: FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown) The HTTP POST response causing this error says: { "error": { "code": 400, "message": "Your bucket has not been set up properly for Firebase Storage. Please visit 'https://console.firebase.google.com/project/{my_project_name}/storage/rules' to set up security rules." } } So apparently, I need to add a new bucket to Firestore and set up access rules before I can upload the file there. Since these buckets are created automatically by my backend microservi

How can I make autoscroll to only activate when the user is not interacting with my page?

From what I understand this script calculate the initial position and advances one pixel at a time but in a 10ms rate so it seems like a smooth scrolling. I like that, but I want it to call the scrolling only when the user is not interacting, in other words, I want it to stop scrolling as soon as the user interacts with the page. How can I accomplish such thing? 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

Python list index out of range in for loop

With the aviationstack API, I try to get info about every flight departing from Marseille (France) airport. I use the first steps to determine how many pages I have to iterate, as the API returns the total number of results and documentation says the default response has a limit of 100 results, then I build URL's according to the latter result. Though the code below could be simplified, it gives promising results, however at the last step, I need to provide counts at the line flight_data = response.get("data") in order to get every item of each offset. But it returns IndexError: list index out of range . I guess because the last offset contains less than 100 items. import requests import json import pandas as pd from pprint import pprint airport = 'LFML' # ICAO code for Marseille Provence airport, France KEY = XXX urllst = [] responselist = [] countlst = [] data = [] # determine how many results we get urlroot = f'http://api.aviationstack.com/v1/flig

How to replace placeholder in string with different value if more placeholders exist?

arr = [1,2,3,4,5,6,7] val = ? (3 different values from arr) result = "${val} and ${val} and ${val}" I want to replace ${val} with arr elements such that ${val} will not be same in result. I seriously don't have idea how to replace different values in place of ${val} Via Active questions tagged javascript - Stack Overflow https://ift.tt/iRDZqtF

How do I get the copied value on onCopy event in React?

Suppose I have a long string: "Jackie has a very big chicken at his farm" And I highlight "chicken" from the string and hit ctrl+C, It will trigger the handleCopy function passed into onCopy attribute of the element. I want to have the value of the substring or string being copied, in this case, "chicken" For example, function handleCopy(event){ //get the copied value here } <input value="Jackie has a very big chicken at his farm" onCopy={handleCopy} /> How am I able to achieve this in React? Via Active questions tagged javascript - Stack Overflow https://ift.tt/iRDZqtF

How to print only one item from a dictionary with a changeable variable

I am trying to print only one key and value from my dictionary at a time and have it print based on the player current room position. Every solution I tried so far, either prints all of the items, all the items 10 times (the number of how many items there are), or none. I been searching for web for several hours now, any help would be much appreciated! rooms = { 'Lower Deck': {'up': 'Main Deck'}, 'Main Deck': {'down': 'Lower Deck', 'forward': 'Main Hallway', 'item': 'Pistol'}, 'Main Hallway': {'right': 'Crew Cabins', 'back': 'Main Deck', 'forward': 'Air Lock'}, 'Crew Cabins': {'back': 'Main Hallway', 'item': 'Dog tags'}, 'Air Lock': {'back': 'Main Hallway', 'forward': 'Crews Lounge'}, 'Crews Lounge': {'back': 'Air Lock', '

Python - I'm not sure why this function I'm defining isn't working. Very fresh to programming

I'm trying to write a small program that calculates the discount of a coupon and then return the total with a 6% sales tax applied. I've done some searching, but I think I'm having trouble understanding the placement of the syntax. If there's a more direct answer already posted, I'll take the link! Thanks in advance. #Apply discount amount to item price and return with 6% sales tax #Function to perform discount calculation def calcDisc(): newTotal = iPrice * (iDisc / 100) print('The new total is: ', newTotal) return newTotal #Function to show total with 6% sales tax def calcDiscPlusTax(): taxTotal = newTotal * 0.6 print('The total with tax is: ', taxTotal) #Variable for item price iPrice = float(input('Please enter the item price: ')) #Variable for item with discount applied iDisc = float(input('Please enter the discount amount: ')) calcDisc() calcDiscPlusTax() source https://stackoverflow.com/questio

Zoomable plot of a list of colors in python with different coordinate systems

I'm trying to program a Python GUI for about 2 - 3 days now, which allows to zoom into a color palette. Since in the GUI or in the window the coordinates start with 0 and get bigger and bigger on x and y, a translation of the points has to be done. Example: I have a list "palette" of 12 colors in the format: [rgb1, rgb2, rgb3 ... ] and would like to draw it on the window. I prefer to draw the color strip from left to right using a for loop, and each iteration it draws a line from bottom to top. so that each pixel does not have a different color, i would have to divide the loop variable by the range of the window and multiply it by the range of the palette. Then I would have to get the color from the list using the rounded value. If I then take this value with a variable (the zoom), I can zoom in and out of the color strip. But then the center of the zoom is always to the left of the window (and he first color) and not where my mouse is. To put it briefly: How can I progr

localStorage how to keep the effect even if the page is refreshed?

I want to know how to keep the effect on my web page even if the page is refreshed. My JS Code: const button = document.querySelectorAll(".btn"); button.forEach((color) => { color.style.backgroundColor = color.getAttribute("data-color"); color.addEventListener("click", () => { const data = color.getAttribute("data-color"); const root = document.querySelector(":root"); const styles = { "--bs-primary-rgb": data, }; for (const [property, value] of Object.entries(styles)) { root.style.setProperty(property, value); } }); }); What does this code do? This code selects all elements with a class of btn and then applies a click event listener to each of them. When one of the buttons is clicked, it gets the value of the data-color attribute and sets it as the value of the --bs-primary-rgb CSS variable on the root element. The querySelectorAll

ImportError: cannot import name 'fetch' from 'js'

I am working on a coursera IBM project with Jupyter on my Ubuntu 22.04 and having problems with the very first cell of one section: # Download and read the `spacex_launch_geo.csv` from js import fetch import io URL = 'https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBM-DS0321EN-SkillsNetwork/datasets/spacex_launch_geo.csv' resp = await fetch(URL) spacex_csv_file = io.BytesIO((await resp.arrayBuffer()).to_py()) spacex_df=pd.read_csv(spacex_csv_file) spacex_df.head(15) and get the error: ImportError: cannot import name 'fetch' from 'js' (/home/tim/.local/lib/python3.10/site-packages/js/__init__.py) I have made sure to pip install js to my machine. Any ideas would be helpful. The only thing I notice when looking at the command line for my machine is that is says: Requirement already satisfied: js in ./.local/lib/python3.10/site-packages (1.0) Is this a problem with a global v. local to user installation of js? And if so, what can I do to

Receiving errors when defining functions (no self parameter, and invalid var type)

I'm trying to make a Python module which provides functions for user input. My code looks like this: class PyInput: def inputString(prompt = "Enter a string: >>> "): """inputString asks the user to input a string.""" userInput = input(prompt) str(userInput) return userInput Unfortunately, I am getting multiple errors: The first says that "Instance methods should take a "self" parameter" (I know what this means, but is there a way to not have to define a function within a class to accept a "self" parameter?) My second error is in my testing code, which looks like this: from PyIO import * vartest = "mystring" tester = PyInput.inputString(vartest) print(tester) and it says that: Argument of type "Literal['Input test: >>> ']" cannot be assigned to parameter "prompt" of type "PyInput" in function "inputSt

Connect 4 Javascript, algorithm makes multible moves before player is allowed to make move again

I'm currently in the process of learning JS and trying to recreate my first real project, a connect 4 minimax algorithm. I've somewhat gotten the algorithm to work, however it makes multiple moves inbetween every player move. I've tried moving around the inputs and changing up the algorithms a bit. Below I have provided the main game loop which it cycles through. If you want to see any of the other functions that are called I'd be happy to provide them. Gif link that shows the phenomena window.onload = function() { let app = new PIXI.Application( { width: 700, height: 700, backgroundColor: 0X0047AB, } ); document.body.appendChild(app.view); app.stage.interactive = true; let text = new PIXI.Text("", { fontFamily: "Arial", fontSize: 24, fill: 0x000000, }); text.x = 10; text.y = 650; app.stage.addChild(text); for (let r = 0; r < rows; r++) { let row = []; for (let c = 0; c < cols; c++)

python re extract smallest substring between two strings [duplicate]

Sorry in advance for a potentially duplicate question, I'm somewhat new to re and can't find an answer I have a string something like this: <foo><bar><biz><Baz><buz>Extract Me!</span><foo><bar> I want to extract Extract Me! , which is between a > and the only </span> that appears in the string. I tried >(.*)</span> , but that extracts ><bar><biz><Baz><buz>Extract Me!</span> . Edit: 1: This question got closed, linking to this as a duplicate , but making the regular expression >(.*)</span> "non greedy" by turning it into >(.*?)</span> yields the same result. I had already attempted this before posting. 2: After some discussions, I was recommended to just use BeautifulSoup , which makes sense. I've solved the issue with re.search(r'(?:>)(\b.*)(<\/span>)' , but I'll provide a bit more code so further exploration can be

How to compare Json date and return a new array

I have problem with the code below. I'm trying to return all votes between two dates, but for some reason it doesn't work well. FirstShiftStart date -> 2022-12-21 8:0:0 FirstShiftEnd date -> 2022-12-21 14:0:0 let current_datetime = new Date(); var firstShiftStart = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " " + 08 + ":" + 00 + ":" + 00; var firstShiftEnd = current_datetime.getFullYear() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getDate() + " " + 14 + ":" + 00 + ":" + 00;; var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0! var yyyy = today.getFullYear(); today = yyyy + '-' + mm + '-' + dd; votesforDay is returning only today&#

Mongoose deleting object ($pull) in Array does not work

I'm trying to delete an object inside an array in my DB using the $pull in Mongoose but does not work. This is my attempt: const listSchema = new Schema({ name: String, items: [] }); const List = mongoose.model("list", listSchema); const itemDeleted = req.body.checkbox; //I get here the ID of the object inside the array const itemListDeleted = req.body.listDeleted; // Here the name of the object that contains the array List.findOneAndUpdate({name:itemListDeleted},{$pull:{items:{_id: itemDeleted}}},function (err,foundList) { if (foundList){ res.redirect("/"+ itemListDeleted); } else { console.log(err); } }) I searched for solutions and everybody recommends using $Pull but in my case, it doesn't work. I log the const and all things appear to be right. Do you have any suggestions? Via Active questions tagged javascript - Stack Overflow https://ift.tt/YcnQmzt

Можете подсказать почему не навешивается addEventListener [closed]

const trash = document.querySelectorAll('.delete'); function addEventForBtn(btn, i) { btn.addEventListener('mouseout', function(e) { e.preventDefault() console.log('hello') btn.parentElement.remove(); movieDB.movies.splice(i, 1); }); } trash.forEach((btn, i) => { addEventForBtn(btn, i) }) Нужно чтобы на все кнопки повесилось событие и выполнялось удаление родителя кнопки. На кнопки навешивается функция но не выполняется при клике на нее Via Active questions tagged javascript - Stack Overflow https://ift.tt/YcnQmzt

Regex to validate characters and numbers concatenated with -

I'm trying to match a string that Characters and numbers cannot be concatenated, if you want to concatenate use a hyphen. For example, these should all match: abc-123-123-*** 123-abc-abc-*** 123-abc-123-*** abc-123-abc-*** abc-efg-*** not match: abc123 123abc abc1 a1b2 Please help me to find a javascript regex. Please help me to find a javascript regex. Via Active questions tagged javascript - Stack Overflow https://ift.tt/YcnQmzt

Discord.js@14.7 not picking up Events.GuildMemberUpdate

For context, this is how I am running my event listeners/handlers //handle events const eventsPath = path.join(__dirname, "events"); const eventFiles = fs .readdirSync(eventsPath) .filter((file) => file.endsWith(".event.js")); for (const file of eventFiles) { const filePath = path.join(eventsPath, file); const event = require(filePath); if (event.once) { client.once(event.name, (...args) => event.execute(...args)); } else { client.on(event.name, (...args) => event.execute(...args)); } } And this is how my events are written: const { Events, EmbedBuilder } = require("discord.js"); const { id } = require("../config/botlogs.channel"); module.exports = { name: Events.GuildMemberUpdate, once: true, async execute(oldMember, newMember) { //send message in botlogs channel const channel = newMember.client.channels.cache.get(id); //embed log const embed = new EmbedBuilder() .setColor("#009

Does anyone know how to create a menu without exiting the page?

Does anyone know how to create a menu without exiting the page? I want to create a settings menu. <style> .material-symbols-outlined { align: right; font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 48 } </style> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" /> <a OnClick="open()" <span class="material-symbols-outlined"> engineering </span></a> <div class="menu"> <p>Settings</p> </div> (I know that i should not use onclick but i don't know how to use anything else) <script> function show(){ div.menu.show=(true) } </script> I wanted it to show div but div is always shown Via Active questions tagged javascript - Stack Overflow https://ift.tt/YcnQmzt