Friday, April 30, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


VHDL how to use floor and log2 together

Posted: 30 Apr 2021 08:46 AM PDT

In the following code, if N equals 127 or 128, I always get BitLength=7 and BitLength2=6. Can someone explain this ?

constant N : integer := 128;  constant N_LOG2 : real := log2(real(N));  signal BitLength : integer := integer(N_LOG2);  signal BitLength2 : integer := integer(floor(N_LOG2));  

I would have expected that BitLength is always equal to BitLength2 :

  • For N=127, they should be equal to 6.
  • For N=128, they should be equal to 7.

Removing rows which contain character(0)

Posted: 30 Apr 2021 08:46 AM PDT

I have a data frame which looks like this:

> head(Companys_)                             CompanyName Filing FilingDate             Ticker  1 10X Capital Venture Acquisition Corp    S-1 2020-09-25 VCVC, VCVCU, VCVCW  2         2020 ChinaCap Acquirco, Inc.    S-1 2007-04-20                     3         26 Capital Acquisition Corp.    S-1 2020-12-23 ADER, ADERU, ADERW  4               5:01 Acquisition Corp.    S-1 2020-09-25               FVAM  5            5G Edge Acquisition Corp.    S-1 2021-03-30                     6              7GC & Co. Holdings Inc.    S-1 2020-12-07  VII, VIIAU, VIIAW  

How should I remove the rows with no value for the Ticker?

The blanks show up as character(0) when you view the data frame.

useEffect called when a variable not in the dependancy list is updated (causing an infinite loop)

Posted: 30 Apr 2021 08:46 AM PDT

I'm trying to do an ajax call when a state changes, and then set another state to the result of that ajax call.

const [plc, setPlc] = useState(null);  const [tags, setTags] = useState([]);    ...    useEffect(()=>{    if(plc != null) {      myAjaxPromiseFunction(plc).catch((err)=>{        console.log(err);      }).then((tags)=>{        setTags(tags);      });    }  }, [plc]);  

For some reason, this results in an infinite loop. However, when I remove the setTags(tags); statement it works as expected. It appears that the setTags function is causing the effect hook to update, but tags is not a part of the dependencies of this effect hook.

FYI, the tags variable is supposed to be a list of objects.

Any ideas? Thanks for the help.

How add JavaFX application icon to task bar?

Posted: 30 Apr 2021 08:46 AM PDT

How can I add an icon of JavaFX application to task bar? Which element in JavaFX is responsible for it?

enter image description here

AWS S3 Static Website isn't serving css files

Posted: 30 Apr 2021 08:46 AM PDT

I've gone through most of the previous related questions and answers that appear similar to mine. Here are some of the things I have tried based on what others have suggested:

  1. Made bucket public
  2. Clear browser cache
  3. I've updated the key and value to match text/css

When I click the website endpoint link inside of S3, the CSS files upload to the browser properly.

But when I go directly to the web address from the browser, the page contains no CSS. The style.css file is saved to my local cpu. Any suggestions are appreciated.

jest/react-testing-library identical tests are failing?

Posted: 30 Apr 2021 08:46 AM PDT

I'm attempting to test the correct styling is applied to a child component when different props are passed to the parent. The first test works exactly as expected but the second test always fails. Debugging this took me duplicating the first test and running both the first test and its duplicate and the second test always fails with an unhelpful error message.

Test code:

describe("ThemeProvider Component", () => {    const defaultProps: ThemeProviderProps = {      children: (        <Typography data-testid="themeProviderChild" variant="bodyLarge">          Test Child Component        </Typography>      ),    }      const renderComponent = (passedProps = defaultProps) =>      render(<ThemeProvider data-testid="ThemeProvider" {...passedProps} />)      it("should render with default theme", () => {      const { getByText } = renderComponent()      const paragraph = getByText("Test Child Component")        expect(paragraph).toHaveStyle(`font-size: 18px`)    })      it("should render with default theme test 2", () => {      const { getByText } = renderComponent()      const paragraph = getByText("Test Child Component")        expect(paragraph).toHaveStyle(`font-size: 18px`)    })  })  

