text:
Q: Number of ordered, unlabeled binary rooted trees with n nodes and k leafs I want to find the number of ordered, unlabeled binary rooted trees with $n$ nodes and $k$ leafs as an exercise.
To be more precise. I am interested in objects like this ((c) 2015 M. Fulmek, PS Kombinatorik) where the line below $n=4$ reads "… and the 7 trees above vertically filpped"
Assigning the weight $w(x)W = z^n y^k$ to every rooted tree $W$ with $n$ nodes and $k$ leafs. The generating function in two indeterminates should start like this
$$ T(z, y) = \sum_W w(x)W = zy + z^2 2y + z^3\left(y^2 + 4y\right) + z^4\left(6y^2 + 8y\right) + \ldots $$
I know that the number of ordered, unlabeled binary rooted trees with $n$ nodes is
$$ \bar T (z) = T(z, 1) = \sum_{n \geq 0} \frac{1}{n + 1} {2n \choose n} z^n. $$
However, I do not know how to proceed from here. How can I express the number of leafs in terms of species?
I am aware of this question.
However, we did not cover Lagrange inversion in class. So I believe there should be a solution without applying it.

A: With this question we run into the problem of determining exactly what
the notation is supposed to mean  and which family of trees from among
the  many possibilities  is being  referenced.  Note  that  the quoted
series with leaves not marked includes a tree of size zero, which does
not match the  quoted expansion. If we do use  the quoted expansion as
the problem definition it appears the species here is
$$\mathcal{T} = \mathcal{Z}\mathcal{Y}
+ \mathcal{Z}\mathcal{T}
+ \mathcal{Z}\mathcal{T}
+ \mathcal{Z}\mathcal{T}^2.$$
We chose this  interpretation because the OP says  that there are four
trees  on three  nodes  with one  leaf,  which upon  making a  diagram
reveals  itself to  be  four paths  ending  in a  node  marked with  a
leaf. For this  to happen we must permit internal  nodes that have one
rather than two  children, so these trees are not  full.  This is what
the species  equation does: we have the  base case of a  leaf node, an
internal node with  a left child, an internal node  with a right child
or an internal node having two children.
This  yields  the  following  equation for  the  bivariate  generating
function:
$$T(z,y) = yz + 2zT(z,y) + zT(z,y)^2.$$
Now clearly  Lagrange or similar is  the preferred way  to treat this,
but according  to OP it  may not be  used.  Solving this  equation and
choosing the branch that yields Catalan numbers we obtain
$$T(z, y) = \frac{1-2z-\sqrt{1-4z(1-z+yz)}}{2z}.$$
Extracting coefficients we have with  $n\ge 1$ (no empty trees in this
species):
$$[z^n] T(z, y) = [z^n] \frac{1-2z-\sqrt{1-4z(1-z+yz)}}{2z}
\\ = [z^{n+1}] \frac{1-2z-\sqrt{1-4z(1-z+yz)}}{2}
\\ = - [z^{n+1}] \frac{1}{2} \sqrt{1-4z(1-z+yz)}.$$
Observe that
$$\sqrt{1-4w} = 1 + \sum_{q\ge 1} {1/2\choose q} 4^q  (-1)^q w^q$$
and
$$2^{2q} (-1)^q {1/2\choose q}
= \frac{2^{2q}}{q!} (-1)^q \prod_{p=0}^{q-1} (1/2-p)
= \frac{2^{q}}{q!} \prod_{p=0}^{q-1} (2p-1)
\\ = - \frac{2^{q}}{q!} \prod_{p=1}^{q-1} (2p-1)
= - \frac{2^{q}}{q!} \frac{(2q-2)!}{2^{q-1}\times (q-1)!}
= - \frac{2}{q} {2q-2\choose q-1}.$$
Returning to the coefficient extraction we have
$$[z^{n+1}] \sum_{q\ge 1} \frac{1}{q} {2q-2\choose q-1}
z^q (1-z+yz)^q
\\ = \sum_{q=1}^{n+1} \frac{1}{q} {2q-2\choose q-1}
[z^{n+1}] z^q (1-z+yz)^q
\\ = \sum_{q=1}^{n+1} \frac{1}{q} {2q-2\choose q-1}
[z^{n+1-q}](1-z(1-y))^q
\\ = \sum_{q=1}^{n+1} \frac{1}{q} {2q-2\choose q-1}
{q\choose n+1-q} (-1)^{n+1-q} (1-y)^{n+1-q}.$$
We thus have for the statistic  of $n$ nodes and $k$ leaves the closed
form
$$\bbox[5px,border:2px solid #00A000]{
(-1)^{n+1-k} \sum_{q=1}^{n+1} \frac{(-1)^q}{q} {2q-2\choose q-1}
{q\choose n+1-q} {n+1-q\choose k}.}$$
We continue by observing that
$$\frac{1}{q} {2q-2\choose q-1} {q\choose n+1-q} {n+1-q\choose k}
\\ = \frac{(2q-2)!}{(q-1)!\times (2q-n-1)!
\times k! \times (n+1-q-k)!}
\\ = {n-k\choose q-1}
\frac{(2q-2)!}{(n-k)! \times (2q-n-1)!
\times k!}
\\ = {n-k\choose q-1} {n\choose k} \frac{1}{2q-1}
{2q-1\choose n}.$$
We get for the sum
$$(-1)^{n+1-k} {n\choose k} \sum_{q=1}^{n+1} \frac{(-1)^q}{2q-1}
{n-k\choose q-1} {2q-1\choose n}
\\ = (-1)^{n+1-k} {n\choose k}
\sum_{q=0}^{n} \frac{(-1)^{q+1}}{2q+1}
{n-k\choose q} {2q+1\choose n}$$
or (recall that $n\ge 1$)
$$\bbox[5px,border:2px solid #00A000]{
\frac{1}{n} (-1)^{n-k} {n\choose k}
\sum_{q=0}^{n} (-1)^q
{n-k\choose q} {2q\choose n-1}.}$$
Working on the inner term we find
$$\sum_{q=0}^{n} (-1)^q
{n-k\choose q} [w^{n-1}] (1+w)^{2q}
\\ = [w^{n-1}] \sum_{q=0}^{n} (-1)^q
{n-k\choose q} (1+w)^{2q}
\\ = [w^{n-1}] (1-(1+w)^2)^{n-k}
= (-1)^{n-k} [w^{n-1}] w^{n-k} (2+w)^{n-k}
\\ = (-1)^{n-k} [w^{k-1}] (2+w)^{n-k}
= (-1)^{n-k} {n-k\choose k-1} 2^{n+1-2k}.$$
We thus obtain for the sum
$$\bbox[5px,border:2px solid #00A000]{
\frac{2^{n+1-2k}}{n} {n\choose k} {n-k\choose k-1}.}$$
This may be re-written one last time if desired:
$$2^{n+1-2k} \frac{(n-1)!}{k!\times (k-1)! \times (n+1-2k)!}
\\ = \frac{2^{n+1-2k}}{k} {2k-2\choose k-1} {n-1\choose 2k-2}$$
and we have in terms of Catalan numbers
$$\bbox[5px,border:2px solid #00A000]{
{n-1\choose 2k-2} C_{k-1} 2^{n+1-2k}.}$$
Surprising to see  that we got this far  without complex variables. We
did consult OEIS  A091894, which proved to
be a valuable resource.
Post Scriptum. Does it sum to Catalan numbers? Start with
$$\frac{2^{n+1}}{n} \sum_{k\ge 1} {n\choose k} {n-k\choose k-1} 2^{-2k}
= \frac{2^{n+1}}{n} \sum_{k\ge 1} {n\choose k} 2^{-2k}
[w^{k-1}] (1+w)^{n-k}
\\ = \frac{2^{n+1}}{n} \sum_{k\ge 1} {n\choose k}
[w^0] \frac{(1+w)^n}{2^{2k} (1+w)^k w^{k-1}}
\\ = [w^0] w(1+w)^n \frac{2^{n+1}}{n} \sum_{k\ge 1} {n\choose k}
\frac{1}{2^{2k} (1+w)^k w^{k}}.$$
For $k=0$ we  get $[w^0] w(1+w)^n 2^{n+1}/n = 0$ and  we may lower the
index to include zero, obtaining
$$[w^0] w(1+w)^n  \frac{2^{n+1}}{n}
\left(1+\frac{1}{4w(1+w)}\right)^n
\\ = [w^0] w(1+w)^n  \frac{2^{n+1}}{n}
\frac{(1+2w)^{2n}}{2^{2n} w^n (1+w)^n}
\\ = [w^0] \frac{1}{w^{n-1}} \frac{1}{n}
\frac{(1+2w)^{2n}}{2^{n-1}}
= [w^{n-1}]\frac{1}{n}
\frac{(1+2w)^{2n}}{2^{n-1}}
= \frac{1}{n} {2n\choose n-1}
\\ = \frac{1}{n+1} {2n\choose n},$$
and indeed it does.
Consulting with combstruct on these we have the following program.

with(combstruct);

GFENUM :=
proc(n)
    option remember;
    local trees, leaves;

    trees := { T=Union(Prod(Z, Y),
                       Prod(Z, T), Prod(Z, T),
                       Prod(Z, T, T)),
               Z=Atom, Y=Epsilon };

    leaves :=
    proc(struct)
        if struct = Y then return 1 fi;
        if struct = Z then return 0 fi;

        return add(leaves(op(q, struct)),
                   q=1..nops(struct));
    end;

    add(y^leaves(t), t in allstructs([T, trees], size=n));
end;

TZY := (1-2*z-sqrt(1-4*z*(1-z+y*z)))/2/z;

GFX := n -> coeftayl(TZY, z=0, n);

GFBINOM :=
n -> add(2^(n+1-2*k)/n*binomial(n,k)*binomial(n-k,k-1)*y^k,
         k=1..floor((n+1)/2));

This will produce e.g. for $n=7$ the generating function
$$5\,{y}^{4}+120\,{y}^{3}+240\,{y}^{2}+64\,y$$
which gives the  same result in all three cases,  from the closed form
of $T(z, y)$, by the binomial coefficient formula and by enumeration.
Remark. I consulted the linked-to document and the diagram included there would seem to confirm that we have the correct species.


text:
Q: Not able to check popup blocker is enabled or not in chrome I am writing the below code in JavaScript and I am not able to check popup blocker is enabled or not in chrome
method 1:
var params = 'height=1,width=1,left=-100,top=-100,location=no,toolbar=no,menubar=no,scrollbars=no,resizable=no,directories=no,status=no';
var testWindow = window.open(null, "popupTest", params);
if( !testWindow
    || testWindow.closed
    || (typeof testWindow.closed=='undefined')
    || testWindow.outerHeight == 0
    || testWindow.outerWidth == 0
    ) {
    // pop-ups ARE blocked
  //  document.location.href = 'popupsBlocked.htm';
    alert("blocked");
}
else {
    // pop-ups are NOT blocked
  testWindow.close();
    alert("not blocked");
}

method 2:
var test = window.open(null, "", "width=0,height=0");
    try {
        test.close();
        alert("Pop-ups not blocked");
    } catch (e) {
        alert("Pop-up blocker is enabled in the browsers");
    }

both methods are not working pls help me....

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to build AccountManager around Android killing the app process I have an app where users can log in and browse the app through several activities. To do that, I have an AccountManager set up in my main activity, the one that is always at the bottom of the activity stack - let's call it MainActivity. There are other activities that depend on the user being logged in, and that use the AccountManager instance that's in MainActivity.
Assuming a user is in an activity stack with such an activity ActivityB on top, and MainActivity on bottom. When the user leaves the app and does other stuff, Android might decide to terminate the app for RAM/CPU usage reasons. When the user then reopens the app, ActivityB will restart and show up, but MainActivity will remain terminated (see documentation under Saving Activity State). This is annoying, because the AccountManager instance will not be remade either, until the user decides to return to MainActivity - causing the functionality of ActivityB to be broken.
Unfortunately, I can't use any Context instance for AccountManager.get(Context), because I need to use the function AccountManager.addOnAccountsUpdatedListener which creates a need for the specified Context instance to remain instantiated, as also described in the documentation.
Is there a nice way to go about this? Can I get an instance of AccountManager without having to rely on MainActivity being instantiated, possibly using a separate static class / singleton?


