Firestore Query to Sum Values Where DocRef – not working

I’m at my wits end with this one. It seems so simple.

The following is in an API call I’ve built with a string parameter for ‘userRef’.

import { Firestore } from '@google-cloud/firestore';

export default async function firestoreQuerySum({
    collection,
    filters,
    projectId,
    userRef
}) {
    try {
        const db = new Firestore(projectId && projectId.length > 1 ? {
            projectId: projectId.trim()
        } : undefined);

        // Assuming userRef is the user ID passed as a string
        //const userDocRef = db.collection('users').doc(userRef);
        
        let query = db.collection(collection) //.where('userRef', '==', userDocRef);
        let snapshot = await query.get();

        let totalPointsValue = 0;
        snapshot.forEach(doc => {
          totalPointsValue += doc.data().pointsValue || 0;
        });

        return totalPointsValue;
    }
    catch(e) {
        return e;
    }
}

The goal is to sum the total points in a ‘rewards’ collection where the variable ‘userRef’ is equal to the stored doc reference in that collection. There don’t appear to be any errors, but even when I remove the where clause it results in 0. Any guidance as to what I’m doing wrong is appreciated.

How to write an AST selector for class decorator and ident rule using @typescript-eslint/parser

I’m trying to exclude some nodes from the @typescript-eslint/ident rule (since Eslint does not work properly with class decorators).

My Typescript looks like the following:

@MyDecorator({
    name: 'MyName',
    options: [{
        name: 'foo',
        type: 'Boolean',
        required: false,
        default: 'True',
    }]
})

Eslint complains about too many indentation characters so I want to ignore the MyDecorator from the rule, like so:

    ...,
    "@typescript-eslint/indent": ["error", "tab", {
        "SwitchCase": 1,
        "ignoredNodes": [
            "[expression.callee.name=MyDecorator] *"
        ]
    }]
    ...
}

I’ve tried a bunch of different selectors (using astexplorer.net for reference). But I think I’m missing out some fundamental detail on how eslint works with selectors.
For example, I would expect Decorator * to target everything inside all decorators but it does not. Why? What am I missing?

The only selectors I got working are Program * and [type=Program] * but of course those target everything so I can’t use that.

I’m using eslint v8.56.0.

Woor-discord.io sendMessage function randomly stopped working

Ive been running a discord bot from a server of mine for a few years now and its always worked just fine when sending messages and recieving them back. For exmaple if you type ‘!hello’ it will respond back to you using the sendMessage function. Recently it seems that either the messages are not getting through or just not working in general with no changes to the code. The weird thing is that when the uploadFile function runs it gets through just fine. Ill provide some code examples below.

    // Configure logger settings
    logger.remove(logger.transports.Console);
    logger.add(new logger.transports.Console, {
        colorize: true
    });
    logger.level = 'debug';
    // Initialize Discord Bot
    var bot = new Discord.Client({
    token: auth.token,
    autorun: true
    });

    bot.on('ready', function (evt) {
        logger.info('Connected');
        logger.info('Logged in as: ');
        logger.info(bot.username + ' - (' + bot.id + ')');
    });


