Can’t find assets folder

I’m trying to replicate a site, so I downloaded all the folders of it and changed it. It worked, but I have a problem with the following part,it doesn’t show anything after “Featured Highlights” , but it should show some scrolling pictures. I don’t have my assets folder, or better, I don’t have this path assets/img, all the pictures are saved in my images folder. I have the js files too.

 <section data-scroll-index="3" class="section work-section border-top-g">
        <div class="container">
            <div class="row justify-content-center section-heading">
                <div class="col-lg-15 text-center">
                    <h6><span class="text-theme">Highlights</span></h6>
                    <h3>Featured Highlights</h3>
                    <p>Here are some awards, articles, documents, certificates, and whatever else I am proud of.</p>
                </div>
            </div>
            <div class="owl-carousel lightbox-gallery" data-items="3" data-nav-dots="true" data-md-items="3" data-sm-items="2" data-xs-items="2" data-xx-items="1" data-space="30" data-autoplay="true">
                <div class="work-box mb-4">
                    <div class="work-img">
                        <a class="gallery-link" href="assets/img/Graduation.jpg">
                            <img src="images/Graduation.jpg" title="Graduation" alt="Magna Cum Laude Graduation">
                        </a>
                    </div>
                    <div class="work-info">
                        <div class="meta">
                            <span class="text-theme">2nd Bachelor's Graduation!</span>
                        </div>
                        <h5>Graduation Photo, December 2022</h5>
                        <p>I did it! I got my second bachelor's degree in computer science, somehow with Magna Cum Laude latin distiction too!</p>
                        <div class="btn-bar">
                            <a class="link-effect gallery-link" href="assets/img/Graduation.jpg">View Picture <i class="bi bi-arrow-up-right"></i></a>
                        </div>
                    </div>
                </div>
                
                <div class="work-box mb-4">
                    <div class="work-img">
                        <a class="gallery-link" href="assets/img/2023_Cybercamp_Anon_2.JPG">
                            <img src="images/2023_Cybercamp_Anon_2.JPG" title="Cyber Camp 2023" alt="CSU Cyber Camp 2023">
                        </a>
                    </div>
                    <div class="work-info">
                        <div class="meta">
                            <span class="text-theme">CyberChallenge 2022</span>
                        </div>
                        <h5>CyberChallenge 2022</h5>
                        <p> I had the opportunity to attend this amazing project. CyberChallenge taught me about penetration testing, Osint, Cryptography and not only in a theorical way, but I had the opportunityto try all this and earn experience in this field. It was based on Capture The flag game, whiche made me cooperate with other guys verusus other teams.
                        

                        </div>
                    </div>
                </div>
                
                
                <div class="work-box mb-4">
                    <div class="work-img">
                        <a class="gallery-link" href="assets/img/Cybersec_Intern_Poster.jpg">
                            <img src="images/Cybersec_Intern_Poster.jpg" title="Cybersecurity internship Poster" alt="Cybersecurity internship Poster">
                        </a>
                    </div>
                    <div class="work-info">
                        <div class="meta">
                            <span class="text-theme">CyberSecurity Internship Team</span>
                        </div>
                        <h5>Poster showing the cybersecurity internship team at Colorado State University</h5>
                        <p>Thanks to the great team at Colorado State University I have been able to further my skills in ways school alone would not have taught.</p>
                        <div class="btn-bar">
                            <a class="link-effect gallery-link" href="assets/img/Cybersec_Intern_Poster.jpg">View Picture <i class="bi bi-arrow-up-right"></i></a>
                        </div>
                    </div>
                </div>
                <div class="work-box mb-4">
                    <div class="work-img">
                        <a class="gallery-link" href="assets/img/Biocybersecurity_Winners.jpg">
                            <img src="images/Biocybersecurity_Winners.jpg" title="Third Place Winners!" alt="Cybersecurity competition winners">
                        </a>
                    </div>
                    <div class="work-info">
                        <div class="meta">
                            <span class="text-theme">BioCybersecurity Hackathon 3rd Place Winners</span>
                        </div>
                        <h5>Placed 3rd at the Bio-Cybersecurity Hackathon</h5>
                        <p>Blake Davis, Tyson O'Leary and I placed third at the annual Biocybersecurity competition. It was an fun and challenging event that involved problems that bordered the intersection of biochemistry and computer science. Check out this article about the challenge -&gt;&gt; <a href="https://natsci.source.colostate.edu/top-3-sweep-computer-science-students-propel-winning-teams-at-bio-cybersecurity-student-challenge/">Article</a></p>
                        <div class="btn-bar">
                            <a class="link-effect gallery-link" href="assets/img/Biocybersecurity_Winners.jpg">View Picture <i class="bi bi-arrow-up-right"></i></a>
                        </div>
                    </div>
                </div>

