Tuesday, May 25, 2021

Posts from Recent Questions - Stack Overflow for 05/25/2021

View this email in your browser
Updates from https://stackoverflow.com/questions

Recent Questions - Stack Overflow



In the 05/25/2021 edition:

How can I Highlight the google map polygon borders on click?

By Sai Charan M on May 25, 2021 04:07 am

I am using Google Map API JS in angular, and I am showing the multiple polygons on map and I want to highlight the border of the polygon when I clicks on polygon, but its highlighting the only last polygon only. In below I am sharing the stackblitz URL for reference

Demo:-https://stackblitz.com/edit/angular-draw-polygon-google-maps-1pdan5?file=app%2Fapp.component.ts

Please help me in these issue Thanks in advance


Read in browser »
share on Twitter

Empty string validation in Spark sql using case when statement

By Vicky on May 25, 2021 04:07 am

spark.sql("select case when cast(age as int) is not null then age else '' end as age, case when cast(age as int) is not null then 'Y' else 'age must be a number' end as age_flag from input").show(false)

Can anyone please add the extra condition of "if age is not provided , we dont need any validation" in the above statement


Read in browser »
share on Twitter

Create an array where the elements are determined by non null values in a row

By x-x on May 25, 2021 04:07 am

I have the following sheet to track participation in events...

Example sheet

... that continues for hundreds of columns and rows. A blank cell indicates that person did not participate in that event. I can not change the layout of this sheet.

For each name I need to create an array of Event IDs for the events they have participated in, which would look like this:

enter image description here

Columns would be fine too.

I am already able to generate this array using (pseudo-formula) QUERY(TRANSPOSE(range), "SELECT (Event ID column) WHERE (user column) IS NOT NULL", 0), however I'm looking for a solution that does not need to TRANSPOSE the sheet, either in memory or in a separate 'helper' sheet.


Read in browser »
share on Twitter

how to install ans use cppclean on ubuntu?

By Engineer Rasul Shamohamadi on May 25, 2021 04:06 am

I want to compile a source code, below error occurred.

cppcleant not found

I searched and found that cppclean must installed with

$ pip install --upgrade cppclean the result is

successfully installed cppclean-0.13 but compile error is steal remained and when I type cppclean result is ** command cppclean not found ** what should I do?


Read in browser »
share on Twitter

Mean points end up next to boxplot bars

By Tiptop on May 25, 2021 04:06 am

I'm trying to put a mean in a boxplot with facets but the mean points does not end up on top of the boxplot but next to them. Any suggestions as how to fix this so that the mean points end up on top of the boxplots?

enter image description here

Here's the code for the ggplot2

(    df %>%    ggplot() +    aes(x = inlet_gas, y = Furfural_uptake, fill = soil_type) +    stat_summary(fun="mean", color="darkred", geom="point",                 shape=15, show.legend=FALSE)+    geom_boxplot() +    scale_fill_hue() +    labs(x = "",         y = "Uptake (% of blank)",         title = "Linalool uptake") +    labs(fill="") +    theme_bw() +    facet_wrap(vars(measurement_type), scales = "free", ncol = 1L)  )    

And here's the data:

