text:
Q: Replacing None with zero-length string in Python I would like to replace the Null value of None with a zero length string. My code seems to have no effect. What am I missing?
mylist = [[2,3,None],[None,3,4]]

for x in mylist:
    for y in x:
        if y is None:
            y = ''

print mylist

A: Unfortunately, all you're currently doing is setting the variable y to a completely different string '', which has absolutely no bearing on your original list, and the information is completely lost when you continue iteration.  To fully replace all those, you could use an indexing for loop.
for i in range(len(mylist)):
    for j in range(len(mylist[i])):
        if mylist[i][j] == None:
            mylist[i][j] = ''

A: You are doing it wrongly, when iterating over a list, you get the list element, trying to set it within the loop does not change it within the actual list, you need to get the index of that element and change it in the list , you can use enumerate function for that.
Example -
mylist = [[2,3,None],[None,3,4]]

for x in mylist:
    for i,y in enumerate(x):
        if y is None:
            x[i] = ''

print mylist
>> [[2, 3, ''], ['', 3, 4]]

A: The variable y is only a temporary read access to the respective element of the list. If you would like to change the list values, try accessing them directly via a counter.
The code below reassembls the entire nested list, which is another alternative:
mylist = [[2,3,None],[None,3,4]]
mylist = [[yI if yI is not None else '' for yI in xI] for xI in mylist]

A: Personally I do not like mutating lists whilst iterating over them, returning a new list is what every function in the standard library does. Here is a function that will return a new list with the desired element replaced, it will work for lists of any "depth" for lack of a better word
def list_replace(old_list, replace=None, replace_with=''):
    new_list = []
    for elem in old_list:
        if isinstance(elem, list):
            new_list.append(list_replace(elem))
        else:
            new_list.append(replace_with if elem == replace else elem)
    return new_list


text:
Q: Spot the mistake when computing the density function of $Y = 1/X$ when the density function of $X$ is known. The random variable $X$ has density function $f_{X}$ given by
\begin{equation}
 f_{X}(x) =
\begin{cases}
\frac{1}{2} \ \ \ \ \ x \in (0,1] \\
\frac{1}{2x^2} \ \ x \in (1,\infty) \\
0 \ \ \ \ \ \ x \in (-\infty,0]
\end{cases}
\end{equation}
Let $F_{X}$ be the distribution function of $X$. The random variable $Y$ is defined as follows $Y = 1/X$.  I want to compute the density function of $Y$.
Here's my attempt:
Let $y \in \mathbb{R}$ and let $F_{Y}(y)$ be the distribution function of $Y$.
\begin{equation}
F_{Y}(y) = P(Y\leq y) = P(1/X \leq y) = P(1/y \leq X) = P(X \geq 1/y)
\end{equation}
case 1: if $y \in (0,1) \implies  1/y \in (1,\infty) $. Then
\begin{equation}
F_{Y}(y) = P(X \geq 1/y) = 1 - P(X < 1/y) = 1 - F_{X}(1/y) = 1- \int_{1}^{1/y} \frac{1}{2x^2} dx = \frac{1+y}{2}
\end{equation}
case 2: if $y \in [1,\infty) \implies  1/y \in (0,1) $. Then
\begin{equation}
F_{Y}(y) = P(X \geq 1/y) = 1 - P(X < 1/y) = 1 - F_{X}(1/y) = 1- \int_{0}^{1/y} \frac{1}{2} dx =1-\frac{1}{2y}
\end{equation}
case 3: if $y \in (-\infty,0) \implies  1/y \in (-\infty,0) $. Then
\begin{equation}
F_{Y}(y) = P(X \geq 1/y) = 1 - P(X < 1/y) = 1 - F_{X}(1/y) = 1- \int_{\infty}^{1/y} 0 dx =1
\end{equation}
\begin{equation}
F_{Y}(y) =
\begin{cases}
1, \ \ \ \ \ \ \ \ \ \ y \in (-\infty,0) \\
\frac{1+y}{2}, \ \ \  \ \ \ \ y \in (0,1) \\
1-\frac{1}{2y},  \ \ \ \  y \in [1,\infty)
\end{cases}
\end{equation}
But the function $F_{Y}(y)$ is not non-decreasing, hence is not a distribution. If $F_{Y}$ were a distribution then it would be easy to compute $f_{Y}$
\begin{equation}
f_{Y}(y) =
\begin{cases}
0, \ \ \ \ \ \ \ \ \ y \in (-\infty,0) \\
\frac{1}{2}, \ \ \  \ \ \ \ y \in (0,1) \\
\frac{1}{2y^{2}},  \ \ \ \  y \in [1,\infty)
\end{cases}
\end{equation}
questions:

*

*Do you know where I made a mistake?

*Do you know another strategy to compute $f_{Y}$?

Thanks in advance.

A: In case 1, it should be
$$P(X \ge 1/y) = \int_{1/y}^\infty \frac{1}{2x^2} \, dx$$
or alternatively
$$P(X \ge 1/y) = 1 - P(X < 1/y) = 1 - \left(\int_0^1 \frac{1}{2} \, dx  + \int_1^{1/y} \frac{1}{2x^2} \, dx\right).$$
You make a similar mistake in case 2.

A: A simpler approach is possible via the formula $$f_Y(y) = f_X(g^{-1}(y)) \left|\frac{dg^{-1}}{dy}\right|,$$ where $Y = g(X) = 1/X$, since $g$ is an injective function.  Then since the density of $X$ may be more compactly written as
$$f_X(x) = \frac{1}{2 \max(1, x^2)} \mathbb 1 (x > 0)$$
then for $g^{-1}(y) = 1/y$ we immediately have $$f_Y(y) = \frac{1}{2 \max(1, 1/y^2)} \mathbb 1 (1/y > 0) \cdot \frac{1}{y^2} = \frac{\min(1, y^2)}{2 y^2} \mathbb 1 (0 < y < \infty) = \frac{\min(1/y^2, 1)}{2} \mathbb 1 (0 < y < \infty)$$ which in piecewise form is $$f_Y(y) = \begin{cases} 0, & y < 0 \\ \frac{1}{2}, & 0 \le y \le 1 \\ \frac{1}{2y^2}, & 1 < y < \infty .\end{cases}$$
This shows that $1/X$ has the same distribution as $X$ itself, which makes sense since the conditional distribution $X \mid 0 < X < 1$, and $1/X \mid X > 1$, are both the same uniform distribution.

A:
Do you know where I made a mistake?

Deciding that $\mathsf P(Y\leq y)=\mathsf P(X\geq 1/y)$ for all $y$ reguardless of location on the number line.

Do you know another strategy to compute $f_Y$?

You're method is okay, but since you are only interested in the pdf, save some thought and assert it as being the unsigned derivative of $F_X(1/y)$.
You do not need to know the value of the CDF at any point, just its gradient.
$$\begin{align}f_Y(y)&=\left\lvert \dfrac{\mathrm d F_X(1/y)}{\mathrm d y}\right\rvert\\[3ex] f_{X}(x) &= \begin{cases} 0 && x \in (-\infty,0]\\{1}/{2} && x \in (0,1] \\ {1}/{2x^2} && x \in (1,\infty)
\end{cases}\\[2ex]F_X(x)&=\begin{cases}0 && x\in(-\infty,0]\\x/2&&x\in(0,1]\\1- 1/2x&&x\in (1,\infty)\end{cases}\\[2ex]F_X(1/y)&=\begin{cases}0 && 1/y\in(-\infty,0]\\1/2y&&1/y\in(0,1]\\1- y/2&&1/y\in (1,\infty)\end{cases}\\[2ex] f_Y(y)&=\begin{cases}0 &&y\in(-\infty,0]\\1/2y^2&&y\in[1,\infty)\\1/2&& y\in(0,1)\end{cases}\end{align}$$

PS: even more effort may be saved by recognising $\left\lvert\dfrac{\mathrm d F_X(1/y)}{\mathrm d y}\right\rvert=\left\lvert \dfrac{\mathrm d (1/y)}{\mathrm d y}\right\rvert~f_Y(1/y)$ so no integration need be performed at all.
$$f_Y(y) =\dfrac{1}{\lvert 2y^2\rvert} \begin{cases} 0 && 1/y \in (-\infty,0]\\{1}/{2} && 1/y \in (0,1] \\ {y^2}/{2} && 1/y \in (1,\infty)
\end{cases}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using variables(int/string) to define frame/object names I have an array of frames and a button that when clicked, will add a new frame to the array.
I'm wondering if I can use the length of the array to determine the name of the new frame to add. For example, if the length of the array is 8, I store this in a variable (for example, int i = length, which is 8).
I then create the frame with i, so
InternalFrame intFrame(i) = new InternalFrame();
intFrameArray.add(intFrame(i));

is using intFrame(i) the correct way to do this? I'm currently not able to test myself as I'm at work but I have had a few problems attempting this last night.

A:
is using intFrame(i) the correct way to do this?

No. You can't. Java won't let you do that. Variable name cannot be dynamic.


text:
Q: Amarok 2.9.0 does not recognize CD drive Kubuntu 18.04 I am aware that 18.04 has changed the default music player to VLC and not Amarok, but I was hoping perhaps that somebody might know something about it nonetheless.
So when I try to run my funky fresh Kamaal the Abstract CD on Amarok (and rip it for my personal use as well ) I see this:

However, the CD functionality works perfectly fine on VLC, K3b (which I ended up having to use to rip it in the end), Brasero, etc. I've tried uninstalling and reinstalling Amarok plus the kio-audio-cd dependencies. too. Here's what it looks like in the terminal when I try to open the CD
`myusername@myusername-MS-7693:~$ amarok
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
QDBusConnection: session D-Bus connection created before QCoreApplication. Application may misbehave.
amarok(2907)/kdecore (KConfigSkeleton) KCoreConfigSkeleton::writeConfig:
amarok(2907)/kdecore (KConfigSkeleton) KCoreConfigSkeleton::writeConfig:
Could not parse stylesheet of widget 0x5563d3e9dc20
**********************************************************************************************
** AMAROK WAS STARTED IN NORMAL MODE. IF YOU WANT TO SEE DEBUGGING INFORMATION, PLEASE USE: **
** amarok --debug                                                                           **
**********************************************************************************************
skyroz666saile@skyroz666saile-MS-7693:~$ amarok(2907): couldn't create slave: "Unable to create io-slave:
klauncher said: Unknown protocol 'audiocd'. ...(continues)

Does anybody have any ideas in regard to this?

A: It's a bug in Amarok itself, which was already reported.
You can track its progress here: https://bugs.kde.org/show_bug.cgi?id=378183
They seem to know what causes it, but it's not mentioned there at the moment.


text:
Q: Remove dropdownlist item using css we have two dropdown lists in our MOSS portal. I want to remove second item of second dropdown list on 'Page Load', not after selecting it . I tried using javascript but as i am a beginner at scripting so it is not working . So guys is there anyway i can remove that item using css .
The dropdownlist is in a user control (ascx) file .
the dropdownlist id is 'drprequest' .
can we do it like :
drprequest:nth-of-child(2){display:none};

because i googled something similar to this one but i couldnt find anything.
If not can anyone give me the script to remove that item. Please help me friends .

A: You can try below CSS code to hide second option from the dropdown with ID drprequest
#drprequest select:nth-child(2) {
    display:none;
}

It will hide the second child of the dropdown using the CSS.
If you want to hide any other option from dropdown than just change the number accordingly.

A: Do you populate dropdown in your ascx.cs file? Try to process data on server-side.
Javascript
Remove option by its position in select:
$("[id$='drprequest'] option:eq(1)").remove()

Remove option by its value:
$("[id$='drprequest'] option[value='{option_val}']").remove()

CSS
[id$='drprequest'] select:nth-child(2) {
    display:none;
}


text:
Q: Can React Server components (RSC) have a lifecycle? As in RSC the React code will be on the server-side for various reasons mentioned HERE
I wonder if there is a way we can leverage the lifecycle and fetching APIs after the mounting point (For example update Or useEffects).

A: No.
From https://github.com/josephsavona/rfcs/blob/server-components/text/0000-server-components.md#capabilities--constraints-of-server-and-client-components :

Server Components: As a general rule, Server Components run once per
request on the server, so they don't have state and can't use features
that only exist on the client. Specifically, Server Components:

*

*❌ May not use state, because they execute (conceptually) only once per request, on the server. So useState() and useReducer() are not
supported.

*❌ May not use rendering lifecycle (effects). So useEffect() and useLayoutEffect() are not supported.

*❌ May not use browser-only APIs such as the DOM (unless you polyfill them on the server).

*❌ May not use custom hooks that depend on state or effects, or utility functions that depend on browser-only APIs.

*✅ May use server-only data sources such as databases, internal (micro)services, filesystems, etc.

*✅ May render other Server Components, native elements (div, span, etc), or Client Components.

Server Hooks/Utilities: Developers may also create custom hooks or
utility libraries that are designed for the server. All of the rules
for Server Components apply. For example, one use-case for server
hooks is to provide helpers for accessing server-side data sources.


text:
Q: Filtrar dados antes de ser renderizado no power pages via javascript/jquery Estou tentando fazer um filtro em uma modal dentro o portal que é criado pelo Power Pages (Dynamics 365 CRM - da Microsoft), contudo esse filtro tem que ser feito antes da modal ser apresentada (é clicado em um botão de busca para abri-la).
Como o resultado da modal é uma table com paginação (10 itens por página) mas o carregamento é feito quando se clica na página (não vem todos os dados de uma só vez) então o modal após ser aplicado o filtro de remoção da linha (tr) após filtragem dos dados através de um array que simula os CNPJ's que devem constar na lista da Table.
Esse é o código:
function filterClientsByContactId(elementId, reference, filterArray){
    var list = $(elementId).find(".entity-lookup").find(".entity-grid").eq(0);

    list.on("loaded", function () {
      list.find("table tbody > tr").each(function () {
        var tr = $(this);
        var i = $(tr).find('td[data-attribute="'+reference+'"]').attr("data-value");
        if (!filterArray.includes(i)) {
            tr.remove();
        }
      });
    });
}

Usando a função, ficaria algo do tipo:
filterClientsByContactId("#fmt_cliente_lookupmodal", "fmt_cnpj", items);

E a variável items, viria por exemplo, nesse formato:
var items = ["25.005.001/0001-20","14.084.025/0001-33", "05.224.144/0001-51"];

Por não ser carregado tudo de uma vez (entendi que é usado o bootstrap) após a execução do código, a paginação da modal as vezes fica com páginas em branco ou, quando em um resultado da página de 10 linhas, se duas estiverem dentro do filtro do CNPJ, mostra apenas 2 linhas e o restante em branco.

Em alguns casos a página fica vazia:

Existe uma forma melhor de fazer com que o modal apresente corretamente os dados após o filtro?
Um detalhe, já tentamos retirar a paginação para mostrar todos os cadastros e depois remover os que não se encaixam no filtro, mas ficou muito lento já que são mais de mil cadastros.


text:
Q: Disable all the unwanted Windows Firewall rules using PowerShell In my Windows Firewall, I've created certain rules that give me more control over my PC. But my rules have become somewhat useless since Windows and other apps are kept adding rules that I don't want.
I've tried to prevent this from happening, but the only way I've found is to use a third-party tool like Tinywall, which isn't exactly what I'm looking for.
So, to fix this, I want to create a PowerShell script that will disable and rename all rules that are not added by me. This way, I can manage them easily.
Rules that are added by me can be easily recognized because all of them start with certain words.
In this case, let's assume it starts with either 'Sample XYZ' or 'Sample ABC'.

*

*Sample XYZ - Windows Update

*Sample ABC - MPC-HC

*Sample ABC - Firefox

*Sample XYZ - Windows News

So far, this is what I have done.
In this part, the script will filter all the rules that I have created and then it'll disable & block all other rules.
To my surprise, this is working as expected.
# This will get all firewall rules
$NR = Get-NetFirewallRule

# This will exclude all the rules added by the user
$NR = $NR | Where-Object DisplayName -NotMatch "Sample ABC"
$NR = $NR | Where-Object DisplayName -NotMatch "Sample XYZ"

# Disable all other rules that are not added by the user
$NR | Set-NetFirewallRule -Enabled False

# Set rules' action to block
$NR | Set-NetFirewallRule -Action Block

These are the parts that don't work.
Task: Add a custom word to the beginning of the rules' display name
Example: If a rule name is 'Microsoft Photos', then it'll be renamed to 'IDWTFR - Microsoft Photos'.
# Add a custom word to the beginning of the rules' display name
# Custom word = 'IDWTFR - '
# Attempt 01: Fail
$NR | Set-NetFirewallRule -DisplayName "IDWTFR - " + $NR.DisplayName

# Attempt 02: Fail
$NR = $NR | ForEach-Object -MemberName DisplayName "IDWTFR - " + $NR.DisplayName | Set-NetFirewallRule

Task: Add unwanted rules to a group named 'Junk Rules'.
# Add to a group
# Attempt 01: Fail
$NR | Set-NetFirewallRule -DisplayGroup "Junk Rules"

To clarify it a bit more, this is the summary of what I am trying to do.

+-----------------------------+---------------------------+----------------+----------------+----------------+-------------+
|          Rule Name          |       New Rule Name       |     Group      |     Action     |     Status     | Created by  |
+-----------------------------+---------------------------+----------------+----------------+----------------+-------------+
| Sample XYZ - Windows Update | Same as before            | Same as before | Same as before | Same as before | User        |
| Sample ABC - MPC-HC         | Same as before            | Same as before | Same as before | Same as before | User        |
| Sample ABC - Firefox        | Same as before            | Same as before | Same as before | Same as before | User        |
| Sample XYZ - Windows News   | Same as before            | Same as before | Same as before | Same as before | User        |
| Microsoft Photos            | IDWTFR - Microsoft Photos | Junk Rules     | Block          | Disable        | Not by user |
| App Installer               | IDWTFR - App Installer    | Junk Rules     | Block          | Disable        | Not by user |
| Feedback Hub                | IDWTFR - Feedback Hub     | Junk Rules     | Block          | Disable        | Not by user |
| Microsoft Edge              | IDWTFR - Microsoft Edge   | Junk Rules     | Block          | Disable        | Not by user |
+-----------------------------+---------------------------+----------------+----------------+----------------+-------------+

I'm new to PowerShell, so any help will be appreciated. Thanks.

A: Since this is your special use case, it's going to a challenge for one to validate without setting up an environment as close as possible to what you show here. I am in no position to do that.
Yet, looking at what you say you have done, here is a refactor option to try. Refactor a bit (again, not tested)
# Get all firewall rule name, and filter out the named rules
Get-NetFirewallRule |
Where-Object -Property Name -notlike 'Sample ABC|Sample XYZ' |
ForEach {
    # Disable all other rules that are not added by the user
    Set-NetFirewallRule -Name $PSItem.DisplayGroup -Enabled False

    # Set rules' action to block
    $PSItem.DisplayName |
    Set-NetFirewallRule -Action Block

    # Rename firewall rule
    If ($PSItem.DisplayName -like '*Microsoft*')
    {Rename-NetFirewallRule -Name $PSItem.DisplayName -NewName "IDWTFR-$($PSitem.DisplayName)"}

    # Create new firewall group
    $PSItem.Group = 'JunkRules' |
    Set-NetFirewallRule -NewDisplayName $PSItem.DisplayName
}


text:
Q: Change button action in object I'm trying to change button action/change button in Firefox PDF web viewer. Is it posible?
Problem step by step:
1.I've got pdf on my website added by:

    <object id="testpdf" data="pdfFile.pdf" type="application/pdf" height="800px" width="100%">

This browser does not support PDFs. Please download the PDF to view it: Download PDF.

    </object>

It is loading fine in firefox pdf web viewer.

*When it is loaded I'd like to change print button in it - remove standard print action and add my action (run "myProtocol:///pdfFile.pdf" or start process "AcroRdr32 /p pdfFile.pdf" - to run printing by Adobe Reader or start printing by Adobe Reader in any other way (except download it and run printing manually)).

Is it possible to do? Demo of firefox web viewer is in https://mozilla.github.io/pdf.js/web/viewer.html
Thank you in advance
EDIT:
I've tried to do it by:
if (document.readyState === 'complete') {
    if (("testpdf").readyState === 'complete') {
        document.getElementById("print").outerHTML = '<button onclick="location.href=\'icprint://C:/pdfFile.pdf\'" id="print" class="toolbarButton print hiddenMediumView" title="Drukowanie">Drukuj</button>';
    };
};

But it's not working, the deeper id, that I've accessed is #testpdf

A: It should be possible, I found the print-Button in the Firefox-Inspector (F12).

You can change the title and the onClick of the button like that:
const ele = document.getElementById('print');
ele.title = 'Drukowanie';
ele.onclick = function() { window.location.href='icprint://C:/pdfFile.pdf'; }

Can you access C:?
=> Something like that, if you use jquery (I have not tested it):
if (document.readyState === 'complete') {
    if ($('#testpdf').readyState === 'complete') {
        const ele = document.getElementById('print');
        ele.title = 'Drukowanie';
        ele.onclick = function() { window.location.href='icprint://C:/pdfFile.pdf'; }
    }
}


text:
Q: How can I use passed in int's to declare the size of an array within c++? In my code, the user is asked to input the number of columns and rows within a Maze. From here I would like to use these input's to define the Size of an array. However these are not constants and therefore they're not accepted.
maze[rows][columns] //ERROR: EXPRESSION MUST HAVE A CONSTANT A

Currently Maze is hardcoded as:
maze[4][5]

I was wondering if there was a work around for this problem or if someone would be able to look at my Code and explain to me how I could create a new Array using these values whilst storing the values from the old array, I believe this needs pointers. I've included my code below:

#include<fstream>
#include<iostream>
#include<string>
#include <vector>
//Maze Size
#define SIZE 5
using namespace std;

bool isSafe(char maze[4][5], int visited[4][5], int x, int y);
bool isValid(int x, int y);
void findShortestPath(char maze[4][5], int visited [4][5], int i, int j, int x, int y, int& min_dist, int dist, string& p_route,string route);
void userInput();
void createMaze(int rows, int columns, string filename);

int main()
{
    userInput();
}

bool isSafe(char maze[4][5], int visited[4][5], int x, int y)
{
    if (maze[x][y] == 'x' || visited[x][y] || maze[x][y] == NULL)
        return false;

    return true;
}

bool isValid(int x, int y)
{
    if (x < 4 && y < 5 && x >= 0 && y >= 0)
        return true;

    return false;
}

void findShortestPath(char maze[4][5], int visited[4][5], int i, int j, int x, int y, int& min_dist, int dist,string&p_route,string route)  //I&J Start Point, X&Y End point
{
    bool solved = false;
    // if destination is found, update min_dist
    while (!solved)
    {

        if (i == x && j == y)
        {
            p_route = route;
            min_dist = min(dist, min_dist);
                if (min_dist != INT_MAX)
                {
                 cout << "The shortest path from source to destination has length " << min_dist << endl;
                 cout << "The route through the maze is: " << p_route << endl;

                }
                else
                {
                    cout << "Destination can't be reached from given source";
                }
            solved = true;
            return;
        }

        // set (i, j) cell as visited
        visited[i][j] = 1;

        // go to bottom cell
        if (isValid(i + 1, j) && isSafe(maze, visited, i + 1, j))
            findShortestPath(maze, visited, i + 1, j, x, y, min_dist, dist + 1, p_route, route.append("S"));

        // go to right cell
        if (isValid(i, j + 1) && isSafe(maze, visited, i, j + 1))
            findShortestPath(maze, visited, i, j + 1, x, y, min_dist, dist + 1, p_route, route.append("E"));

        // go to top cell
        if (isValid(i - 1, j) && isSafe(maze, visited, i - 1, j))
            findShortestPath(maze, visited, i - 1, j, x, y, min_dist, dist + 1, p_route, route.append("N"));

        // go to left cell
        if (isValid(i, j - 1) && isSafe(maze, visited, i, j - 1))
            findShortestPath(maze, visited, i, j - 1, x, y, min_dist, dist + 1, p_route, route.append("W"));

        // Backtrack - Remove (i, j) from visited mazerix
        visited[i][j] = 0;
    }
}

void userInput()
{
    string filename;
    int rows;
    int columns;
    cout << "Please input the name of your maze!" << endl;
    cin >> filename;
    cout << endl;
    cout << "Please input the amount of rows in your maze!" << endl;
    cin >> rows;
    cout << endl;
    cout << "Please input the amount of columns in your maze!" << endl;
    cin >> columns;
    cout << endl;
    createMaze(rows, columns, filename);

}

void createMaze(int rows, int columns, string filename)
{
    int startRow = 0;
    int startColumn = 0;
    int endRow = 0;
    int endColumn = 0;
    int column = 0;
    char maze[4][5];
    ifstream input(filename);
    char data = input.get();
    string route;
    string p_route;

    while (!input.eof())
    {
        for (int row = 0; row < rows; row++)
        {
            while (data != '\n' && !input.eof())
            {
                if (data == 'A')
                {
                    startRow = row;
                    startColumn = column;
                }
                if (data == 'B')
                {
                    endRow = row;
                    endColumn = column;
                }
                maze[row][column] = data;
                column++;
                data = input.get();
            }
            column = 0;

            data = input.get();
        }
    }
    input.close();
    cout << "The Maze being solved is: " << endl;
    for (int y = 0; y < rows; y++)
    {
        for (int x = 0; x < columns; x++)
        {
            cout << maze[y][x];
        }
        cout << endl;
    }
    input.close();
    // construct a mazerix to keep track of visited cells
    int visited[4][5];

    // initially all cells are unvisited
    memset(visited, 0, sizeof visited);

    int min_dist = INT_MAX;
    findShortestPath(maze, visited, startRow, startColumn, endRow, endColumn, min_dist, 0, p_route, route);
}


text:
Q: Feathers-Sequelize Where statement and Query param I have the following feathers-sequelize query:
context.params.sequelize = {
    raw: false,
    include: [{
      model: organisations,
      where: organisationId ? { id: organisationId } : undefined,
      include: [{
        model: roles,
        where: roleId ? { id: roleId } : undefined,
      }],
    }],
    where: single ? (
      sequelize.and(
        sequelize.where(
          sequelize.col('"organisations->organisation_users"."roleId"'),
          sequelize.col('"organisations->roles"."id"'),
        ),
        sequelize.where(
          sequelize.col('"organisations->organisation_users"."userId"'),
          sequelize.col("users.id")
        )
      )
    ) : undefined
  }

I make the following service request:
await UserService.find({ query: { email: data.email } }))

The query object is left out since in the above sequelize query I am setting my own where statement. If I remove the where statement than the query object works. How do I make use of my own where statement and also include the feathers query object?
Thank you & Regards,
Emir

A: In order to add extra conditions to the existing query object, instead of using the params.sqeuelize you add them directly into the query object (since it's available throuhg context.params.query) and since you use a before hook, the query object gets modified before the execution.
In you example should be something like:
if(single) {
    context.params.query.push(
      sequelize.and(
        sequelize.where(
          sequelize.col('"organisations->organisation_users"."roleId"'),
          sequelize.col('"organisations->roles"."id"'),
        ),
        sequelize.where(
          sequelize.col('"organisations->organisation_users"."userId"'),
          sequelize.col("users.id")
        )
      )
   )
}

Probably not the correct syntax, but that's the idea: add extra conditions directly in the feathers query object. Hope this helps.


text:
Q: Create directory for App available to Files app Friends
I have generated a PDF document that I wish to make available to the Files app
This is my code that works well, in that it puts up the dialogue from which I can select "Save to files". (pdfURLis the URL for the PDF document saved in the bundle.  I can pass the data directly but it means I cannot programmatically set the file name)
        Button("Share app") {
            self.isSharePresented = true
        }
        .sheet(isPresented: $isSharePresented, onDismiss: {
            print("Dismiss")
        }, content: {
            PDFSaveController(activityItems: [pdfURL])
        })

But there is no directory for my App.
The user can create it (there is an option to create a directory), but my users will never see that and it will trigger endless angst.
I need to create the directory in the app.
I have followed https://stackoverflow.com/a/61631421/16675319 but the answer there is incorrect.
I have set the "Application supports iTunes file sharing"  (Peculiar)
I use:
        let documentDirectoryURLs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        let documentDirectoryURL = documentDirectoryURLs[0]
        let directoryURL = documentDirectoryURL.appendingPathComponent("TestPDF_Shared", isDirectory: true)
        if !FileManager.default.fileExists(atPath: directoryURL.path) {
            do {
                try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
                return directoryURL
            } catch {
                print(error.localizedDescription)
                assert(false)
            }

which creates a directory, but it is not visible in the files app.
There are other directories visible in the Files app from other applications that I have installed but I did not create those directories as an app user, the apps created them on installation (I assume).
I am using:
iOS 15.2.1
Xcode Version 13.2.1
Swift


text:
Q: How does Armadillo library handle error? Just started on Armadillo library. Through out the documentation and FAQ, I didn't find any reference on how does Armadillo handle errors. For example, how should I know whether "mat A(1e10, 1e10)" is successful or not?

A: The error handling mechanism of Armadillo is not clear from its documentation. By email communication with the author Sanderson, it's figured out that the error handling mechanism of Armadillo is actually a mixture of C++ std exception and C-style return value. However, the information of what exception will be thrown is still incomplete in the documentation.
For example, to define a matrix, I'll suggest not using "mat X(M, N)" because there is no error handling. The safe way is like this (C-style):
  mat X;
  try{
      X.set_size(M, N);
  } catch (...) {
      printf("memory allocation failed\n");
      return -1;
  }

Note that when memory allocation error occurs, exception "std::logic_error" or "std::bad_alloc" will be thrown (see the comment below by mtall), this is not put in the documentation. When return, use "X.reset()" to release the data memory.
And @mtall: I suggest a less harsh attitude to newbies of a specific field is better for the community health. Force others to read incomplete documentations is not a constructive opinion.In fact, most good open source projects come with documentations not so good, that's why we should help make them more clear and user-friendly.

A: Examples from Armadillo's documentation:
For R = chol(X) and chol(R, X) functions: if the decomposition fails, R is reset and chol(X) throws a std::runtime_error exception, while chol(R,X) returns a bool set to false.
For the eig_sym(X) and inv(X) functions: if X is not square, a std::logic_error exception is thrown.
For operators like +, a std::logic_error exception is thrown if incompatible object sizes are used.
For element access like A(i,j), a std::logic_error exception is thrown if the requested element is out of bounds.
etc etc.
The source code for Armadillo is also available, so you can directly look at it and see what it does.


text:
Q: Stack overflow before debugging main function in amd64 I have a working 32 bit application with several dependency. A rough estimation of the dependency is like below -
[handshake_win32.exe] ----> [libhandshake32.dll] ----> [libeay32, ssleay32.dll] ----> [zlib1.dll]
Now I would like to use my libhandshake32.dll through JNI for code reuse. As the JVM is  64-bit so I guess those library needed to be recompiled for x64 arch.
My first target is running the current baseline handshake_win32.exe in x64. So I have recompiled all the dll for x64. But after successful recompilation when I start into debug mode I am getting immediate Stack Overflow at main function.

Unhandled exception at 0x000007f602f79567 in handshake_win32.exe:
  0xC00000FD: Stack overflow.

I have tried to check the dll signature with dumpbin and it seems all have machine type x64.
dependency walker gives the following error message for all of x64 modules -

Error: At least one module has an unresolved import due to a missing
  export function in an implicitly dependent module. Error: Modules with
  different CPU types were found.

It shows that x86 version of MSVCR100.dll was loaded where the actual dll's arch is x64.
Can anyone suggest what are the possible causes of this problem?
Thanks in advance.

A: 1、If you use cmd/bat to compile your dlls,
start the cmd/bat this way:
%comspec% /k ""PATH_TO_VS\VC\vcvarsall.bat"" amd64

or
%comspec% /k ""PATH_TO_VS\VC\vcvarsall.bat"" x86_amd64

instead of:
%comspec% /k ""PATH_TO_VS\VC\vcvarsall.bat"" x86

2、if you use gui, you'd better check the command line:
c/c++->command line
linker->command line

Sometimes, when you change your configeration in vs gui, the command lines do not change,
you'd better start a new project and copy your soure files there.


text:
Q: Python3 [Classes]- Should I create a new variable to store an instance of a class from a user's input, and how? First question here on this site. Still in the very early stages of learning programming and trying to wrap my head around some concepts. I am seriously struggling to find an answer to this problem I have encountered :
So, let's take a simple class:
class Employee():
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

Now I would like to instantiate that class, from a user's input, and store that instance in a variable, which could be then appended to a list, giving me something like :
 list_employees = [emp_1, emp_2, emp_3]

Problem is that these variables (emp_1 etc..) don't exist yet. They would have to be created from the input.
I understand how I could do that myself :
emp_1 = Employee(input("Enter name: "), int(input("Enter salary: ")))

But I'd like this to be done "automatically", if that means anything, so that the user can create an indefinite number of instances.
I don't need this for anything specific, and I could think of ways to go around the issue with dictionaries, but my brain is just struggling conceptually with this "variable creation by the program" idea... I hope I managed to express it clearly and I'd be grateful if anyone could help me with understanding this or explain to me if and how I'm thinking about this wrong!
Cheers!

A: You don't actually need an intermediate variable if all you want is to append the new instance to a list:
# python 2 / 3 compat
try:
   input = raw_input
except NameError:
   pass

def create_emp():
    # Q&D, would need error handling
    name = input("Enter name")
    salary = int(input("Enter salary"))
    return Employee(name, salary)

def create_emps()
    employees = []
    while True:
        employees.append(create_emp())
        answer = input("add another ? (Y/n)")
        if answer.lower().strip() != "y":
            break
    return employees

if __name__ == "__main__":
    employees = create_emps()
    print(employees)

A: You could for example do the following
employees = []
for _ in range(1,4):
    name = input("Enter name: ")
    salary = int(input("Enter salary: "))
    employees.append(Employee(name, salary))

if you want to acces your variables by name try using a dictionary instead of a list to hold your employees
EDIT
With dictionary (f strings only after Python 3.6)
employees = {}
for i in range(1, 4):
    name = input("Enter name: ")
    salary = int(input("Enter salary: "))
    employees[f'emp_{i}'] = Employee(name, salary)

A: You can do this during the instantiation of your object:
class Employee():
    objects = []

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

        Employee.objects.append(self)


text:
Q: Find the Element Occurring b times in an an array of size n*k+b Description
Given an Array of size (n*k+b) where n elements occur k times and one element occurs b times, in other words there are n+1 distinct Elements. Given that 0 < b < k find the element occurring b times.
My Attempted solutions

*

*Obvious solution will be using hashing but it will not work if the numbers are very large. Complexity is O(n)

*Using map to store the frequencies of each element and then traversing map to find the element occurring b times.As Map's are implemented as height balanced trees Complexity will be O(nlogn).
Both of my solution were accepted but the interviewer wanted a linear solution without using hashing and hint he gave was make the height of tree constant in tree in which you are storing frequencies, but I am not able to figure out the correct solution yet.
I want to know how to solve this problem in linear time without hashing?
EDIT:
Sample:
Input: n=2 b=2 k=3
Aarray: 2 2 2 3 3 3 1 1
Output: 1

A: An idea using cyclic groups.
To guess i-th bit of answer, follow this procedure:

*

*Count how many numbers in array has i-th bit set, store as cnt

*If cnt % k is non-zero, then i-th bit of answer is set. Otherwise it is clear.

To guess whole number, repeat the above for every bit.
This solution is technically O((n*k+b)*log max N), where max N is maximal value in the table, but because number of bits is usually constant, this solution is linear in array size.
No hashing, memory usage is O(log k * log max N).
Example implementation:
from random import randint, shuffle

def generate_test_data(n, k, b):
    k_rep = [randint(0, 1000) for i in xrange(n)]
    b_rep = [randint(0, 1000)]
    numbers = k_rep*k + b_rep*b
    shuffle(numbers)
    print "k_rep: ", k_rep
    print "b_rep: ", b_rep
    return numbers

def solve(data, k):
    cnts = [0]*10
    for number in data:
        bits = [number >> b & 1 for b in xrange(10)]
        cnts = [cnts[i] + bits[i] for i in xrange(10)]
    return reduce(lambda a,b:2*a+(b%k>0), reversed(cnts), 0)

print "Answer: ", solve(generate_test_data(10, 15, 13), 3)

A: In order to have a constant height B-tree containing n distinct elements, with height h constant, you need z=n^(1/h) children per nodes: h=log_z(n), thus h=log(n)/log(z), thus log(z)=log(n)/h, thus z=e^(log(n)/h), thus z=n^(1/h).
Example, with n=1000000, h=10, z=3.98, that is z=4.
The time to reach a node in that case is O(h.log(z)). Assuming h and z to be "constant" (since N=n.k, then log(z)=log(n^(1/h))=log(N/k^(1/h))=ct by properly choosing h based on k, you can then say that O(h.log(z))=O(1)... This is a bit far-fetched, but maybe that was the kind of thing the interviewer wanted to hear?

A: UPDATE: this one use hashing, so it's not a good answer :(
in python this would be linear time (set will remove the duplicates):
result = (sum(set(arr))*k - sum(arr)) / (k - b)

A: I assume:

*

*The elements of the array are comparable.

*We know the values of n and k beforehand.

*A solution O(n*k+b) is good enough.

Let the number occuring only b times be S. We are trying to find the S in an array of n*k+b size.
Recursive Step: Find the median element of the current array slice as in Quick Sort in lineer time. Let the median element be M.
After the recursive step you have an array where all elements smaller than M occur on the left of the first occurence of M. All M elements are next to each other and all element larger than M are on the right of all occurences of M.
Look at the index of the leftmost M and calculate whether S<M or S>=M. Recurse either on the left slice or the right slice.
So you are doing a quick sort but delving only one part of the divisions at any time. You will recurse O(logN) times but each time with 1/2, 1/4, 1/8, .. sizes of the original array, so the total time will still be O(n).
Clarification: Let's say n=20 and k = 10. Then, there are 21 distinct elements in the array, 20 of which occur 10 times and the last occur let's say 7 times. I find the medium element, let's say it is 1111. If the S<1111 than the index of the leftmost occurence of 1111 will be less than 11*10. If S>=1111 then the index will be equal to 11*10.
Full example: n = 4. k = 3. Array = {1,2,3,4,5,1,2,3,4,5,1,2,3,5}
After the first recursive step I find the median element is 3 and the array is something like: {1,2,1,2,1,2,3,3,3,5,4,5,5,4} There are 6 elements on the left of 3. 6 is a multiple of k=3. So each element must be occuring 3 times there. So S>=3. Recurse on the right side. And so on.

A: If 'k' is even and 'b' is odd, then XOR will do. :)


text:
Q: Is it possible to create a chain of source maps? I work on a TypeScript file foo.ts.  Once my workflow is done with it, I have the following files:
foo.ts
foo.js         // generated                   - referenced by page in QA
foo.js.map     // source map between foo.ts and foo.js
foo.min.js     // minified version of foo.js  - referenced by page in Production
foo.min.js.map // source map between foo.js and foo.min.js

Debugging in QA works great, since devtools lets me work in foo.ts (e.g. in TypeScript).
However, once I am in production, foo.min.js is referenced by the page and devtools only let me debug with foo.js.  It seems that it can't figure out the chain of source maps from foo.min.js to foo.ts.
Is there a trick that I am missing to allow me to chain the source maps?


text:
Q: Access Denied running "Hello World" program through Eclipse I am very new to Java and Eclipse, and am having trouble.
I wrote the basic Hello World program in Notepad and after some struggle managed to execute it through Command Prompt. In the training program I am doing, I am now suggested to run Hello World through Eclipse. Here is my code in Eclipse:
package program091220;

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

This exactly matches the code in the training video I am watching, besides for a different package name. In the video when the host runs the program it gives the "Hello World" string in the console. When I run the program, I get the following message:

'Launching Hello World' has encountered a problem. Exception occurred
executing command line.

There is an option to view details. The details are:

Exception occurred executing command line. Cannot run program
"C:\Users\Spiralgo\Desktop\Coding\Eclipse\eclipse\Java\jdk-14.0.2\bin\javaw.exe"
(in directory "C:\Users\Spiralgo\eclipse-workspace\September 12
2020"): CreateProcess error=5, Access is denied

I previously ran into the "Access is denied" error when trying to run through Command Prompt, a problem I solved by giving very specific folder location information when executing the program. I'm not sure how or if I can give specific folder information within Eclipse if the code is already within Eclipse itself? I'm still learning what Eclipse even is as an IDE.
Please help. Thank you.


text:
Q: Ejs rendered vars are undefined I'm writing my first webb ap with nodejs and express, using ejs templates.
now when I'm rendering the html files it all works fine, but when I try to render the files with parameters, it seems like the rendered ejs template can't find the parameters I've sent to it.
here is my file structure :
project/
  Views/
    index.ejs
    login.ejs
  public/
    all the css files ..
  node_modules/
  server.js

and here is my server.js :
var express = require('express');
var app = express();
const cookieParser = require('cookie-parser');
const session = require('express-session');
const bodyParser = require('body-parser')

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/Public'));
app.use(cookieParser());
app.use(session({secret: '1234567890QWERTY',resave: false, saveUninitialized: false})); // change the secret to safer one
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.get('/', function(req, res) {
    if (req.session.user == undefined) {
        // if user is not logged-in redirect back to login page //
        res.render('login');
    } else {
        console.log(req.session.user);
        res.render('index', {username:req.session.user});
    }
});

app.get('/login', function(req, res) {
    res.render('login');
});

app.listen(8080);
console.log('port: 8080');

and here is my index.ejs file:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Dashboard</title>

<%= username %>

and for some reason whenever I try to access index.ejs, it returnes an error -
"username is not defined"
any idea what I'm doing wrong? the examples online looks exactly the same
thanks !
after Fadi Bitar answered this is how my server get event looks like and it's stil won't work:
app.get('/', function(req, res) {
    if (req.session.user == undefined) {
        // if user is not logged-in redirect back to login page //
        res.render('login',{username:req.session.user});
    } else {
        console.log(req.session.user);
        res.render('index', {username:req.session.user});
    }
});

// about page
app.get('/login', function(req, res) {
    res.render('login',{username:req.session.user});
});

A: In the initial code, it should work... Without seeing it my guess is that you are trying to echo <%=username%> in login.ejs.
Your updated code has a couple of points where you're using a variable that doesn't exist.
if (req.session.user == undefined) {
    res.render('login',{username:req.session.user});
}

Here you're saying 'if req.session.user is undefined, set username to req.session.user' (undefined).
Then this bit does the same..
app.get('/login', function(req, res) {
    res.render('login',{username:req.session.user});
});

I assume here that when you go to /login req.session.user is not set, so that's why that errors...

A: I believe you are missing the "username" variable in your get function.
Make sure you do:
    res.render('/', {username: "example username"});


text:
Q: JS - Google charts - Cannot read property 'getChartLayoutInterface' of undefined I've recently encountered an issue in which I'm given the console error of:
Cannot read property 'getChartLayoutInterface' of undefined

I've read up on other questions and from what I've seen it's because the Google Vizulation API has not loaded, my code is the following:
<script type="text/javascript">

        // Load the Visualization API and the piechart package.
        google.charts.load('current', {'packages':['corechart']});

        // Set a callback to run when the Google Visualization API is loaded.
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
          var jsonData = $.ajax({
              url: "assets/main/getFrontData.php",
              dataType: "json",
              async: false,
              type: 'post',
              }).responseText;
          var data = new google.visualization.DataTable(jsonData);
          var options = {
            backgroundColor: 'none',
            lineWidth: 4,
            areaOpacity: .2,
            legend: { position: 'none' },
            colors: ['#007cb0'],
            width: 550,
            height: 300
          }
          // Create our data table out of JSON data loaded from server.

         var boundingBox = chart.getChartLayoutInterface().getChartAreaBoundingBox();
   $('#backgroundChart').css('background-position', boundingBox.left + "px " + boundingBox.top + "px").css('background-size', boundingBox.width + "px " + boundingBox.height + "px");

          // Instantiate and draw our chart, passing in some options.
          var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
          chart.draw(data, options);
        }
</script>

The whole point being to put a background image in the graph the same size, any help would be appreciated on why the error is being thrown.

A: Your problem exists due to the fact that 'chart' is undefined prior to being referenced in this line
 var boundingBox = chart.getChartLayoutInterface().getChartAreaBoundingBox();

If you do not have an instance of the object defined before referencing that object, your environment will always return 'undefined'.
Perhaps relocating the instance of 'chart' will do you well. Move this section above the bounding box instantiation:
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);`

