Using UTC for a calendar built from scratch

Let’s say I have to build a calendar from scratch in Angular or any other frontend framework. Considering the following points:

  • I can only use the native Date class.

  • It must allow users to select a date, which can be saved into their browser and loaded afterwards. The user can switch timezones, but the shown date must stay the same.

  • The selected value will be sent to a web service in a timezone agnostic format, such as DD-MM-YYYY.

Taking these points into account, I’ve decided the best option for the calendar would be to build the cells using UTC, and to expect / emit values in UTC as well. However, I’ve encountered an issue when integrating the calendar with other date components (such as datepickers), because they always reflect the date in the local timezone.

This made me think: is this really the best approach? Is there a more flexible solution?

equivalent of javascript code in swift or Objective-C

I want to convert the function in Swift or Objective-C so I can use in Native module of React Native.

export const provisionWithCertificate = async (
    scopeId,
    registrationId,
    keyPath,
    certificatePath,
  ) => {
    const data = {
      registrationId: registrationId,
    };
    const cert = await RNFS.readFile(certificatePath, 'utf8');
    const key = await RNFS.readFile(keyPath, 'utf8');

    try {
      const httpsAgent = new https.Agent({
        cert: cert,
        key: key,
      });
      console.log('httpsAgent', httpsAgent);
      const response = await axios({
        method: 'PUT',
        url: `https://global.azure-devices-provisioning.net/${scopeId}/registrations/${registrationId}/register?api-version=2021-06-01`,
        data: data,
        httpsAgent: httpsAgent,
        headers: {
          'Content-Type': 'application/json',
          'Content-Encoding': 'utf-8',
        },
      });
      return response.data;
    } catch (err) {
      console.log('err', err);
      return err;
    }
  };
  

I tried this using some AI to convert but I am not able find the satisfactory solution.

Animations in Framer Motion

I was trying to implement Framer Motion, to understand how it works, in a personal project of mine.

For now, I wrote the following code (100% working), in these two components:

  • Modal.jsx

    import { createPortal } from "react-dom";
    import { motion } from "framer-motion";
    
    export default function Modal({ title, children, onClose }) {
      return createPortal(
        <>
          <div className="backdrop" onClick={onClose} />
          <motion.dialog
            variants={{
              open: { opacity: 1, translateY: 0 },
              closed: { opacity: 0, translateY: 30 },
            }}
            initial="closed"
            animate="open"
            exit="closed"
            open
            className="modal"
          >
            <h2>{title}</h2>
            {children}
          </motion.dialog>
        </>,
        document.getElementById("modal")
      );
    }
    
  • NewChallenge.jsx

    import { useContext, useRef, useState } from "react";
    import { motion } from "framer-motion";
    
    import { ChallengesContext } from "../store/challenges-context.jsx";
    import Modal from "./Modal.jsx";
    import images from "../assets/images.js";
    
    export default function NewChallenge({ onDone }) {
      const title = useRef();
      const description = useRef();
      const deadline = useRef();
    
      const [selectedImage, setSelectedImage] = useState(null);
      const { addChallenge } = useContext(ChallengesContext);
    
      function handleSelectImage(image) {
        setSelectedImage(image);
      }
    
      function handleSubmit(event) {
        event.preventDefault();
        const challenge = {
          title: title.current.value,
          description: description.current.value,
          deadline: deadline.current.value,
          image: selectedImage,
        };
    
        if (
          !challenge.title.trim() ||
          !challenge.description.trim() ||
          !challenge.deadline.trim() ||
          !challenge.image
        ) {
          return;
        }
    
        onDone();
        addChallenge(challenge);
      }
    
      return (
        <Modal title="New Challenge" onClose={onDone}>
          <form id="new-challenge" onSubmit={handleSubmit}>
            <p>
              <label htmlFor="title">Title</label>
              <input ref={title} type="text" name="title" id="title" />
            </p>
    
            <p>
              <label htmlFor="description">Description</label>
              <textarea ref={description} name="description" id="description" />
            </p>
    
            <p>
              <label htmlFor="deadline">Deadline</label>
              <input ref={deadline} type="date" name="deadline" id="deadline" />
            </p>
    
            <motion.ul
              id="new-challenge-images"
              variants={{
                open: { transition: { staggerChildren: 0.05 } },
              }}
              initial="closed"
              animate="open"
            >
              {images.map((image) => (
                <motion.li
                  key={image.alt}
                  onClick={() => handleSelectImage(image)}
                  className={selectedImage === image ? "selected" : undefined}
                  variants={{
                    closed: { opacity: 0, scale: 0 },
                    open: { opacity: 1, scale: 1 },
                  }}
                >
                  <img {...image} />
                </motion.li>
              ))}
            </motion.ul>
    
            <p className="new-challenge-actions">
              <button type="button" onClick={onDone}>
                Cancel
              </button>
              <button>Add Challenge</button>
            </p>
          </form>
        </Modal>
      );
    }
    

