text:
Q: Proving the context of the formula $\frac{k!}{k_1!\cdot k_2!...k_n!}$ - Need help to understand the context
On $n$ cells $k$ distinguishable particles shall be distributed in
  such a way that in the cell $i$ exactly $k_i$ particles lie,
  $k_1+k_2+...+k_n=k$. An arrangement within each cell is not considered.
  Show that the upper formula specifies the number of different
  distributions.

So I have fixed $n$ cells what do I know about my $k$ objects do I have more than $n$ or less than $n$? All I can deduced from above Information is that I have to distribute every particle.
Also what does it mean that in the cell $i\,k_i$ particles lie what is $k_i$?

A: Sketch:
We know there are $k_1$ particles in the first cell, we need to select which $k_1$.  There are $\binom k{k_1}$ ways to do that.
Having done that we have to choose $k_2$ particles for the second cell.  There are $\binom {k-k_1}{k_2}$ ways to do that.
And so on.
The total count is then $$\binom k{k_1}\times \binom {k-k_1}{k_2}\times \cdots \times \binom {k-k_1-\cdots -k_{n-1}}{k_n}$$
Writing out the binomial coefficients we get $$\frac {k!}{k_1!\times (k-k_1)!}\times \frac {(k-k_1)!}{k_2!\times (k-k_1-k_2)!}\times \cdots$$
And cancellation of common terms does the rest.

A: Some HINTS:
That formula is usually used for "permutations with repeated elements", that is for example:
How many different words can you make with the letters in MATHEMATICS?
The different permutations of these letters are $11!$ but there are some repeated letters so if I index the two "A"s for example then
$$
MA_1THEMA_2TICS
$$
and
$$
MA_2THEMA_1TICS
$$
are distinguishable but without the indices they are the same so we have to "remove" these cases by dividing by the number of ways we can arrange the "A"s in between themselves, that is $2!$.
So the total number of ways to arrange the letters will be
$$
\frac{11!}{2!\cdot2!}
$$
since we have $2$ "M"s as well. These are just some thoughts about the formula.
Now to answer your questions:
I wouldn´t say that $k$ is less than $n$ but nothing in the wording of the question would immediately say the opposite.
$k_i$ would be the number of particles ending up in cell number $i$.


text:
Q: Input container width same as input content I have an input container here:
const InputContainer = styled(BaseInputContainer)`
  display: inline-block;
  width: 100%;
  align-items: center;
  input[type="number"] {
    background: black;
    width: 100%;
    text-align: center;
  }
`;

I want the width of the container to be the same size of the input field, basically
width: fit-content

but that does not work in the InputContainer component. How do I do this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How many steps does it take to "Tarski-Vaughtify" second-order logic? Given a regular logic $\mathcal{L}$, let $\preccurlyeq_\mathcal{L}$ be the usual elementary submodelhood relation for $\mathcal{L}$. There is also a separate submodelhood relation coming from the Tarski-Vaught test: say that $\mathfrak{A}\trianglelefteq_\mathcal{L}\mathfrak{B}$ if $\mathfrak{A}$ is a substructure of $\mathfrak{B}$ and for every $\mathcal{L}$-formula $\varphi$ with parameters from $\mathfrak{A}$ we have $$\varphi^\mathfrak{B}\not=\emptyset\implies \varphi^\mathfrak{B}\cap\mathfrak{A}^{arity(\varphi)}\not=\emptyset.$$
Usually $\trianglelefteq_\mathcal{L}$ is strictly between $\subseteq$ and $\preccurlyeq_\mathcal{L}$. Now every logic $\mathcal{L}$ has a distinguished fragment which "plays nicely" with this substructurehood relation, namely $$\mathcal{L}_{TV}:=\{\varphi\in\mathcal{L}: \mathfrak{A}\trianglelefteq_\mathcal{L}\mathfrak{B}\implies\varphi^\mathfrak{A}=\varphi^\mathfrak{B}\cap\mathfrak{A}^{arity(\varphi)}\}.$$ In general we need not have $\mathcal{L}_{TV}=(\mathcal{L}_{TV})_{TV}$, and so we can non-boringly iterate this process through the ordinals:

*

*$\mathcal{L}_{TV(0)}=\mathcal{L}$,

*$\mathcal{L}_{TV(\alpha+1)}=(\mathcal{L}_{TV(\alpha)})_{TV}$, and

*$\mathcal{L}_{TV(\lambda)}=\bigcap_{\alpha<\lambda}\mathcal{L}_{TV(\alpha)}$ for $\lambda$ limit.

I've asked at MSE about one aspect of this process applied to second-order logic for a single step; here I'd like to ask an orthogonal question. Let the TV-number of a logic $\mathcal{L}$ be the least $\gamma$ such that $\mathcal{L}_{TV(\gamma)}=\mathcal{L}_{TV(\gamma+1)}$.

What is the TV-number of second-order logic?

Embarrassingly, as far as I know we could have $\gamma=1$ (we can't have $\gamma=0$ since $\mathsf{SOL}_{TV}$ has the full downward Lowenheim-Skolem property). I'd separately be interested in any references about this construction; the abstract model theory literature is messy, and I'd like to avoid reinventing as many wheels as possible.
Motivation: The $TV$-process is basically a quick way of whipping up logics with the downward Lowenheim-Skolem property or analogues thereof (count the formulas and think about Skolem functions), but given that it's not idempotent the "$TV^\infty$-process" $\mathcal{L}\leadsto \bigcap_{\alpha\in \mathit{Ord}}\mathcal{L}_{TV(\alpha)}$ may actually be a more natural way of producing such logics. I'm especially interested in second-order logic and its fragments, and so this question is basically a step towards figuring out which of $TV$ or $TV^\infty$ I should be thinking about at the moment.


text:
Q: Parsing XML with XPath in Java - Get data from XML file with Xpath and NodeList in Java I have this xml file and I want to get some values with Xpath.
The half of job is done but I get some trouble in the last part of file(States Node)
<?xml version="1.0" encoding="UTF-8"?>
<favoris>
    <workflow codewf="wf1000">
        <information>
            <title>wf1</title>
            <desc>description 1</desc>
            <nberState>2</nberState>
            <text>text text text text text text text</text>
        </information>
        <states>
            <state id="1" IDemployee="2">description1</state>
            <state id="2" IDemployee="3">description2</state>
        </states>
    </workflow>

    <workflow codewf="wf2000">
        <information>
            <title>wf2</title>
            <desc>description 2</desc>
            <nberState>3</nberState>
            <text>text text text text text text text</text>
        </information>
        <states>
            <state id="1" IDemployee="3">description1</state>
            <state id="2" IDemployee="2">description2</state>
            <state id="3" IDemployee="4">description2</state>
        </states>
    </workflow>

</favoris>

And here the java code:
    package myxml;
import java.io.FileReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class xmlParty {
  public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xPath = factory.newXPath();
    NodeList favoris = (NodeList) xPath.evaluate("/favoris/workflow[@codewf='wf1000']",
            new InputSource(new FileReader("a.xml")),
            XPathConstants.NODESET);
    for (int i = 0; i < favoris.getLength(); i++) {
      Element workflow = (Element) favoris.item(i);
      String title = xPath.evaluate("information/title", workflow);
      String desc_w = xPath.evaluate("information/desc", workflow);
      String nberState = xPath.evaluate("information/nberState", workflow);
      String text = xPath.evaluate("information/text", workflow);
      System.out.println(workflow.getAttribute("codewf") +" "+title + " " + desc_w + " " + nberState + " " + text );

      NodeList States = (NodeList)xPath.evaluate("states/state", workflow, XPathConstants.NODESET);
      System.out.println(States.getLength());
      for (int k = 0; k < States.getLength(); k++) {
          String desc_state = xPath.evaluate("states/state", workflow);
          System.out.println(desc_state );
      }

   }
  }
}

and the output will be :
First example
wf1000 wf1 description 1 2 text text text text text text text
2
description1
description1

Second example
wf2000 wf2 description 2 3 text text text text text text text
3
description1
description1
description1

Looking at the state with ID 2, the text is description2 not description1 .
I think the parser don't move to the second child and it always still at the firsst child.
So how can I do and also how to do too to get the attribute of state????????

A: You will have to do something like:
for (int k = 0; k < States.getLength(); k++) {
          String desc_state = xPath.evaluate("states/state[position()=" + (k + 1) + "]", workflow);
          String id_employee = xPath.evaluate("states/state[position()=" + (k + 1) + "]/@IDemployee", workflow);
          System.out.println(desc_state + ":" + id_employee);
}


text:
Q: Safe trackable links from 301 redirect I want to create a something where a user can submit a link (http://www.example.com?key=value) then be returned with a new link which will redirect to the link provided in a way that is traceable. (http://trackedlink.com/[trackid]).
I was thinking about adding a get value to the end of the link redirect eg, http://www.example.com?key=value&trackid=[trackid]
My concern is that although extremely unlikely this may override an already set get value (trackid). Is there any truely safe way to do this?


text:
Q: Copy Result of a Query into another table I have selected all tables using this query
SELECT TABLE_SCHEMA from information_schema.tables

I want to copy the result of this query to another table info in its column table_names
I want to do this in 1 query. Is this possible?
Thank you in advance :)

A: Maybe this,but not tested
INSERT INTO info (table_names) SELECT TABLE_SCHEMA FROM information_schema.tables

A: INSERT INTO Info
SELECT TABLE_SCHEMA from information_schema.tables

select * from Info

But  SELECT TABLE_SCHEMA from information_schema.tables
 will return dbo, etc, schema names, if you want to get table names use
select name from sys.tables

so use
INSERT INTO Info
SELECT name
FROM sys.tables

See http://www.blackwasp.co.uk/SQLSelectInsert.aspx for example for insert into with select, there're many other samples.


text:
Q: Error al usar Dos modelos en una vista- mvc core I have a model for Musico and another for Commune,
I try to bring both of them this way ..
I tried to use ** Tuple ** among other things but I went back to the base which was this
mi error..
public class ComunaViewModel
  {
    public Comuna ComunaDTO { get; set; }
    public Musico MusicoDTO { get; set; }
  }

