text:
Q: Difficulty modifying an array environment I have an array that I had past help on and now I am attempting to modify that array. However, when doing so, parts of my "theorem" keep getting shifted to the next line.
Here is a MWE:
\documentclass{article}
\usepackage{amsmath,array}% http://ctan.org/pkg/{amsmath,array}
\newcommand{\twolinebrace}{\rlap{$\smash{\raisebox{.5\height}{\bigg\}}}$}}
\newlength{\LHS}\newlength{\RHS}
\newcolumntype{M}{>{$}p{\LHS}<{$}}
\newcolumntype{N}{>{$}p{\RHS}<{$}}
\begin{document}
\begin{theorem}
Let $\{A_{\alpha \colon \alpha \in A}\}$ and $\{B_{\beta \colon \beta \in  B}\}$ be families of subsets if a set $X$. Then:
\[
\renewcommand{\arraystretch}{1.1}
\begin{array}{@{}l@{\quad}l@{}}
\left.\kern-\nulldelimiterspace\\
             \begin{array}                                                                       {>{\bfseries}p{2em}@{\quad}M@{\quad$=$\quad}N}
  (a) & \big(\bigcup_{\alpha\in A} A_{\alpha}\big) \cup \big(\bigcup_{\beta\in B} B_{\beta}\big) & \bigcup_{(\alpha,\beta)} A_{\alpha} \cup B_{\beta}\\
  (b) & \bigg(\bigcap_{\alpha \in A A_{\alpha}} \bigg) \cap \bigg(\bigcap_{\beta \in B B_{\beta}} \bigg) &  \bigcap_{(\alpha,\beta)} A_{\alpha} \cap B_{\beta}
\end{array}\right\} & {\text{Associative Laws}} \\
\left.\kern-\nulldelimiterspace\begin{array}{>{\bfseries}p{2em}@{\quad}M@{\quad$=$\quad}N}
  (c) & X \cup (Y \cup Z) & (X \cup Y) \cup Z \\
  (d) & X \cap (Y \cap Z) & (X \cap Y) \cap Z
\end{array}\right\} & {\text{Associative Laws}} \\
\left.\kern-\nulldelimiterspace\begin{array}{>{\bfseries}p{2em}@{\quad}M@{\quad$=$\quad}N}
  (e) & X \cup (Y \cap Z) & (X \cup Y) \cap (X \cup Z) \\
  (f) & X \cap (Y \cup Z) & (X \cap Y) \cup (X \cap Z)
\end{array}\right\} & {\text{Distributive Laws}} \\
\end{array}
\]
\end{theorem}
\end{document}

I needed to add to my array, and now I am having additional problems. Now, the "text" 'Associative Laws', 'Distributive Laws', and 'de Morgan's Laws' are not being displayed correctly. Here is my latest MWE:
\documentclass{article}
\usepackage{amsmath,array}% http://ctan.org/pkg/{amsmath,array}
\newcommand{\twolinebrace}{\rlap{$\smash{\raisebox{.5\height}{\bigg\}}}$}}
\newlength{\LHS}\newlength{\RHS}
\newcolumntype{M}{>{$}p{\LHS}<{$}}
\newcolumntype{N}{>{$}p{\RHS}<{$}}
\begin{document}
\begin{theorem}
Let $\{A_{\alpha \colon \alpha \in A}\}$ and $\{B_{\beta \colon \beta \in  B}\}$ be families of subsets of a set~$X$. Then:
\[
\renewcommand{\arraystretch}{1.25}
\begin{array}{@{}l@{\quad}l@{}}
\left.\kern-\nulldelimiterspace\begin{array}{>{\bfseries}p{2em}@{\quad}M@{\quad$=$\quad}N}
(a) & X \cup Y &  Y \cup X \\
  (b) & X \cap Y &  X \cap Y
\end{array}\right\} & {\text{Commutative Laws}} \\
\left.\kern-\nulldelimiterspace\begin{array}{>{\bfseries}p{2em}@{\quad}M@{\quad$=$\quad}N}
(c) & X \cup (Y \cup Z) & (X \cup Y) \cup Z \\
  (d) & X \cap (Y \cap Z) & (X \cap Y) \cap Z
\end{array}\right\} & {\text{Associative Laws}} \\
\left.\kern-\nulldelimiterspace\begin{array}{>{\bfseries}p{2em}@{\quad}M@{\quad$=$\quad}N}
(e) & X \cup (Y \cap Z) & (X \cup Y) \cap (X \cup Z) \\
  (f) & X \cap (Y \cup Z) & (X \cap Y) \cup (X \cap Z)
\end{array}\right\} & {\text{Distributive Laws}} \\
\end{array}
\]
\end{theorem}

Any additional help would be greatly appreciated in this matter.

A: Perhaps the following is a little cleaner:

\documentclass{article}
\usepackage{amsmath,amsthm,array}% http://ctan.org/pkg/{amsmath,amsthm,array}
\newcommand{\twolinebrace}{\left.\kern-\nulldelimiterspace\begin{array}{@{}c@{}}\\\\\end{array}\right\}}
\newtheorem{theorem}{Theorem}
\begin{document}
\begin{theorem}
Let $\{A_{\alpha \colon \alpha \in A}\}$ and $\{B_{\beta \colon \beta \in  B}\}$ be families of subsets if a set~$X$. Then:
\[
  \renewcommand{\arraystretch}{1.25}
  \begin{array}{@{}l@{\quad}l@{}}
    \begin{array}{>{\bfseries}p{2em}@{\quad}r@{{}={}}l}
      (a) &
        \big(\bigcup_{\alpha\in A} A_{\alpha}\big) \cup \big(\bigcup_{\beta\in B} B_{\beta}\big) & % LHS
        \bigcup_{(\alpha,\beta)} A_{\alpha} \cup B_{\beta} \\ % RHS
      (b) &
        \big(\bigcap_{\alpha \in A} A_{\alpha} \big) \cap \big(\bigcap_{\beta \in B} B_{\beta} \big) & % LHS
        \bigcap_{(\alpha,\beta)} A_{\alpha} \cap B_{\beta} % RHS
    \end{array} & \twolinebrace\text{Associative Laws} \\
    \begin{array}{>{\bfseries}p{2em}@{\quad}r@{{}={}}l}
      (c) &
        X \cup (Y \cup Z) & % LHS
        (X \cup Y) \cup Z \\ % RHS
      (d) &
        X \cap (Y \cap Z) & % LHS
        (X \cap Y) \cap Z % RHS
    \end{array} & \twolinebrace\text{Associative Laws} \\
    \begin{array}{>{\bfseries}p{2em}@{\quad}r@{{}={}}l}
      (e) &
        X \cup (Y \cap Z) & % LHS
        (X \cup Y) \cap (X \cup Z) \\ % RHS
      (f) &
        X \cap (Y \cup Z) & % LHS
        (X \cap Y) \cup (X \cap Z) % RHS
    \end{array} & \twolinebrace\text{Distributive Laws}
  \end{array}
\]
\end{theorem}
\end{document}

Note that using an array like this (or even just setting the content in a display \[...\]) it can't be broken across the page boundary. If you wish to overcome this limitation, you'll have to set the display as a list rather, or break it up into separate chunks containing each "law pair", allowing content to break inbetween.

A: Just a different flavor to the above though I do not recommend it for multiple uses. The reason being that you would have to adjust the labels each time. But anyhow here it is:
\documentclass{article}
\usepackage{amsmath,amsthm}% http://ctan.org/pkg/{amsmath,array}
\usepackage{picture}
\usepackage{enumitem}
\newtheorem{theorem}{Theorem}
\begin{document}
\begin{theorem}
Let $\{A_{\alpha \colon \alpha \in A}\}$ and $\{B_{\beta \colon \beta \in  B}\}$ be families of subsets if a set $X$. Then:
\begin{enumerate}[label=\bfseries(\alph*)]
    \item $\big(\bigcup_{\alpha\in A} A_{\alpha}\big) \cup \big(\bigcup_{\beta\in B} B_{\beta}\big) = \bigcup_{(\alpha,\beta)} A_{\alpha} \cup B_{\beta}$
    \item $\big(\bigcap_{\alpha \in A} A_{\alpha} \big) \cap \big(\bigcap_{\beta \in B} B_{\beta} \big)=\bigcap_{(\alpha,\beta)} A_{\alpha} \cap B_{\beta}$
                \makebox(0,0){\put(0,10ex){%
               $\left.\rule{0pt}{5ex}\right\}$ Associative Laws}}
    \item $X \cup (Y \cup Z)= (X \cup Y) \cup Z$
  \item $X \cap (Y \cap Z) = (X \cap Y) \cap Z$
                \makebox(0,0){\put(7em,10ex){%
               $\left.\rule{0pt}{5ex}\right\}$ Associative Laws}}
  \item $X \cup (Y \cap Z) = (X \cup Y) \cap (X \cup Z)$
  \item $X \cap (Y \cup Z) = (X \cap Y) \cup (X \cap Z)$
                \makebox(0,0){\put(4.25em,10ex){%
               $\left.\rule{0pt}{5ex}\right\}$ Distributive Laws}}
\end{enumerate}
\end{theorem}
\end{document}


text:
Q: Can pdf kit save images from a url? I have a node.js application in which I'm using pdfkit to generate pdf documents. I want to be able to include images from a url in the pdf. I cant save the image to the file system because my runtime environment is read only and pdf kit seems to find the images to embed from a file system directory. Is there a way I can use an url in pdf kit to embed an image?

Here. This guy modified the pdfkit to include that functionality.

A: PDFKit now supports passing buffers to the doc.image method instead of a filename. See this commit. So you could do as the other answer suggests, and download the image from the URL yourself, and then pass the buffer directly to PDFKit instead of saving it to a file first.

