app script – need help to build a function that set data validation in column B and a dependant data validation in column C

I have a sheet(“validazione”) that contain Last Names(col A) and relative First Names(col B)
The list is huge, so many last names are in the list more than one time with different first name. In the sheet “validazione” i also tried to make last names “unique” and transpose first names in different columns if maybe is easier to get data.

What i want is to made a such of control of data inserted in the sheet “casting” using data validation.
About last names i got it. so when i run the function it fill data validation based on last name source.
But is about first names that i have problem: i want to have a filtered data validation there, that it will show me just the first names related to last names. For example if i have smith john, smith ron, smith jane when i digit or i paste smith in last names, i want that are showed just john,ron,jane and not all the first names in database.

I hope you understood and that you can help me.

here down i have a link to the sheet, and i will paste the code

thank you in advance

https://docs.google.com/spreadsheets/d/1Yv4v3JJCXi_ipAb30aTwsKzZuloeVlluLfLslLmie8Q/edit#gid=0

function setValidation() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var validationSheet = ss.getSheetByName("APPOGGIO DATABASE");
  var dataSheet = ss.getSheetByName("CASTING");

  // Impostazione della convalida dati per i cognomi
  var rangeCognomi = dataSheet.getRange("B3:B1000");
  var cognomiRule = SpreadsheetApp.newDataValidation().setAllowInvalid(false).requireValueInRange(validationSheet.getRange("D2:D"), true).build();
  rangeCognomi.clearDataValidations();
  rangeCognomi.setDataValidation(cognomiRule);
  var casting = dataSheet.getActiveRange().getValues()
  var dati = ss.getRange("D2:E").getValues()
      var nFiltrati = dati.filter(function(filtro){return filtro[0] == casting }) 
  var convNomi = nFiltrati.map(function(list){return list[1] })    
  var cdNomi = SpreadsheetApp.newDataValidation().requireValueInList(convNomi).build()
  ss.getActiveRange().setDataValidation(cdNomi)
 
    }

i tried to use a support sheet for get range but i can’t understand the logical steps to get a filtered value in a single cell. I am a newbie of coding, so i am sure that someone could give me the right way to work on

Flash Messages doesn’t appear – Flask

I have a problem with displaying flash messages using flask.

I followed the online documentation step by step, but it still won’t work.

This is the code i’ve written:

routes.py

from flask import Blueprint, render_template, request, flash

routes = Blueprint('routes', __name__)

# Home route
@routes.route('/')
def home():
    user_agent = request.headers.get('User-Agent')
    """ check = user_agent.find("Instagram") """
    check = 1

    if check == 1:
        flash('It looks like you're using Instagram's built-in browser. Using this browser might result in reduced user experience.', category='info')

    return render_template("home.html", agent = user_agent, flag = check)

base.html

    ...........
    {% with messages = get_flashed_messages(with_categories=true) %}
    {% if messsages %}
    {% for category, message in messages %}
    {% if category == 'info' %}
    <div class="alert alert-info alert-dismissable fade show" role="alert">
        {{ message }}
        <button type="button" class="close" data-dismiss="alert">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    {% endif %}
    {% endfor %}
    {% endif %}
    {% endwith %}

    {% block content %}
    {% endblock %}
    .............

Can anyone help me? I don’t know how to move in this case

TypeError: event.target is undefined [closed]

Trying to make a score system but i keep getting this event.target error can someone help?

onEvent("L1Q1", "click", function(event) {
  var guess = event.target.id;
  if (guess === "L1Q1") {
    score++;
    setScreen("RigtigSkærm");
  } else {
    score--;
    setScreen("Forkertskærm");
  }
  setText("score_label_" + currentLevel, "Score: " + score);
});

Im not really “good” at coding so i didnt realy try anything

have to make subcollection inside firebase setup

I want to make one collection starts with
all_delivery > {hash_id} already generate called this.delivery_client_hashid > “this_client_delivey” > {random hash unknwon}

const get_id2 = firebase.firestore().collection('all_delivery').doc(this.delivery_client_hashid).collection("this_client_delivery").doc();

but I get this error:

FirebaseError: Invalid document reference. Document references must
have an even number of segments, but
all_delivery/5BcX5Mf6TujUiOSk6eup/this_client_delivery has 3.

The reason I leave doc to be blank becuase I want random hash, what’s the reason for the error and how get I get random hash generate after "this_client_deliver"

