Why is my function not working? How to set my object? [closed]

I’m working on online experiment. I created this function to let the participants choose one picture out of two pictures, but it’s not working. Any ideas why?

I’m using jsPsych plugins.

function make_choice_trial(target, foil) {
  var target_path = "img/" + target + ".png";
  var foil_path = "img/" + foil + ".png";
trial = {
    type: jsPsychImageButtonResponse,
    stimulus: target_path, foil_path,
    choices: ['1', '2'],
}

return trial; 

}


var choice_trials_candy = [
  make_choice_trial("candy_cat","Rebecca_rabbit"), ]

  var choice_trials_Rebecca = [
  make_choice_trial("Rebecca_rabbit","candy_cat"),

]

var choice_trials = jsPsych.randomization.repeat(
  [choice_trials_candy, choice_trials_Rebecca],
  [3, 2]
);

Node.JS os.cpus() Reports Wrong CPU Speed on M2 MacBook Air

When I run os.cpus() in node terminal, the returned speed of cpu is 24 which is obviously incorrect. I only met the problem on this exact machine and my other Linux server returns correct numbers, so not really a big deal but very confusing.

My spec is M2 MacBook Air 14" on macOS Sonoma 14.0 and Node.js 18.12.1

Here is the output

> os.cpus()
[
  {
    model: 'Apple M2',
    speed: 24,
    times: {
      user: 210292710,
      nice: 0,
      sys: 106153270,
      idle: 522189360,
      irq: 0
    }
  },
  {
    model: 'Apple M2',
    speed: 24,
    times: {
      user: 203549830,
      nice: 0,
      sys: 98067280,
      idle: 537528550,
      irq: 0
    }
  },
  {
    model: 'Apple M2',
    speed: 24,
    times: {
      user: 191730910,
      nice: 0,
      sys: 90061980,
      idle: 558158070,
      irq: 0
    }
  },
  {
    model: 'Apple M2',
    speed: 24,
    times: {
      user: 179903140,
      nice: 0,
      sys: 82694840,
      idle: 578338150,
      irq: 0
    }
  },
  {
    model: 'Apple M2',
    speed: 24,
    times: {
      user: 133762480,
      nice: 0,
      sys: 27584400,
      idle: 682604710,
      irq: 0
    }
  },
  {
    model: 'Apple M2',
    speed: 24,
    times: {
      user: 113063530,
      nice: 0,
      sys: 19108920,
      idle: 712395620,
      irq: 0
    }
  },
  {
    model: 'Apple M2',
    speed: 24,
    times: { user: 55913160, nice: 0, sys: 11789060, idle: 777338670, irq: 0 }
  },
  {
    model: 'Apple M2',
    speed: 24,
    times: { user: 43927240, nice: 0, sys: 10205050, idle: 791226910, irq: 0 }
  }
]

Cannot Query MongoDB API using HTTP’s requests

i am trying to query the MongoDB API using a API key as the authentication method, but i keep getting the 401 status code.

Here is the code:

fetch(‘https://eu-west-2.aws.data.mongodb-api.com/app/application-0-dhdvm/endpoint/mydatabase’, {
method: ‘GET’,
mode: ‘cors’,
cache: ‘no-cache’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: Bearer ${apiKey}, // Include your API key in the Authorization header
},
})

I generated the API KEY: myAPIkey (I exported the key value before it was created so thats not the problem)

Here is the endpoint i created: EndPoint

Please i need help, somehow i am not able to query the database correctly.

Building a software system for a company to automate its work and calculate expenses and profits

A company transporting goods between the Syrian governorates owns a group of freight vehicles operated by a group of drivers. The company’s trips are documented with a cash or deferred invoice. The company deals with temporary customers with cash invoices and has permanent customers with urgent invoices who enjoy a system of discounts according to the number of trips within the month. There is Expenses paid by the company, such as car maintenance, traffic violations, etc., are documented with bills of exchange. The company wants to build a software system to automate its work and an account for itself, its expenses and its profits, as well as an account for the drivers tool and displaying an account statement for regular customers. What is required is to create a row of deferred invoices immediately after receiving the white paper, in addition to the cash invoice information that contains the fields. The following:

_ Client Name

_Decision

_Full discounts

_And a function to calculate the value of the discount, which includes the value of the fixed discount in addition to the cumulative discount according to the following:

If the number of trips for the customer in this month is two trips, 10% is calculated, or if there are three trips, 15% is discounted, and if it is more than that, 20% is discounted.

I tried to solve it, but I could not because I am a beginner, but I have to solve it

returning empty if the value isn’t edited

So, I am working on an ticket system using Html, Css, JavaScript and Django, and I needed an field that changed depending on another field, after some searching I found a good JavaScript implementation to my case and it worked perfectly on the ticket creation part, but as I was doing the ticket editing part I got stuck with a problem, if there is no changes on the <select> field it simply gets an blank value instead of the value it was previously holding, changing the value works just fine but not changing it doesn’t, I can’t think of a way of preventing this yet and would like to ask if anyone has dealt with an similar problem that could help me.

verticket.html(form part)

<form name="form-ticket" id="formTicket" method="POST" action="{% url 'eticket' ticket.pk %}">
    <div class="col-4 mt-4 m-auto">
        {% if msg %}
            <div class="alert {{class}}">
                {{msg}}
            </div>
        {% endif %}

        {% csrf_token %}
      
        <input class="form-control mt-4" type="text" name="numctt" id="numctt" value="{{ticket.numctt}}" placeholder="{{ticket.numctt}}">
        <input class="form-control mt-4" type="text" name="nomctt" id="nomctt" value="{{ticket.nomctt}}" placeholder="{{ticket.nomctt}}">
        <select required name="areaserv" id="areaserv">
            <option disabled selected hidden>{{ticket.areaserv}}</option>
          </select>
          <select required class="followup" name="tiposerv" id="tiposerv">
            <option disabled selected hidden >{{ticket.tiposerv}}</option>
          </select>
        <input class="form-control mt-4" type="text" name="tickettext" id="tickettext" value="{{ticket.tickettext}}" placeholder="{{ticket.tickettext}}">
        {% block usuario %}
        {% if not request.user.is_staff and ticket.ticketstat == 'Vermelho' %}
        <input class="btn btn-primary mt-4" type="submit" value="Atualizar">
        {% endif %}
        {% endblock %}  
</form>

verticket.html(script part)


const first = document.getElementsByName('areaserv')[0];
const second = document.getElementsByName('tiposerv')[0];
const initial = second.innerHTML;

const optionMap = {
  Informática: ['Visita Técnica'],
  CFTV: ['Instalação', 'Reparo'],
  Alarmes: ['Instalação', 'Reparo'],
  Interfones: ['Instalação', 'Reparo'],
  Telefonia: ['Instalação', 'Reparo'],
};

function addOption(selectElement, text) {
  let option = document.createElement('option');
  option.value = text;
  option.textContent = text;
  selectElement.append(option);
}

Object.keys(optionMap).forEach(text => addOption(first, text));

first.addEventListener('change', evt => {
  second.innerHTML = initial;
  optionMap[evt.target.value].forEach(text => addOption(second, text));
});

views.py

def verticket(request, pk):  
    ticket = Userdb.objects.get(pk = pk)
    context = {'ticket': ticket}
    return render(request,'dashboard/verticket.html', context)

I’ve tried multiple solutions to “fill” the field but the didn’t work, changing the selected to selected=”true” or selected=”{{ticket.areaserv}}” even selected=”selected”, tried giving it an value and it didn’t work too

If any more information is required please feel free to ask.

Which is more effective in wbsite building Html …css or use of PHP? [closed]

I am encountering a problem while deploying my Python Flask app on Heroku. I have followed the Heroku deployment guide, and the app works fine locally. However, when I deploy it to Heroku, I’m getting a 500 Internal Server Error.

