Change the element after resize

Im building a menu bar and I need to change the shown element after the window resize, approximately when its half of the full size. And also the element must be triggered on hover.

I tried many combination with window.width and also with jquery commands like mouseenter, show etc.

Im puting here example code that I tried to run.

The #thu element is an “a” element in my html code, that is th trigger.

#box is the first element to show

thrist is the second element to show, after window resize.

$( "#thu" ).mouseenter(function(){
        $("#box").show();
    });
    $( "#thu" ).mouseleave(function(){
        $("#box").hide();
    });


    if ($(window).width() < 1000){
        $("#box").css("visibility", "hidden");
        
    }
    if ($(window).width() < 1000){
        $( "#thu" ).mouseenter(function(){
        $(".thrist").show();
    });
    $( "#thu" ).mouseleave(function(){
        $(".thrist").hide();
    });
    }

Thanks for any help.

getting information from a javascript json object

I imagine this has been posted before but I wasn’t able to find a data object specifically like this one. I’m struggling to understand how extract information from this data object in javascript. It’s a parsed URL.

 data =  URL {
  href: 'http://localhost:8080/test.txt?cat=Mouse',
  origin: 'http://localhost:8080',
  protocol: 'http:',
  username: '',
  password: '',
  host: 'localhost:8080',
  hostname: 'localhost',
  port: '8080',
  pathname: '/test.txt',
  search: '?cat=Mouse',
  searchParams: URLSearchParams { 'cat' => 'Mouse' },
  hash: ''
}

I can retrieve the URLsearchParams
data.searchParams, which returns { 'cat' => 'Mouse' }

What is this data structure called: { 'cat' => 'Mouse' }. I’m confused by the =>
And how do I retrieve the two objects ‘cat’ and ‘Mouse’ separately inside this data structure?

For example, retrieving then setting a variable equal to the first item, ‘cat’ and another variable equal to ‘Mouse’

Thank you

How to loop into the array that coming from a filter array?

Question, I have objects that I want to filter to get a specific value, but the problem is I need to map also a specific key to get all the value that need for my filter.

Sample code

arr = [{_id: 1234, name: john, contact: [{landline: 321321}, { mobile: 123131}]}, {_id: 1234, name: jane, contact: [{landline: 5435353}, { mobile: 5435353}]}];

const compare = '321321';

arr.filter((x) => x.contact.map((y) => y.landline) === compare); <--- return empty

Thanks!

Is not doing check for form submit in html and javascript

I am making a function in html that preventsyou from submitting if there is something wrong:

<form id="CreateAccount" action="start.html" method="GET">
<div class="main">
<div class="Title">
<h1>Enter your details.</h1>
</div>
<div class="inputs">
<label for="skool">SchoolName:</label>
<input type="text" id="skool" placeholder ="Put the school name" name="skool"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="username">Username:</label>
<input type="text" id="username" placeholder ="Username" name="username">
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="password">Password</label>
<input type="password" id="password" placeholder =" Password" name="password"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p id="p">Error Message</p>
</div>
<div class="inputs">
<label for="confpassword">Confirm Password</label>
<input type="password" id="confpassword" placeholder =" Confirm Password" name="confpassword"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<div class="inputs">
<label for="email">Email:</label>
<input type="email" id="email" placeholder ="Email" name="email"></input>
<i class="fa-solid fa-circle-xmark"></i>
<i class="fa-solid fa-circle-check"></i>
<p>Error Message</p>
</div>
<button class="submitbtn" type="submit">Submit</button>
</div>
</div>

and javascript:

const formm = document.querySelector('#CreateAccount')
const school = document.querySelector('#skool');
const username = document.querySelector('#username');
const email = document.querySelector('#email');
const pwd = document.querySelector('#password');
const conf = document.querySelector('#confpassword');

formm.addEventListener("submit", (event) => {
    if(isFormValid() == true){
        window.location.assign("start.html");
        console.log(2);
    }
    else{
        event.preventDefault();
        console.log(30);
    }
    validateForm();
    console.log(30);
});


