Tauri with Astro Js integration

After searching a bit, I guess it would be useful. The question is : is it possible to configure Tauri with Astro Js ? The answer is yes. So this post is not a question, but an answer to this question.

To configure Tauri with Astro, we will first create an Astro project. After that we will configure Tauri in order it to “wrap around” the existing Astro project. Pay attention to the order :

  1. Install NPM

  2. Install Rust

  3. Install Tauri : cargo install tauri --locked

  4. Install Tauri CLI : cargo install tauri-cli --locked

  5. Create Astro project : npm create astro@latest

Once the Astro project is created, we will use Tauri to integrate into the existing Astro project. To do so, command : cargo tauri init, which creates a minimal Tauri configuration. Check Tauri doc. Tauri will need you to procide a few informations. I give you the base config, please adapt it if you changed the parameters (such as the port or the production files folder name or location) :

  • Name of your app
  • Name of the window
  • Relative path to the production (not dev) files. Per default in Astro the production files are located in the (maybe not currently existing) dist folder. As the path has to be given from the tauri.conf.json file, we will give (per default) ../dist in the prompt
  • The dev server url is per default http://localhost:4321/
  • The frontend dev command in Astro is npm run dev
  • The frontend dev command in Astro is npm run build

When step 6 is done, let’s verify that it is working as expected. Let’s run the command cargo tauri dev. The dev server will be launched on the url specified (here http://localhost:4321) as a typical Astro project. If you type the url in your browser, you will access it, but it is Astro not Tauri. At the same time, Rust will compile the files (which might take some time on first compilation) and generate the application window. If you have the same window as your web browser, then Tauri is working with Astro

Get selected DropDownList Value with LeafLet PopPup

I want to get the value of selected item within leaflet popup and pass this to a url. I have tried document.getElementById but it does not seem to work. The end goal is to pass the variables to Form and add them to the database using Flask.

  const searchControl = L.esri.Geocoding.geosearch({
    position: "topright",
    placeholder: "Enter an address or place e.g. 1 Welcome St",
    useMapBounds: false,

    providers: [
      L.esri.Geocoding.arcgisOnlineProvider({
        apikey: apiKey,
        nearby: {
          lat: -28.100261323878577,
          lng: 26.176619708307275
        }
      })
    ]

  }).addTo(map);

  searchControl._container.querySelector('.geocoder-control-input').focus();

  const results = L.layerGroup().addTo(map);

  searchControl.on("results", (data) => {
    results.clearLayers();

    for (let i = data.results.length - 1; i >= 0; i--) {
      const marker = L.marker(data.results[i].latlng);

      const lngLatString = `${Math.round(data.results[i].latlng.lng * 100000) / 100000}, ${
        Math.round(data.results[i].latlng.lat * 100000) / 100000

      }`;


      marker.bindPopup(`<b>${lngLatString}</b><p>${data.results[i].properties.LongLabel}</p>
      <p>
        <label for="cars">Choose a car:</label>
        <select name="cars" id="cars">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="opel">Opel</option>
        <option value="audi">Audi</option>
        </select>
      </p>

      <p> <a id="confirmLocationLink" href="{{url_for('form')}}?loc='+${lngLatString}+'&locDesc='+${data.results[i].properties.LongLabel}+'&selectedCar='?????"> Confirm location </a> </p>`);

How to use localStorage in nextJS client side

I am getting an error when I try to get local storage data. I use the use client directive at the top but still the issue persists.

'use client';

const baseURL = ‘https://localhost:7264’;
const accessToken = localStorage.getItem(‘accessToken’);

export async function GET(url, claim) {
try {
const res = await fetch(${baseURL + url}, {
method: ‘GET’,
headers: {
accessToken: accessToken,
clientClaim: claim
},
});
if (res.ok) {
const data = res.json();
return data;
}
return null;
} catch (error) {
console.log(error);

    return null;
}

}

Anyone helps me with how can I use localStorage in nextJS, specifically next 14

CanopyTax File download with Pupeeteer is not working

I’m using Puppeteer to automate the download of a CSV file from the Canopy Tax website. The page has a dropdown menu with an “Export CSV” option. Despite my efforts, the download isn’t working as expected. I’ve provided the relevant HTML structure and my Puppeteer code below.
Here is the page.
Payment Page Screenshot

And this is the html content:

<div class="cps-dropdown">
    <div class="cps-btn-icon">
        <a class="cps-link cp-m-0">
            <span class="cps-icon cps-icon-more"></span>
        </a>
    </div>
    <ul class="cps-dropdown-menu cps-pull-right" role="menu" style="z-index: 50;">
        <li>
            <a>
                <svg canopy-styleguide="k1" class="cp-icon af-line-square-up cps-icon cps-dropdown-menu__icon" viewBox="0 0 24 24">
                    <use href="#af-line-square-up" xlink:href="#af-line-square-up"></use>
                </svg>
                Export CSV
            </a>
        </li>
    </ul>
</div>

Here is my code:

scrapeCanopyPayments = async () => {
    try {
        const C = {
            username: 'useremail',
            password: 'password',
        };
        const USERNAME_SELECTOR = '#canopy-login-ui-email';
        const PASSWORD_SELECTOR = '#canopy-login-ui-password';
        const CTA_SELECTOR = '#canopy-login-ui-login';
        const OTP_NEXT_SELECTOR = '.cp-button--primary';
        const OTP_INPUT_SELECTOR = '.cp-input';
        const DOWNLOAD_CSV_SELECTOR = 'ul.cps-dropdown-menu.cps-pull-right li a';

        const websiteUrl = 'https://app.canopytax.com/#/login';
        const paymentUrl = 'https://app.canopytax.com/#/billing/payments/collected';
        const browser = await puppeteer.launch({
            args: ['--no-sandbox', '--disable-setuid-sandbox'],
            ignoreHTTPSErrors: true,
            dumpio: true,
        });

        const page = await browser.newPage();
        await page.setViewport({ width: 1366, height: 768 });
        await page.setUserAgent(userAgent);
        await page.goto(websiteUrl, { waitUntil: 'networkidle2' });
        await page.screenshot({ path: 'login.png' });

        // Log in
        await page.click(USERNAME_SELECTOR);
        await page.keyboard.type(C.username);
        await page.click(PASSWORD_SELECTOR);
        await page.keyboard.type(C.password);
        await page.click(CTA_SELECTOR);

        await page.waitForNavigation();
        await page.screenshot({ path: 'login2.png' });

        // Handle OTP
        await page.click(OTP_NEXT_SELECTOR);
        await page.waitForNetworkIdle();
        await page.screenshot({ path: 'otp-input.png' });
        await sleep(50000);
        const otp = await this.getOtpFromEmail();
        await page.click(OTP_INPUT_SELECTOR);
        await page.keyboard.type(otp);
        await page.click(OTP_NEXT_SELECTOR);
        await sleep(4000);
        await page.screenshot({ path: 'dashboard.png' });

        // Navigate to payment page
        await Promise.all([
            page.goto(paymentUrl, { waitUntil: 'networkidle2', timeout: 0 }),
            page.waitForNavigation({ waitUntil: 'networkidle2' }), // trigger a navigation
        ]);

        await sleep(4000);

        // Trigger CSV download
        await page.click(DOWNLOAD_CSV_SELECTOR);
        await page.waitForNetworkIdle();

        await browser.close();
        return true;
    } catch (e) {
        console.log(e);
        return false;
    }
};

Despite executing the click on the “Export CSV” option, the file download isn’t happening. I’ve checked the console and network requests but haven’t found a solution. Any insights or suggestions on how to make the download work would be greatly appreciated!

Post request returns 500 (Internal Server Error) with Express js

I have a frontend made with pure JS and a node backend app made with Express JS. I try to write default set of requests “get post put delete” and get requests work correctly while post request returns error 500. I’ve read other similar qustions but nothing helped me, maybe someone can give me an insight on this problem. Please take a look at the code:

these are my requests on frontend side:

import Auth from "../services/auth.js";
import location from "../services/location.js";
import loading from "../services/loading.js";
import api from "../services/api.js";

const init = async () => {
    const { ok: isLogged, data } = await Auth.me()

    if (!isLogged) {
        return location.login()
    } else {
        loading.stop()
    }

    const getTodos = async () => {
        return await api('/todo/', {
            method: 'GET'
        }
        )
    }

    const getTodo = async (id) => {
        return await api(`/todo/${id}`, {
            method: 'GET'
        }
        )
    }

    const createTodo = async (values) => {
        return await api('/todo/', {
            method: 'POST',
            body: values,
        }
        )
    }

    createTodo("Test todo").then(data => {console.log(data)});
    getTodos().then(data => {console.log(data)});
    getTodo(1).then(data => {console.log(data)});
}

if (document.readyState === 'loading') {
    document.addEventListener("DOMContentLoaded", init)
} else {
    init()
}

The api function:

import Auth from "./auth.js";
import config from "./config.js";

const api = async (url, options = {}) => {
    const headers = {
        ...(options.headers || {}),
        "Content-Type": "application/json",
    }

    const token = Auth.token
    if (token) {
        headers["Authorization"] = `Bearer ${token}`
    }

    const result = await Promise.all([
        await new Promise(resolve => setTimeout(() => resolve(), 200)),
        await fetch(config.BASE_URL + url, {
            ...options,
            headers
        })
    ])

    const response = result[1]

    return await response.json()
}

export default api

controller from backend app:

class TodoController {
  async add(req: IRequestAuth, res: Response, next: NextFunction) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return next(ApiException.BadRequest('Validation error', errors.array()))
      }

      const { description } = req.body
      const userId = req.user.id
      const newTodo = await todoModel.create({description, userId})
      res.json(setSuccessResponse(newTodo))
    } catch (e) {
      next(e);
    }
  }

And the cors settings I use:

app.use(cors({
   origin: ['http://127.0.0.1:5500'], 
   credentials: true, 
   methods: 'PUT,POST,GET,DELETE,OPTIONS',
   allowedHeaders: '*'
  }))

How to make a lot of if and else if statements about comparing multiple values and sorting from highest to lowest more concise – Javascript [closed]

I am trying to find a way to make my code that I have been working on more concise and compact.

An Engineering named Cartsen Massmann said that I could use this code:

const data=[{
  Surname:"Massmann",Firstname:"Carsten",Initial:"CM",
  q1:8,q2:9,q3:7,q4:9,q5:10, // engineering
  q6:3,q7:6,q8:2,q9:4,q10:1, // medicine
  q11:2,q12:2,q13:1,q14:3,q15:4, // education
  q16:5,q17:3,q18:4,q19:2,q20:3, // agriculture 
  q21:7,q22:8,q23:9,q24:9,q25:8, // mathematics 
  q26:7,q27:7,q28:6,q29:9,q30:8  // science 
}];

const sortedSubjects=(uObj,i=0)=>
["engineering","medical","education","agriculture","mathematics","science"]
 .map(s=>[s,
  Array(5) // five questions per subject ...
 .fill(0)  // filling is necessary, as reduce will not loop over `undefined` values
 .reduce(a=>a+uObj[`q${++i}`],0)]) // sum up scores for each subject
 .sort(([,a],[,b])=>b-a); // sort according to descending scores

const scores=sortedSubjects(data[0]);
console.log("sorted scores:"+JSON.stringify(scores));
console.log(`The highest scoring subjects are ${scores.slice(0,2).map(([s])=>s).join(" and ")}.`);

When ever I run the code, I get this in console:

sorted scores:[["engineering",null],["medical",null],["education",null],["agriculture",null],["mathematics",null],["science",null]]

It just returns Engineering and Medical as the result with no value.

How can I make his code compatible with my data.

A more in-depth explanation about the code would be very helpful too…

How to make child pass array (from db) to parent

How come there is nothing show up. No error, just nothing show up.

App.js is below:

import { PriceRangeData } from './PriceRangeData.js';
import { variables } from './Variables.js';
import React, { Component, useState, useEffect } from "react";

function App() {
    const [priceRangesState, setPriceRangesState] = useState([]);
    const [checkPriceRangesState, setCheckPriceRangesState] = useState([]);

    const childToParent = (childdata) => {
        setPriceRangesState(childdata);
    }

    const handlePriceRangesCheckbox = (e) => {

        const value = e.target.value;
        if (e.target.checked) {
            setCheckPriceRangesState([...checkPriceRangesState, value]);
        } else {
            setCheckPriceRangesState(checkPriceRangesState.filter(item => item !== value));
        }       
    }

    return (
        <>
            {priceRangesState.map(p => <div>{<input key={p.id} type='checkbox' value={p.lowPrice} onChange={handlePriceRangesCheckbox} />} ${p.lowPrice} - ${p.highPrice}</div>)}
        </>
    )

}

export default App;


PriceRangeData.js is below:

import React, { Component } from 'react';
import { variables } from './Variables.js';

export class PriceRangeData extends Component {  



constructor(props) {
    super(props);

    this.state = {            
        employees: []
    }
}

componentDidMount() {
    this.getPriceRanges();
}    

getPriceRanges() {      

    fetch(variables.API_URL, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            this.setState({ employees: data });              
        },
        (error) => {
            alert('Failed');
        })        
}   

render() {              
    return {employees}         
}

}

I am trying to get a list of (array) of data from child (PriceRangeData.js) which get data from the database. And then pass this data to parent (App.js) so that the parent can display this data.

When I run my it, there is nothing show up, not even error.

Please let me know how can I fix it. Thanks a lot in advance!

Fire an event globally on load of every view in odoo

A global solution to fire an event on load of every view in odoo admin side

In odoo16 I am trying to inherit view from view.js as

/** @odoo-module */

console.log('Hoping view be inherited');
import { registry } from "@web/core/registry";
import {View } from '@web/views/view';

class MyView extends View{
    setup() {
        super.setup();
        console.log('View is inherited successfully')
    }
}

This console is shown
console.log('Hoping view be inherited'); means file runs successfully as its included in assets->web.assets_backend->[] in my custom module manifest

but following is never reached
console.log('View is inherited successfully')

Note: the setup of original web/stativ/src/views/view.js

export class View extends Component {
    setup() {
       ...
       console.log('Appears  every time a view is loaded')
    }
}

is called every time a view is loaded

I have also tried to use hooks like

/** @odoo-module */

import { registry } from "@web/core/registry";

const myViewHook = () => {
    // Your custom logic to modify views here
    console.log('Executing on every view load');
};

registry.add("web.dom_loaded", myViewHook);

but it also does not work

Api get the latest products in by Woot Developer Portal [closed]

I am using the API in developer.woot.com. I am trying to get the latest products like Computers section.

I tried few things in Postman like:

https://developer.woot.com/feed/Computers?page=1&order=StartDate
https://developer.woot.com/feed/Computers?page=1&orderBy=StartDate

I try to get all and sort to get the latest but it takes quite a while.

Can someone suggest a way to do that?

What am I missing from my button JS code?

I am trying to create a HTML button that generates a list from my country array on javasript for my coursework.

I’m not sure what I am missing from my code to complete the action, as currently it is saying my function ‘generate-country’ is not defined.

HTML:
<h1>Country Example</h1>

<button onclick ="generateCountry()">Pick a place</button>

<ul id="country-list">
  <!-- country list displayed here --></ul>type here
JS:
const places = ["Australia", "UK", "Canada"];

function generateCountry() {
const countryList = document.getElementById("country-list");
countrylist.innerHTML ="";
    
}

What’s the best engine for remaking an old Flash Game in HTML5 with visual editing included? [closed]

I have a SWF of the old multiplayer flash game from early 2000s. Extracting resources should be a piece of cake.

The game will have multiple scenes. Like main menu, lobby, game, profile, etc.

Working without a visual editor would be much harder. I would like to be able to drag and drop elements on scenes, and then apply code for functionality to various elements such as buttons and server side stuff.

What engine or platform is the best or mostly preferred for a HTML5 2d shooter game?

I tried Phaser 2d editor, but I’m not sure it’s the right choice. This game will be 2d, but it will be involving using a cursor for aiming and mouse clicks for shooting. I;ve tried searching for similar topics on stackoverflow, but nobody really asked about multiplayer shooter game.

vis.js Timeline does not apply CSS style to show the images of the items in the right size

A question for vis.js timeline (Setup: Mac Monterey 12.5.1, Chrome 122.0.6261.94 Official Build(arm64).

I try to set the size of an image in the “title” of all items. For this I use HTML code. One item looks like this:

var items = new vis.DataSet([
    {
    editable: { updateTime: true, updateGroup: false, remove: true }, 
    id: 1,
    className: "blue",
    content: '<a href="http://www.example.com" target="_blank">birthdate () &#10148;  (0 years old)</a>',
    title: '<a href="../static/images/image-not-found-icon.png" target="_blank"><img style="width: 100px;height: 100px;" src="../static/images/image-not-found-icon.png"></a>',
    start: "1989-03-17",
    end: null,
    type: "point",
    },

This result in the original image in big size (stylesheet is not applied). Other HTML is working (text, link etc). In reality, I am using CSS file for the same style, but even inline HTML gives the same result. I have tried several variations like below, but all shows the original image in big size. Any idea how to fix this? (Is this is a bug, or did I make some mistakes?)

<div style="width: 100px;height: 100px;"><a href="../static/images/image-not-found-icon.png" target="_blank"><img src="../static/images/image-not-found-icon.png"></a></div>

<a href="../static/images/image-not-found-icon.png" target="_blank"><img class="small_thumnbnail" src="../static/images/image-not-found-icon.png"></a>

<div ><a href="../static/images/image-not-found-icon.png" target="_blank"><img style="width: 100;height: 100;" src="../static/images/image-not-found-icon.png"></a></div>

By the way, the hyperlink and text are properly displayed for the content of the item.

Many thanks!

SwiperSlide onClick not working when use coverflowEffect depth option on ios mobile

<swiper :effect="'coverflow'" :space-between="20" :grabCursor="true" :initialSlide='initialSlide' :centeredSlides="true" :slideToClickedSlide="true" :slidesPerView="3" @slideChange="onSlideChange" :coverflowEffect="{ rotate: 0, stretch: 20, depth: 180, modifier: 1, slideShadows: false, }" :modules="modules" class="mySwiper"> <swiper-slide v-for="(item,i) in tabList" :key="item.name"> <div class="swiper_content"> <span class="txt" :style="{color:current == i?'#000':'rgba(0,0,0,.6)'}">{{item.title}}</span> <div class="line" v-if="current == i"></div> </div> </swiper-slide> </swiper>

Swiper version:10.3.1

i want to work on my porject

Async/await functionality in an object that returns an instance of itself (for chaining)

I have an instance of a class:

let myInstance = new MyObject();

that looks like this:


export default class MyObject () {
    constructor () {}

    methodOne () {
        // Do stuff …
        return this;
    }

    async methodTwo () {
        let db_query = await Connection.query('<DATABASE QUERY>');

        return this;
    }

    methodThree () {
        // Do stuff …
        return this;
    }

    // etc.
}

This way I can chain methods on the instance:

myInstance
    .methodOne()
    .methodTwo()
    .methodThree()

How can I make sure that methodTwo won’t return (this) until the async/await is resolved?

Doing something like this (won’t work):

let db_query = await Connection.query('<DATABASE QUERY>');

    db_query
        .then(() => {
            return this:
        })

Note: myInstance is itself wrapped in an async/await method.