df <- structure(list(measurement_type = structure(c(1L, 1L, 1L, 1L,  1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L,  3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,  1L, 1L, 1L, 1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,  3L, 3L, 3L, 3L), .Label = c("No VOC addition", "13C mix addition",  "VOC addition [low]", "VOC addition [medium]", "VOC addition [high]"  ), class = "factor"), soil_type = c("forest", "forest", "forest",  "forest", "forest", "heath", "heath", "heath", "forest", "forest",  "forest", "forest", "forest", "forest", "forest", "forest", "forest",  "forest", "forest", "heath", "heath", "heath", "heath", "heath",  "forest", "forest", "forest", "forest", "forest", "forest", "forest",  "forest", "forest", "heath", "heath", "heath", "forest", "forest",  "forest", "forest", "forest", "forest", "forest", "forest", "forest",  "forest", "forest", "heath", "heath", "heath", "heath", "heath",  "forest", "forest", "forest", "forest"), Furfural_uptake = c(1.2,  1.02, 1.22, 1.27, 1.21, 1.17, 1.22, 1.09, 1.03, 1.09, 0.95, 0.92,  0.98, 1.04, 0.64, 0.62, 0.58, 0.62, 0.59, 0.6, 0.61, 0.55, 0.63,  0.55, 0.73, 0.66, 0.73, 0.69, 0.7, 0.71, 0.82, 0.77, 0.7, 0.52,  0.62, 0.57, 0.56, 0.47, 0.44, 0.6, 0.5, 0.52, 0.72, 0.68, 0.64,  0.65, 0.67, 0.63, 0.59, 0.64, 0.69, 0.7, 0.57, 0.58, 0.54, 0.58  ), inlet_gas = c("N2", "N2", "N2", "N2", "N2", "N2", "N2", "N2",  "N2", "N2", "N2", "N2", "N2", "N2", "N2", "N2", "N2", "N2", "N2",  "N2", "N2", "N2", "N2", "N2", "N2", "N2", "N2", "N2", "O2", "O2",  "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2",  "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2", "O2",  "O2", "O2", "O2", "O2")), row.names = c(NA, -56L), groups = structure(list(      inlet_gas = c("N2", "N2", "O2", "O2"), measurement_type = structure(c(1L,      3L, 1L, 3L), .Label = c("No VOC addition", "13C mix addition",      "VOC addition [low]", "VOC addition [medium]", "VOC addition [high]"      ), class = "factor"), .rows = structure(list(1:14, 15:28,          29:42, 43:56), ptype = integer(0), class = c("vctrs_list_of",      "vctrs_vctr", "list"))), row.names = c(NA, -4L), class = c("tbl_df",  "tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",  "tbl_df", "tbl", "data.frame"))  

Read in browser »
share on Twitter

Search column name with multiple conditions pandas

By mapping dom on May 25, 2021 04:06 am

I have a query to retrieve all columns with the name date in them as below

date_raw_cols = [col for col in df_raw.columns if 'date' in col]  

That is also picking up columns with updated which I want to exclude. I've also tried a regex filter as below with same problem of returning updated

df_dates = df_raw.filter(regex='date', axis='columns')```    How do I combine conditions to filter column names. i.e.    Where column name is date but not update  

Read in browser »
share on Twitter

stackoverflow error while downloading image url and set it into firebse real time database

By Sachin Burdak on May 25, 2021 04:06 am

i am getting stackoverflow error while calling storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() and database.getReference().child("users").child(Userid).child("profile picture").setValue(uri);

java code

@Override      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {          super.onActivityResult(requestCode, resultCode, data);            fullimage = findViewById(R.id.fullimage);          profileimage = findViewById(R.id.profileimage);            if (data.getData()!=null){              Uri imgUri = data.getData();                profileimage.setImageURI(imgUri);              fullimage.setImageURI(imgUri);              try {              String Userid = FirebaseAuth.getInstance().getCurrentUser().getUid();                StorageReference storageReference = storage.getReference().child("User profile Pictures").child(Userid);                   storageReference.putFile(imgUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {                     @Override                     public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {                         storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {                    ///// line 71 where getting error                             @Override                             public void onSuccess(Uri uri) {                                 database.getReference().child("users").child(Userid).child("profile picture").setValue(uri);       ///// line 74 where getting error                                 users.setProfilepicture(uri.toString());                             }                         });                     }                 });             }catch (Exception e){                 e.printStackTrace();                 Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();             }          }      }  }  

error message

01-01 08:45:03.220 1545-1545/com.example.signupsignin E/AndroidRuntime: FATAL EXCEPTION: main  Process: com.example.signupsignin, PID: 1545  java.lang.StackOverflowError      at java.lang.Exception.<init>(Exception.java:60)      at java.lang.ReflectiveOperationException.<init>(ReflectiveOperationException.java:51)      at java.lang.reflect.InvocationTargetException.<init>(InvocationTargetException.java:50)      at java.lang.reflect.Method.invokeNative(Native Method)      at java.lang.reflect.Method.invoke(Method.java:515)  

Read in browser »
share on Twitter

Laravel eloquent - Doctrine model and migration equivalent

By R.Damasinoro on May 25, 2021 04:06 am

Coming from a long Symfony-Doctrine background, I have started learning Laravel 8.

One of my first discovery was that migration needed to be manually created after using make:migration (from what I understood thus far) in both Models and Migration.

Symfony, with Doctrine, allowed a bunch of automatisation, and I only needed to create the field or relation from the Model (php annotation or yaml) - before launching doctrine:schema:validate and make:migration https://symfony.com/doc/current/doctrine.html#migrations-adding-more-fields

Did I miss something or a vital package ?
Not having a central file to map/read a model (which linkied php and database) seems weird to me now.
I've only started but the documentation does not seems to mention anything equivalent
https://laravel.com/docs/8.x/migrations#generating-migrations


Read in browser »
share on Twitter

Python LDAP connection issues

By SaraK on May 25, 2021 04:03 am

I am trying to set up LDAP connection using python and fetch the list of users: I am getting issue with this line

Execute search / 1st page

response = connect.search_ext(ldapSearchOrganizationalUnit,                                     ldap.SCOPE_ONELEVEL ,                                     filterstr=ldapSearchFilter,                                     attrlist=ldapSearchReturnAttributes,                                     serverctrls=[page_control])        # Iterate through results with pagination and write to DB        while True:            pages += 1          rtype, rdata, rmsgid, serverctrls = connect.result3(response)          result.extend(rdata)  

catTraceback (most recent call last): File "/usr/src/app/ldap_sync_users.py", line 63, in rtype, rdata, rmsgid, serverctrls = connect.result3(response) Why am i getting this errors from python library: File "/usr/local/lib/python3.9/site-packages/ldap/ldapobject.py", line 764, in result3 resp_type, resp_data, resp_msgid, decoded_resp_ctrls, retoid, retval = self.result4( File "/usr/local/lib/python3.9/site-packages/ldap/ldapobject.py", line 774, in result4 ldap_result = self._ldap_call(self._l.result4,msgid,all,timeout,add_ctrls,add_intermediates,add_extop) File "/usr/local/lib/python3.9/site-packages/ldap/ldapobject.py", line 340, in _ldap_call reraise(exc_type, exc_value, exc_traceback) File "/usr/local/lib/python3.9/site-packages/ldap/compat.py", line 46, in reraise raise exc_value File "/usr/local/lib/python3.9/site-packages/ldap/ldapobject.py", line 324, in _ldap_call result = func(*args,**kwargs)


Read in browser »
share on Twitter

How to create new instance of class in laravel through variable name?

By Salman Ali on May 25, 2021 04:02 am

I'm creating an API which passes me the model name as parameter. So what I want is to create a new instance of that model class and get the required data accordingly. The error which I am facing right now is that it is not generating the namespace even though I have added the model use above. I tried adding "" before the variable new but still didn't work. Also I tried ReflectionClass to initialize class instance but still it is not finding the class. I'd be really grateful if someone can help me out here. enter image description here

enter image description here


Read in browser »
share on Twitter

jquery code problem can someone help me fix it? [duplicate]

By Claudiu Piturca on May 25, 2021 04:02 am

Hello i'm trying to do a login form query code that valides if my username and password is entered correctly with the username and password: New_Username and 123456789,i tried with php but for some reason the php code doesn't work in VS code code:

$(document).ready(function () {      $("#login").click(function () {          var email = $("#email").val();          var password = $("#password").val();          // Checking for blank fields.          if (email == '' || password == '') {              $('input[type="text"],input[type="password"]').css("border", "2px solid red");              $('input[type="text"],input[type="password"]').css("box-shadow", "0 0 3px red");              alert("Please fill all fields...!!!!!!");          } else {              $.post("login.php", {                      Username: New_Username,                      password1: 123456789                  },                  function (data) {                      if (data == 'Invalid Email.......') {                          $('input[type="text"]').css({                              "border": "2px solid red",                              "box-shadow": "0 0 3px red"                          });                          $('input[type="password"]').css({                              "border": "2px solid #00F5FF",                              "box-shadow": "0 0 5px #00F5FF"                          });                          alert(data);                      } else if (data == 'Email or Password is wrong...!!!!') {                          $('input[type="text"],input[type="password"]').css({                              "border": "2px solid red",                              "box-shadow": "0 0 3px red"                          });                          alert(data);                      } else if (data == 'Successfully Logged in...') {                          $("form")[0].reset();                          $('input[type="text"],input[type="password"]').css({                              "border": "2px solid #00F5FF",                              "box-shadow": "0 0 5px #00F5FF"                          });                          alert(data);                      } else {                          alert(data);                      }                  });          }      });  });  

is this the good code for login form query that i mentioned it gives an error saying "$ is not defined",also the login form and validation not working how i fix this error and code?


Read in browser »
share on Twitter

Accessing Pod's service name inside index.html

By Sunny on May 25, 2021 04:01 am

I've some services running inside a kubernetes, where one is ClusterIP, and one is NodePort. Inside my UI container, src/app/build/

curl -i -X GET http://service-name:port/check  

is returning valid json, meaning the containers are connecting and working with the service name.

However, from the UI (for testing purpose running a script to fetch() inside index.html), if I make a call to http://service-name:port/check

I'm getting this error

"(failed)net::ERR_NAME_NOT_RESOLVED"

Any help regarding configurations or debugging will help.


Read in browser »
share on Twitter

Run an action after end animation

By Carle on May 25, 2021 04:00 am

is it possible to run a function after end this animation? Thank you for you help

animation = CurvedAnimation(         parent: controller,         curve: Curves.linear,        ).drive(Tween(begin: 0.0, end: 1));  

Read in browser »
share on Twitter

Python adding subsequent list members to each other

By user964986 on May 25, 2021 04:00 am

I have a following list of elements:

['e1', 'e2', 'e3']  

and I would like to end up with:

['e1', 'e1e2', 'e1e2e3']  

Currently I have the following code that achieves it, but I would like to know whether is there any other method, like a list comprehension, that would make the solution shorter. I'm open to all suggestions, including crazy ones. Also it doesn't need to be a list but anything iterable.

my_list = ['e1', 'e2', 'e3']  new_list =  add_elem = ''  for elem in my_list:      add_elem += elem      new_list.append(add_elem)  

Read in browser »
share on Twitter

MVVM in TableView Cell

By Umair Khan on May 25, 2021 03:57 am

hope you're well, i am working on an app which uses TableView for showing feeds to user using ViewModel and my ViewModel contains a variable which contains data of all cells and other data as well, what i am doing is passing whole ViewModel reference and indexPath to cell, here you can see:

func configureCell(feedsViewModelObj feedsViewModel: FeedsViewModel, cellIndexPath: IndexPath, presentingVC: UIViewController){      //Assigning on global variables      self.feedsViewModel = feedsViewModel      self.cellIndexPath = cellIndexPath      self.presentingVC = presentingVC        let postData = feedsViewModel.feedsData!.data[cellIndexPath.row]        //Populate      nameLabel.text = postData.userDetails.name      userImageView.sd_setImage(with: URL(string: postData.userDetails.photo), placeholderImage: UIImage(named: "profile-image-placeholder"))        updateTimeAgo()      postTextLabel.text = postData.description      upvoteBtn.setTitle(postData.totalBull.toString(), for: .normal)      upvoteBtn.setSelected(selected: postData.isClickedBull, isAnimated: false)      downvoteBtn.setSelected(selected: postData.isClickedBear, isAnimated: false)      downvoteBtn.setTitle(postData.totalBear.toString(), for: .normal)      commentbtn.setTitle(postData.totalComments.toString(), for: .normal)      optionsBtn.isHidden = !(postData.canEdit && postData.canDelete)        populateMedia(mediaData: postData.files)  }  

so, is it the right or good way to pass full ViewModel reference and index to cell and then each cell access its data from data array? (if not please guide me). Many thanks.


Read in browser »
share on Twitter

Typescript make an attribute optionnal in an interface with inneritance

By Saren on May 25, 2021 03:53 am

My objectiv is to clone an interface but changing some parameters. I got a default generated interface from my database like this one

interface Db {    id: number;    name: text;    ...  }  

The interface is pretty long and that's why I don't want to copy all of that (and also because If the database model change, I don't want to manually change my second interface).

So, my second interface should be exactly the same as the database one BUT with the id in optional

I tried:

interface NewInterface extends Db {    id ?: number;  }  

But it return me an error: id is need in ... but optionnal in ...

I prefere also to avoid using delete operator in my code. But it doesn't work, does any one have any idea ?


Read in browser »
share on Twitter

How to take average of an array of same keys with javascript code? [closed]

By Rigin Oommen on May 25, 2021 03:46 am

Can you please contribute the javascript code snippet to acheive this usecase.

Input data set :

[      {          "cost": 0.49,          "accessibility": 0.9,          "bestPractices": 0.81,          "seo": 0.85,          "pwa": 0.58      },      {          "performance": 0.67,          "accessibility": 0.9,          "bestPractices": 0.81,          "seo": 0.85,          "pwa": 0.58      },      {          "performance": 0.71,          "accessibility": 0.9,          "bestPractices": 0.81,          "seo": 0.85,          "pwa": 0.58      }  ]  

Expected Output it should be the average if the three values of the input:

{      "performance": 0.62,      "accessibility": 0.9,      "bestPractices": 0.81,      "seo": 0.85,      "pwa": 0.58  }  

Read in browser »
share on Twitter

React class function arrow [duplicate]

By Dain Park on May 25, 2021 03:45 am

In this code, if I write add function like add = function(){} or add(){} , then I doesn't work. Are there some reasons?

    class App extends.React.Component{  state = {    count: 0    };      add = () => {          console.log('add');          this.setState({count: this.state.count + 1});        }        minus = () => {          console.log('minus');          this.setState({count: this.state.count - 1});        }        render(){          return <div><Potato />          <div>class Component : {this.state.count}</div>          <button onClick={this.add}>add</button>          <button onClick={this.minus}>minus</button>          </div>        }      }  

Read in browser »
share on Twitter

I am getting an text error ' required positional argument: 'coro' ' while making error handler for one of command in my discord bot

By the last Ghoul on May 25, 2021 03:29 am
import discord  from discord.ext import commands    class Text(commands.Cog):    def __init__(self, client):      self.client = client      @commands.command()    @commands.has_permissions(administrator=True)    async def text(self, ctx, *, message):      await ctx.message.delete()      await ctx.send(message)      @text.error()    async def text_error(self, error, ctx):      if isinstance(error, commands.MissingPermissions):        await ctx.send(f"{ctx.auhtor.mention} You don't Have permission to use this command")    def setup(client):    client.add_cog(Text(client))  

The whole error:

File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 609, in _load_from_module_spec      raise errors.ExtensionFailed(key, e) from e  discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.text' raised an error: TypeError: error() missing 1 required positional argument: 'coro'  

Read in browser »
share on Twitter

android retrofit post request request body as raw JSON

By Ahmed feki on May 25, 2021 01:30 am

This is my first time using the retrofit in android (Java) and i don't know how to do post api

in postman i use Request Body as raw JSON

{ "description": "aaaaaa", "reportedpriority_description": "Elevé", "reportedby": "zz", "assetnum": "111", "affectedperson": "ahmed" }

someone can help me with example of code? it return empty response body


Read in browser »
share on Twitter

How do I pull data from mySQL to generate on a dashboard table automatically and make it be updated when a new row in the table is inserted?

By max on May 24, 2021 10:48 pm

I do have a specific question on using mySQL with node.js. So I have this mySQL database which will receive data from elsewhere and I would like to show data on this react app in the form of a table and make it be updated with new data whenever there is a update to the database (insert of a data into the table from elsewhere) How can I do so? Below is my code Front end: Stats.js

import React, { useState, useEffect } from "react";  import Navbar from "../Navbar/Navbar";  import Axios from "axios"; //axios library to make requests to api  import "./Stats.css";    function Stats() {    const [customerList, setCustomerList] = useState(); //store all that information of the database in a list    //make an axios request to get information from database    const getCustomers = () => {      Axios.get("http://localhost:3001/customers").then((response) => {        //console.log("successfully retrieved customers list from database");        console.log(response);        setCustomerList(response.data);      });    };          const [currentTime, setCurrentTime] = useState(1);        useEffect(() => {        fetch("/time")          .then((res) => res.json())          .then((data) => {            setCurrentTime(data.time);          });      }, );        useEffect(() => {        fetch("/time")          .then((res) => res.json())          .then((data) => {            const dateStr = new Date(data.time).toLocalDateString('en-CA');            const timeStr = new Date(data.time).toLocalTimeString();            const dateTime = `${dateStr} ${timeStr}`;            setCurrentTime(dateTime);          });      }, );        return (        <div>          <Navbar />          <h1>Statistics:</h1>          <button onClick={getCustomers}>Show Dashboard</button>          <table className="customertable">            <tr>              <th>S/N</th>              <th>Customer Name</th>              <th>Customer Email</th>              <th>Counts of Visit</th>              <th>Latest Time of Visit</th>              <th>Contacted?</th>            </tr>            {customerList.map((val, key) => {              const dateStr = new Date(val.latest_time_of_visit).toLocalDateString('en-CA');              const timeStr = new Date(val.latest_time_of_visit).toLocalTimeString();              const dateTime = `${dateStr} ${timeStr}`;                return (                <tr>                  <td>{val.ID}</td>                  <td>{val.name}</td>                  <td>{val.email}</td>                  <td>{val.counts_of_visit}</td>                  <td>{dateTime}</td>                  <td>{val.contacted}</td>                </tr>              );            })}          </table>        </div>      );  }    export default Stats;    

Back end server.js

//set up express server  const express = require("express");  const app = express();  //set up sql server  const mysql = require("mysql");  const cors = require("cors");    app.use(cors());  app.use(express.json());  //create a variable called db to make your SQL Statements  const db = mysql.createConnection({    user: "",    host: "",    password: "",    database: "",  });    //GET REQUEST to database to retrieve customers information from database  app.get("/customers", (req, res) => {    db.query("SELECT * FROM customer_info", (err, result) => {      if (err) {        console.log(err);      } else {        res.send(result);      }    });  });    //check if backend server is running  app.listen(3001, () => {    console.log("Your server is running on port 3001");  });    

Read in browser »
share on Twitter

add 2 legends in a geopandas graph

By manueldiaz97 on May 24, 2021 07:57 pm

I have a map of Mexico with the number of murders by state the map looks like thisenter image description here

and that I used is this

fig, ax = plt.subplots(figsize=(10, 10))   ax.set_title('Feminicidios, 2019',               pad = 20,               fontdict={'fontsize':20, 'color': 'black'})  gdf.plot(column='feminicidio', cmap='YlOrRd', ax=ax, zorder=5,legend=True,          legend_kwds={'label': "Feminicidios por Entidad Federativa",'orientation': "horizontal"})  ax.axis('off')  plt.savefig('Feminicidios.png')  

I Would like to ad a new legend or text box with the top 3 states.

PS Im using geopandas.


Read in browser »
share on Twitter

R Lookup values of a column defined by another column's values in mutate()

By AGeographer on May 24, 2021 04:11 pm

I am trying to lookup values from other columns in my data frame/tibble that are dependent on the value in column var. I can achieve this by hardcoding them in case_when():

library(tidyverse)  set.seed(1)  ds <- tibble(var = paste0("x", sample(1:3, 10, replace = T)),               x1 = 0:9,               x2 = 100:109,               x3 = 1000:1009)  ds %>%     mutate(result = case_when(var == "x1" ~ x1,                               var == "x2" ~ x2,                               var == "x3" ~ x3))  #> # A tibble: 10 x 5  #>    var      x1    x2    x3 result  #>    <chr> <int> <int> <int>  <int>  #>  1 x1        0   100  1000      0  #>  2 x3        1   101  1001   1001  #>  3 x1        2   102  1002      2  #>  4 x2        3   103  1003    103  #>  5 x1        4   104  1004      4  #>  6 x3        5   105  1005   1005  #>  7 x3        6   106  1006   1006  #>  8 x2        7   107  1007    107  #>  9 x2        8   108  1008    108  #> 10 x3        9   109  1009   1009  

However, What if I don't have just 3 columns but many xn?
I found that the following works for an external variable/object:

y <- "x2"  ds %>%    mutate(result = !!sym(y))  #> # A tibble: 10 x 5  #>    var      x1    x2    x3 result  #>    <chr> <int> <int> <int>  <int>  #>  1 x1        0   100  1000    100  #>  2 x3        1   101  1001    101  #>  3 x1        2   102  1002    102  #>  4 x2        3   103  1003    103  #>  5 x1        4   104  1004    104  #>  6 x3        5   105  1005    105  #>  7 x3        6   106  1006    106  #>  8 x2        7   107  1007    107  #>  9 x2        8   108  1008    108  #> 10 x3        9   109  1009    109  

But it doesn't work for an internal variable/column in a tibble:

ds %>%    mutate(result = !!sym(var))  #> Error: Only strings can be converted to symbols  

Created on 2021-05-24 by the reprex package (v2.0.0)
Any ideas of how to get this to work within a data frame/tibble column are greatly appreciated.


Read in browser »
share on Twitter

Sort by painless script with missing values

By Vojtěch on May 24, 2021 01:53 pm

I am trying to write a sort script which sorts by a value which might be messing:

  1. doc1: { id: 1, inner: { state: "active" }}
  2. doc2: { id: 2, inner: { state: "inactive" }}
  3. doc3: { id: 3 }

I am trying to sort by inner.state OR empty inner value.

Naively I tried:

doc['inner.state'].value != 'inactive' ? 0 : 1

Which works, but ignores the doc3.

Basically I need something like:

!exists(doc['inner']) || doc['inner.state'].value != 'inactive' ? 0 : 1

I also tried things like:

doc['inner'].empty ? 1 : 0

which results in {"type":"script_exception","reason":"runtime error"}


Read in browser »
share on Twitter

Elasticsearch wildcard, regexp, match_phrase, prefix query returning wrong results

By Aditya on May 24, 2021 10:20 am

I have just started using Elasticsearch, version 7.5.1.

I want to query results which start with a particular word fragment. For example tho* should return data containing:

thought, Thomson, those, etc.

I tried with -

  1. Regexp
[{'regexp':{'f1':'tho.*'}},{'regexp':{'f2':'tho.*'}}]  
  1. Wildcard
[{'wildcard':{'f1':'tho*'}},{'wildcard':{'f2':'tho*'}}]  
  1. Prefix
[{'prefix':{'f1':'tho'}},{'prefix':{'f2':'tho'}}]  
  1. match_phrase
'multi_match': {'query': 'tho', 'fields':[f1,f2,f3], 'type':phrase}  # also tried with type phrase_prefix  

All those are returning correct results, but they all also return the word method.

Similarly cat* is returning the word communication.

What I am doing wrong? Is this something related to analyzer?


Read in browser »
share on Twitter

I can't upload image in wordpress

By duaa hamed on May 24, 2021 07:00 am

when i upload an image in wordpress media library this message appears

post-processing of the image failed likely because the server is busy or does not have enough resources. uploading a smaller image may help. suggested maximum size is 2500 pixels.

i have tried some methods to solve it like increase Maximum upload file size and change php version

I'm using hostGator as a web host .


Read in browser »
share on Twitter




Recent Articles:

Remove Visualizer Menu from Visual Studio
How fix the error 'Exception' when execute yii migrate?
What is role in spring bean?
Python UTC timestamp with ISO format
Twitter
Facebook
Website
Copyright © 2021 reader, All rights reserved.
You are receiving this email because you opted in via our website.

Our mailing address is:
reader
88 CELICA STREET
Davao 8000
Philippines

Add us to your address book


Want to change how you receive these emails?
You can update your preferences or unsubscribe from this list.

Email Marketing Powered by Mailchimp

No comments:

Post a Comment