How do I embed Github skyline in dark mode?

I’ve successfully added a github skyline into an iFrame on my site. However, it is not dark mode as specified in the url, and when it attempts to load the dark mode, three.js warnings are being thrown to the console.

I’ve been following this repo.

Here is how I load it into the iFrame:

App.svelte

And here is what it looks like loaded:

site loaded

Finally, here is what I expected:
expectation

I did manage to check the url I was passing into the iFrame using a normal browser tab, and it still produces the same error. Link.

How do I begin to fix this?

How can I create a keyboard shortcut to execute a button on a webpage that uses javascript?

I daily use a webpage that has a button that I have to “manually” press everytime.

So I was wondering if there is a way to create a keyboard shortcut for that button, using its javascript url destination (in this case javascript:void(‘Iniciar/Detener Dictado’).

I use Chrome as my browser.
Thanks in advance!

This is the picture of the URL: When I put my mouse over the button, the destination url is javascript:void(‘Iniciar/Detener Dictado’)

Where can i find the code “behind the hood” of JS array methods?

I would like to know how array methods are built-in (the source code), for example this prototype todos() is how i imagine the every() method works behind the scenes, i would like to find that documentation, thanks in advance.

Array.prototype.todos = function(fn) {
    for(let item of this) {
        if(!fn(item)) {
            return false
        }
    }
    return true
}

const result = [1, 2, 3].todos(x => x < 10)
console.log(result)

How to get Javascript click event, for modal popup activate, before allowing user to upload a picture attachment

I wish to have the user prompted by modal before uploading picture, how can I prevent the input from being activated at same time as my modal and instead have the input triggered upon closing my displayed modal?

const modal = document.querySelector('.modal');
const openModal = document.querySelector('.open-button');
const closeModal = document.querySelector('.close-button');

openModal.addEventListener('click', () => {

     
   
    modal.showModal();

})


closeModal.addEventListener('click', () => {
    modal.close();

})
<input class="open-button" type="file" 
       accept="image/png, image/jpeg" >
        <button>Send</button>
      </form>
    </div>
  </div>
</div>
</div>
<dialog class="modal" id="modal">
<h2>Hello</h2>
<p>This is a modal</p>
<button class="button close-button">Proceed</button>
  </dialog>

 <footer>

Datatables CRUD operations

I am developing a tasking application that tracks tasks with various metadata for the tasks. When the task is created, the options are saved to a related list. However, the metadata tags may change as the task progresses. I am using DataTables to display the options. The below code loads in the full list of options, then the selected entries, and combines into an array to track changes. As buttons are pressed for primary or secondary, the array is updated for the appropriate action to the item, i.e. if it’s new, flag for create. If it has a list ID number, flag for update, and lastly mark any that have a listID but are not selected for delete. My prototype is working but I do not think I did it in an efficient manner and I am concerned that it will not scale well if I add a 3rd button for tertiary selection. The nested if statement are already getting crazy.

Right now, it is intended that selecting a new primary will clear out any existing secondary selections.

let fullList = [
    {id: "12",title: "A",code:"110"},
    {id: "23",title: "B",code:"120"},
    {id: "13",title: "C",code:"130"},
    {id: "43",title: "D",code:"140"},
    {id: "52",title: "E",code:"150"},
]

let selectList = [
    {listID: "488",id:"23",code:"120",weight:"Primary"},
    {listID: "234",id:"43",code:"140",weight:"Secondary"}
]

let workingList = [];

for (i = 0; i < fullList.length; i++) {
    workingList.push({'rowId':i,'id':fullList[i].id,'title':fullList[i].title,'code':fullList[i].code,'listID':'','weight':'','operation':''});
};

for (var i=0;i<workingList.length;i++) {
    for (var j=0;j<selectList.length;j++) {
        if(workingList[i].code == selectList[j].code) {
            workingList[i].operation = 'Read';
            workingList[i].listID = selectList[j].listID;
            workingList[i].weight = selectList[j].weight;
        }
    }
}

$(document).ready(function() {
    var table = $('#myTable').DataTable({
        processing: true,
        data: workingList,
        rowId: 'rowId',
        columnDefs: [
        {
            orderable: false
        },
    ],
    columns: [
            { data: 'title' },
            { data: 'code' },
            { data: 'weight'},
            { data: 'operation' },
            { data: 'listID' },
            {defaultContent: '<button class="btn-primary bg-primary">Primary</button>'},
            {defaultContent: '<button class="btn-secondary bg-secondary">Secondary</button>'},
        ],
        "rowCallback": function (row, data) {
            if (data.weight == "Primary") {
                $('td',row).eq(2).addClass('selected');
            }
          }
    }); 

    $('#myTable tbody').on('click', 'button.btn-primary', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        var id = row.data().rowId;
        if ($(this).eq(2).hasClass('selected')) {
            $(this).eq(2).removeClass('selected');
            workingList[id].weight = '';
            if (workingList[id].operation == 'Read' || workingList[id].operation == 'Update') {
                workingList[id].operation = "Delete";
            }
            else {workingList[id].operation = ""};
        } else {
            table.$('tr.selected').removeClass('selected');
            $(this).eq(2).addClass('selected');
            workingList[id].weight = 'Primary';
            for (i = 0; i < workingList.length; i++) {
                if (i != id) {
                    workingList[i].weight = "";
                    if (workingList[i].listID != "") {
                        workingList[i].operation = "Delete";
                    }
                    else if (workingList[i].operation == "Create") {
                        workingList[i].operation = "";
                    }
                }
            }
            if (workingList[id].listID == '') {
                workingList[id].operation = "Create";
            }
            else {workingList[id].operation = "Update"};
        }

        table.clear().draw();
        table.rows.add(workingList); // Add new data
        table.columns.adjust().draw(); // Redraw the DataTable
        console.log(workingList[id]);
    });

    $('#myTable tbody').on('click', 'button.btn-secondary', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        var id = row.data().rowId;
        if ($(this).eq(2).hasClass('selected')) {
            $(this).eq(2).removeClass('selected');
            workingList[id].weight = '';
            if (workingList[id].operation == 'Read' || workingList[id].operation == 'Update') {
                workingList[id].operation = "Delete";
            }
            else {workingList[id].operation = ""};
        } else {
            table.$('tr.selected').removeClass('selected');
            $(this).eq(2).addClass('selected');
            workingList[id].weight = 'Secondary';
            for (i = 0; i < workingList.length; i++) {
                if (i != id){
                    if (workingList[i].weight != 'Primary') {
                    workingList[i].weight = "";
                    };
                    if (workingList[i].listID != "") {
                        if (workingList[i].weight != 'Primary') {
                        workingList[i].operation = "Delete";
                        }
                    }
                    else if (workingList[i].operation == "Create") {
                        if (workingList[i].weight != 'Primary') {
                            workingList[i].operation = "";
                        }
                    }
                }
            }
            if (workingList[id].listID == '') {
                workingList[id].operation = "Create";
            }
            else {workingList[id].operation = "Update"};
        }

        table.clear().draw();
        table.rows.add(workingList); // Add new data
        table.columns.adjust().draw(); // Redraw the DataTable
        console.log(workingList[id]);
    });
})

