Wednesday, May 19, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Insert text into Microsoft Access data base

Posted: 19 May 2021 08:15 AM PDT

I have a simple test mdb https://dropmefiles.com/tU0BG and html document https://dropmefiles.com/wezmb, I read some text between tags and then I want to insert it into my mdb column here is the code:

import pyodbc  from bs4 import BeautifulSoup    with open("10_01.htm") as fp:      soup = BeautifulSoup(fp,features="html.parser")      x = soup.find(id = 1).contents[0] # since there will only be one element with the id 1.      x = x[1:-1]      print(x)    conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb,   *.accdb)};DBQ=E:\Kursova3\ElIT_14_2020.mdb;')  c = conn.cursor()  c.execute('''            INSERT INTO tbl_articles (col_art_name_ukr)            VALUES(x)          ''')  conn.commit()  c.close()  conn.close()  

So, how can can I get the value from print(x) argumet x and Insert it into my mdb column?

How to restrict Release Deployments during office hours in Azure DevOps?

Posted: 19 May 2021 08:15 AM PDT

In Azure DevOps we only want that Release Pipelines are allowed to being manually triggered for deployment by engineers from 0:00 AM to 8:00 AM (for example) on workdays. Anything outside that timeslot needs to be disallowed, unless there is a critical issue going on, in this case the engineers should be able to ignore/exclude/omit the timeslot.

Is there a way to restrict deployments for Release Pipelines in Azure DevOps?

sum of the same words in list Python

Posted: 19 May 2021 08:14 AM PDT

For example I have a list with this words:

list=["x","x","x","x","y","y","x"]  

