Wednesday, April 14, 2021

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Flood Element - get an ElementHandle inside an iframe

Posted: 14 Apr 2021 07:53 AM PDT

My document looks something like this:

<html>      <body>          Hello            <iframe ...>              <input name='cardNumber'>          </iframe>      </body  </html>  

I would like to be able to set the input value programmatically. Doing a simple browser.findElement(By.css("input")) doesn't work, because the browser blocks it because of the same-origin policy (see the question here for details SecurityError: Blocked a frame with origin from accessing a cross-origin frame)

Therefore I am trying some magic, but I can't make it to work:

const ccIframe = browser      .page      .frames()      .find(async frame => {          return await frame.title() === "Secure card number input frame"      }) as Frame;  

But now ccIframe is of type Frame which does not have findElement or sendKeys methods. I tried using ccIframe.press instead, but it does not set the value on my form input:

await ccIframe.press("input[name='cardnumber']", "4")  

Any ideas how to achieve this?

Generalizing a code to work on any size Image

Posted: 14 Apr 2021 07:53 AM PDT

I have created a function that will tell how much is present in an image, but it only works on square images. How do I generalize this code to tell how much red is present on any size image?

Def redness(square):      All_red = 0      Others = 0      For x in range(100):         For y in range(100):           Red, green, blue, alpha = square.getpixel((x, y))           All_red = all_red + red           Others = others + green + blue     Return all_red - (others / 2)  

ImportDocumentationPartsCommandInput - Missing 'body' param?

Posted: 14 Apr 2021 07:54 AM PDT

I'm getting this error when sending the ImportDocumentationPartsCommand command "errorMessage": "1 validation error detected: Value null at 'body' failed to satisfy constraint: Member must not be null"

The ImportDocumentationPartsCommandInput interface doesn't have a body param so I opted to using 'any' to test it but I still get the validation error.

const input: any = {      body: JSON.stringify(swaggerSpec),      restApiId: "jisaf123",      mode: "merge",    };  

Create variables from a dict: variable names from dict.keys(), and variable values from dict.values()

Posted: 14 Apr 2021 07:53 AM PDT

I have a dict made of three lists where the key is the list name, and the value the list itself

variables = {'conso_emi':['ENERGYSTARScore', 'SiteEUI(kBtu/sf)', 'SiteEUIWN(kBtu/sf)'],              'surf': ['PropertyGFAParking', 'LargestPropertyUseTypeGFA'],              'num_caract':['NumberofBuildings', 'NumberofFloors', 'Age']}  

Is there a way to create three variables from this dict, where the variable name would be the dict key, and the content of the variable the dict value ? In other words, an automated way of doing it manually like below

conso_emi = ['ENERGYSTARScore', 'SiteEUI(kBtu/sf)', 'SiteEUIWN(kBtu/sf)']  surf = ['PropertyGFAParking', 'LargestPropertyUseTypeGFA']  num_caract = ['NumberofBuildings', 'NumberofFloors', 'Age']  

I have tried unsuccesfully:

INPUT:

for key,vals in zip(variables.keys(), variables.values()):          key = vals    conso_emi  

OUTPUT

NameError: name 'conso_emi' is not defined  

Form or get Azure DevOps URL for Release logs

Posted: 14 Apr 2021 07:52 AM PDT

enter image description hereUsing a PowerShell task running as part of this Agent Job, I want to get the URL to link back to the logs (of the same Agent Job). The URL is consistent but I can't find Predefined variables for releaseID or environmentID which are the missing pieces of the puzzle for the URL. Does anyone know how to get these IDs or another way of programatically retrieving this URL from a task within the Agent Job?

ngAnimate not working outside of current page

Posted: 14 Apr 2021 07:52 AM PDT

I have some problem with ngAnimate in angularjs. If I am on the current page, it works fine, but if I reload the page and then leave to another page my animation not working. I use css animate with js animate together.

Simple code

<style>      .test-animate.ng-enter,      .test-animate.ng-leave       {          transition: all ease-in-out .5s;      }  </style>  
<div style="position: relative;height: 70vh">      <md-card ng-repeat="model in Models track by $index" ng-style="{'width':{true: '100%'}[$index == 0]}" ng-class="{true: 'test-animate'}[$index > 0]" style="position: absolute;top: 0;width: 0;height: 100%;">          ...      </md-card>  </div>  
angular.module('app', ['ngAnimate']).animation('.test-animate', ['$animateCss', ($animateCss) =>  {      return {          enter: (el) =>          {              const index = parseInt($(el).data('index'));              console.log('enter')              return $animateCss(el, {                  event: 'enter',                  structural: true,                  to: {                      'right': 0,                      'width': `calc(100% - ${index * 80}px`,                      'max-width': `calc(100% - ${index * 80}px`                  }              });          },          leave: (el) =>          {              console.log('leave')              return $animateCss(el, {                  event: 'leave',                  structural: true,                  from: {                      'max-width': $(el).css('max-width')                  },                  to: {                      'max-width': 0                  }              });          }      }  }])  

