Cannot rename field in Mongoose without breaking geospatial functionality

Synopsis
I want to rename the ‘address’ field to ‘location’ in my Mongoose schema. The location field only stores address data, such as street, city, postcode, etc. The locationGeo field, on the other hand, contains the geospatial data in the form of a GeoJSON Point for coordinates.

Error
After renaming the ‘address’ field to ‘location’, I am encountering the following error:

MongoServerError: Can't extract geo keys: { <user_data> } unknown GeoJSON type: { street: "Wiejska", city: "Warszawa", postcode: "00-480", streetNumber: "2G", apartmentNumber: null, voivodeship: "mazowieckie" }

Code
userModel:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const userSchema = new Schema({
  firstName: { type: String, default: null },
  lastName: { type: String, default: null },
  nickname: { type: String, unique: true },
  password: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  phone: { type: String, default: null },
  location: {
    street: { type: String  },
    city: { type: String  },
    postcode: { type: String  },
    streetNumber: { type: String  },
    apartmentNumber: { type: Number },
    voivodeship: { type: String },
  },
  locationGeo: {
    type: { type: String, default: 'Point' },
    coordinates: { 
      type: [Number], 
      default: [0, 0], 
    },
  },
});

userSchema.index({ locationGeo: '2dsphere' });

userSchema.index({ 
  phone: 1 
}, { 
  unique: true,
  partialFilterExpression: { phone: { $type: "string" } }
});

module.exports = mongoose.model("User", userSchema);

Function which updates userModel:

module.exports.updateBasicInfo = async (req, res) => {
  const user = res.entity;
  const session = await mongoose.startSession();
  session.startTransaction();
  console.log(req.body)
  //  {
    //   firstName: '',
    //   lastName: '',
    //   location: {
    //     street: 'Wiejska',
    //     city: 'Warszawa',
    //     postcode: '00-480',
    //     streetNumber: '45',
    //     apartmentNumber: '',
    //     point: { lat: 52.2275274, lng: 21.0237868 }
    //   }
    // }
    const { location: newLocation } = req.body;
    const locationGeo = {
        type: "Point",
        coordinates: [newLocation.point.lng, newLocation.point.lat], 
      };

    delete newLocation.point; //don't store coordinates in location
    
    const updateData = { 
      $set: {
        location: newLocation || {},
        locationGeo: locationGeo,
      }
    };
  try {
   
    await user.updateOne(updateData, { session });

    await session.commitTransaction();
    return res.json(user);
  } catch (error) {
    await session.abortTransaction();
    console.error(error);
    return res.status(400).json({ message: error.message || "Update failed." });
  } finally {
    await session.endSession();
  }
};

I’ve tried:

  • Verifying that locationGeo is being updated correctly with valid GeoJSON data.
  • Attempting to update only the location field without updating the locationGeo field at all.

Can anyone explain why this error occurs after renaming the field and how to resolve it while keeping ‘location’ as the field name for the address?

React – show message when map returns no value

i have 2 arrays categorias and noticias;

categorias is like this:

export const Categorias = [
  {
    id: 1,
    name: "actualidade",
    slug: "actualidade",
  },
...
]

and noticias is something like this:

export const Noticias = [
  {
    id: 1,
    titulo: "titulo da primeira notícia",
    slug: "titulo-da-primeira-notícia",
    texto:
      "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc.",
    img: "https://picsum.photos/id/0/5000/3333",
    cat: "politica",
    destaque: true,
  },
...
]

on the homepage i have this code that shows 4 news per category:

{cats.map((item, index) => {
        return (
          <section className={`noticias ${item.name}`} key={index}>
            <div className="container">
              <div className="title">
                <h3>
                  {item.name}
                  <Link to={`/noticias/${item.slug}`}>
                    <p>ver todas</p>
                  </Link>
                </h3>
              </div>
            </div>

            <div className="blocks">
              {[...news]
                .reverse()
                .filter(
                  (noticia) =>
                    noticia.cat === item.slug && noticia.destaque !== true
                )
                .slice(0, 4)
                .map((noticia, idx) => {
                  return <BlockNoticia key={idx} item={noticia} id={idx} />;
                })}
            </div>
          </section>
        );
      })}