I need to get a numbers of x and y (in this case - five "x" and two "y", because I have to use it this integers to my next calculations. Thank you.

How do I set a hostname of a new Win10 instance being added to an AD domain using Terraform? Was working....now not working

Posted: 19 May 2021 08:14 AM PDT

I created a terraform to build a variable number of Win10 instances in an AWS VPC and used a user-data powershell script to set the domain and hostname. It worked up until a few weeks ago. Now, the domain sets properly, but the hostname won't set. I updated to 0.15.3, but continue to have the issue.

here is my terraform:

terraform {    required_providers {      aws = {        source  = "hashicorp/aws"        version = "~> 3.27"      }      ad = {        version = "0.1.0"      }    }  }    provider "aws" {    profile = "default"    region  = "us-east-1"  }    resource "aws_instance" "workstations" {    count = 4    ami           = "ami-1232345...."    instance_type = "t2.small"    key_name      = "KEYNAMEHERE"    vpc_security_group_ids = ["sg-123123123..."]    subnet_id     = "${var.subnet_prv1}"    private_ip    = "10.2.1.${count.index+110}"      user_data = <<EOF      <powershell>        Add-Computer -DomainName DOMAIN.local -NewName WORKSTATION${count.index + 110} -Credential (New-Object -TypeName PSCredential -ArgumentList "USERNAME",(ConvertTo-SecureString -String 'PASSWORD' -AsPlainText -Force)[0]) -Restart      </powershell>    EOF  

I tried it with and without quotes around the domain and hostname....still not working...

any assistance is appreciated!

kubernetes pods are terminated and restarts by CrashLoopBackOff

Posted: 19 May 2021 08:14 AM PDT

I create pod image from docker hub and the status is unavailable. Never starts and restarts with error CrashLoopBackOff:

rancher-v2.4.9 % rancher kubectl get pods -n lorawan NAME READY STATUS RESTARTS AGE lorawan 0/1 CrashLoopBackOff 6 10m cockroachdb 0/1 ContainerCreating 0 10s

please advice

Connect to hidden WiFi "network", transmit data and reconnect to original network

Posted: 19 May 2021 08:14 AM PDT

I have very little experience with non-embedded programming, so i wanted to do a sanity check before I go down this path.

Basically just need to know whether the titular line of actions are possible to do as a 1-click solution in Windows:

  • Disconnect from current WiFi Network.
  • Connect to hidden network (An ESP8266).
  • Transmit data.
  • Disconnect from hidden network.
  • Reconnect to original network, which may be any network.

I am not looking for someone to make this for me, I just need to know whether i have to change approach :)

To clarify a bit, the fans on my Lenovo Legion y530 is a pain in my backside, and there doesn't seem to be a way to fix it in software/bios. So i have decided to make a small, non-intrusive ESP8266 based board that goes between the fans and motherboard, to smooth out the changes in fan-speed, and force the fans to stay above certain speed.

My problem is, i want to be able to adjust this minimal fan speed, as well as the size of the averaging on the PWM signal from the motherboard, so i need to be able to communicate with the ESP8266, without modifying existing hardware on the laptop (and without having to take it apart).

I could go with an ESP32 and use bluetooth, but that would quadrouple the hardware cost, so rather use the 8266.

using await fetch in flask

Posted: 19 May 2021 08:14 AM PDT

I'm trying to use await fetch in JS to use a function that I created in Flask. My code for the JS is:

let dictionary = await fetch("/getName");  let user_name = await dictionary.name;  

and my code in flask is:

@app.route("/getName")  def getName():      output = {"name": ""}      print("hello")      if NAME_KEY in session:          output["name"] = session[NAME_KEY]          print(output)      return jsonify(output)  

why does this not work? to be specific to causes the website to have a 400 bad request.

Where is the dll file for the rlang package?

Posted: 19 May 2021 08:14 AM PDT

Perhaps an odd question but I've deleted the entire rlang folder in my R packages folder and am still seeing the same error message when I try and install the package via install.packages("rlang"):

The DLL version does not correspond to the package version. Please update rlang to the latest version.

I'm on Windows. I've read various threads on this topic and have followed the suggestions as far as I can - I'm using Windows on a work laptop and don't have access to the C:/ drive. My packages folder is on a drive I can access

Find the Twitter text box element with python selenium

Posted: 19 May 2021 08:14 AM PDT

I made my own Twitter complaint bot that tweets at my ISP if the network drops. Code works perfect, until it has to find the Twitter textbox to type the tweet. Main error is:

StaleElementReferenceException: Message: stale element reference: element is not attached to the page document  

I have tried:

  • Adding time delays
  • Using Firefox Driver instead of Google
  • Adding page refreshes before the tweet_at_provider() looks for the textbox
  • Clicking the "Tweet" button to bring up the textbox to then try type in it
  • Using find.element_by_id but twitter changes id every pageload

When I comment out the first function call to test, it will find and type 6/10 times. But when both functions are called the tweet_at_provider() always fails at grabbing the textbox and I get the StaleElement error.

import selenium, time, pyautogui  from selenium import webdriver  from selenium.webdriver.common.keys import Keys  from selenium.common.exceptions import ElementClickInterceptedException, NoSuchElementException, StaleElementReferenceException      PROMISED_DOWN = 200  PROMISED_UP = 10  CHROME_DRIVER_PATH = "C:\Development\chromedriver.exe"  GECKODRIVER_PATH = "C:\\Users\\meeha\\Desktop\\geckodriver\\geckodriver.exe"  TWITTER_USERNAME = "my_username"  TWITTER_PASSWORD = "my_password"      class InternetSpeedTwitterBot():        def __init__(self, driver_path):          self.driver = webdriver.Chrome(executable_path=driver_path)          self.down = 0          self.up = 0        def get_internet_speed(self):          self.driver.get("https://www.speedtest.net/")          self.driver.maximize_window()          time.sleep(2)          go = self.driver.find_element_by_xpath("//*[@id='container']/div/div[3]/div/div/div/div[2]/div[3]/div[1]/a/span[4]")          go.click()          time.sleep(40)            self.down = self.driver.find_element_by_xpath("//*[@id='container']/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[2]/div/div[2]/span")          self.up = self.driver.find_element_by_xpath("//*[@id='container']/div/div[3]/div/div/div/div[2]/div[3]/div[3]/div/div[3]/div/div/div[2]/div[1]/div[3]/div/div[2]/span")            print(f"Download Speed: {self.down.text} Mbps")          print(f"Upload Speed: {self.up.text} Mbps")          time.sleep(3)        def tweet_at_provider(self):          self.driver.get("https://twitter.com/login")          self.driver.maximize_window()          time.sleep(3)          username = self.driver.find_element_by_name("session[username_or_email]")          password = self.driver.find_element_by_name("session[password]")          username.send_keys(TWITTER_USERNAME)          password.send_keys(TWITTER_PASSWORD)          password.submit()          time.sleep(5)            tweet_compose = self.driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]/header/div/div/div/div[1]/div[3]/a/div/span/div/div/span/span')          tweet_compose.click()          time.sleep(2)          textbox = self.driver.find_element_by_xpath('//*[@id="layers"]/div[2]/div/div/div/div/div/div[2]/div[2]/div/div[3]/div/div/div/div[1]/div/div/div/div/div[2]/div[1]/div/div/div/div/div/div/div/div/div/div[1]/div/div/div/div[2]/div/div/div/div')          textbox.send_keys(f"Hey @Ask_Spectrum, why is my internet speed {self.down.text} down / {self.up.text} up when I pay for {PROMISED_DOWN} down / {PROMISED_UP} up???")      bot = InternetSpeedTwitterBot(CHROME_DRIVER_PATH)    bot.get_internet_speed()  bot.tweet_at_provider()  

