How to remove blank space after string Posted: 29 Jan 2022 03:22 AM PST I am trying to remove string from a .txt file in PHP, and when I do that it leaves blank space. What I tried: $content = file_get_contents('../admin/accounts.txt'); $content = str_replace('line3', '', $content); file_put_contents('../admin/accounts.txt', $content); File before edit: line1 line2 line3 line4 line5 File after edit: line1 line2 line4 line5 I want to remove that exact whitespace |
Context Switching Between Parallel Running Threads Posted: 29 Jan 2022 03:22 AM PST The problem is that we have to create 4 threads, the first thread will keep printing the number 1, second thread would keep printing 2s, third thread would keep printing 3s and the fourth thread would be waiting for users input...once the user presses 'q' key, the program would terminate and the number of 1s, 2s, and 3s printed would be printed on the console. #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <ctype.h> #incluse <string.h> void *tm1(void *); void *tm2(void *); void *tm3(void *); void *tm4(); void *tm1(void *arg) { printf("1 "); } void *tm2(void *arg) { printf("2 "); } void *tm3() { printf("3 "); } void *tm4() { int ch = fgetc(stdin); return (void*) &ch; } int main(int argc, char *argv[]) { int *res, i = 0, j = 0, k = 0; srand(time(NULL)); pthread_t th, th1, th2, th3; while(1) { if (pthread_create(&th, NULL, &tm1, NULL) != 0) { return 1; } if (pthread_create(&th1, NULL, &tm2, NULL) != 0) { return 2; } if (pthread_create(&th2, NULL, &tm3, NULL) != 0) { return 3; } if (pthread_create(&th3, NULL, &tm4, NULL) != 0) { return 4; } if (pthread_join(th, NULL) != 0) { return 5; } if (pthread_join(th1, NULL) != 0) { return 6; } if (pthread_join(th2, NULL) != 0) { return 7; } if (pthread_join(th3, (void**) &res) != 0) { return 8; } if (res == 'Q' || res == 'q') { printf("Number of 1s = %d",i); printf("Number of 2s = %d",j); printf("Number of 3s = %d",k; return 9; } } free(res); return 0; } |
Why is my code (in R) not running within a for loop? Posted: 29 Jan 2022 03:21 AM PST THe following code fails to run when I add a for loop. Why is this happening? g01 <- erdos.renyi.game(10, .7, directed = FALSE) E(g01)$weight <- runif(length(E(g01)), 0,4) plot(g01, edge.width=E(g01)$weight) A <-as_adjacency_matrix(g01, attr="weight") B<-mean(p) C<-A-mean diag(C) <- 0 D<-(C)^2/100 Ssum<-sum(D)/2 print(Ssum) Here is the same code within the loop: for(i in 1:1000){g01 <- erdos.renyi.game(10, .7, directed = FALSE) E(g01)$weight <- runif(length(E(g01)), 0,4) plot(g01, edge.width=E(g01)$weight) A <-as_adjacency_matrix(g01, attr="weight") B<-mean(p) C<-A-mean diag(C) <- 0 D<-(C)^2/100 Ssum<-sum(D)/2 print(Ssum)} ANy help would be deeply appreciated, Ishani Mukherjee |
different back button color in expanded and collapsed states of Collapsing Tollbar Posted: 29 Jan 2022 03:21 AM PST How to set different back button color in expanded and collapsed states of Collapsing Tollbar? <com.google.android.material.appbar.AppBarLayout android:id="@+id/main.appbar" android:layout_width="match_parent" android:layout_height="300dp" android:fitsSystemWindows="true"> <com.google.android.material.appbar.CollapsingToolbarLayout android:id="@+id/main.collapsing" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:theme="@style/Theme.TopMovie.AppBarOverlay" app:contentScrim="?attr/colorOnPrimary" app:expandedTitleGravity="bottom|center_horizontal" app:expandedTitleMarginEnd="16dp" app:scrimAnimationDuration="100" app:expandedTitleMarginStart="16dp" app:expandedTitleTextAppearance="@style/TitleTextStyle" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:maxLines="3" app:titleCollapseMode="scale"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" tools:title="TitleTitle" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin" /> </com.google.android.material.appbar.CollapsingToolbarLayout> </com.google.android.material.appbar.AppBarLayout> <style name="Theme.TopMovie.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" > <item name="expandedTitleTextColor">@color/white</item> <item name="collapsedTitleTextColor">?attr/colorOnSecondary</item> <item name="colorControlNormal">?attr/colorOnSecondary</item> </style> colorControlNormal sets color in all states, but I need different colors . |
Google Sheet embeded to my website not fit with mobile view Posted: 29 Jan 2022 03:21 AM PST I used a google sheets and did share it in my website, as this: https://fahadbusiness.com/sa-stock/ but when I use it from my mobile I can't see it very well and the page is too small. Can I find a code so that it can also fit with and mobile? Thanks |
How To make Video Background transparent In ExoPlayer Android Posted: 29 Jan 2022 03:21 AM PST I want to remove background color of video in exoplayer or make it transparent i.e if video background color is red then make it transparent and view behind exoplayer must be visible. Note : I don't want to make changes in Exoplayer background only remove video background which is playing in ExoPlayer I have made lots of search in google but unfortunate did't got right answer, Please let me know its possible or not and its possible using any other way please direct me. Thanks in Advance |
How to build something like litmus.com or emailonacid.com Posted: 29 Jan 2022 03:21 AM PST How do you start building something like litmus.com or emailonacid.com where you can view one email on multiple email clients automatically, I know we can use virtual machines/simulators but how do you automate the process of capturing snapshots of the email on multiple clients like gmail for android, apple mail, outlook on windows etc. - How do you generate a new email for each user
- How do you login with that email on multiple devices for each user
- How do you view emails sent to that email on multiple devices
I just need a starting point for all this please any help would be helpful. Thanks. |
Lexical analysis of line joins (\) in Python Posted: 29 Jan 2022 03:20 AM PST I'm writing a small program that parses Python source files and builds a HTML page of the code but I'm having an issue with implicit line joins. If I have the following code in test_str.py: test_str = "Hello" \ "there" \ "test" \ "string" how can I parse this source code so that it keeps the structure and indentation as it is in test_str.py? To demonstrate the issue I can use the tokenize module from the Python Standard Library, which I'm using in my program for lexical analysis. If I run python -m tokenize test_str.py I get the following output: 0,0-0,0: ENCODING 'utf-8' 1,0-1,8: NAME 'test_str' 1,9-1,10: OP '=' 1,11-1,18: STRING '"Hello"' 2,4-2,11: STRING '"there"' 3,4-3,10: STRING '"test"' 4,4-4,12: STRING '"string"' 4,12-4,13: NEWLINE '' 5,0-5,0: ENDMARKER '' There are no new line characters being tokenized when a line join (\) is encountered, meaning I can't parse this code and keep the same formatting on the Web page. The same goes for function line joins: test_str = " ".join(" Hello") \ .lstrip(" ") The output again doesn't detect that a the code is spread across multiple lines: 0,0-0,0: ENCODING 'utf-8' 1,0-1,8: NAME 'test_str' 1,9-1,10: OP '=' 1,11-1,14: STRING '" "' 1,14-1,15: OP '.' 1,15-1,19: NAME 'join' 1,19-1,20: OP '(' 1,20-1,36: STRING '" Hello"' 1,36-1,37: OP ')' 2,14-2,15: OP '.' 2,15-2,21: NAME 'lstrip' 2,21-2,22: OP '(' 2,22-2,25: STRING '" "' 2,25-2,26: OP ')' 2,26-2,27: NEWLINE '\n' 3,0-3,0: ENDMARKER '' Anyone have any ideas about how to detect line joins so that I have a HTML file that produces an exact replica of the Python source? |
How to add reCaptcha v3 in a .NET MVC project in ContactUs page? Posted: 29 Jan 2022 03:20 AM PST First create a Model-class for ContactUs page named as "Contactus.cs" using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BlockChainingProject_YourFlow.Models { public class Contactus { public string contact_name { get; set; } public string contact_phone { get; set; } public string contact_email { get; set; } public string contact_message { get; set; } } } Now create another Model-class for using the Stored Procedure fot the ContactUs form named as "DatabaseManager.cs". using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; namespace BlockChainingProject_YourFlow.Models { public class DatabaseManager { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["db"].ConnectionString); public bool InsertUpdateDalete(string commond) { SqlCommand cmd = new SqlCommand(commond, con); if (con.State == ConnectionState.Closed) { con.Open(); } int n = cmd.ExecuteNonQuery(); if (n > 0) return true; else return false; } public DataTable GetAllRecord(string command) { SqlDataAdapter sa = new SqlDataAdapter(command, con); DataTable dt = new DataTable(); sa.Fill(dt); return dt; } } } Now go the Controller where you want to write the Action method for the Contact Page. [HttpGet] public ActionResult contactus() { return View(); } [HttpPost] public ActionResult btn_Contact_click(FormCollection form, Contactus c) { try { string to_username = ConfigurationManager.AppSettings["to_username"].ToString(); string form_username = ConfigurationManager.AppSettings["form_username"].ToString(); string form_password = ConfigurationManager.AppSettings["form_password"].ToString(); string smtpAddress = "smtp.gmail.com"; //103.21.58.247 int portNumber = 587; bool enableSSL = true; //false if (form["contact_name"] != "" && form["contact_phone"] != "" && form["contact_email"] != "" && form["contact_message"] != "") { //start query for contact string cmd = "insert into tbl_contact values ('" + c.contact_name + "','" + c.contact_email + "','" + c.contact_phone + "','" + c.contact_message + "')"; if (db.InsertUpdateDalete(cmd)) { //end query for contact using (MailMessage mail = new MailMessage()) { string body = string.Empty; using (StreamReader reader = new StreamReader(Server.MapPath("~/Content/contactmail.html"))) { body = reader.ReadToEnd(); body = body.Replace("FULLNAME", form["contact_name"].ToString()); body = body.Replace("EMAILID", form["contact_email"]); body = body.Replace("PHONE", form["contact_phone"]); body = body.Replace("MESSAGE", form["contact_message"]); } mail.From = new MailAddress(form_username); mail.To.Add(to_username); mail.Subject = "New appointment query from " + form["contact_name"] + " for Leafy Greens Supplychain"; mail.Body = body.ToString(); mail.IsBodyHtml = true; using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)) { smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(form_username, Encrypted.Decryptdata(form_password)); smtp.EnableSsl = enableSSL; smtp.Send(mail); } } using (MailMessage mail = new MailMessage()) { string body = string.Empty; using (StreamReader reader = new StreamReader(Server.MapPath("~/Content/contactreply.html"))) { body = reader.ReadToEnd(); body = body.Replace("FULLNAME", form["contact_name"].ToString()); } mail.From = new MailAddress(form_username); mail.To.Add(form["contact_email"]); mail.Subject = "Thank you for contacting on Leafy Greens Supplychain"; mail.Body = body.ToString(); mail.IsBodyHtml = true; using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber)) { smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(form_username, Encrypted.Decryptdata(form_password)); smtp.EnableSsl = enableSSL; smtp.Send(mail); } } TempData["JavaScriptFunction"] = string.Format("popup();"); } else { TempData["JavascriptFunction"] = string.Format("popupservererror();"); } } else { TempData["JavaScriptFunction"] = string.Format("popupvalidation();"); } } catch (Exception ex) { TempData["JavaScriptFunction"] = string.Format("popupservererror();"); } return Redirect("/Home/Contactus"); } Now add the view for "contactus" method and create a Contactus.CSHTML page. See the below code. @{ ViewBag.Title = "contactus"; Layout = "~/Views/Shared/_Layout.cshtml"; } <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <script> function popup() { swal({ title: "Successful!", text: "Your enquiry is submitted. Thank you for contacting us.", icon: "success", button: "Ok", }); } function popupservererror() { swal({ title: "Server Error!", text: "Server error ! Try again later.", icon: "error", button: "Ok", }); } function errorcaptcha() { swal({ title: "Catcha Error!", text: "Captch error ! Try again later.", icon: "error", button: "Ok", }); } </script> <script src="https://www.google.com/recaptcha/api.js?render=6Lf0cRseAAAAABwR0t7U2I12kx6Popa2yOnvMYe3"></script> @*/*Site Key*/ /*6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_*/*@ <script> grecaptcha.ready(function () { grecaptcha.execute('6Lf0cRseAAAAABwR0t7U2I12kx6Popa2yOnvMYe3', { action: 'contact_us' }).then(function (token) { document.getElementById("<%=hf_token.ClientID%>").value = token; }); }); </script> <script> grecaptcha.ready(function () { grecaptcha.execute('6Lf0cRseAAAAABwR0t7U2I12kx6Popa2yOnvMYe3', { action: 'contact_us' }).then(function (token) { //6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_// $.ajax({ type: "POST", url: "contactus.cshtml/SetToken", data: JSON.stringify({ _token: token }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { console.log('Passed the token successfully'); }, failure: function (response) { alert(response.d); } }); }); }); </script> <script src="js/main.js"></script> <div class="container-fluid lightgreybg course-banner padding-top-50"> <div class="row"> <div class="container"> <div class="row"> <div class="col-md-8 offset-md-2 course-banner-content mb-5"> <h3>About us</h3> <p> Uncover how the blockchain is revolutionising Industry 4.0.<br /> Explore a new way to do business with blockchain strategy and solutions. </p> </div> </div> </div> </div> </div> <div class="container padding-top-50"> <div class="row d-flex align-items-center"> <div class="col-lg-6"> <div class="contactinfoarea"> <h1>Get In Touch</h1> <p>Our team of dedicated business accounting professionals are ready and waiting for your enquiry.</p> <ul> <li> <i class="fa fa-map-marker"></i> Lorem ipsum del<br /> amet seo del </li> <li><i class="fa fa-phone"></i> <a href="tel:1300145032">1300145032</a></li> <li><i class="fa fa-envelope"></i> <a href="mail:info@blockchainbasics.com">info@blockchainbasics.com</a></li> </ul> </div> </div> <div class="col-lg-6 contactinfoform"> @using (Html.BeginForm("btn_Contact_click", "Home", FormMethod.Post)) { <div class="bannerform"> <h3>Write to us</h3> <div class="form-group"> <label class="form-item__label">Name*</label> <input class="form-control" type="text" name="contact_name"> </div> <div class="form-group"> <label class="form-item__label">Phone</label> <input class="form-control" type="text" name="contact_phone"> </div> <div class="form-group"> <label class="form-item__label">Email*</label> <input class="form-control" type="text" name="contact_email"> </div> <div class="form-group"> <label class="form-item__label">Message*</label> <textarea class="form-control" type="text" name="contact_message"></textarea> </div> <div class="form-group text-right margin-top-30"> <input class="btn btn-blue" type="submit" value="Contact Us" name="" /> </div> <input id="hf_token" type="hidden" name="name" value="" /> </div> } </div> </div> if (TempData["JavaScriptFunction"] != null) { <script type="text/javascript"> @Html.Raw(TempData["JavaScriptFunction"]); </script> } </div> <div class="container-fluid mapareacontact"> <div class="row"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3524297.3533693994!2d140.2132509997906!3d-23.94804237605206!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x6bd4df247a62dcfd%3A0xf5f2d0227612be99!2sQueensland%2C%20Australia!5e0!3m2!1sen!2sin!4v1640691574128!5m2!1sen!2sin" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe> </div> </div> <div class="container-fluid padding-bottom-60 padding-top-60"> <div class="row"> <div class="container"> <div class="row d-flex justify-align-center align-items-center"> <div class="col-md-4 newsltrleft mb-5"> <img src="~/Content/images/newsletter-left.svg" width="540" height="793" class="img-fluid" /> </div> <div class="col-md-6 offset-md-2 newsltrright mb-5"> <p>Subscrible now</p> <h2>Get every single update you will get updated every week</h2> <div class="input-group newsletterouter mb-3"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fa fa-envelope"></i></span> </div> <input type="text" class="form-control emailarea" placeholder="Enter email address"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button">Subscrible now</button> </div> </div> </div> </div> </div> </div> </div> Now go the Web.config file for Database Connection and Site Key and Secret Key. See the below code.### @{ ViewBag.Title = "contactus"; Layout = "~/Views/Shared/_Layout.cshtml"; } <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> <script> function popup() { swal({ title: "Successful!", text: "Your enquiry is submitted. Thank you for contacting us.", icon: "success", button: "Ok", }); } function popupservererror() { swal({ title: "Server Error!", text: "Server error ! Try again later.", icon: "error", button: "Ok", }); } function errorcaptcha() { swal({ title: "Catcha Error!", text: "Captch error ! Try again later.", icon: "error", button: "Ok", }); } </script> <script src="https://www.google.com/recaptcha/api.js?render=6Lf0cRseAAAAABwR0t7U2I12kx6Popa2yOnvMYe3"></script> @*/*Site Key*/ /*6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_*/*@ <script> grecaptcha.ready(function () { grecaptcha.execute('6Lf0cRseAAAAABwR0t7U2I12kx6Popa2yOnvMYe3', { action: 'contact_us' }).then(function (token) { document.getElementById("<%=hf_token.ClientID%>").value = token; }); }); </script> <script> grecaptcha.ready(function () { grecaptcha.execute('6Lf0cRseAAAAABwR0t7U2I12kx6Popa2yOnvMYe3', { action: 'contact_us' }).then(function (token) { //6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_// $.ajax({ type: "POST", url: "contactus.cshtml/SetToken", data: JSON.stringify({ _token: token }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { console.log('Passed the token successfully'); }, failure: function (response) { alert(response.d); } }); }); }); </script> <script src="js/main.js"></script> <div class="container-fluid lightgreybg course-banner padding-top-50"> <div class="row"> <div class="container"> <div class="row"> <div class="col-md-8 offset-md-2 course-banner-content mb-5"> <h3>About us</h3> <p> Uncover how the blockchain is revolutionising Industry 4.0.<br /> Explore a new way to do business with blockchain strategy and solutions. </p> </div> </div> </div> </div> </div> <div class="container padding-top-50"> <div class="row d-flex align-items-center"> <div class="col-lg-6"> <div class="contactinfoarea"> <h1>Get In Touch</h1> <p>Our team of dedicated business accounting professionals are ready and waiting for your enquiry.</p> <ul> <li> <i class="fa fa-map-marker"></i> Lorem ipsum del<br /> amet seo del </li> <li><i class="fa fa-phone"></i> <a href="tel:1300145032">1300145032</a></li> <li><i class="fa fa-envelope"></i> <a href="mail:info@blockchainbasics.com">info@blockchainbasics.com</a></li> </ul> </div> </div> <div class="col-lg-6 contactinfoform"> @using (Html.BeginForm("btn_Contact_click", "Home", FormMethod.Post)) { <div class="bannerform"> <h3>Write to us</h3> <div class="form-group"> <label class="form-item__label">Name*</label> <input class="form-control" type="text" name="contact_name"> </div> <div class="form-group"> <label class="form-item__label">Phone</label> <input class="form-control" type="text" name="contact_phone"> </div> <div class="form-group"> <label class="form-item__label">Email*</label> <input class="form-control" type="text" name="contact_email"> </div> <div class="form-group"> <label class="form-item__label">Message*</label> <textarea class="form-control" type="text" name="contact_message"></textarea> </div> <div class="form-group text-right margin-top-30"> <input class="btn btn-blue" type="submit" value="Contact Us" name="" /> </div> <input id="hf_token" type="hidden" name="name" value="" /> </div> } </div> </div> if (TempData["JavaScriptFunction"] != null) { <script type="text/javascript"> @Html.Raw(TempData["JavaScriptFunction"]); </script> } </div> <div class="container-fluid mapareacontact"> <div class="row"> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3524297.3533693994!2d140.2132509997906!3d-23.94804237605206!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x6bd4df247a62dcfd%3A0xf5f2d0227612be99!2sQueensland%2C%20Australia!5e0!3m2!1sen!2sin!4v1640691574128!5m2!1sen!2sin" width="600" height="450" style="border:0;" allowfullscreen="" loading="lazy"></iframe> </div> </div> <div class="container-fluid padding-bottom-60 padding-top-60"> <div class="row"> <div class="container"> <div class="row d-flex justify-align-center align-items-center"> <div class="col-md-4 newsltrleft mb-5"> <img src="~/Content/images/newsletter-left.svg" width="540" height="793" class="img-fluid" /> </div> <div class="col-md-6 offset-md-2 newsltrright mb-5"> <p>Subscrible now</p> <h2>Get every single update you will get updated every week</h2> <div class="input-group newsletterouter mb-3"> <div class="input-group-prepend"> <span class="input-group-text"><i class="fa fa-envelope"></i></span> </div> <input type="text" class="form-control emailarea" placeholder="Enter email address"> <div class="input-group-append"> <button class="btn btn-outline-secondary" type="button">Subscrible now</button> </div> </div> </div> </div> </div> </div> </div> |
Can someone explain the use of last two things in given code Posted: 29 Jan 2022 03:21 AM PST struct Interval { int start; int end; Interval() : start(0), end(0) {} Interval(int s, int e) : start(s), end(e) {} }; I understood int start and int end but can anyone please describe what other two things represent. |
with statement python __enter__ attribute error Posted: 29 Jan 2022 03:22 AM PST This : def add_to_excel(list_to_save, file_to_save_in): my_file = dir_path + '\\' + file_to_save_in with openpyxl.load_workbook(filename=my_file) as links_excel: sheet = links_excel['Sheet1'] for i in list_to_save: sheet.append(i) links_excel.save(filename) return returns this: 3 my_file = dir_path + '\\' + file_to_save_in ----> 4 with openpyxl.load_workbook(filename=my_file) as links_excel: 5 sheet = links_excel['Sheet1'] 6 for i in list_to_save: AttributeError: __enter__ Tried this: You're not using with statement and there's no close() statement so if this is not the first time you're running the code, it's likely that you haven't closed the file properly and it is still sitting in the memory and prevents access. |
How to make react as fast as next.js? Posted: 29 Jan 2022 03:21 AM PST I'm using react and next.js. I build the same project in both of them. One might logically expect that next.js should be compiled slower than react. But my next.js project gets compiled in less than 10 second, while my react project takes more than 40 seconds to compile. And it also uses a lot of CPU. What should I do to make react as fast as next.js? |
How to execute left outer join asynchronously? when the join is on the where clause Posted: 29 Jan 2022 03:20 AM PST I am trying to optimize the following query, let's say I have 2 tables People: id | name | 1 | Ben | 2 | John | 3 | Joey | Pets: id | name | person_id | 1 | Doge | 1 | 2 | Catty | 2 | 3 | Reksi | 1 | It's a 1 to many relationship, but I can't define foreign key because the order in which they may be inserted, so I define a default index for person_id And I execute the following query: select some_fields from People left outer join pets on person_id=id where id=1 That I am trying to optimize. Since the outer left join is being done on the provided id, can I execute this SQL asynchronously? I am using JS and Sequelize (that generates this query), I can technically send 2 queries without joins and use promise.all() to send them both together, and then merge the results manually on JS. But I was wondering if I can tell SQL to execute it like that so it will be more effective? |
How can I make discord bot for strarting minecraft server with python? Posted: 29 Jan 2022 03:23 AM PST That is my cod now: import discord import subprocess client = discord.Client() @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('!StartServer'): await message.channel.send('Server is starting') subprocess.call(['java', '-jar', 'D:\Tests\paper\paper-1.18.1-92.jar']) client.run('token') But when I use command '!StartServer' console whrite this (I already agreed EULA): **Starting org.bukkit.craftbukkit.Main *** Warning, you've not updated in a while! *** *** Please download a new build as per instructions from https://papermc.io/downloads *** System Info: Java 17 (Java HotSpot(TM) 64-Bit Server VM 17.0.1+12-LTS-39) Host: Windows 10 10.0 (amd64) Loading libraries, please wait... 2022-01-29 16:44:05,769 ServerMain WARN Advanced terminal features are not available in this environment [16:44:09 INFO]: You need to agree to the EULA in order to run the server. Go to eula.txt for more info.** How can I fix it? |
Multiple CN groups authentication with Active Directory LDAP Posted: 29 Jan 2022 03:21 AM PST Using Active Directory with Spring for LDAP, If I specify the exact directory (base) of the search, for example String base="CN=Administrators" search/authentication finds the user, but if passed to the method .authenticate(String base="", filter, password), where base is an empty string, then it does not find it and gives an error .authenticate(String base="", filter, password) //error org.springframework.ldap.PartialResultException: Unprocessed Continuation Reference(s); nested exception is javax.naming.PartialResultException: Unprocessed Continuation Reference(s); remaining name '/' Moreover, if I connect to OpenLDAP and not to Active Directory, it allows me to specify an empty string LdapTemplate.authenticate(String base="", filter, password) and finds the user. As I understand it, OpenLdap allows to search through all groups, which is what I need. For example I have several CN Groups like CN=Administrators, CN=FreeUsers, CN=System etc with many CN users inside. How to allow Active Directory search through all of them on authenticate? |
is it possible to rename the variable receiving via { get; set; } in c# class? Posted: 29 Jan 2022 03:21 AM PST so I have this class: public class CheckTweetSingle { public int item1 { get; set; } public int item2 { get; set; } } I get a json string that I am converting the values into item1 and item2. is it possible to change the name of item1 to chairs and item2 to tables, so I can access them via checkTweet.chair instead of checkTweet.item2? I cannot change the way the json string is coming.. thank you. |
Corrected usage of gcov on executable and static library Posted: 29 Jan 2022 03:22 AM PST I have a very simple example of using gcov: library.cpp file compiled and turned into library.a main.cpp file compiled into executable and uses library.a All of this done via a simple bash script: g++ -c library.cpp -Wall -fprofile-arcs -ftest-coverage -o library.o ar rvs library.a library.o g++ main.cpp -Wall -fprofile-arcs -ftest-coverage library.a -o main Now at this point I have the folllowing files (ignoring source and build script): library.o library.gcno library.a main.cpp main main.gcno So far so good. Now I run my main executable, which creates: main.gcda library.gcda Again all as expected. Now for the question - when I run gcov main.cpp I don't get any gcov files for library.cpp. Is that expected? Do I really need to call gcov on every source file I may have at any point in time? Is there not a way to call the first source file i.e main.cpp and have it produce coverage stats for each piece of source main goes on to call? I appear to get gcov files for a lot of core library code that main.cpp uses without need to call them directly with gcov (ostream.gov, locale.gcov...) just not library.gcov |
Retreive associated value from next node for each tag Posted: 29 Jan 2022 03:22 AM PST I have the following XML... <Envelope format="ProceedoOrderTransaction2.1"> <Sender>SENDER</Sender> <Receiver>RECEIVER</Receiver> <EnvelopeID>xxxxx</EnvelopeID> <Date>2021-05-06</Date> <Time>11:59:46</Time> <NumberOfOrder>1</NumberOfOrder> <Order> <Header> <OrderNumber>POXXXXX</OrderNumber> </Header> <Lines> <Line> <LineNumber>1</LineNumber> <ItemName>Ipsum Lorum</ItemName> <SupplierArticleNumber>999999</SupplierArticleNumber> <UnitPrice vatRate="25.0">50</UnitPrice> <UnitPriceBasis>1</UnitPriceBasis> <OrderedQuantity unit="Styck">200</OrderedQuantity> <AdditionalItemProperty Key="ARTIKELNUMMER" Description="Unik ordermärkning (artikelnummer):" /> <Value>999999</Value> <AdditionalItemProperty Key="BESKRIVNING" Description="Kort beskrivning:" /> <Value>Ipsum Lorum</Value> <AdditionalItemProperty Key="BSKRIVNING" Description="Beskrivning:" /> <Value>Ipsum Lorum</Value> <AdditionalItemProperty Key="ENHET" Description="Enhet:" /> <Value>Styck</Value> <AdditionalItemProperty Key="KVANTITET" Description="Kvantitet:" /> <Value>200</Value> <AdditionalItemProperty Key="PRIS" Description="Pris/Enhet (ex. moms):" /> <Value>50</Value> <AdditionalItemProperty Key="VALUTA" Description="Valuta:" /> <Value>SEK</Value> <Accounting> <AccountingLine amount="10000"> <AccountingValue dimensionPosition="001" dimensionExternalID="ACCOUNT">xxx</AccountingValue> <AccountingValue dimensionPosition="002" dimensionExternalID="F1">Ipsum Lorum</AccountingValue> <AccountingValue dimensionPosition="005" dimensionExternalID="F3">1</AccountingValue> <AccountingValue dimensionPosition="010" dimensionExternalID="F2">9999</AccountingValue> </AccountingLine> </Accounting> </Line> </Lines> </Order> </Envelope> I am able to parse out all values correctly to table structure except for 1 value in a way that ensures its it associated with its tagg. So where i stumble is that i am correctly getting 1 row per "AdditionalItemProperty" and i am able to get the "Key" and "Description" tagg values, for example "BESKRIVNING" and "Kort beskrivning:" but i can't (in a reasonable way) get the value( between brackets) that is also associated with each tagg value. So for tagg key value "BESKRIVNING" the associated value is 99999 which seem to be on same hieararchy level (insane i know) as the "AdditionalItemProperty" it is associated with. Seems like they use logic that value for a AdditionalItemProperty will be following the AdditionalItemProperty tagg. I am using sql server 2019. I have gotten this far... -- Purchaseorderrowattributes select top(10) i.value(N'(./Header/OrderNumber/text())[1]', 'nvarchar(30)') as OrderNumber ,ap.value(N'(../LineNumber/text())[1]', 'nvarchar(30)') as LineNumber ,ap.value(N'(@Description)', 'nvarchar(50)') property_description from load.proceedo_orders t outer apply t.xml_data.nodes('Envelope/Order') AS i(i) outer apply i.nodes('Lines/Line/AdditionalItemProperty') as ap(ap) where file_name = @filename Which produces following output... OrderNumber LineNumber property_description PO170006416 1 Antal timmar PO170006416 1 Beskrivning PO170006416 1 Kompetensområde PO170006416 1 Roll PO170006416 1 Ordernummer PO170006416 1 Timpris I can't find a way to add the value for each property in a correct way. Since the ordering of the values will always be same as the ordering of the AdditionalItemProperty i found solution to get ordering of the AdditionalItemProperty and then i could use rownumber and i was then hoping to input the rownumber value into the bracket in ,ap.value(N'(../Value/text())[1]', 'nvarchar(50)') property_description but sql server throws exception that it has to be string literal. so to be clear what i tried doing with something like... ,ap.value(CONCAT( N'(../Value/text())[', CAST(ROWNUMBER as varchar) ,']'), 'nvarchar(50)') property_description |
Regression with indexes in R Posted: 29 Jan 2022 03:21 AM PST I am trying to estimate tax elasticity with OLS. Below you can see example of my dataset. dataset<-data.frame( gross_income_new=c(5000,4000,3000,2000,1500,200,1000,200,1500), gross_income_old=c(4500,3900,2100,1500,1450,210,980,100,1200), tax_burden=c(10,10,9,8,7,10,10,8,8), tax_burden1=c(17,11,12,14,15,14,12,17,15), gross_income_index=c(90,97.5,70,75,97,105,98,50,80), tax_burden_Index=c(170,110,133,175,214,140,120,213,188)) Elasticity = lm(log(gross_income_index)~log(tax_burden_Index), data = dataset) summary(Elasticity) And this is results from regression. Call: lm(formula = log(gross_income_index) ~ log(tax_burden_Index), data = dataset) Residuals: Min 1Q Median 3Q Max -0.36995 -0.05404 0.04150 0.11507 0.29487 Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 6.7252 1.6104 4.176 0.00416 ** log(tax_burden_Index) -0.4557 0.3176 -1.435 0.19447 --- Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1 Residual standard error: 0.2197 on 7 degrees of freedom Multiple R-squared: 0.2273, Adjusted R-squared: 0.1169 F-statistic: 2.059 on 1 and 7 DF, p-value: 0.1945 So for this example first I converted data into indexes, convert in logs an after that I estimate elasticity which is -0.4557 %. Now I want to make prediction into sample for column gross_income_new in order to see how my model works. Here I want to emphasize that I want to try this only with coefficient of elasticity (not with regression equation). In order to do that I try with this equation but I am little bit confused because I worked in indices and now I need to estimate values in different normal values not indexes. So I try with formula Prediction=(gross_income_old) + (tax_burden-tax_burden1)*elasticity But obviously I made same mistakes and result are not good. So can anybody help me how to solve this problem ? |
Webpack how to compile all my scss file without using import in my entry js file Posted: 29 Jan 2022 03:21 AM PST I use webpack ^5.65.0. I want to compile all my scss file into css but I have to use multiple import in my entry index.js like import './index.scss'; import './test.scss' ... I do not want to use import in the index.js file and think it can be done by webpack settings(I am not sure). My webpack.config.js module.exports = { devtool: 'eval-cheap-module-source-map', mode: isDev ? 'development' : 'production', entry: { index: './src/index.js', login: './src/login.js', test:'./test.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[chunkhash:6].js', publicPath: '/' }, module: { rules: [ { test: /\.jsx?$/, use: ['cache-loader','babel-loader'], include: [path.resolve(__dirname, 'src')] }, { test: /\.(sc|sa|c)ss/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'], include: [path.resolve(__dirname, 'src')] } ] } } I have no idea, then add a test.js to put all the scss import in it and add it to the entry.But the output will also has a test.xxxxxx.js file in the dist folder and I do not want it though. So,what is the right way to meet my requirement. Is it possible to just compile all scss file without import in the entry js file? |
Refresh token in Angular Posted: 29 Jan 2022 03:21 AM PST I really need your help. I'm trying to make an authorization system, but I need to do a refresh token. Unfortunately, I can't do that. I have a repository with the project code. Try I will do it in authService with the help storageService. I'm trying to do this in authService and using storageService, but I can't do it and I'm getting errors. Can you please help me do that? Thank you very much https://github.com/Dmytrii9Cherniak/AuthenticationJwtToken auth.service.ts private refreshTokenTimeout: any; refreshToken() { return this.httpClient.post<any>(this.refresh_token_url, {}, { params: { r_token: this.storageService.getToken() } } ) .pipe( tap((token) => { console.log('refreshToken started'); const isRemember = this.storageService.getToken().isRemember; // getting previous storage type const newToken = new Token(token); this.storageService.storageToken(newToken, isRemember) this.startRefreshTokenTimer(); }) ); } private startRefreshTokenTimer() { const token = this.storageService.getToken(); if (!!token) { const expires = new Date(token); const timeout = expires.getTime() - Date.now() - 60 * 1000; this.refreshTokenTimeout = setTimeout( () => this.refreshToken().subscribe(), timeout ); } } private stopRefreshTokenTimer() { clearTimeout(this.refreshTokenTimeout); } storage.service.ts export class StorageService {' storageToken(token: string, rememberUser: boolean) { if(rememberUser) { localStorage.setItem('token', token); } else { sessionStorage.setItem('token', token) } } getToken():string { let token = localStorage.getItem('token'); if (token) { return token } else { token = sessionStorage.getItem('token'); return token! } } removeToken() { localStorage.removeItem('token'); sessionStorage.removeItem('token'); } } |
Using GROUP BY and PARTITION BY together Posted: 29 Jan 2022 03:20 AM PST Here is my first query which returns the result in the image below I get the "Restaurant Name" , "Customer Name", "Count of orders", & "date" from 3 tables namely "Orders", "Customers" and "Restaurants". Then I group it by the restaurant name, customer name, and date. SELECT R.name AS name_of_r, C.name AS name_of_c, COUNT(O.id) AS Orders, date, FROM orders O INNER JOIN restaurants R ON R.id = O.restaurant_id AND R.country = O.country INNER JOIN customers C ON C.id = O.customer_id AND C.country = O.country GROUP BY R.name, C.name, date name_of_r | name_of_c | Orders | date Howdy | John Almagro | 1 | 2021-01-07 Howdy | John Almagro | 1 | 2021-07-01 Howdy | Luke Pablo | 1 | 2021-01-01 Howdy | Steven Smith | 1 | 2021-09-01 JFC | Monty Tron | 1 | 2021-01-01 JFC | Steven Smith | 1 | 2021-05-04 JFC | Steven Smith | 1 | 2021-06-01 KFC | Luke Pablo | 1 | 2021-01-09 KFC | Michael Wren | 1 | 2021-01-01 KFC | Monty Tron | 1 | 2021-04-01 KFC | Steven Smith | 1 | 2021-01-01 KFC | Steven Smith | 1 | 2021-03-01 KFC | Steven Smith | 1 | 2021-08-01 Kitchen Cuisine | Luke Pablo | 1 | 2021-01-05 Kitchen Cuisine | Luke Pablo | 1 | 2021-04-01 Kitchen Cuisine | Steven Smith | 1 | 2021-03-01 Kitchen Cuisine | Steven Smith | 1 | 2021-06-01 McDonald's | Arthur Chen | 1 | 2021-01-01 McDonald's | Arthur Chen | 1 | 2021-03-02 McDonald's | Arthur Chen | 1 | 2021-05-03 McDonald's | Arthur Chen | 1 | 2021-07-01 McDonald's | Arthur Chen | 1 | 2021-08-01 McDonald's | Arthur Chen | 1 | 2021-09-01 Now, what I want to do is partition by "name_of_r" (RESTAURANT NAME) ORDER by "date" and give a row number to each so then I can get the 3rd value of each window. Actually, this is my sub-query from which I want the customer's name who placed the 3rd order at each restaurant. I tried doing this adding row_number() and partition by but it didn't work and gave me a syntax error SELECT R.name AS name_of_r, C.name AS name_of_c, COUNT(O.id), date, ROW_NUMBER() OVER(PARTITION BY R.name ORDER BY date) AS row_num FROM orders O INNER JOIN restaurants R ON R.id = O.restaurant_id AND R.country = O.country INNER JOIN customers C ON C.id = O.customer_id AND C.country = O.country GROUP BY R.name, C.name, date |
Is it safe to drop the local database in mongodb? Posted: 29 Jan 2022 03:22 AM PST Sometimes when we drop a database from mongodb, not all the data is removed from the local database if replication is enabled. I wanted to know if it is safe to drop the local database. |
How can I get N smallest number in an array? Posted: 29 Jan 2022 03:20 AM PST I'm trying to get the N smallest numbers (given by the user) in an array without using methods like sort()... in the last step, I keep getting only the smallest values and 0 for the rest.. where's the problem? //1- Scanner to take inputs Scanner input = new Scanner(System.in); //2- Take the array size as input and store it in "sizeOfArr" var System.out.print("Enter the array size: "); int sizeOfArr = input.nextInt(); //3- Assign the input as an array size int array[] = new int[sizeOfArr]; //4- Looping on the array and update its values by inputs taken from the user for(int i = 0; i < array.length; i++) { System.out.print("Enter "+ (i+1) + "-st element: "); array[i] = input.nextInt(); } //5- Print out the array after convert it to String System.out.println(Arrays.toString(array)); //6- Find the smallest element in the array and print it int minVal = array[0]; for(int i = 0; i < array.length; i++) { if (array[i] < minVal) { minVal = array[i]; } } // System.out.println(minVal); //7- Find the (n) smallest of number defined by the user System.out.print("Enter the number of smallest numbers do you want: "); int n = input.nextInt(); //8- new array to store n smallest numbers int smallestNums[] = new int[n]; //9- trying to loop on the original array n times int counter; for(int i = 0; i < n ; i++) { //10- trying to loop on the original array to store the smallest values in smallestNum[] array. for(int j = 0; j < array.length; j++) { smallestNums[i] = minVal; } if(smallestNums[i] == smallestNums[i]) { break; } } System.out.println(Arrays.toString(smallestNums)); |
MQTT Mosquitto C++ not publishing data (disconnecting before) Posted: 29 Jan 2022 03:21 AM PST I am trying to publish a message both using commands and coding it. With the commands it works fine, I have a Broker running and a Publisher: mosquitto -v mosquitto_pub -d -t testTopic -m "Hello" Then, on the Broker I get a nice response and can read the data in a subscriber correctly: 1642677548: New connection from ::1:60619 on port 1883. 1642677548: New client connected from ::1:60619 as auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 (p2, c1, k60). 1642677548: No will message specified. 1642677548: Sending CONNACK to auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 (0, 0) 1642677548: Received PUBLISH from auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 (d0, q0, r0, m0, 'testTopic', ... (5 bytes)) 1642677548: Received DISCONNECT from auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 1642677548: Client auto-49A467C1-9AB0-9F4D-FEBD-6C99AB992163 disconnected. But having it in code as: int main() { int rc; struct mosquitto* mosq; mosquitto_lib_init(); mosq = mosquitto_new(NULL, true, NULL); rc = mosquitto_connect(mosq, "localhost", 1883, 60); if (rc != 0) { std::cout << "Client could not connect to broker!"; mosquitto_destroy(mosq); return -1; } mosquitto_loop_start(mosq); mosquitto_publish(mosq, NULL, "testTopic", 6, "Hello", 0, false); mosquitto_disconnect(mosq); mosquitto_loop_stop(mosq, false); mosquitto_destroy(mosq); mosquitto_lib_cleanup(); return 0; } Doesn't work, it outputs in the Broker: 1642677347: New connection from ::1:60611 on port 1883. 1642677347: New client connected from ::1:60611 as auto-92BFFD6D-3C20-0BB1-C33D-4B251C137D04 (p2, c1, k60). 1642677347: No will message specified. 1642677347: Sending CONNACK to auto-92BFFD6D-3C20-0BB1-C33D-4B251C137D04 (0, 0) 1642677347: Client auto-92BFFD6D-3C20-0BB1-C33D-4B251C137D04 closed its connection. Is there something wrong in the code or am I missing something here? (P.s. using Windows.) |
Jest Unit test case for React functional component Api call Posted: 29 Jan 2022 03:20 AM PST I am new to Jest Unit test. I need to write testcase for React functional Component, below is the code snippet for api call, useEffect(() => { getInitialData(props.id, props.baseUrl).then((response: any) => { setInitialResponse(response.initialResponse); if (props.initialData) props.initialData(response.initialResponse); setLoader(false); }); }, []); I doesn't know to cover this lines in jest testcase. Passing id and baseUrl to this component, not covering lines after 'then'. I doesn't know How can I mock this also as it is present inside useeffect...Anyone please help me here. |
Process Mining algorithm Posted: 29 Jan 2022 03:21 AM PST If I have windows usage data table like StartTime | EndTime | Window | Value that records a history of windows usage - how can we mine this data to get some repetitive patters, e.g. wnd1->wnd2->wnd3 (set of records running consistently, set of records in different patterns may vary.. ) ? What algorithm is better to use for this? Are there any implementations for Excel, Python and Delphi? |
Why use use #define in an enum block? [duplicate] Posted: 29 Jan 2022 03:20 AM PST In /usr/include/net/if.h I have found the following enum usage: enum { IFF_UP = 0x1, /* Interface is up. */ # define IFF_UP IFF_UP IFF_BROADCAST = 0x2, /* Broadcast address valid. */ # define IFF_BROADCAST IFF_BROADCAST IFF_DEBUG = 0x4, /* Turn on debugging. */ # define IFF_DEBUG IFF_DEBUG IFF_LOOPBACK = 0x8, /* Is a loopback net. */ # define IFF_LOOPBACK IFF_LOOPBACK IFF_POINTOPOINT = 0x10, /* Interface is point-to-point link. */ # define IFF_POINTOPOINT IFF_POINTOPOINT }; My questions: - What's the point in making an enumerated type without a type? So I won't be able to use them in a typesafe way.
- What's the point in making an enum variable then use its value in a #define directive with the same name in the next line?
Thank you |
Flutter - How to blend an image with a gradient colour? Posted: 29 Jan 2022 03:20 AM PST I am attempting to replicate a login screen design my designer did for an app. The background image uses a blendMode of softLight, the catch is that the colour it blends with is a gradient colour. Secondly there is actually two layers of different gradients (one purple gradient, one blue gradient) Original Image: Final Gradient Image Now I have tried using colorBlendMode, e.g. Image.asset( 'assets/pioneer-party.jpg', fit: BoxFit.cover, color: Color(0xff0d69ff).withOpacity(1.0), colorBlendMode: BlendMode.softLight, ), The problem is that the color property only takes a single colour. I then tried BoxDecoration, e.g. DecoratedBox( decoration: new BoxDecoration( color: const Color(0xff7c94b6), image: new DecorationImage( fit: BoxFit.cover, colorFilter: new ColorFilter.mode(Colors.purple.withOpacity(1.0), BlendMode.softLight), image: new NetworkImage( 'http://www.allwhitebackground.com/images/2/2582-190x190.jpg', ), ), ), ), Which still leaves me with the same problem. I then tried stacking each layer individually and then playing around with gradients to make it appear close to the design, e.g. Image.asset( 'assets/pioneer-party.jpg', fit: BoxFit.cover, color: Color(0xff0d69ff).withOpacity(1.0), colorBlendMode: BlendMode.softLight, ), DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: FractionalOffset.topCenter, end: FractionalOffset.bottomCenter, colors: [ Color(0xff0d69ff).withOpacity(0.0), Color(0xff0069ff).withOpacity(0.8), ], ), ), ), DecoratedBox( decoration: BoxDecoration( gradient: LinearGradient( begin: FractionalOffset.topLeft, end: FractionalOffset.bottomRight, colors: [ Color(0xff692eff).withOpacity(0.8), Color(0xff642cf4).withOpacity(0.8), Color(0xff602ae9).withOpacity(0.8), Color(0xff5224c8).withOpacity(0.8), Color(0xff5e29e5).withOpacity(0.8), ], stops: [0.0,0.25,0.5,0.75,1.0] ), ), ), Which gives me somewhat close to what I want, but not entirely what I need. Does anyone know of a way to achieve this? EDIT: I was also thinking about blending the two images together, but haven't found a way of doing that except using opacity or something. Ideally would like it to be rendered natively rather than using "hacks" to achieve it. |
Html preloader - delay page load Posted: 29 Jan 2022 03:21 AM PST I need some help with my new template :). Before the webpage loads I want to show a preloader gif. I done it, however it shows just a little, because the page loads very fast. So I would like to delay the page (with 2 seconds, as an exemple), without affecting the preloader, so it (the preloader) would appear for 2 seconds, so until the page loads. Here is my code (note that it will not work on jsfiddle, because I can't upload the .gif file): jsfiddle.net/hLmxpsnw/ |
No comments:
Post a Comment