Friday, August 6, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


When Null is meaningful

Posted: 06 Aug 2021 08:44 AM PDT

I am learning machine learning so my question might sound basic and I could not find any useful insight to this problem.

I am trying to create an environment for RL where the size of my input is not fixed. As a way around it, I thought about padding the size to a maximum value and then assigning Null to those values that do not exist. Now my question is that these Null values are meaningful, they are not zeros. They are not missing values. They signify the shape and size of the input. How do RL or Neural Network in general deal with Null valuest? What should I be mindful in these scenarios? Are there any example I can look at with similar situation? I appreciate your comments.

Firebase RecyclerView

Posted: 06 Aug 2021 08:43 AM PDT

how can i set progress dialog in this code:

class RetrievePdfView extends AsyncTask<String,Void,InputStream> {

    @Override      protected InputStream doInBackground(String... strings) {         InputStream inputStream=null;         try{               URL url=new URL(strings[0]);             HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();             if(urlConnection.getResponseCode()==200)             {                 inputStream=new BufferedInputStream(urlConnection.getInputStream());             }         }         catch (IOException e)         {             return null;         }         return inputStream;      }        @Override      protected void onPostExecute(InputStream inputStream) {          super.onPostExecute(inputStream);          pdfView.fromStream(inputStream).load();      }  

VS Code shortcut to add starred-block comments

Posted: 06 Aug 2021 08:43 AM PDT

Is there a VS Code built-in shortcut or extension that will insert and correctly format starred-block comments, as described in ESLint's rule "multiline-comment-style"?

I am using TypeScript, but this should apply to vanilla JavaScript and other languages as well.

Example

I should be able to highlight multiple uncommented lines as below:

interface CatInfo {    age: number;    breed: string;  }     type CatName = "miffy" | "boris" | "mordred";     ~~~~START HIGHLIGHT~~~~  const cats: Record<CatName, CatInfo> = {    miffy: { age: 10, breed: "Persian" },    boris: { age: 5, breed: "Maine Coon" },    mordred: { age: 16, breed: "British Shorthair" },  };     cats.boris;  ~~~~END HIGHLIGHT~~~~  

And use a shortcut to comment all highlighted lines, so they look like this:

/*    * const cats: Record<CatName, CatInfo> = {   *   miffy: { age: 10, breed: "Persian" },   *   boris: { age: 5, breed: "Maine Coon" },   *   mordred: { age: 16, breed: "British Shorthair" },   * };   *   * cats.boris;   */  

Anti-examples

I am not looking for Ctrl+/ aka ⌘+/

// const cats: Record<CatName, CatInfo> = {  //   miffy: { age: 10, breed: "Persian" },  //   boris: { age: 5, breed: "Maine Coon" },  //   mordred: { age: 16, breed: "British Shorthair" },  // };    // cats.boris;  

I am not looking for Shift+Alt+A aka Shift+⌥+A

/*   const cats: Record<CatName, CatInfo> = {    miffy: { age: 10, breed: "Persian" },    boris: { age: 5, breed: "Maine Coon" },    mordred: { age: 16, breed: "British Shorthair" },  };    cats.boris;   */  

how i can upcasting in python3?

Posted: 06 Aug 2021 08:43 AM PDT

I have two class like this :

Class

class A(object):   def __init__(self,param1):    self.param1 = param1      def display(self):    print("param1 :",self.param1)        

Super class

class B(A):      def __init__(self,param1,param2):          super().__init__(param1)          self.param2 = param2      def display(self):          print("param1 :",self.param1," and ","param2 :",self.param2)  

if i have an object of class A how can I convert it to an object of class B?

Docker ModuleNotFoundError: No module named 'xhtml2pdf'

Posted: 06 Aug 2021 08:43 AM PDT

I've looked through several websites but I can't seem to find an answer. I'm new to django and docker and whilist building my first project which is a quotation generator, I've been looking for different ways to generate a pdf for each quote.

I found a couple of tutorials on xhtml2pdf and my error appears when I try to run docker-compose up and get the following error:

ModuleNotFoundError: No module named 'xhtml2pdf'

I've installed xhtml2pdf using pip3 install xhtml2pdf and whenever I try to run it again I get: Requirement already satisfied: xhtml2pdf, the same for its dependencies.

I've also tried pip install --upgrade --force-reinstall xhtml2pdf with no luck

on my views.py file if I write from xhtml2pdf import pisa vs code gives me no errors regarding the import

My requirements.txt lookslike this:

psycopg2==2.9.1  pillow>=8.3  xhtml2pdf==0.2.5  reportlab==3.6.1  

Dockerfile:

FROM python:3.8    ENV PYTHONDONTWRITEBYTECODE 1  ENV PYTHONUNBUFFERED 1    WORKDIR /code      COPY requirements.txt .  RUN pip install -r requirements.txt    COPY . .  

Translations for Description / Long Description

Posted: 06 Aug 2021 08:43 AM PDT

Is there a way to add translated text for the app "description" and "Long description". For example: french and spanish? Or how do we handle localization for these text?

enter image description here

AttributeError: partially initialized module 'pickle' has no attribute 'dumps' (most likely due to a circular import) [closed]

Posted: 06 Aug 2021 08:43 AM PDT

I have already installed pickle module. but still I'm getting this error

AttributeError: partially initialized module 'pickle' has no attribute 'dumps' (most likely due to a circular import)  
h=['hey','dasasd','dadsasda']    po=pickle.dumps(h)    upo=pickle.loads(po)    print(upo)  

Optimize imports in Python

Posted: 06 Aug 2021 08:44 AM PDT

If my python imports looks like

from x.y.z.a import method1  from x.y.z.b import method2  from x.y.z.c import method3  

Is there a way to make an alias to from x.y.z so I do not have to write it in each line?

Thanks

requirements for merging two Pandas DataFrame

Posted: 06 Aug 2021 08:43 AM PDT

I do not know why I cannot merge two Dataframes based on their Alpha-3 code and iso_code as follow:

import pandas as pd    vac = pd.read_csv('https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/vaccinations/vaccinations.csv')  world = pd.read_csv('https://gist.githubusercontent.com/tadast/8827699/raw/f5cac3d42d16b78348610fc4ec301e9234f82821/countries_codes_and_coordinates.csv').  

The outcome when I merged was just column names.

Could anyone explain, please?

Blink CardView does not start [Object Animator, Android]

Posted: 06 Aug 2021 08:43 AM PDT

today I'm trying to make blink effect in my CardView... Works if I put backgroundColor but does not if I use strokeColor. I've followed this tutorial to make it real but is not working really... How can I change to make this effect correctly?