http://live.datatables.net/salohoro/1/ is a working copy as well.
Any advice on efficiency and scalability would be appreciated. I was also having issues with the selected class not displaying for secondary.

Group objects from an array of objects based on two or more keys and from an array of dynamically collected values

I need to group objects based on two or more filters on known keys from the values of the dataset.

I believe filtering is the best approach but all of my attempts have failed.

var uniqueKeys = ['course','gradDate'];

var dataSet = [
  {
    lastName:'Jones',
    course:'Standards',
    gradDate:'12/12/2022'
  },
{    
    lastName:'Smith',
    course:'Standards',
    gradDate:'12/12/2022'
  },
{
    lastName:'Martinez',
    course:'Maths',
    gradDate:'12/12/2022'
  },
{
    lastName:'Santiago',
    course:'Photography',
    gradDate:'12/11/2022'
  },
{
    lastName:'Alexi',
    course:'Photography',
    gradDate:'12/11/2022'
  }
]

function returnUniqueValues(array,key){
    return UniqueValue = [...new Set(array.map(item => item[key]))]
}

var uniqueCourses = returnUniqueValues(dataSet,'course') 
//result for this dataset === ["Standards","Maths","Photography"];
var uniqueGradDates = returnUniqueValues(dataSet,'gradDate') 
//Result for this dataset === ["12/12/2022","12/11/2022"];

From here I have two arrays of unique values that I need to group objects from the source dataset (dataSet)

I apologize if I am not describing this correctly, hopefully the example of the expected output will clear it up.

For all steps, if nothing matches the double filter, nothing should return.
Example step through at least with how I have been approaching this problem, follows:

The first step would filter dataSet for all objects that have a course === “Standards” and a gradDate === “12/12/2022”. Here I would would get two objects back. I would then pass that to a new array for reference later.

Second step would filter the source dataset, dataSet for any object that has course === “Standards” and gradDate === “12/11/2022”.

Third step would filter dataSet for all objects where the course === “Maths” and gradDate === “12/12/2022”

Example output for this dataset would by