Is it possible to persist model validation errors and send it to another method in asp.net MVC?

Posted: 14 Apr 2021 07:52 AM PDT

my requirement is to pass group of models through single view model to controller. I did this using html.beginform and passed this group to single method in controller. I want to save these model data in DB. So I called different methods from that single method and saved data. Problem is I am only returning view in main method. That's why validations that I have done for each model are not getting displayed when model is not valid. I validated models in controller using TryValidateObject but errors are not getting displayed in view because I cannot return view from multiple methods. Code:

       public ActionResult mthdSaveAllData(MdlViewmodel mdlviewmodel){         mdlviewmodel.mdlviewmodel1status= mthdSaveModel1Data(mdlviewmodel);         mdlviewmodel.mdlviewmodel2status= mthdSaveModel2Data(mdlviewmodel);         mdlviewmodel.mdlviewmodel3status= mthdSaveModel2Data(mdlviewmodel);         return View(mdlviewmodel);         }  

All three methods return string as status if it's added or not as I can't return view from these 3. In each method, I am validating model object like this.

       public string mthdSaveModel1Data(){         ModelState.Clear();          if (TryValidateModel(mdl_CreateFlashSmile.mdl_IdentificationData)){                somecodehere            }           return status; }  

I have used html.validationfor in view.But it's not getting displayed because I am not returning view from that particular method. I want to know if there is any way to persist validation errors and send it to main method? Please suggest. (I tried to validate form using jquery but it didn't help.I have multiple submit buttons in view)

Correct URL encoding of # Java WebClient

Posted: 14 Apr 2021 07:52 AM PDT

I'm tring to use this code to retrieve data from my API:

        Mono<String> client = WebClient.builder()            .baseUrl("https://localhost:8081/getPost/" + id) // or URLEncoder.encode(id, "UTF-8")            .defaultHeaders(new Consumer<HttpHeaders>() {                @Override                public void accept(HttpHeaders httpHeaders) {                  httpHeaders.addAll(createHeaders());                }              })            .build()            .get()            .retrieve()            .bodyToMono(String.class);  

My Ids starts with '#' so if I use this code it will result in:

https://localhost:8081/getPost/#id1  

The problem is that I need it url encoded so it should be getPost/%23id1, I tried to use URLEncoder on id but the result is double encoded:

 https://localhost:8081/getPost/%25%23id1  

I need to get rid of that %25

Retrieve message from server after an async Axios POST

Posted: 14 Apr 2021 07:53 AM PDT

How do I retrieve message from server after calling:

await axios.post(url, data)  
export const postData = async data => {    try {      let url = `${api}auth/register`;      let res = await axios.post(url, data).catch(e => console.log(e));      return res;    } catch (error) {      console.log(error);      Alert.alert("Error");    }  };  

this is response from server

Now this function is returning undefined in console. My motive is to get the message and code from server response

SQL query slow performance 'LIKE CNTR%04052021%

Posted: 14 Apr 2021 07:52 AM PDT

we have a database that is growing every day. roughly 40M records as of today.

This table/database is located in Azure.

The table has a primary key 'ClassifierID', and the query is running on this primary key.

The primary key is in the format of ID + timestamp (mmddyyy HHMMSS), for example 'CNTR00220200 04052021 073000'

Here is the query to get all the IDs by date

 **Select distinct ScanID   From ClassifierResults   Where ClassifierID LIKE 'CNTR%04052020%**  

Very simple and straightforward, but it sometimes takes over a min to complete. Do you have any suggestion how we can optimize the query? Thanks much.

While loops in Java

Posted: 14 Apr 2021 07:52 AM PDT

I need to code a while or do loop to determine if the number the user entered is within a specific range (30 < value < 70). Then if the user enters something out of the range specify a higher or lower number to be in range.

How to transform a text element so it scales larger left to right?

Posted: 14 Apr 2021 07:53 AM PDT

I'm trying to achieve this look (not the red container, just the text): skewed text

I've tried using tranform: scale and transform: skew to no avail, as they pull the entire axis at once and don't allow the input of two arguments for left and right. The only thing left I can think to do is use 3d transform with perspective, but I could not get that to work either.

