Wednesday, November 17, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


ABI is incomplete for contract written in "Solidity Multiple files format", e.g. 0xedfcb78e73f7ba6ad2d829bf5d462a0924da28ed

Posted: 17 Nov 2021 09:53 AM PST

For this contract https://bscscan.com/address/0xedfcb78e73f7ba6ad2d829bf5d462a0924da28ed#code There are eight source files which are known as "Solidity Multiple files format"

However neither the bscscan website: https://bscscan.com/address/0xedfcb78e73f7ba6ad2d829bf5d462a0924da28ed#code nor the bscscan API: https://api.bscscan.com/api?module=contract&action=getabi&address=0xedfcb78e73f7ba6ad2d829bf5d462a0924da28ed can get full ABI.

They only provide the ABI for the first source file.

How do I get the full and functional ABI to interact with?

In a CSRF attack scenario, who is sending the request? The client browser or the server?

Posted: 17 Nov 2021 09:53 AM PST

I do understand CSRF attacks theoretically and practically, but there is just a little detail which I can't find the answer to, which is frustrating.

Let's assume this classic CSRF attack scenario :

  1. An attacker host a malicious script on a website supposed to make an authenticated user change his email address on a website called "A".
  2. A victim executes this malicious script, which makes him changing his email address without knowing it on the website "A", assuming the victim is connected to the website at that moment.

Now my questions are simple:

  • "Who" is actually making the HTTP request to the website "A": The client browser, or the malicious server? Or both? I would say definitely the client browser only, but I would like to be 100% sure.
  • If an admin would look at the logs of the web server for that particular request, what would he/she sees as the source of this request: The IP address of the victim or the IP address of the malicious website? Or both?
  • Would he/she be able by any way to trace back to the malicious server, or would he/she only see the victim as the source of this request ?

I've already searched this question on stakoverflow and didn't find it, so I hope I'm not creating a duplicate.

Cannot upgrade heroku stack from bamboo-mri-1.9.2 to heroku-20

Posted: 17 Nov 2021 09:53 AM PST

I have an old neglected Heroku stack (bamboo-mri-1.9.2) that I now want to upgrade to Heroku-20. I know bamboo-mri-1.9.2 has long ago stopped being supported, but when I attempt to upgrade via the CLI I get this:

heroku stack:set heroku-20 -a my_app  Setting stack to heroku-20... !   ▸    this stack migration path is not available.    

Via the Heroku dashboard gets a similar result.

I cannot find anything within Heroku or on Google to help - what do I need to do here?

Pager for query with many relations and fields

Posted: 17 Nov 2021 09:53 AM PST

I have a quite complex view with two queries, one select users with related data and another one select orders with related data. Both of them have some filters, but now I have an issue and I am looking for proper and just decent solution, with good performance because I have a lot of data and relationships in the queries. Assume I have:

Query 1 - Select user data, some left joins to other tables, conditions depends on provided parameters.

Query 2 - Select orders depends on users from Query 1, many joins, conditions depends on parameters.

I display data from two queries in one view, users, their data, orders, and some orders data and now I want to implement pager, but it has to work and display proper number of users depends on filters form Query 1 and Query 2. So there is an issue that I can't really limit from any query cuz another one has filters as well so maybe those users maybe aren't really selected to display depends on other query filters. So I guess there are two ways, one is to put those queries in loop and collect data until I get proper number of results depends on query. Another way is to merge those two queries into one, but there an issue that I get many rows per user, so I can't set any page limit and get results only for specific number of users, like for example 30. Because results will be like user 1 => order 1, user 1 => order 2, so is there any way to get specific number of unique results depends on user id or something. Let me know if you have any questions.

Return specific type in generic method depending on enum value without Reflection or dynamic during runtime

Posted: 17 Nov 2021 09:53 AM PST

I have a non-generic IList which i would like to cast depending on an enum value during runtime.

I can not change the type of the non-generic IList in the implementation, because it is library code.

Also i do not want to use Reflection (because it is slow) or the dynamic keyword (because it is unsafe and could lead to mistakes down the road).

In the Library Code there is following class:

public class ListView //THIS IS LIBRARY CODE AND CAN NOT BE CHANGED  {    public IList itemsSource { get; set; }  }  

Then in my CustomListView class which inherits from ListView i want to cast the itemsSource to the appropiate class depending on ItemType.

Another limitation is that CustomListView can not be generic (dictated by the library we use)

public class CustomListView : ListView  {      public dynamic GetItems()      {          switch (ItemType)          {              case ItemType.A:                return itemsSource.Cast<A>().ToList();              case ItemType.B:                return itemsSource.Cast<B>().ToList();              default:                throw new InvalidOperationException("Not supported");          }      }  }  

But i want it to directly return the correct type instead of using dynamic.

Something like (the code below does not work!):

public IList<T> GetItems(ItemType itemType) //The type of T should change depending on what i return  {      switch (ItemType)      {          case ItemType.A:            return itemsSource.Cast<A>().ToList();          case ItemType.B:            return itemsSource.Cast<B>().ToList();          default:            throw new InvalidOperationException("Not supported");      }  }  

How would i implement that?

http server respnd with an output from an async function

Posted: 17 Nov 2021 09:53 AM PST

I want my http respond script to respond with data from my SQL server. So I can use AJAX to update HTML with data from my SQL server. And I cant find a way to do this. I'm just learning about async and I have a feeling that if I can save the output of my async function to a global var then it will work. Any help would save my headache.

