Tuesday, August 10, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to match a Linux driver with a hardware device

Posted: 10 Aug 2021 07:53 AM PDT

I am writing a Linux driver for some custom hardware. My questions is how does Linux match the hardware to my driver. The hardware's DT entry is

nvme_host_sys@43c00000 {          clock-names = "sys_clk_p", "sys_clk_n", "aclk";          clocks = <0x13 0x13 0x13>;          compatible = "xlnx,nvme-host-sys-1.0";          interrupt-names = "intr";          interrupt-parent = <0x4>;          interrupts = <0x0 0x1d 0x4>;          reg = <0x43c00000 0x80000>;          phandle = <0x38>;      };  

I can insert my driver using modprobe and that works fine as I can see the printk in the init being written. I can also create an entry in /dev using mknod and that also works fine. But is the driver now associated with the hardware? Do I need to do something else? Thanks

How do you make make a subscriber to a kotlin sharedflow run operations in parallel?

Posted: 10 Aug 2021 07:53 AM PDT

I have a connection to a Bluetooth device that emits data every 250ms

In my viewmodel I wish to subscribe to said data , run some suspending code (which takes approximatelly 1000ms to run) and then present the result.

the following is a simple example of what I'm trying to do

Repository:

class Repo() : CoroutineScope {      private val supervisor = SupervisorJob()      override val coroutineContext: CoroutineContext = supervisor + Dispatchers.Default      private val _dataFlow = MutableSharedFlow<Int>()      private var dataJob: Job? = null      val dataFlow: Flow<Int> = _dataFlow        init {           launch {              var counter = 0              while (true) {                  counter++                  Log.d("Repo", "emmitting $counter")                  _dataFlow.emit(counter)                  delay(250)              }          }      }    }  

the viewmodel

class VM(app:Application):AndroidViewModel(app) {      private val _reading = MutableLiveData<String>()      val latestReading :LiveData<String>() = _reading        init {          viewModelScope.launch(Dispatchers.Main) {              repo.dataFlow                  .map {                      validateData() //this is where some validation happens it is very fast                  }                  .flowOn(Dispatchers.Default)                  .forEach {                      delay(1000) //this is to simulate the work that is done,                  }                  .flowOn(Dispatchers.IO)                  .map {                     transformData() //this will transform the data to be human readable                   }                  .flowOn(Dispatchers.Default)                  .collect {                      _reading.postValue(it)                  }          }        }  }  

as you can see, when data comes, first I validate it to make sure it is not corrupt (on Default dispatcher) then I perform some operation on it (saving and running a long algorithm that takes time on the IO dispatcher) then I change it so the application user can understand it (switching back to Default dispatcher) then I post it to mutable live data so if there is a subscriber from the ui layer they can see the current data (on the Main dispatcher)

I have two questions

a) If validateData fails how can I cancel the current emission and move on to the next one?

b) Is there a way for the dataFlow subscriber working on the viewModel to generate new threads so the delay parts can run in parallel?

the timeline right now looks like the first part, but I want it to run like the second one Execution timeline

Is there a way to do this?

I've tried using buffer() which as the documentation states "Buffers flow emissions via channel of a specified capacity and runs collector in a separate coroutine." but when I set it to BufferOverflow.SUSPEND I get the behaviour of the first part, and when I set it to BufferOverflow.DROP_OLDEST or BufferOverflow.DORP_LATEST I loose emissions

cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class

Posted: 10 Aug 2021 07:53 AM PDT

I'm new on Java. I get a grip on but I don't know why errors occurs. I'm doing Errors:

Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.gokturk.microserviceuser.MicroserviceUserApplication]; nested exception is java.io.FileNotFoundException: class path resource [com/gokturk/microserviceuser/controller/HelloController.class] cannot be opened because it does not exist

Main class:

package com.gokturk.microserviceuser;    import org.springframework.boot.SpringApplication;  import org.springframework.boot.autoconfigure.SpringBootApplication;    @SpringBootApplication  public class MicroserviceUserApplication {      public static void main(String[] args) {          SpringApplication.run(MicroserviceUserApplication.class, args);      }  }  

My controller folder is empty for now. I removed the HelloController after the test of endpoint. I did just return a string in the endpoint. Even, I didn't from call anywhere but I have a error about HelloController.class can not be opened.

model:

package com.gokturk.microserviceuser.model;    import lombok.Data;    import javax.persistence.*;  import java.time.LocalDateTime;    @Data  @Entity  @Table(name = "users")  public class User {      @Id      @GeneratedValue(strategy = GenerationType.IDENTITY)      private Long id;        @Column(name = "username", unique = true, nullable = false, length = 100)      private String username;        @Column(name = "email", unique = true, nullable = false, length = 100)      private String email;        @Column(name = "password", nullable = false)      private String password;        @Column(name = "created_at", nullable = false)      private LocalDateTime createdAt;  }    

Interface of User repository:

package com.gokturk.microserviceuser.repository;    import com.gokturk.microserviceuser.model.User;  import org.springframework.data.jpa.repository.JpaRepository;    public interface IUserRepository extends JpaRepository<User, Long> {      User findByUsername(String username);  }  

Interface of User Service:

package com.gokturk.microserviceuser.service;    import com.gokturk.microserviceuser.model.User;  import org.springframework.stereotype.Service;    import java.util.List;    @Service  public interface IUserService {      User saveUser(User user);      User findByUsername(String username);      List<User> findAllUsers();  }  

User service:

package com.gokturk.microserviceuser.service;    import com.gokturk.microserviceuser.model.User;  import com.gokturk.microserviceuser.repository.IUserRepository;  import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.context.annotation.Bean;  import org.springframework.security.crypto.password.PasswordEncoder;  import org.springframework.stereotype.Service;    import java.time.LocalDateTime;  import java.util.List;    @Service  public class UserService implements IUserService{      @Autowired      private IUserRepository userRepository;        @Bean      private PasswordEncoder passwordEncoder(){          return passwordEncoder();      }        @Override      public User saveUser(User user) {          user.setPassword(passwordEncoder().encode(user.getPassword()));          user.setCreatedAt(LocalDateTime.now());          return userRepository.save(user);      }        @Override      public User findByUsername(String username) {          return userRepository.findByUsername(username);      }        @Override      public List<User> findAllUsers() {          return userRepository.findAll();      }  }  

Update an existing nested property in Mongoose retrived object

Posted: 10 Aug 2021 07:53 AM PDT

Got a schema like