musico
public class Musico
  {
    [Key]
    public int Id { get; set; }
    public string Nombre { get; set; }
    public string Estilos { get; set; }
    public int IdComuna { get; set; }
    public string Email { get; set; }

Comuna
public class Comuna
  {
    [Key]
    public int Id { get; set; }
    public string Nombre { get; set; }

--
public async Task<IActionResult> Index()
    {
      return View(await _context.Musico.ToListAsync());

    }

view

                @Html.DisplayNameFor(model => model.MusicoDTO.Nombre)

                @Html.DisplayNameFor(model => model.MusicoDTO.Estilos)

                @Html.DisplayNameFor(model => model.ComunaDTO.Nombre)
----
@foreach (var item in Model) {

                @Html.DisplayFor(modelItem => item.MusicoDTO.Nombre)

                @Html.DisplayFor(modelItem => item.MusicoDTO.Estilos)

                @Html.DisplayFor(modelItem => item.ComunaDTO.Nombre)

A: You need to pass List<ComunaViewModel> rather than List<Musico> to your view.
You can try to convert List<Musico> to List<ComunaViewModel>.
public async Task<IActionResult> Index()
    {
       List<Musico> l = await _context.Musico.ToListAsync();
       List<ComunaViewModel> l1 = new List<ComunaViewModel>();
       foreach (var item in l)
       {
           l1.Add(new ComunaViewModel { MusicoDTO = item });
       }
      return View(l1);

    }


text:
Q: Position a Div in Front of Another I am trying to do something really simple here, I want a div with no border but a solid background color to be OVER a div with a border. This means I want the border around the second div to disappear behind the top div when they intersect. This is how the divs look as currently constructed:

Note here that I want DSP Name Settings to appear OVER the top border line. I have been using z-index but it changes essentially nothing. Here is my code as of right now. With the following CSS styles, that according to all Documentation, SHOULD be putting the title on top of the border as I would like, but isn't.

DSP Name Settings

                    <Form>
                        <Form.Group controlId="name" onChange={(event) => handleInput(event)}>
                            <Form.Control
                                type='name'
                                placeholder={"name"}
                                style={{
                                    textAlign: 'center',
                                    border: '1px black',
                                    color: 'black',
                                }}
                            />
                        </Form.Group>
                        <Form.Group controlId="shortcode" onChange={(event) => handleInput(event)}>
                            <Form.Control
                                type='shortcode'
                                placeholder={"shortcode"}
                                style={{
                                    textAlign: 'center',
                                    border: '1px black',
                                    color: 'black',
                                }}
                            />
                        </Form.Group>
                        <Form.Group>
                            <DropdownButton id="dropdown-basic-button" title={"TimeZone"}>
                                <Dropdown.Item><Button className="set-preferences-dropdown-button" variant="info" onClick={() => handleSetTimeZone('EST') } size='lg'>Eastern Standard Time</Button></Dropdown.Item>
                                <Dropdown.Item><Button className="set-preferences-dropdown-button" variant="info" onClick={() => handleSetTimeZone('CT') } size='lg'>Central Time</Button></Dropdown.Item>
                                <Dropdown.Item><Button className="set-preferences-dropdown-button" variant="info" onClick={() => handleSetTimeZone('MT') } size='lg'>Mountain Time</Button></Dropdown.Item>
                                <Dropdown.Item><Button className="set-preferences-dropdown-button" variant="info" onClick={() => handleSetTimeZone('PST') } size='lg'>Pacific Standard Time</Button></Dropdown.Item>
                            </DropdownButton>
                        </Form.Group>
                    </Form>

.set-preferences-name-data {
  margin-left: 3%;
  margin-right: 3%;
  margin-bottom: 5%;
  padding-top: 30px !important;
  padding: 6px;
  border: solid;
  border-width: 2px;
  border-color: '#E2E8F1' !important;
  position: relative;
  z-index: -100 !important;
}

.set-preferences-name-data-title {
  position: absolute;
  margin-top: 20px !important;
  background-color: 'white' !important;
  color: 'white';
  border: solid;
  border-width: 2px;
  border-color: '#E2E8F1' !important;
  z-index: 20 !important;
}

.set-preferences-name-data-title {
  position: absolute;
  background-color: 'white' !important;
  padding-left: 3px;
  padding-right: 3px;
  z-index: 4 !important;
  left: 36.8%;
  top: 3%;
}

DSP Name Settings

      <Form>
        <Form.Group controlId="name" onChange={(event)=> handleInput(event)}> // I've commented out the first text input because it is irrelevant to the issue
        </Form.Group>
        <Form.Group controlId="shortcode" onChange={(event)=> handleInput(event)}> // I've commented out the second text input because it is irrelevant to the issue
        </Form.Group>
        <Form.Group>
          <DropdownButton id="dropdown-basic-button" title={dsp.timeZone}>
            // I removed the DropDown items since they're irrelevant to this issue
          </DropdownButton>
        </Form.Group>
      </Form>

The code that's in question is only rendered if a specified condition is met, so I will also post the main return of the React Component so to make everything a little more clear...
return(

Set ScoreCard Preferences

{renderNameSettings()}

                    Here, you will be able to select at what point values for specific
                    ScoreCard values will be deemed 'fantastic', 'good' and 'fair'. Any time a value is
                    higher than a 'fair' descending value or lower than a 'fair' ascending one, this
                    value will be deemed 'subpar.' This will be reflected by what color the text pops up
                    in for both you and your drivers

       // The rest has been cut off since there is no relation to the rest of the component and the issue

A: Just set a background-color on the top div:
.set-preferences-name-data-title {
  background-color: white;
}


text:
Q: Python script as daemon in ubuntu I created a daemon to run a python script. but it stops whenever i logout from my ubuntu machine.
DAEMON=sudo python /var/www/some_dir/my_python.py
ARGS=/var/www/some_dir/my_python.py
PIDFILE=/var/www/some_dir/my_python.pid

test -x $DAEMON || exit 0

#set -e

case "$1" in
start)
    echo -n "Starting $DESC: "
    start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON &
    echo "$NAME."
    ;;
stop)
    echo -n "Stopping $DESC: "
    start-stop-daemon --stop --pidfile $PIFDILE --exec $DAEMON
    echo "$NAME."
    ;;
restart|force-reload)
    echo -n "Restarting $DESC: "
    start-stop-daemon --stop --pidfile $PIDFILE --exec $DAEMON
    sleep 1
    start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON &
    echo "$NAME."
    ;;
*)
    N=/etc/init.d/$NAME
    echo "Usage: $N {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac
exit 0

can anyone tell me how can i do it.

A: It's a long time since this question was asked, but I came across this situation today.
To start the process in the background, use
start-stop-daemon -Sbm --pidfile $PIDFILE --exec $DAEMON

To stop it:
start-stop-daemon -K --pidfile $PIDFILE

From the start-stop-daemon man page:

-b , -background
Force the daemon into the background. Some daemons don't create
  pidfiles, so a good trick is to get the daemon to run in the
  foreground, and use the this option along with -m , -make-pidfile to
  create a working pidfile.
  -m , -make-pidfile
Saves the pid of the daemon in the file specified by the -p, -pidfile
  option. Only useful when used with daemons that run in the foreground
  and forced into the background with the --b, -background option.

A: Try to remove & from your start-stop-daemon invocations. Also, you should read how to write proer initscripts because there are several other errors in your initscript.


text:
Q: Encrypt HTTP Post request in an HTML file I have an HTML page which is sending an HTTP post request to a third party application. Now that application has enabled encryption/decryption and I have to encrypt the POST request using AES/ECB/PKCS5PADDING.
Can someone help me with the approach on how this can be implemented in an HTML file.


text:
Q: Why is my HashMap not getting populated My code for finding factorial for integers upto 100.I am using BigInteger, but my problem is that my HashMap is not getting populated.
public class FCTRL2 {
static Map<Integer,BigInteger> list = new HashMap<Integer,BigInteger>();

