electron app keypress console hook alternative for process stdin

electron keyboard shortcuts , dont go to this link, as this is tutorial for hooking the keypress on the browser, not console.

I understand I can hook key events with this, for the BROWSER WINDOW. How can I do the same for the CONSOLE ?

in nodejs, it goes with process.stdin.setRawMode(true) YET process.stdin.setRawMode is not a property of the app as I run my application with electron myapp.js rather than node myapp.js

readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
    
process.stdin.on('keypress', (str, key) => {
  if (key.ctrl && key.name === 'c') {
    process.exit();
  } else {
    console.log(`You pressed the "${str}" key`);
    console.log();
    console.log(key);
    console.log();
  }
});

This works well with node app but not electron app As isTTY for node returns True but doesn’t for electron. I get process.stdin.setRawMode is not a function, it is undefined. Any alternatives for electron ? Thank you

Storing form information from my online website [closed]

I have a basic knowledge of HTML, CSS, JS and I’ve seen a lot of tutorials using XAMPP and SQL but I wanna ask: 1) Is XAMPP and SQL viable for published online websites? 2) How can you store data from forms on your website that is published online and also automatically format it and re-use it in your Javascript? ( Not looking for actual code, just general ideas and links for information would be nice ).

More details: My idea is to have forms on my website and get the submissions in an array in Javascript and then by using magic code, every for example Monday at 12:13 I wanna change the array I’m using right now with the one I created using submissions from the form.

I thought about storing the submissions in a txt file using javascript and then at for example monday 12:13 change the data in my array by picking randomly data from the txt file. But I don’t know if that can work on hosted websites.

Remove quote marks from excel cells using node xlsx

I’m using node-xlsx to try and write a simple data structure to a new Excel file. When it gets written, I see no quotation marks around the cell data yet when I upload the file into a browser using automation, it gets rejected because quote marks have been added to all the string values. I’m not clear why this is happening

The code:

export async function createNewExcelFile(testInfo, fileType, adaptationId) {
const [tomorrow, nextMonth] = await getDatesForFile();

const data = [
    ['installer number', 'Adaptation ID', 'effectiveFrom', 'EffectiveTo'],
    [33228, adaptationId, tomorrow, nextMonth],
];
// @ts-ignore
const buffer = xlsx.build([{name: "Sheet One", data: data}]);

//write the buffer to a file in a temp folder
const tempFilePath = path.join(process.cwd(), 'src/test-data/temp-files', uuid.v4() + '.xlsx');
fs.writeFileSync(tempFilePath, buffer);

return tempFilePath;
}

All values except for the number 33228 are affected so looks like this is a lead – how can I prevent this behaviour? Using replace() with a regex seems to have no effect.

storybook react –> stories not showing

I have upgraded the storybook of a project to 6.5.16 and am currently facing the problem, that the stories are not showing. The sidebar shows story titles and the story itself, but clicking on either doesn’t do anything. I am getting a devtools warning

DevTools failed to load source map: Could not load content for http://localhost:8080/index.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

but not sure whether that’s relevant.

main.ts

const config: StorybookConfig = {
  stories: ["../src/**/*.tsx"],
  addons: [
    "@storybook/addon-actions",
    "@storybook/addon-knobs",
    "@storybook/addon-essentials",
    "@storybook/addon-viewport",
  ],
  features: {
    storyStoreV7: true,
  },
  framework: "@storybook/react",
  core: {
    builder: "@storybook/builder-webpack5",
  },
  staticDirs: [path.resolve(__dirname, "../resources")],
  webpackFinal: async (config: any) => {   
    if (config.resolve?.alias) {
      config.resolve.alias = {
        ...config.resolve.alias,
        "@style-variables": path.resolve(__dirname, "../src/styles/variables"),
      };
    }

    if (config.plugins) {
      config.plugins.push(new MiniCssExtractPlugin({ filename: "[name].css" }));
    }

    if (config.module?.rules) {
      config.module.rules.push({
        test: /.(sa|sc|c)ss$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {},
          },
          "css-loader",
          {
            loader: "sass-loader",
            options: {
              implementation: require("sass"),
              sassOptions: {
                includePaths: [
                  path.resolve(__dirname, "./../../../node_modules"),
                ],
              },
            },
          },
        ],
      });
    }
    return config;
  },
};
module.exports = config;

Also got a preview.js

