Monday, August 2, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Adding extra space to pages in PDF

Posted: 02 Aug 2021 08:51 AM PDT

I have a couple of PDFs I want to add a few inches on one side to give myself more room for handwritten comments in a notes app. Basically, I want to give myself more room to scribble on the sides of the pages (lecture scripts).

The pages should not be scaled, I simply want the contents to stay at the same spot from the upper left corner, but add more space at the right and maybe at the bottom.

Is there a good way to to this either using one of the Python PDF libs or using a command line tool?

DNSPython - Direct access to the `name` of a DNS query

Posted: 02 Aug 2021 08:50 AM PDT

I'm not sure how I can get the domain name of the DNS query (of type dns.message.Message) with dnspython. query.question returns a list of RRsets that I then have to index (with 0 most of the time) before I can read the name field.

> query.question  [<DNS google.com. IN A RRset: []>]  > query.question[0].name  google.com.  

canonical_name() exists but only works for responses, not queries.

> response.canonical_name()  google.com.  

Is there any way to get something similar for queries, instead of indexing the list of RRsets in question?

Airflow becomes unstable beyond 16 DAGs in parallel

Posted: 02 Aug 2021 08:50 AM PDT

As in the title - I changed the airflow cfg (default -> 16 DAGs in parallel). No I am able to spawn >16 but even 1 above 16 causes problems - airflow "looses" connection with AWS instance and kills the whole process returning failed status (each process takes 2-3 days to complete). I tried to spawn more workers but it didn't seem to help with overall airflow stability.

Pandas: Add Datetime as prefix

Posted: 02 Aug 2021 08:50 AM PDT

I am trying to add the date as a prefix to the column names to get something like this:

In:   Source    Out:  DatetimeIndex(['2020-10-13 10:00:00+00:00'], dtype='datetime64[ns, UTC]', name='timestamp', freq=None)    In:  table = ['AR']  table = table.add_prefix(source[0][0]+'_')    Out:  2020-10-13 10:00:00+00:00_AR  

However I am getting te following error:

**TypeError: unsupported operand type(s) for +: 'Timestamp' and 'str' **

I am not sure how to fix this. Also, is it possible to remove the UTC time? i.e. remove the "+00:00"

Shouldn't I be warned about undefined behavior with -INT_MIN?

Posted: 02 Aug 2021 08:50 AM PDT

Consider the following C program:

#include <limits.h>    int main() {    int x = INT_MIN;    int y = -x;    return y;  }  

This program has undefined behavior, as the negation of INT_MIN is not representable; or, to be a language lawyer - since the C standard says so.

Now, the compiler knows, or can know, this is the case. And yet - neither GCC nor clang emit a warning about this (GodBolt); only sanitizing undefined behavior catches it - at run-time.

Why is it this the case? Is it too costly to try to prove UB is occurring at compile time, generally, so compilers don't bother?

How to transfer data from S3 Requester Pays bucket with BigQuery Data Transfer Service?

Posted: 02 Aug 2021 08:50 AM PDT

I would like to transfer data to GCP from a third party S3 bucket with BigQuery Data Transfer Service. The bucket is configured for Requester Pays, so that my AWS account is charged for egress. Thus I am required to send a header with my data transfer requests consenting to the charges.

How do I do that with BigQuery Data Transfer Service?

How to Search in Repos of Most copied/pasted Functions between multiple repos?

Posted: 02 Aug 2021 08:50 AM PDT

Is there a way to find most copied/pasted functions or bulk of codes between multiple repos? For example, in react I'd rather make a component out of stuff copied around too many times and share between so when I update the component this copied function will take an impact everywhere. Otherwise function updated at one location will not be updated in an another location.

Need to merge multiple image collections chronologically (google earth engine)

Posted: 02 Aug 2021 08:50 AM PDT

I am working on a project to track changes across cropland and cropland productivity, near dams. I have a per-year image collections for each dam, that show me NDVI values on croplands only. They were made by getting cropland classification on buffer zones around dams -> reducing to vectors -> selfmask -> getting NDVI values -> clipping to cropland per year -> turning it into imagecollections (more or less). For example, for 2018, I can visualise it like this cropland productivity near GERD dam in 2018

