(JS) Google Script App Search / Filter for keyword

I have been stumped on this for a while. I am fairly new to Google script app and wanted to see if there is a way to make this happen. So far, I’ve used a few methods within Google Sheet but seem to not get it working.

The code below does give me an output of all the data, however, the data that is nested in the data.custom_fields[x] has multiple objects that is separated by “,”. I would like to be able to filter out the other key words and just use whatever is inside "display_value=". The display_value= is not always in the same area so have to run a search for them.

I am assuming some kind of If statement would be used here..

An example of the object is:

{type=x, resource_subtype=x, created_by={name=x, gid=x, resource_type=x}, display_value=Cool Value, description=x, enabled=x, resource_type=custom_field, gid=x, enum_options=[x.lang.Object;x, enum_value={x}, name=x}

I’ve tried to split function as well but not sure how to filter out the words I need.

function Users() {
  var options = {
   "headers" : {
     "Authorization": "API Key here"
   }
  }
  var response = UrlFetchApp.fetch("URL here", options);

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheets = ss.getSheets();
  var sheet = ss.getSheetByName("Tab Name here"); // specific sheet name getSheetByName(""); alternatively use ss.getActiveSheet()

  var dataAll = JSON.parse(response.getContentText()); //
  var dataSet = dataAll.data; // "data" is the key containing the relevant objects
  var rows = [],
    data;
  
  for (i = 0; i < dataSet.length; i++) {
  data = dataSet[i];
  rows.push([
    data.gid,
    data.name, 
    data.permalink_url,
    data.due_on,
    data.custom_fields[1],
    data.custom_fields[2],
    data.custom_fields[4],
    data.custom_fields[5],
    data.custom_fields[6],
    data.custom_fields[7],
    data.custom_fields[8],
    data.custom_fields[9],
    
    ]); //your JSON entities here
  }
var details = itemResponse.getResponse();
  if(details.indexOf("detail_value=")>-1)
  // [row to start on], [column to start on], [number of rows], [number of entities]
  dataRange = sheet.getRange(2, 1, rows.length, 12);
  dataRange.setValues(rows);

Thank you in advance!

In a slideshow, how do I prevent slides from receiving “click” events after dragging?

I have a slideshow:

        <div (mousedown)="onMouseDown($event)"
          (mousemove)="onMouseMove($event)"
          (mouseup)="onMouseUp($event)">
          <div class="swiper-wrapper">
            <div *ngFor="let item of items; index as i;">
              <custom-slide class="custom-slide"></custom-slide>
            </div>
          </div> 
        </div>

Methods onMouseDown, onMouseMove and onMouseUp are for dargging it using mouse.

The custom-slide Angular component listens to click events and pops up a dialog upon clicks.

But the problem is every time finish dragging the slideshow, a click event is always sent to a custom-slide component, therefore a dialog is popped up, which is what I want to avoid.

I tried to write the onMouseUp as below, but it doesn’t work

  onMouseUp() {
    this.mouseIsDown = false;

    const elements = document.getElementsByClassName("custom-slide");

    if(this.isScrolling) {
      for(let i = 0; i < elements.length; i++){
        elements[i].addEventListener("click", this.preventClick);
      }
    } else {
      for(let i = 0; i < elements.length; i++){
        elements[i].removeEventListener("click", this.preventClick);
      }
    }

    this.isScrolling = false;
  }

  preventClick(event) {
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();
  }

Although in the preventClick method I prevented everything, but the slide can still receive the click event and pop up the dialog…

Could anyone teach me how to prevent it?

Thanks!

Sort desc if item is included in an array with lodash or with out

I have a array of objects like so:

const attendList = [
{
  "first": "John",
  "last": "Foo",
  "uid": "-Lz8YxIYM_4L3f9nKM70",
},
{
  "first": "Jake",
  "last": "Foo",
  "uid": "-Lz8YxIYM_4L3fsdfM70",
}
...
]

Then I have an array containing the keys

const found = ["-Lz8YxIYM_4L3fsdfM70", "-Lz8YxIYM_4L3fsdf333", "-Lz8YxIYM_r4hfsdf333" ]

I want to sort attendList by placing the items that are in found at the bottom of the list. My incorrect attempt (using lodash) is:

let SetItemsLast = _.sortBy(attendList, ({uid}) => found.includes(uid) ? 0:1);

I’m obviously not doing it correctly. How can I resolve this?

Next.js inline script only loads once

I’ve implemented Tiny Slider in my Next.js app which requires an inline script on the page to control the slider’s behaviour. Now while the script loads properly the first time I launch index.js, every time I navigate to another page using Link and come back to index.js, the script doesn’t load.

Here’s how I’ve written the script in index.js

 {/* Script */}
        <Script id='tester'>
          {`
            var slider = tns({
              container: '.my-slider',
              items: 6,
              autoplay: true,
              autoplayTimeout: 2000,
              gutter: 20,
              autoplayButtonOutput: false,
              controls: false,
              navPosition: 'bottom',
              nav: false,
              mouseDrag: true,
              arrowKeys: true,
              responsive: {
                300: {
                  items: 2,
                  gutter: 50,
                  center: true,
                  fixedWidth: 250,
                },
                700: {
                  items: 3,
                  gutter: 50,
                  center: true,
                  fixedWidth: 250,
                },
                1440: {
                  items: 3,
                  gutter: 50,
                  fixedWidth: 250,
                  center: true,
                }
              }
            });
          `}
        </Script>

I need the script to load every time index.js loads, not just the first time around. Any ideas on how I can do this? The entire code is here – https://github.com/YaddyVirus/Esttheva

When I try to find the URL for an image using Chrome Developer Tool, there will sometimes be no URL and instead just show ::before or ::after

I am on a website, such as Reddit.com, and when I try to find the URL for an image using Chrome Developer Tool, there will sometimes be no URL. Instead, I will see ::before or ::after. So how can I find the URL to the image?

This is an example: I am trying to find the image URL of a home logo.Instead of showing the image URL, ::before shows up.

Update JavaScript with live

I got ten elements and I store them by querySelectorAll or getElementsByClassName(which return live HTML collections). Imagine they’re all having the same class name, I get a PHP function to filter them, so currently, only three of them are generated by PHP once the page is loaded, as I init the filter function, the other elements then only being generated.

But the variable is still storing the initial dom elements which are the three elements originally shown before the filter. Now how do I update the variable so that they include the new elements that are newly generated like after the filter button is clicked?

Getting a reference to a value of the target in a nested proxy

I use nested proxies like so in my code:

let proxyValidator = {
  get(target, property) {
    console.log(target)
    if(typeof target[property] == "object") {
      return new Proxy(target[property], proxyValidator)
    } else {
      return target[property]
    }

  },
  set(target, property, value) {
    console.log(target)
    target[property] = value
  }
}

This makes me able to do the following:

let colors = new Proxy({
  cold: {
    darker: {
      darkBlue: "#00008b",
      darkViolet: "#330066",
    },
    lighter: {
      lightGreen: "#90ee90",
      lightBlue: "#add8e6",
    }
  },
  warm: {
    orange: "#ffa500",
    red: "#00ff00",
  }
}, proxyValidator)

// Setting red to the true red color
colors.warm.red = "#ff0000" // Works.

colors.warm.red = "#ff0000" works, and really changes the value in the colors object. However, I cannot change the color this way:

let colorReference = colors.warm.red
colorReference = "#ff0000"

Shouldn’t I be getting a reference to colors.warm.red? If so, why does it not change, and how can I simulate this?
It’s quite important for me to use proxies because I’m developing a library.

Catch ERR_CONNECTION_REFUSED Error in React

I am trying to Catch an Error of my Fetch Function.

enter image description here

ive tried to catch my function with this:

updateState() {
    fetch('http://127.0.0.1:3333/xxx')
        .then((res) => res.json())
        .then((json) => {
                this.setState(() => {
                    return {
                        lightState: json.value
                    }
                });
            }
        ).catch(function () {
        console.log("error");
    });
}

but i still get the Errormessage in the console

PS:
In the Console i also get the “error” from the catch function. But the ERR_CONNECTION_REFUSED error still comes up

How do generator callback functions work for javascript express routing

I’m trying to understand how the following javascript code summary works

routes = router(); //express router
router.get('/home', callback);

const callback = function *(req, res, next) {
  const a = yield getFromDB(1) //Asynchronous
  const b = yield getFromDB(2) //Asynchronous
  return {
    status: 200,
    body: a + b
  };
};

When the /home url is called via a user, the app returns status 200 and a body of a + b. This implies that the callback generator function gets run all the way through. Does anyone know the specifics of what exactly happens? Is next() getting called on the generator until completion? Is the code blocked for the asynronous getFromDB()? Thanks an advance for anyones help!

extract campaigns containing different strings

I am trying to extract campaigns containing 2 different strings:

var keywordSelector = AdsApp.keywords()
 .withCondition("CampaignName CONTAINS_ANY ['Apple','Orange']")

I am aware CONTAINS_ANY operator works with labels only, so what would be the operator for campaign names?

something similar to IN operator that can extract multiple campaigns matching exactly:

var keywordSelector = AdsApp.keywords()
.withCondition("campaignName IN ['S_Apple_EX', 'S_Orange_EX']");

Not send image for a specific role | Discord.js and canvas

I don’t know how to describe this problem, but I just know that it doesn’t work on canvas when I want an image for a specific role:

if (interaction.member.roles.cache.has('980553630782464068') === user.id) list2.push("MODERATOR");
          .replace("MODERATOR", "Moderador", user.id)

It turns out that the image does not appear on the canvas, and this error is happening for a long time

CSS animation is bugged on certain position values

So, I have an element that transitions when hovering. However, there is a weird flickering bug when using some of the position values. It is very very weird and I’ve never seen anything like this.
Does anyone have any idea why this might happen?

works:
absolute, relative,

does not work:
fixed, sticky, static

How could I detect if there is an uppercase character in a string

I’ve read countless articles about people able to detect if all characters in a string are uppercase…

function isUpperCase(str) {
    return str === str.toUpperCase();
}


isUpperCase("hello"); // false
isUpperCase("Hello"); // false
isUpperCase("HELLO"); // true

But I’m curious how I can take a string, and search to see if any characters are uppercase, and if so, return true or return a string with the characters that are uppercase.

Any help is massively appreciated, I’m trying to avoid posts on here but I couldn’t find an answer that worked for me anywhere else.

ES6 JavaScript async await not resolving

The following code was an attempt to rework the recursive solution I posted here: How to do a Recursive ES6 Object Mutator.

This one is a simple match and replace, but has the same async dependency.

I have the following json input as a simple tester:

[
  {
    "name" : "dexterity ability score increase by 1",
    "description" : "your dexterity score increases",
    "benefit": {
      "appliesTo": "$$$StatisticDef|(#name#:#dexterity#,#type#:#ability#)",
      "appliesWhen": "ongoing",
      "atLevel": 1,
      "category": "addition",
      "value": 1
    }
  }
  
]

Two things to note here:

  1. the value for appliesTo. This is the string that I want to replace
    with a MongoDB fetched value (the async dependency).

  2. The structure is an array of 1 value, this is to show that the input
    could have many values

I’m running this in the following mocha test, using sinon for mocking (this is not part of this query, it all seems to work, I’m just showing how this is being executed).

describe('FeatureDefAdder suite', function () {

  var mock = sinon.mock(StatisticDef)
  

  test('should try again with the linear resolver', async function () {

    var queryObjJson = '{"name":"dexterity","type":"ability"}'
      mock
        .expects('findOne')
        .withArgs(JSON.parse(queryObjJson))
        .chain('select')
        .withArgs('_id')
        .chain('exec')
        .resolves('5dbff89209dee20b18091ec3')
    const data = JSON.parse(
      await readFile(
        new URL(
          '../../../../seeder/character/data/FeatureDef.json',
          import.meta.url
        )
      )
    )

    const result = await linearMongoObjectResolver(JSON.stringify(data))

    // returns data subbed by [object Promise]
    console.log('substituted: ' + result)

    const objectified = JSON.parse(result)
    console.log('objectified: ' + objectified)

    console.log('resval ' + objectified[0]['benefit']['appliesTo'])
  })
})

and now the matcher code:

const linearMongoObjectResolver = async (data) => {
  // assume data is any json screed
  // need to find text that matches /"([$]{3}.*#))"/ signifying the DSL string /([$]{3}.*#))/
  // in each case, use the content to pull out the Mongo schema class and the query for the findOne call
  console.log(' input data: ' + data)
  var copyData = data

  // "$$$StatisticDef|(#name#:#dexterity#,#type#:#ability#)"
  copyData = await copyData.replace(/([$]{3}.*#))/, async (match) => {
    //console.log({ match })

    var parts = splitForeignKeyReference(match)
    var queryObjJson = jsonify(parts[1])

    console.log(
      ' mongoObj: ' +
        parts[0] +
        ' querydsl: ' +
        parts[1] +
        ' queryobjjson: ' +
        queryObjJson
    )

    // query obj = {name: 'dexterity', type: 'ability'}
    // console.log(' typeof query is object?: ' + typeof JSON.parse(queryObjJson))
    var subbedInstance = '""'
    console.log(' 1.subbedInstance: ' + subbedInstance)
    if (parts[0] === 'StatisticDef') {
      subbedInstance = await StatisticDef.findOne(
        JSON.parse(queryObjJson)
      ).select('_id')
    }
    console.log(' 2.subbedInstance: ' + subbedInstance)

    return subbedInstance
  })

  return copyData
}

and the (truncated) test output:

 input data: [{"name":"dexterity ability score increase by 1","description":"your dexterity score increases","benefit":{"appliesTo":"$$$StatisticDef|(#name#:#dexterity#,#type#:#ability#)","appliesWhen":"ongoing","atLevel":1,"category":"addition","value":1}}]
 mongoObj: StatisticDef querydsl: (#name#:#dexterity#,#type#:#ability#) queryobjjson: {"name":"dexterity","type":"ability"}
 1.subbedInstance: ""
substituted: [{"name":"dexterity ability score increase by 1","description":"your dexterity score increases","benefit":{"appliesTo":"[object Promise]","appliesWhen":"ongoing","atLevel":1,"category":"addition","value":1}}]
objectified: [object Object]
resval [object Promise]
 2.subbedInstance: 5dbff89209dee20b18091ec3

So despite the “subbedInstance” getting the value, after the Promise resolution, the “substituted” console output (at the test level) shows the unresolved “[object Promise]” for the “appliesTo” value.

So why does the awaited value remain unresolved? even though it actually is resolved?

React Transition Group with css modules not applying classes

I have a next js app using scss modules where i am trying to use react transition group on a hamburder menu when list items are clicked in to.

The classes from my module don’t seem to be getting applied to the css transition.

const HamburgerMenu: FC = () => {
    const [menu, setMenu] = useState<string>('main');
    const [animationIn, setAnimationIn] = useState<boolean>(false);
    const changeMenu = (value: string): void => {
        setMenu(value);
        setAnimationIn(true);
    };
    return (
        <nav className={style.nav}>
            {menu === 'main' && (
                <ul>
                    <li>HOME</li>
                    <li onClick={() => changeMenu('resources')}>
                        FREE RESOURCES
                        <span className={style.chevron}>{'  >'}</span>
                    </li>
                    <li onClick={() => changeMenu('courses')}>
                        COURSES
                        <span className={style.chevron}>{'  >'}</span>
                    </li>
                    <li>BLOG</li>
                    <li>SHOP</li>
                    <li>CONTACT</li>
                </ul>
            )}
            {menu === 'resources' && (
                <CSSTransition
                    in={animationIn}
                    timeout={200}
                    classNames={{
                        enter: style['transition-enter'],
                        enterActive: style['transition-enter-active'],
                        exit: style['transition-exit'],
                        exitActive: style['transition-exit-active'],
                    }}
                >
                    <Resources changeMenu={changeMenu} />
                </CSSTransition>
            )}
            {menu === 'courses' && (
                <CSSTransition
                    in={animationIn}
                    timeout={200}
                    classNames={{
                        enter: style['transition-enter'],
                        enterActive: style['transition-enter-active'],
                        exit: style['transition-exit'],
                        exitActive: style['transition-exit-active'],
                    }}
                >
                    <Courses changeMenu={changeMenu} />
                </CSSTransition>
            )}
        </nav>
    );
};

export default HamburgerMenu;

type MenuProps = {
    changeMenu: (val: string) => void;
};

const Courses: FC<MenuProps> = ({ changeMenu }) => {
    return (
        <ul>
            <li onClick={() => changeMenu('main')}>
                <span className={`${style.chevron} ${style.left}`}>
                    {'<  '}
                </span>
                BACK
            </li>
            <li>IN-PERSON</li>
            <li>ONLINE</li>
        </ul>
    );
};

const Resources: FC<MenuProps> = ({ changeMenu }) => {
    return (
        <ul>
            <li onClick={() => changeMenu('main')}>
                <span className={`${style.chevron} ${style.left}`}>
                    {'<  '}
                </span>
                BACK
            </li>
            <li>MY BOOK</li>
        </ul>
    );
}; 

When a particular list item is clicked the change menu function gets called and sets the setMenu state to a string which will render a different component.

Originally my in property used the truthy value of

menu === 'resources'

for example, but then also tried using a setAnimation hook in case i needed to have the value turn to true after the component was mounted but that doesnt seem to work either.

Any ideas?

Here is my css module file.

.transition {}

.transition-enter {
    opacity: 0.01;
    transform: translate(0, -10px);
    border: 1px solid red;
  }
  .transition-enter-active {
    opacity: 1;
    transform: translate(0, 0);
    transition: all 300ms ease-in;
  }
  .transition-exit {
    opacity: 1;
    transform: translate(0, 0);
  }
  .transition-exit-active {
    opacity: 0.01;
    transform: translate(0, 10px);
    transition: all 300ms ease-in;
  }