I have left some categories with no news on purpose so i can show a message when there are none.

This is working fine except when there are no news from a category.

How can i show a message like “there are no news in this category”?

Responsive ThreeJS PlaneGeometry

I’m trying to get more familiar with ThreeJS and shaders. Currently trying to make a shader that creates water ripples on a background Image so I’ve created this:

https://jsfiddle.net/9yx2jadg/3/

It works as I was hoping but I can’t seem to wrap my head around scaling the plane responsively for different screen aspect ratios, or am I meant to be adjusting the frustum?

At the moment what happens is that as you change the screen/browser size the image itself either distorts and stretches or you get black bars above and below or to the side of the image.

The following code is from line 111 of the Javascript of the JSFiddle:

const updateImagePlaneScale = () => {

    // Image aspect ratio
    const imageAspectRatio = 2000 / 1333;

    // Viewport aspect ratio
    const viewportAspectRatio = sizes.width / sizes.height;

    
    // Ensure the imagePlane always fills the the largest dimension of the viewport and maintains aspect ratio for the other axis

    // If the viewport is wider than the image
    if (viewportAspectRatio > imageAspectRatio) {
        imagePlane.scale.x = frustumSize * viewportAspectRatio;
        imagePlane.scale.y = frustumSize;
    } else {
        imagePlane.scale.x = frustumSize * imageAspectRatio;
        imagePlane.scale.y = frustumSize / viewportAspectRatio;
    }    
};

Ideally, I’d like to have it behave in the same manner as the CSS background-size:cover property. Wether it be by scaling the plane up, or cropping the camera fustrums? I just can’t seem to understand how to do it in ThreeJS

I’ve tried scaling the plane and fiddling with the frustums but they just cause the same issue in different ways or other issues.

React AG Grid – Validate a Custom Cells if Row selected

I have a Grid of 3 columns. Each row contains a cell with a Checkbox and two Custom Cell Components (by default empty). Whenever a Custom Cell is clicked, a Modal opens up allowing the user to:

  • Select a value from radio buttons
  • Insert a value from input field
    If a row is selected the Custom Cells of that row are mandatory, therefore should not be empty in order to proceed (a Submit button will then be displayed).

I tried using cellClass but it doesn’t work as intended. Also I would like to apply validation and the class on the other cell when the user clicks the Checkbox too.

What is the best way to validate that the Custom Cells of a selected row are not empty and apply a class to it?

Here is the code of my Grid:

const Grid = () => {
  const [rowData] = useState<IRow[]>([
    {
      boolean: false,
      car_brand: '',
      car_name: '',
    },
    {
      boolean: false,
      car_brand: '',
      car_name: '',
    },
    {
      boolean: false,
      car_brand: '',
      car_name: '',
    },
  ]);

  const [columnDefs] = useState<ColDef[]>([
    {
      field: 'boolean',
      headerName: '',
      editable: true,
    },
    {
      field: 'car_brand',
      headerName: 'Car Brand',
      cellRenderer: SelectCarBrand,
      cellClass: (params) => {
        if (params.data.boolean && params.data.car_brand === '') {
          return 'cell-fail';
        }
      },
    },
    {
      field: 'car_name',
      headerName: 'Car Name',
      cellRenderer: EnterCarName,
      cellClass: (params) => {
        if (params.data.boolean && params.data.car_name === '') {
          return 'cell-fail';
        }
      },
    },
  ]);

  return (
    <div>
      <AgGridReact rowData={rowData} columnDefs={columnDefs} />
    </div>
  );
};

export default Grid;

Here is the code of one Custom Component:

const SelectCarBrand = (params: CustomCellRendererProps) => {
    const { isOpen, onOpen, onClose } = useDisclosure();

    const [radioValue, setRadioValue] = useState<string>();


    const handleOnChange = (value: string) => {
        setRadioValue(value);
        params.setValue(value);
    };

    const handleConfirm = () => {
     if (radioValue === undefined || radioValue === '') {
        params.setValue('');
    } else {
        params.setValue(radioValue);
    }
     onClose();
    };

    const handleOnClose = () => {
    if (radioValue === undefined || radioValue === '') {
        params.setValue('');
    }
    onClose();
    };

    return (
    <Box>
        <HStack onClick={onOpen} cursor="pointer">
        {!radioValue && (
            <Text>
            Select Car Brand
            </Text>
        )}
        {radioValue && <Text>{radioValue}</Text>}
        </HStack>

        <Modal isOpen={isOpen} onClose={handleOnClose}>
        <ModalOverlay />
        <ModalContent>
            <ModalHeader>
            Select Car Brand
            </ModalHeader>
            <ModalCloseButton />
            <ModalBody>
            <RadioGroup onChange={(e) => handleOnChange(e)}>
                <Stack>
                <Radio value="Tesla">
                    <Text>Tesla</Text>
                </Radio>
                <Radio value="Ferrari">
                    <Text>Ferrari</Text>
                </Radio>
                <Radio value="Lamborgini">
                    <Text>Lamborgini</Text>
                </Radio>
                </Stack>
            </RadioGroup>
            </ModalBody>

            <ModalFooter>
            <Button onClick={handleOnConfirm}>
                Confirm
            </Button>
            </ModalFooter>
        </ModalContent>
        </Modal>
    </Box>
    );
};
  
export default SelectCarBrand;

Bundling, minifying and transposing Javascript to ES5

I created a javascript library that follows jQuery syntax but relies entirely on more modern syntax. Whilst everything it uses is supported by ES5, I wrote it using ES6 classes and arrow functions that are not supported by say IE11.

The source is broken up into four files none of which export functions but do use ES6 features. The first creates an object of functions, the second extends the Array class to perform most utilities, the third does the same as the second but for AJAX etc…

I want to combine them all into one output file. This is simple but it remains in ES6 syntax. I’m looking for a way to compile them to a single file and transpose to ES5.

I can see that web pack supports this and I have that installed for other parts of the project. But it relies on module.exports and assumes a much more component based setup. Is there a way to configure it to take all the input files (not exported functions), combine them in a specific order and transpose to ES5 in the process. If so, how to set this up.

Input

./src/init.js
./src/utilities.js
./src/ajax.js
./src/misc.js

Intended Output (with support for ES5 browsers)

./library.js

Adjucent similar values grouping in SAP Viz frame column chart

Here I am facing an issue where Vizframes column chart grouping the adjucent similar values on x-axis,into one data label as below screen for temparature values where I want to remove that and use that value for each coloumn without merging/grouping.

<viz.feeds:FeedItem id='categoryAxisFeed2' uid="categoryAxis" type="Dimension" values="Temperature"/>

Here is my XML Code

<viz:VizFrame height=”25rem” width=”100%” class=”graphborder” id=”idVizFrame” uiConfig=”{applicationSet:’fiori’}”
vizType=’column’ vizProperties=”{title: {text: ‘Usage Trend’}}” destroyLegendGroup=”true”>
viz:dataset
<viz.data:FlattenedDataset data=”{JsonModel>/graphDtls}”>
viz.data:dimensions
<viz.data:DimensionDefinition name=”Meter Read Type” value=”{JsonModel>Istablart}” />
<viz.data:DimensionDefinition name=”Period” value=”{JsonModel>Period}”/>
<viz.data:DimensionDefinition name=”Temperature” value=”{JsonModel>Temperature}” />
</viz.data:dimensions>
viz.data:measures
<viz.data:MeasureDefinition name=”KWh/Therms” value=”{JsonModel>Consumption}”/>
</viz.data:measures>
</viz.data:FlattenedDataset>
</viz:dataset>
viz:feeds
<viz.feeds:FeedItem id=’valueAxisFeed’ uid=”valueAxis” type=”Measure” values=”KWh/Therms”/>
<viz.feeds:FeedItem id=’categoryAxisFeed2′ uid=”categoryAxis” type=”Dimension” values=”Temperature”/>
<viz.feeds:FeedItem id=’categoryAxisFeed’ uid=”categoryAxis” type=”Dimension” values=”Period”/>
<viz.feeds:FeedItem id=’categoryAxisFeed3′ uid=”categoryAxis” type=”Dimension” values=”Meter Read Type”/>
</viz:feeds>
viz:dependents
<viz:Popover id=”idPopOver”></viz:Popover>
</viz:dependents>
</viz:VizFrame>