I guess I’m missing this script

    <script src="assets/vendor/bootstrap/js/bootstrap.min.js"></script>


                

How Can I Resolve a “Couldn’t Find a Component Error”?

Currently, I am having a problem that when I am trying to render Ionicons using Fonts.loadAsync, it works, but it gave me an error, and I fixed it, but then another error popped up, one that I can understand, but can solve in this situation, because it seemed like nonsense since I did everything correct. The error is: “Couldn’t Find A Component, getComponent, or children for the Screen ——-” (hiding screen name). I already have everything in the correct position and correct place, but it didn’t do anything.

Here is my Navigator Code for App.js:

// import { StatusBar } from 'expo-status-bar';
import * as Font from "expo-font"
import { StyleSheet,
  Text,
  Platform, 
  View, 
  SafeAreaView, 
  Button, 
  Alert,
  Dimensions} from 'react-native';
import {useDeviceOrientation, useDimensions} from '@react-native-community/hooks'
import React, {useCallback} from "react";
import WelcomeScreen from './app/assets/screens/WelcomeScreen';
import SigningInFirst from "./app/assets/screens/SigningInFirst";
import SettingsScreen from "./app/assets/screens/SettingsScreen";
import {useNavigation, NavigationContainer} from "@react-navigation/native"
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import SecondLoginScreen from './app/assets/screens/SecondLoginScreen';
import ThirdSignStep from './app/assets/screens/ThirdSignStep';
import LoginScreen from './app/assets/screens/LoginScreen';
import MapScreen from './app/assets/screens/MapScreen';
import BottomTabNavigation from './app/assets/screens/BottomTabNavigation';
import MessagingScreen from './app/assets/screens/MessagingScreen'
import Profile from './app/assets/screens/Profile'
const Stack = createNativeStackNavigator();
export default function App() {
// const orient  = useDeviceOrientation();
// const handlePress = () => console.log("ArrivTrack")
// const navigation = useNavigation();


  return (
    // <WelcomeScreen />
    // <SignInJs />
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name = "WelcomeScreen" component={WelcomeScreen} options={{headerShown:false}} />
        <Stack.Screen name = "Message" component={MessagingScreen} options={{headerShown:false}} />
        <Stack.Screen name = "Profile" component={Profile} options={{headerShown:false}} />
        <Stack.Screen name = "Step1" component={SignInJs} options={{headerShown:false}} />
        <Stack.Screen name = "Step2" component={SecondLoginScreen} options={{headerShown:false}} />
        <Stack.Screen name = "Step3" component={ThirdSignStep} options={{headerShown:false}} />
        <Stack.Screen name = "LoginPage" component={LoginScreen} options={{headerShown:false}} />
        <Stack.Screen name = "MapScreen" component={MapScreen} options={{headerShown:false}} />
        <Stack.Screen name = "SettingsScreen" component={SettingsScreen} options={{headerShown:false}} />
        <Stack.Screen name = "BottomTabNavigation" component={BottomTabNavigation} options={{headerShown:false}}/>
      </Stack.Navigator>
    </NavigationContainer>
    
  );
}

const stylesContainer = {backgroundColor:"black"}
const textStyles = {color:"white"}
const buttonStyles = {color:"white", backgroundColor:"dodgerblue"}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
    paddingTop: Platform.OS === 'android' ? 20: 0,
    justifyContent: "center",
    alignItems: "center",
    // color: "white",
  },
});

And my code for the Fonts.loadAsync:

import * as Font from "expo-font";
export async function loadFontsAsync(){
    await Font.loadAsync({
        ionicons:require("./Ionicons.ttf")
        
    })
}

And the code for the page where the weird error is being caused:

import * as React from 'react';
import { View, Text, Ionicons } from 'react-native';
import { loadFontsAsync } from './loadFonts';

const Profile = () => {
  const [fontsLoaded, setFontsLoaded] = React.useState(false);

  React.useEffect(() => {
    const loadFonts = async () => {
      await loadFontsAsync();
      setFontsLoaded(true);
    };

    loadFonts();
  }, []);

  if (!fontsLoaded) {
    return <Text>Loading fonts...</Text>; // Or render a loading indicator
  }

  return (
    <View>
      <Ionicons fontFamily="ionicons" name="person" color="red" size={36} />
      {/* Other components */}
    </View>
  );
};

export default Profile;

And the error image:

error

  • I tried to solve this by myself first, since I knew how to fix it.
  • Tried Using a bit of AI help.

I expected that the error would go away if I corrected syntax, and I would see my image. But it actually turned out to be false and the error that I don’t know why is there is hanging around.

Javascript variable const and let

So i was studying that you can update value of let variable but not of const variable but the const variable was still declared when i wrote the following code:

let a = 24;    
const b = a + 5;    
console.log(b);

and i still got answer 29 so what is that i am thinking wrong.
even this code didn’t show any error in vs code,
code is ;-

let a;
const b = 0;
for (a= 1 ;a<= 5 ;a=a+1){
     b = a+ 5;
}
console.log(b);

but in edge’s console log it shoed this error:-
Uncaught TypeError: Assignment to constant variable.
at first.js:6:8

What I tried is mentioned above, and I was expecting it to show an error that const cannot be updated, but it gave me the answer.

What should I do to ensure that data is passed individually for each session entry on the website?

General Description:
I am developing a website with software using:
frontend – HTML, CSS, JavaScript (TypeScript), Angular
backend – Java, Spring, Rest

Problem Description:
The problem is that I would like to create some random (or pseudo-random) variable unique to each session entry, so that without sending requests and creating endpoints, this variable would be the same for files written in TypeScript and Java (Spring). It seems to me that some sort of session ID code would need to be written to create unique submission paths and endpoints for each individual entry.

General Problem Description:
I need some tool to ensure that data entered by the user is sent individually for each session entry. Because I’m afraid that if several people visit my site at the same time and input data from different devices, they may overlap with each other or overwrite each other.
Let’s assume such a situation:
In session 1, Grześ enters data, e.g., the number 20, and sends it to the server, and at the same time, in session 2, Maciek enters data, e.g., the number 40. Both Grześ and Maciek receive a response as if the last value entered, i.e., 40, was entered.

I absolutely must prevent such a situation!

Dear users, do you have any ideas for solving this problem?

I tried adding a counter to each session and incorporating that counter into the request paths and endpoints… Unfortunately, it didn’t work.

I also attempted to implement session ID code in Spring Security, but ended up breaking half of the application without achieving any result…

And I’m not sure how to solve the problem of introducing individual data for each session entry on the website in a way that avoids conflicts with multiple users overwriting data entered at the same time.

Why does 1 is printed before 4 in this execution of js code?

async function check() {
  await Promise.resolve(console.log(1));
  console.log(2);
}
console.log(3);
check();
console.log(4);

The answer is 3,1,4,2

As I know the async function will go to web API to resolve and main program will execute first so I thought
the output will be 3, 4 , 1 , 2 but that’s wrong.

Can anyone explain this in terms of event loop and micro task queue how the correct answer is executed.

Uncaught TypeError: messages[0] is undefined

I’m trying to add a timestamp to every message in a chat app. There is a component called MessageHistory where I’m trying to do that.