addParameters({
  docs: {
    container: DocsContainer,
    page: DocsPage,
  },
});

function loadStories() {
  require("./../dist/index.js");
}

const storyWrapper = (story) => (
  <div className="storywrapper" style={{ margin: 35 }}>
    {story()}
  </div>
);

addDecorator(
  withInfo({
    inline: true,
    header: false,
    source: true,
    maxPropsIntoLine: 1,
  })
);

addDecorator(storyWrapper);
configure(loadStories, module);

and this as an example story:

export default {
  title: 'Selector',
  decorators: [withKnobs],
};

export const Default = () => (
  <Component
    isDisabled={ isDisabled() }
    items={ SELECTOR_ITEMS }
    selectedItem={ SELECTOR_ITEMS[0] }
  />
);

(left the imports out)

As I wrote, the stories seem loaded but are not showing. Please help 🙂

Fixing navbar hover on touch devices

Note: Not a duplicated because I already tried all other answers the last 2 days and nothing is working in my case because my navbar is custom made, without ul/li, without jQuery, neither Bootstrap but just pure css (until now)

I have this navbar in pure CSS and it works fine on desktop computers but the hover is kind of buggy when you hover on mobile devices (touch devices). It jumps when hovering and the :hover css instructions (black background and white font color) are not followed by touch devices.

I am trying to fix it with css or some simple javascript but nothing seems to work.

Here is what I have until now

The HTML

    <div id="menu" class="active">
      <div class="categories" open><a href="#void">News</a>
        <div class="locations">
          <a href="#">Europe</a>
          <a href="#">Asia</a>
          <a href="#">Africa</a>
          <a href="#">Oceania</a>
          <a href="#">North America</a>
          <a href="#">South America</a>
        </div>
      </div>
    
      <div class="categories" open><a href="#void">Education</a>
        <div class="locations">
          <a href="#">Europe</a>
          <a href="#">Asia</a>
          <a href="#">Africa</a>
          <a href="#">Oceania</a>
          <a href="#">North America</a>
          <a href="#">South America</a>
        </div>
      </div>
    
    </div>

The CSS

 #menu {
      grid-area: menu;
      width: 100%;
      height: auto;
      text-align: left;
      border-bottom: 3px solid #121212;
      background-color: inherit;
      position: -webkit-sticky;
      position: sticky;
      top: 0;
      cursor: pointer;
      z-index: 8;
    }
    .categories {
      display: block;
      position: relative;
      width: 92%;
      margin: 0 auto;
      overflow: hidden;
      height: auto;
      text-align: left;
    }
    .categories a {
      display: block;
      position: relative;
      width: 100%;
      height: 42px;
      line-height: 42px;
      font-size: 1em;
      text-transform: uppercase;
      text-align: left;
      border-bottom: 1px dotted #121212;
    }

    .categories a:hover {
      color: #ffffff;
      background-color: #121212;
      padding-left: 25px;
    }


    .locations {
      display: none;
      position: relative;
      width: auto;
      height: auto;
      text-align: left;
      overflow: hidden;
      padding-left: 25px;
      padding-right: 25px;
      margin: 0 auto;
    }
    .locations a {
      display: block;
      font-size: 0.938em;
      color: #121212;
      text-transform: capitalize;
      text-align: left;
      height: 38px;
      line-height: 38px;
      border-bottom: 1px dotted #121212;
    }
    .locations a:hover {
      color: #e5633f;
      background-color: inherit;
      padding-left: 0px;
      text-transform: capitalize;
    }

    .categories .locations {
      display: block;
    }

Already tested with all related answers/solutions using the following:

cursor:pointer
hover:active
hover:focus
css media queries hover:hover 
pointer: fine

any idea how to solve this in 2023?

Number of Pixel higher in other, smaller Region leads to output-too-large-error

I want to create samples of forest cover pixels at 1 km resolution in different areas of the world in the Javascript API of the Google Earth Engine. For some regions it works well, for others, I get the error that the reprojection output too large.
In my example, in area 1, the sample can be created, whereas in area 2, the sample fuction gives the output-too-large-error. Area 1 is bigger but has less pixel than area 1. Is this due to the projections and how can I get the sample of area 2 without reducing the size of the area?

I tried to create a sample of forest cover in area 2, like I did for area 1, but the error reprojection output too large pops up.
https://code.earthengine.google.com/?scriptPath=users%2Fch_gohr%2FApps%3AQuestionNumberOfPixelProblem

