Is it possible to conditionally add an element to a possibly undefined array on an object in one line in JS?

I have an object with ids for keys that I want to conditionally add an array to. I could do this, but I don’t want this code repeated 3 times in my function:

const myObj = {};
const myKey = '1233';
const myValue = true;

if (!(myKey in myObj)) {
    myObj[myKey] = [];
}
myObj[myKey].push(myValue);

I would like to do something myObj[myKey].upsert(myValue), but modifying the Object prototype currently causes performance issues. Using Object.create (as suggested) causes a lot of TypeScript issues in my application and I was casting my object back to one without the upsert method to pass it along which felt bloated and wrong.

So I opted to use the nullish coelescing assignment operator in my code:

const myObj = {};
const myKey = '1233';
const myValue = true;

myObj[myKey] ??= [];
myObj[myKey].push(myValue);

and that works great! But, is it possible to do this in one line?

I was thinking something like this might work, but no:

myObj[myKey] ??= [...myObj[myKey], myValue]

How can I replace the first value in the second list with the last value in the previous list?

In this list of objects we have value groupID, Which contains a list.

What I want is to replace the first value in the list with the last value in the previous list.

let testArr = [
    {groupID: [1900, 1890, 1880], Letter: "A"},
    {groupID:[1888, 1898, 1908, 1918, 1928, 1938], Letter: "B"},
    {groupID: [1927, 1917, 1907], Letter: "A"},
    {groupID: [1912, 1922, 1932, 1942, 2012, 2022, 2032, 2042], Letter: "B"},
    {groupID: [2039, 2029, 2019, 2009], Letter: "A"},
    {groupID: [2013, 2023, 2033], Letter: "B"},
]

The result is:

let testArr = [
    {groupID: [1900, 1890, 1880], Letter: "A"},
    {groupID:[1880, 1898, 1908, 1918, 1928, 1938], Letter: "B"},
    {groupID: [1938, 1917, 1907], Letter: "A"},
    {groupID: [1907, 1922, 1932, 1942, 2012, 2022, 2032, 2042], Letter: "B"},
    {groupID: [2042, 2029, 2019, 2009], Letter: "A"},
    {groupID: [2009, 2023, 2033], Letter: "B"},
]

I have this code, but it’s silly and doesn’t work with async and await:

let add = []

for (let i = 0; i < testArr.length; i++){
    if (testArr[i].groupID.length != 0){
        add.push(testArr[i].groupID[testArr[i].groupID.length-1])
    }
}
for (let i = 1; i < testArr.length; i++){

    testArr[i].groupID.splice(0,1, add[i-1])
}

and Thanks in advance.

Airmeasure chart lines with Rails Charts / Chartkick/ Chart.js

I would like to create multiple chart lines with Rails Charts

I have tried for some time and no succeeded.

I want to create something like this:

enter image description here

Each color line should represent room_id column from airmeasures table.

The x should take data from timestamps column, and the y line should take data from measure_float column.

I can also provide a link from my github if needed.
Or can be created with Chartkick / chart.js or any other(I have tried with those also)

Here is a link from one csv file.

I have imported data from csv files to seeds.rb file.

require 'csv'

def import_csv(file_name)
  file_path = "db/csv/#{file_name}.csv"

  CSV.foreach(file_path, headers: true) do |row|
    Airmeasure.create!(row.to_h)
  end
end

import_csv('20211101_B3D54FD00007B2')
import_csv('20211101_B3D54FD000088A')
import_csv('20211101_B3D54FD000088F')

schema.rb

ActiveRecord::Schema[7.0].define(version: 2023_11_23_221627) do
  create_table "airmeasures", force: :cascade do |t|
    t.datetime "timestamps"
    t.string "measure_type"
    t.integer "measure_float"
    t.string "brand"
    t.string "serial_number"
    t.integer "establishment_id"
    t.string "establishment_name"
    t.string "establishment_city"
    t.string "establishment_postcode"
    t.string "establishment_address"
    t.float "establishment_latitude"
    t.float "establishment_longitude"
    t.integer "room_id"
    t.string "room_name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