Error:

FAIL src/ThemeProvider/ThemeProvider.test.tsx      ● ThemeProvider Component › should render with default theme test 2        expect(element).toHaveStyle()        - Expected        - font-size: 18px;          29 |     const paragraph = getByText("Test Child Component")        30 |      > 31 |     expect(paragraph).toHaveStyle(`font-size: 18px`)           |                       ^        32 |   })        33 |          at Object.<anonymous> (src/ThemeProvider/ThemeProvider.test.tsx:31:23)  

As you can see it doesn't give an 'actual' result, only the expected.

How to determine if a PKCS#8 private key is well-formed?

Posted: 30 Apr 2021 08:45 AM PDT

I have an application using a private key as long string input, and would like to validate the key against PKCS#8 format-specifications (but not the validity of the private key itself).

An example of private key (with carriage returned replaced by \n):

-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCoknaik3X9AwXf\n1nb/BfHlR4RBcij+Ri2RzxZfdcTuhcIL4XLrgwaz/Skx3R/UjU3eoxneBjcGeA7X\nQX75aXMS2FKrfQEJ6mp9AVQTowPC5VkAp8L8vk/cBrckZFHQsm9bHnLirJ6LYhWK\nsLbvgpJo+P4OMG4P/GeQVwaWwLxaZNSs0sEjVRuy0vbWCO4jJwnmZpPMxU0sRCRN\nxod3n6DJ0XhwCP/CxhlFVHjoM/nX/HGlPWkwG05BFBH4J9Zy4SNNNg6CDjIsl56R\n2Fu8d/RHtIB/UPhIEoV6t5rWkJx4SP76OwjiXl9IGiDWpb6uu2/OQctZRBezxvCZ\nO4lgzKFXAgMBAAECggEAYK4XsmhmbCTWsqka+GqdcIVS2gIydpsjOZQO3dL6jl5S\ni2PS+DXem04f2URcJBiix4S9qjPgTSqAQH6E52DOKcm9qDL6bIhwaJ9hbB27Y4UM\nRa7xyukPfj6vvQR4U/xyl0zgURb1mzU266MsWDOH6wKbGuI1zZ9SelsfIUkK/cAV\ns6Ao4kzCCQWZMQ/GkYxtQXg/tdPtI2Ueexon0Xtr4bc50XefEFvpKNi3ZqX7fRHV\ne2bvnzKH6TN6DlEBruIdRwLsfmFXMIXU98D1OYokaaeVeHH5iZ2nXrlGGw72RfcQ\nawrEHvMTTUhzg5LnMw30Smq1ogPanhLtbofPqIQJwQKBgQDfxKZ7lFle+tiMEKmU\n87uiRavAHrmQNipqBcbtadJqqQtvGOCxwSg9phh2YnwxRSyw1oBpg4ogvg1QbhqV\nUNfB8b/M2kpPRpGZpjCvi6En8GzK6K4e/UQJ4i0l7tPT9tt3TynbMwb3xFcEnFEX\nIxfcWnlbC5tm5Sea6b4BzwK84QKBgQDA2nvqHNsqU9HyCX61R5Bo2QLnsI4CgUBk\nz2hhc4bteb//mKCWeVvPNRu9AFhNEJzix0/EEkCVhbpIKE1DUCzBPWI/4CkH1bRc\nRBE7/7I3pcMBbV22OdGoISmUf6IFZSyQuBoShLDBH3CVmqdmto9b5nwYaTgdycvt\nxpyQvdKtNwKBgHFzF2EyXnlcPqwMyp29URU9s41NRpGKFMj6MtgtvcPb/vMNruYQ\nY2GWM3LaDdNBGh5yMlrMmRxunvt3Rz0K5sjq025+AgzdX3aCHs7xwPwp1k6t15HY\noEVOictgob8mujBsT3FWFqNJxUCOLELJxRAwQrTZVqm9Zu4Qsgfit6WhAoGBAKWx\nUbOUNU0JlSDBvaacpNsgUFmlnG1UhXHXrVPFAVE5QJeml5qRDCtb8sgQ6szTkCdb\nnRHVqL2Olrz2O2OxF7KzPZ2pxzbfCkYXiUMmbgVXmtK4F0LALHyqeWIHwrml8oMo\nWeY9MOvMSluO83LRORx5S3dht4AIZ/iTouLM5JxDAoGAcAnam49TeCFZuOu5/QCb\nGYyAntOQL/nunSbuHoNvC+bBrcUX2BfDkalkzlm/YRJgmqSQ7Ih3fbp4i5NCVtpM\n1dafoyed5UqY0F7Vou7JJE57tlKieKPhQOMTSl2Q5WMvby+owRb0Sx325xQvoslH\nQM9+y6wy6YMdNweC+JkcZVo=\n-----END PRIVATE KEY-----  