 private fun createBlinkEffect() {        val animator = ObjectAnimator.ofInt(mCardView,          "strokeColor",          ContextCompat.getColor(this, COLOR.WHITE),          ContextCompat.getColor(this, COLOR.RED))        animator.duration = 400      animator.setEvaluator(ArgbEvaluator())      animator.repeatMode = ValueAnimator.REVERSE      animator.repeatCount = ValueAnimator.INFINITE      animator.start()  }  

this is my layout_item

<androidx.cardview.widget.CardView      xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:id="@+id/mCardView"      android:layout_width="120dp"      android:layout_height="152dp"      android:layout_marginEnd="24dp"      android:layout_marginBottom="4dp"      app:strokeWidth="2dp"      app:strokeColor="@android:color/transparent"      app:cardCornerRadius="12dp">  

Thanks for your time

Same font looks different in different areas of a document

Posted: 06 Aug 2021 08:42 AM PDT

I am using a monospace font in the text on my webpage. For larger sizes, the font appears to be normal without any discrepancies; however, in small paragraph-appropriate sizes, the variations in the font become more noticeable to the point where certain characters(the number 1) appear bulged in one end. Notice that this does not occur for all instances of the character; for some instances, there is no discrepancy. I am certain that this is caused due to font spacing and that they are caused when the character ,"lands" in the middle of a pixel.

Here is the code: pre{padding:2px 4px;font-size:100%;color:#c7254e;border-radius:4px}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;;} pre{white-space: pre-wrap; /* Since CSS 2.1 / white-space: -moz-pre-wrap;

Notice: I am using Mac OS X with sub-pixel anti-aliasing turned on. This is not causing the issue.

Edit: I am using Meslo LG M as the font.

get_attribute method in selenium using python is not working when 2 attributes were given in an xpath

Posted: 06 Aug 2021 08:43 AM PDT

I am not able to fetch textfamily value from below line.

attribute_value = find_elements_by_xpath("//body//Text[@text = 'Hi' and @textfamily]").get_attribue('textfamily')

whereas its working fine when using like below

attribute_value = find_elements_by_xpath("//body//Text[@textfamily]").get_attribue('textfamily')

Could someone kindly provide a solution to this?

Note: Above are not an accurate examples. they are not actual scripts with which I was facing problem. for some reason I am not able to provide my exact script here. I hope you can get the idea using above context where when I have only one attribute I was able to get it using get_attribute but not when I give a condition like @text='Hi' which is in the same tag.

How to access a <summary> tag with selenium

Posted: 06 Aug 2021 08:43 AM PDT

enter image description hereOn this webpage, there is a button which I need to press. This is the HTML source:

<details>      <summary aria-controls="dc_2" tabindex="0" role="button" aria-expanded="true"><span>The company I am travelling with is not listed</span>  

I tried to access it with the XPATH of the span tag, however it does not work. Any suggestions?

Find if array can be divided into two subarrays of equal sum if any one element can be deleted

Posted: 06 Aug 2021 08:43 AM PDT

Given a array of numbers find if there is a way to delete/remove a number from the array and make one partition in the array( dividing the array into two subarrays ) such that sum of elements in subarray1 is equal to sum of elements in subarray2.

A subarray is a contiguous part of array.  Array [1, 2, 3, 4] has (1), (1,2), (2,3,4),(1,2,3,4) etc.. as its subarrays but not (1,3) , (2,4) , (1,3,4), etc..  

Now let us consider one example:-

(Follow 0-based indexing )  Array[] = [ 6, 2, 2, 1, 3 ]    Possible solutions  Delete Array[0] => updated array: - [ 2,2,1,3 ]  Possible partition              : - [2,2] and [3,1] where (2+2) = (3+1) = 4  or  Delete Array[1] => updated array: - [ 6,2,1,3 ]  Possible partition              : - [6] and [2,1,3] where (6) = (2+1+3) = 6  or  Delete Array[2] => updated array: - [ 6,2,1,3 ]  Possible partition              : - [6] and [2,1,3] where (6) = (2+1+3) = 6  

Now a similar question already exists where we just have to, find if array can be divided into two subarrays of equal sum , can be done in O(n) =>

PsuedoCode:- The efficient solution involves calculating sum of all elements of the array in advance. Then for each element of the array, we can calculate its right sum in O(1) time by using total sum of the array elements minus sum of elements found so far. The time complexity of this solution would be O(n) and auxiliary space used by it will be O(1).

So to solve our problem one brute force method is:- remove every element once and check if the array can be divided into two subarrays of equal sum. Thus it will require O(n^2) time.

So can we do better than this time complexity?

Promise.all does not await for then

Posted: 06 Aug 2021 08:43 AM PDT

First of all I am a newbie in nodejs, please be indulgent :) I have a problem with some async functions. In my case, a first API call is made and then a sub call is made on every item returned. this is my code after the first call is made :

const countryStatesCalls: Promise<any>[] = [];  countries.forEach((country, index) => {    countries[index] = convertToCountry(country);    const countryStatesCall = (countryId: number) => {      return new Promise((resolve, reject) => {        const countryStatesList = getStateCountries(countryId);        if (countryStatesList) {          if (Object.prototype.toString.call(countryStatesList) !== '[object Array]') {            resolve([]);          } else {            resolve(countryStatesList);          }        } else {          reject([]);        }      });    };    countryStatesCalls.push(      countryStatesCall(countries[index].id).then(countryStates => {        countries[index].states = countryStates;      }).catch(countryStatesType => {        countries[index].states = countryStatesType;      })    );  });    await Promise.all(countryStatesCalls).then(_ => {    res.json(countries)  });  

the following code

res.json(countries)  

is supposed to be executed after all promises execution has been finished.

I think my mistake may be obvious but can you help me please, I read many topics and I cannot see what am I doing wrong.

Thank you in advance

Linux command to fetch line count from pgp file

Posted: 06 Aug 2021 08:44 AM PDT

I have a requirement to fetch the line count of .pgp file. I know for normal file we can use this below command:

sshpass -p 'pswd3@' ssh -o StrictHostKeyChecking=no abc@qa4.unix.gsm1900.org tail -n +1 /var/test/data_20201202010002.txt.pgp | wc -l  

But for.pgp file we need to decrypt and count the lines. Can anyone please help to do that.

Change timeout value with StartService method

Posted: 06 Aug 2021 08:44 AM PDT

I'm trying to start a service with StartService method. According to the documentation:

StartService will block for 30 seconds if any service is busy handling a control code.

How can I change this timeout value?

Using SQL to return a complete conversion table

Posted: 06 Aug 2021 08:43 AM PDT

I have a table (UOMC) filled with Unit of Measure conversions. If you are familiar with JDE E1, this may look familiar. Each row has a conversion from one unit to another, along with a conversion to the "Primary Unit of Measure" or smallest unit of measure. [For example][1] [1]: https://i.stack.imgur.com/o4zfr.png

I want a SQL statement that will return a complete set of conversions, including to Miles from Feet.

+-------+--------+------+------------+-----------------+  | To    | From   | Conv | PrimaryUOM | ConvToPrimary   |  +-------+--------+------+------------+-----------------+  | Feet  | Inches |   12 | Inches     |              12 |  | Yards | Feet   |    3 | Inches     |              36 |  | Miles | Yards  | 1760 | Inches     |           63360 |  +-------+--------+------+------------+-----------------+    CREATE TABLE [UOMC](      [To] [nchar](10) NULL,      [From] [nchar](10) NULL,      [Conv] [int] NULL,      [PrimaryUOM]  [nchar](10) NULL,      [ConvToPrimary] [int] NULL      ) ON [PRIMARY]  GO;    INSERT INTO [UOMC]             ([To],[From],[Conv],[ConvToPrimary])       VALUES             ('Feet','Inches',12,'Inches',12),             ('Yards','Feet',3,'Inches',36),             ('Miles','Yards',1760,'Inches',63360)  GO;  

The desired result...

+-------+--------+------+  | To    | From   | Conv |  +-------+--------+------+  | Feet  | Inches |   12 |  | Yards | Feet   |    3 |  | Miles | Yards  | 1760 |  | Miles | Feet   | 5280 |  +-------+--------+------+  

Using lock, Monitor Pulse and Wait to synchronize threads [closed]

Posted: 06 Aug 2021 08:43 AM PDT

I have read the official documentation and about 25 tutorials, but I'm still struggling with how I might synchronize say, 3 threads with Monitor Pulse() and Wait() methods and using lock objects.

(Yes, I know there are other techniques of synchronization, but this should be doable and it's frustrating me)

Here's my simple "proof of concept" idea I came up with.

Let's say I have three threads, each with a task:

  1. Thread1 runs a task that prints out all integers divisible by 3
  2. Thread2 runs a task that prints out all integers whose remainder is 1 when divided by 3
  3. Thread3 runs a task that prints out all integers whose remainder is 2 when divided by 3

I'd like ultimately the output to be: 0,1,2,3,4,5,6,... up to whatever integer limit I might choose but we can say 50 or 100 - it doesn't matter.

I'd like to more fully understand the mechanism of lock vs Monitor.Wait() and Monitor.Pulse() and how they can work together.

If I understand correctly, when a thread encounters a lock(someObject) { ... }, it gains exclusive access to that critical area if it's the first one there. Any other thread that encounters a lock on the same object is stuck on that line (i.e., lock(someObject)) in its respective code, correct?

If thread 1 has the lock(someObject) calls Monitor.Wait(someObject), then the thread 1 releases the lock and enters the waiting queue, correct? Then if any other thread (e.g., thread 2) calls Monitor.Pulse(someObject), it would move the thread1 into the ready queue?

No matter what I try, it seems like the code keeps just waiting/blocking infinitely.

I guess my summary questions are:

  1. Do I need more than one lock object to synchronize three threads using Pulse and Wait?
  2. Where would the Wait and Pulse go in this code? Inside a lock around the loop that is being used to iterate over the values that we want to print? Inside a lock, placed only inside a condition (e.g., if (i % 3 == 2)) ? Etc.
  3. Are there any resources (e.g., websites, youtube videos, books) that use Monitor Pulse() and Wait() that aren't 10+ years old?

I'm thankful for any helpful input!

Can I use validate unique keys across separate objects using JOI?

Posted: 06 Aug 2021 08:42 AM PDT

The current validation looks similar to this:

.pattern(/^Object.*$/, Joi.object({        config: Joi.object()  }))  

If I have two objects that pass the pattern validation, is it possible to also validate that the keys across all objects in both myLists are unique? For instance, this would cause the entire validation to fail because they share a key in myList, animal.

request = {    ObjectOne: {      config: {        myList: [{          animal: 'dog'        }]      }    },      ObjectTwo: {      config: {        myList: [{          animal: 'cat'        }, {          color: 'blue'        }]      }    }  }  

This validation would also fail because the key animal occurs twice in myList

request = {    ObjectOne: {      config: {        myList: [{          animal: 'dog'        }, {          animal: 'cat'        }]      }    }  }  

Create n new columns by n distinct groups in data.table

Posted: 06 Aug 2021 08:42 AM PDT

I have the following data table, and would like to sum y twice grouping the first time by g1 and the second time by g2.

Usually I would just chain the calculations together, but I would like to be able to do the grouped sum n different times by n groups.

library(data.table)    DT <- data.table(      g1 = c("a", "b"),      g2 = c("a", "a"),      y = c(3,5)    )    new_cols <- paste0("sum_by_", c("g1", "g2"))  group_cols <- c("g1", "g2")    # Supplying cols to by like this groups by g1 AND g2, when in reality I want it to   # take g1 the first time and g2 the second time.   DT[, paste(new_cols) := lapply(rep(y, length(new_cols)), sum),     by = .(group_cols)][]  

this gives me:

#    g1 g2 y sum_by_g1 sum_by_g2  # 1:  a  a 3         3         3  # 2:  b  a 5         5         5  

when I actually want:

#    g1 g2 y sum_by_g1 sum_by_g2  # 1:  a  a 3         3         8  # 2:  b  a 5         5         8  

Is there any slick data.table way to do this? Something like supplying .SD to by (this in itself doesn't seem to work)?

Edit: Changed y from c(1,1) to c(3,5)

Edit Rationale: Actual and desired outputs while y = c(1,1) gave the impression that I wanted to count the observations in each group, when I actually want to sum(y) for each group.

Gin-Gonic NewRelic Integration

Posted: 06 Aug 2021 08:43 AM PDT

I am trying to integrate go app with newrelic and with below code I am able to see my api transactions in new relic.

 import (     "github.com/newrelic/go-agent/v3/integration/nrgin"     "github.com/newrelic/go-agent/v3/newrelic"    )     var router = gin.Default()     nr, _ := newrelic.NewApplication(             newrelic.ConfigAppName("TestApp"),            newrelic.ConfigLicense("NRKEY"),  )   router.Use(nrgin.Middleware(nr))     router.GET("/user", userHandler)   

with above sample code, when get user request is initiated I am able to see the api details in newrelic transactions. But the problem is database query traces are empty in newrelic.

I found a way to get query details by adding newrelic.DatastoreSegment in individual models, but I don't want this approach because I have many models.

Is there anyway I can handle this situation in router?

SvelteKit and Swiper 6.8.1: how to use slideTo(index)

Posted: 06 Aug 2021 08:44 AM PDT

Slider 6.8.1 works well with SvelteKit. I would like to be able to select a certain slide also by program. This is apparently possible with swiper.slideTo(index, speed).

swiper is created for example like this:

const swiper = new Swiper('.swiper-container', {    speed: 400,    spaceBetween: 100,  });  

However, SvelteKit requires Swiper to be imported like this:

import Swiper from 'swiper/esm/svelte/swiper.svelte';  

But then new Swiper returns the error message

__vite_ssr_import_1__.default is not a constructor

This is quite understandable, but how to solve the problem?

How to fixed vertical positioning glitch in Mapbox callout

Posted: 06 Aug 2021 08:43 AM PDT

So I have a custom AnnotationView class (what the pin itself looks like) and a custom CalloutView class (what the bubble that appears above it looks like) For some reason, I get this odd behavior where if I press the annotation, it selects and appears properly (as seen in the first picture), but then if I deselect the annotation and reselect it (without moving the map at all), the callout reappears in the wrong positioning. The problem appears to be the rect.origin.y value, but I'm not sure--I tried hardcoding it but the problem still persists. In the video, I click my mouse down and it causes the annotation to move up. Any help much appreciated!

class AnnotationView: MGLAnnotationView {      weak var delegate: MapAnnotationDelegate?      var pointAnnotation: MGLPointAnnotation?            required override init(reuseIdentifier: String?) {          super.init(reuseIdentifier: reuseIdentifier)          if reuseIdentifier == "default" {              super.centerOffset = CGVector(dx: 0, dy: -17.5)          }          let rect = CGRect(x: 0, y: 0, width: 35, height: 35)          let button = UIButton(frame: rect)          let image = UIImage(named: reuseIdentifier ?? "default")?.resize(targetSize: CGSize(width: 35, height: 35))          button.setImage(image, for: .normal)          button.setImage(image, for: .selected)          button.setImage(image, for: .highlighted)          button.imageView?.contentMode = .scaleAspectFit          button.addTarget(self, action: #selector(annotationAction), for: .touchUpInside)          frame = rect          addSubview(button)          isEnabled = false      }            required init?(coder: NSCoder) {          return nil      }            @objc private func annotationAction() {          delegate?.tappedAnnotation(annotation: pointAnnotation!)      }  }    class CustomCalloutView: UIView, MGLCalloutView {      var representedObject: MGLAnnotation            // Allow the callout to remain open during panning.      let dismissesAutomatically: Bool = false      let isAnchoredToAnnotation: Bool = true            // https://github.com/mapbox/mapbox-gl-native/issues/9228      override var center: CGPoint {          set {              var newCenter = newValue              newCenter.y -= bounds.midY              super.center = newCenter          }          get {              return super.center          }      }            lazy var leftAccessoryView = UIView() /* unused */      lazy var rightAccessoryView = UIView() /* unused */            weak var delegate: MGLCalloutViewDelegate?            let tipHeight: CGFloat = 10.0      let tipWidth: CGFloat = 20.0            let mainBody: UIButton            required init(representedObject: MGLAnnotation) {          self.representedObject = representedObject          self.mainBody = UIButton(type: .system)                    super.init(frame: .zero)                    backgroundColor = .clear                    mainBody.backgroundColor = .white          mainBody.tintColor = .black          mainBody.contentEdgeInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0)          mainBody.layer.cornerRadius = 4.0                    addSubview(mainBody)      }            required init?(coder decoder: NSCoder) {          fatalError("init(coder:) has not been implemented")      }            // MARK: - MGLCalloutView API      func presentCallout(from rect: CGRect, in view: UIView, constrainedTo constrainedRect: CGRect, animated: Bool) {                    delegate?.calloutViewWillAppear?(self)                    view.addSubview(self)                    // Prepare title label.          mainBody.setTitle(representedObject.title!, for: .normal)          mainBody.sizeToFit()          mainBody.backgroundColor = .red                    if isCalloutTappable() {              // Handle taps and eventually try to send them to the delegate (usually the map view).              mainBody.addTarget(self, action: #selector(CustomCalloutView.calloutTapped), for: .touchUpInside)          } else {              // Disable tapping and highlighting.              mainBody.isUserInteractionEnabled = false          }                    // Prepare our frame, adding extra space at the bottom for the tip.          let frameWidth = mainBody.bounds.size.width          let frameHeight = mainBody.bounds.size.height + tipHeight          let frameOriginX = rect.origin.x + (rect.size.width/2.0) - (frameWidth/2.0)          let frameOriginY = rect.origin.y - frameHeight          frame = CGRect(x: frameOriginX, y: frameOriginY, width: frameWidth, height: frameHeight)                    if animated {              alpha = 0                            UIView.animate(withDuration: 0.2) { \[weak self\] in                  guard let strongSelf = self else {                      return                  }                                    strongSelf.alpha = 1                  strongSelf.delegate?.calloutViewDidAppear?(strongSelf)              }          } else {              delegate?.calloutViewDidAppear?(self)          }      }            func dismissCallout(animated: Bool) {          if (superview != nil) {              if animated {                  UIView.animate(withDuration: 0.2, animations: { \[weak self\] in                      self?.alpha = 0                  }, completion: { \[weak self\] _ in                      self?.removeFromSuperview()                  })              } else {                  removeFromSuperview()              }          }      }            // MARK: - Callout interaction handlers            func isCalloutTappable() -> Bool {          if let delegate = delegate {              if delegate.responds(to: #selector(MGLCalloutViewDelegate.calloutViewShouldHighlight)) {                  return delegate.calloutViewShouldHighlight!(self)              }          }          return false      }            @objc func calloutTapped() {          if isCalloutTappable() && delegate!.responds(to: #selector(MGLCalloutViewDelegate.calloutViewTapped)) {              delegate!.calloutViewTapped!(self)          }      }            // MARK: - Custom view styling            override func draw(_ rect: CGRect) {          // Draw the pointed tip at the bottom.          let fillColor: UIColor = .white                    let tipLeft = rect.origin.x + (rect.size.width / 2.0) - (tipWidth / 2.0)          let tipBottom = CGPoint(x: rect.origin.x + (rect.size.width / 2.0), y: rect.origin.y + rect.size.height)          let heightWithoutTip = rect.size.height - tipHeight - 1                    let currentContext = UIGraphicsGetCurrentContext()!                    let tipPath = CGMutablePath()          tipPath.move(to: CGPoint(x: tipLeft, y: heightWithoutTip))          tipPath.addLine(to: CGPoint(x: tipBottom.x, y: tipBottom.y))          tipPath.addLine(to: CGPoint(x: tipLeft + tipWidth, y: heightWithoutTip))          tipPath.closeSubpath()                    fillColor.setFill()          currentContext.addPath(tipPath)          currentContext.fillPath()      }  }  

For context, the relevant Mapbox map delegate functions are:

func tappedAnnotation(annotation: MGLPointAnnotation) {      let selectedAnnotation = control.mapView.selectedAnnotations.first      guard control.mapView.annotations != nil, selectedAnnotation !== annotation else { return }      //control is the actual map being passed into this coordinator function      for annotation in control.mapView.annotations! {          if annotation.subtitle == "PrimaryAnno" {              control.mapView.removeAnnotation(annotation)          }      }      control.mapView.selectAnnotation(annotation, animated: false, completionHandler: nil)  }    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {      if annotation is MGLPointAnnotation {            var reuseid = ""          //I use the subtitles to indicate which image I use for my annotations          if annotation.subtitle! == "primaryAnno" {              reuseid = "default"          } else {              reuseid = annotation.subtitle!          }              if let reusable = mapView.dequeueReusableAnnotationView(withIdentifier: reuseid) as? AnnotationView {              reusable.pointAnnotation = annotation as? MGLPointAnnotation              return reusable          } else {              let new = AnnotationView(reuseIdentifier: reuseid)              new.delegate = self              new.pointAnnotation = annotation as? MGLPointAnnotation              return new          }      } else {          return nil      }  }  

And this is a protocol I use to define the tapping on an annotation:

protocol MapAnnotationDelegate: AnyObject {      func tappedAnnotation(annotation: MGLPointAnnotation)  }  

UPDATE: I figured out that the 'correction' happens when I click on the map or change the region, so the issue is with the initial tap on annotation. I've tried setting a breakpoint in the tappedAnnotation function and it seems like once that function ends (it subsequently redirects to the annotationAction() function), the callout just renders in the wrong position.

1

2

https://youtu.be/4x5o9T6p8aw

[Solved]How to display PDF thumbnails by using the Internet Explorer8,9,10

Posted: 06 Aug 2021 08:43 AM PDT

When I try to do it by PDF.js 'Hello, world!' example , PDFJS.getDocument not working and not throwing an error.

the example pdf.getPage(pageNumber).then(function(page) { is outdated and cannot be used!Please refer to the following code.

      reader.addEventListener('load', function(event) {        const orientation = getOrientation(reader.result);        const data = arrayBufferToDataURL(reader.result);        pdfjsLib.disableWorker = true;        pdfjsLib.GlobalWorkerOptions.workerSrc = 'pdf.worker.js';        var loadingTask = pdfjsLib.getDocument(new Uint8Array(event.target.result));        loadingTask.promise.then(function(pdf) {           }, function (reason) {          // console.error(reason);          // alert(reason);        });  

This is not your fault, the latest version of pdf.js does not support Internet Explorer8,9,10.although the old version may support Internet Explorer11, there will be many problems when it represents PDF.


In fact, the main reason is that the old version of the browser does not support ECMAScript6.So you need to try to figure out how to convert ES6 to Es5 and each difference between the ie version.

  • What are the differences between IE8, IE9, IE10, and IE11?
  • What are the differences between es5, es6?
  • Convert ES6 JavaScript to ES5.

I have studied the differences of queries for a long time. I won't discuss it here. I just talk about how to convert.


Use babel-cli to convert

$ npm install --save-dev babel-cli  $ npm install --save hapi  

You need to specify the plugin to use when you are transforming with a Babel. This is es2015 preset to transfer from ES6 (es2015) to Es5. babel/preset-es2015 babel/preset-es2017

.babelrc

{    "presets": ["es2015"]  }  

src/index.js

import Hapi from 'hapi';    const server = new Hapi.Server();  server.connection({    host: 'localhost',    port: 8000  });    // Add routing  server.route({    method: 'GET',    path: '/hello',    handler: function(request, reply) {      console.log('[/hello] requested');      reply('hello world');    }  });    server.start();  

dist/index.js

$ babel src/index.js --out-file dist/index.js  
'use strict';    var _hapi = require('hapi');    var _hapi2 = _interopRequireDefault(_hapi);    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }    var server = new _hapi2.default.Server();  server.connection({    host: 'localhost',    port: 8000  });    // Add routing  server.route({    method: 'GET',    path: '/hello',    handler: function handler(request, reply) {      console.log('[/hello] requested');      reply('hello world');    }  });    server.start();    

When you think there should be no problem, I'm sorry, there are other problems. Garbled code appears when representing a specific Japanese character-set

  • You need to modify the adode pdf bcmap file(/pdf.js/cmaps/*.bcmap)

download the cmap-resources which you want, and add it


Problem Solved

Problem-Solved

How to change multiple values at the same time using ramdajs

Posted: 06 Aug 2021 08:44 AM PDT

I am new to ramdajs. Let's say I have an object:

{a: 1, b: 2, c: 3}  

I can do this to change a to 11:

  const aLens = R.lensProp('a');    R.set(aLens, 11, {a: 1, b: 2, c: 3});  

How do I change a to 11 and b to 22 with just one call?

How to disable connection pooling in Hibernate

Posted: 06 Aug 2021 08:43 AM PDT

I have a web application that currently uses c3p0 and Hibernate to connect to a Firebird 1.5 database.

I am facing a problem from time to time where the database just stops responding, even trying to manually restart the service doesn't have any effect, and it doesn't generate any logs, so I have to manually reboot the machine to get it working again.

I think that maybe Firebird hangs when the pool tries to acquire a specific number of connections or something like that. So, I need to test my app without connection pooling, to check if this is or is not the problem.

I can't simply remove c3p0 configs from persistence because this way Hibernate would use its own integrated connection pool. So how to do it?

Is it possible to override the default socket options in requests?

Posted: 06 Aug 2021 08:43 AM PDT

I've written a very simple client for a rest API using the excellent requests library for python. Everything works great util I run the client through a loadbalancer, which sanely detects idle tcp connections and kills them. I'd like for my client to use some different tcp keep alive options than are the defaults on my platform (linux). But I don't see any easy way to tell the socket library that I'd like to choose some default options for new sockets.

When using socket.create_connection directly this is easy enough to do with a decorator, but I've no idea how I'd make that decorated call available when the actual call is buried in some 3rd party library as is the case with requests.

thanks in advance

FFmpeg RTP streaming error [closed]

Posted: 06 Aug 2021 08:42 AM PDT

I want to broadcast a video file via FFmpeg, but I get this error:

Only one stream supported in the RTP muxer

I get that error when I write this:

ffmpeg.exe -i SomeVideo.mp4 -f rtp rtp://127.0.0.1:11111  

I don't know what's wrong.

Installing multiple versions of a package with pip

Posted: 06 Aug 2021 08:42 AM PDT

In my application I would like to use:

  • packageA, which requires packageX==1.3
  • packageB, which requires packageX==1.4
  • packageX==1.5

How can I install multiple versions of packageX with pip to handle this situation?

No comments:

Post a Comment