| How to subscribe binance via websocket by pyside6? Posted: 16 Oct 2021 07:58 AM PDT i can get stream by this code: from PySide6.QtWebSockets import QWebSocket ... self.websocket = QWebSocket() self.websocket_base_url = 'wss://stream.binance.com:9443/ws' self.websocket.open(self.websocket_base_url + '/btcusdt@kline_5m') self.websocket.textMessageReceived.connect(self.on_message_received) def on_message_received(self, msg): print(msg) this can received stream normally, but i want to use subscribe, so i write this: self.websocket = QWebSocket() self.websocket_base_url = 'wss://stream.binance.com:9443/ws' self.websocket.open(self.websocket_base_url) info = { "method": "SUBSCRIBE", "params": [ "btcusdt@aggTrade" ], "id": 1 } ret = self.websocket.sendTextMessage(json.dumps(info)) print(str(self.websocket.state())) self.websocket.textMessageReceived.connect(self.on_message_received) def on_message_received(self, msg): print(msg) print() output: PySide6.QtNetwork.QAbstractSocket.SocketState.ConnectingState and self.on_message_received() no message received. i dont know why...  |
| How to localize a DataGridTextColumn? Posted: 16 Oct 2021 07:57 AM PDT While developing my app in WPF i used that code for localizing: <DataGridTextColumn Header="{x:Static p:Resources.DwApplicationId}" Binding="{Binding Id}"/> Now i try to upgrade the app to WinUI3, and there are no "x:Static" allowed. Also i have to use another way (Windows.ApplicationModel.Resources.ResourceLoader) to get the strings. I googled for hours, but nothing found. Maybe anyone knows how to fix it?  |
| Expose docker port to external wan interface in a linux host with iptables rules Posted: 16 Oct 2021 07:56 AM PDT I have a host with two nic one lets call eth0 and another eth1. eth0 is local lan and has no iptables filters. eth1 is a wan and has iptables dropping everything. Also I've a docker with a service in the port 80. When I run the docker I map the port 8086 to the 80. Then I open the firewall with: iptables -I INPUT 1 -p tcp -m tcp --dport 8086 -j ACCEPT The result is: I can reach the service from the internal lan in the expected port 8086 and no response from WAN. I've tested the traffic in the wan nic with: tcpdump -i any -n port 8086 I missing something, how can I open that port? The result of iptables -L is: Chain INPUT (policy ACCEPT) target prot opt source destination ACCEPT tcp -- anywhere anywhere tcp dpt:8086 ACCEPT tcp -- anywhere anywhere tcp dpt:466 ACCEPT tcp -- anywhere anywhere tcp dpt:1521 ACCEPT icmp -- anywhere anywhere ACCEPT tcp -- anywhere anywhere tcp dpt:12540 ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED DROP all -- anywhere anywhere Chain FORWARD (policy ACCEPT) target prot opt source destination DOCKER-USER all -- anywhere anywhere DOCKER-ISOLATION-STAGE-1 all -- anywhere anywhere ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED DOCKER all -- anywhere anywhere ACCEPT all -- anywhere anywhere ACCEPT all -- anywhere anywhere ACCEPT all -- anywhere anywhere ctstate RELATED,ESTABLISHED DOCKER all -- anywhere anywhere ACCEPT all -- anywhere anywhere ACCEPT all -- anywhere anywhere Chain OUTPUT (policy ACCEPT) target prot opt source destination Chain DOCKER (2 references) target prot opt source destination ACCEPT tcp -- anywhere 172.18.0.2 tcp dpt:https Chain DOCKER-ISOLATION-STAGE-1 (1 references) target prot opt source destination DOCKER-ISOLATION-STAGE-2 all -- anywhere anywhere DOCKER-ISOLATION-STAGE-2 all -- anywhere anywhere RETURN all -- anywhere anywhere Chain DOCKER-ISOLATION-STAGE-2 (2 references) target prot opt source destination DROP all -- anywhere anywhere DROP all -- anywhere anywhere RETURN all -- anywhere anywhere Chain DOCKER-USER (1 references) target prot opt source destination RETURN all -- anywhere anywhere How can I expose that port to the public wan?  |
| Multiple objects moving in turtle? Posted: 16 Oct 2021 07:55 AM PDT while True: setupSeats() createPassenger() for passenger in passengers: passenger.speed(passengerspeed) for i in range(len(seats)): x = seats[i].pos()[0] y = seats[i].pos()[1] passengers[i].setx(x) passengers[i].sety(y) if i>1: passengers[i+1].setx(x-100) This is for a plane simulation, passengers are red gif objects initiliazed at -900, 100. The issue is I can get them moving one by one to their seat, but how would I get it to so that the passenger behind follows the current passenger and they all update.  |
| Types object base on arras of another object Posted: 16 Oct 2021 07:55 AM PDT i have a next code: const arr = [ { name: 'john', age: '20' }, { name: 'anna', age: '30' } ] Now i create a new object based at arr: const obj = {} // {john:20,anna:30} arr.forEach(o => obj[o.name]=o.age) How can i dynamical type this obj, need interface like this: interface IObj { john: number, anna: number }  |
| mongo client stuck while accessing data from mongo db in cloud9 dev environment Posted: 16 Oct 2021 07:55 AM PDT We were testing our component in react and suddenly react code that accesses data from Mongo db through mongo client is stuck. We are not able to fetch data from database. We can access mongo db through compass. We are developing our app in cloud9 dev environment. client is react and server is django.  |
| Why do checkable menu items not display checkboxes Posted: 16 Oct 2021 07:55 AM PDT Menu: <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <group android:checkableBehavior="all"> <item android:id="@+id/itemFoo1" android:checkable="true" android:title="Foo1" /> <item android:id="@+id/itemFoo2" android:checkable="true" android:title="Foo2" /> </group> </menu> The designer in Android Studio shows checkboxes:  However, the app does not display checkboxes:  Could anyone offer a clue about this? The layout using the menu: <com.google.android.material.navigation.NavigationView android:id="@+id/navigationView" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="end" app:menu="@menu/activity_foo_view"/>  |
| react child functional class not re-rendering when I select new link from list Posted: 16 Oct 2021 07:55 AM PDT When I try to click on the new link at the new level the Pokemon name will update but not the associate abilities component. Noticed the fetch methods not getting triggered on second link click. Here is the child class import React, { useState, useEffect } from "react"; import { Link, useLocation} from "react-router-dom"; import "./Abilities.scss" let Ability = () => { useEffect(()=> {fetchAbilities().then(r => console.log("got getting ability")) ;},[]) let props = useLocation(); // @ts-ignore let url = props.state.item.url; let [abilities, setAbilities] = useState([]); let fetchAbilities= async () => { let data = await fetch(url); let items = await data.json(); let abilities1 = items.abilities; let denormalized = { "name":"", "abilities": [] } for(let i = 0; i< abilities1.length; i++){ let abilityUrl = abilities1[i].ability.url let response = await fetch(abilityUrl); let promise = await response.json(); denormalized.name = promise.names; // @ts-ignore denormalized.abilities.push(promise) } // @ts-ignore setAbilities(denormalized); } // @ts-ignore let getAbilities =(ability)=> { let a =<div> <div> {ability.name} </div> </div> return a; } // @ts-ignore let getAbiltiesFromPokeom = (poke) => { let abilities = poke.pokemon.abilities; console.log(abilities); let li = <li className="listItems"> {(abilities|| []).map((a : any)=>getAbilities(a))} </li> return li; }; // @ts-ignore let abilityName = <>{abilities.name}</>; // @ts-ignore let effectEntries = <>{abilities.effect_entries}</>; let getAbilitInfo =(a: any)=> { let div = <div>{a.name}</div> //a.abilities[0].effect_changes[0].effect_entries[1] let col = []; let ab = 0; if(a.abilities != undefined ) { if(a.abilities.length>0 ) { for (let i = 0; i < a.abilities.length; i++) { try { let effectEntry = a.abilities[i].effect_entries[0].effect; let name = a.abilities[1].name let items = <div> <div> <p>{name}</p> </div> <div>{effectEntry}</div> </div> col.push(items); } catch (e){ } } } } let div1 = <div> <div> {col} </div> </div>; return div1 } return <div className="abilities"> {getAbilitInfo(abilities)} </div> } export default Ability; Bridge class import React, {Component, useState, useEffect } from "react"; import "./Pokemon.scss" import {BrowserRouter as Router, Link, Route, useLocation, useHistory} from "react-router-dom"; import Ability from "../abilities/Ability"; let Pokemon = () => { useEffect(()=> {fetchItems().then(r => console.log("got pokemon details")) ;},[]) let props = useLocation(); // @ts-ignore let url = props.state.item.url; let [pokemon, setPokemon] = useState([]); let fetchItems = async () => { let data = await fetch(url); let items = await data.json(); setPokemon(items); } // @ts-ignore let getAbilities =(ability)=> { setPokemon(ability) let a = <Link id={ability.name + "-"} to={{pathname :"/component/abilities/Ability", state: {ability}}}> </Link> // <Ability ability = {ability}/> return a; } // @ts-ignore let getAbiltiesFromPokeom = (poke) => { let abilities = poke.pokemon.abilities; console.log(abilities); let li = <li className="listItems"> {(abilities|| []).map((a : any)=>getAbilities(a))} </li> return li; }; // @ts-ignore let p = <>{props.state.item.name}</>; let div = <div > <div id="a" > <div> <p className="poke">{p}</p> </div> <p className="poke"> <ul> {getAbiltiesFromPokeom({pokemon})} <Route path="/components/:repo" component={Ability} /> </ul> </p> </div> </div>; return div }; export default Pokemon; patent class import React, {Component, useState, useEffect} from "react"; import "./LeftHandNav.scss" import {BrowserRouter as Router, Route, Link , useHistory} from "react-router-dom"; import Pokemon from "./pokemon/Pokemon"; import Ability from "./abilities/Ability"; function LeftHandNav() { useEffect(()=> {fetchItems();},[]); // @ts-ignore let url = "https://pokeapi.co/api/v2/pokemon/"; let [items, setItems] = useState([]) let fetchItems= async ()=> { let data = await fetch(url); let items = await data.json(); setItems(items.results); } function getLi(item:any, id:number) { let li = <Link id={item.name + "-" + id} to={{pathname :"/components/pokemon/Pokemon/"+item.name, state: {item}}} > <li className="listItems" key={id}> <div className="listItems"> {item.name} </div> </li> </Link> return li; } let id = 0; let div = <div> <div className="hbox"> <Router> <div id="pokemonNav" > <ul className="listItems"> <div> <p>Pokemon</p> </div> {items.map(item =>getLi(item, ++id))} </ul> </div> <div> <Route path="/components/pokemon/" component={Pokemon} /> </div> </Router>; </div>; </div> return div } export default LeftHandNav; How do I force it to call this again? I added onBlur to asynchonously call the fetch again to update the state, but so far not luck  |
| Confusing error message when passing bytes to print with file pointing to a binary file Posted: 16 Oct 2021 07:57 AM PDT The documentation for the print function specifies that the input argument is coerced to string. However, if bytes are passed and the file= parameter points to a file open for binary write, the error message produced is: >>> out = open('temp', 'wb') >>> print(b'abc', file=out) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: write() argument 1 must be bytes or buffer, not str which is, to say the least, confusing, since I clearly passed print a bytes object as argument 1.  |
| SQL CHECK() how to check if input is numeric value? Posted: 16 Oct 2021 07:55 AM PDT Hey how can I check if the input has 5 numbers? I tried everything like isnumeric/LIKE '%[0-9]%' they all not working... I tried the following but it doesn't work.. please help CREATE TABLE Code ( PIN TEXT NOT NULL, CHECK(LENGTH(title) = 5), CHECK(title LIKE '[0-9][0-9][0-9][0-9][0-9]'));  |
| Post message after hitting download button Posted: 16 Oct 2021 07:55 AM PDT The code below generates a table and it is also possible to download this table just press the Download button. As I have a small database here, it works pretty fast. However, I'm using a much larger database, so I'd like to insert some message after the person presses the button, like: "Wait a few moments while your spreadsheet downloads".This message could have a duration or perhaps appear until the moment of finalizing the download. Could you help me do this? Executable code below: library(shiny) library(shinythemes) library(dplyr) library(writexl) library(tidyverse) library(lubridate) function.test<-function(){ df1 <- structure( list(date1= c("2021-06-28","2021-06-28","2021-06-28"), date2 = c("2021-07-01","2021-07-02","2021-07-04"), Category = c("ABC","ABC","ABC"), Week= c("Wednesday","Wednesday","Wednesday"), DR1 = c(4,1,0), DR01 = c(4,1,0), DR02= c(4,2,0),DR03= c(9,5,0), DR04 = c(5,4,0),DR05 = c(5,4,0),DR06 = c(5,4,0),DR07 = c(5,4,0),DR08 = c(5,4,0)), class = "data.frame", row.names = c(NA, -3L)) return(df1) } return_coef <- function(df1, dmda, CategoryChosse) { x<-df1 %>% select(starts_with("DR0")) x<-cbind(df1, setNames(df1$DR1 - x, paste0(names(x), "_PV"))) PV<-select(x, date2,Week, Category, DR1, ends_with("PV")) med<-PV %>% group_by(Category,Week) %>% summarize(across(ends_with("PV"), median)) SPV<-df1%>% inner_join(med, by = c('Category', 'Week')) %>% mutate(across(matches("^DR0\\d+$"), ~.x + get(paste0(cur_column(), '_PV')), .names = '{col}_{col}_PV')) %>% select(date1:Category, DR01_DR01_PV:last_col()) SPV<-data.frame(SPV) mat1 <- df1 %>% filter(date2 == dmda, Category == CategoryChosse) %>% select(starts_with("DR0")) %>% pivot_longer(cols = everything()) %>% arrange(desc(row_number())) %>% mutate(cs = cumsum(value)) %>% filter(cs == 0) %>% pull(name) (dropnames <- paste0(mat1,"_",mat1, "_PV")) SPV <- SPV %>% filter(date2 == dmda, Category == CategoryChosse) %>% select(-any_of(dropnames)) if(length(grep("DR0", names(SPV))) == 0) { SPV[head(mat1,10)] <- NA_real_ } datas <-SPV %>% filter(date2 == ymd(dmda)) %>% group_by(Category) %>% summarize(across(starts_with("DR0"), sum)) %>% pivot_longer(cols= -Category, names_pattern = "DR0(.+)", values_to = "val") %>% mutate(name = readr::parse_number(name)) colnames(datas)[-1]<-c("Days","Numbers") datas <- datas %>% group_by(Category) %>% slice((as.Date(dmda) - min(as.Date(df1$date1) [ df1$Category == first(Category)])):max(Days)+1) %>% ungroup m<-df1 %>% group_by(Category,Week) %>% summarize(across(starts_with("DR1"), mean)) m<-subset(m, Week == df1$Week[match(ymd(dmda), ymd(df1$date2))] & Category == CategoryChosse)$DR1 if (nrow(datas)<=2){ return (as.numeric(m)) } else if(any(table(datas$Numbers) >= 3) & length(unique(datas$Numbers)) == 1){ yz <- unique(datas$Numbers) return(as.numeric(yz)) } else{ mod <- nls(Numbers ~ b1*Days^2+b2,start = list(b1 = 0,b2 = 0),data = datas, algorithm = "port") return(as.numeric(coef(mod)[2])) } } ui <- fluidPage( shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE, br(), tabPanel("", sidebarLayout( sidebarPanel( uiOutput('daterange'), br() ), mainPanel( dataTableOutput('table'), br(), br(), downloadButton("dl", "Download") ), )) )) server <- function(input, output,session) { data <- reactive(function.test()) data_subset <- reactive({ req(input$daterange1) days <- seq(input$daterange1[1], input$daterange1[2], by = 'day') df1 <- subset(data(), as.Date(date2) %in% days) df2 <- df1 %>% select(date2,Category) Test <- cbind(df2, coef = apply(df2, 1, function(x) {return_coef(df1,x[1],x[2])})) Test }) output$daterange <- renderUI({ dateRangeInput("daterange1", "Period you want to see:", start = min(data()$date2), end = max(data()$date2)) }) output$table <- renderDataTable({ data_subset() }) output$dl <- downloadHandler( filename = function() { "data.xlsx"}, content = function(file) { writexl::write_xlsx(data_subset(), path = file) } ) } shinyApp(ui = ui, server = server)  |
| How do I download the image after making the changes? [duplicate] Posted: 16 Oct 2021 07:56 AM PDT I am working on a photo editor and I want to add a download button that will download the image after the user makes the necessary changes. The changes are working fine but I am not able to figure out how to download the image. Does anyone have any ideas on how I can proceed further (preferably without using a canvas tag)? Here's my HTML: <!-- upload image button --> <p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p> <p><label for="file" style="cursor: pointer;" id="fileBtn">UPLOAD IMAGE</label></p> <p><img id="img"></p> <!-- side nav --> <div class="sidenav"> <label for="filter-select">FILTER AND ADJUST</label> <div class="slider"> <p style="color: aliceblue;">Sepia</p> <input id="sepia" type="range" oninput="setSepia(this);" value="0" step="0.1" min="0" max="1"><span id="Amount" style="color: white;"> 0</span><br/><br> <p style="color: aliceblue;">Grayscale</p> <input id="Grayscale" type="range" oninput="setGs(this);" value="0" step="0.1" min="0" max="1"><span id="Amount2" style="color: white;"> 0</span><br/><br> </div> <label onclick = "RotateImg()">ROTATE</label> <label onclick = "flipping()">FLIP</label> <label onclick = "invert()">INVERT COLOURS</label> <label onclick = "original()">ORIGINAL</label> </div> Here's my JavaScript: function loadFile(event) { var image = document.getElementById('img'); image.src = URL.createObjectURL(event.target.files[0]); } const options = { sepia: 0, grayscale: 0, rotation: 0, scale: 1, invertVal: 0 }; function setSepia(e){ options.sepia = e.value; document.getElementById('Amount').innerHTML= e.value; redraw(); } function setGs(e){ options.grayscale = e.value; document.getElementById('Amount2').innerHTML= e.value; redraw(); } let rotation = 0; function RotateImg(){ rotation += 90; if (rotation == 360) { rotation = 0; } options.rotation = rotation; redraw(); } let scale = 1 function flipping() { scale -= 2 if (scale <= -2) { scale = 1; } options.scale = scale; redraw(); } let invertVal = 0 function invert() { invertVal += 100 if (invertVal > 100) { invertVal = 0 } options.invertVal = invertVal; redraw(); } function original() { document.getElementById("img").style["webkitFilter"] ="sepia(0) grayscale(0)"; document.querySelector("img").style.transform = "rotate(0deg) scaleX(1)"; } function redraw() { document.getElementById("img").style["webkitFilter"] ="sepia(" + options.sepia + ") grayscale(" + options.grayscale + "); document.querySelector("img").style.transform = `rotate(${options.rotation}deg) scaleX(${options.scale})`; }  |
| Mongoose findOne as : Array = [FindOne , FindOne, FindOne ,FindOne, FindOne...] , Using ExpressJs Posted: 16 Oct 2021 07:56 AM PDT I have user login have the special _id, then when doing any activate in the web app, like pass some exam or upload anything will add as database with the iduse what iduse mean ? : for my app any Schema has an iduse with the original _id. that just for knew the user and what you doing in the app web. Okay new I wanna to find all the same iduse with findOne keywork. in mongoose :
var iduser = current.id.user //that mean the _id of user who login var something = await storescors16.findOne({ iduser }) as you know I have more than one iduser. and I wanna to find it with the findOne keyword in mongoose. output as : { _id: new ObjectId("616ad9b3bc8e8dkjfbvoue"), iduser: ' 616ab2006cb743bc31bf2590', level: '3', day: 'some', date: '2021-10-13', time: '7 : 30', objectif: 'something ', __v: 0 } { _id: new ObjectId("616ad9b3b52942942484bvoueq49"), iduser: ' 616ab2006cb743bc31bf2590', level: '3', day: 'some', date: '2021-10-13', time: '7 : 30', objectif: 'something ', __v: 0 } { _id: new ObjectId("616ad9b3hbdfiw5169333333jfbvoueq9c"), iduser: ' 616ab2006cb743bc31bf2590', level: '3', day: 'some', date: '2021-10-13', time: '7 : 30', objectif: 'something ', __v: 0 } { _id: new ObjectId("611111111111doufbwoeurgbu6"), iduser: ' 616ab2006cb743bc31bf2590', level: '3', day: 'some', date: '2021-10-13', time: '7 : 30', objectif: 'something ', __v: 0 } NodeJs for get data router.get('/result', auth, async(req, res) => { var ids = req.session.user._id var points = await model.findOne({ ids }) res.render('./options/result', { notes: ponts, }) }); And for display it use ejs : <% for (var i = 0; i < notes.length; i++) { %> <div class="child"> <div class="itms sld1"> <%=notes.objectif%> </div> <div class="itms sld"> <%=notes.time%> </div> <div class="itms sld"> <span> <%=notes[i].date%> </span> </div> <div class="itms sld"> <%=notes[i].day%> </div> <div class="itms sld"> <%=notes[i].level%> </div> </div> <% } %>  |
| Display images with matplotlib Posted: 16 Oct 2021 07:57 AM PDT I wanna display in a list of lists the images inside it using matplotlib. So for example I wanna have in the first row, the images of the first list, the second row, the images of the second list and so on. I tried this, but I obtain the images in each row, maybe because it will call over and over again subplot. How can I fix it? list_plot = [['query/obj100__40.png', 'model/obj100__0.png', 'model/obj19__0.png', 'model/obj23__0.png', 'model/obj33__0.png', 'model/obj69__0.png'], ['query/obj12__40.png', 'model/obj12__0.png', 'model/obj80__0.png', 'model/obj53__0.png', 'model/obj51__0.png', 'model/obj41__0.png'], ['query/obj17__40.png', 'model/obj17__0.png', 'model/obj15__0.png', 'model/obj91__0.png', 'model/obj3__0.png', 'model/obj84__0.png']] index_plot=0 for query in list_plot: for qm_images in query: plt.subplot(3,5,index_plot+1) plt.imshow(np.array(Image.open(qm_images))) plt.show() index_plot += 1   |
| How can I "iterate" over a query in a view? Posted: 16 Oct 2021 07:55 AM PDT I have the the following SQL query. SELECT us.foo, us.user_id_2, ( SELECT COUNT(*) FROM my_table x WHERE x.foo >= us.foo AND x.user_id_2 = 53 ) AS position FROM my_table us WHERE us.user_id_1 = 53 ORDER BY position; This gives me results like this: | foo | user_id_2 | position | | 42 | 687 | 0 | | 40 | 9832 | 1 | | 39 | 12 | 2 | | ... | ... | ... | This can be interprted as follows: User 687 is the first match for user 53 with score 42. User 9832 is the second match with score 49 and so on. My problem is that the user is 53 is hardcoded in the query. I need the results for every user in the users table. To be more precisely, I want something like this: | foo | user_id_1 | user_id_2 | position | | 42 | 53 | 687 | 0 | | 40 | 53 | 9832 | 1 | | 39 | 53 | 12 | 2 | | ... | ... | ... | ... | | 193 | 12 | 53 | 0 | | 175 | 12 | 9832 | 1 | | ... | ... | ... | ... | What I basically want is iterating over SELECT id FROM users use that id instead my hardcoded 53 from my query. Ordering does not matter here. I'm using MariadDb 10.3. How can I do this? The structure of my_table is: | user_id_1 | user_id_2 | foo | | 53 | 687 | 42 | | 687 | 53 | 42 | | 53 | 9832 | 40 | | 9832 | 53 | 40 | | 53 | 9832 | 39 | | 9832 | 53 | 39 | | ... | ... | ... |  |
| Swiper.js Carousel How to control multiple carousel with middle mouse at the same time Posted: 16 Oct 2021 07:56 AM PDT I have 5 carousel on the screen they all are controlled by same navigation buttons.I also need to control them with middle mouse scroll. When i activate mouse wheel control only the carousel which mouse is on top is moving when scrolled. I need to move them all.  |
| Checking MQTT Clients id Connections Posted: 16 Oct 2021 07:58 AM PDT Is there a way to find out the ids of the MQTT clients connecting to the server? If so, how can I do that? this is my client-side: def on_message(mosq, obj, msg): data = msg.payload.decode('utf-8') with open('/var/www/html/data1.json', 'w') as fd: fd.write(data) print("dosya kaydedildi") def on_connect(client, userdata, flags, rc): global connected_flag if rc==0: connected_flag=True #set flag print("connected OK") client.subscribe("photo",0) #subscribe print("subscribed OK") else: print("Bad connection Returned code=",rc) broker="10.10.10.25" client = mqtt.Client() #create new instance print("Connecting to broker ",broker) client.on_connect = on_connect client.on_message = on_message client.on_disconnect = on_disconnect this is my server-side: mqtt.Client.connected_flag = False counter = 0 def on_publish(mosq,userdata,mid): mosq.disconnect() while True: try: counter+=1 client = mqtt.Mosquitto("image-send") client.on_publish = on_publish client.connect("10.10.10.25") f = open('sample.json') imagestring = f.read() client.publish("photo",payload,1) print("Dosyalar Gönderiliyor") client.loop_forever() time.sleep(0.5) if counter==0: print("Tekrar Bağlantı kuruldu") except: print("Baglantı Kesildi") while True: print("Lütfen baglantınızı kontrol ediniz") time.sleep(0.8) break My system includes 4 clients and 1 server, server sends to clients some data, and clients send to server raspberry pis info like CPU temp, pi current vb. The server will save this information to the database according to the client ids. Is it possible?  |
| How to track who invited a bot with discord.js? Posted: 16 Oct 2021 07:58 AM PDT How to track who invited a Discord bot in a guild, using discord.js? I want to create an anti-bot event and take action against the inviter.  |
| 'Firebase Not Defined' An Answer For Version 9 Of Firebase Posted: 16 Oct 2021 07:56 AM PDT Im trying to make a database call/post but im getting the error functions.js:7 Uncaught ReferenceError: firebase is not defined From my research it is my understanding that 'firebase' is defined in the firebase.js script file that is imported using the CDN code from the setting panel in Firebase.. But all the help pages i find are from 2014-2017 and version 9 of Firebase uses a completely different import language.. These pages are no help to me.. I am using the standard import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"; Am I right in thinking that because this import is happening (and its seemingly is - firebase-app.js is showing up in the inspector) That firebase should be defined... Or is firebase defined somewhere else and im missing something?? If this is the case where is firebase defined and how do i import it (with V9 Firebase) Thanks Edit: Im doing this all through a tutorial I found on Youtube, its from 2019.. Is it possible that calling upon 'firebase' now is outmoded and that is what I am having these troubles? Or should i expect it to work and keep trying to find a solution?  |
| Adding a Loading Screen for AppComponent ngoninit Posted: 16 Oct 2021 07:57 AM PDT I have some authentication and other startup services being called on ngoninit for app.component.ts so that the screen remains black before moving to the homepage. I created a loader service that will display a loading page while its active, however I am still seeing the black screen. As it stands I always see false for showLoader on the loader component app.component.ts ngOnInit(){ this.loaderService.showLoader; //startupservice calls and auth calls this.loaderService.hideLoader; } loader.service loaderSubject = new Subject<any>(); constructor(){ } showLoader(){ this.loaderSubject.next(true); } hideLoader(){ this.loaderSubject.next(false); } loader.component showLoader = false; constructor(private loaderService : LoaderService) { } ngOnInit(): void { this.loaderService.loaderSubject.subscribe((value) => this.showLoader = value); }  |
| How to divide a string into several strings in C++? Posted: 16 Oct 2021 07:55 AM PDT First, I'll explain, what I want to archive: assuming the following string, 25a0: ebfffa01 bl dac <abort@plt> (notice there are whitespaces before the first character), then my target is to get the following output: 25a0: ebfffa01 bl dac <abort@plt> The problem is that the string can be divided by several (consecutive) whitespaces, therefore my current solution does not work correctly: vector<vector<string>> getStructuredContent(vector<string> content) { vector<vector<string>> structuredContent; for(string line: content) { char space_char = ' '; vector<string> words{}; stringstream sstream(line); string word; while (getline(sstream, word, space_char)){ if(word != "") words.push_back(word); } structuredContent.push_back(words); } return structuredContent; } The output for the string above is currently: 25a0: ebfffa01 bl dac <abort@plt> Maybe someone has an idea how to fix this?  |
| why "urllib request error " is not working Posted: 16 Oct 2021 07:57 AM PDT import urllib.request, urllib.parse, urllib.error fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt') for line in fhand: print(line.decode().strip()) traceback (most recent call last): SyntaxError: invalid character '→' (U+2192)  |
| PHP Page appears to be caching for some users but not for others? Posted: 16 Oct 2021 07:56 AM PDT I have a strange situation and I'm hoping someone might have experienced this before and know what possible scenarios might cause this to occur. I have a PHP website which accesses data from an SQL database. Users fill out a form to add or edit data which is POSTED and the data is written to the database. If the user is editing existing data, the php loads the data needed for the form, and I use JavaScript to fill the data into the appropriate fields once the page has loaded. All of this works correctly for me on all the machines I've tested, and most users. HOWEVER... SOME users are reporting that they are not seeing the correct data in their forms, but rather outdated information. Thus, when these users "edit" a form, rather than seeing the information that is currently contained within the database, they see old information. My understanding is that (normally) php files aren't cached since they are executed on the server and then the final product is being handed to the user. Is there any situations which might cause a certain user to somehow cache these "assembled" files once they are received from the server and then reloaded the next time the page loads? Example: Today a client was trying to edit the information using the form. They called me because a field was showing something incorrect. I logged into my site and loaded the same form. My form was showing the correct data (as contained within the SQL database), while theirs was showing different data. Two different users looking at the same php webpage, and same form, using the same browser (chrome), which should be displaying the same data, but is not. I'm baffled as to how to trace this issue and fix it. UPDATE: After playing around a bit, I suspect that it may be an issue of the client's browser or internet being a bit slower than most, which might be causing the Javascript to execute before the page is fully loaded. I changed it to execute the javascript onload using jQuery which might fix the issue until I can recode a more elegant solution, but have not yet heard back from this particular client so don't know if that fixed the issue for them quite yet...but it certainly won't hurt.  |
| How to Fillet (round) Interior Angles of SF line intersections Posted: 16 Oct 2021 07:56 AM PDT I am working with OSM data to create vector street maps. For the roads, I use line geometry provided by OSM and add a buffer to convert the line to geometry that looks like a road. My question is related to geometry, not OSM, so I will use basic lines for simplicity. library(dplyr) library(ggplot2) library(sf) # two lines representing an intersection of roads l1 <- st_as_sfc(c("LINESTRING(0 0,0 5)","LINESTRING(-5 3,5 3)")) # union the two lines (so they "intersect" instead of overlap once buffered l2 <- l1 %>% st_union() ggplot()+ geom_sf(data = st_buffer(l2, dist = 0.75)) This will yield something like this:  Ultimately, I am trying to render roads similarly to map APIs like Google, OSM, Bing, etc. These fillet (round) the inner angles like this:  I've searched through the st_ series methods in the sf package but haven't found a solution. The closest I have found is some arguments for st_buffer that control the shape of endcaps and the number of angles used for outer angles (but not the inner angles). Is there a simple/practical solution for this, or am I better off getting used to un-rounded intersections? Thanks  |
| Oriented projectiles keep facing camera Posted: 16 Oct 2021 07:56 AM PDT I'm trying to render a 2d image that represent a projectile in a 3d world and i have difficulty to make the projectile face the camera without changing its direction. Im using JOML math library.  my working code to orient the projectile in his direction public Quaternionf findRotation(Vector3f objectRay, Vector3f targetRay) { Vector3f oppositeVector = new Vector3f(-objectRay.x, -objectRay.y, -objectRay.z); // cas vecteur opposé if(oppositeVector.x == targetRay.x && oppositeVector.y == targetRay.y && oppositeVector.z == targetRay.z) { AxisAngle4f axis = new AxisAngle4f((float) Math.toRadians(180), 0, 0, 1); Quaternionf result = new Quaternionf(axis); return result; } objectRay = objectRay.normalize(); targetRay = targetRay.normalize(); double angleDif = Math.acos(new Vector3f(targetRay).dot(objectRay)); if (angleDif!=0) { Vector3f orthoRay = new Vector3f(objectRay).cross(targetRay); orthoRay = orthoRay.normalize(); AxisAngle4f deltaQ = new AxisAngle4f((float) angleDif, orthoRay.x, orthoRay.y, orthoRay.z); Quaternionf result = new Quaternionf(deltaQ); return result.normalize(); } return new Quaternionf(); } Now i want to add a vector3f cameraPosition parameter to rotate the projectile only on its x axis to face the camera but i dont know how to do it. For example with this code the projectile correctly rotate around his x axis but not face the camera so i want to know how to find the correct angle. this.lasers[i].getModel().rotate((float) Math.toRadians(5), 1, 0, 0); I tried this to rotate around axis X with transforming vector before compute angle. this.lasers[i] = new VisualEffect(this.position, new Vector3f(1,1,1), color, new Vector2f(0,0.33f)); this.lasers[i].setModel(new Matrix4f().scale(this.lasers[i].getScale())); this.lasers[i].getModel().rotate(rotation); this.lasers[i].getModel().translateLocal(this.lasers[i].getPosition()); Vector3f vec = new Vector3f(cameraPosition).sub(this.position); Vector4f vecSpaceModel = this.lasers[i].getModel().transform(new Vector4f(vec, 1.0f)); Vector4f normalSpaceModel = this.lasers[i].getModel().transform(new Vector4f(normal, 1.0f)); float angleX = new Vector2f(vecSpaceModel.y, vecSpaceModel.z).angle(new Vector2f(normalSpaceModel.y, normalSpaceModel.z)); this.lasers[i].getModel().rotate(angleX, 1, 0, 0);   |
| Gzip compression is not working in docker on Elastic Beanstalk? Posted: 16 Oct 2021 07:58 AM PDT I have an instance with docker platform(nodejs image) on AWS Elastic Beanstalk And i have tried to use gzip compression for my application but it's not working i don't know why I used the compression package for middleware in my application like app.use(compression()) And i also checked nginx config in the instance that gzip is enabled Sorry for my english i'm not good at it  |
| how to write to a new cell in python using openpyxl Posted: 16 Oct 2021 07:56 AM PDT I wrote code which opens an excel file and iterates through each row and passes the value to another function. import openpyxl wb = load_workbook(filename='C:\Users\xxxxx') for ws in wb.worksheets: for row in ws.rows: print row x1=ucr(row[0].value) row[1].value=x1 # i am having error at this point I am getting the following error when I tried to run the file. TypeError: IndexError: tuple index out of range Can I write the returned value x1 to the row[1] column. Is it possible to write to excel (i.e using row[1]) instead of accessing single cells like ws.['c1']=x1  |
| How to loop over posts in Hexo with native Jade construction Posted: 16 Oct 2021 07:57 AM PDT I know, that I can use something like this: - site.posts.each(function(article){ h2.title= article.title p.article= arcticle.content - }) I feel this way wrong, because Jade has its own native construction for looping over something, but it seems not working: each article in site.posts h2.title= article.title p.article= arcticle.content  |
| What does 'Language Construct' mean? Posted: 16 Oct 2021 07:58 AM PDT I am learning C from 'Programming in C' by Stephen Kochan. Though the author is careful from the beginning only not to confuse the students with jargon, but occasionally he has used few terms without explaining their meaning. I have figured out the meaning of many such terms with the help of internet. However, I could not understand the exactly meaning of the phrase 'language construct', and unfortunately the web doesn't provide a good explanation. Considering I am a beginner, what does 'language construct' mean?  |
| How to check if a model has a certain column/attribute? Posted: 16 Oct 2021 07:57 AM PDT I have a method that needs to loop through a hash and check if each key exists in a models table, otherwise it will delete the key/value. for example number_hash = { :one => "one", :two => "two" } and the Number table only has a :one column so :two will be deleted. How do I check if a model has an attribute or not?  |
No comments:
Post a Comment