This will ensure that the chart exists in your DOM, before referencing it for DOM manipulation.


text:
Q: How to connect a django app in heroku to mongodb atlas? how can i connect my django app in heroku to mongodb atlas without installing the mLab add-on ?
i have tried to add a config var of my mongo database but it doesn't work maybe because its not a link of mLab and its a django app not nodejs. and mLab did not accept creating accounts anymore.
is there any solution for that ?


text:
Q: Deriving the formula of the surface of a sphere using triangles. My friend tried to find the formula of the surface of a sphere using the following reasoning, but we can't see the mistake:
Let's first take half a sphere and divide the sphere into infinitely small triangles like this:
 Bad drawing, but I hope you understand the idea.
Then, we can unwrap it and arrange the hemisphere into half a rectangle:  The height will be $\frac{\pi r}{2}$ because it is a quarter of the length of a circumference and the base will be $2 \pi r$.
We can now insert the other half rectangle of the other hemisphere divided in infinitely small triangles in this way:
It will nicely create a rectangle (if we rearrange the side triangles) and to get the area of the rectangle, just multiply the base times height, ending with $\pi^2 r^2$.
We know that that the correct answer is $4 \pi r^2$, but we can't figure out the error.

A: At the most abstract level, the discrepancy is due to the sphere not being a developable surface: it cannot be projected onto a plane while preserving areas and angles at once. Thus, it is not correct to say that the triangle on the unit sphere with angles $\frac\pi2$, $\frac\pi2$ and $dx$ – the "infinitely small triangles" in the argument – has the same area as the planar right triangle of leg lengths $dx$ and $\frac\pi2$.


