Monday, April 25, 2022

Recent Questions - Stack Overflow

Recent Questions - Stack Overflow


Scrapy-Selenium: Chrome Driver does not load page

Posted: 25 Apr 2022 01:00 PM PDT

I have two projects, one with Selenium and one using Scrapy-Selenium, which fits into a Scrapy spider program format but uses Selenium for automation.

I can get the Chromedriver to load the page I want for the basic Selenium program, but something about the second project (with Scrapy) prevents it from loading the URL. Instead it's stuck at showing data:, in the URL bar.

First project (works fine):

from selenium import webdriver  from selenium.webdriver.common.keys import Keys  driver = webdriver.Chrome(executable_path="./chromedriver")  driver.get("https://ricemedia.co")  

Second project (doesn't load page):

import scrapy  from scrapy_selenium import SeleniumRequest  from selenium import webdriver  import time    class ExampleSpider(scrapy.Spider):      name = 'rice'        def start_requests(self):          print(13)          yield SeleniumRequest(              url="https://ricemedia.co",              wait_time=3,              callback=self.parse          )        def parse(self, response):          print(20)          driver = webdriver.Chrome(executable_path="./chromedriver")          driver.maximize_window()          time.sleep(20)  

I have browsed StackOverflow and Google, and the two most common reasons are outdated Chrome Drivers and missing http in the URL. Neither is the case for me. The path to chromedriver seems alright too (these two projects are in the same folder, along with the same chromedriver). Since one works and the other doesn't, it should have something to do with my Scrapy-Selenium spider.

Please help, thanks!

react-img-mapper blanck screen

Posted: 25 Apr 2022 01:00 PM PDT

I have a project where i need to map specific areas of an image, for that i'm trying to use react-img-mapper, but when i try to run the example code, the only think that shows is a blanck screen, react do not log any erros. What am i doing wrong ?

import React from 'react';  import ImageMapper from 'react-img-mapper';    const Mapper = props => {    const URL = 'https://raw.githubusercontent.com/img-mapper/react-docs/master/src/assets/example.jpg';    const MAP = {      name: 'my-map',      // GET JSON FROM BELOW URL AS AN EXAMPLE      areas: 'https://raw.githubusercontent.com/img-mapper/react-docs/master/src/assets/example.json',    };        return <ImageMapper src={URL} map={MAP} />  }    export default Mapper;  

Understanding what this xml2 error means: Excessive depth in document: 256 use XML_PARSE_HUGE option

Posted: 25 Apr 2022 01:00 PM PDT

I'm trying to solve this error and I don't know R well enough to even understand what this means let alone how to fix it. I'm webscraping the links from this web search. Could someone explain?

Error in read_xml.raw(raw, encoding = encoding, base_url = base_url, as_html = as_html,  :     Excessive depth in document: 256 use XML_PARSE_HUGE option [1]  

How to read each cell of a column in csv and take each as input for jq in bash

Posted: 25 Apr 2022 12:59 PM PDT

I am trying to read each cell of CSV and treat it as an input for the JQ command. Below is my code:

line.csv | |:---- | | 11 | | 22 | | 33 |

Code to read CSV:

while read line    do       echo "Line is : $line"    done < line.csv  

Output: Line is 11 Line is 22

jq Command

jq 'select(.scan.line == '"$1"') | .scan.line,"|", .scan.service,"|", .scan.comment_1,"|", .scan.comment_2,"|", .scan.comment_3' linescan.json | xargs  

I have a linescan.json which have values for line, service, comment_1, comment_2, comment_3

I want to read each value of csv and treat the input in jq query where $1 is mentioned.

Please advice

I honestly do not know why this won't work

Posted: 25 Apr 2022 12:59 PM PDT

So, I am following a tutorial to make a rock paper scissors game, and I have basically just copy and pasted this part of the code and it won't work. It works for the dude, but not for me. Please help!

    function getComputerChoice() {              const choices = ['c', 'd', 'k'];              console.log(Math.random());          }  

Having trouble getting plotly dash app set up

Posted: 25 Apr 2022 12:59 PM PDT

I'm trying to build a quick interactive app that uses data I've pulled from a few APIs to return a visualization to the user. I'm attempting to use dash to do this and I'm struggling to get the app to actually run. Can someone let me know what I'm doing wrong here?

from dash import Dash, dcc, html  from dash.dependencies import Input, Output    app = Dash(__name__)    app.layout = html.Div([        html.H1('Campaign Advertising Contributions: Supporting and Opposing', style = {'text-align': 'center'}),        dcc.Input(          id = 'cand_name_input',          type = 'text',          placeholder = 'Insert Candidate Name',          debounce = True,          pattern = r"[A-Za-z]",          spellCheck = False,          inputMode = 'latin-name',          name = 'Candidate Name',          n_submit = 0,          n_submit_timestamp = -1,          autoFocus = True,          n_blur = 0,          n_blur_timestamp = -1,          disabled = False,          readOnly = False,          required = True,          size = '30'      ),        dcc.Dropdown(id = 'slct_office',                  options = [                      {'label': 'President', 'value': 'President'},                      {'label': 'Senate', 'value': 'Senate'},                      {'label': 'House', 'value': 'House'}],                  multi = False,                  style = {'width': '40%'}      ),        dcc.Input(          id = 'year_input',          type = 'number',          placeholder = 'Insert Candidate Name',          debounce = True,          min = 2008, max = 2020, step = 2,          minLength = 0, maxLength = 50,          disabled = False,          readOnly = False,          required = True,          size = '30'      ),        html.Div(id='output_container', children=[]),      html.Br(),        dcc.Graph(id='my_visibility_graph', figure={})  ])    if __name__ == '__main__':      app.run_server(debug=True)  

I'm just trying to get an empty page (with my inputs and dropdown) to show up when I go to the http://127.0.0.1:8050/ url but it won't connect.

Make composable wrap content

Posted: 25 Apr 2022 12:59 PM PDT

I am trying to make the ImageComposable along with the two Text composable, align to the bottom of Assemble composable. Following is the code for that:

@Composable  fun ImageComposable(url:String){      val painter = rememberAsyncImagePainter(          model = ImageRequest.Builder(LocalContext.current).data(url).apply{              placeholder(drawableResId = R.drawable.ic_broken_pic)          }.build()      )      Image(painter = painter, contentDescription = null, Modifier.padding(2.dp).border(width = 2.dp, shape = CircleShape, color = MaterialTheme.colors.onPrimary)    }    @Composable  fun Assemble(url:String){      Column (modifier = Modifier.fillMaxWidth().height(400.dp).background(MaterialTheme.colors.primary)          .padding(16.dp), verticalArrangement = Arrangement.Bottom) {          ImageComposable(url)          Text(text = "title")          Text(text = "Body")      }  }  

but the ImageComposable ends up taking all the height and width of the Assemble composable and I am not able to see the two Text composables that I added in the column. So I am confused as to what is the exact problem here. I thought at least it should show the ImageComposable along with the two Text composable but it is not happening.

I am using coil image loading library here for parsing the image from url. For now in testing, I am passing url as an Empty String. Hence I am calling the composable as:
Assemble("")

I didn't find any document that would help me understand this behavior. So I wanted to know the reason to this problem and possible solutions to overcome it.

Is there a way to verify an Antlr input file without running it?

Posted: 25 Apr 2022 12:58 PM PDT

I have the following code taking the input of my input file:

var inputStream = new AntlrInputStream(File.ReadAllText(fileName));  var lexer = new LegitusLexer(inputStream);  var commonTokenStream = new CommonTokenStream(lexer);  var parser = new LegitusParser(commonTokenStream);  parser.AddErrorListener(this);    var context = parser.program();  var visitor = new LegitusVisitor(_io.GetDefaultMethods(), _io.GetDefaultVariables())  {      Logger = _logger  };  visitor.Visit(context);  

But when I call parser.program(), my program runs as it should. However, I need a way to validate that the input file is syntactically correct, so that users can verify without having to run the scripts (which run against a special machine).

Does Antlr4csharp support this easily?

Dataframes not subtracting Python

Posted: 25 Apr 2022 12:58 PM PDT

I have two dataframes with different column names. For some reason when I subtract them, I get NaN for all rows. The error occurs at market_4._data

indicator_stats = [          # Name, Desc, Ticker          ['1 Normal Yield Curve', 'Z Score of 2s10s between -1 and 1', ['USGG2YR Index', 'USGG10YR Index']],          ['2 Low Number of Large Equity Moves','',[('SPX Index','tot_return_index_gross_dvds')]],          ['3 Normal Credit Spreads', 'Z Score of Credit Spreads between -1 and 1', ['CSI BARC Index']],          ['4 Normal Equity to Bond Yield','', [('SPX Index','EARN_YLD'),'USGG10YR Index']]          ]        result_names = ["market_1","market_2","market_3","market_4"]            for var, vals in zip(result_names, indicator_stats):      name, desc, tickers = vals      val = ct.IndicatorCalc(name=name, desc=desc, tickers = tickers)            globals()[var] = val    ....        # Indicator 4. Normal Equity to Bond Yield       market_4._data['eq_rp'] = market_4.data['SPX Index'].asfreq('D').ffill()['SPX Index'] - market_4.data['USGG10YR Index'].asfreq('D').ffill()['USGG10YR Index']      market_4.indicator = ct.z_score(market_4._data['eq_rp'].asfreq('M'),periods=72)      market_4.signal = ct.z_between(market_4.indicator,-1,1)      market.load_influence(market_4)  

the functin IndicatorCalc pulls from Bloomberg, creating a dictionary of SPX's EARN_YLD and USGG10YR's PX_LAST. These successfully pull through, creating a dataframe with columns MultiIndex([('SPX Index', 'EARN_YLD')], names=['ticker', 'field']) and MultiIndex([('USGG10YR Index', 'PX_LAST')], names=['ticker', 'field'])

Could you use C inline assemby to align instructions? (without Compiler optimizations)

Posted: 25 Apr 2022 12:58 PM PDT

So basically I have to do an University project where we have to use cache optimizations to improve the performance of a given code but we must not use compiler optimizations to achieve it.

One of the ideas I had reading bibliography is to align the beginning of a basic block to a line cache size. But can you do something like :

asm(".align 64;")  for(int i = 0; i<N; i++)  ... (whole basic block)  

in order to achieve what I'm looking for? I have no idea if it's possible to do that in terms of instruction alignment, I've seen some trick like _mm_malloc to achieve data alignment but none for instructions. Could anyone please give me some light about the matter?

How to set speed of playermovement in Java 2D platform game

Posted: 25 Apr 2022 12:58 PM PDT

I am following this tutorial on how to create a Java2D platform game. I followed the code precisely, but when I tried to run it, the player moves way too fast when moving left and when jumping and falling compared to when it's moving right.

My player class looks like this:

package Entity;    import TileMap.*;    import java.awt.*;  import java.util.ArrayList;  import javax.imageio.ImageIO;  import java.awt.image.BufferedImage;      public class Player extends MapObject {        // Player stats      private int health, maxHealth, fire, maxFire, fireCost, fireBallDamage, scratchDamage, scratchRange;      private boolean dead, flinching, firing, scratching, gliding;      private long flinchTimer;          // private ArrayList<FireBall> fireballs;      private ArrayList<BufferedImage[]> sprites;        private final int[] numFrames = { 2, 8, 1, 2, 4, 2, 5 };          // Animation actions      private static final int IDLE = 0;      private static final int WALKING = 1;      private static final int JUMPING = 2;      private static final int FALLING = 3;      private static final int GLIDING = 4;      private static final int FIREBALL = 5;      private static final int SCRATCHING = 6;      private int currentAction;        // Constructor      public Player(TileMap tm) {          super(tm);            width = height = 30;          cWidth = cHeight = 20;            moveSpeed = 0.3;          maxSpeed = 1.6;          stopSpeed = 0.4;          fallSpeed = 0.15;          maxFallSpeed = 4.0;          jumpStart = -4.8;          stopJumpSpeed = 0.3;            facingRight = true;            health = maxHealth = 5;          fire = maxFire = 2500;            fireCost = 200;          fireBallDamage = 5;          //fireBalls = new ArrayList<FireBall>();            scratchDamage = 8;          scratchRange = 40;            // Load sprites          try {                BufferedImage spritesheet =                      ImageIO.read( getClass().getResourceAsStream("/Sprites/Player/playersprites.gif"));                sprites = new ArrayList<BufferedImage[]>();                // Loop through animation actions              for (int i = 0; i < 7; i++){                    BufferedImage[] bi = new BufferedImage[numFrames[i]];                    for (int j = 0; j < numFrames[i]; j++) {                      // numFrames[6] = SCRATCH has width = 60                      if (i != 6) {                          bi[j] = spritesheet.getSubimage(j * width, i * height, width, height);                      } else {                          bi[j] = spritesheet.getSubimage(j * width * 2, i * height, width, height);                      }                  }                    sprites.add(bi); // Add BufferedImageArray to animations list              }          } catch (Exception e) { e.printStackTrace(); }            animation = new Animation();          currentAction = IDLE;          animation.setFrames(sprites.get(IDLE));          animation.setDelay(400);      }        // Getters      public int getHealth() { return health; }      public int getMaxHealth() { return maxHealth; }      public int getFire() { return fire; }      public int getMaxFire() { return maxFire; }        // Setters      public void setFiring() { firing = true; }      public void setScratching() { scratching = true; }      public void setGliding(boolean b) { gliding = b; }        private void getNextPosition() {          // Movement          if (left) {              dx -= moveSpeed;              if ( dx < -maxSpeed) { dx = 0; }          } else if (right) {              dx += moveSpeed;              if (dx > maxSpeed) { dx = maxSpeed; }          } else {              if (dx > 0) {                  dx -= stopSpeed;                  if ( dx < 0 ) { dx = 0; }              } else if (dx < 0) {                  dx += stopSpeed;                  if (dx > 0) { dx = 0; }              }          }            // Cannot attack while moving, unless in the air          if ( currentAction == SCRATCHING || currentAction == FIREBALL && !( jumping || falling)) { dx = 0; }            // Jumping          if (jumping && !falling) {              dy += jumpStart;              falling = true;          }          if (falling) {              if ( dy > 0 && gliding) { dy += fallSpeed * 0.1; }              else { dy += fallSpeed; }                if ( dy > 0 ) { jumping = false; }              if ( dy < 0 && !jumping ) { dy += maxFallSpeed; }                if ( dy > maxFallSpeed ) { dy = maxFallSpeed; }          }      }        public void update() {            // Update position          getNextPosition();          checkTileMapCollision();          setPosition(xtemp, ytemp);            // Set animations          if (scratching) {              if (currentAction != SCRATCHING) {                  currentAction = SCRATCHING;                  animation.setFrames(sprites.get(SCRATCHING));                  animation.setDelay(50);                  width = 60;              }          } else if (firing) {              if (currentAction != FIREBALL) {                  currentAction = FIREBALL;                  animation.setFrames(sprites.get(FIREBALL));                  animation.setDelay(100);                  width = 30;              }          } else if (dy > 0) {              if (gliding) {                  if (currentAction != GLIDING) {                      currentAction = GLIDING;                      animation.setFrames(sprites.get(GLIDING));                      animation.setDelay(100);                      width = 30;                  }              } else if (currentAction != FALLING) {                  currentAction = FALLING;                  animation.setFrames(sprites.get(FALLING));                  animation.setDelay(100);                  width = 30;              }          } else if (dy < 0) {               if ( currentAction != JUMPING) {                  currentAction = JUMPING;                  animation.setFrames(sprites.get(JUMPING));                  animation.setDelay(-1);                  width = 30;               }          } else if ( left || right ) {              if ( currentAction != WALKING) {                  currentAction = WALKING;                  animation.setFrames(sprites.get(WALKING));                  animation.setDelay(40);                  width = 30;              }          } else {              if ( currentAction != IDLE) {                  currentAction = IDLE;                  animation.setFrames(sprites.get(IDLE));                  animation.setDelay(400);                  width = 30;              }          }          animation.update();            // Set direction          if ( currentAction != SCRATCHING && currentAction != FIREBALL) {              if ( right) { facingRight = true; }              if ( left ) { facingRight = false; }          }      }        public void draw(Graphics2D g) {            setMapPosition();            // Draw player          if (flinching) {              long elapsed = (System.nanoTime() - flinchTimer) / 1000000;              if (elapsed / 100 % 2 == 0) { return; } // Gives the appearance of blinking          }            if (facingRight) {              g.drawImage(animation.getImage(), (int) (x + xmap - width/2), (int) (y + ymap - height/2), null);          } else {              g.drawImage(animation.getImage(), (int) (x + xmap - width/2 + width), (int) (y + ymap - height/2),                                                       -width, height, null);          }      }  }  

I tried changing

private void getNextPosition() {          // Movement          if (left) {              dx -= moveSpeed;              if ( dx < -maxSpeed) { dx = -maxSpeed; }  

to

private void getNextPosition() {          // Movement          if (left) {              dx -= moveSpeed;              if ( dx < -maxSpeed) { dx = 0; }  

Which helped for the left-movement, but it created a lag in the graphics, so I tried changing theAnimation-class which looks like this:

package Entity;    import java.awt.image.BufferedImage;    public class Animation {        private BufferedImage[] frames;      private int currentFrame;        private long startTime, delay;        private boolean playedOnce;        public void Animation() {          playedOnce = false;      }        public void setFrames(BufferedImage[] frames) {          this.frames = frames;          currentFrame = 0;          startTime = System.nanoTime();          playedOnce = false;      }        public void setDelay(long d) { delay = d; }      public void setFrame(int i) { currentFrame = i; }        public void update() {          if (delay == -1) { return; }            long elapsed = (System.nanoTime() - startTime) / 1000000;          if (elapsed > delay) {              currentFrame++;              startTime = System.nanoTime();          }            if (currentFrame == frames.length) {              currentFrame = 0;              playedOnce = true;          }      }        public int getFrame() { return currentFrame; }      public BufferedImage getImage() { return frames[currentFrame]; }      public boolean hasPlayedOnce() { return playedOnce; }  }  

Which I thought was where I could fix the problem, but I am uncertain as I am new to gamelogic. Is there any way I can slow down the movement of the player? All help is appreciated!

How to extract all column and value from pyspark row?

Posted: 25 Apr 2022 12:58 PM PDT

i am trying to extract all columns and value respectively from the below data frame row?

+--------+----------+-----+----+-----+-----------+-------+---+  |name    |department|state|id  |name | department| state | id|  +--------+----------+-----+----+-----+-----------+-------+---+  |James   |Sales     |NY   |101 |James|  Sales1   |null   |101|   row=  [Row(name=James,department=Sales,state=NY,id=101,name=James,department=Sales1,state=None,id=101)]    tem_dict={}  for indext,value in enumerate(row):      if row[index] in tem_dict:           tem_dict[row[index]]=[row[index], value]      else:          tem_dict[row[index]]=value    

But this not giving expected result. since it has repeated element i want to combine the value of similar column and print it in a array as seen below

#expected

[{name:[james,james],departement:[Sales,Sales1],state:[NY,none],id:[101,101]}]  

Any solution to this?

Pandas: If condition on multiple columns having null values and fillna with 0

Posted: 25 Apr 2022 01:00 PM PDT

I have a below dataframe, and my requirement is that, if both columns have np.nan then no change, if either of column has empty value then fill na with '0' value. I wrote this code but why its not working. Please suggest.

import pandas as pd  import numpy a np    data = {'Age': [np.nan, np.nan, 22, np.nan, 50,99],          'Salary': [217, np.nan, 262, 352, 570, np.nan]}  df = pd.DataFrame(data)  print(df)    cond1 = (df['Age'].isnull()) & (df['Salary'].isnull())  if cond1 is False:      df['Age'] = df['Age'].fillna(0)      df['Salary'] = df['Salary'].fillna(0)    print(df)  

Update object in array using useState and a button

Posted: 25 Apr 2022 12:59 PM PDT

I have a list of users That I want to maintain, I was able to delete a user from the list and add a new user to the list, But I can not update an existing user.

import {useState} from 'react'

const ChildComp = ()=> { const [users,setUsers] = useState([{name:"Leanne " ,age : "40", city : "Gwenborough",}, {name:"Ervin " ,age : "35", city : "Wisokyburgh",}, {name:"Clementine " ,age : "22", city : "McKenziehaven",}])

const [user,setUser] = useState({name : "" , age : 0, city :""})  const [deletUser,setDeletUser] = useState ("")        const deletMe =() =>  {      let array = [...users]      let index = array.findIndex(item=>item.name===deletUser)          if (index!==-1)      {          array.splice(index,1)          setUsers(array)      }  }    const Update = (e) =>  {                let array = [...users]      let index = array.findIndex(item=>item.name===deletUser)          if (index!==-1)      {          array.splice(index,1)          setUsers(array)          setUsers([...users,user])               }          }      return(<div>      <h1>add user  </h1>        Name :  <input type ="text" onChange = {e=> setUser({...user,name:e.target.value})}/><br/>      Age :  <input type ="text" onChange = {e=> setUser({...user,age:e.target.value})}/><br/>      City :  <input type ="text" onChange = {e=> setUser({...user,city:e.target.value})}/><br/>        <input type = "button" value ="Add" onClick ={e=>setUsers([...users,user])}/>      <input type ="button" value = "Update" onClick = {Update}/><br/>        <h3>Delet user  </h3>        <input type = "text" name = "dleteUser" onChange = {e=>setDeletUser(e.target.value)}/>      <input type ="button" value = "DELET" onClick = {deletMe}/><br/>            <table border = "1">     {users.map((item,index) =>     {         return <tr key = {index}>             <td > {item.name}  </td>             <td > {item.age}  </td>             <td > {item.city}  </td>         </tr>     })}     </table>           </div>      )  

} export default ChildComp;

Some trouble with learning Swift

Posted: 25 Apr 2022 01:00 PM PDT

below is what I'm trying to do. I keep getting Overriding declaration requires an 'override' keyword error and Expected expression in list of expressions even tho I'm sure I don't need the override keyword for override an init method, I just tested it out, someone can help?

import Cocoa    ///The challenge is this: make a class hierarchy for animals, starting with Animal at the top,  ///then Dog and Cat as subclasses, then Corgi and Poodle as subclasses of Dog,  ///and Persian and Lion as subclasses of Cat.  ///But there's more:  ///The Animal class should have a legs integer property that tracks how many legs the animal has.  ///The Dog class should have a speak() method that prints a generic dog barking string,  ///but each of the subclasses should print something slightly different.  ///The Cat class should have a matching speak() method, again with each subclass printing something different.  ///The Cat class should have an isTame Boolean property, provided using an initializer.      class Animal{      let legs: Int            init(legs: Int) {          self.legs = legs      }        }    class Dog: Animal{      func speak() -> Void {          print("bauBauBau")      }      init() {          super.init(legs: 4)      }  }  final class Corgi: Dog{      override func speak(){          print("bauLoveBau")      }      super.init(legs: 4)          }  final class Poodle: Dog{      override func speak(){          print("bauMoreLoveBau")      }      super.init(legs: 4)    }    class Cat: Animal{      var isTame: Bool            func speak() -> Void {          print("miaoMiaoMiao")      }      init(legs: Int, isTame: Bool) {          super.init(self.legs: legs)          self.isTame = isTame      }          }  final class Persian: Cat{      override func speak(){          print("miaoMaisMiao")      }      init(legs: Int, isTame: Bool) {          super.init(super.legs: legs)          super.isTame = isTame      }  }  final class Lion: Cat{      override func speak(){          print("miaoImBetterThanYouMiao")      }      init(legs: Int, isTame: Bool) {          super.init(super.legs: legs)          super.isTame = isTame      }  }  

get first value from each group of 2 columns

Posted: 25 Apr 2022 12:59 PM PDT

My dataset df looks like this:

main_id    time               day        1          2019-05-31         1          1          2019-06-30         1          1          2019-05-30         2    2          2018-05-30         1  

I want to create a new df df_time that contains a new column giving the very first value from each combination of main_id and day. For example, the output here could look like this:

main_id     day      first_occuring_time  1           1        2019-05-31  1           2        2019-05-30  2           1        2018-05-30  

How to I make the select drop down show the currently selected value in Vue?

Posted: 25 Apr 2022 12:59 PM PDT

Similar to Select always first value select vue.js but I am making a custom component.

I have an SFC with a few extra debug output

<script>  export default {    props: ['modelValue', 'options'],    emits: ['update:modelValue']  }  </script>    <template>    <div>          <select      :value="modelValue"      @change="$emit('update:modelValue', JSON.parse($event.target.value))"    >      <option value="" disabled>no selection</option>      <option v-for="option in options" :value="JSON.stringify(option)" :selected="JSON.stringify(modelValue) === JSON.stringify(option)">X{{JSON.stringify(option)}}X{{JSON.stringify(modelValue) === JSON.stringify(option)}}</option>    </select>       {{modelValue}}    </div>  </template>  

And a calling component

<script>  import CustomInput from './CustomInput.vue'    export default {    components: { CustomInput },    data() {      return {        message: '',        blah: [          {a:"a"},          {b:2},          {c:{d:1}},        ]      }    },    computed: {          theMessage() {        return JSON.stringify(this.message);      }  }  }  </script>    <template>    <CustomInput v-model="message" :options="blah"/> {{ theMessage }}  </template>  

But I am not able to get the selected item to appear in the dropdown even if the "label" is showing it should be selected.

Playground

How can i read this particular json which has a number as a key in php? [duplicate]

Posted: 25 Apr 2022 01:00 PM PDT

Please see json below

{    "id": "1",    "name": "john",    "data": {      "1": {        "amount": "9000",        "slip": "/image'/loidsds.jpg"      },      "method": "pump"    }  }  

I am trying to read amount and slip how can i manage to do this is PHP ?

I have tried the following

$object->data->1->amount and $object->data->1->slip

I got some errors please help me find an alternative

How to calculate minutes passed since given date

Posted: 25 Apr 2022 01:00 PM PDT

I have a dataframe that has a column named Created_Timestamp. I want to see how many minutes passed since that given date. I want to know dwell time in minutes from the column Created_Timestamp.

 Created_Timestamp          Dwell Time   2022-04-25 00:33:33.482      842 min    2022-04-25 08:30:52.904      364 min    2022-04-25 12:11:04.624      144 min  

Dwell Time will be from current time.

curtime = dt.now()  df['Dwell Time'] = curtime - df['Created_Timestamp']  

This did not work as I intended. How can I do this correctly?

Djoser "Password Changed Confirmation" Email Not Sending

Posted: 25 Apr 2022 12:59 PM PDT

Good day,

I have successfully overwritten 3 of the default Djoser templates and can receive those emails, but I can't get the "Password Changed Confirmation" email to send.

According to djoser/conf.py, djoser/email.py, and djoser/templates/email it appears I am doing everything correctly. But it's not obvious why this one isn't sending as there are no errors being raised.

The project directory has these relevant files and paths:

project    - core      - email.py      - settings.py    - templates      - email        - activation.html                    # works        - confirmation.html                  # works        - password_changed_confirmation.html # does not work        - password_reset.html                # works  

settings.py was set as per the Djoser docs.

DJOSER = {      'LOGIN_FIELD': 'email',      'USER_CREATE_PASSWORD_RETYPE': True,      'SET_PASSWORD_RETYPE': True,      'SEND_ACTIVATION_EMAIL': True,      'ACTIVATION_URL': 'activate/{uid}/{token}',      'SEND_CONFIRMATION_EMAIL': True,      'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}',      # I set this to True as per the docs:      'PASSWORD_CHANGED_EMAIL_CONFIRMATION:': True,      'USERNAME_RESET_SHOW_EMAIL_NOT_FOUND': True,      'PASSWORD_RESET_SHOW_EMAIL_NOT_FOUND': True,      'SERIALIZERS': {          'user_create': 'users.serializers.UserCreateSerializer',          'user': 'users.serializers.UserCreateSerializer',      },      'EMAIL': {          # These 3 templates send:          'activation': 'core.email.ActivationEmail',          'confirmation': 'core.email.ConfirmationEmail',          'password_reset': 'core.email.PasswordResetEmail',          # This one does not:          'password_changed_confirmation': 'core.email.PasswordChangedConfirmationEmail',      }  }  

In email.py I create my custom class to reference the template. The print statements don't even fire so I don't think this is even getting called.

from djoser import email    # Override the default Djoser confirmation email.  class PasswordChangedConfirmationEmail(email.PasswordChangedConfirmationEmail):      template_name = 'email/password_changed_confirmation.html'        def send(self, to, *args, **kwargs):          print(f"Sending password changed mail to {to}")          try:              super().send(to, *args, **kwargs)          except:              print(f"Couldn't send mail to {to}")              raise          print(f"Password changed mail sent successfully to {to}")  

Sending a reset password POST request yields the following (expected) messages in the console:

Sending password reset mail to ['someone@somewhere.com']  Password reset mail sent successfully to ['someone@somewhere.com']  [25/Apr/2022 13:53:56] "POST /api/v1/users/reset_password/ HTTP/1.1" 204 0  

I then go to the URL it provides and send a POST request with the provided uid and token successfully to the reset_password_confirm end-point.

[25/Apr/2022 14:13:33] "POST /api/v1/users/reset_password_confirm/ HTTP/1.1" 204 0  

I can successfully change the password, but there aren't any print statements from that PasswordChangedConfirmationEmail class and no email received.

What am I doing wrong here?

Any help would be appreciated, thank you.

React bootstrap responsive layout

Posted: 25 Apr 2022 12:58 PM PDT

I try to have sidebar on left and in center main.js I get this on desktop, but in mobile the main.js just disappear.

div style={{  backgroundImage:  "url(" + "/sasa.jpg" + ")",   backgroundRepeat: "no-repeat",  backgroundSize: 'cover',  display: "flex",  float: "left"}}>    <Col md={2} xs={8}>    <Aside  setValue={setValue}  />      </Col>  <Col md={2}>      </Col>        <Col md={8} xs={12}>  <Main data={value}/>      </Col>      </div>  

how to have one under one element on mobile using this sm, XS, etc stuff?

Make copy of Google Spreadsheet on google shared drives via apps script

Posted: 25 Apr 2022 12:59 PM PDT

This code make a copy of the given file, gives it a new name and moves it to destination.

DriveApp.getFileById(fileId).makeCopy(fileName,fileDestination)  

How can I have the same function when I have all my files on Shared Drive? I have activated the Drive API and everything works fine except the code above!

Azure AD login automatically for a specific user

Posted: 25 Apr 2022 01:00 PM PDT

I'm in the process of migrating an ASP.Net MVC app from windows authentication to Azure AD Authentication.

One of the requirements of the app is that some parts of it are accessed on a kiosk in a warehouse and it should auto-login to the web app. With windows authentication and the correct internet settings we can use the domain user to login without any prompt and the kiosk is then authenticated and has some specific roles to access only the parts of the app we`re interested in.

Is it possible to achieve the same result using Azure AD authentication, as in have a user logged in to a local AD, possibly to azure AD via powershell, automatically be logged in to an ASP.Net MVC app that uses Azure AD for authentication without any prompt?

I'm looking at any way to achieve the result of no login prompt for the kiosk user which is both in the local AD and azure AD.

Thanks

Regex validate PIN Codewars

Posted: 25 Apr 2022 01:00 PM PDT

For this Codewars challenge, I cannot understand why the logic is not working. I've found other solutions, but would like to understand why this is not working:

ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything but exactly 4 digits or exactly 6 digits.

If the function is passed a valid PIN string, return true, else return false.

function validatePIN (pin) {        const splitPin = pin.toString().split('')    const finalArr = [];      for (let i = 0; i < splitPin.length; i++){        if (!Number.isInteger(pin[i])){      return false;    } else if (Number.isInteger(pin[i])){      finalArr.push(pin[i]);    }  }    if(finalArr.length === 4 || finalArr.length === 6){      console.log(finalArr.length)      return true;    }       }  

ENMTML: "error in evaluating the argument 'object' in selecting a method for function 'coef': variable lengths differ"

Posted: 25 Apr 2022 12:58 PM PDT

I am working in environmental niche modelling (ENM) for 3 species on the R package ENMTML (https://github.com/andrefaa/ENMTML), it is off-CRAN.

Description of objets:

  • envt is a directory path to a folder with 19 bioclimatic (.asc) variables, directly from Worldclim website cutted to the study area
  • occ_t1 is a directory path to a tab delimited text file of three columns with species name, longitude, and latitude data. Example of .txt (firts rows): enter image description here

My lines of code were:

ENMTML(    pred_dir = envt,  proj_dir = NULL,  occ_file = occ_t1,   sp= 'species',  x= 'x',   y='y',  min_occ = 20,  thin_occ = NULL,  eval_occ = NULL,  colin_var = c(method= 'PCA'),  imp_var = TRUE,  sp_accessible_area = c(method='BUFFER', type= '1'),  pseudoabs_method = c(method= 'ENV_CONST'),  pres_abs_ratio= 1,  part = c(method='BOOT', replicates= '1', proportion= '0.7'),   save_part = FALSE,   save_final = TRUE,  algorithm = c('SVM', 'RDF', 'MXD'),  thr= c(type= 'MAX_KAPPA'),  msdm=NULL,   ensemble= c(method='PCA'),  extrapolation=FALSE  )    Checking for function arguments ...  Loading environmental variables ...  RasterBrick successfully created!  Performing a reduction of variables collinearity ...  Warning in if (tolower(e) %in% c(".tiff", ".tif")) { :    the condition has length > 1 and only the first element will be used  Loading and processing species occurrence data ...  Results can be found at:    C:/Users/Result  Generating masks for species acessible area  ...  Performing partition of species occurrence data ...  Total species to be modeled 3  Fitting Models....  Error in { :     task 1 failed - "error in evaluating the argument 'object' in selecting a method for function 'coef': variable lengths differ (found for 'data')"  

Can anyone help me? I have no idea how to resolve this error.

Error in { : task 1 failed - "error in evaluating the argument 'object' in selecting a method for function 'coef': variable lengths differ (found for 'data')"

Thank you very much! Regards

I'm trying to get JFrame to work, but it keeps popping up with a error saying "Could not find or load main class"

Posted: 25 Apr 2022 12:59 PM PDT

I'm trying to get into learning JFrames and I was just following a tutorial, when I was done and tried running VS code said my build failed and then came up with the error "Could not find or load main class"

    import javax.swing  import javax.swing.JFrame;  import javax.swing.plaf.DimensionUIResource;    import java.awt.*;    public class wagwag {            private static void woah(){            JFrame frame = new JFrame("simple GUI");          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            JLabel text = new JLabel("I am the label", SwingConstants.CENTER);          text.setPreferredSize(new Dimension(300,100));          frame.getContentPane().add(text, BorderLayout.CENTER);            frame.setLocationRelativeTo(null);          frame.pack();          frame.setVisible(true);      }      public static void main(String[] args) {          woah();      }  }  

There's the whole code that I have written down. I know that the naming is dumb, but I just wanted to see if I could get JFrame to actually work lol.

MIN Vs MAX function in SQL

Posted: 25 Apr 2022 01:00 PM PDT

I am running below two queries but the run time is quite different for both. Could you please advise where it is going wrong.

Below query is giving output in less than 20 secs

select MAX(last_mod_date) last_mod_date  from dbo.raw  where prog_id like '198.A-2006%'  and dp_cat='SCIENCE'  

Below query is giving output in 5-7 mins (sometimes more than 10 mins)

select MIN(last_mod_date) last_mod_date  from dbo.raw  where prog_id like '198.A-2006%'  and dp_cat='SCIENCE'  

I tried doing update stats, reorg index which is on the column last_mod_date. But I don't see any benefit from these actions. Please find the attached execution plan of MIN query.enter image description here

How can I scale all images to the same dimensional area?

Posted: 25 Apr 2022 12:59 PM PDT

I'm loading in several images. They are various lengths and widths, but I would like for them all to feel as though they are the same "size". So, if one image is 200x100 and another image is 200x400, I would like for them both to scale in such a way that they take up the same amount of space on the screen. If I fix the width to be 200, then the second element is 4 times the size of the first.

For example:

.my_img {      width: 200px;  }  

produces this behavior

How can I use css to fix the area of an image or other element? Where by area, I mean literally length times width. I would like to load in an image of arbitrary dimensions, and scale it (preserving aspect ratio) so that its area is fixed to be a given value.

Running nltk.download in Azure Synapse notebook ValueError: I/O operation on closed file

Posted: 25 Apr 2022 12:59 PM PDT

I'm experimenting with NLTK in an Azure Synapse notebook. When I try and run nltk.download('stopwords') I get the following error:

ValueError: I/O operation on closed file  Traceback (most recent call last):      File "/home/trusted-service-user/cluster-env/env/lib/python3.6/site-packages/nltk/downloader.py", line 782, in download      show(msg.message)      File "/home/trusted-service-user/cluster-env/env/lib/python3.6/site-packages/nltk/downloader.py", line 775, in show      subsequent_indent=prefix + prefix2 + " " * 4,      File "/mnt/var/hadoop/tmp/nm-local-dir/usercache/trusted-service-user/appcache/application_1616860588116_0001/container_1616860588116_0001_01_000001/tmp/9026485902214290372", line 536, in write      super(UnicodeDecodingStringIO, self).write(s)    ValueError: I/O operation on closed file  

If I try and just run nltk.download() I get the following error:

EOFError: EOF when reading a line  Traceback (most recent call last):      File "/home/trusted-service-user/cluster-env/env/lib/python3.6/site-packages/nltk/downloader.py", line 765, in download      self._interactive_download()      File "/home/trusted-service-user/cluster-env/env/lib/python3.6/site-packages/nltk/downloader.py", line 1117, in _interactive_download      DownloaderShell(self).run()      File "/home/trusted-service-user/cluster-env/env/lib/python3.6/site-packages/nltk/downloader.py", line 1143, in run      user_input = input("Downloader> ").strip()    EOFError: EOF when reading a line  

I'm hoping someone could give me some help on what may be causing this and how to get around it. I haven't been able to find much information on where to go from here.

Edit: The code I am using to generate the error is the following:

import nltk  nltk.download('stopwords')  

Update I ended up opening a support request with Microsoft and this was their response:

Synapse does not support arbitrary shell scripts which is where you would download the related model corpus for NLTK

They recommended I use sc.addFile, which I ended up getting to work. So if anyone else finds this, here's what I did.

  1. Downloaded the NLTK stopwords here: http://nltk.org/nltk_data/
  2. Upload the stopwords to the follwoing folder in storage: abfss://<file_system>@<account_name>.dfs.core.windows.net/synapse/workspaces/<workspace_name>/nltk_data/corpora/stopwords/
  3. Run the below code to import them

.

import os  import sys  import nltk  from pyspark import SparkFiles    #add stopwords from storage  sc.addFile('abfss://<file_system>@<account_name>.dfs.core.windows.net/synapse/workspaces/<workspace_name>/nltk_data/',True)    #append path to NLTK  nltk.data.path.append(SparkFiles.getRootDirectory() + '/nltk_data')    nltk.corpus.stopwords.words('english')  

Thanks!

"Invalid remote: origin" error when importing to Eclipse (m2eclipse, eGit)

Posted: 25 Apr 2022 01:00 PM PDT

In Eclipse when I try to import a project from a repository (File > Import > Maven > Check out Maven Projects from SCM) I select 'git' (eGit installed), fill in the ssh://... address (all the keys and access permissions are set), finally type in the password for rsa and...

Invalid remote: origin: Invalid remote: origin  

According to this: http://youtrack.jetbrains.com/issue/IDEA-77239 writing .git at the end of address should solve the problem but actually it does not.

I have totally no idea how to resolve it further. Any ideas?

Edit: And I use Windows. It seems like an important piece of information to add.

No comments:

Post a Comment