home.html.erb

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
  </head>
  <body>

    <div class="container">
        <%= line_chart Airmeasure.order(timestamps: :asc).pluck(:timestamps, :measure_float) %>
    </div>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
  </body>
</html>

pages_controller.rb

class PagesController < ApplicationController
  def home
    @airmeasures = Airmeasure.select("timestamps", "measure_type", "measure_float", "room_name")
  end
end

how to transfer file from server to client via json

I am trying to transfer the processed pdf file on the server to the client side so that the user can download it.
Here is my code on the server –

@app.task
def pdf_protect(file_path, file_id, password):
    with open(file_path, 'rb') as file:
        reader = PdfReader(BytesIO(file.read()))

    writer = PdfWriter()
    writer.append_pages_from_reader(reader)
    writer.encrypt(password)

    output = io.BytesIO()
    writer.write(output)
    output.seek(0)

    send_notification.delay({'filename': 'result.pdf', 'content': base64.b64encode(output.read()).decode('utf-8')}, file_id)

In this code I use the pypdf library and encrypt the pdf with the given password.
After that, I try to convert the processed pdf file into bytes and pack it into json in order to send it to the client side via a websocket connection.

On the client side I have the following code –

chatSocket.onmessage = function (e) {
    const data = JSON.parse(e.data);
    var blob = new Blob([data.message.content], {type: "application/pdf"});
    console.log(data.message.content)
    downloadLink.href = URL.createObjectURL(blob);
    downloadLink.download = data.message.filename;
    chatSocket.close();
};

In this code I get the data from the json and make a link to download the file.

But after downloading and opening the pdf file, the error “Failed to load the PDF document.” or just a blank page.

But what happens when I send a response to the client via FileResponse and then use the same method to make a link to download the file and download it, then everything works fine.

This is what this code looks like −

protected_pdf_file = services.pdf_protect(form.cleaned_data['file'], form.cleaned_data['password'])
return FileResponse(
    protected_pdf_file,
    as_attachment=True,
    filename='protected_pdf.pdf',
)

And here is the code services.protect_pdf() –

def pdf_protect(pdf_file, password):
    reader = PdfReader(pdf_file)

    writer = PdfWriter()
    writer.append_pages_from_reader(reader)
    writer.encrypt(password)

    output = io.BytesIO()
    writer.write(output)
    output.seek(0)

    return output

Please tell me what the problem is and how to transfer files from the client to the server via json.
Thank you!

NET8 Blazor how to create the js.map files?

In my project NET8 Blazor project, I added some JavaScript to use. When I deploy the website to the server, I noticed that some js.map are not present, a few of them related to Blazor itself.

enter image description here

I tried in Visual Studio to find a way to generate them but I can’t find any.

Is there a way to generate those files?

How do I fix this program? [closed]

I am a noob in programming, so I am making a game in p5.js to learn, however, there is an issue…

let camX;
let camY;
let camZ;
let seed;
let objects = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  camx = 0;
  camy = 80;
  camz = 0;
  seed = 450
  for(let i = 0; i < 606; i++)
  {
    randomSeed(seed);
    objects.push([random(-400, 400), random(-400, 400), random(0, 2)]);
  }
}

function moveCam()
{
  if(keyIsPressed)
  {
    if(key == "a")
      {
        camx += 2;
      }
    if(key == "d")
      {
        camx -= 2;
      }
    if(key == "w")
      {
        camz -= 2;
      }
    if(key == "s")
      {
        camz += 2;
      }
  }
}

function drawObjects()
{
  for(let i = 0; i < 606; i++)
    {
      if(objects[i][2] == 0)
      {
        translate(objects[i][0], -20, objects[i][1]);
        box(20);
      }
      if(objects[i][2] == 1)
      {
        translate(objects[i][0], -40, objects[i][1]);
        box(40);
      }
      if(objects[i][2] == 2)
      {
        translate(objects[i][0], -10, objects[i][1]);
        sphere(40);
      }
    }
}

function draw() {
  background(220);
  
  push();
  translate(camx, camy, camz);
  box(8000, 20, 8000);
  drawObjects();
  pop();
}

when I run this code, it displays a white plane, however, none of the randomly generated objects seem to show up…

I have checked and there are elements in the array, so I am completely lost.