function MessageHistory({ messages }) {
  const activeUser = useSelector((state) => state.activeUser)
  const date = new Date(messages[0].createdAt)
  const hour = date.getHours();
  const minute = date.getMinutes();
  const timestamp = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2,'0')}`;
  ....
  <Box mr={2}><span>{timestamp}</span></Box>
  ....

messages is the array containing all the messages of a chat. This piece of code throws a type error in the ui.

Problem with javascript code in react app

Working on this react webpage switching from standard html and it does nothing when i click the dark/light Theme Toggle button i wrote using addEventListener(‘click’..) i believe this to be the issue as i haven’t managed to get it to work in other parts of the code. I’ve made sure the ID is correct and the names of the files are correct.
This one simple non-working use case i’ve tried: to move to the TV Show page after clicking TV Show in home navigation bar.

document.getElementById('TV-Shows').addEventListener('click', function(event) {
    event.preventDefault(); // prevent default link behavior
    console.log("TV Shows link clicked");
    // Redirect to TV Shows page
    window.location.href = 'TVShows.html';

Does nothing as in when i click the ‘TV Show’ nav it stays on the previous page ‘home page’.


 <li><a id="TV-Shows" href="#">TV
        Shows</a></li>


Another place, as mentioned, i’ve tried to use it is in the logic for a dark-mode/light-mode toggle button.

document.getElementById('theme-toggle').addEventListener('click', function(event) {
    event.preventDefault();
    const body = document.body;
    if (body.classList.contains('light-mode')) {
        body.classList.remove('light-mode');
        body.classList.add('dark-mode');
    } else {
        body.classList.remove('dark-mode');
        body.classList.add('light-mode');
    }

});
});

The CSS code for this is just #dark-mode and #light-mode(i.e code for color and background colour) both are correct as i’ve called it separately in the html file as


<div class="dark-mode"> 

And vice versa. Page colour changes.

Laravel Livewire ‘wire:click’ not functioning on Table Component

I am building a base layout for listing the records using Laravel Livewire.

<div class="card shadow" x-data="{ table:@entangle('table').live }">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <div class="m-0 font-weight-bold text-primary">Details</div>
        <div class="dropdown no-arrow">
            <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right shadow animated--fade-in" aria-labelledby="dropdownMenuLink">
                <template x-for="column in table.columns">
                    <div class="dropdown-item form-group">
                        <div class="custom-control custom-checkbox" x-id="['checkbox']">
                            <input :id="$id('checkbox')" class="custom-control-input" type="checkbox" x-model="table.columns.find(x => x.label === column.label).visible">
                            <label class="custom-control-label" :for="$id('checkbox')" x-text="column.label"></label>
                        </div>
                    </div>
                </template>
            </div>
        </div>
    </div>
    <div class="card-body">   
        <div class="table-responsive">
            <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                <thead>
                    <tr>
                        @foreach ($table->columns as $column)
                            <th x-show="table.columns.find(x => x.label == `{{ $column['label'] }}`).visible" data-orderable="true">{{ $column['label'] }}</th>
                        @endforeach
                    </tr>
                </thead>
                <tbody>
                    @forelse ($data as $collection)
                        <tr>
                            @foreach ($table->columns as $row)                             
                                <td class="align-middle" x-show="table.columns.find(x => x.label == `{{ $row['label'] }}`).visible">
                                    @if (is_array($row['options']))
                                        @isset($row['options']['_action'])

                                            {{-- Blade Component: Table Action --}}

                                        @endisset

                                        {{-- Some code... --}}

                                    @else

                                        {{-- Display data here.... --}}

                                    @endif
                                </td>
                            @endforeach
                        </tr>
                    @empty
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

table-action.blade.php

<div class="d-flex align-content-center flex-wrap" role="group" aria-label="Basic example">
    @foreach ($row['options']['_action'] as $action)
        @php
            $tag = isset($action['href']) ? 'a' : 'button';

            $classes = [
                'm-1 btn btn-sm',
                'btn-icon-split' => $action['icon'] ?? false,
                'btn-primary' => $action['color'] === 'primary',
                'btn-danger' => $action['color'] === 'danger',
                'btn-success' => $action['color'] === 'success',
            ];
        @endphp
        @if(!isset($action['can']) || Gate::allows($action['can'], $collection))
            <{{ $tag }} {{ (new IlluminateViewComponentAttributeBag($action))->class($classes)->except(['can', 'color', 'icon', 'label']) }}>
                @isset($action['icon'])
                    <span class="icon"><i class="fas fa-sm {{ $action['icon'] }}"></i></span>
                @endisset
                @isset($action['label'])
                    <span class="text">{{ $action['label'] }}</span>
                @endisset
            </{{ $tag }}>
        @endif
    @endforeach
</div>

Assuming the array for $row['options']['_action']:

$options = [
    '_action' => [
        [
            "label" => "Edit",
            "can" => "update",
            "icon" => "fa-edit",
            "color" => "primary",
            "href" => route('example.edit', [ 'record' => '_data:id' ]),
        ],

        [
            "label" => "Delete",
            "can" => "delete",
            "icon" => "fa-trash",
            "color" => "danger",
            "type" => "button",
            "wire:click" => "delete(_data:id)",
            "wire:confirm" => "Are you sure you want to delete this record?"
        ]
    ],
];

Here, _data:id is equivalent to $collection->id which is handled separately on the loop statement above.

Now, when I click the action button, wire:click and wire:confirm are both not working.

Let’s demonstrate my issue in the short:

Button:

<button type="button" wire:click="test()" wire:confirm="Are you sure?" x-bind:click="console.log('Button clicked!')">Button</button>

Table:

<div>
    {{-- Working here. --}}
    <table>
        {{-- Working here. --}}
        <tbody>
            {{-- Working here. --}}
            <tr>
                {{-- Working here. --}}
                <td>
                    {{-- Not working here... --}}
                </td>
            </tr>
        </tbody>
    </table>
</div>

Even, alpine x-bind:click="console.log('Button clicked!')" is running before the button is clicked. Also, I tried moving the Blade component to the Livewire component but my issues were not resolved.

Could anyone identify the issue I’m currently encountering?

GridArea in a JSX file

Beginner here. I’m developing a Word Add-in using the React framework in OfficeJS.

I’m trying to position my components using Grid. My GridTemplateAreas loads correctly. However, I can’t position my components in my Grid by using GridArea. My components are positioned one after the other in the different areas, from left to right and from top to bottom, without taking into account the GridArea I’ve assigned them.

This doesn’t seem to be an issue with the style, as the background color loads correctly.

Here is my App.jsx :

import PropTypes from "prop-types";
import React from "react";

const useStyles = makeStyles({
  container: {
    display: "grid",
    minHeight: "100vh",
    gridGap: "20px",
    gridTemplateColumns: "1fr 5fr",
    gridTemplateAreas: `
                    'sidebar header'
                    'sidebar herolist'
                    'sidebar footer'
                   `,
  },
sidebar: {
    gridArea: "sidebar",
    backgroundColor: "blue",
    textAlign: "center",
  },
  herolist: {
    gridArea: "herolist",
    backgroundColor: "yellow",
    textAlign: "center",
  },
  header: {
    gridArea: "header",
    backgroundColor: "green",
    textAlign: "center",
  },

  footer: {
    gridArea: `footer`,
    backgroundColor: "red",
    textAlign: "center",
  },
});

const App = (props) => {
  const styles = useStyles();

  return (
    <div className={styles.container}>
      <div className={styles.sidebar}>Sidebar</div>
      <div className={styles.header}>Header</div>
      <div className={styles.herolist}>Herolist</div>
      <div className={styles.footer}>Footer</div>
    </div>
  );
};

App.propTypes = {
  title: PropTypes.string,
};

export default App;

Here’s the result, showing that the components have not been positioned in the dedicated area:

enter image description here

Do you have any idea why my GridArea property is not taken into account?

Thanks in advance.

jQuery Ajax passing value on php same page – update

How to retrieve:

<div id="test">
  <?php
    if (isset($_POST['sweets']))
    {
      ob_clean();
      echo $_POST['sweets'];
      exit;
    }
  ?>
</div>

<form id="a" action="" method="post">
  <select name="sweets" onchange="change()" id="select1">
    <option >Chocolate</option>
    <option selected="selected">Candy</option>
    <option >Taffy</option>
    <option >Caramel</option>
    <option >Fudge</option>
    <option >Cookie</option>
  </select>
</form>

   <!-- Script -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  function change() {
    var sweets = $("#select1").val();
    $.ajax({
      type: "POST",
      data: { sweets: sweets },
      success: function(data) {
        $("#test").html(data);
      }
    });
  }
</script>

passing value to php string:

$string = $_POST['sweets'];
<!-- I'm looking for this: -->

I hope this is possible. I’ve looked around stackoverflow and google for an answer but could not find one for my purpose.

D3.js Error transition arc ” attribute d: Expected arc flag (‘0’ or ‘1’),”

I am currently trying to create a sunburst chart using the sunburst library. Thanks to the help from this forum, I was able to add an update function. Now, I always get the following error message at the transition of an ARC-element when my Datasource will be updated (image below):

<path> attribute d: Expected arc flag ('0' or '1'),"

As shown here and here, there seems to be a problem with the transition of the ARC-elements. The D3’s default transition can’t interpolate my ARC-Elements correctly.

So, as described in the entries, I added the custom interpolator as a function and linked it to my transition.

Unfortunately it does not work, the error still occurs.

Can someone please explain to me why it doesn’t work and how the error can be corrected?

arcTween function:

        // Custom interpolator
        function arcTween(a) {
            var i = d3.interpolate(this._current, a);
            this._current = i(0);
            return function(t) {
                return arc(i(t));
            };
        }

Image of Error
enter image description here

My Code:

            // Data
            const data1 = {
            "name": "TOPICS",
            "id": 1,
            "children": [{
                "name": "Topic A",
                "id": 2,
                "children": [{
                    "name": "Sub A1",
                    "id": 5,
                    "size": 4
                    }, {
                    "name": "Sub A2",
                    "id": 6,
                    "size": 4
                    }]
            }, {
                "name": "Topic B",
                "id": 3,
                "children": [{
                    "name": "Sub B1",
                    "id": 7,
                    "size": 3
                    }, {
                    "name": "Sub B2",
                    "id": 8,
                    "size": 3
                    }, {
                    "name": "Sub B3",
                    "id": 9,
                    "size": 3
                    }]
            }, {
                "name": "Topic C",
                "id": 4,
                "children": [{
                    "name": "Sub A3",
                    "id": 10,
                    "size": 4
                    }, {
                    "name": "Sub A4",
                    "id": 11,
                    "size": 4
                    }]
            }]
            };

            const data2 = {
            "name": "TOPICS",
            "id": 1,
            "children": [{
                "name": "Topic A",
                "id": 2,
                "children": [{
                    "name": "Sub A1",
                    "id": 5,
                    "size": 4
                    }, {
                    "name": "Sub A2",
                    "id": 6,
                    "size": 4
                    }]
            }, {
                "name": "Topic B",
                "id": 3,
                "children": [{
                    "name": "Sub B1",
                    "id": 7,
                    "size": 3
                    }, {
                    "name": "Sub B2",
                    "id": 8,
                    "size": 3
                    }, {
                    "name": "Sub B3",
                    "id": 9,
                    "size": 3
                    }]
            }]
            };

            //-------------------------------------------------------------------------------------------            
            // Declare variables
            let i_region_static_id = "sunburst",
            parentDiv = document.getElementById(i_region_static_id),
            width = parentDiv.clientWidth,
            height = 450,
            root,
            rootDepth,
            x,
            y,
            arc,
            middleArcLine,
            middleAngle,
            color = d3.scaleOrdinal(d3.schemeCategory10);
            maxRadius = (Math.min(width, height) / 2) - 5;


            const partition = d3.partition();
            //-----------------------------------------------------------------------------------
            // SVG-Element
            let svg = d3.select('#' + i_region_static_id).append('svg')
                            .style('width', width)
                            .style('height', height)
                            .attr('viewBox', `${-width / 2} ${-height / 2} ${width} ${height}`)
                            .on('dblclick', d => {
                                if (event.detail === 2) focusOn() // Double click
                            });
            //-----------------------------------------------------------------------------------
            // X-Scale
            x = d3.scaleLinear()
                    .range([0, 2 * Math.PI])
                    .clamp(true);

            //-----------------------------------------------------------------------------------
            // Y-Scale
            y = d3.scaleSqrt()
                    .range([maxRadius * .1, maxRadius]);

            //-------------------------------------------------------------------------------------------
            // Text-fit constant
            const textFits = d => {
                    const CHAR_SPACE = 6;

                    const deltaAngle = x(d.x1) - x(d.x0);
                    const r = Math.max(0, (y(d.y0) + y(d.y1)) / 2);
                    const perimeter = r * deltaAngle;

                    return d.data.name.length * CHAR_SPACE < perimeter;
            };

            //-----------------------------------------------------------------------------------
            // Create Arc generator
            arc = d3.arc()
                .startAngle(d => x(d.x0))
                .endAngle(d => x(d.x1))
                .innerRadius(d => Math.max(0, y(d.y0)))
                .outerRadius(d => Math.max(0, y(d.y1)))

            //-----------------------------------------------------------------------------------
            middleArcLine = d => {
                const halfPi = Math.PI / 2;
                const angles = [x(d.x0) - halfPi, x(d.x1) - halfPi];
                const r = Math.max(0, (y(d.y0) + y(d.y1)) / 2);

                const middleAngle = (angles[1] + angles[0]) / 2;
                const invertDirection = middleAngle > 0 && middleAngle < Math.PI; // On lower quadrants write text ccw
                if (invertDirection) {
                    angles.reverse();
                }

                const path = d3.path();
                path.arc(0, 0, r, angles[0], angles[1], invertDirection);
            return path.toString();
            }

            //-------------------------------------------------------------------------------------------
            // Check if node in depth
            function maxDepth(d) {
            if (rootDepth == undefined) { // If user clicks next to sun = root undefined
                rootDepth = 0;
            }
            return ((d.depth - rootDepth) < 2);
            }

            //-------------------------------------------------------------------------------------------
            // Custom interpolator
            function arcTween(a) {
                var i = d3.interpolate(this._current, a);
                this._current = i(0);
                return function(t) {
                    return arc(i(t));
                };
            }

            //-------------------------------------------------------------------------------------------
            function focusOn(d = {
                    x0: 0,
                    x1: 1,
                    y0: 0,
                    y1: 1
            }) {
            // Reset to top-level if no data point specified

            // Activate top-level node if no data point specified 
            if (d.data == undefined) {
                svg.selectAll(".slice")
                .filter(d => d.parent == undefined && d.children != undefined)
                // .each(function(d) {
                //     activateNode(d);
                // });
            }

            root = d; // Root-node
            rootDepth = root.depth; // Root node depth for maxDepth(d)

            const transition = svg.transition()
                .duration(750)
                .tween('scale', () => {
                const xd = d3.interpolate(x.domain(), [d.x0, d.x1]),
                    yd = d3.interpolate(y.domain(), [d.y0, 1]);
                return t => {
                    x.domain(xd(t));
                    y.domain(yd(t));
                };
                });

            transition.selectAll('.slice')
                .attr('display', d => maxDepth(d) ? null : 'none'); // Display nodes only in depth for transition

            transition.selectAll('path.main-arc')
                .filter(d => maxDepth(d))
                .attrTween('d', d => () => arc(d));

            transition.selectAll('path.hidden-arc')
                .filter(d => maxDepth(d))
                .attrTween('d', d => () => middleArcLine(d));

            transition.selectAll('text')
                .filter(d => maxDepth(d))
                .attrTween('display', d => () => textFits(d) ? null : 'none'); // Display text only in depth

            moveStackToFront(d);

            // Foreground nodes -> inner nodes higher than outer nodes 
            function moveStackToFront(elD) {
                svg.selectAll('.slice').filter(d => d === elD)
                .each(function(d) {
                    this.parentNode.appendChild(this);
                    if (d.parent) {
                    moveStackToFront(d.parent);
                    }
                })
            }
            }

            //-------------------------------------------------------------------------------------------
            // Initialize and Update sun 
            function sun(pData) {
                // const color = d3.scaleOrdinal(d3.quantize(d3.interpolateRainbow, pData.children.length + 1));
                root = d3.hierarchy(pData); //set data

                root.sum(d =>
                    (d.children == undefined) ? ((d.size == undefined) ? 1 : d.size) : 0 //parent value defined by childrens values
                );

                const slice = svg.selectAll('g.slice')
                    .data(
                    partition(root)
                    .descendants(),
                    function(d) { return d.data.id; }
                    );

                //-------------------------------------------------------------------------------------------
                // Enter Section
                const newSlice = slice.enter()
                                        .append('g').attr('class', 'slice')
                                        .attr('display', d => d.depth < 2 ? null : 'none') // Hide levels lower depth
                                        .on('dblclick', (e, d) => {
                                                            e.stopPropagation();
                                                            focusOn(d);
                                                            })

                newSlice.append('path')
                            .attr('class', 'main-arc')
                            .style('fill', d => (d.data.color == undefined) ? color((d.children ? d : d.parent).data.name) : d.data.color) //set source color, otherwise default color
                            .attr('d', arc);

                newSlice.append('path')
                        .attr('class', 'hidden-arc')
                        .attr('id', (_, i) => `hiddenArc${i}`)
                        .attr('d', middleArcLine);

                const text = newSlice.append('text')
                        .attr('display', d => textFits(d) ? null : 'none'); // Hide text on lower levels


                text.append('textPath')
                        .attr('startOffset', '50%')
                        .attr('xlink:href', (_, i) => `#hiddenArc${i}`)
                        .text(d => d.data.name) // Set text in sector 
                        .attr('fill', d => 'black');
                
                // Update Section
                slice.select('path')
                        .attr('class', 'main-arc')
                        .style('fill', d => (d.data.color == undefined) ? color((d.children ? d : d.parent).data.name) : d.data.color)
                        .each(function(d) {
                            this.x0 = d.x;
                            this.dx0 = d.dx;
                        })
                        .transition().duration(500).attrTween("d", arcTween)
                        .attr("d", arc);
                
                slice.select('.hidden-arc')
                        .attr('class', 'hidden-arc')
                        .attr('id', (_, i) => `hiddenArc${i}`)
                        .each(function(d) {
                            this.x0 = d.x;
                            this.dx0 = d.dx;
                        })
                        .transition().duration(500).attrTween("d", arcTween)
                        .attr('d', middleArcLine);

                slice.select('text')
                        .attr('display', d => textFits(d) ? null : 'none');
                
                slice.select('textPath')
                        .attr('startOffset', '50%')
                        .attr('xlink:href', (_, i) => `#hiddenArc${i}`)
                        .transition().duration(500)
                        .text(d => d.data.name) // Set text in sector 
                        .attr('fill', d => 'black');

                // Delete Section
                // slice.exit().transition().duration(500).style("fill-opacity", 0.2).remove();
                slice.exit().transition().duration(500).style("fill-opacity", 0.2).remove();
            }

            //-------------------------------------------------------------------------------------------

            sun(data1)

            let i = 0;
            d3.interval(() => {
            if (i++ % 2 === 0) {
                console.log("data2")
                sun(data2);
            } else {
                console.log("data1")
                sun(data1);
            }

            }, 2000)