function isFormValid(){
    const inputscontainers = document.querySelectorAll('.inputs')
    let result=true;
    inputscontainers.forEach((container) => {
        if(container.classList.contains("error")){
            return false;
    }})
}
function validateForm(){
    if(username.value.trim() == ''){
        setError(username, 'Name cannot be empty');
    }else if(username.value.trim() < 5){
        setError(username, 'Idrc');
        console.log(3);
    }
    else{
        setSuccess(username);
    }
    if(email.value.trim() == ''){
        setError(email, 'You forgot to fill in your email.');
    }
    else if(isEmailValid(email.value)){
        setSuccess(email);
    }else{
        setError(email, "Provide a valid email");
    }
    if(pwd.value.trim()==''){
        setError(pwd, "Password can't be empty");
    }else if(pwd.value.trim().length<6 || pwd.value.trim().length>20){
        setError(pwd, 'Length must be minimum 6 characters and max 20.');
    }else{
        setSuccess(pwd);
    }
    if(conf.value.trim() == ''){
       setError(conf, 'This is an empty password');
    }else if(conf.value !== pwd.value){
        setError(conf, 'Passwords dont match');
    }
    else{
        setSuccess(conf);
    }
        
        
    
}

function setError(elementr, errorMessage){
    const parents = elementr.parentElement;
    parents.classList.add("error");
    parents.classList.remove("success");
    const paragraph = parents.querySelector('p').textContent = errorMessage;
}

function setSuccess(elementr){
     const parents = elementr.parentElement;
    parents.classList.add("success");
    parents.classList.remove("error");
}
    
function isEmailValid(email){
    const reg =/^(([^<>()[].,;:s@"]+(.[^<>()[].,;:s@"]+)*)|(".+"))@(([^<>()[].,;:s@"]+.)+[^<>()[].,;:s@"]{2,})$/i;
    return reg.test(email);
}

When i click the submit button, It does not check if the code is valid, which really bug me:
LLike it reeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeally does.
My expected outcome is to redirect to another page if it is valid, which doesn happen! Help!

how to use smart wizard with angular

I am trying to use smart-wizard with angular 12 and having a bit of trouble in making it work. Here are the steps that I followed :

  • npm install smartwizard
  • Then imported smart wizard in my component I want to use it in.
import {
  Component,
  OnInit
} from '@angular/core';
import {
  MatDialogRef,
  MAT_DIALOG_DATA
} from '@angular/material/dialog';
import {
  smartWizard
} from 'node_modules/smartwizard';
import * as $ from "jquery";

@Component({
  selector: 'app-start-up-wizard',
  templateUrl: './start-up-wizard.component.html',
  styleUrls: ['./start-up-wizard.component.scss']
})
export class StartUpWizardComponent implements OnInit {

  constructor(public dialogRef: MatDialogRef < StartUpWizardComponent > ) {}

  ngOnInit(): void {
    console.log("reaching here");
    $('#smartwizard').smartWizard();
  }

  onClose(): void {
    this.dialogRef.close();
  }
}
<div id="smartwizard">
  <ul>
    <li><a href="">Step Title 1<br /><small>Step Description 1</small></a></li>
    <li><a href="">Step Title 2<br /><small>Step Description 2</small></a></li>
    <li><a href="">Step Title 3<br /><small>Step Description 3</small></a></li>
    <li><a href="">Step Title 4<br /><small>Step Description 4</small></a></li>
    <li><a href="">Step Title 5<br /><small>Step Description 5</small></a></li>
  </ul>
  <div>
    <div id="step1">
      Step Content 1
    </div>
    <div id="step2">
      Step Content 2
    </div>
    <div id="step3">
      Step Content 3
    </div>
    <div id="step4">
      Step Content 4
    </div>
    <div id="step5">
      Step Content 5
    </div>
  </div>
</div>
<a (click)="onClose()" class="btn btn-dark" style="margin-left: 5px;color:white;">Close</a>

