Plot the numerical solution of the differential equation for 0 ≤ t ≤ 50: x 00 + 0.15x 0 − x + x 3 = 0.3 cost , x(0) = −1 , x 0 (0) = 1

What am I doing wrong here ???

In(195):= DSolve({x''(t) + 0.15 x'(t) - x(t) + x(t)^3 == 0.3 Cos(t), x(0) == -1,x'(0) == 0}, x(t), t)
Out(195)= DSolve({-x(t) + x(t)^3 + 0.15 Derivative(1)(x)(t) + (x^(Prime)(Prime))(t) == 0.3 Cos(t),x(0) == -1, Derivative(1)(x)(0) == 0}, x(t), t)

Linear Programming Problems with decimal solutions for problems requiring whole number solution

I have an LPP which asks for the maximum number of pairs of shoes that can be manufactured to maximize the profit. The LPP is:


Maximize Z=1350x + 975y
Subject to, 3x+1.5y≤275
     2.5x+2y≤300
     x, y≥0

The solution I obtained is x=44.45; y=94.44
Now, since x and y can only be positive integers, what will the final solution be? I’m confused about this step. Any help is welcome :-]

differential equations – Series solution of an ODE with nonpolynomial coefficients

Basically, I have a second-order differential equation for g(y) (given below as odey) and I want to obtain a series solution at $y=infty$ where g(y) should vanish. That would be easy if the ODE contains polynomial coefficients, hence the Frobenius method can used. But in my case, the coefficients are not polynomial because of the presence of powers proportional to p (can take positive non-integer values). I have also expanded ir at infinity and have taken up to first order (given by irInf) since if I directly use ir, then it would be a mess later for the ODE.

ir(y_) := (Sqrt)(-5 + y^2 + (3 2^(1/3))/(2 + 10 y^2 - y^4 + Sqrt(64 y^2 + 48 y^4 + 12 y^6 + y^8))^(1/3) - (6 2^(1/3)y^2)/(2 + 10 y^2 - y^4 + Sqrt(64 y^2 + 48 y^4 + 12 y^6 + y^8))^(1/3) + (3 (2 + 10 y^2 - y^4 + Sqrt(64 y^2 + 48 y^4 + 12 y^6 + y^8))^(1/3))/2^(1/3))
dir(y_) := D(ir(x), x) /. x -> y
irInf(y_) = Series(ir(y), {y, (Infinity), 1}) // Normal

p=1/10; (*p>=0*)
odey = (2 irInf(y) - p irInf(y)^(1 - p)) D(irInf(y), y) g'(y) + irInf(y)^2 g''(y) - l (l + 1) g(y) // Simplify

What steps can I take to solve this? Thanks

differential equations – Series solution of an ODE with nonpolynomial coefficients

Basically, I have a second-order differential equation for g(y) (given below as odey) and I want to obtain a series solution at $y=infty$ where g(y) should vanish. That would be easy if the ODE contains polynomial coefficients, hence the Frobenius method can used. But in my case, the coefficients are not polynomial because of the presence of powers proportional to p (can take positive non-integer values). I have also expanded ir at infinity and have taken up to first order (given by irInf) since if I directly use ir, then it would be a mess later for the ODE.

ir(y_) := (Sqrt)(-5 + y^2 + (3 2^(1/3))/(2 + 10 y^2 - y^4 + Sqrt(64 y^2 + 48 y^4 + 12 y^6 + y^8))^(1/3) - (6 2^(1/3)y^2)/(2 + 10 y^2 - y^4 + Sqrt(64 y^2 + 48 y^4 + 12 y^6 + y^8))^(1/3) + (3 (2 + 10 y^2 - y^4 + Sqrt(64 y^2 + 48 y^4 + 12 y^6 + y^8))^(1/3))/2^(1/3))
dir(y_) := D(ir(x), x) /. x -> y
irInf(y_) = Series(ir(y), {y, (Infinity), 1}) // Normal

p=1/10; (*p>=0*)
odey = (2 irInf(y) - p irInf(y)^(1 - p)) D(irInf(y), y) g'(y) + irInf(y)^2 g''(y) - l (l + 1) g(y) // Simplify

