Can’t loop over object.prototype

Class SomeClass {
   myFunction() {
    console.log('Hello, World');
  }
}

for (let obj in SomeClass.prototype) {
    console.log(obj);
  }

Hi everyone, I am trying to loop over class’s prototype but it’s not working, it doesn’t give an error loop just won’t execute, I tried running this code in dev tools same situation, what’s wrong here, how do I loop over prototype object?

Show one div’s contents at a time every 4 seconds

I have a bunch of slide divs inside of a wrapper container. As you can see I have two of them set to display: none initially. Every 4000ms I would like to smoothly transition into the next slide. I have tried a few things with set interval in js and no luck.

Here is my code:

body {
  padding: 0;
  margin: 0;
}

.wrapper {}

.slide {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 100vh;
}

img {
  outline: solid 5px #fff;
}

.single img {
  width: 100%;
  height: 100%;
}

.split img {
  width: 50%;
  height: 100%;
}

.quad img {
  width: 50%;
  height: 50%;
}
<div class="wrapper">
  <div class="slide single">
    <img src="https://dummyimage.com/3840x2160/000/fff">
  </div>

  <div class="slide split" style="display: none;">
    <img src="https://dummyimage.com/3840x2160/000/fff">
    <img src="https://dummyimage.com/3840x2160/000/fff">
  </div>

  <div class="slide quad" style="display: none;">
    <img src="https://dummyimage.com/3840x2160/000/fff">
    <img src="https://dummyimage.com/3840x2160/000/fff">
    <img src="https://dummyimage.com/3840x2160/000/fff">
    <img src="https://dummyimage.com/3840x2160/000/fff">
  </div>
</div>

Cannot read properties of undefined (reading ‘_id’) while reading user from backend nodejs

I am getting the following error in nodejs and expressjs, the code is given below

module.exports.forgotPassword = async (req, res) => {
  try {
    const email = req.body.email;
    const user = await User.findOne({ email: email });
    console.log(user);
    if (user === null) throw new Error("Please register first");
    if (user !== null) {
      const id = user[0]._id.toHexString();
      const token = crypto.randomBytes(64).toString("hex");
      let link = `${id}/${token}`;
      res.status(200).send(link);
    }
  } catch (err) {
    res.status(401).send({ error: err.message });
  }
};

Create Collection on Sign Up

I’m trying to allow users to sign up and in doing so create a collection for themselves in firebase/firestore. The function would essentially authenticate AND create a db/reroute them to a homepage. This logic has been started in the “createDatabaseOnSignUp” function below. (or is it a variable?)

I’m getting an error that says “firebase is not defined.”

I’m a self taught coder so maybe I’m missing something very obvious. If anyone can point me in the right direction or knows the correct thing to import I’d be very grateful.

My code looks like this:

import React, { useRef } from "react";
import { useAuth } from "../../context/AuthContext";
import "./SignUp.scss";
import { Link } from "react-router-dom";
import { collection, getDocs, doc, setDoc, getDoc } from "firebase/firestore";
import { db } from "../../firebase-config";

function SignUp() {
  const { signUp, currentUser } = useAuth();
  const emailRef = useRef();
  const passwordRef = useRef();

  // console.log(currentUser.email);

  const createDatabaseOnSignUp = (emailRef, passwordRef, name) => {
    // create firebase database for user
    const user = firebase
      .auth()
      .signUp(emailRef, passwordRef)
      .then((cred) => {
        return;
        db.collection("name").doc(
          cred.user.uid.set({
            emailRef,
            name,
          })
        );
      });
    return { user };
    // sign up with userAuth
    //navigate to homepage

    // console log success
    console.log("Thanks for registering! Make your first label!");
  };

  return (
    <div className="signup">
      <div></div>
      <h1 className="signup__title">Please Sign Up...</h1>
      <div className="signup__section">
        <label className="signup__label">Email</label>
        <input className="signup__input" ref={emailRef} type="email"></input>
      </div>
      <div className="signup__section">
        <label className="signup__label">Password</label>
        <input
          className="signup__input"
          ref={passwordRef}
          type="password"
        ></input>
      </div>
      <div className="signup__section">
        <label className="signup__label">Confirm Password</label>
        <input className="signup__input" type="password"></input>
      </div>
      <button
        className="signup__button"
        onClick={() =>
          signUp(emailRef.current.value, passwordRef.current.value)
        }
      >
        Sign Up
      </button>
      <h3 className="signup__text">
        Already have an account?{" "}
        <Link to="/login" className="signup__underline">
          Log in
        </Link>
      </h3>
    </div>
  );
}