Please help me lol

Change selected text content with a chrome extension

I’m trying to edit selected text using content_sript.js in my chrome extension. The highlighted text should only cover one node in the html but I haven’t figured out how to enforce that yet

This is the code in content_scripts.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { if (request.action === "changeText") { console.log(window.getSelection().toString()); console.log(window.getSelection()); window.getSelection().deleteFromDocument(); const new_text = "Text i need to insert"; sendResponse({worked:true}); } });
I have figured out how to delete the selected text but now I need to somehow insert the text back in.

How to add filter option above the ox_options[‘baseTpl’] of fancybox

$fancybox_options['baseTpl'] = '<div class="modula-fancybox-container modula-lightbox-' . $settings['gallery_id'] . '" role="dialog" tabindex="-1">' .
                                       '<div class="modula-fancybox-bg"></div>' .
                                       '<div class="modula-fancybox-inner">' .
                                       '<div class="modula-fancybox-infobar"><span data-fancybox-index></span>&nbsp;/&nbsp;<span data-fancybox-count></span></div>' .
                                       '<div class="modula-fancybox-toolbar">{{buttons}}</div>' .
                                       
                                       '<div class="modula-fancybox-navigation">{{arrows}}</div>' .
                                       '<div class="modula-fancybox-stage"></div>' .
                                       '<div class="modula-fancybox-caption"><div class="modula-fancybox-caption__body"></div></div>' .
                                       "</div>" .
                                       "</div>";

I would like to add filter option on the lightbox gallery.

How to specify only the id of the appearing text, without specifying the ids of the hiding texts?

When you click on a certain button, a certain text is displayed, and when you click on another button, the text changes to another one. The problem is that I need to indicate all possible identifiers of texts that need to be hidden. How to specify only the id of the appearing text, without specifying the ids of the hiding texts?
I don’t know English well, so I used Google translator.

 function hideh1(Id){
   document.getElementById(Id).style.display = "none";
 }

 function showh1(Id){
   document.getElementById(Id).style.display = "block";
 }
<button onclick="showh1('Text11'); hideh1('Text00');
  hideh1('Text22'); hideh1('Text33')">Text1</button>
<button onclick="showh1('Text22'); hideh1('Text00');
  hideh1('Text11'); hideh1('Text33')">Text2</button>
<button onclick="showh1('Text33'); hideh1('Text00');
  hideh1('Text11'); hideh1('Text22')">Text3</button>
<button onclick="showh1('Text00'); hideh1('Text11');
  hideh1('Text22'); hideh1('Text33')">Text00</button>

<h1 id="Text00">Text00</h1>
<h1 id="Text11" style="display:none">Text11</h1>
<h1 id="Text22" style="display:none">Text22</h1>
<h1 id="Text33" style="display:none">Text33</h1>

I have built a app using Tauri (Svelte + Rust). How to make async invoke request from Svelte to Rust such that it dosent freeze the whole UI?

The whole UI freezes when rust function is invoked that calls another async function.

  1. I created a tauri runtime in my main fn()
Main function in main.rs :-

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            make_type_request_command,
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

Here “make_type_request_command” is an async tauri command function that is calling another async function make_request which returns Result<Value, Box>.

Async Tauri command function :-

#[tauri::command(async)]
async fn make_type_request_command(
    url: &str,
    method: &str,
    headers: &str,
    body: &str,
    request: &str,
) -> Result<Value, String> {
    let result: Result<Value, Box<dyn Error>> = make_request(url, method, headers, body, request).await;
    match result {
        Ok(value) => return Ok(value),
        Err(err) => {
            return Ok(serde_json::Value::String(err.to_string()))
        }
    };
}

Its giving me the error

future cannot be sent between threads safely
the trait `Send` is not implemented for `dyn StdError`".

I have tried a bunch of things already,

  1. Setting #[tokio::main] in make_type_request_command that removes all errors but gives below error at runtime.
thread 'tokio-runtime-worker' panicked at 'Cannot start a runtime from within a runtime. This happens because a function (like `block_on`) attempted to block the current thread while the thread is being used to drive asynchronous tasks.'
  1. Added Send + Sync everywhere where error was being returned. Still errored out.

  2. tauri async spawn inside command function.

  3. Making main function async on current thread using tokio.

  4. Remove Box from everywhere possible that is not implementing send.