My simple Listen script is:

var test = "hello!"    var http = require('http');  http.createServer(function (req, res) {    res.writeHead(200, {'Content-Type': 'text/plain'});    res.write(test);    res.end();  }).listen(8080);   

and my sql code is:

const util = require('util');  var mysql = require('mysql');    var con = mysql.createConnection({      host: "XXXXX",      user: "XXXXX",      password: "XXXXX",      database: "XXX"    });    var DBresult=null;    function getdb(){    const query = util.promisify(con.query).bind(con);    (async () => {      try {        const rows = await query('SELECT * FROM mylist');        DBresult=rows;             } finally {        con.end();      }    })()  }    

Split payload from JSON String

Posted: 17 Nov 2021 09:53 AM PST

I receive these huge Strings via WebSocket:

[    "BTC-31DEC21-100000-P",    "{\"data\":{\"bids\":{\"0.01\":{\"price\":0.01,\"volume\":66.2,\"exchange\":\"DER\"},\"5.0E-4\":{\"price\":5.0E-4,\"volume\":1.1,\"exchange\":\"DER\"},\"0.637\":{\"price\":0.637,\"volume\":8.4,\"exchange\":\"DER\"}},\"asks\":{\"0.664\":{\"price\":0.664,\"volume\":8.4,\"exchange\":\"DER\"}}},\"isMasterFrame\":true}"  ]  

or

[    "BTC-31DEC21-36000-C",    "{\"data\":[{\"price\":0.422,\"volume\":8.4,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"  ]  

or

[    "BTC-31DEC21-60000-P",    "{\"data\":[{\"price\":0.105,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1055,\"volume\":28.7,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.106,\"volume\":7.6,\"exchange\":\"DER\",\"side\":\"ASKS\"},{\"price\":0.1065,\"volume\":43.0,\"exchange\":\"DER\",\"side\":\"ASKS\"}],\"isMasterFrame\":false}"  ]  

I want to make a check isMasterFrame