  public static void main(String[] args){
        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        int numberOfInput=0;
        String input=null;
        try {
            numberOfInput = Integer.parseInt(in.readLine());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        while(numberOfInput > 0){
            try {
                input = in.readLine();
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            BigInteger inputBig = new BigInteger(input);
            **System.out.println(factorial(inputBig));** prints correct factorial
        **System.out.println(list.get(factorial(inputBig).intValue()));** prints null
            numberOfInput--;
        }
  }

  public static BigInteger factorial(BigInteger input){
    if(list.containsKey(input.intValue()))
        return list.get(input.intValue());

    if(input.equals(new BigInteger("1")))
        return new BigInteger("1");
    BigInteger output;
    output = input.multiply(factorial(input.subtract(new BigInteger("1"))));
    list.put(input.intValue(), output);
    return output;
  }

}

A: Replace
System.out.println(list.get(factorial(inputBig).intValue()));

with
System.out.println(list.get(inputBig.intValue()));

because You are inserting value to map here: list.put(input.intValue(), output);

A: Try this
public static BigInteger factorial(BigInteger input) {
    if (list.containsKey(input.intValue()))
        return list.get(input.intValue());

    if (input.equals(BigInteger.ONE)) {
        list.put(input.intValue(), BigInteger.ONE);
        return BigInteger.ONE;
    }
    BigInteger output = input.multiply(factorial(input.subtract(BigInteger.ONE)));
    list.put(input.intValue(), output);
    return output;
}

And add a print after your numberOfInput while loop...
for (int key : list.keySet()) {
    System.out.println(list.get(key));
}

Seems to correctly output
1
10
3628800
1
2
6
24
120
720
5040
40320
362880
3628800

A: I did a test,first simplify read data,focus on logic:
I use BigInteger.valueOf() .
public class FCTRL2 {

  public static void main(String[] args){

        InputStreamReader read = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(read);
        Scanner scanner = new Scanner(in);
        //simplify read data first ,here focus on calculation logic
        while(scanner.hasNext()) {
             long val = scanner.nextLong();
             BigInteger inputBig = BigInteger.valueOf(val);
             System.out.println(factorial(inputBig));
        }
        scanner.close();
  }

  public static BigInteger factorial(BigInteger input){
    if(map.containsKey(input.intValue())) {
        System.out.println("from map");
         return map.get(input.intValue());
    }
    if(input.equals(new BigInteger("1")))
        return new BigInteger("1");
    BigInteger output;
    output = input.multiply(factorial(input.subtract(new BigInteger("1"))));
    map.put(input.intValue(), output);
    System.out.println("from new calculating");
    return output;
  }
  private static Map<Integer,BigInteger> map = new HashMap<Integer,BigInteger>();
}

see output and it seems the map cached some data.
Is this the logic what you want ?


text:
Q: Proving Cauchy criterion for a sequence of functions.
Proof.
(=>): First, we assume that $(f_n)$ converges uniformly on $A$, say to $f(x)$. Let $\epsilon > 0$ be given and choose and $N$ so that for all $n > N$ and all $x \in A$ one has $|f_n(x) - f(x)| < \epsilon $.
Now, Take $n_0 = N$.  Let $n \in \mathbb{N}$ be arbitrary. Clearly, $n+m > n_0$ as $m > m_0$ and so
$$ |f_{m+n}(x) - f_m(x) | \leq |f_{m+n} - f | + |f-f_m| < 2 \epsilon $$
Since this is true for any $x \in A$, then we are done.
(<=): Suppose now that the Cauchy Criterion is satisfied. Let $\epsilon > 0$. Let $x \in A$ and Pick $n_0$ so that if $m > n_0$ then (with $n=1$)
$$ |f_m - f | = | f_m - f_{m+1} | + |f_{m+1} - f | < 2 \epsilon  $$
and thus $f_m $ converges uniformly to $f$ and we done.
IS this enough for a solution? Any constructive criticism is extremely welcome!

A: As was noted in the comments, the forward direction is fine apart from a the typo of $m_0$ for $n_0$. For the other direction, however, you're going to need to use that Cauchy criterion to construct a function $f$ and then show that the functions converge uniformly on $\mathbf{A}$ to that function $f$.
We're assuming that for each $\epsilon>0$ there is an $n_\epsilon\in\Bbb N$ such that $|f_{n+m}(x)-f_m(x)|<\epsilon$ whenever $m>n_\epsilon$, $n\in\Bbb N$, and $x\in\mathbf{A}$. This is clearly equivalent to saying that for each $\epsilon>0$ there is an $n_\epsilon\in\Bbb N$ such that $|f_n(x)-f_m(x)|<\epsilon$ whenever $m,n>n_\epsilon$ and $x\in\mathbf{A}$, which means that $\langle f_n(x):n\in\Bbb N\rangle$ is a Cauchy sequence in $\Bbb R$ (or possibly $\Bbb C$) for each $x\in\mathbf{A}$. Every Cauchy sequence in $\Bbb R$ (or $\Bbb C$) converges, so we can define a function $f$ on $\mathbf{A}$ by setting
$$f(x)=\lim_{n\to\infty}f_n(x)$$
for each $x\in\mathbf{A}$.
Now that we have $f$, we can check that $\langle f_n:n\in\Bbb N\rangle$ converges uniformly on $\mathbf{A}$ to $f$. We'll use the following lemma.

Lemma. Let $\langle x_n:n\in\Bbb N\rangle$ be a sequence in $\Bbb R$ (or $\Bbb C$) converging to $x$, and suppose that $\epsilon>0$ and $n_0\in\Bbb N$ are such that $|x_n-x_m|<\epsilon$ whenever $n,m>n_0$; then $|x_n-x|\le\epsilon$ for each $n>n_0$.
Proof. Suppose that $|x_n-x|>\epsilon$ for some $n>n_0$, and let $\delta=|x_n-x|-\epsilon>0$. The sequence converges to $x$, so there is an $m>n_0$ such that $|x_m-x|<\delta$. But then $$|x-x_n|\le|x-x_m|+|x_m-x_n|<\delta+\epsilon=|x-x_n|\;,$$ which is absurd. Thus, $|x_n-x|\le\epsilon$ for all $n>n_0$. $\dashv$

Let $\epsilon>0$, and let $n_0\in\Bbb N$ be such that $|f_n(x)-f_m(x)|<\frac\epsilon2$ whenever $m,n>n_0$ and $x\in\mathbf{A}$. It follows immediately from the lemma that $|f_n(x)-f(x)|\le\frac\epsilon2<\epsilon$ for all $n>n_\epsilon$ and $x\in\mathbf{A}$, i.e., that $\langle f_n:n\in\Bbb N\rangle$ converges uniformly to $f$.


text:
Q: 6-node binary tree, exactly 2 have exactly 1 child Is such a binary tree possible? I've drawn out what I believe to be all possible iterations, and I cannot find a tree that satisfies these properties. Note that this is not a BST, so the values of the keys don't matter. There are countless with exactly 1 "single child" node, such as :
      a
     / \
    b   c
   /          //b is only such node
  d
 / \
e   f

And many with exactly 3 "single child" nodes:
          a
         /
        b
       /          //a, b, and d
      c
     / \
    d   e
   /
  f

Does such a binary tree exist (6 nodes, exactly 2 nodes with exactly 1 child)? If so, please provide an example.

A: This is an impossible structure to create with the standard binary tree containing 2 child pointers. If you had an nontraditional tree with 3 child pointers this would be possible.


text:
Q: Why are there different Ethernet PHY magnetic configurations? I'm looking at pcb-mount Ethernet ports like these:

I'm seeing a few different configurations of the magnetics within the ports. On a single Wurth data sheet, there are 4:

Schematic 2 is the part we currently use, but is going obsolete. I found potential replacements which look more like Schematic 1.
What is the difference? Are there benefits to the different designs?

A: Schematic 1 offers direct connection to the center tap of the exterior
port windings, and is suitable for PoE connection (which may either
draw power, or supply power, over twisted pair).   Schematics 2 and 4
do not have low-resistance connection suitable for PoE.   Schematic #3
does technically have the ability to connect to PoE, but only
through an inductor (which may saturate).
Modern designs would usually allow bidirectional use of
the four lanes, and #2 does not.   It is not surprising that it may
become obsolete, in favor of #4.


text:
Q: Create database in other database? I'm new to SQL Server, and I'm asking if can I create a database in other database like this:
mydatabase1[database] -> mydatabase2[database] -> mytable[table]

A: No.  SQL Server stores data in a hierarchy, consisting of:

*

*Tables are in schema.

*Schema are in databases.

*Databases are in servers.

The full access for a table uses a four-part naming convention:  server.database.schema.table.  However, most code does not use all four.
If you are thinking that databases are like folders and tables are like files, then that is the wrong analogy.


text:
Q: How to Deploy an ASP.NET Web API- and Browser-based Application to a Production Environment (Please forgive if this is posted in an incorrect forum.  We didn't know exactly where to post it.)
We have an ASP.NET Web API single page application - a browser-based app running in IIS to serve up HTML5/CSS3/JavaScript, which talks to the ASP.NET Web API endpoint only to access a database and transfer JSON data.  Everything is working great in our development environment - that is, we have one Visual Studio solution with an ASP.NET Web API project and two class library projects for data access.  While development and testing on development boxes, using IIS Express to a localhost:port to run the site and access the Web API, everything is fine.
Now we need to move it to a production environment (and we're having problems - or just not understanding what needs to be done).
The production environment is all internal (nothing will be exposed on the public Internet).  There are two domains.  One domain, the corporate domain, is where all users login normally.  The other domain, the process domain, contains the SQL Server instance that our app and Web API will need to access.
The IT staff wants to put a DMZ between the two domains to house the IIS app and shield the users on the corporate domain from having access into the process domain directly.  So, I guess what they want is:
corp domain (end users) <–> firewall (open port 80) <–> DMZ (web server running IIS) <–> firewall (open port 80 or 1433????) <–> process domain (IIS for Web API and SQL Server)
We're developers and don't really understand all the networking aspects, so we're wondering how to deploy our browser/Web API application in this scenario.

*

*Do we need to break up our application so that all the client code (HTML5/CSS3/JavaScript/images/etc.) is on the IIS server in the DMZ, while the Web API gets installed on the server in the process domain?

*Or, does the entire app (client code and Web API) stay together on the IIS server in the DMZ, which then somehow accesses the SQL Server instance to get data?

*From the IIS server and app in the DMZ, would you simply access the Web API on the server in the process domain by going to "http://server/appname/api/getitmes"?

*In the second firewall between the DMZ and the process domain, would you have to open port 1433 or just port 80 since the Web API is a HTTP endpoint?

*Or, is there some better way of deployment (i.e., how ASP.NET Web API single page applications written all in HTML5 and JavaScript supposed to be deployed to production environments?)?

I'm sure there are other questions, but we'll start with these.  Thanks!!!
(Note: the servers are Win2k8 R2, SQL Server 2k8 R2, and IIS 7.5.)

A: I can understand your IT group wanting to break this out, but it seems they too also don't fully understand how this setup works.  I won't go into that too much but essentially the only traffic you will be exchanging with the servers up to the process domain is standard HTTP traffic (assuming you are using the Web API for REST calls)
Essentially you end up with the following:
           Initial Request
SPA Web Server ---> Client (Running SPA)
                      |
                      | - REST Call
          Firewall -> | - Port 80 Only
                Web API Server
                      |
                      | - SQL (1433) .NET Connection/Data Source
          Firewall -> | - Port 1433 / 1434
             Backend SQL Servers

Remember that with a SPA the only communication the client has with the SPA web server is the initial request to get the HTML, JS and CSS.  After that (depending on how you wrote it) it should be directly issuing REST calls to the Web API server.
The Web API server issues SQL queries directly to the database from there.
So the long and short of it is as follows:
TL;DR: You should have a firewall between your clients and your two IIS instances (they can be the same server btw) to allow either/or HTTP and HTTPS traffic.  Then on another interface of that web server(s) you have a connection to the Process domain and only SQL traffic is allowed to come in (1433 and 1434).
Hope that helps.


text:
Q: SQLite3 and Implicit rowid's SQLite3 gives you a default primary key called rowid for each table if you don't specify a primary key.  However, it looks like there are some disadvantages to relying on this:

The VACUUM command may change the ROWIDs of entries in tables that do not have an explicit INTEGER PRIMARY KEY.

http://www.sqlite.org/lang_vacuum.html
I want to alter an existing SQLite3 database to use explicit primary keys rather than implicit rowid's so I have the ability to run vacuum when necessary.  Can I do this without rebuilding the whole database?

A: You don't need to rebuild the whole database. However since SQLite doesn't support ALTER TABLE statements you need to:

*

*create a temporary table with the correct schema

*copy all data from the original table to the temp table

*delete the original table

*rename the temp table

I suggest you use a app such as SQLiteman to do this for you.


text:
Q: Return two arrays from observeSingleEvent I have questions and answers in Firebase Realtime Database, which I need to be downloaded and put in to arrays. I have created a function which takes a parameter and should return two arrays
let data = fetchQuestions(category: "Animals")
qAni = data.ques
aAni = data.ans

fetchQuestions method:
func fetchQuestions(category: String) -> (ques: [String], ans: [String]) {
        var q = [String]()
        var a = [String]()
        ref.child("QA/Category").observeSingleEvent(of: .value, with: { (snapshot) in
            let value = snapshot.value as? [String: Any]
            for (k, v) in value! {
                if k == category {
                    let QA = v as! NSArray
                    for i in QA {
                        let question = i as! [String: String]
                        q.append(question["question"]!)
                        a.append(question["answer"]!)
                    }
                    return (q, a)  ** Unexpected non-void return value in void function
                }
            }
        })
    }

I have tried to use dispatch group, but then I receive a different error.

A: You are currently returning from the completion block of observeSingleEvent and its return type is void, What you need is you need to create completionHandler with your fetchQuestions. Now with Swift instead of using NSArray use Swift native array. Also instead of maintaining two array maintain one array with custom objects of struct or class.
So first create one struct like this.
struct Category {
    let question: String
    let answer: String
}

Now make completionHandler with your fetchQuestions like this way.
func fetchQuestions(category: String, completion: @escaping([Category]) -> Void) {
    var array = [Category]
    ref.child("QA/Category").observeSingleEvent(of: .value, with: { (snapshot) in
        let value = snapshot.value as? [String: Any]
        for (k, v) in value! {
            if k == category {
                let QA = v as! [[String:String]]
                for i in QA {
                    let que = i["question"]!
                    let ans = i["answer"]!
                    array.append(Category(question: que, answer: ans))
                }
            }
        }
        completion(array)
    })
}

Now call fetchQuestions this way.
self.fetchQuestions(category: "Animals") { categories in
    //access categories here
    print(categories)
}

Note: Instead of comparing value in for loop you can also use queryEqual(toValue:) with your request to get specific result check this SO thread for more details on it.

A: Its because you are returning a value from a closure instead you should use different closure for that. Try it:
func fetchQuestions(category: StringcompletionBlock:@escaping (_ ques:[String], _ ans :[String]) -> ()) {
    var q = [String]()
    var a = [String]()
    ref.child("QA/Category").observeSingleEvent(of: .value, with: { (snapshot) in
        let value = snapshot.value as? [String: Any]
        for (k, v) in value! {
            if k == category {
                let QA = v as! NSArray
                for i in QA {
                    let question = i as! [String: String]
                    q.append(question["question"]!)
                    a.append(question["answer"]!)
                }

            }
          return completionBlock(q,a)
        }
    })
}

@escaping is required :   when the closure is passed as an argument to
  the function, but is called after the function returns.


text:
Q: LWJGL: Discolored Textures So I am developing a small Pong replica simply for some practice with LWJGL.  Since there is no easy way to write customizable text in LWJGL, I am using textures for the start button, other buttons, and so on.  However, when I drew the texture, it turned out to be discolored on my purple background.  If I change the background to white, there is no discoloration.  Help?
Also, my start button texture is something like 50x22, but I put it on a 64x64 image because Slick can only load resolutions that are an exponent of two.  I adjusted the rectangle being drawn so that it is not warped, and the rest of the image is transparent, so it shouldn't be visible once I sort out the above problem.  Are there any alternatives to my method?
This is where I initialize my OpenGL stuff:
public static void setCamera()
{
    glClear(GL_COLOR_BUFFER_BIT);
    glEnable(GL_TEXTURE_2D);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,width,0,height,-1,1);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
}

And this is where I draw the texture:
public void draw()
{
    logic();
    glPushMatrix();
    glTranslated(x,y,0);
    texture.bind();
    glBegin(GL_QUADS);
    glTexCoord2d(0,1); glVertex2d(0,-196.875);
    glTexCoord2d(1,1); glVertex2d(width+18.75,-196.875);
    glTexCoord2d(1,0); glVertex2d(width+18.75,height);
    glTexCoord2d(0,0); glVertex2d(0,height);
    glEnd();
    glPopMatrix();
}

Thanks :)

A: As discussed in comments, your initial problem was that you had neglected to reset the "current color" before drawing your texture. GL is a glorified state machine, it will continue to use the color you set for every other draw operation... so setting glColor3d (...) when you drew your background also affects your foreground image.
Adding the following before drawing your textured quad will fix this problem:
glColor3f (1.0f, 1.0f, 1.0f);

However, you have brought up a new issue in your comments related to blending. This question boils down to a lack of a blending function. By default when you draw something in OpenGL it will merely overwrite anything else in the framebuffer.
What you need for transparency to work is enable blending and use this function:
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

This effectively does the following:
NewColor = (NewColor.RGB * NewColor.A) + OldColor.RGB * (1.0 - NewColor.A)

With this, the parts of your texture that have an alpha value != 1.0 will be a mix of whatever was already in the framebuffer and what you just drew.
Remember to enable blending before you draw your transparent objects:
glEnable (GL_BLEND);

and disable it when you do not need it:
glDisable (GL_BLEND);

Lastly, you should be aware that the order you draw translucent objects in OpenGL is pretty important. Opaque objects (such as your background) need to be drawn first. In general, you need to draw things from back-to-front in order for alpha blending to function correctly. This is the opposite order you would ideally want for opaque geometry (since hardware can skip shading for obstructed objects if you draw objects in front of them first).


text:
Q: Summary sheet created from multiple worksheets using a dynamic range I have a 176 worksheets in a workbook, that all have the same format/structure, but are a difference size in row length.
I want to copy the data that is held in range A10:V(X) where X is a calculable number. This data will be pasted underneath each other, in columns B:W of the main sheet "RDBMergeSheet" and the name of the sheet that each row came from will be pasted into Column A of RDBMergeSheet so it can be seen which rows came from which sheets
X = (The lowest used row number in column J) - 3
If it makes it easier, another way to calculate X is find the row number in column A that contains the word "total" and subtract 1 from it.
The following link contains an example of such a sheet, with sanitised data.
https://imgur.com/a/emlZj
The code I've got so far, with help, is:
    Sub ImportData()

Dim x       As Long
Dim LR      As Long

Dim wks     As Worksheet

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .DisplayAlerts = False
End With

Set wks = Sheets("RDBMergeSheet"): If Not wks Is Nothing Then wks.Delete
Set wks = Worksheets.Add(after:=Worksheets(Sheets.Count))
wks.Name = "RDBMergeSheet"

For x = 1 To Worksheets.Count - 1
    LR = Application.Max(1, Sheets(x).Cells(Rows.Count, 10).End(xlUp).Row - 3)
    With wks.Cells(Rows.Count, 1)
        .Offset(1, 1).Resize(LR, 22).Value = .Cells(1, 10).Resize(LR, 22).Value
        .Offset(1).Resize(LR - 9).Value = Sheets(x).Name
    End With
Next x

wks.Select

With Application
    .ScreenUpdating = False
    .EnableEvents = False
    .DisplayAlerts = False
End With

Set wks = Nothing

End Sub

This errors out with a 1004: Application defined or object defined error on line
.Offset(1, 1).Resize(LR, 22).Value = .Cells(1, 10).Resize(LR, 22).Value

If anyone has any ideas on either how to resolve this I would be extremely grateful.

A: Please give this a try and tweak it as per your requirement to make sure the correct data is copied starting from the correct row on destination sheet.
Sub ImportData()
Dim LR As Long, dLR As Long, i As Long
Dim wks As Worksheet

With Application
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
    .EnableEvents = False
    .DisplayAlerts = False
End With

On Error Resume Next
Set wks = Sheets("RDBMergeSheet")
wks.Cells.Clear
On Error GoTo 0

If wks Is Nothing Then
    Set wks = Worksheets.Add(after:=Worksheets(Sheets.Count))
    wks.Name = "RDBMergeSheet"
End If

For i = 1 To Worksheets.Count - 1
    If Worksheets(i).Name <> wks.Name Then
        LR = Application.Max(1, Sheets(i).Cells(Rows.Count, 10).End(xlUp).Row - 3)
        If LR > 9 Then
            If wks.Range("B1").Value = "" Then
                dLR = 1
            Else
                dLR = wks.UsedRange.Rows.Count + 1
            End If
            wks.Range("B" & dLR & ":X" & LR - 9).Value = Worksheets(i).Range("B10:X" & LR).Value
            wks.Range("A" & dLR).Value = Worksheets(i).Name
        End If
    End If
Next i

On Error Resume Next
wks.Select
dLR = wks.UsedRange.Rows.Count
wks.Range("A1:A" & dLR).SpecialCells(xlCellTypeBlanks).Formula = "=R[-1]C"

wks.Range("A1:A" & dLR).Value = wks.Range("A1:A" & dLR).Value

With Application
    .Calculation = xlCalculationAutomatic
    .ScreenUpdating = True
    .EnableEvents = True
    .DisplayAlerts = True
End With

Set wks = Nothing

End Sub


text:
Q: Save ggpairs figures created by lapply into single pdf I am trying to generate several figures using ggpairs and save them all in a single PDF. The code below is a simplified version of what I would like to accomplish. The error is included as well. I am able to generate the figures, but not able to arrange them into a single file. Any help would be appreciated, Thanks!
mtcars <- as.data.frame(mtcars)

#Define my plotting function
plot_corr_matrix <- function(col) {

  ggpairs(mtcars, columns = c(col:(col+2)), diag = list(continous = "blankDiag"), upper  = list(continuous = "blank")) +
    theme_bw()
  }

#Use lapply to go through several variables
plots <- lapply(seq(1,7, by = 3 ), plot_corr_matrix)

#Save in single PDF
ggsave(
  filename = "Correlation Test.pdf",
  plot = marrangeGrob(plots, nrow=5, ncol=1),
  width = 8.5, height = 11
)

Error:
Error in gList(list(data = list(mpg = c(21, 21, 22.8, 21.4, 18.7, 18.1,  :
  only 'grobs' allowed in "gList"

A: You can use ggpubr::ggarrange, which has argument plotlist, which can use the list of ggplots as input and put them all in a single figure to save.


text:
Q: Error with doctrine mapping import I'm trying to import a database already created for another project (not a symfony one), so I can use it inside a symfony project.
Validation works
    php bin/console doctrine:schema:validate
    [Mapping]  OK - The mapping files are correct.
    [Database] OK - The database schema is in sync with the mapping files.
But when I make php bin/console doctrine:mapping:import AppBundle annotation it return

In MappingException.php line 588:
  It is not possible to map entity 'Tprovincia' with a composite primary
  key as part of the primary key of another entity 'Tlocalidad#paiscod'.

This is de configuration of those tables
CREATE TABLE tprovincia
(
  paiscod smallint NOT NULL, -- Código de país
  procod smallint NOT NULL, -- Código de provincia
  prodes character varying(100) NOT NULL, -- Nombre de provincia
  prodesamp character varying(250) NOT NULL, -- Descripción ampliada de provincia
  prousupro character varying(30) NOT NULL, -- Pro Usu Pro
  profecpro timestamp without time zone NOT NULL, -- Pro Fec Pro
  CONSTRAINT tprovincia_pkey PRIMARY KEY (paiscod, procod),
  CONSTRAINT itprovincia1 FOREIGN KEY (paiscod)
      REFERENCES tpais (paiscod) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);

CREATE TABLE tlocalidad
(
  paiscod smallint NOT NULL, -- Código de país
  procod smallint NOT NULL, -- Código de provincia
  loccod integer NOT NULL, -- Código de localidad
  locdes character varying(100) NOT NULL, -- Descripción de localidad
  loccodpos character(8) NOT NULL, -- Código postal localidad
  locusupro character varying(30) NOT NULL, -- Loc Usu Pro
  locfecpro timestamp without time zone NOT NULL, -- Loc Fec Pro
  CONSTRAINT tlocalidad_pkey PRIMARY KEY (paiscod, procod, loccod),
  CONSTRAINT itlocalidad1 FOREIGN KEY (paiscod, procod)
      REFERENCES tprovincia (paiscod, procod) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
  OIDS=FALSE
);

One more thing, the database is a postgreSQL one.
Hope someone can help.
Thanks!

A: The problem is the composite primary keys defined here:
CONSTRAINT tprovincia_pkey PRIMARY KEY (paiscod, procod)

and here:
CONSTRAINT tlocalidad_pkey PRIMARY KEY (paiscod, procod, loccod)

What you could do is modify your database a little bit to use a more typical single id field as primary key (you can keep the old key with a UNIQUE index to have something that is close to a primary key) and then reference that as foreign key.


text:
Q: GOOGLE sheets: search pair of values in two column to match and get value I a GOOGLE sheets, I need to search for a pair of values in two column to match and get value.
Take a look at this capture to see what I mean:

I tried with =VLOOKUP(B2:C2;F:G;E:E) in this google sheets document (anyone can edit): https://docs.google.com/spreadsheets/d/1D2VPUvxJIZxIY1cqbgsoDnja2g1pmw19ScNA1JLQ1mg/edit?usp=sharing but it not working.
Is there a way to do this.

A: In A2 try
=ArrayFormula(IF(LEN(B2:B)*LEN(C2:C); VLOOKUP(B2:B&C2:C; {F2:F&G2:G\ E2:E}; 2; 0);))


text:
Q: find First/ Last observation value by group? I am trying to find the first/last observation by group. I tired both R and excel (because it is so slow in R so I tried excel). The excel took less than one second, but R took 8 MINUTES!!!. The code logic for both are almost the same.
The data is a panel data regarding purchasing fruit. The same shopper could buy multiple times at different time. I have 233,000 observations. Data is like(sorted by day shopper first and day):
    Day Shopper Choice
    1   A   apple
    2   A   apple
    1   B   Banana
    1   C   apple
    2   C   Banana
    3   C   apple
    1   D   berry
    2   D   berry

My r code for the first obseravtion. I want to tag the first observation in a group by indicator "1", a new column.
 for (i in 1:n)
 { ifelse (dt$shopper[i+1]==dt$shopper[i],newcol[i+1]<-0,newcol[i+1]<-1)
  }

My excel code is:
          if(B2<>B1,1,0)
I need the repurchase matrix given the same shopper. To define the  repurchase : the repurchase of the "1st purchase" is the "2nd purchase"; And the repurchase of the "2nd purchase" is the "3rd purchase" The last purchase has no repurchase. Sorry it sounds like a twister.
so my solution is get two choice col and move the second col one row above so I can calculate the repurchase matrix by shopper/or aggregate.The desired output for tagging first obs by group should be as follow. With the  columns of choice and choice 2 and I can calculate the repurchase matrix by nrow.
Day Shopper Choice  tagging choice 2
 1  A   apple      0       *apple*
 2  A   apple      *apple*  0
 1  B   Banana     0        0
 1  C   apple      0        Banana
 2  C   Banana     Banana   apple
 3  C   apple      apple    0
 1  D   berry      0        *berry*
 2  D   berry      *berry*  0

[update]. If there is only one purchase for this user, there is no repurchase. If the purchase is the last purchase of the user, there is no repurchase. So the final repurchase matrix by choice in this case is
        second  inside bracket are the probability
first   apple banana berry
apple   1 (0.5)  1      0
banana  1        0 (0)  0
berry   0        0      1 (1)

Below is how I calculate the repurchase matrix after tagging the first purchase of the user. i is the row (apple, banana, Berry etc) and j (apple, banana, Berry etc) is the column. [the speed is ok give the fact that I repurchase matrix is 40*40 after tagging and adding the seconding choice column)
    for (i in 1:n){
    for(j in 1:n){
    repurchase_matrix[i,j]=nrow(dt[dt[,1]==i&dt[,2]==j,])}}

A: First, assuming the data are sorted by Shopper and then by Day in ascending order, you can add a column indicating the purchase number with
df$Purchase <- unlist(with(df, tapply(Shopper, Shopper, seq_along)))
df
#  Day Shopper Choice Purchase
#1   1       A  apple        1
#2   2       A  apple        2
#3   1       B Banana        1
#4   1       C  apple        1
#5   2       C Banana        2
#6   3       C  apple        3
#7   1       D  berry        1
#8   2       D  berry        2

Then reshape the data-frame to "wide" format with
df.w <- reshape(df[c('Shopper', 'Choice', 'Purchase')],
                idvar='Shopper', v.names='Choice', timevar='Purchase',
                direction='wide')
df.w
#  Shopper Choice.1 Choice.2 Choice.3
#1       A    apple    apple     <NA>
#3       B   Banana     <NA>     <NA>
#4       C    apple   Banana    apple
#7       D    berry    berry     <NA>

Finally you calculate the repurchase matrix of the first two purchases
with(df.w, prop.table(table(First=Choice.1, Second=Choice.2)))
#        Second
#First        apple    Banana     berry
#  apple  0.3333333 0.3333333 0.0000000
#  Banana 0.0000000 0.0000000 0.0000000
#  berry  0.0000000 0.0000000 0.3333333

To calculate the repurchase matrix of all purchases, start with the repurchase matrices of every two consecutive purchases
repurchase <- lapply(seq(2, ncol(df.w) - 1),
                     function(i) table(First=df.w[[i]], Second=df.w[[i + 1]]))
repurchase <- simplify2array(repurchase)
repurchase
#, , 1
#
#        Second
#First    apple Banana berry
#  apple      1      1     0
#  Banana     0      0     0
#  berry      0      0     1
#
#, , 2
#
#        Second
#First    apple Banana berry
#  apple      0      0     0
#  Banana     1      0     0
#  berry      0      0     0

then add all matrices to get the "total" repurchase matrix
apply(repurchase, 1:2, sum)
#        Second
#First    apple Banana berry
#  apple      1      1     0
#  Banana     1      0     0
#  berry      0      0     1

(absolute frequencies)
prop.table(apply(repurchase, 1:2, sum))
#        Second
#First    apple Banana berry
#  apple   0.25   0.25  0.00
#  Banana  0.25   0.00  0.00
#  berry   0.00   0.00  0.25

(relative frequencies)

A: In R, we can use dplyr.  After grouping by 'Shopper', create the 'Flag' column for first observation by using the logical condition row_number() < 2 and convert the logical to integer if required.
library(dplyr)
df1 %>%
   group_by(Shopper) %>%
   mutate(Flag = as.integer(row_number() < 2))

If we can use the minimum and maximum 'Day' as the identifier, then use the logical condition based on that.
df1 %>%
     group_by(Shopper) %>%
     mutate(Flag = as.integer(Day %in% range(Day)))

Or using data.table
library(data.table)
setDT(df1)[, Flag := as.integer(Day %in% range(Day)), by = Shopper]

Or using base R, we can compare the previous 'Shopper' with the current 'Shopper' (assuming that the dataset is already ordered)
i1 <- with(df1, Shopper[-1]!= Shopper[-nrow(df1)])
as.integer(c(TRUE, i1)|c(i1, TRUE))
#[1] 1 1 1 1 0 1 1 1

All these methods should be faster than the for loop in the OP's code.
Update
Based on the updated expected output, if we need to replace the 1st observation with "0" while the others remain same, either an ifelse or replace can be used and using the lead of 'tagging', we create the 'tagChoice2'.
df1 %>%
   group_by(Shopper) %>%
   mutate(tagging = ifelse(row_number()==1, "0", as.character(Choice)),
          tagChoice2 = lead(tagging, default = "0"))
#   Day Shopper Choice tagging tagChoice2
#  <int>   <chr>  <chr>   <chr>      <chr>
#1     1       A  apple       0      apple
#2     2       A  apple   apple          0
#3     1       B Banana       0          0
#4     1       C  apple       0     Banana
#5     2       C Banana  Banana      apple
#6     3       C  apple   apple          0
#7     1       D  berry       0      berry
#8     2       D  berry   berry          0

A: I was looking for answer to finding first and last value of a column by grouping
in data.table. After looking here and there, and thinking about it, here you go.
To create order of rows by group:
library(data.table)

DT <- data.table(col1 = rep(LETTERS[1:2], each = 4), col2 = c(3,12,5,56,6,678,233,70))
setorder(DT, col1, col2)
DT
   col1 col2
1:    A    3
2:    A    5
3:    A   12
4:    A   56
5:    B    6
6:    B   70
7:    B  233
8:    B  678

DT[, rank := order(col2), by = col1]
DT
   col1 col2 rank
1:    A    3    1
2:    A    5    2
3:    A   12    3
4:    A   56    4
5:    B    6    1
6:    B   70    2
7:    B  233    3
8:    B  678    4

To create first and last values by group:
DT[, first_val := col2[1], by = col2]
DT[, last_val := col2[.N], by = col1]
DT
   col1 col2 rank first_val last_val
1:    A    3    1         3       56
2:    A    5    2         3       56
3:    A   12    3         3       56
4:    A   56    4         3       56
5:    B    6    1         6      678
6:    B   70    2         6      678
7:    B  233    3         6      678
8:    B  678    4         6      678

A: You can try install the Microsoft R open as your default R. In terms of math calculation, it is way faster than R base. Because it employs more cores while the R.BASE only uses one core to compute.


text:
Q: Production Grade microservices architecture in AWS I have a new web application which in our company we have decided to be like below and i am creating the architecture for the first time
so would require some inputs.
1) Front End - React.js
2) Backend - Java (Spring boot)
3) Architecture - Microservices
4) Infra - AWS
5) CI - Jenkins
We have divided the development in three phases
Phase 1 - Create AWS infra, front end service and few backend services using Spring Boot and Spring Cloud. Keep the use of AWS services to as minimum as possible
Phase 2 - Create more backend services and dockerize everything
Phase 3 - Orchestrate previous phase using Kubernetes and use more AWS services if required
I am at phase 1 and after going through lot of resources and study material, need help in creating production grade architecture and AWS environment.
There are lot of individual resources but did not find much on how the real system should look like in when it is live.
1) how to isolate environments?
My understanding - create organization which will have 5 accounts -  root, security, shared-services ,prod and non-prod aws accounts. Non-prod can have multiple environments if required like test,stage.
Something like this