bot.on('message', function (user, userID, channelID, message, evt) {

// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `!`
    if (message.substring(0, 1) == '!') {
        var args = message.substring(1);
        var cmd = args;
        
        switch(cmd) {
            
            //checking for user to reply yes
            case 'yes':

                bot.sendMessage({
                    to: channelID,
                    message: "Hello!"
                });
                break;
            case 'no:
 
                bot.uploadFile( {
                    to: channelID,
                    file: '/MY/FILE/PATH/pic.jpg'
                });
                break;

I saw in some posts that the “sendMessage” function was deprecated and to use the “send” function but even after updating the woor-discord.io library it says that “send” is not a function.

How to check if header value same or not?

I was trying to check when from submit same header value not selected from dropdown ..How do prevent form submit with that?

 <thead>
        <tr>
            @foreach($contact as $header)
              <th>{{ $header }}
                <select style="width:100%" class="form-select mapping-select mt-2 mb-2" name="tag[]">
                   <option value="contact_name">Contact Name</option>
                   <option value="contact_email">Contact Email</option>
                   <option value="contact_number">Contact Number</option>
                   <option value="contact_location">Contact Location</option>
                </select>
              </th>
                                       
             @endforeach
          </tr>
         </thead>
                               

How to take JavaScript object and determine TypeScript type from it?

Given an object like this:

const obj = {
  "a64multi": {
    "label": "Foo",
    "type": "video",
    "frameLevelMultithreading": true,
    "sliceLevelMultithreading": true,
    "experimental": true,
    "supportsDrawHorizontalBand": true,
    "supportsDirectRenderingMethod1": true
  },
  "a64multi5": {
    "label": "Multicolor charset for Commodore 64, extended with 5th color (colram) (codec a64_multi5)",
    "supportsDirectRenderingMethod1": true
  }
}

How can you determine the TypeScript type definition from it programmatically? That is, how can you generate the TypeScript source code that defines this object’s type?

I know about typeof obj to get the type of the object using TypeScript, but how do you implement that? I would like to take an arbitrary JavaScript Object type (key/value pairs), and figure out the TypeScript definition of the values that the keys can take. So in this case it would be:

type ObjType = 
  | {
    label: string
    type: string
    frameLevelMultithreading: boolean
    sliceLevelMultithreading: boolean
    experimental: boolean
    supportsDrawHorizontalBand: boolean
    supportsDirectRenderingMethod1: boolean
  }
  | {
    label: string
    supportsDirectRenderingMethod1: boolean
  }

My nth guess at this would be to basically build up a string for all the keys like this:

console.log(generateHashTypeScriptType('ExampleType', {
  "a64multi": {
    "label": "Foo",
    "type": "video",
    "frameLevelMultithreading": true,
    "sliceLevelMultithreading": true,
    "experimental": true,
    "supportsDrawHorizontalBand": true,
    "supportsDirectRenderingMethod1": true
  },
  "a64multi5": {
    "label": "Multicolor charset for Commodore 64, extended with 5th color (colram) (codec a64_multi5)",
    "supportsDirectRenderingMethod1": true
  }
}))

function generateHashTypeScriptType(typeName, obj) {
  const types = {}
  for (const name in obj) {
    const type = determineType(obj[name])
    types[JSON.stringify(type)] = true
  }
  const finalTypes = Object.keys(types).map(string => JSON.parse(string))
  return generateTypeScriptType(typeName, finalTypes);
}

function generateTypeScriptType(name, types) {
  const text = []
  text.push(`export type ${name} = `)
  types.forEach(type => {
    text.push(`  |`)
    const lines = generateTypeScriptObjectType(type)
    text[text.length - 1] += lines.shift()
    lines.forEach(line => {
      text.push(`  ${line}`)
    })
  })
  return text.join('n')
}


function generateTypeScriptObjectType(type) {
  const text = []
  text.push(` {`)
  for (const name in type) {
    const val = type[name]
    switch (val.type) {
      case 'string':
        text.push(`  ${name}: string`)
        break
      case 'number':
        text.push(`  ${name}: number`)
        break
      case 'boolean':
        text.push(`  ${name}: boolean`)
        break
      case 'object':
        text.push(`  ${name}:`)
        const lines = generateTypeScriptObjectType(val.children)
        text[text.length - 1] += lines.shift()
        lines.forEach(line => {
          text.push(`  ${line}`)
        })
        break
    }
  }
  text.push(`}`)
  return text
}

function determineType(obj) {
  const out = {}
  for (const name in obj) {
    const val = obj[name]
    if (typeof val === 'string') {
      out[name] = {
        type: 'string'
      }
    } else if (typeof val === 'number') {
      out[name] = {
        type: 'number'
      }
    } else if (typeof val === 'boolean') {
      out[name] = {
        type: 'boolean'
      }
    } else if (val && typeof val === 'object') {
      out[name] = {
        type: 'object',
        children: determineType(obj)
      }
    }
  }
  return jsonSort(out)
}

// https://github.com/DawnImpulse/json-keys-sort/blob/master/index.js
function typeOf(data) {
  const objectConstructor = {}.constructor
  const arrayConstructor = [].constructor
  const stringConstructor = 'test'.constructor
  if (data && data !== null && data.constructor === objectConstructor) {
    return 'OBJECT'
  } else if (data && data !== null && data.constructor === arrayConstructor) {
    return 'ARRAY'
  } else if (data && data !== null && data.constructor === stringConstructor) {
    return 'STRING'
  } else {
    return ''
  }
}

function jsonSort(data, sort) {
  if (typeOf(data) === 'ARRAY') {
    let newData = []
    for (let w = 0; w < data.length; w++) {
      let d = data[w]
      if (typeOf(d) === 'OBJECT' || typeOf(d) === 'ARRAY')
        newData.push(jsonSort(d, sort))
      else {
        newData.push(d)
      }
    }
    return newData
  } else if (typeOf(data) === 'OBJECT') {
    let newKeys = [],
      keys,
      newData = {}

    if (sort === undefined)
      sort = true

    keys = Object.keys(data).sort()

    if (!sort) {
      for (let i = keys.length - 1; i >= 0; i--)
        newKeys.push(keys[i])
      keys = newKeys
    }

    for (let j = 0; j < keys.length; j++) {
      let key = keys[j]
      if (typeOf(data[key]) === 'OBJECT')
        newData[key] = jsonSort(data[key], sort)
      else if (typeOf(data[key]) === 'ARRAY') {
        newData[key] = []
        for (let k = 0; k < data[key].length; k++) {
          let d = data[key][k]
          if (typeOf(d) === 'OBJECT' || typeOf(d) === 'ARRAY')
            newData[key].push(jsonSort(data[key][k], sort))
          else
            newData[key].push(data[key][k])
        }
      } else
        newData[key] = data[key]
    }

    return newData
  } else
    throw new Error('must be an object/array')
}

See the console.log output to see what it does. The second half of the code is from json-keys-sort.

Is there a better or more optimal way of accomplishing this? Is there a library for this already? Can I do it without having to write any code other than using some API?

How to upload and view pdf in nz-upload?

`Hi, i am trying to upload pdf file in 17 version of nz-zorro , but it is showing in red color and view button is disabled , but for image type it works fine and image is viewed and in version 7 it works fine for pdf file here is my code :

This is my code picture card to accept multiple pictures . I should able to upload and view both image and pdf file . currently i can view only image. and for pdf i view icon is disabled`

<nz-upload  nzAction="{}" nzListType="picture-card" [(nzFileList)]="viewDocFile" [nzShowButton]="nzUploadBoxBtn"[nzShowUploadList]="showUploadList" [nzPreview]="handlePreview" 
[nzBeforeUpload]="beforeUpload"><span nz-icon nzType="plus"></span><div class="ant-upload-text">Upload</div></nz-upload>

how to use mobile touchmove event

window.addEventListener("wheel", function(e){
    e.preventDefault();
  },{passive : false});

  var mHtml = $("html");
  var page = 1;

  mHtml.animate({scrollTop : 0},10);

  $(window).on("wheel", function(e) {
      if(mHtml.is(":animated")) return;
      if(e.originalEvent.deltaY > 0) {
          if(page == 4) return;
          page++;
      } else if(e.originalEvent.deltaY < 0) {
          if(page == 1) return;
          page--;
      }
      var posTop =(page-1) * $(window).height();
      mHtml.animate({scrollTop : posTop});
  })
  
window.addEventListener("touchmove", function(e){
    e.preventDefault();
  },{passive : false});

  var mHtml = $("html");
  var page = 1;

  mHtml.animate({scrollTop : 0},10);

  $(window).on("touchmove", function(e) {
      if(mHtml.is(":animated")) return;
      if(e.originalEvent.deltaY > 0) {
          if(page == 4) return;
          page++;
      } else if(e.originalEvent.deltaY < 0) {
          if(page == 1) return;
          page--;
      }
      var posTop =(page-1) * $(window).height();
      mHtml.animate({scrollTop : posTop});
  })

this is my code. code that causes the section to go down when scrolling. so we put a touchmove event so that it can work on mobile. but not working touchmove event. how to fix it?

Is It possible to in some type of way make a variable in javascript have this —> var phone number = “(” + Array[1] + Array[2] + Array[3] “)”

this is my code

function createPhoneNumber(numbers)
{
  const phonelimit = [10]
  
  for(var i = 0; i < 10; i++)
    { 
      var j = i + 1
      if (i == 9)
        {
          j -= 10
          
        }
      phonelimit[i] = j
      
      
    }
   var phoneNumber = "(" + phonelimit[0] + phonelimit[1] + phonelimit[2] + ") " + phonelimit[3] + phonelimit[4] + phonelimit[5] + "-" + phonelimit[6] + phonelimit[7] + phonelimit[8] + phonelimit[9])
   return phoneNumber
}

my problem is that i am using a site called codehs for my highschool Java + javascript

and it only will allow me to submit it if it outputed using a return not a causal console.log

so some how i need to put all this junk that makes the phone number string into a variable then return the variable

I tried to do multiple toString() methods to create the whole format of the phone number thing with the numbers one variable but they didn’t work

while trying to use console.log

How useState works?

export const App = (props) => {
  const [data, setData] = useState(0)
  console.log('1: ', data)
  const onClick = () => {
    setData(1)
  }
  return <button onClick={onClick}>button</button>
}

From the above example, I got result

1: 0
1: 1
1: 1
(‘1’ printed twice even though setState same value)

and In other case below, I got infinite loop.

export const App = (props) => {
  const [data, setData] = useState(0)
  console.log('1: ', data)
  setData(1)
  
  return <button onClick={onClick}>button</button>
}

I don’t know why the result came out like this.

What is the order of output of the following piece of js code?

async function async1() {
  console.log("a");
  await async2();
  console.log("b");
}

async function async2() {
  console.log("c");
  await async3();
  console.log("zzzzz");
}

const async3 = async () => {
  console.log("qqqq");
};

console.log("d");
async1();

setTimeout(() => {
  console.log("e");
}, 0);

new Promise((resolve, reject) => {
  console.log("f");
  resolve();
}).then(() => {
  console.log("g");
});
.as-console-wrapper { max-height: 100% !important; }

Here’s what I envisioned:
d, a, c, qqqq, f, zzzzz, b, g, e。

But the order in which it runs in the browser is:

d
a
c
qqqq
f
zzzzz
g
b
e

After the first execution completes, the microtask queue should be console.log("zzzzz"); console.log("b"); console.log("g");
The order of execution is, zzzzz b g, but the result in the browser is not like this, is there something I’m thinking wrong?

extremely grateful!

Need generating a list from an object

I’m working in a front-end in which I receive an order from the database and I need to generate a PDF but only wit 10 items per page. I need to generate a list of orders with the same attributes but with 10 items each until the original order items list finishes.

Here an example:

const order = {
    name: 'services',
    items: ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
}

const paginate = (order, pages, start, end) => {

    if (order.items.length <= end) {
        return pages.concat({
            name: order.name,
            items: order.items.slice(start, end)
        })
    } else {
        start += 4
        end += 4
        paginate(order, start, end)
    }

}

but that gives me the Maximum call stack size exceeded error. For this example I’m trying to split the order with 3 items. Any help will be really good.

Creating an end screen for my game using javascript, css, and html

I’ve been trying to create an end screen for my candy crush game utilizing a timer but for some reason when the timer hits 0 and the conditions are met, the screen doesn’t come up. Any idea why this might be happening?

function timer() {
  var seconds = 120;
  var timer = setInterval(function() {
    document.getElementById("safeTimerDisplay").innerHTML = seconds;
    seconds--;
    if (seconds < 0) {
      clearInterval(timer);
    }
  }, 1000);
}

timer();


function endGame() {
  if (seconds === 0 && score > 1800) {
    console.log(endWindow1)
  }
}
#EndWindow1 {
  background: url("./endscreen.jpg") no-repeat center center fixed;
  background-size: cover;
  font-family: Arial, Helvetica, sans-serif;
  color: white;
  text-align: center;
}
<div id="EndWindow1" style="display:none;"></div>
<h1>Timer: <span id="safeTimerDisplay"></span></h1>

I tried using a conditional and stating that if the user’s score was over 1800 and the clock hits 0, a specific image should come up that I specified using the file in the css folder. When the clock hits 0 though, nothing ends up happening and you can proceed with the game as normal.

How to set label based on toggle switch value

I use Bootstrap 5 and I wand to use a switch-toggle.

How to set Label based on Switch value.

This does not work:

<div class="form-check form-switch">
  <input type="checkbox" class="form-check-input" id="status">
  <script>
   if ($('#status').val() == 1) {
      <label for="site_state" class="form-check-label">Aktif</label>
   } else {
      <label for="site_state" class="form-check-label">Tidak Aktif</label>
   }
   </script>
</div>

Anyone have an idea ?