var finalData = [
    [{
            lastName: 'Jones',
            course: 'Standards',
            gradDate: '12/12/2022'
        },
        {
            lastName: 'Smith',
            course: 'Standards',
            gradDate: '12/12/2022'
        },
    ],
    [{
        lastName: 'Martinez',
        course: 'Maths',
        gradDate: '12/12/2022'
    }],
    [{
            lastName: 'Santiago',
            course: 'Photography',
            gradDate: '12/11/2022'
        },
        {
            lastName: 'Alexi',
            course: 'Photography',
            gradDate: '12/11/2022'
        }
    ]
]

End goal is to then loop through each group (in this case of anybody with the same course and gradDate pairs) and populate a report with their information like lastname. In this example there are 3 unique combinations of course and gradDate that actually exist. Scaling, I full expect thousands of different courses with up to 4 different dates possible.

JavaScript Advanced Syntax – I don’t understand

So I recently copied this code from the internet to format strings inline:

module.exports=function(){
    String.prototype.FormatPlus = String.prototype.FormatPlus || function(){
        "use strict";
        let str = this.toString();
        if (arguments.length) {
            let t = typeof arguments[0];
            let key;
            let args = ("string" === t || "number" === t) ? Array.prototype.slice.call(arguments) : arguments[0];
            
            for (key in args) {
                str = str.replace(new RegExp("\{" + key + "\}", "gi"), args[key]);
            }
            
            return str;
        }
    }
}

I understand most of it, except this part:

let args = ("string" === t || "number" === t) ? Array.prototype.slice.call(arguments) : arguments[0];

Is there any professional JavaScript Node.js programmers that can break-down every bit of this line please? Thank you.

Alguem pode me ajudar em linguagem c? [closed]

boa noite.
A questao parece ser simples, mas como nao sou programador c peço ajuda aos colegas. Poderiam me ajudar com a questao baixo?

  • Leia 2 matrizes 3×2 de números inteiros.
  • Organize os números em ordem crescente.
  • Crie uma matriz 3×4 com os números ordenados anteriormente.

Materia da faculdade mas o professor e um lixo e no achei nada no youtube…

Poderiam me ajudar a resolver? muito obrigado

CSS gradients and -webkit-background-clip not allowing a transition