text:
Q: Rust specify lifetime of local variable I'm quite new to Rust and still having issues with the concept of lifetime specifiers.
I have a Vec (or any other collection) of references. Now I want to replace a specific reference with another reference to a newly created local variable. The problem now is, that the local new variable has a shorter lifetime than the vector which would invalidate the reference.
An example code that tries do do what I want but throws an compile time error:
fn main() {
    let values = ["one".to_string(), "lorem".to_string(), "three".to_string()];
    let borrowed_values = vec![&values[0], &values[1], &values[2]];
    println!("{:?}", do_the_impossible(borrowed_values));
}

fn do_the_impossible(mut data: Vec<&String>) -> Vec<&String> {
    let replacement = "two".to_string();
    data[1] = &replacement;
    return data;
}

The question now is: How do I create a new variable with the same lifetime as the vector?
I want to use references because cloning the objects would be pretty expensive.
My initial idea was to use lifetime specifiers which indicate that the local variable should live as long as the vector does. But I couldn't find a syntactical right way to do this. Is it even possible to specify the lifetime of a local variable?
And if not, is there any other way to avoid cloning the elements of the vector? My last resort would be using an Rc pointer.
Thanks in advance!

A: This sounds like a use case for std::borrow::Cow, which allows you to have a value which may be backed by a borrow or an owned value.
You would instead write something like:
use std::borrow::Cow;