Can slicing beyond an array’s boundaries cause issues?

I noticed that when I use slice to return elements that are beyond the limits of an array, it just stops at the end of the array and it doesn’t produce an error. Is there ever an issue with doing this? E.g.

EntryMap.forEach(function (url, index) {
    //Get the next 10 entries after the current entry and turn them into a map
    let NextEntriesArr = EntryMap.slice(index, index + 9);
    return nextEntriesArr;
}

Once we iterate through the last few elements in the array here, NextEntriesArr holds one less value each iteration until we’re at the end of the array. No error occurs. Can I leave my code like this?

Refactor this function to reduce its Cognitive Complexity using React

Trying to understand Cognitive Complexity with the following example. Is it more about reducing codes to its simplest form??

How do I optimize my code and make it more readable. The condition is if the array objects has a property “average”, then display a table with average column else don’t display the average column.

let columns: any[] = []

export const tableHeaders = (arr) => {
    if (arr?.length > 0 && arr?.some(x => x.hasOwnProperty('average'))) {

        if(arr?.some(x => x.average  == "NA"))
        {
            columns = [
                {
                    Header: 'MONTH',
                    accessor: 'date',
                    sortType: (a:any, b:any) => {
                        return (new Date(a.values.date).getTime() < new Date(b.values.date).getTime() ? -1 : 1)
                    }
                },
                {
                    Header: 'TOTAL',
                    accessor: 'total',
                } 
            ]
        }
        else{
            columns = [
                {
                    Header: 'MONTH',
                    accessor: 'date',
                    sortType: (a:any, b:any) => {
                        return (new Date(a.values.date).getTime() < new Date(b.values.date).getTime() ? -1 : 1)
                    }
                },
                {
                    Header: 'TOTAL',
                    accessor: 'total',
                },
                {
                    Header: 'AVERAGE',
                    accessor: 'average',
                }    
            ]
        }
    }
    else
    {
        columns = [
            {
                Header: 'MONTH',
                accessor: 'date',
                sortType: (a:any, b:any) => {
                    return (new Date(a.values.date).getTime() < new Date(b.values.date).getTime() ? -1 : 1)
                }
            },
            {
                Header: 'TOTAL',
                accessor: 'total',
            }  
        ]
    }

    return columns
}

Bootstrap JavaScript in Webpack 5 – only working as ESM?

When importing Bootstrap JS components directly, the functionality doesn’t fully work but no errors are shown in the console:

import Dropdown from 'bootstrap/js/dist/dropdown'

The method below works but includes all of bootstrap JS, even parts not being used

import { Dropdown } from 'bootstrap'

With the first import, I can see Popper positioning the dropdown when the toggle is clicked but nothing is displayed, and aria-expanded attribute doesn’t toggle. Same result in webpack development/production mode. Manually instantiating the dropdown in JS also doesn’t make any difference:

const myDropDown = Dropdown.getOrCreateInstance(myDropDownToggle);

What am I missing?

How to iterate through Page Object selectors declared in the constructor (Playwright)

I’ve got a web page, where I have defined numbers of filters. Chosing value for a single filter immediately affects shown results. I’m trying to define a function that will iterate through each filter, assert results are updated, then clean the filter. This action will be perform for each of the filters.

The moment of performing the iteration gives me troubles. I’m open to any other approach of defining my selectors, the function as long as it fulfills the goal.

Here’s my Page class:

import { Page, Locator} from '@playwright/test'

export Class MyPage {
   readonly page: Page;
   readonly filterA: Locator;
   readonly filterB: Locator;
   readonly filterC: Locator;
   ...and so on...
}

constructor(page: Page) {
   this.page = page;
   this.filterA = page.getByTestId('filterA');
   this.filterB = page.getByTestId('filterB');
   this.filterC = page.getByTestId('filterC');
   ...and so on...
}

async applySingleFilter() {

   const filterWithValues = {
        filterA: "1",
        filterB: "2",
        filterC: "3"
   }
 
   let filter: any = null;
   for (filter in filtersWithValues) {
       this.hereMyProblem.selectOption(filtersWithValues[filter])
   }
   // next action that will happen within this method:
   // assert that filter affected shown results
   // perform cleaning the filter
}
  1. I tried putting my selectors within the constructor into an array, but I cannot refer to them in the this.heresMyProblem.selectOption(filtersWithValues[filter])

transform whole text to make a sum in JasperReport

In my report I try to count the number of dormant stops materializing in my database by the value yes/no. The trouble is I can’t in jasper tranform the text in integer.

I tested in sum calculation integer class
expression:value ==$F{arret_dorm} != null && $F{arret_dorm}. equalsIgnoreCase(“yes”)? 1: 0
or I also tested this IF( $F{arret_dormant} =”No”,1,0)
and for initial value 1
the problem is that I have an error message saying that “he operator!= is undefined for the argument type(s) boolean, null
so that it is not an integer at once as I can aire to transform my initial value into integer? I tried parseInt(): value expression:$F{arret_dorm}.getValue.parseInt(Oui,1) but it didn’t work.

Angular 12 web component incorrectly appending dropdowns

I want to create a web element with angular, it includes inside some components, such as primeng split-button, and its going to be used with Vanilla JS.

Split-button has a property “appendTo”, which takes target element to attach the overlay, valid values are “body” or a local ng-template variable of another element. Even if i set it as ‘body’, or HTMLBodyElement it keeeps appending to itself. Even if I call web-element in overlay window and pass a correct node to appendTo it keeps appearing right next after button.Example of settings, even string ‘body’ performes the same resultWrong position it has to be in the end of body tag

Is there some chances to fix it, maybe I have to build each inside component as a web-element and then only create a full covering?

The property of the question is to make dropdown instances appending to right element, not to itself.

How to Add spinner for infinity scroll with ajax

I have PHP HTML script where data is fetching from database with infinity scroll feature. Sometime if internet is slow it’s taking more time for showing next data. So I want to add loading spinner when data is loading after scroll. I am using jQuery bootstrap and ajax

This is my html code.

<div class="container">

    

      <div style="margin-top:70px; margin-bottom:0px;" class="form-group">

        <div class="input-group">

          <span class="input-group-addon">Search</span>

          <input style="z-index:1;" type="text" name="search_text" id="search_text" placeholder="Search Name, Father Name, Mobile" class="form-control" />

        </div>

      </div>

      <br />

      <div id="result"></div>

    </div>

This is my javascript code.

<script>

  $(document).ready(function() {

  var start = 0;

  var limit = 20;

  var reachedMax = false;

  

  function load_data() {

  if (reachedMax) return;

  $.ajax({

  url: "search.php",

  method: "POST",

  data: {

  start: start,

  limit: limit,

  query: $('#search_text').val()

  },

  success: function(data) {

  if (data == '') {

  reachedMax = true;

  } else {

  $('#result').append(data);

  start += limit;

  }

  }

  });

  }

  

  $('#search_text').on('keyup', function() {

  start = 0;

  reachedMax = false;

  $('#result').empty();

  load_data();

  });

  

  load_data();

  

  $(window).scroll(function() {

  if ($(window).scrollTop() == $(document).height() - $(window).height())

  load_data();

  });

  });

  </script>

**This is my Search.php file **

<?php

include 'conn.php';

$output = '';

$start = $_POST["start"];

$limit = $_POST["limit"];

$hasMoreData = true;

if (isset($_POST["query"]) && !empty($_POST["query"])) {

    $search = mysqli_real_escape_string($connect, $_POST["query"]);

    $query = "SELECT * FROM user_list 

              WHERE name LIKE '%" . $search . "%'

              OR phone LIKE '%" . $search . "%' 

              OR fname LIKE '%" . $search . "%' 

              ORDER BY CASE frequency WHEN 'One Time' THEN 0 ELSE 1 END DESC, bakaya_month DESC

              LIMIT $start, $limit";

} else {

    $query = "SELECT * FROM user_list 

              ORDER BY CASE frequency WHEN 'One Time' THEN 0 ELSE 1 END DESC, bakaya_month DESC

              LIMIT $start, $limit";

}

$result = mysqli_query($connect, $query);

if (mysqli_num_rows($result) > 0) {

    while ($row = mysqli_fetch_array($result)) {

        $output .= '

            <form id="myForm-' . $row["id"] . '" action="profile.php" method="get">

                <input type="hidden" name="user-id" value="' . $row["id"] . '">

                <div class="user-list">

                    <div class="user-image">

                        <img src="upload/' . $row["image"] . '" alt="User Image" onclick="openPopup(this.src)">

                    </div>

                    <div onclick="submitForm('myForm-' . $row["id"] . '')" class="user-info">

                        <h4>' . $row["name"] . '</h4>

                        <p>' . $row["fname"] . '</p>

                    </div>

                    <div onclick="submitForm('myForm-' . $row["id"] . '')" class="unread-count" data-unread="' . $row["bakaya_month"] . '">' . $row["bakaya_month"] . '</div>

                </div>

            </form>

        ';

    }

} else {

    $hasMoreData = false;

    if ($start == 0) {

        $output .= 'Data Not Found';

    }

}

echo $output;

if (!$hasMoreData) {

    exit();

}

?>

Is there a way to fix React not showing?

Please help me

My React project was displaying very well on localhost until today when I start the project with NPM start I can only white screen on chrome

No error.

I’m using window 10
all my IIS are on
I reinstalled them

Please how can I fix this.

Storing pointers to class-level functions in a class-level map

I’m creating a kind of factory class, where I store some pointers to class-level functions in a map, and the main factory function uses the map to determine how to create the service to be returned. Below is a simplified version:

class ServiceFactory {
  constructor() {
    this._serviceInstances = new Map();
    this._serviceCreators = new Map([['someID', this._getSpecificService]]);
  }

  getService(identifier) {
    const serviceGetter = this._serviceCreators.get(identifier) || this._getDefaultService;
    return serviceGetter();
  }

  _getSpecificService() {
    return this._getServiceInstance(SpecificService);
  }

  _getDefaultService() {
    return this._getServiceInstance(DefaultService);
  }

  _getServiceInstance(serviceConstructor) {
    let instance = this._serviceInstances.get(serviceConstructor);
    if (!instance) {
      instance = new serviceConstructor();
      this._serviceInstances.set(serviceConstructor, instance);
    }
    return instance;
  }
}

Usage of this is as follows:

const factory = new ServiceFactory();
const service = factory.getService('someID');
// expect(service).toBeInstanceOf(SpecificService);

However I’m running into an error where the getServiceInstance appears to be undefined

Cannot read property ‘getServiceInstance’ of undefined

I’m expecting the chain of calls to be:

  • getService -> _getSpecificService -> _getServiceInstance

However what I’m seeing is:

  • getService -> _getSpecificService -> undefined

What’s going on here? I’m storing a reference to this._getSpecificService (which has a reference to this._getServiceInstance) in a map, however when the former is called, the latter does not appear to exist?

How do I detect page reload not page change in react application

Is there any way I can detect page reload on react app. I only want to detect when the page is reloaded when user clicks the reload button or shortcut keys to reload the page not when the page changes without reload when using react router.

I tried using beforeunload but it also detects page changes that react router does.

useEffect(() => {
    window.addEventListener("beforeunload", alertUser);
    return () => {
      window.removeEventListener("beforeunload", alertUser);
    };
  }, []);

Material ui Autocomplete : Get data from URL and preselect a field ONLY if there is a match

I’m working on a page using MUI Autocomplete, I want to get a choice from URL and preselect the autocomplete field with it if exist, and if not to select nothing and show the default Autocomplete without any selection.

I’m trying with something like this :

const {elementFromUrl} = useParams() // john
const dataArray = [{id:1,name:'simon'},{id:2,name:'john'},{id:3,name:'micka'}]
<Autocomplete
                  defaultValue={elementFromUrl?.toUpperCase() || null}
                  loading={isLoading}
                  fullWidth
                  onChange={(e, value) => setApplication(value?.name)}
                  disablePortal
                  getOptionLabel={(option) =>
                    option?.name || elementFromUrl?.toUpperCase()
                  }
                  id="combo-box-demo"
                  options={dataArray}
                  sx={{ width: 500 }}
                  PaperComponent={({ children }) => (
                    <Paper>
                      {children}
                    </Paper>
                  )}
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Applications"
                    />
                  )}
                />

But the problem here is it’s works perfectly when the element exist in my array, but if I try another one that not exist the autocomplete show it as preselected one.
I want to selected ONLY if it exist, have you an idea how to achieve this ?

In the console I get :

MUI: The value provided to Autocomplete is invalid.
None of the options match with `"CCCCCCCCCCCC"`.
You can use the `isOptionEqualToValue` prop to customize the equality test.