export default SignUp;

Firestore query from collection if value exist in mapped array in expo

Im trying to get data from a collection where the information inside it is: owner_uid
members collection

and query my user collection if it exist there , if so to map it in array
users info collection

is there a way to query this?

also tried to map the the “members collection” and then try to query comparing to the array with no success , is it possible?
the code i tried:

 const { chh } = props.route?.params; //current house hold
  const [members, setMembers] = useState([]);
  const [chhUsers, setChhUsers] = useState([]);

  useEffect(() => {
    const q = query(collection(db, `households/${chh.title}/members/`));
    const querySnapshot = getDocs(q).then((querySnapshot) => {
      setChhUsers(querySnapshot.docs.map((doc) => doc.data()));
    });
    console.log(chhUsers);
  }, []);

  useEffect(() => {
    setTimeout(() => {
      const userdb = collection(db, `users`);
      const q = query(userdb, where("owner_uid", "==", chhUsers));
      const querySnapshot = getDocs(q).then((querySnapshot) => {
        setMembers(querySnapshot.docs.map((doc) => doc.data()));
      });
      console.log(members);
    }, 2000);
  }, []);

what i get from chhUsers:

Array [
  Object {
    "owner_uid": "4g8urzWb6RPP44ak9iPIlZidWDo2",
  },
]

but the query of console.log(members); return empty

if i change the chhUsers in const q = query(userdb, where(“owner_uid”, “==”, chhUsers));
it return me the info

Sinon – Can I temporarily mock a method on a stub?

I’m retrofitting unit tests to legacy code, and have setup sinon and proxyquire to inject stubs for dependencies.