All animations, after various tests, work correctly, in particular:

  • The animation in Modal.jsx, animates the <dialog> with a fade-in-from-bottom style animation

  • The animations in New Challenge.jsx animates the list <ul> by setting an animation delay on the elements of the list with staggerChildren and the list items <li> with a bounce style animation.

As mentioned above, everything works and the animations are triggered correctly.

What I wanted to understand is, where does the list <ul> get the initial state “closed” from? From the Modal?

Is there a better way to do what I’m trying to do?

I am not an expert in using this library, but I find it very useful and would like to learn how to use it in the best possible way.

Could anyone help me understand?

http fetch reset not recognized in javascript

The following JavaScript code sends a file to an embedded LWIP HTTP server in chunks.

As can be seen in the Wireshark trace, a reset sometimes occurs during transmission. In this case, the request is aborted, however the script does not receive any information from this and returns true even in case of an error.

Does anyone have a tip on how to teach the script to recognize such an error?

The function should only return true if the request was successful, otherwise the call will repeated again with the same chunk.

reset while http post

async function uploadChunk(chunk) {
  let result = false;
  const formData = new FormData();
  formData.append("file", chunk);
  sleep(10);
  
  try {
    const response = await fetch("http://" + target_ip + "/update", {
      method: "POST",
      mode: "no-cors",
      body: formData
    });
    res = await response;
    const ok_string = "OK";
    result = (response.ok & (response.statusText === ok_string));
    console.log(res);
  } catch (error) {
    console.error("Failed to upload chunk: ", error);
  }
  
  return result;
}

Get live chat open up using external button

This is my script for the live chat which is embedded in header.php in wordpress environment.

<script src="https://widgets.leadconnectorhq.com/loader.js" 
 data-resources-url="https://widgets.leadconnectorhq.com/chat-widget/loader.js" 
 data-widget-id="668ecb1edad1ad570c3c3c41"></script>

I want to use another div like structure more of a button to have it open and toggle it

I’ve tried adding js to trigger button but failed due to same-origin policy of google

How to implement global exception handling in grpc-js server interceptor?

I’m trying to implement global error handling using a gRPC server interceptor in grpc-js.

Below is my implementation:

function errorHandlingServerInterceptor(methodDescriptor, call) {
    const listener = (new grpc.ServerListenerBuilder())
        .withOnReceiveMetadata((metadata, next) => {
            try {
                next(metadata);
            } catch (error) {
                handleAndLogError(call, error);
            }
        })
        .withOnReceiveMessage((message, next) => {
            try {
                next(message);
            } catch (error) {
                handleAndLogError(call, error);
            }
        })
        .withOnReceiveHalfClose((next) => {
            try {
                next();
            } catch (error) {
                handleAndLogError(call, error);
            }
        })
        .withOnCancel(() => {
            logger.error(`Request was cancelled by the client.`);
        })
        .build();

    const responder = (new grpc.ResponderBuilder())
        .withStart(next => {
            next(listener);
        })
        .withSendMetadata((metadata, next) => {
            next(metadata);
        })
        .withSendMessage((message, next) => {
            next(message);
        })
        .withSendStatus((status, next) => {
            if (status.code !== grpc.status.OK) {
                logger.error(`Error status code: ${status.code}, details: ${status.details}`);
            }
            next(status);
        })
        .build();

    return new grpc.ServerInterceptingCall(call, responder);
}

I expected that errors thrown within the service methods would be caught by the try-catch blocks in the interceptor. However, this doesn’t seem to be happening. Can anyone explain why the errors thrown in service methods aren’t being caught and provide a solution to properly catch and handle these errors for global error handling?

html2canvas doesn’t capture text in textarea in SVG

I am working on an Angular node-based application, the nodes in which are html tables containing <textarea>. When I try to generate project previews using html2canvas, neither the text in <textarea> nor <mat-icons> are rendered, maybe it’s the same problem.
Here is the expectation/result:

And also the html structure of the component:

Why does CASL allow unrestricted read access in my conditionally defined rule?

I have defined a CASL rule for a User subject, with a condition to allow read access only to users belonging to a specific Org. Here is my implementation:

function defineAbilityFor(user) {
   const { can } = new AbilityBuilder();
   can("read", "User", { orgId: user.orgId });
   return build();
}

The rule works as expected when I check permissions for a specific user object:

defineAbilityFor({ orgId: "123" }).can("read", subject("User", { orgId: "123" })); // true

