Unable to declare multiple custom named properties TypeScript MUI v5 Palette

I am trying to setup many custom attributes to keep things semantically easy to update in the future. However I am having issues with having more than just one custom property in MUI v5

Ts Error

TS2717: Subsequent property declarations must have the same type. Property 'background' must be of type 'TypeBackground', but here has type 'PaletteColor'.

palette.ts

export const palette = {
  primary: {
    light: '#6D6B8C',
    main: '#6514DD',
    dark: '#6D6B8C',
  },
  secondary: {
    main: '#6D6B8C',
  },
  error: {
    main: '#bd4646',
  },
  background: {
    main: '#fff',
    paper: '#F5F5F5',
  },
  border: {
    main: '#DADAE1',
    primary: '#DADAE1',
  },
  text: {
    primary: '#6D6B8C',
    secondary: '#000',
  },
}


declare module '@mui/material/styles' {
  interface Palette {
    border: Palette['primary']
    background: Palette['primary']
  }

  // allow configuration using `createTheme`
  interface PaletteOptions {
    border?: PaletteOptions['primary']
    background?: PaletteOptions['primary']
  }
}

enter image description here

How to get the final state from an array of objects representing changes

I have an array of changes (objects) and would like to get the final state after all the changes have been made.

For example, having this array of changes:

const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);

const item1 = {
  id: 'id1',
  timestamp: yesterday,
};
const item2 = {
  id: 'id2',
  timestamp: today,
};
const item3 = {
  id: 'id3',
  timestamp: tomorrow,
};

const changes = [
  {
    action: 'swap',
    item1,
    item2,
  },
  {
    action: 'swap',
    item1,
    item2: item3,
  },
]

I am expecting this array with the final state of each item:

const finalState = [
  {
    id: item1.id,
    timestamp: item3.timestamp,
  },
  {
    id: item2.id,
    timestamp: item1.timestamp,
  },
  {
    id: item3.id,
    timestamp: item2.timestamp,
  },
]

currently, the logic I am using is this one. However it is not working properly.

export const convertChangesToFinalState = ({
  changes,
}): FinalChanges => {
  const finalState: {
    [id: string]: FinalChange;
  } = {};

  for (const { item1, item2 } of changes) {
    finalState[item1.id] = {
      id: item1.id,
      timestamp: new Date(finalState[item2.id]?.timestamp ?? item2.timestamp),
    };

    finalState[item2.id] = {
      id: item2.id,
      timestamp: new Date(finalState[item1.id]?.timestamp ?? item1.timestamp),
      // timestamp: new Date(new Date(item2.timestamp).getTime() !== new Date(finalState[item1.id]?.timestamp).getTime()? finalState[item1.id]?.timestamp : item1.timestamp),
    };
  }

  return Object.values(finalState);
};

Could you please help me solve this?

Thank you in advance!

Select2 User Select Add a new Company Popup Window

I have this Company control that list all the company from the database. I also added this Add a New Company... -1 which I would like the user to select if it is a new company that a pop up window will display and the user can enter the information. Any help would be great

enter image description here

    html += "<h3 class='form-section'>Submission Information</h3><div class='row'>";
    html += "<div class='col-md-6'><div class='form-group'><label class='control-label'>Company</label>";
    
   html += "<select id='txtCompany' name='txtCompany' class='form-control select2-multiple' multiple='multiple'>";
    
    html += "<option value=''></option> <option value='-1'>Add a New Company...</option>";
    html += "<optgroup label = 'Existing Company' >";
    $.each(data.listOfRequesters, function (index, r) {
    if (requesterList.includes(r.SubmissionRequesterId)) {
       html += "<option value='" + r.SubmissionRequesterId + "' selected='selected'>" + r.Company + "</option>"
     } else {
    html += "<option value='" + r.SubmissionRequesterId + "'>" + r.Company + "</option>"
    }
    });
    
   html += "</optgroup></select>";

Access Javascript file in Kotlin/JS

I have a bunch of Javascript files I need to access from Kotlin Code.

I created a js-files directory in my root project with the needed .js files and a package.json which looks like this:

{
  "name": "js-files",
  "version": "1.0.0",
  "dependencies": {
  }
}

My build.gradle looks like this:

plugins {
    kotlin("js")
}

version = "unspecified"

repositories {
    mavenCentral()
}

kotlin {
    js {
        useCommonJs()

        nodejs()
        browser {
            webpackTask {
                output.libraryTarget = "commonjs2"
            }
        }

        binaries.executable()
    }
}

dependencies {
    val path = rootProject.projectDir.resolve("js-files").canonicalPath
    implementation(npm("js-protos", "file:$path"))
}

The idea for this I got from this post.

For debugging, i have the following js file in js-files:

export function func() {
    console.log("This is my test function.")
}

and my kotlin main looks like this:

@JsModule("js-files")
external fun func()

fun main() {
    func()
}

However, when i run the project using vrowserDevelopmentRun i receive this error:

Module not found: Error: Can't resolve 'js-files' in 'path-to-my-project/build/js/packages/project-name-js/kotlin-dce-dev'

Maybe there is an easier way of binding my js files but after hours of research i found nothing. I’m thankful for any help.

How would I upload a file from one pc, to another, to the directory that my HTML index is hosted and stored

I’ve seen many posts on uploading files, however I’ve not seen any regarding uploading files to a html page on one PC; and then taking those files and downloading them back in the host pc.

I have a simple html page that is hosted by node.js. My index is located in a directory stored in the standard location for NPM (var/www/html). I can login to my web page on multiple PCs on my network.
I wanted to be able to login to my Web Wrowser from any of my devices and then upload a file. I would then want to trigger a function where that file is downloaded back on the host pc. Essentially I upload from pc A to pc B (host pc) -ideally saving the file in a specific directory in the pc that holds my hosted html template

I’ve had a few ideas of how to do this but I’m not sure where I’m going wrong.

<span>File Upload<input type="file" id="photo" name="photo" accept="image/png, image/jpeg"></span>

<form action="yourScript">
  <input type="file" id="myFile" name="filename">
  <input type="submit">
  <a href="var/www/html" download> </a>
</form>

I’m using Apache/2.4.38 (Raspbian) Server.
Is there a function that I can call after submit that tells the server to download the uploaded file to the host pc (same directory where my index.html is located)?

Thanks for taking the time.

Javascript: Switch from importing data from XML file to importing data from a JS object array

I need to edit a script to switch from reading XML data from an xml file to reading data from a JS object array instead.

let’s assume the xml file is x.xml:

<xml>
   <location>
     <name>cafe 1</name>
     <address>1 cafe st</address>
   </location>
   <location>
     <name>cafe 2</name>
     <address>2 cafe st</address>
   </location>
</xml>

The below code populates an array with data from an xml file