What steps can I take to solve this? Thanks

Solution to Javascript coding assignment that did not get me to the interview stage

I recently completed a coding challenge for a company that did not get me to the next stage.
They were kind enough to provide the following feedback:

The coding assignment does not match what we are looking for, a mid-level Front End Engineer.
The code does not fully comply with what is asked in the assignment and the code readability is sometimes hard.

I have no problems with these criticisms as I am still in my first year as a professional developer.
However, I am really curious as to how a mid-level engineer would approach the problem. Any advice on how improve readability would also be greatly appreciated (it’s a mess in some spots I know…). I am not sure which sections they are referring to that do not comply with what is asked in the assignment.

I will list both the code and the requirements below.

Requirements

  1. When index.html is opened in the browser, the content of constant USERS in json/data.js will appear as a table on the browser. Table column order should be the same as the order already written in index.html.
    • Name is the last name and the first name, respectively, separated by a space.
  2. When button#start is clicked, table rows will randomly rearrange every second.
  3. The process in 2 can be stopped when button#stop is clicked.
  4. When user name very long (left to your own appreciation), an ellipsis is shown.
  5. When button#sort is clicked, rows will be sorted by balance in descending order. If two or more balances are the same, rows will be sorted in ascending id order.
  6. When the process in 2-3 is running, disable button#sort.

Additional Notes

  • Please write your code so as to avoid triggering unnecessary reflows and repaints.

… and here is the code:

JS

class App {
    constructor(props) {
        this.startRandomBtn = document.getElementById('start');
        this.stopRandomBtn = document.getElementById('stop');
        this.sortTableBtn = document.getElementById('sort');
        this.table  = document.querySelector('.table');
        this.data = props.users;
        this.active;
        this.init();
    }

    sortTable() {
        let switching, shouldSwitch, rows, i
        switching = true

        while (switching) {
            switching = false;
            rows = this.table.rows;

            for (i = 1; i < (rows.length - 1); i++) {
              shouldSwitch = false;
              let balanceX = rows(i).querySelector('.balance').textContent
              let balanceY = rows(i + 1).querySelector('.balance').textContent;
              let idX = rows(i).getAttribute('data-id')
              let idY = rows(i + 1).getAttribute('data-id')

              if (parseInt(balanceX) === parseInt(balanceY)) {
                if (parseInt(idX) < parseInt(idY)) {
                    shouldSwitch = true;
                    break;
                }
              }

              if (parseInt(balanceX) < parseInt(balanceY)) {
                shouldSwitch = true;
                break;
              }
            }
            if (shouldSwitch) {
                rows(i).parentNode.insertBefore(rows(i + 1), rows(i));
                switching = true;
              }
        }
    }

    setTable() {
        this.data.forEach(item => {

            let trNode = document.createElement('tr');

            for (const key in item) {
                if (key === "id") {
                    trNode.setAttribute('data-id', item(key))
                }
                else if (key === "name") {
                    let tdNode = document.createElement('td');
                    let firstName = item(key).first
                    let lastName = item(key).last

                    if (lastName.length > 11) {
                        lastName = lastName.slice(0,11).concat("...");
                    }

                    tdNode.textContent = `${lastName}, ${firstName}`
                    trNode.appendChild(tdNode)
                } 
                else if (key === "pictureUrl") {
                    let img = document.createElement('img')
                    img.src = `${item(key)}`

                    trNode.appendChild(img)
                }
                
                else {
                    let tdNode = document.createElement('td');
                    tdNode.textContent = `${item(key)}`
                    if (key === "accountBalance") {
                        tdNode.classList.add("balance")
                    }

                    trNode.appendChild(tdNode)
                }
              }
              this.table.appendChild(trNode)     
        })
    }

    stopRandomize () {
        clearInterval(this.active);
        this.sortTableBtn.classList.remove("disabled");
        this.sortTableBtn.style.pointerEvents = "auto";
    }