Terrible example of things I've tried: https://codepen.io/fortypercenttitanium/pen/YzNLEoR

<div class="container">    <h1 class="text-cone">Player 1:</h1>  </div>  
.container {    background: red;    display: flex;    width: 400px;    height: 200px;  }    .text-cone {    font-size: 5rem;  /*   transform: scale(1, 0.6); */  /*   transform: skew(0deg, 15deg); */  /*   transform: rotateY(45deg); */  }  

Extra Output None

Posted: 14 Apr 2021 07:53 AM PDT

I'm creating a program that asks the user to guess a random number, here's the code:

import random    # Declaração de Variáveis  num = random.randint(0, 10)  presora = int(input(print("Por favor adivinhe um número de 0 a 10: ")))    # Corpo  while presora != num:      presora = int(input(print("Desculpe você errou, tente de novo: ")))      vida = -1      print(vida)  else:      print("Parabéns, você acertou!")      quit()  

but whenever I run it appears none at the end:

Por favor adivinhe um número de 0 a 10:

None

Can someone help me?`

Dart: How to use Youtube Data API to upload videos?

Posted: 14 Apr 2021 07:53 AM PDT

I am trying to upload videos on Youtube using googleapis, I tried this:

      import 'package:googleapis/youtube/v3.dart';      import 'package:googleapis_auth/auth_io.dart';            final _credentials = ServiceAccountCredentials.fromJson(r'''      {        "private_key_id": ...,        "private_key": ...,        "client_email": ...,        "client_id": ...,        "type": "service_account"      }      ''');            const _scopes = [YouTubeApi.youtubeUploadScope];            Future<void> main() async {        final httpClient = await clientViaServiceAccount(_credentials, _scopes);        try {          final youtube = YouTubeApi(httpClient);                    youtube.videos.insert(request, part);  //What do to here??              } finally {          httpClient.close();        }      }    

Now I don't know how to proceed next? I didn't find any documentation regarding this.

span icon does not stay in the same place when I collapse the page

Posted: 14 Apr 2021 07:52 AM PDT

I made a datatable and one of my columns contains icons with a number above it in a span badge. When my table is open to full capacity, the badge is placed in the right place (here is the photo), Table 100%

but when I reduce a lot the badge changes places like in this photo. Reduced table

This is the code:

{                          data: null,                          className: "dt-center",                          title: "Actions <i style=\"color:red\" class=\"feather icon-info\" data-toggle=\"popover\"  data-trigger=\"hover\"></i>",                          render: function (data, type, row, meta) {                              var childRowIcon = '';                              if (row?.nbGroupeActif > 0) {                                  childRowIcon = ' | <a class="secondChild-details-control"><i data-prognom="' + row.PROG_NOM + '" data-progid="' + row.FK_programme + '" data-centreid="' + rowData.ecoleCode + '" data-instid="' + row.FK_etablissement + '" style="color:#009c9f;" class="ficon fa fa-arrow-circle-down secondChild-details-control dt-center"></i><span class="badge badge-pill badge-warning badge-up secondChild-details-control" title="Vous avez ' + row?.nbGroupeActif + ' groupes reliés à ce programme" style="right:5px;font-size: 0.60em;">' + row?.nbGroupeActif + '</span></a>';                              }                              var ajoutIcon = '<a href="#AjoutDupOffreModal" data-dismiss="modal" data-action="ajout" data-value="0" data-toggle="modal" data-prognom="' + row.PROG_NOM + '" data-progid="' + row.FK_programme + '" data-centreid="' + row.FK_ecole + '" data-instid="' + row.FK_etablissement + '" title="@Resource.AjoutOffreService"><i class="feather icon-file-plus"></i></a>';var poubelleIcon = '<a href="#SupprimerProgCFModal" data-dismiss="modal" data-toggle="modal" data-prognom="' + row.PROG_NOM + '" data-progid="' + row.FK_programme + '" data-centreid="' + row.FK_ecole + '" data-instid="' + row.FK_etablissement + '" title="@Resource.Supprimer"><i class="feather icon-trash-2"></i></a>';                                  return '' + ajoutIcon + ' | ' + poubelleIcon + '' + childRowIcon + '';                          },                          targets: "no-sort",                          orderable: false                      }  

What are my options to fix the problem?

I need to disable Vue.js devtools for production mode but it should be enabled for development mode

Posted: 14 Apr 2021 07:52 AM PDT

I don't want my users to inspect the app using devtools so I would like to disable it in the production mode. But I need it in local/development mode. I have tried the below but it is not working.

I have created .env and .env.production files with a variable VUE_APP_ROOT_API

.env file

VUE_APP_ROOT_API=http://localhost

.env.production

VUE_APP_ROOT_API=https://prod.com

in webpack configuration, I have added below

devtool: process.env.VUE_APP_ROOT_API === 'PROD' ? 'source-map' : ''

Please help me.

Check if excel range has shape with VBA

Posted: 14 Apr 2021 07:53 AM PDT

Hi I'm trying to work through a table downloaded from a 3rd party that uses ticks (shapes) rather than text in the cells. The shapes have no textframe characters. I can't filter the ticks in excel so I want to replace then with text e.g. Yes. Here is my working code but get run time error 438 due to object errors I have tried the excel vba object model but can't get it to work. The VBE doesn't seem to have the Selection.ShapeRange

https://docs.microsoft.com/en-us/office/vba/api/excel.shape

https://docs.microsoft.com/en-us/office/vba/api/excel.shaperange

Here is my code

Sub ReplaceShapeswithYes()    ' Inserts text where a shape exists    Dim ws As Worksheet  Dim NumRow As Integer  Dim iRow As Integer  Dim NumShapes As Long    Set ws = ActiveSheet    NumRow = ws.UsedRange.Rows.Count    For iRow = 2 To NumRow            Cells(iRow, 10).Select      'NumShapes = ActiveWindow.Selection.ShapeRange.Count ' tried both      NumShapes = Windows(1).Selection.ShapeRange.Count            If NumShapes > 0 Then      Cells(iRow, 10).Value = "Yes"      End If                Next iRow    End Sub  

Many thanks

React, insert/append/render existing <HTMLCanvasElement>

Posted: 14 Apr 2021 07:53 AM PDT

In my <App> Context, I have a canvas element (#offScreen) that is already hooked in the requestAnimationFrame loop and appropriately drawing to that canvas, verified by .captureStream to a <video> element.

In my <Canvas> react component, I have the following code (which works fine):

NOTE: master is the data object for the <App> Context.

function Canvas({ master, ...rest } = {}) {      const canvasRef = useRef(master.canvas);            const draw = ctx => {          ctx.drawImage(master.canvas, 0, 0);      };      useEffect(() => {          const canvas = canvasRef.current;          const ctx = canvas.getContext("2d");          let animationFrameId;            const render = () => {              draw(ctx)              animationFrameId = window.requestAnimationFrame(render)          }          render();                    return () => {              window.cancelAnimationFrame(animationFrameId);          }      }, [ draw ]);        return (          <canvas              ref={ canvasRef }              onMouseDown={ e => console.log(master, e) }          />      );  };  

Edited for clarity based on comments

In my attempts to render the master.canvas directly (e.g. return master.canvas in <Canvas>), I get some variation of the error "Objects cannot be React children" or I get [object HTMLCanvasElement] verbatim on the screen.

It feels redundant to take the #offScreen canvas and repaint it each frame. Is there, instead, a way to insert or append #offScreen into <Canvas>, so that react is just directly utilizing #offScreen without having to repaint it into the react component canvas via the ref?

How do I set Multipart Boundaries ubuntu 20.04

Posted: 14 Apr 2021 07:53 AM PDT

I just upgraded my servers to ubuntu 20.04 Software the worked with the current php (7.4) now doesnt I am getting FILES error 3 because of modsecurity It is because when i do a file upload i get

Multipart parsing error: Multipart: Final boundary missing   

I am pretty sure its a setting I am not seeing Any ideas so far I did

a2enmod headers    a2enmod mime_magic    [Wed Apr 14 06:51:49.408489 2021] [:error] [pid 45290] [client 96.225.42.186:62939] ModSecurity: Warning. Matched "Operator `Eq' with parameter `0' against variable `REQBODY_ERROR' (Value: `1' ) [file "/etc/modsecurity3/modsecurity.d/modsecurity.conf"] [line "53"] [id "200002"] [rev ""] [msg "Failed to parse request body."] [data "Multipart parsing error: Multipart: Final boundary missing."] [severity "2"] [ver ""] [maturity "0"] [accuracy "0"] [hostname "www.simplifiedchurch.net"] [uri "/sc/603af891cf463b33c286c37e21ecddc4/expenses_ajax/doajaxAUTOfileupload.php"] [unique_id "161839750873.019595"] [ref "v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v115 (80 characters omitted)"], referer: https://website.net/sc/603af891cf463b33c286c37e21ecddc4/55a591650f223bc6074c23240d3bb4b1.php  [Wed Apr 14 06:51:49.408680 2021] [:error] [pid 45290] [client 96.225.42.186:62939] ModSecurity: Warning. Matched "Operator `Eq' with parameter `0' against variable `REQBODY_ERROR' (Value: `1' ) [file "https://rules.malware.expert/download.php?rules=generic"] [line "23"] [id "400000"] [rev ""] [msg "Malware Expert - Failed to parse request body: Multipart parsing error: Multipart: Final boundary missing."] [data ""] [severity "0"] [ver ""] [maturity "0"] [accuracy "0"] [hostname "www.website.net"] [uri "/sc/603af891cf463b33c286c37e21ecddc4/expenses_ajax/doajaxAUTOfileupload.php"] [unique_id "161839750873.019595"] [ref "v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v1152,1v115 (80 characters omitted)"], referer: https://website.net/sc/603af891cf463b33c286c37e21ecddc4/55a591650f223bc6074c23240d3bb4b1.php  