text:
Q: python multiprocessing pool, wait for processes and restart custom processes I used python multiprocessing and do wait of all processes with this code:
...
            results = []
            for i in range(num_extract):
                url = queue.get(timeout=5)
                try:
                    print "START PROCESS!"
                    result = pool.apply_async(process, [host,url],callback=callback)
                    results.append(result)
                except Exception,e:

                    continue

            for r in results:
                r.get(timeout=7)
...

i try to use pool.join but get error:
Traceback (most recent call last):
  File "C:\workspace\sdl\lxchg\walker4.py", line 163, in <module>
    pool.join()
  File "C:\Python25\Lib\site-packages\multiprocessing\pool.py", line 338, in joi
n
    assert self._state in (CLOSE, TERMINATE)
AssertionError

Why join dont work? And what is the good way to wait all processes.
My second question is how can i restart certain process in pool? i need this in the reason of memory leak. Now In fact i do rebuild of all pool after all processes done their tasks (create new object pool to do process restarting).
What i need: for example i have 4 process in pool. Then process get his task, after task is done i need to kill process and start new (to refresh memory leak).

A: You are getting the error because you need to call pool.close() before calling pool.join()
I don't know of a good way to shut down a process started with apply_async but see if properly shutting down the pool doesn't make your memory leak go away.
The reason I think this is that the Pool class has a bunch of attributes that are threads running in daemon mode. All of these threads get cleaned up by the join method. The code you have now won't clean them up so if you create a new Pool, you'll still have all those threads running from the last one.


text:
Q: UISearchController add's offset while editing UISearchController add's a offset when editing begins. In Landscape mode it works perfectly fine, but does not in portrait mode.
Are there any settings in storyboard that can help to overcome this issue.
The following works but, shows a animation which goes at +320 and then brings back to -320.
func updateSearchResultsForSearchController(searchController: UISearchController) {
        self.mySearchContorller.searchBar.frame=CGRectMake(-320, 0, self.myTable.frame.size.width, 44.0)

    }

I have used storyboard with a segue (Show Detail).Attached is a screen shot of the storyboard.

A: Downloaded your project and played with it and it seems the problem is here:
Change
self.tblSearchController.definesPresentationContext = true to definesPresentationContext = true
Also, you're subclassing UITableViewController, don't create your own table but drag one into your storyboard and use it. Here's how your DetailViewController should look like:
class DetailTableViewController: UITableViewController {
var tblSearchController:UISearchController!

override func viewDidLoad() {
    super.viewDidLoad()

    self.tblSearchController = UISearchController(searchResultsController: nil)
    self.tableView.tableHeaderView=self.tblSearchController.searchBar
    definesPresentationContext = true

}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let aCell:UITableViewCell! =  tableView.dequeueReusableCellWithIdentifier("Cell")
    return aCell
}

}


text:
Q: Why does Shake recommend disabling idle garbage collection? In the Shake documentation it recommends compiling using the flag -with-rtsopts=-I0 to disable idle garbage collection. Why does Shake recommend that?

A: By default (without the flag) GHC performs a garbage collection (GC) if all Haskell threads have been idle for 0.3 seconds. Since a build system is regularly running external processes, it is quite common for all Haskell threads to be idle for > 0.3s, which causes a lot of unnecessary garbage collections. Since the machine is likely to be fully loaded from the processes Shake is running, the GC will take time away that could otherwise be doing useful work. The problem is exacerbated if the GC runs multi-threaded.