    randomizeArray() {

        // Disable sort button while list is being randomized
        this.sortTableBtn.classList.add("disabled");
        this.sortTableBtn.style.pointerEvents = "none";

        this.active = setInterval(() => {
            let rowsCollection = document.querySelectorAll('tr');
            let rows = Array.from(rowsCollection).slice(1);

            for (let i = rows.length - 1; i > 0; i--) {
                let j = Math.floor(Math.random() * (i + 1));
                let temp = rows(i);
                rows(i) = rows(j);
                rows(j) = temp;
            }

            for (const row of rows) {
                this.table.appendChild(row);
            }
        }, 1000)
    }

    init() {
        // Set up event listeners
        this.startRandomBtn.addEventListener('click', () => this.randomizeArray());
        this.stopRandomBtn.addEventListener('click', () => this.stopRandomize());
        this.sortTableBtn.addEventListener('click', () => this.sortTable());

        // Initialize Table
        this.setTable();
    }
}

new App({
    users: USERS 
});

HTML

<form role="form">
        <div class="form-group mb-5 d-flex justify-content-center">
          <button id="start" type="button" class="btn btn-success mx-3">start random</button>
          <button id="stop" type="button" class="btn btn-success mx-3">stop random</button>
          <button id="sort" type="button" class="btn btn-success mx-3">sort</button>
        </div>
      </form>

      <div class="contents">
        <table class="table ">
          <thead>
            <tr>
              <th scope="col">Name</th>
              <th scope="col">Email</th>
              <th scope="col">Phone</th>
              <th scope="col">Picture</th>
              <th scope="col">Balance</th>
            </tr>
          </thead>
          <tbody>
          </tbody>
        </table>
      </div>

I will include the json data as well, in case its of interest

const USERS = (
  {
    "id": "5",
    "name": {
      "title": "Mr",
      "first": "Pitágoras",
      "last": "Fogaça"
    },
    "email": "pitagoras.fogaca@example.com",
    "phone": "(77) 7242-0589",
    "pictureUrl": "image/1.jpg",
    "accountBalance": 100
  },
  {
    "id": "7",
    "name": {
      "title": "Miss",
      "first": "Maddison",
      "last": "Mitchell"
    },
    "email": "maddison.mitchell@example.com",
    "phone": "051-630-3570",
    "pictureUrl": "image/2.jpg",
    "accountBalance": 150
  },
  {
    "id": "2",
    "name": {
      "title": "Mr",
      "first": "Landon",
      "last": "Caldwell"
    },
    "email": "landon.caldwell@example.com",
    "phone": "(481)-936-9008",
    "pictureUrl": "image/3.jpg",
    "accountBalance": 120
  },
  {
    "id": "9",
    "name": {
      "title": "Mr",
      "first": "Lee",
      "last": "Chapman"
    },
    "email": "shyn.sdr@example.com",
    "phone": "063-85445367",
    "pictureUrl": "image/4.jpg",
    "accountBalance": 110
  },
  {
    "id": "10",
    "name": {
      "title": "Mr",
      "first": "Lewis",
      "last": "Overgoor"
    },
    "email": "lewis.overgoor@example.com",
    "phone": "(835)-339-5805",
    "pictureUrl": "image/5.jpg",
    "accountBalance": 80
  },
  {
    "id": "1",
    "name": {
      "title": "Ms",
      "first": "Venla",
      "last": "Korpi"
    },
    "email": "venla.korpi@example.com",
    "phone": "06-156-153",
    "pictureUrl": "image/6.jpg",
    "accountBalance": 190
  },
  {
    "id": "3",
    "name": {
      "title": "Mr",
      "first": "Hubert Blaine",
      "last": "Wolfeschlegelsteinhausenbergerdorff"
    },
    "email": "hubert-blaine.wolf@example.com",
    "phone": "003-16911265",
    "pictureUrl": "image/7.jpg",
    "accountBalance": 100
  },
  {
    "id": "8",
    "name": {
      "title": "Miss",
      "first": "Maria",
      "last": "Christensen"
    },
    "email": "maria.christensen@example.com",
    "phone": "87931526",
    "pictureUrl": "image/8.jpg",
    "accountBalance": 190
  },
  {
    "id": "4",
    "name": {
      "title": "Mr",
      "first": "Philip",
      "last": "Brown"
    },
    "email": "philip.brown@example.com",
    "phone": "<img onerror='window.document.body.innerHTML = "<h1>XSS</h1>";' src="https://codereview.stackexchange.com/"> ",
    "pictureUrl": "image/9.jpg",
    "accountBalance": 120
  },
  {
    "id": "6",
    "name": {
      "title": "Mr",
      "first": "Viljami",
      "last": "Wallo"
    },
    "email": "viljami.wallo@example.com",
    "phone": "06-616-693",
    "pictureUrl": "image/10.jpg",
    "accountBalance": 95
  }
);

