Friday, April 23, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


How to display my async request in react admin?

Posted: 23 Apr 2021 07:58 AM PDT

How to display my async request in react admin (function field)? My request is correct. But I have the following error: Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

I am on new on react-admin and I don't know how to resolve this error. Can you help me? How to display my async request in react admin (function field)? My request is correct. But I have the following error:

export const TreeList = props => (      <ListGuesser {...props}>          <FieldGuesser source={"code"} />            <FunctionField              label="Image"              render={                  async (record) => {                          let content = ''                  let response = await fetch('https://nuxt-api.io.local/api/media_objects')                                           const res = await response.json()                       content = res['hydra:member'].find(value => { return value['@id'] === record.outlinedImage }).contentUrl || ''                          return (                      <img width="100"                           src={`https://nuxt-api.io.local${content}`} alt="Upload image"                      />                  );              }}          />      </ListGuesser>  );  

Why is my image overlay not working on iPhone but is on all other devices and platforms I have tested?

Posted: 23 Apr 2021 07:58 AM PDT

Img hover overlay is working on all other platforms that I have tested (desktop, android etc.) but it doesn't seem to work on Iphone. Can anyone point me in the right direction please. Im not sure if it is to do with the z-index or whether it might need web-kits?

When you hover or click on .service it should show the overlay text. Please see below code

HTML

<div id="service-event" class="service">          <img class="bg-img" src="Images/Steel .JPG" alt="Steel" id="steel">          <div class="main-img-title">              <div class="img-title" id="steel-title">STEEL</div>          </div>          <div class="img-overlay">              <p class="overlay-img-description" id="steel-desc">Our steel crews are experienced with the construction of                  system                  scaffolding, black steel tower and truss structures. We specialise in supplying steel climbing teams                  with the support of steelhand ground labourers as well as plant operators who are familiar with the                  requirements of truss and steel assembly.</p>          </div>      </div>  

CSS