fn main() {
    let values = ["one".to_string(), "lorem".to_string(), "three".to_string()];
    let borrowed_values: Vec<_> = values.iter().map(Cow::Borrowed).collect();
    println!("{:?}", do_the_impossible(borrowed_values));
}

fn do_the_impossible<'a>(mut data: Vec<Cow<'a, String>>) -> Vec<Cow<'a, String>> {
    let replacement = "two".to_string();
    data[1] = Cow::Owned(replacement);
    return data;
}


text:
Q: How to log FATAL (or any custom log level) with SLF4J and Log4j2 I have those specific requirements :

*

*Need to be able to log in FATAL level

*Need to use SLF4J

*Need to use Log4j2
Right now, here's my implementation:
final Logger logger = LoggerFactory.getLogger(HelloWorld.class);
final Marker marker = MarkerFactory.getMarker("FATAL");
logger.error(marker, "!!! Fatal World !!!");

Here's my PatternLayout (in yaml):
PatternLayout:
  Pattern: "%d{ISO8601_BASIC} %-5level %marker [%t] %logger{3.} - %msg%n"

Here's my log output :
20150506T155705,158 ERROR FATAL [main] - !!! Fatal World !!!

Do you have any idea about how to efficiently to remove the "ERROR" from the log output?
Thank you very much

A: Here's the closest working solution I came with some colleagues :

*

*Create a Fatal Marker class using SLF4J Markers.

*Using a RoutingAppender, use the Marker as the routing pattern:  "$${marker:}"

*Configure a Fatal-specific appender that has its own PatternLayout that doesn't include the LogLevel but a hardcoded FATAL level.

Here's the Java sample :
Marker fatal = MarkerFactory.getMarker("FATAL");
// Usage example
final Logger logger = LoggerFactory.getLogger(FatalLogger.class);
logger.log(fatal, "this is a fatal message");

// Log sample :
20150514T115144,279  FATAL [main] FatalLogger - this is a fatal message

Here's the YAML sample :
Configuration:
  status: debug

  Appenders:
    RandomAccessFile:
      - name: APPLICATION_APPENDER
        fileName: logs/application.log
        PatternLayout:
          Pattern: "%d{ISO8601_BASIC} %-5level %msg%n"
      - name: FATAL_APPENDER
        fileName: logs/application.log
        PatternLayout:
          Pattern: "%d{ISO8601_BASIC} FATAL %msg%n"

    Routing:
      name: ROUTING_APPENDER
      Routes:
        pattern: "$${marker:}"
        Route:
        - key: FATAL
          ref: FATAL_APPENDER
        - ref: APPLICATION_APPENDER #DefaultRoute

  Loggers:
    Root:
      level: trace
      AppenderRef:
        - ref: ROUTING_APPENDER

A: I know the question is for log4j.  I found this page when looking in relation to logback.  Here's what sl4j recommends: https://www.slf4j.org/faq.html#fatal.

A: Here is what I did for log4j which I also recommend for log4j2....
Write your own custom slf4j static binder aka bridge. This requires a little work but is well worth it for a variety of complicated reasons 1 that I will blog about one day.
Here is what you do.

*

*You copy this code here: https://github.com/apache/logging-log4j2/tree/master/log4j-slf4j-impl

*You then want to edit the Log4jLogger class and change the marker methods (trace,error,warn,info, etc) to dispatch appropriately. ie if (marker.contains("FATAL")) fatal(....);

*Exclude the original log4j-slf4j-impl from your project and use your new code in place.

<soap-box-rant>
I honestly think slf4j is severely flawed because

*

*it makes it very difficult/impossible to override hardcore static initialization along with also not providing logger.fatal(...).

*Markers are not needed and are inherently complex:

*

*Very very very few projects use markers. I actually looked/grepped open source projects and marker usage is close to zero low.

*The ones that use marker are because fatal is missing. It is not 80/20. Markers are for the 1% and fatal is for the 99%.

*Many developers think that somehow using the marker "fatal" will map it to fatal.

*Few know what a detached marker is including myself.

*There is overlap with what the MDC context provides. Given event dimension oriented databases (elasticsearch, druid, etc) the MDC context is superior (name/value pair).

</soap-box-rant>
1 one of them being able to actually be part of the boot process of your logging framework opposed to hard to determine almost arbitrary static initialization

A: Marker is not really what you want here. Marker is for "enriching" log messages, making them more easily searchable. You are trying to change the log level/priority, which is a little different.
You're using logger.error() which will log the message as an ERROR level.
If there is no FATAL level pre-defined (usually there is, such as logger.fatal()), then use the generic logger.log() which allows you to specify the log level.
logger.fatal(yourMessage);

OR
logger.log(priorityLevel, yourMessage);

UPDATE:
From the SLF4J website:

The Marker interface, part of the org.slf4j package, renders the FATAL level largely redundant. If a given error requires attention beyond that allocated for ordinary errors, simply mark the logging statement with a specially designated marker which can be named "FATAL" or any other name to your liking.

http://www.slf4j.org/faq.html#fatal
So, with SLF4J, it is not possible to have a FATAL log level. I strongly disagree with the rationale behind this decision, but it is what it is.

A: The only solution I've found so far is to use have 5 markers :
final Marker traceMarker = MarkerFactory.getMarker("TRACE");
final Marker debugMarker = MarkerFactory.getMarker("DEBUG");
final Marker infoMarker = MarkerFactory.getMarker("INFO");
final Marker warnMarker = MarkerFactory.getMarker("WARN");
final Marker errorMarker = MarkerFactory.getMarker("ERROR");
final Marker fatalMarker = MarkerFactory.getMarker("FATAL");

And log passing the marker everytime :
logger.info(infoMarker, "!!! INFO World !!!");
logger.error(errorMarker, "!!! ERROR World !!!");
logger.error(fatalMarker, "!!! FATAL World !!!");

And modify the PatternLayout to totally remove the LogLevel and always log the Marker, such as :
PatternLayout:
  Pattern: "%d{ISO8601_BASIC} %marker [%t] %logger{3.} - %msg%n"

I kind of think this solution is a hack... It would also remove the log level of any external library using the LogLevel the right way.
Summary : This solution isn't a good solution.
UPDATE : I tried another solution, writing a RewritePolicy :
public class FatalRewritePolicy implements RewritePolicy {

    public static final String FATAL = "FATAL";

    @Override
    public LogEvent rewrite(final LogEvent logEvent) {

        final Marker marker = logEvent.getMarker();
        if (marker == null)
            return logEvent;

        // Log Level is final in the LogEvent, there's no way we can modify it.
        Level level = logEvent.getLevel();

        return null;
    }
}

There seems to be no way to change the LogLevel of a LogEvent in Log4j2 (which make sense).
Summary : Still no solution.

A: You could add "FATAL" at the beginning of your message.  For example:
LOGGER.error("FATAL: database connection lost.");

You do lose some things, like filtering based on level, but this may be ok for many people, especially since you're unlikely to filter out FATAL statements (debug and trace, sure).