Area 1 Area 2
34850 pixel 47520 pixel
290178 size 180507 size
// area one (in Kongo) ~ 13500 km2
var area1 = ee.Geometry.Polygon([
  [14.19122253254795,0.05331228757480185],
[15.58099304036045,0.05331228757480185],
[15.58099304036045,1.7421917151626107],
[14.19122253254795,1.7421917151626107],
[14.19122253254795,0.05331228757480185]]);

// area two (in Russia) ~ 7500 km2
var area2 = ee.Geometry.Polygon([
  [90.9046606531284,51.67169657462456],
[92.9206518640659,51.67169657462456],
[92.9206518640659,52.85502821573008],
[90.9046606531284,52.85502821573008],
[90.9046606531284,51.67169657462456]]);

///// Forest Mask based on GLAD 2010
// more than 30 % tree cover at 30 m
var TC30 = GLAD_BR114.updateMask(GLAD_BR114.gte(30));

// get binary mask: every pixel gte 0 = fc more than 30 % is 1 
var fc101 = TC30.gt(0);

// create forest cover at MODIS resolution
var modis = ee.ImageCollection('MODIS/061/MYD11A1').first().select('LST_Day_1km');
var modisProjection = modis.projection();
var modisScale = modisProjection.nominalScale();

var forestMean = fc101.unmask()     // see https://developers.google.com/earth-engine/guides/resample
    .reduceResolution({
      reducer: ee.Reducer.mean(),
      maxPixels: 5000,
    })
    .reproject({
      crs: modisProjection, scale: modisScale,
    });
// select pixel greater than 50 % Landsat pixel coverage
var ForestMask = forestMean.updateMask(forestMean.gte(0.5)).rename('Forest10');

// clip forest mask to two example areas
var Maskf_1 = ForestMask.clip(area1);
var Maskf_2 = ForestMask.clip(area2);

Map.addLayer(Maskf_1);
Map.addLayer(Maskf_2);
// count and define forest sample size = 10 % of forest count in the area
var forestCount_area1 = Maskf_1
  .reduceRegion({
    reducer: 'count',
    geometry: area1,
    scale: modisScale,
    bestEffort: true,
  });
//print(forestCount_area1);  // works
var SampleSize_area1 = ee.Number(forestCount_area1.get('Forest10')).multiply(20).divide(100).round();
//print(SampleSize_area1); 

var forestCount_area2 = Maskf_2
  .reduceRegion({
    reducer: 'count',
    geometry: area2,
    scale: modisScale,
    bestEffort: true,
  });
//print(forestCount_area2); // does not work
var SampleSize_area2 = ee.Number(forestCount_area2.get('Forest10')).multiply(20).divide(100).round();
print(SampleSize_area2);

// Is it because of more 0 dimensions in area 2 than area 1?
var numberOfPixels = function(img){
  
  var imgDescription = ee.Algorithms.Describe( img );
  var height = ee.List( ee.Dictionary( ee.List(  ee.Dictionary( imgDescription ).get("bands") ).get(0) ).get("dimensions") ).get(0);
  var width = ee.List( ee.Dictionary( ee.List(  ee.Dictionary( imgDescription ).get("bands") ).get(0) ).get("dimensions") ).get(1);
  
  //print("width", width )
  //print("height", height )
  
  return  ee.Number( width ).multiply( ee.Number( height ) );
};
print(numberOfPixels(Maskf_1),'number of pixels in area 1'); // 34850
print(numberOfPixels(Maskf_2),'number of pixels in area 2'); // 47520
print(area1.area().divide(100000).round(),'size of area 1'); // 290178
print(area2.area().divide(100000).round(),'size of area 2'); // 180507

Transitioning from NeoVis.js to Vis.js for Better Customisation: Worth the Effort?

We’re currently working on a project involving complex graph data visualization, and we’ve been using NeoVis.js as our main tool. However, we’ve recently encountered a roadblock when trying to customise simple features, such as changing node colours, which has proven to be unexpectedly challenging.

This led us to consider migrating our visualization component to Vis.js, primarily because it offers additional capabilities and features that may better cater to our evolving needs.

Here is what we are specifically looking to understand:

Workload: What is the expected effort required for such a transition? Is it something that could be achieved within, let’s say, a 2-week sprint by a couple of people? Or does it require a larger time and resource commitment?

Benefits: After overcoming the initial transition, what benefits did you observe? We’re particularly interested in understanding if the customization possibilities were substantially improved, and if you found that Vis.js was easier to adapt to evolving project needs.

JavaScript Knowledge: Our team has a moderate level of JavaScript proficiency. Is this sufficient for managing the transition and efficiently working with Vis.js?

Feature comparison: Apart from the customization, are there any other significant advantages of Vis.js over NeoVis.js? We’re trying to build a compelling argument for this transition, so any specific insights would be extremely helpful.

To provide some additional context, our product manager currently views this transition as a ‘nice-to-have’ rather than a ‘must-have’. They are under the impression that if the transition is only to accomplish a single task, it might not be worth the investment. However, I believe that we might encounter similar difficulties in the future as our application evolves, making the transition to Vis.js potentially worthwhile.

One final note: I understand that NeoVis.js is essentially a wrapper around Vis.js, simplifying some operations at the cost of customisation options. This gives me hope that the transition might not be as complex as a complete platform change.

Any insights, experiences, and advice are very much appreciated. Thank you!

Static Site Generation Using dynamic routes in nuxt2

I am trying to do the static site generation but when I run the yarn generate command then it creates all other routes & adds them in the dist folder but in the case of my dynamic routes like pages/accommodations/_id.vue not automatically add it in the dist folder. Even I try with nuxt.config.js with this code for one accommodation. It makes the route but does not add it to the dist folder & sometimes it will add it in the dist folder & show error of maximum call stack size exceeded

generate: {
fallback: true,
routes() {
  return [
    '/nl/accommodations/maison-sumiane'
  ]
}

},

Angular 14 and auth0: How do I add a url path to the api that doesn’t get Authorisation added to it Every time I make a request

