text:
Q: Proof that the equation $x^2 - 3y^2 = 1$ has infinite solutions for $x$ and $y$ being integers I have seen the Pell's equation wiki page but I need to prove this from scratch without mentioning any formula. I have also seen multiple answers on this site but the answers tend to skip over and assume formulas.
This is what people do -> $x^2 - 3y^2 = 1$ has solution 1, 0.
Next they say we "observe" that $$(x',y') = (2x + 3y, x + 2y)$$ is also a solution.
What I'm asking is how they get this value. Can someone help?

A: I see a couple issues that may prove to be stumbling blocks. First you might have had problems verifying the solution $\,(\bar x,\bar y) = (2x+3y,x+\color{#c00}3y)\,$ because it is incorrect: the $\color{#c00}3$ should be $2.\,$ Now one can may verify that $\,(\bar x,\bar y)\,$ is also a solution using no more than simple integer arithmetic
$$\begin{eqnarray}
\bar x^2 &=&\quad\ (2x+3y)^2 &=&\,\ \ \ 4x^2\,+\ 9y^2 +\, 12xy\\
-3\,\bar y^2&=&-3(x^2+2y)^2 &=&\, -3x^2-12y^2-12xy \\
\hline
\bar x ^2 -\, 3\bar y^2&& &=& \ \ \ \ x^2\ -\ 3y^2 =\, 1
\end{eqnarray}\qquad\qquad  $$
Though some explanations of the genesis of this composition law on the solution space may utilize ideas that you have not yet learned (such as the multiplicativity of the norm map on quadratic felds), the above direct proof that $\,(\bar x, \bar y)\,$ is a solution does not require such methods. Rather, it is a simple calculation using only integer arithmetic.
Said composition law is a special case of the fact that one may compose (multiply) any two solutions using the Brahmagupta–Fibonacci identity below. Above is the special case $\,a,b = 2,1.$
$$\begin{eqnarray} (a^2-3b^2)(x^2-3y^2) &\,=\,& (ax+3by)^2- 3(ay+bx)^2\\
(a+b\sqrt{3})(x+y\sqrt{3})\, &\,=\,& \ \,ax+3by\ \ +\,\ \  (ay+bx)\sqrt{3}
\end{eqnarray}\qquad$$
Again, though the composition law may be intuitively derived by taking the norm of the quadratic integers listed below it, you can verify the integer identity above it using only integer arithmetic - independent of "irrational" numbers, quadratic fields, norms, etc.

A: Based on a similar result I know for $x^2 -2y^2 = 1$, I would bet solid gold it falls out of abstract algebra in the study of the ring $\mathbb{Z}[\sqrt{3}] = \{ a + \sqrt{3}b \ | \ a, b \in \mathbb{Z} \}$.
We define a function $N: \mathbb{Z}[\sqrt{3}] \to \mathbb{Z}$ modeled on the complex norm, which multiplies a number by its complex conjugate.
$N(x + \sqrt{3}y) := (x +\sqrt{3}y)(x - \sqrt{3}y) = x^2 -3y^2$
Now, it just so happens that this shares a nice property of the complex norm.
For any two elements $z, w \in \mathbb{Z}[\sqrt{3}]$ we have $N(zw) = N(z)N(w)$. This isn't difficult to prove, just do the computation.
So, say we have some $x + \sqrt{3}y = z \in \mathbb{Z}[\sqrt{3}]$ with $N(z) = x^2 -3y^2 = 1$. It's easy to check that $(2, 1)$ is also a solution, and hence $N(2 + \sqrt{3}) = 1$.
Now we have $1 = N(z)N(2 + \sqrt{3}) = N((x + \sqrt{3}y)(2 + \sqrt{3})) = N((2x+3y) + \sqrt{3}(x + 2y))$.
But $N((2x+3y) + \sqrt{3}(x + 2y)) = 1$ means that $(2x+3y, x + 2y)$ is a solution.
If your initial values for x and y are both positive, then the solution they generate must be larger, so each new solution must be distinct.

A: The way I think about the Pell equation is like this:
$x^2 - 3y^2$ is an integer and it can't be $0$ because $\sqrt 3$ is irrational. So closest it can be to $0$ is $1$ (or $-1$, the other variant for Pell equation).
This leads us to search for good rational approximations for $\sqrt 3$. These we get from the continued fraction expansion of $\sqrt 3$.
All the solution of the Pell equation come from the continued fraction expansion. Now, since the expansion is periodic for $\sqrt d$ (general $d$ in Pell equation), we can derive a formula for the solutions.

A: In algebraic number theoretic terms, this means that there are infinitely many units in $\mathbb{Z}[\sqrt{3}]$. I'm hardly an expert on algebraic number theory (I only know that I know nothing), but I do know how to get this result using its basic methods (usually found in the first two or three chapters of most algebraic number theory textbooks).
This limited knowledge of the topic makes me want to start with $x = 2$, $y = 1$ as a prototypical solution rather than $x = 1$, $y = 0$. Verify that $2^2 - 3 \times 1^2 = 1$. Also verify that $(2 - \sqrt{3})(2 + \sqrt{3}) = 1$.
What if instead of multiplying $(2 + \sqrt{3})$ by $(2 - \sqrt{3})$ we multiply it by itself? We get $(2 + \sqrt{3})^2 = 7 + 4\sqrt{3}$. Notice that $7^2 - 3 \times 4^2 = 1$, and also notice that $(7 - 4\sqrt{3})(7 + 4\sqrt{3}) = 1$. And then $(2 + \sqrt{3})(7 + 4\sqrt{3}) = 26 + 15\sqrt{3}$, $26^2 - 3 \times 15^2 = 1$, $(26 - 15\sqrt{3})(26 + 15\sqrt{3}) = 1$.
What's going on here is that $2 + \sqrt{3}$ is a unit with a norm of 1. The norm is multiplicative, so if we multiply a number with a norm of 1 by any number that also has a norm of 1, the product will also have a norm of 1. And since this multiplication can be carried on infinitely, this means we can obtain as many numbers with a norm of 1 as we can calculate.
But... is computing $(2 + \sqrt{3})^n = x + y\sqrt{3}$ the most efficient way to get more pairs of $x$ and $y$? Is there some kind of pattern we could exploit to obtain new values of $x$ and $y$ without having to invoke irrational numbers at all? So far we've obtained the first four values of two sequences: 1, 2, 7, 26; and 0, 1, 4, 15.
Can we figure out an obvious pattern for these two sequences? $x_1 = 1$, $x_2 = 2$, $x_n = 4x_{n - 1} - x_{n - 2}$; and $y_1 = 0$, $y_1 = 1$, $y_n = 4y_{n - 1} - y_{n - 2}$. Maybe this works, maybe it doesn't work, but regardless it would be better to figure out something in which the $x$ and $y$ are dependent on each other. With trial and error, and a little cleverness, we might figure out $x_n = 2x_{n - 1} + 3y_{n - 1}$ and $y = x_{n - 1} + 2y_{n - 1}$.
So, for example, plugging in $x_4 = 26$ and $y_4 = 15$ gives us $x_5 = 97$ and $y_5 = 56$. Let's check that this worked correctly: $97^2 - 3 \times 56^2 = 9409 - 3 \times 3136 = 9409 - 9408 = 1$; $(97 - 56\sqrt{3})(97 + 56\sqrt{3}) = 1$.

If you're still reading, I'd like to throw a couple more algebraic number theory concepts at you. A fundamental unit (what could be called the "prototypical" unit) can be proper or improper, meaning that its norm is 1 or $-1$. In $\mathbb{Z}[\sqrt{3}]$, it's proper. In $\mathbb{Z}[\sqrt{2}]$, it's improper: $(1 - \sqrt{2})(1 + \sqrt{2}) = -1$. This tells us that both $x^2 - 2y^2 = 1$ and $2y^2 - x^2 = 1$ have infinitely many solutions in integers. But, depending on how we go about it, solutions for one equation would alternate with solutions for the other.

A: More generally,
$(u^2-dv^2)(x^2-dy^2)
=(ux+dvy)^2-d(uy+vx)^2
$.
So
$(x^2-dy^2)^2
=(x^2+dy^2)^2-d(2xy)^2
$.
(Another totally unoriginal answer)


text:
Q: Implementing Iterator of the custom Collection backed by PriorityQueue and HashMap I've implemented HashPriorityQueue class, which combines HashMap (for fast lookup) and PriorityQueue (for sorting the data).
Another improvement I made is to guarantee ordered iteration.
Because PriorityQueue does not promise such a thing, from JavaDocs:

The Iterator provided in method iterator() is not guaranteed to traverse the elements of the priority queue in any particular order.

I also want to guarantee ordered iteration and should work in a multithreaded environment.
To make HashPriorityQueue class work I've already done the following steps:

*

*Extended HashMap class.

*Added a private field PriorityQueue.

*Override all the methods that change the values of the HashMap so that I can add and remove values from my queue.

*Added queue-related methods: poll() and peek().

*Add an implementation of a custom Iterator for this new data structure that internally makes a copy of the queue and uses poll() in the next() method to maintain ordered iteration.

Code:
public class HashPriorityQueue<K, V> extends HashMap<K, V> implements Iterable<AbstractMap.SimpleEntry<K, V>>{
    private final PriorityQueue<K> queue;

    /* CONSTRUCTORS */

    public HashPriorityQueue(Comparator<K> comparator) {
        queue = new PriorityQueue(comparator);
    }

    public HashPriorityQueue() {
        queue = new PriorityQueue();
    }

    /* QUEUE METHODS */

    public AbstractMap.SimpleEntry<K, V> poll() {
        K key = queue.poll();
        V val = remove(key);
        return new AbstractMap.SimpleEntry<K, V>(key, val);
    }

    public AbstractMap.SimpleEntry<K, V> peek() {
        K key = queue.peek();
        V val = get(key);
        return new AbstractMap.SimpleEntry<K, V>(key, val);
    }

    @Override
    public V remove(Object key) {
        queue.remove(key);
        return super.remove(key);
    }

    public V remove(AbstractMap.SimpleEntry<V, K> entry) {
        return remove(entry.getKey());
    }

    @Override
    public V put(K key, V value) {
        queue.add(key);
        return super.put(key, value);
    }

    @Override
    public Iterator<AbstractMap.SimpleEntry<K, V>> iterator() {
        return new PriorityIterator();
    }

    private class PriorityIterator implements Iterator<AbstractMap.SimpleEntry<K, V>>{
        PriorityQueue<K> keys;
        K cursor;

        public PriorityIterator() {
            keys = new PriorityQueue<>(HashPriorityQueue.this.queue);
        }

        @Override
        public boolean hasNext() {
            return !keys.isEmpty();
        }

        @Override
        public AbstractMap.SimpleEntry<K, V> next() {
            cursor = keys.poll();
            V v = HashPriorityQueue.this.get(cursor);
            return new AbstractMap.SimpleEntry<>(cursor,v);
        }

        @Override
        public void remove() {
            HashPriorityQueue.this.remove(cursor);
        }
    }
}

Currently, the iterator creates a copy of the queue and iterates over the keys by polling them from the copy of the queue. The corresponding value is being obtained from the map using get().
The iterator isn't aware of any structural and non-structural medications of the map.
So the actual question is:
How can I ensure that my Collection has not been modified during the process of iteration? I was thinking of adding a boolean flag isChanged, would it be a good approach?
I would also appreciate other suggestions regarding this implementation.

A:
which will also guarantee ordered iteration and should work in a
multi-threaded environment.

Firstly, let's start with a single-threaded implementation and then expand it.
Disclaimer: I don't treat this problem as having practical application, but rather as a project having a value from the educational perspective.
The rationale behind this remark would be clear if we enumerate the time complexities of the operations available with this custom Collection in comperison with TreeMap:

*

*iterator() - O(n * log n) (worse than TreeMap);

*remove() - O(n) (worse than TreeMap);

*poll() - O(log n);

*put() - O(log n);

*peek() - O(1);

*get() - O(1) (better than TreeMap).

Operations with Iterator:

*

*next() - O(log n)  (worse than iterator returned by the TreeSet);

*hasNext() - O(1);

*iterating over the all keys - O(n * log n).

get() - is the only method in this collection that performs better then corresponding methods of the TreeMap. All the rest have the same or even worse performance due to being effected by the ovehead of maintaining the PriorityQueue which has a logorithmic time complexity for enqueuing and dequeuing methods.
Favor Composition over Inheritance
When you need to be able to use the functionality of a particular class in another class, inheritance isn't the first approach you have to think about, rather the last resort.
Why? Inheritance creates tight coupling, like in the code you've provided your new Collection happens to be completely dependent on the implementation of HashMap.
In fact, your custom class is broken. You didn't override all the methods that allow to modify the map structurally, for instance compute(), merge(), etc. But there's more to that, since it's a subclass of HashMap, it can be altered by removing elements from the collection of values obtained via values() or by removing the entries from the entry set, in these case there would be not possible to change the PriorityQueue accordingly.
Sure, values() and entrySet() can be overridden by making them return unmodifiable collections. So it turns out you need override almost each and every method. And nevertheless a new functionality which can be introduced in the future or changes of the existing methods might break your code.
For more information on that see the Item "Favor composition over inheritance" of the "Effective Java" by Joshua Bloch (former Sun-employee which has developed many features of Java including Collections framework).
The better approach would be to use Composition, i.e. replace IS-A relationship with HAS-A relationship by creating a class that uses a HashMap, i.e. has a field of type HashMap, rather than being a HashMap itself. And that would be a Loose coupling because your Collection no longer depends on the HashMap implementation, methods of your collection would delegate calls to the HashMap allowing it to do whatever it does internally.
You are not bound with any contracts and can expose only a limited number of methods that allow to interact with your Collection.
Note that unfortunately you can't implement Map interface because it might cause problems if interface would be extended.
That how it might be implemented:
class HashPriorityQueueNonSync<K, V> implements Iterable<Map.Entry<K, V>> {

    private final PriorityQueue<K> queue;
    private final Map<K, V> map = new HashMap<>();
    private int modCount = 0;

    /* CONSTRUCTORS */

    public HashPriorityQueueNonSync(Comparator<K> comparator) {
        queue = new PriorityQueue<>(comparator);
    }

    public HashPriorityQueueNonSync() {
        queue = new PriorityQueue<>();
    }

    /* QUEUE METHODS */

    public Map.Entry<K, V> poll() {
        modCount++;
        K key = queue.poll();
        V val = remove(key);
        return Map.entry(key, val);
    }

    public Map.Entry<K, V> peek() {
        K key = queue.peek();
        V val = map.get(key);
        return Map.entry(key, val);
    }

    /* MAP METHODS */

    public V get(Object key) {
        return map.get(key);
    }

    public V put(K key, V value) {
        modCount++;
        queue.add(key);
        return map.put(key, value);
    }

    public V remove(Object key) {
        modCount++;
        queue.remove(key);
        return map.remove(key);
    }

    public V remove(Map.Entry<K, V> entry) {
        modCount++;
        queue.remove(entry.getKey());
        return map.remove(entry.getKey());
    }

    @Override
    public Iterator<Map.Entry<K, V>> iterator() {
        return new PriorityIterator();
    }

    private class PriorityIterator implements Iterator<Map.Entry<K, V>> {
        private PriorityQueue<K> keys;
        private K cursor;
        private final int expectedModCount;

        public PriorityIterator() {
            this.keys = new PriorityQueue<>(HashPriorityQueueNonSync.this.queue);
            this.expectedModCount = HashPriorityQueueNonSync.this.modCount;
        }

        @Override
        public boolean hasNext() {
            return !keys.isEmpty();
        }

        @Override
        public Map.Entry<K, V> next() {
            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            cursor = keys.poll();
            V v = HashPriorityQueueNonSync.this.get(cursor);
            return Map.entry(cursor, v);
        }

        @Override
        public void remove() {
            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            HashPriorityQueueNonSync.this.remove(cursor);
        }
    }
}

How to prevent Structural modification during Iteration
The common practice to ensure that iterator would reflect the actual state of the collection is to introduce two counters of modifications: one as the instance field of the collection (modCount in the code above), another in the Iterator (expectedModCount).
When these variables are not equal, that means that there has been a modification after the iterator was created that was done other than the means of iterator. All the implementations of Iterator from the JDK would throw ConcurrentModificationException in such a case.
Concurrent implementation
First of all, there two concepts to consider:

*

*Atomicity - when a thread is modifying the state of an object (in this case changes the underlying queue and map of the custom collection), all other threads can not observe intermediate changes, they can see either both queue and map fully modified or not. We can ensure that all actions on both queue and map would occur atomically by using synchronized keyword on methods of this custom Collection. The approach shown below is very basic and can be observed in legacy collections like Vector and Hashtable, but because under the hood we have two separate underlying collections which need to be accessed atomically it hard apply anything more neat than synchronized.

*Happens-before Order - describes visibility of subsequent changes. If one action happens-before another, then the first is visible to and ordered before the second. One of the ways to ensure this is by using the volatile keyword.
Note that methods of the iterator doesn't require synchronization (it's mean to be used withing a single thread only), but we need to synchronize the method of the collection responsible for obtaining the iterator.
That's how concurrent implementation might look like:
public class HashPriorityQueue<K, V> implements Iterable<Map.Entry<K, V>> {

    private final PriorityQueue<K> queue;
    private final Map<K, V> map = new HashMap<>();
    private volatile int modCount = 0;

    /* CONSTRUCTORS */

    public HashPriorityQueue(Comparator<K> comparator) {
        queue = new PriorityQueue<>(comparator);
    }

    public HashPriorityQueue() {
        queue = new PriorityQueue<>();
    }

    /* QUEUE METHODS */

    public synchronized Map.Entry<K, V> poll() {
        modCount++;
        K key = queue.poll();
        V val = remove(key);
        return Map.entry(key, val);
    }

    public synchronized Map.Entry<K, V> peek() {
        K key = queue.peek();
        V val = map.get(key);
        return Map.entry(key, val);
    }

    /* MAP METHODS */

    public synchronized V get(Object key) {
        return map.get(key);
    }

    public synchronized V put(K key, V value) {
        modCount++;
        queue.add(key);
        return map.put(key, value);
    }

    public synchronized V remove(Object key) {
        modCount++;
        queue.remove(key);
        return map.remove(key);
    }

    public synchronized V remove(Map.Entry<K, V> entry) {
        modCount++;
        queue.remove(entry.getKey());
        return map.remove(entry.getKey());
    }

    @Override
    public synchronized Iterator<Map.Entry<K, V>> iterator() {
        return new PriorityIterator();
    }

    private class PriorityIterator implements Iterator<Map.Entry<K, V>> {
        private PriorityQueue<K> keys;
        private K cursor;
        private final int expectedModCount;

        public PriorityIterator() {
            this.keys = new PriorityQueue<>(HashPriorityQueue.this.queue);
            this.expectedModCount = HashPriorityQueue.this.modCount;
        }

        @Override
        public boolean hasNext() {
            return !keys.isEmpty();
        }

        @Override
        public Map.Entry<K, V> next() {
            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            cursor = keys.poll();
            V v = HashPriorityQueue.this.get(cursor);
            return Map.entry(cursor, v);
        }

        @Override
        public void remove() {
            if (expectedModCount != modCount) {
                throw new ConcurrentModificationException();
            }
            HashPriorityQueue.this.remove(cursor);
        }
    }
}

A very small Test
main()
public static void main(String[] args) {
    HashPriorityQueue<Integer, Integer> hpq = new HashPriorityQueue<>();

    ExecutorService executor = Executors.newFixedThreadPool(3);

    executor.submit(() -> { for (int i = 3; i < 7; i++) hpq.put(i, 1 << i); });
    executor.submit(() -> { for (int i = 0; i < 3; i++) hpq.put(i, 1 << i); });
    executor.submit(() -> { for (int i = 7; i < 10; i++) hpq.put(i, 1 << i); });

    try {
        executor.awaitTermination(3, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    executor.shutdown();

    hpq.forEach(System.out::println);
}

Output:
0=1
1=2
2=4
3=8
4=16
5=32
6=64
7=128
8=256
9=512

redpajama_set_name: RedPajamaStackExchange


text:
Q: Session Variable In php This simple issue I know, in my program session variable is already working properly but now it show some error. I am starting the session in my config page with session_start();  ob_start(); And then include this page in all pages. But if run the program I receive this error message:

Cannot send session cache limiter - headers already sent

If remove the included config page the session variable is notworking.
session_start();
  ob_start();

  $dbcont = mysql_connect("localhost","root","");
  mysql_select_db("emplist",$dbcont);

if($_POST["subSubmit"]=="Submit") {
    $user = $_POST["txtUsername"];
    $pass = $_POST["txtPassword"];

    if ($user == "user" && $pass == "pass") {

     $_SESSION["uaid"] = "ADMIN SECTION";

     header("Location:welcome.php");
       exit();
    }else{
    $err = "Login Failed. Check You UserID/Password";
    }

     }

?>

<html>
    <head>
        <title>.:: Employee Management ::.</title>

</head>
    <body>

              <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="form1" id="form1" onSubmit="return checklogin();">

             USER ID : <input type="text" name="txtUsername" id="txtUsername" onKeyUp="return clearerr();">

             PASSWORD : <input type="password" name="txtPassword" id="txtPassword" onKeyUp="return clearerr();">

             <input type="submit" class="FormButton" name="subSubmit" id="subSubmit" value="Submit">

             <input type="reset" class="FormButton" name="butReset" id="butReset" value="Reset">

                    </form>

    </body>
</html>

This is my main page code. If login is successful then the control will be moved to "Welcome.php" page in that page I just echo the session variable.

A: move the session_start(); to the very top
You see, The RULE is you cannot have anything before the session_start(); NOT ONE CHARACTER, otherwise, the browser thinks the webpage has already started, so before you start session_start(); YOU CANNOT START THE HEADER. You start the header with any character, this includes white spaces (space bar).
So also choose your browser Accordingly.

A: Try to delete BOM symbols rom script.

A: If you haven't already, try putting session_start() before any output is generated from the script.


text:
Q: 'props' of undefined inside map closure I get TypeError: Cannot read property 'props' of undefined. I need to my Li component to receive props. I'm using styled-component by the way.
const Li = styled.li`
  border-top: 0 none;
`;

class Popular extends Component {
    render() {
        var languages = ['All', 'Javascript', 'Java', 'Python'];
        return (

                {languages.map(function(lang){
                    return (
                        <Li className={`list-group-item p-2 ${this.props.className}`}>
                            {lang}

                    )
                })}

        );
    }
}

export default Popular;

A: You need to bind the callback of languages.map to the popular class. You can either use arrow function like this
{languages.map((lang) => {

or just pass this as the second argument of map function like this
{languages.map(function(lang){
       ...
}, this)}

or you can bind it using bind function like this
{languages.map((function(lang){
       ...
}).bind(this))}


text:
Q: C# free audio libraries for download Are there some free audio libraries for commericial use (like NAudio) that is able to play mp3 (but not NAudio!)
thanks very much! :)

A: You can use the built in WMPLib - see this MSDN article on Creating the Windows Media Player Control Programmatically.
At the most basic level you'll need code like this:
private void PlayFile(String url)
{
    Player = new WMPLib.WindowsMediaPlayer();
    Player.URL = url;
    Player.controls.play();
}

However, you also get events to tell you that the play state has changed so you can start playing a new track, or close the form (for example):
Player.PlayStateChange +=
    new WMPLib._WMPOCXEvents_PlayStateChangeEventHandler(Player_PlayStateChange)

private void Player_PlayStateChange(int NewState)
{
    if ((WMPLib.WMPPlayState)NewState == WMPLib.WMPPlayState.wmppsStopped)
    {
        this.Close();
    }
}

It does mean that your application is tied to Windows - so you can't use Mono.

A: You could try using DirectSound. The entries for DirectSound are removed from the "Add Reference" dialog in VS 2008 or higher (I think) but you can still browse in the GAC for the proper DLLs. Look for the latest version. It's pretty easy, something like:
Device dev = new Device();
dev.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority); // this refers to the form to which DirectSound is tied
SecondaryBuffer sound = new SecondaryBuffer("path\\to\\file", dev);
sound.Volume = /* volume */;
sound.Play(0, BufferPlayFlags.Default);


text:
Q: Object doesn't support property or method 'slideToggle' in MS Edge called from an iframe I am trying to slideToggle a div with "main-nav" id from an iframe:

    ..

...

but I am getting an Error: 0:Object doesn't support property or method 'slideToggle'.
I am using this onClick event handler for a.dropdown-toggle link:
$(function(){
  $("a.dropdown-toggle").on("click", function(){
    $("#main-nav", window.parent.document).slideToggle(300);
  });
});

I am testing in Microsoft Edge 44.18362.267.0, Microsoft EdgeHTML 18.18362 .
I am loading jQuery library before my script attaches the onClick eventhandler.
I tried $("#main-nav", window.parent.document).slideToggle(300); in the edge console and it works correctly.
Any ideas what could be the problem here? Thanks.
EDIT
After pushing my code to github I tested it in chrome and got this Error:
Uncaught TypeError: $(...).slideToggle is not a function
    at HTMLAnchorElement.myEventHandler (navbar.html:48)
    at HTMLAnchorElement.dispatch (jquery-3.3.1.slim.min.js:2)
    at HTMLAnchorElement.v.handle (jquery-3.3.1.slim.min.js:2)
myEventHandler @ navbar.html:48
dispatch @ jquery-3.3.1.slim.min.js:2
v.handle @ jquery-3.3.1.slim.min.js:2

SOLUTION
Then I found out this solution.
The problem was in including slim minified version of jQuery, changing this to just minified version helped.

A: The solution is described here.
The problem is in including slim minified version of jQuery, changing this to just minified version solves the issue.


text:
Q: Start a ZFS RAIDZ zpool with two discs then add a third? Let's say I have two 2TB HDDs and I want to start my first ZFS zpool. Is it possible to create a RAIDZ with just those two discs, giving me 2TB of usable storage (if I understand it right) and then later add another 2TB HDD bringing the total to 4TB of usable storage. Am I correct or does there need to be three HDDs to start with?
The reason I ask is I already have one 2TB drive I'm using that's full of files. I want to transition to a zpool but I'd rather only buy two more 2TB drives if I can. From what I understand, RAIDZ behaves similarly to RAID5 (with some major differences, I know, but in terms of capacity). However, RAID5 requires 3+ drives. I was wondering if RAIDZ has the same requirement.
If I have to, I can buy the three drives and just start there, later adding the fourth, but if I could start with two and move to three that would save me $80.

A: Unfortunately, at the moment it is not possible:

It is not possible to add a disk as a column to a RAID-Z, RAID-Z2, or RAID-Z3 vdev. This feature depends on the block pointer rewrite functionality due to be added soon. One can however create a new RAID-Z vdev and add it to the zpool.

RAID-Z1 might work with just 2 drives, but clearly this is not very useful if extra drives cannot be added later. RAID-Z (like RAID 5) becomes more efficient, in terms of usable storage space, the more drives that are used.

A: RAID-Z1 can be used with only two disks but there is no advantage at all compared to mirroring - unless your two disks have different sector sizes, so that they can't be mirrored (e.g.: a new 4K sector disk and an older 512 byte disk).
As already stated, adding a device to a RAID-Z isn't supported. Should you want to add a disk to an existing RAID-Z, the only way is to backup your data elsewhere, destroy the the pool and recreate it with the extra disk added then restore your data.

A: Don't have enough "reputation" to comment, so putting this in as a separate answer
RE: Holger G suggestion
while I agree that this is NOT safe...
I found this thread looking for a way to go from RAIDZ1 to RAIDZ2 at a later date when extra drive can be acquired.
So Holgers suggestion works great for me - create a RAIDZ2 with one dev as sparse file,
offline the file device
and have effectively RAIDZ1 for a while and then add a real device at some point to double the redundancy
Also works for the situation where the one drive holds the data that is to be copied to the new raid, as the OP has.

A: A method some people use, but that is not recommended:

*

*Create a pool with 2 drives and a sparse file (of the right, virtual size to match the other drives), and then immediately offline the sparse file.  This will create a degraded RAID-Z1 pool with two drives worth of capacity and no redundancy.

*Copy data to the degraded pool.

*Replace the offlined sparse-file with the third disk and resilver.

The number of "devices" that a vdev is created with, is permanent after creation.  Therefore, you must have three "disks" at the time of creation.  This method gives a way to create a degraded RAID-Z1 pool and later restore the absent redundancy.
This method is not recommended, because while copying and while the 3rd drive is absent, there is no redundancy/parity.  But it can work.

A: Just a point to make some light:

*

*If one disk can fail without prior knowing when will it fail... why two can not fail at the same time? or three or four or five, etc.?

But, think on this other situation:

*

*One disk has failed

*You put a new one and let it 're-build' to be safe

*While such 're-build' is been done (maybe some hours) another disk fails

You lost all!!! That is the main reason to tolerate a simultaneous two disk fail.
But if you are really paranoid (like me) you will use only Stripping, no other RAID level.
Am i mad? No, of course... i do not mind one disk fail and loose all data! I will really not loose anything just because i am really paranoid.
My paranoid scheme:

*

*ZFS with stripping (2x, 3x, 4x ... or 10x disks), just to fit the max bandwidth of the bus (sata III, usb 3.1 gen 2, etc)

*And other similar five ZFS (without power, so can not get damaged)

How to use all of such ZFS:

*

*Have only two of them at the same time (just to sync changes)... like a master with five slaves

Paranoid point of view:

*

*If one ZFS fails... like been hit by a storm ligth, burned, stolen, etc... i still have five copies more inside different places (bank, bunker, internet cloud, friends house, vacation house, etc)

To sync some of them... i must carry with me one ZFS and do the sync on the other physical place / country / etc... so i use one of thoose slaves.
Think when i talk about HDDs on one ZFS, on another ZFS can be 3.1 Gen2 64GiB USB sticks! No need to be identical size, type, etc.
Really paranoid point of view.
For thoose not so paranoid, and if they can support to loose all... there is RaidZ levels... i prefer to 'mirror' by my self.
Another advantage of do manual 'syncs' is your own fails:

*

*You have a hypotetic perfect never ever fail ZFS system, but you decide to delete a file... some days after you discovered you missed the file you wanted to delete and delete one that you did not want to (by human error)... you are out of lucky unless you have a BackUp

So... again... if you need a BackUp, why not speed up the ZFS at max by only striping?... you will still be needing to do BackUp after all.
Well, the answer can be:

*

*System partition for a24h online system

For data partitions i do not see the need for RaidZ levels versus having a external USB ZFS clone ready to be connected as soon as main ZFS in use fails... just unmount ZFS main point and mount the other good ZFS in place... then with another machine re-create the off-line ZFS that got damaged.
If you have two computers, you have what you need to 7x24h with just only a few seconds (boot time) of down-time.
For home users that want their photos stay safe... use more than two ZFS and have at least one or two of them never ever connected at the same time as the rest. Paranoid? Not at all.
It is just i learn the hard way how things can go really wrong!
Just to clarify... what happen...

*

*I was using the PC normally

*Data was getting to fail

*I took out the HDDs and place the ones that was OK

*Data on them also got damaged in less than ten seconds

*I lost all my data (not fully since i was a little paranoid and have BackUp on DVD media)

The problem was really in the the controller (integrated on the mainboard), not the disks... it was altering data on read/write operations.
Since then... my data is not on internal sata disks anymore... only on external USB 3.1 Gen 2 enclosures i can plug and un-plug (each disk in its own enclosure)... and when one fails... i test all things prior to connect to that PC anything with real data... RAM, processor, USB port, etc... with a dummy USB enclosure to test patterns... if that is OK... then i test the failed disk... if it works on another enclosure or not, on another PC or not, etc... to really know who is causing the fail... really paranoid, i know!
But learning from experience:

*

*Never ever trust a disk fail is caused by the disk it self... test it... it could be the controller, the cables, the power suppy, etc.

*Or worst, it could be the RAM

Talking about RAM, i had an not so old PC (BIOS based 64Bits processor) that if (think on three identical RAM Modules, call them A, B and C):

*

*i put A on the PC works perfect (no matter on what of the four slots)

*i put B on the PC works perfect (no matter on what of the four slots)

*i put C on the PC works perfect (but only on one of the four slots, on the other tree it causes a lot of fails, BSODs, etc)

*i put A & B it causes a lot of fails, BSODs, etc

*i put A & C on the PC works perfect (no matter on what of the four slots)

*i put B & C on the PC works perfect (no matter on what of the four slots)

*i put A & B & C on the PC it causes a lot of fails, BSODs, etc

If i test such modules on another PC, all of them works really great, no problem, no defect, etc.
Things can go really mad... and if you do not test all combinations you can not know what is failing... yes really paranoid to test all combinations of three ram modules on four slots... but what i had discoverd let me blind... the failing alone module works perfect if another one is present but not if another two... yes, i also tested with another three and fail!
Oh, yes, all same brand, kind, etc... identical... only way to difference them is a sticker i placed on them for such! And yes, buyed at the same time, they came on the same manufacture locked plastic case.
Sometimes a ZFS fail can be caused by RAM... then no matter how many levels of RaidZ you have... you can loose all.
Oh, near forget... use ECC memory, else ZFS can not be trusted! And do not use any HDD with internal cache, internat RAID, etc. unless it is designed to do writes on the order sent (or do all of them in a power cut).
I only use HDDs with enought internal energy capacity to write all its cache to the plates after an abrupt power lost!
All this points / weakness let me with one conlcusion:

*

*Best speed up things and do your own BackUPs

*Have some 100% copies Off-Line and without power

*Have something ready to recieve power and replace the failed part

That is why i have >2 PCs with >10 USB HDDs (5 ZFS copies *3 HDDs each in stripped)... i got the best of both... safe and speed! But i get the worst part... neeed to sync all of them periodically... but data safety is the most important part! also i do not want to wait a lot for such syncs (aka, striping comes in work).
And if a 3*HDDs stripe fail... i can test which one had fail of such three for some hours/days/weeks... while i have another ZFS copie On-Line and working... after be sure the other two are OK i buy a new one (maybe 30 to 45 days to arrive) and re-create such 3*HDDs ZFS and put data on it to have that fifth copy again.
Not cheap at all! But not as a main-data center price, of course... and no electricity bill (most HDDs are without power, only 3 or 6 at the same time).
Hope some one finds the idea useful (i use it daily).


text:
Q: Construction of a graph with diameter four. I am trying to find graphs or classes of graphs where exactly two vertices have eccentricity four(and are pendant vertices) and rest of the vertices have eccentricity three. Vertices with ecc four are the only pendant vertices. Following family is the one satisfying the above criteria. Can anyone help in finding other graphs too. Thanks for the help
Such graphs are called almost self centered graphs

A: First of all we can extend your own example: you have indicated one vertex producing an infinite family,
but every vertex (except the pendants) can be used: if you have one "good" graph and a vertex $v$ in it
that is not a pendant, you can make a copy $v'$ and make $v'$ adjacent to all neighbors of $v$.
Then $d(v,v')=2$, the eccentrity of $v'$ is equal to the eccentrity of $v$ and other eccentricities do not change.
The conditions for a good graph imply that it must contain an induced $P_5$ with the pendants as its endpoints.
Following construction arose by considering the situation where the central vertex of this $P_5$ does not have
any other neighbors.
The construction is far from exhaustive. I doubt you will be able to find an exhaustive description
(apart from the one implied by the problem itself), because following is true: if $G$ is any graph,
then there is a good graph containing $G$ as an induced subgraph (when you have read the answer
you will understand why).
So let $xuzvy$ be the induced $P_5$.
Let $G$ be any $U,V$-bigraph without isolated vertices and let $H$ be any graph of diameter at most 3 and without isolated vertices.
Now we create a graph by making every vertex of $U$ adjacent to $u$, every vertex of $V$ adjacent to $V$
and every vertex of $H$ adjacent to at least one vertex of $U$ and at least one vertex of $V$.
It is easy to see that the result is a good graph, by a small case analysis (let me know if you have trouble with this).
To enlarge the family even further you can add an arbitrary number of edges "inside" $U$
and ditto inside $V$.
Can you explain why these families are interesting for you? This does not look like a homework exercise, and for me they are not very interesting.


text:
Q: Some misunderstanding on quadratic equation. I have the following equation
$$x^2+4x+4=0$$
When I calculate $x = -2$. So I can write equation as follows
$$(x-2)^2=0$$
But when I open parenthesis, this $x^2-4x+4$ is not equal to this $x^2+4x+4$.
Any idea what do I miss here why two equations not equal?

A: That's because $x^2 +4x +4$ is not equal to $(x-2)^2$, but rather $(x+2)^2$.
This makes your equation $$(x+2)^2 =0$$
The solutions are $x=-2,-2$

A: To be more specific, it's supposed to be $(x-(-2))^2$. Try to substitute $x=-2$ into that expression and see what you get. That should help you understand why the signs are the way they are.


text:
Q: Roblox - Rotating a Model I am working on a game which allows some buildings to be placed and
procedurally rotated.
I found the following rotation code which I am trying to incorporate:
function TransformModel(objects, center, new, recurse)
    for _,object in pairs(objects) do
        if object:IsA("BasePart") then
            object.CFrame =     new:toWorldSpace(center:toObjectSpace(object.CFrame))
        end
        if recurse then
            TransformModel(object:GetChildren(), center, new, true)
        end
    end
end

which is invoked as follows in my building placement script:
local center = model:GetModelCFrame()
TransformModel( model:GetChildren(), center, center * CFrame.Angles(0,math.rad(45),0), true )

So the code works, somewhat... The model does sort of rotate but only after it jumps into the air and lands haphazardly before finally settling down in the rotated position, although its far from an exact 45 degree rotation after the physics effect of jumping in the air and settling back down.
I am not quite sure but I suspect there is a better way to accomplish this where the model smoothly rotates. Any help would be greatly appreciated.
Thanks,
Andy

A: GetModelCFrame is a deprecated method. It is instead recommended to utilize the PrimaryPart, GetPrimaryPartCFrame, and SetPrimaryPartCFrame. Setting the primary part designates a specific part in the model to serve as a base that you can move around via its CFrame. What's nice about this approach is that if you transform the PrimaryPart of a Model with these methods, all of the other parts in the Model will also transform to maintain their offset from the PrimaryPart.
For placing buildings and props, it is usually desired to have this part be a flat part at the bottom that represents the footprint of the building.
For example, consider the following model:

In this case the best part to make the primary part would be the one on the bottom. If your model doesn't have a part incorporated in the geometry then you can make an invisible and cancollide false part to serve as the base. In the following example, there is a tree model that doesn't have a wide base, but we want to make sure the footprint is large enough that it wouldn't overlap with other nearby objects:

In this case the yellow part should be made fully transparent at runtime.
So in terms of the code to actually orient a model in the way you want, all you have to do is call SetPrimaryPartCFrame with the new CFrame. The TransformModel function simply becomes:
local function TransformModel(model, newCFrame)
    model:SetPrimaryPartCFrame(newCFrame)
end

When you want to call this function to say rotate a model 45 degrees:
local model = game.Workspace.Model
model.PrimaryPart = model.Base
local rotatedCFrame = model:GetPrimaryPartCFrame() * CFrame.Angles(0, math.rad(45), 0)

TransformModel(model, rotatedCFrame)

A: I believe I found an answer that works for my problem, though I am not sure if this is the best way to fix it. I created an extra part to act as a base which is the exact width and height of the model, the model then sits on top of the new base part and the base is anchored. That seems to have fixed it - is there a better way?

A: Now, GetPrimaryPartCFrame and SetPrimaryPartCFrame are not recommended for future projects. Instead, it is best to use SetPivot() and GetPivot().
(I understand that this topic was quite a while back ago, so I'm saying this to people who stumble upon this)


text:
Q: CSS, Left and Right borders override part of top one Example: http://jsfiddle.net/CM33V/1/
Is it possible without additional html elements remove grey lines from left and right borders on red one?
Code is simple:
div {
    width:300px;
    height:100px;
    border:1px solid #CCC;
    border-top:15px solid #C90110;
}

This code is used in email html layout, so i am not sure it is okay to workaround with shadows.

A: Im afraid if you want a fix for HTML email, you're pretty much stuck with having to add additional elements, as this is the way borders work in CSS. For browsers however..
Demo Fiddle
....there is one way you could fix it without technically adding anything to your HTML (but only because :pseudo elements arent added to the DOM), its a bit cheeky though:
div {
    width:300px;
    height:100px;
    border-top:15px solid #C90110;
    position:relative;

}
div:after{
    position:absolute;
    border:1px solid #CCC;
    border-top:none;
    height:100%;
    width:100%;
    content:'';
    display:block;
    box-sizing:border-box;
}

A: The short answer is no, not for the purpose you want at least (on a web page easy!)
If you are doing this as an email template, and for cross-(browser, email client - insert appropriate word here) you should use two separate divs anyway (in fact TABLES(shock horror) are better for emails in most cases!)
Email is a really tricky one to get right so stick the the simplest method - two divs, one red, one white with left, right and top borders - it will work across the most email clients that way.
Answer below covers how to do it on web so +1 for that one (would give +2 as he did a fiddle but cant do that :-P)


text:
Q: Showing expanded \let command with \typeout I have already seen the related page macros - What is the difference between \let and \edef?, but I'm afraid it still doesn't expain to me the following MWE:
\documentclass{minimal}

\begin{document}

\let\tmpa=Hello
\edef\tmpb{A\tmpa}
\tmpb           % typesets "ello AH"
\typeout{\tmpa} % writes "\tmpa" in terminal
\typeout{\tmpb} % writes "A\tmpa" in terminal
\end{document}

This is how I understand it:

*

*\let\tmpa= sees first character of Hello, H - it sees it as a single token and gets assigned to it (that is, \let\tmpa=H)

*The remaining characters ("ello") from \let\tmpa=Hello "fall through" and get typeset (the "ello" in "ello AH")

*\edef\tmpb{A\tmpa} runs => since \tmpa=H, then \tmpb should expand to "AH"

*\tmpb runs => as expected, "AH" is typesed after the previous "ello"

And the confusion comes from \typeout{\tmpa} - from the typeset output, I'm pretty sure \tmpa=H; so I expect \typeout{\tmpa} to result with H, but it doesn't - and instead it writes again \tmpa! Same thing if I try to expand it via \edef and throw it in another command (\tmpb), and then I try to \typeout that command.
Why does \typeout in this case not show the "expanded" value of \tmpa? How can I get \typeout to show the expanded value of \tmpa?

Ah well, I asked this question; then I asked myself for it to be closed, given that Showing expanded \let command with \typeout generally provides an answer; in the meantime I came up with an answer I wanted to document - but now I cannot anymore, because it's closed :/ So I posted the answer in macros - How do I 'expand' a control sequence \let to a character?; but that answer simply doesn't belong there.
Then finally I realized I can edit my question post, even if it is closed (I just cannot add an answer) - so better to delete the answer from the other question, and move it here I guess (although now that it is here, it would have been better it's an answer :/ Ah nevermind).
So, not to nag the mods to reopen and reclose again, I'll post that answer here:
Basically, to \typeout the contents of that example:

*

*Use \meaning to convert \tmpa to "The letter H"

*Use a "parser" macro, to extract the third word from a set of three words

So finally we have the corrected MWE, that can print the content of \tmpa (given here we explicitly expect it to be one letter) to terminal:
\documentclass{minimal}

\begin{document}

\def\wordIIIofIII #1 #2 #3{#3}

\let\tmpa=Hello
\edef\tmpb{A\tmpa}
\tmpb           % typesets "ello AH"
\typeout{\tmpa} % writes "\tmpa" in terminal
\typeout{\tmpb} % writes "A\tmpa" in terminal

\edef\tmpc{\meaning\tmpa}
\typeout{\tmpc}         % writes "the letter H" in terminal
\edef\tmpd{\expandafter\wordIIIofIII\tmpc}
\typeout{\tmpd}         % writes "H" in terminal

\typeout{\the\catcode`H}                  % 11
% \typeout{\the\catcode`\tmpd} % "! Improper alphabetic constant."
\typeout{\the\catcode\expandafter`\tmpd}  %11

\end{document}

A: The syntax for the \let primitive is
\let<cs>=<token>

where <cs> is a control sequence or active character, <token> is a single token and = can be omitted or surrounded by optional spaces. So
\let\?=H
\let\? =H
\let\? = H
\let\?H
\let\? H

are all equivalent (I used \? so that no space is ignored in the tokenization stage).
The so defined <cs> inherits all the characteristics of the <token> (but depending on the token it may or may not be always used as a substitute). In particular, after
\let\tmpa=H

the token \tmpa will be unexpandable, just because H is unexpandable.
The command \typeout uses the \write mechanism, which does expansion, but using an output stream that is never assigned a file, so the result is written on the terminal and the log file, also adding an instruction so that \protect does its work correctly (for instance \typeout{\itshape} prints \itshape, while \write255{\itshape} would explode).
Under \write, unexpandable tokens are written by their name. And it's good it's this way: after \write\@outputstream{\bgroup}, finding out { in the output may be disastrous. Similarly one could have good reasons for writing out \tmpa instead of H.
The strategy with \meaning is correct, but it works only in this particular case and it would fail with \bgroup, whose meaning is
\bgroup=begin-group character {

You may find it useful to look at the expl3 function \tl_analysis_show:N; compiling the following file
\RequirePackage{expl3}
\let\tmpa=H

\ExplSyntaxOn
\tl_analysis_show:n { \tmpa }

will show on the terminal
The token list contains the tokens:
>  \tmpa (control sequence=the letter H).

(For releases before TeX Live 2017, you will need \usepackage{l3tl-analysis} in addition to \usepackage{expl3} for this to work and \tl_show_analysis:N, now a deprecated command.)

Why isn't your \typeout{\the\catcode`\tmpd} working? Because an alphabetic constant is `<character> (where <character> may also be <backslash><character>) and after the backquote a multiletter control sequence is found, which is illegal.
The line \typeout{\the\catcode\expandafter`\tmpd} works, because \catcode expands tokens until finding something that can start a <number> (if not found, TeX raises an error). So the \expandafter is expanded.


text:
Q: How to do screencast with animated presentations Here is a snapshot of a screencast I was watching:

How do you create such animated presentation in a screencast? I know how to capture stuff I am doing on my computer as screencast, but how do you build a dynamic presentation? What are the tools available for a Mac user?

A: Camtasia
has versions for both Windows and OS X although the OS X version doesn't offer that many features. You could take a look at the free trial and see if it works out for you. I think it's a decent software.

Snapz Pro X
is a dedicated OS X screencasting software and comes at $69. It also has some nice features but might not be the right thing for you.
SMART Software
is specialized on note-taking for classes, meetings and presentations. We used it at University. It allows you to write on your screen with digital ink by using a graphics tablet or a touchscreen.


text:
Q: Fill data.table with NA-values, using the nearest non-na-observation I have a data.table as so:
library(data.table)
dt.tst <- CJ(Type = c("A", "B"),
             Range_val = seq(0,20000, by = 1000))

dt.tst[Range_val == 2000 & Type == "A", Value := 0.987]
dt.tst[Range_val == 2000 & Type == "B", Value := 1.987]

dt.tst[Range_val == 9000 & Type == "A", Value := 1.056]
dt.tst[Range_val == 9000 & Type == "B", Value := 2.138]

dt.tst[Range_val == 16000 & Type == "A", Value := 1.563]
dt.tst[Range_val == 16000 & Type == "B", Value := 2.089]

I would like to fill the NA:s in the Value-column:

*

*With the closest non-na-value by the Range_val-column and Type.

*In case of a tie the highest Range_val and it's corresponding Value should be used (but this is not a deal-breaker, speed is more important).

I could do this pretty simple but slow with a for-loop. So I would like a more clean way of doing this (and faster). What would be a good data.table-way of doing this?
There will always be non-na-values but the intervals might differ.

A: dt.tst[is.na(Value), Value := dt.tst[!is.na(Value)][dt.tst[is.na(Value)], roll = "nearest", on = .(Type, Range_val)]$Value]

output
dt.tst

#     Type Range_val Value
#  1:    A         0 0.987
#  2:    A      1000 0.987
#  3:    A      2000 0.987
#  4:    A      3000 0.987
#  5:    A      4000 0.987
#  6:    A      5000 0.987
#  7:    A      6000 1.056
#  8:    A      7000 1.056
#  9:    A      8000 1.056
# 10:    A      9000 1.056
# 11:    A     10000 1.056
# 12:    A     11000 1.056
# 13:    A     12000 1.056
# 14:    A     13000 1.563
# 15:    A     14000 1.563
# 16:    A     15000 1.563
# 17:    A     16000 1.563
# 18:    A     17000 1.563
# 19:    A     18000 1.563
# 20:    A     19000 1.563
# 21:    A     20000 1.563
# 22:    B         0 1.987
# 23:    B      1000 1.987
# 24:    B      2000 1.987
# 25:    B      3000 1.987
# 26:    B      4000 1.987
# 27:    B      5000 1.987
# 28:    B      6000 2.138
# 29:    B      7000 2.138
# 30:    B      8000 2.138
# 31:    B      9000 2.138
# 32:    B     10000 2.138
# 33:    B     11000 2.138
# 34:    B     12000 2.138
# 35:    B     13000 2.089
# 36:    B     14000 2.089
# 37:    B     15000 2.089
# 38:    B     16000 2.089
# 39:    B     17000 2.089
# 40:    B     18000 2.089
# 41:    B     19000 2.089
# 42:    B     20000 2.089

A: If I understand your goal correctly, i,e., assigning a NA in the Value column with its nearest non-NA value, probably you can try max.col + outer like below
dt.tst[
  ,
  Value2 := replace(
    Value,
    is.na(Value),
    na.omit(Value)[max.col(-abs(outer(which(is.na(Value)), which(!is.na(Value)), `-`)), "last")]
  ), Type
][]

which gives
    Type Range_val Value Value2
 1:    A         0    NA  0.987
 2:    A      1000    NA  0.987
 3:    A      2000 0.987  0.987
 4:    A      3000    NA  0.987
 5:    A      4000    NA  0.987
 6:    A      5000    NA  0.987
 7:    A      6000    NA  1.056
 8:    A      7000    NA  1.056
 9:    A      8000    NA  1.056
10:    A      9000 1.056  1.056
11:    A     10000    NA  1.056
12:    A     11000    NA  1.056
13:    A     12000    NA  1.056
14:    A     13000    NA  1.563
15:    A     14000    NA  1.563
16:    A     15000    NA  1.563
17:    A     16000 1.563  1.563
18:    A     17000    NA  1.563
19:    A     18000    NA  1.563
20:    A     19000    NA  1.563
21:    A     20000    NA  1.563
22:    B         0    NA  1.987
23:    B      1000    NA  1.987
24:    B      2000 1.987  1.987
25:    B      3000    NA  1.987
26:    B      4000    NA  1.987
27:    B      5000    NA  1.987
28:    B      6000    NA  2.138
29:    B      7000    NA  2.138
30:    B      8000    NA  2.138
31:    B      9000 2.138  2.138
32:    B     10000    NA  2.138
33:    B     11000    NA  2.138
34:    B     12000    NA  2.138
35:    B     13000    NA  2.089
36:    B     14000    NA  2.089
37:    B     15000    NA  2.089
38:    B     16000 2.089  2.089
39:    B     17000    NA  2.089
40:    B     18000    NA  2.089
41:    B     19000    NA  2.089
42:    B     20000    NA  2.089
    Type Range_val Value Value2


text:
Q: Need to generate the Regex between Two delimiters I need to find a regex which can give me String between two delimiters(In this case @)
I have previously used this (?<=@)(.*?)(?=@)
But the problem with this is
Instead of picking two tokens I am getting three token from this line
UPDATE XYZ
SET EVENTTIME='21:01', DEADLINE='21:21',
COMPONENTNAME = '@token1@_some_update',checkthgis= '@token2@' WHERE TYPE='STATIC_UPDATE'

*

*token1

*_some_update',checkthgis=

*token 2

I am using this Ansible code for this
   - name: Find the tokens (@----@) in the fileString
      set_fact:
        tokens: "{{ fileString | regex_findall(regexp)}}"
      vars:
        regexp: '(?<=\@)(.*?)(?=\@)'

    - name: Replace the token in the configuration files
      replace:
        path: "{{file}}"
        regexp: "@{{token}}@"
        replace: "{{ lookup('ini', '{{token}} type=properties file=/root/xyz/myfile.properties default=@{{token}}@')}}"
      with_items: "{{tokens}}"
      loop_control:
        loop_var: token

Ideally this should give me only
token1 and token2

A: If you use (?<=@).*?(?=@) the pattern will match any 0+ chars as few as possible between each pair of @ in the string, and once matched, it goes on to look for matches at the place were it found the previous match and to the right of it. Since the (?=@) is a lookahead, a zero width assertion, the regex may start matching on the @ that has just been the ending delimiter.
You may use
(?<=@)([^\s@]+)(?=@)

See the regex demo
It matches:

*

*(?<=@) - a position immediately preceded with @

*([^\s@]+) - Group 1: any 1+ chars other than whitespace and @

*(?=@) - a  position immediately followed with @


text:
Q: How to pass shell arguments with VBoxManage guestcontrol? I run a command from the host machine on the guest machine (both Ubuntu) as
VBoxManage guestcontrol Ubuntu1 run --exe "script.sh" --username xx --password xx --wait-stdout

where the shell script on the guest machine is as
#!/bin/bash
echo $1

How can I pass the argument 1 while executing the shell script?
I assumed it should work as
run --exe "script.sh arg1"

but it does not.

A: SSH
We can run an application on a virtual guest with an SSH session from the host to this machine. However this requires that networking was enabled, and that openssh-server was installed an runs on the guest machine.
VBoxManage guestcontrol
As an alternative we can use built-in features of Virtual Box to execute a program on a running guest VM. This can be done with VBoxManage guestcontrol.
The example line below will just run ls on the virtual machine's root:
VBoxManage --nologo guestcontrol "<vm_name>" run --exe "/bin/ls" --username <guestuser> --password <password> --wait-stdout

Running a graphical application on the guest requires us to define the DISPLAY environment variable to the guest with the option --putenv. Next example will run and open gedit on the guest:
VBoxManage --nologo guestcontrol "<vm_name" run --exe "/usr/bin/gedit" --username <guestuser> --password <password> --putenv "DISPLAY=:0" --wait-stdout

We can also pass options to open a program. Next example will open a file vmtest in the guest gedit:
VBoxManage --nologo guestcontrol "vm_name" run --exe "/usr/bin/gedit" --username <guestuser> --password <password> --putenv "DISPLAY=:0" --wait-stdout -- gedit/arg0 vmtest

Options and arguments are separated from the command with -- as can best be seen in below example of a script from the host.

Example host script
Below script will play an example.ogg file using paplay in a guest machine when run on the host. Replace the variables with appropriate values.
#!/bin/bash

VM_NAME=myvm
VM_USER=takkat
VM_PASSWD=topsecret
VM_EXEC=paplay
VM_EXEC_PATH=/usr/bin/paplay
VM_ARGS=/home/takkat/Music/example.ogg

VBoxManage --nologo guestcontrol $VM_NAME run --exe $VM_EXEC_PATH \
--username $VM_USER --password $VM_PASSWD --wait-stdout \
-- {$VM_EXEC}/arg0 $VM_ARGS


text:
Q: What type of feed is most appropriate for a feed in a user profile that shows all of the posts that he or she has voted on? I am writing an app where users can make posts.
Each post has a vote button. In the user's profile page, I would like to have a feed that shows all posts that were voted on by the user.
In this case, should I create a Flat Feed named "voted"? Then, would I add an activity to "voted" each time a user clicks on the vote button of a post? Is this best way?
I am new to the getstream API so any feedback to enhance my understanding of the API and its possibilities would be much appreciated. Thank you.

A: It seems that "vote" action in my case would be best represented as a "reaction" in the getstream API. So, the write up on reactions in the docs seems to be a good starting point: Reactions


text:
Q: Can I change difficulty level or mode without starting over? I'm on Hard / Classic mode, and my units are dying a lot.  Classic mode = permadeath, so my units are gone forever, and this is becoming frustrating. Can I change to a different difficulty level or mode without starting over?

A: No it can't. You'll have to restart the game to change difficulty.


text:
Q: Bayes Factor for two exponential samples I'm trying to solve myself such a problem: calculation of Bayes Factor for two groups from exponential distributions.
$$x_1, x_2, \ldots, x_n\sim \exp(\lambda_1)$$
$$y_1, y_2, \ldots, y_m\sim \exp(\lambda_2)$$
I will show what I have already done and my two questions are below.
The null hypothesis is $$H_0: \mu_1=\mu_2$$ but here it translates to $$H_0:\lambda_1=\lambda_2$$
I need two entities: likelihood function for this data and priors on lambdas.
The likelihood seems to be:
$$L(\lambda_1, \lambda_2\mid x_1, \ldots, x_n, y_1\ldots, y_m)= \lambda_1^n\cdot \exp(-\lambda_1\cdot n\cdot\bar{x}) \cdot\lambda_2^m\cdot\exp(-\lambda_2\cdot m\cdot\bar{y})  $$
To calculate Bayes Factor, I need to have two marginal likelihoods: $$m_0(x_1, \ldots, x_n,y_1, y_2, \ldots, y_m)$$ for null model ($\lambda_1=\lambda_2$), and $$m_1(x_1, \ldots, x_n,y_1, y_2, \ldots, y_m)$$ for alternative model ($\lambda_1\neq\lambda_2$).
Q1. Does those marginals look like this?:
$$m_0(x_1, \ldots, x_n,y_1, y_2, \ldots, y_m)=\int \lambda^{n+m}\cdot \exp(-\lambda\cdot (n\cdot\bar{x} + m\cdot\bar{y}))\cdot \pi(\lambda) d\lambda$$
$$m_0(x_1, \ldots, x_n,y_1, y_2, \ldots, y_m)=\int \lambda_1^n\cdot \exp(-\lambda_1\cdot n\cdot\bar{x}) \cdot\lambda_2^m\cdot\exp(-\lambda_2\cdot m\cdot\bar{y})\cdot\pi(\lambda_1, \lambda_2)\ d\lambda_1 d\lambda_2$$
where $\pi(\cdot)$ means prior.
Q2. I guess, I need a prior $\pi(\lambda)$ on $\lambda$ for null model and prior $\pi(\lambda_1, \lambda_2)$ for $\lambda_1$ and $\lambda_2$ for alternative model?
Is it possible to assume that $\pi(\lambda_1, \lambda_2)=\pi(\lambda_1)\cdot \pi(\lambda_2)$ (independence of $\lambda_1$ and $\lambda_2$)?


text:
Q: How to run MapReduceIndexerTool job from Java? I want to run MapReduceIndexerTool from Java.
Right now I do it from command line using hadoop jar as you can see here, but I want to check it's status (to see if it's finalized, in progress, etc.) from Java code.
So basically I want to run it from Java in order to be able to check it's status from Java. Is there a way to run it from command line and check it's status from Java?
Also, there is a way to make Map Reduce to send an event (on a callback for example) when a job is completed? Something like a webhook?

A: As far as I know Tool interface exposes only int run(String[] args) method, so in general you would create new instance, form proper argument string and call that method.
From other hand, MapReduceIndexerTool has int run(Options options) method, that could be used to run it without forming shell-style argument. However, this method is protected, so this will need to have calling class to be created in same package as MapReduceIndexerTool.


text:
Q: Python - interactive ZSH shell I have this code which drops into a shell when executed via terminal:
command = ['zsh', '--no-rcs']
env_vars = os.environ.copy()
try:

        p = Popen(command,
                preexec_fn=os.setsid,
                stdin=fd_new,
                stdout=fd_new,
                stderr=fd_new,
                env=env_vars,
                universal_newlines=True)

        while p.poll() is None:
            r, w, e = select.select([sys.stdin, main_fd], [], [])
            if sys.stdin in r:
                d = os.read(sys.stdin.fileno(), 10240)
                os.write(main_fd, d)
            elif main_fd in r:
                o = os.read(main_fd, 10240)
                if o:
                    os.write(sys.stdout.fileno(), o)
    finally:

        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)

It works, however when I type "exit" in the new shell it does not exit, I have to press the enter key once for it to then exit the new shell.
Why is that?


text:
Q: C# PHP communication I'm writing an app that will authenticate user from a MySQL database.
I have written it in Java (android) but am now porting to Windows phone.
the PHP file uses $get and then echoes the response:
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);

mysql_select_db($database_localhost, $localhost);

$username = $_POST['username'];

$query_search = "select * from users where user = '".$username."'";
//$query_search = "select * from users where username = '".$username."' AND password     = '".$password. "'";

$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo "No Such User Found";
} else  {
    echo "User Found";
}

How can I pass the username variable to PHP and then receive the result?

A: YOUR CODE IS VULNERABLE TO SQL-INJECTION METHOD USE PDO/MYSQLi to AVOID THIS
Create loaded event handler:
using System;
public MainPage()
{
InitializeComponent();

Loaded += new RoutedEventHandler(MainPage_Loaded);
}

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
System.Uri myUri = new System.Uri("Your php page url");
HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(myUri);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback),myRequest);
}