A: you can use http.get:
    http.get('YOUR URL TO GET THE IMAGE').on('response', function(res)
    res.setEncoding('binary');
    res.on('data', function(chunk){
       buffer += chunk;
    });
    res.on('end', function(){

    fs.writeFile('PATH TO SAVE IMAGE', buffer, 'binary', function (err) {
        if (err){
           throw err;
        }
        doc = new PDFDocument({ size: 'LETTER or any other size pdfkit offer' });
        doc.image('PATH TO SAVE IMAGE', 0, 0, { fit: [WIDTH, HEIGHT] })
        .fontSize(10).text('text 1', 100, 170)
        .fontSize(16).text('text 2', 60, 120)

    }); //After file is download and was write into the HD will use it

}).end(); //EO Downloading the file

redpajama_set_name: RedPajamaStackExchange


text:
Q: Missing concatenation part in PHP Here is the code:
 <?php

      for($i =0, $x = 100 ; $i<1; $i++){

      echo $x .  'y' . $i+1 . ' = '. $i*$x . '
';
      }

    ?>

My Expected Output was: 100 y 1 = 0
But the actual result was: 101 = 0;
Where did 'y' go?
https://ideone.com/n9HYGp

A: . have more operator precedence than +.
echo $x .  'y' . $i+1 = 101

Because it will operate as
echo ($x .  "y" . $i)+1 ;

This is what happens.
$x3=  ($x .  "y" . $i); //100y0
$u = $x3+1 ;  //101

You are doing + operation on a string. So the first digits before any characters will be taken as integer value.
Eg:
10y0g8 = 10
t10  =0

By doing an Arithmetic Operation, interpreter will convert string to integer, and it will discard all other characters. so 100y+1 = 101 it won't be 101y

A: as explained in the above (Subin Thomas) answer the addition of 1 with the varchar value like 100y0 will add 1 with 100(the first occurence of integer). the following code will work as you expected
<?php

  for($i =0 ,$x = 100; $i<1; $i++){

  echo $x .  'y' . ($i+1) . ' = '. $i*$x . '
';
  }

?>

A: To test :
<?php

  for($i =0, $x = 100 ; $i<1; $i++){

  echo $x .  'y' . ($i+1) . ' = '. $i*$x . '
';
  }

?>


text:
Q: Doubt about file access rights between user/groups I am the single user on this Linux machine. I tried the following procedure to protect files, but it does not work as I expected. Could someone explain why?
$ touch file
$ sudo chown root:root file
$ sudo chmod a-w file
$ ls -l file
-r--r--r-- 1 root root 0 2012-02-29 01:06 file
$ rm file
rm: remove write-protected regular empty file `file'? yes
$ ls -l file
ls: cannot access file: No such file or directory

"File" is read-only and owned by root. Why was my regular user able to delete it?

A: It is an odd behavior of linux permissions, but permissions to delete files are granted by the permissions on the directory, not the file.
Try this:
mkdir test
touch test/file

# Make the Directory ro
chmod a-w test

ls -l test/file
-rw-rw-r-- 1 bodhi bodhi 0 2012-02-28 21:13 test/file

rm test/file
rm: cannot remove `test/file': Permission denied

Write permission. On a regular file, this means you can modify the file, aka write new data to the file. In the case of a directory, the write permission means you can add, remove, and rename files in the directory. This means that if a file has the write permission bit, you are allowed to modify the file's contents, but you're allowed to rename or delete the file only if the permissions of the file's directory allow you to do so.

See http://www.tuxfiles.org/linuxhelp/filepermissions.html
To allow (RW) access to file, but prevent deletion or renaming, set the sticky bit on the directory.
# change "test" to your directory
chmod +t test
touch test/file
chmod a+w test/file

ls -l | grep test
drwxrwxrwt 4 bodhi bodhi  4096 2012-03-07 17:08 test

ls -l test | grep file
-rw-rw-rw- 1 bodhi bodhi   13 2012-03-07 17:10 file

# su to another user, "test"
test@ufbt:/home/bodhi$ echo 'It works !!!' >> test/file

test@ufbt:/home/bodhi$ cat test/file
It works !!!

test@ufbt:/home/bodhi$ rm test/file
rm: cannot remove `test/file': Operation not permitted

http://www.techcuriosity.com/resources/linux/advanced_file_permissions_in_linux.php

If the sticky bit is set for a directory, only the owner of that directory or the owner of a file can delete or rename a file within that directory.


text:
Q: How to code a default namespace and a namespace with a prefix for single XML element in JAVA I want my xml element as follows
<exElement xmlns="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema">

I used the following code
rootElement.setAttributeNS("urn:hl7-org:v3", "xsd", "http://www.w3.org/2001/XMLSchema");

And gives me the Element as follows which is different than what i want.
<exElement xmlns:ns0="urn:hl7-org:v3" xsi:ns1="http://www.w3.org/2001/XMLSchema">

Can anyone please correct my code if there is an issue? Help will be greatly appriciated.

A: Try this :
I am using xom library for XML-manipulation :
Element root = new Element("exElement");
root.addNamespaceDeclaration("xsi","http://www.w3.org/2001/XMLSchema");
root.setNamespaceURI("urn:hl7-org:v3");

Document document = new Document(root);
System.out.println("XML :: " + document.toXML());

that's working fine for me & give me result :
XML :: <?xml version="1.0"?>
<exElement xmlns="urn:hl7-org:v3" xmlns:xsi="http://www.w3.org/2001/XMLSchema" />

still some problem post me.


text:
Q: Why are these memory orders applied here in the implementation of the lock free queue in C++ Concurrency in Action? Brief Description:
The code below is an implementation of a lock-free queue from C++ Concurrency in Action 2nd Edition. The queue uses a linked list as the underlying data structure and is implemented with split reference counting technology.
What confuses me is that there are multiple compare_exchange_strong in the code that use the acquire memory order, but I don't understand why this order is used.
For example, among all accesses to the count member of a node object (see below), there are no store operations with release order, but there are many compare_exchange_strong operations with acquire order.
For the complete code for this lock-free queue, my explanation of the code, and a detailed description of my problem, please read the full description section.

Full description:
I am reading the second edition of C++ Concurrency in Action by Anthony Williams. The book describes how to implement a lock-free queue using split reference counting technique. I'll start by briefly explaining how the code works based on my understanding to help you read the code quickly. The full implementation of this queue will be given later.
The implementation uses a singly linked list to implement the queue. The queue holds pointers to the head node and tail node of the linked list, which are head and tail in the code respectively, and tail points to a dummy node.
When pushing an element into the queue, we need to put the element value in the dummy node pointed to by tail, then add a dummy node after the node, and let tail point to the new dummy node.
When popping an element from the queue, we should pop the element pointed to by head, and then set head to head->next. When head and tail point to the same node (i.e. a dummy node), the queue is empty.
The code uses reference counting to manage the lifetime of deleted nodes. The reference count associated with a node is divided into two parts, the external reference count and the internal reference count. The external count plus the internal count is the full reference count value for that node. The external count is stored in the pointer to the node (i.e. counted_node_ptr in the code), while the internal count is stored inside the node object (i.e. count in the code).
In order to prevent the object pointed to by a thread from being deleted by another thread before dereferencing the pointer, the external counter must be incremented first to ensure that the node is not deleted. This is done by increase_external_count() in the code.
When an external reference no longer refers to a node, the external count stored in it must be added to the node's internal count, which is done by free_external_counter(). The internal count is stored in count.internal_count in the node object. And count.external_counters represents the number of external references referencing this node. Because these external references each hold their own external counts, these counts must all be taken into account. The node can only be safely deleted if and only if the internal count is 0 and the number of the external counter is also 0.
For references in pop that did not successfully point to the node being popped (usually because another thread has already popped it), those references are simply discarded, but their reference counts must be subtracted. This is done by release_ref(). This function decrements the internal count of the node by one. Every time the reference count is decremented, or the inner count and the external count are merged, a check is made to see if the condition for the node to be deleted is met.
Here is the complete implementation of the lock-free queue in the book:
template<typename T>
class lock_free_queue
{
private:
    struct node;
    struct counted_node_ptr
    {
        int external_count;
        node* ptr;
    };

    std::atomic<counted_node_ptr> head;
    std::atomic<counted_node_ptr> tail;

    struct node_counter
    {
        unsigned internal_count:30;
        unsigned external_counters:2;
    };

    struct node
    {
        std::atomic<T*> data;
        std::atomic<node_counter> count;
        counted_node_ptr next;

        node()
        {
            node_counter new_count;
            new_count.internal_count=0;
            new_count.external_counters=2;
            count.store(new_count);
            next.ptr=nullptr;
            next.external_count=0;
            data.store(nullptr);
        }

        void release_ref()
        {
            node_counter old_counter=
                count.load(std::memory_order_relaxed);
            node_counter new_counter;
            do
            {
                new_counter=old_counter;
                --new_counter.internal_count;
            }
            while(!count.compare_exchange_strong(
                      old_counter,new_counter,
                      std::memory_order_acquire,std::memory_order_relaxed));
            if(!new_counter.internal_count &&
               !new_counter.external_counters)
            {
                delete this;
            }
        }
    };

    static void increase_external_count(
        std::atomic<counted_node_ptr>& counter,
        counted_node_ptr& old_counter)
    {
        counted_node_ptr new_counter;
        do
        {
            new_counter=old_counter;
            ++new_counter.external_count;
        }
        while(!counter.compare_exchange_strong(
                  old_counter,new_counter,
                  std::memory_order_acquire,std::memory_order_relaxed));
        old_counter.external_count=new_counter.external_count;
    }

    static void free_external_counter(counted_node_ptr &old_node_ptr)
    {
        node* const ptr=old_node_ptr.ptr;
        int const count_increase=old_node_ptr.external_count-2;
        node_counter old_counter=
            ptr->count.load(std::memory_order_relaxed);
        node_counter new_counter;
        do
        {
            new_counter=old_counter;
            --new_counter.external_counters;
            new_counter.internal_count+=count_increase;
        }
        while(!ptr->count.compare_exchange_strong(
                  old_counter,new_counter,
                  std::memory_order_acquire,std::memory_order_relaxed));
        if(!new_counter.internal_count &&
           !new_counter.external_counters)
        {
            delete ptr;
        }
    }
public:
    lock_free_queue() {
        counted_node_ptr h;
        h.ptr = new node;
        h.external_count = 1;

        head.store(h);
        tail.store(h);
    }

    lock_free_queue(const lock_free_queue&) = delete;
    lock_free_queue& operator=(const lock_free_queue&) = delete;

    ~lock_free_queue() {
        while (pop())
            ;
    }

    void push(T new_value)
    {
        std::unique_ptr<T> new_data(new T(new_value));
        counted_node_ptr new_next;
        new_next.ptr=new node;
        new_next.external_count=1;
        counted_node_ptr old_tail=tail.load();
        for(;;)
        {
            increase_external_count(tail,old_tail);
            T* old_data=nullptr;
            if(old_tail.ptr->data.compare_exchange_strong(
                   old_data,new_data.get()))
            {
                old_tail.ptr->next=new_next;
                old_tail=tail.exchange(new_next);
                free_external_counter(old_tail);
                new_data.release();
                break;
            }
            old_tail.ptr->release_ref();
        }
    }

    std::unique_ptr<T> pop()
    {
        counted_node_ptr old_head=head.load(std::memory_order_relaxed);
        for(;;)
        {
            increase_external_count(head,old_head);
            node* const ptr=old_head.ptr;
            if(ptr==tail.load().ptr)
            {
                ptr->release_ref();
                return std::unique_ptr<T>();
            }
            if(head.compare_exchange_strong(old_head,ptr->next))
            {
                T* const res=ptr->data.exchange(nullptr);
                free_external_counter(old_head);
                return std::unique_ptr<T>(res);
            }
            ptr->release_ref();
        }
    }
};

I think I fully understand how push and pop work and think they are correct. But what I don't understand is why some atomic operations in the code use that memory order, and the book doesn't give a reason.
The count member of the node object stores the node's internal count value, as well as the number of external references to the node. The count member is used only a few times in the code:

*

*In the constructor of node, there is a seq-cst store for count:

node()
{
    node_counter new_count;
    new_count.internal_count=0;
    new_count.external_counters=2;
    count.store(new_count);   // seq-cst store
    next.ptr=nullptr;
    next.external_count=0;
}

*In release_ref, there are relaxed load and compare_exchange_strong for count:

void release_ref()
{
    node_counter old_counter=
        count.load(std::memory_order_relaxed);  // relaxed load
    node_counter new_counter;
    do
    {
        new_counter=old_counter;
        --new_counter.internal_count;
    }
    while(!count.compare_exchange_strong(
           old_counter,new_counter,
           std::memory_order_acquire,std::memory_order_relaxed)); // acquire RMW operation
    // ...
}

*In free_external_counter, there are also relaxed load and
acquire compare_exchange_strong:

static void free_external_counter(counted_node_ptr &old_node_ptr)
{
    node* const ptr=old_node_ptr.ptr;
    int const count_increase=old_node_ptr.external_count-2;
    node_counter old_counter=
        ptr->count.load(std::memory_order_relaxed);   // relaxed load
    node_counter new_counter;
    do
    {
        new_counter=old_counter;
        --new_counter.external_counters;
        new_counter.internal_count+=count_increase;
    }
    while(!ptr->count.compare_exchange_strong(
              old_counter,new_counter,
              std::memory_order_acquire,std::memory_order_relaxed));  // acquire RMW
    // ...
}

It can be seen that, except for a seq-cst store performed in the constructor of node, other operations are load operations with relaxed or acquire order, but no store operations with release order.
So what is the purpose of using acquire memory order here? What operation should it be synchronized with?
In addition, increase_external_count also uses acquire order, what is the reason here? While other atomic operations use the default seq-cst ordering, some of these operations seem to be able to be replaced with weaker memory ordering as well.

A: Good catch.  These are data races.  ThreadSanitizer agrees in both cases.
In free_external_counter:
        while(!ptr->count.compare_exchange_strong(
                  old_counter,new_counter,
                  std::memory_order_acquire,std::memory_order_relaxed));
        if(!new_counter.internal_count &&
           !new_counter.external_counters)
        {
            delete ptr;
        }

We read the object *ptr before the compare_exchange (to get ptr->count).  But since the compare_exchange is not release, the read of *ptr could in theory be reordered after it.  If so, then by the time the read of *ptr happens, the counter has already been decremented, and in the meantime some other thread might have decremented it again and then done delete ptr.
I am not sure how this could happen in real life, short of having a time machine, because we had to read *ptr in order to even find the object ptr->count that we are supposed to be writing to.  You'd need some miraculous machine that can speculatively make stores globally visible, and then roll back all other cores if it turns out the wrong address or value was stored.  But anyway, the C++ memory model doesn't forbid it.
There's a similar bug in release_ref, where the object being raced on is *this.
I think these can be fixed by upgrading the compare-exchanges to acq_rel.  That should ensure that all accesses to *ptr happen before its deletion.  In fact, as you point out, we only need the acquire ordering in the case that the count has become zero, since it's only the delete ptr that must be protected from reordering before the compare_exchange.  You could do that by having just release ordering on the compare_exchange, and putting an acquire fence inside the if block, just before delete ptr;.  I have not taken the time to prove this correct, though.
On the other hand, I also think you're right that the compare_exchange in increase_external_count could be weakened to relaxed.   When it's called, the counter must already be positive, or else accessing the counter itself is unsafe. So code that follows the compare_exchange would be equally well protected if it were reordered before it. (This is not a proof, of course.)


text:
Q: How do I add the explorer to GraphiQL using 'flask-graphql'? I am serving GraphiQL using flask-graphql but do not see any way to enable GraphiQL's "explorer" without using Node.JS. Is there a way to enable the explorer for a Python (flask-graphql) backend?

A: Node.js is not required, but React is since both graphiql and graphiql-explorer are React components. flask-graphql just renders an HTML page with a script that renders the GraphiQL interface using React as shown here.
You should be able to provide your own template for rendering this page when creating your GraphQLView via the graphiql_template option as shown here.
Copy and paste the existing template, then add the script tag for the library:
<script src="//cdn.jsdelivr.net/npm/graphiql-explorer@0.4.6/graphiqlExplorer.min.js"></script>

And implement the component as shown here. Since you're not transpiling this code, you won't be able to use JSX, so you'll need to do something like...
React.createElement(
  "div",
  { className: "graphiql-container" },
  React.createElement(
    GraphiQLExplorer,
    { /* props here */ },
  ),
  React.createElement(
    GraphiQL,
    { /* props here */ },
  )
)

A: Someone asked on the flask-graphql repo how to do it and I provided the initial template setup to get the explorer with some minor styles over that: Enabling "explorer" at Flask-graphql.


text:
Q: Layout weight is not fit, it change every input I have a spinner, an edittext and a button in a horizontal linearlayout. When I have enter something into edittext, it increase every character and others decrease. There is an eanough blank area input but it does not change, every time it increase how long character I input.
How can I fix it?
layout
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="@dimen/ly"
    android:gravity="center"
    android:orientation="horizontal"
    android:weightSum="10" >

    <Spinner
        android:id="@+id/spinner1"
        style="@style/submitspinner"
        android:layout_weight="2"
        android:entries="@array/a_code"
        android:prompt="@string/p_code" />

    <EditText
        android:id="@+id/editText1"
        style="@style/submitstyle"
        android:layout_weight="5"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        style="@style/submitstyle"
        android:layout_weight="3"
        android:text="@string/btn_submit" />
</LinearLayout>

style
<style name="submitstyle">
        <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:layout_margin">10sp</item>
    <item name="android:textColor">@android:color/holo_blue_dark</item>
    <item name="android:textSize">@dimen/pt</item>
</style>
<style name="submitspinner" parent="@android:TextAppearance.Widget.TextView.SpinnerItem">
        <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">match_parent</item>
    <item name="android:layout_margin">10sp</item>
    <item name="android:textColor">@android:color/holo_blue_dark</item>
    <item name="android:textSize">@dimen/pt</item>
</style>

A: I have changed style as below and it worked well...
submitstyle and submitspinner style
from
<item name="android:layout_width">wrap_content</item>

to
<item name="android:layout_width">0dp</item>

I found good tuts for this but I have closed the tab, I cannot share it...

A: //change you style from
<item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">match_parent</item>

//to
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>


text:
Q: Recreate Git repo from multiple Branches I have a Git repo that has been acting funny.
I can checkout all of my branches, I can work on each of them normally, and I can perform gitk to each one and view their individual commits successfully — with one exception...
.... there is one branch that I can't seem to access.  With any action I try to perform that includes the flawed branch, I receive an error.
For example: gitk --all yields fatal: blah blah blah (as a side note, more details about the error can be viewed here, but I am trying to come by a solution from a totally different angle).
The Question
Is there a way to recombine all of the other, working branches together such that I can use this repo again — only losing the commits from the broken branch since the broken branch does not have any other branches extending from it?

A: You could create a remote and push all your 'good' branches onto that remote.  Then in a new local directory, do a git clone of that remote.
After that, if you do git branch -a you should see all your local and remote branches.  You can create a local tracking branch for each remote branch with:
    git checkout -b branch remote/branch

After this, you should have a local repo with all 'good' branches.


text:
Q: TypeError: Fetch argument array has invalid type numpy.ndarray, must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)
I am trying to reproduce the results in siaseme LSTM to compare the semantic similarity of two sentences from here :- https://github.com/dhwajraj/deep-siamese-text-similarity
I am using tensorflow 1.4 & python 2.7
The train.py is working properly. For evaluating the model, I created a match_valid.tsv file which is a subset of "train_snli.txt" available there. I have modified the getTsvTestData function present in the input_helpers.py file.
def getTsvTestData(self, filepath):
        print("Loading testing/labelled data from "+filepath+"\n")
        x1=[]
        x2=[]
        y=[]
        # positive samples from file
        for line in open(filepath):
            l=line.strip().split("\t")
            if len(l)<3:
                continue
            x1.append(l[1].lower()) # text
            x2.append(l[0].lower()) # text
            y.append(int(l[2])) # similarity score 0 or 1
        return np.asarray(x1),np.asarray(x2),np.asarray(y)

I am getting error from this part of code in eval.py
for db in batches:
            x1_dev_b,x2_dev_b,y_dev_b = zip(*db)
            #x1_dev_b = tf.convert_to_tensor(x1_dev_b,)
            print("type x1_dev_b {}".format(type(x1_dev_b))) # tuple
            print("type x2_dev_b {}".format(type(x2_dev_b))) # tuple
            print("type y_dev_b {}\n".format(type(y_dev_b))) # tuple

            feed = {input_x1: x1_dev_b,
                    input_x2: x2_dev_b,
                    input_y:y_dev_b,
                    dropout_keep_prob: 1.0}

            batch_predictions, batch_acc, sim = sess.run([predictions,accuracy,sim], feed_dict=feed)

            print("type batch_predictions {}".format(type(batch_predictions))) # numpy.ndarray
            print("type batch_acc {}".format(type(batch_acc))) # numpy.float32
            print("type sim {}".format(type(sim))) # numpy.ndarray

            all_predictions = np.concatenate([all_predictions, batch_predictions])

            print("\n printing batch predictions {} \n".format(batch_predictions))

            all_d = np.concatenate([all_d, sim])

            print("DEV acc {} \n".format(batch_acc))

I am getting this error. I tried to use print statement in sess.run() to find the type but it didn`t work.
Traceback (most recent call last):
  File "eval.py", line 92, in <module>
    batch_predictions, batch_acc, sim = sess.run([predictions,accuracy,sim], feed_dict=feed)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 889, in run
    run_metadata_ptr)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1105, in _run
    self._graph, fetches, feed_dict_tensor, feed_handles=feed_handles)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 414, in __init__
    self._fetch_mapper = _FetchMapper.for_fetch(fetches)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 234, in for_fetch
    return _ListFetchMapper(fetch)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 341, in __init__
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 242, in for_fetch
    return _ElementFetchMapper(fetches, contraction_fn)
  File "/home/joe/anaconda2/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 275, in __init__
    % (fetch, type(fetch), str(e)))
