Why do jest tests fail with a stacktrace pointing to very first character of the test declaration?

I have a collection of Jest tests that run in CI. They normally pass, and when they fail, jest normally shows the error location and stack trace and failures are easy to fix.

However, occasionally, seemingly random tests fail with a mysterious stacktrace that gives no indication what the actual issue is. Instead, Jest just points to the actual test declaration function and gives no other helpful info.

What sort of failure does this indicate in Jest? I’m struggling to understand the class of issue that this indicates.

Example failure:

 FAIL  __test__/server/api/v1/externalApi.test.ts (338.997 s, 790 MB heap size)
  ● external API v1 › with base project › Should be able to get all runs for a project



      372 |     });
      373 |
    > 374 |     it("Should be able to get all runs for a project", async () => {
          |     ^
      375 |       //simulate the project being published
      376 |       await hexVersionRepo.update(hexVersion.id, {
      377 |         published: true,

      at it (__test__/server/api/v1/externalApi.test.ts:374:5)
      at describe (__test__/server/api/v1/externalApi.test.ts:125:3)
      at Object.describe (__test__/server/api/v1/externalApi.test.ts:63:1)

And then a separate log of the stacktrace shows the following:

Error: 
    at it (/home/circleci/project/packages/integration-tests/__test__/server/api/v1/externalApi.test.ts:374:5)
    at _dispatchDescribe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:596:26)
    at describe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:564:44)
    at describe (/home/circleci/project/packages/integration-tests/__test__/server/api/v1/externalApi.test.ts:125:3)
    at _dispatchDescribe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:596:26)
    at describe (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/jestAdapterInit.js:564:44)
    at Object.describe (/home/circleci/project/packages/integration-tests/__test__/server/api/v1/externalApi.test.ts:63:1)
    at Runtime._execModule (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:1247:24)
    at Runtime._loadModule (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:909:12)
    at Runtime.requireModule (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runtime/build/index.js:812:12)
    at jestAdapter (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-circus/build/runner.js:92:13)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at runTestInternal (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runner/build/testWorker.js:262:16)
    at runTest (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runner/build/testWorker.js:326:7)
    at Object.worker (/home/circleci/project/node_modules/.pnpm/[email protected]/node_modules/jest-runner/build/testWorker.js:480:12)

Find when pattern appear in memory with Frida

I have peace of code that search pattern in memory with Frida

let pattern = "aa bb cc dd ee ff 11 22 33 44 55 66 77 88 99 00"
Process.enumerateRanges('--rw-')  
    .forEach(range => {
        Memory.scan(range.base, range.size, pattern, {
            onMatch(address, size) {
                const mod = Process.findModuleByAddress(address);
                console.log("Found at: " + address + " in module: " + (mod ? mod.name : "unknown"));
            },
            onComplete() { }
        });
    });

How can I edit that code to search every time when that code appear in memory?

I want to know which code insert that pattern to memory?
Maybe read/memory/recv I don’t know

How do I add options to my bootstrap select statement? [closed]

I want to use bootstrap-select, specifically the selectpicker class with data-live-search. But I wanted to dynamically create the select dropdown, which should take an array of options and input those options into the HTML.

This can be done very easily without bootstrap, like this…

HTML:

<select id="options">
  <option>One</option>
</select>

JavaScript:

var select = document.getElementById("options");
select.innerHTML += "<option>Two</option>"

Resulting HTML:

<select id="options">
  <option>One</option>
  <option>Two</option>
</select>

But if you try that code in a snippet like this, it doesn’t work. There is even documentation saying it is very difficult to do.

<head>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta2/css/bootstrap-select.min.css">
</head>

<body>
  <select id="options" class="selectpicker" multiple aria-label="Default select example" data-live-search="true">
    <option value="1">One</option>
  </select>
</body>

<footer>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta2/js/bootstrap-select.min.js"></script>
</footer>

How to do group objects by a specific property in javascript

I am tying to group objects by a specific property from an array object without using reduce method. Is it possible? If it is possible how to do it?

const arr = [
  { name: 'Alice', age: 21 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 21 },
  { name: 'David', age: 25 },
  { name: 'Eve', age: 30 }
];

Output should be like below:

console.log(arr);

// {
//   '21': [{ name: 'Alice', age: 21 }, { name: 'Charlie', age: 21 }],
//   '25': [{ name: 'Bob', age: 25 }, { name: 'David', age: 25 }],
//   '30': [{ name: 'Eve', age: 30 }]
// }

Performance Issues in React Hook Form with watch() and Select dropdown

I’m using React Hook Form (RHF) for form handling and Yup for validation in my React app. I have a dynamic list of rows, each containing an Autocomplete component from Material-UI (MUI), along with other form fields. The goal is to validate and track each row’s input.

Issue:
When I change the value of an Autocomplete dropdown in one of the rows, I use the watch() function from RHF to check if the selected option has already been used elsewhere in the form. This is done to prevent selecting a duplicate option in any of the rows.

While this approach works correctly, I’m encountering performance issues when the watch() function is active. Specifically, when I change a dropdown value, the form becomes very slow, and other inputs start lagging significantly. This issue doesn’t occur until I change the Autocomplete value, and once the dropdown value is updated, the form’s responsiveness suffers.

What I’m trying to achieve:
I need to track the value of the Autocomplete dropdown and check for duplicates across rows using watch().

At the same time, I want the form to remain fast and responsive, even when the dropdown values are updated.

Here’s a simplified version of my code:

<Controller
  control={control}
  name={`goals.${index}.${GoalInputs.TERRITORY}`}
  render={({ field: { onChange, ...field } }) => {
    const findTerritory = territoryOptions?.find(({ value }) => value === field?.value);
    return (
      <SingleSelect
        {...field}
        fullWidth
        options={territoryOptions}
        value={findTerritory || null}
        onValueChange={(_, value) => {
          const goals = watch('goals') as GoalValues[];
          const isExist = goals?.find(({ territory }: any) => territory === value?.value);
          if (isExist) {
            showError({ message: 'This territory is already selected' });
            onChange('');
          } else {
            onChange(value?.value);
          }
        }}
        error={!!error?.[GoalInputs.TERRITORY]}
        helperText={error?.[GoalInputs.TERRITORY]?.message as string}
        sx={{ minWidth: 200 }}
      />
    );
  }}
/>

enter image description here

I have tried ChatGPT to solve the issue, but it didn’t work.
Also, I have tried to use the getValues function, but it was also having the same problems.

In a react native project, Zod and React Hook Form not working properly together

Trying to integrate React Hook Form and Zod in a react native project by applying validation rules using Zod to a signup form, but when I press the button, Zod isn’t triggered to show any errors, even if the input fields are empty

const signUpSchema = z.object({
  firstName: z
    .string({ message: 'First name is required' })
    .min(2, { message: 'First name must be longer than 2 characters' }),
  lastName: z
    .string({ message: 'Last name is required' })
    .min(2, { message: 'Last name must be longer than 2 characters' }),
  mobileNom: z.string({ message: 'Mobile number is required' }),
  email: z.string({ message: 'Email is required' }),
  password: z
    .string({ message: 'Password is required' })
    .min(8, { message: 'Password must be longer than 8 characters' }),
});

const AuthForm = ({
  headerText,
  navLinkText,
  submitBtnText,
  onSubmit,
  routeName,
  error,
}) => {
  const [permissionResponse, requestPermission] = MediaLibrary.usePermissions();
  const [image, setImage] = useState();

  // START
  const form = useForm({
    resolver: zodResolver(signUpSchema),
    defaultValues: {
      firstName: '',
      lastName: '',
      mobileNom: '',
      email: '',
      password: '',
    },
  });

  // END

  async function handleUpload() {
    if (permissionResponse.status !== 'granted') {
      await requestPermission();
    }

    let result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ['images', 'videos'],
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
  }

  return (
    <KeyboardAvoidingView
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      style={{ flex: 1 }}
    >
      <SafeAreaView edges={['bottom']}>
        <ScrollView
          contentContainerStyle={styles.container}
          keyboardShouldPersistTaps="handled"
        >
          <FormProvider {...form}>
            <Text style={styles.text}>{headerText}</Text>
            <Text style={styles.note}>
              * Please note that every field must be filled.
            </Text>
            {routeName == 'login' && (
              <>
                <View style={styles.name}>
                  <CustomTextInput
                    containerStyle={{ flex: 1 }}
                    placeholder="First Name"
                    name="firstName"
                  />
                  <CustomTextInput
                    containerStyle={{ flex: 1 }}
                    placeholder="Last Name"
                    name="lastName"
                  />
                </View>
                <CustomTextInput
                  autoCapitalize="none"
                  autoCorrect={false}
                  placeholder="Mobile Number"
                  inputMode="numeric"
                  name="mobileNom"
                />
              </>
            )}
            <CustomTextInput
              autoCapitalize="none"
              autoCorrect={false}
              placeholder="Email"
              inputMode="email"
              name="email"
            />
            <CustomTextInput
              autoCapitalize="none"
              autoCorrect={false}
              secureTextEntry
              placeholder="Password"
              name="password"
            />
            {routeName === 'login' && (
              <CustomTextInput
                autoCapitalize="none"
                autoCorrect={false}
                secureTextEntry
                placeholder="Confirm Password"
                name="confirmPassword"
              />
            )}
            {routeName == 'login' && (
              <Pressable style={styles.upload} onPress={handleUpload}>
                <Feather name="upload" style={styles.icon} />
                <Text style={styles.uploadText}>Upload your syndicate id</Text>
              </Pressable>
            )}

            {routeName == 'signup' && (
              <Pressable onPress={() => {}}>
                <Text style={styles.note}>Forgot your password?</Text>
              </Pressable>
            )}
            <Pressable style={styles.btn} onPress={form.handleSubmit(onSubmit)}>
              <Text style={styles.btnText}>{submitBtnText}</Text>
            </Pressable>
            <Link style={styles.btnSecondary} href={routeName}>
              {navLinkText}
            </Link>
          </FormProvider>
        </ScrollView>
      </SafeAreaView>
    </KeyboardAvoidingView>

and this is the code for each input field


const CustomTextInput = ({ containerStyle, name, ...textInputProps }) => {
  const {
    field: { value, onChange, onBlur },
    fieldState: { error },
  } = useController({ name });


  return (
    <View style={[styles.field, containerStyle]}>
      <TextInput
        {...textInputProps}
        style={[styles.input, error ? styles.errorInput : {}]}
        value={value}
        onChangeText={onChange}
        onBlur={onBlur}
      />
      <Text style={styles.error} numberOfLines={1}>
        {error?.message}
      </Text>
    </View>
  );
};

Zod rules never show up on the screen or in the console

add css style with both php and Javascript

I got a .css file linked to my HTML file.
And somewhere, as a basis to my question, I got this:

<div class="input_container">

Later on, with javascript, I can add a .error to activate some class changes.

inputControl.classList.add('error');

Changing the class="input_container" to <div class="input_container.error">

Perfect.
But now when I enter this page through a diffrent direction, I want/need PHP to add this .error aswell.

And the following (simplified) does to work.

$style = "input_container";
<div class=<? echo """.$style."""; ?>>

Chart.js Stacked Horizontal Bar Char Leading White Space

I’m using Chart.js in a Vue 3 application. I have this thing just about wrapped up with how I want it. However, there is this small white gap before the start of the graph as it is drawn that I cannot seem to get rid off. There is no gap at the end of the chart when I inspect it. I’d like to be able to get rid of it as it throws of the centering of the chart in its container. Worse case I’ll negative pad it but that feels hacky.

Thanks in advance for any insight on how to remove this.

Here is the configuration options I’m using so far

const options = computed(() => ({
  indexAxis: "y",
  responsive: true,
  maintainAspectRatio: false,
  plugins: {
    legend: { display: false },
    tooltip: { enabled: false },
    datalabels: { display: false },
  },
  scales: {
    x: {
      stacked: true,
      min: 0,
      max: total.value,
      beginAtZero: true,
      grid: { display: false, drawBorder: false },
      ticks: { display: false },
      border: { display: false },
      barPercentage: 1.0,
      categoryPercentage: 1.0,
    },
    y: {
      stacked: true,
      beginAtZero: true,
      grid: { display: false, drawBorder: false },
      ticks: { display: false },
      border: { display: false },
      barPercentage: 1.0,
      categoryPercentage: 1.0,
    },
  },
  animation: {
    duration: 800,
    easing: "easeOutQuart",
  },
  layout: {
    padding: 0,
  },
  chartArea: {
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
  },
}));

And here is the gap that I’m dealing with

chart.js bar gap

Does anybody have a good frontend for an xhr backend communication? [closed]

This Node.js application uses Express and MySQL to serve book and order data through various API endpoints. The server listens on port 3000 and uses a custom lekerdez function that wraps db.query in a Promise for cleaner async handling. It exposes endpoints like /vegpont, /vegpont2, /tipusok, /regenyek, and /magyarul, each running different SQL queries to retrieve information such as book counts, categories, titles, and filtered order data. Error handling is included, returning appropriate HTTP 500 responses when SQL queries fail. Static files are served from the public directory.

Does anybody have a frontend solution for this backend?

const express = require('express');
const mysql = require('mysql');

const app = express();
app.use(express.static("public"));

const db = mysql.createConnection({
    host: '',
    user: '',
    database: ''
});

app.listen(3000,() => {
    console.log('A szerver elindult a 3000-es porton...');  
});

function lekerdez(sql) {
    return new Promise((resolve, reject) => { 
      db.query(sql, (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        } 
      });
    });
}   

app.get('/vegpont',(req, res) => {   
    const sql1 = `SELECT COUNT(*) AS 'osszes', (COUNT(*) * rg.ar) AS 'osszeg', rg.id, rg.kategoria, rg.magyar, rg.angol, rg.ev, rg.ar
                FROM regeny rg left JOIN rendeles re ON rg.id = re.regenyid GROUP BY rg.id;`;
    lekerdez(sql1)
    .then((adatok)  => {
        res.send(adatok);
    })
    .catch((hiba) => {
        console.log(hiba);
        res.status(500).send(`Hiba történt az adatok lekérdezése során: ${hiba}`);
    });    
});

app.get('/vegpont2',(req, res) => {   
    const sql1 = `SELECT * from rendeles;`;
    lekerdez(sql1)
    .then((adatok)  => {
        res.send(adatok);
    })
    .catch((hiba) => {
        console.log(hiba);
        res.status(500).send(`Hiba történt az adatok lekérdezése során: ${hiba}`);
    });    
});

app.get('/tipusok',(req, res) => {   
    const sql1 = `SELECT kategoria AS 'Főszereplő', COUNT(*) AS 'Regények száma' FROM regeny GROUP BY kategoria;`;
    lekerdez(sql1)
    .then((adatok)  => {
        res.send(adatok);
    })
    .catch((hiba) => {
        console.log(hiba);
        res.status(500).send(`Hiba történt az adatok lekérdezése során: ${hiba}`);
    });    
});

app.get('/regenyek',(req, res) => {   
    const sql1 = `SELECT magyar FROM regeny ORDER BY magyar;`;
    lekerdez(sql1)
    .then((adatok)  => {
        res.send(adatok);
    })
    .catch((hiba) => {
        console.log(hiba);
        res.status(500).send(`Hiba történt az adatok lekérdezése során: ${hiba}`);
    });    
});

app.get('/magyarul',(req, res) => {
    const sql1 = `SELECT re.datum AS 'Dátum', re.darab AS 'Mennyiség' FROM regeny rg left JOIN rendeles re ON rg.id = re.regenyid WHERE rg.magyar = "${req.query.magyar}" AND re.darab > 1 ORDER BY re.datum;`;
    lekerdez(sql1)
    .then((adatok)  => {
        res.send(adatok);
    })
    .catch((hiba) => {
        console.log(hiba);
        res.status(500).send(`Hiba történt az adatok lekérdezése során: ${hiba}`);
    });    
});

How can I highlight the active buildings in terms of their form?

Has anyone developed apps using React Native?
While working on a mobile app for a real estate agency, I encountered the following issue:

active objects should appear on the map in yellow — the fill should match the structure of the building, but when zooming in, the buildings are not fully filled.

I’m using the MapLibre map.

How to highlight the active buildings according to their form?

  <ShapeSource
          id="kyiv-buildings-source"
          shape={activeBuildings}
          onPress={handleObjectPress}>
          <FillLayer
            id="active-buildings-2d"
            style={{
              fillColor: '#ffe600', 
              fillOpacity: 0.95,
            }}
          />
          {/* 3D-екструзія */}
          <FillExtrusionLayer
            id="active-buildings-extrusion"
            style={{
              fillExtrusionColor: '#ffe600',
              fillExtrusionOpacity: 1,
              fillExtrusionHeight: [
                'case',
                ['has', 'height'],
                ['to-number', ['get', 'height']],
                ['has', 'building:levels'],
                ['*', ['to-number', ['get', 'building:levels']], 4],
                50,
              ],
              fillExtrusionBase: 0,
            }}
          />
        </ShapeSource>

one page/block per scroll event

I have multiple rendered pages inside a div. Each individual page is treated as a block. Initially, I display the first block (div), which fully occupies the initial view. When I scroll down, the second block comes into the user’s view.

In my case, with every scroll action, only the next block should come into view. If the user scrolls again, then only the next div should appear in the view. Since users can scroll quickly, I want to listen to every single scroll event and then move to the next page accordingly.

Here’s what I’ve tried:
Initially, I only have the first two blocks rendered inside the div. When I’m on the first page and the user scrolls down quickly, the view moves only to the next page because only the next page is available. I listen to the scroll event, and at the end of the scroll event, I add the next page.

However, the issue arises when the user tries to scroll again before the previous scroll event has ended. I want to move to the next page in that case, but I don’t have it yet because the end listener hasn’t been called.

My question is: How can I differentiate every scroll movement, i.e., how can I detect every single wheel event separately?

Need a code in pure javascript. Actually, The same scrolling handled in Macbook Calendar. I want same handling in javascript.

How to pass custom variables in Laravel notifications?

I’m using Laravel notifications to send email notification now I’ve to change the logo of the header dynamically so I need to pass variable from the notification class.

return (new MailMessage)
            ->subject($this->emailContent['subject'])
            ->line(new HtmlString($this->emailContent['email_body']))
            ->action('Pay Invoice', url('/'))
            ->line('Thank you for using our application!')
            ->attachData(base64_decode($this->pdf), 'invoice.pdf', [
                'mime' => 'application/pdf',
            ])
            ->with(['logo' => getEmailTemplateLogo($this->invoice->business)]);

I see many blogs suggesting with() but it also not working. Am I missing here? Could someone please guide?

I’m using the default header file which I get by publishing the vendor:publish resourcesviewsvendormailhtmlheader.blade.php

@props(['url','logo'])
<tr>
<td class="header">
<a href="{{ $url }}" style="display: inline-block;">
<img src="{{ $logo }}" style="width:100px;"> // not getting logo here
</a>
</td>
</tr>

How to Register and Display a Custom Post Type for Books in WordPress?

I’m building a WordPress site for a bookshop and want to create a custom post type called “Books” to manage book entries. I’ve added the following code to my theme’s functions.php file to register the post type:

function register_book_post_type() {
    $args = array(
        'public' => true,
        'label'  => 'Books',
        'supports' => array('title', 'editor', 'thumbnail'),
        'has_archive' => true,
        'show_in_menu' => true
    );
    register_post_type('book', $args);
}
add_action('init', 'register_book_post_type');

I expected to see “Books” in the WordPress admin menu and create new book entries, but the post type doesn’t appear. I’m using WordPress 6.4 and PHP 8.0. I tried flushing permalinks via Settings > Permalinks, but it didn’t help. What am I missed in making the custom post type visible and usable?

How to handle sketches in Composer-based projects [duplicate]

I need to sketch out some behavior from a dependency (GuzzleHttpClient) installed via composer. How do I finagle my include_path in a sketch (located under <project root>/sketches) such that I can use GuzzleHttpClient in my sketch?

Just so you can see what I’m doing, here’s my sketch in its entirety.

<?php

use GuzzleHttpClient;

$client_id = 'my_client_id';
$username = 'my_username';
$password = 'bad_password';
$client = new Client;

$client->post(
    "https://my.sso.site/protocol/openid-connect/token",
    [
        'client_id' => $client_id,
        'username' => $username,
        'password' => $password,
        'grant_type' => 'password'
    ]
);

I want to see what exception gets thrown