text:
Q: Flutter : Open Page from page inside bottomnavigationview i want to open profile page from home page without press 'profile' button inside bottomnavigation item.
Thanks for help.
this is a main class of my project. i put all page here and i already import all page here.
MainClass
int _currentIndex = 0;
    final List<Widget> _children = [
        HomePage(),
        MessagePage(),
        ProfilePage()
    ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
     appBar: AppBar(
       title: Text('My Flutter App'),
     ),
    body: _children[_currentIndex],
     bottomNavigationBar: BottomNavigationBar(
       currentIndex: _currentIndex,
       onTap: onTabTapped,
       items: [
         BottomNavigationBarItem(
           icon: new Icon(Icons.home),
           title: new Text('Home'),

         ),
         BottomNavigationBarItem(
           icon: new Icon(Icons.mail),
           title: new Text('Messages'),
         ),
         BottomNavigationBarItem(
           icon: Icon(Icons.person),
           title: Text('Profile')
         )
       ],
     ),
   );
 }

and this my home page. this page same as profile and message page. i need to open profile page from home page without pressing profile menu in bottom. i just wanna press profile button inside home page.
HomePage
import 'package:flutter/material.dart';
import 'package:navigation/profile_page.dart';

class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            Text("Home Page"),
            RaisedButton(
              child: Text("GO TO PROFILE PAGE"),
              onPressed: (){

                );
              },
            )
          ],
        ),
      ),
    );
  }
}

A: This can be done by directly calling the class name.
For example consider Profile() be the class extending statefull class.
Home class
....

int _index = 1;

  final options = [
    Text('Home'),
    Text('Message'),
    Profile() //directly call the class to load
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My flutter app"),
      ),
      body: Center(
        child: options.elementAt(_index),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          new BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          new BottomNavigationBarItem(
            icon: Icon(Icons.message),
            title: Text('message'),
          ),
          new BottomNavigationBarItem(
              icon: Icon(Icons.person),
              title: Text('profile')
          )
        ],
        currentIndex: _index,
        onTap: _onTapped,
      ),
    );
  }

  void _onTapped(int index) {
    setState(() {
      _index = index;
    });
  }

Similarly you can load other classes too.
hope it helped:)


text:
Q: How to Insert checkbox checked values id in Many to Many relationship table? I wanted to add the value of checkbox ids to many to many relation table between two tables Course-Student
i have 3 tables Course{ CourseID,CourseName }, Studdent{StudentID,StudentName} and CourseStudet{CourseID, StudentID}
Course table already have course{1.DataScience,2.English,3.Physics}
while Inserting Student i have shown course checkboxes with these options fetching list of these courses from database to show in view to user when he is about to register now i am confused how to insert into database?
public class CourseModel {

        public List<Course> mycourse{ get; set; }

        public string StudentName {get; set;}

    }

EF generated Class

 public partial class Course
    {
        public Course()
        {
            this.Student= new HashSet<Student>();
        }

        public int CourseID { get; set; }
        public string CourseName { get; set; }

        i have inserted this field to check for checked value
        public bool Ischecked { get; set; }

        public virtual ICollection<Student> Student { get; set; }
    }

 public partial class Student
    {

        public Student()
        {
            this.Course= new HashSet<Course>();
        }

        public int StudentID { get; set; }
        public string StudentName { get; set; }

        public virtual ICollection<Course> Course{ get; set; }
    }

 public ActionResult Index()
        {
            CourseModel coursemodel = new CourseModel();
            using (Entities db = new Entities())
            {
                coursemodel.mycourse = db.Course.ToList<Course>();

                 return View(coursemodel);

            }

        }
        [HttpPost]
        public ActionResult Index(CourseModel course)
        {
            return View(course);
        }

View

@using (Html.BeginForm("index", "Course", FormMethod.Post))

         <input type="Text" name="StudentName" placeholder="Name" />

{

        @for (int i = 0 ; i < Model.mycourse.Count; i++)
        {
            if (i % 3 == 0) {
                @:

            }

            @Html.CheckBoxFor(x => x.mycourse[i].Ischecked)
            @Model.mycourse[i].CourseName
            @Html.HiddenFor(x => x.mycourse[i].CourseID)
            @Html.HiddenFor(x => x.mycourse[i].CourseName)

        }

   <input type="submit" value="Submit" />
}

i am getting checkbox id,name and which course is checked now how can i add student with including these values to relationship table CourseStudent ?

A: You have problems with your database design. Remove ischecked field.Remember while you are designing entities, you shouldn't put fields that are for view. It is like that I make Reports table from my each query.
correct your models
  public partial class Course
{
    public Course()
    {
        this.Student = new HashSet<Student>();
    }

    public int CourseID { get; set; }
    public string CourseName { get; set; }

    public virtual ICollection<Student> Student { get; set; }
}

public partial class Student
{

    public Student()
    {
        this.Course = new HashSet<Course>();
    }

    public int StudentID { get; set; }
    public string StudentName { get; set; }

    public virtual ICollection<Course> Course { get; set; }
}

Add viewmodels(You can use view models for showing custom data for your view)
You can read more
ViewModel
public class CourseViewModel
{
    public Course course { get; set; }
    public bool CheckBox { get; set; }
}

public class StudentCourseViewModel
{
    public List<CourseViewModel> coursesVM { get; set; }
    public Student student { get; set; }
}

Controller
  public ActionResult index()
  {
      Entities db = new Entities();
      List<CourseViewModel> courselist = new List<CourseViewModel>();
      foreach (var item in db.Course.ToList())
        {
            courselist.Add(new CourseViewModel { course = item});
        }
      StudentCourceViewModel model = new StudentCourseViewModel(
      {
          student = new student(),
          coursesVM = courselist   }
      };
      return View(model);
  }
  [HttpPost]
  public ActionResult Save(StudentCourseViewModel model)
  {
      Entities db = new Entities();
      Student stdindb = db.Students.FirstorDefault(c => c.StudentName == model.student.StudentName);
      if(stdindb == null)
      {
       stdindb = new student(){//your properties};
       db.students.add(stdindb);
      }
      foreach (var item in model.coursesVM)
      {
        if (item.Ischecked)
          {
            stdindb.Course.Add(db.course.single(c=>c.CourseId == item.course.CourseId ));
          }
        }
        db.SaveChanges();
        return View();
  }

View
@model SchoolCMS.Models.StudentCourseViewModel
@{
    ViewBag.Title = "Select Course";
}

@using (Html.BeginForm("Save", "home", FormMethod.Post))
{
@Html.TextBoxFor(c=>c.student.StudentName)

    @for (int i = 0; i < Model.coursesVM.Count; i++)
    {

            @Html.CheckBoxFor(c => c.coursesVM[i].Ischecked)
            @Html.HiddenFor(c => c.coursesVM[i].course.CourseID)

        @Html.DisplayFor(c => c.coursesVM[i].course.CourseName)

    }

    <input type="submit" value="Submit" />
}


text:
Q: browser not defined for ts-jest and puppeteer I am trying to create snapshot-tests with puppeteer for my typescript create react app. Regular testing with jest is working fine, but as soon as I am trying to create the snapshots with the browser and have to use the browser variable within my .test.ts file I'm being told that browser is not defined.
I can't seem to work around this problem even though I have been trying to resolve this issue for hours.
For reference, here are my jest settings within my package.json file:
  "jest": {
"preset": "jest-puppeteer-preset",
"collectCoverageFrom": [
  "src/**/*.{js,jsx,ts,tsx}"
],
"setupFiles": [
  "<rootDir>/config/polyfills.js"
],
"testMatch": [
  "<rootDir>/src/**/__tests__/**/*.(j|t)s?(x)",
  "<rootDir>/src/**/?(*.)(spec|test).(j|t)s?(x)"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
  "^.+\\.(js|jsx|mjs)$": "<rootDir>/node_modules/babel-jest",
  "^.+\\.tsx?$": "<rootDir>/config/jest/typescriptTransform.js",
  "^.+\\.css$": "<rootDir>/config/jest/cssTransform.js",
  "^(?!.*\\.(js|jsx|mjs|css|json)$)": "<rootDir>/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
  "[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|ts|tsx)$"
],
"moduleNameMapper": {
  "^react-native$": "react-native-web"
},
"moduleFileExtensions": [
  "web.ts",
  "ts",
  "web.tsx",
  "tsx",
  "web.js",
  "js",
  "web.jsx",
  "jsx",
  "json",
  "node",
  "mjs"
],
"globals": {
  "ts-jest": {
    "tsConfigFile": "tsconfig.test.json"
  }
}

And here are the dependencies I'm using:
"typescript": "^2.9.2",
"puppeteer": "^1.1.1",
"jest-image-snapshot": "^2.3.0",
"jest": "22.4.2",
"jest-puppeteer-preset": "^2.0.1",
"ts-jest": "22.0.1",

Any help would be appreciated a lot!

SOLUTION:
In combination with the marked answer below and this guide things worked out for me. For some reason I was trying to access browser as a global variable. Turns out I was doing things wrong from the very beginning. You are supposed to define browser like this:
  const browser = await puppeteer.launch({
    headless: true // whether you want to run the test headless
  });

which ended up working.

A:
browser not defined for ts-jest and puppeteer

Per the jest puppeteer docs you need to ensure you have @types/jest-environment-puppeteer installed as that provides the global browser definition.


text:
Q: --harmony flag in Node.js 0.12 throws SyntaxError So I wrote the following:
index.js
let x = 31

console.log(x)

And tried testing it with the --harmony flag:
alex@alex-K43U:~/node/es6$ node --harmony index.js

But I get an error:
/home/alex/node/es6/index.js:1
(function (exports, require, module, __filename, __dirname) { let x = 31
                                                            ^
SyntaxError: Illegal let declaration outside extended mode

What am I doing wrong? I already updated to node 0.12.1.

A: You need to enable strict mode in order to use let.
You can either:
"use strict"
let x = 31
console.log(x)

Or:
node --harmony --use_strict index.js

Then it works as expected:
victor@ubuntu:~/Documents$ node --harmony --use_strict index.js
31


text:
Q: d3 - Rotate x-axis labels I'm trying this graph:

with my data.
I wanted to rotate the x-axis labels.
Here's the code :
var timeLabels = svg.selectAll(".timeLabel")
          .data(times)
          .enter().append("text")
            .text(function(d) { return d; })
            .attr("x", function(d, i) { return i * gridSize; })
            .attr("y", 0)
            .style("text-anchor", "end")
            .attr("transform", "translate(" + gridSize / 2 + ", -6)rotate(-90)")
            .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });

But the result I get is. Entire labels get rotated to -90 deg in a single straight line. Instead I wanted each label to be rotated to -90 deg. Like this:

I even tried using .attr("transform", function(d) {return "translate(" + gridSize / 2 + ", -6)rotate(-90)"}) but it didn't help.
Result :

Help will be very much pleased.

A: The problem is that when you rotate an element, it gets rotated around the origin point, (0,0), of the local coordinate system.  If the element you're rotating isn't right next to the origin, it can end up moved quite a large distance, and possibly moved outside the chart altogether.
There are two ways you can fix it:

*

*Position the label with a "transform" attribute instead of with x and y attributes.  That way, the label's coordinate system -- including the (0,0) point of rotation -- will be positioned with it, and the rotation will happen where you expect.  The code @Manoj gave follows that system, but assumes you are using the default xAxis function.  For your custom axis label code, your labels are given a y value of 0, and an x value determined from a function.  You just need to move those values into the transform attribute, paying careful attention that the transformation of the overall position comes before the rotation and adjustment:
var timeLabels = svg.selectAll(".timeLabel")
  .data(times)
  .enter().append("text")
    .text(function(d) { return d; })
    .attr("transform", function(d, i) {
          return "translate(" + ( i * gridSize) + ",0)"
                  + "translate(" + gridSize / 2 + ", -6)rotate(-90)";
     } )
    .style("text-anchor", "end")
    .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ?
                               "timeLabel mono axis axis-worktime" :
                               "timeLabel mono axis");
     });