creating "POST" data stream:
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest myRequest = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = myRequest.EndGetRequestStream(callbackResult);

// Create the post data
string postData = "username=value";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Add the post data to the web request
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();

// Start the web request
myRequest.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), myRequest);
}

receive response:
 void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
    HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
    using (StreamReader httpWebStreamReader = new     StreamReader(response.GetResponseStream()))
    {
        string result = httpWebStreamReader.ReadToEnd();
        //For debug: show results
        Debug.WriteLine(result);
    }
}

A: use a in-linky stuff like I have a script in my server and you just write: "example.com/save.php?username=textbox1.text&score=points"


text:
Q: Static methods with typescript & mongoose does: "An interface may only extend a class or another interface." I try to add a static method to my Model, but if I do it, I got this Error: An interface may only extend a class or another interface.
This is my code:
import * as mongoose from 'mongoose';
import {IPermission} from './IPermission';

export interface IRoleDocument extends mongoose.Document {
    name: string,
    inherit_from: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Role'
    },
    permissions: Array<IPermission>
};

export interface IRole extends mongoose.Model<IRoleDocument> {

};

Error comes from export interface IRole extends mongoose.Model<IRoleDocument>
Greetz

A: As far I I know it is impossible to inherit from intersection/union types in typescript. And in case of mongoose type definitions mongoose.Model<T> is declared as intersection type:
type ModelConstructor<T> = IModelConstructor<T> & events.EventEmitter;