text:
Q: How can I make this sql INSERT SELECT query work on an empty table? I have the following query, that works on both MySQL and MariaDB:
INSERT into some_table (column1, column2, column3, column4, column5)
SELECT  'val1', 'val2', 'val3', 'val4', 'val5'
FROM `some_table`
WHERE NOT EXISTS (
  SELECT `column1`, `column2` from `some_table`
  WHERE `column1` = 'val1' and `column2` = 'val2'
) limit 1`

It checks if a row exists based on unique values for val1 and val2: If the row exists, the query does nothing. If the row doesn't exist, the query inserts a new row with the values of val1, val2, val3, val4 and val5.
The query works, unless the table is empty, in which case, no value is being inserted.
How can I modify this query to also work with an empty table?
(Note: I cannot create a unique index on this table)

A: Don't select from the table itself, select from the special table DUAL.
INSERT into some_table (column1, column2, column3, column4, column5)
SELECT  'val1', 'val2', 'val3', 'val4', 'val5'
FROM DUAL
WHERE NOT EXISTS (
  SELECT `column1`, `column2` from `some_table`
  WHERE `column1` = 'val1' and `column2` = 'val2'
)

DUAL is a special dummy table name that can be used when you don't need to extract data from a real table.
Another option would be to create a unique index on (column1, column2) and then use INSERT IGNORE. If you try to create a duplicate, it will be skipped silently.
ALTER TABLE some_table ADD UNIQUE INDEX (column1, column2);
INSERT IGNORE into some_table (column1, column2, column3, column4, column5)
VALUES ('val1', 'val2', 'val3', 'val4', 'val5')


text:
Q: Use of Explicit Interface in C# I can hide a method in an implementing class as following using Explicit Interface:
interface IInterface
{
    void f1();

}
public class C1 : IInterface
{
    void IInterface.f1()
    {
        Console.WriteLine(" Method Called ....");
    }

}

Then could access the method:
C1 C = new C1();
IInterface i = C;
i.f1();

The method f1 will be hidden from the implementing class C1. What is the purpose of this kind of feature? Could anybody provide me an real life sceanrio where we require the same?

A: Here is a good example from MSDN, it helped my understanding why they could be helpful:
This example displays the dimensions of a box in both metric and English units. The Box class inherits two interfaces IEnglishDimensions and IMetricDimensions, which represent the different measurement systems. Both interfaces have identical member names, Length and Width.
// explicit2.cs
// Declare the English units interface:
interface IEnglishDimensions
{
   float Length();
   float Width();
}
// Declare the metric units interface:
interface IMetricDimensions
{
   float Length();
   float Width();
}
// Declare the "Box" class that implements the two interfaces:
// IEnglishDimensions and IMetricDimensions:
class Box : IEnglishDimensions, IMetricDimensions
{
   float lengthInches;
   float widthInches;
   public Box(float length, float width)
   {
      lengthInches = length;
      widthInches = width;
   }
// Explicitly implement the members of IEnglishDimensions:
   float IEnglishDimensions.Length()
   {
      return lengthInches;
   }
   float IEnglishDimensions.Width()
   {
      return widthInches;
   }
// Explicitly implement the members of IMetricDimensions:
   float IMetricDimensions.Length()
   {
      return lengthInches * 2.54f;
   }
   float IMetricDimensions.Width()
   {
      return widthInches * 2.54f;
   }
   public static void Main()
   {
      // Declare a class instance "myBox":
      Box myBox = new Box(30.0f, 20.0f);
      // Declare an instance of the English units interface:
      IEnglishDimensions eDimensions = (IEnglishDimensions) myBox;
      // Declare an instance of the metric units interface:
      IMetricDimensions mDimensions = (IMetricDimensions) myBox;
      // Print dimensions in English units:
      System.Console.WriteLine("Length(in): {0}", eDimensions.Length());
      System.Console.WriteLine("Width (in): {0}", eDimensions.Width());
      // Print dimensions in metric units:
      System.Console.WriteLine("Length(cm): {0}", mDimensions.Length());
      System.Console.WriteLine("Width (cm): {0}", mDimensions.Width());
   }
}

A: There are scenarios when you don't want to expose something on the public API in the direct form. Maybe it will never work; maybe the public API can expose a more appropriate signature of the same functionality. For example:
public int Add(Foo foo) {...} // takes a known type and returns the new index
void ICollection.Add(object obj) {...} // takes object and returns void

A more common example is when it would be impossible not to - for example, IEnumerable and IEnumerable<T> each have a GetEnumerator() method - same inputs, but a different return value. C# does not allow overloading by return value, so you need at least two methods:
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }

public IEnumerator<T> GetEnumerator() { ...}

although they could also both be explicit. Or indeed, in IEnumerator<T>:
public T Current { get { ... } }
object IEnumerator.Current { get { return Current; } }

Additionally, sometimes you just want to rename things. For example, for some reason a Frobber has a method which naturally is Frob(). But it also implements an IDoSomething interface which has a DoIt() method; you can now make the APIs reflect the most appropriate terminology to express intent:
class Frobber : IDoSomething {
  public void Frob() {..}
  void IDoSomething.DoIt() { Frob(); }
}

A: You could check out the difference between implicit and explicit interface here:
C# Interfaces. Implicit implementation versus Explicit implementation

A: One of the real scenarios is the method name collision. Imagine:
interface IWarehouseItem
{
    string Name {get;} // the NAME of the PRODUCT
    int Count {get;}
    int PricePerUnit {get;}
}

interface IWarehouseSupplierInformation
{
    string Name {get;} // the NAME of the SUPPLIER
    int ID {get;}
    int IDAddress {get;}
}

class PurchaseableItem : Entity, IWarehouseItem, IWarehouseSupplierInformation
{
    ....
    // how to implement those different names?
     ....
    string IWarehouseItem.Name { get { this.Product.Name; } }
    ...
    string IWarehouseSupplierInformation.Name { get { this.Supplier.Name; } }
}

One may argue that this example is just a bad design of the interfaces and data structure, but not always you are able to make them proper, or have the power to change them at all.
Other times, you may be forced to implement some interface on a class, but you really really don't want those methods to be visible for the class' user. All explicit implementations are considered private, hence, unless you explicitely cast the object back to that offending interface, noone will ever see or be able to use those methods.


text:
Q: I need help in ruby
*

*I'm making a software but I don't want to publish it's source code right now because I don't want people to steal my hard work. I'm not rude or anything like that. Below is an example of what the program I'm making looks like.

print "Username : "
name = gets.chomp

print "Password : "
pass = gets.chomp

if name =="user" and pass=="pa$$word"
print "Hello"

else print "Error, incorrect details"

Now this is a simplest login form in ruby but what bad happens here is whenever the user inserts wrong information the program will simply shutdown and what I want to happen is that I want to keep the program asking the user for right information until right information is inserted.

*

*Are you a windows user? Do know how to program in batch files?
examples
echo Hello world
         cls
pause
So here is the code for ruby
a. print "Command : "
b. command = gets.chomp

c. if command == "Hello"

d. print "Hi, how are you?"

e. elsif command == "help"

f. print "Say hi to me, chat with me"

now what I want here too is just like in the first question
Details : After the user types in "Hi" the program just shuts down but what I want here it to make the program ask go to line a again

A: Use a while loop which continually asks for entry and checks the user's submission until a valid result is entered.
username = nil

while username.nil?
  puts "What is your username?"
  entered_username = gets.chomp

  if entered_username == "Bob"
    username = entered_username
  end
end

puts "Thanks!"

When run on the terminal this produces:
What is your username?
sdf
What is your username?
dsfsd
What is your username?
sdfsd
What is your username?
sdfds
What is your username?
sdf
What is your username?
Bob
Thanks!

A: 1.
until (print "Username : "; gets.chomp == "user") and
      (print "Password : "; gets.chomp == "pa$$word")
  puts "Error, incorrect details"
end
puts "Hello"

2.
loop do
  print "Command : "
  case gets.chomp
  when "Hello" then print "Hi, how are you?"; break
  when "help" then print "Say hi to me, chat with me"; break
  end
end

A: Here is the easy method :) If anyone is stuck with the problem I encountered all you do is this. The "while" loop
number = 1          # Value we will give for a string named "number"
while number < 10   # The program will create a loop until the value
                    # of the string named "number" will be greater than 10

    puts "hello"

                    # So what we need to do now is to end the loop otherwise
                    # it will continue on forever
                    # So how do we do it?
                    # We will make the ruby run a script that will increase
                    # the string named "number"'s value every time we run the loop

    number = number + 1
end                 # Now what happens is every time we run the code all the program
                    # will do is print "hello" and add number 1 to the string "number".
                    # It will continue to print out "hello" until the string is
                    # greater than 10


text:
Q: Spline Interpolation Performance in Scala vs Java I translated this spline interpolation algorithm from apache.commons.math from Java into Scala in the most straightforward way I could think of (see below).  The function I ended up with runs 2 to 3 times slower than the original Java code.  My guess is that the problem stems from the extra loops coming from the calls to Array.fill, but I can't think of a straightforward way to get rid of them.  Any suggestions on how to make this code perform better?  (It would also be nice to write it in a more concise and/or functional way -- suggestions on that front would be appreciated as well.)
type Real = Double

def mySplineInterpolate(x: Array[Real], y: Array[Real]) = {

  if (x.length != y.length)
    throw new DimensionMismatchException(x.length, y.length)

  if (x.length < 3)
    throw new NumberIsTooSmallException(x.length, 3, true)

  // Number of intervals.  The number of data points is n + 1.
  val n = x.length - 1

  // Differences between knot points
  val h = Array.tabulate(n)(i => x(i+1) - x(i))

  var mu: Array[Real] = Array.fill(n)(0)
  var z: Array[Real] = Array.fill(n+1)(0)
  var i = 1
  while (i < n) {
    val g = 2.0 * (x(i+1) - x(i-1)) - h(i-1) * mu(i-1)
    mu(i) = h(i) / g
    z(i) = (3.0 * (y(i+1) * h(i-1) - y(i) * (x(i+1) - x(i-1))+ y(i-1) * h(i)) /
            (h(i-1) * h(i)) - h(i-1) * z(i-1)) / g
    i += 1
  }

  // cubic spline coefficients --  b is linear, c quadratic, d is cubic (original y's are constants)
  var b: Array[Real] = Array.fill(n)(0)
  var c: Array[Real] = Array.fill(n+1)(0)
  var d: Array[Real] = Array.fill(n)(0)

  var j = n-1
  while (j >= 0) {
    c(j) = z(j) - mu(j) * c(j + 1)
    b(j) = (y(j+1) - y(j)) / h(j) - h(j) * (c(j+1) + 2.0 * c(j)) / 3.0
    d(j) = (c(j+1) - c(j)) / (3.0 * h(j))
    j -= 1
  }

  Array.tabulate(n)(i => Polynomial(Array(y(i), b(i), c(i), d(i))))
}

A: You can get rid of all the Array.fill since a new array is always initialized with 0 or null, depending on whether it is a value or a reference (booleans are initialized with false, and characters with \0).
You might be able to simplify the loops by zipping arrays, but you'll only make it slower. The only way functional programming (on the JVM anyway) is going to help you make this faster is if you make it non-strict, such as with a Stream or a view, and then you go ahead and not use all of it.


text:
Q: Scala - Define a function with the following signature that searches for element n of a list the initial code is:
def nth(list: List[Int], x: Int) = ???

and I try this:
def nth(list: List[Int], n: Int): Option[Int] =
  list match {
    case h :: t if n > 0 => nth(t, n - 1)
    case _ => list
  }

but it doesn't work
thank you for helping me I try the previous code

A: First of all since the return type is Option[Int] you need to return None when list has less then n (or n-1 depended on n being zero or one based) elements, then you need to return Some when you reach the nth element. Check out the scaladoc for Option type.
For example simple recursive solution can look like this (zero based n):
def nth(list: List[Int], n: Int): Option[Int] =
  list match {
    case h :: t if n > 0  => nth(t, n - 1)
    case h :: t if n == 0 => Some(h)
    case _                => None
  }


text:
Q: Assembly to C Translation: Order of Local variables? Okay so I am trying to translate this assembly into C.
So my confusion is at line 7, where it seems that 2 * x is stored in the variable i. But this does not seem to follow the order of the C code. Am I interpreting this wrong? Is it actually storing 2 * x into val?
Assembly:

C:

A: I do not see your C code but the assembler code is clear enough. It adds the argument to itself and stores it in a local variable.
EDIT: Now I see the C code. It seems that at address -4( %ebp ) there is variable val, that is the code correspomds to
int val = 2 * x;

By the way it is easy to check what is the order of variables in the stack. Write a simple program
#include <stdio.h>

int main(void)
{
    int a[1] = { 0 };
    int b = 0;

    a[1] = 15;

    printf( "%d\n", b );
    printf( "%d\n", a[0] );

    return 0;
}

If 15 will be outputed then the compiler places variables on the stack in the reverse order. I tested this code with GCC at www.ideone.com and got the expected result that is
15
0


text:
Q: GWT Anchor action by hand I have an Anchor widget in my gwt-application.
If you click on it a link will bring you to a website.
I want to call the link by hand in a program-method.
Like: anchor.click()  ;)

A: Window.Location.assign(anchor.getHref());

should work.


text:
Q: Button to submit and validate form, if valid then run a function I have a form that currently when I click a button it validates the form. But if the form validates I would like it to then toggle my accordion.
So to validate my form I have:

Click me

Then to open my Accordion the code is:
ng-click="ctrl.toggle()"
Just not sure how I can add the toggle onto my Click me link if the form is valid.
Any help is welcomed.
Thanks

A: You can have a function called by the button when clicking, which will validate and expand the accordion accordingly.
To achieve this, the button would be:
Click me

Then, you will have this function in your controller:
$scope.validateAndSend = function() {
    if (formIsValid() == true) {
        ctrl.toggle();
    }
}

Replace formIsValid() with your validation function and it should work.


text:
Q: Circumference of an ImplicitRegion I define an ellipse by using an ImplicitRegion:
R = ImplicitRegion[4 z^2 + r^2 == 10, {z, r}]

I would like to get the perimeter of this ellipse. I was hoping to simply use Perimeter:
Perimeter[R]

However this returns "Undefined." Are there any suggestions on how to compute the perimeter of an ImplicitRegion?

A: *

*ArcLength work for one-dimension region which imbeded in two-dimension region.

R = ImplicitRegion[4 z^2 + r^2 == 10, {z, r}]
RegionMeasure[R]
ArcLength[R]

2 Sqrt[10] EllipticE[-3]

*

*Perimeter work for a two dimension region.

R2 = ImplicitRegion[4 z^2 + r^2 <= 10, {z, r}]
Perimeter[R2]

2 Sqrt[10] EllipticE[-3]


text:
Q: An element not belong to any proper prime ideal in given commutative ring with 1. It may be a dumb question but. Assume $R$ be a commutative ring with unity 1. Let $x\in R$ given.
If $x$ is invertible I know that it cannot be in any proper ideal. If $x$ is not invertible can I say that there should be at least one prime ideal contains that. Of course I am talking about nontrivial cases, such as R being a field etc.
I tried to construct an ideal contains it but even the set $\{x\in R| \text{x is non invertible}\}$ is not an ideal iff $R$ is not local ring.

A: With our OP Jale'de jaled we take $R$ to be a unital commutative ring with unit $1$.
Then if
$x \in R \tag 1$
is invertible, and
$J \subset R \tag 2$
is an ideal of $R$ with
$x \in J, \tag 3$
we have
$1 = x^{-1}x \in J \tag 4$
so for any
$y \in R \tag 5$
it follows that
$y = y \cdot 1 \in J \tag 6$
which implies
$R \subset J; \tag 7$
combining (2) and (7) yields
$J = R, \tag 8$
and we have shown that no invertible element is contained in a proper ideal, that is one which is not the whole of $R$.
If $x$ is not invertible, we may consider the principal ideal
$xR = \{xy, \; y \in R \}; \tag 9$
note that
$1 \notin xR, \tag{10}$
lest
$\exists z \in R, \; xz = 1, \tag{11}$
i.e.,
$z = x^{-1}, \tag{12}$
in contradiction to the assumption that $x$ has no inverse.  In light of (10), $xR$ is a proper ideal, hence there exists a maximal ideal
$M \subsetneq R \tag{13}$
with
$x= x \cdot 1 \in xR \subset M \subsetneq R, \tag{14}$
and since every maximal ideal is prime, we see that $x$ is contained in some prime ideal.


text:
Q: Python - question regarding the concurrent use of `multiprocess` I want to use Python's multiprocessing to do concurrent processing without using locks (locks to me are the opposite of multiprocessing) because I want to build up multiple reports from different resources at the exact same time during a web request (normally takes about 3 seconds but with multiprocessing I can do it in .5 seconds).
My problem is that, if I expose such a feature to the web and get 10 users pulling the same report at the same time, I suddenly have 60 interpreters open at the same time (which would crash the system). Is this just the common sense result of using multiprocessing, or is there a trick to get around this potential nightmare?
Thanks

A: You are barking up the wrong tree if you are trying to use multiprocess to add concurrency to a network app. You are barking up a completely wrong tree if you're creating processes for each request. multiprocess is not what you want (at least as a concurrency model).
There's a good chance you want an asynchronous networking framework like Twisted.

A: If you're really worried about having too many instances you could think about protecting the call with a Semaphore object.  If I understand what you're doing then you can use the threaded  semaphore object:
from threading import Semaphore
sem = Semaphore(10)
with sem:
    make_multiprocessing_call()

I'm assuming that make_multiprocessing_call() will cleanup after itself.
This way only 10 "extra" instances of python will ever be opened, if another request comes along it will just have to wait until the previous have completed.  Unfortunately this won't be in "Queue" order ... or any order in particular.
Hope that helps

A: locks are only ever nessecary if you have multiple agents writing to a source. If they are just accessing, locks are not needed (and as you said defeat the purpose of multiprocessing).
Are you sure that would crash the system? On a web server using CGI, each request spawns a new process, so it's not unusual to see thousands of simultaneous processes (granted in python one should use wsgi and avoid this), which do not crash the system.
I suggest you test your theory -- it shouldn't be difficult to manufacture 10 simultaneous accesses -- and see if your server really does crash.


text:
Q: Flot - combine Bar and stacked chart in a sigle chart Is it possible to combine Bar chart and stacked chart in flot?
I did line with bar.
Bar chart will have 4 legends. 5th bar will be stacked.

A: Depending on which stack plugin you use this is different but should be possible in all of them, since the option for stacking is usually specified per dataseries.


text:
Q: Unable to understand LIKE behavior Considering the following two tables:
series
id  name            screen_name     deleted_at
9   Series Name 9   Screen Name 9   NULL
11  Series Oneb     seriesoneb      NULL
15  Mad Dogs        maddogs         NULL

tickets
id  series_id   subject     deleted_at
8   15          Subject 8   NULL
13  11          Subject 13  NULL
28  9           Subject 28  NULL
34  11          Subject 34  NULL
37  9           Subject 37  NULL
41  9           Subject 41  NULL
48  9           Subject 48  NULL

How is it possible that the following query:
SELECT *
FROM `tickets`
WHERE (
    SELECT count( * )
    FROM `series`
    WHERE `series`.`deleted_at` IS NULL
    AND `tickets`.`series_id` = `series`.`id`
    AND screen_name LIKE '%series name%'
    OR name LIKE '%series name%'
    AND `series`.`deleted_at` IS NULL
)

Gives me 7 rows, shouldn't it be 6?

A: Try to add parenthesis for OR condition as below
SELECT *
FROM `tickets`
WHERE (
    SELECT count( * )
    FROM `series`
    WHERE `series`.`deleted_at` IS NULL
    AND `tickets`.`series_id` = `series`.`id`
    AND (screen_name LIKE '%series name%' OR name LIKE '%series name%')
    AND `series`.`deleted_at` IS NULL
)

A: Your problem is probably precedence in the where clause.  It is parsed as:
 WHERE (`series`.`deleted_at` IS NULL AND
        `tickets`.`series_id` = `series`.`id` AND
        screen_name LIKE '%series name%'
       ) OR
       (name LIKE '%series name%' AND
        `series`.`deleted_at` IS NULL
       )

I suspect that you want:
 WHERE `series`.`deleted_at` IS NULL AND
        `tickets`.`series_id` = `series`.`id` AND
        (screen_name LIKE '%series name%' OR
         name LIKE '%series name%'
        )


text:
Q: How to scroll horizontally repeatedly? When i press and hold zl, first the window is moved left by one char and than the cursor starts moving to right. I want to be able to hold zl and the behavior to be the window moving to left, like it is when holding ctrl+e.

A: You can write 2zl for 2 characters and 4zl for 4 characters and thus you can also use 100zl for 100, so you just have to write any number before zl.

A: If you want to hold some key to achieve "repeat" zl or zh, you have to create a mapping for that, with keys like ctrl. That is because, the z doesn't work in this way.
E.g. (just an example, you can pick the keys you like to combine with ctrl)
nnoremap <c-l> zl
nnoremap <c-h> zh


text:
Q: Friend Function Accessibility Issue I am trying to make a friend function for another class, but my current layout is causing access issues and header-include issues.
In my project I have two files: Class A and Class B. For the sake of brevity, everything is inlined in the header file, as it still demonstrates my issue.
#ifndef CLASSA
#define CLASSA

#include "ClassB.h"

class A {
   private:
      int x;
   public:
      A(int x) {
          this->x = x;
      }
      friend void testFriend(A in);
};

#endif

#pragma once
#ifndef CLASSB
#define CLASSB
#include <cstdio>
#include "ClassA.h"

class B {
public:
   void testFriend(A in) {
       printf("%d", in.x);
   }
};
#endif

However, with this setup, Visual Studio thinks that class A's private member elements are inaccessible despite it being a member function. Furthermore, they are including each other which will cause errors eventually. This setup works fine when these two classes are in the same header file, though. How can I achieve a setup like this, where one class has a member function that needs to be a friend with another class, and while having the two classes be in separate header files.

A: friend void testFriend(A in); is unrelated to B::testFriend.
You can make the whole class friend instead:
class A {
   private:
      int x;
   public:
      A(int x) : x(x) {}
      friend class B;
};

class B {
public:
   void testFriend(A a) { std::cout << a.x; }
};

A: The declaration
friend void testFriend(A in);

makes a non-member function named testFriend a friend of the class. It does not make B::testFriend a friend of class A.
You can solve the problem by making B a friend of A. This will require only a forward declaration.
#ifndef CLASSA
#define CLASSA

// No need for this.
// #include "ClassB.h"
class B;

class A {
   private:
      int x;
   public:
      A(int x) {
          this->x = x;
      }

      // This does not work.
      // friend void testFriend(A in);

      // Make B a friend of the class.
      friend B;
};

#endif

Now,
class B {
public:
   void testFriend(A in) {
       printf("%d", in.x);
   }
};

should work just fine.

A: void testFriend(A in); refers to a function in the global scope. What you need is void B::testFriend(A in);. However, this will require B to already be declared and implemented.
But to implement testFriend in B, A must be declared so that you can use an A as a parameter. Plus, A must be implemented for you to use A.in. If you have separate headers and implementations for your classes this shouldn't be a problem.
However, if you decide to do this in one file, you'll need to declare and implement in this order:
class A;

class B {
  public:
    void testFriend(A in);
};

class A {
 private:
    int x;
 public:
    A(int x) {
        this->x = x;
    }
    friend void B::testFriend(A in);
};

void B::testFriend(A in) {
    printf("%d", in.x);
}


text:
Q: free() call works on simulator, makes iPad angry. iPad smash My app is running out of memory. To resolve this, I free up two very large arrays used in a function that writes a framebuffer to an image. The method looks like this:
-(UIImage *) glToUIImage {
    NSInteger myDataLength = 768 * 1024 * 4;
    // allocate array and read pixels into it.
    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, 768, 1024, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    // gl renders "upside down" so swap top to bottom into new array.
    // there's gotta be a better way, but this works.
    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
    for(int y = 0; y <1024; y++)
    {
            for(int x = 0; x <768 * 4; x++)
            {
                    buffer2[(1023 - y) * 768 * 4 + x] = buffer[y * 4 * 768 + x];
            }
    }

     // make data provider with data.
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);

    // prep the ingredients
    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * 768;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

    // make the cgimage
    CGImageRef imageRef = CGImageCreate(768, 1024, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

    // then make the uiimage from that
    UIImage *myImage = [UIImage imageWithCGImage:imageRef];

    //free(buffer);
    //free(buffer2);

    return myImage;
}

Note the two called to free(buffer) and free(buffer2) at the end there? Those work fine on the iPad simulator, removing the memory problem and allowing me to generate with impudence. However, they kill the iPad instantly. Like, the first time it executes it. If I remove the free() calls it runs fine, just runs out of memory after a minute or two. So why is the free() call crashing the device?
Note - it's not the call to free() that explicitly crashes the device, it crashes later. But that seems to be the root cause/..
EDIT - Someone's asked about where it exactly crashes. This flow goes on to return the image to another object, which writes it to a file. When calling the 'UIImageJPEGRepresentation' method, it generates an EXT_BAD_ACCESS message. I assume this is because the UIImage I'm passing it to write to the file is corrupt, null or something else. But this only happens when I free those two buffers.
I'd understand if the memory was somehow related to the UIIMage, but it really shouldn't be, especially as it works on the simulator. I wondered if it is down to how iPad handles 'free' calls...

A: From reading the docs, I believe CGDataProviderCreateWithData will only reference the memory pointed to by buffer2, not copy it. You should keep it allocated until the image is released.
Try this:

static void _glToUIImageRelease (void *info, const void *data, size_t size) {
    free(data);
}

-(UIImage *) glToUIImage {
    NSInteger myDataLength = 768 * 1024 * 4;
    // allocate array and read pixels into it.
    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, 768, 1024, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    // gl renders "upside down" so swap top to bottom into new array.
    // there's gotta be a better way, but this works.
    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
    for(int y = 0; y

A: First things first, you really should check if malloc failed and returned NULL. However, if that doesn't solve your problem, use a debugger and step through your programm to see exactly where it fails (or at least to get a stack trace). From my experience, odd failures like crashing somewhere in unsuspected areas almost always are buffer overflows corrupting arbitrary data some time before.

A: Buffer(s) are undersized?  Look at the loops.
for(int y = 0; y <1024; y++)
{
     for(int x = 0; x <768 * 4; x++)
     {
          buffer2[(1023 - y) * 768 * 4 + x] = buffer[y * 4 * 768 + x];
     }
}

let y == 0 and x == (768*4)-1, the index of buffer2 exceeds allocated size.
Probably outside range before that?


text:
Q: Visual studio code color picker I love visual studio code but there's one thing that is missing in my opinion.
A color picker.
Does anyone know if there's a color picker for visual studio code just like in visual studio?

A: In release 1.15.1 they have added a color picker.
https://code.visualstudio.com/updates/v1_15#_color-picker

A: I know it's a bit old topic but it may help someone. To make color pick working you need as Mia mentioned Install Node.js and add it to $PATH. It will ask you during installation about adding both Node.js and NPM (Node Package Manager) to PATH.
If picker still doesn't work there are 3 settings (quote from official description):

*

*If the dialog box is not shown correctly, set colorHelper.disableGpu to 1.

*If that wasn't solved yet, set colorHelper.disableShadow to true.

*If that wasn't solved yet, set colorHelper.disableTransparent to true.

For me setting colorHelper.disableTransparent to true fixed the problem.
colorHelper.disableGpu and colorHelper.disableShadow left default.
To get to that settings press Ctrl+,

A: You do NOT need a third-party extension for this
This feature has been built into VS Code since 2017, but needs to be enabled first. In my case I kept seeing this claimed everywhere, but despite being on the latest version no amount of hovering or right-clicking triggered the colour picker. Even some digging through Google and the original GitHub issues didn't bring up the fact that this feature is disabled by default and needs to be enabled.

To enable VS Code's built-in color picker
Go to Settings (Ctrl+,) and search for the Color Decorators option:

Color Decorators
Controls whether the editor should render the inline color decorators and color picker.

Check the box to enable it (if it isn't already checked). Exit Settings, and go back to your file with colours in it. Close and re-open VS Code if necessary.
You should now see a coloured square next to each colour - click on these boxes to bring up the color picker. Note that the
Bonus tip
Although you no longer need to install a third-party extension for this, there are still useful extensions for working with colours that VS Code doesn't (yet) come built-in with. If you work with colours a lot (eg. front-end web dev) I highly recommend installing the Color Highlight extension by Sergei N - I've used this for years and can't count the amount of my time it's saved by allowing me to quickly scan through a file for a colour that I need to adjust.

A: The extension Color Picker does actually work but you need to Install Node.Js from this website, also note that when you first try to use the plugin it does an initial configuration which takes a few minutes.

A: For anyone else encountering this issue but not finding a solution in the above answers, this answer from Hashim Aziz led me to the solution for my issue. I was  seeing the Color Picker built into VS Code just stop functioning for new colour codes I typed in. I was working on a large CSS of 3,000+ lines and I did not realise that alongside an Enable/Disable toggle for the Color Picker function, it also has a limit to the number of color pickers it will render at once, as seen in the below screenshot. Mine was set to a default of 500, so when I set it to 5000, it fixed my issue. Hopefully this helps someone else in the future!

A: VSCode does not have a color picker, sorry.
It does have color preview for CSS (see this: https://code.visualstudio.com/Docs/languages/css ) and a very robust extension system.
A feature like that may be added in the future, or somebody may create an extension, but for now you will have to pick your colors elsewhere.

A: I have battled with this for a while, fortunately I was able to find a way around it...
Try this.

*

*Open Visual Studio Code and install the "VS Color Picker" extension. The "Install"
button will be changed to "Disable"...if that is displayed then you are sure the
extension is installed.

*Press "CTRL + SHIFT + P", a drop-down box will be displayed at the top of VS Code, the
items there are arranged in alphabetical order, so you might want to scroll down to
find the installed extension "VS Color Picker", or you can use the search box provided
to get the installed extension.

*Hover over the "VS Color Picker" extension, towards the right a settings symbol will
show, click on it and a "Keyboard Shortcut" window will be opened, inside this new
window you will find the "VS Color Picker" extension, double-click on it, and you will
see a pop-up box requesting you to input your desired shortcut for calling the
extension...put what you feel comfortable with, for me, I used "Alt + Shift + P", then
press enter and close the window....then try it and let me know if it works…thanks.

A: Install the windows global color picker "PowerToys".
https://github.com/microsoft/PowerToys/releases/download/v0.51.1/PowerToysSetup-0.51.1-x64.exe

Use Windows+Shift+C to activate anytime.
Open Color Picker > Open Settings. Make sure its enabled.Done!

A: Sometimes you need to pick a color inside js or txt files, in that case you can just type 'color picker' within Google search.
https://www.google.com/search?q=color+picker

A: *

*Open Visual Studio Code and click on Extensions tab (ctrl + shift + x)

*Search for vscode-color-picker and click on install.

*vscode-color-picker


text:
Q: npm install fails on a vagrant VM with debian 7.8 and postgres 9.3 I need to reproduce a production node environment with specific (old) versions, on my local mac machine using vagrant, and when i run npm install it always fails with errors as follow:

*

*optional dep failed continuing fsevents@0.3.6

*optional dep failed, continuing readable-stream@1.1.13

*optional dep failed, continuing imagemin-xx

*EEXIST, open '/root/.npm/0ae333bd-t-npm-inherits-2-0-1-package-tgz.lock'
File exists: /root/.npm/0ae333bd-t-npm-inherits-2-0-1-package-tgz.lock
Move it away, and try again.

I have tried many things without success:

*

*npm install --no-bin-links

*sudo npm install

*npm cache clean

*rm -r node_modules

*rm -r /root/.npm/

I could not figure out what I am doing wrong and what's the cause...
Any idea about what I am doing wrong or some suggestions would be welcome. Thanks.
Here is my env details:

*

*OS: Debian 7.8

*node: v0.10.36

*npm: 1.4.28

*PostgreSql : 9.3.6

*PostGis: 2.1

*git:1.7.10.4

*ruby: 1.9.3

I have 2 directories in my vagrant project:

*

*www: containes my app

*config: containes packages list and db dump

My vagrant  file:
Vagrant.configure(2) do |config|
    config.vm.box = "puppetlabs/debian-7.8-64-puppet"
    config.vm.hostname = "ppld-preprod"
    config.vm.provision "shell", path: "provision.sh"

    config.vm.network "forwarded_port", guest: 80, host: 8999

    config.vm.synced_folder "./", "/vagrant", disabled: true
    config.vm.synced_folder "www", "/vagrant/www"
    config.vm.synced_folder "config", "/vagrant/config"
end

My provision file:
apt-get -y update

dpkg --set-selections < /config/packages_list
apt-get -y -u dselect-upgrade

wget http://nodejs.org/dist/v0.10.36/node-v0.10.36.tar.gz
tar xfz node-v0.10.36.tar.gz
cd node-v0.10.36
./configure
make

make install

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ wheezy-pgdg main" > /etc/apt/sources.list.d/pgdg.list'

sudo apt-get -y install wget ca-certificates
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

apt-get -y update

sudo apt-get -y install postgresql-9.3-postgis-2.1
sudo apt-get -y install postgresql-server-dev-9.3

sudo apt-get -y install git

sudo chown -R $(whoami) "/vagrant/"
sudo chmod -R 777 /vagrant/

cd /vagrant/www/ppld/
sudo npm install

A: Your issue is really strange, can you update your npm to version 2+ ?
npm update -g npm


text:
Q: array dicing cfsimplexml object I have an array like this
[17] => CFSimpleXML Object
        (
            [Key] => habteen.mp3
            [Size] => 5931725
         )

[18] => CFSimpleXML Object
        (
            [Key] => lawnesareh.mp3
            [LastModified] => 2011-05-07T22:24:15.000Z

        )

and I want to get the value of Key and size. Howd I go about that?

A: A CFSimpleXML object is part of the Amazon Webservices PHP api that provides a wrapper around SimpleXML. It has a special constructor that catches unknown function calls and translates them into xpath requests.
The default response is to return another CFSimpleXML object, which oftentimes you simply want the value, so you have to cast it to its proper type.
$key = (string)$array[17]->Key

Another more complex example might look something like this. If you have an known EC2 instance at AWS, and you needed its availability zone heres how that would look:
$description = $ec2->describe_instances(array('InstanceId' => $instance_id));

$availability_zone = (string)$description->body->reservationSet->item->instancesSet->item->placement->availabilityZone;

Where $ec2 is an instance of an AmazonEC2 object and $instance_id is the id of your instance (something like i-6301ea00).  The $description that comes back will come back as a CFSimpleXML object, therefore the function calls above will actually translate into a traversal of the XML document to get the availabilityZone.

A: The following will iterate through the array items and check if the objects have a Key and Size property:
foreach($arr as $item)
{
   if(isset($item->Key))
   {
       $item->Key;
   }
   if(isset($item->Size))
   {
       $item->Size;
   }
}


text:
Q: Single file non-validating xml parser/reader I'm looking for a simple non-validating XML parser in either C or C++.
Several years back I found one that was just a single file solution but I can't find
it anymore.
I'm after some links and suggested ones that are very small and lightweight
ideally suited for an embedded platform.

A: Expat
You can work with or without validation and in "streaming mode". It is very lightweight.

A: What about something like pugixml. From their site...

pugixml is a light-weight C++ XML
  processing library. It features:

*

*DOM-like interface with rich traversal/modification capabilities

*Extremely fast non-validating XML parser which constructs the DOM
  tree from an XML file/buffer

*XPath 1.0 implementation for complex data-driven tree queries

*Full Unicode support with Unicode interface variants and
  automatic encoding conversions

  The library is extremely portable and
  easy to integrate and use.
pugixml is developed and maintained
  since 2006 and has many users. All
  code is distributed under the MIT
  license, making it completely free to
  use in both open-source and
  proprietary applications.

Also, this answer has more info.
There is also tinyxml and RapidXml.

A: There is definitely a pure C, tiny xml parser available. It was cited in an earlier answer on SO, but I can't find it right now. If I remember right, it's just a few hundred lines of code.
Update: Here's the question/answer that references it:
Is there a good tiny XML parser for an embedded C project?
And the actual code:
http://mercurial.intuxication.org/hg/cstuff/file/tip/tinyxml

A: RapidXML is a single-header (multiple headers if you want extra functionality) ultra-lightweight, ultra-fast implementation. It can operate in "destructive" mode, that means by setting pointers right into the XML and possibly overwriting some, avoiding all extra memory allocations and data copies.
tinyxml is not precisely single-header, but it is still fairly lightweight compared to other parsers. I've used it for half a decade without ever encountering an issue. The author has recently started with "tinyxml-2", which is supposedly better and even more lightweight, but I've not had occasion to actually try that one yet.

A: http://mercurial.intuxication.org/hg/cstuff/file/tip/tinyxml
can this parser work with nested XML like
<CServiceType>
   <serno>61</serno>
   <caption1 />
   <caption2>Satelite</caption2>
   <caption3 />
</CServiceType>


text:
Q: How to edit the layout of woocommerce blocks? Since woocommerce is using gutenberg blocks I can't find out how to edit the layout on the front end e.g. remove the image and wrap the title in a h2?
The templating functionality only seems to work with their custom fields and not the blocks rendered using js - https://docs.woocommerce.com/document/woocommerce-theme-developer-handbook/
I know I can fudge some things with css but it want solve all layout issues.
Thanks.
Woocommerce blocks
Front end of website

A: Try using the render_block filter you can find inside the homonym function:
add_filter( 'render_block', 'so59123547_render_block_filter', 10, 2 );

function so59123547_render_block_filter( $block_content, $block ) {
    if( $block['blockName'] === 'woocommerce/NAME-OF-THE-BLOCK' ) {
        // do what you want
    }
    return $block_content;
}


text:
Q: Need help proving sequences involving inferiors $$L = \inf\limits_{n\ge1}   b_n  $$ where $$b_n = \sup\limits _{k\ge n} a_k $$
and $$ \{a_k\}_ {k =1}^{\infty}$$
I need to show that if $\epsilon$ is any positive number, then there is an integer N such that $\lvert b_n - L \rvert < \epsilon  $ for all $n \ge N$
Please help!

A: Let $\varepsilon>0$. By definition of $L$, there is an $N\in\mathbb N$ s.t. $$L\leq b_N<L+\varepsilon.$$
Therefore, since $(b_n)$ is decreasing, for all $n>N$,
$$L\leq b_n\leq b_N<L+\varepsilon\implies |b_n-L|<\varepsilon.$$

A: First you should suppose that $b_1=\sup\limits_{k\ge 1}{a_k}<\infty$, i.e $b_1$ is finite. Then because for each next $b_n$ you take supremum over a smaller set of $a_k$ means that $b_n$ is a monotonically decreasing sequence of numbers. By assumption you know that it is bounded from below by the finite number $L$ which is also its infimum, i.e $L=\inf\limits_{n\ge 1}{b_n}$. In this way we conclude that the sequence $\{b_n\}_{n=1}^\infty$ has a limit point. Now we prove that this limit is $L$.
By assumption we have that $L=\inf\limits_{n\ge 1}{b_n}$. This means that for each $\epsilon>0$ there exists some element $b_{n_0}$ such that $L\leq b_{n_0}<L+\epsilon$. But also we showed that $b_n$ is a monotonically decreasing sequence, so $b_{n_0} \ge b_n,\,\,\forall n>n_0:$ which means $L\leq b_n\leq b_{n_0}<L+\epsilon,\,\,\forall n>n_0$. The last is equivalent to $|L-b_n|<\epsilon,\,\,\forall n>n_0=:N$


text:
Q: c# windows form Filtering using RadioButton Can any one tell me how to filter the Datagridview based on selected radio button, i have attached a screenshot of the form I created, need to filter based on deposit and withdrawal. I have taken TransactionType as enum.

A: Loop through the rows in your DGV and check if the first cell value = value (Deposit/Withdrawal/Both depending on which RadioButton is checked), then set
DataGridView1.Rows[rowIndex].Visible = false;

A: You can change your DataSource according the selected radio button.
BindingSource bs = new BindingSource();
grid.DataSource = bs;

By changing your radiobutton selection
bs.DataSource = q;
bs.ResetBindings(false);

for q use:

*

*var q = Transactions

*var q = Transactions.Where(t=>t.TransactionType==Deposit)

*var q = Transactions.Where(t=>t.TransactionType==Withdrawal)

A: A code that does what you want would look like this: (probably not the right variable names)

*

*Check value which radio button is checked

*according to which one is checked, read column"transactionType" of each row,

*render visible or not the rows you want.

Foreach(DataGridViewRow row in DataGridView.Rows)
{
  if(radioButtonDeposit.isChecked())
  {
    if(row["TransactionType"].Value == Enum.Deposit)
    {
       row.Visible = true;
    }
    else
    {
       row.Visible = false;
    }
  }
  else if(radioButtonWithdrawal.isChecked())
  {
    if(row["TransactionType"].Value == Enum.Withdrawal)
    {
       row.Visible = true;
    }
    else
    {
      row.Visible = false;
    }
  }
  else
    row.Visible = true;
}


text:
Q: Numerical issue with SCIP: same problem, different optimal values I'm having the following numerical issue while using SCIP solver as a callable library via PySCIPOpt:

two equivalent and almost identical models for the same problem yield different optimal
  values and optimal solutions, with optimal values having a relative difference of order 1e-6

An independent piece of software verified that the solutions yielded by both models are feasible for the original problem and that their true values agree with the optimal values reported by SCIP for each model. Until the appearance of this instance a bunch of instances of the same problem had been solved, with both models always agreeing on their optimal solutions and values.
Is it possible to modify the numerical precision of SCIP for comparing the values of primal solutions among them and against dual bounds? Which parameters should be modified to overcome this numerical difficulty?
What I tried
I've tried the following things and the problem persisted:

*

*Turning presolving off with model.setPresolve(SCIP_PARAMSETTING.OFF).

*Setting model.setParam('numerics/feastol', epsilon) with different values of epsilon.

Since feasible sets and objective functions agree (see description below), I've checked that the actual coefficients of the objective functions agree by calling model.getObjective() and comparing coefficients for equality for each variable appearing in the objective function.
The only thing that seemed to help was to add some noise (multiplying by numbers of the form 1+eps with small eps) to the coefficients in the objective function of the model yielding the worst solution. This makes SCIP to yield the same (and the better) solution for both models if eps is within certain range.
Just in case, this is what I get with scip -v in the terminal:

SCIP version 6.0.2 [precision: 8 byte] [memory: block] [mode:
  optimized] [LP solver: SoPlex 4.0.2] [GitHash: e639a0059d]

Description of the models
Model (I) has approximately 30K binary variables, say X[i] for i in some index set I. It's feasible and not a hard MIP.
Model (II) is has the same variables of model (I) plus ~100 continuous variables, say Y[j] for j in some index set J. Also model (II) has some constraints like this X[i_1] + X[i_2] + ... + X[i_n] <= Y[j].
Both objective functions agree and depend only on X[i] variables, the sense is minimization. Note that variables Y[j] are essentially free in model (II), since they are continuous and  they do not appear in the objective function. Obviously, there is no point in including the Y[j] variables, but the optimal values shouldn't be different.
Model (II) is the one yielding the better (i.e. smaller) value.

A: sorry for the late answer.
So, in general, it can definitely happen that any MIP solver reports different optimal solutions for formulations that are slightly perturbed (even if they are mathematically the same), due to the use of floating-point arithmetic.
Your problem does seem a bit weird though. You say the Y-variables are free, i.e. they do not have any variable bounds attached to them? If this is the case, I would be very surprised if they don't get presolved away.
If you are still interested in this problem, could you provide your instance files to me and I will look at them?


text:
Q: Simplify $y(t)=e^{-t}u(t) * \sum_{k=-\infty}^{\infty}\delta(t-3k)$ in the form of $y(t)=Ae^{-t}$ for $0\le t<3$ I am learning convolution, and this is one of my exercise problems. Let
$$y(t)=e^{-t}u(t) * \sum_{k=-\infty}^{\infty} \delta(t-3k)$$
Show that $y(t)=Ae^{-t}$ for $0\le t<3$, and determine the value of $A$.
Here, $u(t)$ is 1 if $t>0$ and 0 if $t<0$. (Undefined at $t=0$); $\delta(t)=0$ if $t\ne0$ and its integral over all $t$ on the real line is 1.
My (incorrect) solution:
If $0\le t<3$, then $\sum_{k=-\infty}^{\infty} \delta(t-3k)$ agrees at all points with $\delta(t)$, and $e^{-t}u(t)$ with $e^{-t}$, so
$$y(t)=e^{-t} * \delta(t)$$
Thus, $y(t)=e^{-t}$ and $A=1$.
Correct answer:
$$A = \frac{1}{1-e^{-3}}$$
Question:
I ask for a nice solution that leads to this answer, since my textbook only gives the answer. Also, I want to know which one of my assertions/premises are incorrect, since my final answer is wrong.

A: Pretty sure you just assumed the sum meant it was already written as a convolution. This is the convolution of a sum with $e^{-t}u(t)$:
$y(t)=\int_{-\infty}^{\infty} (e^{-\tau}u(\tau)\sum_{k=-\infty}^{\infty} \delta(t - \tau -3k))d\tau$
$y(t)=\int_{-\infty}^{\infty} (e^{-(t-\tau)}u(t-\tau)\sum_{k=-\infty}^{\infty} \delta(\tau -3k)) d\tau$ by commutativity
$y(t)=e^{-t} \int_{-\infty}^{\infty} (e^{\tau}u(t-\tau)\sum_{k=-\infty}^{\infty}\delta(\tau -3k)) d\tau$
$y(t)=e^{-t} \int_{-\infty}^{t} e^{\tau} \sum_{k=-\infty}^{\infty}\delta(\tau -3k)d\tau$
$y(t)=e^{-t}  \int_{-\infty}^{t} \sum_{k=-\infty}^{\infty} e^{\tau} \delta(\tau -3k)d\tau$
$y(t)=e^{-t}  \int_{\infty}^{t} e^0 \delta(\tau) + e^{-3} \delta(\tau + 3) + e^{-6} \delta(\tau + 6 ) + ...d\tau$ for $0 < t < 3$
$y(t)=e^{-t} (e^0 + e^{-3} + e^{-6} + ...)$
This is an infinite geometric sum:
$A = \sum_{i=0}^{\infty} (e^{-3})^{i} = \frac{1}{1-e^{-3}}$

A: One way to restate @cmitch answer is to consider algebraic properties of convolution namely commutativity and the following
$$f(t)*\delta(t-a)=f(t-a)$$
And using these properties we have
$$e^{-t}u(t)*\delta(t-3k)=e^{-(t-3k)}u(t-3k)$$
Now for $0\leq t\lt 3$, $u(t)=1$ iff $-\infty\lt k\leq 0$ and $u(t-3k)=0$ otherwise.
So
$$y(t)=\sum_{k=-\infty}^0e^{-t}e^{3k}\cdot 1=e^{-t}\sum_{j=0}^{+\infty}e^{-3i}$$
And we have the expected result. There is nothing new in this proof because the convolution identity is just proved by manipulating the integrals.


text:
Q: std::thread and ros::ok() do not work in ROS I have a function that is executing by std::thread. I want it works until the user closes the terminal that running roscore by pressing Ctrl+C. Because of that I use this inside the thread:
void publish_camera_on_topic(std::vector<Camera> cameras, const std::vector<ros::Publisher> publishers, const int camera_index)
{

  int frameSize;
  BYTE *imagePtr;

  // frame id
  int frame_id = 0;

  cv_bridge::CvImage img_bridge;
  sensor_msgs::Image img_msg;

  while (ros::ok()) {
    // Grab and display a single image from each camera

    imagePtr = cameras[camera_index].getRawImage();

    frameSize = cameras[camera_index].getFrameSize();

    cameras[camera_index].createRGBImage(imagePtr,frameSize);

    unsigned char* pImage = cameras[camera_index].getImage();
    if (NULL != pImage) {

      Mat image(cameras[camera_index].getMatSize(), CV_8UC3, pImage, Mat::AUTO_STEP);

      // release asap
      cameras[camera_index].releaseImage();

      //cvtColor(image, image, CV_BGR2RGB,3);

      // publish on ROS topic
      std_msgs::Header header; // empty header
      header.seq = frame_id; // user defined counter
      header.stamp = ros::Time::now(); // time
      img_bridge = cv_bridge::CvImage(header, sensor_msgs::image_encodings::RGB8, image);
      img_bridge.toImageMsg(img_msg); // from cv_bridge to sensor_msgs::Image
      publishers[camera_index].publish(img_msg); // ros::Publisher pub_img = node.advertise<sensor_msgs::Image>("topic", queuesize);

    }

    // increase frame Id
    frame_id = frame_id + 1;
  }

  std::cout << "ROS closing for thread of camera " << camera_index << " recieved." << std::endl;

}

Also, I create thread like this:
 // image publisher
  // for each camera create an publisher
  std::vector<ros::Publisher> publishers;
  for (size_t i = 0; i < cameras.size(); i++) {
    char topic_name[200];
    sprintf(topic_name, "/lumenera_camera_package/%d", i + 1);
    publishers.push_back(nh.advertise<sensor_msgs::Image>(topic_name, 10));
  }

  // work with each camera on a seprate thread
  std::vector<std::thread> thread_vector;
  for(size_t i=0; i < cameras.size(); i++) {
    thread_vector.push_back(std::thread(publish_camera_on_topic, cameras, publishers, i));
  }

  ros::spin();

  std::for_each(thread_vector.begin(), thread_vector.end(), [](std::thread &t){t.join(); });

  for(size_t i=0; i < cameras.size(); i++) {
    cameras[i].stopStreaming();
  }

  ROS_INFO("Node: [lumenera_camera_node] has been Ended.");

However, when I press Ctrl+C in the terminal and stop the roscore, the threads keep running, and the value of ros::ok() does not change.

A: The problem is solved. The issue is ros::ok() does not check for ROS master. Instead of this line:
while (ros::ok()) { //do sth}
This line should be used:
while (ros::ok() && ros::master::check()) { // do sth}


text:
Q: Animate View Controller from Callout I have a set of annotations that each have a callout. I want the callout to animate in a new view controller page but keep the current on in the background. My first thought was to just create a normal push and have a clear background but I did not think that all the way through. Here is my current code which pushes to a new page.
    - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    InfoViewController  *objDetail = [[InfoViewController alloc] initWithNibName:@"InfoViewController" bundle:nil];

    objDetail.pawpost = (PAWPost *)view.annotation;
    [self.navigationController pushViewController:objDetail animated:YES];

}

Any suggestions how to animate in one view controller over the current one?


text:
Q: different result by transforms and transformFunc in rxDatastep I would like to add a new column in an xdf file. I tested both  transforms and transformFunc in rxDatastep.
This line of code works fine for me:
rxDataStep(nyc_jan_xdf,transforms = list(newCol5=ifelse(payment_type==1,10,20)))

but If I use transformFunc:
CashVsCard<-function(x)
{
  if(x$payment_type==1){
    x$newCol13=10
  } else {
    x$newCol13=20
  }
  return(x)
}
rxDataStep(nyc_jan_xdf,transformFunc = CashVsCard)

it doesnt work and returns this error:
Error in doTryCatch(return(expr), name, parentenv, handler) :
  The variable 'newCol13' has a different number of rows than other columns in the data: 1 vs. 10
In addition: Warning message:
In if (x$payment_type == 1) { :
  the condition has length > 1 and only the first element will be used

Why transformFunc doesnt work?
an example of my Data:
structure(list(VendorID = c(2L, 2L, 2L, 1L, 1L, 1L), tpep_pickup_datetime = c("2016-01-01 00:00:00",
"2016-01-01 00:00:00", "2016-01-01 00:00:03", "2016-01-01 00:00:04",
"2016-01-01 00:00:05", "2016-01-01 00:00:06"), tpep_dropoff_datetime = c("2016-01-01 00:00:00",
"2016-01-01 00:00:00", "2016-01-01 00:15:49", "2016-01-01 00:14:32",
"2016-01-01 00:14:27", "2016-01-01 00:04:44"), passenger_count = c(5L,
1L, 6L, 1L, 2L, 1L), trip_distance = c(4.90000009536743, 10.539999961853,
2.4300000667572, 3.70000004768372, 2.20000004768372, 1.70000004768372
), pickup_longitude = c(-73.9807815551758, -73.9845504760742,
-73.9693298339844, -74.0043029785156, -73.9919967651367, -73.9821014404297
), pickup_latitude = c(40.7299118041992, 40.6795654296875, 40.7635383605957,
40.7422409057617, 40.718578338623, 40.7746963500977), RatecodeID = c(1L,
1L, 1L, 1L, 1L, 1L), store_and_fwd_flag = c("N", "N", "N", "N",
"N", "Y"), dropoff_longitude = c(-73.9444732666016, -73.9502716064453,
-73.9956893920898, -74.0073623657227, -74.0051345825195, -73.9709396362305
), dropoff_latitude = c(40.7166786193848, 40.7889251708984, 40.7442512512207,
40.7069358825684, 40.7399444580078, 40.7967071533203), payment_type = c(1L,
1L, 1L, 1L, 1L, 1L), fare_amount = c(18, 33, 12, 14, 11, 7),
    extra = c(0.5, 0.5, 0.5, 0.5, 0.5, 0.5), mta_tax = c(0.5,
    0.5, 0.5, 0.5, 0.5, 0.5), tip_amount = c(0, 0, 3.99000000953674,
    3.04999995231628, 1.5, 1.64999997615814), tolls_amount = c(0,
    0, 0, 0, 0, 0), improvement_surcharge = c(0.300000011920929,
    0.300000011920929, 0.300000011920929, 0.300000011920929,
    0.300000011920929, 0.300000011920929), total_amount = c(19.2999992370605,
    34.2999992370605, 17.2900009155273, 18.3500003814697, 13.8000001907349,
    9.94999980926514)), .Names = c("VendorID", "tpep_pickup_datetime",
"tpep_dropoff_datetime", "passenger_count", "trip_distance",
"pickup_longitude", "pickup_latitude", "RatecodeID", "store_and_fwd_flag",
"dropoff_longitude", "dropoff_latitude", "payment_type", "fare_amount",
"extra", "mta_tax", "tip_amount", "tolls_amount", "improvement_surcharge",
"total_amount"), row.names = c(NA, 6L), class = "data.frame")

A: I have found it. It is not the best solution but it works. I should only change the function like this:
CashVsCard<-function(x)
{

  p<-length(x$payment_type)
  for(i in 1: p)
  {

    if(x$payment_type[i]==1)
    {
      x$cash_vs_Card4[i]="Card"
    }   else    {
      x$cash_vs_Card4[i]="Others"
    }
  }
  return(x)
}


text:
Q: Dynamic database tables I have an idea where I would like to dynamically add tables to my database(through a website). I probably cannot use entity framework then, but I am not sure what the best tools would be.
So the idea is that a user would be able to create new "entities" and therefore create new tables in the database. There are only 3 types of entities(but multiple of each type) that user will be able to create so in theory I could have 3 tables with a entity filter but since there will be millions of records per entity and entities will never be used together I do not want to store them in the same table.
So my initial idea is to create a table per entity, what would be the best way to communicate with the database? Custom data access layer?
I am also open to other suggestions...

A: You could use Dapper with dynamic objects, it's really fast and fits exactly your needs.
https://code.google.com/p/dapper-dot-net/

A: I eventually used entity framework.
Firstly I created a template for each type I would have. Lets say TypeA, TypeB and added it to my model. Then I used the model builder to switch between Mappings
SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

DbModelBuilder builder = new DbModelBuilder(DbModelBuilderVersion.V6_0);
builder.Configurations.Add(new EntityTypeConfiguration<TypeA>());

builder.Entity<Tweet>().ToTable("Table1");

using (MyEntities myEntities= new MyEntities (builder.Build(conn).Compile()))
{
    var a = myEntities.Tweets.ToList();//Return table 1
}

DbModelBuilder builder2 = new DbModelBuilder(DbModelBuilderVersion.V6_0);
builder2.Configurations.Add(new EntityTypeConfiguration<TypeA>());
builder2.Entity<TypeA>().ToTable("Table2");

using (MyEntities myEntities= new MyEntities (builder.Build(conn).Compile()))
{
    var a = myEntities.Tweets.ToList();//Return table 2
}


text:
Q: Ruby 2.3.1 how to set the project root directory in config.rb I have a project in Ruby 2.3.1 and I'm using at the moment absolute path to a folder where I'm having uploaded files. What I would like to use instead is a relative path.
I would like to know how to set in Ruby config.rb the root directory / so I could call when I need the relative path to a folder like
root_dir + '/public/files'
The project is a Ruby RESTFull API which works with Solr for index/search PDF files. The app is a custom app with Sinatra and Rsolr.
This API has an upload function which points to a folder.
My Upload script:
post '/api/uploads' do
  #puts params
  fns = params['files'].map {|f| f[:filename]}.join(";")
  param = fns.chomp.split(";")
  #find pdf files
  param.select! {|f| f =~ /.*\.pdf/}

  array_length = param.length # or $param.size

  puts "length of $param is : #{array_length}"

  if(array_length==0)
    raise( "files not pdf: #{fns}")
  end
  i = 0
  resp = []
  while i.to_i < array_length do
    puts i
    filename = params[:documents][i][:filename]
    tmpfile = params[:documents][i][:tempfile]
    target = settings.homedir+'/'+filename
    localpath = File.join(settings.filesdir, filename)
    File.open(localpath, 'wb') do |f|
      f.write tmpfile.read
    end

    resp << {:fileurl => target}
    i = i + 1
  end

My config.rb:
set :root, File.dirname(__FILE__)
    set :filesdir, 'absolute_path/public/documents/pdf' # Set pdf files folder absolute path
    set :homedir, '/pdf'                         # Set pdf home directory
    set :solrbase, 'http://localhost:8983/solr/' # Set Solr connection path
    set :solrcore, 'docs'                        # Set name of the Solr core

    set :bind, '0.0.0.0'
    set :port, 3003                              # Set port of the API

    set :show_exceptions, false

    configure do
        mime_type :pdf, 'application/pdf'
  end

I would like to not write the absolute path and get a relative path so for example, another developer can use it immediately without set again the absolute path.


text:
Q: what makes an application a sidecar? so we have two containers running in a pod.. the idea is to have main container doing the job( receiving request) and a secondary container doing a background task of constantly checking the main app network status
i have my deployment file with the secondary container coming up first and then the main container coming after, please check code snippet below https://gist.github.com/dapseen/51bc7e59b96d934938a4afce34c615bb Is it because of the placement of container i.e fund worker coming starting up first that makes it the main app and other container coming up after makes it secondary container.
Is there a special annotation in k8 that can tell cluster or kubernetes the container to make side car?
Question rephrased...
how can i specify that a container should be sidecar
UPDATE
The question came as a result of things i saw in rancher, i am using rancher for Kubernetes management, please check image below

I think rancher takes the first container as the main app and the second to be sidecar.. i cant find documentation to support it .
rancher version: 2.2.3

A: Side car is just a design pattern that is upto you to implement. Kubernetes supports the side car pattern but does not implement it for you.  Hence there is no option to inform kubernetes to treat a container as the side car.

A: So i later figured this out, unfortunately rancher doc did not explain this..
I clearly understood that sidecar is a design pattern and you clearly gave it a name in your head, it doesnt have anything to do with kubernetes. Initially i was looking for a label or special annotation to label sidecar so rancher UI can pick it up and i can make my changes to it.
I resolve to re-arranging my deployment file and make my main app to be deployed first before the sidecar. I think order is important in selecting sidecar for rancher UI.
Take a look at the image below.

Conclusion, order is important in choosing sidecar in rancher UI
Thanks


text:
Q: Looking for Fantasy book about Fish/Whale Oil I can barely remember this book, I read it early to mid-2000's. It was a young adult book.

*

*The book takes place on a small island, I believe off the coast of Ireland or England, where fishing, and specifically fish(or whale?) oil is a big deal.

*The main character is a boy.

*There is a big magical fish that has a legend around it.

*At one point the main character is dragged/taken down under the ocean and walks around under the sea.(I remember a specific part where he takes off his boots to swim and then regrets it later)

*There's this big message about how the island doesn't need to use fish/whale oil to do everything anymore because they have like synthetic oil on the mainland, but the people on the island don't want to change their ways.

The only thing else I can remember about the book is that I believe it starts with a wake.
Thanks, any help would be great!

A: The Lampfish of Twill by Janet Taylor Lisle. 1991.
Along the coastline of Twill, life is precarious. Murderous currents, deadly whirlpools, and violent storms so endanger the lives of its fisher folk that the standard greeting is "Congratulations"--for having survived another day. "Weeps" or wakes for drowned friends are common. Celebrations, like those after the netting of a giant lampfish, whose bones make fishhooks and whose meat feeds an entire village, are few and riotous. The story focuses on two inhabitants of this imagined but recognizable landscape. Orphaned Eric lives with his unsentimental Aunt Opal, lavishing love meant for his drowned parents on Gully, a sea gull he rescued from the waves and raised from infancy. Eric's obsessive attempts to net a lampfish single-handed are thwarted by the mysterious, half-mad Ezekiel Cantrip, the only known survivor of a descent into a whirlpool.


text:
Q: Navigation of items in a list
*

*I have 15 items in a list

*I have 10 such lists

*Each list SHOULD OCCUPY at most 1 row on the page

*Overflow items should be navigated via "NEXT" or "PREV" button.

*For displaying items in each list, I "float:left".

*But then the overflow items wrap to next row.

For now, I am doing a hack for my laptop screen size:

*

*I .hide() all items at window load for each list

*Then .show() first 4 items for each list

*I have configured next and prev buttons accordingly.

I am positive this is wrong. But it enabled me to see how the look and feel is of what I wanted to do.
Please suggest me the correct approach. All major websites handle this. This is very common problem. I am just ignorant for now.

A: The easiest way to achieve this is probably:

*

*Don't use float:left, just use regular inline display.

*For the container element, use overflow:hidden.

*Wrap the container element in an outer container, also with overflow:hidden.

*Now, when the user clicks next/prev, adjust/animate the margin of the inner container, so that it slides across to reveal the other elements.

A: I think I solved the problem by another SO response:
How to move first child to the end?
Thanks for all your help


text:
Q: Bash Script not working as intended So, I'm a complete newbie when it comes to scripting, like this is my first one.  I have created the following script:
# This simply declares which states we are using to create tarballs from
for blah in ar ky ms ny;
do
    # This will go into each tomcat-state directory and create a tarball in /home/ec-user for all files older than 90 days
    find /var/www/apps/tomcat-${blah}/logs -type f -mtime +90 | xargs tar -cvzf /home/ec2-user/archive-${blah}.tar.gz;

    # This creates a master archive tarball containing all the archive-state.tar.gz files
    tar -cvzf /home/ec2-user/ebd-log-archives.tar.gz /home/ec2-user/archive-${blah}.tar;

    # Since in step one, we archives all files older than 90 days, this step removes them.
    # find /var/www/apps/tomcat-${blah}/logs -type f  -mtime +90 -exec rm {} \;

    # And since we have the master archive file, this removes the archive-state files
    rm /home/ec2-user/archive-${blah}.tar.gz;
done

I have commented out the deleting of the logs for testing.
The problem is, when I get the master tarball, it only has NY in it, or whichever I put as my last in the loop (I tested this to make sure it wasn't just a odd NY thing)
Not sure what's going on, I tested it against an older script SIMILAR to this in wording on that server, and that one runs fine.
Edit: Thanks for the responses, I have updated the script to:
# This creates the master tarball we will be using
tar -cvzf /home/ec2-user/ebd-log-archives.tar.gz

# This simply declares which states we are using to create tarballs from
for blah in ar ky ms ny;
do
    # This will go into each tomcat-state directory and create a tarball in /home/ec-user for all files older than 90 days
    find /var/www/apps/tomcat-${blah}/logs -type f -mtime +90 | xargs tar -cvzf /home/ec2-user/archive-${blah}.tar.gz;

    # This creates a master archive tarball containing all the archive-state.tar.gz files
    tar -rvzf /home/ec2-user/ebd-log-archives.tar.gz /home/ec2-user/archive-${blah}.tar;

    # Since in step one, we archives all files older than 90 days, this step removes them.
    # find /var/www/apps/tomcat-${blah}/logs -type f  -mtime +90 -exec rm {} \;

    # And since we have the master archive file, this removes the archive-state files
    rm /home/ec2-user/archive-${blah}.tar.gz;
done

I'll try running with this and posting an update

A: Every time you run tar -c, the tool creates a new archive. If you tell it to use an existing name (ebd-log-archives.tar.gz in your case), the old archive will be overwritten.
You can create an empty archive ("a master archive") before the loop and then tar -r (instead of tar -c) inside the loop.
From man 1 tar:

-c, --create
Create a new archive. […]
[…]
-r, --append
Append files to the end of an archive. Arguments have the same meaning as for -c (--create).


text:
Q: HSA Data copy between RAM and GPU-RAM Reading the wikipage about HSA found this block diagram.
Could not understand the benefits of passing pointer through PCI-ex
Does this avoids data copying from system memory to graphics memory ?
As far as I understand to process the content of the pointer the GPU will need it to be present in the graphics memory.

A: If you have separate graphics memory, but you're doing HSA, you have to somehow unify the address spaces.  The CPU can see graphics memory, mapped to physical address space.  And the GPU can access main memory via DMA.  You can set up the CPU and GPU with page tables that direct the same virtual addresses to the same place, which will require one of them to go (transparently) over the PCIe bus.
Where you save time and energy is that you don't have to copy everything you MIGHT want to access; the CPU and GPU access only the data they actually need to use.


text:
Q: Can I use super.someMethod to init a member variable in Java? it just simple Android code like this
there was a textview and a list view.
public class MaintActivity extends Activity {
    private TextView text = (TextView)super.findViewById(R.id.text);
    //cause android application crash
    public void onCreate(Bundle savedInstanceState){
          super.onCreate(savedInstanceState);
          super.setContentView(R.layout.main);
          //when I write this.text = (TextView) super.findViewById(R.id.text); here, I get rid of crashing
    }
}

A: Generally, there's nothing wrong in calling a method when initializing a variable in Java. However, in this specific case:
private TextView text = (TextView)super.findViewById(R.id.text);

You cannot call findViewById() before onCreate(). The code will NPE because the activity Window has not yet been set up. Also you likely want to call it after setContentView() so it will actually have a chance of returning something.
In Android activities in general, you shouldn't really be doing anything at runtime before onCreate().

A: There's nothing wrong in general with calling superclass methods and getting return values from them.  There might be a problem with the particular method you're calling, or the way you're calling it, or what you're doing with the result, but merely calling a superclass method and assigning its result to a variable is not an error.

A: As answered by laalto, the real issue is not the use of super keyword, but NullPointerException due to Activity cannot find the view before it is set-up in onCreate().
As for your question title itself: yes, you can, and you've tested it by yourself.
This will run without error if you "fix" your code to: (using the same code as yours)
public class MaintActivity extends Activity {
    private TextView text;

    public void onCreate(Bundle savedInstanceState){
          super.onCreate(savedInstanceState);
          super.setContentView(R.layout.main);
          this.text = (TextView) super.findViewById(R.id.text);
    }
}

Though, it's strange in this case, since setContentView() and findViewById() will certainly not be overridden. Better to use this or no keyword at all.


text:
Q: Can AutoMapper map to an attached entity? For my update operations, my controller action does something like this:
    public Task<IHttpActionResult> Update(int id, CustomerTypeDto customerTypeDto)
    {
        var entity = customerTypeService.Get(id);

        entity.Number = customerTypeDto.Number;
        entity.Description = customerTypeDto.Description;

        entity = customerTypeService.Save(entity);

        return Ok<CustomerTypeDto>(Mapper.Map<CustomerTypeDto>(entity));
    }

This is a simple example with a simple entity consisting of 2 properties. Most of my entities are complex entities having tons of properties and deep relationships.
I need to load the entity from the DB first so that it starts being tracked by the context. I set the properties and then save the updated entity back into the DB. The repository's update method looks like this:
    public virtual void Update(T entity)
    {
        DbEntityEntry dbEntityEntry = dataContext.GetEntry(entity);
        if (dbEntityEntry.State == EntityState.Detached)
        {
            dbSet.Attach(entity);
            dbEntityEntry.State = EntityState.Modified;
        }
    }

Doing the above, EF correctly creates and Update SQL statement consisting of only the changes properties.
With Automapper, is it possible to map the dto class to the model after it was loaded from db, so that changes can be tracked when the mapping occurs?
Instead of doing:
entity.Number = customerTypeDto.Number;
entity.Description = customerTypeDto.Description;

Is it possible to do:
entity = Mapper.Map(customerTypeDto, entity);

If this is not possible, what other alternatives are there apart from setting individual properties? Maybe using GraphDiff or this Delta implemenation?


text:
Q: Loading jasperreports' .jrxml files In my project I have stored .jrxml files in a package called com/bio/ofm/mnu/views/reports/jasperReports/
When I try to load a .jrxml I get following error,
net.sf.jasperreports.engine.JRException: java.io.FileNotFoundException: com/bio/ofm/mnu/views/reports/jasperReports/repAuditReport.jrxml (No such file or directory)
        at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:174)
        at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:154)
        at net.sf.jasperreports.engine.JasperCompileManager.compileReport(JasperCompileManager.java:146)
        at com.bio.ofm.mnu.views.panels.RepAuditReport$2.run(RepAuditReport.java:87)
        at java.lang.Thread.run(Thread.java:722)
Caused by: java.io.FileNotFoundException: com/bio/ofm/mnu/views/reports/jasperReports/repAuditReport.jrxml (No such file or directory)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at net.sf.jasperreports.engine.xml.JRXmlLoader.load(JRXmlLoader.java:169)
        ... 4 more

This is how I load the file,
String fileName = getClass().getClassLoader().getResource("com/bio/ofm/mnu/views/reports/jasperReports/repAuditReport.jrxml").getFile();

   JasperReport report = JasperCompileManager.compileReport("com/bio/ofm/mnu/views/reports/jasperReports/repAuditReport.jrxml");

please help

A: When loading the file as a stream like below it worked,
InputStream in = this.getClass().getClassLoader().getResourceAsStream("com/bio/ofm/mnu/views/reports/jasperReports/repAuditReport.jrxml");

JasperReport report = JasperCompileManager.compileReport(in);

A: i'm compiling my reports like that:
ByteArrayInputStream is = MyRenderer.class.getClassLoader().getResourceAsStream("anytemplate.jrxml");

JasperDesign jasperDesign = JRXmlLoader.load(is);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);


text:
Q: Queue full for Signalr with Redis backplane Sometimes we get the following error on with the Signalr implementation using Redis as backplane:
System.InvalidOperationException: The queue is full.

at Microsoft.AspNet.SignalR.Messaging.ScaleoutStream.Send(Func`2 send, Object state)