Of course, you could combine those two translation statements, as:
    .attr("transform", function(d, i) {
          return "translate(" + ( (i + 0.5) * gridSize) + ",-6)"
                  + "rotate(-90)")

*Alternately, you can specify a center of rotation in the rotate statement, by including the x and y values of the point you want it to rotate around:
var timeLabels = svg.selectAll(".timeLabel")
  .data(times)
  .enter().append("text")
    .text(function(d) { return d; })
    .attr("x", function(d, i) { return i * gridSize; })
    .attr("y", 0)
    .attr("transform", function(d, i) {
          return "translate(" + gridSize / 2 + ", -6)" +
                 "rotate(-90 "+ ((i + 0.5) * gridSize) + " " + (-6) +")";
     } )
    .style("text-anchor", "end")
    .attr("class", function(d, i) { return ((i >= 8 && i <= 16) ?
                               "timeLabel mono axis axis-worktime" :
                               "timeLabel mono axis");
     });

As you can see, this version is rather repetitive, as we have to calculate the position of the label twice -- once to position it, and once to set the center of rotation.  You can see why most examples (and the d3 axis functions) position the labels with translations, so they can just be rotated in place.

A: Try this code:
Fiddle:
 svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("id", "x")
    .attr("transform", "translate(0," + (h) + ")")
    .call(xAxis)
    .selectAll("text")
    .style("text-anchor", "end")
    .attr("dx", "-.8em")
    .attr("dy", ".15em")
    .attr("transform", function (d) {
    return "rotate(-90)";
});


text:
Q: Elementary matrices help I need serious help on why I am getting the answer wrong here. I followed the exact same method as: Express the following invertible matrix A as a product of elementary matrices
But the computer is telling me I am wrong.
Computer's answer:

My answer:

A: The third matrix is not an elementary matrix (heck, it has a column of zeros and isn't invertible).

A: You left a $1$ off of $E_3^{-1}$.  It should be $$\pmatrix{1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 1 & \color{red}1}$$
Once you make that change you should get the correct solution.
For future reference, you should note that the comment that the computer gives you was big hint about your mistake.  It says that at least one of your matrices isn't an elementary matrix.  So you should have gone back through, saw that the matrix you have for $E_3^{-1}$ isn't an elementary matrix, and then reworked that one.


text:
Q: JQUERY Populate "Select" options dynamically based on input from another select element I would like to change the options in a select element based on what i select in another select element (dropdown box).
I have two select boxes (RUNS and SAMPLES) on my PHP page. What i intend to do is to change options in the second select box based on a query that is performed against a database using the option selected in first select box.
I have a table in my database that connects "SAMPLES" to "RUNS". The first select box is populated by a set of 'RUNS' on page load. I would like the 'SAMPLES' that belong to the selected RUN to populate in the SAMPLES box.
The HTML would be something like
<select name='run_id' id='run_id>
    <option value='1'>RUN 1</option>
    <option value='2'>RUN 2</option>
    <option value='4'>RUN 3</option>
    <option value='5'>RUN 4</option>
</select>

The backend table "sample_runs" has columns run_id and sample_name. I have a PHP script as follows,
<?php
mysql_connect("localhost","uname","pwwd");
mysql_select_db("dbname");
$run_id = $_GET['run_id'];
$sql = "select distinct sample_name from samples where run_id = '$run_id'";
$rsd = mysql_query($sql);
while($rs = mysql_fetch_array($rsd)){
    echo '<option value='.$rs['sample_name'],'>'.$rs['sample_name']."</option>";
}
?>

I can modify the PHP script (easy part), but can someone share some code with me on how to populate the sample name options based on the run_id selected in the RUNS box.
Greatly appreciate the help.

A: If your data set is small enough, you could send all of the data on page load.  Do this by building a JSON object that represents your entire dataset in PHP.  You can use PHP's json_encode function to do this:  http://php.net/manual/en/function.json-encode.php
Once you've built up a JSON string, you'll need to send it to some JavaScript to handle the population of the sample name options based on the selected run_id.  There's a good discussion on that here:  How to pass variables and data from PHP to JavaScript?
Finally, you'll need to write JavaScript to do the DOM manipulation necessary to change the contents of the second HTML select box.  Here's an example of that:  Adding options to select with javascript
If your data set is too large to send in a single request, you'll need to build up a REST API to provide the data for each run when it is selected.
Good luck!!


text:
Q: Comparative form of shy I've been looking for this answer a lot and people say diferent things are true. Is it shyer and the shyest, shier and shiest or more shy and the most shy? According to Merriam-Webster dictionary it's shyer and the shyest, shier and shiest. (http://www.merriam-webster.com/dictionary/shyer) The same goes to Dictionary.com (http://dictionary.reference.com/browse/shy). So does this mean both are right?

A: What Merriam-Webster is saying by including the comparatives shyer, shyest, shier and shiest is simply that these are words; it's not implying that more shy and most shy are ungrammatical. If you look at their definition of polite, it gives politer and politest and makes no mention of more polite and most polite, even though these latter forms are used quite a bit more often. (See Google Ngram.)
The same is true with shy; more shy and most shy are used fairly frequently and are not ungrammatical. Similarly, Merriam-Webster includes both the shyer and shier spellings because they are both fairly common, and neither can be said to be wrong.

A: Both are correct, yes.  It is never ungrammatical to add "more" before an adjective, unless it is already in comparative form.
The dictionaries you mentioned are just noting that superlative and comparative forms of the adjectives do exist, as that is not always the case.


text:
Q: If x, y, and z are positive numbers such that $3x < 2y < 4z$, which of the following statements could be true? This is more or less a question about how many cases I should be trying in general on the quantitative section of the GRE.
I got this question wrong and it is because I did not try enough cases, so I was wondering if anyone has any tips on how to see that a given condition may be true without trying 5 different cases.
Question:
If x, y, and z are positive numbers such that $3x < 2y < 4z$, which of the following statements could be true? Indicate all such statements.
a. $x=y$
b. $y=z$
c. $y>z$
d. $x>z$

My work:
For a)
$x=2, y=2, z=3$
$3x=6, 2y=4, 4z=12$
$6<4<12$ is false.
a) cannot be true.
For b)
$x=1, y=4, z=4$
$3x=3, 2y=8, 4z=16$
$3<8<16$ is true.
b) can be true.
For c)
$x=1, y=4, z=3$
$3x=3, 2y=8, 4z=12$
$3<8<12$ is true.
c) can be true.
Now d) was the reason for missing this question. I plugged in one case as I did with a) yet there is in fact a threshold such that this works.
For example:
$x=7, y=11, z=6$
$3x=21, 2y=22, 4z=24$
$21<22<24$ is true.
d) can be true.
However, during the practice test (this was the last question I was crunched for time and had to the second to last because this one looked easier) I only plugged in one case and it didn't work so I quit.
Tips?

A: Your work for part (a) is useless.  It is given that $x, y, z$ always satisfy $3x < 2 y < 4 z$.  If you choose $x,y,z$ that violate that constraint, they are not relevant to the problem.
Part (a): $x < \frac{2}{3}y$, so $x$ is never as large as $y$, so $x \neq y$ always.
For parts (b) and (c), you made valid choices of $x,y,z$, so have these answers.
For part (d), $3x<4z$ is the given relation (that is, $x < \frac{4}{3}z$) and $x>z$ can be satisfied if $z < x < \frac{4}{3} z$, which is easy to arrange for large enough $z$.  You also require a multiple of $2$, $2y$, between $3x$ and $4z$, so you may have to go a little bigger.
In a bit more detail on (d): $z < x < \frac{4}{3} z$, so look at multiples of $3$ for $z$ so I don't have to waste time on that fraction.  $z=3$ is too small because there's no room for $x$ between $3$ and $4$.  $z = 6$ forces $x = 7$.  Is there an even number between $21$ and $24$?  Yes, $22$, so $y=11$.

A: Simplify the inequality to three separate inequalities:
$$(1)\quad x<\dfrac{2}{3}y$$
$$(2)\quad y<2z$$
$$(3)\quad x<\dfrac{4}{3}z$$
Now we conclude easily
(a) false by (1)
(b) true by (2) since $z=y<2z$ still holds.
(c) true by (2) since $z<1.5z=y<2z$ is possible
(d) true by (3) since $z<1.1z=x<\dfrac{4}{3}z$ is possible.

A: In a), you try one specific set of numbers only. So at best you show that a)  is sometimes false. This does not exclude the possibility that it is sometimes true. Instead, if $x,y,z$ are positive and $3x<2y<4z$, then
$$ 3x<2y<2y+y=3y$$
and hence $x<y$ (and not $x=y$). We see that a) is always false and never true* under the given assumptions.
Of course ouy are right that for the three cases, where one has to show that the asked statement can be true, a single specific example suffices. However, it does not suffice to plug in just any valid triple - after all, it need not be (and is not) the case that the statement is always true. Thus it suffices to plug in one set of numbers, but it has to be a smartly chosen one. In other words, you have to contemplate the given conditions and the target property as to what "obstacles" there might be for the target property and if these obstables can be shown to always be there or if they disappear in certain achievable situations ...


text:
Q: Identificar indices repetidos e efetuar a troca somente de um deles Possuo o seguinte vetor:
a = [1, 2, 3, 4, 1, 3]

Preciso percorrer esse vetor e identificar quais os valores repetidos.
Após identificá-los, preciso que apenas um deles seja trocado por um valor aleatório entre 1 e 11.
Por exemplo:
O vetor de saída seria algo assim:
a = [1, 2, 3, 4, 10, 9]

Ou seja, identifiquei que o índices 0 e 2 estão repetidos. Porém, efetuo a troca somente dos índices 4 e 5 e mantenho os valores do 0 e 2.
Alguém poderia me ajudar com isso?
Grato aos que puderem.

A: Uma forma simples é percorrer todos os valores em a, verificar se o valor corrente pertence à lista b, que será a saída, e enquanto pertencer, sortear um novo número entre 1 e 11, até que este não esteja presente na lista para então adicioná-lo. Em Python, ficaria assim:
from random import randint

a = [1, 2, 3, 4, 1, 3]
b = []

for value in a:
    while value in b:
        value = randint(1, 11)
    b.append(value)