For examples of how to use mongoose in typescript you can check this topic on SA
But you still can use intersection instead of inheritance to get your required interface, like this:
interface IRoleDefinition
{
    myExtraProperty: string;
}

type IRole = mongoose.Model<IRoleDocument> & IRoleDefinition;

More info about intersection types vs inheritance: github


text:
Q: Suppose $\mathcal{V}$ be a subspaces of $\mathbb{R}^n$, Suppose $\mathcal{V}$ be a subspaces of $\mathbb{R}^n$,
Suppose $P: \mathbb{R}^n\to\mathbb{R}^n$ be a projection, then I need to prove the following
$$ \mathcal{V}\cap\text {im } P=P^{-1}\mathcal{V}\cap\text{im }P$$
Suppose $x\in \mathcal{V}\cap\text {im } P\Rightarrow x\in\mathcal{V}\text { and } \exists y\in \text{ im } P\ni x=Py\in \mathcal{V}\Rightarrow Px=Py=x=P^{-1}x\in P^{-1}\mathcal{V}\Rightarrow x\in P^{-1}\mathcal{V}\cap im P$
now, suppose $x\in P^{-1}\mathcal{V}\cap im P$ so $Py=x$
I am not able to prove please help.

A: I would go and try to prove both inclusions separately.
So let's focus on $$ (\mathcal{V}\cap\text {im } P) \subset (P^{-1}\mathcal{V}\cap\text{im }P) $$
first.
$$ x \in (\mathcal{V}\cap\text {im } P) \Rightarrow x \in V \land x \in {im } P $$
 $$ \Rightarrow   x \in V \land \exists y \in \mathbb{R}^n :  Py=x  $$
 By the definition of a projection we get:
$$ \Rightarrow   x \in V \land Py = Px = x $$
$$ \Rightarrow  x \in (P^{-1}\mathcal{V}\cap\text{im }P) $$
Now for the second part I'll give you the following hint because P is a projection we know:
 $$ x \in \text {im } P \iff Px = x $$
I hope that will help you a bit.


text:
Q: How to bind a toggle button using knock out I have written the below code to see the working of Toggle Button. But it seems the data bind is not working.
Below is the HTML code

            <input type="checkbox" id="toggle123" data-bind="click:isToggleTrueOrFalse" />

Below is the Style

Below is the script

My requirement is when clicking on the toggle button I have to get the true or false in the console. Currently only false is coming in console.
Also I have tried using

and
<input type="checkbox" id="toggle123" data-bind="click:toggleAssociation1" />

but it also did not work.
Will click event work for this. Or shall we have to use any other event.
Can some one help me on this.

A: You're using the wrong bindings for what you're trying to achieve. The click binding is used to call functions that perform some action. Observables and Computed Observables on the other hand are meant to hold values.
What you need is the checked binding (https://knockoutjs.com/documentation/checked-binding.html). And once you use this you won't need the following bit of code -
var checkBox = document.getElementById("toggle123");
  if (checkBox.checked == true){
     return true;
  }
  else{
     return false;
  }

Here's the way to use checked binding:

function viewmodel(){
  var self = this;
  self.isToggleTrueOrFalse = ko.observable();

  //to check the value whenever it updates, we can subscribe to the observable like this:
  self.isToggleTrueOrFalse.subscribe(function(latestValue){
    console.log(latestValue);
  });
}

ko.applyBindings(viewmodel());
.switch {
 position: relative;
 display: inline-block;
 width: 60px;
 height: 34px;
}

.switch input {
 opacity: 0;
 width: 0;
 height: 0;
}

.slider {
 position: absolute;
 cursor: pointer;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
 background-color: #ccc;
 -webkit-transition: .4s;
 transition: .4s;
}

.slider:before {
 position: absolute;
 content: "";
 height: 26px;
 width: 26px;
 left: 4px;
 bottom: 4px;
 background-color: white;
 -webkit-transition: .4s;
 transition: .4s;
}

input:checked+.slider {
 background-color: #2196F3;
}

input:focus+.slider {
 box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
 -webkit-transform: translateX(26px);
 -ms-transform: translateX(26px);
 transform: translateX(26px);
}

/* Rounded sliders */

.slider.round {
 border-radius: 34px;
}

.slider.round:before {
 border-radius: 50%;
}

    <input type="checkbox" id="toggle123" data-bind="checked:isToggleTrueOrFalse" />


text:
Q: Bubble sort defect using inline assembly code I am making a bubble sort function in assembly code for my computer systems class.
My function looks like this
 int sorter(int* list, int count, int opcode) {
 __asm {
        mov ebx, opcode             ; opcode in ebx
        push 0                      ; outer count
        mov ecx, 0                  ; start ecx at 0 to start loop
        mov esi, list               ; set esi to list value/ starting address
        jmp iloop                   ; jump to inner loop
    oloop:                          //OUTER LOOP
        push ecx                    ;
        mov ecx, 0                  ; put the 2nd value in the list in the inner loop count
    iloop:                          // inner loop
        mov edx, dword ptr[esi + 4 * ecx]; move first value in edx
        mov eax, dword ptr[esi + 4 + 4 * ecx]; move next value in list to eax
        cmp ebx, 2                  ; compare opcode with 2
        je dsnd                     ; if opcode is equal to 2 then we are using descending order
        cmp eax, edx                ; compare values at eax and edx
        jg no_swap                  ; if value is greater eax(2nd value) then dont swap /ascending order
    cont:                           //continue from descend
        push edx                    ; push contents of edx to stack
        pop dword ptr[esi + 4 + 4 * ecx]; pop the contents on stack to address of value in eax
        push eax                    ; push value in eax to stack
        pop dword ptr[esi + 4 * ecx]; pop value on stack to address of value previously in eax
    no_swap:                        //no  value swap
        inc ecx                     ; increment inner count
        cmp ecx, count              ; compare inner loop count to acutal length
        jne iloop                   ; if not equal jump back to inner loop
        pop ecx                     ; get outer count
        inc ecx                     ; to check for n-1 in outer loop
        cmp ecx, count              ; compare outer loop count to length
        jne oloop                   ; if not equal jump back to outer loop
        jmp done                    ;
    dsnd:
        cmp eax, edx                ; compare values at eax and edx
        jl no_swap                  ; if value is less then dont swap
        jmp cont                    ; continue with loop

    done:
    }

Where opcode is either 1 for ascending sort or 2 for descending order,
list is a pointer to list of ints, and count is the number of ints in the list
For ascending sort, my program works fine, but with descending I have issues as shown in these test runs:
input 10 -20 5 12 30 -5 -22 55 52 0
Number of integer = 10
Ascend_or_Descend = 1
-22 -20 -5 0 5 10 12 30 52 55    # correct

input 48 -24 48 -24 10 100 -10 60 -256 10 -10 4096 -1024 60 10 -10
Number of integer = 16
Ascend_or_Descend = 1
-1024 -256 -24 -24 -10 -10 -10 10 10 10 48 48 60 60 100 4096 # correct

input 10 -20 5 12 30 -5 -22 55 52 0
Number of integer = 10
Ascend_or_Descend = 2
4283780 55 52 30 12 10 5 0 -5 -20 # incorrect

input 48 -24 48 -24 10 100 -10 60 -256 10 -10 4096 -1024 60 10 -10
Number of integer = 16
Ascend_or_Descend = 2
1500056 4096 100 60 60 48 48 10 10 10 -10 -10 -10 -24 -24 -256 # incorrect

It seems to take the lowest value and swaps it with an address. I am no expert with assembly.


text:
Q: Casting child to parent with generics Class a <T> {
   public T j;
}

class b:a <int> {

}

If this were not a generic then you could do the following:
a foo = new b();

Is there anyway to do the same with the generic case?
Is there a better method to do that?

A: You can use:
a<int> foo = new b();

A: You need the generic parameters declared in a:
class a<T>
{
    public T j;
}

You also need them in b to be able to derive from a:
class b<T> : a<T> { }

and then you can cast b<T> to a<T>:
a<int> foo = new b<int>();

Or you can derive from specific a:
class b : a<int> { }

and then cast:
a<int> foo = new b();

A: public static void Main()
{
    Base<int> foo = new Derived();
}

class Base<T>
{
    public T data;
}

class Derived:Base<int>
{
}


text:
Q: how to add textbox dynamically and save in asp.net I want to add textboxes dynamically and save these values to database in asp.net, Is there any controls for this in asp.net?
how can I do this in asp.net?

A: To add dynamic control in your .aspx file below is sample code.
Add below div in your .aspx file with id which is addControl
<div id="addControl" runat="server">
</div>

You can create dynamic TextBox control by adding below code in you .cs file.
Add Control is a id of above define div.
 TextBox txt1 = new TextBox();
 txt1.ID = "txtOne";
 txt1.Text = "";
 txt1.CssClass = "myClass";
 txt1.ClientIDMode = System.Web.UI.ClientIDMode.Static;
 addControl.Controls.Add(txt1);

With the help of NameValueCollection you can get the value of TextBox.
NameValueCollection frmCollection = Request.Form;
string inputString = frmCollection["txtOne"];

NameValueCollection represents a collection of associated String keys
  and String values that can be accessed either with the key or with the
  index.

A: You can use the Panel to create the Dynamic Text box. Panel pnlTextBox;
protected void Page_PreInit(object sender, EventArgs e)
{
    //Create a Dynamic Panel
    pnlTextBox = new Panel();
    pnlTextBox.ID = "pnlTextBox";
    pnlTextBox.BorderWidth = 1;
    pnlTextBox.Width = 300;
    this.form1.Controls.Add(pnlTextBox);

    //Create a LinkDynamic Button to Add TextBoxes
    LinkButton btnAddtxt = new LinkButton();
    btnAddtxt.ID = "btnAddTxt";
    btnAddtxt.Text = "Add TextBox";
    btnAddtxt.Click += new System.EventHandler(btnAdd_Click);
    this.form1.Controls.Add(btnAddtxt);

    //Recreate Controls
    RecreateControls("txtDynamic", "TextBox");
}

For saving to DB:
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />

C#
protected void Save(object sender, EventArgs e)
{

        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("INSERT INTO Names(Name) VALUES(@Name)"))
            {
                cmd.Connection = con;
                cmd.Parameters.AddWithValue("@Name", txtDynamic.Text);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }

}

For More details please refer this link
Edit
As you mentioned in your Comments that you are using Jquery  , so in order to load that during the postbacks try to load the Textbox in
function pageLoad() {// your dynamic Text box code using Jquery}


text:
Q: ubinize erro in image file in linux i m trying to build an image file from source code every thing works ok but at the end i get the following msg and .img file is not created
ubinize: volume size was not specified in section "ubifs", assume minimum to fit image "tmp/ubifs.img"98660352 bytes (94.1 MiB)


text:
Q: Having an error org.hibernate.HibernateException. The error is in the init method (while running the application as java app.) Mvn clean and Mvn install are successful without warnings and errors.The files hibernate.cfg.xml and App.java are:
The error from console during initialization is:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
    at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:97)
    at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:67)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:170)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755)
    at com.icdab.www.icdab_first.App.init(App.java:33)
    at com.icdab.www.icdab_first.App.main(App.java:76)

Hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver.class">oracle.jdbc.OracleDriver</property>
    <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:ORCL</property>
    <property name="hibernate.connection.username">system</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hiberante.dialect">org.hibernate.dialect.Oracle10gDialect</property>
    <property name="show_sql">true</property>
    <mapping class="com.icdab.www.icdab_first.CompundKey" />
    <mapping class="com.icdab.www.icdab_first.Customer" />
    <mapping class="com.icdab.www.icdab_first.Employee" />
    <mapping class="com.icdab.www.icdab_first.EventPlan" />
    <mapping class="com.icdab.www.icdab_first.EventPlanLine" />
    <mapping class="com.icdab.www.icdab_first.EventRequest" />
    <mapping class="com.icdab.www.icdab_first.Facility" />
    <mapping class="com.icdab.www.icdab_first.Location" />
    <mapping class="com.icdab.www.icdab_first.ResourceTbl" />

</session-factory>
</hibernate-configuration>

App.java:
package com.icdab.www.icdab_first;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
 * Hello world!
 *
 */
public class App
{
    private SessionFactory factory;
    private void init(){
        System.out.println("in init");
        Configuration config = new Configuration().configure("hibernate.cfg.xml")
                /*.addAnnotatedClass(CompundKey.class)
                .addAnnotatedClass(Customer.class)
                .addAnnotatedClass(Employee.class)
                .addAnnotatedClass(EventPlan.class)
                .addAnnotatedClass(EventPlanLine.class)
                .addAnnotatedClass(EventRequest.class)
                .addAnnotatedClass(Facility.class)
                .addAnnotatedClass(Location.class)
                .addAnnotatedClass(ResourceTbl.class) */;

        // learn why did you use the annotatedclass and configuration.
          ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
          factory=config.buildSessionFactory(registry);
    }
    @SuppressWarnings("deprecation")
    private void persistAnnotatedLists(){
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        Customer customer = new Customer();
        customer.setAddress("address123");
        customer.setCity("lansing");
        customer.setContact("1632 ne ave");
        customer.setCustname("john");
        customer.setCustno("1234");
        customer.setInternal("internal");
        customer.setPhone(122345679);
        customer.setState("OR");
        customer.setZip(97654);

        List<EventRequest> ers = new ArrayList<EventRequest>();

        ers.add(new EventRequest(123,new Date(92,5,1),new Date(91,5,1),new Date(93,5,1),"av",123,456,124));
        ers.add(new EventRequest(1234,new Date(92,5,2),new Date(91,5,2),new Date(93,5,2),"av",124,457,125));
        customer.setEventrequests(ers);
        session.save(customer);

        session.getTransaction().commit();
        System.out.println("done persist");
    }
    private void retrieveList(){
        Session session = factory.getCurrentSession();
        session.beginTransaction();

        List list = session.createQuery("from com.icdab.www.icdab_first.Customer").list();

        for (Object object : list) {
            System.out.println("** List items: "+object);
        }
        session.getTransaction().commit();
        System.out.println("Done retrieve");
    }