TypeError: Fetch argument array([ 1.,  1.,  0.,  0.,  0.,  1.,  1.,  0.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,
        0.,  1.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,
        0.,  0.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  1.,  1.,  1.,  1.,
        1.,  0.,  0.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  1.,  1.,  0.,  0.,  0.,
        0.,  0.,  0.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,  0.,  0.,  0.,
        0.,  0.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  1.,  0.,
        0.,  0.,  0.,  0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  0.,
        1.,  1.,  1.,  1.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,  0.,  1.,
        1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  0.,  0.,  0.,  1.,  0.,
        0.,  1.,  0.,  0.,  1.,  0.,  0.,  1.,  1.,  0.,  0.,  1.,  0.,
        0.,  0.,  1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,
        0.,  1.,  0.,  0.,  1.,  0.,  1.,  1.,  0.,  1.,  0.,  1.,  0.,
        0.,  0.,  0.,  1.,  0.,  0.,  0.,  1.,  0.,  1.,  0.,  0.,  1.,
        1.,  0.,  0.,  1.,  0.,  1.,  0.,  0.,  0.], dtype=float32) has invalid type <type 'numpy.ndarray'>, must be a string or Tensor. (Can not convert a ndarray into a Tensor or Operation.)

Actually, I am trying to do a query similarity, comparing the query vector to all document vectors in my corpus and rank the sentences based on the similarity score. I know that currently the LSTM is just comparing two sentences with each other and output the similarity as 0 or 1. How can I do that?

A: The problem is that you are replacing the value of sim, which (I suppose) initially contains a reference to a TensorFlow tensor or operation, with the result of evaluating it (which is a NumPy array), so the second iteration fails because sim is not a TensorFlow tensor or operation anymore.
You can try something like this:
for db in batches:
            x1_dev_b,x2_dev_b,y_dev_b = zip(*db)
            #x1_dev_b = tf.convert_to_tensor(x1_dev_b,)
            print("type x1_dev_b {}".format(type(x1_dev_b))) # tuple
            print("type x2_dev_b {}".format(type(x2_dev_b))) # tuple
            print("type y_dev_b {}\n".format(type(y_dev_b))) # tuple

            feed = {input_x1: x1_dev_b,
                    input_x2: x2_dev_b,
                    input_y:y_dev_b,
                    dropout_keep_prob: 1.0}

            batch_predictions, batch_acc, batch_sim = sess.run([predictions,accuracy,sim], feed_dict=feed)

            print("type batch_predictions {}".format(type(batch_predictions))) # numpy.ndarray
            print("type batch_acc {}".format(type(batch_acc))) # numpy.float32
            print("type batch_sim {}".format(type(batch_sim))) # numpy.ndarray

            all_predictions = np.concatenate([all_predictions, batch_predictions])

            print("\n printing batch predictions {} \n".format(batch_predictions))

            all_d = np.concatenate([all_d, batch_sim])

            print("DEV acc {} \n".format(batch_acc))


text:
Q: Syntax error in for loop (Ruby/RSpec) While running the RSPEC test as shown below im getting this error:
Using Accessor#strict_set for specs
SyntaxError: /home/sam/projects/logstash.king-foo.dev/ansible/roles/logstash/spec/syslog.rb:6: syntax error, unexpected kEND
end
  ^
             load at org/jruby/RubyKernel.java:1101
           (root) at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:1
             each at org/jruby/RubyArray.java:1613
  load_spec_files at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896
  load_spec_files at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/configuration.rb:896
              run at /opt/logstash/vendor/bundle/jruby/1.9/gems/rspec-core-2.14.7/lib/rspec/core/command_line.rb:22