at Microsoft.AspNet.SignalR.Infrastructure.Connection.Send(ConnectionMessage message)

at Microsoft.AspNet.SignalR.ConnectionExtensions.Send(IConnection connection, String connectionId, Object value)

Anyone know whats going on here? Is this the MaxQueueLength that is limiting for scaleout or something else?


text:
Q: How to implement a Xamarin Forms SwipeGesture on small screens I have a Xamarin Forms app where I add to a MAIN VIEW 3 views: view 1 / header, view 2, view 3.
On Desktop I want to have them (and I already have them) this way:

What I'm looking is a different behaviour just for small screens. I would like to "show/hide" view 2 & view 3 with SwipeGesture, and have something like this:

Whenever I swipe, I get View 3 individual. If I swipe back, I get View 2. How can I make it through SwipeGesture? Maybe combining with OnIdiom, but how? What if the desktop app they have resized small? That's why I want to have something like breakpoints of the screen instead of OnIdiom.
Is there a way to do it on XAML without code behind?


text:
Q: How to process large XML file (9 GB) with STAX api I'm always getting Heap memory problem while processing huge file.Here i'm processing 9 GB xml file.
This is my code.
            XMLInputFactory inputFactory = XMLInputFactory.newInstance();
            InputStream in = new FileInputStream(sourcePath);
            XMLEventReader eventReader =  inputFactory.createXMLEventReader(in);

            Map<String, Cmt> mapCmt = new ConcurrentHashMap<String, Cmt>();
            while (eventReader.hasNext()) {
                XMLEvent event = eventReader.nextEvent();
                if (event.isStartElement()) {
                //some processing and assigning value to map
                Cmt cmt = new Cmt();
                //get attributes
                cmt.setDetails(attribute.getValue());
                mapCmt.put(someKey,cmt);
                }
            }

