Thursday, May 26, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


how to make generic component in react native?

Posted: 26 May 2022 01:26 PM PDT

I want to make a generic component but how can I make it ?

Model:

export interface ISelectOptionsRLV<T, C> {    data: T[];    onPress: (option: C[]) => void;  }  

GenericComponentList:

import { StyleSheet, Text, View, FlatList } from 'react-native'  import React from 'react'  import { ISelectOptionsRLV } from './Model'    const SelectOptionsRLV = ({ data, onPress }: ISelectOptionsRLV) => {    return (      <FlatList        data={data}        ...      />    )  }    export default SelectOptionsRLV    const styles = StyleSheet.create({})  

Now I get this error:

Generic type 'ISelectOptionsRLV<T, C>' requires 2 type argument(s)  

I know this error I have to set my types, but then its not generic, I mean I need 4 of my flatlist components and each data type is different. So then I have to make 4 Files, or how I can do it? I want all my data thats come in the component generic so I dont want tocreate 4 Component I want one Flatlist component and use it everytime

How can I track multiple AugmentedImages at once?

Posted: 26 May 2022 01:26 PM PDT

I am trying to scan multiple Augmented Images at once. For this, I added an onUpdateListener on my AR Scene

if(isImageDetected){      return;  }  Collection<AugmentedImage> augmentedImages = frame.getUpdatedTrackables(AugmentedImage.class);    for(AugmentedImage augmentedImage : augmentedImages){      if(augmentedImage.getTrackingState() == TrackingState.TRACKING){          String imageResourceName = augmentedImage.getName();          if(imageResourceName.equals("pic1.png")){              isImageDetected = true;              renderAndPlayVideo(augmentedImage, R.raw.vid1);          }          if(imageResourceName.equals("pic2.png")){              isImageDetected = true;              renderAndPlayVideo(augmentedImage, R.raw.vid2);          }        }    }  

Obviously, by setting the isImageDetected flag to true, the app will not try to scan at every phone movement to prevent crashes. However, it's also stopping me from scanning two images at once.

Any ideas are appreciated. Thank you.

How to update or manually set a value for timestamp in winston?

Posted: 26 May 2022 01:26 PM PDT

I have a specific requirement where I need to be able to manually set the timestamp value for a log in winston. The use case can be described as being a time machine, so I need to be able to see how logs would have been output going back through time.

I see that the format.timestamp(opts?: TimestampOptions) method has options, but it appears to only be for formatting.

Is there a way to do it without creating a custom logger?

Thanks in advance!

Option to unlink cask from brew (or skip updating)

Posted: 26 May 2022 01:25 PM PDT