But nothing worked.

It will be really helpful if someone can help me with this. I want the UI to not freeze until the request is resolved.

how to serve plain js single page application on github pages?

the website gives error 404 upon reload when it path except https://username.github.io/projname/
it does all routing to my paths using navbar links


const router=(hrf)=>{
    history.replaceState(null,null,hrf)
}

export default router

the function below is giving router paths

item.addEventListener('click', (e) => {
            document.querySelectorAll('.linkbtn').forEach(el=>{
                el.style.backgroundColor=''
            })
            document.getElementById('projectbtn').style=''
            e.preventDefault()
            router(e.target.parentElement.href)
            component(e.target.id.slice(0,-3))
            item.style.backgroundColor='#f2f2f2'

        })

i was expecting github to serve index.html with index.js to be served at all paths just
rest is handled by js

type here

How to close dropdown when focus is lost

I am using tailwind css and jquery.

I have tried several things and I am not really getting it.
code below you will see I have place focusout on the outer div that contains the dropdown code. I put the focus on the searchbox when it is opened. It will open and focus on the search box is fine the dropdown stays open. But if I click on the person in the dropdown list, it is supposed to select and put a check box next to their name to indicate selected; however, the dropdown closes.

I mean I guess technically the <a tag got the focus but I thought it would consider that the parent <div tag still had focus since the <a tag is in the div tag. This does not happen with the search box, if I type in it, it is fine and I place the focus there. I am a little bit baffled.

<div id="select_users" style="">
                              

<script type="text/javascript">
     function fn_assigned_users() {
          var element_id = 'assigned_users';
          var link_id  = element_id + "_item_link";

          var open = false;
          var selected = [];
          var textField ='text';
          var valueField = 'value';
          var list = JSON.parse('[{"selected": false, "text": "Angela  Law", "value": 1}]');
          var button_elment = $(`#${element_id}_button`);
          var dropdown_elment = $(`#${element_id}_dropdown`);
          var selectedValues = $(`#${element_id}_selected`);
          selectedValues.value = selected.join(",");
          var searchElement = $(`#${element_id}_dropdown_search`);
          dropdown_elment.focusout(function() {
               open = false;
               dropdown_elment.hide();
          });
          searchElement.on("keyup", function multi_dropdown_search_keyup(sender, arg){
               for (let idx = 0; idx < list.length; idx++){
                    if (list[idx][textField].toLowerCase().includes(searchElement[0].value.toLowerCase()))
                         $(`#${link_id}_${idx}`).show();
                    else
                         $(`#${link_id}_${idx}`).hide();
               }
          });
          button_elment.on("click", function multi_dropdown_button_click (sender, args){
               open = !open;
               if (open){
                    dropdown_elment.show();
                    searchElement.focus();
               }
               else 
                    dropdown_elment.hide();
          });


          $(`[id^='${link_id}']`).each(
               (idx, linkElm)=>{ 
                    $(linkElm).on('click', function multi_dropdown_link_click (sender, args){
                         let idx = $(linkElm).data('index');
                         list[idx].selected = !list[idx].selected;
                         itmElement =  $(`#${element_id}_item_check_${idx}`);
                         if (list[idx].selected) {
                             itmElement.show();
                              selected.push(list[idx].value);
                              selectedValues.value = selected.join(",");
                         }
                         else {
                              itmElement.hide();
                              selected = selected.filter(f=> f != list[idx].value);
                              selectedValues.value = selected.join(",");
                         }
                         return false;
                    });
               }
          );
          function clearSelection (){
               for (itm in list){
                    itm.selected = false;
               }
               selected = [];
               selectedValues = "";
               $(`[id^='${link_id}']`).each((idx, linkElm)=>{
                    itmElement =  $(`#${element_id}_item_check_${idx}`);
                    itmElement.hide();
               });
          }
          return {
               clear: clearSelection
          }
     }
     $(function (){
          assigned_users_instance = fn_assigned_users();
     });
</script>