I'getting heap memory problem in iteration after some time.
Please help me to write optimized code.
Note: server have available 3 GB heap space. I can't increase server space.
I'm executing with following parameters - -Xms1024m -Xmx3g
My xml looks like this.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<DatosAbonados xmlns="http://www.cnmc.es/DatosAbonados">
    <DatosAbonado Operacion="1" FechaExtraccion="2015-10-08">
        <Titular>
            <PersonaJuridica DocIdentificacionJuridica="A84619488" RazonSocial="HERMANOS ROJAS" NombreComercial="PINTURAS ROJAS"/>
        </Titular>
        <Domicilio Escalera=" " Piso=" " Puerta=" " TipoVia="AVENIDA" NombreVia="MANOTERAS" NumeroCalle="10" Portal=" " CodigoPostal="28050" Poblacion="Madrid" Provincia="28"/>
        <NumeracionAbonado>
            <Rangos NumeroDesde="211188600" NumeroHasta="211188699" ConsentimientoGuias-Consulta="1" VentaDirecta-Publicidad="1" ModoPago="1">
                <Operador RazonSocial="11888 SERVICIO CONSULTA TELEFONICA S.A." DocIdentificacionJuridica="A83519389"/>
            </Rangos>
        </NumeracionAbonado>
    </DatosAbonado>
    <DatosAbonado Operacion="1" FechaExtraccion="2015-10-08">
        <Titular>
            <PersonaJuridica DocIdentificacionJuridica="A84619489" RazonSocial="HERMANOS RUBIO" NombreComercial="RUBIO PELUQUERIAS"/>
        </Titular>
        <Domicilio Escalera=" " Piso=" " Puerta=" " TipoVia="AVENIDA" NombreVia="BURGOS" NumeroCalle="18" Portal=" " CodigoPostal="28036" Poblacion="Madrid" Provincia="28"/>
        <NumeracionAbonado>
            <Rangos NumeroDesde="211186000" NumeroHasta="211186099" ConsentimientoGuias-Consulta="1" VentaDirecta-Publicidad="1" ModoPago="1">
                <Operador RazonSocial="11888 SERVICIO CONSULTA TELEFONICA S.A." DocIdentificacionJuridica="A83519389"/>
            </Rangos>
        </NumeracionAbonado>
    </DatosAbonado>