print b

O resultado seria:
[1, 2, 3, 4, 8, 9]

Isto é, os índices 4 e 5 foram identificados como duplicados e foram sorteados outros valores, nesse casso 8 e 9 respectivamente.

Veja funcionando no Ideone.

Inclusive, esta lógica funcionará bem com mais de um valor repetido. Veja:
from random import randint

a = [1, 2, 3, 4, 1, 1, 1, 1, 1]
b = []

for value in a:
    while value in b:
        value = randint(1, 11)
    b.append(value)

print b

Gerando o resultado:
[1, 2, 3, 4, 7, 11, 8, 6, 10]

Veja funcionando no Ideone.

Porém, se a lista de valores possuir mais de 11 elementos, chegará uma hora que o programa irá tentar sortear um valor e nunca encontrará um válido, pois todos os valores entre 1 e 11 pertencem à lista, ficando preso infinitamente no laço while - partindo da premissa que a lista de valores conterá inicialmente apenas valores entre 1 e 11. Desta forma, uma verificação quanto ao comprimento da lista deverá ser feita para evitar tal problema:
from random import randint

a = [1, 2, 3, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
b = []

if len(a) <= 11:
    for value in a:
        while value in b:
            value = randint(1, 11)
        b.append(value)

    print b
else:
    print "A lista 'a' deve conter no máximo 11 elementos."

Veja funcionando no Ideone.


text:
Q: ActiveDirectory Current Username in ASP.NET I'm trying to get both ActiveDirectory and standard forms login working but one thing is stopping me. I can't get the name of the current windows user. The closest I've got is var i = WindowsIdentity.GetCurrent();, but that gives me the name of the IIS app pool user. I have Anonymous Authentication, Forms Authentication and Windows Authentication enabled in IIS. I can load users from AD so I assume my web.config is setup correctly.
Edit: This is my web.config (using a Facade provider):
<membership defaultProvider="HybridMembershipProvider">
      <providers>
        <clear />
        <add name="HybridMembershipProvider" type="MyApp.Data.HybridMembershipProvider" AspNetProviderName="AspNetSqlMembershipProvider" ActiveDirectoryProviderName="ADMembershipProvider" />
        <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyAppConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
        <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ADConnectionString"
            attributeMapUsername="sAMAccountName" enableSearchMethods="true" attributeMapEmail="mail"/>
      </providers>
    </membership>

Edit 2: Here's my IIS security setup.

A: If you turn on ASP.Net Impersonation in IIS, you can get the username like you wanted to. This will only work if that data is in the forms membership provider / AD, and they are not Anonymous.
Also, mixing Forms based and Windows/AD based auth is doable but not recommended.  See this if you need to do it.
EDIT: I think I misunderstood what you wanted so here's a high-level glossing over of what goes on with the aforementioned solution:
If you turn off Anonymous Authentication, and turn on Asp.Net Impersonation, IIS will do a 401 Challenge whenever somebody visits the site.
If everything is on the same domain, the web browser will send your credentials to IIS, IIS will validate them against it's Active Directory, and then AD will give IIS an Identity to work with.
When you have Asp.Net Impersonation turned on, IIS will then bind that Identity to the current thread/request.  So after authentication happens, you can just grab the username from the current thread identity, and then query Active Directory like:
using System.Threading;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

......

PrincipalContext pc = null;
UserPrincipal principal = null;

try
{
    var username = Thread.CurrentPrincipal.Identity.Name;
    pc = new PrincipalContext(ContextType.Domain, "active.directory.domain.com");
    principal = UserPrincipal.FindByIdentity(pc, username);

    var firstName = principal.GivenName ?? string.Empty
    var lastName = principal.Surname ?? string.Empty
    return string.Format("Hello {0} {1}!", firstName, lastName);
}
catch ...
finally
{
    if (principal != null) principal.Dispose();
    if (pc != null) pc.Dispose();
}

A: The .Net apps I've written where I've used windows authentication I can still use User.Identity.Name to get the AD username. This usually includes the DC of course, and returns the users SAM Account name. I was not trying to implement both at the same time but User.Identity.Name for sure works separately

A: Try this if you are using forms authentication with active directory:
Context.User.Identity.Name

//code snippet
sub Page_Load(sender as object, e as EventArgs)
  lblName.Text = "Hello " + Context.User.Identity.Name & "."
  lblAuthType.Text = "You were authenticated using " &   Context.User.Identity.AuthenticationType & "."
end sub

Ref:
Active Directory Authentication from ASP .NET
How to authenticate against the Active Directory by using forms authentication and Visual Basic .NET
Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication
Ref:
You can use Windows authentication with ASP.NET in a number of ways:

*

*Windows authentication without impersonation. This is the default setting. ASP.NET performs operations and accesses resources by using your application's process identity, which by default is the Network Service account on Windows Server 2003.

*Windows authentication with impersonation. With this approach, you impersonate the authenticated user and use that identity to perform operations and access resources.

*Windows authentication with fixed-identity impersonation. With this approach, you impersonate a fixed Windows account to access resources using a specific identity. On Windows Server 2003, you should avoid this impersonation approach; instead, use a custom application pool with a custom service identity.
As per the documentation you can obtain the authenticated user's Windows token.
IIdentity WinId= HttpContext.Current.User.Identity;
WindowsIdentity wi = (WindowsIdentity)WinId;

If there is something wrong then check your application
  impersonation method as per the MSDN documentation of How To: Use Windows Authentication in ASP.NET 2.0

Refer ScottGu's article Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

A: This is a segment of code I used in my ASP.NET MVC App not too long ago, it helped for me, Don't know if it will help you though, you are free to check though
    private static void CheckIfUserExists(string p)
    {
        try
        {
                var user = (from x in Data.EntityDB.UserInfoes where x.SAMAccountName == p select x).FirstOrDefault();
                DirectoryEntry entry = new DirectoryEntry(Properties.Settings.Default.LDAPPath); //this is the connection to your active directory
                DirectorySearcher search = new DirectorySearcher(entry);
                search.PropertiesToLoad.Add("*");
                search.Filter = "(&(sAMAccountName=" + p + ")(objectCategory=person))";
                SearchResult searchResult = search.FindOne();
            //If the user under the alias is not found, Add a new user. Else, update his current data
            if (user == null)
            {
                XXXXXXX.Models.UserInfo newUserEntry = new Models.UserInfo
                {
                    SAMAccountName = p,
                    First_Name = searchResult.Properties.Contains("givenName") ? searchResult.Properties["givenName"][0].ToString() : string.Empty,
                    Last_Name = searchResult.Properties.Contains("sn") ? searchResult.Properties["sn"][0].ToString() : string.Empty,
                    Title = searchResult.Properties.Contains("title") ? searchResult.Properties["title"][0].ToString() : string.Empty,
                    Office = searchResult.Properties.Contains("l") ? searchResult.Properties["l"][0].ToString() : string.Empty,
                    Country = searchResult.Properties.Contains("c") ? searchResult.Properties["c"][0].ToString() : string.Empty,
                    Telephone = searchResult.Properties.Contains("telephoneNumber") ? searchResult.Properties["telephoneNumber"][0].ToString() : string.Empty,
                    Mobile_Phone = searchResult.Properties.Contains("mobile") ? searchResult.Properties["mobile"][0].ToString() : string.Empty,
                    Email_Address = searchResult.Properties.Contains("mail") ? searchResult.Properties["mail"][0].ToString() : string.Empty,
                    Image_Path = string.Format(Properties.Settings.Default.UserPicturePath, p),
                    LastUpdate = DateTime.Now,
                };

update
Take notice that I also queried a different database in this extract, ignore all the Linq statements. The DirectoryEntry, DirectorySearcher and SearchResult Classes should help you with what you need.
update 2
the variable p can be replaced by the HttpContext.Current.User.Identity Property
update 3
Here is a current list of LDAP names (where you see searchResult.Properties.Contains("") Over here which points to different user attributes in the active directory

A: I'd give a try with:
var i = Environment.CurrentUser;
and you can use also my class:
http://pastebin.com/xnYfVsLX


text:
Q: Missing tesseract50.dll from conda installation I have a Windows 11 64x computer with a new conda env created. I installed tesseract from conda using:
conda install -c conda-forge tesseract

Before the 5.0 release, a file called tesseract41.dll was created in env_name\Library\bin, along with the tesseract exe. Now with the release of tesseract 5.0, I can't find the file tesseract50.dll. What I do see is a file called tesseract50.lib in env_name\Library\lib.
I can use tesseract from the command line normally. However, I'm trying to use the API in Python, so can't use the lib file as ctypes.cdll.LoadLibrary doesn't detect it as a valid app.
I can´t use libraries such as PyTesseract, because it is too slow, and I can't use tesserocr as it doesn't support Python 3.10, and the wheels are outdated, so I need to build my own wrapper.
QUESTION
How can I get the tesseract50.dll file without having to build tesseract from source or install it from binaries?


text:
Q: Firebase fcm background notification not working below android 11 in flutter Fcm is coming in android 11 fine I am receiving notification both in background and foreground but in  android version below 10 is not getting background notification but receiving in foreground so can you help me to solve this issue
This is the code of Main
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print('Handling a background message ${message.messageId}');
}

Future<void> main() async {

  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  LocalNotificationService.initialize();

  runApp(const MyApp());
}
class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
  void initState() {
  FirebaseMessaging.onMessage.listen(
        (message) {
      print("FirebaseMessaging.onMessage.listen");
      if (message.notification != null) {
        LocalNotificationService.createanddisplaynotification(message);

      }
    },
  );
  FirebaseMessaging.onMessageOpenedApp.listen((message) {
          if (message.notification != null) {
      LocalNotificationService.createanddisplaynotification(message);

    }
  },);

    super.initState();
  }

}

This is the code of local notification service
class LocalNotificationService{
  static final FlutterLocalNotificationsPlugin _notificationsPlugin =
  FlutterLocalNotificationsPlugin();

  static Future<void> initialize() async {
    // initializationSettings  for Android
    const InitializationSettings initializationSettings =
    InitializationSettings(
      android: AndroidInitializationSettings("@mipmap/ic_launcher"),
    );

    _notificationsPlugin.initialize(
      initializationSettings,
      onSelectNotification: (String? id) async {
        print("onSelectNotification");
        if (id!.isNotEmpty) {
          print("Router Value1234 $id");

          // Navigator.of(context).push(
          //   MaterialPageRoute(
          //     builder: (context) => DemoScreen(
          //       id: id,
          //     ),
          //   ),
          // );

        }
      },
    );
  }
  static void createanddisplaynotification(RemoteMessage message) async {
    try {
      const NotificationDetails notificationDetails = NotificationDetails(
        android: AndroidNotificationDetails(
          "pushnotificationapp",
          "pushnotificationappchannel",
          importance: Importance.max,
          priority: Priority.high,
        ),
      );

      await _notificationsPlugin.show(
        0,
        message.notification!.title,
        message.notification!.body,
        notificationDetails,
        payload: message.data['_id'],
      );
    } on Exception catch (e) {
      print(e);
    }
  }

}