Thank you for taking the time to look!

ordinary differential equations – General solution of a system of ODEs where $A – lambda I = 0$, for a given $lambda$ of $A$.

I have the following system of ODEs

$$
begin{cases}
x’ = -ax \
y’ = -ay \
end{cases}
implies
begin{bmatrix}
x’ \ y’
end{bmatrix}
=
begin{bmatrix}
-a & 0 \
0 & -a
end{bmatrix}
begin{bmatrix}
x \ y
end{bmatrix}
$$

its eigenvalue $lambda = -a$, and substituting it to $(A – lambda I)mathbf{k} = mathbf{0}$:

$$ (A – lambda I)k =
begin{bmatrix}
-a – (-a) & 0 \
0 & -a – (-a)
end{bmatrix}
begin{bmatrix}
k_1 \ k_2
end{bmatrix}
=
begin{bmatrix}
0 & 0 \
0 & 0
end{bmatrix}
begin{bmatrix}
k_1 \ k_2
end{bmatrix}
=
begin{bmatrix}
0 \ 0
end{bmatrix} ,
$$

which implies that all vectors in $mathbb{R}^2 (neq mathbf{0})$ is an eigenvector of $lambda = -a$.

How do I write its homogeneous solution? Is it just $mathbf{v} = mathbf{k}e^{-at}$, where $mathbf{k}$ is any vector in $mathbb{R}^2$? But I believe there must be more terms since $lambda$ is a repeated eigenvalue but I do not know what it could be.

Redirect users from admin pages the optimal solution

On two different sites I use two somewhat different solutions. Are they different in terms of security and performance? Which is better? Are there even better ones?

Solution 1.

/** Redirect users from admin pages if not administrators **/
add_action( 'admin_init', function() {
    if( ! current_user_can( 'manage_options' ) && ( ! wp_doing_ajax() ) ) {
        wp_safe_redirect( site_url() );
        exit;
    }
} );

Solution 2.

/** Redirect users from admin pages if not administrators **/
add_action( 'admin_init', function() {
    if( ! in_array( 'administrator', wp_get_current_user()->roles ) ) {
        wp_redirect( get_bloginfo( 'wpurl' ) );
        exit;
    }
} );

combinatorial optimization – Relation of optimal solution of the directed vertex-disjoint 3-cycle cover to a relaxed version

let $G(V,E)$ be a complete graph with $nltinfty$ vertices that has an associated asymmetric cost-matrix $Omegainmathbb{R}^{ntimes n}, OmeganeOmega^T$ whose elements $omega_{ij}gt0$ determine the weights of the corresponding directed edges $e_{ij}in E$.

$3DCC_{mathrm{opt}}$ denotes the lightest vertex-disjoint cycle cover of $(G,Omega)$ in which every cycle covers at least three vertices.

let
$H_{mathrm{opt}}(V,F)subset G(V,E),\quad e_{ij}in Fimplies e_{ji}notin F\quad operatorname{deg}_{mathrm{in}}(v_i)ge 1,\quad operatorname{deg}_{mathrm{out}}(v_i)ge 1,\quadoperatorname{card}(F)=2n,\quadsumlimits_{e_{ij}in F}omega_{ij} = min$