    public static void main (String[] args){
        App app = new App();
        app.init();
        app.persistAnnotatedLists();
        app.retrieveList();
    }
}

And the project structure is:


text:
Q: How to reset my save page after saving? I want to modify my jsp page after submission with some additional readonly fields. I have used iterators and if conditions. I am working in struts2. How to reset my save page after saving?
public String savePerson(){
        Session hSession = ActionManager.getHibernateSession();
        profileObj.setProfileId(pid);
        Date doBirth = DateFunctions.toDate(dob);
        profileObj.setDob(doBirth);

        try{

            pid = ProfileDAO.getInstance().addProfils(hSession, profileObj);
            addressObj.setProfileId(pid);
            AddressDAO.getInstance().addAddress(hSession, addressObj);
            setMessage("Succesfully saved.");

            if (pid > 0){
                hSession.clear();
                resetProfile(pid);
//i want to include my jsp page with hidden fields additionally.
                }

        } catch (HibernateException hExc) {
            setMessage("Unable to save.");
            return ERROR;
        } finally {
            ActionManager.closeHibernateSession();
        }
        return SUCCESS;
        }

A: So a few things.  First to answer your question.  Generally, after a save you do a redirect to different page to prevent the POST from being processed twice should the user click "Refresh" on the page after they save.  In your case, I would redirect to a different method, perhaps show() where you load the Profile from id and then display the JSP page.  The redirect URL would be something like "show?pid=${profileObj.profileId}.
You have a model object called profile.  You don't need separate member variables in your action to "catch" the request parameters.  You can just name your field in the JSP page profileObj.profileId and assuming you have a setProfileObj(Profile profileObj) in your action, Struts2 will create your Profile object for you and populate the right properties based on matching request Parameters.  It will even do this for dates!  (You can customize how Struts2 converts dates by creating and registering your own date converter).
So you POST these parameters and Struts creates your model with the values populated.  You use your DAO an save Profile and then redirect like I mentioned in the first paragraph.
You also have some mixing of concerns in your Action.  If you are going to use the DAO pattern, then you should really have all of your persistence code (Hibernate Sesssion, etc) encapsulated there.