$.ajax({
               type: "GET",
               url: "x.xml",
               dataType: "xml",
               success: function(xml) {    
                   $(xml).find('location').each(function(){
   i +=1;
                       var name = $(this).find('name').text();
                       var address = $(this).find('address').text();
                     
                        table[i] = {name:name, address:address};
                       
                               
                   });

..can I rewrite that output as


var table = [
                  {"name":"cafe 1", "address":"1 cafe st"},
                  {"name":"cafe 2", "address":"2 cafe st"},
                  ]

…and call data in the array using

var m; 
for ( m = 1; m < table.length-1; m++) {

                      if (table[m].name == "cafe 1" ....

Function overloading with generic types in Flow

I have a component

<ButtonGroup
  value={value}
  options={[1, 2, 3, 4, 5, 6].map((x) => {
    return { label: x, value: x };
  })}
/>

I am using Flow for type checking and want to know, whether it is possible to have ButtonGroup component be generically typed in such a way that it will raise a Flow error if type of value is not the same as type of option.[0].value? This should work for any matching type, e.g number, array, etc. and only raise if type of value and option[at_some_index].value are different

What I currently have:


type Props<T> = {
  options: Array<{
    label: React$Node,
    value: T,
  }>,
  value: T,

};

This works fine for checking matching types but only for a particular type. E.g if I do

export const ButtonGroup = ({options, value}: Props<number>) => {do stuff}

It will work for number types as expected, but if I add union types to have the same behaviour for strings, arrays, like so Props<number | string | []> flow stops raising an error if types of values don’t match.

Below also doesn’t work:

export const ButtonGroup = <T>({options, value}: Props<T>) => {do stuff}

I know this can be done in Typescript and was just wondering whether this can be done in Flow?

Thank you!

Is there an NPM library or built-in for keyboard event key constants? [closed]

There are many questions that refer to keyCode (deprecated) and code, but I am not seeing much in regards to key. I am trying to reduce the amount of “magic strings” in my code.

Should I be using key, or should I switch to code? The code does not know if the Shift key was hit, but the key will be formatted in upper-case. Key also works with special characters, because it detects the keyboard layout better.

I am using the following logic, but I do not want to potentially create a map of all keys if I can help it.

const VirtualKeyBoard = {
  ENTER: 'Enter',
  A_LOWER: 'a',
  A_UPPER: 'A',
}

const elements = {
  code    : document.querySelector('#code'),
  key     : document.querySelector('#key'),
  keyCode : document.querySelector('#keyCode'),
};

const updateMap = (e) => 
  Object.keys(elements).forEach((key) =>
    elements[key].textContent = e[key]);

const onKeyPress = (e) => {
  const { code, key, keyCode } = e;
  updateMap(e);
  if (key === VirtualKeyBoard.ENTER) {
    console.log('You hit ENTER!');
  } else if (key === VirtualKeyBoard.A_LOWER) {
    console.log('You hit lower-case "a"!');
  } else if (key === VirtualKeyBoard.A_UPPER) {
    console.log('You hit upper-case "A"!');
  }
}
  

document.body.addEventListener('keypress', onKeyPress);
.as-console-wrapper {
  max-height: 4em !important;
}

html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.grid {
  display: grid;
  grid-row-gap: 0.25em;
  padding: 0.5em;
  border: thin solid grey;
}

.grid-2 {
  grid-template-columns: repeat(2, 1fr);
  grid-column-gap: 1em;
}
<div class="grid grid-2">
  <div>Code</div>
  <div id="code">_</div>
  <div>Key</div>
  <div id="key">_</div>
  <div>KeyCode</div>
  <div id="keyCode">_</div>
</div>

How to stop loop if only one of these isn’t true?

I have a while function that will run in auto mode if auto mode is activated (checkBox.checked)

The problem is this code only stops once both a and b are greater than my game limit # (bestof.value). I want it to stop once only one of these is not true.

When I use while(a || b < bestof.value) it times out until the stack reaches its limit. It also returns no values.

if (checkBox.checked == true){
    while(a && b < bestof.value){
    myFunction();
};

Any idea how I can solve this?

Browser or Tab Close Event to notify server in ASP.NET MVC Application

Hello Fellow Developers,

I am currently working on the ASP.NET MVC application to get trigger browser or tab close event or request to notify the server so we can discard the changes on the server if the user has close the client (Browser or Tab).

Unfortunately, I have had no luck until now, I have tried JavaScript beforeunload event but this is not the requirement as this event also triggered on Refresh and some other issue regarding UX.

Furthermore, I also tried to implement with ServiceWorker Push Notification but it has some other problem as the user can not give permission for Push Notification.

Currently, I just need to notify the server when Browser or Tab is closed or about to close; is there any way to do this, with ServiceWorker or other API?

The above error occurred in the component

Im getting this issue when i add the switch tag, so far i think i have not mixed up any tags but iam not understanding where exactly i have made the error

please help me resolve this issue for this code im getting this error
im new to react js pls help me solve this issue

import "regenerator-runtime/runtime";
import React from "react";
import { login, logout } from "./utils";
import "./global.css";
import "bootstrap/dist/css/bootstrap.min.css";
import { Container, Navbar, Nav, NavDropdown } from "react-bootstrap";
import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

// components
import Home from "./Components/Home";
import NewPoll from "./Components/NewPoll";
import PollingStation from "./Components/PollingStation";


import getConfig from "./config";
const { networkId } = getConfig(process.env.NODE_ENV || "development");

export default function App() {
  return (
    <Router>
      <Navbar collapseOnSelect expand='lg' bg='dark' variant='dark'>
        <Container>
          <Navbar.Brand href='/'>
            VoteBlocks
          </Navbar.Brand>
          <Navbar.Toggle aria-controls='responsive-navbar-nav' />
          <Navbar.Collapse id='responsive-navbar-nav'>
            <Nav className='mx-auto'></Nav>
            <Nav>
              <Nav.Link href='/NewPoll'>New Poll</Nav.Link>
              <Nav.Link onClick={window.accountId === "" ? login : logout}>
                {window.accountId === "" ? "Login" : window.accountId}
              </Nav.Link>
            </Nav>
          </Navbar.Collapse>
        </Container>
      </Navbar>

      <Switch>

        <Route exact path='/'>
          <Home />
        </Route>

        <Route exact path='/PollingStation'>
          <PollingStation />
        </Route>

        <Route exact path='/NewPoll'>
          <NewPoll />
        </Route>

      </Switch>

    </Router>
  );
}

How to use openstack on client side

I try to make a upload/download services of files for my website, and i’m trying to use the object storage from openstack. The thing is, i have no problem doing it via php and openstack php sdk, but when i’m trying to do it via some javascript, i can’t find a good sdk or methods.
I’m not using node, I have a php server, and a javascript client. I would like to uploads or download files directly from the javascript client. I don’t want the file to transfer through the php server. I managed to create openstack tokens with the php sdk, maybe i could send those to the javascript so then they can authenticate? It’s been one week of searching with no solutions…

Force cache invalidation in Instagram web viewer

I have a website that is constantly updated because it has a feed streaming live data. However, no matter how hard I try, the page continues using an old javascript bundle that renders the website, and also, inside the Webpack, I’m generating JS files using a hash to distinguish from older versions.

chunkFilename: '[name].[chunkhash].js'

It only happens in Instagram web viewer. I’m also using Loadable to code split, it’s a React Hooks project, and in a common browser, like Chrome, Safari, Firefox, it’s working properly, the problem is with the Instagram web viewer. Does anyone have this problem and already solved it?