2) How to create security/network layer?
My understanding - create private and public subnets and create vpc peering between like shared-service and non-prod env and use iam roles.
3) Best way for designing microservices?
my understanding - have a micro frontend and microservices in backend. Client will request webpage in browser the request will come to UI service.

*

*I am confused what is the order of components.

*Either it should come to react app first and then it would go to api gateway or ELB?

*Do we need ELB?

*Request would come to ELB and then it will go to API gateway and further?

*Answer to all these questions will determine answer to next question

*Option A or B? Or if both are wrong? Or where should be arrows heading from client to backend services?
Option A

Option B

4) Which resources to keep in private and public subnets?
my understanding - in phase 1, follow one instance per service model so each service will have ec2 instance. in later phases we will move to containerization. few things are clear that backend services and persistence like DB will be in private subnet and keep very less resources in public like only bastion hosts etc
- Question is depending on answer for question #3, what others should be public?

- ELB, api gateway, service discovery?

- do i need to keep NAT gateway always so as to allow private ones to access internet?

5) What should be the complete release deployment workflow?
my understanding - developer commits code, jenkins should trigger the build, store artifacts and deploy.
    - how should jenkins server communicate with other machines to deploy services?
- how credentials are managed for communication between jenkins and ec2 instances?

- what is the production grade structure for jenkins project? like does build, deploy and test should be separate items?

