Tuesday, September 7, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


upload an image to a pdf file using php and fpdf

Posted: 07 Sep 2021 08:29 AM PDT

I want to upload a logo image inside a pdf file and put it in a cell and I want to do this strategy: I want to measure the dimensions of the image to know whether it is portrait, landscape or quadrate image.

portrait image -> Height image = H cell, Width image = (H cell / H image)* W cell.

landscape image -> W image = W cell, H image = (W cell / W image)* H cell.

quadrate image -> H image = H cell, W image = W cell. and evantually center the image inside the cell. I tried to do it as in the code down but it didnt work, any suggestion would be appreciated about the strategy or the code or how to fix the logo in the picture down would be appreciated.

if ($layoutCertificateLogo != null) {              list($x1, $y1) = getimagesize($layoutCertificateLogo);              $x2 = 40;              $y2 = 40;              //check if the image is portrait              if ($y1>$x1) {                  $y2 = 80;                  $x2 = (80/$y1)*80;               }              //check if the image is landscape              else if ($x1 > $y1){                  $x2 = 80;                  $y2 = (80/$x1)*80;              }              //check if the image is quadrate              else{                  $x2 = 80;                  $yx = 80;              }                            $pdf->Cell(80, 80, $pdf->Image($layoutCertificateLogo, $pdf->GetX(), $pdf->GetY(), $x2, $y2, $layoutCertificateLogo_ext), 0, 0, 'L', false);          }          $pdf->Output();  

now the logo looks like this enter image description here and the code of this logo in the picture is this :

if ($layoutCertificateLogo != null) {              list($x1, $y1) = getimagesize($layoutCertificateLogo);              $x2 = 40;              $y2 = 40;              if (($x1 / $x2) < ($y1 / $y2)) {                  $y2 = 0;              } else {                  $x2 = 0;              }              $pdf->Cell(80, 80, $pdf->Image($layoutCertificateLogo, $pdf->GetX(), $pdf->GetY(), $x2, $y2, $layoutCertificateLogo_ext), 0, 0, 'L', false);          }          $pdf->Output();  

Finding the JSON file containing a particular key value , among multiple JSON files

Posted: 07 Sep 2021 08:28 AM PDT

So, I have 5 JSON files named as JSON1,JSON2,JSON3,JSON4 and JSON5. General format of these json files is

General format of JSON files

{    "flower": {      "price": {        "type": "good",        "value": 5282.0,        "direction": "up"       }      },    "furniture": {      "price": {        "type": "comfy",        "value": 9074.0,        "direction": "down"       }     }  }  

Among all these json files , I need to find that json file which has a particular value/data given by the user. for eg- if the user gives an input for the "value" = 9074 that it want to search in all the JSON files and gives an output as the JSON file which contains the value mentioned along with the line which has the mentioned data.

The approach I used was:

import json  with open('JSON1.json','r') as f1:      item1 = json.load(f1)  with open('JSON2.json','r') as f1:      item2 = json.load(f1)  with open('JSON3.json','r') as f1:      item3 = json.load(f1)  with open('JSON4.json','r') as f1:      item4 = json.load(f1)  with open('JSON5.json','r') as f1:      item5 = json.load(f1)  # Input the value that user want to search  item = input("Enter the value:\n")    # function to search the json file  def search_json(value):   int i = 0;    for keyvalue in item(i+1):      i++;      if value == keyval['value']        return keyvalue[name of the json file]    if(search_json(item) !=None):   print("this value is present in json log :",search_json(item))  

the output observed should be:

Enter the value: 9074

This value is present in json log JSON1 and is present at 12 line of code

But, the above approach isn't efficient and correct . As, I'm new to learning python therefore I'm confused with the correct approach. It'll be really grateful if someone could help.

My GCD Program not working correctly in c++

Posted: 07 Sep 2021 08:28 AM PDT

I'm making an app to calculate GCD(greatest common divider) for class and its working but the output is always being 0, I tries like a zillion things allready but couldn't find a solution.

PLEASE HELP!!🥺🥺

int n1, n2, GCD = 1, rem;  cin >> n1 >> n2;  if (n2 > n1)  {      n1 = n1 + n2;      n2 = n1 - n2;      n1 = n1 - n2;  }  rem = n1 % n2;  while (rem > 0)  {      if (n1 == n2)      {          GCD = rem;          break;      }      if (n2 > rem)      {          n1 = n2;          n2 = rem;      }      else      {          n1 = rem;      }      rem = n1 % n2;  }  cout << "\nGCD = "  << GCD << endl;  

any thoughts how to solve

GraphDB undirected graph path search

Posted: 07 Sep 2021 08:28 AM PDT

GraphDB 9.9 introduced the powerful feature for retrieving paths (shortests paths, cycles etc.)

However, from the documentation it is not clear whether this can also be used for nondirected graphs - i.e. ignoring the edge directions given by triples.

Is it possible to apply the path search functions without (e.g. in social networks where most relationships are mutual). Of course duplicating each edge with its inverse version can be a solution but not very elegant.

Overlay map with second layer of symbols

Posted: 07 Sep 2021 08:28 AM PDT

I have created a world map in R which highlights some countries according to a variable in a data set. I now want to add another layer of symbols to the world map. The dataset contains six additional dummy variables. For any of them being "1" I would want a symbol to be placed on the map. Is this possible? Could anyone point me to a solution/application/command to do this?

Here is a stylized version of my dataset. For all countries where Symbol 1-6 = 1 I would like to have an actual symbol, or annotation, on the map, in addition to the coloring that is already applied.

library(tidyverse)  library(sf)  library(rvest)  library(stringr)  library(scales)  library(viridis)    map.world <- map_data('world')    map.world<-map.world[!(map.world$region=="Antarctica"),]    a <- c("Belgium", "Canada", "USA", "UK")  symbol1 <- c(1, 0, 1, 0)  symbol2 <- c(0, 1, 1, 0)  symbol3 <- c(0, 0, 1, 1)  symbol4 <- c(1, 0, 0, 0)  symbol5 <- c(1, 1, 1, 1)  symbol6 <- c(0, 0, 1, 0)    mapping <- data.frame(a, symbol1, symbol2, symbol3, symbol4, symbol5, symbol6)  mapping$country <- "YES"    plot_data <- left_join(map.world, mapping, by = c('region' = 'a'))    plot_data$country[is.na(plot_data$country)] <- "NO"    p <-  ggplot(plot_data, aes( x = long, y = lat, group = group)) +    geom_polygon(aes(fill = country))     p + theme(legend.position="bottom",             axis.line=element_blank(),axis.text.x=element_blank(),             axis.text.y=element_blank(),axis.ticks=element_blank(),             axis.title.x=element_blank(),             axis.title.y=element_blank(),             panel.background = element_blank(), panel.border=element_blank(),panel.grid.major=element_blank(),             panel.grid.minor=element_blank(),plot.background=element_blank()) +    scale_fill_manual(name="", values=c("#ADD8E6", "#00008B", "#E5E4E2"))  

"Expression.Error: We don't support query strings containing keys without values in this context " power query excel

Posted: 07 Sep 2021 08:28 AM PDT

I try to connect excel with Sharepoint. I am able to get the folders but inside some folders there are more than 10 folders but power query editor only shows first 3 or 2 folders. There is an error message for other folders which says "Expression.Error: We don't support query strings containing keys without values in this context" .

On some folders I am able to see the all number of folders but in some only top 3 shown. What might be the problem?

Thank you.

enter image description here

How can I retain the Date index after a groupby / rolling operation on a Multiindexed Dataframe?

Posted: 07 Sep 2021 08:28 AM PDT

Creating the following example DataFrame:

import pandas as pd  df = pd.DataFrame(data=[[1, 1, 10, 20], [1, 2, 30, 40], [1, 3, 50, 60],                          [2, 1, 11, 21], [2, 2, 31, 41], [2, 3, 51, 61]],                    columns=['id', 'date', 'd1', 'd2'])  df.set_index(['id', 'date'], inplace=True)  

The DataFrame looks like this:

>>> df           d1  d2  id date  1  1     10  20     2     30  40     3     50  60  2  1     11  21     2     31  41     3     51  61  

Now, I want to apply a function (sum in the example) on a moving window, on the column d1, and I care about keeping the id and the date as indexes in the end.

I would do this:

df = df.groupby(level='id').rolling(window=2)['d1'].sum()  

The output I obtain has the following format (in Pandas 1.1.5):

>>> df    id  1      NaN  1     40.0  1     80.0  2      NaN  2     42.0  2     82.0  Name: d1, dtype: float64  

I have seen other examples online, where the output is actually what I want:

>>> df    id      date  1          1      NaN  1          2     40.0  1          3     80.0  2          1      NaN  2          2     42.0  2          3     82.0  Name: d1, dtype: float64  

How do I obtain this output? What am I doing wrong?

How to make a Split screen image slider

Posted: 07 Sep 2021 08:28 AM PDT

I just wanna know have to make a image slider which splits in half when scrolled down below and revels the content. can anyone pls tell and note it's an image slider so it will have many elements so you can't duplicate it 2 times and use clip-path i guess...

How to convert HSL color into HSV color in python (no external library)?

Posted: 07 Sep 2021 08:29 AM PDT

How to convert hsl color into hsv color without any external library in python?

def HEX2HSV(hex):      hv=HEX2HSL(hex)  # this function return converted HSL value of Hex color code {'h': 300, 's': 67.0, 'l': 80.0}      # how to convert HSL in to HSV in python without external library?    convertedhsv = HEX2HSV('#eeaaee') # {'h':300,'s':67.0,'l':80.0}  

hue in HSL and HSV are same but saturation are different and light and value are also different so how can I convert saturation and light of HSL into saturation and value of HSV in python?

Functions of structures in C

Posted: 07 Sep 2021 08:29 AM PDT

I am learning linked lists in C , and I don't understand these 2 lines:

struct LinkedList{      int data;      struct LinkedList *next;   };    typedef struct LinkedList *node; //1    node createNode(){               //2      node temp;       temp = (node)malloc(sizeof(struct LinkedList));       temp->next = NULL;      return temp;  }  

In //1 What does it mean to assign a pointer as a name for the structure in typedef? and in //2 how can we have a function of the structure(node aka struct Linkedlist) ,as functions cannot be members of structures?

Why are Dart null-safety problems showing up inconsistently in 2 places

Posted: 07 Sep 2021 08:28 AM PDT

I have a flutter app. I'm using VSCode. When I do the following I get the following error reported in two places (the 'PROBLEMS' area and in the 'Debug Console':

faulty code:

bool fff = (preferences?.getBool("_wantSpaces"));  

error msg:

"message": "A value of type 'bool?' can't be assigned to a variable of type 'bool'.\nTry changing the type of the variable, or casting the right-hand type to 'bool'.",

If I modify the code like this both errors go away: good code:

bool fff = (preferences?.getBool("_wantSpaces")) ?? false;  

If I modify the code like this both errors go away: good code:

bool fff = (preferences?.getBool("_wantSpaces"))!;  

But, if I modify the code like this only the error in the 'Problems' goes away: half good code:

bool fff = (preferences?.getBool("_wantSpaces"))!;  

Questions: Why is the error reported in 2 places? I would prefer to use the 2nd form (with the !), but I can't

Thanks

How to fix HTML/CSS/JQuery sidebar - content should be hidden until selected

Posted: 07 Sep 2021 08:28 AM PDT

I have the following code which works just fine, with the exception of:

  • When I click the open in the sidebar, it should show only that material ("Click on 'Charts' should show Charts material). I should not be able to scroll down the page and see everything.
  • When an option from the sidebar is selected, it should be highlighted (class="active") so that you know which page you're on.

If there's a better way to do this, I'm open to suggestions.

HTML

<!DOCTYPE html>  <html lang="en">  <head>          <meta charset="UTF-8">          <title>Side Navigation Bar</title>          <link rel="stylesheet" href="styles.css">          <script src="https://kit.fontawesome.com/b99e675b6e.js"></script>          <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>          <script>                  $(document).ready(function(){                          $(".hamburger").click(function(){                            $(".wrapper").toggleClass("active")                          })                  });          </script>  </head>  <body>    <div class="wrapper">            <div class="top_navbar">                  <div class="logo"><a>Demonstration</a></div>                    <div class="top_menu">                          <div class="home_link"><a href="#"><span class="icon"><i class="fas fa-home"></i></span><span>Home</span></a>                          </div>                  </div>          </div>            <div class="main_body">                    <div class="sidebar_menu">                  <div class="inner__sidebar_menu">                            <ul>                                  <li><a href="#top" class="active"><span class="icon"><i class="fas fa-border-all"></i></span>      <span class="list">Dashboard</span></a></li>                                  <li><a href="#chart">   <span class="icon"><i class="fas fa-chart-pie"></i></span>       <span class="list">Charts</span></a></li>                                  <li><a href="#">        <span class="icon"><i class="fas fa-address-book"></i></span>    <span class="list">Contact</span></a></li>                                  <li><a href="#">        <span class="icon"><i class="fas fa-address-card"></i></span>    <span class="list">About</span></a></li>                                  <li><a href="#">        <span class="icon"><i class="fab fa-blogger"></i></span>         <span class="list">Blogs</span></a></li>                                  <li><a href="#">        <span class="icon"><i class="fas fa-map-marked-alt"></i></span>  <span class="list">Maps</span></a></li>                          </ul>                            <div class="hamburger">                                  <div class="inner_hamburger">                                          <span class="arrow">                                                  <i class="fas fa-long-arrow-alt-left"></i>                                                  <i class="fas fa-long-arrow-alt-right"></i>                                          </span>                                  </div>                          /div>                    </div>                  </div>            <a name="dash" id="dash">              <div class="container">                          <div><h1>Dashboard</h1></div>                      <div class="item_wrap">                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>                      <div class="item_wrap">                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>                      <div class="item_wrap">                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>                      <div class="item_wrap">                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>              </div>          </a>            <a name="chart" id="chart">              <div class="container">                          <div><h1>Charts</h1></div>                      <div class="item_wrap">                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>                      <div class="item_wrap">                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>                      <div class="item_wrap">                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>                      <div class="item_wrap">                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                              <div class="item">Chartum ipsum dolor sit amet, consectetur adipisicing elit. Laborum omnis nihil aut aperiam adipisci suscipit ullam sunt saepe cupiditate quam distinctio officiis tempore laudantium, animi amet corrupti ratione est commodi! Sunt tempora quod magnam optio, reiciendis veritatis, necessitatibus eos molestias facilis reprehenderit maiores ipsum quaerat placeat laborum, a aspernatur corporis.</div>                      </div>              </div>          </a>            </div>  </div>    </body>  </html>  

CSS

@import url('https://fonts.googleapis.com/css?family=Montserrat+Subrayada|Ubuntu:400,500,700&display=swap');    * {          margin: 0;          padding: 0;          list-style: none;          font-family: 'Ubuntu', sans-serif;          box-sizing: border-box;          text-decoration: none;  }    body {          background: #e8edf5;          width: 100%;          height: 100%;  }    .wrapper .top_navbar {          width: 100%;          height: 65px;          display: flex;          position: fixed;          top: 0;  }    .wrapper .top_navbar .logo {          width: 250px;          height: 100%;          background: #3421C0;          border-bottom: 1px solid #22119d;  }    .wrapper .top_navbar .logo a {          display: block;          text-align: center;          font-family: 'Montserrat Subrayada', sans-serif;          font-size: 20px;          color: #fff;          padding: 20px 0;  }    .wrapper .top_navbar .top_menu {          width: calc(100% - 250px);          height: 100%;          background: #fff;          padding: 0 40px;          display: flex;          justify-content: space-between;          align-items: center;  }    .wrapper .top_navbar .top_menu .home_link a {          display: block;          background: #3421C0;          color: #fff;          padding: 8px 15px;          border-radius: 3px;  }    .wrapper .top_navbar .top_menu .home_link a:hover,  .wrapper .top_navbar .right_info .icon_wrap:hover  {          background: #5343c7;  }    .wrapper .top_navbar .right_info {          display: flex;  }    .wrapper .top_navbar .right_info .icon_wrap {          padding: 8px 15px;          border-radius: 3px;          background: #3421C0;          color: #fff;          margin: 0 5px;          cursor: pointer;  }    .main_body .sidebar_menu {          position: fixed;          top: 65px;          left: 0;          background: #3421C0;          width: 250px;          height: 100%;          transition: all 0.3s linear;  }    .main_body .sidebar_menu .inner__sidebar_menu {          position: relative;          padding-top: 60px;  }    .main_body .sidebar_menu ul li a {          color: #7467d3;          font-size: 18px;          padding: 20px 35px;          display: block;          white-space: nowrap;  }    .main_body .sidebar_menu ul li a .icon {          margin-right: 8px;  }    .main_body .sidebar_menu ul li a span {          display: inline-block;  }    .main_body .sidebar_menu ul li a:hover {          background: #5343c7;          color: #fff;  }    .main_body .sidebar_menu ul li a.active {          background: #22119d;          color: #fff;  }    .main_body .sidebar_menu .hamburger {          position: absolute;          top: 5px;          right: -25px;          width: 50px;          height: 50px;          background: #e8edf5;          border-radius: 50%;          cursor: pointer;  }    .main_body .sidebar_menu .inner_hamburger,  .main_body .sidebar_menu .hamburger .arrow {          position: absolute;          top: 50%;          left: 50%;          transform: translate(-50%,-50%);  }    .main_body .sidebar_menu .inner_hamburger {          width: 40px;          border-radius: 50%;          height: 40px;          background: #3421C0;  }    .main_body .sidebar_menu .hamburger .arrow {          color: #fff;          font-size: 20px;  }    .main_body .sidebar_menu .hamburger  .fa-long-arrow-alt-right {          display: none;  }    .main_body .container {          width: calc(100% - 250px);          margin-top: 65px;          margin-left: 250px;          padding: 25px 40px;          transition: all 0.3s linear;  }    .main_body .container .item_wrap {          display: flex;          margin-bottom: 20px;  }    .main_body .container .item_wrap .item {          background: #fff;          border: 1px solid #e0e0e0;          padding: 25px;          font-size: 14px;          line-height: 22px;  }    .main_body .container .item_wrap .item:first-child {          margin-right: 20px;  }            /* after adding active class */  .wrapper.active .sidebar_menu {          width: 100px;  }    .wrapper.active .hamburger .fa-long-arrow-alt-right {          display: block;  }    .wrapper.active .hamburger .fa-long-arrow-alt-left {          display: none;  }    .wrapper.active .sidebar_menu ul li a .list {          display: none;  }    .wrapper.active .main_body .container {          width: calc(100% - 100px);          margin-left: 100px;  }  

Async pipe and subscribe on the same Observable

Posted: 07 Sep 2021 08:29 AM PDT

I'm using async pipe in my template to get a list of users that match a certain condition (getNonRedirectingList). Users are stored in a Firestore instance.

In my component template I have the following (simplified) code:

    <div *ngIf="users$ | async as users" class="uwrapper">          <div *ngFor="let u of users">{{u.name}}</div>      </div>  

and this works like a charm: it produces 3 <div> blocks, that match the 3 users I'm expecting.

However in the Typescript code I also need to subscribe to the same Observable that @angular/fire returns

ngOnInit(): void {    this.users$ = this.userSvc.getNonRedirectingList().pipe(share());    firstValueFrom(this.users$).then(users => {      for (let i = 0; i < users.length; i++) {        console.log(i);      }    });  }  

I'd expect

0  1  2  

as output in the console, but I get nothing instead. Even setting a breakpoint at the console.log(i) line, it never gets hit.

I've already tried with and without .pipe(share()), I've also tried calling getNonRedirectingList twice in the hope of getting two different Observable and I've also tried using subscribe() and unsubscribe() instead of firstValueFrom(), but the result was just the same: the async pipe worked, my code did not.

EDIT after S Overflow's answer:

Tried this too, with same results

this.users$.pipe(tap(users => {    for (let i = 0; i < users.length; i++) {      console.log(i);    }  }));  

Any clues?

How to save firebase cloud messaging tokens?

Posted: 07 Sep 2021 08:29 AM PDT

Im trying to use firebase cloud messaging to enable push notifications on my PWA. but i can't figure out how to save tokens after the 'user' click on 'accept' on the push notification subscription message. Should i save token to a firebase database? or there is a automatic system to subscribe/unsubscribe/ clean the list of tokens.

How to raise an exception if caller forgot to use with-block on context manager method

Posted: 07 Sep 2021 08:28 AM PDT

I have a function decorated with @contextmanager, that users of my code should call using a with-block. Sometimes they forget that and call it bare.

@contextmanager  def foo():      print("before")      yield      print("after")    # correct usage  with foo():      pass # or do some actual work    # incorrect usage, just returns a contextlib._GeneratorContextManager object  foo()  

I would like to raise an exception, or at least ensure my __exit__ function gets called if someone makes this mistake.

Plotly dash population bar chart not working properly

Posted: 07 Sep 2021 08:28 AM PDT

I wanted to do a simple population bar chart, but I can't understand it. My dataset is:

Age,Women,Men  "18-24",1.8%,2%  "25-34",20.9%,13.7%  "35-44",19.3%,14.6%  "45-54",9.3%,8%  "55-64",3.6%,2.9%  "65+",2.3%,1.6%  

And the code is:

example_graph11  =  px.bar(facebook2, x='Age', y=['Men', 'Women'], barmode='stack',              title = 'Percentage of Facebook fans by age and gender')  

But the result is weird, and I don't understand what input data should I put. I tried with a pyramid chart as well and it didn't work.

Image of the result

How to optimize Impala query to combine LIKE with IN (literally or effectively)?

Posted: 07 Sep 2021 08:29 AM PDT

I need to try and optimize a query in Impala SQL that does partial string matches on about 60 different strings, against two columns in a database of 50+ billion rows. The values in these two columns are encrypted and have to be decrypted with a user defined function (in Java) to do the partial string match. So query would look something like:

SELECT decrypt_function(column_A), decrypt_function(column_B) FROM myTable WHERE ((decrypt_function(column_A) LIKE '%' + partial_string_1 + '%') OR (decrypt_function(column_B) LIKE '%' + partial_string_1 + '%')) OR ((decrypt_function(column_A) LIKE '%' + partial_string_2 + '%') OR (decrypt_function(column_B) LIKE '%' + partial_string_2 + '%')) OR ... [up to partial_string_60]  

What I really want to do is decrypt the two column values I'm comparing with, once for each row and then compare that value with all the partial strings, then go onto the next row etc (for 55 billion rows). Is that possible somehow? Can there be a subquery that assigns the decrypted column value to a variable before using that to do the string comparison to each of the 60 strings? Then go onto the next row...

Or is some other optimization possible? E.g. using 'IN', so ... WHERE (decrypt_function(column_A) IN ('%' + partial_string_1 + '%', '%' + partial_string_2 + '%', ... , '%' + partial_string_60 + '%')) OR (decrypt_function(column_B) IN ('%' + partial_string_1 + '%', '%' + partial_string_2 + '%', ... , '%' + partial_string_60 + '%'))

Thanks

How to query an array and retrieve it from MongoDB

Posted: 07 Sep 2021 08:28 AM PDT

I have a document on the database that looks like this:enter image description here

My question is the following:

How can I retrieve the first 10 elements from the friendsArray from database and sort it descending or ascending based on the lastTimestamp value.

I don't want to download all values to my API and then sort them in Python because that is wasting my resources.

I have tried it using this code (Python):

listOfUsers = db.user_relations.find_one({'userId': '123'}, {'friendsArray' : {'$orderBy': {'lastTimestamp': 1}}}).limit(10)  

but it just gives me this error pymongo.errors.OperationFailure: Unknown expression $orderBy

Any answer at this point would be really helpful! Thank You!

Replicating Excel if then statement in python [closed]

Posted: 07 Sep 2021 08:28 AM PDT

I am trying to write a conditional statement using python and jupyter notebook. The statement would be similar to an Excel 'if' 'then' statement that returns cases that are True. For example, I have a file with 3 columns (Date, Region, Volume). I want to write a code for instances when region is Florida, so that I can plot volume and date for Florida only.

SQL Update involving two tables with multiple column conditioning

Posted: 07 Sep 2021 08:29 AM PDT

I have two tables:

enter image description here

and

enter image description here

I would like to update Table Second according to the contents of columns A,B and C in Table First. The colours in the diagram are to clarify how the update should occur.

I have obviously simplified the real problem, but I tried this:

Update Second  set Group = (select distinct Group               from First                where First.A =Second.A                 and First.B = Second.B                 and First.C = Second.C)   

but I was getting an error

Cannot insert the value NULL into column 'Group'

when in fact both tables don't have NULL values. I presume because there are several rows on both tables it is maybe more complicated than I think?

Use R shiny to add a sheet to a pre-existing excel file with action button

Posted: 07 Sep 2021 08:28 AM PDT

I have an excel file called testfile.xlsx. the first sheet of this file is called sheet1. I have written appended a new sheet called New_Sheet using xlsx package as follows

library(xlsx)  setwd()##set the file path to where testfile.xlsx is located  write.xlsx('new_data', "testfile.xlsx", sheetName="New_Sheet", append=TRUE)  

This adds the required sheet.

I have created the following shiny app to write the sheet to the file

library(shiny)  library(xlsx)  library(openxlsx)  library(readxl)    ui <- fluidPage(     titlePanel("Writer App"),  sidebarLayout(sidebarPanel(fileInput(inputId = "file", label = "Read File Here", accept =   c(".xlsx")),actionButton(inputId = "Run", label = "Write Data to Table")),  mainPanel(dataTableOutput(outputId = "table1"))))    server <- function(input, output) {  datasetInput <- reactive({  infile<- input$file  if (is.null(infile))    return(NULL)      #READ .XLSX AND .CSV FILES  if(grepl(infile, pattern = ".xlsx" )==T){    data=read_excel(infile$datapath)  } else if(grepl(infile , pattern = ".csv" )==T)  {data=read.csv(infile$datapath )}    #RENAME DATAFRAME WITH UNDERSCORES  names(data)<-gsub(pattern = " ", replacement = "_", x =  names(data))  return(data) })  output$table1 <- renderDataTable({      datasetInput()})    observeEvent(input$Run,{      infile<-input$file  testfile<-(infile[1])  filepath<-(input$file)  filepath<-gsub(pattern = "0.xlsx", replacement ="" , x = filepath)      # print(infile$datapath[1])  print(filepath)  print(testfile)      setwd(dir = filepath)  write.xlsx('new_data', testfile, sheetName="New_Sheet3", append=TRUE)})  }    shinyApp(ui = ui, server = server)  

The app renders the data in the excel sheet as a table without any problems .When we push the run app button, the print commands generate the name of the file and the filepath. The write excel function doesnt work. Is there a way to insert the new_data sheet using the action button. I request someone to guide me here.

How to multiply 5% in assembly language and display it out in 2 decimal place

Posted: 07 Sep 2021 08:28 AM PDT

I initialize the price of the food and request user to input a quantity and I am able to get an accurate result after multiplication. But can I ask how to use the total amount to multiply with 5% so that when user apply promo code they can get a 5% discount? and how to display out the final result to 2 decimal places? I am new to this language and could not solve this, any of your help is much appreciated!

        MOV BL, 10                                      ;move 10 to BL register            MOV AH, 09H          LEA DX, QUANTITY                                ;prompt user to input quantity          INT 21H            MOV AH, 01H                                     ;User input quantity          INT 21H          SUB AL, 48                                      ;Minus ASCII 48 --> 0 from AL to get quantity             MUL BL                                          ;AL*BL --> multiply quantity with price          AAM                                             ;ascii adjust after multiplication  to show result in 2 digit             MOV CX, AX                                      ;result stored in AX, move it to CX          ADD CH, 48                                      ;ADD ASCII 48 --> 0 to CH (1st digit) to display later          ADD CL, 48                                      ;ADD ASCII 48 --> 0 to CL (2nd digit) to display later            MOV AH, 09H          LEA DX, TOTAL_PRICE                             ;display total price:           INT 21H            MOV AH, 02H          MOV DL, CH                                      ;display higher byte(1st digit) of total price value             INT 21H            MOV AH, 02H          MOV DL, CL                                      ;display lower byte(2nd digit) of total price value          INT 21H  

Type interface com.example.JSF.mappings.StudentMapper is not known to the MapperRegistry

Posted: 07 Sep 2021 08:29 AM PDT

I am trying to get data from database using mybatis 3.2 and when I run the project this error appearing : Type interface com.example.JSF.mappings.StudentMapper is not known to the MapperRegistry.

StudentMapper

package com.example.JSF.mappings;    import com.example.JSF.bean.Student;    import java.util.List;      public interface StudentMapper {        List<Student> findAllStudents();      Student findStudentById(Integer id);      void insertStudent(Student student);      }  

MyBatis file config

<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE configuration      PUBLIC "-//mybatis.org//DTD Config 3.0//EN"      "http://mybatis.org/dtd/mybatis-3-config.dtd">  <configuration>  <typeAliases>      <typeAlias alias="Student"                 type="com.example.JSF.bean.Student"/>  </typeAliases>  <environments default="development">      <environment id="development">          <transactionManager type="JDBC"/>          <dataSource type="POOLED">              <property name="driver" value="com.mysql.jdbc.Driver"/>              <property name="url"                        value="jdbc:mysql://localhost:3306/jsf"/>              <property name="username" value="root"/>              <property name="password" value=""/>          </dataSource>      </environment>  </environments>  <mappers>      <mapper resource="StudentMapper.xml"/>  </mappers>  </configuration>  

StudentMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>  <!DOCTYPE mapper      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  <mapper namespace="com.example.JSF.bean.Student">      <resultMap type="Student" id="StudentResult">        <id property="studId" column="stud_id"/>        <result property="name" column="name"/>        <result property="email" column="email"/>         <result property="dob" column="dob"/>      </resultMap>  <select id="findAllStudents" resultMap="StudentResult">      SELECT * FROM STUDENTS  </select>  <select id="findStudentById" parameterType="int"          resultType="Student">      SELECT STUD_ID AS STUDID, NAME, EMAIL, DOB      FROM STUDENTS WHERE STUD_ID=#{Id}  </select>    <insert id="insertStudent" parameterType="Student">        INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)        VALUES(#{studId },#{name},#{email},#{dob})    </insert>  </mapper>  

MyBatisSqlSessionFactory

package com.example.JSF.bean;  import java.io.*;  import org.apache.ibatis.io.Resources;  import org.apache.ibatis.session.*;  public class MyBatisSqlSessionFactory  {     private static SqlSessionFactory sqlSessionFactory;     public static SqlSessionFactory getSqlSessionFactory() {      if(sqlSessionFactory==null) {          InputStream inputStream;          try {              inputStream = Resources.                      getResourceAsStream("mybatis-config.xml");              sqlSessionFactory = new                      SqlSessionFactoryBuilder().build(inputStream);          } catch (IOException e) {              throw new RuntimeException(e.getCause());          }      }      return sqlSessionFactory;  }    public static SqlSession openSession() {        return getSqlSessionFactory().openSession();    }  }   

StudentService

package com.example.JSF.service;  import java.util.List;    import com.example.JSF.bean.MyBatisSqlSessionFactory;  import com.example.JSF.bean.Student;  import com.example.JSF.mappings.StudentMapper;  import org.apache.ibatis.session.SqlSession;  import org.slf4j.Logger;  import org.slf4j.LoggerFactory;  public class StudentService {      private final Logger logger =          LoggerFactory.getLogger(getClass());    public List<Student> findAllStudents() {      SqlSession sqlSession =              MyBatisSqlSessionFactory.openSession();      try {          StudentMapper studentMapper =                  sqlSession.getMapper(StudentMapper.class);          return studentMapper.findAllStudents();      } finally {          sqlSession.close();      }  }    public Student findStudentById(Integer studId) {      logger.debug("Select Student By ID :{}", studId);      SqlSession sqlSession =              MyBatisSqlSessionFactory.openSession();      try {          StudentMapper studentMapper =                  sqlSession.getMapper(StudentMapper.class);          return studentMapper.findStudentById(studId);      } finally {          sqlSession.close();      }  }      public void createStudent(Student student) {      SqlSession sqlSession =              MyBatisSqlSessionFactory.openSession();      try {          StudentMapper studentMapper =                  sqlSession.getMapper(StudentMapper.class);          studentMapper.insertStudent(student);          sqlSession.commit();      } finally {          sqlSession.close();        }  }    }  

Define Multiple Enums in a Single File in Matlab

Posted: 07 Sep 2021 08:28 AM PDT

Is it possible to define multiple enumerations in a single Matlab file? Or is it possible to have "local" enums in the same way we can define local funtions at the end of a file?

I am working on a project where it would be handy to have multiple enumeration classes, but it is annoying to use a classdeff every time because it requires a separate file, and this means that there are lots of short files whose sole purpose it is to define enumerations. At the moment, each enumeration looks like this:

classdef exampleEnumType < uint32            enumeration          zero(0),          one(1),          two(2),      end    end  

Is there a way to compactly define enumerations in Matlab so that I do not need a separate file for each (using Matlab 2021a)?

Why does a dependency default to the latest even when I specify a version in the Pipfile?

Posted: 07 Sep 2021 08:29 AM PDT

I am trying to pin and install a dependency with Pipenv. I specify a version in the Pipfile, but when checking what version has been installed it shows the latest pre-release. I am specifying a version that is not the latest or a pre-release, but it will default to it. Any idea on how to solve this? I have tried purging the virtual environment and installing the cli via cli, and nothing has worked.

enter image description here

enter image description here

Xamarin Forms - physical keyboard dims page when no input control is present

Posted: 07 Sep 2021 08:28 AM PDT

My actual application is using a bluetooth scanner in HID mode and capturing the input on the DispatchKeyEvent of the MainActivity. It works great except that the screens dims to some dark opaque color where it looks like everything is disabled and you have to navigate back to a page with an input control and tap on it to get the screen to go back to normal.

It's not as noticeable in the stock template but in my actual application (Screen shots at bottom) the dimming is very noticeable; it's a blue-gray opaque overlay that really stands out. I have no idea why it's like that. I'd almost just be happy if my actual app dimmed like the default forms sample.

Steps:

  1. Make a Xamarin Forms app from one of the templates.
  2. Change nothing.
  3. Run simulator.
  4. Press a button on your keyboard.

Result: The screen dims and the soft keyboard does not popup.

Next Steps:

  1. Add an Entry control. < Entry/> will do.
  2. Click on it and the screen brightens back up.
  3. Delete < Entry/>
  4. Press a key on your keyboard and the soft keyboard pops up and the screen doesn't dim again.

What I want:

  1. To know where the dim/overlay color/opacity is set so I can change it.
  2. To not allow the soft keyboard to try and popup at all unless there's an entry field that has focus.

Here's screenshots from the default forms app:

Not Dim:

Not Dim

Dimmed after pressing the keyboard:

Dim

My actual test device is a Samsung Galaxy XCover Pro running Android 10.0. I'm working on porting a native Xamarin Android app to Forms so we can run it on iOS as well. I never had this issue with my android app and I'm not sure how to track down what's happening.

Here's a before pic. I've got an Entry field focused.

before scan

After scanning a barcode with my bluetooth scanner this happens:

dim after scanning

I can reproduce this with a scanner on the "Welcome to Xamaring Forms!" as well, the screenshots don't really show the change in overlay color; its much more subtle; I really would like to know why in my app the overlay is so much more obvious.

How to capture answers from Facebook Group Membership Questions?

Posted: 07 Sep 2021 08:29 AM PDT

I'm trying to figure out how to capture answers from a Facebook Group's Membership Questions? What I mean is when a new member joins a FB group, the group admins can set up to 3 questions to ask the incoming member. I want to capture that data when the member submits the form.

I've been combing through the FB Graph API but can't seem to find anything about it. Can anyone please point me in the right direction?

Thanks!

Installing R 4.0.2 version

Posted: 07 Sep 2021 08:28 AM PDT

I used to work in R 3.4.0 version. Hovewer, this version doesn't support such packages as keras and tensorflow.

I was adviced to upgrade my R version to the newest one. I downloaded the most recent R version 4.0.2 from the official site, then ran the following code:

install.packages("keras")  library(keras)  install_keras()  

And got the following error:

Error in install_keras() :  You should call install_keras() only in a fresh R session that has not yet initialized Keras and TensorFlow (this is to avoid DLL in use errors during installation)  

After this, when I tried to quit R session by q() , I faced the following error:

Error: option error has NULL value  Error: no more error handlers available (recursive errors?); invoking 'abort' restart  Error: option error has NULL value  

I've never faced such an error before. When I used old R version, I typed q() and then had to choose between y and n. No errors appeared.

I'm asking you to help to to solve this problem.

fatal: Not a valid object name: 'master'

Posted: 07 Sep 2021 08:28 AM PDT

I have a private server running git 1.7 When I

git init   

a folder it doesn't create a master branch. Cause when i do:

git branch   

it doesn't list anything. When I do:

git --bare init  

it creates the files. When I type

git branch master   

it says:

fatal: Not a valid object name: 'master'.  

Excel VBA - Stop running program that was started by Shell?

Posted: 07 Sep 2021 08:28 AM PDT

Excel 2002 VBA.

I have a macro that launches an external script whenever a certain condition is met:

Shell("c:\program\script.exe")  

How do I stop that running program when the condition is not met?

No comments:

Post a Comment