  const TestSchema = new mongoose.Schema({        foo:[{            foo_id: mongoose.Schema.ObjectId,          foo_name: String,            bar:[{                bar_id: mongoose.Schema.ObjectId,              bar_name: String,                baz:[{                    baz_id: mongoose.Schema.ObjectId,                  baz_name: String,              }]          }]      }]  })    module.exports = mongoose.model("Test", TestSchema, "tests");    

foo holds an array of objects, those foo objects all are "grandparent" level objects which may optionally contain a property bar that again holds an array containing objects all those will be "father" level objects. And again in those father level objects we may have a property baz which holds again array of objects those are like "child" level objects

I have retrived an object using findOne()

  {      foo:[          {              foo_id: "60fa62fcc37dd7caab965ef7",              foo_name: 'this is 1st foo'          },          {              foo_id: "61056862936f599b9e32472b",              foo_name: 'this is 2nd foo',                bar:[                  {                      bar_id: "60fa62fcc37dd7caab965ef4",                      bar_name: 'this is 1st bar inside 2nd foo',                  },                  {                      bar_id: "61056862936f599b9e324729",                      bar_name: 'this is 2nd bar inside 2nd foo',                        baz:[                          {                              baz_id: "60f822b80d641754a4878bc5",                              baz_name: 'this is 1st baz inside 2nd bar inside 2nd foo',                          },                          {                              baz_id: "60f822b80d641754a4878bc9",                              baz_name: 'this is 2nd baz inside 2nd bar inside 2nd foo',                          }                      ]                  },              ]          },          {              foo_id: "60fa62fcc37dd7caab965ef7",              foo_name: 'this is 3rd foo'          }        ]  }  

Now suppose I have the object I changed the value of the property baz_name whose baz_id happens to be 60f822b80d641754a4878bc9

var obj = await Test.findOne(id).exec()  obj.foo[1].bar[1].baz[1] = 'you have been changed!'  //but how we shall update you? in db   

I want to do something like this provided answer but accomdate the "JSON path" indexes as well

How to record screentime in c++?

Posted: 10 Aug 2021 07:53 AM PDT

I am a newbie to C++ and wanted to create a Screentime application like in ios for windows. But unfortunately, I am stuck after creating the default bootstrap by using visual studio 2019. Can anyone suggest to me where I should do next and other related resources? I just wanted to create a simple app (let's say screentime) that monitors other apps active and focused state whenever the screentime app is run and store the app name, start time and end time it in a text file.

Want to show a menu bar over image modal in "react-native-image-layout" to provide option for image like delete, etc

Posted: 10 Aug 2021 07:53 AM PDT

Background: So I am Implementing react-native-image-layout to create a gallery view where you can click on the image and then the image appears on modal and then you have headers and footers where you can add buttons which can do some functionality like close the modal n all.

Example: Now I want something like this: like there is a menu popped over

My Implementation: And this is where I actually want it. The ImageViewer I created <--- I want the menu when I click that dot-horizontal button.

ERROR: No matching distribution found for snowflake-connector-python==2.5.0

Posted: 10 Aug 2021 07:53 AM PDT

I am trying to install the Snowflake Connector and am getting an error.

pip install -r https://raw.githubusercontent.com/snowflakedb/snowflake-connector-python/v2.5.0/tested_requirements/requirements_36.reqs  pip install snowflake-connector-python==2.5.0  

This results in:

ERROR: Could not find a version that satisfies the requirement snowflake-connector-python==2.5.0 (from versions: 1.3.17, 1.3.18, 1.4.0, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.6.0, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.6.12, 1.7.0, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8.0, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.9.1, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.2.0, 2.2.1, 2.2.2, 2.2.3, 2.2.4, 2.2.5, 2.2.6, 2.2.7, 2.2.8, 2.2.9, 2.2.10, 2.3.0, 2.3.1, 2.3.2, 2.3.3, 2.3.4, 2.3.5, 2.3.6, 2.3.7, 2.3.8, 2.3.9, 2.3.10, 2.4.0, 2.4.1, 2.4.2, 2.4.3, 2.4.4, 2.4.5, 2.4.6, 2.5.0, 2.5.1)  ERROR: No matching distribution found for snowflake-connector-python==2.5.0  

Any suggestions?

How would you reference a password MD5 hash in Discord.py?

Posted: 10 Aug 2021 07:53 AM PDT

I have written an amateur python script for password cracking. I am trying to crack my own password using such a device, but am having trouble. My problem is this: I need to somehow reference someone's discord password in the code. I have downloaded the Discord.py API and imported it via import discord. Being new to Python and APIs, I am frankly a complete idiot in this endeavor.

I understand people's passwords are typically encoded in MD5 hashes which are what can try to be cracked. But does anybody know how I might be able to reference such a hash from the Discord API so I can store it in a variable and try and use the variable to match the hash?

I have also been told that MD5 hashes are no longer considered secure, so does Discord use a different type of encryption I would have to use? Whatever the encryption is, I would appreciate being told what to do in this scenario and how I have to accomplish this.

I have no idea what I am doing, so now that you understand my motives, please correct anything I am doing wrong. I would appreciate help VERY much. Thank you, and have a good day!

Capitalization not displayed in Django site after modifying Django models.py

Posted: 10 Aug 2021 07:52 AM PDT

how to check inputstream is password protected or not using java

Posted: 10 Aug 2021 07:52 AM PDT

i want to check whether given Input Stream(byte []) is password protected. i googled lots of website but all are specific file type , want generic API which will work for all file type. thanks in advance

How do I connect Manticore search to Apache Nutch crawled results folder?

Posted: 10 Aug 2021 07:52 AM PDT

Im been trying to connect manticore search to nutch for a while but no coders is able, the way to do this is by pointing Manticore to Apache saved search results but coders say is not as easy as described. Im not sure if a plugin needs to be created or just adding a url to folder that contains search results.

Manticore Search https://youtu.be/-5lB6_L28gw

Thanks for reading this

upgrade to angular 12 with optimization flag set to true, breaks php files

Posted: 10 Aug 2021 07:52 AM PDT

I am using a index.php files on my angular application, when I build my project using ng build, the php tags in my index.php gets commented like so enter image description here

I found that setting optimization to false fixes this problem and the file gets build corretly as following : enter image description here

However, using optimization set to true with angular 9 10 and 11 was working fine. This is only happening after upgrading the application to angular 12.

I can't find any documentation about angular 12 upgrade that could causes this behavior.

I would like to still use optimization set to true because this is a good usage of angular since it optimizes the code.

enter image description here

Also When reading about optimization flag, I see no reason why this would comment out my php tags inside my index.php, unless this is considered maybe dead-code and angular comments it for performance issue ?

Here is my build configuration : enter image description here

asyncio Add Callback after Task is completed, instead of asyncio.as_completed?

Posted: 10 Aug 2021 07:52 AM PDT

In asyncio, it there a way to attach a callback function to a Task such that this callback function will run after the Task has been completed?

So far, the only way I can figure out is to use asyncio.completed in a loop, as shown below. But this requires 2 lists (tasks and cb_tasks) to hold all the tasks/futures.

Is there a better way to do this?

import asyncio  import random      class Foo:      async def start(self):          tasks = []          cb_tasks = []            # Start ten `do_work` tasks simultaneously          for i in range(10):              task = asyncio.create_task(self.do_work(i))              tasks.append(task)              # How to run `self.handle_work_done` as soon as this `task` is completed?            for f in asyncio.as_completed(tasks):              res = await f              t = asyncio.create_task(self.work_done_cb(res))              cb_tasks.append(t)            await asyncio.wait(tasks + cb_tasks)        async def do_work(self, i):          """ Simulate doing some work """          x = random.randint(1, 10)          await asyncio.sleep(x)          print(f"Finished work #{i}")          return x        async def work_done_cb(self, x):          """ Callback after `do_work` has been completed """          await asyncio.sleep(random.randint(1, 3))          print(f"Finished additional work {x}")      if __name__ == "__main__":      foo = Foo()      asyncio.run(foo.start())  

Dumb regular expressions question - what is grep("^c\\.", names(df)) doing?

Posted: 10 Aug 2021 07:53 AM PDT

What the title says. I found that bit in a code fragment and it's returning "numeric(0)" for my data so I am unable to determine what it's doing except to know that it's not locating anything in my data.

I admit I am very ignorant in the various ways to compose a regular expression so if anyone has a good reference for it for R I'd love to bookmark it.

I didn't include any reproducible data because I am really just asking a coding question, not a data-driven solution.

How can I check whether innerHTML is empty?

Posted: 10 Aug 2021 07:52 AM PDT

so i am trying to set a Class on a Parent Element (Section), when the second Child Div innerHTML is empty.

So for example: (This Section should get a class of "hide-section" to hide it)

<section class="ef-area">     <div class="child-1">         <div class="child-2">         </div>     </div>  </section>  

This one should not be hidden because "child-2" is not empty

<section class="ef-area">     <div class="child-1">        <div class="child-2">           <div class="child-3">              ...//What Ever           </div>        </div>    </div>  </section>  

I looped over all "ef-area" sections but how can i set only those sections to display = none when the second child (child-2) is empty.

What I did is:

    let efAreaDivs = document.querySelectorAll(".ef-area > div > div");          for (singleDiv of efAreaDivs) {            if (singleDiv.innerHTML == "") {        singleDiv.closest("section").classList.add("hide-section");      }  

The class "hide-section" never gets set.

I think js always ignores it, because there are singleDiv´s that are not empty or am I wrong?

How do I add blog posts to my website automatically with js?

Posted: 10 Aug 2021 07:53 AM PDT

guys! So, I'm planning on building a blog from scratch using html, css and javascript.

I don't want to create a new html file and manually add it everytime I write an article.

How can I automate this process? Can I use javascript to do that? Maybe node.js?

Ps I'm aware that it would be easier to build one using WordPress and the likes but I have my reasons for doing it this way, thanks.

Is it possible to trigger a lambda init in AWS?

Posted: 10 Aug 2021 07:53 AM PDT

Aws lambdas have 3 steps in their lifecycle:

  • init
  • invoke
  • shutdown

Is there a way to trigger automatically a lambda init without deploying any code?

Update:

I have some actions that are launched during the init: saving the content of a file in a variable. Then during the invoke actions, the content is not downloaded anymore. But I need to launch the action of downloading from time to time. Then, I was wondering if there's a way to trigger the init action.

How to call NavController from fragment?

Posted: 10 Aug 2021 07:53 AM PDT

In my fragment_main.xml, I have the following code :

<?xml version="1.0" encoding="utf-8"?>  <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      android:layout_width="match_parent"      android:layout_height="match_parent">        <androidx.fragment.app.FragmentContainerView          android:id="@+id/nav_host_fragment"          android:name="androidx.navigation.fragment.NavHostFragment"          android:layout_width="match_parent"          android:layout_height="0dp"          app:layout_constraintBottom_toTopOf="@+id/bottomBar"          app:layout_constraintEnd_toEndOf="parent"          app:layout_constraintStart_toStartOf="parent"          app:layout_constraintTop_toTopOf="parent"          app:navGraph='@navigation/bottom_bar_nav_graph' />      <!--custom bottom navigation ui-->    </androidx.constraintlayout.widget.ConstraintLayout>  

I would like to have access to navController(bottom_bar_nav_graph) from fragment. Is it possible?

null values passed when passing ITestContext attribute value to onTestStart method

Posted: 10 Aug 2021 07:53 AM PDT

I want to pass the variables that I set using ITestContext to onTestStart

   public void login(ITestContext Test){          Test.setAttribute("nodeName","05 test");          Test.setAttribute("nodeDetails","05 This belongs to regresion test");     }  

I used below code but only null values get printed.

 @Override      public void onTestStart(ITestResult result) {          //get the node name          String node= (String) result.getTestContext().getAttribute("nodeName");          String nodeDetails= (String) result.getTestContext().getAttribute("nodeDetails");          System.out.println("onTestStart node is "+node);          System.out.println("onTestStart nodeDetails is* "+nodeDetails);  }  

However, I did notice that when I put it to onTestSuccess method.

My original requirement is to pass the node name and node details for extent's report node creation in onTestStart method. Kindly help.

test = report.createTest(result.getMethod().getMethodName()).createNode(node).pass(nodeDetails);  

Search in SQLite Inserted Data in the ListView with The EditText?

Posted: 10 Aug 2021 07:53 AM PDT

RecordListActivity.Java

//        query   String select = "Select name, phone from RECORD Where(name like " + "'%name%'" +                  ")";              Cursor cursor2 = mSQLiteHelper.searchData(select);              if (cursor2.getCount() > 0 ){                  Toast.makeText(RecordListActivity.this, "Not Found", Toast.LENGTH_SHORT).show();              }  

// SearchView

mSearchView.addTextChangedListener(new TextWatcher() {              @Override              public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {                  Log.d("data", charSequence.toString());              }                @Override              public void onTextChanged(CharSequence charSequence2, int i, int i1, int i2) {                    }                @Override              public void afterTextChanged(Editable editable) {                }          });  

database

public Cursor searchData(String sql2){            SQLiteDatabase database = this.getReadableDatabase();          return database.rawQuery(sql2,null);          }  

Model

private int id;      private String name;      private String phone;        public Model(int id, String name, String phone) {          this.id = id;          this.name = name;          this.phone = phone;      }        public int getId() {          return id;      }        public void setId(int id) {          this.id = id;      }        public String getName() {          return name;      }        public void setName(String name) {          this.name = name;      }        public String getPhone() {          return phone;      }        public void setPhone(String phone) {          this.phone = phone;      }  

my goal is to search the listview by phrases. When a keyword is entered in the search (EditText), I want the listview to be filtered accordingly. I already have the EditText ready there, while, I am new that's why don't know how to do that, please help me? thanks

Search(Edittext), it takes keyword but doesn't show what I have given in the input

Does Paginator from django.core.paginator reduces the load on server?

Posted: 10 Aug 2021 07:52 AM PDT

I am using Django.core.paginator for splitting the data into pages in the Django web framework.

data = emodel.objects.filter(Id=e_id, Date__range=(start_date,end_date))  

and in paginator:

page = request.GET.get('page', 1)      paginator = Paginator(data, settings.PAGE_LIMIT)            try:          data_list = paginator.page(page)      except PageNotAnInteger:          data_list = paginator.page(1)      except EmptyPage:          data_list = paginator.page(paginator.num_pages)              context = {"data_list":data_list}        return render(request, 'my_app/data.html', context)  

Does the result fetch all queries first and then split it? or only PAGE_SIZE get fetched from a database?

if "Yes" then, Is there any method to reduce the server load along with model.objects.filter(....)

Masking a Substring in Hive Views

Posted: 10 Aug 2021 07:53 AM PDT

I need to create a View on top of a Hive Table, masking data in a particular column. The Table has a column of String Type. The data in that particular column is of JSON structure. I need to mask a value of a particular field say 'ip_address'

{"id":1,"first_name":"john","last_name":"doe","email":"sample@123.com","ip_address":"111.111.111.111"}  

expected:

{"id":1,"first_name":"john","last_name":"doe","email":"sample@123.com","ip_address":null}  

These are the few Built-in Hive Functions I have tried, they don't seem to help my cause.

  • mask
  • get_json_object
  • STR_TO_MAP
  • if clause

Also I don't think substring and regexp_Extract are useful here coz the position of the field value is not always predetermined plus I'm not familiar with regex expressions.

PS: Any help is appreciated that would help me avoid writing a new UDF.

Is it possible to integrate nvcc with gcc/g++ in windows?

Posted: 10 Aug 2021 07:52 AM PDT

I would linke to know if it is possible to use gcc/g++ as the c/c++ compiler in windows based CUDA? Furthermore, how can I compile fortran together with nvcc? I am running CUDA 10.2 and the mingw gcc 8.1.0.

How to write unit test for gcloud storage?

Posted: 10 Aug 2021 07:53 AM PDT

I want to write unit test for the below code

var (      NewClient = storage.NewClient  )  client, err := NewClient(ctx)  bucket := client.Bucket(BucketName)  if _, err := bucket.Attrs(ctx); err != nil {      bucket.Create(ctx, projectId, nil)  rc, err := client.Bucket(BucketName).Object("object1").NewReader(ctx)  

bucket.Create() and bucket.Attrs() are http calls, also Bucket(), Object() and NewReader() returning structs(So in my sense there is no meaning of implement interface for this use case)

Note: storage.NewClient() is also http call but i am avoiding external call using monkey pathching approch in my test by providing custom implementaion.

var (      NewClient = storage.NewClient  )  

Getting Country Name from coordinates takes too Long

Posted: 10 Aug 2021 07:53 AM PDT

I have a data from NASA websites which has bunch of coordinates and from these coordinates, I'm trying to find which country they belong via geopy in every 1 hour. But unfortunately it takes quite a lot to get the country names .

How can I reduce the process of time ?

Here's my code;

import pandas as pd  import numpy as np  from geopy.geocoders import Nominatim  geolocator = Nominatim(user_agent="geoapiExercises")    df=pd.read_csv("https://firms.modaps.eosdis.nasa.gov/data/active_fire/modis-c6.1/csv/MODIS_C6_1_Europe_24h.csv")  df.latitude=df.latitude.astype(str)  df.longitude=df.longitude.astype(str)      country_list=[]    for i in range(len(df)):      try:          location = geolocator.reverse(df.latitude[i]+","+df.latitude[i])          country=location.raw["address"]["country"]          country_list.append(country)      except:          country_list.append("None")          print(i)          continue    df_s=pd.Series(country_list)  df["Country"]=df_s  df.to_csv("map_data_R00.csv",index=False)  

How do I filter values from a many to many relationship?

Posted: 10 Aug 2021 07:52 AM PDT

If i have a many to many relationship between articles and tags, what is the best way to go about selecting all articles that contain tags that a specific user has stored?

For this example, assume there's a users table with a user_id column. Articles

Article_id Article_name
1 Dogs
2 Cats
3 Sheep

Tags

Tag_id
Pets
Outdoors
Grass

Article_Tags

Article_id tag_id
1 Pets
1 Grass
1 Outdoors
2 Outdoors
3 Grass
3 Outdoors

Users_Tags

User_id tag_id
User1 Pets
User1 Grass
User2 Pets

If I wanted to show all articles that has any of the tags that a user has stored associated with their id in Users_Tags, what would be the best way to do so? I mettled with nested selects and inner joins but I couldn't logic out the best way to go about this.

For example, since User1 has the tags Pets and Grass stored with their User_id, I would want to return the articles with the ID of 1 and 2, since both of those articles have at least one of the users' stored tags associated with it.

Article_id | Article_ Name |Tag_id       1     |       Dogs    |  Pets       1     |       Dogs    |  Grass       3     |       Sheep   |  Grass  

A sample output is provided above. I included repeats of the same article for clarities sake, although in reality I would like to only repeat an article a single time.

Can this rxjs merge logic be simplified?

Posted: 10 Aug 2021 07:53 AM PDT

I have an observable (onAuthStateChanged) from the Firebase client that:

  1. emits null immediately if the user is not signed in, and
  2. emits null and then a user object a few moments later if the user is signed in.
const observable = new Observable((obs) => {      return app.auth().onAuthStateChanged(          obs.next,          obs.error,          obs.complete      )  })  

What I want is to:

  1. ignore any emitted null values for the first 1000ms of the app lifecycle (null coming after 1000ms is accepted)
  2. always emit user object regardless of what time it comes
  3. if no user object comes in the first 1000ms, then emit null at the 1000ms mark

Here is what I've done (and it seems to work). However, I'm reluctant to use this code as it doesn't seem that concise:

const o1 = observable.pipe(skipUntil(timer(1000)))    const o2 = observable.pipe(      takeUntil(o1),      filter((user) => user !== null)  )    const o3 = timer(1000).pipe(takeUntil(o2), mapTo(null))    merge(o1, o2, o3).subscribe({      next: setUser,      error: console.log,      complete: () => console.log("error: obs completed, this shouldn't happen"),  })  

Is there a way to do this without merge? I tried going through the docs but I'm quite lost.

Thanks for your help!

Dynamic file creation in COBOL/JCL

Posted: 10 Aug 2021 07:53 AM PDT

I have an requirement, Where I have to read DB2 table and create multiple output file, one for each program name in the table. We don't know how many unique program name in the table. My job will run every 4 hrs. So for eg: my first run may have 10 program name and I will have to create 10 output file and second run may 20 program name and 20 output files.

I'm looking for a dynamic way to create DD name and file name in the JCL as well in my COBOL program. So I don't want to define 20 or max DD statement in my JCL, as this 20 can be 50,60....

Please help me with the possibilities.

PySimpleGui - how do you remove text from input text box

Posted: 10 Aug 2021 07:53 AM PDT

How do you clear text in an input box PySimpleGui? I'm trying window ['-INPUT-'] ('') but I recieve a key error. I want it so that the text in the box gets replaced with an empty string after each iteration so the user doesn't have to delete the text themselves.

Flutter/Dart/Firestore: How can I add a list of maps to firebase?

Posted: 10 Aug 2021 07:53 AM PDT

Sorry if this is a repeated question. I have tried searching around but have been unable to find a solution to this problem.

I have a list of maps in dart. For example:

List<Map<String, String>> questionsAndAnswers = [{'questions':'How many?', 'answer':'five'},  {'question':'How much?', 'answer':'five dollars'}];  

I would like to store this list of maps into firestore and I have seen that you can manually create an array of maps but I would like to do this programmatically.

enter image description here

Does anyone know how this can be achieved? I've tried _firestore.collection('Quiz').add(questionsAndAnswers); but this hasn't been successful and I'm receiving the following error: The argument type 'List<Map<String, String>>' can't be assigned to the parameter type 'Map<String, dynamic>'.

Thank you in advance for all your help.

No comments:

Post a Comment