I would really appreciate if some experienced architects can help me out if you  have configured same in your enterprise/organisations and also let me know if there are any references available online which i could not find for building such production grade systems
Note - Phase 1 should be designed in a way to have as smooth transition as possible to phase 2 and 3

A: This is a complex question which we cannot do justice to on Stack Overflow.
I would recommend spending some time reading:

*

*Implementing Microservices on AWS

*Delivering Excellence with Microservices on AWS

*Serverless Application Lens
You could also research content from AWS serverless heroes.


text:
Q: Scala swing wait for a button press after pressing a button So What I want to do is to press a button and inside the ButtonClicked Event I want to wait completing the event, until I press a specific button/one of the specified buttons.
I also know that there are some similar questions to this topic but I wasnt able to find a fix out of the answers
So basically this:
reactions += {
    case event.ButtonClicked(`rollDice`) =>
        some code ...
        wait for one of the specified buttons to be pressed and then continue
        some code ...

Is there an easy way to solve this problem without the use of threads?

A: There are certainly some abstractions you could set up around the event layer, but you asked for "easy", so my suggestion is to set a flag/state when the dice are rolled, and then check for that flag in the other buttons' event handler.
private var postDiceRollState: Option[InfoRelatedToRollDice] = None

reactions += {
  case event.ButtonClicked(`rollDice`) =>
    // capture whatever info you need to pass along to the later button handler
    val relevantInfo = /* some code... */

    // store that info in the "state"
    postDiceRollState = Some(relevantInfo)

  case event.ButtonClicked(other) if isPostDiceRollButton(other) =>
    // when the other button gets clicked, pull the relevant info from your "state"
    postDiceRollState match {
      case Some(relevantInfo) =>
        postDiceRollState = None // clear state
        doInterestingStuff(relevantInfo) // "some code..."
      case None =>
        // nothing happens if you didn't roll the dice first
    }
}

Note: I represented the "flag" as an Option, under the assumption that you might have some information you want to capture about the rollDice event. If you don't actually have anything to put in there, you could represent your state as private var didRollDice: Boolean = false and set/clear would be setting it to true/false respectively.


text:
Q: how to handle multiple forms on one page? On one page i have list of questions with diffrent tipe of answers. (texboxes, checkboxes etc) Page is dynamicly generated. I have to store answers in database. What is the best way to do this? multiple forms or something else?
it would be great if i could send ajax request after every answer but i don't know how to accomplis that (how to detect that user have entered the answer and went to next question)
i'm using asp.net mvc with c#

A: You can send only a single form per HTTP request, so to make things more simple, you should only use a single form and give each answer field a unique name that you can then use on the server to map it to the database.
I suggest not to send an AJAX request after the applicant has "finished" with a question. Many people want to answer all questions and then go over the answers a second time.
Therefore, I also advise against using a "Wizard" approach (or a one question per page and you get the next question after submitting the current answer).

A: I agree with Aaron's response that you don't want to save their response using an AJAX request after every question. However, if you ever encounter a situation where you do need to fire an AJAX request based on the user editing data in a form field, you can accomplish this by listening for Javascript events like 'onChange' and 'onBlur' and fire the AJAX request from that event listener.


text:
Q: Pattern in C# for loading data from large files with low memory impact I have a scenario, where I load data from large files, e.g. json and I would like to keep the memory usage as low as possible. The other problem is that I would like to encapsulate the data loading from the processing part, so I can also implement an importer for xml for example.
If the data contains only a simple list it is quite easy, I can define an interface like this:
interface IImporter
{
   IEnumerable<Data> LoadFrom(Stream stream);
}

And then I can implement it using the yield keyword:
class JsonImporter : IImporter
{
    public IEnumerable<Data> LoadFrom(Stream stream)
    {
        JsonReader reader = ...;
        ...
        while (...)
        {
            yield return new Data(reader.Read(...));
        }
    }
}

The advantage is that the memory impact is very low, if the JsonReader works efficiently only one Data object is in memory (depending on the processing). The negative side is that you cannot iterate over the enumerable twice depending on the situation.
But what happens if there is more complex data, e.g. first a header with some simple properties in json and then two array with totally different structure? In this case an IEnumerable does not work anymore. Do you have some patterns here or is there a framework for this. I think also about buffering and how the consumer can notify the producer that processing has been finished, so the stream (or the sql connection, ...) can be closed and disposed. Looking for some ideas.


text:
Q: Change color of child element while there is "use" element in SVG
in this image the top is view on screen while the bottom is only see while hover over it with SVG.
For that My SVG Code is as below.
<svg width="164px" height="125px" viewBox="0 0 164 125" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:sketch="http://www.bohemiancoding.com/sketch/ns">
    <title>android-store</title>
    <defs></defs>
    <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd" sketch:type="MSPage">
        <g id="android-store-+-social-android-+-social-android-copy-2" sketch:type="MSLayerGroup">
            <g id="android" transform="translate(1.000000, 1.000000)">
                <rect id="Rectangle-4" stroke="#4CA141" sketch:type="MSShapeGroup" x="0" y="0" width="162" height="53" rx="2"></rect>
                <g id="Group" transform="translate(9.000000, 10.000000)" fill="#4CA141" sketch:type="MSShapeGroup">
                    <g transform="translate(0.000000, 9.630682)" id="Shape">
                        <path d="M5.45454545,7.875 L5.45454545,15.5113636 C5.45454545,16.0994318 5.83806818,16.7045455 6.42613636,16.7045455 L8.86363636,16.7045455 L8.86363636,21.1363636 C8.86363636,22.2698864 9.77556818,23.1818182 10.9090909,23.1818182 C12.0426136,23.1818182 12.9545455,22.2698864 12.9545455,21.1363636 L12.9545455,16.7045455 L17.1306818,16.7045455 L17.1306818,21.1363636 C17.1306818,21.7755682 17.4204545,22.3465909 17.8806818,22.7215909 C18.2130682,23.0113636 18.65625,23.1818182 19.1335227,23.1818182 L19.1590909,23.1818182 L19.1761364,23.1818182 C20.3096591,23.1818182 21.2215909,22.2698864 21.2215909,21.1363636 L21.2215909,16.7045455 L23.5738636,16.7045455 C24.1704545,16.7045455 24.5454545,16.0994318 24.5454545,15.5198864 L24.5454545,7.88352273 L24.5454545,1.36363636 L5.45454545,1.36363636 L5.45454545,7.875 L5.45454545,7.875 Z"></path>
                        <path d="M27.9545455,0 C26.8210227,0 25.9090909,0.911931818 25.9090909,2.04545455 L25.9090909,10.2272727 C25.9090909,11.3607955 26.8210227,12.2727273 27.9545455,12.2727273 C29.0880682,12.2727273 30,11.3607955 30,10.2272727 L30,2.04545455 C30,0.911931818 29.0880682,0 27.9545455,0 L27.9545455,0 Z"></path>
                        <path d="M2.04545455,0 C0.911931818,0 0,0.911931818 0,2.04545455 L0,10.2272727 C0,11.3607955 0.911931818,12.2727273 2.04545455,12.2727273 C3.17897727,12.2727273 4.09090909,11.3607955 4.09090909,10.2272727 L4.09090909,2.04545455 C4.09090909,0.911931818 3.17897727,0 2.04545455,0 L2.04545455,0 Z"></path>
                    </g>
                    <path d="M19.7045455,2.22443182 L21.28125,0.357954545 C21.3153409,0.315340909 21.2642045,0.221590909 21.1704545,0.144886364 C21.0767045,0.0767045455 20.9659091,0.0596590909 20.9403409,0.110795455 L19.3039773,2.05397727 C18.1448864,1.59375 16.7301136,1.30397727 14.9914773,1.30397727 C13.2443182,1.29545455 11.8210227,1.57670455 10.6619318,2.02840909 L9.04261364,0.119318182 C9.00852273,0.0767045455 8.90625,0.0852272727 8.8125,0.153409091 C8.71875,0.221590909 8.66761364,0.306818182 8.70170455,0.366477273 L10.2613636,2.20738636 C6.15340909,3.98863636 5.53977273,8.36079545 5.45454545,9.63920455 L24.5113636,9.63920455 C24.4346591,8.35227273 23.8295455,4.03977273 19.7045455,2.22443182 L19.7045455,2.22443182 Z M11.65625,7.20170455 C11.1081019,7.20170455 10.65625,6.75057673 10.65625,6.20170455 C10.65625,5.65283237 11.1006944,5.20170455 11.65625,5.20170455 C12.2043981,5.20170455 12.65625,5.65283237 12.65625,6.20170455 C12.65625,6.75057673 12.2118056,7.20170455 11.65625,7.20170455 L11.65625,7.20170455 Z M18.0426136,7.20170455 C17.4944655,7.20170455 17.0426136,6.75057673 17.0426136,6.20170455 C17.0426136,5.65283237 17.4870581,5.20170455 18.0426136,5.20170455 C18.5907618,5.20170455 19.0426136,5.65283237 19.0426136,6.20170455 C19.0426136,6.75057673 18.5907618,7.20170455 18.0426136,7.20170455 L18.0426136,7.20170455 Z" id="Shape"></path>
                </g>
                <g id="Available-on-+-Android-Store" transform="translate(50.000000, 9.000000)" font-family="Open Sans, sans-serif" fill="#4CA141" sketch:type="MSTextLayer" font-weight="normal">
                    <text id="Available-on" font-size="10">
                        <tspan x="0" y="11">Available on</tspan>
                    </text>
                    <text id="Android-Store" font-size="16">
                        <tspan x="0" y="31">Android Store</tspan>
                    </text>
                </g>
            </g>

            <use x="1" y="71" xlink:href="#android" style=""/>

        </g>
    </g>
</svg>

Now from the above code the top image is repeat but in this i have repeated the whole covered  element which has id="android". But you can see for the repeated image i want to change child element's color.
Another thing is i want to use that as an background image so please do not suggest code as inline SVG Working.


text:
Q: What is the meaning of this NLP notation? I am learning NLP to try and do relation extraction on a corpus. I found these slides and am trying to parse the notation for a high-dimensional feature vector (shown below).

where

How do I turn the top most equation into an English sentence? For each input text unit, x ; for each possible feature, y -- the feature x is-a y can be represented by a feature vector? I am used to seeing cartesian product notation and I am used to seeing function notation and I am used to seeing set builder notation. But there are too many unfamiliar things going on in that line for me to understand what it says. What does the colon mean? What does the arrow mean?

A: That means that f is a function which takes an input and an output and produces a vector. In this context, the input is usually a word sequence, and the output a candidate labeling of that word sequence - e.g. a sequence of part-of-speech tags or a parse tree. There are some examples on slide 8 of Ryan McDonald's slide deck linked in the question.
McDonald makes this point too, but I'll repeat it here: In some cases, we can produce a feature vector purely from the input sequence (without reference to an output). E.g., if we're tagging word 2 of the sentence 'F is a function', and our feature mapping included only the current word and the previous word, we'd incorporate 'F' as the previous word and 'is' as the current word. But in some cases (notably 'structured prediction') we'll want to include features depending on a candidate labeling as well - perhaps a label sequence over the entire input (note that that will usually result in a huge feature space).
One other note: McDonald's mapping is to a real-valued vector (R^n), but in NLP, we often find that indicator features are sufficient, so many systems us a bit vector instead (still in a very high dimensional space). The formalism doesn't change (only the mapping function f), but the simplifying assumption will often allow efficiencies in the weight vector storage and dot-product implementation.

A: This is function notation. It says that there is a function f with a domain = X x Y and a codomain = R^n -- where X is some input text and Y is some label.
In other words, it maps each of all possible combinations of texts and labels and maps them somewhere into an n-dimensional space.


text:
Q: Pragmatic use of code-behind in MVVM pattern I'm trying to follow the MVVM pattern in a WPF application as good as I can, mainly to be able to create unit tests for my ViewModel logic.
In most cases data binding between ViewModel properties and properties of visual elements works fine and is easy. But sometimes I encounter situations where I cannot see an obvious and straightforward way while a solution to access and manipulate controls from code-behind is very easy.
Here is an example of what I mean: Inserting a text fragment into a TextBox at the current caret position
Since CaretIndex isn't a dependency property it can't be bound directly to a ViewModel's property. Here is a solution to work around this limitation by creating a dependency property. And here is the solution to do this in code-behind. I would prefer the code-behind way in this situation. Another problem I recently had was binding a dynamic collection of columns to a WPF datagrid. It was clear and simple to program in code-behind. But for a MVVM-friendly databinding approach I could only find work arounds in several blogs which all looked quite complex to me and had various limitations in one or the other aspect.
I don't want to keep the MVVM architecture clean of code-behind logic at all costs. If the amount of work arounds is too big, a MVVM-friendly solution requires a lot of code which I don't fully understand (I'm still a WPF beginner) and is too time consuming I prefer a code-behind solution and sacrifice automatic testability of a few parts of my application.
For the mentioned pragmatic reasons I am looking now for "patterns" to make controlled use of code-behind in an application without breaking the MVVM architecture or without breaking it too much.
Up to now I've found and tested two solutions. I will draw rough sketches with the Caret Position example:
Solution 1) Give the ViewModel a reference to the View through an abstract interface

*

*I would have an interface with methods which would be implemented by the view:
public interface IView
{
    void InsertTextAtCaretPosition(string text);
}

public partial class View : UserControl, IView
{
    public View()
    {
        InitializeComponent();
    }

    // Interface implementation
    public void InsertTextAtCaretPosition(string text)
    {
        MyTextBox.Text = MyTextBox.Text.Insert(MyTextBox.CaretIndex, text);
    }
}

*Inject this interface into the ViewModel
public class ViewModel : ViewModelBase
{
    private readonly IView _view;

    public ViewModel(IView view)
    {
        _view = view;
    }
}

*Execute code-behind from a ViewModel's command handler through the interface methods
public ICommand InsertCommand { get; private set; }
// Bound for instance to a button command

// Command handler
private void InsertText(string text)
{
    _view.InsertTextAtCaretPosition(text);
}

To create a View-ViewModel pair I would use dependency injection to instantiate the concrete View and inject it into the ViewModel.
Solution 2) Execute code-behind methods through events

