Capturing data from Data Layer Variable object Posted: 29 Mar 2021 07:59 AM PDT |
Passing Puppeteer log result into contenteditable field (non-input)? Posted: 29 Mar 2021 07:59 AM PDT It took a while to find out how to pass value into form input using this code: await page.$eval('input[name=wc_name]', (el, name) => { el.value = name; }, result.name); But my question is, how do I pass the value into non-input (contenteditable)? I know how to do it with manual text: await page.type("[class='ql-editor ql-blank']", 'mymanualpricesethere'); I'm trying to pass result.price I have tried: await page.type("[class='ql-editor ql-blank']", (el, price) => { el.value = price; }, result.price); But it doesn't pass (I see blank) Need some help. |
Decode back from base64 to get the name of the file Posted: 29 Mar 2021 07:59 AM PDT The issue that I'm having is I need to have access to the name of the image that I am displaying. I'm using spring-boot for my backend, here is how I am getting my images: public List<String> readImages() throws IOException { return Files.list(Paths.get(context.getRealPath("/images"))) .filter(Files::isRegularFile) .map(this::encode) .filter(Objects::nonNull) .collect(Collectors.toList()); } private String encode(Path file) { try { String extension = FilenameUtils.getExtension(file.getFileName().toString()); String encodeBase64 = Base64.getEncoder().encodeToString(Files.readAllBytes(file)); return "data:image/"+extension+";base64,"+encodeBase64; } catch (Exception e) { return null; } } My .HTML <div class="col-6" *ngFor='let image of images'> <img [src]="image" class="img-thumbnail"> </div> How do I get name of the image that is being sent? Also, how do I display a particular image instead of... all of them? Any help is greatly appreciated |
How to convert an iterator-like that has a `next()` methode to a regular `begin`/`end` iterator pair? Posted: 29 Mar 2021 07:59 AM PDT In the codebase I inherited, there is a class that look like an iterator (this isn't the exact code, but the logic is similar). template <class T> class IteratorLike { T* next() &; // either return a pointer to a valid value or nullptr }; The way you use it is very similar to the way you use Rust iterators: IteratorLike<...> it = ...; while(auto* item = it.next()) { do_something(*item); } How do I convert it to make it compatible with C++ range-based for loop, algorithms, or range-v3? I'm using C++14 (gcc5.5 to be more precise), so I can't have a sentinel type that is different from the type of the iterator itself. So far it seems that the easiest way is to store both the iterator and the next value in my wrapper: template <class T> class MyIterator { { private: IteratorLike<T> m_iter; T* m_value; public: using value_type = T; using difference_type = std::ptrdiff_t using pointer = T*; using reference = T&; using iterator_category = std::input_iterator_tag; reference operator*() const { assert(m_value && "trying to read past the end of the iterator"); return *m_value; } pointer operator->() { // I'm not sure the assert is needed here assert(m_value && "trying to read past the end of the iterator"); return m_value; } // Prefix increment Iterator& operator++() { m_value = m_iter.next(); return *this; } // Postfix increment Iterator operator++(int) { Iterator tmp = *this; ++(*this); return tmp; } // used by `my_collection.begin()` explicit MyIterator(IteratorLike<T> iter) : m_iter{m_iter} , m_value{this->self.next()} {} // missing operator == and operator != as well as the constructor // used `my_collection.end() } However, I fail to understand what my_collection.end() should return, nor how to have meaningful comparison operators. Note: I'm basically trying to do the exact reverse of this. |
Equivalent curl -F in PowerShell Invoke-webrequest Posted: 29 Mar 2021 07:59 AM PDT I'm trying to find the equivalent of this curl command in PowerShell with Invoke-webrequest : curl -k https://url/api \ -H "Authorization: mykey" \ -F "json=@test.json;type=application/json" \ -F "file=@test.txt; type=application/octet-stream"``` -H is ok, but I didn't find for two -F option. Any idea ? Many thanks. |
MSSql in a docker container on Mac: cannot connect to database Posted: 29 Mar 2021 07:59 AM PDT I've inherited a docker-ized database project - it successfully starts up a sql-server database (confirmed by the sql container's logs). I also need to be able to connect to that database, from other tools I'm running on my machine - for example DBeaver (or other db GUI). Each time I try to connect, I see this error message: The TCP/IP connection to the host host.docker.internal, port 1450 has failed. Error: "host.docker.internal. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.". I get the same error when trying to connect using the IP address of docker's bridge network. I've confirmed that the sql container is forwarding it's internal port 1433 to 1450 (0.0.0.0:1450->1433/tcp ). There are also no error logs in the sql docker container to help me out. I've also tried connecting using localhost & 0.0.0.0 as the host. Those throw a login failed error, which is going in the wrong direction. I am running docker for mac v20.10.5 on osx v10.15.7. I'm not sure where the problem is - docker settings? Mac settings? SQL-server configuration? Something else? |
React Location returns undefined Posted: 29 Mar 2021 07:59 AM PDT I'm trying to get the user location for a weather app but the log return undefined const [lat, setLat] = useState(); const [long, setLong] = useState(); useEffect(() => { const handleLocation = () => { navigator.geolocation.getCurrentPosition((position) => { setLat(position.coords.latitude); setLong(position.coords.longitude); }); console.log(lat); console.log(long); }; if (navigator.geolocation) { navigator.permissions.query({ name: 'geolocation' }).then(function (result) { if (result.state === 'granted') { console.log(result.state); handleLocation(); } else if (result.state === 'prompt') { console.log('prompt'); } else if (result.state === 'denied') { console.log('Denied'); } }); } }, [lat, long]); I get the log granted confirming that the browser granted the location but then I get undefined for the lat and long |
how do i make my X button delete the specific object inside array? Posted: 29 Mar 2021 07:59 AM PDT first time that I'm posting here I'm very new to web development and I'm currently trying to make my X button to delete the specific object inside an array it goes like this- the user can make 3 yellow notes-the user add inside inputs the values and then it stored as object and displayTasks() refreshes the the notes-inside displayTasks()-when the user press X it triggers the onclick() that needs to remove this certain object but instead it always removes the last note and object in the array how do I make it choose the exact object that inside a div? I hope I'm clear on this! thanks is advance! function deleteTask(index) { tasks.splice(index, 1); displayTasks(); } let escape = document.createElement("p"); escape.setAttribute("class", "escape glyphicon glyphicon-remove"); escape.innerHTML = `X`; escape.onclick = function callback() { deleteTask(task); console.log(task); // escape.onclick = function() { // deleteTask(task); // } } class Task{ constructor(mytask,mydate,mytime){ this.task=mytask; this.date=mydate; this.time=mytime; } } const myTask = document.getElementById("task") const date = document.getElementById("date") const time = document.getElementById("time") const save = document.getElementById("save") const reset = document.getElementById("reset") const paragraph = document.getElementById("mypara") const taskRow = document.getElementById("taskRow") const tasks = [] function addTask() { // 1. add new note to tasks array // 2. call displayNotes() if (tasks.length > 2) { return alert("Too Many Notes please Complete One"); } tasks.push(new Task(myTask.value, date.value, time.value)); resetTask(); displayTasks(); } function resetTask() { myTask.value = ''; date.value = ''; time.value = ''; } function deleteTask(index) { tasks.splice(index, 1); displayTasks(); } function displayTasks() { // 1. delete all inner html in tasks row // 2. for each element in tasks array: add a task html to the tasks row taskRow.innerHTML = ""; for (task in tasks) { console.log(tasks) let taskDiv = document.createElement("div"); taskDiv.setAttribute("class", "col-sm task"); let description = document.createElement("p"); description.setAttribute("class", "description"); description.innerHTML = `${tasks[task].task}<br>` let finishDate = document.createElement("div"); finishDate.setAttribute("class", "date"); finishDate.innerHTML = `${tasks[task].date}`; let escape = document.createElement("p"); escape.setAttribute("class", "escape glyphicon glyphicon-remove"); escape.innerHTML = `X`; escape.onclick = function callback() { deleteTask(task); console.log(task); // escape.onclick = function() { // deleteTask(task); // } } taskDiv.appendChild(escape) taskDiv.appendChild(description); taskDiv.appendChild(finishDate); taskRow.appendChild(taskDiv); } } body { background-image: url("/jpglibrary/tile.gif"); position: absolute; left: 450px; } .notes{ position: absolute; } /* .task_input{ overflow-y: auto; } */ .notesInput{ position: relative; padding: 10px; margin: 10px; background-image: url("jpglibrary/formbg.jpg"); } .savebutton{ position: absolute; left: 500px; bottom: 30px; } .resetbutton{ position: absolute; left: 500px; bottom: 0px; } h1{ font-family: 'cuteFont'; text-align: center; margin-top: 30px; font-size: 8ch; } .innertext{ height: 188px; width: 170px; position: absolute; top: 408px; } .date{ position: absolute; padding: 4px; bottom: 7px; height: 28px; width: 100px; font-size: 13px; } .task{ background-image: url("/jpglibrary/notebg.png"); background-repeat: no-repeat; height: 240px; width: 100px; padding: 0px; animation: fadeIn ease 2s; } .description{ position:absolute; top: 40px; padding: 3px; width: 175px; height: 170px ; overflow-y: auto; } .escape{ padding-left: 160px; padding-top: 20px; } @font-face{ font-family: cuteFont; src: url("fonts/CuteNotes.ttf"); } @keyframes fadeIn { 0% { opacity: 0; } 100% { opacity: 1; } } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body id="main_body"> <div class='container'> <h1>My Task Board</h1> <!-- <div class="notes"> <img src="jpglibrary/formbg.jpg" class="mx-auto d-block"> <img src="jpglibrary/formbg.jpg" class="mx-auto d-block"> <img src="jpglibrary/formbg.jpg" class="mx-auto d-block"> </div> --> <div class=notesInput> <input type="text" placeholder="My task" id="task" class="task_input"> <br> <div> <label>Finish Date <br> <input type="date" id="date"> </label> </div> <div> <label>Finish Time<br> <input type="time" id="time"> </div></label> <div class="savebutton"> <input type="button" value="Save" onclick=addTask() id="save"> </div> <div class="resetbutton"> <input type="button" onclick="resetTask()" value="Reset" id="reset"> </div> </div> <div id="tasksContainer" class="container"> <div id="taskRow" class="row"> </div> </div> </div> </body> <script src="Task.js"></script> <script src="script.js"></script> </html> those are the notes |
java Swing gui color crash Posted: 29 Mar 2021 07:59 AM PDT my swing gui looks before is much more nice and beautiful. However, after some testing and experimenting with the code. It turn out disastrous, the gui turn hair wire. Can someone help me with this or guide enter image description here |
Virtual scroll for Angular material table columns Posted: 29 Mar 2021 07:59 AM PDT I have a material table with around 1000 columns and I want to virtualize these columns, there are a lot of examples that show virtualization of rows using cdk-virtual-scroll but not for columns. Is there a way to do the virtualizations to columns. |
How can I run a search list using Youtube API v3? Posted: 29 Mar 2021 07:59 AM PDT I'm trying to run a search list using Youtube API v3. I've run the quickstart.js in order to configure my OAuth2 as described here and apparently everything worked saying This channel's ID is UC_x5XG1OV2P6uZZ5FSM91Ttw. Its title is 'Google Developers', and it has 181445346 views. Typescript code: import express, { Request, Response } from 'express'; import { google, // The top level object used to access services Auth, // Namespace for auth related types } from 'googleapis'; const auth: Auth.GoogleAuth = new google.auth.GoogleAuth(); const youtube = google.youtube({ version: 'v3', auth, }); const app = express(); app.get('/', (req: Request, res: Response) => { youtube.search.list({ part: ['id, snippet'], maxResults: 10, q: 'my query search' }) .then( results => { res.send(results); }) .catch( err => { res.send(err); }) }); const port = process.env.PORT || 3300; app.listen(port, () => console.log(`app is listening on PORT: ${port}`)) but I get the following error: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information. at GoogleAuth.getApplicationDefaultAsync (/Users/username/dev/my-project/node_modules/google-auth-library/build/src/auth/googleauth.js:173:19) at processTicksAndRejections (internal/process/task_queues.js:93:5) at async GoogleAuth.getClient (/Users/suername/dev/my-project/node_modules/google-auth-library/build/src/auth/googleauth.js:545:17) at async GoogleAuth.request (/Users/username/dev/my-project/node_modules/google-auth-library/build/src/auth/googleauth.js:598:24) |
async fetch & decode of .wav file works on desktop, but not on mobile (WebAudioAPI) Posted: 29 Mar 2021 07:59 AM PDT scratching my head a bit at this one. i'm currently working on a web-based synthesizer program, using WebAudioAPI. it works quite well on desktop, but on mobile it seems to fail on loading & decoding the impulse response from a wav file. the impulse response is used in conjunction with a convolver node, to implement a convolution reverb. oddly enough, everything else works fine on mobile - oscillators, waveshapers, gain nodes, etc, and the application itself does not stop running (as it would if there were an unhandled exception). it's almost as if the file itself is not being decoded or loaded into the convolver node properly - when i send my sources to the node, on mobile, it outputs only silence. here is the code i have for performing these tasks: //calculate reverb impulse response & assign to convolver node buffer calcIR(); async function calcIR() { let wavFile = await fetch("./wavData/ir4.wav"); let wavBuffer = await wavFile.arrayBuffer(); voice1.reverb.buffer = await synthCtx.decodeAudioData(wavBuffer); } in this case, buffer is the property of the convolver node which holds the decoded impulse response data, & synthCtx is my web audio context; ir4.wav is the actual impulse response. the async function call follows the synchronous instantiation of voice1, to make sure that the nodes are actually initialized before trying to change one of their properties. i have not stopped playing around & troubleshooting, and i have a few more things i will probably try, but i figured i'd consult SE just to see if anyone here has an idea :] also, just to clarify, i have indeed tested it on mobile, and am calling the resume() function on the context from a touchEnd event, so i know the issue isn't the context being muted. as above, everything works on mobile & sounds great - save for silence from the convolver node. any help is appreciated! ramona |
Date/ time function Posted: 29 Mar 2021 07:59 AM PDT I have a "phone payment" form that have four (4) columns - Phone_Number
- user_name
- invoice_date
- invoice_amount
- exceeding_amount
what I want to accomplish is having the invoice_date set to the 24th of the new month when a new record is entered for each user. so for example - January records should show Phone_number User_name invoice_date invoice_amount 123456 test 24/1/2021 100 678901 testing 24/1/2012 200 and February records should show Phone_number User_name invoice_date invoice_amount 123456 test 24/2/2021 200 678901 testing 24/2/2012 300 and so on for the rest of the months |
How to fit data to a polynomial using arbitrary precision package mpmath? Posted: 29 Mar 2021 07:59 AM PDT I am using the python's arbitrary precision package mpmath . At some point, I need to fit data into a power series. I could not find in mpmath a similar function as the numpy polyfit . Then, I ended up reducing the precision to float to find the power series coefficients using numpy polyfit , as illustrated in the excerpt of the code below. for i in range(0,len(dt)): Eeq_b[i]=Es[i]*(1-nup[i])/((1+nup[i])*(1-2*nup[i])) # Young's modulus for plane strain Geq[i]=Es[i]/(2*(1+nup[i])) # shear modulus Eeq_bnp[i]=float(Eeq_b[i]) Geqnp[i]=float(Geq[i]) # power series coefficients for Eeq_b and Geq porder=12; pfitEeq_b=np.polyfit(dtnp,Eeq_bnp,porder) As I am experiencing some convergencies issues, it seems higher precision to the coefficients of the polynomial would be required. mpmath has functions such as chebyfit , which aims at approximating a polynomial to a function (not data points) in a defined internal. Does anyone know how to fit data point to a polynomial using mpmath? |
how do you not print if x is the same? Posted: 29 Mar 2021 07:59 AM PDT I'm kind of a newbie in python. I want to create a program that when you copy something to your clipboard, It 'prints' it on the 'app'. It works, but the issue is that every two seconds it displays what you may have copied 2 hours ago. I want it to be that when the clipboard is the same, it only shows one time and then it waits until you have copied something else. This is what i have so far import pyperclip from tkinter import * r = Tk() def aper(): global x x = pyperclip.waitForPaste() Label(r, text = x).pack() r.after(2000, aper) r.after(2000, aper) r.mainloop() Thank you! |
How to show a video in browser from a URL in Flask? Posted: 29 Mar 2021 07:59 AM PDT I am creating a web application using flask. I am able to upload the video from my local system and can show the uploaded video in the browser as well. But the next thing I want to do is to upload a video from the URL and show that video in the browser. Below is what I have tried: `<div class="container"> <form> <label for="homepage">Add your URL:</label> <input type="url" id="url_input" name="url_input" value="" placeholder="Enter URL here"><br><br> <iframe id="video_here1" src="" style="display: none" width="420" height="345" ></iframe><br><br> <input type="submit"> </form> <script type="text/javascript"> document.getElementById('url_input').onchange = function(){ var video = document.getElementById('video_here1'); video.style.display = 'block' video.src = document.getElementById('url_input').value; } </script> </div>` I am not able to show the video from the URL. Please see the attached screenshot for your reference. Can anyone help me to figure out how to upload and show a video from the URL in Flask? Thanks in advance. |
What is the difference between mvn pre-clean / clean / post-clean? Posted: 29 Mar 2021 07:59 AM PDT what is the difference between these 3 commands: mvn pre-clean / clean / post-clean? Pre and post are unusual to be used. We go straight forward with mvn clean but why? |
Completly break out of post request while being in forEach() function Posted: 29 Mar 2021 07:59 AM PDT The code below is an extract of a try catch block of a node.js backend. I want to break out of the complete post request if an item of the req.body is missing. I think right now the return res only breaks out of the forEach() function which results in the [ERR_HTTP_HEADERS_SENT] error because it's sending another response later on. Object.values(req.body).forEach(value=>{ if (!value) { return res .json({ message: "You are missing personal information.", success: false }) .status(500); } }); // stop this code from running function generateUser(name) { const {doc, key} = new Document(KeyType.Ed25519) return { doc, key, name, } } ... |
Pandas: How to plot multiple dataframes with same index on the same plot using plotly? Posted: 29 Mar 2021 07:59 AM PDT I have a few dataframes that is each dedicated to 1 single city. The date column is the index. They all share the same date index. The only column is the sales of a particular in that city on that day, with column name being the city name. They look like these: +------------+--------+ | date | City_A | +------------+--------+ | 2020-01-01 | ... | +------------+--------+ | 2020-01-02 | ... | +------------+--------+ | ... | | +------------+--------+ | 2020-12-30 | ... | +------------+--------+ | 2020-12-31 | ... | +------------+--------+ +------------+--------+ | date | City_B | +------------+--------+ | 2020-01-01 | ... | +------------+--------+ | 2020-01-02 | ... | +------------+--------+ | ... | | +------------+--------+ | 2020-12-30 | ... | +------------+--------+ | 2020-12-31 | ... | +------------+--------+ +------------+--------+ | date | city_C | +------------+--------+ | 2020-01-01 | ... | +------------+--------+ | 2020-01-02 | ... | +------------+--------+ | ... | | +------------+--------+ | 2020-12-30 | ... | +------------+--------+ | 2020-12-31 | ... | +------------+--------+ I would like to plot all cities daily sales in 2020 in one single line chart, with x axis being the date, and y axis being the daily sales. Each city has its own line with unique color, in Plotly. Usually if I only have a few cities (for example, 3 cities), I would just merge the 3 dataframes together and plot it. However, the real data I have contains 30+ cities, so I am wondering if it makes sense at all to merge all those 30+ cities' separate dataframes before plotting it? Is there a quick and elegant way to plot those together without having to merge the 30+ dataframes first? Much appreciation for your help! |
prepend an created element at a specific place Posted: 29 Mar 2021 07:59 AM PDT I'm pretty new to coding (januari,2021) and with a lot of online searching I'm able to get pretty far but at this point I'm pretty stuck. setTimeout(function(){ var supbtn = document.createElement("BUTTON"); supbtn.innerHTML = "Support"; supbtn.className = "Support-logout-class"; supbtn.onclick = function(){window.open("LinkToSite","_blank")}; document.body.appendChild(supbtn); }, 2000); There is a default wordpress plugin that the company that I work for uses, and as we are in the proces of building a custom site for this use case we want to try and upgrade the current. (With a lot of succes so far) Basically there is a default code and I want to add the above stated "button" element at a specific place, currently it's adding inside the "body" and that works perfect! The code where I want to place it: <div class="wpws-webinar-summary-content sc-iBEsjs sJWcq"> <div class="sc-fZwumE cyVGPD"></div> <div class="wpws-webinar-summary-logout sc-gmeYpB fOXvtE"> <svg class="wpws-33" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation" title="Verlaat het webinar"><path fill="none" d="M0 0h24v24H0z"></path> <path d="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"></path> </svg> </div> </div> I want the generated button to appear before: class="wpws-webinar-summary-logout" (why before?, because if I'm right the code "" isn't set, as in it can change between pages. And I know for sure "wpws-webinar-summary-logout" isn't going to change) But I just can't seem to find the right search term for this, and when I think I'm close I don't quite seem to understand it yet. Any, tips, tricks, examples, someone can give to me? Many thanks in advance! Gr. Ian |
Specify concrete type for methods in Scala trait Posted: 29 Mar 2021 07:59 AM PDT I want to define a method in a Scala trait where both a parameter to the method and the return type correspond to the same concrete class which extends the trait. I've tried something like the following: trait A { def foo(obj: this.type): this.type } case class B(val bar: Int) extends A { override def foo(obj: B): B = { B(obj.bar + 1) } } object Main { def main(args: Array[String]) = { val b1 = new B(0) val b2 = new B(0) val b3: B = b1.foo(b2) } } However, trying to compile this code gives the following error: Test.scala:5: error: class B needs to be abstract. Missing implementation for: def foo(obj: B.this.type): B.this.type // inherited from trait A case class B(val bar: Int) extends A { ^ Test.scala:6: error: method foo overrides nothing. Note: the super classes of class B contain the following, non final members named foo: def foo: ((obj: _1.type): _1.type) forSome { val _1: B } override def foo(obj: B): B = { ^ 2 errors There's obviously something I'm misunderstanding about the Scala type system here. The signature of foo in class B is what I want it to be, but I don't know how to correctly define the method in A (or if this is even possible). It seems like this question is asking something quite similar, but I don't immediately see how the answer applies in my situation. |
Problem with GDB (MinGW-w64) in Visual Studio Code Posted: 29 Mar 2021 07:59 AM PDT The debugger in MiniGW won't work: no errors, no warning, but just after Start Debugging shows that in the console: Executing task: d:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin\g++.exe -g D:\Temp\helloworld\helloworld.cpp -o D:\Temp\helloworld\helloworld.exe < Terminal will be reused by tasks, press any key to close it. debugger looks like starts to work, but waits a couple of seconds and stops, without tracing inside or just direct execution without debugging. Everything was taken from here (incl example). The launch.json file is also simple: { "configurations": [ { "name": "g++.exe - Build and debug active file", "type": "cppdbg", "request": "launch", "program": "D:\\Temp\\helloworld\\helloworld.exe", "args": [], "stopAtEntry": true, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb", "miDebuggerPath": "D:\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\gdb.exe", "setupCommands": [ { "description": "Enable pretty-printing for gdb", "text": "-enable-pretty-printing", "ignoreFailures": true } ], "preLaunchTask": "C/C++: g++.exe build active file" } ] } No spaces in dir names were used or other known issues as claimed by others. A couple of times tried to reinstall MVC and MinGW, but it ain't help. |
Await issue in foreach Gmail API Posted: 29 Mar 2021 07:59 AM PDT I need to authenticate multiple tokens of different users and get inbox mails. Here is the code await configuredMails.forEach( async(mails) => { let token = mails.token; oAuth2Client.setCredentials(token); let inboxMails = await listInboxMails(oAuth2Client); }); listInboxMails = async (auth) => { const gmail = google.gmail({version: 'v1', auth}); await gmail.users.messages.list( { userId: 'me', q: query, maxResults: 1 },async (err, res) => { const messages = res.data.messages; if (typeof messages != undefined && messages != undefined) { await messages.forEach(async(message) => { let messageID = message.id; let threadID = message.threadId; let threadDetails = await this.getThreadDetails(threadID); if(threadDetails != null){ await gmail.users.messages.get( { userId: 'me', id: messageID },async(err, res) => { ..................... ...................... Here issues is before executing the gmail.users.messages.get() function the loop is iterating. So the next token is setting. So it shows Requested entity not found error. Because the oAuth2Client is replacing |
Symfony - Insert in a row if a value email already exist else create a new row [duplicate] Posted: 29 Mar 2021 07:59 AM PDT Sorry for my bad english, I have 3 Entity: [My Tables][1] I have a form (demandeType) for submit a new demande, the demande form is join by "Demandeur" and "Obj" entities. DemandeType > class DemandeType extends AbstractType { > public function buildForm(FormBuilderInterface $builder, array $options): void > { > $builder > ->add('date') > ->add('obj_requested') > ->add('person_asking', DemandeurType::class) > ; > } > > public function configureOptions(OptionsResolver $resolver) > { > $resolver->setDefaults([ > 'data_class' => Demande::class, > ]); > } } My problem is here: I need to check if a value email already exists in the database before add a new row to the demande index actually, all demande create a new line in the index, like that: [Actual Index][2] And I want to insert in date field the date of the new demande, and the Obj name on the same column if a user submit a second demande with same email adress. My goal is to have this thing: [Index Perfect][3] I have tried many solution in the demande controller, directly with the Twig template etc... This is my entities: Demande <?php namespace App\Entity; use Doctrine\Common\Collections\ArrayCollection; use App\Repository\DemandeRepository; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity(repositoryClass=DemandeRepository::class) */ class Demande { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="datetime") */ private $date; /** * @ORM\ManyToOne(targetEntity=Demandeur::class, inversedBy="demandes", cascade={"persist"}) * @ORM\JoinColumn(nullable=false) */ private $person_asking; /** * @ORM\ManyToOne(targetEntity=Obj::class, inversedBy="demandes") * @ORM\JoinColumn(nullable=false) */ private $obj_requested; /** * @Assert\Type(type="App\Entity\Demandeur") * @Assert\Valid */ protected $demandeur; public function __construct() { $this->date = new \DateTime(); } public function getId(): ?int { return $this->id; } public function getDate(): ?\DateTimeInterface { return $this->date; } public function setDate(\DateTimeInterface $date): self { $this->date = $date; return $this; } public function getPersonAsking(): ?Demandeur { return $this->person_asking; } public function setPersonAsking(?Demandeur $person_asking): self { $this->person_asking = $person_asking; return $this; } public function getObjRequested(): ?Obj { return $this->obj_requested; } public function setObjRequested(?Obj $obj_requested): self { $this->obj_requested = $obj_requested; return $this; } } Demandeur <?php namespace App\Entity; use App\Repository\DemandeurRepository; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=DemandeurRepository::class) */ class Demandeur { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) * @Assert\NotBlank */ private $lastname; /** * @ORM\Column(type="string", length=255) */ private $firstname; /** * @ORM\Column(type="string", length=255) * @Assert\Email( * message = "L'email '{{ value }}' n'est pas valide." * ) */ private $email; /** * @ORM\Column(type="string", length=255) */ private $phone_number; /** * @ORM\Column(type="string", length=255) */ private $company; /** * @ORM\OneToMany(targetEntity=Demande::class, mappedBy="person_asking", orphanRemoval=true) */ private $demandes; public function __toString() { return $this->lastname; } public function __construct() { $this->demandes = new ArrayCollection(); } public function getId(): ?int { return $this->id; } public function getLastname(): ?string { return $this->lastname; } public function setLastname(string $lastname): self { $this->lastname = $lastname; return $this; } public function getFirstname(): ?string { return $this->firstname; } public function setFirstname(string $firstname): self { $this->firstname = $firstname; return $this; } public function getEmail(): ?string { return $this->email; } public function setEmail(string $email): self { $this->email = $email; return $this; } public function getPhoneNumber(): ?string { return $this->phone_number; } public function setPhoneNumber(string $phone_number): self { $this->phone_number = $phone_number; return $this; } public function getCompany(): ?string { return $this->company; } public function setCompany(string $company): self { $this->company = $company; return $this; } /** * @return Collection|Demande[] */ public function getDemandes(): Collection { return $this->demandes; } public function addDemande(Demande $demande): self { if (!$this->demandes->contains($demande)) { $this->demandes[] = $demande; $demande->setPersonAsking($this); } return $this; } public function removeDemande(Demande $demande): self { if ($this->demandes->removeElement($demande)) { // set the owning side to null (unless already changed) if ($demande->getPersonAsking() === $this) { $demande->setPersonAsking(null); } } return $this; } } Obj <?php namespace App\Entity; use App\Repository\ObjRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=ObjRepository::class) */ class Obj { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $name; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $photo_link; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $video_link; /** * @ORM\Column(type="text", nullable=true) */ private $summarize; /** * @ORM\OneToMany(targetEntity=Demande::class, mappedBy="obj_requested", orphanRemoval=true) */ private $demandes; public function __construct() { $this->demandes = new ArrayCollection(); } public function __toString() { return $this->id; } public function getId(): ?int { return $this->id; } public function getName(): ?string { return $this->name; } public function setName(string $name): self { $this->name = $name; return $this; } public function getPhotoLink(): ?string { return $this->photo_link; } public function setPhotoLink(?string $photo_link): self { $this->photo_link = $photo_link; return $this; } public function getVideoLink(): ?string { return $this->video_link; } public function setVideoLink(?string $video_link): self { $this->video_link = $video_link; return $this; } public function getSummarize(): ?string { return $this->summarize; } public function setSummarize(?string $summarize): self { $this->summarize = $summarize; return $this; } /** * @return Collection|Demande[] */ public function getDemandes(): Collection { return $this->demandes; } public function addDemande(Demande $demande): self { if (!$this->demandes->contains($demande)) { $this->demandes[] = $demande; $demande->setObjRequested($this); } return $this; } public function removeDemande(Demande $demande): self { if ($this->demandes->removeElement($demande)) { // set the owning side to null (unless already changed) if ($demande->getObjRequested() === $this) { $demande->setObjRequested(null); } } return $this; } } My controllers DemandeController (without my failed email check) #[Route('/new', name: 'demande_new', methods: ['GET', 'POST'])] public function new(Request $request, MailerInterface $mailer, DemandeurRepository $demandeur): Response { $demande = new Demande(); $form = $this->createForm(DemandeType::class, $demande); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($demande); $entityManager->flush(); $email = (new Email()) ->from('alain.renault.communication@example.com') ->to('brlagasse@example.com') ->subject('Une demande vient d\'être effectuée !') ->html('<p>Une demande vient d\'être effectuée !</p>'); $mailer->send($email); return $this->redirectToRoute('demandeur_index'); } return $this->render('demande/new.html.twig', [ 'form' => $form->createView(), 'demande' => $demande, ]); } I've tried this function in my controller: public function new(Request $request, MailerInterface $mailer, DemandeurRepository $demandeur): Response { $demande = new Demande(); $demandeur = new Demandeur(); $demandeurRepository = $this->getDoctrine()-getRepository(Demandeur::class); $demandeur = $demandeurRepository->findBy(['email' => $_POST['email']]); $form = $this->createForm(DemandeType::class, $demande); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($demande); $entityManager->flush(); Can someone help me please :) ! [1]: https://i.stack.imgur.com/ubuEn.png [2]: https://i.stack.imgur.com/RHIlc.png [3]: https://i.stack.imgur.com/7TVdT.png |
Cloud Firestore is not adding data in flutter Posted: 29 Mar 2021 07:59 AM PDT In my project, I simply created a form with an image picker. The idea is to create an event data with name, email, image and more. I already uploaded the image to Firebase storage but I cannot add the rest of my data to Firestore. The data is correctly fetched and passed to next page, though. Here is my code: onPressed: () async { if(_formKey.currentState.validate()&& _image!=null){ var name = nameController.text; var price = priceController.text; var description = descriptionController.text; var location = locationController.text; var ticket = ticketController.text; var date; if(dateChecked==true){ setState(() { date = _startDate; }); } else if(dateChecked==false){ setState(() { date=_days[_selectedDay]; }); } var time = _time; var type = _options[_selectedIndex]; var img; await Firebase.initializeApp(); Reference reference = await _storage.ref().child('${name}/${date}'); final UploadTask uploadTask = reference.putFile(_image); uploadTask.whenComplete(() async{ img = await uploadTask.snapshot.ref.getDownloadURL(); print(img); Navigator.of(context).push(MaterialPageRoute( builder: (context) => PostSuccess( name,price,date,time,location,type,_image,description,ticket ))); }); await FirebaseFirestore.instance.collection('events').doc(name).set( { 'name': name, 'price': price, 'date': date, 'time': time, 'location': location, 'type': type, 'description': description, 'tickets': ticket }); } else{ print('validate first'); } }, Where am I making the mistakes? |
How to parse complex JSON in C#? Ultimately I want to display the result in DataGridView Posted: 29 Mar 2021 08:00 AM PDT This is my first time parsing complex JSON in C# and I am little confused with parsing JSON structure like this. However, I was able to successfully parse the simple JSON. I am including the JSON and the method I am following here: [{ "L1": null, "L2": { "Name": "XXX", "contact": "xxxxx", "address": "XXXX" } }, { "L1": { "gender": "XXX", "contact": "xxxxx", "mail_address": "XXXX" }, "L2": null }] I am using two separate class like shown below: public class L2 { public string Name{ get; set; } public string contact{ get; set; } public string address{ get; set; } } public class L1 { public string gender{ get; set; } public string contact{ get; set; } public string mail_address{ get; set; } } public class Root{ private L1 L1{get;set;} private L2 L2{get;set;} } I am using these lines to parse: string jsonText = File.ReadAllText("log_test.txt"); List<Root> data = (List<Root>)JsonConvert.DeserializeObject<List<Root>>(jsonText); When I run it, it runs without any errors but my ultimate goal is to display all the results in a table (or DataGridView). How do I access every properties? In the first object, L1 doesn't have any fields but it does have fields in second object. So how can I do "L1.gender" ? Any help is appreciated. Thanks !! |
How to make PowerShell wait till output of the command is shown? Posted: 29 Mar 2021 07:59 AM PDT How to make powershell show output of the second command before executing the third command? Write-Host 'List of disks:' Get-PhysicalDisk $number = Read-Host -Prompt 'Please choose number from disks above:' |
How to disable years selection in date picker field based on value selected in another dropdown field? Posted: 29 Mar 2021 07:59 AM PDT DOB Datepicker should disable the years based on the value selected in the dropdown field. - I have a dropdown with 3 values - ADULT, INFANT and CHILD.
- There is another field called DOB which opens a datepicker.
UI image When I select ADULT from the dropdown,in the DOB datepicker, it should enable only from last 100 years to today. It should disable the other years. (Should be able to select from 29 March 1921 to 29 March 2021(today)) Similary, when I select CHILD from the dropdown,in the DOB datepicker, it should enable only from last 12 years to today. It should disable the other years. For INFANT, last 2 years. HTML Component Code <div class="form-group col-md-3" [ngClass]="displayFieldCss('paxType',passengerFormIndex)" *ngIf = "getControlCheckInfo('paxType')"> <label>{{'Pax Type' | translate}}<span *ngIf = "getControlCheckInfo('paxType', true)" class="mandatory-fields err-msg">*</span></label> <select class="form-control" formControlName="paxType"> <option [ngValue]="null">Select Pax Type</option> <option *ngFor="let data of paxData" [ngValue]="data">{{data.passengerTypeName}}</option> </select> <app-field-error-display [displayError]="isFieldValid('paxType',passengerFormIndex)" errorMsg="Please enter the pax type"> </app-field-error-display> </div> <div class="form-group col-md-3" [ngClass]="displayFieldCss('dateOfBirth',passengerFormIndex)" *ngIf = "getControlCheckInfo('dateOfBirth')"> <label>{{'Date of Birth' | translate}}<span *ngIf = "getControlCheckInfo('dateOfBirth', true)" class="mandatory-fields err-msg">*</span></label> <input [min]="mindateOfBirth" matInput [matDatepicker]="dob" placeholder="Date of Birth" class="form-control" formControlName="dateOfBirth" (click)="dob.open()"> <mat-datepicker #dob></mat-datepicker> <app-field-error-display [displayError]="isFieldValid('dateOfBirth',passengerFormIndex)" errorMsg="Please enter the Date Of Birth"> </app-field-error-display> </div> I have the respective functions in ts file. |
the Barcode Scanner from googles mlkit doesn't recognize any barcodes Posted: 29 Mar 2021 07:59 AM PDT So i followed googles tutorial for their barcode scanner (this one) and the qr scanning works like a charm. The only problem is that i don't need qr codes but rather bar codes. But they don't work. It doesn't detect anything. I tried multiple online bar codes and ones from around the house but none got recognised as a barcode. this is the code in my activity that handles the image and scanner: public void btnClick(View v) { Intent imageTakeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if(imageTakeIntent.resolveActivity(getPackageManager())!=null){ startActivityForResult(imageTakeIntent, 101); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode==101 && resultCode==RESULT_OK) { Bundle extras = data.getExtras(); Bitmap imageBitmap = (Bitmap) extras.get("data"); imageView.setImageBitmap(imageBitmap); image = InputImage.fromBitmap(imageBitmap, 0); barCodeScanning(); } } public void barCodeScanning(){ BarcodeScannerOptions options = new BarcodeScannerOptions.Builder() .setBarcodeFormats( Barcode.FORMAT_CODE_128, Barcode.FORMAT_CODE_93, Barcode.FORMAT_CODE_93, Barcode.FORMAT_CODABAR, Barcode.FORMAT_EAN_13, Barcode.FORMAT_EAN_8, Barcode.FORMAT_ITF, Barcode.FORMAT_UPC_A, Barcode.FORMAT_UPC_E, Barcode.FORMAT_PDF417, Barcode.FORMAT_DATA_MATRIX, Barcode.FORMAT_QR_CODE, Barcode.FORMAT_AZTEC) .build(); BarcodeScanner scanner = BarcodeScanning.getClient(); Task<List<Barcode>> result = scanner.process(image) .addOnSuccessListener(new OnSuccessListener<List<Barcode>>() { @Override public void onSuccess(List<Barcode> barcodes) { System.out.println(barcodes.size()); for (Barcode barcode: barcodes) { Rect bounds = barcode.getBoundingBox(); Point[] corners = barcode.getCornerPoints(); String rawValue = barcode.getRawValue(); System.out.println(rawValue); int valueType = barcode.getValueType(); System.out.println(valueType); } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { e.printStackTrace(); } }); } The console looks fine to me except the line E/libc: Access denied finding property "ro.hardware.chipname" which is marked red but didn't turn up any helpful results on google. This is the complete console output: 02/26 18:29:10: Launching 'app' on HMD Global Nokia 5.3. Install successfully finished in 2 s 230 ms. $ adb shell am start -n "com.project.kuecheninventar/com.project.kuecheninventar.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER Connected to process 28314 on device 'hmd_global-nokia_5_3-N0AA003687KA2700363'. Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page. I/Perf: Connecting to perf service. W/kuecheninventa: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed) Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed) I/AdrenoGLES: QUALCOMM build : cfd6c90, Id60e6598a1 Build Date : 01/27/20 OpenGL ES Shader Compiler Version: EV031.27.05.03 Local Branch : mybranchea40f85b-21cb-f1fb-b0c0-5cb90179c3e0 Remote Branch : quic/gfx-adreno.lnx.1.0.r91-rel Remote Branch : NONE Reconstruct Branch : NOTHING Build Config : S P 8.0.12 AArch64 I/AdrenoGLES: PFP: 0x016ee187, ME: 0x00000000 W/Gralloc3: mapper 3.x is not supported D/TransportRuntime.JobInfoScheduler: Scheduling upload for context TransportContext(cct, VERY_LOW, MSRodHRwczovL2ZpcmViYXNlbG9nZ2luZy5nb29nbGVhcGlzLmNvbS92MGNjL2xvZy9iYXRjaD9mb3JtYXQ9anNvbl9wcm90bzNc) with jobId=-1883559869 in 86400000ms(Backend next call timestamp 0). Attempt 1 I/DynamiteModule: Considering local module com.google.mlkit.dynamite.barcode:10000 and remote module com.google.mlkit.dynamite.barcode:0 Selected local version of com.google.mlkit.dynamite.barcode I/tflite: Initialized TensorFlow Lite runtime. I/native: barcode_detector_client.cc:239 Not using NNAPI E/libc: Access denied finding property "ro.hardware.chipname" D/TransportRuntime.SQLiteEventStore: Storing event with priority=VERY_LOW, name=FIREBASE_ML_SDK for destination cct D/TransportRuntime.JobInfoScheduler: Upload for context TransportContext(cct, VERY_LOW, MSRodHRwczovL2ZpcmViYXNlbG9nZ2luZy5nb29nbGVhcGlzLmNvbS92MGNjL2xvZy9iYXRjaD9mb3JtYXQ9anNvbl9wcm90bzNc) is already scheduled. Returning... I/System.out: 0 D/TransportRuntime.SQLiteEventStore: Storing event with priority=VERY_LOW, name=FIREBASE_ML_SDK for destination cct D/TransportRuntime.JobInfoScheduler: Upload for context TransportContext(cct, VERY_LOW, MSRodHRwczovL2ZpcmViYXNlbG9nZ2luZy5nb29nbGVhcGlzLmNvbS92MGNjL2xvZy9iYXRjaD9mb3JtYXQ9anNvbl9wcm90bzNc) is already scheduled. Returning... D/TransportRuntime.SQLiteEventStore: Storing event with priority=VERY_LOW, name=FIREBASE_ML_SDK for destination cct D/TransportRuntime.JobInfoScheduler: Upload for context TransportContext(cct, VERY_LOW, MSRodHRwczovL2ZpcmViYXNlbG9nZ2luZy5nb29nbGVhcGlzLmNvbS92MGNjL2xvZy9iYXRjaD9mb3JtYXQ9anNvbl9wcm90bzNc) is already scheduled. Returning... D/TransportRuntime.SQLiteEventStore: Storing event with priority=VERY_LOW, name=FIREBASE_ML_SDK for destination cct D/TransportRuntime.JobInfoScheduler: Upload for context TransportContext(cct, VERY_LOW, MSRodHRwczovL2ZpcmViYXNlbG9nZ2luZy5nb29nbGVhcGlzLmNvbS92MGNjL2xvZy9iYXRjaD9mb3JtYXQ9anNvbl9wcm90bzNc) is already scheduled. Returning... The line System.out.println(barcodes.size()); just prints 0 which means the barcode list is empty. Did i do something wrong or why does the qr code regognize but no bar code? |
How to change MySQL JS> to only MYSQL? Posted: 29 Mar 2021 07:59 AM PDT I did custom installation for MYSQL and only included MySQL shell, server, and python connector but I don't know from where Java script came from and because of that I can't connect python and Mysql. Please help |
No comments:
Post a Comment