text:
Q: Why is my code giving absurd ouputs that makes no sense? i am new to C and was writing a code that prints the max and min from a array of integers.
Ex:- Input is 1 2 3 4 5, then the output will be min=1+2+3+4=10 and max=2+3+4+5=14. My code is giving output 0 0 instead of 10 14. I just can't figure out why.

#include <stdio.h>

int main()
    {
        int len;
        int max=0,min=0;
        scanf("%d", &len);
        int arr[len];
        for(int i=0;i<len;i++)
            {
                scanf("%d", &arr[i]);
            }
        int cpy;
        for(int i=0;i<len;i++)
            {
                for(int j=i+1;j<len;j++)
                    {
                        if(arr[i]>arr[j])
                            {
                                 cpy = arr[i+1];
                                 arr[i+1]=arr[i];
                                 arr[i]=cpy;
                            }
                    }
            }

        for(int i=0;i<len-1;i++)
            {
                min = min + arr[i];
                max = max + arr[i+1];
            }
        printf("%d %d", min, max);
    }

A: In this part :
if(arr[i]>arr[j])
{
    cpy = arr[i+1];
    arr[i+1]=arr[i];
    arr[i]=cpy;
 }

You compare i and j index , but swap i and i+1 indexes. In your case :

*

*5  1 2 3 4 5 gives 14 10

*5  5 4 3 2 1 gives 13 10

You also should be looping i < len - 1. Even if it works as j loop will not run for i = len - 1, it is always better to avoid unnecessary looping which could lead to undefined behavior.
You may have problem with the declaration of arr (I got error but it may depends on the compiler) . Try allocating it :
#include <stdlib.h>
…..
int *arr = calloc(len, sizeof (*arr));


text:
Q: clean, breakable left-aligned array-like environment The centered, yet left-aligned aspect of \begin{array}{lll} ... \end{array} is what I usually go with to give a list of conditions. My only problem with it, is that it is not breakable, so I try to replace it with \begin{align}... \end{align}-like environments.
The closest result I get is with \begin{flalign*} ...\end{flalign*}. Then I can use \allowdisplaybreaks[2]. But I generally have to play around with &'s to get the "look" I want.
Is there a cleaner way to achieve a breakable left-aligned array-like environment?
Below is a concrete example, comparing the result with both array and flalign.
(Also, as a side question, is it me, or are there some irregularities in the vertical spacing in the flalign version: namely there is more vertical spacing between line 5 and line 6, than between others, because of the subscript at the end of line 6. If so, can I avoid that?)
Thanks for reading!
\documentclass[draft,11pt]{article}
\sloppy

\usepackage{amsmath,amssymb}