*

*The ViewModel is publisher of special events and command handlers raise those events
public class ViewModel : ViewModelBase
{
    public ViewModel()
    {
    }

    public event InsertTextEventHandler InsertTextEvent;

    // Command handler
    private void InsertText(string text)
    {
        InsertTextEventHandler handler = InsertTextEvent;
        if (handler != null)
            handler(this, new InsertTextEventArgs(text));
    }
}

*The View subscribes to these events
public partial class View : UserControl
{
    public View()
    {
        InitializeComponent();
    }

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        ViewModel viewModel = DataContext as ViewModel;
        if (viewModel != null)
            viewModel.InsertTextEvent += OnInsertTextEvent;
    }

    private void UserControl_Unloaded(object sender, RoutedEventArgs e)
    {
        ViewModel viewModel = DataContext as ViewModel;
        if (viewModel != null)
            viewModel.InsertTextEvent -= OnInsertTextEvent;
    }

    private void OnInsertTextEvent(object sender, InsertTextEventArgs e)
    {
        MyTextBox.Text = MyTextBox.Text.Insert(MyTextBox.CaretIndex, e.Text);
    }
}

I am not sure if the Loaded and Unloaded events of the UserControl are good places to subscribe and unsubscribe to the events but I couldn't find problems during test.
I have tested both approaches in two simple examples and they both seem to work. Now my questions are:

*

*Which approach do you think is preferable? Are there any benefits or downsides of one of the solutions which I possibly don't see?

*Do you see (and perhaps practice) other solutions?

Thank you for feedback in advance!

A: Developing WPF applications I found both ways useful. If you need just one call from ViewModel to View, the second option, with event handler, looks simpler and good enough. But if you are requiring more complex interface between these layers, then it makes sense to introduce interface.
And my personal preference is to revert your option one and have a IViewAware interface implemented by my ViewModel and inject this ViewModel into View. Looks like an option three.
public interface IViewAware
{
    void ViewActivated();
    void ViewDeactivated();

    event Action CloseView;
}

public class TaskViewModel : ViewModelBase, IViewAware
{

    private void FireCloseRequest()
    {
        var handler = CloseView;
        if (handler != null)
            handler();
    }

    #region Implementation of IViewAware
    public void ViewActivated()
    {
        // Do something
    }

    public void ViewDeactivated()
    {
        // Do something
    }

    public event Action CloseView;
    #endregion
}

And this a simplified code for your View:
    public View(IViewAware viewModel) : this()
    {
        _viewModel = viewModel;

        DataContext = viewModel;
        Loaded += ViewLoaded;

    }

    void ViewLoaded(object sender, RoutedEventArgs e)
    {
        Activated += (o, v) => _viewModel.ViewActivated();
        Deactivated += (o, v) => _viewModel.ViewDeactivated();

        _viewModel.CloseView += Close;
    }

In real application I usually use an external logic to connect V and VM, for example Attached Behaviors.

A: Specifically for this problem
The simplest solution to this specific case is adding an attached property that does it or a behavior. Behaviors can be a silver bullet for most of these rich-gui-not-supported cases in mvvm.
As for the general case
ViewModel should never ever under any circumstance know about the view, and not even about an IView. in MVVM its "always look up", which means a View can look @ the VM, and the VM can look at the Model. never the other way around.
This creates much better maintainability, since this way the ViewModel doesn't do two things (incharge of logic AND the gui), but only one thing. This is where MVVM is superior to any prior MV* pattern.
I would also try to refrain from having the View rely on the ViewModel in a coupled way. this creates ugly code, and a breakable dependency between the two classes, but sometimes this is more pragmatic as you said.
A prettier way is to send a Loose Message (e.g. Messenger in MVVMLight, or EventAggregator in Prism) from the ViewModel to the View, and thus there is no strong dependency between the two. Some think this is better although IMO this is still a dependency.
Writing code in the View is OK in some situations, and this could be one of those situation. You could achieve a perfect solution using attached-behaviors, but the priniciple is important, like you asked.
MVVM is problematic when you need GUI that is very rich or the UI doens't have the right Properties to bind to.
In those situations you would resort to one of three things:

*

*Attached Behaviors.

*Deriving from existing controls and adding the properties you'd like.

*Actually writing code in the View.

All of those ways are legitimate, but I've ordered them according to what you should resort to first.
To Summarize
The most important thing you have to keep in MVVM is not to keep the codebehind free, but to keep all logic & data to the ViewModel, where as the View must only contain View-related code. The reason architects tell you not to write code behind at all is only because it's a slippery slope. You start writing something small, and you end up doing logical stuff or maintaining application state in the View, which is the big no-no.
Happy MVVMing :)

A: I'd try to keep away from having the ViewModel a reference to the View.
A way of doing that in this case:
Derive from TextBox and add a dependency property that wraps the CaretIndex by subscribing to the OnSelectionChanged event that lets you know the caret has moved.
This way the ViewModel is able to know where the caret is by binding to it.

A: To my mind, the first option is preferable. It still maintains the separation between the View and the ViewModel (via the view interface), and keeps things in their logical places. The use of events is less intuitive.
I am in favour of pragmatic use of code behind in situations where it is either impossible to achieve through bindings, or requires you to add hundreds of lines of XAML to achieve what we can achieve with 3 lines of code behind.
My gut feeling is that if you can more or less be sure of correctness by code review of the code behind (which is the same as what we do with XAML anyway) and keep the main complexity where we can unit test it - ie the ViewModel, then we have a happy medium. It is all too easy to create technically pure MVVM which is a maintainability nightmare.
All IMHO :D

A: I would try and implement this as a blend behavior of the text box similar to this example of selecting and expanding a tree view without using code behind.  I'll try and trow an example together.
http://www.codeproject.com/KB/silverlight/ViewModelTree.aspx
Edit: Elad already mentioned using attached behaviors, which, after doing a couple, really make doing things like this simple.
Another example of a behavior for popup windows in an mvvm fashion: http://www.codeproject.com/KB/silverlight/HisowaSimplePopUpBehavior.aspx

A: Often you need work with controls from code behind when the control is hardly compotible with MVVM. In this case you can use AttachedProperties, EventTriggers, Behaviors from blend SDK to extend functionality of the control. But very often I use inheritance to extend functionality of control and make it more MVVM compatible. You can create own set of controls inherited from base with implemented view functionality. A big advantage of this approach is that you can access ControlTemplate controls, it often neccessary to implement specific view functionality.


text:
Q: Struct in Objective c i need to create four Struct in objective c
they are:
typedef struct FILE_TRANSFER_REQUEST_STRUCT
{
    uint8_t header[16];  // This would be MD5 of String "SymbolTalk"
    uint8_t type;        // Type of structure -> FILE_TRANSFER_REQUEST
    char    fileName[512];
    int     totalSize; //4096
    int     chunkSize; //1024
    int     numChunks; // 4
}FileTransferRequest;

typedef struct FILE_TRANSFER_RESPONSE_STRUCT
{
    uint8_t header[16];  // This would be MD5 of String "SymbolTalk"
    uint8_t type;        // Type of structure -> FILE_TRANSFER_RESPONSE
    ;
}FileTransferResponse;

typedef struct FILE_CHUNK_REQUEST_STRUCT
{
    uint8_t header[16];  // This would be MD5 of String "SymbolTalk"
    uint8_t type;        // Type of structure -> FILE_CHUNK_REQUEST

    uint8_t data[1024];
    uint8_t chunkNumber;
    uint8_t chunkSize;
}FileChunkRequest;

typedef struct FILE_CHUNK_RESPONSE_STRUCT
{
    uint8_t header[16];  // This would be MD5 of String "SymbolTalk"
    uint8_t type;        // Type of structure -> FILE_CHUNK_RESPONSE
    uint8_t chunkNumber;

}FileChunkResponse;

however i have no idea about Objective struct.how  can i do this.where i need to create  this struct(need to avoid class).is it write in objective c class file.can any one tell me how can i get this struct in another class..can any one help me...

A: You would do this exactly the same way as you would in plain C.  Put them in one of your .h files (whichever one makes the most sense for what they are used for), outside of your @interface block.  Then they will not be part of any class.
To use them in a class, just #import the .h file with your struct definition in it.

A: Just use like this...
typedef struct FILE_CHUNK_RESPONSE_STRUCT
{
    uint8_t header[16];  // This would be MD5 of String "SymbolTalk"
    uint8_t type;        // Type of structure -> FILE_CHUNK_RESPONSE
    uint8_t chunkNumber;

}FileChunkResponse;

@class sampleViewController;