Attachment screen red highlighted:
enter image description here

How to use session across multiple domains for OAUTH2

Background

I’ve got a Azure Static Web App serving a React SPA with a connected Azure Functions backend on a custom domain (let’s call it mysite.com). It uses Azure basic auth (aka EasyAuth). Now I have a VM serving Postgres and pg_tileserv. On that VM I have oauth2_proxy in front of pg_tileserv on a subdomain (tiles.mysite.com). If I open tiles.mysite.com in a browser then I can authenticate just fine and, on a standalone basis, it works.

My problem

I want to be able to fetch tiles from the VM from the webapp but I can’t auth to the tileserv from the session on the main site.

What I’ve tried

I tried adding an iframe on my mysite.com that goes to tiles.mysite.com. The iframe will login from existing cookies without user intervention but when I fetch tiles it doesn’t bring those cookies to the fetch requests so those fail (get 302).

Trying to avoid

I know I could put nginx and uvicorn on my VM and host the webapp and api there so that all the auth is in one place but I kind of like having the resource separation.

Desired Solution

I’m open to almost any other approach. I’d prefer to stay away from having to subscribe to even more Azure services (like Front Door) though. I don’t mind switching from oauth2_proxy or adding nginx if that would solve my issue somehow.

Is it possible to use WebShare API (navigator.share) to share images from other origins than my own?

I’m trying to use the file field of navigator.share in order to share an X amount of images which can come from other origins/urls than my own website, but the files field expects File objects, which I’m currently getting through the fetch function and then using .blob() on the response result.

The problem is that unlike using tags with the src attribute I can’t use fetch to pull images from other origins which is a functionality that I need to finish my product.

I tried to pull the images using fetch which is constrainted by CORS, that means I can’t use .share to share any image I want but only those that are from my origin.

Problem: 307 Temporary Redirect Error in AJAX Request

Problem: 307 Temporary Redirect Error in AJAX Request

I am facing an issue where, while making an AJAX request from my WordPress website, I sometimes get a 307 Temporary Redirect error. The request is being redirected to the following URL:

"https://recaptcha.cloud/?template=cpg&server=37.27.57.153:443&ip=182.177.153.69&http=&host=yourwebsite.com&real_ip=&proto=&url=/wp-admin/admin-ajax.php"

This issue occurs intermittently, and after some time, the error resolves on its own, but it reappears again. The page being redirected to is protected by cPGuard.

Details:
The 307 Temporary Redirect happens with requests to wp-admin/admin-ajax.php.
The redirect is happening to the recaptcha.cloud URL, and it seems to be an anti-bot protection service, possibly related to cPGuard.
Questions:
How can I stop the redirect and prevent this issue from happening in the future?
Is it possible to disable cPGuard or adjust its settings if I don’t have access to cPanel?
Could this issue be due to something related to IP blocking or rate limiting?

Steps Taken So Far:
No Security Plugin:
I am not using any security plugins on my WordPress site (such as Wordfence or iThemes Security), and I am using the Astra free theme.

No cPGuard Settings in cPanel: I don’t have access to cPGuard settings in my cPanel, and I can’t find any settings for it.

Yii2 show partial view inside a modal with fetch() Vanilla JS

i’ve a problem using fetch() API for showing a partial view inside a modal.

My controller is this:

public function actionIndexAjax()
    {
        if (Yii::$app->request->isAjax) {
            return $this->renderAjax('selectImage');  
        }
    }

And in my principal view a i have a button that triggers the modal, so i creata a javascript code
to get this view with fetch() like this:

fetch(url, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
            }
        }).then(function (response) {
            if (response.ok) {
                return response.json();
        }else{
                return Promise.reject(response);
            }            
        }).then(function (data) {
            console.log(data);

        }).catch(function (error) {
            console.warn('Something went wrong.', error);
        });

But i get this error:

SyntaxError: JSON.parse: unexpected character at line 2 column 1 of
the JSON data

I don’t know where the problem is