how can i get hourly weather from current day start time from openweather API using Flask

Posted: 14 Apr 2021 07:53 AM PDT

import arrow  import requests  import geocoder  from flask import Flask, render_template    API_KEY = "1a2b3c4d"    app = Flask(__name__)    @app.route("/")  def index():      return render_template("index.html")    @app.route("/api/data")      def get_data():      x, y = geocoder.ip("me").latlng          exclude = "current,alerts,minutely"      api_url = f"http://api.openweathermap.org/data/2.5/onecall/timemachine?lat={x}&lon={y}&dt=    {1618252200}&appid={API_KEY}&units=metric"       resp = requests.get(api_url)  
  1. And the output that I am getting is output How can i change the GMT date to Ist

I need the response like Example if the current date is 14.04.2021 I want the temperature details from 14.04.2021 12 am to 12 pm

Correct ID validation in c#

Posted: 14 Apr 2021 07:52 AM PDT

I'm currently creating a student attendance system using c# and MySQL. There is a barcode scanner to scan student id. i have stored student information in std_info column and attendance information in std_att column. The scanning and adding is working perfectly. The barcode scanner is scanning the student id number.

How can it be modified to show an error message if the barcode scanner went wrong and someone add data that is not in the database?

Here is the code for add to database:

private void button3_Click(object sender, EventArgs e)          {                            cmd = new MySqlCommand();              cmd.CommandText = "insert into std_att (nibm_id, nic, name, address, number, batch) SELECT * FROM `std_info` where nibm_id like '" + textBox1.Text + "%'";              if (textBox1.Text == "")              {                  label10.Text = "*Please scan the ID";                  errorProvider1.Clear();                               }              else              {                  con.Open();                  cmd.Connection = con;                  cmd.ExecuteNonQuery();                  con.Close();                  MessageBox.Show("Data Inserted ✔️");                    string Query = "select * from std_att ;";                  MySqlCommand MyCommand2 = new MySqlCommand(Query, con);                  MySqlDataAdapter MyAdapter = new MySqlDataAdapter();                  MyAdapter.SelectCommand = MyCommand2;                  DataTable dTable = new DataTable();                  MyAdapter.Fill(dTable);                  dataGridView1.DataSource = dTable;              }          }  