<div class="w-60">
  <div class="relative mt-2">
     <input id="assigned_users_selected" name="assigned_users" type="hidden">
     <button type="button" id="assigned_users_button" name="assigned_users_button" class="relative w-full cursor-default rounded-md bg-white 
               py-1.5 pl-3 pr-10 text-left text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 
               focus:outline-none focus:ring-2 focus:ring-indigo-600 sm:text-sm sm:leading-6">
          <span class="flex items-center">
               <span class="ml-1 block truncate"> Assign Users</span>
          </span>
          
          <span class="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2 text-gray-500">
               <svg class="w-2.5 h-2.5 ms-3" fill="none" viewBox="0 0 10 6">
                    <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 4 4 4-4"/>
               </svg>
          </span>
     </button>
     <div style="display: none;" id="assigned_users_dropdown" name="assigned_users_dropdown" class="absolute z-10 mt-1 max-h-60 w-full overflow-auto rounded-md 
               bg-white py-1 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
          <div class="p-3">
               <input type="text" id="assigned_users_dropdown_search" name="assigned_users_dropdown_search" class="block w-full p-2 ps-2 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-600 dark:border-gray-500 
                    rk:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500" placeholder="Search user">
          </div>
          <ul>
               
               <li class="text-gray-900 relative cursor-default select-none py-2 pl-1 pr-9" id="listbox-option-0" role="option">
                         <a href="#" data-index="0" id="assigned_users_item_link_0" name="assigned_users_item_link_0">
                              <div class="flex items-center">
                                   <span class="font-normal ml-3 block truncate">
                                        Angela  Law
                                   </span>
                              </div>
                              <span style="display:none" id="assigned_users_item_check_0" name="assigned_users_item_check_0" class="text-indigo-600 absolute inset-y-0 right-0 flex items-center pr-4">
                                   <svg class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                                        <path fill-rule="evenodd" d="M16.704 4.153a.75.75 0 01.143 1.052l-8 10.5a.75.75 0 01-1.127.075l-4.5-4.5a.75.75 0 011.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 011.05-.143z" clip-rule="evenodd"></path>
                                   </svg>
                              </span>
                         </a>
               </li>

          </ul>
     </div>
  </div>
</div>


                         </div>

I am trying to make this keep the dropdown down open as long as any typing and clicking in happening in the dropdown section. and when it clicks or types or tabs outside that area it closes automatically

Expected an assignment or function call and instead saw an expression no-unused-expressions with react

I am developing a website using my opinion. This error appears and I do not know how to solve it

 Expected an assignment or function call and instead saw an expression  no-unused-expressions

it is appears in extraReducers section
error

my code :

const bookSlice = createSlice({
  name: 'book',
  initialState: { books: [], isLoading: false, error: null, book: null },
  reducers: {},
  extraReducers: (builder) => {
    //GET BOOKS
      builder.addCase(getBooks.pending, (state) => {
      state.isLoading = true;
      state.error = null;
    }),
      builder.addCase(getBooks.fulfilled, (state, action) => {
        state.isLoading = false;
        state.books = action.payload;
      }),
      builder.addCase(getBooks.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      }),
      // INSERT BOOK
      builder.addCase(insertBook.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      }),
      builder.addCase(insertBook.fulfilled, (state, action) => {
        state.isLoading = false;
        state.books.push(action.payload);
      }),
      builder.addCase(insertBook.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      });
  },
});

how to solve that error ?

how to optimise component that useContext in React

the question is simple but it probably has some answers that I’m still not aware of

How to optimise component, that use useContext ? Obviously this component will be rerendered every time context value changed(correct me if i’m wrong) and the same works for redux either(again correct me). I’m trying to crack this question to avoid pitfalls at interview.

I asked chat GPT and it answered me the following

import React, { useContext, memo } from 'react';

const MyComponent = memo(() => {
  const contextValue = useContext(MyContext);

});

But as far as I understand – that is not correct and won’t affect rerendering.

What I think is that we can wrap in react memo components that are children of that component that use useContext, and when we use useContext we should be aware of the price we pay to use global state, that it will cause some redundant rerenders and we can just optimize children on such components to prevent rerender (if we need it);