However, this also returns true:

defineAbilityFor({ orgId: "123" }).can("read", "User"); // true

I don’t understand why the second example returns true since I expected it to only allow read access when the orgId matches. Could someone explain why this is happening? A reference to the relevant documentation would be helpful.

Additionally, how can I modify my defineAbilityFor function to ensure that only the first example returns true and the second returns false?

How to create and use multiple standalone vue apps in one html page (Vue2 + Django)

Im kind off new to vue and I’m trying to implement a vue + vuetify + vuex frontend in my already half written django application, I want the vue applications to connect independently of each other in different divs of html pages

At the moment, with this connection:

<div class="tab-content" id="settings-tab-content">
    <script type="application/json" id="initial-data">
        { "is_superuser": {{ is_superuser|lower }} }
    </script>

    <div class="tab-pane fade" id="groups-tab-content" role="tabpanel" aria-labelledby="groups-tab">
        <div id="userGroups"></div>
    </div>

    <div class="tab-pane fade" id="structure-tab-content" role="tabpanel" aria-labelledby="structure-tab">
        <div id="app"></div>
    </div>
</div>
import Vue from 'vue'
import clinicStructure from './clinicStructure.vue'
import userGroups from './userGroups.vue'
import router from './router'
import store from './store'
import vuetify from './plugins/vuetify'
import '@mdi/font/css/materialdesignicons.css'
import 'vuetify/dist/vuetify.min.css'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  vuetify,
  render: h => h(clinicStructure)
}).$mount('#app')

new Vue({
  router,
  store,
  vuetify,
  render: h => h(userGroups)
}).$mount('#userGroups')

Components and building with this

    "build": "vue-cli-service build --dest=../../static/builds/prod",
    "dev": "vue-cli-service build --dest=../../static/builds/dev --mode=development --watch"

works fine but modal windows from one element open in another (in the one that is mounted first)

So, how can I make a separate vue component connect to a specific div without affecting other components

p.s. I can’t make one entry point for frontend and then process paths through vue router, I need django to give html with connected vue components

Javascript issue – pure code without using cdn or javascript library like jquery

I have code that was working with Jquery however I have been asked to convert to pure Javascript as there a preference for using JS only.

I have tried without success and also tried to use an online converter but this didn’t work great and was still giving errors.

Just wondering if someone could take a look at the jquery code that was working for suggestions on how to get the same working with Javascript only.

$('.one').click(function() {
  $(this).toggleClass('selected');
  $('.two').removeClass('selected');
});

$('.two').click(function() {
  $(this).toggleClass('selected');
  $('.one').removeClass('selected');
});

$('.ready').click(function() {
  if ($(".one").hasClass("selected")) {
    $("#sec-1").hide();
    $("#sec-2").show();
  } else if ($(".two").hasClass("selected")) {
    $("#sec-1").show();
    $("#sec-2").hide();
  }
});

$('.return').click(function() {
  $("#sec-1").show();
  $("#sec-2").hide();
  $("#grid").empty();
});

obj = JSON.parse(json - data - 1);
obj1 = JSON.parse(json - data - 2);

//create objects
function Product(image, title, link) {
  this.image = image;
  this.title = title;
  this.link = link;
}

// Create Product Objects
var used = false;

$('.btn-test').click(function(e) {
  if (used == false) {
    used = true;
    e.preventDefault();
    $("#grid").append("<br/><p class='hello'>Hello " + $('#txt_name').val() + " , <br/><br/> here's the output </p>");
    if ($(".testclass").hasClass("selected")) {
      for (var i = 0; i < obj.Products.length; i++) {
        new Product("obj.Products[i].image", "obj.Products[i].title", "obj.Products[i].link");
        $("#grid").append("<div class='grid-item'><div><img src='" + obj.Products[i].image + "</p> </div><div>" + obj.Products[i].price + "</div><div class='prod'> <a class='product' href='" + obj.Products[i].link + "'>Go to Product Page" + "</a></div></div>");
      }
      $("#grid").append("<br/><p class='grid-link'><a href=" + '' + ">Go to</a></p>");
    } else if ($(".testclass1").hasClass("selected")) {
      for (var i = 0; i < obj1.Products.length; i++) {
        new Product("obj1.Products[i].image", "obj1.Products[i].title", "obj1.Products[i].link");
        $("#grid").append("<div class='grid-item'><div><img src='" + obj1.Products[i].image + "</p> </div><div>" + obj1.Products[i].price + "</div><div class='prod'> <a class='product' href='" + obj1.Products[i].link + "'>Go to Product Page" + "</a></div></div>");
      }
      $("#grid").append("<br/><p class='grid-link'><a href=" + '' + ">Go to</a></p>");
    }
  }
  used = false;
});