How to get double nested data with gorm?

Posted: 19 May 2021 08:14 AM PDT

I am developing an application that manages quotes using go and gorm. Users create quote, quotes have multiple tags, and users can add quotes to their favorites.

I want to get a list of quotes that a user has added to their favorites. And at that time, I want to get the tag attached to the quotes.

Here is my data models.

type Quote struct {      ID            int       `gorm:"primary_key" json:"id"`      CreatedAt     time.Time `json:"created_at"`      UpdatedAt     time.Time `json:"updated_at"`      Text          string    `json:"text"`      Page          int       `json:"page"`      Published     bool      `gorm:"default:false" json:"published"`      Tags          []Tag     `gorm:"many2many:quotes_tags;" json:"tags"`      User          User      `json:"user"`      UserID        string    `json:"user_id"`      FavoriteUsers []User    `gorm:"many2many:users_quotes;" json:"favorite_users"`  }    type User struct {      ID              string    `json:"id"`      CreatedAt       time.Time `json:"created_at"`      UpdatedAt       time.Time `json:"updated_at"`      Username        string    `json:"username"`      Quotes          []Quote   `json:"quotes"`      FavoriteQuotes  []Quote   `gorm:"many2many:users_quotes;" json:"favorite_quotes"`  }    type Tag struct {      ID        int       `gorm:"primary_key" json:"id"`      CreatedAt time.Time `json:"created_at"`      Name      string    `json:"name"`  }    

I tried the following and got the favorite quote, but the tags was null. Is there a way to do this with gorm? Thank you in advance.

func (service *Service) GetUser(uid string) (models.User, error) {      fmt.Println(uid)      user := models.User{}      if result := service.db.Preload(clause.Associations).First(&user, "id = ?", uid); result.Error != nil {          return models.User{}, result.Error      }      return user, nil  }    func (service *Service) GetFavoriteQuotes(uid string) ([]models.Quote, error) {      user, err := service.GetUser(uid)      if err != nil {          return []models.Quote{}, err      }      return user.FavoriteQuotes, nil  }  

How to upload .xlsx file successfully

Posted: 19 May 2021 08:14 AM PDT

I'm trying to upload an .xlsx file using Karate and after dozens of hours spent on that.. I give up.

Given url 'http://example.com'  * multipart file file = { read: 'this:testFile.xlsx', filename: 'testFile.xlsx', contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }  * header Content-Type = 'multipart/form-data'  When method post  Then status 200  