I expected it to work but I am getting an error in console saying that “TypeError: jquery__WEBPACK_IMPORTED_MODULE_0__(…).smartWizard is not a function
at StartUpWizardComponent.ngOnInit” which I dont understand as after npm installing the smart wizard and importing. it should have been available to the component.

Remove spinners from Input where type= Number (Reactjs)

I have an input of type ‘number’ which added spinners to my input. I dont want them there as I have custom buttons for the spinner actions.

 <input
                      className="input"
                      type="number"
                      value={this.state.HD}
                      onBlur={this.changeHD}
                    ></input>

CSS class of input

.input {
  background-color: rgba(255, 255, 255, 0);
  box-shadow: inset 0 1px 0 0 #E6E7EB, inset 0 -1px 0 0 #E6E7EB;
  width: 80px;
  height: 40px;
  color: #999999;
  font-family: 'Roboto';
  font-size: 14px;
  line-height: 16px;
  width: 80px;
  text-align: center;
  padding: 12px;
}

Update asp-route-id with jQuery

I’m building a razor pages application, and I want to use a modal as a partial view.

Foreach loop from where I’m opening the modal:

@foreach (var item in Model.SourceFiles)
                {

                    <tr>
                        <td>@item.Id</td>
                        <td>@item.FileName</td>
                        <td>@item.Created</td>
                        <td>
                            @(item.IsConverted == true ? "Exported" : "Imported")
                        </td>
                        <td>
                            <button type="submit" class="btn btn-primary" asp-page-handler="FileContent" asp-route-fileId="@item.Id">View</button>
                        </td>
                        <td>
                            @if ((await authorizationService.AuthorizeAsync(User, "DeletePolicy")).Succeeded)
                            {
                                <a href="#" class="btn btn-danger" onclick="triggerDeleteModal(@item.Id)">Delete</a>
                            }
                        </td>
                    </tr>
                }

I’m trying to set a new value of an asp-route-id tag using javaScript (jQuery), but I cant get it to work.

function triggerDeleteModal(itemId) {
    $('#' + 'deleteModal').modal('toggle');
    $("#confirmDeleteButton").attr('asp-route-deleteid', itemId)
}

Modal (partial view):

<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalTitle" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteModalTitle">Caution!</h5>
            </div>
            <div class="modal-body">
                <p style="white-space: pre-wrap;">@Model.DeleteModalText</p>
                <p></p>
            </div>
            <div class="modal-footer">
                <button type="submit" id="confirmDeleteButton" class="btn btn-secondary" data-bs-dismiss="modal">Yes</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
            </div>
        </div>
    </div>
</div>