.slice {
    cursor: pointer;
}

.slice .main-arc {
    stroke: #fff;
    stroke-width: 1px;
}

.slice .hidden-arc {
    fill: none;
}

.slice text {
    pointer-events: none;
    text-anchor: middle;
}
<!DOCTYPE html>
<html>             
<!-- Code Vorschlage mit STRG+Leertaste aktivieren-->
    <head>              
        <link rel="stylesheet" href="sun.css">
        <meta charset="utf-8" />    <!-- Welche Sonderzeichen verwendet werden können -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />    <!-- Wie sollte sich die Seite auf einem Handy verhalten -->
        <title> Sunbrust2 </title>      <!-- title als Tag -->
        <!-- Load plotly.js into the DOM -->
        <script src='https://cdn.plot.ly/plotly-2.11.1.min.js'></script>
        <style>

        </style>
    </head>
    <body>             
        <div id="sunburst"></div>
        <script src="https://d3js.org/d3.v7.js" charset="utf-8"></script>
        <!-- <script src="https://d3js.org/d3.v4.min.js" charset="utf-8"></script> -->
        <script src="https://unpkg.com/d3fc" charset="utf-8"></script> 
    </body>     <!-- HTML schließender Tag--> 
</html>     <!-- HTML schließender Tag-->