let further
$3DCH_{mathrm{opt}}(V,D)subset H_{mathrm{opt}}(V,F),\quad operatorname{deg}_{mathrm{in}}(v_i)= 1,\quad operatorname{deg}_{mathrm{out}}(v_i)= 1,\quadsumlimits_{e_{ij}in D}omega_{ij} = min$
be the lightest vertex-disjoint cycle cover of $H_{mathrm{opt}}$

Question:

  • do we have $3DCC_{mathrm{opt}}subset H_{mathrm{opt}}$ and if not,
  • what is known about $sumlimits_{e_{ij}in D}omega_{ij} – sumlimits_{e_{ij}in F}omega_{ij}$

Background of the question is that $H_{mathrm{opt}}$ can be calculated efficiently and
from it its optimal vertex-disjoint cycle cover $3DCH_{mathrm{opt}}$ which might be an acceptable approximation for the optimal solution of the original problem.

sound – Lenovo ideapad specific microphone problem (Know the solution but something is stopping me from applying it)

Lenovo ideapad specific microphone problem (Know the solution but something is stopping me from applying it)

I just upgraded to 20.10 which made a bunch of problems I had on my first install reappear.

One such thing is the fact the mic does not work.

I found (miraculously) out that it’s specific to Ideapad and I also got the solution which worked perfectly.

The thing is when both left and right mic channels ( I call them channels but I don’t know what they really are) are working the mic is muted.

So all I have to do is use pavucontrol to mute the left one.

The thing is this time there are some auto balancing shenanigans at work that are getting in the way.

I mute the left thing, mic becomes functional as soon as I speak the balancing machinations get into action and unmute the left channel and sets left and right to the same level which basically mutes the mic.

Any idea what is getting in the way ?

The so called channels
https://imgur.com/a/oPCYl48

My solution for Advent of Code 2020, Day 4, in C

Here is my solution for Advent of Code 2020, Day 4, Part 1 in C. I tried using fscanf or fgets, but couldn’t find a nice of doing it, so I ended up using getc. Is there a way of using fscanf or fgets that makes this code better? Also, how does the code look in general?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct keyValuePair
{
    char key(4);
    char value(20);
} KeyValuePair;

typedef struct passport
{
    KeyValuePair fields(8);
    int numberOfFields;
} Passport;

int main()
{
    FILE* f = fopen("../input.txt", "r");
    if (f == NULL)
    {
        printf("Fail opening filen");
        return -1;
    }

    Passport passports(1000);
    int currentPassport = 0;
    int currentField = 0;

    char key(4);
    char value(20);

    int c;
    while (!feof(f))
    {
        c = getc(f);
        if (c == 'n')
        {
            ++currentPassport;
            currentField = 0;
            continue;
        }
        else
        {
            // read key
            key(0) = (char)c;
            key(1) = (char)getc(f);
            key(2) = (char)getc(f);
            key(3) = ''; // place null terminator at the end

            // discard ':'
            c = getc(f);

            // read value
            int index = 0;
            while (c != ' ' && c != 'n')
            {
                c = getc(f);
                if (c == EOF) { break; } // at the last line, instead of a new line we have EOF
                else if (c != ' ' && c != 'n') { value(index++) = (char)c; }
            }
            value(index) = '';  // place null terminator at the end

            strcpy(passports(currentPassport).fields(currentField).key, key);
            strcpy(passports(currentPassport).fields(currentField).value, value);
            ++currentField;

            ++passports(currentPassport).numberOfFields;
        }
    }

    int numberOfValidPassports = 0;
    for (int i = 0; i <= currentPassport; ++i)
    {
        if (passports(i).numberOfFields == 8) { ++numberOfValidPassports; }
        else if (passports(i).numberOfFields == 7)
        {
            int cidFound = 0;
            for (int j = 0; j < passports(i).numberOfFields; ++j)
            {
                if (strcmp(passports(i).fields(j).key, "cid") == 0)
                {
                    // passport contains cid and has 7 fields, therefore invalid
                    cidFound = 1;
                    break;
                }
            }
            if (!cidFound) { ++numberOfValidPassports; }
        }
    }

    printf("Number of valid passports: %d", numberOfValidPassports);

    fclose(f);
    return 0;
}