</DatosAbonados>

My Cmt class is :
public class Cmt {
    private List<DetailInfo> details;

    public List<DetailInfo> getDetails() {
        return details;
    }
    public void setDetails(DetailInfo detail) {
        if(details == null){
            details = new ArrayList<DetailInfo>();
        }
        this.details.add(detail);
    }
}

Actually Cmt object is very less, But i have DetailInfo object for
  every  element. So  huge no. of DetailInfo object is
  created.

My Logic is this :
if (startElement.getName().getLocalPart().equals("DatosAbonado")) {
                    detailInfo = new DetailInfo();

                    Iterator<Attribute> attributes = startElement.getAttributes();
                    while (attributes.hasNext()) {
                        Attribute attribute = attributes.next();
                         if(attribute.getName().toString().equals("Operacion")){
                            detailInfo.setOperacion(attribute.getValue());
                        }
                    }
                }
if (event.isEndElement()) {
                EndElement endElement = event.asEndElement();
                if (endElement.getName().getLocalPart().equals("DatosAbonado")) {
                    Cmt cmt = null;
                    if(mapCmt.keySet().contains(identificador)){
                        cmt = mapCmt.get(identificador);
                    } else{
                        cmt = new Cmt();
                    }
                    cmt.setDetails(detailInfo);
                    mapCmt.put(identificador, cmt);
}
}