I have similar image collections for 29 dams, from 2001 to 2019. I would like to merge them on a per dam basis and create a visualisation where I can track how cropping patterns change, as well as how their vegetation growth rates change.

I am using rgee. I am not entirely sure which part of the code to insert in this since I am super new to GIS and GEE in general and would appreciate feedback.

Summary: have imagecollections that are damname_year, where damname is region of interest (that shifts per year), and year goes from 2001-2019. How do I make it so that all years for each dam are in one collection and chronological?

Thanks

estoy intentando deplegar mi app en heroku desde la terminar git CMD pero me da este error

Posted: 02 Aug 2021 08:49 AM PDT

remote:            checking for pkg-config... (cached) /usr/bin/pkg-config  remote:            checking pkg-config is at least version 0.16... yes  remote:            checking for GTK+ - version >= 3.0.0... Package gtk+-3.0 was not found in the pkg-config search path.  remote:            Perhaps you should add the directory containing `gtk+-3.0.pc'  remote:            to the PKG_CONFIG_PATH environment variable  remote:            No package 'gtk+-3.0' found  remote:            no  remote:            *** Could not run GTK+ test program, checking why...  remote:            *** The test program failed to compile or link. See the file config.log for the  remote:            *** exact error that occurred. This usually means GTK+ is incorrectly installed.  remote:            configure: error:  remote:            The development files for GTK+ were not found. For GTK+ 2, please  remote:            ensure that pkg-config is in the path and that gtk+-2.0.pc is  remote:            installed. For GTK+ 1.2 please check that gtk-config is in the path,  remote:            and that the version is 1.2.3 or above. Also check that the  remote:            libraries returned by 'pkg-config gtk+-2.0 --libs' or 'gtk-config  remote:            --libs' are in the LD_LIBRARY_PATH or equivalent.  remote:  

e intentado todas las formas de hacer el deploy al parecer no es ese el problema

ya instale GTK-3.0 y puse la ruta en el path

C:\msys64\mingw64\bin  

Why the regex to mark beginning of line doesn't work?

Posted: 02 Aug 2021 08:50 AM PDT

Why the commented regex doesn't work? I thought '^' also marks beginning of line. isn't it?

#include <iostream>  #include <regex>    int main()  {       std::string str ("this subject has a submarine as a subsequence");       std::regex re ("\\b(sub)([^ ]*)");       // std::regex re ("^(sub)([^ ]*)");       // std::regex re ("(^sub)([^ ]*)");               std::cout << "entire matches:";         std::regex_token_iterator<std::string::iterator> rend;        std::regex_token_iterator<std::string::iterator> a ( str.begin(), str.end(), re );        while (a!=rend) std::cout << " [" << *a++ << "]";        std::cout << std::endl;            return 0;  }  

Generate Package.swift from Xcode

Posted: 02 Aug 2021 08:50 AM PDT

I've added some dependencies to my project using Xcode and I need to generate a Package.swift file for Travis-CI.

There's a solution other than manually add all my dependencies to this file.

Thanks

I need to get the percentage of sum of grouped rows using SQL DB2

Posted: 02 Aug 2021 08:49 AM PDT

Below is the table :

AccountNo Symbol Amount
A1 IBM 10
A1 CSCO 20
A1 GOOG 30
A2 IBM 40
A2 FB 10

I need to get the Percentage of IBM on Account A1. i.e. 10 * 100 / 60 = 16.6%

I need to get the Percentage of CSCO on Account A1.i.e. 20 * 100 / 60 = 33.33%

I need to get the Percentage of GOOG on Account A1.i.e. 30 * 100 / 60 = 50 %

I need to get the Percentage of IBM on Account A2.i.e. 40 * 100 / 50 = 80%

I need to get the Percentage of FB on Account A2.i.e. 10 * 100 / 50 = 20%

I tried below query but does not execute:

select AccountNo, SYMBOL, Value, Float(cast((value(Amount,0)) as DECIMAL(18,2))) / FLOAT(cast((value(t2.total,0)) as DECIMAL (18,2))) * 100  from mytable   (select sum(Amount) as total from mytable group by AccountNo) as T2  where Amount > 0  group by AccountNo, SYMBOL, Value, T2.total;  

I would like to know how to combine If, AND and OR in a complex statement in PHP

Posted: 02 Aug 2021 08:50 AM PDT

I have a problem I would like some help with. I am generating random numbers to convert to a password using chr($v). I am using an if statement to make sure I only use printable characters. I have got this successfully working in C++ for Arduino and Pascal using Lazarus for Windows & Linux. I am now trying to write a Web based version and cannot get the code below to work, in either form in PHP 7.3. The first one is the one that works in C++ and Pascal, although in Pascal I have to use the words AND and OR! Any help would be greatly appreciated!! Many thanks.

if (($v > 47) && ($v < 58)) || (($v > 64) && ($v <91)) || (($v > 96) && ($v < 123))  
if ($v > 47 && $v < 58) || ($v > 64 && $v <91) || ($v > 96 && $v < 123)  

Php laravel login and registration notification error

Posted: 02 Aug 2021 08:50 AM PDT

I have registration and authorization forms. They work, except for the error output. For example, if authorization is unsuccessful, it should display the error 'Authorization failed' on the 'number' field. Or, during registration, it should display in the number field 'This user is already registered'. In this case, the redirect works, but_the_errors_themselves are not displayed. That is, the page is simply being updated. What could be the mistake? registration.blade.php:

@extends('layouts.app')  @section('title-block')      Регистрация  @endsection    @section('content')        <div class="container">          <h1 align="center">              <a href="/"><img src="{{asset('images/logo.jpg')}}" alt="logo" class="home"></a>              Register          </h1>      </div>      <hr>      <div class="container" align="center">          <form name="register" method="POST" action="{{route('user.registration')}}">              @csrf              <input class="text-input" type="text" placeholder="Enter your surname" name="surname" required>              <input class="text-input" type="text" placeholder="Enter your name" name="name" required><br>                <input class="text-input-full-width" type="text" placeholder="Enter your number" name="number" required><br>                <input class="text-input" type="text" placeholder="Enter your father`s name" name="fathers_name" required>              <input class="text-input" type="text" placeholder="Enter parent number" name="parents_number" required><br>                <input class="text-input-full-width" id="password" name="password" type="password" required placeholder="Enter password"><br>                <label for="studies"id="RegistrationForm"><b>Choose your studies</b></label><br>              <div class="btn-group" role="group" aria-label="Basic checkbox toggle button group">                  <input type="checkbox" class="btn-check" id="btncheck1" autocomplete="off" name="btnstudies[]" value="Math">                  <label class="btn btn-outline-primary" for="btncheck1">Math</label>                    <input type="checkbox" class="btn-check" id="btncheck2" autocomplete="off" name="btnstudies[]" value="Language">                  <label class="btn btn-outline-primary" for="btncheck2">Language</label>                    <input type="checkbox" class="btn-check" id="btncheck3" autocomplete="off" name="btnstudies[]" value="Physics">                  <label class="btn btn-outline-primary" for="btncheck3">Physics</label>        </div>              <br>              <label for="classes"id="RegistrationForm"><b>Classes</b></label><br>                <div class="btn-group-vertical" role="group">                    <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off" checked value="2">                  <label class="btn btn-outline-primary" for="btnradio1">2nd class</label>                    <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off" value="3">                  <label class="btn btn-outline-primary" for="btnradio2" >3rd class</label>                    <input type="radio" class="btn-check" name="btnradio" id="btnradio3" autocomplete="off" value="4">                  <label class="btn btn-outline-primary" for="btnradio3">4th class</label>                    <input type="radio" class="btn-check" name="btnradio" id="btnradio4" autocomplete="off" value="5">                  <label class="btn btn-outline-primary" for="btnradio4">5th class</label>                    <input type="radio" class="btn-check" name="btnradio" id="btnradio5" autocomplete="off" value="6">                  <label class="btn btn-outline-primary" for="btnradio5">6th class</label>                    <input type="radio" class="btn-check" name="btnradio" id="btnradio6" autocomplete="off" value="7">                  <label class="btn btn-outline-primary" for="btnradio6">7th class</label>              </div>              <br>              <div class="final">                  <input type="checkbox" class="check-term" id="btncheck4" autocomplete="off" required>                  <label class="check-agree" for="btncheck4">I agree with a <a href="documents/term.txt">Terms</a></label><br>                  <button class="main-button" type="submit" name="sendMe" value="1" required>Register</button><br>                  <br><label class="check-agree" for="btncheck5">If you have already registrated, <a href="/login"> log in</a></label>              </div>              <hr>        </form>  @endsection  