I’ve checked the Heroku logs, and it seems like there’s an issue with the database connection. I’m using SQLAlchemy and have configured the database URL correctly in my config.py file. Locally, the app connects to the database without any problems.

Here’s a snippet of the error message from the Heroku logs:

yaml
Copy code
2023-11-27T12:34:56.789012+00:00 app[web.1]: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) could not connect to server: Connection timed out
2023-11-27T12:34:56.789012+00:00 app[web.1]: Is the server running on host “my-database-host” (xxx.xxx.xxx.xxx) and accepting
2023-11-27T12:34:56.789012+00:00 app[web.1]: TCP/IP connections on port 5432?
I’ve double-checked my database credentials, and everything seems correct. Could someone please help me troubleshoot this issue and provide guidance on how to resolve it? Thank you!

Content of website not displayed after display: none; -> display: flex;

I’m in the process of designing a website. I want a couple of containers to be hidden when the page is first loaded which can then be displayed with certain buttons.

I am trying to put this into code the following way:
I put these CSS classes into the section of my website:

<style>
  .hidden-section {
    display: none;
  }

  .visible-section {
    display: flex;
  }
</style>

Then I include the following script:

<script>
    // Function to toggle visibility
    function toggleVisibility() {
      var container = document.getElementById("your-container-id");

      // Toggle the visibility classes
      if (container.classList.contains("hidden-section")) {
        container.classList.remove("hidden-section");
        container.classList.add("visible-section");

        // Trigger a reflow
        void container.offsetWidth;
      } else {
        container.classList.remove("visible-section");
        container.classList.add("hidden-section");
      }
    }

    // Find the button and attach the click event handler
    document.addEventListener("DOMContentLoaded", function() {
      var button = document.querySelector('#myButton');
      button.addEventListener('click', toggleVisibility);
    });
 </script>

While the button to trigger the change of visibility has the CSS ID #myButton and the respective container the CSS ID #your-container-id.
When I have the container to be displayed when the page is initially loaded everything works as expected.

However, when the container get assigned the .hidden-section class upon the initial load, some of the content is not being display. When I resize my browser windows it appears though. So it somehow has to do something with calculating the size of the container.
Can anyone give me further hints how to fix this?

Thanks,
Julius

Delete everything from localForage [closed]