@interface sampleAppDelegate : NSObject <UIApplicationDelegate> {
   struct FILE_CHUNK_RESPONSE_STRUCT mystructure;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

@property (nonatomic, retain) IBOutlet sampleViewController *viewController;

@end

Objective-C is the superset of c it supports all c code... If you want to use C++ related classes change the file name to .mm instead of .m


text:
Q: What is smallest addressable value in an octal number called? In a binary number, the smallest addressable value is called as a bit.
In a decimal number, the smallest addressable value is called as a digit.
In an octal number, what is the smallest addressable value called as?

A: According to the Obsolete and unusual units section of the Units of information wikipedia page, an octal digit (3 bit word) has been variously described using the terms:

*

*tribit, triad, triade, and tribble.

which all fit quite nicely.
Having said that, having been a programmer for over 30 years I have never come across any of these words being used in this sense.

A: No matter what base system you use it is called a digit.
So if it is not clear from the context and you need/want to emphasize that it is a digit of a number in base 8 representation then call it octal digit.
Note: Also "bit" is just short for "binary digit".


text:
Q: How can I use a custom field on a SharePoint List edit form? I have a list on a SharePoint site. When I open that list in InfoPath, I see the fields to the right. When I load the edit form, store a value and run a rule based on that stored value.
I will have potentially SEVERAL of these decision points, and adding a new column to my list to store/manage each decision point will clutter the original list beyond recognition.
How can I create a field in my SharePoint-linked InfoPath form directly, but NOT have it associated with a SharePoint list? I don't care if the data is lost when the form closes. It will be regenerated each time the form loads.

A: Short answer: you can't. But I think you have a couple options.
Try using a custom Content Type rather than creating columns directly on the list. When using a CT, you can make the backing fields (i.e. the 'decision point' columns) hidden so they don't appear in forms. This could still produce more 'clutter' than what you're comfortable with, though.
You can also try creating a secondary data source based on a simple XML document. I think this is the method you're looking for. I've only done it one time, but it worked well in my not-too-complicated use case.
First create an XML file, something like this:
<?xml version="1.0" encoding="UTF-8"?>
<logic>
    <valueA></valueA>
    <valueB></valueB>
    <valueC></valueC>
</logic>

Here I've given myself three fields - valueA, valueB, valueC - for storing my 'decision points' inside a single group. Multiple groups may be allowed but I've not tried that.
Next, create a data connection to Receive data from an XML document. You are required to include the file as a resource (which you want to do anyway) when working with SharePoint list forms. And since the XML is basically empty, you might as well load the data on form open. That's about it for the data connection. You can set initial values for these fields in a Form Load rule, if necessary.


text:
Q: email host domain is active or not php/ lumen Is there any library to check whether an email address has an active domain?
Actually, I want to validate an email address whose host domain must be active. I am using Laravel - Lumen micro framework.

A: You can consider the MailboxValidator Laravel Email Validation Package in Github to validate email address using remote API. It connects to the mail server of MX records in real time to check if one account is valid or not. There are both Free and paid plan.
For more information, you can also visit https://www.mailboxvalidator.com/resources/articles/how-to-use-mailboxvalidator-laravel-email-validation-package-to-validate-email-during-registration/


text:
Q: Can a victor volunteer for the Hunger Games? Can a victor volunteer for the Hunger Games?
I was thinking, that if a victor was in the age range for the games, would they be able to volunteer for another tribute?
So to say, if Primrose was picked again (if she was, the odds most certainly won't have been in her favor), would Katniss be able to volunteer and go into the games again?
This question excludes the 75th Games, as this is under different circumstances.

A: I don't think they could, simply because a volunteer comes from the pool of candidates.
Think about the reverse happening for the 75th Hunger Games only victors were in the pool of potential tributes so random teenager X couldn't volunteer to protect their victor.

A: No, only those in the reaping can volunteer.
Victors who are still of reaping age would not be allowed to volunteer to take someone's place in the Hunger Games. The rule of volunteering for the Hunger Games is that another eligible candidate - meaning someone whose name would have been put into the reaping balls but not chosen - can take the place of the one who was chosen.

"The rule is that once a tribute's name has been pulled from the ball, another eligible boy, if a boy's name has been read, or girl, if a girl's name has been read, can step forward to take his or her place." - The Hunger Games (Chapter 2)

Victors' names are not put into the reaping balls again after they win their Games (except of course for the 75th Hunger Games), so they would not be eligible to volunteer.

"But never that I myself would have to be a player in the Games again. Why? Because there's no precedent for it. Victors are out of the reaping for life. That's the deal if you win. Until now." - Catching Fire (Chapter 13)

Volunteers must be eligible to compete in the Games themselves. This becomes even more clear in the case of the 75th Games, when victors are the only ones eligible to compete.

"Without hesitation, he reads, "On the seventy-fifth anniversary, as a reminder to the rebels that even the strongest among them cannot overcome the power of the Capitol, the male and female tributes will be reaped from their existing pool of victors." - Catching Fire (Chapter 12)

The only ones eligible to volunteer for the 75th Hunger Games are previous victors. Only a victor could step in to take the place for one of the victors chosen.

"Brutus, a volunteer from District 2, who must be at least forty and apparently can't wait to get back in the arena. Finnick, the handsome bronze-haired guy from District 4 who was crowned ten years ago at the age of fourteen. A hysterical young woman with flowing brown hair is also called from 4, but she's quickly replaced by a volunteer, an eighty-year-old woman who needs a cane to walk to the stage." - Catching Fire (Chapter 14)

So Haymitch could volunteer for Peeta, and Peeta could volunteer for Haymitch, but no one else could volunteer for either of them because they were the only two living male victors from District 12. No one was eligible to volunteer for Katniss, because she was the only living female victor from District 12.


text:
Q: Control limits in $\bar{x}$ and R chart I am learning a Quality Control course and in theory part I don't understand calculating the control limits for $\bar{x}$ and R chart.I want to know, say when I calculate the R chart control limits no points plot outside the control limit.And therefore using this $\bar{R} $ values I can then go to calculate $\bar{x} $ chart control limits.In that say 2 sample values are plotted outside the control limits and in each of these suppose an assignable cause was found.Therefore we have to remove this point and recalculate control limits for $\bar{x}$ chart.My question is do I have to recalculate the R chart control limits also.Because now in $\bar{x}$ chart 2 samples are removed.Or do I use the earlier $\bar{R} $value and use removing the two samples only recalculate $\bar{x}$?
Also say there's a pattern is present like a cycle or a  shift in process level.Even if all the points lie inside the control limit with the presence of a pattern does it indicate that the process is out of control?Or is the process in control, but some factor affects to shift the process level?

A: Yes you have to recalculate the R chart control limits as well. Even though there is no point outside the control limits in R chart, removal of two points due to x-bar chart changes the control limits of R chart.
For the second part, if there is a pattern or a cycle you can say that the system is not in statistical control. Therefore you have to look for an assignable cause


text:
Q: Solid of revolution for area bounded by parabolas Show that the volume generated by revolving the region in the first quadrant bounded by the parabolas $y^{2} =x$,
 $y^{2}= 8x, x^{2}= y, x^{2}= 8y$ about the x axis is $279 \pi /2$
This problem is to be solved by changing the variables as $ y^{2} = ux , x^{2} = vy$
I can find the volume of solid of revolution when it is easy to calculate without changing variables.
Formula is given by $ \int \pi y^{2} dx$
Now how the integral will change after changing the variables$?$

A:
$$\int\limits_{x=1}^2 \pi \left( (x^2)^2 - (\sqrt{x})^2 \right)\ dx \\
+ \int\limits_{x=2}^4 \pi \left( (\sqrt{8 x})^2 - (\sqrt{x})^2 \right)\ dx \\
+ \int\limits_{x=4}^8 \pi \left( (\sqrt{8 x})^2 - (x^2/8)^2 \right)\ dx \\
= \frac{279 \pi}{2} $$

A: Start by rewriting all the equations in terms of $y$, or even better $y^2$
$$\begin{align}y^2&=x\\y^2&=8x\\y^2&=x^4\\y^2&=x^4/64\end{align}$$
Plot the parabolas as shown below:

The intersections are at $(1,1)$, $(2,4)$, $(4,2)$, and $(8,8)$.
So in terms of $x$, you have three integral domains, $1$ to $2$, $2$ to $4$, and $4$ to $8$.
$$V=\pi\int_1^2(x^4-x)dx+\pi\int_2^4(8x-x)dx+\pi\int_4^8(8x-x^4/64)dx$$


text:
Q: Divisor on Elliptic Curve A divisor on an elliptic curve E is a formal sum of points $$D=\sum_{P\in E}n_P(P)$$ where the $n_P$ are integers only a finite number of which are nonzero.
Could anyone please explain what is the difference between $(P)$ and $P$ ? I know $P\in E$  is a point on $E$.  And what is the use of formal sum here ?

A: A divisor is a gadget that we use to keep track of values attached to points on a curve. The notation $(P)$ is just to indicate what values are attached to what points. For instance, the divisor $D=3(P)+5(Q)$ is meant to indicate that $n_P=3$ and $n_Q=5$. If you are confused about this notation, you could think of a divisor as a vector, such that each coordinate is associated with a point on the curve, i.e., $D=(n_P)_{P\in C}$, but you can easily see that this notation is inefficient because if I write now $(\ldots,0,0,0,3,0,\ldots,0,5,0,0,\ldots)$, it is not clear what point is attached to $3$ and what point is attached to the value $5$, unless I used some notation like $(\ldots,0,0,0,3_P,0,\ldots,0,5_Q,0,0,\ldots)$ of something like that. Moreover, this vector notation has all those unnecessary zeroes, and, of course, it is also misleading because there may be an uncountable number of points on $C$. Thus, we prefer to write $D=3(P)+5(Q)$ to indicate a divisor with $n_P=3$, and $n_Q=5$, and $n_R=0$ for all $R\neq P,Q$.
If you want to think about a concrete divisor, think about the divisor of a function. Let $f(x)= (x-P)^3(x-Q)^5$, for some real numbers $P,Q$, and define $D=\sum_{x\in \mathbb{R}} \operatorname{ord}_x(f)\cdot  (x)$, there $\operatorname{ord}_x(f)$ is the order of vanishing of $f$ at $x$. Then, $D=3(P)+5(Q)$.

A: Well, I think the author wants to distinguish formally between the point $P$ on the curve and the symbol $(P)$ (that stands for $P$) in a formal linear combination of points. This distinction is not necessary. It should be clear from the context.

A: I don't think there should be a difference between $(P)$ and $P$. Seeing it as a "formal sum" is probably a little bit confusing, since it doesn't really tell you anything. It might be helpful to think of a divisor $D$ as an element of the free abelian group on the points of your elliptic curve. As far as the usage goes, they are basically everywhere. It might help to just go through an algebraic geometry book and see it in action.


text:
Q: How to check if main parameter exist and validate it in C++ If I wanted to validate if the user has entered a specific parameter to the program how would I do it? This is my current code:
#include <iostream>
#include <cstdlib>

int main (int argc, char* argv[]) {

    if (argv[1] == "--para") {
        std::cout << "Some text here..." << std::endl;
    }

}

The code above will not work because I need some way to convert the parameter to a string so I can validate it in my if statement.
What I do not know is how to check if the --para exists at all when using multiple parameters into the program.
Example:
./main parameter1 parameter2 --para

A: You can construct and use a std::vector of std::strings directly:
#include <iostream>
#include <string>
#include <vector>

int main(int argc,char* argv[])
{
    std::vector<std::string> params{argv, argv+argc};

    for (auto i : params)
        if (i == "--para") {
            std::cout << "Some text here..." << std::endl;
        }

    return 0;
}

If you want to know if at least one of the parameters was a match you could use a standard library algorithm to check for you:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main(int argc,char* argv[])
{
    std::vector<std::string> params{argv, argv+argc};
    const std::string para{"--para"};

    if (std::any_of(params.begin(),params.end(),[&para](std::string val) {return val==para; }))
            std::cout << "Some text here..." << std::endl;

    return 0;
}

A: You need to do the check in a loop:
for( int i = 1; i < argc; i++ ) {
    if (strcmp(argv[i], "--para") == 0) {
        std::cout << "Some text here..." << std::endl;
    }
}

Instead of using strcmp you can convert the character pointer to a string:
for( int i = 1; i < argc; i++ ) {
    std::string str(argv[i]);
    if (str ==  "--para") {
        std::cout << "Some text here..." << std::endl;
    }
}

A: you can do it in pure c using strcmp. For example to check first parameter:
if(argc > 1 && strcmp(argv[1], "--para") == 0) {
// do some stuff here
}

You can just loop over other arguments and apply the same logic to check others

A: This is a solved problem.  There are lots of libraries out there.  I like argp, but it's gnu specific (I think).  It's also C, not C++, but can be made to work.  Boost has a utility for this also.  I'm sure there are dozens of others.  Don't reinvent the wheel.
http://optionparser.sourceforge.net/
http://tclap.sourceforge.net/
boost
What parameter parser libraries are there for C++?