How to use DaprServer instance for exposing API endpoints and receiving events in Javascript at the same time?

Given the following JavaScript application running on Node on the Dapr runtime:

import { DaprServer, CommunicationProtocolEnum } from "@dapr/dapr";
import express from "express";

const myApp = express();

myApp.get("/my-custom-endpoint", (req, res) => {
  res.send({ msg: "My own express app!" });
});

const daprServer = new DaprServer({
      serverHost: "127.0.0.1",
      serverPort: "3000",
      serverHttp: myApp,
    });

await daprServer.pubsub.subscribe("pubsub", "messages", async (messageId) => {
        console.log(`Subscriber received: ${JSON.stringify(messageId)}`)
    });

await daprServer.start();

In this example, we would like to use the daprServer instance to both:

  • Expose HTTP API endpoints
  • Listen to events from the pubsub pubsub on the messages topic

However when running this via dapr run --app-id background-with-api --app-port 3000 -- node main.js, event listening seems to be disabled.

The same setup is actually feasible with C# and asp.net core, since node now supports threads I don’t see why this doesn’t work with Javascript?

Am I missing something ?

Custom Json parser unable to process the string value for the key

I am trying to write my own JSON parser code but it is throwing error.
I notice following issues for the sample JSON code: {"name":"John","age": 30}