.service {      position: relative;      width: 80%;      height: 200px;      margin: 60px 10%;      box-shadow: rgba(0, 0, 0, 0.3) 0px 19px 38px, rgba(0, 0, 0, 0.22) 0px 15px 12px;      transition: all 0.3s;  }    .main-img-title {      position: absolute;      top: 0;      left: 0;      width: 100%;      height: 100%;      display: flex;      justify-content: center;      align-items: center;      font-size: 2.5em;      font-weight: 700;      color: #f8f9fa;      opacity: 1;      transition: 0.5s;       }      .img-title {      background-color: rgba(0,0,0,0.7);      padding: 2px 10px;      font-size: 1.1em;  }      .img-overlay {      position: absolute;      top: 0;      left: 0;      width: 100%;      height: 100%;      padding: 0 1%;      background:rgba(0,0,0,0.7);      color: #f8f9fa;      display: flex;      flex-direction: wrap;      justify-content: center;      align-items: flex-end;      text-align: center;      opacity: 0;    }    .service:hover .main-img-title .img-title{      animation-name: title-slide-up;      animation-duration: 0.3s;      animation-fill-mode: forwards;      z-index: 50;      background-color: rgba(0,0,0,0);   }    .service:hover .img-overlay {      opacity: 1;      }    #service-event:hover .main-img-title .img-title{      animation-name: title-slide-up-low;      animation-duration: 0.3s;      animation-fill-mode: forwards;  }     .overlay-img-description {       font-size: 18px;       height: 70%;       display: flex;       justify-content: center;       align-items: center;       margin: 0;       padding: 0 1%;       width: 100%;       max-height: 200px;   }     .overlay-img-description ul {       padding: 0;   }       .overlay-img-description li {      display: inline-block;      font-size: 20px;     }     .overlay-img-description li + li::before {      content: "";      display: inline-block;      vertical-align: middle;      margin: 0 13px;      width: 10px;      height: 10px;      border-radius: 50%;      background-color: currentColor;   }     .overlay-img-description p {       margin: 10px 0 0 0 ;       font-size: 0.9em;          }      @keyframes title-slide-up-low {      from{transform: translateY(0)}      to{transform: translateY(-45px)}  }  

How to read an element from a response

Posted: 23 Apr 2021 07:58 AM PDT

I want to receive the value inside the <on> element from a response.

response = requests.post(url)  

the original content of this response will return a byte value instead of XML

data = response.text  # making sure that response is returned as string  print(data)  

which gives me the following output

<?xml version="1.0" encoding="utf-8"?>  <ok generator="zend" version="5.7"><on>1C96FY</on><co>K73Q5N0N15P3</co></ok>  

Desired output

print(data)  ------------------  1C96FY  

Thanks in advance

How to avoid NaN while using pd.Grouper if there are missing values?

Posted: 23 Apr 2021 07:58 AM PDT

I have 1-minute bitcoin data, which I need to group into 5-minute data. I am using pd.Grouper function in order to achieve this task, here is my code:

df_5min = df_5min = df.groupby(pd.Grouper(key="Date_Time", freq = '5min', origin='epoch', dropna=False)).agg({                                          "Open":  "first",                                          "High":  "max",                                          "Low":   "min",                                          "Close": "last",                                          "Volume_(BTC)": "sum",                                          "Volume_(Currency)": "sum"})  

No NaN in the original Dataframe

If you look at my original dataframe(1 minute data), there is no rows with NaN's.

But when I group the data into 5-minute data using the above code, I get a lot of NaN's:

enter image description here

I checked my 1-minute data to see if there are missing values in that time period:

enter image description here

As it can be seen, indeed there are missing values, but that is the case with other minutes group as well, like between 2:00:00 to 2:05:00 there is only one value 2:04:00 and so on.

What might be giving me these NaN's and how can I avoid this? I would like to get the aggregation as mentioned in my above code.

Make unchecked checkboxes unvailable at specific amount but selected checkboxes still uncheckable

Posted: 23 Apr 2021 07:58 AM PDT

I have the following sandbox with a problem that I can't solve https://codesandbox.io/s/morning-bird-cs5uj. I have an array with objects (in the example with 2 objects but in my actual project way more than 2) and the objects of the array are displayed as checkboxes. There is also a button that increases an amount and the checkboxes can only be selectable while the amount is smaller than 5. When the amount is over 5 the checkboxes that are not checked should be disabled but the ones that are checked should still be available to uncheck. Is there a way to make this possible? Thanks in advance!

Linux SCHED_DEADLINE

Posted: 23 Apr 2021 07:58 AM PDT

Is it possible to set SCHED_DEADLINE period lower than 0,1ms? I use command chrt -a -d -T 2000 -D 5000 -P 99999 -p 0 7290 and i get an error: wrong argument. At the same time I command chrt -a -d -T 2000 -D 5000 -P 100000 -p 0 7290 works perfectly fine.

OpenLayers with CSS zoom unclickable

Posted: 23 Apr 2021 07:58 AM PDT

I am using a media rule in CSS to scale my site for small screens

@media screen and (max-width:900px) {    body {      zoom: 70%;    }  }  

This causes all feature selection in OpenLayers to stop working. I tried specifying zoom: 100% for just my map elements and it did not help. My selection is based off of the 'ol/interaction/Select' class

let select = new Select({    style: (feature) => {      this.featureClick(feature);      return null;    }  });    map.addInteraction(select);  

The style function stops being called so I'm thinking I might need to refresh the map in some way but can't find the right way to go about it.

How can we show code execution time in Visual Studio Code

Posted: 23 Apr 2021 07:57 AM PDT

I'm using Visual Studio Code to run my python scripts but I want to see the amount of time the code takes for executing from start to end. Some like this shown in MySQL 1

Thank you for your help

Retrieving data from JSON file in JS getting an error

Posted: 23 Apr 2021 07:58 AM PDT

Im getting a Uncaught SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

var mydata = JSON.parse("file.json");  console.log(myJSON)  

Below is an example of the data in the JSON file.

[[1,1,0,1,1,0,0,0,1,1,1,1,1,1],  [1,0,0,1,1,0,0,0,1,1,1,1,1,0],  [1,0,0,1,1,0,1,1,1,1,1,1,1,1],  [1,0,0,1,1,0,0,0,1,1,1,1,1,0], .... etc]  

How can I retrieve the data from this JSON file in JS?

Is it not possible to write a JSON like this?

When I open the file in the browser, it looks like a neat JSON array?

browser JSON file

Fit image inside square hitbox based on parent width

Posted: 23 Apr 2021 07:58 AM PDT

Questions that look like duplicates but ARENT:

I'm trying to create a layout of cards, where each card has an image of unknown aspect. The image should be resized, keeping its original aspect, to fit inside a 1:1 box, whose width is the card's width. All the cards of a flex-row are then stretched in height to match the highest card.

enter image description here

Text under the image should flow directly underneath it, so a parent <div> doesn't work because it would create an empty space.

Javascript solutions are not allowed - and in general the content of the site must not jump around.

Here is what I have so far, but it isn't complete. The height of the image is still not "contained" to the width of the parent.

.catalog{      display: flex;      flex-flow: row wrap;      justify-content: center;      align-items: stretch;  }    .catalog > article {      flex: 0 0 10ch;      margin: 0.5em;      padding: 0.5em;      background-color: #faa;  }    img.fitted{      /* fit image inside square hitbox based on parent width */      width: 100%;      max-height: (this.calculated_width); /*what goes here?*/      height: auto;      object-fit: contain;  }
    <main class='catalog'>          <article>              <img src="https://i.imgur.com/tshbW0t.png" class='fitted'>              Square image          </article>          <article>              No image          </article>          <article>              <img src="https://i.imgur.com/JLiwyaG.png" class='fitted'>              Wide image          </article>          <article>              <img src="https://i.imgur.com/gmp2LyI.png" class='fitted'>              Tall image          </article>    </main>

I can't for the life of me figure this out. Is it even possible?

max(dict, dict.get) when dict items are NamedTuple objects

Posted: 23 Apr 2021 07:58 AM PDT

My goal is to find the id of the element in the dictionary, where similarity parameter is the highest.

I'm not sure I understand why these 2 methods are working identically and I would really appreciate it if someone could explain.

Here is my python 3.6 code:

  class ParentCandidate(NamedTuple):      similarity: float      title: str      c1 = ParentCandidate(0.875, 'longest title 1')  c2 = ParentCandidate(1, 'title 2')  c3 = ParentCandidate(0.9, 'title 3')  c4 = ParentCandidate(1.1, 'title 4')  c5 = ParentCandidate(0.5, 'title 5')    candidates = {1: c1, 2: c2, 3: c3, 4: c4, 5: c5}    closest_method1 = max(candidates, key=candidates.get)  closest_method2 = max(candidates, key=lambda sim: candidates[sim].similarity)  print(closest_method1, closest_method2)  assert closest_method1 == closest_method2  

Second method works exactly as planned and it seems clear how we identify max similarity value as we are referring directly to it. Whilst I simply do not understand how the max() function is able to do it's job when it receives NamedTuple objects for comparison.

@Output and @HostListener click causes Maximum call stack size exceeded when named the same

Posted: 23 Apr 2021 07:58 AM PDT

When having an @Output named click, and having a @HostListener listening for click, is it possible to make it so that a Maximum call stack size exceeded error doesn't occur? I would like to keep the output value as click, as I already know that I can just rename the output name and it will work.

I have tried e.stopPropagation(), but that just gives me an error saying that stopPropagation is not a function.

I have a component that looks like this. It has an incoming click listener and an outgoing click emitter:

@Component({    selector: 'my-button',    template: `      <button>{{label}}</button>    `  })  export class Button {    @Input() label = '';    @Input() uri?: string;    @Output('click') onButtonClick = new EventEmitter<string>();      @HostListener('click')    onClick() {      if (this.uri) {        this.onButtonClick.emit(this.uri);      }    }  }  

I am then using it like this:

<my-button label="Google" uri="http://google.com" (click)="doSomething()"></my-button>  

Here is a Stackblitz

cannot find symbol class ActivityMainBinding

Posted: 23 Apr 2021 07:57 AM PDT

I am facing with this problem related to a generated class for dataBinding. I couldn't figure this out.

enter image description here

Delete CRLF in text file using Bash or Notepad++

Posted: 23 Apr 2021 07:59 AM PDT

I think this is easier than I think, anyway I would like to know your ideas. I have this file:

AVP78031.1    AVP78042.1    ATO98108.1    ATO98120.1  

But I need to do this:

AVP78031.1  AVP78042.1  ATO98108.1  ATO98120.1  

Is there a way in NotePad++ to do this? However, I think this type of edition could do it in Bash Script or even only with the terminal. Is there a way to do this?

If you think that there is another way easier to do this, please let me know.

Any suggestion is always welcome.

Thank you for your time!

Angular innerHtml

Posted: 23 Apr 2021 07:58 AM PDT

I am relative new in Angular and I have the following question. I have a component: my.component.html

<app-loading *ngIf="loading" message="Inhalt wird geladen..." delay="0"></app-loading>  <div [innerHtml]="content | safeHtml"></div>  

And the following ts file: my.component.ts

export class MyComponent implements OnInit {    loading: boolean;    @Input() serviceUrl: string;    content: string;    constructor(public service: MyService) { }    ngOnInit() {      this.loading = true;      this.content = '';      this.service.getMyContent(this.serviceUrl).then(myContent => this.onMyContentRead(myContent));  }    onMyContentRead(dto: SimpleDto) {      this.loading = false;      this.content = dto.output;  }  

}

It calls a REST service and gets the dto.output, which is a string contains the following html content from MyClassToShow.html

<li id="myBox_panels">      <a href="%s" id="myBox_page_link">%s</a>      <app-tooltip [myText]="test"></app-tooltip>  </li>  

The tooltip components exists, and looks like this:

@Component({  selector: 'app-tooltip',  template: `      <a class="help" [pTooltip]="text" [tooltipPosition]="tooltipPosition" </a>   })    export class TooltipComponent implements OnInit {  tooltipPosition: string;    @Input() text;    constructor(private el: ElementRef) { }    ngOnInit() {      this.setTooltipPosition();  }    setTooltipPosition() {      ....  }  

It seems that the app-tooltip selector is not realized, because its template content is not displayed on the webpage, altough I can see the selector on the console log. The innerHtml can only contain plain HTML code?

How can I get my app-tooltip template as well?

Thnak you a lot in advance!

Vim: How to delete to closing square bracket in nested block

Posted: 23 Apr 2021 07:57 AM PDT

I have a long nested list in Python:

[{'name': 'John', 'args': [[1], [165], [22]]},  {'name': 'Tom', 'args': [[2], [180], [28]]},  ...  {'name': 'James', 'args': [[143], [174], [45]]}, # Delete from here on  ...  {'name': 'Ron', 'args': [[298], [199], [38]]}]  

and want delete from somewhere in the middle until the closing bracket. If I had a similar nested block with round brackets or braces, I could use d]) or d]}. That works as expected, but d]] not. Unfortunately f, t are also no good options, because of the nested structure.

How to add a function to the button generated by JavaScript?

Posted: 23 Apr 2021 07:58 AM PDT

I have a table in HTML that shows data about products. Well, in this table I want to add a button that allows the user to delete that product if he wishes, that button will be automatically generated together with the information in the table through JavaScript.

<!-- This is my table in HTML -->  <table id="tableVolume" border="1">      <thead>          <tr>              <th>  Volume  </th>              <th>  Serial Number  </th>              <th>  Situation  </th>              <th>  Delete  </th>          </tr>      </thead>  <tbody>  </tbody>  </table>  

The table without information should look like this:

enter image description here

In JavaScript I have a function that will work with this table, one to add blank lines and another to add information, including the delete button.

// Function to add lines to a table  $scope.insertLines = function () {            var tableS = document.getElementById("tableVolume");      var numOfRowsS = tableS.rows.length;      var numOfColsS = tableS.rows[numOfRowsS-1].cells.length;      var newRowS = tableS.insertRow(numOfRowsS);        for (var k = 0; k < numOfColsS; k++)      {          newCell = newRowS.insertCell(k);          newCell.innerHTML = '&nbsp;';      }  };    //Function to add informations to a table  $scope.infosnaTabelaSecun = function(number) {      if (FindCodigo != null && matchTraco == null) {          for (var k = 0; k < $scope.FindSerialNumber.length; k++) {              tableVolume.rows[number+k+1].cells[0].innerHTML = volTotal;              tableVolume.rows[number+k+1].cells[1].innerHTML = lines[(5+k)].substring(4);               tableVolume.rows[number+k+1].cells[2].innerHTML = "";              tableVolume.rows[number+k+1].cells[3].innerHTML = "<button class='button-one' onclick='DeleteSrlNumber()'> <i class='fas fa-trash-alt'></i></button>";          }      }      else if (matchTraco != null) {          for (var k = 0; k < (lines.length - $scope.pularLnhs); k++) {              tableVolume.rows[number+k+1].cells[0].innerHTML = volTotal;              tableVolume.rows[number+k+1].cells[1].innerHTML = lines[($scope.pularLnhs+k)].substring(4);                tableVolume.rows[number+k+1].cells[2].innerHTML = "";              tableVolume.rows[number+k+1].cells[3].innerHTML = "<button class='button-one' onclick='DeleteSrlNumber()'> <i class='fas fa-trash-alt'></i></button>";          }      }  };  

The rest of the code doesn't matter much, so much so that there are names of variables and functions that I didn't give details. What matters to me is the line

tableVolume.rows[number+k+1].cells[3].innerHTML = "<button class='button-one' onclick='DeleteSrlNumber()'> <i class='fas fa-trash-alt'></i></button>";  

where I add a button to each row in the table automatically. Well, I can add the button but I can't connect that button to a function, for example, when clicking the button it will delete the line where it is.

enter image description here

How would I do that? Link a function to this button that I created using JavaScript?

How to convert a string from one pattern to another?

Posted: 23 Apr 2021 07:58 AM PDT

I have one big string like this

//my.content.com/one.two  ......  //content.com/one_Two/three  ......  //content.com/three  

I want to replace part of it like this:

bigString.replaceAll("//(.*)content.com(.*)", "https://$1content.com$2)  

where replaceAll from Java.

I want to get the following string:

https://my.content.com/one.two  ......  https://content.com/one_Two/three  ......  https://content.com/three  

I know about replace function in Kotlin, but I think it works only with following cases:

val bigString = "abcDEFgh"  val result = bigString.replace("(.*)DEF(.*)".toRegex(), "XYZ")  println(result)     input: abcDEFgh  output: XYZ   

but it doesn't transform string into another pattern

Is it possible to do it in Kotlin?

ModuleNotFoundError: No module named 'mxnet.contrib.amp' When importing gluonnlp

Posted: 23 Apr 2021 07:58 AM PDT

I have the following versions of mxnet==1.4.0 and gluonnlp==0.9.1 installed using pip.

However when I run the following codeimport gluonnlp as nlp it yields the following error

ModuleNotFoundError: No module named 'mxnet.contrib.amp'  

So I try to manually import the missing module using

from mxnet.contrib import amp  import gluonnlp as nlp  

which also yields an error

ImportError: cannot import name 'amp' from 'mxnet.contrib' (/usr/local/lib/python3.7/dist-packages/mxnet/contrib/__init__.py)  

I've been running the code on Colab. Is there a possible workaround for this issue?

Please Advise.

Get value from Pyspark Column and compare it to a Python dictionary

Posted: 23 Apr 2021 07:58 AM PDT

So I have a pyspark dataframe that I want to add another column to using the value from the Section_1 column and find its corresponding value in a python dictionary. So basically use the value from the Section_1 cell as the key and then fill in the value from the python dictionary in the new column like below.

Original dataframe

DataId ObjId Name Object Section_1
My data Data name Object name rd.111 rd.123

Python Dictionary

object_map= {'rd.123' : 'rd.567'}  

Where section 1 has a value of rd.123 and I will search in the dictionary for the key 'rd.123' and want to return that value of rd.567 and place that in the new column

Desired DataFrame

DataId ObjId Name Object Section_1 Section_2
My data Data name Object name rd.111 rd.123 rd.567

Right now I got this error with my current code and I dont really know what I did wrong as I am not to familiar with pyspark

There is an incorrect call to a Column object in your code. Please review your code.

Here is my code that I am currently using where object_map is the python dictionary.

test_df = output.withColumn('Section_2', object_map.get(output.Section_1.collect()))  

To grep from file to get expected result

Posted: 23 Apr 2021 07:58 AM PDT

I have file contains variable ans with some values defined. i am trying to get all those variables using grep command. i want to list them on basis of "=" sign. i know using grep "ans" Test.txt will list out all the ans variable. but that is not what i am looking for. if i do grep "ans=" Test.txt it should list all variables present with name ans.

Please help me how can i make this work

test.txt        ans= 10;      ans =11;      ans   = 5;      ans   =    8;    

the normal grep command o/p:-

grep ans test.txt    ans= 10;  ans =11;  ans   = 5;  ans   =    8;  

Expected grep command o/p:-

grep "ans=" test.txt    ans= 10;  ans =11;  ans   = 5;  ans   =    8;  

Is it possible to install only master when installing kubernetes with Kubespray?

Posted: 23 Apr 2021 07:58 AM PDT

I am trying to install kubernetes using kubespray.

I have successfully configured master and worker, but I wanted to know if only masters without workers could be installed. In inventory.ini, only the hostname of the master was specified and the installation proceeded, and the following failure message was displayed.

Is there a way to install only master excluding worker with kubespray? help!

failed: [node1] (item=kube-node) => {  "ansible_loop_var": "item",  "assertion": "groups.get('kube-node')",  "changed": false,  "evaluated_to": false,  "item": "kube-node",  "msg": "Assertion failed"  

}

Dialogflow RE2 Regex

Posted: 23 Apr 2021 07:57 AM PDT

I am new here. I wanted to ask a question on using REGEX for an entity in DialogFlow

I wanted the entity to accept all text and spaces except for the symbol *

I have tried to use [A-Za-z0-9 ][^*], but it is not working. Any advice. thanks!

When I port-forward to a JupyterHub notebook, how can I keep the notebook alive if the connection drops?

Posted: 23 Apr 2021 07:58 AM PDT

I am running JupyterHub inside a k8s (GKE) cluster and so to access my user pod I port-forward into the proxy as follows:

kubectl port-forward proxy-nnnnnnnn-mmmm -n my_namespace -o 8000 8000  

The line can be slightly fragile at times and the connection is not very robust. If the connection drops for a few seconds, all is well.

But the connection can drop for much longer (up to ~ one minute, say). Then, if in JupyterLab I reconnect to the relevant kernel, output remains but any variables stored in memory are lost. This means I have to rerun the notebook from scratch, which is a major pain as some of the steps are very slow and intensive.

I wonder if the kernel is dying in spite of what's offered in the reconnection menu, or if there is some other problem. I'm not sure why the kernel stays up for a breakage of a few seconds but no longer, and whether this is simply a keep-alive issue.

If connection is lost for a time I also wonder whether a still-running process keeps operating, and whether its output can be recaptured.

What is going on?

Is there a way to keep the variables, imports etc. after an arbitrarily-long drop?

GitHub has an old and inconclusive thread on this - see https://github.com/jupyterhub/jupyterhub/issues/1318.

Edit:

Pod logs give:

[W 2021-04-22 10:08:34.039 SingleUserNotebookApp zmqhandlers:179] WebSocket ping timeout after 118914 ms.  [W 2021-04-22 10:08:37.121 SingleUserNotebookApp zmqhandlers:179] WebSocket ping timeout after 119816 ms.  Websocket closed  [W 2021-04-22 10:08:39.887 SingleUserNotebookApp zmqhandlers:179] WebSocket ping timeout after 118526 ms.  [I 2021-04-22 10:08:42.123 SingleUserNotebookApp kernelmanager:222] Starting buffering for 528deedd-ffa7-4c9d-b945-4cffdc3fe0e4:794ec160-0dd5-4d14-978a-00ed5a73b7ef  [I 2021-04-22 10:08:44.889 SingleUserNotebookApp kernelmanager:222] Starting buffering for 84cefe31-3d80-4db0-92aa-d4a3786b61d9:d3d4915f-8d4d-4d7a-be13-780a6d8b6b88  

Other unresolved GitHub threads:

https://github.com/jupyterhub/jupyterhub/issues/248

https://github.com/jupyter/notebook/issues/1164

Edit 2:

After explicitly enabling a no-timeout to cull (see comment* in default jupyter config and example at https://jupyterhub.readthedocs.io/en/stable/reference/config-user-env.html#example-enable-a-jupyter-notebook-configuration-setting-for-all-users - though this may be a red herring), after a disconnection the pod logs now show:

[I 2021-04-23 07:15:38.629 SingleUserNotebookApp multikernelmanager:201] Kernel shutdown: 23867ac2-0a9b-4f40-9ec8-359d7ee89dbf  [I 2021-04-23 07:15:38.931 SingleUserNotebookApp log:181] 204 DELETE /user/me/api/sessions/ed12abce-5182-47ca-a573-09fede0323ea?1619162137969 (me@::ffff:127.0.0.1) 304.20ms  [I 2021-04-23 07:15:39.807 SingleUserNotebookApp kernelmanager:179] Kernel started: b792d5ab-a800-4272-acb4-5bebced385b0, name: python3  

comment (*):

## Timeout (in seconds) after which a kernel is considered idle and ready to be                                                                                                  #  culled. Values of 0 or lower disable culling. Very short timeouts may result                                                                                                  #  in kernels being culled for users with poor network connections.                                                                                                              c.MappingKernelManager.cull_idle_timeout = 0  

So when I reconnect to the running kernel through the pop-up dialogue, the kernel is being deleted and restarted (which fits with the fact that I am seeing a lost session).

Why is the session getting lost?

Edit 3

Looking at the Chrome JS console logs, there is an ERR_CONNECTION_REFUSED when I try to reconnect.

That led me to this unresolved github issue, where someone had the same problem - https://github.com/jupyter/notebook/issues/2266

Then from there to this SO question - Jupyter Server Reachable from outside but refuse localhost connection

Now I will continue in my answer to this question.

Django/React App: How to have both Django URLS (for the api to send data) and React URLS (to render my components) in my web app, compatibly

Posted: 23 Apr 2021 07:58 AM PDT

I just added this to the urls.py in my react folder: re_path(r'^(?:.*)/?$', views.index), after following this stackoverflow post: react routing and django url conflict. My error in the dev tools is: Unknown_URL_Scheme

However, in my situation, this creates problems. My method of sending JSONs to my react is through the url: "api/leads," which is now inaccessible. How do I produce a way for my react urls to exist in harmony with my django urls? Attached are my django urls.py, react--> App.js, urls.py, views.py, index.html, and DataFetching.py (where you will be able to see how I send the data from my api).

Django: urls.py

from django.urls import path  from . import views    urlpatterns = [      path('api/lead/', views.LeadListCreate.as_view()),    ]  

Django Project: urls.py

from django.contrib import admin  from django.urls import path, include, re_path    urlpatterns = [      path('admin/', admin.site.urls),      path('', include('leads.urls')),      path('', include('frontend.urls')),        ]  

React--> urls.py

from django.urls import path, re_path  from . import views    urlpatterns = [      #path('', views.index),      re_path(r'^(?:.*)/?$', views.index),  ]  

By the way, I tried to look at the documentation for urls(r^...) and it wouldn't tell me how to import it, but instead basically said that urls is basically the same as re_path; this may be the problem, nonetheless, I would still not know the solution.

React-->views.py

from django.shortcuts import render      def index(request):      return render(request, 'frontend/index.html')  

React--> App.js

import './index.css';  import BellIcon from './icons/bell.svg';  import MessengerIcon from './icons/messenger.svg';  import CaretIcon from './icons/caret.svg';  import PlusIcon from './icons/plus.svg';  import DataFetching from "../DataFetching";  import DropdownMenu from "../DropDown";  import React, { useState } from 'react';  import {    BrowserRouter as Router,    Switch,    Route,    Link  } from "react-router-dom";      function App() {    return (      <Router>      <div className="App">        <Navbar>          <NavItem icon={<PlusIcon />} />          <NavItem icon={<BellIcon />} />          <NavItem icon={<MessengerIcon />} />          <NavItem icon={<CaretIcon />}>            <h1> Hello World </h1>            <DropdownMenu></DropdownMenu>          </NavItem>        </Navbar>                <Switch>            <Route path="/about">              <About />              <DataFetching />            </Route>            <Route path="/users">              <Users />            </Route>            <Route path="/">              <Home />            </Route>          </Switch>      </div>      </Router>    );  }    function Home() {    return <h2>Home</h2>;  }    function About() {    return <h2>About</h2>;  }    function Users() {    return <h2>Users</h2>;  }  

(There is more, but it is not relevant)

DataFetching.js

import React, {useState, useEffect} from 'react'  import axios from 'axios'    function DataFetching() {      const [leads, setLeads] = useState([])        useEffect(() => {          axios.get("api/lead")              .then(res =>{                  console.log(res)                  setLeads(res.data)              })              .catch(err => {                  console.log(err)              })      }, [])      return (          <div>              <ul>                  {                      leads.map(lead => <li key={lead.id}>{lead.name} says {lead.message}</li>)                  }              </ul>          </div>      )  }    export default DataFetching    

index.html

<!DOCTYPE html>  <html>  <head>      <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700;900&display=swap" rel="stylesheet">      <title>React App</title>  </head>  <body>    <noscript>You need to enable JavaScript to run this app.</noscript>    <div id="root">        <!-- React will load here -->    </div>    {% load static %}    <script src="{% static "frontend/main.js" %}"></script>  </body>    </html>  

If you have a better way to send data to my react app, or other useful insights, feel free to drop in the chat!

EDIT PROGRESS: NONE, STILL HAVE NO CLUE ABOUT WHERE TO EVEN START ON THIS PROBLEM, CAN'T FIND ANYTHING OF SUSBSTANCE ON THE TOPIC

Generating random natural numbers with higher probability for lower numbers?

Posted: 23 Apr 2021 07:58 AM PDT

I'm looking for a function like Python's random.randint() which generates random whole numbers between a and b, but one which is more likely to generate numbers closer to a, with only a few closer to b.

Is there a function that does that?

How can you add icon to a share sheet in swift?

Posted: 23 Apr 2021 07:57 AM PDT

I am using a share sheet in my iOS app. I am trying to figure out how I can add an icon to the top left corner of it when it opened. I added a photo example of what I mean.

[Example photo of what I mean][1]

    @IBAction func shareButtonClicked(_ sender: Any) {            //Set the default sharing message.          let message = "Check out Num8r, Its so much fun!"          let link = NSURL(string: "https://apps.apple.com/us/app/num8r/id1497392799")            // Screenshot:          UIGraphicsBeginImageContextWithOptions(self.view.frame.size, true, 0.0)          self.view.drawHierarchy(in: self.view.frame, afterScreenUpdates: false)          let img = UIGraphicsGetImageFromCurrentImageContext()          UIGraphicsEndImageContext()            //Set the link, message, image to share.          if let link = link, let img = img {              let objectsToShare = [message,link,img] as [Any]              let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)              activityVC.excludedActivityTypes = [UIActivity.ActivityType.airDrop, UIActivity.ActivityType.addToReadingList]              self.present(activityVC, animated: true, completion: nil)      }  }  

Typescript: Type 'string | undefined' is not assignable to type 'string'

Posted: 23 Apr 2021 07:58 AM PDT

When I make any property of an interface optional, I an error like following while assigning its member to some other variable

TS2322: Type 'string | undefined' is not assignable to type 'string'.   Type 'undefined' is not assignable to type 'string'.

interface Person {    name?:string,    age?:string,    gender?:string,    occupation?:string,  }    function getPerson(){    let person = <Person>{name:"John"};    return person;  }  let person: Person = getPerson();  let name1:string = person.name;//<<<Error here   

How do I get around this error?

Unable to Finish connecting to SonarQube server

Posted: 23 Apr 2021 07:58 AM PDT

This is going to sound like a ridiculous question, but using the SonarLint Eclipse plugin (v3.2.0) on the latest Eclipse (Oxygen), I am unable to add a new SonarQube server connection.

I am working behind a company firewall, but that doesnt appear to be an issue. I am following the steps here and am able to successfully connect to our internal SonarQube instance, provide my credentials, but it is just on the final step, that the 'Finish' button does not seem to do anything, see screen below:

enter image description here

I appreciate there is probably some background processes need to run in order for this Finish to actually finish :) But this doesnt appear to be doing anything...Anyone else experience this issue?

Any before people ask, I've restarted Eclipse/laptop, uninstalled and reinstalled SonarLint plugin etc.

Thanks in advance!

List of files in assets folder and its subfolders

Posted: 23 Apr 2021 07:58 AM PDT

I have some folders with HTML files in the "assets" folder in my Android project. I need to show these HTML files from assets' sub-folders in a list. I already wrote some code about making this list.

lv1 = (ListView) findViewById(R.id.listView);  // Insert array in ListView    // In the next row I need to insert an array of strings of file names  // so please, tell me, how to get this array    lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, filel));  lv1.setTextFilterEnabled(true);  // onclick items in ListView:  lv1.setOnItemClickListener(new OnItemClickListener() {      public void onItemClick(AdapterView<?> a, View v, int position, long id) {          //Clicked item position          String itemname = new Integer(position).toString();            Intent intent = new Intent();          intent.setClass(DrugList.this, Web.class);          Bundle b = new Bundle();          //I don't know what it's doing here          b.putString("defStrID", itemname);           intent.putExtras(b);          //start Intent          startActivity(intent);      }  });  

No comments:

Post a Comment