In some tests I need to verify that methods on one or more dependencies were called correctly, while allowing all other method calls on the same objects to behave like stubs (returning default values, rather than passing the calls to the real implementations.

So far I’ve tried a number of approaches, and occasionally have gotten it to seemingly work until I do a little code cleanup, and things again break (when it works the code is in very poor shape–so while it seems like its working it’s unclear if it will continue to work or what code is actually having the desired effect).

Below is what I’m currently trying, with comments about my intentions.

const proxyquire = require('proxyquire')
const stubUtils = stub(require('./utils'))
const stubService = stub(require('./service'))

// Setup the SuT to default to talking to stubs
const systemUnderTest = proxyquire('./index', {
    './utils': stubUtils,
    './service': stubService
})

let sandbox
describe('index.doSomething()', () => {
    beforeEach(() => {
        // I'm attempting to revert any test-specific setup and put the dependencies back to default stubs
        sinon.reset();

        // the legacy code is configured by environment variables, between tests I want to reset process.env since each test requires a different configuration
        sandbox = sinon.createSandbox()
        sandbox.stub(process, 'env').value({})

        // someMethod() is printed in a bunch of logs which call .length on it, so my baseline setup needs to configure it
        stubService.someMethod.returns('')
    })

    afterEach(() => {
        // tests *should* call their own .verify(), but I'm assuming adding it here will catch it if the tests miss it
        sinon.verify()
        sandbox.restore()
    })

    // There are several basic "modes" for the code under test
    describe('Scenario A', () => {
        beforeEach('Scenario A Setup', () => {
            // Each scenario sets a few common settings
            process.env.SOME_CONFIG_VALUE = 'mode A'
            // ...
        })

        it('uses the environment variable appropriately', () => {
            // Here's where I'm struggling
            // In this one test I need to verify a call is made with the correct argument on an object that is otherwise behaving like a stub
            const expected = "the expected value"
            process.env.IMPORTANT_VALUE = expected

            // throws: stubUtils.restore is not a function
            //stubUtils.restore()

            // throws: TypeError: Attempted to wrap someMethod which is already wrapped
            const mockCall = sinon.mock(stubUtils).expects('someMethod').withArgs(expected)

            systemUnderTest.doSomething()

            mockCall.verify()
        })

        // it(...  // more tests, similarly needing to mock various methods on the stubs
    })

    // describe('Scenario B', () => {
    // ... and so on.  There are several scenarios, each with several unit tests

Type ‘string[]’ is not assignable to type ‘listData[]’

I am working on generic component where list view can be utilized by other components. But the issue is data format is different for each component. In my project I can’t use type any[] which will cause linting issues that I can’t skip also.

list-view.component.html(shared component)

          <div *ngFor="let list of lists">
              <ng-template #defaultTemplate>
                  <p> {{list}}</p>
             </ng-template>
             <ng-container
              [ngTemplateOutlet]="optionTemplate || defaultTemplate"
              [ngTemplateOutletContext]="{ $implicit: list}"
             >
            </ng-container>
          </div>

list-view.component.ts

          import {Component,ContentChild,EventEmitter,Input,Output,TemplateRef} from '@angular/core';

          export interface listData{
             id: number;
             brand: string;
             model: string;
             url: string;
          }

          @Component({
             selector: 'app-my-selector',
             templateUrl: './my-selector.component.html',
          })
           export class MySelectorComponent {
               @Input() lists: listData;  **// can't use any[], because of linting issue.**
               @ContentChild('optionTemplate', { static: false }) optionTemplate: TemplateRef;
               constructor() {}
           }

test1.component.html

           <div class="container">
              <app-my-selector [lists]="list">
                  <ng-template #optionTemplate let-list>
                       <img src="{{list.url}}" alt="{{list.model}}">
                       <p>{{list.brand}}: {{list.model}}</p>
                  </ng-template>
              </app-my-selector>
            </div>

test1.component.ts

            import { Component } from '@angular/core';

             export interface listData{
               id: number;
               brand: string;
               model: string;
               url: string;
             }
             @Component({
                  selector: 'app-test1',
                  templateUrl: './test1.component.html',
             })
             export class Test1Component {
                 list: listData= [
                      {
                          id: 1,
                          brand: 'TATA',
                          model: 'Indica - 2008',
                          url: '/indica-img.jpg'
                      },
                      {
                          id: 2,
                          brand: 'Suzuki',
                          model: 'Swift - 2011',
                          url: '/swift-img.jpg'
                      }
                   ];
                 constructor() {}
                }

test2.component.html

                   <div class="container">
                      <app-my-selector [lists]="list"></app-my-selector>
                   </div>

test2.component.ts

                   import { Component, OnInit } from "@angular/core";
                   @Component({
                        selector: "app-test2",
                        templateUrl: "./test2.component.html",
                   })
                   export class Test2Component {
                      list: string[];  **// this is where causing the issue.**
                      constructor() {}
                      ngOnInit() {
                         this.list = ['Harley Davidson','Bajaj','Triumph'];
                      }
                    }

If I run the above code I am getting Type ‘string[]’ is not assignable to type ‘listData[]’ in test2.component.html. Because test1 component is array of object data & test2 component is array data. So with out using any[] how can I achieve this.

Laravel css and js not loading in on the first page

I can’t figure out why my css and js doesn’t load. I am using node and rand the npm install and npm run dec commads multiple times and also tried writing the paths like this :

    <!-- Styles -->
    <link rel="stylesheet" href="{{ asset('public/css/app.css') }}">

    <!-- Scripts -->
    <script src="{{ asset('public/js/app.js') }}" defer></script>

and like this:

    <!-- Styles -->
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

And still my page looks like this:
enter image description here

This is my main paige that loads up first when you enter the site. When i go into the “view page source” and click on the links for the css and js files it returns a 404 page. All the other pages i have are experiencing the same issue.

Error playing video with Javascript and HTML: Failed to load resource

I’m trying to play a video with HTML and Javascript. A video is generated through some local processes, and once done, I have a Javascript that triggers the video playback right away and displays it:

document.getElementById("video").innerHTML = "<video style="margin-right:"+videospace+"" height="300" controls><source src="video.mp4" type="video/mp4"></source></video>";
document.getElementById("video").style.display = "inline";

It works for some videos (apparently smaller sizes/resolutions), but when a video is slightly larger (2600×800), it keeps looping and never loads/plays it (maybe due to the reason that once the video is still sitting on disk and given it’s slightly larger, the video player doesn’t get enough time/buffering to load it). And Javascript shows this error:

Failed to load resource: net::ERR_REQUEST_RANGE_NOT_SATISFIABLE video

How to solve it?

How to check if a variable exists in TypeScript?

I have code that loops, and I want to initialize the variable one within the code. To do this, I check if the variable exists, and if not, initialize it.

In JavaScript, I would normally just do the following

if (typeof variableExample === 'undefined') {
    // run this code
}

But TypeScript doesn’t like this. It tells me that it can’t perform this because it cannot find the variable:

Any ideas for getting around this?

How to overcome syntax error issue while Injecting Javascript code from angularjs controller

I am trying to add the following javascript code through one angular controller

    const script = document.createElement('script');
    script.setAttribute('type', 'text/javascript');
    script.type = 'text/javascript';
    script.async = false;

    script.setAttribute('src', './exampleJSCode.js');

The exampleJSCode file contains javascript functions but when I run this code I get lots of syntax errors (around 54) but the exampleJSCode file is formatted correctly.

How to escape that character which is causing syntax error?

data map function does not rendering data in as Text React Native

import React, { useEffect, useState } from "react";
import {
  Button,
  StyleSheet,
  TextInput,
  View,
  TouchableOpacity,
  Text,
} from "react-native";
import axios from "axios";
export default function Home() {
  const [data, setData] = useState([]);
  const [indexNo, setIndexNo] = useState("");

  const getUserData = () => {
    axios
      .get(`https://jsonplaceholder.typicode.com/todos/${indexNo}`)
      .then((res) => {
        const fData = res.data.data;
        console.log(fData);
      });
  };
  return (
    <>
      <View style={styles.mainView}>
        <View style={styles.searchView}>
          <TextInput
            style={styles.searchBar}
            keyboardType="numeric"
            placeholder="Index Number  e.g.25"
            placeholderTextColor="#4F4F4F"
            blurOnSubmit="true"
            value={indexNo}
            onChangeText={(e) => {
              setIndexNo(e);
            }}
          />
          <TouchableOpacity style={styles.button} onPress={getUserData}>
            <Text style={styles.buttonText}>Search</Text>
          </TouchableOpacity>
        </View>
        <View style={styles.subView}>
          <Text style={styles.title}>Your Details</Text>

          <View style={{ padding: 40 }}>
            {data?.map((item) => {
              return (
                <Text style={styles.flatListText}>
                  {" "}
                  {item.birthYear} {data?.contactNumber}
                </Text>
              );
            })}
          </View>

          <View style={styles.cardButtonRow1}>
            <TouchableOpacity style={styles.buttonGroup}>
              <Text style={styles.btGroupText}>Sem 01</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.buttonGroup}>
              <Text style={styles.btGroupText}>Sem 02</Text>
            </TouchableOpacity>
          </View>
          <View style={styles.cardButtonRow2}>
            <TouchableOpacity style={styles.buttonGroup}>
              <Text style={styles.btGroupText}>Sem 03</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.buttonGroup}>
              <Text style={styles.btGroupText}>Sem 04</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>
    </>
  );
}
const styles = StyleSheet.create({
  mainView: {
    backgroundColor: "#393939",
    flex: 1,
  },
  searchView: {
    marginTop: 50,
    flexDirection: "row",
    flexWrap: "wrap",
  },
  searchBar: {
    marginLeft: 40,
    backgroundColor: "#D9D9D9",
    color: "#4F4F4F",
    width: "50%",
    height: 40,
    textAlign: "center",
    borderRadius: 50,
  },
  button: {
    marginLeft: 17,
    marginRight: 40,
    backgroundColor: "#2369F0",
    width: "24%",
    height: 40,
    borderRadius: 50,
  },
  buttonText: {
    color: "#fff",
    fontSize: 20,
    textAlign: "center",
    margin: 7,
  },
  subView: {
    backgroundColor: "#535353",
    margin: 40,
    width: "80%",
    flex: 1,
    borderRadius: 30,
  },
  title: {
    fontSize: 20,
    fontWeight: "bold",
    textAlign: "center",
    paddingTop: 15,
    color: "#fff",
  },
  cardButtonRow1: {
    flexDirection: "row",
    marginLeft: 30,
    flexWrap: "wrap",
    marginTop: 220,
  },
  cardButtonRow2: {
    flexDirection: "row",
    flexWrap: "wrap",
    marginLeft: 30,
    bottom: 30,
  },
  buttonGroup: {
    backgroundColor: "#2369F0",
    width: "30%",
    height: "40%",
    borderRadius: 30,
    margin: 20,
  },
  btGroupText: {
    color: "#fff",
    textAlign: "center",
    padding: 3,
  },
  flatListText: {
    color: "red",
    fontSize: 26,
  },
});

I need to fetch data from given url. I gave state value to url param. It work perfectly, output object I assigned to state. when I console log that object, data come as json object. So I need that values print as Text in app. I used that for map function, but it does not work. Error or any issues dose not visible any where . please help. I’m testing with iphone7 . used CLI expo. I

How to list elements of an object in React Typescript?

I want to list the elements of the objects in my Typescript react project.
If I make in this way:

const data = Dependencies.backend.getList(caseDetailUrl + this.props.id);
data.then(res => {
      console.log(res)
    })

The output is but when I refresh page it prints 2 times I don’t know why:

{
    "id": "669f83",
    "creation_date": "2022-01-13 10:33:06.046652+01:00",
    "case_type": "Sum",
    "current_stage": "",
    "last_change_date": "2022-01-14 14:35:17.563449+01:00",
    "status": 1,
}

I want to display these info but I can’t.

Firstly, I try:

let case_value
data.then(res => {
      case_value.push(res)
    })

and It shows an error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘push’)

And when I use .map instead of .then

Property ‘map’ does not exist on type ‘Promise<unknown[] | undefined>’.ts(2339)

My whole code is:

import React from "react";
import { Dependencies } from "../../../shared/utils/dependencies";
import { caseDetailUrl } from "../../constants/backend-constants";

interface CaseDetailProps {
  id: string,
}

class CaseDetail extends React.Component<CaseDetailProps> {

  render() {
    const data = Dependencies.backend.getList(caseDetailUrl + this.props.id);
    let case_value
    data.then(res => {
      case_value.push(res)
    })
    return (
      <div className="caseDetail">
        <h1>Hi!</h1>
        <h3>{this.props.id}</h3>
      </div>
    );
  }
}

export default CaseDetail;

How can I display it?

In Chrome “javascript:window.open” on a blank tab

On Chrome, I created links in the Bookmarks tab.
I wanted them to open in a new tab rather than overwriting the existing tab.
So the bookmark I made were

javascript:window.open("https://example.com")

and not directly

https://example.com

It works fine, but when I launch it on a new tab (completly blank), that doen’t do anything, the site isn’t loaded

Is there a way to make that work even on a blank tab ? (creating a new tab or overwriting it, indifferently)