-> My code is unable to read the string value Jhon
-> It is always taking numeric value along with } with value 30

below is my code for the JSON parser:

function customJSONParse(jsonString){
    const sanitizedString = jsonString.replace(/s/g, '');

    if(sanitizedString[0]==='{'){
        return parseObject(sanitizedString);
    }else if(sanitizedString[0]==='['){
        return parseArray(sanitizedString);
    }else{
        throw new SyntaxError('Unexpected token');
    }
}

function parseObject(jsonString){
    const object={};
    let key;
    let value;
    let startIndex=1;
    while(jsonString[startIndex]!=='}'){
        const colonIndex= jsonString.indexOf(':',startIndex);
        key=jsonString.substring(startIndex,colonIndex).replace(/"/g,'');
        const commaIndex=jsonString.indexOf(',',colonIndex);

        const valueString = jsonString.slice(colonIndex+1,commaIndex!==-1?colonIndex:undefined);
        value= parseValue(valueString); 
        object[key]=value;
        startIndex=commaIndex!=-1?commaIndex+1:jsonString.length-1;
    }
    return object;
}

function parseValue(valueString){
    if(valueString==='true'){
        return true;
    }else if(valueString==='false'){
        return false;
    }else if(valueString==='null'){
        return null;
    }
    else if(!isNaN(valueString)){
        return parseFloat(valueString);    
    } 
    else if(valueString[0]==='"'){
        return valueString.slice(1,-1);
    }
    else{
        throw new SyntaxError('Unexpected Token');
    }

}

Can anyone help me to fix the logical issue in my code?

Block file opening when drag and drop

I use the following script to upload files using drag and drop.

// dragover and dragenter events need to have 'preventDefault' called
// in order for the 'drop' event to register. 
// See: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Drag_operations#droptargets
dropContainer.ondragover = dropContainer.ondragenter = function(evt) {
  evt.preventDefault();
};

dropContainer.ondrop = function(evt) {
  // pretty simple -- but not for IE :(
  fileInput.files = evt.dataTransfer.files;

  // If you want to use some of the dropped files
  const dT = new DataTransfer();
  dT.items.add(evt.dataTransfer.files[0]);
  dT.items.add(evt.dataTransfer.files[3]);
  fileInput.files = dT.files;

  evt.preventDefault();
};
<!DOCTYPE html>
<html>
<body>
<div id="dropContainer" style="border:1px solid black;height:100px;">
   Drop Here
</div>
  Should update here:
  <input type="file" id="fileInput" />
</body>
</html>

If I upload multiple files at once, it’s OK, it work.
But if I upload only a file, the browser open the file in a new tab.
How to do to block this action and only put the file in the box ?

React SSR with async reducer – Unexpected key found in preloadedState argument passed to createStore

I am trying to implement code splitting in my redux code of react application using the injectReducer approach. It works well with only client side rendering but fails with server side rendering when I try to dump the server sent store into redux as it happens at root level of my client code before I reach the page level component that calls the inject reducer.

For instance 'pageASate' is added dynamically into redux using inject reducer. On server I add it dynamically and render the page. Once the page renders on client and the store dump { 'pageAState': '...some data'} is recein=ved from server, I try to initialise redux with same at root level.

const store = configureStore(window.SERVER_STATE)

Since the server state has the ‘pageAState’ which is not part of reducers list sent to redux, it throws below error:

Unexpected key “pageASate” found in preloadedState argument passed to
createStore. Unexpected keys will be ignored.

Hence the store is getting initialised without state of pageA sent by server causing he page to get blank and re-render again once data is fetched again on client. How can it be handled?