Here is a piece of code I'm using. This is one of hundreds versions of it, but I'm putting just this one, because every time the result is the same. Uploaded file has 0 B size...

I have read and applied suggestions from all over the internet (of course including examples from Karate docs) and each and every time I have exaclty the same result - 0 byte file on the server.

In a few of threads here, I saw comments that for 'thousands' of Karate users it works, so I'm kindly asking one of you to share some real-world working example of successfull .xlsx file upload.

How can I ignore all of the rows that come before a successful login in mysql?

Posted: 19 May 2021 08:14 AM PDT

In order to block a user in my application after a certain amount of failed attempts, I'm using this query:

SELECT COUNT(user) as cant  FROM mo_bitacora  WHERE d_accion = 'failed'   and f_registro between (now() -INTERVAL 30 MINUTE) and now()   and usuario = 'user'  

This counts how many failed attempts the user has got in 30 minutes. The thing is that if the user does a successful login and then log out and then make another failed attempt, his user will be blocked. This is a pretty rare scenario but still an unwanted behavior.

How can I ignore all of the rows that come before a successful login?

Succesfull login saves in this table as a 'succesfull' on d_accion. Table binnacle has the following columns:

usuario varchar(45)   f_registro datetime   d_accion varchar(45)   d_direccion_ip varchar(45)  

Cannot handle Unhandled Promise Rejection using try-catch

Posted: 19 May 2021 08:14 AM PDT

Hi I just downloaded ytdl-core module and I am encountering a Promise Rejection which I cannot handle! Can anyone please help?

app.get("/getaudio", async (req, res) => {    const videoID = req.query.v;    const quality = req.query.q;    try {      ytdl("http://www.youtube.com/watch?v=" + videoID, {        quality: quality,        filter: "audioonly",      }).pipe(res);    } catch (e) {      res.status(500).send("Encountered Error: " + e.message);    }  });  

Here is the code I wrapped the whole thing in a try catch block but still cannot handle the Promise Rejection Any pointers is Appreciated.

Here is the stacktrace if this helps:

(node:1752) UnhandledPromiseRejectionWarning: Error: No such format found: asdasd      at Object.exports.chooseFormat (D:\Code and Other Things\YTAudioStream\node_modules\ytdl-core\lib\format-utils.js:168:11)      at downloadFromInfoCallback (D:\Code and Other Things\YTAudioStream\node_modules\ytdl-core\lib\index.js:86:26)      at D:\Code and Other Things\YTAudioStream\node_modules\ytdl-core\lib\index.js:20:5      at runMicrotasks (<anonymous>)      at processTicksAndRejections (internal/process/task_queues.js:97:5)  

I know I provided an invalid quality param and that is intentional, I want to handle this rejection in my code

I'm trying understand some code and how it works but when it runs nothing shows up

Posted: 19 May 2021 08:14 AM PDT

here is the code in question. I have been trying to figure this out to no progress if anyone has even a slight clue about what I should do please let me know.

#include<iostream>  #include<cstdio>  #include<algorithm>  using namespace std;  int main()  {      int t, n, y, r;      scanf("%d", &t);      while (t--)      {          scanf("%d %d %d", &n, &y, &r);          if (((y + r) % 2 == 0) || (r == 30 && (y == 9 || y == 11)))              cout << "YES" << '\n';          else              cout << "NO" << '\n';      }      return 0;  }  

append column values to row pandas

Posted: 19 May 2021 08:13 AM PDT

df = pd.DataFrame()  df['col1'] = ('y','y','y')  df['col2'] = ('a','b','c')  df['col3'] = ('x','x','x')  print df  

I have this df and am trying to copy or move the b,c to new columns in row one. I've tried pivot_table, pd.groupby, and for index, row in top.iterrows():

But there may not always be three rows in the df. So if there aren't any rows then don't do anything.