Barcode scanning part

  private void VideoCaptureDevice_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)          {                Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();              BarcodeReader reader = new BarcodeReader();              var result = reader.Decode(bitmap);              if (result != null)              {                  textBox1.Invoke(new MethodInvoker(delegate ()                  {                        cmd = new MySqlCommand();                      cmd.CommandText = " SELECT * FROM `std_info` where nibm_id like '" + textBox1.Text + "%'";                      cmd.CommandType = CommandType.Text;                      cmd.Connection = con;                      con.Open();                      MySqlDataReader dr = cmd.ExecuteReader();                        while (dr.Read())                      {                          textBox1.Text = result.ToString();                          label3.Text = dr.GetValue(2).ToString();                          label4.Text = dr.GetValue(1).ToString();                          label8.Text = dr.GetValue(5).ToString();                    }                          con.Close();                    }));                }              pictureBox1.Image = bitmap;          }  

Screen shot of the program

Why do RxJS pipe subscribe callbacks sometimes not fire?

Posted: 14 Apr 2021 07:53 AM PDT

I'm sure this is a design issue on my part, but I'm trying to understand why RxJS pipe.subscribe callbacks do not fire. In the code below, next, error, and complete callbacks do not fire. What needs to change to make that happen?

In this case, the polling of the endpoint works just fine but the .subscribe callbacks never get called.