I did install mactex 2021 with brew, but now when I run brew update && brew upgrade brew wants to update mactex to Version 2022.0321 - which I do not want for personal reasons. Is there a way to either permanently skip the updating of a cask with brew (similar to brew pin, see https://apple.stackexchange.com/a/435914) or to remove brews knowledge that this cask was installed by brew and thus skipping all updates?

Thanks!

Uncaught ReferenceError: jQuery is not defined error when using select2

Posted: 26 May 2022 01:25 PM PDT

I have read this: Uncaught ReferenceError: jQuery is not defined

Which led me to this: Uncaught ReferenceError: $ is not defined?

After understanding the problem that I was not referencing jQuery before I was using it I changed my code.

From this:

<head>      <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />      <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>  </head>  

I moved jQuery to the top like this:

<head>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>      <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />      <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>  </head>  

That fixed my first Uncaught ReferenceError. I am however still getting the same error but from select2.

Uncaught ReferenceError: jQuery is not defined      <anonymous> https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js:2      <anonymous> https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js:2  select2.min.js:2:83  

I do not know how to reference it any sooner and ever their own page shows how to setup the code.

How to update radio button checked status with keyboard in real time JS

Posted: 26 May 2022 01:26 PM PDT

So I have an accordion with invisible radio buttons. Everything works fine and well, until I try to get the status of the radio button. I have 4 rows of the following code for each accordion radio button:

const ac1 = document.getElementById('ac-1');  

Radio buttons wrapped in a form:

<form class="ac-container">  <input id="ac-1" name="accordion-1" type="radio" checked="checked">  <input id="ac-2" name="accordion-1" type="radio">  <input id="ac-3" name="accordion-1" type="radio">  <input id="ac-4" name="accordion-1" type="radio">  </form>  

And this is my radio button CSS:

.ac-container input {      opacity: 0;  }  

To check the status of the radio button I've tried:

if (ac1.checked) {    //do something  }     if (document.getElementById('ac-1').checked) {    //do something  }  

I need the radio button status so I can display stuff in real time. For regular clicks I'm just using addEventListener('click', (e) => {} and it works fine, but I need the radio buttons to also function with keyboard. That's why I need the status, so if a radio button is checked I can immediately update what's needed.

I'm not sure if this is the problem but, when I click on the radio buttons, the 'checked' attribute never transfers from one button to the other?

I'll keep looking and update if I find anything.

Python deploying django with django channels on heroku

Posted: 26 May 2022 01:26 PM PDT

I have been trying to deploy my application on heroku with django channels and I always get the following error

2022-05-26T20:09:58.137436+00:00 app[web.1]: ModuleNotFoundError: No module named 'core'  

I have seen previous questions such as Deploying asgi and wsgi on Heroku but even when following these steps I can't get the deployment to work.

My channel layers in settings.py:

ASGI_APPLICATION = "server.asgi.application"  CHANNEL_LAYERS = {      'default': {          'BACKEND': 'channels.layers.InMemoryChannelLayer',      },  }  

My asgi.py:

import os    from django.core.asgi import get_asgi_application    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')    application = get_asgi_application()  

My wsgi.py file

import os    from django.core.wsgi import get_wsgi_application    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')    application = get_wsgi_application()  

My Procfile

web: daphne server.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2  chatworker: python manage.py runworker --settings=server.settings -v2  

My file structure

server      |      |_ _ chat      |   |      |   |_ __init__.py      |   |      |   |_ admin.py      |   |      |   |_ consumers.py      |   |      |   |_ models.py      |   |       |   |_ routing.py      |   |       |   |_ urls.py      |   |      |   |_ views.py      |_ _ server      |   |      |   |_ __init__.py      |   |      |   |_ asgi.py.py      |   |      |   |_ routing.py      |   |      |   |_ settings.py      |   |       |   |_ urls.py      |   |      |   |_ wsgi.py      |      |_ _ manage.py      |      |_ _ Procfile      |      |_ _ requirements.txt      |      |_ _ __init__.py  

Put text on top div that is inside another div

Posted: 26 May 2022 01:25 PM PDT

I want to put the text over the div that is containing an image and that div is inside another div that also has an image.

.marioHeader {    background-image: url("resources/marioBackground.jpg");    background-size: 600px;    height: 500px;    background-position: bottom;    display: flex;    justify-content: center;    align-items: center;    background-repeat: repeat-x;    background-color: #6096ff;    margin-top: 50px;    text-align: center;  }    .title {    text-align: center;  }    .headermario {    background-image: url("resources/banner.png");    background-size: 600px;    background-repeat: no-repeat;    background-position: bottom;    background-color: red;    height: 200px;    width: 90%;  }
<div class="marioHeader">    <h1 class="title">Super Mario</h1>    <div class="headermario">    </div>  </div>

It looks like this: enter image description here

I want it to look like this: enter image description here

Is DEGSeq software appropriate for gene expression analysis? Are the software statistical assumptions wrong?

Posted: 26 May 2022 01:25 PM PDT

I have received a paper for review and they have used DEGSeq for gene expression analysis. I have seen several gene expression software like DESeq2, EdgeR, Limma, Cuffdiff2 used widely, but not DEGSeq! In a post from Biostars, it has been mentioned that the statistical assumption of DEGSeq software is wrong and it shouldn't be used at all! Here is the link for the manuscript of DEGSeq software. I am wondering if anyone can help me understanding if the proposed assumptions of the software are incorrect and why, in a laidback manner. I appreciate it!

Deserializing JSON into C# Product ID with Shopify API

Posted: 26 May 2022 01:26 PM PDT

Hi I am trying to deserialize this json. And my application does not do it for me.

i am using c#

any suggestion? thanks

this way i try to deserialize

            var deserialize = resultado.Content.ReadAsStringAsync().Result;              var a = JsonConvert.DeserializeObject<product>(deserialize);  

json received

{"product":{"id":6979552313549,"title":"Balance 100% Whey Protein 2.8kg w\/ FREE Magnesium complete powder","body_html":"Mountaineering backpack","vendor":"Balance","product_type":"physical","created_at":"2022-05-16T17:41:57-06:00","handle":"balance-100-whey-protein-2-8kg-w-free-magnesium-complete-powder-1","updated_at":"2022-05-26T12:34:07-06:00","published_at":"2022-05-16T17:41:57-06:00","template_suffix":null,"status":"active","published_scope":"web","tags":"Protein Powders, Specials, Stacks and Packs, Whey Protein Blend (WPI\/WPC)","admin_graphql_api_id":"gid:\/\/shopify\/Product\/6979552313549","variants":[{"id":40875072585933,"product_id":6979552313549,"title":"Default Title","price":"700.00","sku":"","position":1,"inventory_policy":"deny","compare_at_price":null,"fulfillment_service":"manual","inventory_management":"shopify","option1":"Default Title","option2":null,"option3":null,"created_at":"2022-05-26T12:34:07-06:00","updated_at":"2022-05-26T12:34:07-06:00","taxable":true,"barcode":null,"grams":0,"image_id":null,"weight":0.0,"weight_unit":"kg","inventory_item_id":42969806831821,"inventory_quantity":0,"old_inventory_quantity":0,"requires_shipping":true,"admin_graphql_api_id":"gid:\/\/shopify\/ProductVariant\/40875072585933"}],"options":[{"id":8937193341133,"product_id":6979552313549,"name":"Title","position":1,"values":["Default Title"]}],"images":[{"id":30230589407437,"product_id":6979552313549,"position":1,"created_at":"2022-05-26T12:34:07-06:00","updated_at":"2022-05-26T12:34:07-06:00","alt":null,"width":2862,"height":2143,"src":"https:\/\/cdn.shopify.com\/s\/files\/1\/0618\/4189\/9725\/products\/Definici_C3_B3n-del-producto-y-servicio_0bf23268-fee3-4b3b-a577-aeaa2336d6fc.png?v=1653590047","variant_ids":[],"admin_graphql_api_id":"gid:\/\/shopify\/ProductImage\/30230589407437"}],"image":{"id":30230589407437,"product_id":6979552313549,"position":1,"created_at":"2022-05-26T12:34:07-06:00","updated_at":"2022-05-26T12:34:07-06:00","alt":null,"width":2862,"height":2143,"src":"https:\/\/cdn.shopify.com\/s\/files\/1\/0618\/4189\/9725\/products\/Definici_C3_B3n-del-producto-y-servicio_0bf23268-fee3-4b3b-a577-aeaa2336d6fc.png?v=1653590047","variant_ids":[],"admin_graphql_api_id":"gid:\/\/shopify\/ProductImage\/30230589407437"}}}

Unit tests for verifying html string in java spring boot

Posted: 26 May 2022 01:25 PM PDT

I am looking for a way to write unit/integration test for verifying html string in java spring boot. (I already checked with JSOUP, looking for a best practice)

NoSuchElementException: no such element: Unable to locate element during web scrape

Posted: 26 May 2022 01:25 PM PDT

I am trying to scrape this website: https://www.tripadvisor.com/Restaurants-g293718-Algiers_Algiers_Province.html

I used this code:

driver.Navigate().GoToUrl("https://www.tripadvisor.com/Restaurants-g293718-Algiers_Algiers_Province.html");            var collection = driver.FindElements(By.XPath("//div[@class='cauvp Gi o']"));    foreach (var item in collection)  {      string name = item.FindElement(By.XPath(".//a[@class='bHGqj Cj b']")).Text;      string location = "Algiers";      string type = item.FindElement(By.XPath(".//div[@class='bhDlF bPJHV eQXRG']/span/span")).Text;      IWebElement img= item.FindElement(By.XPath(".//div[@class='bdLpT w carousel fjXXd ddFHE']/div/ul/li/div"));            string image = img.GetCssValue("background-image").Replace("url(\"",string.Empty).Replace("\")",string.Empty);      string link = item.FindElement(By.XPath(".//a[@class='bHGqj Cj b']")).GetAttribute("href");  }  

But I got this error message:

NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"./a[@class='bHGqj Cj b']"} (Session info: headless chrome=101.0.4951.67)

How do I access files outside the public folder?

Posted: 26 May 2022 01:26 PM PDT

I have a JavaScript file in public/js.

From this file I want to access a .html.twig file located in the project directory in /templates/. How can I access files outside the /public directory?

Replacing Street abbreviations

Posted: 26 May 2022 01:25 PM PDT

I am working with SQL Server and am trying to replace the abbreviations of some of certain streets into its full name.

For example, turning Dr to Drive, St to Street, etc.

I do not want to flat out match the wildcard '%Dr' and replace it with 'Drive' because there might be some street names that contain Dr.

For example, I wrote this code:

SELECT DISTINCT      ssn, first_name, last_name,      CASE           WHEN ADDRESS1 LIKE '%DR.%'              THEN REPLACE(UPPER(ADDRESS1), 'DR.', 'DRIVE')          WHEN ADDRESS1 LIKE '% Dr%'              THEN REPLACE(UPPER(ADDRESS1 ), 'DR', 'DRIVE')          ELSE UPPER(ADDRESS1)      END AS fullAddress,  FROM       table1  

I am using all instances of Dr, Dr., Drive, etc, however one of the addresses are:

Address |   1111 Driftwood Ave  

And if I use the above code, it would turn 'Driftwood' into 'Driveftwood' and that is not my goal. How do I get it to change only when its 'Dr' and nothing else using a pattern match

Can I run Robot tests with Appium Browserstack?

Posted: 26 May 2022 01:26 PM PDT

Can I run tests written Robot Framework in Browserstack for automated testing?

If BrowserStack does not support it which framework supports it?

  • Sauce labs
  • Perfecto
  • Kobiton
  • Headspin

Conditionally use set-retuning function as join clause

Posted: 26 May 2022 01:25 PM PDT

Context:

I'm implementing a "job posting" feature that will list jobs available for users. A job can be set for either an interval start_date and end_date or sparse dates in an array service_dates. The availability check should be made using the previously described date information present at the jobs model against an availabilities model.

Their structures are the following

Jobs

        Column          |             Type                                 -------------------------+------------------------------   id                      | bigint                           service_dates           | timestamp without time zone[]   start_date              | timestamp without time zone      end_date                | timestamp without time zone    

Availabilities

        Column          |             Type                                 -------------------------+------------------------------   id                      | bigint                           date                    | date   spaces_left             | integer     

When joining then, I wanna cross the job's dates with the matching dates that exist in the availabilities table. The problem is that the job's dates are available in two different ways.

For sparse dates I can have it working if I do the following left join:

SELECT j.*  FROM jobs j  LEFT JOIN       availabilities a           ON a.user_id = 1234          AND a.date in (            --this will compose a set of the sparse dates            SELECT UNNEST(j.service_dates)          )  

For the start_date and end_date option this will do the trick:

SELECT j.*  FROM jobs j  LEFT JOIN       availabilities a           ON a.user_id = 1234          AND a.date in (            --this will compose a set with the date range between the two dates            SELECT GENERATE_SERIES(j.start_date::date, j.end_date::date, '1 day'::interval)          )  

My problem is that I need to apply either one or another based on the condition of jobs.service_dates being present for the particular job record. Originally I thought I could do the following:

SELECT j.*  FROM jobs j  LEFT JOIN       availabilities a           ON a.user_id = 1234          AND a.date in (            -- use one or the other based on whether or not there's something on j.service_dates            CASE cardinality(j.service_dates) > 0            WHEN TRUE THEN               (SELECT UNNEST(j.services))            ELSE              (SELECT GENERATE_SERIES(j.start_date::date, j.end_date::date, '1) day'::interval)            END          )  

But I get the following error: ERROR: more than one row returned by a subquery used as an expression

if I try to select from whatever would be returned by the CASE statement there I get the follwing: ERROR: set-returning functions are not allowed in CASE

I think I have what I need in terms of how to logically relate the tables within the scenarios that can be presented already figured out. What I need is a way to conditionally apply either logic.

Closure won't capture argument

Posted: 26 May 2022 01:25 PM PDT

I'm a beginner in Rust, I took an example from a tutorial and decided to play around. The function fn new , in Cacher, does not see the second argument, here is closure, i trying to pass |num,num2|. I can't figure out what I'm doing wrong. We work with one argument

struct Cacher<T>    where  T: Fn(u32) -> u32,  {      calculation: T,      value: Option<u32>,      multiplication : T,  }        impl<T> Cacher<T>  where      T:  Fn(u32) -> u32,  {         fn new(calculation: T, multiplication : T) -> Cacher<T> {          Cacher {              calculation,              value: None,               multiplication,          }      }  fn generate_workout(intensity: u32, random_number: u32, test_test_multiplication: u32,) {      let mut expensive_result = Cacher::new( |num,num2|  {          println!("calculating slowly...");          thread::sleep(Duration::from_secs(2));          num + num2      });  

Here is the error

error[E0061]: this function takes 2 arguments but 1 argument was supplied    --> src/main.rs:43:32     |  43 |       let mut expensive_result = Cacher::new( |num,num2|  {     |  ________________________________^^^^^^^^^^^__-     | |                                |     | |                                expected 2 arguments  44 | |         println!("calculating slowly...");  45 | |         thread::sleep(Duration::from_secs(2));  46 | |         num + num2  47 | |     });     | |_____- supplied 1 argument     |  note: associated function defined here    --> src/main.rs:21:8     |  21 |     fn new(calculation: T, multiplication : T) -> Cacher<T> {    

Find min of max values in a HashMap<String, List<Integer>>

Posted: 26 May 2022 01:26 PM PDT

I have a HashMap like HashMap<String, List<Integer>>, I want to find the maximum value for each map entry and in turn find the minimum of those maximum values. I know this can be done using a couple of for loops. But was wondering if there's another way of doing it (maybe with streams?)

The final result I'm looking for is an integer. Ex:

HashMap<String, List<Integer>> values = new HashMap<>();    values.put("a", Arrays.asList(4, 8, 9, 10)); // max value is 10  values.put("b", Arrays.asList(20, 32, 1, 2)); // max value is 32  values.put("c", Arrays.asList(11, 50, 20, 6)); // max value is 50    // I need the min value out of the above maximums i.e. 10 (final answer)  

Pattern/tactic for exchange data between 2 requests to Web API

Posted: 26 May 2022 01:25 PM PDT

Context

REST API - is some Web application in the Azure Cloud with only one endpoint:

Request: GET /connections/{id}  Response: { "ip": "some ip", "port": 0 }  

The service doesn't have any database or storage.

Client - an application that knows some connectionID and wants to connect to the Server at a specific time (e.g 10:00AM). The Client doesn't know its public IP or the public IP of the Server.

Server - an application that will accept a connection. The Server knows the connectionID and a specific time (e.g 10:00AM) for a possible connection. The Server doesn't know its public IP or the public IP of the Client.

connectionID - can be a server name

Requirements

Implement the only one endpoint (Rendezvous server) for Public IPs exchanging:

  • Return Server public IP to the Client
  • Return Client public IP to the Server

enter image description here After this "Hole Punching" step, they both will do port binding for connection (out of the scope)

Question: Could you please help me to find a proper pattern/tactic/suggestion for the implementation of this exchange endpoint in ASP.NET Core Web API service?

The question is not about how to get IP, or NAT. It just showed for the context!

Implementation

I'm thinking about this:

add some storage to the REST API (could be Blob/Azure Table, not sure about DB).On request

  • check if the record exists, where connectionID == 1ww1 and IP != 162.168.1.75 (that means the Server was first), read the IP value and return
  • check if the record doesn't exist, insert IP = 162.168.1.75, connectionID = 1ww1 and poll the table until the record is returned by condition where connectionID == 1ww1 and IP != 162.168.1.75, read the IP value and return.

Is there a more efficient way to do that? Maybe to avoid table polling and use some events (in memory/Azure Server Bus)? Or use Cosmos DB for data storage and its Change Feed for events?

To read IP I use this code in a controller:

public IActionResult Get([FromQuery] string connectionId)  {      var myIp = HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString();      var myPort = HttpContext.Connection.RemotePort;            // wait on the second connection (can be Client or Server)        var otherIp = ...      var otherPort = ...      return Ok(new Resposne{ Ip = otherIp, Port = otherPort });  }  

Please share your thoughts. Thank you in advance.

How to get data about a specific user from Firebase

Posted: 26 May 2022 01:26 PM PDT

There is a Firebase database into which I drive in some data during registration, they fall into the Users section under the UID key from Auth:

public void writeUserToDB(Object data, String currentUser){      DatabaseReference myRef = mDataBase.child("Users/" + currentUser);      myRef.setValue(data);  }      mRegisterBtn.setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {                      String id = mDataBase.getKey();          String name = mName.getText().toString().trim();          String email = mEmail.getText().toString().trim();          String password = mPassword.getText().toString().trim();          String userBinder = mUserBinder.getText().toString().trim();                      if (TextUtils.isEmpty(email)) {              mEmail.setError("Write your email...");              return;          }          if (TextUtils.isEmpty(password)) {              mEmail.setError("Write your password...");              return;          }          if (TextUtils.isEmpty(name)) {              mName.setError("Write your name...");              return;          }          if (password.length() < 8) {              mPassword.setError("Password must have 8+ symbols.");              return;          }                      fAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {              @Override                public void onComplete(@NonNull Task<AuthResult> task) {                  if (task.isSuccessful()) {                      User newUser = new User(currentUser, id, name, email, password, userBinder);                                              currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();                      writeUserToDB(newUser, currentUser);                        Toast.makeText(Register.this, "Пользователь зарегистрирован.", Toast.LENGTH_LONG).show();                      startActivity(new Intent(getApplicationContext(), MainActivity.class));                    } else {                      Toast.makeText(Register.this, "Произошла ошибка. Повторите." +                              task.getException().getMessage(), Toast.LENGTH_LONG).show();                  }              }          });      }  });  

In firebase it looks like:

Users:    UID: {      email      name      password      userbinder    }  

I need to get this data in MainActivity as String variables to use when another button is clicked.

How do I set region for BigQuery ML.FORECAST(?

Posted: 26 May 2022 01:25 PM PDT

Using BigQuery ML, I create a model in an EU dataset:

CREATE OR REPLACE MODEL mydataset.mymodel...  

It evaluates fine:

ML.EVALUATE(MODEL mydataset.mymodel)...  

but when I try to predict:

ML.FORECAST(MODEL mydataset.mymodel,...  

I get:

Dataset myproject:mydataset was not found in location US   

Why is FORECAST so xenophobic and how can I make it right?

$GOPATH/go.mod exists but should not

Posted: 26 May 2022 01:26 PM PDT

Recently I have started learning to Go but facing some issues. I have done some research but non-work for me.

I get $GOPATH/go.mod exists but should not error. While command go get github.com/bmizerany/pat

Please check

enter image description here

My GOPATH is D:\Go-Workspace\NweWebApp

I have command go mod init github.com/GirishBhutiya/myFirstGoApp before get command.

Also please check my go.mod file in screenshot.

I have just start new project no go files added but still face similar issues.

How to Build object from both base and derived class using generics in java

Posted: 26 May 2022 01:26 PM PDT

Having fetched data from database, and mapped to two POJO, I want to create the same object with these two POJO using generics.

Let's say I mapped data to a base class and a derived class with some field:

public class BaseObj {      String baseVar;    // constructor, getter/setter  }    public class DerivedObj extends BaseObj {      String derivedVar;    // super constructor, getter/setter  }  

I wish to use both baseVar and derivedVar values to form the same object:

public class MyObject {      String myBaseVar;    String myChildVar;     // constructor, getter/setter  }  

How to create a generic method, that can take both base class and derived class, and create MyObject? So far I have tried:

static <T extends BaseObj> MyObject buildObj(T obj) {    MyObject myObj = new MyObject();      myObj.setMyBaseVar(obj.getBaseVar());      // ⬇⬇⬇ The method getDerivedVar() is undefined for the type T ⬇⬇⬇    myObj.setMyChildVar(obj.getDerivedVar());     // Clearly it can't infer getDerivedVar from base class      return myObj;  }  

This is a simplified version, MyObject is a deeply nested one. Is it possible to do that? Since my situation is getting db data mapped to POJO, and these data are related to each other, or is there other way that I'm missing?

Sandbox here

Setting the correct height in vertical mode in Swiper

Posted: 26 May 2022 01:26 PM PDT

It's been days that I'm working on setting the swiper in my application but I still no luck and found no working sample anywhere from here to the Github issues or elsewhere on the net.

I can not set a dynamic height for the swiper in vertical mode via none of the suggested solutions to this problem.

I have several images as slides that give a height of thousands of pixels but if I switch it to a text it is fine as the height of the text is like 10 px. Any div above a certain height will result in abnormal height.

I found that the suggested CSS does not work as it just limits the height of the window and is very unpleasant as the pictures are cut off.

The js solutions are the correct way to do it but I can not find a working solution and the ones that I have tried all result in half of the job solutions.

It seems the correct way uses the onSlideChangeStart to correct the next slide height like below but this does not work as the swiper of the vertical is not recognized in its own settings.

onSlideChangeStart: (swiper)->  $(swiper.slides).each ->      $(this).css height: if $(this).index() != swiper.activeIndex then 0 else 'auto'  

I tried to use the active class instead of the API as it is not working when calling even the swiperV.activeIndex in its own onSlideChangeStart like below but swiper-slide-active is not defined.

This is my settings for the 3 nested sliders.

    var swiperVV = new Swiper('.swiper-container-vv', {          direction: 'vertical',          updateOnWindowResize: true,          grabCursor: true,          loop: true,          mousewheel: true,          lazy: true,          zoom: true,          effect: 'slide',          spaceBetween: 0,          pagination: {              el: '.swiper-pagination-v',              clickable: true,          },       });      var swiperH = new Swiper('.swiper-container-h', {          initialSlide:0,          spaceBetween: 0,          autoHeight: true,          updateOnWindowResize: true,          grabCursor: true,          loop: true,          parallax: true,          lazy: true,          effect: 'slide',          pagination: {              el: '.swiper-pagination-h',              clickable: true,          },          scrollbar: {              el: '.swiper-scrollbar',              hide: true,          },      });      var swiperV = new Swiper('.swiper-container-v', {          direction: 'vertical',          autoplay: {              delay: 5000,          },          autoHeight: true,          updateOnWindowResize: true,          grabCursor: true,          loop: true,          mousewheel: true,          lazy: true,          zoom: true,          effect: 'slide',          spaceBetween: 0,          pagination: {              el: '.swiper-pagination-v',              clickable: true,          },          slideChange: resizeSwiper()      });        function resizeSwiper() {          console.log($('.swiper-container-v .swiper-slide swiper-slide-active').height());          $('.swiper-container-v, .swiper-container-v .swiper-slide').css({ height: $('.swiper-container-v .swiper-slide .swiper-slide-active').height() });        }  

i have gone through all the samples of suggested users like the ones listed below in github, stackoverflow and codepen. https://github.com/nolimits4web/swiper/issues/48 https://github.com/nolimits4web/Swiper/issues/153

Connect as client in a remote socket server

Posted: 26 May 2022 01:26 PM PDT

I need to build a simple PHP service socket to connect as client with a remote socket server and lintening then. The problem is that I need to connect with the host URL and not the host IP.

I've tried with socket_create() method, but it only connect using IP. Other method that I've tried was stream_socket_server() that allow URL conections, but I cannot keep up a listening to receive responses.

echo "Socket started...\n";    $server = 'ssl://sockserver.com/moreurl/params?56298';  $host = "sockserver.com";  $port = 80;  set_time_limit(0);    $socket = socket_create(AF_INET, SOCK_STREAM, 0);  $result = socket_connect($socket, $server, $port);  socket_bind($socket, $host);  socket_listen($socket);    while (true) {    $result = socket_read ($socket, 1024);    if($result){      echo "Reply From Server  :".$result;    }  }    socket_close($socket);  

So, I need to keep a listening to a remote server Socket as PHP client using an URL like host.

Kafka keeps rebalancing consumers

Posted: 26 May 2022 01:26 PM PDT

We have 10 consumers in a group listening for a topic. What is happening very often is to see the consumers being rebalanced very often (which completely stops the consumer process for some time).

# ./kafka-consumer-groups.sh --describe --bootstrap-server localhost:9092  --describe  --group ParserKafkaPipeline | grep -e ParserBody | sort  ParserBodyToParse 0          99              99              0               consumer-1-f29b7eb7-b871-477c-af52-446fbf4b0496  /10.12.18.58    consumer-1  ParserBodyToParse 1          97              97              0               consumer-10-6639ee02-8e68-40e6-aca1-eabd89bf828e /10.12.18.58    consumer-10  ParserBodyToParse 2          97              97              0               consumer-11-c712db8b-0396-4388-9e3a-e8e342355547 /10.12.18.58    consumer-11  ParserBodyToParse 3          97              98              1               consumer-12-0cc6fe12-d640-4344-91c0-f15e63c20cca /10.12.18.58    consumer-12  ParserBodyToParse 4          97              98              1               consumer-13-b904a958-141d-412e-83ea-950cd51e25e0 /10.12.18.58    consumer-13  ParserBodyToParse 5          97              98              1               consumer-14-7c70ba88-8b8c-4fad-b15b-cf7692a4b9ce /10.12.18.58    consumer-14  ParserBodyToParse 6          98              98              0               consumer-15-f0983c3d-8704-4127-808d-ec8b6b847008 /10.12.18.58    consumer-15  ParserBodyToParse 7          97              97              0               consumer-18-de5d20dd-217c-4db2-9b39-e2fdbca386e9 /10.12.18.58    consumer-18  ParserBodyToParse 8          98              98              0               consumer-5-bdeaf30a-d2bf-4aec-86ea-9c35a7acfe21  /10.12.18.58    consumer-5  ParserBodyToParse 9          98              98              0               consumer-9-4de1bf17-9474-4bd4-ae61-4ab254f52863  /10.12.18.58    consumer-9    # ./kafka-consumer-groups.sh --describe --bootstrap-server localhost:9092  --describe  --group ParserKafkaPipeline | grep -e ParserBody | sort  Warning: Consumer group 'ParserKafkaPipeline' is rebalancing.  ParserBodyToParse 0          99              99              0               -               -               -  ParserBodyToParse 1          99              99              0               -               -               -  ParserBodyToParse 2          99              99              0               -               -               -  ParserBodyToParse 3          99              100             1               -               -               -  ParserBodyToParse 4          99              100             1               -               -               -  ParserBodyToParse 5          99              100             1               -               -               -  ParserBodyToParse 6          100             100             0               -               -               -  ParserBodyToParse 7          99              99              0               -               -               -  ParserBodyToParse 8          100             100             0               -               -               -  ParserBodyToParse 9          100             100             0               -               -               -  

Notice the warning in the second call above.

Consuming these messages might take a long time, but it shouldn't take more than two minutes. I checked that the limit on consumer.poll is 5 minutes, which shouldn't be an issue. Are there some logs to check what exactly is happening?

UPDATE:

We use Kafka 2.2.1 and Java consumer. We didn't change the default value of max.session and max.heartbeat. The consumer is basically waiting for IO from other service, so it is not using any CPU – that is why I expect the heartbeat should be working correctly.

Our consumer code is following:

    inline fun <reified T : Any> consume(              topic: KafkaTopic,              groupId: String,              batchSize: Int = 50,              crossinline consume: (key: String?, value: T) -> (Unit)      ) = thread {          val consumerProperties = Properties()          consumerProperties.putAll(properties)          consumerProperties.put(ConsumerConfig.GROUP_ID_CONFIG, groupId)          consumerProperties.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, batchSize)            val consumer = KafkaConsumer<String?, ByteArray>(consumerProperties)            consumer.subscribe(listOf(topic.toString()))            while (true) try {              val records = consumer.poll(Duration.ofMinutes(pollDurationMinutes))              log.debug("Topic $topic consumed by group $groupId: ${records.count()} records.")              records.forEach { record -> consumeRecord(record, topic, consume) }          } catch (e: Exception) {              log.fatal("Couldn't consume records: ${e.message}.", e)              // sleep to prevent logging hell when connection failure              Thread.sleep(1000)          }      }  

using MultipartFormDataStreamProvider and ReadAsMultipartAsync

Posted: 26 May 2022 01:25 PM PDT

How would i go about using MultipartFormDataStreamProvider and Request.Content.ReadAsMultipartAsync in a ApiController?

I have googled a few tutorials but I can't get any of them to work, I'm using .net 4.5.

Code:

public class TestController : ApiController  {      const string StoragePath = @"T:\WebApiTest";      public async void Post()      {          if (Request.Content.IsMimeMultipartContent())          {              var streamProvider = new MultipartFormDataStreamProvider(Path.Combine(StoragePath, "Upload"));              await Request.Content.ReadAsMultipartAsync(streamProvider);              foreach (MultipartFileData fileData in streamProvider.FileData)              {                  if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))                      throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));                                        string fileName = fileData.Headers.ContentDisposition.FileName;                                    if (fileName.StartsWith("\"") && fileName.EndsWith("\""))                      fileName = fileName.Trim('"');                                        if (fileName.Contains(@"/") || fileName.Contains(@"\"))                      fileName = Path.GetFileName(fileName);                                        File.Copy(fileData.LocalFileName, Path.Combine(StoragePath, fileName));              }          }          else          {              throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));          }       }  }  

I get the exception

Unexpected end of MIME multipart stream. MIME multipart message is not complete.

when the await task; runs. Does anyone know what I am doing wrong or have a working example in asp.net?

Put content in HttpResponseMessage object?

Posted: 26 May 2022 01:26 PM PDT

Several months ago, Microsoft decided to change up the HttpResponseMessage class. Before, you could simply pass a data type into the constructor, and then return the message with that data, but not anymore.

Now, you need to use the Content property to set the content of the message. The problem is that it is of type HttpContent, and I can't seem to find a way to convert a string, for example, to HttpContent.

Does anyone know how to deal with this issue? Thanks a lot.

How to generate a self-signed SSL certificate using OpenSSL? [closed]

Posted: 26 May 2022 01:26 PM PDT

I'm adding HTTPS support to an embedded Linux device. I have tried to generate a self-signed certificate with these steps:

openssl req -new > cert.csr  openssl rsa -in privkey.pem -out key.pem  openssl x509 -in cert.csr -out cert.pem -req -signkey key.pem -days 1001  cat key.pem>>cert.pem  

This works, but I get some errors with, for example, Google Chrome:

This is probably not the site you are looking for!
The site's security certificate is not trusted!

Am I missing something? Is this the correct way to build a self-signed certificate?

No comments:

Post a Comment