Any idea ?

Screwed up my git repository and not experienced enough to undo it

Posted: 30 Apr 2021 08:45 AM PDT

I'm in second year of college taking computer science and for that I needed to create an app. I chose to use visual studio, and to use a online git repository (Azure DevOps) to keep it backed up as my school has access to it. I found the ability to make commits very useful, as well as the history. While I am somewhat familiar with commiting, branches and such, I am a total noob to git and have only ever used it through visual studio, using the features built in.

I was about to make a final commit and tie everything off, but apparently visual studio changed their layout, which threw me a bit, but I pushed my final commit, not realizing that the version on my computer was a couple of commits behind. Visual studio threw an error, with a dialog box that I can't remember. I clicked Pull and Push, expecting it to just work (like I was used to) and pull the new commits, then make the final commit. this was not the case, and I have no idea how to undo this. My current repo looks like this, both on server and my machine: enter image description here

From what research I have done, I think, but am not sure, that rebase is the command I need, but even then, I don't really know what it will do, or how to use it. How can I get to a repo with my old and new commits in a line without that annoying side branch?

Python ldap3 how to get all members of a group

Posted: 30 Apr 2021 08:46 AM PDT

I have tried every solution on Stackoverflow for this and none work. Using python3 and ldap3 I can make the bind with the user and with the service account and I can even extract the users email address. But I cannot verify that he is from a certain group. I am trying to get all members of the group and then I will see if he exists in that group.

Users DN: OU=Users,O=Acme Who is a member of: CN=my-users,OU=MyUsers,OU=Groups,O=Acme

Here is the code I have so far..

try:      l = bind_user(MyServiceAccount, MyServiceAccountPassword)  except Exception as e:      logger.info(f'Error attempting to bind with ldap server: {e}')      return(f'Error logging in. Details: {e}')        #### This first search works and returns the users email address ###      search_filter = f"(cn={user_name})"      search_attribute =['mail']      l.search(search_base='OU=Users,O=Acme',           search_scope=SUBTREE,           search_filter=search_filter,           attributes=search_attribute)        print('l.response',l.response)      email = l.response[0]['attributes']['mail'] # All Good to here                   ### This next search does not work. it just returns and empty list       l.search(          search_base='CN=my-users,OU=MyUsers,OU=Groups,O=Acme',          search_filter='(cn=my-users)',          search_scope='SUBTREE',          attributes = ['member'],          size_limit=0      )            print(f'printing entries = {l.entries}') # Outputs []      print(f'Group response = {l.response}') # This also outputs []            for entry in l.entries: # Never happens          print(entry.member.values)  

Passing an array of strings as an argument into a double pointer parameter

Posted: 30 Apr 2021 08:46 AM PDT

For the following code:

char* fcn(char **para){    }    int main(void){    char *arg[] = {"XX", "YY", "ZZ"};    char *s = fcn(arg);   }  

Why is it that when we pass the argument into the function in char *s = fcn(arg);, we don't need to do &arg? arg[] seems to me a single pointer, so shouldn't we do &ptr for it to be referenced by a double pointer as in the parameter of fcn(): char* fcn(char **para)?

Verifying the existence of a file in the terminal

