Open url contents on click of a tab in same tab pane

I am a beginner in web development. I am working on a small project which needs to open a url(something like http://192.168.1.107:8080) content on click of a tab, in the same tab pane. The mentioned url is a client, which displays some runtime data(eg: temperature) continuously.

I could find some code snippets on creating tabs, but I’m keen to get this specific requirement working.

I would appreciate any code snippets, links or information on displaying a url data in same tab pane please.

thanks

In Chromium browsers React data table, right side columns flicker on a small screen or resizing a browser

I am using the Npm package React data grid https://github.com/adazzle/react-data-grid to bind data.

Issue example
https://codesandbox.io/s/react-data-grid-example-9sb93?file=/src/App.tsx

In a small screen size system or resizing the browser, the right side of the columns started flickering.

Table column flickering only comes in chromium-browser

Does anyone have a solution?

need to convert class component to function component

I am new to react native I have uploaded the whole code here I needĀ help to convert this class component to a function component, thanks in advance.

import React, { Component, Fragment } from "react";
import {
  TouchableOpacity,
  Text,
  View,
  KeyboardAvoidingView,
  Modal,
  TextInput,
  Platform,
  Keyboard,
  Dimensions,
  ScrollView,
  StatusBar,
  SafeAreaView,
} from "react-native";
import QRCodeScanner from "react-native-qrcode-scanner";
import styles from "./scanStyle";
import AppStore from "../../stores/AppStore";
import { handleScreenNavigation } from "../../utils/NavigationService";
import Theme from "../../utils/Theme";
import LinearGradient from "react-native-linear-gradient";
import CardView from "react-native-cardview";
import Scanstore from "../../stores/Scanstore";
import Toast from 'react-native-simple-toast';
import { Screen } from "../../components/common/Screen";
import { UniversalNavigationHeader } from "../../components/common/NavigationHeader";
import Iconpack from "../../utils/Iconpack";
// import { ScrollView } from "react-native-gesture-handler";

const hRem = AppStore.screenHeight / 812;
const wRem = AppStore.screenWidth / 375;


const STATUSBAR_HEIGHT = StatusBar.currentHeight;

const totp = require("totp-generator");

let b32_regex = /^[a-zA-Z2-7]+=*$/;



class Scan extends Component {
  constructor(props) {
    super(props);
    this.state = {
      scan: false,
      ScanResult: false,
      result: null,
      isShow: false,
      textName: "",
      secretKey: "",
      backupCode: "",
      isBackUpCode: true,
      textInputHighlight: null,
      textInputHighlight2: null,
      textInputHighligh3: null,
      value: "",
      height: 0,
      updateHeightSecretKey: 0,
      platformUri:"",
      styleChange:false,
      keyboardState: 'closed'
    };
  }

  componentDidMount() {
    if(this.props.route.params.edit){
    //   console.log("Appstore.userPin*******************",   this.props.route.params.index,
    //   this.props.route.params.edit,
    //  this.props.route.params.otpFrom,
    //   this.props.route.params.backUpCode,
    //   this.props.route.params.friendlyName)
      this.setState({  secretKey:this.props.route.params.secretKey,
        platformUri :this.props.route.params.otpFrom,
        textName : this.props.route.params.friendlyName ,
        backupCode :  this.props.route.params.backUpCode,
        isBackUpCode: this.props.route.params.backUpCode.length>0?false:true,
        isShow:true
      })
    }
  
    // this.setState({ isShow: true, secretKey: "fsdfsfsf",platformUri:"fdsfsffs" });

    //let data = base32.decode("otpauth://totp/Google%3Arakesh.s%40catalystmedia.io?secret=tqskd2aiylctmid2vzi4lirnuhbshqem&issuer=Googlethe");
    // Keys provided must be base32 strings, ie. only containing characters matching (A-Z, 2-7, =).
    // var hotp = require('hotp')
    // var key = 'tqskd2aiylctmid2vzi4lirnuhbshqem'
    // var counter = 0
    // var tokenhotp = hotp(key, counter, { digits: 6 })
    // // var tokentotp = hotp.totp( key, { digits: 6 })//converting hotp to totp
    // // console.log("totp same---> ", tokentotp)
    // console.log("hotp same ---> ", tokenhotp)
    // console.log("totp diff--->", token);
    // // this.otpList()
    // AppStore.incrementCount()
  }

  componentWillUnmount () {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  componentWillMount () {
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
  }

  _keyboardDidShow = () => {
    this.setState({
        keyboardState: 'opened'
    });
  }

  _keyboardDidHide = () => {
    this.setState({
        keyboardState: 'closed',
        styleChange:false

    });
    console.log("console,console")
  }

  handleCreate = () => {
    console.log(this.state.secretKey,"---------------->",b32_regex.exec(this.state.secretKey))
    if((this.state.secretKey.length>0) && (b32_regex.test(this.state.secretKey) && (this.state.secretKey.length % 8) === 0) ){
      // console.log("----->",AppStore.secretKeyAdded)
      if (AppStore.secretKeyAdded){

        Scanstore.addNewKeyAuthenticator(
          this.state.secretKey,
          this.state.platformUri !== undefined ?this.state.platformUri:"",
          this.state.textName,
          this.state.backupCode
        );
      } else {
        
        Scanstore.setKeyAuthenticator(
          this.state.secretKey,
          this.state.platformUri !== undefined ?this.state.platformUri:"",
          this.state.textName,
          this.state.backupCode
        );
      }
      Scanstore.fetchSecretKeyArray();
    }
    

    else if(this.state.secretKey.length===0){
      // console.log("enter valid")
      Toast.show("Please enter the Secret Key", Toast.LONG);
    }
    else{
      Toast.show("Please enter valid Secret Key", Toast.LONG);
    }

  };

  updateSize = (height) => {
    this.setState({
      height,
    });
  };

  updateSizeSecretKey = (updateHeightSecretKey) => {
    this.setState({
      updateHeightSecretKey,
    });
  };

  bottomModal = () => {
    return (
      <View style={styles.modalStyle}>
        
        <LinearGradient
          start={{ x: 0, y: 0.3 }}
          end={{ x: 0, y: 1.2 }}
          colors={["#020A13", "#000000"]}
          style={styles.modalContent}
        >
        
          <TouchableOpacity
            onPress={() => this.setState({ isShow: false })}
            style={styles.topBar}
          />

<View style={{height: this.state.styleChange ? 200 :"100%",paddingHorizontal:20 }} >
  <ScrollView>
          <CardView
            cardElevation={8}
            cardMaxElevation={2}
            cornerRadius={15}
            style={[
              {
                shadowColor: this.state.textInputHighlight,
              },
              styles.friendlyNameCard,
            ]}
          >
            <TextInput
              style={[styles.input, styles.mod0]}
              placeholderTextColor={Theme.white_color}
              onFocus={() => {
                this.setState({
                  textInputHighlight: Theme.hightLightColor,
                  textInputHighlight2: null,
                  textInputHighligh3: null,
                  styleChange:true
                });
              }}
              onBlur={()=>{
                this.setState({styleChange:false})
              }}
              onChangeText={(value) => {
                this.setState({ textName: value });
              }}
              onSubmitEditing={Keyboard.dismiss}
              value={this.state.textName}
              placeholder={"Friendly Name"}
            />
          </CardView>

          <CardView
            cardElevation={8}
            cardMaxElevation={2}
            cornerRadius={15}
            style={[
              {
                shadowColor: this.state.textInputHighlight2,
              },
              styles.secretKeyStyle,
            ]}
          >
            <TextInput
              style={[
                styles.input,
                {
                  maxHeight: Platform.OS == "android" ? 76 : 44,
                  height:Platform.OS == "android"?this.state.updateHeightSecretKey :44,
                },
              ]}
              placeholderTextColor={Theme.white_color}
              editable={true}
              multiline={true}
              onFocus={() => {
                this.setState({
                  textInputHighlight2: Theme.hightLightColor,
                  textInputHighlight: null,
                  textInputHighligh3: null,
                  styleChange:true
                });
              }}
              onChangeText={(value) => {
                this.setState({ secretKey: value });
              }}
              onContentSizeChange={(e) =>
                this.updateSizeSecretKey(e.nativeEvent.contentSize.height)
              }
              value={this.state.secretKey}
              onSubmitEditing={Keyboard.dismiss}
              placeholder={"Secret Key"}
            />
          </CardView>

          {this.state.isBackUpCode ? (
            <TouchableOpacity
              style={styles.backUp}
              onPress={() => {
                this.setState({ isBackUpCode: false });
              }}
            >
              <Text style={[styles.backUpText,{marginLeft:10 }]}>Want to add Backup Codes?</Text>
            </TouchableOpacity>
          ) : (
            <View style={styles.backUp}>
              <Text
                style={{ ...Theme.encodeSansReg15, color: Theme.white_color,marginLeft:10 }}
              >
                Enter Backup Codes
              </Text>
              <CardView
                cardElevation={8}
                cardMaxElevation={2}
                cornerRadius={15}
                style={[
                  {
                    shadowColor: this.state.textInputHighligh3,
                  },
                  styles.backUpCodeStyle,
                ]}
              >
                <TextInput
                  style={[
                    styles.input,
                    {
                      maxHeight: Platform.OS == "android" ? 102 : 70,
                      height:Platform.OS == "android"?this.state.height: 70,
                    },
                  ]}
                  placeholderTextColor={Theme.white_color}
                  editable={true}
                  multiline={true}
                  onFocus={() => {
                    this.setState({
                      textInputHighligh3: Theme.hightLightColor,
                      textInputHighlight: null,
                      textInputHighlight2: null,
                      styleChange:true
                    });
                  }}
                  onChangeText={(value) => {
                    this.setState({ backupCode: value });
                  }}
                  onContentSizeChange={(e) =>
                    this.updateSize(e.nativeEvent.contentSize.height)
                  }
                  onSubmitEditing={Keyboard.dismiss}
                  value={this.state.backupCode}
                  placeholder={"Backup Code"}
                />
              </CardView>
            </View>
          )}
<View style={{flexDirection:"row", justifyContent:"space-around",alignItems:"center",marginTop:40,marginBottom:AppStore.isAndroid?20:0}}>
          <TouchableOpacity
            style={styles.createButton}
            onPress={() => {
              if(this.props.route.params.edit){

                Scanstore.editElement( 
                  this.props.route.params.index ,
                  this.state.secretKey,
                  this.state.platformUri ,
                  this.state.textName ,
                  this.state.backupCode 
              )
              this.setState({ isShow: false, styleChange:false });
              Scanstore.fetchSecretKeyArray();
              Toast.show("Updated Successfully.", Toast.LONG);

              }
              else{
                this.handleCreate();
                this.setState({ isShow: false, styleChange:false });
              }
              


            }}
            // onLongPress={() => this.setState({ scan: false })}
          >
            <Text style={[styles.tapText, { fontWeight: "600" }]}>{this.props.route.params.edit?"Update":"Create"}</Text>
          </TouchableOpacity>

          <TouchableOpacity
            // style={{ marginTop: 25 }}
            
            onPress={() => 
              {this.setState({ isShow: false, styleChange:false }) 
          console.log("87887787")
            }
          }
            onLongPress={() => this.setState({ scan: false })}
          >
            <Text style={styles.cancelButton}>Cancel</Text>
          </TouchableOpacity>
         </View>
         </ScrollView>

         </View>
        </LinearGradient>
    
      </View>
    );
  };

  onSuccess = (e) => {
    const check = e.data.substring(0, 7);
    console.log("check", check);
    console.log("scanned data ->    " + e.data + "      the whole bunch of data -> ");
    let fetchedData = e.data;
    let secretKey,platformUri;
    if (fetchedData.includes("totp")) {
      secretKey = fetchedData.split("=");
      platformUri = secretKey[2]
      console.log("------------", secretKey);

      secretKey = secretKey[1].split("&");

      // const totpGen = ;
      // let lengthId = AppStore.rData.length;

      // AppStore.addTotp({
      //   id: lengthId,
      //   title: secretKey[0],
      //   otpFrom:platform,
      // });
    }

    // console.log("what the hell", AppStore.deviceIdInfo);

    this.setState({
      result: e,
      scan: false,
      ScanResult: true,
    });
    if (e.data.includes("totp") ) {
      // handleScreenNavigation("OtpScreen", {})
      this.setState({ isShow: true, secretKey: secretKey[0],platformUri:platformUri });
    }
    else if(e.data.includes("hotp")) {
      Toast.show("Something went wrong", Toast.LONG);

    } else {
      Toast.show("Please scan valid QR", Toast.LONG);
handleScreenNavigation("MainAdd")
    }
  };

  scanAgain = () => {
    this.setState({ scan: true, ScanResult: false });
  };

  render() {
    const { height } = this.state;

    let newStyle = {
      height,
    };
    let newStyleSecretKey = {
      height,
    };
    return (
      <SafeAreaView>
      <KeyboardAvoidingView
        behavior={Platform.OS === "ios" ? "padding" : null}
        style={{ flex: 1 }}
      >
           {/* <Screen
            style={styles.mod1}
            statusBar={"light-content"}
            variant={true}
            showMenu={false}
            onNavigate={this.props.navigation}
          >
                 <UniversalNavigationHeader
                hideBack={false}
                goBack={this.props.navigation.goBack}
              /> */}
        <View style={styles.scrollViewStyle}>
          <Fragment>
            {true && (
              <QRCodeScanner
                reactivate={false}
                showMarker={true}
                ref={(node) => {
                  this.scanner = node;
                }}
                cameraStyle={styles.cameraView}
                onRead={this.onSuccess}
          //       topContent={
          //         <View style={{zIndex:9999,width:AppStore.screenWidth,marginTop:Platform.OS === 'ios'?STATUSBAR_HEIGHT:0 }}>
          // <TouchableOpacity
          //   underlayColor={"none"}
          //   style={{ padding:  20, }}
          //   onPress={() => this.props.navigation.goBack()}
          // >
          //   <Image
          //     style={{ width: wRem * 12, height: hRem * 21, }}
          //     source={Iconpack.GLOBAL_BACK_BUTTON}
          //   />
          // </TouchableOpacity>                  
          // </View>
          //       }
                bottomContent={
                  <View style={styles.bottomContainer}>
                    <TouchableOpacity
                      style={styles.tapStyle}
                      onPress={() => this.setState({ isShow: true })}
                      onLongPress={() => this.setState({ scan: false })}
                    >
                      <Text style={styles.tapText}>Have a Key? Tap Here</Text>
                    </TouchableOpacity>
                  </View>
                }
              />
            )}
          </Fragment>

          <Modal
            animationType="slide"
            transparent={true}
            visible={this.state.isShow}
            onRequestClose={() => {
              this.setState({ isShow: false });
            }}
          >
            <KeyboardAvoidingView
              behavior="position"
              enabled
              // style={{paddingBottom:30}}
            >
              {this.bottomModal(newStyle, newStyleSecretKey)}
            </KeyboardAvoidingView>
          </Modal>
          {/* </View> */}
        </View>
        {/* </Screen> */}
      </KeyboardAvoidingView>
      </SafeAreaView>
    );
  }
}

export default Scan;

I have tried several ways but I am getting errors that’s why I have pasted the whole code here, also one thing is I have used mobx for state management purposes.

how i change .setImage in embed without restart bot or write cmd again?

as u can see name topic how do I make the .setImage change every update when i change the image without deleting a msg? or write cmd once again

my first attempt : I tried to make it by uploading the image from a hosting site and to get the image link and from there I change the image and then I used setInterval to update the line .setImage but did not work for me this is my code of first attempt

let exampleEmbed = new MessageEmbed()
        .setColor('#0099ff')
        exampleEmbed.setImage('https://test.000webhostapp.com/images/image.jpg')
        .setTimestamp()

    try {
        let message1 = await message.channel.send({ embeds: [exampleEmbed] });
        setInterval(async function(){
            let exampleEmbed2 = new MessageEmbed()
            .setColor('#0099ff')
            exampleEmbed2.setImage('https://test.000webhostapp.com/images/image.jpg')
            console.log('updated')
            await message1.edit({ embeds: [exampleEmbed2] })
        },7000)

    } catch(err) {
        console.log(err)
    }

my second attempt was from the local computer I used MessageAttachment to get me the file path of image and then I also used setInterval to update the line function inside .setImage + MessageAttachment every 7 seconds it didn’t work either. Although when I type the command again, the (updated) image appears on the second try
here is my codes try second attempt

let exampleEmbed = new MessageEmbed()
        .setColor('#0099ff')
        exampleEmbed.setImage('https://test.000webhostapp.com/images/image.jpg')
        .setTimestamp()

    try {
        let message1 = await message.channel.send({ embeds: [exampleEmbed] });
        setInterval(async function(){
            let exampleEmbed2 = new MessageEmbed()
      const attachement =  new MessageAttachment('./images/image.jpg','image.jpg');
            .setColor('#0099ff')
            exampleEmbed2.setImage('attachment://image.jpg')
            console.log('updated')
            await message1.edit({ embeds: [exampleEmbed2], files: [attachement] })
        },7000)

    } catch(err) {
        console.log(err)
    }

Is there another way please? i would like to do the image update sync in any way without restart the bot or even writing cmd again

_firebase__WEBPACK_IMPORTED_MODULE_5__.default.collection is not a function

making a discord clone, im trying to use the database in firebase but it doesnt seem to be working I keep getting this error, “firebase__WEBPACK_IMPORTED_MODULE_5_.default.collection is not a function” heres my code

    useEffect(() => {
        db.collection('channels').onSnapshot((snapshot) => 
            setChannels(
                snapshot.docs.map((doc) => ({
                id: doc.id,
                channel: doc.data(),
            })) 
          ) 
        );
    }, []);

btw this is how I declared my database in firebase.js

const db = getFirestore(app);

looked around everywhere but I cant seem to find an answer

Stop image and text slide after scroll in mobile view

I have page with ten step sections first top to last bottom with text slide left side and image slide with right side on screen after scroll second section scroll to third section so on… the same function applied on mobile device but that function not good for mobile device, I need to stop slide function in mobile device I have added complete script which is applied, thanks in advance.

jQuery(document).ready(function($){
    //change this value if you want to change the speed of the scale effect
    var scaleSpeed = 0.3,
    //change this value if you want to set a different initial opacity for the .cd-half-block
        boxShadowOpacityInitialValue = 0.7,
        animating = false; 
    
    //check the media query 
    var MQ = window.getComputedStyle(document.querySelector('body'), '::before').getPropertyValue('content').replace(/"/g, "").replace(/'/g, "");
    $(window).on('resize', function(){
        MQ = window.getComputedStyle(document.querySelector('body'), '::before').getPropertyValue('content').replace(/"/g, "").replace(/'/g, "");
    });

    //bind the animation to the window scroll event
    triggerAnimation();
    $(window).on('scroll', function(){
        triggerAnimation();
    });

    //move to next/previous section
    $('.cd-vertical-nav .cd-prev').on('click', function(){
        prevSection();
    });
    $('.cd-vertical-nav .cd-next').on('click', function(){
        nextSection();
    });
    $(document).keydown(function(event){
        if( event.which=='35' ) {
            prevSection();
            event.preventDefault();
        } else if( event.which=='45' ) {
            nextSection();
            event.preventDefault();
        }
    });

    function triggerAnimation(){
        if(MQ == 'mobile') {
            //if on desktop screen - animate sections
            (!window.requestAnimationFrame) ? animateSection() : window.requestAnimationFrame(animateSection);
        } 
        else {
            //on mobile - remove the style added by jQuery 
            $('.cd-section').find('.cd-block').removeAttr('style').find('.cd-half-block').removeAttr('style');
        }
        //update navigation arrows visibility
        checkNavigation();
    }
    
    function animateSection () {
        var scrollTop = $(window).scrollTop(),
            windowHeight = $(window).height(),
            windowWidth = $(window).width();
        
        $('.cd-section').each(function(){
            var actualBlock = $(this),
                offset = scrollTop - actualBlock.offset().top,
                scale = 1,
                translate = windowWidth/1+'px',
                opacity,
                boxShadowOpacity;

            if( offset >= -windowHeight && offset <= 0 ) {
                //move the two .cd-half-block toward the center - no scale/opacity effect
                scale = 1,
                opacity = 1,
                translate = (windowWidth * 0.5 * (- offset/windowHeight)).toFixed(0)+'px';

            } else if( offset > 0 && offset <= windowHeight ) {
                //the two .cd-half-block are in the center - scale the .cd-block element and reduce the opacity
                translate = 0+'px',
                scale = (1 - ( offset * scaleSpeed/windowHeight)).toFixed(5),
                opacity = ( 1 - ( offset/windowHeight) ).toFixed(5);

            } else if( offset < -windowHeight ) {
                //section not yet visible
                scale = 1,
                translate = windowWidth/2+'px',
                opacity = 1;

            } else {
                //section not visible anymore
                opacity = 0;
            }
            
            boxShadowOpacity = parseInt(translate.replace('px', ''))*boxShadowOpacityInitialValue/20;
            
            //translate/scale section blocks
            scaleBlock(actualBlock.find('.cd-block'), scale, opacity);

            var directionFirstChild = ( actualBlock.is(':nth-of-type(even)') ) ? '-': '+';
            var directionSecondChild = ( actualBlock.is(':nth-of-type(even)') ) ? '+': '-';
            if(actualBlock.find('.cd-half-block')) {
                translateBlock(actualBlock.find('.cd-half-block').eq(0), directionFirstChild+translate, boxShadowOpacity);
                translateBlock(actualBlock.find('.cd-half-block').eq(1), directionSecondChild+translate, boxShadowOpacity); 
            }
            //this is used to navigate through the sections
            ( offset >= 0 && offset < windowHeight ) ? actualBlock.addClass('is-visible') : actualBlock.removeClass('is-visible');      
        });
    }

    function translateBlock(elem, value, shadow) {
        var position = Math.ceil(Math.abs(value.replace('px', '')));
        
        if( position >= $(window).width()/2 ) {
            shadow = 0; 
        } else if ( position > 1 ) {
            shadow = boxShadowOpacityInitialValue;
        }

        elem.css({
            '-moz-transform': 'translateX(' + value + ')',
            '-webkit-transform': 'translateX(' + value + ')',
            '-ms-transform': 'translateX(' + value + ')',
            '-o-transform': 'translateX(' + value + ')',
            'transform': 'translateX(' + value + ')'
        });
    }

    function scaleBlock(elem, value, opac) {
        elem.css({
            '-moz-transform': 'scale(' + value + ')',
            '-webkit-transform': 'scale(' + value + ')',
            '-ms-transform': 'scale(' + value + ')',
            '-o-transform': 'scale(' + value + ')',
            'transform': 'scale(' + value + ')',
            'opacity': opac
        });
    }

    function nextSection() {
        if (!animating) {
            if ($('.cd-section.is-visible').next().length > 0) smoothScroll($('.cd-section.is-visible').next());
        }
    }

    function prevSection() {
        if (!animating) {
            var prevSection = $('.cd-section.is-visible');
            if(prevSection.length > 0 && $(window).scrollTop() != prevSection.offset().top) {
                smoothScroll(prevSection);
            } else if(prevSection.prev().length > 0 && $(window).scrollTop() == prevSection.offset().top) {
                smoothScroll(prevSection.prev('.cd-section'));
            }
        }
    }

    function checkNavigation() {
        ( $(window).scrollTop() < $(window).height()/2 ) ? $('.cd-vertical-nav .cd-prev').addClass('inactive') : $('.cd-vertical-nav .cd-prev').removeClass('inactive');
        ( $(window).scrollTop() < $(window).height()/2 ) ? $('.cd-vertical-nav .cd-next').addClass('active') : $('.cd-vertical-nav .cd-next').removeClass('active');
    }
    

    function smoothScroll(target) {
        animating = true;
        $('body,html').animate({'scrollTop': target.offset().top}, 500, function(){ animating = false; });
    }
});

i want to count the number of sentiments that are in excel which i have called with jspreadsheet, but it comes out #ERROR

`
var name = document.getElementById("name").value;
var url = window.location.origin + '/storage/excel-data/' + name

jspreadsheet(document.getElementById('spreadsheet'), {
    worksheets: [{
        csv: url,
        search: true,
        csvHeaders: true,
        tableOverflow:true,
        tableHeight:'450px',
        columns: [
            { width:300 },
            { width:80 },
            { width:100 },
        ],
        footers:[
            [
                'Total Positif',
                '=COUNTIF(H:H,"positive")',
            ],
            [
                'Total Negatif',
                '=COUNTIF(H:H,"negative")',
            ]
        ],
    }]
});
`

How to make current element become previous element in a loop?

I am trying to make a 1v1 card game where the player and computer take turns putting down 1 poker card per turn. In the first turn, the first card that is played will be the first current card. In the second turn, the current card in the previous turn becomes the new previous card and there is a new current card played. How do I do this?

My code below does not do this.

while (playerDeck.length > 0 && computerDeck.length > 0) {
  currentCard = playerDeck.pop();
  nextCard = computerDeck.pop();
  previousCard = currentCard;
  currentCard = nextCard;
}

How to make linaria work with turbo repo and next js?

To set up linaria with next js we can use next-linaria package as shown in with-linaria example. Setting up next js for linaria, we can do npx create-next-app -e with-linaria. However, I get trouble in adding linaria to the ui package in a turbo repo monorepo.

Following is directory structure of scaffold by npx create-turbo

- apps
  - admin
  - web
- packages
  - ui

I want to use linaria for ui component as well.

how can i change & save by class name

I have a a page like control panel for the index.html page and I want to change the contains from this page to that.

        <div>
            <span id= "item-name" class="item-name">phone 1</span>
            <span id= "item-name" class="item-name">phone 2</span>
        </div>

like here how can I access to phone 1 and change it permanent from that page.

Thank you

CSS not working properly on Custom HTML Elements

I’ve been trying to make a custom HTML Element by extending the HTMLElement class. I try adding some style to it by linking a CSS file that is in the same directory as my other two files – index.html and custom.css.

Main folder

  • index.html
  • custom.css
  • custom.js

index.html:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="nofollow" type="text/css" href=''>
</head>
 
    <body>
        <script src="./custom.js"></script>
        <smooth-button text="Smooth button" no-1 = 1 no-2 = 2></smooth-button>
    </body>
 
</html>

custom.css:

smooth-button{
    display: block;
    color: blue;
    background-color: orange;
}

custom.js:

class SmoothButton extends HTMLElement{
 
    constructor(){
        super();
        this.shadow = this.attachShadow({mode: "open"})
    }
 
    connectedCallback(){
        this.render();
    }
 
    render(){
        this.SumOfNo1AndNo2 = null;
        if(this.getAttribute("no-1")!=null && this.getAttribute("no-2")!=null){
            this.SumOfNo1AndNo2 = parseInt(this.getAttribute("no-1")) + 
            parseInt(this.getAttribute("no-2"));
        }
        else{
            console.log("Invalid attribute.")
        }
        this.shadow.innerHTML = `<button>` + this.getAttribute("text") + " " + this.SumOfNo1AndNo2   
        + "</button>"
    }
 
}
 
customElements.define("smooth-button", SmoothButton);  

With this, I get a button as expected, with the text, but the style is applied to the element as a whole and not to the elements it’s made of. How can I apply the styles separately to each of its elements (just a <button> for now) with an external CSS file? I’m using external CSS because it’s somehow better as I read it here.

Please help me with this i am provided all the information needed below [closed]

I am a computer science student in my first semester of the college. I know basic of C, learning c++ on my own and started data structures and Algorithms a month ago. Before that I studied HTML,CSS and basics of javascript till dom manipulation then i started c++ again.
I am planning to complete DS algo by the upcoming month and then start web dev again.
Is my speed ok? If yes can I monetize my skills that I have untill this point.
If no! What do I need to learn at what speed please help.

Why do I have to use both .toString() and JSON.stringify()?

const SHA256 = require("crypto-js/sha256");

// the possible colors that the hash could represent
const COLORS = ['red', 'green', 'blue', 'yellow', 'pink', 'orange'];

// given a hash, return the color that created the hash
function findColor(hash) {
    let hashedColor;

    COLORS.forEach(color => {
        let hashedColor = SHA256(JSON.stringify(color)).toString();
        console.log(hashedColor);
        if (hashedColor === hash) {
            return color;
        };
    });
};


module.exports = findColor;

I’m experimenting with some hashing and manually using a rainbow table. When I import the SHA256 method, I find that I can create a hash for each of the colors but that this returns an object, which I then need to .stringify() to be able to console.log() the actual hash.

My question is, why do I have to both JSON.stringify() and .toString()?

I think I don’t quite understand what data type the SHA256 function gives me, and I can’t find it anywhere.