A: The root of your problems is most likely this:
mapCmt.put(someKey, cmt);

You are populating a hashmap with a number of large Cmt objects.  You need to do one of the following:

*

*Process the data immediately rather than saving it in a data structure.

*Write the data out to a database for later querying.

*Increase the heap size.

*Figure out a less "memory hungry" representation for your data.

The last two approaches don't scale though.  As you increase the size of the input file, you will need progressively more memory ... until you eventually exceed the memory capacity of your execution platform.

A: DatosAbonnado is the killer indeed. If you have plenty of 'm this will cause your application to choke.
The approach is simply not scalable. As pointed out by Stephan C you need to process the DatosAbonnado as it arrives and not collect them in a container.
Since this is a typical scenario for which I developed LDX+ code generator, I went to the steps of:

*

*creating an XML Schema file from XML (because you had not provided it) using: https://devutilsonline.com/xsd-xml/generate-xsd-from-xml

*generate code with LDX+

This code generator is actually using SAX, and the resulting code allows you to:

*

*serialize the complexElements to Java objects

*configure how to treat 1 to many relationships (like the one you have here) at runtime

I uploaded the code here: https://bitbucket.org/lolkedijkstra/ldx-samples
To see the code navigate to the Source folder. There you'll find DatosAbonnados.
This approach really scales well (memory consumption is flat)


text:
Q: Evaluate $\log 64$ using the change of base formula? Is that even possible? I mean, there is no base.

A: Usually, $\log$ means $\log_e = \ln$ or $\log_{10}$. Either way, there isn't a neat answer to the question. The most you can do is write $\ln 64 = 6\ln 2$ and $\log_{10}64 = 6 \log_{10}2$, using that $2^6=64$. Now the problem boils down to knowing the values of $\ln 2$ and $\log_{10}2$. These values can be approximated numerically using calculus, for example.