Posted: 30 Apr 2021 08:45 AM PDT

I am copying some code from github, but when I try accesing a file within, the terminal outputs "No such file or directory".

I've tried looking for the files manualy in the computer but indeed I cannot find them.

My guess is that the cloning is saving the codes somewhere else, and when I try to change directory it cannot access it since it does not exist in the computer.

Here is what I get to see in the terminal:

fun4all@Fun4AllSingularity:~$ git clone https://github.com/sPHENIX-Collaboration/macros.git  Cloning into 'macros'...  remote: Enumerating objects: 8930, done.  remote: Counting objects: 100% (422/422), done.  remote: Compressing objects: 100% (179/179), done.  remote: Total 8930 (delta 278), reused 348 (delta 241), pack-reused 8508  Receiving objects: 100% (8930/8930), 1.84 MiB | 1.72 MiB/s, done.  Resolving deltas: 100% (5193/5193), done.  fun4all@Fun4AllSingularity:~$ cd macros/macros/g4simulations/  bash: cd: macros/macros/g4simulations/: No such file or directory  

I'm not sure if it is important, but I am using a virtual box, this is not in my local computer.

Also, it worked before, just recently it started giving this problem.

I have an error at runtime, but not in Console

Posted: 30 Apr 2021 08:46 AM PDT

To be brief, i have this error in Chrome console :

jQuery.Deferred exception: Cannot read property 'split' of undefined TypeError: Cannot read property 'split' of undefined  

This is my js code :