When pressing the yes-button (#confirmDeleteButton) in the modal to submit the form, the id is not getting passed in the asp-route-deleteid tag helper, and the id is always 0 in the OnPost-method.

Code behind where deleteid always is 0:

public async Task<IActionResult> OnPostAsync(int deleteid)
{ 
    //code for deleting stuff
}

When trying to console.log the value of any attribute besides asp-route tags, the value is shown. When trying to log the value of an asp-route tag, the value is undefined.

Any ideas of how I can get the asp-route-deleteid to be passed to the code behind?

BR

Dark & Light system across multiple pages

I wanted to make a dark & light theme system for my website but it is not working correctly.
I made a switch in wich you can toggle dark or light mode.

<input type="checkbox" id="slider">

It was kinda working, but it worked only for the header(header file is added across all pages). I don’t know how I can fix it, I tried to make it via JS but I’m not good at it. I know that it has to be done with localStorage or with cookies, but I don’t understand anything of this.
Can someone help me out?

A-FRAME – The click of my cursor triggers the event of the portal even if it does not point on it

I am doing an a-frame VR project where I need to make “portals” that are useful for the user to move from one room to another. My problem is that I use a cursor for the click event, but it trigger the portal event even if there is a huge gap between the cursor and the portal.

I am using a js.script that you can find here : https://github.com/stemkoski/A-Frame-Examples/blob/master/js/link-controls.js

There is my portal :

<a-link position="0 1.6 -14" rotation="0 0 0"
href="paris.html" title="Paris" image="#photoparis"></a-link>

As for my cursor, I just did a normal cursor inside the a-camera tag.

See there, an example of the gap between cursor and portal.

Can someone help me to understand why there is this problem ? I would like to specify that when I use only the cursor of my mouse there is not this problem and it is necessary that I click precisely on the portal so that the event is activated.

Thanks you in advance for your answers, and don’t hesitate to tell me if there is something that I have poorly explained. Also, pardon me if I have made english mistake.

dygraph y2 axis was never shown

I am build a service based list (php and js/jquery) with dygraphs. I need to show always both y-Scala. At the first hand is to show different values in the same diagram, on the other hand I need the exact same length of the widget. But the y2 Scala was never shown. Does anybody know which restriction makes my configuration useless?

However, I configure the series, with or without different mapping to the one or other Scala, or toggle it. I checked out that the legend is not cut the dygraph canvas.

{
  axes: {
  ​​​  x: {
​​​​      axisLabelWidth: 30,
​​​​      dateWindow: ["2022-02-15T03:57:01.473Z", "2022-02-15T12:57:01.473Z"],
​​​​​      drawAxis: true,
​​​​      pixelsPerLabel: 100
​​​    },
    y: {
​​​​      axisLabelWidth: 40,
​​​​      drawAxis: true,
​​​​      gridLinePattern: [2, 2],
​​​​​      independentTicks: true,
​​​​      pixelsPerLabel: 50,
​​​​      valueFormatter:options_arr.axes.y.valueFormatter(y),
​​​​​      valueRange: [-1, 3],
​​​​​      visibility: true
    },
​​​​    y2: {
​​​​      axisLabelWidth: 40,
​​​​      drawAxis: true,
​​​​      gridLinePattern: [4, 4],
​​​​​      independentTicks: true,
​​​​      pixelsPerLabel: 50,
​​​​      valueFormatter:options_arr.axes.y2.valueFormatter(y2),
​​​​​      valueRange: [-1, 3],
      visibility: true
    },
    ​​​​colors: ["#a1467e", "#000000", "#ff972f", "#ff0000", "#0000c0"],
​​​    connectSeparatedPoints: true,
​​    customBars: true,
​​    disableZoom: true,
​​    height: 300,
​​    labels: ["Time", "B", "Q", "R"],
    labelsDiv: div#archive-legend-7.dygraph-legend,
​​    labelsKMB: true,
​​    labelsSeparateLines: true,
​​    labelsShowZeroValues: true,
​​    legend: "always",
​​    legendFormatter:options_arr.legendFormatter(aData),
​​​    plugins: [ canvas_: canvas, direction_: "both" ],
​​​​    relative: false,
​​    series: {
      "B": {
        axis: "y"
​​​​      },
      "Q": {
​​​​        axis: "y"
      },
      ​​​​"R": {
​​​​        axis: "y"
      }
​​​​    },
    stepPlot: true,
​​    strokeWidth: 2,
​​    title: "B2B",
​​    width: 1200,
​​    xlabel: "Time",
​​    y2label: "SW",
​​    ylabel: "Feedback"
 }
​​​```

If anybody has a clue.

Duplicating cube from a json file based on numerical values

     fetch("./json/TMA-1.json")
      .then( response => { response.json()
    .then( data => { 
        console.log(data);
       if(data.length > 0) {
           var cube = [];

to loop the cube so it will appear next to each other like a graph

           data.forEach((u) => {
            cube[u] = new THREE.BoxGeometry;
            const material = new THREE.MeshBasicMaterial( { color: 0x00ff00, wireframe: false } );
            scene.add(cube[u]);
        }
           )}}
      )
      })

the code above needs to turn json array as a bar graph based on the numerical value fetched

  [ 
  { "Car_Company": "ALFA ROMEO", "YR2018": 535, "YR2019": 456, 
 "YR2020": 444, "YR2021": 446 
 }, 
   { "Car_Company": "ASTON MARTIN", 
  "YR2018": 213, "YR2019": 218, "YR2020": 238, "YR2021": 263
}

Algorithm in appscript to merge intervals determined by a key(Google sheets)

I need a bruteforce algorithm in appscript to merge the intervals into one or more intervals that contain all the ranges for an specific ID.

Example: for ID 11403

{43896,44463} 
{44245,44245}
{44257,44257}
{44258,44258}
{44258,44258}
{44265,44316}
{44271,44271}
{44277,44279}
{44300,44326}
{44363,44363}
{44363,44363}
{44376,44376}
{44265,44316}
{44271,44271}
{44410,44410}
{44537,44537}
{44540,44553}
{44544,44547}

The results must be:

{43896,44410}
{44537,44537}
{44540,44553}

Sheet of use: https://docs.google.com/spreadsheets/d/1UR0xgjCHVxE2Vt0-teSK25f-Kej14Kwfhu5hyhXbDNg/edit?usp=sharing

Returning a file from memory to a view for a user to download C#/js

I want to load a file from a URL into memory in a controller and pass it back to the user in the view

This is what I have

[Route("api/Download")]
[HttpPost]
public async Task<StreamContent> Download([FromBody]string url){
    
    WebRequest request = FtpWebRequest.Create(url);
    using (WebResponse response = request.GetResponse())
    {
        //load file into stream
        Stream responseStream = response.GetResponseStream();
    }
    
    //return file to view
}

This is what the above function is called by;

async downloadAttach(URL: any) {
        window.open(await WebApiManager.post('Download', URL));
    }

However I havent been able to work out how to force it to download on the users side when they click a HTML button

Any help would be appreciated.

What is correct configuration of input parameters for calculating RSI (and ROC)

I have tried to use Technical Indicators library to calculate RSI (and ROC) for candlestick’s closing prices, but when I compare results from Binance, I am not getting quite accurate results:

I fetch data using this Binance API:

This is example of usage for RSI and ROC indicators:

If I do this:

let inputData = {
        values: data, // 15 candlesticks, 1m candlestick data, values[0] is oldest closing price
        period: 14,
      };

and I do calculation:

const results_rsi = RSI.calculate(inputData);

I get single element array, with quite inaccurate result in compare to (realtime) data on Binance.

If I do this:

let inputData = {
        values: data, // 100 candlesticks, 1m candlestick data, values[0] is oldest closing price
        period: 14,
      };

 const results_rsi = RSI.calculate(inputData);

I get a result with a bunch of elements, and if I compare result_rsi‘s last element with Binance RSI 14 (1m) I get actually very accurate result. Also, I have read in one of the git issues that providing more historical data is better.

Now, so far so good… Or at least that is what I thought 🙂 However, both RSI and ROC results were very accurate.

The thing is, when I applied same logic, but with different parameters, say like this:

let inputData = {
        values: data, // 100(or even 200 and 500) candlesticks, 1h candlestick data, values[0] is oldest closing price
        period: 30,
      };

       const results_rsi = RSI.calculate(inputData);
      const results_roc = ROC.calculate(inputData);

and I check last element of results_rsi and results_roc (which I consider that are actual results, but maybe not?), I am still getting quite good results for RSI, but not for ROC I am getting very wrong results. It makes me think if I even use this library correctly, and I am not quite sure if even RSI results are correct, cause I didn’t try it for many different parameters.

So, the questions :

(from docs):

var data = 
[11045.27,11167.32,11008.61,11151.83,10926.77,10868.12,10520.32,10380.43,10785.14,10748.26,10896.91,10782.95,10620.16,10625.83,10510.95,10444.37,10068.01,10193.39,10066.57,10043.75];

var period = 12;
        
var expectResult = [-3.85,-4.85,-4.52,-6.34,-7.86,-6.21,-4.31,-3.24];
    
ROC.calculate({period : period, values : data});
  1. What is the actual result of ROC here? Cause the array is returned.
  2. How input values should be sorted? (what should be the values[0])?
  3. Where am I wrong? 😀