I am using localstorage and localforage (https://localforage.github.io/localForage) to store data for a website. To get a fresh start, I will allow users to delete everything. However, the clear method for localforage does not seem to work. I am able to delete all localstorage data, but not the localforage stores.

Any ideas?

        console.log('clearing local storage');
        localStorage.clear();
        console.log('clearing local forage');
        localforage.clear().then(function () {
          // Run this code once the database has been entirely deleted.
          console.log('Database is now empty.');
        }).catch(function (err) {
          // This code runs if there are any errors
          console.log(err);
        });

Any ideas? Or perhaps alternative routes to delete everything in one go?

How to set free trials with firebase stripe extension

I am wondering if it is currently possible to create free trials with the firebase stripe extension…

 const sessionRef = await addDoc(
        collection(db, "users", user.uid, "checkout_sessions"),
        {
          price: selectedProduct.priceId, // Use the price ID from the selected product
          success_url: `${window.location.origin}/selector/dashboard`,
          cancel_url: `${window.location.origin}/upgrade`,
          allow_promotion_codes: true,
          trial_period_days: 7, // Added the trial period here
          trial_from_plan: true, // added true
        },
      );

I read somewhere you could add the trial period and trial_from_plan – but I’m not finding the ability to actually set a trial period anywhere when I create a product on the stripe site.

Any help is appreciated thanks

How difficult is it? [closed]

I bought a design template, which runs with Tailwind css and js. I would now like to use it in Angular.
The template uses a lot of JavaScripts for the functions, how hard is it to make them usable in Angular? Is that possible or do I need new ones?

I’m not a pro with Angular, that’s why I’m asking.

Regards

How do I maintain the state of a show/hide button and content after executing a search using JavaScript?

In my Ruby on Rails application, I have an index page with Ransack filtering. The Ransack form can be shown or hidden with an onclick event. My current code works fine, but once a search is executed in the form, the button goes back to “Show filters” although the form is already visible. How can I fix this to maintain its state after a search and retain functionality?

Here is the relevant HTML:

<div>
  <p id="filterToggle" style="cursor: pointer;">Show filter</p>
    <div id="filterForm" class="mb-2">
    <%= search_form_for @q do |f| %>
      <%= f.label :name_i_cont, "Filter by name" %>
      <%= f.text_field :name_i_cont, :placeholder => "Enter a few characters" %>
     <div>
       <%= link_to "Clear filters", digs_path(@dig) %>
       <%= f.submit :class => "btn btn-outline-secondary mt-2" %>
     </div>
    <% end %>
  </div>
</div>

And here is my JavaScript function:

document.addEventListener('DOMContentLoaded', function() {
        const filterToggle = document.getElementById('filterToggle')
        const filterForm = document.getElementById('filterForm');

        filterForm.style.display = 'none';

        filterToggle.onclick = function() {
          if (filterForm.style.display !== 'none') {
            filterForm.style.display = 'none';
            filterToggle.innerText = 'Show filter';
          }
          else {
            filterForm.style.display = 'block';
            filterToggle.innerText = 'Hide filter';
          }
        }
      });

Thanks!

Weird output of JavaScript number.toString method

I’m very new with JavaScript and I was trying to play around doing a function that should do some basic validation of phone numbers. I know for a professional result you should use regex but I’m just trying to practice.

While debugging and searching on the internet I understood that number.toString should have radex specified to base 8 in order to return the number in human readeable form (maybe a bad expression but you’ll see what I mean by that). In doing so it removes starting 0s. The problem is that if i replace the 0 with any other digits (i tried 1 & 2) the toString method adds another character which I don’t understand why.

e.g:

var test=1756432173 console.log(test.toString(8).length)

Should give a length of 10 not 11

If i do the below i get a length of 9 which makes sense

var test=0756432173 console.log(test.toString(8).length)

I’m running everything in VSCode using the Code Runner extension in case its relevant

Please help me understand this behavior

issue with a closure, cannot modify the value

I have the following code, after the first setCount I am not able to return the new variable update, what is wrong? thanks

const A = (() => {
  const operateState = <T>(initialValue: T): [T, (value: T) => void] => {
    let _value = initialValue;
    const setState = (newValue: T) => {
      _value = newValue;
    };
    return [_value, setState];
  };
  return {
    operateState,
  };
})();

console.clear()
const [count, setCount] = A.operateState(1);
console.log(count)
setCount(2)
console.log(count) // it should be 2

Adding blur effect to CSS loader

I have integrated a loader feature such that when users click on the submit button, a loader is displayed on the page, indicating that the form submission is in progress. How can I apply a blur effect to the entire page while the loader is active, excluding the loader itself from blurring?

I have tried setting the body to blur, like this:

body.loading {
    filter: blur(5px);
    pointer-events: none; 
}

But it completely hid the spinner causing the entire page to turn into a white background. Here is my code so far:

const myForm = document.getElementById("postForm");

myForm.addEventListener("submit", function(event) {
  event.preventDefault()
  const loader = document.querySelector(".loading");
  loader.classList.add("visible");

  document.body.classList.add("loading");
  document.getElementById("submitbutton").disabled = true;

  setTimeout(() => {
    event.target.submit()
  }, 1000);
})
.loading {
  display: flex;
  justify-content: center;
  visibility: visible;
}

.loading::after {
  content: "";
  width: 50px;
  height: 50px;
  border: 10px solid #dddddd;
  border-top-color: #009579;
  border-radius: 50%;
  animation: loading 1s linear infinite;
  z-index: 1;
}

@keyframes loading {
  to {
    transform: rotate(1turn);
  }
}

.visible {
  visibility: visible;
}
<button id="submitbutton" type="submit">Create
   <div class="loading"></div>
</button>

<form id="postForm"></form>