I tried messing around with the syntax but without success.
files = Dir['../configs/filter*.conf']
@@configuration = String.new
files.sort.each.do |file|
  @@configuration << File.read(file)
end

describe "my first logstash rspec test", :if => RUBY_ENGINE == "jruby"  do
  extend LogStash::RSpec

  config(@@configuration)
  ... some code here ...
end

Does anybody know what i'm doing wrong?
Why do i get a syntax error for the end statement ander the @@configuration variable?

A: The error means there was an unexpected end in your code. Just simply replace the 3rd line with
files.sort.each do |file|

I optionally recommend you use { and } instead of do and end. The { and } are space-insensitive and you are less likely to receive an error than do and end.


text:
Q: Read multiple lines from a large file in non-ascending order I have a very large text file, over 1GB, and I have a list of integers that represent line numbers, and the need is to produce another file containing the text of the original files line numbers in the new file.
Example of original large file:
ogfile line 1
some text here
another line
blah blah

So when I get a List of "2,4,4,1" the output file should read:
some text here
blah blah
blah blah
ogfile line 1

I have tried
string lineString = File.ReadLines(filename).Skip(lineNumList[i]-1).Take(1).First();
but this takes way to long as the file has to be read in, skipped to the line in question, then reread the next time... and we are talking millions of lines in the 1GB file and my List<int> is thousands of line numbers.
Is there a better/faster way to read a single line, or have the reader skip to a specific line number without "skipping" line by line?

A: The high-order bit here is: you are trying to solve a database problem using text files. Databases are designed to solve big data problems; text files, as you've discovered, are terrible at random access. Use a database, not a text file.
If you are hell-bent upon using a text file, what you have to do is take advantage of stuff you know about the likely problem parameters. For example, if you know that, as you imply, there are ~1M lines, each line is ~1KB, and the set of lines to extract is ~0.1% of the total lines, then you can come up with an efficient solution like this:

*

*Make a set containing the line numbers to be read. The set must be fast to check for membership.

*Make a dictionary that maps from line numbers to line contents.  This must be fast to look up by key and fast to add new key/value pairs.

*Read each line of the file one at a time; if the line number is in the set, add the contents to the dictionary.

*Now iterate the list of line numbers and map the dictionary contents; now we have a sequence of strings.

*Dump that sequence to the destination file.

We have five operations, so hopefully it is around five lines of code.
void DoIt(string pathIn, IEnumerable<int> lineNumbers, string pathOut)
{
  var lines = new HashSet<int>(lineNumbers);
  var dict = File.ReadLines(pathIn)
    .Select((lineText, index) => new KeyValuePair<int, string>(index, lineText))
    .Where(p => lines.Contains(p.Key))
    .ToDictionary(p => p.Key, p => p.Value);
  File.WriteAllLines(pathOut, lineNumbers.Select(i => dict[i]));
}

OK, got it in six. Pretty good.

Notice that I made use of all those assumptions; if the assumptions are violated then this stops being a good solution.  In particular we assume that the dictionary is going to be small compared to the size of the input file. If that is not true, then you'll need a more sophisticated technique to get efficiencies.
Conversely, can we extract additional efficiencies?  Yes, provided we know facts about likely inputs. Suppose for example we know that the same file will be iterated several times but with different line number sets, but those sets are likely to have overlap. In that case we can re-use dictionaries instead of rebuilding them. That is, suppose a previous operation has left a Dictionary<int, string> computed for lines (10, 20, 30, 40) and file X.  If a request then comes in for lines (30, 20, 10) for file X, we already have the dictionary in memory.
The key thing I want to get across in this answer is that you must know something about the inputs in order to build an efficient solution; the more restrictions you can articulate on the inputs, the more efficient a solution you can build. Take advantage of all the knowledge you have about the problem domain.

A: Use a StreamReader, so you don't have to read the entire file, just until the last desired line, and store them in a Dictionary, for later fast search.
Edit: Thanks to Erick Lippert, I included a HashSet for fast lookup.
List<int> lineNumbers = new List<int>{2,4,4,1};
HashSet<int> lookUp = new HashSet<int>(lineNumbers);
Dictionary<int,string> lines = new Dictionary<int,string>();

using(StreamReader sr = new StreamReader(inputFile)){
    int lastLine = lookUp.Max();
    for(int currentLine=1;currentLine<=lastLine;currentLine++){
        if(lookUp.Contains(currentLine)){
            lines[currentLine]=sr.ReadLine();
        }
        else{
            sr.ReadLine();
        }
    }
}
using(StreamWriter sw = new StreamWriter(outputFile)){
    foreach(var line in lineNumbers){
        sw.WriteLine(lines[line]);
    }
}

A: You may use a StreamReader and ReadLine method to read line by line without shocking the memory:
var lines = new Dictionary<int, string>();
var indexesProcessed = new HashSet<int>();
var indexesNew = new List<int> { 2, 4, 4, 1 };

using ( var reader = new StreamReader(@"c:\\file.txt") )
  for ( int index = 1; index <= indexesNew.Count; index++ )
    if ( reader.Peek() >= 0 )
    {
      string line = reader.ReadLine();
      if ( indexesNew.Contains(index) && !indexesProcessed.Contains(index) )
      {
        lines[index] = line;
        indexesProcessed.Add(index);
      }
    }

using ( var writer = new StreamWriter(@"c:\\file-new.txt", false) )
  foreach ( int index in indexesNew )
    if ( indexesProcessed.Contains(index) )
      writer.WriteLine(lines[index]);

It reads the file and select the desired indexes then save them in the desired order.
We use a HashSet to store processed indexes to speedup Contains calls as you indicate the file can be over 1GB.
The code is made to avoid index out of bound in case of mismatches between the source file and the desired indexes, but it slows down the process. You can optimize if you are sure that there will be no problem. In this case you can remove all usage of indexesProcessed.
Output:
some text here
blah blah
blah blah
ogfile line 1

A: One way to do this would be to simply read the input file once (and store the result in a variable), and then grab the lines you need and write them to the output file.
Since the line number is 1-based and arrays are 0-based (i.e. line number 1 is array index 0), we subtract 1 from the line number when specifying the array index:
static void Main(string[] args)
{
    var inputFile = @"f:\private\temp\temp.txt";
    var outputFile = @"f:\private\temp\temp2.txt";

    var fileLines = File.ReadAllLines(inputFile);
    var linesToDisplay = new[] {2, 4, 4, 1};

    // Write each specified line in linesToDisplay from fileLines to the outputFile
    File.WriteAllLines(outputFile,
        linesToDisplay.Select(lineNumber => fileLines[lineNumber - 1]));

    GetKeyFromUser("\n\nDone! Press any key to exit...");
}

Another way to do this that should be more efficient is to only read the file up to the maximum line number (using the ReadLines method), rather than reading the whole file (using the ReadAllLines method), and save just the lines we care about in a dictionary that maps the line number to the line text:
static void Main(string[] args)
{
    var inputFile = @"f:\private\temp\temp.txt";
    var outputFile = @"f:\private\temp\temp2.txt";

    var linesToDisplay = new[] {2, 4, 4, 1};
    var maxLineNumber = linesToDisplay.Max();
    var fileLines = new Dictionary<int, string>(linesToDisplay.Distinct().Count());

    // Start lineNumber at 1 instead of 0
    int lineNumber = 1;

    // Just read up to the largest line number we need
    // and save the lines we care about in our dictionary
    foreach (var line in File.ReadLines(inputFile))
    {
        if (linesToDisplay.Contains(lineNumber))
        {
            fileLines[lineNumber] = line;
        }

        // Increment our lineNumber and break if we're done
        if (++lineNumber > maxLineNumber) break;
    }

    // Write the output to our file
    File.WriteAllLines(outputFile, linesToDisplay.Select(line => fileLines[line]));

    GetKeyFromUser("\n\nDone! Press any key to exit...");
}