let payload = JSON.parse(messageString[1]);    if (payload.hasOwnProperty("isMasterFrame")) {   for (let i = 0; i < payload.pairs.length; i++) {     let currentPair = payload.data[i]        currentPair = currentPair.replace(/\0/g, ''); //Remove null chars         if (currentPair.toUpperCase() != 'KILL') {             props.onAddAvailablePair(currentPair);          }         }        } else {               // print some output with payload which holds "isMasterFrame":false       }  

When I run the code I get error:

TypeError: Cannot read properties of undefined (reading 'length')  

Data from one inner pair: {\"price\":0.423,\"volume\":0.0,\"exchange\":\"DER\",\"side\":\"ASKS\"} should be split and inserted into the loop one by one

Do you know how I can fix this issue?

Get values from dynamic object array

Posted: 17 Nov 2021 09:53 AM PST

Hello In Javascript I get error result from API result array object can be

{     ProjectName:["Invalid Project Name"],     entityName:["Invalid entityName"]    }  

or

{     ProjectName:["Invalid Project Name"],        }  

and key names are dynamic which comes from API. so I just need values as

["Invalid Project Name","Invalid entityName"]  

How can I convert this object to this array ?

Thanks in advance

Detecting if the system time doesn't correspond to system timezone [Javascript]

Posted: 17 Nov 2021 09:52 AM PST

I have a particular system configuration where my timezone is setted at (UTC-03:00) but I configured the system time to an hour after (e.g: Originally my time using the timezone must be 14:41, but I updated to 15:41).

What I want to know if there is a way using any library to know that the time is not correlated with the timezone.

Other solution could be to resolve the time using moment or other library returning the time using the system timezone and not the system time.

I tired using Date or moment with moment-timezone with no luck.

E.g:

System Time: 15:46 (+1 Hour configured manually)

Timezone Time: 14:46 (This should be the hour if isn't updated)

moment()  //result Wed Nov 17 2021 15:46:19 GMT-0300  

What I want is

moment().someFunc()  //result Wed Nov 17 2021 14:46:19 GMT-0300  // Could be a function, property, just a difference to use it.  

How do I solve it?

Posted: 17 Nov 2021 09:52 AM PST

I am currently trying to solve a problem involving lists and sorting (i.e.) when a list (not a normal one ,but a list of tuple ) is entered ; the program should print out the list but in an orderly(increasing order) manner based on the 2nd elements of each tuples. ex: Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)] Here is what I have tried until now:

def sorting(L):  le=len(L)  G=[]  Lnew=[list(l) for l in L]  for i in range(le):      G.append(Lnew[i][1])      G.sort()      Lnew.remove(Lnew[i][1]) #where the problem is      for k in range(len(G)):          Lnew[k][1]=G[k]          for elt in Lnew:              tuple(elt)  return L  

An error displays "list.remove(x): x not in list" . how do I proceed in that case? or is there a simpler way to tackle the problem ?

How can I display images from my Django DB?

Posted: 17 Nov 2021 09:52 AM PST

Currently, although it may not be best practice, I have images stored in my django database and want to fetch them to display in a gallery page. However, I cannot get the image to display at all, which I think is because it does not arrive at the correct path.

 <img src ="{% static 'img/' object.image %}">  

This code is to try and arrive at the correct directory for the uploaded image which is

\AFA\src\artForAll\static\img  

Also object.image comes from this model

class GalleryPost(models.Model):      title       = models.CharField(max_length=120)      description = models.TextField(blank =True, null=True)      artist      = models.CharField(max_length=120)      featured    = models.BooleanField(default= False)      image       = models.ImageField(null = True, blank = True, upload_to = "static/img/")  

All of the other fields here work and I can see that the image is being uploaded to the correct place.

Python | Writing on csv file with extra spacings

Posted: 17 Nov 2021 09:52 AM PST

I'm generating numbers with 21 characters, I want to write each number generated on a csv file.

The output has spaces between each character of every number so instead of "001657618586303086816" I have "0 0 1 6 5 ... 1 6".

Here is my code:

def generate_numbers(n):      f=open("data.csv","a",newline='')      writer=csv.writer(f,delimiter=' ')        for i in range(n):          numb='0016' + str(randint(111111111111111,999999999999999)) + '16'                writer.writerow(nib)            f.close()  

Thank you

Errors on C# animator code, cant find the class?

Posted: 17 Nov 2021 09:52 AM PST

I am new to Unity and I am trying to make code where if someone is hit then a animator is used but it does not work.

using System.Collections.Generic;  using UnityEngine;  using UnityEngine.  public class VelociraptorScript : MonoBehaviour  {      public Animator anim;             //Used to check if the target has been hit                 public bool isHit = false;      /*      [Header("Audio")]      public AudioClip DinoDeath;          */     // public AudioSource audioSource;         // Update is called once per frame      void Update()      {          if (isHit == true)          {              anim = GetComponent<Animator>();              //Animate the target Velo Death              anim.Play("Velociraptor_Death",0,0);             //Play audio             // audioSource.GetComponent<AudioSource>().clip = DinoDeath;              //audioSource.Play();                           }      }  }  

sorry for the bunch of comments

I get these errors in Unity

Assets\VelociraptorScript.cs(4,19): error CS1002: Identifier expected

Assets\VelociraptorScript.cs(4,19): error CS1002: ; expected

Assets\VelociraptorScript.cs(7,25): error CS1002: ; expected

Can someone help me out with these errors? Thanks!

How to correclty place labels in piechart using ggplot?

Posted: 17 Nov 2021 09:53 AM PST

reprex:

library(tidyverse)  library(ggrepel)    tibble(    n = c(1, 1, 1, 2, 50, 46),    label = paste0(c(1, 1, 1, 2, 50, 46), "%")) %>%     ggplot(aes(x = "", y = n)) +    geom_bar(width = 1, stat = "identity") +    geom_text(aes(x = 1.6, label = label),              position = position_stack(vjust = 0.5)) +    coord_polar("y")    

result (undesired overlaps):

enter image description here

desired output:

enter image description here

enter image description here

I tried ggrepel but result is not desired.

tibble(    n = c(1, 1, 1, 2, 50, 46),    label = paste0(c(1, 1, 1, 2, 50, 46), "%")) %>%     ggplot(aes(x = "", y = n)) +    geom_bar(width = 1, stat = "identity") +    ggrepel::geom_text_repel(aes(x = 1.6, label = label),              position = position_stack(vjust = 0.5)) +    coord_polar("y")    

result (I don't know how to add lines or arrows).

enter image description here

Rules to realtime database

Posted: 17 Nov 2021 09:53 AM PST

I use Firebase, to be precise a real-time database, and I don't know what rules should I set. I set these rules:

{    "rules": {          ".read": "data.child('Users').child(auth.uid).exists()",          ".write": true    }  }  

but now everybody can write. When I set these:

{    "rules": {          ".read": "data.child('Users').child(auth.uid).exists()",          ".write": "auth != null"    }  }  

users using Gmail cannot log in because record in the database isn't created. This is my code responsible for creating user:

fAuth.createUserWithEmailAndPassword(reg_email, reg_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {      @Override      public void onComplete(@NonNull Task<AuthResult> task) {          if (task.isSuccessful()) {          fAuth.getCurrentUser().sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {                  @Override                  public void onComplete(@NonNull Task<Void> task) {                      if (task.isSuccessful()) {                          userID = fAuth.getCurrentUser().getUid();                          reg_user = new User(reg_email, sex, btn_text, 0, 0);                          databaseReference.child(userID).setValue(reg_user);                          Intent intent = new Intent(getApplicationContext(), LoginActivity.class);                          startActivity(intent);                          finish();                          FirebaseAuth.getInstance().signOut();                      } else {                          Toast.makeText(RegisterActivity.this, "Error " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();                          progressBar.setVisibility(View.INVISIBLE);                      }                  }              });          } else {              Toast.makeText(RegisterActivity.this, "Error " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();              progressBar.setVisibility(View.INVISIBLE);          }      }  });  

Aggregate function not adding new column MongoDB

Posted: 17 Nov 2021 09:53 AM PST

When I execute below column it is giving results as column is added , but when I query the table, new column is not showing up.

db.getCollection("arcm_qc").aggregate([   {          $addFields: {              MGE_ID: { $arrayElemAt: [{ "$split": ["$MCA Go", "-"] }, 0] }            }      }    ])  

Error: The uri `parameter to` open Uri()`must be a string got "undefined ".Make sure the first parameter to` mongoose.connect() is a string

Posted: 17 Nov 2021 09:52 AM PST

I am working on webchat app

const express = require("express");  const connectDB = require("./config/db");  const dotenv = require("dotenv");     const userRoutes = require("./routes/user Routes");  const chat Routes = require("./routes/chat Routes");  const message Routes = require("./routes/messageRoutes");  const { notFound, errorHandler } = require("./middleware/errorMiddleware");  const path = require("path");    dotenv.config();  connectDB();  const app = express();    app.use(express.json()); // to accept json data`     });  

I am trying to resolve it but it did not happen please can anyone resolve it

order details customer formatting [closed]

Posted: 17 Nov 2021 09:53 AM PST

needs_shipping_address(); ?>
<?php if ( $show_shipping ) : ?>    <section class="woocommerce-columns woocommerce-columns--2 woocommerce-columns--addresses col2-set addresses">      <div class="woocommerce-column woocommerce-column--2 woocommerce-column--billing-address col-2">    <?php endif; ?>    <h3 class="woocommerce-column__title"><?php esc_html_e( 'Billing address', 'woocommerce' ); ?></h3>    <address>      <?php echo wp_kses_post( $order->get_formatted_billing_address( esc_html__( 'N/A', 'woocommerce' ) ) ); ?>        <?php if ( $order->get_billing_phone() ) : ?>          <p class="woocommerce-customer-details--phone"><?php echo esc_html( $order->get_billing_phone() ); ?></p>      <?php endif; ?>        <?php if ( $order->get_billing_email() ) : ?>          <p class="woocommerce-customer-details--email"><?php echo esc_html( $order->get_billing_email() ); ?></p>      <?php endif; ?>  </address>    <?php if ( $show_shipping ) : ?>        </div><!-- /.col-2 -->        <div class="woocommerce-column woocommerce-column--2 woocommerce-column--shipping-address col-2">          <h3 class="woocommerce-column__title"><?php esc_html_e( 'Shipping address', 'woocommerce' ); ?></h3>          <address>              <?php echo wp_kses_post( $order->get_formatted_shipping_address( esc_html__( 'N/A', 'woocommerce' ) ) ); ?>                <?php if ( $order->get_shipping_phone() ) : ?>                  <p class="woocommerce-customer-details--phone"><?php echo esc_html( $order->get_shipping_phone() ); ?></p>              <?php endif; ?>          </address>      </div><!-- /.col-2 -->    </section><!-- /.col2-set -->    <?php endif; ?>    <?php do_action( 'woocommerce_order_details_after_customer_details', $order ); ?>  

i want to make the billing address and shipping address side by side and the format of the text horizontally not vertical. I need help here, cause i'm trying so hard, but i couldn't find out how.

this are the screenshoot of my order-details-customer page

Searching for an item in a list that's nested inside another list based on a property value in C# using LINQ?

Posted: 17 Nov 2021 09:53 AM PST

Is there a way to search for an item in a list that's nested inside another list based on a property value using LINQ?

Given the follow models below, for a given Order (variable customerOrder), I want to return the earliest order date (Date) where the Day is "Sunday".

models:

public class Order  {      public int Id { get; set; }      public List<OrderLine> OrderLines { get; set; }  }    public class OrderLine  {      public string Description { get; set; }      public List<OrderDate> OrderDates { get; set; }  }    public class OrderDate  {      public DateTime Date { get; set; }      public string Day { get; set; }  }  

code:

var dates = new List<DateTime>();  foreach(var a in customerOrder.OrderLines)  {      var orderDate = a.OrderDates.Where(x => x.DateTypeId.Equals("Sunday")).FirstOrDefault();      dates.Add(orderDate.ActualDate);  }  dates.OrderBy(d => d.Date);    return dates.FirstOrDefault();  

Select columns of specific types and manipulate their content

Posted: 17 Nov 2021 09:53 AM PST

here it is my problem in the form of a reproducible example and my partial attempt of solution

# input  mydf_in<-data.frame(a=letters[6:10],                    b=c("<0.5","2","<0.5", "9", "10"),                    c=1:5,                    d=6:10,                    e=c("<0.8","12","<0.8", "<0.8", "<0.8"))    mydf_in    # output   # the desired final result    mydf_out<-data.frame(a=letters[6:10],                       b=c(0.5,2,0.5,9,10),                       b_flag=c(1,0,1,0,0),                       c=1:5,                        d=6:10,                        e=c(0.8,12,0.8,0.8,0.8),                       e_flag=c(1,0,1,1,1)                       )    mydf_out    library(tidyverse)    mydf_in %>%    select(where(~ is.character(.x) &                    any(str_detect(.x, "<")                       )                 )           ) %>%        # in between here is missing the creation and    # the population of the flagging columns, i.e. "b_flag" and "e_flag"        mutate(across(everything(), ~ as.numeric(str_replace(.x, "<", ""))))  

in short, what is missing in the between of the above code snippet, for each selected column:

  • create a corresponding flagging column
  • populate the rows of the flagging column with 1 or 0 depending on the presence of the sign "<" (see desired output)

C# Regex Replace on alphanumeric and all special characters

Posted: 17 Nov 2021 09:52 AM PST

I'm looking for a regex which can ignore any characters which are not alphanumeric or a special character. I am interested in not hard-coding a list of special characters.

Oracle - Filter JSON array while using json_objectagg

Posted: 17 Nov 2021 09:53 AM PST

In my PL/SQL code I'm receiving a JSON array:

[     {"name": "Tony", " age": "20", "city": "Bigville"},     {"name": "Lucas", "age": "40", "city": "Smallville"},     {"name": "Mike",  "age": "40", "city": "Otherville"}  ]  

Then I use this code to generate an object like this: {"Tony": "20", "Lucas": "40"}:

   select json_objectagg(key "name" value "age") into v_patch     from(        with t(dta) as ( select json_query(:data, '$') from dual )        select "name", "age" from t        cross join json_table(dta,           '$' columns(nested path '$[*]'              columns(                 "name" varchar2(1024) path '$.name',                 "age"  varchar2(1024) path '$.age'              )           )        )     );  

How can I filter the array above so that only persons from Bigville or Smallville are added to the final object?

How can I load Cloud Storage data into Bigquery using Python?

Posted: 17 Nov 2021 09:53 AM PST

I have some datasets (27 CSV files, separated by semicolons, summing 150+GB) that get uploaded every week to my Cloud Storage bucket.

Currently, I use the BigQuery console to organize that data manually, declaring the variables and changing the filenames 27 times. The first file replaces the entire previous database, then the other 26 get appended to it. The filenames are always the same.

How can I do it using Python?

GUI breaks on setting custom size of tkinter window?

Posted: 17 Nov 2021 09:52 AM PST

I am creating a Calculator application with Tkinter, and I've included all the useful buttons there. But the problem is whenever I resize my Tkinter window to a custom size using geometry() method, all buttons don't scale up in the same ratio. To be precise, the buttons in the first column strech a lot leaving other buttons the same size they were. Is there a way to fix all this because it has become harder to include more things in the default size.

Here are some images:
Without custom geometry-Without custom geometry
With custom geometry (800x800)- With custom geometry

Here's the useful bit of code:

root = Tk()  root.grid_rowconfigure(0, weight=1)  root.grid_columnconfigure(0, weight=1)  root.resizable(False, False)    segoe_font = tkFont.Font(family='Segoe UI', size=16)  segoe_font_ac = tkFont.Font(family='Segoe UI', size=8)    entry_text = StringVar()  inout = Entry(root, textvariable=entry_text)  inout.grid(row=0, column=0, columnspan=4, sticky="nsew")    button18 = Button(root, text="AC", command=allclear, font=segoe_font_ac).grid(row=1, column=0, sticky="nsew")  button1 = Button(root, text="C", command=clear, font=segoe_font).grid(row=1, column=1, sticky="nsew")  button2 = Button(root, text="/", command=divide, font=segoe_font).grid(row=1, column=2, sticky="nsew")  button3 = Button(root, text="×", command=multiply, font=segoe_font).grid(row=1, column=3, sticky="nsew")  button5 = Button(root, text="7", command=tsev, font=segoe_font).grid(row=2, column=0, sticky="nsew")  button6 = Button(root, text="8", command=teig, font=segoe_font).grid(row=2, column=1, sticky="nsew")  button7 = Button(root, text="9", command=tnin, font=segoe_font).grid(row=2, column=2, sticky="nsew")  button4 = Button(root, text="-", command=minus, font=segoe_font).grid(row=2, column=3, sticky="nsew")  button9 = Button(root, text="4", command=tfou, font=segoe_font).grid(row=3, column=0, sticky="nsew")  button10 = Button(root, text="5", command=tfiv, font=segoe_font).grid(row=3, column=1, sticky="nsew")  button11 = Button(root, text="6", command=tsix, font=segoe_font).grid(row=3, column=2, sticky="nsew")  button8 = Button(root, text="+", command=plus, font=segoe_font).grid(row=3, column=3, sticky="nsew")  button12 = Button(root, text="1", command=tone, font=segoe_font).grid(row=4, column=0, sticky="nsew")  button13 = Button(root, text="2", command=ttwo, font=segoe_font).grid(row=4, column=1, sticky="nsew")  button14 = Button(root, text="3", command=tthr, font=segoe_font).grid(row=4, column=2, sticky="nsew")  button15 = Button(root, text="=", command=equals, font=segoe_font).grid(row=4, column=3, rowspan=2, sticky="nsew")  button16 = Button(root, text="0", command=tzer, font=segoe_font).grid(row=5, column=0, columnspan=2, sticky="nsew")  button17 = Button(root, text=".", command=decimal, font=segoe_font).grid(row=5, column=2, sticky="nsew")    entry_text.trace("w", lambda *args: character_limit_and_check_entered_value(entry_text))  root.mainloop()  

Can anyone help?

How can I extract frames from a video using node.js?

Posted: 17 Nov 2021 09:53 AM PST

I want to use fluent-ffmpeg (or equivalent) to extract some frames from a video. I want to be able to define a starting point and an end as well as a frame rate:

import ffmpeg from 'fluent-ffmpeg'    let myVideo = ffmpeg('/my-video.mp4')    // pseudocode  let extractedFrames = await myVideo.extractFrames({    startTime: 12, // secs    endTime: 625, // secs    frameRate: 14 // define a lower frame rate to avoid similar frames as much as possible  })  

Is this possible ?

( I am aware of ffmpeg-extract-frames but it doesn't provide such options. )

Python re.sub to correct HTML errors

Posted: 17 Nov 2021 09:53 AM PST

I have HTML pages in which there are various code errors, such as this one:

<ul class="x1">    <p>Some text</p>    <p> Some other text</p>  </ul>  

I would like to replace all <p></p> occurrences with <li></li> in all ul blocks, while keeping the rest of the content, using Python re.sub().

What I would like your help with is formulating the correct RegEx to target only the <p></p> occurrences if they are within a <ul></ul> block - because there are other, perfectly valid paragraphs.

R: split-apply-combine for geographic distance

Posted: 17 Nov 2021 09:53 AM PST

I have downloaded a list of all the towns and cities etc in the US from the census bureau. Here is a random sample:

dput(somewhere)  structure(list(state = structure(c(30L, 31L, 5L, 31L, 24L, 36L,   13L, 21L, 6L, 10L, 31L, 28L, 10L, 5L, 5L, 8L, 23L, 11L, 34L,   19L, 29L, 4L, 24L, 13L, 21L, 31L, 2L, 3L, 29L, 24L, 1L, 13L,   15L, 10L, 11L, 33L, 35L, 8L, 11L, 12L, 36L, 28L, 9L, 31L, 8L,   14L, 11L, 12L, 36L, 13L, 8L, 5L, 29L, 8L, 7L, 23L, 25L, 39L,   16L, 28L, 10L, 29L, 26L, 8L, 32L, 40L, 28L, 23L, 37L, 31L, 18L,   5L, 1L, 31L, 18L, 13L, 11L, 10L, 25L, 18L, 21L, 18L, 11L, 35L,   31L, 36L, 20L, 19L, 38L, 2L, 40L, 13L, 36L, 11L, 29L, 27L, 22L,   17L, 12L, 20L), .Label = c("ak", "al", "ar", "az", "ca", "co",   "fl", "ga", "hi", "ia", "il", "in", "ks", "ky", "la", "md", "mi",   "mo", "ms", "mt", "nc", "nd", "ne", "nj", "nm", "nv", "ny", "oh",   "ok", "or", "pa", "pr", "ri", "sc", "sd", "tx", "ut", "va", "wa",   "wi"), class = "factor"), geoid = c(4120100L, 4280962L, 668028L,   4243944L, 3460600L, 4871948L, 2046000L, 3747695L, 839965L, 1909910L,   4244824L, 3902204L, 1963750L, 622360L, 669088L, 1382972L, 3125230L,   1722736L, 4539265L, 2804705L, 4039625L, 451465L, 3467020L, 2077150L,   3765260L, 4221792L, 133904L, 566320L, 4033150L, 3463180L, 223460L,   2013675L, 2232405L, 1951600L, 1752142L, 4445010L, 4655684L, 1336416L,   1729080L, 1840842L, 4804672L, 3932207L, 1523675L, 4260384L, 1321912L,   2159232L, 1735307L, 1867176L, 4839304L, 2057350L, 1309656L, 655380L,   4082250L, 1350680L, 1275475L, 3147745L, 3505010L, 5352285L, 2483337L,   3909834L, 1912945L, 4068200L, 3227900L, 1366304L, 7286831L, 5505350L,   3982390L, 3149915L, 4974480L, 4249440L, 2943346L, 677430L, 280770L,   4247872L, 2902242L, 2039075L, 1735281L, 1932565L, 3580120L, 2973852L,   3722620L, 2943238L, 1755938L, 4643100L, 4251904L, 4830920L, 3056575L,   2801940L, 5156048L, 137000L, 5508925L, 2057300L, 4861172L, 1736477L,   4021200L, 3677783L, 3832060L, 2614900L, 1820332L, 3043750L),       ansicode = c(2410344L, 2390453L, 2411793L, 1214759L, 885360L,       2412035L, 485621L, 2403359L, 2412812L, 2583481L, 2390095L,       2397971L, 2396237L, 2585422L, 2411819L, 2405746L, 2398338L,       2394628L, 2812929L, 2586582L, 2408478L, 2582836L, 885393L,       2397270L, 2402898L, 2584453L, 2405811L, 2405518L, 2412737L,       2389752L, 2418574L, 2393549L, 2402559L, 2629970L, 2399453L,       2378109L, 2812999L, 2402563L, 2398956L, 2396699L, 2409759L,       2393028L, 2414061L, 2805542L, 2404192L, 2404475L, 2398514L,       2629884L, 2408486L, 2396265L, 2405306L, 2411363L, 2413515L,       2405064L, 2402989L, 2583899L, 2629103L, 2585016L, 2390487L,       2397481L, 2393811L, 2413298L, 2583927L, 2812702L, 2415078L,       1582764L, 2400116L, 2400036L, 2412013L, 2633665L, 2787908L,       2583158L, 2418866L, 1214943L, 2393998L, 485611L, 2398513L,       2394969L, 2806756L, 2397053L, 2406485L, 2395719L, 2399572L,       1267480L, 2389516L, 2410660L, 2409026L, 2806379L, 2584894L,       2404746L, 2586459L, 2396263L, 2411528L, 2398556L, 2412443L,       2584298L, 1036064L, 2806333L, 2396920L, 2804282L), city = c("donald",       "warminster heights", "san juan capistrano", "littlestown",       "port republic", "taylor", "merriam", "northlakes", "julesburg",       "california junction", "lower allen", "antwerp", "pleasantville",       "el rancho", "santa clarita", "willacoochee", "kennard",       "effingham", "la france", "beechwood", "keys", "orange grove mobile manor",       "shiloh", "west mineral", "stony point", "east salem", "heath",       "stamps", "haworth", "rio grande", "ester", "clayton", "hackberry",       "middle amana", "new baden", "melville", "rolland colony",       "hannahs mill", "germantown hills", "la fontaine", "aurora",       "green meadows", "kaiminani", "pinecroft", "dawson", "park city",       "hinsdale", "st. meinrad", "kingsland", "powhattan", "bowersville",       "palos verdes estates", "wyandotte", "meigs", "waverly",       "sunol", "arroyo hondo", "outlook", "west pocomoke", "buchtel",       "chatsworth", "smith village", "glenbrook", "rock spring",       "villalba", "bayfield", "waynesfield", "utica", "sunset",       "milford square", "lithium", "swall meadows", "unalaska",       "martinsburg", "ashland", "leawood", "hindsboro", "gray",       "turley", "trimble", "falcon", "linn", "olympia fields",       "mitchell", "mount pleasant mills", "greenville", "park city",       "arkabutla", "new river", "huntsville", "boulder junction",       "potwin", "red lick", "huey", "dougherty", "wadsworth", "grand forks",       "chassell", "edgewood", "lindsay"), lsad = c("25", "57",       "25", "21", "25", "25", "25", "57", "43", "57", "57", "47",       "25", "57", "25", "25", "47", "25", "57", "57", "57", "57",       "21", "25", "57", "57", "43", "25", "43", "57", "57", "25",       "57", "57", "47", "57", "57", "57", "47", "43", "25", "57",       "57", "57", "25", "25", "47", "57", "57", "25", "43", "25",       "43", "25", "57", "57", "57", "57", "57", "47", "25", "43",       "57", "57", "62", "25", "47", "47", "25", "57", "57", "57",       "25", "21", "25", "25", "47", "25", "57", "25", "43", "25",       "47", "25", "57", "25", "57", "57", "57", "25", "57", "25",       "25", "47", "43", "57", "25", "57", "43", "57"), funcstat = c("a",       "s", "a", "a", "a", "a", "a", "s", "a", "s", "s", "a", "a",       "s", "a", "a", "a", "a", "s", "s", "s", "s", "a", "a", "s",       "s", "a", "a", "a", "s", "s", "a", "s", "s", "a", "s", "s",       "s", "a", "a", "a", "s", "s", "s", "a", "a", "a", "s", "s",       "a", "a", "a", "a", "a", "s", "s", "s", "s", "s", "a", "a",       "a", "s", "s", "s", "a", "a", "a", "a", "s", "s", "s", "a",       "a", "a", "a", "a", "a", "s", "a", "a", "a", "a", "a", "s",       "a", "s", "s", "s", "a", "s", "a", "a", "a", "a", "s", "a",       "s", "a", "s"), latitude = c(45.221487, 40.18837, 33.500889,       39.74517, 39.534798, 30.573263, 39.017607, 35.780523, 40.984864,       41.56017, 40.226748, 41.180176, 41.387011, 36.220684, 34.414083,       31.335094, 41.474697, 39.120662, 34.616281, 32.336723, 35.802786,       32.598451, 39.462418, 37.283906, 35.867809, 40.608713, 31.344839,       33.354959, 33.840898, 39.019051, 64.879056, 39.736866, 29.964958,       41.794765, 38.536765, 41.559549, 44.3437, 32.937302, 40.768954,       40.673893, 33.055942, 39.867193, 19.757709, 40.564189, 31.771864,       37.093499, 41.800683, 38.168142, 30.666141, 39.761734, 34.373065,       33.774271, 36.807143, 31.071788, 27.985282, 41.154105, 36.534599,       46.331153, 38.096527, 39.463511, 42.916301, 35.45079, 39.100123,       34.81467, 18.127809, 46.81399, 40.602442, 40.895279, 41.13806,       40.433182, 37.831844, 37.50606, 53.910255, 40.310917, 38.812464,       38.907263, 39.684775, 41.841711, 36.736661, 39.476152, 35.194804,       38.478798, 41.521996, 43.730057, 40.724697, 33.111939, 45.630946,       34.700227, 37.142945, 34.782275, 46.1148, 37.938624, 33.485081,       38.605285, 34.399808, 42.821447, 47.921291, 47.036116, 40.103208,       47.224885), longitude = c(-122.837813, -75.084089, -117.654388,       -77.089213, -74.476099, -97.427116, -94.693955, -81.367835,       -102.262708, -95.994752, -76.902769, -84.736099, -93.272787,       -119.068357, -118.494729, -83.044003, -96.203696, -88.550859,       -82.770697, -90.808692, -94.941358, -114.660588, -75.29244,       -94.926801, -81.044121, -77.23694, -86.46905, -93.497879,       -94.657035, -74.87787, -148.041153, -100.176484, -93.410178,       -91.901539, -89.707193, -71.301933, -96.59226, -84.340945,       -89.462982, -85.722023, -97.509615, -83.945334, -156.001765,       -78.353464, -84.443499, -86.048077, -87.928172, -86.832128,       -98.454026, -95.634011, -83.084305, -118.425754, -94.729305,       -84.092683, -81.625304, -102.762746, -105.666602, -120.092812,       -75.579197, -82.180426, -96.514499, -97.457006, -119.927289,       -85.238869, -66.481897, -90.822546, -83.973881, -97.345349,       -112.028388, -75.405024, -89.88325, -118.642656, -166.529029,       -78.324286, -92.239531, -94.62524, -88.134729, -94.985863,       -107.792147, -94.561898, -78.65389, -91.844989, -87.691648,       -98.029974, -77.026451, -96.110256, -108.925311, -90.121565,       -80.595817, -86.532599, -89.654438, -97.01835, -94.161474,       -89.289973, -97.05148, -77.893875, -97.08933, -88.530745,       -85.737461, -105.152791), designation = c("city", "cdp",       "city", "borough", "city", "city", "city", "cdp", "town",       "cdp", "cdp", "village", "city", "cdp", "city", "city", "village",       "city", "cdp", "cdp", "cdp", "cdp", "borough", "city", "cdp",       "cdp", "town", "city", "town", "cdp", "cdp", "city", "cdp",       "cdp", "village", "cdp", "cdp", "cdp", "village", "town",       "city", "cdp", "cdp", "cdp", "city", "city", "village", "cdp",       "cdp", "city", "town", "city", "town", "city", "cdp", "cdp",       "cdp", "cdp", "cdp", "village", "city", "town", "cdp", "cdp",       "urbana", "city", "village", "village", "city", "cdp", "cdp",       "cdp", "city", "borough", "city", "city", "village", "city",       "cdp", "city", "town", "city", "village", "city", "cdp",       "city", "cdp", "cdp", "cdp", "city", "cdp", "city", "city",       "village", "town", "cdp", "city", "cdp", "town", "cdp")), row.names = c(22769L,   24845L, 3314L, 24015L, 17360L, 28139L, 10085L, 19881L, 3886L,   8750L, 24027L, 20585L, 9362L, 2499L, 3333L, 6041L, 16321L, 6847L,   25249L, 14051L, 22233L, 1210L, 17425L, 10353L, 20053L, 23545L,   253L, 1951L, 22166L, 17386L, 685L, 9771L, 11134L, 9225L, 7386L,   25001L, 25862L, 5663L, 6950L, 8239L, 26555L, 20991L, 6108L, 24388L,   5551L, 10772L, 7056L, 8470L, 27292L, 10202L, 5451L, 3116L, 22660L,   5776L, 5317L, 16546L, 17582L, 29958L, 12103L, 20709L, 8779L,   22515L, 16665L, 5902L, 31901L, 30658L, 21745L, 16574L, 28632L,   24127L, 15046L, 3455L, 930L, 24087L, 14494L, 10016L, 7055L, 8993L,   18048L, 15434L, 19615L, 15043L, 7454L, 25775L, 24194L, 27115L,   15857L, 14038L, 29305L, 276L, 30693L, 10201L, 27863L, 7075L,   22046L, 19267L, 20311L, 12502L, 8093L, 15798L), class = "data.frame")  

I would like to calculate the distance between each entry in the city column using the longitude and latitude columns and the gdist function. I know that the following for loop works and is easy to read:

dist_list <- list()  for (i in 1:nrow(somewhere)) {        dist_list[[i]] <- gdist(lon.1 = somewhere$longitude[i],                             lat.1 = somewhere$latitude[i],                             lon.2 = somewhere$longitude,                             lat.2 = somewhere$latitude,                            units="miles")      }  

However: IT TAKES FOREVER to run on the full dataset (31K+ rows)--as in hours. I'm looking for something that will speed up this calculation. I figured something in the split-apply-combine approach would work well, since I would like to eventually involve a pair of grouping variables, geo_block and ansi_block but honestly anything would be better than what I have.

I have tried the following:

somewhere$geo_block <- substr(somewhere$geoid, 1, 1)  somewhere$ansi_block <- substr(somewhere$ansicode, 1, 1)    somewhere <- somewhere %>%    split(.$geo_block, .$ansi_block) %>%    mutate(dist = gdist(longlat = somewhere[, c("longitude", "latitude")]))  

But am unsure of how to specify the second set of long-lat inputs outside of the standard for loop.

My question:

  1. How do I use the split-apply-combine approach to solve this problem with geo_block and ansi_block as a grouping variable as above? I would like to return the shortest distance and the name of the city and the value of geo_block corresponding to this distance.

All suggestions are welcome. Ideally the desired result would be fairly quick because the actual dataset I'm working with is quite large. Since I'm a bit in the woods here, I've added a bounty to the question to generate a little more interest and hopefully a wide set of potential answers that I can learn from. Thanks so much!

Type hints in namedtuple

Posted: 17 Nov 2021 09:53 AM PST

Consider following piece of code:

from collections import namedtuple  point = namedtuple("Point", ("x:int", "y:int"))  

The Code above is just a way to demonstrate as to what I am trying to achieve. I would like to make namedtuple with type hints.

Do you know any elegant way how to achieve result as intended?

Vim indent xml file

Posted: 17 Nov 2021 09:53 AM PST

I am learning Vim but I thought this was a simple task but I cannot get it to work. I have browser SO but the solutions are not working for me.

I am trying to correctly indent an file (xml). The command I use is:

gg=G   

or ggVG= (made this one up myself probably does something different ;))

My .vimrc is:

syntax on   filetype plugin indent on   set nu   

"The parameter is incorrect." error using netsh http add sslcert

Posted: 17 Nov 2021 09:53 AM PST

Following the instructions on "How to: Configure a Port with an SSL Certificate" in this link: http://msdn.microsoft.com/en-us/library/ms733791.aspx, I entered this command on the commandline (duh):

> netsh http add sslcert ipport:10.141.146.227:7001 certhash=5d48e604007b867ae8a69260a4ad318d2c05d8ff appid={EDE3C891-306C-40fe-BAD4-895B236A1CC8}  The parameter is incorrect.  

My certhash thumbprint was taken from the certificate in Certificates(Local Computer)>Personal>Certificates folder.

The appid GUID was generated.

What else is wrong that I need to fix to get this to work?

No comments:

Post a Comment