var fn_comments = function () {      if ($('.o-commentaires-items').length) {          var cls = $(this).find($(".comment-parent")).attr('id').split(' ')[0];          number = cls.substr(cls.lastIndexOf("-") + 1);            // var targetBtn = $(this).closest($(".comment-parent").attr("data-comment-parent"));          console.log("closest : ", 'collapsee-' + number);          $(this).find($(".comment-parent").next(".indented").attr({              "id":  "collapse-"+number,              "aria-labelledby":  "heading-"+number          }));      }  }  

how can I extends from another class

Posted: 30 Apr 2021 08:45 AM PDT

I'm new in Python/Django and I'm working on a little project to improve my self, I would like to know how can I extends or how can I call a function from another class I already tried but I got some errors

this is my code : first class

# Create your views here.  class ContactCenter(object):      def myFunction(self, logged_user_id = None):           print("hello")  

second class

from apps.contact.views import ContactCenter    class ListModelMixin(object):        def list(self, request, *args, **kwargs):          ContactCenter.myFunction()  

React Native: Using JS Stylesheet vs CSS/SCSS for styles

Posted: 30 Apr 2021 08:46 AM PDT

I've been told that using CSS/SCSS to define styles in React Native is a better practice than just using the native StyleSheet from 'react-native'.

I've been looking around a lot and can't find a single reason to agree on that, rather than the fact that if you already have css styles, it's easier to import them into React Native, than "converting" them.

But I don't see any reason to start a brand new React Native application with CSS/SCSS.

Am I missing something? Is it a matter of taste? Is it even possible to use only CSS/SCSS on React Native?

C++ program ends with no reason after fork()? [closed]

Posted: 30 Apr 2021 08:46 AM PDT

My program is behaving really strange, in main.cpp I have:

int main(int argc, char *argv[]) {  while (true)    {      SmallShell &smash = SmallShell::getInstance();      std::string cmd_line;      std::getline(std::cin, cmd_line);      smash.executeCommand(cmd_line.c_str());    }      return 0;  }      void SmallShell::executeCommand(const string &cmd_line) {      /** Add spaces before and after >/>> **/      string e_cmd_line = _trim(cmd_line);      bool is_redirection_command = false;      int f_ocu = e_cmd_line.find_first_of('>');      if (f_ocu != string::npos)      {          is_redirection_command = true;          e_cmd_line.insert(f_ocu, " ");          int l_ocu = e_cmd_line.find_last_of('>');          e_cmd_line.insert(l_ocu + 1, " ");      }        Command *cmd = CreateCommand(e_cmd_line, is_redirection_command);      if (cmd->is_built_in()) // redirection is BUILT_IN command      {          // BUILT_IN COMMANDS CAN'T BE STOPPED OR KILLED          cmd->execute();          delete cmd;      } else      {          pid_t pid = fork();          if (pid < 0)          {              perror("smash error: fork failed");          } else if (pid > 0)          {              waitpid(pid, nullptr, WUNTRACED); //CHECKED FINE              delete cmd;          } else          {              setpgrp();              cmd->execute();              delete cmd;          }      }  }  

when the input is ls, I call shell like this:

ExternalCommand::ExternalCommand(const string &cmd_line) : Command(cmd_line) {  }    void ExternalCommand::execute() {      string f_cmd = cmd_str;      if (execlp("/bin/bash", "bash", "-c", f_cmd.c_str(), nullptr) < 0)      {          perror("smash error: execv failed");      }  }  

but when the input is ls > something (redirection command) I want to call shell with only ls as in previous case so I added a new if case like this:

Command *SmallShell::CreateCommand(const string &cmd_line, bool is_redirection_command) const {      string cmd_s = _trim(string(cmd_line));      string firstWord = cmd_s.substr(0, cmd_s.find_first_of(" \n"));        if (is_redirection_command)      {              Command *cmd = new ExternalCommand("ls");              cmd->execute();              delete cmd;      } else      {          return new ExternalCommand(cmd_line);      }  }  

It works as the previous case but my program gets terminated instantly. why is that?

my output:

ls                                                                                                                                                                         a.out  Commands.cpp  Commands.h  main.cpp                                                                                                                                  ls > me                                                                                                                                                                    a.out  Commands.cpp  Commands.h  main.cpp                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        ...Program finished with exit code 0                                                                                                                                       Press ENTER to exit console.       

In case you want to hand-try my code here is a link: https://onlinegdb.com/Hkx0Rfstvu

all details are already included in question.

Is it possible to count how many triangles there are in an image by using opencv and numpy?

Posted: 30 Apr 2021 08:46 AM PDT

for example in this picture there are nested triangles therefore it is not a regular shape

How can I count and order in a custom way items of a list?

Posted: 30 Apr 2021 08:46 AM PDT

I have a list of keyboard keys which looks like this (but is much longer):

pressed_keys = ['u', 'u', 't', 'q', 'q']

I want to count them and order them in the way that appear on the keyboard. For example, for that list I would like to get [2,0,0,0,1,0,2,...etc] . I know collections.Counter, but It only gives the keys which were pressed.

outlook add-in is not working internet explore using react js

Posted: 30 Apr 2021 08:46 AM PDT

Outlook add-in is not working on internet explorer give us the error SCRIPT5022: Office.js has not fully loaded. Your app must call "Office.onReady()" as part of it's loading sequence (or set the "Office.initialize" function). If your app has this functionality, try reloading this page.

Is there a way to make a windowed fullscreen mode in pygame?

Posted: 30 Apr 2021 08:45 AM PDT

I want the window to be my resolution but still have the top bar appear. Just like you maximise a window. This is what I have so far.

os.environ['SDL_VIDEO_CENTERED'] = '1'  display_info = pygame.display.Info()  self.width, self.height = display_info.current_w, display_info.current_h  self.screen = pygame.display.set_mode((self.width, self.height), pygame.NOFRAME)  

but it seems to not work and only fullscreen the window to my resolution. What am I missing?

Numerical integration of array with array value as upper limit

Posted: 30 Apr 2021 08:46 AM PDT

So I have the following code:

import numpy as np  import scipy.special as spec  import scipy.integrate as integrate    a = array  b = constant * a  c = b*a/constant  e3 = spec.expn(3,c)  

Now, I need to compute the integral for e3 going from 0 to a. Since e3 is a function of c which in turn is a function of a I'm having a hard time solving this one. I've tried using a loop, integrate.quad or both in order to solve this but I keep getting all sorts of errors.
I'm pretty new at integrating sutff in python so any help would be appreciated.

Problem uploading sketch to arduino uno/esp8266

Posted: 30 Apr 2021 08:46 AM PDT

Getting this error while uploading:

Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"  Executable segment sizes:  IROM   : 236720          - code in flash         (default or ICACHE_FLASH_ATTR)     IRAM   : 26892   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)     DATA   : 1252  )         - initialized variables (global, static) in RAM/HEAP     RODATA : 780   ) / 81920 - constants             (global, static) in RAM/HEAP     BSS    : 24976 )         - zeroed variables      (global, static) in RAM/HEAP     Sketch uses 265644 bytes (27%) of program storage space. Maximum is 958448 bytes.    Global variables use 27008 bytes (32%) of dynamic memory, leaving 54912 bytes for local variables. Maximum is 81920 bytes.    esptool.py v2.8    Serial port COM3    Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):      File "C:\Users\Arsh\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.7.4/tools/upload.py", line 65, in <module>        esptool.main(cmdline)      File "C:/Users/Arsh/Documents/ArduinoData/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 2890, in main        esp.connect(args.before)      File "C:/Users/Arsh/Documents/ArduinoData/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 483, in connect        raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))    esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header    esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header    or it says Invalid Head of Packet(0xF0)      _        This report would have more information with  "Show verbose output during compilation"  option enabled in File -> Preferences.  

This is the pin configuration:

Insted of the 3.3v im using a voltage regulator.
Also RX connected to RX & TX to TX.

Code:

  #include <ESP8266WiFi.h>    void setup()  {    Serial.begin(115200);    Serial.println();      WiFi.begin("username", "password");      Serial.print("Connecting");    while (WiFi.status() != WL_CONNECTED)    {      delay(500);      Serial.print(".");    }    Serial.println();      Serial.print("Connected, IP address: ");    Serial.println(WiFi.localIP());  }    void loop() {}  

Someone suggested to ground the GPIO0, didn't work.
Tried installing different version of the Board:"Generic ESP8266 Module" still getting the same error.

The module works fine when working without the library using the Board:"arduino uno"

Clock hand is not rotating the way I want

Posted: 30 Apr 2021 08:45 AM PDT

I have made a clock using html css and javascript. the problem I'm running into is when the seconds hand completes a clockwise rotating, it goes from 360deg to 0deg following an anticlockwise rotation instead of continuing clockwise. Video: https://gyazo.com/92a5c8d685256c99a96bf74c9c041a9d

const hourEl = document.querySelector('.hour')  const minuteEl = document.querySelector('.minute')  const secondEl = document.querySelector('.second')  const timeEl = document.querySelector('.time')  const dateEl = document.querySelector('.date')  const toggle = document.querySelector('.toggle')    const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];  const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];    function setTime() {     const time = new Date();     const month = time.getMonth()     const day = time.getDay()     const date = time.getDate()     const hours = time.getHours()     const hoursForClock = hours >= 13 ? hours % 12 : hours;     const minutes = time.getMinutes()     const seconds = time.getSeconds()     const ampm = hours >= 12 ? 'PM' : 'AM'       hourEl.style.transform = `translate(-50%, -100%) rotate(${scale(hoursForClock, 0, 11, 0, 360)}deg)`     minuteEl.style.transform = `translate(-50%, -100%) rotate(${scale(minutes, 0, 59, 0, 360)}deg)`     secondEl.style.transform = `translate(-50%, -100%) rotate(${scale(seconds, 0, 59, 0, 360)}deg)`       timeEl.innerHTML = `${hoursForClock}:${minutes < 10 ? `0${minutes}` : minutes} ${ampm}`     dateEl.innerHTML = `${days[day]}, ${months[month]} <span class="circle">${date}</span>`  }  const scale = (num, in_min, in_max, out_min, out_max) => {     return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;  }    setTime()    setInterval(setTime, 1000)
.needle.hour {     transform: translate(-50%, -100%) rotate(0deg);  }    .needle.minute {     transform: translate(-50%, -100%) rotate(0deg);     height: 100px;  }    .needle.second {     transform: translate(-50%, -100%) rotate(0deg);     height: 100px;    background-color: #e74c3c;  }
<div class="clock-container">    <div class="clock">      <div class="needle hour"></div>      <div class="needle minute"></div>      <div class="needle second"></div>      <div class="center-point"></div>    </div>    <div class="time"></div>    <div class="date"><span class="circle"></span></div>  </div>

RBAC (Role Binding Access Control) on K3s

Posted: 30 Apr 2021 08:46 AM PDT

after watching a view videos on RBAC (role based access control) on kubernetes (of which this one was the most transparent for me), I've followed the steps, however on k3s, not k8s as all the sources imply. From what I could gather (not working), the problem isn't with the actual role binding process, but rather the x509 user cert which isn't acknowledged from the API service

$ kubectl get pods --kubeconfig userkubeconfig

error: You must be logged in to the server (Unauthorized)

Also not documented on Rancher's wiki on security for K3s (while documented for their k8s implementation)?, while described for rancher 2.x itself, not sure if it's a problem with my implementation, or a k3s <-> k8s thing.

$ kubectl version --short  Client Version: v1.20.5+k3s1  Server Version: v1.20.5+k3s1    

With duplication of the process, my steps are as follows:

  1. Get k3s ca certs

This was described to be under /etc/kubernetes/pki (k8s), however based on this seems to be at /var/lib/rancher/k3s/server/tls/ (server-ca.crt & server-ca.key).

  1. Gen user certs from ca certs
#generate user key  $ openssl genrsa -out user.key 2048    #generate signing request from ca  openssl req -new -key user.key -out user.csr -subj "/CN=user/O=rbac"    # generate user.crt from this  openssl x509 -req -in user.csr -CA server-ca.crt -CAkey server-ca.key -CAcreateserial -out user.crt -days 365  

... all good: enter image description here

  1. Creating kubeConfig file for user, based on the certs:
# Take user.crt and base64 encode to get encoded crt  cat user.crt | base64 -w0    # Take user.key and base64 encode to get encoded key  cat user.key | base64 -w0  
  • Created config file:
apiVersion: v1  clusters:  - cluster:      certificate-authority-data: <server-ca.crt base64-encoded>      server: https://<k3s masterIP>:6443    name: home-pi4  contexts:  - context:      cluster: home-pi4      user: user      namespace: rbac    name: user-homepi4  current-context: user-homepi4  kind: Config  preferences: {}  users:  - name: user    user:      client-certificate-data: <user.crt base64-encoded>      client-key-data: <user.key base64-encoded>  
  1. Setup role & roleBinding (within specified namespace 'rbac')
  • role
apiVersion: rbac.authorization.k8s.io/v1  kind: Role  metadata:    name: user-rbac    namespace: rbac  rules:  - apiGroups:    - "*"    resources:    - pods    verbs:    - get    - list  
  • roleBinding
apiVersion: rbac.authorization.k8s.io/v1  kind: RoleBinding  metadata:    name: user-rb    namespace: rbac  roleRef:    apiGroup: rbac.authorization.k8s.io    kind: Role    name: user-rbac  subjects:    apiGroup: rbac.authorization.k8s.io    kind: User    name: user   

After all of this, I get fun times of...

$ kubectl get pods --kubeconfig userkubeconfig  error: You must be logged in to the server (Unauthorized)  

Any suggestions please?

Apparently this stackOverflow question presented a solution to the problem, but following the github feed, it came more-or-less down to the same approach followed here (unless I'm missing something)?

correst use of append and Alignat from pylatex while pdf creating (python)

Posted: 30 Apr 2021 08:45 AM PDT

I want to use save some formulas from latex in pdf

from pylatex import Document, Section, Subsection, Command,Package, Alignat    doc = Document(default_filepath='basic.tex', documentclass='article')  doc.append('Solve the equation:')  doc.append(r'$$\frac{x}{10} = 0 \\$$',Alignat(numbering=False, escape=False))  doc.generate_pdf("test", clean_tex=True)  

But I get an error:

   doc.append(r'$$\frac{x}{10} = 0 \\$$',Alignat(numbering=False, escape=False))  TypeError: append() takes 2 positional arguments but 3 were given  

How should I solve my problem?

How to display custom vector tiles on Google Maps

Posted: 30 Apr 2021 08:45 AM PDT

The goal is to display large amount of data on Google Maps. By large amount I mean around 10 millions of segments stored in PostgreSQL database. The segments represent some characteristics of roads, so segments should overlay the roads in base map. The segment properties may change over time.

The best technical solution for this problem is to use custom tile server (please correct if wrong).

According to Google Maps JS API, I found out two ways to draw over the map using custom tile server:

I have tried both. The first one does not fit my needs because GeoJson appears too large, what results in performance issues. The second one is bad from UX point of view, because it is using raster tiles, whereas nowadays we should use vector tiles. I also looked at OpenLayers / Leaflet, but didn't find an official way to go with Google Maps (see https://github.com/mapbox/mapbox-gl-js/issues/1791).

The key here would be to use vector tiles, however I cannot manage to render vector tiles (MVT) on Google Maps.

Is there any ways at all to render vector tiles on Google Maps Platform?

How to focus a paper-input in lit-element

Posted: 30 Apr 2021 08:45 AM PDT

I have a <paper-input> element on my page that I want selected when the page loads. I tried to focus it when the page is first updated but that hasn't worked.

firstUpdated() {      this.shadowRoot.querySelector('#input').focus();  }  

The paper-input page suggests that setting tabindex is required for input.focus() to work, so I did that as well and it did not work. I have also tried the solutions suggested for this SO question about paper-input in polymer, and none of them worked.

Is there a way to focus a paper-input in lit-element?

How to check whether server supports HTTP/2 in JavaScript on browser

Posted: 30 Apr 2021 08:46 AM PDT

I'd like to know the way to check whether a server supports HTTP/2 in JavaScript in Browser. If possible, I would like to know the way without using an API server.

The reason to check is as follows.

  • In most browsers, HTTP/1 requests are limited to 6-8 concurrent requests.
  • To detect HTTP/2, and provide the number of requests properly

Disable specific days in material ui calendar in React

Posted: 30 Apr 2021 08:46 AM PDT

I am using material-ui v0.20.0 for React js This is my DatePicker component

<Field      name='appointmentDate'      label="Select Date"      component={this.renderDatePicker}  />    renderDatePicker = ({ input, label, meta: { touched, error }, ...custom,props }) => {      return (          <DatePicker             {...input}             {...custom}             autoOk={true}             floatingLabelText={label}            dateForm='MM/DD/YYYY'             shouldDisableDate={this.disabledDate}            minDate={ new Date()}            value={ input.value !== '' ? input.value : null }            onChange={(event, value) => input.onChange(value)}           />      );  };  

What should I write in disabledDate(){...} if I want to disable any of the day/s ?

Think python exercise 6.4

Posted: 30 Apr 2021 08:45 AM PDT

A number, a, is a power of b if it is divisible by b and a/b is a power of b. Write a function called is_power that takes parameters a and b and returns True if a is a power of b. Note: you will have to think about the base case. I found this peace of code as it's solution:

def is_power(a,b):      if (a % b == 0):          return True          if (a/b == 1):              return True          else:              (is_power (a/b, b) )      else:          return False  

But I guess some lines are not necessary. Here is my own code:

def is_power(a,b):      if (a % b == 0):          return True      else:          return False  
  1. What is the reason of existence of extra lines?
  2. Both codes don't work for float numbers such as is_power(2.25, 1.5). Both, return False.

How to enter Greek characters in Emacs

Posted: 30 Apr 2021 08:46 AM PDT

This page indicates that Greek letters can be inserted into Emacs by using M-i. However, Emacs 23.2.1 in a Debian Squeeze variant inserts the "tab" character when M-i is pressed. How can I insert Greek letters such α and β in Emacs?

No comments:

Post a Comment