\newcommand{\labarrow}[1]{\ensuremath{\overset{#1}{\rightarrow} }}
\newcommand{\N}{\ensuremath{\mathsf{N}}}
\newcommand{\diam}[1]{\ensuremath{\langle #1 \rangle}}
\newcommand{\da}{\mathopen{\downarrow}}
\newcommand{\model}{\mathbb{M}}
\newcommand{\logic}[1]{\textsf{#1}}

\allowdisplaybreaks[2]

\begin{document}

$$
\begin{array}{lll}
\model,w,g \models x & \textup{ iff } & g(x)=w\\
\model,w,g \models \logic{turn}_i & \textup{ iff } & \rho(x)=i\\
\model,w,g \models @_x \phi & \textup{ iff } & g(x)\in|\model| \textup{ and }         \model,g(x),g\models\phi\\
\model,w,g \models \da x.\phi & \textup{ iff } & \model,w,g[g(x):=w]\models\phi\\
\model,w,g \models [!\N_i]\phi & \textup{ iff } & {\model|_{\N_i(w)}},w,g \models \phi\\
\model,w,g \models \diam{\alpha}\phi & \textup{ iff } & \textup{there exists some }v\textup{ with }(w,v)\in||\alpha||^\model\\ & &\textup{and }\model,v,g \models \phi
\end{array}
$$

\begin{flalign*}
&&&\model,w,g \models x && \textup{ iff } && g(x)=w&&\\
&&&\model,w,g \models \logic{turn}_i && \textup{ iff } && \rho(x)=i&&\\
&&&\model,w,g \models @_x \phi && \textup{ iff } && g(x)\in|\model| \textup{ and } \model,g(x),g\models\phi&&\\
&&&\model,w,g \models \da x.\phi && \textup{ iff } && \model,w,g[g(x):=w]\models\phi&&\\
&&&\model,w,g \models [!\N_i]\phi && \textup{ iff } && {\model|_{\N_i(w)}},w,g \models \phi&&\\
&&&\model,w,g \models \diam{\alpha}\phi && \textup{ iff } && \textup{there exists some }v\textup{ with }(w,v)\in||\alpha||^\model&&\\
&&& && &&\textup{and }\model,v,g \models \phi&
\end{flalign*}

\end{document}

A: You want alignat rather than flalign. Note the tabular used for splitting the last item into two lines, so that no page break is taken here and the vertical spacing is better.
\documentclass[draft,11pt]{article}
\usepackage[pass,showframe]{geometry} % just to show page frames
\setlength{\textheight}{5cm} % just to induce a page break
\usepackage{lipsum} % for some text

\usepackage{amsmath,amssymb}

\newcommand{\labarrow}[1]{\overset{#1}{\rightarrow}}
\newcommand{\N}{\mathsf{N}}
\newcommand{\diam}[1]{\langle #1 \rangle}
\newcommand{\da}{\mathopen{\downarrow}}
\newcommand{\model}{\mathbb{M}}
\newcommand{\logic}[1]{\textsf{#1}}

% for the ``iff'' separator
\newcommand{\eiff}{\hspace{1.5em}\textup{iff}\hspace{1.5em}} % adjust the amount

\allowdisplaybreaks[2]

\begin{document}

\lipsum*[2]
\begin{alignat*}{3}
&\model,w,g \models x                 && \eiff &&
  g(x)=w \\
&\model,w,g \models \logic{turn}_i    && \eiff &&
  \rho(x)=i \\
&\model,w,g \models @_x \phi          && \eiff &&
  g(x)\in|\model| \textup{ and } \model,g(x),g\models\phi \\
&\model,w,g \models \da x.\phi        && \eiff &&
  \model,w,g[g(x):=w]\models\phi \\
&\model,w,g \models [!\N_i]\phi       && \eiff &&
  {\model|_{\N_i(w)}},w,g \models \phi \\
&\model,w,g \models \diam{\alpha}\phi && \eiff &&
  \begin{tabular}[t]{@{}l@{}}
  there exists some $v$ with $(w,v)\in||\alpha||^\model$ \\
  and $\model,v,g \models \phi$
  \end{tabular}
\end{alignat*}

\end{document}

A: I would suggest alignat.  Consider
\begin{alignat*}{3}
   &xx &\quad& yy &\quad& zz \\
   &pp && qq && rr
\end{alignat*}

Then each piece of mathematics will be left aligned in its column, and the space between the columns will be given by \quad.  You could adjust this spacing by using other spacing commands, \hspace{1em} will be the same as one quad.

\documentclass[draft,11pt]{article}

\usepackage{amsmath,amssymb}

\newcommand{\labarrow}[1]{\ensuremath{\overset{#1}{\rightarrow} }}
\newcommand{\N}{\ensuremath{\mathsf{N}}}
\newcommand{\diam}[1]{\ensuremath{\langle #1 \rangle}}
\newcommand{\da}{\mathopen{\downarrow}}
\newcommand{\model}{\mathbb{M}}
\newcommand{\logic}[1]{\textsf{#1}}

\allowdisplaybreaks[2]

\begin{document}

\begin{alignat*}{3}
&\model,w,g \models x &\quad& \textup{ iff } &\quad& g(x)=w\\
&\model,w,g \models \logic{turn}_i && \textup{ iff } && \rho(x)=i\\
&\model,w,g \models @_x \phi && \textup{ iff } && g(x)\in|\model| \textup{ and } \model,g(x),g\models\phi\\
&\model,w,g \models \da x.\phi && \textup{ iff } && \model,w,g[g(x):=w]\models\phi\\
&\model,w,g \models [!\N_i]\phi && \textup{ iff } && {\model|_{\N_i(w)}},w,g \models \phi\\
&\model,w,g \models \diam{\alpha}\phi && \textup{ iff } && \textup{there exists some }v\textup{ with }(w,v)\in||\alpha||^\model\\
& && &&\textup{and }\model,v,g \models \phi
\end{alignat*}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to make a validation form to email and password I would like to make a validation of a form. More precisely, I need to ask for my user to fill the form with the following conditions:

*

*email: it must have letters and one @,

*password: it must have letters, numbers and only lower letters.
How can I ask it to my users in JS?

I have here the code for "name" but I don't know which method use to others:
let nome = document.querySelector('#name')
nome.addEventListener('keyup', () =>
    {if(nome.value.length <= 5)
        {nome.setAttribute('style', 'border-color: red')}
    else
        {nome.setAttribute('style', 'border-color: green')}});

Indeed I have been using, now, this code here.
These are the variables:
let nome = document.getElementById('nome');
let nomeCombinaRegex = nome.value.match(/^((\b[A-zÀ-ú']{3,40}\b)\s*){2,}$/);
let nomeVerde = nome.setAttribute('style', 'color:green');
let nomeRed = nome.setAttribute('style', 'color:red');

This is the HTML:

<input id="nome" type="text" required autofocus placeholder="Nome" oninput="nameValidate()">

This is the JS Function:
function nameValidate()
    {if(nomeCombinaRegex)
        {nomeVerde}
    else
        {nomeAlert;
        nomeRed}}

Question:
What am I doing wrong? the code doesn't work (I'm new in JS)

A: Regular expressions can be used to describe strings with certain conditions. For example, you can test your email and password strings as follows:
const emailRegex = /^[A-za-z]+@[A-za-z]+$/
const passwordRegex = /^[a-z0-9]+$/

emailRegex.test(email)
passwordRegex.test(password)

A: the most fun and easy way to solve this issue is using regex, you can play with it here.
Similar question is here , you can create regex according to your need
function matchString() {
  var string = document.querySelector('#name');

  // it matches small and capital alphabeds,
  // if you dont want number remove 0-9
  // this also work for only alphabeds and @ ([a-zA-Z0-9])+@ or ^([a-zA-Z0-9])+\@
  var result = string.match(/^([a-zA-Z0-9_\.\-])+\@/g);
  document.write("Output : " + result);
}

A: Do not simply change the styles. Instead, inform the browser that the input is invalid. This provides a better user experience, especially for people using screen readers.
For email addresses, browsers already have a built-in way to check whether they are valid. For more complex conditions, you can use the pattern attribute or the "input validity" methods.

const email = document.getElementById("email-input");

const pass = document.getElementById("pass-input");
pass.addEventListener("input", (ev) => {
  if (pass.value.match(/\d/) && pass.value.match(/[a-z]/) && !pass.value.match(/[A-Z]/)) {
    pass.setCustomValidity("");
  } else {
    pass.setCustomValidity('"' + pass.value + '" is not a valid password.');
  }
});

const form = document.getElementById("signup-form");
form.addEventListener("submit", (ev) => {
  alert(`Success!\nE-mail: ${email.value}\nPassword: ${pass.value}`);

  // Prevent the navigation
  ev.preventDefault();
});
input:valid {
  border-color: green;
}
input:invalid {
  border-color: red;
}
<form id="signup-form">
  E-mail <input type="email" name="email"  id="email-input" required>

  Password <input type="password" name="pass" id="pass-input" required>

  <button type="submit">Submit</button>
</form>


text:
Q: What does this series converge to? $\sum_{k=0}^n \left(\frac{1}{4k+1}+\frac{1}{4k+3}-\frac{1}{2k+1}\right)$ What does the following expression converge to?
$$\sum_{k=0}^n \left(\frac{1}{4k+1}+\frac{1}{4k+3}-\frac{1}{2k+1}\right)$$
(It looks like this problem)
$\displaystyle\sum_{k=0}^n a_{2k+1}+a_{2k+2}-a_{k+1}$ ;
$\displaystyle\sum_{k=0}^n a_{k+1}$ does not converge.

A: $$\mathop {\lim }\limits_{n \to  + \infty } \sum_{k=0}^n \left(\frac{1}{4k+1}+\frac{1}{4k+3}-\frac{1}{2k+1}\right)=$$
$$=\mathop {\lim }\limits_{n \to  + \infty } \sum_{k=0}^n\left(\frac{1}{4k+1}-\frac{1}{4k+2}\right)-\mathop {\lim }\limits_{n \to  + \infty } \sum_{k=0}^n\left(\frac{1}{4k+2}-\frac{1}{4k+3}\right)=$$
$$=\frac{\pi}{8}+\frac{\ln2}{4}-\left(\frac{\pi}{8}-\frac{\ln2}{4}\right)=\frac{\ln2}{2}.$$

A: @Michael Rozenberg gave the answer by telescoping.
We can also have more than the limit itself since
$$S_n=\sum_{k=0}^n \left(\frac{1}{4k+1}+\frac{1}{4k+3}-\frac{1}{2k+1}\right)=\frac{1}{2} \left(H_{2 n+\frac{3}{2}}-H_{n+\frac{1}{2}}\right)$$ where appear harmonic numbers.
Using the asymptotics
$$H_p=\gamma +\log \left({p}\right)+\frac{1}{2 p}-\frac{1}{12
   p^2}+O\left(\frac{1}{p^3}\right)$$ apply it twice and continue with Taylor series to get
$$S_n=\frac{\log (2)}{2}-\frac{1}{64 n^2}+O\left(\frac{1}{n^3}\right)$$
Computing for $n=5$
$$S_5=\frac{1170028}{3380195}\approx 0.3461$$ while the truncated series gives $0.3459$.

A: We can write the sum like this:
$$\sum_{k=0}^n \left(\frac{1}{4k+1}+\frac{1}{4k+3}-\frac{1}{2k+1}\right)=\sum_{k=0}^n\left(\frac{1}{4k+1}+\frac{1}{4k+2}+\frac{1}{4k+3}+\frac{1}{4k+4}\right)-\sum_{k=0}^n\left(\frac{1}{4k+4}+\frac{3}{2}\left(\frac{1}{2k+1}+\frac{1}{2k+2}-\frac{1}{2k+2}\right)\right)=H_{4n+4}-\frac{1}{4}H_{n+1}-\frac{3}{2}H_{2n+2}+\frac{3}{4}H_{n+1}=H_{4n+4}+\frac{1}{2}H_{n+1}-\frac{3}{2}H_{2n+2}$$
Using $H_n = \ln n+\gamma +\mathcal{E}_n$ with $\mathcal{E}_n \to 0$, we can see that:
$$\lim_{n\to \infty}\sum_{k=0}^n \left(\frac{1}{4k+1}+\frac{1}{4k+3}-\frac{1}{2k+1}\right)=\lim_{n\to \infty} \left(\ln(4n+4)+\frac{1}{2}\ln(n+1)-\frac{3}{2}\ln(2n+2)\right)=\ln \sqrt{2}$$

A: Another way:
$$\sum_{k=0}^{+\infty}\left(\frac{1}{4k+1}+\frac{1}{4k+3}-\frac{1}{2k+1}\right)=$$
$$=\sum_{k=0}^{+\infty}\left(\frac{1}{4k+1}-\frac{1}{4k+2}+\frac{1}{4k+3}-\frac{1}{4k+4}\right)-\sum_{k=0}^{+\infty}\left(\frac{1}{4k+2}-\frac{1}{4k+4}\right)=$$
$$=\ln2-\frac{\ln2}{2}=\frac{\ln2}{2}.$$


text:
Q: C fscanf gets me duplicate lines I'm trying to display the details of each process, by redirecting the output of 'ps' command. I have redirected the ps output to a file. I'm reading from it and displaying the Pid and Command using fscanf. But I see that I get some lines duplicated, and in some cases a negative value for the Pids.
void TR69_DM_GetProcDetails(char *FileName, int32_t *ProcCount, struct ProcessInfo *ProcVar)
{
    char CharBuf[BUF_SIZE] ;
    int32_t i = 0;

    int Pid;
    char Cmd[100];

    FILE *FileDesc;
    FileDesc = fopen (FileName, "r");

    printf("\nFile pointer %ld\n", ftell(FileDesc));
    fscanf (FileDesc, "%[^\n]\n", CharBuf);
    puts(CharBuf);

    printf("\nFile pointer %ld\n", ftell(FileDesc));

    while ( EOF != fscanf (FileDesc, "%*s %lu %*d %*d %*s %*s %*s %s", &Pid, Cmd))
    {
        printf("\n PID is %d and cmd is %s", Pid, Cmd);
    //  i++;
    }

}

and I get the following output sample:

 PID is 2104 and cmd is /usr/lib/indicator-datetime/indicator-datetime-service
 PID is 2107 and cmd is /usr/lib/indicator-messages/indicator-messages-service
 PID is 2114 and cmd is /usr/lib/indicator-session/indicator-session-service
 PID is 2134 and cmd is /usr/lib/geoclue/geoclue-master
 PID is 2142 and cmd is gnome-screensaver
 PID is 2145 and cmd is /usr/lib/gnome-disk-utility/gdu-notification-daemon
 PID is 2342 and cmd is /usr/bin/python
 PID is 2342 and cmd is /usr/bin/python
 PID is 4316 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is -4 and cmd is /sbin/dhclient
 PID is 4444 and cmd is /usr/sbin/ntpd
 PID is 4444 and cmd is /usr/sbin/ntpd
 PID is 4444 and cmd is /usr/sbin/ntpd
 PID is 4444 and cmd is /usr/sbin/ntpd
 PID is 113 and cmd is /usr/sbin/ntpd
 PID is 113 and cmd is /usr/sbin/ntpd
 PID is 5411 and cmd is sshd:
 PID is 5411 and cmd is sshd:
 PID is 5411 and cmd is sshd:
 PID is 5584 and cmd is sshd:
 PID is 5584 and cmd is sshd:
 PID is 5585 and cmd is -bash
 PID is 6790 and cmd is /usr/lib/firefox-4.0.1/firefox-bin
 PID is 7007 and cmd is /usr/lib/firefox-4.0.1/plugin-container
 PID is 7007 and cmd is /usr/lib/firefox-4.0.1/plugin-container
 PID is 7007 and cmd is /usr/lib/firefox-4.0.1/plugin-container
 PID is 6790 and cmd is /usr/lib/firefox-4.0.1/plugin-container
 PID is 6790 and cmd is /usr/lib/firefox-4.0.1/plugin-container
 PID is 6790 and cmd is /usr/lib/firefox-4.0.1/plugin-container
 PID is 7023 and cmd is /usr/lib/nspluginwrapper/i386/linux/npviewer.bin
 PID is 7023 and cmd is /usr/lib/nspluginwrapper/i386/linux/npviewer.bin
 PID is 7023 and cmd is /usr/lib/nspluginwrapper/i386/linux/npviewer.bin
 PID is 7023 and cmd is /usr/lib/nspluginwrapper/i386/linux/npviewer.bin
 PID is 7023 and cmd is /usr/lib/nspluginwrapper/i386/linux/npviewer.bin
 PID is 8390 and cmd is man
 PID is 8390 and cmd is man
 PID is 8402 and cmd is pager
 PID is 8402 and cmd is pager
 PID is 8827 and cmd is ping
 PID is 8827 and cmd is ping
 PID is 8869 and cmd is bash
 PID is 8907 and cmd is bash
 PID is 12637 and cmd is cat
 PID is 12637 and cmd is cat
 PID is 15164 and cmd is tftp
 PID is 15185 and cmd is vim
 PID is 15185 and cmd is vim
 PID is 16827 and cmd is telnet
 PID is 16827 and cmd is telnet
 PID is 17117 and cmd is sshd:
 PID is 17117 and cmd is sshd:
 PID is 17117 and cmd is sshd:
 PID is 17226 and cmd is sshd:
 PID is 17226 and cmd is sshd:
 PID is 17227 and cmd is -sh
 PID is 18120 and cmd is su
 PID is 18127 and cmd is bash
 PID is 18896 and cmd is sshd:
 PID is 18896 and cmd is sshd:
 PID is 18896 and cmd is sshd:
 PID is 19069 and cmd is sshd:
 PID is 19069 and cmd is sshd:
 PID is 19070 and cmd is -sh
 PID is 20313 and cmd is gedit
 PID is 20313 and cmd is gedit
 PID is 20313 and cmd is gedit
 PID is 20334 and cmd is ssh
 PID is 20334 and cmd is ssh
 PID is 20337 and cmd is [kworker/1:1]
 PID is 20341 and cmd is su
 PID is 20349 and cmd is bash
 PID is 20371 and cmd is [kworker/0:1]
 PID is 20375 and cmd is [kworker/0:2]
 PID is 20377 and cmd is [kworker/1:0]
 PID is 21342 and cmd is [kjournald]
 PID is 23384 and cmd is /opt/Adobe/Reader9/Reader/intellinux/bin/acroread
 PID is 23384 and cmd is /opt/Adobe/Reader9/Reader/intellinux/bin/acroread
 PID is 23495 and cmd is gnome-terminal
 PID is 23498 and cmd is gnome-pty-helper
 PID is 23499 and cmd is bash
 PID is 26446 and cmd is ssh
 PID is 26446 and cmd is ssh
 PID is 26733 and cmd is sshd:
 PID is 26733 and cmd is sshd:
 PID is 26843 and cmd is -bash
 PID is 26943 and cmd is sshd:
 PID is 26943 and cmd is sshd:
 PID is 27036 and cmd is sshd:
 PID is 27036 and cmd is sshd:
 PID is 27036 and cmd is sshd:
 PID is 27052 and cmd is /usr/lib/openssh/sftp-server
 PID is 27149 and cmd is sshd:
 PID is 27149 and cmd is sshd:
 PID is 27150 and cmd is -bash
 PID is 27734 and cmd is ssh
 PID is 27734 and cmd is ssh
 PID is 28265 and cmd is bin/TR69_DM
 PID is 0 and cmd is bin/TR69_DM
 PID is 28266 and cmd is ps
 PID is 28266 and cmd is ps
 PID is 29510 and cmd is su
 PID is 29510 and cmd is su
 PID is 29517 and cmd is bash
 PID is 29951 and cmd is minicom
 PID is 30056 and cmd is bash
 PID is 30293 and cmd is bash
 PID is 30329 and cmd is ssh
 PID is 30329 and cmd is ssh
 PID is 30597 and cmd is bash
 PID is 30632 and cmd is ssh
 PID is 30632 and cmd is ssh
 PID is 31508 and cmd is bash

What might have went wrong?

A: fscanf() returns the number of assignments made. Checking against EOF is insufficient as some assignments may have been made and remaining ones not, meaning subsequent code would be processing stale or uninitialized values. The following loop will stop processing at the first line when the format is unexpected and avoid stale values:
while ( 2 == fscanf (FileDesc, "%*s %lu %*d %*d %*s %*s %*s %s", &Pid, Cmd))
{
}

An improved solution would use fgets() to read a line and then use sscanf() to parse the read line. This will allow you to detect EOF and allow multiple attempts to parse the line using different formats:
char line[1024];
while (fgets(line, sizeof(line), stdin))
{
    if (2 == sscanf (line, "%*s %lu %*d %*d %*s %*s %*s %s", &Pid, Cmd))
    {
    }
    else if (2 == sscanf (line, "some-other-format", &Pid, Cmd))
    {
    }
    else
    {
        fprintf(stderr, "Unable to parse '%s'\n", line);
    }
}

Additionally, prevent potential buffer overrun by specifying the maximum number of characters that sscanf() should write to Cmd. This should be one less than the size of Cmd, leaving room for the terminating null character. For example:
if (2 == sscanf(line, "%lu %255s", &Pid, Cmd))


text:
Q: Why won't the Guide leave? I'm making personalised houses for my NPCs, but they have decided to move into the wrong rooms. I've destroyed all the furniture, back walls and regular walls, and they still insist that the single floating blocks are their houses! How do I stop them from staying there?

A: As of the latest update (1.1), there is an NPC UI that allows you to assign living spaces, as well as query a room to see if it is suitable, or why it isn't.

A: When I want to move an NPC to a new house, I do this:

*

*Create the new house and make sure it is the ONLY place that has the comfort items required for a house (Bed, Light source, etc.)

*Remove the bed, lights, chairs, etc. from the NPCs current house.

*Get the NPC stuck in a hole so that a) the NPC cannot leave and b) lava cannot flow out (you can see where this is going :P )

*Get a bucket of lava and dump it in the hole

*The NPC will die and when they come back they should be in their new house

To get rid of the lava after that, you can turn it into obsidian.

A: When their current home becomes unsuitable, the NPCs try to find another home.
This generally involves a teleport. I'm not sure whether they can actually move into a new home by walking to it, but even so, they're not very good at navigating terrain. 3 block drops and jumps are all they can manage.
For obvious reasons, they won't teleport if you're looking at them. Leave them alone for a bit and they should move.


text:
Q: Seems doctrine listener is not fired Got a service which should be executed the moment an object is persisted. Though, I think the code looks like it should work, it doesn't. I configured the service like the following yml.
services:
    bla_orm.listener:
        class: Bla\OrmBundle\EventListener\UserManager
        arguments: [@security.encoder_factory]
        tags:
            - { name: doctrine.event_listener, event: prePersist }

The class:
namespace Bla\OrmBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Bla\OrmBundle\Entity\User;

class UserManager {

        protected $encoderFactory;

        public function __construct(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface $encoderFactory) {
            $this->encoderFactory = $encoderFactory;
        }

        public function prePersist(LifecycleEventArgs $args) {
            $entity = $args->getEntity();

            if ($entity instanceof User) {

                $encoder = $this->encoderFactory ->getEncoder($entity);
                $entity->setSalt(rand(10000, 99999));
                $password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
                $entity->setPassword($password);
            }
        }

    }

Symfony version:
Symfony version 2.3.3 - app/dev/debug

Output of container:debug
[container] Public services
Service Id                                      Scope     Class Name
annotation_reader                               container Doctrine\Common\Annotations\FileCacheReader
assetic.asset_manager                           container Assetic\Factory\LazyAssetManager
assetic.controller                              prototype Symfony\Bundle\AsseticBundle\Controller\AsseticController
assetic.filter.cssrewrite                       container Assetic\Filter\CssRewriteFilter
assetic.filter_manager                          container Symfony\Bundle\AsseticBundle\FilterManager
assetic.request_listener                        container Symfony\Bundle\AsseticBundle\EventListener\RequestListener
cache_clearer                                   container Symfony\Component\HttpKernel\CacheClearer\ChainCacheClearer
cache_warmer                                    container Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerAggregate
data_collector.request                          container Symfony\Component\HttpKernel\DataCollector\RequestDataCollector
data_collector.router                           container Symfony\Bundle\FrameworkBundle\DataCollector\RouterDataCollector
database_connection                             n/a       alias for doctrine.dbal.default_connection
debug.controller_resolver                       container Symfony\Component\HttpKernel\Controller\TraceableControllerResolver
debug.deprecation_logger_listener               container Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener
debug.emergency_logger_listener                 container Symfony\Component\HttpKernel\EventListener\ErrorsLoggerListener
debug.event_dispatcher                          container Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher
debug.stopwatch                                 container Symfony\Component\Stopwatch\Stopwatch
debug.templating.engine.php                     container Symfony\Bundle\FrameworkBundle\Templating\TimedPhpEngine
debug.templating.engine.twig                    n/a       alias for templating
doctrine                                        container Doctrine\Bundle\DoctrineBundle\Registry
doctrine.dbal.connection_factory                container Doctrine\Bundle\DoctrineBundle\ConnectionFactory
doctrine.dbal.default_connection                container stdClass
doctrine.orm.default_entity_manager             container Doctrine\ORM\EntityManager
doctrine.orm.default_manager_configurator       container Doctrine\Bundle\DoctrineBundle\ManagerConfigurator
doctrine.orm.entity_manager                     n/a       alias for doctrine.orm.default_entity_manager
doctrine.orm.validator.unique                   container Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntityValidator
doctrine.orm.validator_initializer              container Symfony\Bridge\Doctrine\Validator\DoctrineInitializer
event_dispatcher                                container Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
file_locator                                    container Symfony\Component\HttpKernel\Config\FileLocator
filesystem                                      container Symfony\Component\Filesystem\Filesystem
form.csrf_provider                              container Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider
form.factory                                    container Symfony\Component\Form\FormFactory
form.registry                                   container Symfony\Component\Form\FormRegistry
form.resolved_type_factory                      container Symfony\Component\Form\ResolvedFormTypeFactory
form.type.birthday                              container Symfony\Component\Form\Extension\Core\Type\BirthdayType
form.type.button                                container Symfony\Component\Form\Extension\Core\Type\ButtonType
form.type.checkbox                              container Symfony\Component\Form\Extension\Core\Type\CheckboxType
form.type.choice                                container Symfony\Component\Form\Extension\Core\Type\ChoiceType
form.type.collection                            container Symfony\Component\Form\Extension\Core\Type\CollectionType
form.type.country                               container Symfony\Component\Form\Extension\Core\Type\CountryType
form.type.currency                              container Symfony\Component\Form\Extension\Core\Type\CurrencyType
form.type.date                                  container Symfony\Component\Form\Extension\Core\Type\DateType
form.type.datetime                              container Symfony\Component\Form\Extension\Core\Type\DateTimeType
form.type.email                                 container Symfony\Component\Form\Extension\Core\Type\EmailType
form.type.entity                                container Symfony\Bridge\Doctrine\Form\Type\EntityType
form.type.file                                  container Symfony\Component\Form\Extension\Core\Type\FileType
form.type.form                                  container Symfony\Component\Form\Extension\Core\Type\FormType
form.type.hidden                                container Symfony\Component\Form\Extension\Core\Type\HiddenType
form.type.integer                               container Symfony\Component\Form\Extension\Core\Type\IntegerType
form.type.language                              container Symfony\Component\Form\Extension\Core\Type\LanguageType
form.type.locale                                container Symfony\Component\Form\Extension\Core\Type\LocaleType
form.type.money                                 container Symfony\Component\Form\Extension\Core\Type\MoneyType
form.type.number                                container Symfony\Component\Form\Extension\Core\Type\NumberType
form.type.password                              container Symfony\Component\Form\Extension\Core\Type\PasswordType
form.type.percent                               container Symfony\Component\Form\Extension\Core\Type\PercentType
form.type.radio                                 container Symfony\Component\Form\Extension\Core\Type\RadioType
form.type.repeated                              container Symfony\Component\Form\Extension\Core\Type\RepeatedType
form.type.reset                                 container Symfony\Component\Form\Extension\Core\Type\ResetType
form.type.search                                container Symfony\Component\Form\Extension\Core\Type\SearchType
form.type.submit                                container Symfony\Component\Form\Extension\Core\Type\SubmitType
form.type.text                                  container Symfony\Component\Form\Extension\Core\Type\TextType
form.type.textarea                              container Symfony\Component\Form\Extension\Core\Type\TextareaType
form.type.time                                  container Symfony\Component\Form\Extension\Core\Type\TimeType
form.type.timezone                              container Symfony\Component\Form\Extension\Core\Type\TimezoneType
form.type.url                                   container Symfony\Component\Form\Extension\Core\Type\UrlType
form.type_extension.csrf                        container Symfony\Component\Form\Extension\Csrf\Type\FormTypeCsrfExtension
form.type_extension.form.http_foundation        container Symfony\Component\Form\Extension\HttpFoundation\Type\FormTypeHttpFoundationExtension
form.type_extension.form.validator              container Symfony\Component\Form\Extension\Validator\Type\FormTypeValidatorExtension
form.type_extension.repeated.validator          container Symfony\Component\Form\Extension\Validator\Type\RepeatedTypeValidatorExtension
form.type_extension.submit.validator            container Symfony\Component\Form\Extension\Validator\Type\SubmitTypeValidatorExtension
form.type_guesser.doctrine                      container Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser
form.type_guesser.validator                     container Symfony\Component\Form\Extension\Validator\ValidatorTypeGuesser
fragment.handler                                container Symfony\Component\HttpKernel\Fragment\FragmentHandler
fragment.listener                               container Symfony\Component\HttpKernel\EventListener\FragmentListener
fragment.renderer.hinclude                      container Symfony\Bundle\FrameworkBundle\Fragment\ContainerAwareHIncludeFragmentRenderer
fragment.renderer.inline                        container Symfony\Component\HttpKernel\Fragment\InlineFragmentRenderer
http_kernel                                     container Symfony\Component\HttpKernel\DependencyInjection\ContainerAwareHttpKernel
kernel                                          container
locale_listener                                 container Symfony\Component\HttpKernel\EventListener\LocaleListener
logger                                          container Symfony\Bridge\Monolog\Logger
mailer                                          n/a       alias for swiftmailer.mailer.default
monolog.handler.chromephp                       container Symfony\Bridge\Monolog\Handler\ChromePhpHandler
monolog.handler.debug                           container Symfony\Bridge\Monolog\Handler\DebugHandler
monolog.handler.firephp                         container Symfony\Bridge\Monolog\Handler\FirePHPHandler
monolog.handler.main                            container Monolog\Handler\StreamHandler
monolog.logger.deprecation                      container Symfony\Bridge\Monolog\Logger
monolog.logger.doctrine                         container Symfony\Bridge\Monolog\Logger
monolog.logger.emergency                        container Symfony\Bridge\Monolog\Logger
monolog.logger.event                            container Symfony\Bridge\Monolog\Logger
monolog.logger.profiler                         container Symfony\Bridge\Monolog\Logger
monolog.logger.request                          container Symfony\Bridge\Monolog\Logger
monolog.logger.router                           container Symfony\Bridge\Monolog\Logger
monolog.logger.security                         container Symfony\Bridge\Monolog\Logger
monolog.logger.templating                       container Symfony\Bridge\Monolog\Logger
profiler                                        container Symfony\Component\HttpKernel\Profiler\Profiler
profiler_listener                               container Symfony\Component\HttpKernel\EventListener\ProfilerListener
property_accessor                               container Symfony\Component\PropertyAccess\PropertyAccessor
request                                         request
response_listener                               container Symfony\Component\HttpKernel\EventListener\ResponseListener
router                                          container Symfony\Bundle\FrameworkBundle\Routing\Router
router_listener                                 container Symfony\Component\HttpKernel\EventListener\RouterListener
routing.loader                                  container Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader
security.context                                container Symfony\Component\Security\Core\SecurityContext
security.encoder_factory                        container Symfony\Component\Security\Core\Encoder\EncoderFactory
security.firewall                               container Symfony\Component\Security\Http\Firewall
security.firewall.map.context.dev               container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.firewall.map.context.login             container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.firewall.map.context.rest              container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.firewall.map.context.secured_area      container Symfony\Bundle\SecurityBundle\Security\FirewallContext
security.rememberme.response_listener           container Symfony\Component\Security\Http\RememberMe\ResponseListener
security.secure_random                          container Symfony\Component\Security\Core\Util\SecureRandom
security.validator.user_password                container Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator
sensio.distribution.webconfigurator             n/a       alias for sensio_distribution.webconfigurator
sensio_distribution.webconfigurator             container Sensio\Bundle\DistributionBundle\Configurator\Configurator
sensio_framework_extra.cache.listener           container Sensio\Bundle\FrameworkExtraBundle\EventListener\CacheListener
sensio_framework_extra.controller.listener      container Sensio\Bundle\FrameworkExtraBundle\EventListener\ControllerListener
sensio_framework_extra.converter.datetime       container Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DateTimeParamConverter
sensio_framework_extra.converter.doctrine.orm   container Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\DoctrineParamConverter
sensio_framework_extra.converter.listener       container Sensio\Bundle\FrameworkExtraBundle\EventListener\ParamConverterListener
sensio_framework_extra.converter.manager        container Sensio\Bundle\FrameworkExtraBundle\Request\ParamConverter\ParamConverterManager
sensio_framework_extra.view.guesser             container Sensio\Bundle\FrameworkExtraBundle\Templating\TemplateGuesser
sensio_framework_extra.view.listener            container Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener
service_container                               container
session                                         container Symfony\Component\HttpFoundation\Session\Session
session.handler                                 container Symfony\Component\HttpFoundation\Session\Storage\Handler\NativeFileSessionHandler
session.storage                                 n/a       alias for session.storage.native
session.storage.filesystem                      container Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage
session.storage.native                          container Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage
session.storage.php_bridge                      container Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage
session_listener                                container Symfony\Bundle\FrameworkBundle\EventListener\SessionListener
streamed_response_listener                      container Symfony\Component\HttpKernel\EventListener\StreamedResponseListener
swiftmailer.email_sender.listener               container Symfony\Bundle\SwiftmailerBundle\EventListener\EmailSenderListener
swiftmailer.mailer                              n/a       alias for swiftmailer.mailer.default
swiftmailer.mailer.default                      container Swift_Mailer
swiftmailer.mailer.default.plugin.messagelogger container Swift_Plugins_MessageLogger
swiftmailer.mailer.default.spool                container Swift_FileSpool
swiftmailer.mailer.default.transport            container Swift_Transport_SpoolTransport
swiftmailer.mailer.default.transport.real       container Swift_Transport_EsmtpTransport
swiftmailer.plugin.messagelogger                n/a       alias for swiftmailer.mailer.default.plugin.messagelogger
swiftmailer.spool                               n/a       alias for swiftmailer.mailer.default.spool
swiftmailer.transport                           n/a       alias for swiftmailer.mailer.default.transport
swiftmailer.transport.real                      n/a       alias for swiftmailer.mailer.default.transport.real
templating                                      container Symfony\Bundle\TwigBundle\Debug\TimedTwigEngine
templating.asset.package_factory                container Symfony\Bundle\FrameworkBundle\Templating\Asset\PackageFactory
templating.filename_parser                      container Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser
templating.globals                              container Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables
templating.helper.actions                       container Symfony\Bundle\FrameworkBundle\Templating\Helper\ActionsHelper
templating.helper.assets                        request   Symfony\Component\Templating\Helper\CoreAssetsHelper
templating.helper.code                          container Symfony\Bundle\FrameworkBundle\Templating\Helper\CodeHelper
templating.helper.form                          container Symfony\Bundle\FrameworkBundle\Templating\Helper\FormHelper
templating.helper.logout_url                    container Symfony\Bundle\SecurityBundle\Templating\Helper\LogoutUrlHelper
templating.helper.request                       container Symfony\Bundle\FrameworkBundle\Templating\Helper\RequestHelper
templating.helper.router                        container Symfony\Bundle\FrameworkBundle\Templating\Helper\RouterHelper
templating.helper.security                      container Symfony\Bundle\SecurityBundle\Templating\Helper\SecurityHelper
templating.helper.session                       container Symfony\Bundle\FrameworkBundle\Templating\Helper\SessionHelper
templating.helper.slots                         container Symfony\Component\Templating\Helper\SlotsHelper
templating.helper.translator                    container Symfony\Bundle\FrameworkBundle\Templating\Helper\TranslatorHelper
templating.loader                               container Symfony\Bundle\FrameworkBundle\Templating\Loader\FilesystemLoader
templating.name_parser                          container Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser
translation.dumper.csv                          container Symfony\Component\Translation\Dumper\CsvFileDumper
translation.dumper.ini                          container Symfony\Component\Translation\Dumper\IniFileDumper
translation.dumper.mo                           container Symfony\Component\Translation\Dumper\MoFileDumper
translation.dumper.php                          container Symfony\Component\Translation\Dumper\PhpFileDumper
translation.dumper.po                           container Symfony\Component\Translation\Dumper\PoFileDumper
translation.dumper.qt                           container Symfony\Component\Translation\Dumper\QtFileDumper
translation.dumper.res                          container Symfony\Component\Translation\Dumper\IcuResFileDumper
translation.dumper.xliff                        container Symfony\Component\Translation\Dumper\XliffFileDumper
translation.dumper.yml                          container Symfony\Component\Translation\Dumper\YamlFileDumper
translation.extractor                           container Symfony\Component\Translation\Extractor\ChainExtractor
translation.extractor.php                       container Symfony\Bundle\FrameworkBundle\Translation\PhpExtractor
translation.loader                              container Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader
translation.loader.csv                          container Symfony\Component\Translation\Loader\CsvFileLoader
translation.loader.dat                          container Symfony\Component\Translation\Loader\IcuResFileLoader
translation.loader.ini                          container Symfony\Component\Translation\Loader\IniFileLoader
translation.loader.mo                           container Symfony\Component\Translation\Loader\MoFileLoader
translation.loader.php                          container Symfony\Component\Translation\Loader\PhpFileLoader
translation.loader.po                           container Symfony\Component\Translation\Loader\PoFileLoader
translation.loader.qt                           container Symfony\Component\Translation\Loader\QtFileLoader
translation.loader.res                          container Symfony\Component\Translation\Loader\IcuResFileLoader
translation.loader.xliff                        container Symfony\Component\Translation\Loader\XliffFileLoader
translation.loader.yml                          container Symfony\Component\Translation\Loader\YamlFileLoader
translation.writer                              container Symfony\Component\Translation\Writer\TranslationWriter
translator                                      n/a       alias for translator.default
translator.default                              container Symfony\Bundle\FrameworkBundle\Translation\Translator
twig                                            container Twig_Environment
twig.controller.exception                       container Symfony\Bundle\TwigBundle\Controller\ExceptionController
twig.exception_listener                         container Symfony\Component\HttpKernel\EventListener\ExceptionListener
twig.loader                                     container Symfony\Bundle\TwigBundle\Loader\FilesystemLoader
twig.translation.extractor                      container Symfony\Bridge\Twig\Translation\TwigExtractor
uri_signer                                      container Symfony\Component\HttpKernel\UriSigner
bla_orm.listener                                container Bla\OrmBundle\EventListener\UserManager
validator                                       container Symfony\Component\Validator\Validator
web_profiler.controller.exception               container Symfony\Bundle\WebProfilerBundle\Controller\ExceptionController
web_profiler.controller.profiler                container Symfony\Bundle\WebProfilerBundle\Controller\ProfilerController
web_profiler.controller.router                  container Symfony\Bundle\WebProfilerBundle\Controller\RouterController
web_profiler.debug_toolbar                      container Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener

Update
It seems that the listener is not invoked when an updateAction, generated by generate:doctrine:crud has taken place though. At another part of the code the lister seems to be invoked. Though, there are both Controller types and both us $em->persist($something); $em->flush(); to save the changes. I would expect that in both cases the listener is invoked.

A: Based on your response to my comment here is the answer:
The Lifecycle Events section in doctrine documentation states that prePersist only triggers when an insert occures and not an update. Try using same method but with both prePersist and preUpdate events
Refference: http://docs.doctrine-project.org/en/latest/reference/events.html#lifecycle-events

A: Change your service to this:
services:
    bla_orm.listener:
        class: Bla\OrmBundle\EventListener\UserManager
        arguments: [@security.encoder_factory]
        tags:
        - { name: doctrine.event_listener, event: prePersist }
        - { name: doctrine.event_listener, event: preUpdate }

And change your listener to this:
namespace Bla\OrmBundle\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Bla\OrmBundle\Entity\User;

class UserManager {

    protected $encoderFactory;

    public function __construct(\Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface $encoderFactory) {
        $this->encoderFactory = $encoderFactory;
    }

    public function prePersist(LifecycleEventArgs $args) {
        $this->generatePassword($args);
    }

    public function preUpdate(LifecycleEventArgs $args) {
        $this->generatePassword($args);
    }

    public function generatePassword(LifecycleEventArgs $args) {
        $entity = $args->getEntity();

        if ($entity instanceof User) {

            $encoder = $this->encoderFactory ->getEncoder($entity);
            $entity->setSalt(rand(10000, 99999));
            $password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
            $entity->setPassword($password);
        }
    }

}

You probably need an extra check, cause I think you don't want to change the password on every update.


text:
Q: Adding "et al." in natbib with five authors if the citation has more than five authors? In our publishment regulations, there is an instruction for citations as follows:

*

*All authors should be included in reference lists unless there are 6 or more, in which case only the first 5 should be given,
followed by et al. (not italicized)

I currently have a citation with 6 authors (with lastnames A, B, C, D, E, F). By using natbib & chicago as bibliography style (it's also the same with plainnat), when I cite it with citet*{paper1}, I get the following output:
"... methodology A, B, C, D, and F [26]. As ..."
which is close but not exactly what the instruction wants.
Expected output is:
"... methodology A, B, C, D, and E et al. [26]. As ..."
There are two problems here,

*

*It includes F (last author's surname) where the instruction dictates E to be used. Here, we need to explicitly put a cut-off on the 5th author, and printing 5th last-name as the last one in citation.

*There is no "et al." in the citation.

For the 2nd problem I can just put "et al." afterwards basically, this's a sort of work around I think of, which would yield the following,
"... methodology A, B, C, D, and F [26] et al. As ...", which would be kind of ugly.
For the 1st problem, I am not sure about how the authors should be in order for this, any suggestion for that is also appreciated.
If there are bibliography styles (afaik there is not by searching a while) supports this automatically or with a little modification, it would be great.

A: Thanks for clarifying that the formatting requirement pertains to both the formatted items in the bibliography and to citation call-outs.
I suggest you proceed as follows:

*

*Make a copy of your main bib file; if the bib file's name is (say), references.bib, call the copy something like references-trunc5.bib.

*Open the file references-trunc5.bib in an editor; the program you use to create and edit tex files will do fine.

*Hopefully, the bib file doesn't contain too many entries with more than 5 authors (or editors). Find these entries and replace name6 and beyond with and others. E.g., change
author = "A and B and C and D and E and F and G and H and I and J and K"

to
author = "A and B and C and D and E and others"

Importantly, do not change anything else about the bib entries in question. In particular, don't change the citation "keys" of the entries.

*Save the bib file in a directory that's searched by BibTeX.

*In the main tex file, change the instruction
\bibliography{references}

to
\bibliography{references-trunc5}

*Finally, perform a complete recompile cycle -- LaTeX, BibTeX, and LaTeX twice more -- to fully propagate the changes.
Two final comments:

*

*Unless you have a very good reason to use \citet*, I think you're better off using  \citet.

*Things would be even easier if you could use biblatex, as you wouldn't have to change the bib file. All you'd have to do is set the option maxnames=5.

A full MWE (minimum working example) and its output:

\documentclass{article}
\begin{filecontents}[overwrite]{references-trunc5.bib}
@misc{abcdefghijk,
      author = "A and B and C and D and E and others",
      title  = "Thoughts",
      year = 3001
     }
\end{filecontents}

\usepackage[authoryear, round]{natbib}
\bibliographystyle{plainnat} % or some other suitable bib style

\begin{document}
\noindent
\citet*{abcdefghijk}. \citet{abcdefghijk}.
\bibliography{references-trunc5}
\end{document}


text:
Q: Move UITableViewCell Hi everyone I am a newbie to iOS.
I have implemented a UITableView with 3 sections in  UITableViewController. And I have displayed the section rows to each section.
 - (void)viewDidLoad
  {
    [super viewDidLoad];

    self.clearsSelectionOnViewWillAppear = NO;

    self.navigationItem.rightBarButtonItem = self.editButtonItem;

sectionTittle=[[NSMutableArray alloc]initWithObjects:@"Real Madrid",@"Barcelona",@"Liverpool", nil];
firstSection=[[NSMutableArray alloc]initWithObjects:@"Cr7",@"Garath Bale",@"Pepe",
              nil];
secondSection=[[NSMutableArray alloc]initWithObjects:@"Lionel Messi",@"Neymar",@"Pique",
              nil];
thirdSection=[[NSMutableArray alloc]initWithObjects:@"Gerrard",@"Saurez",@"Lallana",
               nil];

       }

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return sectionTittle.count;
  }

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

if(section==0)
{
  return [firstSection count];
}
if(section==1)
{
    return [secondSection count];
}
if(section==2)
{
    return [thirdSection count];
}
return 0;

  }

     - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hi" forIndexPath:indexPath];

cell.textLabel.textColor=[UIColor brownColor];

if (indexPath.section == 0)
{
    cell.textLabel.text=[firstSection objectAtIndex:indexPath.row];

}

if (indexPath.section == 1)
{
    cell.textLabel.text = [secondSection objectAtIndex:indexPath.row];
}
if (indexPath.section == 2)
{
    cell.textLabel.text = [thirdSection objectAtIndex:indexPath.row];
}

// Configure the cell...
     return cell;
    }

     - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  {

 return [sectionTittle objectAtIndex:section];
  }

  - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
  }

Now my output looks like this:

I want to move the rows between the these 3 sections. How can I do it..? While I try doing it the row moves between the section, but while saving it creates a problem.
How can i go through it..?
Thanks

A: Use This Code
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{
    NSMutableArray *arrayTemp=[arrayMain objectAtIndex:sourceIndexPath.row];
    [arrayVisibleCountryList removeObjectAtIndex:sourceIndexPath.row];
    [arrayVisibleCountryList insertObject:arrayTemp atIndex:destinationIndexPath.row];
}
- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
    //Uncomment these lines to enable moving a row just within it's current section
    if ([sourceIndexPath section] != [proposedDestinationIndexPath section])
    {
        proposedDestinationIndexPath = sourceIndexPath;
    }

    return proposedDestinationIndexPath;
}

A: You can use below tableView method. It moves your cell from sourceIndexPath to destinationIndexPath.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;

A: You need to utilise UITableView re-ordering capacity. The cells can be re-ordered across sections.
To enable re-ordering mode:
[self.tableView setEditing:TRUE animated:TRUE];

This enables the TableView in editing mode which includes enables deletion mode along with re-ordering. If you do not want the deletion mode implement:
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewCellEditingStyleNone;

}
The re-order support accessory view is shown if you have implemented moveRowAtIndexPath like, for your case:
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath
{

// Logic to change data source
NSMutableArray *deleteFrom = [self getDataSourceArrayFromIndexPath:sourceIndexPath];
NSMutableArray *addTo = [self getDataSourceArrayFromIndexPath:destinationIndexPath];
[addTo insertObject:[deleteFrom objectAtIndex:sourceIndexPath.row] atIndex:destinationIndexPath.row];
[deleteFrom removeObjectAtIndex:sourceIndexPath.row];

}

where getDataSourceArrayFromIndexPath is:
-(NSMutableArray*) getDataSourceArrayFromIndexPath:(NSIndexPath*) index
{
switch (index.section) {
    case 0:
        return self.firstSection;
        break;
    case 1:
        return self.secondSection;
        break;
    case 2:
        return self.thirdSection;
        break;
    default:
        break;
}
return nil;
}


text:
Q: Maximum integer value for a variable in NetLogo I'm trying to increment an agent property on each tick in the "go" procedure. But it will not increment after some value above 10000's.

*

*What could be the issue? Is my code wrong?

*What is the maximum value that can hold by a variable?

to go
  ask people with [diagnosis = "infected" and tested? = true] [
    set infected-time infected-time + 1
  ]
  ask people with [infected-time > 80000] [
    set color white
    set infected-time 0
  ]
  ......
  ......
  tick
end


text:
Q: Libc6 problem in Ubuntu Mate 21.04 I have updated ubuntu from 20.10 to 21.04
apt says that the version of  package libc6 is 2.33, but in folder /usr/lib/x86_64-linux-gnu/  there is only libc-2.32.so.
I have tried to reinstall with apt, then manually with dpkg but I obtained no results.
The problem is that some programs do not work (i.e. R) because they explicitely request version 2.33 of libc6.
What can I do?


text:
Q: How to kill a process and keep it killed so it cannot come back? So hello AU :D
I've been playing some TF2 and on a lot of servers there are ads (video ads) and they loop it and it goes on forever.
I've been told that you can mute/destroy the ads if you kill the process it stops the ad. The process is steamwebhelper and that's the ad, its in the background, I try to kill the process, it does work for a little bit then it will come back. And then I have to kill it again and so on...
Is there anyway too keep a process killed so it cannot come back again?
I'm aware that the steam web helper also shows deals on games and such but I really don't need any of that, I just want to play without the ads and the pop ups.
If any other information is needed please ask :D
I am running Ubuntu 14.04

A: Maybe you can use my method. Each time when i want end all game and steam, I use this command.
pkill -9 -f steam


text:
Q: Alias of awk command - too many quotes Probably missing something simple here but I am not a shell scripting expert.
I have a local command that works perfectly.
tail -f /path/to/file | awk '
  /INFO/ {print "\033[32m" $0 "\033[39m"}
  /ERROR/ {print "\033[31m" $0 "\033[39m"}
  /WARNING/ {print "\033[33m" $0 "\033[39m"}
'

If I ssh into my boxes and paste it in, it works well.  But I can't seem to alias it because it's already using both kinds of quotes, so alias='...' won't work.  I've also tried making it into a function:
function tailMyFile {
    tail -f /path/to/file | awk '
    /INFO/ {print "\033[32m" $0 "\033[39m"}
    /ERROR/ {print "\033[31m" $0 "\033[39m"}
    /WARNING/ {print "\033[33m" $0 "\033[39m"}';
}

Which tells me: -bash: /INFO/: No such file or directory

A: try this way of function declaration:
tailMyFile() {
    tail -f /path/to/file | awk '
    /INFO/ {print "\033[32m" $0 "\033[39m"}
    /ERROR/ {print "\033[31m" $0 "\033[39m"}
    /WARNING/ {print "\033[33m" $0 "\033[39m"}';
}

However, it seems as though your error is not pertaining to how the functions is defined, but whether your /INFO/ directory is properly seen, can you cd /INFO without any problems?


text:
Q: If $\lim x_n=x$ and $x>0$, prove that there exists a natural number $M$ such that $x_n>0$ for all $n \geq M$ If $\lim x_n=x$ and $x>0$, prove that there exists a natural number $M$ such that $x_n>0$ for all $n \geq M$
I have tried to write down the definition of $\lim x_n=x$ which is
$$\forall \epsilon>0, \exists N\in\mathbb{N} \text{ st }\forall n\geq N,|x_n-x|<\epsilon$$
But I have no idea how to relate it to the consequent.

A: Let $\epsilon = \frac{x}{2}$.
Pick $N \in \mathbb{N}$ such that for $n \geq N$, we have
$$ |x_n - x| < \epsilon $$
$$ x - x_n \leq |x_n - x| < \epsilon = \frac{x}{2} $$
$$ x_n > x - \frac{x}{2} = \frac{x}{2} > 0$$

A: Well, as you said,
$$\lim x_n=x \iff
\forall \epsilon>0, \exists N\in\mathbb{N} \text{ s.t. }\forall n\geq N,|x_n-x|<\epsilon.$$
So, for example, with $\epsilon = \frac{x}{2}$ you have :
$$ \exists M\in\mathbb{N} \text{ s.t. }\forall n\geq N, 0<\frac{x} {2}<x_n<\frac{3x}{2}.$$


text:
Q: Get request is not fulfilling Angular-Express I'm new to MEAN stack I want to have data fetch from express server (which I created with mongodb) when I click button, the function on button click was executed but request was not fulfilled, the database, server all running fine, I just got nothing at console, here are my client and server files:

*

*client(running on http://localhost:3001)

*Imported modules and added to imports in ngModule

import { Http , Headers, HttpModule, Response, RequestOptions } from "@angular/http";

Injected in constructor as service,  then:
template:
<button md-button class="button1" (click)="newQues()">Submit</button>

In class:
newQues(){

  this.http.get('https://localhost:3000/')
                .map(this.extractData)
                .catch(this.handleError);  //these copied from angular2
                                           //official documentation
}

private extractData(res: Response) {
let body = res.json();
console.log(body);  //not getting console nor error
return body.data || { };
}

server running on port 3000
app.get('/', function (req, res) {

   model.findOne({ id: 1}, function (err, data) {
   if (err) {
   console.log(err)
   } else {
   console.log(data);
   res.send(data);
}
})

getting these error when requesting
the whole server code:
import * as express from "express";
var app = express();
import * as path from "path";
import * as mongoose from "mongoose";
import * as lodash from "lodash";
import * as morgan from "morgan";

app.use(express.static(path.join(__dirname, "./../client")));

var uriString = 'mongodb://localhost/quizapp';
mongoose.connect(uriString, function (err, res) {
if (err) {
console.log("Error occured while establishing connection " + err);
} else {
console.log("Connection successful ");
}
})

var schema = new mongoose.Schema({     //schema
question: String,
id: Number
})

var quizz = mongoose.model('Quiz', schema);  //creating model

var firstDoc = new quizz({
question: 'question 1',
id: 1
})
var secondDoc = new quizz({
question: 'question 2',
id: 2
})

var question_data = [firstDoc, secondDoc];

quizz.insertMany(question_data, function (err, res) {
if (err) {
console.log("Error occured while saving document object " + err)
} else {
console.log("Data Saved Successful");
}
})

app.get('/data', function(req, res) {
quizz.findOne({ id: 1}, function (err, data) {
 if (err) {
   console.log(err)
 } else {
   console.log(data);
   res.send(data);   //res.json
 }
 })
 })

when I'm routing to localhost:3000/data the data from database displayed on window but when requesting that route from client(see client side code this.http.get) error occurring(picture attached)

A: for extracting data you have to subscribe to it. try this way
export class SimpleHTTPComponent {
      data: Object;
      loading: boolean;

      constructor(public http: Http) {
      }

      makeRequest(): void {
        this.loading = true;
        this.http.request('http://jsonplaceholder.typicode.com/posts/1')
          .subscribe((res: Response) => {
            this.data = res.json();
            this.loading = false;
          });
      }
    }

and i think you are not using this with body. your console.log should be like this. console.log(this.body);


text:
Q: How to add shadow to an arc on hover? (Chart.js v3.9.1) When I tried to create a custom plugin, it always changed the shadow of the entire chart. How can I only change the specific arc? Thank you.
I want to add shadow to an arc on hover.
Something like this


text:
Q: How to check if last k commands ran successfully I am running a couple of bash commands and want to check if all of them ran successfully at the end. How should I go about this?
This is what I tried.
$ man # command 1 with exit status 1
What manual page do you want?

$ res1=$? # command 2 with exit status 0
# this also stores exit code of previous code i.e 1

$ res2=$? # storing exit code of previous command i.e 0

# Now I want to check if all previous commands worked fine with their exit codes
$ echo $res1 && $res
1
0: command not found

What is incorrect with my current approach. Or What should be the right thing to do? Is there a better way to generalize it for last k commands.

Thanks in advance.

A: I had some problems as this too
id solve my problem in this way
first, I wrote a function that checks the status of the command I run in my script

function show_process_status() {
    if [ $? == 0 ]; then
        echo $1
    else
        echo $2
        break
    fi
}

then in my script, I call this function after any command that I run, for example :
function update_system (){
    echo "start updating system"
    sudo apt-get update -y
    show_process_startus "repos updated successful" "An error occurred on updating repos"
    if [[ $1 == "full" ]]; then
        sudo apt-get dist-upgrade -y
        show_process_startus "system updated successful" "An error occurred on updating systems"
    elif [[ $1 == "fix" ]]; then
        sudo apt-get update --fix-missing
        show_process_startus "update fix missing successful" "An error occurred on fix missing"
        sudo apt-get update
    fi
}

in the show_process_status function I get two-argument the first one is printed when the code run and exits successfully and the second one is used when the command exit is unsuccessful.


text:
Q: results page in search center (sharepoint online): is the refiner parameter Site so long that it overlaps? Is there someone here that can tell me if in their non branded (not formatted) Results page in the sharepoint.com/search site collection if you add as a refiner the Site collection url (I think it is called Site) the url is usually too long and it overlaps with the results on the page?
For tenants of O365 the beginning of the URL is always
https://tenant.sharepoint.com...
In my case tenant is already 13 letters.
If it overlaps with the results, what is the best approach to make it better?
Have it wrap with Css? shorten the https://tenant to ...? Use a smaller font?


text:
Q: componentWillReceiveProps and callback issues I've got a big issue - probably a lack of understanding - in React. I've got a child component that makes a callback and has a componentWillReceiveProps function. The issue is that I cannot write on the text input the child is holding. I'll explain myself better in code.
The problem
I have a child with a text input. That child is inside his parent.
I need to:

*

*Type manually on the text input.

*Notify the parent that the text was changed.

*Modify the input from the parent under certain circumstances.

The child
Has a text prop for the text to display.
textChanged is the callback the parent will suscribe to.
The parent
Contains the child, has a function for the child's callback that does not update the child's state and holds a button to modify the child's text.
The issue
If I write text into the input, it doesn't work well.
If I remove the callback calling in the child (the this.props.textChanged(event.target.value); part) the input works well but the parent doesn't receive child updates.
If I remove the componentWillReceiveProps part, I cannot update the child's text from his parent.
You can play with the code snippet - it "works".

The question
How can I achieve the desired behaviour? Is my aim wrong?
Thanks in advance!

A: Not exactly sure of what you're trying to do, but I'd get your Parent component to choreograph the rules and handle events like text change and button clicks, just letting the Child component be effectively 'dumb', concentrating on rendering its data.
As an example, I've implemented this here
as you will see, most of the lifecycle methods in the Child component can be removed. Now if you need to apply any 'business logic' to amend what has been typed in, you can do this in the controlling Parent component's handleTextChange function (say, convert to upper case and set the state).
This container pattern is very common and idiomatic in React:
https://medium.com/@learnreact/container-components-c0e67432e005#.jg5yiorko


text:
Q: Cannot create dynamically img via javascript I try to create img element via javascript and set it into td element, but id doesn't work. I can't see any image or icon that img is not found. My server is running on localhost now so that's the reason for img url
function fillTable(actualMarkers){
        // Get array of classes without jQuery
        var theTable = document.createElement('table');
        theTable.id = 'actualPlaces';
        // Note, don't forget the var keyword!
        for (var i = 0, tr, tdName, tdId, tdImage, imgPlace ; i < actualMarkers.length; i++) {
            tr = document.createElement('tr');
            tdId = document.createElement('td');
            tdImage = document.createElement('td');
            tdName = document.createElement('td');
            imgPlace = document.createElement('img');
            imgPlace.src = 'http://localhost:8080/webapp/images/var/webapp/photos/small/tuc.png';
            imgPlace.height = '20';
            imgPlace.width = '20';
            var marker = actualMarkers[i];
            tdId.appendChild(document.createTextNode(marker.get("id")));
            tdId.className = 'unvisible';
            tdImage.appendChild(imgPlace);
            tdName.appendChild(document.createTextNode(marker.get("name")));
            tr.appendChild(tdId);
            tr.appendChild(tdImage);
            tr.appendChild(tdName);
            theTable.appendChild(tr);
        }

        document.getElementById('foundPlaces').appendChild(theTable);
        addRowHandlers();
    }

A: Usually the src attribute look like :
 imgPlace.src = 'photos/small/tuc.png';

Try to change your images path, but I think it's very strange have two time "webapp" in your src url.


text:
Q: IBM Worklight - App displays properly in browser but not when previewing in the MBS I am writing a Worklight Hybrid application and utilizing jQuery Mobile in it.
The HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
            <link rel="shortcut icon" href="images/favicon.png">
            <link rel="apple-touch-icon" href="images/apple-touch-icon.png">

            <link rel="stylesheet" href="jqueryMobile/jquery/jquery.mobile-1.3.1.css">
            <link rel="stylesheet" href="css/itemDetails.css">

Item Details

The CSS:
@CHARSET "UTF-8";

#itemDetailsNavBar
{
    background: #ffb400 !important;
    height: 44px;
    padding-top: 20px;
}

#listButtonLeft {
    background: transparent url("images/list.png");
    box-shadow: none;
    data-corners :"false";
    margin-top: 19px;
    border: none;
}

#editButtonRight {
    background: transparent url("images/edit.png");
    box-shadow: none;
    data-corners :"false";
    margin-top: 15px;
    border: none;
}

When previewing in a browser I see it properly:

But when previewing via Worklight Console's MBS, this is what I am getting:

A: I removed the CSS from the head and added it just before the body end tag and everything seems to work fine both in simulator and the MBS.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">

Item Details

   <link rel="stylesheet" href="css/itemDetails.css">


text:
Q: Try to loading multiples pugins in config but only the last one is loaded On CKeditor4, I have created different plugins and loaded them in config but only the last one is loaded. In the following case, only plugin3 is loaded. When i load each plugin individually each one works:
CKEDITOR.editorConfig = function( config ) {
    // Define changes to default configuration here.
    config.language = 'en';

    config.toolbarGroups = [
        { name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
        { name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
        { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] },
        { name: 'forms', groups: [ 'forms' ] },
        '/',
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] },
        { name: 'links', groups: [ 'links' ] },
        { name: 'insert', groups: [ 'insert' ] },
        '/',
        { name: 'styles', groups: [ 'styles' ] },
        { name: 'colors', groups: [ 'colors' ] },
        { name: 'tools', groups: [ 'tools' ] },
        { name: 'others', groups: [ 'others' ] },
        { name: 'about', groups: [ 'about' ] }
    ];

    config.removeButtons = 'Save,Preview,Print,Templates,Form,HiddenField,Flash,Iframe';

    config.extraPlugins = 'plugin1';
    config.extraPlugins = 'plugin2';
    config.extraPlugins = 'plugin3';
};

The code of three plugins is similar :
CKEDITOR.plugins.add( 'plugin1', {
    icons: 'plugin1',
    init: function( editor ) {
        editor.addCommand( 'insertPlugin1', {
            exec: function( editor ) {
                editor.insertHtml( '[bbcode1][/bbcode1]' );
            }
        });
        editor.ui.addButton( 'Plugin1', {
            label: 'Insert things',
            command: 'insertPlugin1',
            toolbar: 'insert'
        });
    }
});

Why it behaves like that? How to load all extra plugins?

A: Please, read the docs first: https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_config.html#cfg-extraPlugins
config.extraPlugins = 'plugin1,plugin2,plugin3';


text:
Q: Testing internal api calls with VCR gem I am using rspec with capybara for testing.
I want to test my api end point, I can do it with rspec. But while searching on net for api testing I found a gem vcr which can save api call response in yml file, So no multiple hit on server and also decrease test run time.
I have tried to configure it with local environment, But seems like it work for external api calls only.
Anyone having experience in configure with local environment setup.
Tried setup capaybara to run server in test environment but didn't get any success.
Capybara.configure do |config|
  config.run_server = true
  config.server_port = 7000
  config.app_host = 'http://localhost:7000'
end

But getting following issue:
Errno::ECONNREFUSED:
      Connection refused - connect(2) for "localhost" port 7000


text:
Q: 415 Unsupported Media Type in post request Does anyone know what could cause ERROR 415  (Unsupported Media Type)? Thank you
  createArticleOld : async ({ commit, dispatch }, data) => {
    let added = await dispatch('authorizedPostOld',
        { action: 'article',
          data,
          headers:  {
            'Content-Type': 'application/json-patch+json',
            'Accept': 'application/json-patch+json',
          },
        }
    )
    console.log(added)
    commit('ADD_ARTICLE', added)
  },

A: Typically, an HTTP response status of 415 is telling you that the format of the data you're sending isn't accepted by the server, as described briefly here:

The origin server is refusing to service the request because the payload is in a format not supported by this method on the target resource.
The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

So, to solve the problem, you need to find out the format that the server expects to receive data in, and send that. The easiest way will be to check the documentation for (or ask the developer of) the server.
If you check the raw response returned to your browser (or perform the same request via something like cURL or Postman), you might find some clues in there as to the formats that the endpoint accepts, or the specific problem causing the error response.
Of course, this relies on the developer of the server implementing the HTTP statuses correctly, and it's quite possible that they've made an error. As a complete guess, given that you're setting the Accept header, it could be that the server is trying to tell you that it can't give you a response in the format "application/json-patch+json", although that should give you a 406.


text:
Q: dashed lines in UIView ? How to change the border style of UIView. I need to display dotted bordered line on UIView Class.
Can some one please help me with this

A: you will be better off using a background image.
make the dotted image using photoshop or alike , import it into your project
and use :
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"dottedBackground.png"]];

A: See UIBezierPath's - (void)setLineDash:(const CGFloat *)pattern count:(NSInteger)count phase:(CGFloat)phase method. This allows you to draw dashed lines.


text:
Q: Multi-server Solr configuration question I have a three-server Solr setup.  Server 1 adds new data to the solr index every few minutes.  Servers 2 & 3 use the index on server 1 using a file sharing configuration.  To get the index updates, servers 2 & 3 run the simple command below every few minutes.
java -jar /path/to/solr/post/file/post.jar

The whole system has been running fine for a few months, but now that our index is growing in size, servers 2 & 3 become unresponsive during or after running the post.jar.
When architecting my solution, it made sense to have one index shared across servers.  This allowed for one master data acquirer server and multiple query processing servers.  Am I looking at this wrong?  Do I need a unique (yet identical) index on each of my query processing Solr servers?
Thanks!
GBooks

A: So I was using my own kludged together multi-server configuration.  After a bit of re-architecting, I am now using replication built into Solr 1.4!  It is pretty simple to set up.  If you are looking to set it up, I can help!
GBooks


text:
Q: Sring @AutoConfigureRestDocs causes MockMvc port to change to 8080 A SpringBoot project with testing was working fine until I added @AutoConfigureRestDocs. Then the testing starting running on port 8080 where before there was no port that was apparent.
So, when I used to have
mockMvc.perform(get("/employee/address/1")
    .accept(MediaType.APPLICATION_JSON_VALUE))
     .andExpect(jsonPath("$._links.self.href", is("http://localhost/employee/address/1")))

and it worked now it is failing with the error
java.lang.AssertionError: JSON path "$._links.self.href"
Expected: is "http://localhost/employee/address/1"
     but: was "http://localhost:8080/employee/address/1"

I've tried to change application.yml to add server.port: -1 and other things but I cannot control the port. I'm not even sure what to set it to though I suppose 80 would be correct.

A: If you check the API of AutoConfigureRestDocs,you will see below description:

The default value of uriPort is 8080, so you need to change it explicitly
@AutoConfigureRestDocs(uriPort = "80")


text:
Q: Objects relationship (between objects in different collections) in MongoDB
TL/DR: I have two Models each with its own repository, context and controller for MongoDB. How do I build relationships between them similar to how RDBMS would use ForeignKey to reference one model from another.

So I have two models, one referencing another one:
[Validator(typeof(OrgNameValidator))]
public class Org : BaseEntity
{
     public string Name { get; set; }
}

public class Portfolio : BaseEntity
{
    public string Name { get; set; }
    public bool IsPrivate { get; set; }
    public Org Organization { get; set; }
}

I use MongoDB as backend so each of the two has their own context, repository and controller (This may be right or wrong, but for the education purposes I am trying to focus on the task of managing relationship between MongoDB documents that is abstracted from the representation at the model/class level).
My attempt is that when I save a Portfolio, at the database level, it will create a document in the Portfolio collection that has a field for Org with ObjectID referencing a document in the Org collection.
So I am trying to POST a new Portfolio:
[HttpPost]
public async Task<IActionResult> Post([FromBody] Portfolio portfolio)
{
    try
    {
        if (ModelState.IsValid)
        {
            await _repository.AddRecord(portfolio);
            return new OkObjectResult(portfolio);
        }
        else
        {
            return await Task.FromResult(BadRequest(ModelState));
        }
    }
    catch (Exception ex)
    {
        return await Task.FromResult(StatusCode(500, ex.Message));
    }
}

So there are two scenarios that happen:

*

*When passing Org _Id for Organization field (similar with how some other frameworks let you do this) - you end up with invalid input problem: the Organization field is Org class so it won't validate and I think I am missing some object mapping or something else that potentially comes out of box with AspNetCore.MVC that would allow me to mitigate this.

*When giving it all Org details - will save the Org details inline Portfolio document in its own Portfolio collection. I assume this is logical since from the object perspective, Org is an Org so it validates the object and nests it into the document - how would it "know" that it needs to save the document in a different collection via a different repository implementation.
I would assume that I could convert things a little to actually be this (having Organization be represented as string storing it's _id and then working out the logic of retrieving the relevant data via getters in Portfolio class):
public class Org : BaseEntity
{
     public string Name { get; set; }
}

public class Portfolio : BaseEntity
{
    public string Name { get; set; }
    public bool IsPrivate { get; set; }
    public string Organization { get; set; }

    public getOrganization{get{return _repo<Org>.getOrgById(this.Organization)}}
}

I am still thinking that there must be something I am missing that will allow me to keep the "conventional" model/class structure similar to how I would have it with RDBMS implementations while having a document-oriented storage at the backend.
Another option here is using MongoDBRef type to reference other documents but it requires a bit of coding to align this to be flexible across modelling entities. I looked for MongoDB repository/entity frameworks implementations and found a few (Yarn, MongoRepository, Simple.Data, SharpRepository) but none are compatible with AspNetCore yet.
What is the pattern in asp.net core that allows me to orchestrate object relationships between different models and objects with MongoDB?


text:
Q: What is gap statistics? For finding optimal number of clusters, one way that has been suggested is gap statistics. I have looked online but the articles are very math heavy and I am not able to make sense of it. If I could get a simple answer to it, that will really help.

A: You generate random data and compare the quality of your clustering to results of clustering random data. If the result isn't better than clustering random data, the clustering probably did not work. But of course it is not sufficient to cluster randomly once, but you'll need many runs.


text:
Q: Can 'sheep' be a verb? I read the below text and can "sheep" really be used for verb?

Thank you for the great answer, and of course the obsessive compulsive drones who work for free to keep the owners of Stack Exchange paid good money will comment about any answer that doesn't fall in with protocol. It's really a sad system. People without a life working for more "privileges" just a way for the owner to get more money. Top business model, that's for sure. But does SE really give a flying two cents about either the asker or answerers? Does SE really make the Internet a better place? Not when moderators and other unpaid drones are more worried about the SE protocol rather than normal human relations. SE is driven by advertisement, so all this crap about building a great site is just a distraction from its real purpose... putting money into the pockets of a few, on the sweat and labour of people sheeped into its privileges system

A: No, to sheep is not a standard verb (which you will find in the dictionary)
However, from the context is it clear what is meant - those people are easily influenced by the system (or the SE owners) and lured into it.
However, for comic effect, the rules of grammar are often bent.


text:
Q: C# & SQL Server - insert into different tables (if/case statement) I have list of SYMBOLS and their data that are being inserted into MYTABLE. I would like that if SYMBOL = 'ABC', the data will be inserted into MYTABLE_ABC, if SYMBOL = 'DCE' it will inserted into MYTABLE_DCE etc...
I am using SQL Server. Thinking about IF/CASE statement? But can't figure out the syntax in C# console app.
Public String toInsert()
{
    String output = "insert into MYTABLE (id,symbol,date,time, value,type) values ( " + id + ",'" + symbol + "', ('" + date +"'), ('" + time + "')," + value + ",'" + type + "')";
    return output;
}

A: why not just write the table name as a variable? You can do to the string whatever you like, because it is a string, not a function or something else.
Like:
String Table_Name;
switch (symbol)
{
    case "ABC": Table_Name = "MYTABLE_ABC";
    case "DEF": Table_Name = "MYTABLE_DEF";
(blabla....)
}
String output = "insert into " +Table_Name+ " (id,symbol,date,time, value,type) values ( " + id + ",'" + symbol + "', ('" + date +"'), ('" + time + "')," + value + ",'" + type + "')";

            return output;

A: How about...
public String toInsert()
{
  if (symbol == "ABC")
    return "insert into MYTABLE_ABC (id,symbol,date,time, value,type) values ( " + id + ",'" + symbol + "', ('" + date +"'), ('" + time + "')," + value + ",'" + type + "')";
  else
  if (symbol == "DEF")
    return "insert into MYTABLE_DEF (id,symbol,date,time, value,type) values ( " + id + ",'" + symbol + "', ('" + date +"'), ('" + time + "')," + value + ",'" + type + "')";
  else
    return null;
}

A: Use the String.Format() method and to do the string concatenations.
You could just append the value symbol to "MYTABLE_" when creating the insert statement string. If every value of symbol follows the same pattern then that will work. If you want more flexibility to identify unknown symbol values or to format the table name differently depending on the value of symbol, then using a switch statement might be the way to go.
public String toInsert()
{
    String output = String.Format("insert into MYTABLE_{0} (id,symbol,date,time, value,type) values ( '{1}', ('{2}'), ('{3}'), {4}, '{5}', {6} )", symbol, id, symbol, date, time, value, type);

    return output;
}

public String toInsert()
{
    String tableName;

    switch (symbol)
    {
        case "ABC":
        case "XYZ":
        case "B2M":
            tableName="MYTABLE_" + symbol;
            break;
        case "A12":
            tableName="MYTABLE_TEST";
            break;
        case string.Empty:
        case NULL:
            tableName="MYTABLE";
            break;
        default:
            // as an example the default case could throw an error if you don't want to process unknown symbols. Or you could use a different tableName format pattern
            // throw new Exception("Unknown value of symbol variable ({0}", symbol);
            tableName = "MYTABLE_UnknownSymbol_"+symbol;
            break;
    }

    String output = String.Format("insert into {0} (id,symbol,date,time, value,type) values ( '{1}', ('{2}'), ('{3}'), {4}, '{5}', {6} )", myTableName, id, symbol, date, time, value, type);

    return output;
}


text:
Q: Why is "compile" called 2 times when calling "run" in SBT Play Framework Project In my play framework project using SBT, I'm trying to run a custom task before the compile task. This is easily done by adding this in the build.sbt.
lazy val hello = taskKey[Unit]("says hello to everybody :)")

hello := {
  println("hello, world")
}

(compile in Compile) := ((compile in Compile) dependsOn hello).value

When I do sbt compile, it runs the hello task once then it compiles the code. Like it was expected!
Strangely, when I run sbt run, the hello task is run 2 times. Like this
(Server started, use Enter to stop and go back to the console...)
hello, world
[info] Compiling 1 Java source to C:\dev\CS\CSBackEnd\target\scala-2.12\classes ...
hello, world
[info] p.a.d.DefaultDBApi - Database [default] initialized
[info] p.a.d.HikariCPConnectionPool - Creating Pool for datasource 'default'

Any idea how to prevent this or at least understand what is going on under the hood? In this example, it's only to print a string but in real life, a complex validation will be called instead and it can't run 2 times because it will take too much time.
Thanks
** EDIT **
Here is the output when I do sbt inspect tree run.
[info] welcome to sbt 1.3.13 (Oracle Corporation Java 1.8.0_201)
[info] loading global plugins from C:\Users\jcote\.sbt\1.0\plugins
[info] loading settings for project csbackend-build from plugins.sbt ...
[info] loading project definition from C:\dev\CS\CSBackEnd\project
[info] loading settings for project root from build.sbt ...
[info] set current project to S360ControlSite (in build file:/C:/dev/CS/CSBackEnd/)
[info] Compile / run = InputTask[Unit]
[info]   +-Compile / run / mainClass = Task[scala.Option[java.lang.String]]
[info]   +-Global / javaOptions = Task[scala.collection.Seq[java.lang.String]]
[info]   +-baseDirectory =
[info]   | +-thisProject = Project(id root, base: C:\dev\CS\CSBackEnd, configurations: List(compile, runtime, test, provided, optional, web-assets, web-assets-test, web-plugin, universal, universal-docs, universal-src, windows, docker, linux, rpm, debian), plugins: List(org.openapitools.openapistylevalidator..
[info]   |
[info]   +-fileWatchService = play.dev.filewatch.DefaultFileWatchService@205b0b3a
[info]   | +-Global / pollInterval = 500 milliseconds
[info]   | +-Global / sLog = sbt.internal.LogManager$$anon$1@6531d251
[info]   | +-target = target
[info]   |   +-baseDirectory =
[info]   |     +-thisProject = Project(id root, base: C:\dev\CS\CSBackEnd, configurations: List(compile, runtime, test, provided, optional, web-assets, web-assets-test, web-plugin, universal, universal-docs, universal-src, windows, docker, linux, rpm, debian), plugins: List(org.openapitools.openapistylevalid..
[info]   |
[info]   +-playAssetsClassloader = Task[scala.Function1[java.lang.ClassLoader, java.lang.ClassLoader]]
[info]   | +-playAllAssets = Task[scala.collection.Seq[scala.Tuple2[java.lang.String, java.io.File]]]
[info]   |   +-playPrefixAndAssets = Task[scala.Tuple2[java.lang.String, java.io.File]]
[info]   |     +-Web-assets / webPublic = target\web\public\main
[info]   |     | +-assetsTarget = target\web
[info]   |     |   +-target = target
[info]   |     |     +-baseDirectory =
[info]   |     |       +-thisProject = Project(id root, base: C:\dev\CS\CSBackEnd, configurations: List(compile, runtime, test, provided, optional, web-assets, web-assets-test, web-plugin, universal, universal-docs, universal-src, windows, docker, linux, rpm, debian), plugins: List(org.openapitools.openapist..
[info]   |     |
[info]   |     +-assetsPrefix = public/
[info]   |
[info]   +-playCommonClassloader = Task[java.lang.ClassLoader]
[info]   | +-Compile / dependencyClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   | | +-Compile / dependencyClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | | +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | |
[info]   | | +-Compile / externalDependencyClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   | | | +-Compile / externalDependencyClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | | | +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | | |
[info]   | | | +-Compile / managedClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   | | | | +-Global / appConfiguration = xsbt.boot.AppConfiguration@5f22d8ea
[info]   | | | | +-Compile / classpathConfiguration = Task[sbt.librarymanagement.Configuration]
[info]   | | | | | +-Compile / configuration = compile
[info]   | | | | | +-Global / internalConfigurationMap = sbt.Defaults$$$Lambda$1562/1187225933@797c8f80
[info]   | | | | | +-update = Task[sbt.librarymanagement.UpdateReport]
[info]   | | | | |
[info]   | | | | +-Global / classpathTypes = Set(eclipse-plugin, maven-plugin, bundle, scala-jar, hk2-jar, orbit, test-jar, jar)
[info]   | | | | +-Global / isMetaBuild = false
[info]   | | | | +-Compile / managedClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | | | | +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | | | |
[info]   | | | | +-Global / reresolveSbtArtifacts = false
[info]   | | | | +-update = Task[sbt.librarymanagement.UpdateReport]
[info]   | | | | +-Global / useCoursier = true
[info]   | | | |
[info]   | | | +-Compile / unmanagedClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   | | |   +-Global / buildDependencies = sbt.internal.BuildDependencies@6c0a821a
[info]   | | |   +-Compile / configuration = compile
[info]   | | |   +-Global / settingsData = Task[sbt.internal.util.Settings[sbt.Scope]]
[info]   | | |   +-thisProjectRef = ProjectRef(file:/C:/dev/CS/CSBackEnd/,root)
[info]   | | |   +-Compile / unmanagedClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | |     +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | | |
[info]   | | +-Compile / internalDependencyClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   | |   +-Global / buildDependencies = sbt.internal.BuildDependencies@6c0a821a
[info]   | |   +-Compile / classpathConfiguration = Task[sbt.librarymanagement.Configuration]
[info]   | |   | +-Compile / configuration = compile
[info]   | |   | +-Global / internalConfigurationMap = sbt.Defaults$$$Lambda$1562/1187225933@797c8f80
[info]   | |   | +-update = Task[sbt.librarymanagement.UpdateReport]
[info]   | |   |
[info]   | |   +-Compile / configuration = compile
[info]   | |   +-Compile / exportedProductJars / transitiveClasspathDependency = ()
[info]   | |   +-Compile / exportedProductJarsIfMissing / transitiveClasspathDependency = ()
[info]   | |   +-Compile / exportedProductJarsNoTracking / transitiveClasspathDependency = ()
[info]   | |   +-Compile / exportedProducts / transitiveClasspathDependency = ()
[info]   | |   +-Compile / exportedProductsIfMissing / transitiveClasspathDependency = ()
[info]   | |   +-Compile / exportedProductsNoTracking / transitiveClasspathDependency = ()
[info]   | |   +-Compile / internalDependencyClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | |   | +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   | |   |
[info]   | |   +-Global / settingsData = Task[sbt.internal.util.Settings[sbt.Scope]]
[info]   | |   +-thisProjectRef = ProjectRef(file:/C:/dev/CS/CSBackEnd/,root)
[info]   | |   +-Global / trackInternalDependencies = TrackAlways
[info]   | |
[info]   | +-playCommonClassloader / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |   +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |
[info]   +-playDefaultAddress = 0.0.0.0
[info]   +-playDefaultPort = 9000
[info]   +-playDependencyClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   | +-Runtime / externalDependencyClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   |   +-Runtime / externalDependencyClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |   | +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |   |
[info]   |   +-Runtime / managedClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   |   | +-Global / appConfiguration = xsbt.boot.AppConfiguration@5f22d8ea
[info]   |   | +-Runtime / classpathConfiguration = Task[sbt.librarymanagement.Configuration]
[info]   |   | | +-Runtime / configuration = runtime
[info]   |   | | +-Global / internalConfigurationMap = sbt.Defaults$$$Lambda$1562/1187225933@797c8f80
[info]   |   | | +-update = Task[sbt.librarymanagement.UpdateReport]
[info]   |   | |
[info]   |   | +-Global / classpathTypes = Set(eclipse-plugin, maven-plugin, bundle, scala-jar, hk2-jar, orbit, test-jar, jar)
[info]   |   | +-Global / isMetaBuild = false
[info]   |   | +-Runtime / managedClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |   | | +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |   | |
[info]   |   | +-Global / reresolveSbtArtifacts = false
[info]   |   | +-update = Task[sbt.librarymanagement.UpdateReport]
[info]   |   | +-Global / useCoursier = true
[info]   |   |
[info]   |   +-Runtime / unmanagedClasspath = Task[scala.collection.Seq[sbt.internal.util.Attributed[java.io.File]]]
[info]   |     +-Global / buildDependencies = sbt.internal.BuildDependencies@6c0a821a
[info]   |     +-Runtime / configuration = runtime
[info]   |     +-Global / settingsData = Task[sbt.internal.util.Settings[sbt.Scope]]
[info]   |     +-thisProjectRef = ProjectRef(file:/C:/dev/CS/CSBackEnd/,root)
[info]   |     +-Runtime / unmanagedClasspath / streams = Task[sbt.std.TaskStreams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |       +-Global / streamsManager = Task[sbt.std.Streams[sbt.internal.util.Init$ScopedKey[_ <: Any]]]
[info]   |
[info]   +-playDevSettings = List()
[info]   +-playInteractionMode = Console Interaction Mode
[info]   +-playMonitoredFiles = Task[scala.collection.Seq[java.io.File]]
[info]   | +-Compile / twirlCompileTemplates / sourceDirectories = List(C:\dev\CS\CSBackEnd\app)
[info]   | | +-Compile / sourceDirectory = app
[info]   | |   +-baseDirectory =
[info]   | |     +-thisProject = Project(id root, base: C:\dev\CS\CSBackEnd, configurations: List(compile, runtime, test, provided, optional, web-assets, web-assets-test, web-plugin, universal, universal-docs, universal-src, windows, docker, linux, rpm, debian), plugins: List(org.openapitools.openapistyleval..
[info]   | |
[info]   | +-Global / settingsData = Task[sbt.internal.util.Settings[sbt.Scope]]
[info]   | +-thisProjectRef = ProjectRef(file:/C:/dev/CS/CSBackEnd/,root)
[info]   |
[info]   +-playRunHooks = Task[scala.collection.Seq[play.sbt.PlayRunHook]]
[info]   +-Global / sbtVersion = 1.3.13
[info]   +-Global / state = Task[sbt.State]

A: I can't tell you why you're seeing the behaviour you're observing. I can reproduce the error with SBT 1.3.13. When I use SBT 1.4.9 the custom task only runs once as you would expect.