Below id the current code I have which authorizes every endpoint /* but I want to specify a specific endpoint that I can bypass.

this.authClientConfig.set({
              domain: auth0Config.domain,
              clientId: auth0Config.clientId,
              useRefreshTokens: true,
              authorizationParams: {
                redirect_uri: window.location.origin,
                audience: auth0Config.audience,
              },
              httpInterceptor: {
                allowedList: [
                  {
                    uri: `${appConfig.baseApiUrl}*`,
                    tokenOptions: {
                      authorizationParams: {
                        // The attached token should target this audience
                        audience: auth0Config.audience
                      }
                    }
                  }
                ]
              }
             });

After installing nodejs version 20.3.1 still –> TypeError: First parameter has member ‘readable’ that is not a ReadableStream

sorry to bother you with my tiny problem.
After reading threw the previous questions about the same error and installing nodejs and npm to the latest versions, the error is still showing up. And I dont know what to do to get rid of it.

This is what I get, when running dev:

PS C:Usersmaximmaxim> npm run dev

> [email protected] dev
> astro dev

   astro  v2.7.2 started in 182ms

  ┃ Local    http://localhost:3000/
  ┃ Network  use --host to expose

C:Usersmaximmaximnode_modulesweb-streams-polyfilldistpolyfill.js:362
            throw new TypeError(context + " is not a ReadableStream.");
                  ^

TypeError: First parameter has member 'readable' that is not a ReadableStream.
    at assertReadableStream (C:Usersmaximmaximnode_modulesweb-streams-polyfilldistpolyfill.js:362:19)
    at convertReadableWritablePair (C:Usersmaximmaximnode_modulesweb-streams-polyfilldistpolyfill.js:3524:9)
    at ReadableStream.pipeThrough (C:Usersmaximmaximnode_modulesweb-streams-polyfilldistpolyfill.js:3608:29)
    at fetchFinale (node:internal/deps/undici/undici:11082:56)
    at mainFetch (node:internal/deps/undici/undici:10974:9)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v20.3.1
PS C:Usersmaximmaxim>

Please, can anyone help me figure out what I did wrong?
I am currently working on a simple static webpage with a few pics and a contact form. So nothing special really…

I am more than thankful for any kind of ideas! 🙂

I tried:

  • installing nodejs and npm to the newest versions as it has been mentioned in similar questions and answers in stack overflow conversations

How to check if string is a date or not?

We are using react, what we are trying to achieve is: if input string is date we want to show it in MM/DD/YY HH:MM AM/PM format but we are not sure about input string it can be anything.

I saw so many similar questions are already answered and they are suggesting to use Date.Parse(“iputstring”) or new Date(“inputstring”) but it is not helping me because in my case input string can be anything eg. “0”, “10”, “10/10/2023” , “ASB” etc.

And when string like “0” is passed to Date.Parse or new Date it doesn’t say it is not date instead Date.Parse giving me a timestamp and new Date giving me default date.

Which I don’t want, I want’ to be 100% sure that input string is date.

Please guide me on this, thanks in advance.

Need to migrate JAVA 17 to web server technologies

I would like to migrate JAVA 17 to web server technologies like JavaScript html, without rewriting the code. That is need to give a call to JAVA 17 from javascript. As per requirement we are not supposed to use any tool for the conversion and also not supposed to use JAVA servlets. Please help me on this

I cant’t get the latest cookies via middleware or nuxtServerInit in server side in Nuxt2

When a user logs in, I set a token in cookies. I have written a middleware to check whether the user is logged in or not based on the token. However, I have noticed that when the page is first loaded, the cookies I obtain from context.req are not the latest version. Only when I refresh the page, do I get the updated cookies.

So, if I want to obtain the latest cookies on the server-side, what should I do?

I just want to get the latest cookies in server-side.

Hello what is the ways to make this code better and make the cost less [closed]

Hello I have this code in react project I loaded the API_KEY in the html file but I’m seraching for another way to only load the API_KEY when enter to the component which has this code so please help me Thank’s

import React from 'react';
import GoogleMapReact from 'google-map-react';
import { BsCapsule } from 'react-icons/bs';
import { FaMapMarkedAlt } from 'react-icons/fa';
import { useState } from 'react';

const StepThree = ({errors}) => {

  const [center, setCenter] = useState({ lat: 27, lng: 3 });
  const [marker, setMarker] = useState({ lat: 27, lng: 3 });
  const [searchValue, setSearchValue] = useState('');

  const handleMapClick = ({ lat, lng }) => {
    setCenter({ lat, lng });
    setMarker({ lat, lng });

    const geocoder = new google.maps.Geocoder();
    console.log(geocoder)
    geocoder.geocode({ location: { lat, lng } }, (results, status) => {
      if (status === 'OK' && results[0]) {
        setSearchValue(results[0].formatted_address);
      } else {
        setSearchValue('There is a problem now')
      }
    });
  };


  var input = document.getElementById('location-input');
  var autocomplete = new google.maps.places.Autocomplete(input);
  autocomplete.setTypes(['geocode']); // only suggest geographic locations
  autocomplete.setFields(['address_components', 'geometry', 'name']); // return more detailed results
  // autocomplete.setLanguage('en'); // suggest locations in English
  autocomplete.addListener('place_changed', function () {
    var place = autocomplete.getPlace();
    if (place.geometry) {
      var lat = place.geometry.location.lat();
      var lng = place.geometry.location.lng();
      setMarker({ lat, lng })
      setCenter({ lat, lng })
    }
  });


  return (
    <div className='step__container'>
      <div className="input__wrapper z-[800]">
        <div className='input__container'>
          <FaMapMarkedAlt className="input__icon " />
          <input id="location-input" type="text" placeholder={searchValue}  className='input__field ' />
          {errors.location && (
            <label className="input__error-label">{errors.location}</label>
          )}
        </div>

      </div>
      <div className="h-[250px] w-[80%] flex flex-col">
        <div className="flex-1">
          <GoogleMapReact
            // bootstrapURLKeys={{ key: 'AIzaSyBTlSamMjj1vDJw1qnCtA8swbnbuoyXPos' }}
            center={center}
            defaultZoom={3}
            onClick={handleMapClick}
            options={{ gestureHandling: 'greedy' }}
          >
            {/* <Marker lat={markerd.lat} lng={markerd.lng} /> */}
            <div className='text-blue-600 h-[2.1rem] w-[2.2rem] ' lat={marker?.lat} lng={marker?.lng} >
              <BsCapsule className='w-full h-full' />
            </div>
          </GoogleMapReact>
        </div>
      </div>
    </div>
  );
};

export default StepThree;

Hello I have this code in react project I loaded the API_KEY in the html file but I’m seraching for another way to only load the API_KEY when enter to the component which has this code
so please help me
Thank’s