Browser console is returning null for document.getElementById() (table element)

I’m very confused why my console output is null when I’m trying to get an element by id.

I have a table and I want to append rows to my table body via JS but first I need to get the tbody element by its id.

This is my code:

<tbody id='startNode'>
  <tr>
    <td>1</td>
  </tr>
<tbody>
var startNode = document.getElementById('startNode');
console.log(startNode);

I’m not sure if this could be a side effect but in a <script> I have a jQuery function and other JS functions.

$(document).ready(function() {
  $(".img-preview").click(function(ev) {
    var prevPos = $(".img-preview").position();
    console.log(prevPos);
    
    $(".marker").remove();
    
    console.log(ev.pageY - prevPos.top)
    console.log(ev.pageX - prevPos.left)
    
    $(".img-preview").append(
      $('<div class="marker"></div>').css({
        position: 'absolute',
        top: (ev.pageY - prevPos.top) + 'px',
        left: (ev.pageX - prevPos.left) + 'px',
        width: '5px',
        height: '5px',
        background: '#ff0000'
      })
    );
  });
});

If x+x has no overflow or underflow, is x+x-x always equals to x?

For example, when writing some formula, if I see something like:

x+x-x+...

(x+x-x is at the start) which if x+x has no overflow or underflow, is the result remains the same after simplifying to:

x+...

? Because I think x+x is just the exponent of the float number*2, but matissa remains unchanged, and x+x-x is just the exponent *2 and then /2, so I think it should be the same as x, but I’m not sure if it is correct.

Also I test some random numbers, which seems hold after running the following several times:

for(var i=0;i<1000;i++){
  var r=Math.random();
  if(r+r-r!=r){
    alert(r);
    break;
  }
}

How to Monkey Patch Js Class Constructor

I am fairly new to js and I have a problem that seems I can solve by modifying the constructor of a class. This does not work

// original class in lib
class BasePrinter {
  constructor() {
    console.log("BasePrinter constructor");
  }
}

// patching
function patchBasePrinter() {
  const originalConstructor = BasePrinter.prototype.constructor;

  BasePrinter.prototype.constructor = function(...args) {
    console.log("Patched constructor logic before");

    originalConstructor.apply(this, args);

    console.log("Patched constructor logic after");
  };
}

// Apply the patch
patchBasePrinter();

const printer = new BasePrinter();

The other posts ive seen on this are either inconclusive or end with a solution of patching a method instead.

The real use case is to apply new logic when any class property is changed. The system is already reactive. I just want to add new logic and all the techniques I can find have to do with patching the constructor class

how can I move script type=”text/html” to seperate file in .net mvc?

I have this script inside my index.cshtml.

<script id="meterGrid_ActionPanel" type="text/html">
    <div class='btn-group'>
        <a class='btn btn-primary btn-xs dropdown-toggle' data-toggle='dropdown'>
            <span class='caret'>
            </span>
        </a>
        <ul class='dropdown-menu'>
            <li>
                <a class='open-dynamic-modal-link'
                   data-title='Profile Capture Period for #=MeterNo#'
                   data-url='@Url.Content("~/Meters/LoadProfileCapturePeriodPartial?meterno=#=MeterNo#")'
                   data-large='false'
                   data-onload='initCheckboxes'
                   data-close='Close'
                   data-primary='Submit'>Set Profile capture Period </a>
            </li>
        </ul>
    </div>
</script>

And this code then used in kendo grid column template using javascript function.

function getMetersActionPanel(data) {
    return kendo.template($("#meterGrid_ActionPanel").html())(data);
}

Here is the kendo MVC grids basic representation

.Columns(c =>
{  
    c.Template(m => @Html.ActionLink("", "", "", null))
        .Width(75)
        .ClientTemplate("#= getMetersActionPanel(data) #");
})

What I want to do?

Now what I really want do it to move this script #meterGrid_ActionPanel to seperate file as it has lots of content and separating the HTML template from main view file will make the code cleaner and more modular.

What I tried So far?

I tried to load this html through partial view and ajax call, but I think it’s not a proper way to have server side call for each column. I have around 28000 columns in each grid so. I have also checked the js and html file options but no luck with that.

Main complexity that I need to handle along with this implementation

  • the script has parameters that I need to pass from javascript function getMetersActionPanel side, check data parameter which contains around 11-12 properties.

Any help or suggestion would be highly appreciated!

Laravel for Front End

I’m Front End and We have a Laravel project on GitHub, and I previously cloned it using git clone. The team has now made updates to the project, and I want to download these updates into my local project so I can run it in VS Code.
I use Composer and Laragon on Windows 11.

I’m Front End | Laravel