text:
Q: Animation of tube with fixed height the problem is following:
my task is to make an animation: tube changes its radius but doesn't change its height.
With command
Animate[Graphics3D[{CapForm["Square"], Tube[{{0, 0, 0}, {0.5, 0.5, 0.5}}, r]}],
        {r, 10^(-9), 1}, AnimationRunning -> False]`

It changes both radius and length. How to make the fixed length?

A: So the answer is:

*

*Fix PlotRange otherwise box will be scaled to fit the Tube and it creates an illusion of changing height.

*

*Use different CapForm because "Square" creates excess (edit) which is proportional to the radius of basis! (Thanks @Nasser)

Well, not obvious but seems logical, "square" referrs to that.

Take a look here:
Graphics3D[{
                     Tube[{{0, 0, 0}, {0, 0, 2}}, 1],
  CapForm["Square"], Tube[{{2, 2, 0}, {2, 2, 2}}, 1],
  CapForm[None],     Tube[{{4, 4, 0}, {4, 4, 2}}, 1],
  CapForm["Butt"],   Tube[{{6, 6, 0}, {6, 6, 2}}, 1],
                     Cylinder[{{8, 8, 0}, {8, 8, 2}}, 1]
  }, Axes -> {0, 0, 1}]


text:
Q: Tika pass parser info during incremental read I know Tika has a very nice wrapper that let's me get a Reader back from parsing a file like so:
Reader parsedReader = tika.parse(in);

However, if I use this, I cannot specify the parser that I want and the metadata that I want to pass in. For example, I would want to pass in extra info like which handler, parser, and context to use, but I can't do it if I use this method. As far as I know, it's the only one that let's me get a Reader instance back and read incrementally instead of getting the entire parsed string back.
Example of things I want to include:
        Parser parser = new AutoDetectParser();
        BodyContentHandler handler = new BodyContentHandler(-1);
        Metadata metadata = new Metadata();
        metadata.set(Metadata.RESOURCE_NAME_KEY, fileName); //This aids in the content detection
        ParseContext context = new ParseContext();
        context.set(Parser.class, parser);
        parser.parse(is, handler, metadata, context);

However, calling parse on a parser directly does not return a reader, and the only option I have(noticed in the docs) is to return a fully parsed string, which might not be great for memory usage. I know I can limit the string that is returned, but I want to stay away from that as I wanto the fully parsed info, but in incremental fashion. Best of both world, is this possible?

A: One of the many great things about Apache Tika is that it's open source, so you can see how it works. The class for the Tika facade you're using is here
The key bit of that class for your interest is this bit:
public Reader parse(InputStream stream, Metadata metadata)
        throws IOException {
    ParseContext context = new ParseContext();
    context.set(Parser.class, parser);
    return new ParsingReader(parser, stream, metadata, context);
}

You see there how Tika is taking a parser and a stream, and processing it to a Reader. Do something similar and you're set. Alternately, write your own ContentHandler and call that directly for full control!


text:
Q: How to remove splash in a material PageView component? How does one remove the splash in a material PageView component?
I have tried to set the ThemeData's accentColor and splashColor to Colors.transparent, but this results in a transparent black splash for the entire app.
I have tried to create a NoSplashContainer much like from this solution and but the splash remains inside the children.
import 'package:flutter/material.dart';

class NoSplashContainer extends StatelessWidget {
  final Widget child;
  NoSplashContainer(this.child) : assert(child != null);
  @override
  Widget build(BuildContext context) {
    return (new Container(
        child: new Theme(
            data: Theme
                .of(context)
                .copyWith(splashFactory: const NoSplashFactory()),
            child: child)));
  }
}

class NoSplashFactory extends InteractiveInkFeatureFactory {
  const NoSplashFactory();

  @override
  InteractiveInkFeature create({
    @required MaterialInkController controller,
    @required RenderBox referenceBox,
    @required Offset position,
    @required Color color,
    bool containedInkWell: false,
    RectCallback rectCallback,
    BorderRadius borderRadius,
    double radius,
    VoidCallback onRemoved,
  }) {
    return new NoSplash(
      controller: controller,
      referenceBox: referenceBox,
    );
  }
}

class NoSplash extends InteractiveInkFeature {
  NoSplash({
    @required MaterialInkController controller,
    @required RenderBox referenceBox,
  })  : assert(controller != null),
        assert(referenceBox != null),
        super(
          controller: controller,
          referenceBox: referenceBox,
        );

  @override
  void paintFeature(Canvas canvas, Matrix4 transform) {}
}

I use NoSplashContainer like so..
new NoSplashContainer(new PageView(
   children: ...,
)));

but the splash is still present in the PageView.

A: There's a Widget called Theme that will apply a theme to descendant widgets. So, you can use Theme to customize any part of your app without modifying theme of the whole app. Something like this:
new Theme(
      data: Theme.of(context).copyWith(
        splashColor: Colors.transparent
      ),
      child:....
    );


text:
Q: How do I allow anyone to view my files on my network? I have created a little server on Ubuntu 13.10, I've shared certain folders using SAMBA.
On my WINDOWS PC my username and password is the same as the username and password of the server, so I'm assuming that's why I can connect there, but connecting to the server from my brothers pc is a different story.
I have added to /etc/sudoers :
jinglez ALL=(ALL:ALL) NOPASSWD:ALL
Thinking that when he try's to map a new network drive, that he then would be able to login as jinglez and the server password, but this didn't work, however when we created a new user account on his pc, with the above info it did, does anyone know how to fix this?

A: The sudoers file is not used by samba to control user access. This will depend on your Samba configuration, but most samba configurations have the line
security = user which requires every user to have an account on your Ubuntu server. So you will have to add the user jinglez to the system (you can use the sudo adduser command to create this).
Once you've added the user to the system, you'll also have to add them to Samba's user list with the smbpasswd tool. Finally, to ensure they have permission to read/write the shares, be sure to add them to the same group as your original user and set the directory's group ownership to that. For more instructions you can refer to this answer: Samba and User Acount Passwords.
Remember to restart your samba service with sudo service samba restart to apply.
If you don't want to create a new user account for your brother there are other options (you can set security on the "share" level, or even do advanced stuff like changing the PAM module Samba uses for authentication) but this is the simplest way.


text:
Q: Is the set of functions $\{t\mapsto tx(t)\mid x\colon [0,1]\to\mathbb{R}\text{ and }(\forall t\in [0,1])\,\lvert x(t)\rvert \leq 1\}$ equicontinuous? Is the following set of real-valued continuous functions on $[0,1]$ equicontinuous?
$$
A = \{t\mapsto tx(t)\mid x\colon [0,1]\to\mathbb{R}\text{ and }(\forall t\in [0,1])\,\lvert x(t)\rvert \leq 1\}
$$
My attempt:
Let $t_0\in [0,1],\varepsilon>0$.
Then $\lvert tx(t)-t_0x(t_0)\rvert=\lvert tx(t)-t_0x(t)+t_0x(t)-t_0x(t_0)\rvert \leq\lvert t-t_0\rvert+\lvert x(t)-x(t_0)\rvert$
But $\lvert t-t_0\rvert+\lvert x(t)-x(t_0)\rvert$ is not equicontinuous, however I can not find a counterexample of not equicontinuous functions in $A$ or another bound for $\lvert tx(t)-t_0x(t_0)\rvert$.
Thanks.

A: I don't think they are equicontinuous. Near $1$, the influence of $t$ is negligible.
For instance, if we let $x_n(t)=t^n$, then this family will not be equicontinuous at $t=1$. Because for any $t<1$ you can get $n$ big enough so that $t^n$ is arbitrarily close to zero.


text:
Q: How to put numbers in parenthesis in the S column using siunitx package In the following minimal code, when I replace the l columns by S I get an error message saying
invalid-number!! Invalid numerical input '(4.36)'.!!
See the siunitx documentation for further information.!!

It goes on.  It is important that I put the numbers in the third and fifth columns in parenthesis.
\documentclass{article}
\usepackage{booktabs}
\usepackage{ctable}
\usepackage{siunitx}
\usepackage{multirow}

\begin{document}
\ctable[
     caption = {caption here},
     label = {tab:tab1},
     pos = {!ht},
     center
] {@{}lS@{\enskip}>{(}l<{)}S@{\enskip}>{(}l<{)}}{
    \tnote[$\dagger$]{footnote here}
}{ \FL
\multirow{2}{*}{var} & \multicolumn{4}{c}{Title here} \\
\cmidrule{2-5}
    & \multicolumn{2}{c}{[AA]} & \multicolumn{2}{c}{[BB]} \ML
$var_{12}$ & 1.37 & 4.36 & 1.50 & 8.91  \\
$var_{13}$ & 1.73 & 8.43 & 1.84 & 10.88
\LL}
\end{document}

A: Instead of providing the option table-parse-only to the siunitx package, you could also provide the -- in my opinion less intrusive -- option input-symbols = (). Doing so tells siunitx to treat the symbols ( and ) as ordinary inputs, i.e., not to assign any special meaning to them (such as denoting uncertainty...).
Two nice features of this approach are (i) you needn't do anything special in the header information of the tabular environment in order to enter the parentheses in the body of the table and (ii) the ability of the siunitx package to align numbers on their decimal points (and to perform any other parsing tasks) is not affected.

\documentclass{article}
\usepackage{booktabs,siunitx}
\sisetup{input-symbols = ()} % "(" and ")" are ordinary inputs
\begin{document}
\begin{table}[ht!]
\caption{caption here} \label{tab:tab1}
\centering
\begin{tabular}{@{}lSSSS@{}}
\toprule
& \multicolumn{4}{c}{Title here} \\
\cmidrule{2-5}
& \multicolumn{2}{c}{[AA]} & \multicolumn{2}{c@{}}{[BB]} \\
\midrule
$var_{12}$ & 1.37 & (4.36) & 1.50 &  (8.91)\\
$var_{13}$ & 1.73 & (8.43) & 1.84 & (10.88)\\
\bottomrule
\end{tabular}
\end{table}
\end{document}

A: There are two things we should be careful about.

*

*parenthesis are used to indicate the uncertainty through the table-figures-uncertainty macro

*We can use table-parse-only to get the parsing only feature.

For item 1 above, we can hide ( and ) from siunitx by using braces → {(} and {)} so that they are not meant to indicate the uncertainty. table-parse-only gives correct spacing.
Code:
\documentclass{article}
\usepackage{booktabs}
\usepackage{ctable}
\usepackage{siunitx}
\usepackage{multirow}
%\sisetup{detect-weight=true,table-space-text-pre={(},table-space-text-post={)}}

\begin{document}
\ctable[
     caption = {caption here},
     label = {tab:tab1},
     pos = {!ht},
     center
] {@{}lS@{\enskip}>{{(}}S[table-parse-only]<{{)}}S@{\enskip}>{{(}}S[table-parse-only]<{{)}}}{
    \tnote[$\dagger$]{footnote here}
}{ \FL
\multirow{2}{*}{var} & \multicolumn{4}{c}{Title here} \\
\cmidrule{2-5}
    & \multicolumn{2}{c}{[AA]} & \multicolumn{2}{c}{[BB]} \ML
$var_{12}$ & 1.37 & 4.36 & 1.50 & 8.91  \\
$var_{13}$ & 1.73 & 8.43 & 1.84 & 10.88
\LL}
\end{document}

A: As a comment to @Donna's comment in @Mico's post (no rep yet...), you can place the parens in curly braces, and rounding will still occur.
\documentclass{article}
\usepackage{booktabs,siunitx}
\sisetup{input-symbols = ()} % "(" and ")" are ordinary inputs
\begin{document}
\begin{table}[ht!]
\caption{caption here} \label{tab:tab1}
\centering
\begin{tabular}{@{}lSSSS@{}}
\toprule
& \multicolumn{4}{c}{Title here} \\
\cmidrule{2-5}
& \multicolumn{2}{c}{[AA]} & \multicolumn{2}{c@{}}{[BB]} \\
\midrule
$var_{12}$ & 1.3723 & {(}4.3646{)} & 1.5045 &  {(}8.9111{)}\\
$var_{13}$ & 1.7343 & {(}8.4365{)} & 1.8445 & {(}10.8888{)}\\
\bottomrule
\end{tabular}
\end{table}
\end{document}


text:
Q: Error in stored procedure SQL SERVER Hi I want insert data with bulk insert, a csv file and a Stored procedure,
my problem is when I use a parameter instead of the path of the csv file, when I change the path for the parameter I get the next error

Msg 102, Level 15, State 1, Procedure carga_masiva, Line 7 [Batch
  Start Line 7] Incorrect syntax near '@ruta'. Msg 319, Level 15, State
  1, Procedure carga_masiva, Line 7 [Batch Start Line 7] Incorrect
  syntax near the keyword 'with'. If this statement is a common table
  expression, an xmlnamespaces clause or a change tracking context
  clause, the previous statement must be terminated with a semicolon.

This is my stored procedure:
USE [prueba]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[carga_masiva]
--Parametros que utilizara el procedimiento almacenado
    @ruta nvarchar(250)
AS
--Query que realizara el procedimiento almacenado
    SET NOCOUNT ON;
    BULK INSERT USUARIO
    FROM @ruta
    WITH
    (
      FIELDTERMINATOR= ';',
      ROWTERMINATOR = '\n'
     )

A: Try this should work:
ALTER PROCEDURE [dbo].[carga_masiva] @ruta nvarchar(250) AS
DECLARE @bulkinsert NVARCHAR(2000), @filepath nvarchar(500)
SET @filepath = @ruta
SET
  NOCOUNT ON;

SET @bulkinsert =
       N'BULK INSERT USUARIO FROM ''' +
       @filepath +
       N''' WITH ( FIELDTERMINATOR = '','', ROWTERMINATOR = ''\n'')'

EXEC sp_executesql @bulkinsert

You could consider building up your BULK INSERT statement as a string  and then execute it as dynamic SQL.

A: I think the issue might be round where you are inserting from as it is expecting a location as a string e.g. 'C:\Doc' rather than C:\Doc.
Dynamic SQL would be an option e.g.
USE [prueba];
GO
SET ANSI_NULLS ON;
GO
SET QUOTED_IDENTIFIER ON;
GO
ALTER PROCEDURE [dbo].[carga_masiva]
--Parametros que utilizara el procedimiento almacenado
@ruta NVARCHAR(250)
AS
--Query que realizara el procedimiento almacenado
     SET NOCOUNT ON;
     DECLARE @SQL NVARCHAR(1024);
     SET @SQL = '

    BULK INSERT USUARIO
    FROM '+CHAR(39)+@ruta+CHAR(39)+'
    WITH
    (
      FIELDTERMINATOR= '';'',
      ROWTERMINATOR = ''\n''
     )
';
     EXEC sp_executesql
          @SQL;

Pinal Dave has a handy post here : https://blog.sqlauthority.com/2008/02/06/sql-server-import-csv-file-into-sql-server-using-bulk-insert-load-comma-delimited-file-into-sql-server/
The MS Docs are here : https://learn.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017


text:
Q: What is the min and max post quality score? I've seen or heard of flagged posts with scores ranging from -11 to 100, but without knowing what the total range is these scores are somewhat meaningless.
What I'd like to know is:

*

*What's the lowest possible score (a perfectly bad question)

*What's the highest possible score (a perfectly good question)

*What's the threshold where posts are flagged as "low quality posts" for moderator attention?

[Edit]
To clarify, I'm talking about the quality score that you see on the /review page, not the vote score.  For example, this answer has a vote score of 0 and a quality score of 79.

A: It's just a heuristic based on
Heuristics for detecting a bad answer?
Posts start out with a value of 100; the threshold to appear is < 80.

A: Posts are flagged as "very low quality" when they are shorter than 220 chars, and

*

*The answer contains text matching one of these regular expressions: "thank|cheers|thx|great" and "same.*?(problem|error|bug)"

*The answer contains just a single URL

In such cases, the flag is applied, independently from the quality score of the post.


text:
Q: Nested promise functions I have a button that I want to track when the user press it, and if the tracking ajax call returns data, then execute a promise, when thats all done, continue with the button event.
Below is what I have so far, however the button event and the 2nd promise fire at the same time. The button event isn't waiting for the 2nd promise to resolve

*

*Click button

*AJAX call records the event

*If AJAX doesn't return a question then alert hello.

*If the AJAX call returns a question, then build and open modal, when modal closes, then alert hello.

$('.my_button').on('click', function() {
    ui_tracking('button_1').then(function () {
        alert('Hello');
    });
});

function ui_tracking(type, payload) {
    var deferred = $.Deferred();

    var log_action = function () {
        $.ajax({
            url: '/api/submit_action',
            type: 'POST',
            dataType: 'json',
            data: {
                type: type,
                payload: JSON.stringify(payload)
            },
            success: function(results, textStatus, xhr) {
                if (typeof(results) !== 'undefined' && results !== null) {
                    if (typeof(results.data) !== 'undefined' && results.data !== null) {
                        if (results.data.question) {
                            startQuestion(results.data.question).then(function () {
                                deferred.resolve();
                            }, function() {
                                deferred.reject();
                            });
                        }
                    }
                }

                deferred.resolve();
            },
            error: function (xhr, textStatus, errorThrown) {
                deferred.reject();
            }
        });
    };

    log_action();

    return deferred.promise();
}

function startQuestion(question_data) {
    var deferred = $.Deferred();

    var openQuestion = function () {
        $('#question-modal .modal-body .question').html(question_data.question).attr('data-question-id', question_data.id);

        $('#question-modal').modal('show').on('hidden.bs.modal', function (e) {
            deferred.resolve();
            $('#question-modal').unbind('hidden.bs.modal');
        });
    };

    openQuestion();
    return deferred.promise();
}

sf

A: your success: callback calls deferred.resolve(); straight away (at the end, after the if condition)
    success: function(results, textStatus, xhr) {
        if (typeof(results) !== 'undefined' && results !== null) {
            if (typeof(results.data) !== 'undefined' && results.data !== null) {
                if (results.data.question) {
                    startQuestion(results.data.question).then(function () {
                        deferred.resolve();
                    }, function() {
                        deferred.reject();
                    });
                }
            }
        }
        // this gets called regardless of the above conditions!
        deferred.resolve();

Knowing $.ajax returns a (jQuery) Promise, I believe you could simplify ui_tracking function as follows:
function ui_tracking(type, payload) {
    return $.ajax({
        url: '/api/submit_action',
        type: 'POST',
        dataType: 'json',
        data: {
            type: type,
            payload: JSON.stringify(payload)
        }
    }).then(function(results) {
        if (results && results.data && results.data.question) {
            return startQuestion(results.data.question);
        }
    });
}

In the above .then, if the conditions are not met, the return is undefined ... basically the same thing as you were doing with deferred.resolve() - the returned Promise will be resolved to undefined once the ajax completes
However, if the conditions are all met, the return is the Promise returned by startQuestion - which will mean the returned Promise will be that which is returned by startQuestion - therefore your code will wait on that promise to resolve before continuing
Also, no need for error handling that simply returns a rejected promise - let the outer call handle errors
Alternatively, you could write the whole lot as
$('.my_button').on('click', function() {
    ui_tracking('button_1')
    .then(startQuestion)
    .then(function () {
        alert('Hello');
    });
});

function ui_tracking(type, payload) {
    return $.ajax({
        url: '/api/submit_action',
        type: 'POST',
        dataType: 'json',
        data: {
            type: type,
            payload: JSON.stringify(payload)
        }
    });
}

function startQuestion(results) {
    var deferred;
    var openQuestion = function (question_data) {
        $('#question-modal .modal-body .question').html(question_data.question).attr('data-question-id', question_data.id);

        $('#question-modal').modal('show').on('hidden.bs.modal', function (e) {
            deferred.resolve();
            $('#question-modal').unbind('hidden.bs.modal');
        });
    };
    if (results && results.data && results.data.question) {
        deferred = $.Deferred();
        openQuestion(results.data.question);
        return deferred.promise();
    }
}

Sure the logic has moved about, so maybe not exactly what you'd like

A: You can encapsulate each "step" in a function returning a promise (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and then "chain" them.
This is a great post on executing promises in a series: http://www.datchley.name/promise-patterns-anti-patterns/#executingpromisesinseries (you may need a polyfill for your promising: https://github.com/stefanpenner/es6-promise)


text:
Q: Is it safe to abandon a child when moving in with your husband? Frank seduced Pauline, who was dating Hank, and convinced her to dump him. (Yes, Frank is a d*ck) Things happened, and Pauline somehow got pregnant ; Frank proposed to her, and they eventually got married.
The thing is, Pauline's child was already born, and Frank wasn't there because you know, being a conductor at the Opera and working 5 hours a day is hard. Hence he discovered the child's name only when Pauline came to live in his house ; he thinks Hank might have chosen the name (Pauline and him were still living together), because it is awful. (The awful name will not be revealed here, to avoid hurting anyone bearing it.)
Now Pauline and Frank are living together. Without their child, who stayed with Hank.
What are the consequences of such a situation ? Will the child hate his parents, will the mother experience a mental breakdown ?

A: It's perfectly fine to abandon a child. No consequences at all.
Pauline and Frank are living happily, and have a little girl.


text:
Q: Why is my video fast forwarded after converting it from a DVD with VLC and how can I fix it? I am trying to convert some series I have on DVD to a digital video file like MP4.
However the first few seconds after the MGM intro are sped forward. In fact, only the video is sped up. The audio is just fine. That leads to the video and audio being out of sync for the rest of the episode.
I have converted many episodes of the same series without problems before using H-264 and MPEG-4 AAC.
Other codecs do not work either. I have tried MPEG-1 through 4, DIVX 1 through 3, H-263 through 265, and WMV 1 & 2. The problem persists.
Using other containers such as MKV, Webm and WMV did not work either.

I am running Ubuntu 20.04 having a Ryzen 9 3900 XT and a RX 5600 XT card.
What can I do to solve this problem and have the video be converted properly?


text:
Q: Doodle on top of Sweave output It might not be possible to do this, but I was wondering if there is a way to doodle on top of the LaTeX output, or in my case on top of Sweave output.
See example underneath!!

\begin{tikzpicture}
\node[right,text width=11.7cm,rounded corners,fill=blue!20,inner sep=1ex]{
\begin{center}
\textbf{EXERCISE \ex}
\end{center}
Let's create a random sample of 10 smaller case letters from the alphabet as follows:
<<>>=
test.letters <- sample(letters,10)
@
\begin{enumerate}
\item Create a factor out of this vector and inspect it.
\item What do you notice when inspecting the given levels of this factor?
\item How can you make sure that the whole alphabet is taken into account in the levels? \end{enumerate}
\vspace{.1in}};
\end{tikzpicture}

HERE'S THE PLAIN LATEX EXPORT
\batchmode
\makeatletter
\def\input@path{{\string"C:/Documents and Settings/LSDEMMLJ/Desktop/R intro v1.1/\string"/}}
\makeatother
\documentclass[british]{beamer}
\usepackage{mathptmx}
\usepackage[T1]{fontenc}
\usepackage[latin9]{inputenc}
\setcounter{secnumdepth}{3}
\setcounter{tocdepth}{3}
\setlength{\parskip}{\bigskipamount}
\setlength{\parindent}{0pt}
\usepackage{amsmath}
\usepackage{amssymb}

\makeatletter
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands.
 % this default might be overridden by plain title style
 \newcommand\makebeamertitle{\frame{\maketitle}}%
 \AtBeginDocument{
   \let\origtableofcontents=\tableofcontents
   \def\tableofcontents{\@ifnextchar[{\origtableofcontents}{\gobbletableofcontents}}
   \def\gobbletableofcontents#1{\origtableofcontents}
 }
 \def\lyxframeend{} % In case there is a superfluous frame end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands.
\usepackage{graphicx}
\usepackage{mdwlist}
\usepackage{xr}
\usepackage{units}
\usepackage{fancyhdr}
\usepackage{textcomp}
\usepackage{latexsym}
\usepackage{multicol}
\usepackage{dirtree}
\usepackage{keystroke}
\usepackage{url}
\usepackage{hyperref}

\usetheme{Madrid}
\makeatletter
\defbeamertemplate*{title page}{mytitlepage}[1][]
{
  \vbox{}
  \vfill
  \begin{centering}
    \begin{beamercolorbox}[sep=8pt,center,#1]{}
      \usebeamerfont{title}\inserttitle\par%
      \ifx\insertsubtitle\@empty%
      \else%
        \vskip0.25em%
        {\usebeamerfont{subtitle}\usebeamercolor[fg]{subtitle}\insertsubtitle\par}%
      \fi%
    \end{beamercolorbox}%
    \vskip1em\par
    \begin{beamercolorbox}[sep=8pt,center,#1]{author}
      \usebeamerfont{author}\insertauthor
    \end{beamercolorbox}
    \begin{beamercolorbox}[sep=8pt,center,#1]{institute}
      \usebeamerfont{institute}\insertinstitute
    \end{beamercolorbox}
    \begin{beamercolorbox}[sep=8pt,center,#1]{date}
      \usebeamerfont{date}\insertdate
    \end{beamercolorbox}\vskip0.5em
    {\usebeamercolor[fg]{titlegraphic}\inserttitlegraphic\par}
  \end{centering}
  \vfill
}
\makeatother

\title[Intro to R \theframenumber]{An Introduction to the R Statistical Environment}
\author{Joanne Demmler}
\institute[Swansea University]{CIPHER\\ College of Medicine}
\date{5th of June 2013 \\{\tiny Version 1.2}}

\AtBeginPart{%
    {%  start a group to keep the template change local
        \setbeamertemplate{background canvas}{%
            \color{blue!20!white!80}\rule{\paperwidth}{\paperheight}%
        }%
        \frame{\partpage}%
    }%  end group
}

\hypersetup{pdfpagemode=None}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart}
\usetikzlibrary{decorations.pathreplacing}

\newcounter{bar}
\newcommand{\ex}{%
        \stepcounter{bar}%
        \thebar}

% add highlighting to text
\usepackage{color}
\newcommand{\hilight}[1]{\colorbox{yellow}{#1}}

\makeatother

\usepackage{babel}
\usepackage{Sweave}
\begin{document}
\begin{frame}[fragile,allowframebreaks]
\frametitle{Vector exercises}

\begin{tikzpicture}
\node[right,text width=11.7cm,rounded corners,fill=blue!20,inner sep=1ex]{
\begin{center}
\textbf{EXERCISE \ex}
\end{center}
Let's create a random sample of 10 smaller case letters from the alphabet as follows:
\begin{Schunk}
\begin{Sinput}
> test.letters <- sample(letters,10)
\end{Sinput}
\end{Schunk}
\begin{enumerate}
    \item Create a factor out of this vector and inspect it.
    \item What do you notice when inspecting the given levels of this factor?
    \item How can you make sure that the whole alphabet is taken into account in the levels?
\end{enumerate}
\vspace{.1in}};
\end{tikzpicture}
\end{frame}

\lyxframeend{}
\end{document}

AND THE LYX EXAMPLE:
#LyX 2.0 created this file. For more info see http://www.lyx.org/
\lyxformat 413
\begin_document
\begin_header
\textclass beamer
\begin_preamble
\usepackage{graphicx}
\usepackage{mdwlist}
\usepackage{xr}
\usepackage{units}
\usepackage{fancyhdr}
\usepackage{textcomp}
\usepackage{latexsym}
\usepackage{multicol}
\usepackage{dirtree}
\usepackage{keystroke}
\usepackage{url}
\usepackage{hyperref}

\usetheme{Madrid}
\makeatletter
\defbeamertemplate*{title page}{mytitlepage}[1][]
{
  \vbox{}
  \vfill
  \begin{centering}
    \begin{beamercolorbox}[sep=8pt,center,#1]{}
      \usebeamerfont{title}\inserttitle\par%
      \ifx\insertsubtitle\@empty%
      \else%
        \vskip0.25em%
        {\usebeamerfont{subtitle}\usebeamercolor[fg]{subtitle}\insertsubtitle\par}%
      \fi%
    \end{beamercolorbox}%
    \vskip1em\par
    \begin{beamercolorbox}[sep=8pt,center,#1]{author}
      \usebeamerfont{author}\insertauthor
    \end{beamercolorbox}
    \begin{beamercolorbox}[sep=8pt,center,#1]{institute}
      \usebeamerfont{institute}\insertinstitute
    \end{beamercolorbox}
    \begin{beamercolorbox}[sep=8pt,center,#1]{date}
      \usebeamerfont{date}\insertdate
    \end{beamercolorbox}\vskip0.5em
    {\usebeamercolor[fg]{titlegraphic}\inserttitlegraphic\par}
  \end{centering}
  \vfill
}
\makeatother

\title[Intro to R \theframenumber]{An Introduction to the R Statistical Environment}
\author{Joanne Demmler}
\institute[Swansea University]{CIPHER\\ College of Medicine}
\date{5th of June 2013 \\{\tiny Version 1.2}}

\AtBeginPart{%
    {%  start a group to keep the template change local
        \setbeamertemplate{background canvas}{%
            \color{blue!20!white!80}\rule{\paperwidth}{\paperheight}%
        }%
        \frame{\partpage}%
    }%  end group
}

\hypersetup{pdfpagemode=None}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart}
\usetikzlibrary{decorations.pathreplacing}

\newcounter{bar}
\newcommand{\ex}{%
        \stepcounter{bar}%
        \thebar}

% add highlighting to text
\usepackage{color}
\newcommand{\hilight}[1]{\colorbox{yellow}{#1}}
\end_preamble
\use_default_options false
\begin_modules
beamer-fragile
sweave
\end_modules
\maintain_unincluded_children false
\language british
\language_package default
\inputencoding auto
\fontencoding global
\font_roman times
\font_sans default
\font_typewriter default
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100
\font_tt_scale 100

\graphics default
\default_output_format pdf2
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref false
\papersize default
\use_geometry true
\use_amsmath 2
\use_esint 1
\use_mhchem 1
\use_mathdots 1
\cite_engine basic
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\use_refstyle 1
\index Index
\shortcut idx
\color #008000
\end_index
\secnumdepth 3
\tocdepth 3
\paragraph_separation skip
\defskip bigskip
\quotes_language english
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 3
\html_css_as_file 0
\html_be_strict false
\end_header

\begin_body

\begin_layout Standard
\begin_inset Flex FragileFrameAllowframebreaks
status open

\begin_layout Plain Layout
\begin_inset Flex FragileTitle
status open

\begin_layout Plain Layout
Vector exercises
\end_layout

\end_inset

\end_layout

\begin_layout Plain Layout
\begin_inset ERT
status open

\begin_layout Plain Layout

\backslash
begin{tikzpicture}
\end_layout

\begin_layout Plain Layout

\backslash
node[right,text width=11.7cm,rounded corners,fill=blue!20,inner sep=1ex]{
\end_layout

\begin_layout Plain Layout

\backslash
begin{center}
\end_layout

\begin_layout Plain Layout

\backslash
textbf{EXERCISE
\backslash
ex}
\end_layout

\begin_layout Plain Layout

\backslash
end{center}
\end_layout

\begin_layout Plain Layout

Let's create a random sample of 10 smaller case letters from the alphabet
 as follows:
\end_layout

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

test.letters <- sample(letters,10)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\begin_layout Plain Layout

\backslash
begin{enumerate}
\end_layout

\begin_layout Plain Layout

\backslash
item Create a factor out of this vector and inspect it.
\end_layout

\begin_layout Plain Layout

\backslash
item What do you notice when inspecting the given levels of this factor?
\end_layout

\begin_layout Plain Layout

\backslash
item How can you make sure that the whole alphabet is taken into account
 in the levels?
\end_layout

\begin_layout Plain Layout

\backslash
end{enumerate}
\end_layout

\begin_layout Plain Layout

\backslash
vspace{.1in}};
\end_layout

\begin_layout Plain Layout

\backslash
end{tikzpicture}
\end_layout

\end_inset

A: The LyX file you posted didn't work here, but it looks like you have the tikzpicture environment in an ERT. By adding some more TikZ code, you can do a lot of things, including the ellipses and text in your image. This method is a little impractical perhaps, as you have to try several times to get the position and size of the additions correctly.
First, you have to name the node, so change the first line of the tikzpicture to
 \node (block) [right, ...

The node will now be named block, and we can use it's corners as coordinates, and place stuff relative to that. Here I've simply used xshift and yshift to place the stuff relative to the lower left corner. (Another way could be to use a similar technique to what I  describe in Highlight a table row with a rectangular overlay.)
\draw [red,very thick] ([xshift=3.55cm,yshift=3.65cm]block.south west) circle[x radius=.7cm,y radius=.3cm];
\node [red,right] at ([xshift=3.25cm,yshift=4.2cm]block.south west) {random sample and permutations, see \texttt{> ?sample}};

\draw [blue,very thick] ([xshift=4.9cm,yshift=3.65cm]block.south west) circle[x radius=.7cm,y radius=.3cm];
\node [blue,right] at ([xshift=3.9cm,yshift=3cm]block.south west) {26 lower case letters of the Roman alphabet};

The \draw lines draw ellipses (note the different x radius and y radius for the circle. As you may guess, block.south west is the lower left corner, and ([xshift=3.25cm,yshift=4.2cm]block.south west) is the point 3.25cm to the right, and 4.2cm above, this corner.
Here is the complete code for just this tikzpicture. I modified the code slightly, to get output similar to yours (I don't have the Sweave package).
\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\node (block) [right,text width=11.7cm,rounded corners,fill=blue!20,inner sep=1ex]  {
\begin{center}
\textbf{EXERCISE 1}
\end{center}
Let's create a random sample of 10 smaller case letters from the alphabet as follows:
\begin{verbatim}
<<>>=
test.letters <- sample(letters,10)
@
\end{verbatim}
\begin{enumerate}
\item Create a factor out of this vector and inspect it.
\item What do you notice when inspecting the given levels of this factor?
\item How can you make sure that the whole alphabet is taken into account in the levels? \end{enumerate}
\vspace{.1in}};

\draw [red,very thick] ([xshift=3.55cm,yshift=3.65cm]block.south west) circle[x radius=.7cm,y radius=.3cm];
\node [red,right] at ([xshift=3.25cm,yshift=4.2cm]block.south west) {random sample and permutations, see \texttt{> ?sample}};

\draw [blue,very thick] ([xshift=4.9cm,yshift=3.65cm]block.south west) circle[x radius=.7cm,y radius=.3cm];
\node [blue,right] at ([xshift=3.9cm,yshift=3cm]block.south west) {26 lower case letters of the Roman alphabet};
\end{tikzpicture}
\end{document}


text:
Q: How do I make sure that radiobuttons arent clickable if the checkbox is unchecked in android studio? I'm practicing an exercise from a book, and it's asking me to first, create a checkbox and then three radiobuttons. If the checkbox is unchecked, then the radiobuttons should appear to be disabled/grey/unclickable. However, as soon as you check the checkbox, the radiobuttons should appear to be working and clickable.
I created the layout for both the checkbox and the radiobuttons (radiobuttons are a part of radiogroup) but I'm having troubling connecting them in the way the exercise is asking.
How would I go about writing this out in the mainactivity?

A: You can use if statement for check your checkbox is already click or not. Set your button in condition disabled/grey first after that use if statement for check your checkbox, if checkbox have clicked usable your button.
your code will look like this
Button button1, button2, button3;
Checkbox checkbox;

button1 = findViewById (yourid);
button2 = findViewById (yourid);
button3 = findViewById (yourid);
checkbox = findViewById (yourid);

//Disable your button first
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);

if(checkbox.isChecked()){
  button1.setEnabled(true);
  button2.setEnabled(true);
  button3.setEnabled(true);
 }
else{
  Toast.makeText(getApplicationContext(), "Checkbox Haven't clicked",
  Toast.LENGTH_SHORT).show();
 }


text:
Q: Timestamp converter not working in Spring Data Rest with Spanner I'm trying to convert the input timestamp which will be in the string format to cloud timestamp with the help of a Spring Data Rest custom converter which is not working. Need an help on the same in understanding why custom converters are not invoked.
Input: http://localhost:8080/apipromocentral/promotions
RequestBody : {"startDateTime": "2019-11-07 15:53:00"}
POJO:
@ApiModel
@Data
@AllArgsConstructor
@Table(name = "PROMOTIONS")
public class Promotion {
  /**
   * promotion id
   */
  @ApiModelProperty(notes = "Id of the Promotion", required = true)
  @PrimaryKey
  @Column(name = "PROMO_ID")
  private String promotionId;

  @ApiModelProperty(notes = "Start Date Time of a promotion", allowableValues="yyyy-MM-dd HH:mm:ss", required = true)
  @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
  @Column(name = "START_DATE_TIME")
  private Timestamp startDateTime; //java.sql.timestamp;

}

converter code
@Component
public class TimestampWriteConverter implements Converter<java.sql.Timestamp, Timestamp> {

    @Override
    public Timestamp convert(java.sql.Timestamp sqlTimestamp) {
        //Return com.google.cloud.Timestamp;
        return Timestamp.of(sqlTimestamp);
    }
}

exception
"message": "FAILED_PRECONDITION: com.google.api.gax.rpc.FailedPreconditionException: io.grpc.StatusRuntimeException: FAILED_PRECONDITION: Invalid value for column START_DATE_TIME in table PROMOTIONS: Expected TIMESTAMP.",
        "trace": "com.google.cloud.spanner.SpannerException: FAILED_PRECONDITION: com.google.api.gax.rpc.FailedPreconditionException: io.grpc.StatusRuntimeException: FAILED_PRECONDITION: Invalid value for column START_DATE_TIME in table PROMOTIONS: Expected TIMESTAMP.\r\n\tat com.google.cloud.spanner.SpannerExceptionFactory.newSpannerExceptionPreformatted(SpannerExceptionFactory.java:156)\r\n\tat com.google.cloud.spanner.SpannerExceptionFactory.newSpannerException(SpannerExceptionFactory.java:45)\r\n\tat com.google.cloud.spanner.SpannerExceptionFactory.newSpannerException(SpannerExceptionFactory.java:112)\r\n\tat

A: Looking at the documentation, looks like you need pass the TimestampWriteConverter converter to ConverterAwareMappingSpannerEntityProcessor.
@Configuration
public class ConverterConfiguration {

    @Bean
    public SpannerEntityProcessor spannerEntityProcessor(SpannerMappingContext spannerMappingContext) {
        return new ConverterAwareMappingSpannerEntityProcessor(spannerMappingContext,
                Arrays.asList(new TimestampWriteConverter()),
                Arrays.asList());
    }
}


text:
Q: Test file is not running via maven on azure pipeline I'm using maven for building the automation project and using junit for running my test scripts . Its BBD framework where we have feature file, stepdefinition page.I have created pipeline , agent on azure devops . When running the pipeline it showing as build successful but still no tests cases are running .
Logs in maven :-
2022-10-07T13:21:37.3334382Z ##[section]Starting: Maven SmartBots/pom.xml
2022-10-07T13:21:37.3341187Z ==============================================================================
2022-10-07T13:21:37.3341428Z Task         : Maven
2022-10-07T13:21:37.3341633Z Description  : Build, test, and deploy with Apache Maven
2022-10-07T13:21:37.3341821Z Version      : 3.169.2
2022-10-07T13:21:37.3341987Z Author       : Microsoft Corporation
2022-10-07T13:21:37.3342231Z Help         : https://docs.microsoft.com/azure/devops/pipelines/tasks/build/maven
2022-10-07T13:21:37.3342495Z ==============================================================================
2022-10-07T13:21:38.2158528Z [command]/usr/bin/mvn -version
2022-10-07T13:21:38.2158912Z Apache Maven 3.5.4 (Red Hat 3.5.4-5)
2022-10-07T13:21:38.2159093Z Maven home: /usr/share/maven
2022-10-07T13:21:38.2159584Z Java version: 1.8.0_345, vendor: Red Hat, Inc., runtime: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.345.b01-1.el8_6.x86_64/jre
2022-10-07T13:21:38.2160036Z Default locale: en_US, platform encoding: UTF-8
2022-10-07T13:21:38.2160548Z OS name: "linux", version: "4.18.0-372.26.1.el8_6.x86_64", arch: "amd64", family: "unix"
2022-10-07T13:21:38.2163101Z SYSTEMVSSCONNECTION exists true
2022-10-07T13:21:38.2164119Z [command]/usr/bin/mvn -f /E/azdosagents/agent2/_work/113/s/SmartBots/pom.xml test
2022-10-07T13:21:38.7149886Z [INFO] Scanning for projects...
2022-10-07T13:21:38.7906399Z [INFO]
2022-10-07T13:21:38.7921739Z [INFO] ------------------------< com.company:SmartBots >-------------------------
2022-10-07T13:21:38.7923753Z [INFO] Building com.optum.ManualTracker 0.1.1-SNAPSHOT
2022-10-07T13:21:38.7925045Z [INFO] --------------------------------[ jar ]---------------------------------
2022-10-07T13:21:39.7344370Z [INFO]
2022-10-07T13:21:39.7433482Z [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ SmartBots ---
2022-10-07T13:21:39.7994520Z [INFO] Using 'UTF-8' encoding to copy filtered resources.
2022-10-07T13:21:39.8047081Z [INFO] Copying 21 resources
2022-10-07T13:21:39.8074402Z [INFO]
2022-10-07T13:21:39.8075718Z [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ SmartBots ---
2022-10-07T13:21:39.8834648Z [INFO] Nothing to compile - all classes are up to date
2022-10-07T13:21:39.8835474Z [INFO]
2022-10-07T13:21:39.8836068Z [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ SmartBots ---
2022-10-07T13:21:39.8901220Z [INFO] Using 'UTF-8' encoding to copy filtered resources.
2022-10-07T13:21:39.8901907Z [INFO] skip non existing resourceDirectory /E/azdosagents/agent2/_work/113/s/SmartBots/src/test/resources
2022-10-07T13:21:39.8902441Z [INFO]
2022-10-07T13:21:39.8902979Z [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ SmartBots ---
2022-10-07T13:21:39.8903395Z [INFO] No sources to compile
2022-10-07T13:21:39.8903634Z [INFO]
2022-10-07T13:21:39.8904175Z [INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ SmartBots ---
2022-10-07T13:21:39.9333349Z [INFO] ------------------------------------------------------------------------
2022-10-07T13:21:39.9334415Z [INFO] BUILD SUCCESS
2022-10-07T13:21:39.9334944Z [INFO] ------------------------------------------------------------------------
2022-10-07T13:21:39.9335464Z [INFO] Total time: 1.237 s
2022-10-07T13:21:39.9337421Z [INFO] Finished at: 2022-10-07T08:21:39-05:00
2022-10-07T13:21:39.9338075Z [INFO] ------------------------------------------------------------------------
2022-10-07T13:21:40.0354312Z No test result files matching /E/azdosagents/agent2/_work/113/s/**/surefire-reports/TEST-*.xml were found, so publishing JUnit test results is being skipped.
2022-10-07T13:21:40.0408313Z ##[section]Finishing: Maven SmartBots/pom.xml


text:
Q: MYSQL - SELECT AS alias to be used in subquery I want to be able to use one of the items I am selecting further down in my sub query.
As you can see in this example I have set the "variable" in question as 100 but in reality this is going to be a dynamic number so I will need to be able to access it in the subquery.
INSERT INTO users_friends (userId, friendId)
SELECT 77, id as noob
FROM users WHERE email = 'a@g.com'
AND
NOT EXISTS (SELECT * FROM users_friends
WHERE userId = 77 and friendId = noob)
LIMIT 1

A: I'm not completely sure I understand your question, but NOT EXISTS works just like LEFT JOIN and IS NULL.  So I think this will work:
SELECT 77, @noob
FROM users u
  JOIN (SELECT @noob:= 100) r
  LEFT JOIN users_friends uf on u.userid = uf.userid and uf.friendid = @noob
WHERE email = 'a@g.com'
  AND uf.userid IS NULL

And here is the SQL Fiddle.

A: EDIT
I would recommend changing your table structure.
    CREATE TABLE users_friends(
userid int,
friendid int,
primary key (userid, friendid)
);

CREATE TABLE users (
 userid int primary key,
 email varchar(100),
 name VARCHAR (100),
 index (email,name)
);

INSERT INTO users VALUES (1, 'a@g.com', 'noob'), (2,'b@g.com', 'Joe');

INSERT INTO users_friends (userId, friendId)
VALUES (2, (SELECT userId
FROM users
WHERE email = 'a@g.com'
AND name = "noob"
AND NOT exists (SELECT * FROM users_friends as uf
            JOIN users as u
            ON u.userid = uf.userid
            where uf.friendid = 2 AND name = "noob"
           )
           )
       );

SQL FIDDLE DEMO
Try this:
    <?php

    function select_query ($userid,$friendname, $email){
    $host = "host";
    $user = "username";
    $password = "password";
    $database = "database name";

    // open connection to databse
    $link = mysqli_connect($host, $user, $password, $database);
            IF (!$link){
                echo ("Unable to connect to database!");
            }
            ELSE {
               //Is someone registered at other conference from table registration
               $query = "    INSERT INTO users_friends (userId, friendId)
VALUES (".$userId.", (SELECT userId
FROM users
WHERE email = '".$email."'
AND name = '".$friendname."'
AND NOT exists (SELECT * FROM users_friends as uf
            JOIN users as u
            ON u.userid = uf.userid
            where uf.friendid = ".$userId." AND name = '"$friendname"'
           )
           )
       )";
               $result = mysqli_query($link, $query);
               return $query;
               return $result;
            }
            mysqli_close($link);
    }

    echo select_query(1,noob,'a@g.com');
   ?>

Like I mentioned above I not sure what you mean. If you mean dynamic in the sense that you can change the value of the variable this might help. In your previous posts you used PHP. So, my guess is that your are using PHP.

A: I think the safest approach is to define these in a subquery.  I typically give this the alias of const:
INSERT INTO users_friends (userId, friendId)
    SELECT const.userId, const.noob
    FROM users cross join
         (select 77 as userId, 100 as noob) const
    WHERE email = 'a@g.com' AND
          NOT EXISTS (SELECT *
                      FROM users_friends
                      WHERE userId = const.userId and friendId = const.noob
                     )
    LIMIT 1

I am concerned about SGeddes's approach, because it relies on the correct evaluation of variables outside the scope of the query.  This might work in this case, but I prefer a solution where the query does not rely on outside variables.  By the way, this should also work in any database, and is not MySQL-specific.

A: INSERT INTO users_friends (userId, friendId)
SELECT 77, id
FROM users WHERE email = 'a@g.com'
AND
NOT EXISTS (SELECT * FROM users_friends
WHERE userId = 77 and friendId = (SELECT id
FROM users WHERE email = 'a@g.com'))
LIMIT 1


text:
Q: PHP/AJAX Image Grabbing script similar to functionality Facebook messaging When sending a message on Facebook, if you include a URL it generally grabs a picture from the webpage and adds it at the bottom as a thumbnail. You then have the ability to select through a number of pictures featured on the site.
I can see how this could be built, but to save me the hassle I wonder if somebody has already done it already in a publicly available format?
Thanks!

A: Alright, the code sample I prepared for you was too long to add as a comment of the first.   So here's the correct code, verified to work on my local PHP environment (5.3.1):
<?php
/**
 * Sample CURL Image Extractor
 *
 * Prepared for stackoverflow.com
 *
 * @author Sam Skjonsberg <skoneberg@gmail.com>
 **/

if(!function_exists('json_encode'))
{
    die('You need at least PHP 5.2 to use this script.');
}

//
// JSON & No-Cache Headers
// Uncoment when implemented as an actual JSON service
//
//header('Cache-Control: no-cache, must-revalidate');
// Date in the past to ensure it isn't cached
//header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
//header('Content-type: application/json');
//

//$url      =   parse_url($_REQUEST['url']);
// Harcoded url for demonstration
// Shameless self-plug :)
$url        =   'http://www.codeviking.net';

if(!empty($url))
{

    if(!preg_match('%^https?://%i', $url))
    {
        echo get_json_error('Invalid URL');
    }

    $ch     =   curl_init();

    curl_setopt_array(
                        $ch,
                        array
                        (
                            CURLOPT_URL             =>  $url,
                            CURLOPT_RETURNTRANSFER  =>  true,
                            CURLOPT_FOLLOWLOCATION  =>  true
                        )
                     );

    $html   =   curl_exec($ch);

    if(!empty($html))
    {
        $doc                =   new DOMDocument($html);

        $doc->loadHTML($html);

        $images             =   $doc->getElementsByTagName('img');

        $image_srcs         =   array();

        foreach($images as $img) {
            foreach($img->attributes as $attribute_name => $attribute_node)
            {
                if($attribute_name == 'src')
                {
                    $src            =   $attribute_node->nodeValue;

                    // Parse image into absolute URL
                    if(!preg_match('%^https?://%i', $src))
                    {
                        $src    =   $url . '/' . preg_replace('%^\.?/%', '', $src);
                    }

                    $image_srcs[]   =   $src;

                }
            }
        }

        echo json_encode($image_srcs);

        // And there you have it, a collection of image
        // paths to parse through on the client and add <img src="image_src" /> for each.
        //
        // So, for instance as your ajax success callback
        //
        //
        // var images = parseJSON(image_json);
        // for(var i = 0; i < images.length; i++)
        // {
        //  image_src = images[i];
        //  /* Requires jQuery */
        //  $('body').append($('<img />').attr('src', image_src));
        // }
    }
    else
    {
        echo get_json_error('Invalid URL');
    }
}
else
{
    echo get_json_error('Invalid URL');
}

function get_json_error($msg)
{
    $error  =   array('error' => $msg);
    return json_encode($error);
}

That really should work.   Also I'd appreciate a vote up on the answer as I'm trying to break the 100 point mark!  Thanks and good luck!

A: Really shouldn't be hard to implement.  Coding is fun, take this and roll with it:
$ch = curl_init();

curl_setopt_array($ch, array(CURLOPT_URL => $_POST['url'], CURLOPT_FOLLOWLOCATION => true, CURLOPT_RETURNTRANSFER, true));

$results = curl_exec($ch);

$doc = new DOMDocument();

$doc->loadHTML($results);

$images = $doc->getElementsByTagName('img');

This should return a DOMNodeList I believe -- from there you iterate through and pull out the src attribute for each image, stick it into json_encode(), and then write a nice webservice to submit a url and return the nice little collection of images.
I realize its not what you're asking for, but its a start.