RegisterController.php:

<?php    namespace App\Http\Controllers;  use App\User;  use Illuminate\Http\Request;  use App\Http\Controllers\Controller;  use Illuminate\Support\Facades\Auth;    class RegisterController extends Controller  {  //    public function studies(Request $request){  //        dd($request->get('btnstudies'));  //        //you an store it in database now  //    }      public function save(Request $request){          if(Auth::check()){              return redirect(route('user.private'));          }        $validateFields = $request->validate([            'number' =>'required',          'password' => 'required',        ]);          if(User::where('number',$request['number'])->exists()){              return redirect(route('user.registration'))->withErrors([                  'number' => 'Такой пользователь уже зарегистрирован',                    ]);          }   $studies = implode(", ",$request['btnstudies'] );      $user = User::create([            'password' => $request['password'],          'name' => $request['name'],          'surname'=>$request['surname'],          'number'=>$request['number'],          'fathers_name'=>$request['fathers_name'],          'parents_number'=>$request['parents_number'],          'class' => $request['btnradio'],          'studies' =>$studies      ]);        if($user){          Auth::login($user);            return redirect(route('user.private'));      }            return redirect(route('user.login'))->withErrors([              'formError' => 'Произошла ошибка при сохранении пользователя'          ]);      }  }      

login.blade.php:

@extends('layouts.app')  @section('title-block')      Log in  @endsection  @section('content')      <div class="container">          <h1 align="center">              <a href="/"><img src="{{asset('images/logo.jpg')}}" alt="logo" class="home"></a>              Log in          </h1>      </div>      <hr>      <div class="container" align="center">          <form name="sign" method="POST" action="{{route('user.login')}}">          @csrf                  <input class="text-input" type="text" placeholder="Enter your number" name="number">              <input class="text-input" type="text" placeholder="Enter your password" name="password">                <button class="main-button" type="submit" name="sendMe" value="1" required>Log in</button><br>              <br><label class="check-agree" for="btncheck5">Don't have an account? You can <a href="/registration"> register it right now</a></label>      </form>      </div>      <hr>  @endsection    

LoginController.php:

<?php    namespace App\Http\Controllers;  use App\Http\Controllers\Controller;  use Illuminate\Http\Request;  use Illuminate\Support\Facades\Auth;    class LoginController extends Controller  {      public function login(Request $request){          $formFields = $request->only('number','password');          if(Auth::attempt($formFields)){              return redirect()->intended('/private');          }          return redirect(route('user.login'))->withErrors([             'number' => 'Авторизоваться не удалось'          ]);      }  }  

Assign the text to center of the circle image

Posted: 02 Aug 2021 08:49 AM PDT

I want to assign the text "Upload Profile Picture" in the center of the circle image. But it didn't display the text when I run the code. Below is the html code and css code. enter image description here

      <div class="small-12 medium-2 large-2 ">           <div class="circle upload-button d-flex mx-auto mb-4" style="position:unset;">                          <img class="profile-pic" src="">             <div class="centered">Upload Profile Picture</div>                        </div>              <input class="file-upload" type="file" accept="image/*"/ >                   </div>        .profile-pic {          max-width: 222px;          max-height: 222px;          margin-left: auto;          margin-right: auto;          display: block;      }        .file-upload {          display: none;      }      .circle {          border-radius: 50%;          overflow: hidden;          width: 228px;          height: 228px;          border: 8px solid #dbdbdb;          position: absolute;          top: 72px;        transition: all .3s;      }        .circle:hover {        background-color: #909090;        cursor: pointer;      }      img {          max-width: 100%;          height: auto;          min-width: 212px;          min-height: 212px      }  

Execute function after NSWindow is closed in swift

Posted: 02 Aug 2021 08:49 AM PDT

I have a view in which an area is selected by drawing a rectangle. Then a screenshot is taken of that area which is used for some other function which takes some time to complete.

let workerQueue = DispatchQueue.global(qos: .userInitiated)              workerQueue.async{                            self.closeWindow()                        DispatchQueue.main.async {                 someOtherFunction()             }  }    func closeWindow(){      DispatchQueue.main.async{              self.window?.close()      }  }  

The problem is that currently there is a delay in the view being removed caused by the otherFunction(). When I remove the other function from the code it runs smoothly.

Is it possible to remove this delay?

How many ways are there to write cgi files?

Posted: 02 Aug 2021 08:50 AM PDT

I have recently used .cgi extension on my Python Code and printed the html tags with print() in python written in that file but to my wonder it worked on my browser. I had seen perl before this it is .cgi but it uses a different syntax of printing . It is very weird that the same .cgi extension can be run by so many languages . I just want to know that how is cgi just a common extension for all server sided languages or is it particularly because I myself don't know much about the .cgi extension and mixing it with others.

Can I programmatically pass a prop to children components in react?

Posted: 02 Aug 2021 08:50 AM PDT

I want children of my component to have class prefix. Apparently, we can access chidren via this.props.children, but it's not recommended to modify it's value. But anyway it feels unnatural to hardcode it, so maybe you could come up with an idea?

<Aside className="right">    <Timer className="right" />    <LoginFrame className="right" buttonTitle="this.state.buttonTitle" />  </Aside>    

For example, I want my Timer to have className="right__timer", where __timer postfix is specified in the component itself

How to overload polymorphic == and != operator in c++

Posted: 02 Aug 2021 08:50 AM PDT

class Media {  public:      bool operator==(const Media& other) const {}      bool operator!=(const Media& other) const {}  };    class Book : public Media {  public:      bool operator==(const Book& other) const {} // commenting out this line solves this issue.      bool operator!=(const Book& other) const {}  };    class Game : public Media {  public:      bool operator==(const Game& other) const {}      bool operator!=(const Game& other) const {}  };    int main() {      Book book;      Game game;        bool res = book == game;  // doesn't compile.  }  

I have these 3 classes and they must have their own == and != operators defined. But then I also have to compare between two siblings using those operators.

I could've written a (pure) virtual function, say, virtual bool equals(const Media& other) const in the base class that subclasses override. And then call that function in the bodies of == and != opertor definition in base class Media. But that feature is gone when I add another bool operator==(const Book& other) const {} in the Book class (the same goes for the Game class too).

Now I want to compare between siblings using those operators and still have all 6 definition in those 3 classes. How do I make it work?

Pandas - scatter plot - rotation of cmap label

Posted: 02 Aug 2021 08:50 AM PDT

I am doing a simple scatter plot directly via pandas.

My data frame has columns A,B,C.

I plot A vs. B and visualize C values via color.

    import numpy as np      import pandas as pd      import matplotlib.pyplot as plt      import matplotlib as mpl            %matplotlib inline  

Code:

    ycol_label = 'B'      xcol_label = 'A'            f = df1.plot.scatter(x=xcol_label, y=ycol_label, c='C', cmap='coolwarm')            h = plt.ylabel(ycol_label)      h.set_rotation(0)      type(f)  

How do I change the orientation of that C label which I have on the far right?

I want to rotate it and show it as the B label is shown (on the far left).

I have hard time to even google for this because I don't know how this rightmost element
is called (the one with the cool warm color scale). I want to rotate that element's label basically.

pic9

Discord.js Button on Embed

Posted: 02 Aug 2021 08:50 AM PDT

would like to make this send an embed instead of it saying "If you want to apply, click the button below.", and have the apply button underneath the embed I have read up about some Component array and embed array stuff but I can't seem to get anything working with that If anyone could help me out id appreciate it 🙂

Two very helpful people have helped me

@Skulaurun Mrusal and @PerplexingParadox

Thank you! 🙂

enter image description here

client.on("message", async (message) => {        // Don't reply to bots    if (message.author.bot) return;      if (message.content == "#req") {           if(!message.member.hasPermission("MANAGE_MESSAGES"))       {          message.reply("You do not have permission to do that!");          return;       }      // Perform raw API request and send a message with a button,      // since it isn't supported natively in discord.js v12      client.api.channels(message.channel.id).messages.post({        data: {          embeds: [reqEmbed],          components: [            {              type: 1,              components: [                {                  type: 2,                  style:  4,                  label: "Apply",                  // Our button id, we can use that later to identify,                  // that the user has clicked this specific button                  custom_id: "send_application"                }              ]            }          ]        }      });    }  });  

folders and files are not visible after uploading file though multer

Posted: 02 Aug 2021 08:49 AM PDT

I am working on a small project. discussing Step by step

  1. At first I am uploading zip files though multer
  2. extracting those files (How can I call extract function after completing upload using multer?)
  3. After extracting those I am trying to filter those files
  4. after filtering those files I want to move some files to another directory

in my main index.js I have

  • A simple route to upload files which is working
// MAIN API ENDPOINT   app.post("/api/zip-upload", upload, async (req, res, next) => {      console.log("FIles - ", req.files);  });  
  • Continuous checking for if there is any zip file that needs to unzip but the problem is after uploading it's not showing any files or dir
// UNZIP FILES   const dir = `${__dirname}/uploads`;  const files = fs.readdirSync("./uploads");    const filesUnzip = async () => {      try {          if (fs.existsSync(dir)) {              console.log("files - ", files);              for (const file of files) {                  console.log("file - ", file);                  try {                      const extracted = await extract("./uploads/" + file, { dir: __dirname + "/uploads/" });                      console.log("Extracted - ",extracted);                      // const directories = await fs.statSync(dir + '/' + file).isDirectory();                    } catch (bufErr) {                      // console.log("------------");                      console.log(bufErr.syscall);                  }              };                // const directories = await files.filter(function (file) { return fs.statSync(dir + '/' + file).isDirectory(); });              // console.log(directories);            }      } catch (err) {          console.log(err);      }      return;  }      setInterval(() => {      filesUnzip();  }, 2000);  
  • Moving files to static directory but here is the same problem no directory found
const getAllDirs = async () => {      // console.log(fs.existsSync(dir));      // FIND ALL DIRECTORIES       if (fs.existsSync(dir)) {          const directories = await files.filter(function (file) { return fs.statSync(dir + '/' + file).isDirectory(); });          console.log("Directories - ",directories);          if (directories.length > 0) {              for (let d of directories) {                  const subdirFiles = fs.readdirSync("./uploads/" + d);                  for (let s of subdirFiles) {                      if (s.toString().match(/\.xml$/gm) || s.toString().match(/\.xml$/gm) !== null) {                          console.log("-- ", d + "/" + s);                            const move = await fs.rename("uploads/" + d + "/" + s, __dirname + "/static/" + s, (err) => { console.log(err) });                          console.log("Move - ", move);                      }                  }              }          }      }  }  setInterval(getAllDirs, 3000);  

how to label sections in a bar chart [duplicate]

Posted: 02 Aug 2021 08:51 AM PDT

What is the most simple way to label all the sections?

x = ['A', 'B', 'C', 'D']  y1 = np.array([2, 4, 5, 1])  y2 = np.array([1, 0, 2, 3])  y3 = np.array([4, 1, 1, 1])    plt.bar(x, y1, color='#d67ed0')  plt.bar(x, y2, color='#e6ad12', bottom=y1)  plt.bar(x, y3, color='#13c5ed', bottom=y1+y2)    plt.show()  

Like "A"-Violet labeled as "2" on the plot

What does this mean: a pointer to void will never be equal to another pointer?

Posted: 02 Aug 2021 08:49 AM PDT

One of my friends pointed out from "Understanding and Using C Pointers - Richard Reese, O'Reilly publications" the second bullet point and I wasn't able to explain the first sentence from it. What am I missing?

Pointer to void

A pointer to void is a general-purpose pointer used to hold references to any data type. An example of a pointer to void is shown below:

void *pv;  

It has two interesting properties:

  • A pointer to void will have the same representation and memory alignment as a pointer to char.
  • A pointer to void will never be equal to another pointer. However, two void pointers assigned a NULL value will be equal.

This is my code, not from the book and all pointers are having the same value and are equal.

#include <stdio.h>    int main()  {    int a = 10;     int *p = &a;     void *p1 = (void*)&a;    void *p2 = (void*)&a;      printf("%p %p\n",p1,p2);    printf("%p\n",p);        if(p == p1)       printf("Equal\n");    if(p1 == p2)       printf("Equal\n");    }  

Output:

 0x7ffe1fbecfec 0x7ffe1fbecfec   0x7ffe1fbecfec   Equal   Equal  

Iterate through a child map in a for loop in groovy

Posted: 02 Aug 2021 08:50 AM PDT

Let us assume I have a map like below which contains another map (child map) within it. I like to print the child map as individual rows for each key.

def map =[       1: [      [name:"Jerry", age: 42, city: "New York"],      [name:"Long", age: 25, city: "New York"]    ],      2: [      [name:"Dustin", age: 29, city: "New York"],      [name:"Bob", age: 34, city: "New York"]    ]  ]  

Currently, I iterate through the parent map, and am able to print the names. But, that is not actually what I want. I wanted to see if I can atleast iterate through the parent map. I do not see errors so far.

    for(allentries in map){      loggerApi.info("${allentries.key}: ${allentries.value.name}") // this prints [Jerry, Long] for key 1 & [Dustin, Bob] for key 2      loggerApi.info("${allentries.key}: ${allentries.value.age}")      loggerApi.info("${allentries.key}: ${allentries.value.city}")            }  

Can you please let me know what I should add to the above code to see individual rows like these:

Name Age City  Jerry 42 New York  Long 25 New York  Dustin 29 New York  Bob 34 New York  

Appreciate.

Thank you.

Br, Noor.

How to delete all transactions Record of netsuite using map reduce script?

Posted: 02 Aug 2021 08:49 AM PDT

The transaction types will be dynamic.When I execute the map reduce script, all transactions record of netsuite will be deleted.

Vue preventing default router-link behaviour works in Chrome but not in Firefox

Posted: 02 Aug 2021 08:50 AM PDT

I have a component that has a router-link as a root tag. I want to prevent its default link behavior so it would fall back to the link if something is wrong with JS or it's disabled.

I made it work in Chrome with such event modifiers: @click.native.capture.prevent

But it doesn't work in Firefox. What am I missing?

Codesandbox: https://codesandbox.io/s/vue-dynamic-components-forked-vhovz?file=/src/App.vue

UPD: I found a workaround, but I'm still curios why this isn't working

need some javascript for a pdf form

Posted: 02 Aug 2021 08:50 AM PDT

not sure if I've come to the right place or not. Any help is appreciated.

I am creating a form that will post certain air quality test results on a building. Users will insert particular numbers in the form (e.g., concentration of certain gases, etc.). If number meets acceptable standards (e.g., below acceptable maximum), then I would like a check box to turn on that says the building meets the safety standards.

let A be air quality value let B be maximum accepted value let C be checkbox indicating pass

So, if A is less than B, then C is ON (pass) but if A is greater than B, C is OFF (fail)

Ideally, C will be a graphic of a green check mark or a red ex.

thx

How could I add more android emulator devices in Visual Studio for Mac for Xamarin?

Posted: 02 Aug 2021 08:50 AM PDT

I want to add some new virtual devices for Android using Visual Studio for Mac so I could use them with Xamarin. I've followed https://docs.microsoft.com/en-us/xamarin/android/get-started/installation/android-emulator/device-manager?tabs=macos&pivots=macos but surprisingly I only have the Nexus series (One, S, Galaxy, 7, 4, 10) in my Base Devices My Base Devices

while MS Documentation also has Pixel etc. Screenshot from Microsoft Docs

In OS I've APIs 21 to 28 installed.

  1. How could I add more devices there?
  2. Is it possible (next to Pixel) to also get e.g. Samsung Galaxy S3 to S10 into the list so I could easily create an emulator using the Galaxy S10 specs.

Backgrounded subshells use incrementally more memory

Posted: 02 Aug 2021 08:50 AM PDT

I am starting 1000 subshells in the background in a loop. I assume they use roughly the same amount of memory.

for i in `seq 1000`; do    (      echo $i;      sleep 100;    )&  done;  

However, they do not. Each new subshell eats up a little bit more memory than the previous one. Their memory usage is increasing.

$ ps -eo size,command --sort -size | grep subshell | head -n2    624 /bin/bash /tmp/subshells.sh    624 /bin/bash /tmp/subshells.sh  $ ps -eo size,command --sort -size | grep subshell | tail -n2    340 /bin/bash /tmp/subshells.sh    340 /bin/bash /tmp/subshells.sh  

The smallest subshell used 340KB, while the largest one needed 624KB.

What's going on here? Is there a way to avoid this? I'm sad because my parallel computation is organized in a way that it needs thousands of backgrounded subshells, and I'm running out of memory.

No comments:

Post a Comment