N.B. Instead if i use the jquery function works fine.

Umbraco 13 forms conditions rendering script

I am using a custom theme for umbraco forms and to make conditions work for the custom theme I had to add the following to my Script.cshtml file:

Html.AddFormThemeScriptFile("~/App_Plugins/UmbracoForms/Assets/themes/default/umbracoforms.js");

But this script file umbraco.js is not loaded directly when the form is loaded on a new browser page and conditions do not work unless the site is refreshed once then the script can be seen and conditions work as expected.

What could this depend on ?

Blob could not be loaded from a localhost as src blob:

I’m having some trouble loading an audio file in WAV format returned from the backend as a Blob in Angular.

I have in my services the following:

getFileBlob(uniformName: string, path: string) {
    const currentPath = path.replace(/\/g, '/');
    return this.http.get(`${environment.api_url}/content/v1.4/${currentPath}/${uniformName}/_blob`, { responseType: 'blob' });
  }

Where in my Angular component, I have the following:

this.dService.getFileBlob().subscribe((response: Blob) => {
        const url = URL.createObjectURL(response);
        this.type.set(response.type);
        this.src.set(url);
      });

I have the correct mapping in my audio source tag:
[screenshot from the inspect1

In my template, I have:

<audio #media [vgMedia]="$any(media)" id="myAudio" preload="{{ preload }}" crossorigin>
      <source src="{{ src() }}" type="{{ type() }}">
      <track
      src="assets/data/Downloaded_transcriptVVV.vtt"
      kind="metadata"
      label="Cue Points"
      default
      #metadataTrack
    />
  </audio>

When I paste the blob in the browser, I get the file downloaded – (blob:http://localhost:4200/7071f3e7-9738-4ad7-b08f-67ddb5852c53)
The problem is that the native HTML audio does not play at all.
One important note is that I’m using Angular in a zoneless mode.
If, however, I put a direct relative URL in the place of the src, it works:

`this.src.set(‘/assets/audio/E_2024-10-07_H_100748_060.wav’)

I would highly appreciate anyone’s advice on what I’m doing wrong.

Site blocking Captcha Solver extension

I have a crawler and I’m trying to use Captcha Solver’s services that are used in Chrome Extensions (such as CapSolver), but the site I’m trying to scrape apparently detects those extensions in my browser and blocks all the following requests I try to do after successfully using the Captcha Solver. I would like to ask how much information about my extensions a site can have, so I can change the Extension files so it don’t look like a Captcha Solver extension.

Sending Data From Javascript to FastAPI

How do I send data from client (javascript) to my server (python fastapi)? I am having trouble understanding the format that I need my data in. I have this “simple” example that I’ve been trying to get working to help me understand what is happening.

    document.getElementById('submitButton').addEventListener('click', async (event) => {
        event.preventDefault();

        const formData = new FormData();
        formData.append('input_data', 'I am working');

        try {

            const response = await fetch('/function/', {
                method: 'POST', 
                body: formData
            });

            const result = await response.json();
            if (response.ok) {
                console.log('Response ok');
            } else {
                console.log('Response not ok');
            }


        } catch (error) {
            console.log('error');
        }
    });
@app.post('/function/')
async def function(input_data: str = Form(...)):
    print(input_data)
    return {'message': 'Success!'}

Does triggering component renders during animation frame wait til frame is done, or synchronously reflow/paints then finish the frame callback?

I’ve seen a few similar-ish questions but I’m struggling to find a definitive answer – any advice appreciated!

Consider:

  • you have a react component
  • you have an animation loop running via requestAnimationFrame(update), in a singleton

Then:

  • in a single frame, which runs update exactly once, the react component is re-rendered twice

What happens:

  1. The browser interrupts the update execution in order to synchronously perform re-layout and re-paint as soon as the component finishes the re-render (so this would happen twice in the single frame)

  2. The browser schedules the re-layout and re-paint each time the comp performs a render, but this only actually happens once the update function has finished execution

  3. Something else?

I would like to think that the re-renders are scheduled to come into affect at the next layout/paint cycle, but I need to be sure because otherwise I’ll need to take pains not to result in more than one potential redraw each frame…