this.service        .postThing('/endpoint', {params})        .then((response.id) => {          interval(3000)            .pipe(              switchMap(() => this.service.getThing('/endpoint', response.id)),              retryWhen((errors) =>                errors.pipe(filter((err) => err.status === 404))              )            )            .subscribe(              (data) => {                console.log(data);              },              (error) => {                console.log(error)              },              () => {                this.service.stopLoading()              }            );        });  

Alpha–beta pruning in non-binary-tree

Posted: 14 Apr 2021 07:53 AM PDT

Is the classical Alpha–beta pruning code on c++ works with Non-binary-tree(3 or more children for node), because all examples of this code are used with binary trees, and when I run this code on VS, the real answer(on paper) and the result of the code are different.Is it normal? Here is the code from the internet:

#include <iostream>  #include <algorithm>  #include <cmath>  #include <climits>  #define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))  using namespace std;  int getHeight(int n) {     return (n == 1) ? 0 : 1 + log2(n / 2);  }  int minmax(int height, int depth, int nodeIndex,  bool maxPayer, int values[], int alpha,  int beta) {     if (depth == height) {        return values[nodeIndex];     }     if (maxPayer) {        int bestValue = INT_MIN;        for (int i = 0; i < height - 1; i++) {  //MAYBE THE PROBLEM IS HERE??????           int val = minmax(height, depth + 1, nodeIndex * 2 + i, false, values, alpha, beta);           bestValue = max(bestValue, val);           alpha = max(alpha, bestValue);           if (beta <= alpha)              break;        }        return bestValue;     } else {        int bestValue = INT_MAX;        for (int i = 0; i < height - 1; i++) {           int val = minmax(height, depth + 1, nodeIndex * 2 + i, true, values, alpha, beta);           bestValue = min(bestValue, val);           beta = min(beta, bestValue);           if (beta <= alpha)              break;        }        return bestValue;     }  }  int main() {     int values[] ={9,3,10,20,1,15,2,27,35,4,7,14,2,1,55,0,8,6,0,2,80,47,33,42,14,25,1 }; ////for example, 9,3 and 10 are the children of the same node     int height = getHeight(SIZE(values));     int result = minmax(height, 0, 0, true, values, INT_MIN, INT_MAX);     cout <<"Result : " << result << "\n";     return 0;  }  

Microsoft Graph ItemNotFound error when trying to get a workbook from sharepoint

Posted: 14 Apr 2021 07:52 AM PDT

I followed this tutorial: https://mihai-albert.com/2020/05/13/using-microsoft-graph-to-modify-excel-files-stored-in-sharepoint-online-with-c/