This has been my last attempt. I don't remember exactly what I tried with .groupby or pivot_table

for index, row in df.iterrows():      df1['col2'+row] = df1['col2'][row]      top_comb = top_comb.append(top)    
Col1 | Col2 | Col3 | Col21 | Col22    y   |   a  |  x   |  b    |   c    

Triple dot CSS animation on a loading screen

Posted: 19 May 2021 08:14 AM PDT

I have a simple loading screen where I would like to have one dot appear at a time at the end of the text.

Unfortunately I can only get them to blink, when I would like for one to appear at a time and then start over.

I am currently using a fade in animation that looks like the following:

@keyframes fadeIn {      0% { opacity: 0 }      100% { opacity: 1 }  }  

Here is a sample of what I have:

const App = () => {      return (    <h1>      Loading<span>.</span><span>.</span><span>.</span>    </h1>    )  }      ReactDOM.render(      <App />,      document.getElementById('app')  );
@keyframes fadeIn {      0% { opacity: 0 }      100% { opacity: 1 }  }    span:nth-child(1) {    opacity: 0;    animation: fadeIn 500ms infinite;  }  span:nth-child(2) {    opacity: 0;    animation: fadeIn 500ms infinite;    animation-delay: 500ms;  }  span:nth-child(3) {    opacity: 0;    animation: fadeIn 500ms infinite;    animation-delay: 1000ms;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>  <div id="app"></div>

As you can see, currently, it does show one at a time, but then just has all three of them blinking. How could I make them show one at a time, and then start over?

Thanks!

How to determine the best number of threads for I/O in an application

Posted: 19 May 2021 08:14 AM PDT

I'm writing an application that will run on a Windows Server with 6 cores.

Big picture -- 10,000 users attempting to access the same files on a disk with read/write operations.

10,000 users are queued into a certain number of "Access Threads". These access threads are queued into a single "Disk Access" thread.

Besides a WAG - how to determine what a "good" number (X) of "Access Thread" should be used?

I stated that the computer has 6 cores but I'm not sure that would impact the number since the whole application is 80% disk access and 20% data processing.

What are the potential trade-offs I should consider to implement 10,000 to one --- OR ---- 10,000 to X to one -- and if the later is true what should X be?

I'm using C++ as the language.

Thanks for any insight.

Several comments about overlapped IO I should clarify on. The application is NOT centered on single disk access (as IO) but one acquiring data from multiple disk files - process that data (differently for each "Access Thread" and returning a "package" of resultant data. I'm sorry I did not clarify this as the comments appear to be treating "Disk Access" as the main question

Flask - CGI - need to fix issues with htaccess

Posted: 19 May 2021 08:14 AM PDT

So I have successfully deployed a Flask app using CGI. In order to get the app working, my .htaccess file had to look like this:

RewriteEngine On  RewriteCond %{REQUEST_FILENAME} !-f  RewriteRule ^(.*)$ /home/user/public_html/mysite/cgi-bin/main.cgi/$1 [L]  

However, I am facing a couple of issues.

  1. mysite.com works, but when I link other pages to the home page, it takes them to mysite.com/cgi-bin/main.cgi. I'd like for the links to take users to mysite.com. Similarly, when I try to link to another page, it goes to mysite.com/cgi-bin/main.cgi/page2, when I actually want it to be mysite.com/page2. How can I fix this?

  2. The following .htaccess content seems to not work:

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]  RewriteRule ^(.*)$ http://%1/$1 [R=301,L]  RewriteCond %{HTTPS} !=on  RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]  Header always set Content-Security-Policy "upgrade-insecure-requests;"  

I'm not sure if the above two issues are related, but I'd like to fix both.

Google Sheets keep max value constant

Posted: 19 May 2021 08:14 AM PDT

Refer the sheet in the figure enter image description here

For the H column, I want Hj = Gj+MAX(F)-Fj , where j = row number.
The given formula works for the second row, but when I drag to other rows, MAX value also changes. I want MAX(F2:F8) to be constant and other values to change. How can I do that?

POST method problem in php in trying to create CRUD

Posted: 19 May 2021 08:14 AM PDT

I'm trying to create a CRUD data grid with php it is very simple but facing a problem with POST method every time I refresh my page it enters my previous data. Im trying to learn php i have basic knowledge of different languages like c# and java. Kindly answer me as soon as possible.

here is my code :

home.php :

<!DOCTYPE html>  <html lang="en">    <head>    <title>PHP CRUD</title>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width, initial-scale=1">    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>  </head>    <body>      <?php require_once 'process.php'; ?>      <?php        $mysqli = new mysqli('localhost','root','','crud')or die(mysql_error($mysqli));        $result= $mysqli->query("SELECT * FROM data")or die($mysqli->error);        ?>        <div class="row justify-content-center">        <table class="table">          <thead>            <tr>              <th>Name</th>              <th>Location</th>              <th colspan="2">Action</th>            </tr>          </thead>          <?php while ($row = $result->fetch_assoc()): ?>          <tr>            <td>              <?php echo $row['name'] ?>            </td>            <td>              <?php echo $row['location'] ?>            </td>            <td></td>          </tr>          <?php endwhile; ?>        </table>      </div>          <div class="container">        <div class="row justify-content-center">            <form action="process.php" method="GET">              <div class="form-group">                <label>Name</label>              <input type="text" name="name" class="form-control" value="Enter your name">              </div>              <div class="form-group">                <label>Location</label>              <input type="text" name="location" class="form-control" value="Enter Your Location">              </div>              <div class="form-group">                <button type="submit" name="save" class="btn btn-primary">Save</button>              </div>              </form>          </div>      </div>        </body>    </html>

This the the process.php :

<?php    $mysqli = new mysqli('localhost','root','','crud') or die(mysql_error($mysqli));    if(isset($_GET['save']))  {      $name=$_GET['name'];      $location=$_GET['location'];      $mysqli->query("INSERT INTO data (name,location) VALUES ('$name','$location')") or die($mysqli->error);  }    ?>  

Javascript file blocked by a corporate firewall

Posted: 19 May 2021 08:14 AM PDT

We have a site where we're using zxcvbn by Dropbox to inform users of their password strength, however, we've been getting occasional reports that it doesn't work.

Turns out that these users (reasonably rare) are accessing our website from their workplace which has a strict corporate firewall policy, because the js file contains swearwords and NSFW words (to mark the password as insecure if it contains these commonly used words), the whole JS file is being blocked from loading.

The rest of our site loads fine, including other JS files.

How could we encrypt or minify this js file to a point where it didn't get blocked for having "bad" words in the request, but be successfully decrypted at the client side to actually do it's job and detect unsafe passwords?

This JS Fiddle will (sort of) demonstrate the problem: https://jsfiddle.net/0cgap96m/3/

<script src="https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.4.2/zxcvbn.js" integrity="sha512-TZlMGFY9xKj38t/5m2FzJ+RM/aD5alMHDe26p0mYUMoCF5G7ibfHUQILq0qQPV3wlsnCwL+TPRNK4vIWGLOkUQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>    <div id="test">    </div>  
window.onload = function(){      var name = prompt("Put in a fake password to test?");          var passwordStrength = zxcvbn(name);        document.getElementById('test').innerHTML = JSON.stringify(passwordStrength);  };  

That should work fine normally - now try blocking https://cdnjs.cloudflare.com/ajax/libs/zxcvbn/4.4.2/zxcvbn.js using an adblocker or something, and it'll obviously start failing. This is essentially what's happening for the users, but it's blocked by their corporate firewall rather than a local adblocker.

How to get params and query params from url in angular 9

Posted: 19 May 2021 08:14 AM PDT

I have a url , I want to get params and queryparams both and each request parameter should be separated out using '&' except first one.First one will be separated by '?' For Ex Request URL:abc.com/abc:abc:abc:0xa35df9cdf?ab=1234567?lang=en I should get in variable let result = abc:abc:abc:0xa35df9cdf?ab=1234567&lang=en , I have used this, but I need in a single variable and also dynamic, my query param can be multiple

app.component.ts

import { Component,OnInit,ActivatedRoute } from '@angular/core';    @Component({    selector: 'my-app',    templateUrl: './app.component.html',    styleUrls: [ './app.component.css' ]  })  export class AppComponent  {    name = 'Angular';  constructor(route: ActivatedRoute) {}        ngOnInit() {      this.route.params.subscribe((param: any) => { console.log(param) })  this.route.queryParams.subscribe((param: any) => { console.log(param) })  }  }  

How to debounce ajax requests in typeahead.js

Posted: 19 May 2021 08:14 AM PDT

I am using twitter typeahead library to implement searching functionality.

I found the approach of sending POST request through ajax in typeahead.

Problem is: It is firing requests for every word I type no matter how fast or slow and on backspaces too.

Here is my code snippet:

$('.typeahead').typeahead({      hint: true,      highlight: true,      minLength: 2,  }, {      source: function (query, process) {          return $.ajax({                  url: "Somedomain" + "post/api/skills",                  type: 'post',                  data: { query: query, limit: 15 },                  dataType: 'json',                  success: function (result) {                      console.log(result);                      var resultList = result.skills.map(function (item) {                          var aItem = { value: item };                          return aItem;                      });                        process(resultList);                      return;                  }              });      },      displayKey: 'value',  });  

I tried:

Using lodash library's debounce in source like this, but it is not sending any ajax requests.

Code snippet:

function debounceIt(query, process) {      return $.ajax({                  url: "Somedomain" + "post/api/skills",                  type: 'post',                  data: { query: query, limit: 15 },                  dataType: 'json',                  success: function (result) {                      console.log(result);                      var resultList = result.skills.map(function (item) {                          var aItem = { value: item };                          return aItem;                      });                        process(resultList);                      return;                  }              });  }    $('.typeahead').typeahead({      hint: true,      highlight: true,      minLength: 1,  }, {      source: function (query, process) {          _.debounce(function () {               debounceIt(query, process);          }, 300);      },      displayKey: 'value',  });  

Can anyone help how to solve this? I tried seeing similar posts on stack overflow but couldn't find any solution.

Openpyxl copy and paste as values in new workbook

Posted: 19 May 2021 08:14 AM PDT

I am trying to copy the first 100 rows in a source file to a new destination file with openpyxl. My source file has formulas, but I want to copy and paste as values in the new workbook. When I add data_only=True, (see code below), it copies only the values of my source sheet and therefore not the data in the formula cells - these are just empty in the destination file. How do I copy everything and paste as values in the destination sheet?

WB1 = load_workbook("sample_book.xlsx")  WB1_WS1 = WB1["Ark2"]  WB2 = Workbook()    #Create new worksheet in new workbook  for i in range(1,2):      WB2.create_sheet(f"WS{i}")        #Delete first sheet  WB2.remove(WB2.worksheets[0])    #Define the ranges and sheets   copy_ranges = [100]  copy_to_sheets = ["WS1"]    # Copy the values from the rows in WB1 to WB2  for i in range (len(copy_ranges, data_only=True)):      #Set the sheet to compy to      ws = WB2[copy_to_sheets[i]]      #initialize row offset       offset = 1      for s in range (i):          offset+=copy_ranges[s]                #copy the row and append       for j in range(offset, offset + copy_ranges[i]):          #if j==0:          #  continue           for row in WB1_WS1.iter_rows(min_row=j,max_row=j,min_col=1,max_col=WB1_WS1.max_column):              values_row = [cell.value for cell in row]          ws.append(values_row)    #save  WB2.save("WB2.xlsx")  

Laravel Eloquent - querying Transactions on the bases of months

Posted: 19 May 2021 08:14 AM PDT

I have a transaction table in which I have a date on which a transaction occurred. Date is stored as "04-24-2021" as "m-d-Y" format. I want to get transactions occurring in every month from the latest to oldest transaction. For example, if the latest transaction occurred in '04-24-2021' and the oldest occurred in '02-04-2020' then I want to get transactions grouped by months from 04-2021 to 04-2020. What is the best way to do so?

How can I install a pecl extension like mcrypt in DDEV-Local's web container?

Posted: 19 May 2021 08:14 AM PDT

In PHP 7.2 and higher the mcrypt extension is no longer available, but my project depends on it. I know that the project shouldn't be using something as ancient as mcrypt, but I don't have any say in this. I know that mcrypt was removed from PHP7.2+ but is still in pecl.

What can I do for this project to support php-mcrypt in 7.2 and higher?

How to store data from Google Ngram API?

Posted: 19 May 2021 08:14 AM PDT

I need to store the data presented in the graphs on the Google Ngram website. For example, I want to store the occurences of "it's" as a percentage from 1800-2008, as presented in the following link: https://books.google.com/ngrams/graph?content=it%27s&year_start=1800&year_end=2008&corpus=0&smoothing=3&share=&direct_url=t1%3B%2Cit%27s%3B%2Cc0.

The data I want is the data you're able to scroll over on the graph. How can I extract this for about 140 different terms (e.g. "it's", "they're", "she's", etc.)?

Why is composer not using my repository fork for a package?

Posted: 19 May 2021 08:14 AM PDT

I followed information on the internet and this post (Change Composer git source for a package) but am still having no luck getting composer to use my fork of the repository. What is wrong here?

{  "name": "sociablegroup/reeb",  "repositories": [    {      "type": "vcs",      "url": "https://github.com/michael-bender/laravel-doctrine.git"    }  ],  "require": {      "laravel/framework": "5.0.*",      "beatswitch/lock": "0.1.*",      "beatswitch/lock-laravel": "0.2.*",      "laravel/socialite": "~2.0",      "league/tactician": "0.5.*",      "doctrine/migrations":"@dev",      "atrauzzi/laravel-doctrine": "dev-master"  },  "require-dev": {      "phpunit/phpunit": "~4.0",      "phpspec/phpspec": "~2.1",      "laracasts/generators": "~1.1"  },  "autoload": {      "classmap": [          "database"      ],      "psr-4": {          "App\\": "app/"      }  },  "autoload-dev": {      "classmap": [          "tests/TestCase.php"      ]  },  "scripts": {      "post-install-cmd": [          "php artisan clear-compiled",          "php artisan optimize"      ],      "post-update-cmd": [          "php artisan clear-compiled",          "php artisan optimize"      ]  },  "config": {      "preferred-install": "dist"  }  }  

I've tried using the SSH url instead of HTTPS. I've tried with --prefer-source. I just can't seem to get it to pull in from my repo.

Word wrapping in phpstorm

Posted: 19 May 2021 08:14 AM PDT

How can I enable Word wraping in phpstorm? I need to enable it only for some of my files (with extension .txt). Is is possible?

Exceeding Max Char Limit in Excel

Posted: 19 May 2021 08:14 AM PDT

How do I use more than 255 characters in Excel's CONCATENATE function? I am actually also using the CONCATENATE function within the HYPERLINK function in EXCEL. An example looks like this:

=HYPERLINK(CONCATENATE("http://www.google/com/morethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255charsmorethan255chars","morethan255chars morethan255charsmorethan255charsmorethan255charsmorethan25"),"link");  

UPDATE: It's not issue with CONCATENATE function, but an issue with the first parameter of the HYPERLINK function. Using a string longer than 255 characters directly/indirectly (ex: =HYPERLINK(K204,"link") where K204 contains the 256-character length link) fails the HYPERLINK function

I realize that I can use a URL shortener, but I am doing this for ALOT of links which would require ALOT of manual use of the URL shortener.

No comments:

Post a Comment