.nav-content a {
    color: #000;
    text-decoration: none;
    font-size: 1.1em;
    padding: 20px 40px 20px 40px;
    background-image: linear-gradient(90deg, #000, #000);
    -webkit-background-clip: text;
    font-family: 'Raleway', sans-serif;
    transition: .4s ease-in-out;
}
.nav-content a:hover {
    background-image: linear-gradient(90deg, #6E1D16, #E4DA1E, #D5347D, #15DAE7,#6E1D16, #E4DA1E, #D5347D, #15DAE7);
    -webkit-background-clip: text;
    color: rgba(0,0,0,.1);
    cursor: pointer;
}
<nav class="nav-content">

  <a>Home</a>
  <a>Contact</a>
  <a>About</a>
  
</nav>

So I am trying to get my “navbar” to do a transition-out, but it will only transition-in. I know that gradient transitions are not supported, but does anyone know how to do this? I am fine with a work around too.

How to filter array in vue js and get true/false?

I am to do an app with Vue.js but can not filter data in order to get whether author has posted a publication or not.

Imagine that we have an array (code below):

I need a function which returns False if author = x does exist in the array and True if not.

I wrote a method but it doesn’t work this way (tried console.log but nothing returned):

export default {
    name: 'Post',
    data () {
      return {
user: 15,
offers: [
    {
        "id": 3,
        "author": 20
    },
    {
        "id": 4,
        "author": 14
    }
]
}
},
methods: {

  postedPermission() {
        for (var offer in this.offers) {
          if (offer.author == this.user) {
            return false;
          }
          else return true;
        } 
      },

},

beforeMount() {
   this.postedPermission()
}

}

Django & AJAX combined

I’m trying to submit a simple form in Django that will contain an image to process it on server and get a response without refreshing the page. I look up for some tutorials how to use AJAX and jQuery to do this but I don’t have much knowledge at this matter. I’m completly stuck and have no idea what shall I do next. So far my code looks like this:

models.py

class Snip(models.Model):
    #some fields
    snip = models.FileField(upload_to="snips/")
    latex = models.TextField(default = '')

forms.py

from .models import Snip
from django import forms


class SnipForm(forms.ModelForm):
    class Meta:
        model = Snip
        fields = ['snip']

HTML:

<form id="snipForm" method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="...">
<div class="row align-items-center">
<div class="col-12">
<label for="id_snip">Snip:</label>
<input type="file" name="snip" required="" id="id_snip" class="btn-success p-2 rounded">
<input type="submit" name="upload" id="upload" class="btn btn-secondary">
</div>
</div>
</form>

JavaScript/AJAX

var snip = document.getElementById("id_snip");
var upload_btn = document.getElementById("upload")
upload_btn.addEventListener('click', function () {
var form_data = new FormData();
var ins = document.getElementById('snip_file').files.length;

if(ins == 0) {
    return console.log("No snip!!!")
         }
  form_data.append("file[]", snip.files[0]);
  csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
  form_data.append("csrfmiddlewaretoken", csrf_token);
  $.ajax({
    url: "{% url 'generate' %}", 
    dataType: 'json', 
    cache: false,
    contentType: false,
    processData: false,
    //data: {'data': form_data, 'csrfmiddlewaretoken': csrf_token},
    data: form_data,
    type: 'post',
    success: function (response) { 
      // change some content on the page
    },
    error: function (response) {
      console.log("error")
    }
  });
});

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from .models import Snip
from .forms import SnipForm
from django.http import JsonResponse
from django.core import serializers

def generate(request):
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
    if is_ajax and request.method == "POST":
        file = request.FILES['snip']
        processed_image = "Some text from OCR"
        return JsonResponse({'text':'Yay, I got text from OCR'})

    if request.method == 'GET':
        Users = User.objects.all()
        form = SnipForm()
        user_list = []
        for user in Users:
            if user.get_full_name():
                user_list.append(user.get_full_name())
        return render(request, "new.html", {'Users': user_list,     'form': form})

To sum up:
The image is loaded to id_snip input tag. After clicking on id="upload" button it should be sent to django server and then to outer OCR API to receive some text back. Then it’s supposed to be displayed on the front end without refreshing the page. However after clicking submit I get error:

The view docs.views.generate didn't return an HttpResponse object. It returned None instead.

My first thought was to check the is_ajax value. It occured to be false. So my question is:

  1. How can I check if the request “is AJAX”? I know in previous versions of django it was is_ajax() method but since some like 3.1 version is not recommended
  2. Is there any simple way to do it? My goal is to put received response (text) somewhere else on the page.

Thank you in advance 🙂

extracting parameters with matches [duplicate]

trying to match the strings within each []

was thinking

let str = '[one] [two] [three] [four]'
let matches = str.match(/[(w+)]/g)
console.log(matches)

but it returns strings including the []

0: "[one]"
1: "[two]"
2: "[three]"
3: "[four]"

whats the right regex for this 🙂

Created a POST request for a conversation list in mongoDB. How to avoid POST request from creating duplicate documents?

I am creating an application that connects volunteers to newcomers using ReactJS. In the app I have developed a chat mechanism that will help newcomers connect with volunteers and vice-versa. I have implemented a feature that displays the featured volunteers with their info and a button that says ‘contact’. I have hooked up the contact button so that when pressed the user gets directed to the chat and a new conversation list document is created in MongoDB using the POST request.

The problem I am running into is that the POST request keeps on running every time I click the ‘contact’ button resulting in multiple duplicates of the username getting rendered. I am struggling with finding a solution to the problem. I would like only one username to get rendered to the page and not have a whole bunch of duplicates. Any help is greatly appreciated.

The GET method that grabs the email and POST method that creates a new document

```
**VolunterCard.jsx**
React.useEffect(() => {
  const getImage = async () => {
    let response = await fetch(`/image/[email protected]`);
    let data = await response.json();
    console.log(`Data is:`, data);
    setVolunteer(data);
  };
  getImage();
}, []);


const createConversation = async () => {
  const newConversation = {
    members: {
      senderEmail: user.email,
      recieverEmail: volunteer.email
    },
  };

  const data = JSON.stringify(newConversation)
  await fetch("/conversation", {
    method: "POST",
    headers: {
      "Content-type": "application/json",
    },
    body: data,
  })
};```
**Conversation.jsx (Where the user gets rendered)**
useEffect(() => {
  const chatMembers = conversation.members.find(
    (member) => member !== currentUser.email
  );

  const getUsersFirstName = async () => {
    try {
      const response = await axios.get("/name?email=" + chatMembers);
      setUser(response.data);
    } catch (err) {
      console.log(err.message);
    }
  };
  getUsersFirstName();
}, [currentUser, conversation, isLoading]);

if (isLoading) {
  return <div>isLoading...</div>;
}

return (
  <div style={{cursor: 'pointer'}}>
    {user.firstName} {user.lastName} - {user.email}
  </div>
);
};```



  **converstionModel.js**
```const mongoose = require("mongoose")

const conversationSchema = new mongoose.Schema({
  members: {
      type: Array,   
  }
}, { timestamps: true});


const conversationModel = mongoose.model("Members", conversationSchema);

const createMembers = async (members) => {
  const newMembers = await conversationModel.create(members);
  return newMembers
};```