When I use graph-explorer and do a GET https://graph.microsoft.com/v1.0/drives/{drive-id}/root/search(q='{search-text}')?select=name,id,webUrl then I get the item id with no problem. But then when I want to get the workbook in my application

 private readonly GraphServiceClient _graphServiceClient;          public GraphService(             IOptions<AzureAdOptions> azureAdOptions)          {              var confidentialClientApplication = ConfidentialClientApplicationBuilder                     .Create(azureAdOptions.Value.ClientId)                     .WithTenantId(azureAdOptions.Value.TenantId)                     .WithClientSecret(azureAdOptions.Value.ClientSecret)                     .Build();                var authProvider = new ClientCredentialProvider(confidentialClientApplication);              _graphServiceClient = new GraphServiceClient(authProvider);          }            public async Task Test()          {              try {                  var range = await _graphServiceClient.Drives[{drive-id}].Items[{item-id}]                  .Request()                  .GetAsync();                                 }              catch (Exception e)              {                  Console.WriteLine(e.Message);              }  

then I get an itemnotfound error despite putting in the correct id's. It can find the drive if I just add that part, so it doesn't seem like there's a problem with my setup. has anyone encountered this problem or knows how to solve this?

Also, if I want to get a workbook which is located in a group, can I use the same code, just switch out the item id ? or do I have do add groupid in some way?

tell me about apng iamge? [closed]

Posted: 14 Apr 2021 07:53 AM PDT

how I created apng image other than how they code and combined it in one frame tell me more about apng image? apng image

pandas styling doesn't display for all rows in large dataframes in Chrome or Edge

Posted: 14 Apr 2021 07:53 AM PDT

Update 2:

  • The issue seems to be Google Chrome and Microsoft Edge
  • Jupyter Lab in Firefox correctly displays all of the styled rows and correctly renders an output HTML file.
  • The question is then, what are the relevant settings in Chrome and Edge, or why doesn't this work in Chrome or Edge?

Original:

  • Questions - they are interrelated:
    1. Why aren't all of the rows displaying the background styling in Jupyter or writing to HTML?
      • All rows should have green styling, but the last 5 do not display the styling.
    2. How can all of the rows be made to display the background styling?
  • Given a large dataframe, in this case 474 rows x 35 columns, the applied styling stops displaying.
    • enter image description here
  • If the number of rows or columns increases beyond this size, then more rows aren't displayed.
  • We can see from the styling map, that the rows are correctly mapped with a background color, but it isn't displayed.
    • enter image description here
  • If the number of rows or columns is reduced, then all of the rows display the correct styling.
  • Tested in jupyterlab v3.0.11
  • In PyCharm 2021.1 (Professional Edition) Build #PY-211.6693.115, built on April 6, 2021 saving the redendered styler to a file has the same result, so this isn't just an issue with jupyter.
  • This issue is reproducible on two different systems, that I have tried.
  • If the shape is reduced to 471 rows × 35 columns or 474 rows × 34 columns, then all rows correctly display the highlighting.
  • Associated pandas bug report: 40913

Reproducible DataFrame

import pandas as pd  import numpy as np  from faker import Faker  # conda install -c conda-forge faker or pip install Faker    # for fake names  fake = Faker()    # test data  np.random.seed(365)  rows = 11000    # change 36 or 158 to test where the rows stop appearing  vals = {f'val{i}': np.random.randint(1, 11, size=(rows)) for i in range(1, 36)}  data = {'name': np.random.choice([fake.unique.name() for i in range(158)], size=rows),          'cat': np.random.randint(1, 4, size=(rows))}  data.update(vals)    df = pd.DataFrame(data)    # used to create the mask for the background color  mean = df.groupby('cat').mean().round(2)    # calculate the mean for each name and cat  cat_mean = df.groupby(['name', 'cat']).mean()      def color(x):      """Function to apply background color"""      c1 = 'background-color: green'      c = ''       # compare columns      mask1 = x.gt(mean)      # DataFrame with same index and columns names as original filled empty strings      df1 =  pd.DataFrame(c, index=x.index, columns=x.columns)      # modify values of df1 column by boolean mask      df1.iloc[mask1] = c1      display(df1)        return df1    # Last line in notebook displays the styled dataframe  cat_mean.style.apply(color, axis=None)    # Last line in PyCharm saving rendered styler to file  cm = cat_mean.style.apply(color, axis=None).set_precision(3).render()    with open('cm_test.html', 'w') as f:      f.write(cm)  

Reference

  • This answer was referenced for the function to apply the background color.
  • This question is similar, but has no answer.

Output of pd.show_versions()

INSTALLED VERSIONS  ------------------  commit           : f2c8480af2f25efdbd803218b9d87980f416563e  python           : 3.8.8.final.0  python-bits      : 64  OS               : Windows  OS-release       : 10  Version          : 10.0.19041  machine          : AMD64  processor        : Intel64 Family 6 Model 60 Stepping 3, GenuineIntel  byteorder        : little  LC_ALL           : None  LANG             : None  LOCALE           : English_United States.1252    pandas           : 1.2.3  numpy            : 1.19.2  pytz             : 2021.1  dateutil         : 2.8.1  pip              : 21.0.1  setuptools       : 52.0.0.post20210125  Cython           : 0.29.22  pytest           : 6.2.3  hypothesis       : None  sphinx           : 3.5.3  blosc            : None  feather          : None  xlsxwriter       : 1.3.8  lxml.etree       : 4.6.3  html5lib         : 1.1  pymysql          : None  psycopg2         : None  jinja2           : 2.11.3  IPython          : 7.22.0  pandas_datareader: 0.9.0  bs4              : 4.9.3  bottleneck       : 1.3.2  fsspec           : 0.9.0  fastparquet      : None  gcsfs            : None  matplotlib       : 3.3.4  numexpr          : 2.7.3  odfpy            : None  openpyxl         : 3.0.7  pandas_gbq       : None  pyarrow          : None  pyxlsb           : None  s3fs             : None  scipy            : 1.6.2  sqlalchemy       : 1.4.5  tables           : 3.6.1  tabulate         : 0.8.9  xarray           : None  xlrd             : 2.0.1  xlwt             : 1.3.0  numba            : 0.53.1  

Example from jezrael

  • enter image description here
  • It was stated in the comment "for me working perfectly...". However, as can be seen, the last 5 rows should contain green styling, but they do not.

Workaround

Split DataFrame

  • It's dissatisfying, but splitting the DataFrame and applying the style will work, since if reduces the overall size.
cat_mean.iloc[:237, :].style.apply(color, axis=None)  cat_mean.iloc[237:, :].style.apply(color, axis=None)  

Save to Excel

  • All rows are displayed correctly with the highlight color when saving to Excel
test = cat_mean.style.apply(color, axis=None)  test.to_excel('test.xlsx', engine='openpyxl')  

Update 1:

  • The following options produced the same results as the original attempts
    • Standard python console creating HTML file
    • PyCharm creating HTML file
    • Jupyter Lab displaying styled dataframe in a cell.

Output of pd.show_versions()

INSTALLED VERSIONS  ------------------  commit           : 2cb96529396d93b46abab7bbc73a208e708c642e  python           : 3.9.2.final.0  python-bits      : 64  OS               : Windows  OS-release       : 10  Version          : 10.0.19041  machine          : AMD64  processor        : Intel64 Family 6 Model 60 Stepping 3, GenuineIntel  byteorder        : little  LC_ALL           : None  LANG             : None  LOCALE           : English_United States.1252    pandas           : 1.2.4  numpy            : 1.20.0  pytz             : 2021.1  dateutil         : 2.8.1  pip              : 21.0.1  setuptools       : 52.0.0.post20210125  Cython           : None  pytest           : None  hypothesis       : None  sphinx           : None  blosc            : None  feather          : None  xlsxwriter       : None  lxml.etree       : None  html5lib         : None  pymysql          : None  psycopg2         : None  jinja2           : 2.11.3  IPython          : 7.22.0  pandas_datareader: None  bs4              : None  bottleneck       : None  fsspec           : None  fastparquet      : None  gcsfs            : None  matplotlib       : None  numexpr          : None  odfpy            : None  openpyxl         : None  pandas_gbq       : None  pyarrow          : None  pyxlsb           : None  s3fs             : None  scipy            : None  sqlalchemy       : None  tables           : None  tabulate         : None  xarray           : None  xlrd             : None  xlwt             : None  numba            : None  

BigCommerce product update not returning image array

Posted: 14 Apr 2021 07:52 AM PDT

We have a large catalog where we update products on a regular basis. The product update works, and returns the product and other arrays except for images. Existing images are updated and new images are added, but the responseMessage does not contain the image array. I can create a workaround, but it would not as graceful as handling a single product object.

HttpResponseMessage responseMessage = await client.PutAsync(String.Format("catalog/products/{0}", product.BigCommerceProductId), httpContent);

How to save sensitive data on heroku?

Posted: 14 Apr 2021 07:52 AM PDT

I have linked my GitHub to a Heroku project and I want to use nodemailer. At some point I want to make this repository public, so obviously I do not want to commit a file that contains sensitive info (email and pass). Is there a way to store this data and just include it at any .js file without it appearing in my GitHub?

Extract multiple values from raster using for loop

Posted: 14 Apr 2021 07:52 AM PDT

I'm trying to extract multiple cell values from a raster using the following for-loop:

testis <- NULL  for(i in paste0("y", 2011:2019)){    testis[i] <- raster::extract(rf[[c(1, 3)]], i[, 1:2])  }  

In replacement for:

e_change <- raster::extract(rf[[c(1, 3)]], y2019[, 1:2]) #extract cell values  

Although, I get the following error:

Error in h(simpleError(msg, call)) : error in evaluating the argument 'y' in selecting a method for function 'extract': incorrect number of dimensions

discord ASCII bot python characters aren't all the same length so it looks bad

Posted: 14 Apr 2021 07:53 AM PDT

So made a simple discord bot that gives the user a banner command ' @commands.Cog.listener() async def on_ready(self): print('Dictbot running smooth')

@commands.command()  async def banner(self, ctx, *, msg):      ascii_banner = self.cus_fig.renderText(msg)       discord_banner = ''      for charecter in ascii_banner:          discord_banner += charecter          if (charecter == ' '):              discord_banner += '  '                print(ascii_banner)      await ctx.send(discord_banner)    @commands.command()  async def font(self, ctx, *, fontName):      self.cus_fig = Figlet(font=fontName)  

I used pyfiglet which works just find when i print the art to terminal but in discord not all the characters are the same width so it looks super ugly. I did a temporary fix by making all of the single spaces become 3 spaces which works OK but the letters are slightly off. And I can only use the banner3 font which is only pounds and spaces. is their any way to make all the characters the same distance apart in discord? Or a better way to do what im doing

No comments:

Post a Comment