Proving sum of negative powers of 2 equals one before becoming greater than one

Question: Let $x$: $x_1 \geq x_2 \geq x_3\geq...\geq x_n$ be negative powers of 2 with sum greater than one. Then $\exists$ $l$ s.t. $x_1 + x_2 + ... + x_l = 1$. It seems obvious from examples, but I'm finding it a bit difficult to prove it. Any help would be highly appreciated.
Comment: Consider the set of all subsets of the powers whose sum is greater than $1$. Consider a minimal element of this set (i.e., removing any element makes the sum less than $1$). What does this tell you about the minimal element? Can you derive a contradiction?
Comment: Do we need to look at all the subsets or just the prefix subarrays. I was initially trying to find a contradiction in this manner: Since $x_1, x_2,..,x_l$ are multiples of $x_{l+1}$ it means $A*x_{l+1} + x_{l+1} > 1$ with $A*x_{l+1} < 1$ (where $A*x_{l+1} \geq x_{l+1}$).
Answer: Your comment is close.
Let $S_i = x_1+x_2+\cdots + x_i$.
For the first case $l=1$, the first sum $S_1 = x_1<1$. For the last case $l=n$, $S_n > 1$ (as given). For the increasing sum $S_l$, there must be a largest $l$ that satisfy $S_l < 1$.
Assume that $k$ is the greatest integer that satisfy $$S_k = \sum_{i=1}^kx_i < 1$$
Then the goal is to prove that the next sum
$$S_{k+1}=\sum_{i=1}^{k+1}x_i = 1.$$
As you pointed out, $S_k = \sum_{i=1}^k x_i$ is an integer multiple of $x_{k+1}$, so let $S_k = Ax_{k+1}$. Then from the hypothesis,
$$\begin{align*}
Ax_{k+1} &< 1\\
A &< x_{k+1}^{-1}
\end{align*}$$
$x_{k+1}^{-1}$ is an integer for being a positive power of $2$, and since both sides are integers,
$$\begin{align*}
A + 1 &\le x_{k+1}^{-1}\\
Ax_{k+1} + x_{k+1} &\le 1\\
S_{k+1} &\le 1
\end{align*}$$
Also by the definition of $k$, $S_{k+1} \not< 1$.
Then the only possibility is that $$S_{k+1} = \sum_{i=1}^{k+1}x_i = 1$$
Answer: Consider the partial series, up until the value passes $1$. Considering the last value used, we can calculate the minimum remaining number of steps ($MRS_i$) until the series reaches $1$, and this will always be an integer.
We can start with a partial series value of $0$ and the assumption that previous value $x_0 = 1$. This gives us $MRS_0 = 1$.
Now examining the next value, we can recalculate $MRS$ in the light of this. If $x_i<x_{i-1}$, we known that $x_{i-1}$ exactly divides $x_{i}$ and we multiply the previous $MRS$ by $\dfrac{x_i}{x_{i-1}}$, an integer, and either way we then subtract one, to again get an integer $MRS_i$. So as we apporach a partial series value of $1$ it is always an integer number of terms away, until $MRS_\ell = 0$ as required for the full series to pass $1$.
Note that this results holds whenever $x_i \mid x_{i-1}$ is a property of the sequence - we don't actually need the successive $x_i$ to be (negative) powers of two. Also, if the series passes other integers, it will also hit them exactly.


Which way is better Linq Select Query or For Loop to search something in generic List?

Question: As far as performance is concerned,
Which way is better Linq Select Query or For Loop to search something in generic List?
Comment: And in general any of the umpteen questions you find if you search for "linq performance".
Comment: See http://stackoverflow.com/questions/1044236
Answer: A for loop may well be very slightly faster. Measure it to find out for sure... but then look at the readability. (EDIT: When you measure it, try doing so for rather longer than the benchmark in the accepted answer does. Also compare the time taken for this piece of code with the time for the rest of your program. Is this really a bottleneck?)
I wouldn't usually use a "select" unless you actually need to project a sequence of results though. To find a single element, either use:
list.Find(x => x.Name == "Foo");

or
list.FirstOrDefault(x => x.Name == "Foo");

I believe both of these are significantly more readable than the corresponding for loop. If you're just looking for an object then you might want to consider using a HashSet<T> instead or in combination with the list.
EDIT: Here's a benchmark to test it. Code is below results.
c:\Users\Jon\Test>test 1000000 500000 1000
FindCustomerLinq: 28531
FindCustomerListFind: 12315
FindCustomerForLoop: 9737
FindCustomerForEachLoop: 14743

So that's looking in a list of a million elements, finding one half way through it, but doing it 1000 times. So yes, the for loop is actually three times as fast... but you'd have to be doing this an awful lot before this difference actual becomes significant. If you're doing this kind of thing that much, you should look for other options such as a Dictionary.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

public class Customer
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

class Test
{
    static void Main(string[] args)
    {
        int size = int.Parse(args[0]);
        int id = int.Parse(args[1]);
        int iterations = int.Parse(args[2]);

        var list = new List<Customer>(size);
        for (int i=0; i < size; i++)
        {
            list.Add(new Customer {
                ID = i,
                Address = "Address " + i,
                Name = "Cusomer Name " + i,
                Phone= "Phone " + i,
            });
        }

        Time(FindCustomerLinq, list, id, iterations);
        Time(FindCustomerListFind, list, id, iterations);
        Time(FindCustomerForLoop, list, id, iterations);
        Time(FindCustomerForEachLoop, list, id, iterations);
    }

    static void Time(Func<List<Customer>, int, Customer> action,
                     List<Customer> list,
                     int id, int iterations)
    {
        Stopwatch sw = Stopwatch.StartNew();
        for (int i=0; i < iterations; i++)
        {
            action(list, id);
        }
        sw.Stop();
        Console.WriteLine("{0}: {1}", action.Method.Name, (int) sw.ElapsedMilliseconds);
    }

    static Customer FindCustomerLinq(List<Customer> customers, int id)
    {
        return customers.FirstOrDefault(c => c.ID == id);
    }

    static Customer FindCustomerListFind(List<Customer> customers, int id)
    {
        return customers.Find(c => c.ID == id);
    }

    static Customer FindCustomerForLoop(List<Customer> customers, int id)
    {
        for (int i=0; i < customers.Count; i++)
        {
            if (customers[i].ID == id)
            {
                return customers[i];
            }
        }
        return null;
    }

    static Customer FindCustomerForEachLoop(List<Customer> customers, int id)
    {
        foreach (Customer c in customers)
        {
            if (c.ID == id)
            {
                return c;
            }
        }
        return null;
    }
}

Answer: Some days before i tried same thing as R&D for 50000 Records and found that
for loop takes approx 60% time as the time taken by linq where clause
Elapsed time for Linq : 87 ms
Elapsed time for Linq : 48 ms
Elapsed time for Linq : 143 ms
Elapsed time for Linq : 76 ms
and so on.. for details please see the code how i did it
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace SearchingList
{
    public partial class Form1 : Form
    {
        private int searchingID = 0;
        public int SearchingID
        {
            get
            {
                if (string.IsNullOrEmpty(txtID.Text))
                    searchingID = 0;
                else
                    int.TryParse(txtID.Text, out searchingID);
                return searchingID;
            }
            set
            {
                SearchingID = searchingID;
            }
        }
        public Form1()
        {
            InitializeComponent();
        }

        private void btnsearch_Click(object sender, EventArgs e)
        {
            List<Customer> lstcustomersFound = new List<Customer>();
            Stopwatch stp = new Stopwatch();
            stp.Start();
            lstcustomersFound = GetSearchedCustomersByLinq(SearchingID, (List<Customer>)dgvAllData.DataSource);
            stp.Stop();
            lblLinq.Text = "Elapsed Time Linq : " + stp.ElapsedMilliseconds.ToString() + " ms";
            stp.Start();
            lstcustomersFound = GetSearchedCustomersByForLoop(SearchingID, (List<Customer>)dgvAllData.DataSource);
            stp.Stop();
            lblFor.Text ="Elapsed Time for loop : " + stp.ElapsedMilliseconds.ToString() + " ms";
            dgvSearched.DataSource = lstcustomersFound;
        }

        private List<Customer> GetSearchedCustomersByForLoop(int searchingID, List<Customer> lstcustomers)
        {
            List<Customer> lstcustomersFound = new List<Customer>();
            foreach (Customer customer in lstcustomers)
            {
                if (customer.CusomerID.ToString().Contains(searchingID.ToString()))
                {
                    lstcustomersFound.Add(customer);
                }
            }
            return lstcustomersFound;
        }

        private List<Customer> GetSearchedCustomersByLinq(int searchingID, List<Customer> lstcustomers)
        {
            var query = from customer in lstcustomers
                        where customer.CusomerID.ToString().Contains(searchingID.ToString())
                        select customer as Customer;
            return query.ToList();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            List<Customer> customers = new List<Customer>();
            Customer customer;
            for (int id = 1; id <= 50000; id++)
            {
                customer = new Customer();
                customer.CusomerAddress = "Address " + id.ToString();
                customer.CusomerID = id;
                customer.CusomerName = "Cusomer Name " + id.ToString();
                customer.CusomerPhone= "Phone " + id.ToString();
                customers.Add(customer);
            }
            dgvAllData.DataSource = customers;
        }

    }
}

Customer Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SearchingList
{
    public class Customer
    {
        public int CusomerID { get; set; }
        public string CusomerName { get; set; }
        public string CusomerAddress { get; set; }
        public string CusomerPhone { get; set; }
    }
}

As performance is consideration i will go for For Loop instead of Linq
Comment: That's *copying* a list rather than finding a specific entry. I'd also argue that you're measuring for *way* too short a time for those results to be meaningful. Your condition is also very suspicious - looking for "10" will find "100" for example... and why convert the searchingID to a string on every iteration in the loop? I know you're doing the same thing in both cases, but even so I wouldn't use this as a good benchmark.
Comment: I created one more program not posted here , where customerId was an string and serched result can be populated based on text changed in customer id text box..and performance result was almost same
Comment: I'm probably missing something, but don't you have to reset that Stopwatch somewhere?


Computed field: sum fields from different content type

Question: I use the module "computed field".
How can I calculate (sum) the value from one field in one content type and a field from other content type? Is it possible?
Sorry for my English.
Comment: How are the two content types connected?  If you have an Entity Reference or Relation that links them, this is pretty easy.  If not, it might be very hard.
Comment: they connected by taxonomy term.
Comment: If they are not connected directly, you need to give more information.  The computed field is on a node of content type ABC.  How many other nodes need to be considered?
Answer: You could do that by querying database :
<code><?php
$database = \Drupal::service('database');

$database->select('node_<FIELD>', 'n');
$database->fields('n', ['bundle']);
$database->addExpression('SUM(n.<FIELD>_value)', 'sum');
$database->groupBy('n.bundle');
$results = $database->execute();

foreach($results->fetchAll() as $result){
    print $result->bundle.' : '.$result->sum;
}
</code>
This example is for node, but quiet similar with taxonomy or other entity type.
Answer: You can create one view and add your fields. Then review the following response:
Or the following response


Enlighten me... the science behind differentiation

Question: This a tricky math question I encountered.
I know a little bit about the answer. But I want somebody who is very good at math to help me find the real reason behind this.
OK
Lets start
$1^2 = 1$
$2^2 = 2+2$
$3^2 = 3+3+3$
...........................
................................
$x^2 = x+x+x+x+.....(x times)$
Differentiating with respect to $x$
We get
$2x = 1+1+1+1...... (x times)$
which is equal to
$2x = 1*x$
$2x = x$
Which is incorrect.
Where did I go wrong?? :O :O
Comment: if you make x a variable then the "x times" varies as well, so it would have to be taken into account when differentiating
Comment: See [this](http://math.stackexchange.com/questions/1096/where-is-the-flaw-in-this-argument-of-a-proof-that-1-2-derivative-of-repeated).
Comment: @DavidMitra Thanks... I saw it. It really answers my question. :)
Answer: Please think of the case when $x$ belongs to a real number and not an integer.
Then you will get the idea, say what happens when x = 1.5?
$ x^2 = x * x $
$\frac{d}{dx} x^2 = x + x = 2x $
Answer: Your problem arises because you have made the assumption that
$$\frac{d}{dx}\sum_{i=1}^{x}x$$
can be calculated by simply summing the derivatives of the individual summands; i.e., you have made the assumption that
$$\frac{d}{dx}\sum_{i=1}^{x}x=\sum_{i=1}^{x}\frac{d}{dx}x.$$
This is not true; the value of $x$ affects both the elements of the sum and the number of elements in the sum.


How to remove [DCC Error] : E2035 Not enough actual parameters

Question: I am a Delphi learner. I was looking for some codes to convert basic colours in Hue, Saturation and Value. I have got it in this forum and  I have implemented it like :
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Math;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Label1: TLabel;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure HSVToRGB(Const H, S, V: Real; Out R, G, B: Real);
const
  SectionSize = 60/360;
var
  F: real;
  P, Q, T: real;
  Section: real;
  SectionIndex: integer;
begin
  if H < 0 then
    begin
      R:= V;
      G:= R;
      B:= R;
    end
  else
    begin
      Section:= H/SectionSize;
      SectionIndex:= Floor(Section);
      F:= Section - SectionIndex;
      P:= V * ( 1 - S );
      Q:= V * ( 1 - S * F );
      T:= V * ( 1 - S * ( 1 - F ) );
      case SectionIndex of
        0:
          begin
            R:= V;
            G:= T;
            B:= P;
          end;
        1:
          begin
            R:= Q;
            G:= V;
            B:= P;
          end;
        2:
          begin
            R:= P;
            G:= V;
            B:= T;
          end;
        3:
          begin
            R:= P;
            G:= Q;
            B:= V;
          end;
        4:
          begin
            R:= T;
            G:= P;
            B:= V;
          end;
        else
          begin
            R:= V;
            G:= P;
            B:= Q;
          end;
      end;
    end;
end;

procedure RGBToHSV(Const R, G, B: Real; Out H, S, V: Real);
var
  Range: real;
  RGB: array[0..2] of real;
  MinIndex, MaxIndex: integer;
begin
  RGB[0]:= R;
  RGB[1]:= G;
  RGB[2]:= B;

  MinIndex:= 0;
  if G < R then MinIndex:= 1;
  if B < RGB[MinIndex] then MinIndex:= 2;

  MaxIndex:= 0;
  if G > R then MaxIndex:= 1;
  if B > RGB[MaxIndex] then MaxIndex:= 2;

  Range:= RGB[MaxIndex] - RGB[MinIndex];

  if Range = 0 then
    begin
      H:= -1;
      S:= 0;
      V:= R;
    end
    else
      begin
        case MaxIndex of
          0:
            begin
              H:= (G-B)/Range;
            end;
          1:
            begin
              H:= 2 + (B-R)/Range;
            end;
          2:
            begin
              H:= 4 + (R-G)/Range;
            end;
        end;
        S:= Range/RGB[MaxIndex];
        V:= RGB[MaxIndex];
        H:= H * (1/6);
        if H < 0 then H:= 1 + H;
      end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Hue, Saturation, Value: real;
  Red, Green, Blue: integer;
begin
  Red := GetRValue(Label1.Font.Color);
  Green := GetGValue(Label1.Font.Color);
  Blue := GetBValue(Label1.Font.Color);
  Hue := RGBToHSV(GetRValue(Label1.Font.Color), GetGValue(Label1.Font.Color), GetBValue(Label1.Font.Color));
  Saturation := RGBToHSV(GetRValue(Label1.Font.Color), GetGValue(Label1.Font.Color), GetBValue(Label1.Font.Color));
  Value := RGBToHSV(GetRValue(Label1.Font.Color), GetGValue(Label1.Font.Color), GetBValue(Label1.Font.Color));
  ShowMessage (FloatToStr(Hue) +','+ FloatToStr(Saturation)+',' + FloatToStr(Value));
end;

end.

At the time of compilation Delphi is throwing 3 Error as
[DCC Error] Unit1.pas(150): E2035 Not enough actual parameters.
on the lines below :
Hue := RGBToHSV(GetRValue(Label1.Font.Color), GetGValue(Label1.Font.Color), GetBValue(Label1.Font.Color));
Saturation := RGBToHSV(GetRValue(Label1.Font.Color), GetGValue(Label1.Font.Color), GetBValue(Label1.Font.Color));
Value := RGBToHSV(GetRValue(Label1.Font.Color), GetGValue(Label1.Font.Color), GetBValue(Label1.Font.Color));
How to remove the Errors?
Comment: have a look at `; Out H, S, V: Real` of `RGBToHSV(Const R, G, B: Real; Out H, S, V: Real);`
Comment: .. and remove the left side, it is not a function
Comment: Add the three missing parameters, which are `Real` variables to receive the HSV values.
Comment: why do you want to implement a function that already and for long is part of Delphi ?
Answer: I'm going to attempt to walk you through how to solve such a problem yourself.
Step 1: Work out what the compiler error means
Frankly, this error is self-explanatory.

Not enough actual parameters

Well, you did not pass enough parameters. However, if it's not obvious, then type the error message text, and the error code, E2035 in this case, into your favoured search engine. That will lead you to the documentation for the compiler error which says:

This error message occurs when a call to procedure or function gives less parameters than specified in the procedure or function declaration.

And there are some examples to demonstrate how it can happen. That's all useful information. Take some time to read it carefully.
Step 2: Identify the line of code which leads to the error
There are three instances which all look like this:
Hue := RGBToHSV(GetRValue(Label1.Font.Color), GetGValue(Label1.Font.Color),
  GetBValue(Label1.Font.Color));

Step 3: Apply what we learnt in step 1 to the failing line of code
There are 4 function/procedure calls. Check the parameters for each one. Check the declaration of the function against parameters you pass when the calling, that is the actual parameters.
For the three inner functions, the parameter counts match. But look at the call to RGBToHSV. That function has six parameters, but you passed only three.

The above is a general procedure to adopt when facing a compiler error that you do not understand. You will be able to apply this technique when you face other, different, compiler errors.
Answer: procedure RGBToHSV(Const R, G, B: Real; Out H, S, V: Real);

You are declaring 6 parameters, without any return value, yet you call it using 3 parameters only, assigning its return value (which doesn't exist) to a variable. You should change the calls to just one:
RGBToHSV(
  GetRValue(Label1.Font.Color),
  GetGValue(Label1.Font.Color),
  GetBValue(Label1.Font.Color),
  <variable that will hold Hue value>,
  <variable that will hold Saturation value>,
  <variable that will hold Value value>
);


How to get mysql query last five week of current day

Question:
My table structure is like this:

Column Name:
id
name
start_date
end_date

Example: today day is "Wednesday" so i want to get last five week's Wednesday data, with check between start_date and end_date
please check current day wise data
Comment: So... What have you tried? Look at `date()`, `strtotime('last Wednesday', time())`
Comment: SELECT *,WEEKDAY(created_date) as weekdays
FROM user
WHERE created_date BETWEEN start_date AND end_date ORDER BY start_date ASC LIMIT 5
Comment: What's created_date? See https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query
Answer: Write below line in where condition
WHERE created_date >= DATE_ADD(CURDATE(), INTERVAL -3 DAY);

Comment: there is no use created_date
Answer: First with PHP code get last 5 days of current day then pass those days in sql query
<?php
function last_days($total)
{
    $days= array();
    $today = date("l");
    for($i = 1; $i<= $total;$i++)
    {
        $days[] = date('Y-m-d',strtotime("-$i $today"));
    }
    return $days;
}
$days = last_days(5);
//print_r($days);
$days_str = "'".implode("','", $days)."'";
$query = "SELECT *,WEEKDAY(created_date) as weekdays FROM user WHERE created_date IN ($days_str) ORDER BY start_date ASC";

DEMO


Limit items in shopping cart

Question: Is there a way to limit users on my site to buy only 2 items from a list of products?
Am using Drupal 7 with Commerce module and Rules.
I added a new rule to when adding or removing and item from the shopping cart, it would check if the total quantity is bigger than 2, then it would remove the last element like this.

Event
  Before adding a product to the cart
After adding a product to the cart
Conditions
Total product quantity comparison
  Parameter: Order: [commerce_order], Operator: >, Quantity: 2
Actions
Remove an item from a list
Selected list: commerce-order:commerce-line-items

and the item to remove is

commerce-order:commerce-line-items:2

Sadly its not working, and I really need your help.
thanks
Comment: The conversation at http://www.drupalcommerce.org/node/673 may be useful to you, but you have more sophisticated requirements.
Comment: well, this is helpful but in my case cause I want the action to be removing an element from the cart.
Comment: stumbled on this, but if you are still looking for the rule(s) necessary to limit product quantities, you can see the post at http://www.drupalcommerce.org/node/1053
Answer: I had a similar problem:
I had to check for certain conditions before adding an item to the cart (not after adding). And if the condition is not met the item should not be added.
The only way i could resolve this is by adding a "Execute custom PHP code" action with the code:
<code>drupal_goto('any_path');
</code>
This doesn't look very correct but its the only thing that worked for me.
Comment: this doesn't seem to be very robust solution :)
but it may came in handy

Limit items in shopping cart


Devel query log not showing all queries

Question: I've enabled the Devel query log, and it's logging most queries as expected. However, I've got this module which connects to another database and executes a few queries against that one. All queries goes through db_select(), db_query(), db_insert(), db_delete() or db_update().
However, queries executed against the other database (connection is configured on the fly, and not through the settings.php file) never appears in the query log.
Any way I can make it work, so that ALL queries appear in query log at the bottom of the page?
Note: Caching does not seem to have anything to do with it. I've cleared all caches, returned to the page, and still no queries appear in the query log.
Comment: Interesting question.  Just to rule it out, have you checked if caching has anything to do with this?
Comment: Caching does not seem to have anything to do with it. I've cleared all caches, returned to the page, and still no queries appear in the query log.
Answer: It's because Devel uses the Database::getLog() static method to get a list of the queries that have run for the page.
That method can only be run for a single connection at a time, and Devel specifically requests logs for the 'default' database connection (see devel_shutdown_real()):
$queries = (devel_query_enabled() ? Database::getLog('devel', 'default') : NULL);

In short you've got 2 options that I can think of:

Edit the devel module file directly, forcing it to loop through all available connections and combine the query logs (obviously hacking contrib modules is not recommended though)
Implement your own logic in a custom module and have a second set of query logs appear at the bottom of your page. The devel_shutdown() function and devel_shutdown_real() should give you all the code you need to get started if you go down this route.

Devel query log not showing all queries


Which linux-based firewall?

Question: We are looking to replace our current aging firewall/router with a new one.
We would prefer it to be free/opensource if possible.
Our minimum requirements would be:
<code>1) Site-to-site VPN
2) Web URL/IP filtering
3) 2 WAN connections with load-balancing
4) Easy-to-use web inferface
</code>
Any suggestions? and why you chose yours.
Answer: PFsense is easier solution for you.
you may want to check monowall, ipfire (ipcop with 2.6 kernel) or untangle
but all of them except pfsense has no web gui for multiwan setup.
in fact most of them is not supporting multiwan solutions.
but pfsense has different options for multiwan.
because multiwan is not an easy to setup. it has many restrictions on connection.
here is some sources
http://doc.pfsense.org/index.php/Multi-WAN_Version_1.2.x
(Andrew, this thing is not allowing me to vote up or comment.
that's why i wrote as new answer)
Comment: pfSense has no native web filtering solution, OpenDNS might do the job.
Comment: With plugins. Squid & dansguardian can be installed easily with a few clicks. & all sort of url filter & blacklists like shalla can be applied via plugins. OpenDNS can be a problem when you have too many clients. it has limits to query which can exceeded so fast.
Comment: Ah yes, the joys of the reputation system... +1 for putting in more explanation than I had time for!
Comment: +1 Note, pfSense and M0n0wall are both FreeBSD based, which is not Linux.
Answer: pfSense is what I'm trialling at the moment, based on a similar question I had. It's FreeBSD based but seems to do everything we need (and I think it does everything you want). You can also look at things like Endian Firewall, SmoothWall, eBox Platform, etc.
Answer: Untangle is free and OSS, with premium subscriptions for load balancing and more robust web filtering - http://www.untangle.com - available on 14-day free trials.
Recommended top Content filter by Spiceworks community, too.
Disclaimer: I work for Untangle, so please try it out for yourself, don't take my word for it.
Answer: This sounds like a job for... IPCop!
Seriously, IPCop rawks. It has a massive array of plugins, is easier than falling off a log to use and it even runs off of a CD if you need it to.
Answer: I am not 100% sure about the load balancing, but as a standalone nix solution. I am really like the Endian Community Firewall.
http://www.endian.com/en/community/overview/
Answer: I'd suggest m0n0wall, which is not Linux based, but BSD comes close to it, I think.
I myself use OpenBSD, but m0m0wall is what I suggest for users that need quick setup and a nice interface.

Which linux-based firewall?


diminished chord in degree

Question: I would like to write dowb a jazz grid in "Degree notation" in order to make it "tonality free", but i'm stucked with a problem.
The song is billie's bounce and i don't know how to write the diminished chord after the 4th degree (see picture).
Also i don't know what's the fonction of that chords and what makes it so powerfull on this progression.
Thank you!
Answer: It certainly won't be IVo, as that would make it Bbo. And the same goes for Vo, making it Co. Out of diminished chords, that actually leaves the one for which you search. In F, it's called (here) Bo, but the same notes occur in Io. Often with a dim chord, the four notes can be played in any order. I often see in charts, say, Bo, written as a chord symbol, but with either F, Ab, B (Cb here!) or D written in as the lowest (bass) note. So, I'd go for Io. Jazz players will often choose how they voice chords anyhow, so, although it may be slightly technically inaccurate, the correct notes will come out. Only in a different order...(Eric Morecombe!).
Your 'degree notation' bears a striking resemblance to NNS.
Comment: Have a good look into it. I've used a bastardised version for a good 50 yrs, but don't like certain bits, like '-' for minor. Mainly as in handwritten stuff, it's too easy to miss or worse, see a mark that's not there intentionally! Tend to use lower case for minors. Or simple 'm'.
Comment: I'll go for Io since you're right, the notes are the same =) Thank you

Edit : What is NNS? ^^
Comment: NNS= Nashville Numbering System, where instead of a chord chart in a particular key, songs' accompaniments in chords is written in Roman Numerals, so session musos can simply read the RN, and chord types, and transpose instantly. Something like you're doing!
Comment: Ohh very good, i couldn't put a name on this system, it was just a simple "Scale degree notation" to me =)

I've learned twice much as i was hoping to! Thanks!
Comment: Well, new material to learn \o/ I like it. See you Tim
Comment: Seems like I now have a -15 score for this. But it's not shown here. Glitch?
Comment: @Doktor Mayhem - Perhaps a mod. could reconcile the -15 for this answer. Don't care any more about downvotes - only the reasons given! But here, the sums don't add up ( or even subtract).
Answer: IV#o or Four sharp diminished.  I'd choose that since the letter name indicates degree.  Since Bb is the fourth of F (and you've indicated F and the I) B natural is the sharp fourth rather than a flat fifth.  Of course you could use substitutions to replace the diminished chord with something else.  If these are real book changes as opposed to an original score those are seldom exact (or even correct).
Comment: Of course! This is it =) I've completly forgettent that you could put alterations to the roman number. Now it's all clear. Thank you

diminished chord in degree


Can a std::array be unpacked into a non-type template parameter pack with Boost.Hana?

Question: template<int...>
struct S {};

constexpr auto a = std::array{0, 1, 2};

I would like to unpack the elements of a as template arguments to S. That is; S<0, 1, 2>.
A possible C++2a implementation:
template<auto tuple_like, template<auto...> typename Template>
constexpr decltype(auto) unpack()
{
    constexpr auto size = std::tuple_size_v<decltype(tuple_like)>;
    return []<std::size_t... Is>(std::index_sequence<Is...>) {
        return Template<std::get<Is>(tuple_like)...>{};
    }(std::make_index_sequence<size>{});
}

using Result = decltype(unpack());

Is there an idiomatic way to do this in Boost.Hana?
Answer: I suppose the natural heterogeneous-type Boost.Hana approach is to lift the std::array elements into a hana::tuple of hana::integral_constants and also lift the class template to a metafunction:
template<int...>
struct S {};

using namespace boost::hana::literals;
constexpr auto a = boost::hana::make_tuple(0_c, 1_c, 2_c);

template<template<auto...> typename Template>
constexpr auto lift_non_type_template = []<typename... Ts>(Ts...) {
    return boost::hana::type_c<Template<Ts::value...>>;
};

using Result = decltype(boost::hana::unpack(a, lift_non_type_template<S>))::type;


Finding a fit using power function with integer coefficient

Question: Problem:
Consider fitting the following data (y-values):
$$ 16, 60, 180, 400, 700, 1200, 2000, 3000, 4300, 6000, 8000, 10500$$
where the x-values range from 1 to 12
into the following model:
$$
y = \alpha + \beta x^\gamma
$$
where $\alpha,\beta \in \mathbb{N}$ and $\gamma \in \mathbb{R}$.
The integral constraints may be relaxed. Exponential model may be considered.

Attempts and Questions:
I've tried:

Building the model in Geogebra and fiddling around with the parameters.
Using Wolfram Alpha, applying power fit, and exponential fit directly on the data. Wolfram uses least-squares best fit. The integral constraints were not satisfied.
Linearise the model based on Ian Miller's answer using Excel with $\beta = 11.05077$ and $\gamma = 2.6908$.

What would be a general way to approach this sort of problem?
Ignoring $\alpha$, is my model equivalent to the one used in wolfram? (confusion on my part, addressed)
Should I minimise the error using percentage (relative error) instead of traditional squared difference? $10500 \pm 200$ shold be more tolerable compared to $16 \pm 200$, for instance.

Here are the results:
$$
\begin{array}{cc|cccc}
& & \text{Geogebra} & \text{Wolfram (power)} & \text{Wolfram (exponential)} & \text{Linearisation} \\
x & y & 4x^{3.17} & 4.88906x^{3.08717} & 198.887e^{0.33343x} & 11.05077x^{2.6908}\\
\hline
1 & 16 & 6 & 4.88906 & 277.596 & 11.05077\\
2 & 60 & 48 & 41.5486 & 387.4539 & 71.35166\\
3 & 180 & 162 & 145.271 & 540.7877 & 212.4371\\
4 & 400 & 384 & 353.091 & 754.803 & 460.6971915\\
5 & 700 & 750 & 703.177 & 1053.514 & 839.81\\
6 & 1200 & 1296 & 1234.56 & 1470.44 & 1371.646\\
7 & 2000 & 2058 & 1986.95 & 2052.362 & 2076.741\\
8 & 3000 & 3072 & 3000.67 & 2864.579 & 2974.59\\
9 & 4300 & 4374 & 4316.52 & 3998.229 & 4083.836\\
10 & 6000 & 6000 & 5975.79 & 5580.518 & 5422.412\\
11 & 8000 & 7986 & 8020.13 & 7788.993 & 7007.643\\
12 & 10500 & 10368 & 10491.6 & 10871.47 & 8856.323\\
\end{array}
$$
Comment: Is the first value for $x=0$ or for $x=1$? In geogebra you use $x=0$ but with excel you use $x=1$
Comment: I forgot I added an extra (x,y) = (0,0) in geogebra for the origin, the other pairs remained the same though, and the last data point in geogebra is the (12, 10500). I will reflect this in the question to make it clear, thanks :)
 I forgot to mention, so, yes, this means y can be anything at x=0.
Comment: The point $(0,0)$ implies that $\alpha=0$ which might not be the case. You are leading the model by adding this point.
Comment: Fair point (pun unintended). The geogebra file did not fix the model based on any of the points though, they only serve as a visual cue to get a general idea of the fitness and I simply play around with the parameters using the sliders. I've been ignoring it all this time. I will remove that point so there's no more confusion.
Comment: @sllnJin This question has blown out a lot since you originally asked it. I suggest you attempt to refocus it to a specific thing. Are you interesting in investigating/learning about techniques or are you wanting to find the best fit for you data?
Comment: I didn't think it would grow this big because I didn't know how big the subject was. During the course of discussing this, I also learned enough about the subject to realise that it wasn't so much as data fitting that I was interested in, but it was the model building. I was interested in figuring out if my model is right, and if not, how should I go about reverse engineering it. The only reason why I chose the model I described was because it was used to generate other data; the only lead I had. I agree with your remark that this is getting out of control. I will try to clean up the question.
Comment: (exceeding character limit, continuing) However, I also found out that by reflecting this change, I cannot keep all of the existing answers relevant. Would the best option be to start a new, slightly related question for model building (if necessary after my own research on it) and accept one of the answers here according to the spirit of the original question about data fitting? I will, of course, try to edit the question to make it better while keeping the focus as is if this option is taken.
Answer: Mathematica provides a NonlinearModelFit function. Using this on your data gives as best fit $y=23.0164 + 4.65795\,x^{3.10605}$. Unfortunately integer constraints are not accepted. However, the best fit suggests taking $\alpha=23$, $\beta=5$. This gives $y=23 + 5\,x^{3.07641}$. The residuals are
$$
{-12., -5.17575, 10.1776, 21.2413, -29.7907, -61.4688, -12.945,
-23.8777, -34.3632, 15.1153, -16.272, 30.331}
$$
Comment: This method gives a really good fit. I do not have access to Mathematica, however, and being able to solve this kind of problem beyond the 15-day trial periods is essential. I'm taking a look at the [documentation for NonlinearModelFit method](https://reference.wolfram.com/language/ref/NonlinearModelFit.html) and was wondering if it would be equivalent to this [Nonlinear least squares section](https://cran.r-project.org/doc/manuals/r-release/R-intro.html#Nonlinear-least-squares-and-maximum-likelihood-models) I just found in the R manual since I do have access to R.
Comment: Yes, I think it uses non linear least squares.
Comment: Another thing you could try is "guess" a good value for $\alpha$ (it seems reasonable of start with $\alpha=16$),  use a power model and choose $\beta$ to be the closest integer to the parameter four. This implies repeating the process for different values of $\alpha$.
Comment: I've been trying to play around with different values for the parameters for a bit. Is there a more intelligent and systematic way of adjusting the values based on what the current one yields? For example, if the current parameters give a curve that _under_estimates earlier values, but _over_estimates later values, then we should adjust $\gamma$ to make it "bend" less, and then we may have to bring $\beta$ up a bit to push everything up since we bent down slightly too much, and so on and so forth. The model should be able to inform us of these behaviours, right?
Comment: What you say seems reasonable, but I really can't tell. Moreover, $\alpha$ and $\beta$ are integers, so you cannot push them a little bit.
Comment: @JuliánAguirre. It is a funny problem, indeed ! If you have time to waste, have a look at my answer and, please, comment.
Answer: Note: Your model is a power model, e.g. $x$ is raised to a power. This is very different to a exponential model from Wolfram which has $x$ in the exponent position. There are many possible models you can attempt to fit your data to. Which one to pick will depend on the shape of the data and the physics behind what is generating the data - sometimes you know or suspect a certain link between the data.
This also depends what you mean by best fit. Wolfram probably has used a least squares fit. What you are describing is trying to minimize the percentage error (probably with a least squares approach). As such you will get two different results.
A lot of software packages will actually end up minimizing something other than the least squares fit as they will linearize the data based on the model then find the linear equation of best fit before converting the coefficients from that back to the chosen model. For example a standard exponential model of the form: $y=\alpha e^{\beta x}$ can be rewriten as $\ln y=\ln\alpha+\beta x$. If you plot $x$ vs $\ln y$ you will get a straight line with gradient of $\beta$ and intercept of $\ln\alpha$.
Your model however can not be linearized. Using three parameters prevents this (as far as I know). From your picture it appears you have set $\alpha$ to zero so if we do that your model can be linearized as follows:
$y=\beta x^\gamma$
$\ln y = \ln\beta + \gamma\ln x$
So if you take your data and make two new columns: $\ln y$ and $\ln x$ they should fit a straight line with gradient of $\gamma$ and intercept of $\ln\beta$. This will not minimize the sum of least squares but will minimize the sum of least squares of the logarithms of the values which might look more like what you were after. Again best fit can be somewhat subjective.
UPDATE:
I've taken your table and looked at the sum of the least squares for both models and the the linearized model is better that the Wolfram one using the least squares of the logarithm as the metric for 'best fit'.
($y_m$ is from the linearized model and $y_w$ is from the Wolfram model)
$$
\begin{array}{c|c|cc}
& y & \ln x & \ln y & y_m & y_w & \ln y_m & \ln y_w & \ln y_m - \ln y & \ln y_w - \ln y & (\ln y_m - \ln y)^2 & (\ln y_w - \ln y)^2 \\
\hline
 & y & ln x & ln y & y_m & y_w & ln y_m & ln y_w & ln y_m - ln y & ln y_w - ln y & (ln y_m - ln y)^2 & (ln y_w - ln y)^2 \\
 & 16 & 0 & 2.77259 & 11.05062 & 4.88906 & 2.40249 & 1.587 & -0.3701 & -1.18559 & 0.13698 & 1.40562 \\
 & 60 & 0.69315 & 4.09434 & 71.35208 & 41.54858 & 4.26763 & 3.72686 & 0.17328 & -0.36748 & 0.03003 & 0.13504 \\
 & 180 & 1.09861 & 5.19296 & 212.44079 & 145.27129 & 5.35866 & 4.9786 & 0.16571 & -0.21435 & 0.02746 & 0.04595 \\
 & 400 & 1.38629 & 5.99146 & 460.70883 & 353.09121 & 6.13277 & 5.86673 & 0.1413 & -0.12474 & 0.01997 & 0.01556 \\
 & 700 & 1.60944 & 6.55108 & 839.83639 & 703.1769 & 6.73321 & 6.55561 & 0.18213 & 0.00453 & 0.03317 & 0.00002 \\
 & 1200 & 1.79176 & 7.09008 & 1371.69573 & 1234.55534 & 7.2238 & 7.11847 & 0.13373 & 0.02839 & 0.01788 & 0.00081 \\
 & 2000 & 1.94591 & 7.6009 & 2076.82579 & 1986.94883 & 7.6386 & 7.59436 & 0.03769 & -0.00655 & 0.00142 & 0.00004 \\
 & 3000 & 2.07944 & 8.00637 & 2974.72218 & 3000.66617 & 7.99791 & 8.00659 & -0.00846 & 0.00022 & 0.00007 & 0 \\
 & 4300 & 2.19722 & 8.36637 & 4084.0311 & 4316.52455 & 8.31484 & 8.37021 & -0.05153 & 0.00384 & 0.00266 & 0.00001 \\
 & 6000 & 2.30259 & 8.69951 & 5422.68738 & 5975.79055 & 8.59835 & 8.69547 & -0.10117 & -0.00404 & 0.01023 & 0.00002 \\
 & 8000 & 2.3979 & 8.9872 & 7008.01714 & 8020.13397 & 8.85481 & 8.98971 & -0.13239 & 0.00251 & 0.01753 & 0.00001 \\
 & 10500 & 2.48491 & 9.25913 & 8856.81688 & 10491.59058 & 9.08894 & 9.25833 & -0.17019 & -0.0008 & 0.02896 & 0 \\
 &  &  &  &  &  &  &  &  & \Sigma: & 0.32635 & 1.60308 \\
 \end{array}
$$
Comment: @sllnJin I had made a critical typo in my original answer (and then carried it through). The slope of the linearized equation should be $\color{red}{\ln}\beta$ not just $\beta$. I've updated the table since and by that metric the linearized model is better.
Comment: So we are basically transforming the data into a linear model _using_ the assumption that we have about the model of the original data, then we find line of best fit for this linear model, which should now be a lot easier, then transform everything back! Ok, I'm fiddling around using this idea and will be updating the question, but I can't seem to obtain a good result from this yet :/
Comment: It seems I was brain-dead when working on this thinking that $x^\gamma$ is exponential and so I got confused when I saw the actual exponential function and still didn't realise it until you pointed it out. When I put _power_ instead of _exponential_ into [wolfram](http://www.wolframalpha.com/input/?i=16+60+180+400+700+1200+2000+3000+4300+6000+8000+10500+fit+power), I did get results really close to what [Julián Aguirre](http://math.stackexchange.com/a/1498481/202136) has done.
Not quite sure how I should reflect this realisation on the questions.
Comment: @Update Looking at the sum of least squares of differences of logarithms alone and I would not gather that $y_m$ is this far off compared to $y_w$. Most of the $y_m$ values were off by an order of magnitude. I can't help but doubt that I have done something wrong for the $y_m$. Am I right to assume a perfect fit isn't possible unless we overfit it or find the correct model? This goes back to your first point about understanding the characteristics of the data itself.
Comment: I would like to learn a bit more about your first paragraph. Is there any introductory resource(s) you could point me to? Your inputs have been very educational.
Answer: I have been doing almost the same as Julián Aguirre did. Using $\alpha,\beta \in \mathbb{N}$ and $\gamma \in \mathbb{R}$ as yo you wished, I varied parameters $\alpha,\beta$ (running the calculation over a quite large grid o values) until I get a minimum value of the sum of squares.
It appears that, whatever $\alpha$ could be, $\beta=5$ always leads to the minimum value of the sum of squares. For this value of $\beta$, the following table gives the sum of squares as a function of $\alpha$ in the area of the minimum of $SSQ$.
$$\left(
\begin{array}{cc}
\alpha & SSQ \\
 0 & 6988 \\
 1 & 6908 \\
 2 & 6842 \\
 3 & 6790 \\
 4 & 6752 \\
 5 & 6729 \\
 6 & 6719 \\
 7 & 6724 \\
 8 & 6743 \\
 9 & 6776
\end{array}
\right)$$
while $\alpha=23$ would lead to $SSQ=8723$.
For the optimum value $(\alpha=6)$, rounded to next integer, the predicted values are $$\{11,48,153,362,714,1247,2000,3013,4327,5982,8019,10479\}$$ the residuals being $$\{5,12,27,38,-14,-47,0,-13,-27,18,-19,21\}$$ and the model is $$y=6+5 \,x^{3.07743}$$
Comment: This fits extremely well while also respecting the integral constraints.


Paired t-test with redundant data

Question: As part of my work I've gathered biological data for a set of (n=3) mice under two conditions ~ treatment and control. Since there is some inherent variability in behavioral research, I collected data from each mouse under both treatment and control on multiple occasions.
For example, consider I'm looking at total distance traveled x. Mouse #A will have a set of data that looks like this:
Mouse #A: xT1, xT2, xT3, xC1, xC2, xC3
Here, the subscripts T and C represent treatment/control, respectively, while the numbers indicate that there's multiple data of each category.
My aim is to test whether there's a statistical difference in x across the two conditions, which inherently brings me to the paired t-test. However, for a paired t-test, one only needs a single pair of values (xT,xC) for each mouse. I wanted to know if there's a way to perform the paired t-test when there's multiple values for each condition.
To elucidate: each of the three mice has three xT and xC collected. There is some variance in xT1-3 and xC1-3 for each mouse.
Right now, I only see two solutions to my dilemma. 1) I choose a random xT and xC for each mouse to perform the test. 2) I average xT1-3 and xC1-3 for each mouse and use the averages to perform the test.
Of course, I think the second option has more merit, although I do not know if it is the right way to handle this scenario, or if there's a better way. I am not statistically inclined. Either way, both options make it so that I reduce the input of the paired t-test from 18 datapoints (6 per mouse) to 6 data points (2 per mouse). I do not find this appealing as it will just artificially drive my p-value up (is this a bad way to think about it?).
What I'm curious to know is if there's a way I could do a paired t-test that includes all 18 data points? Of course, I could pair (xT1, xC1), (xT2, xC2), and (xT3, xC3) together and just add them all to the pile. But then I have 3 pairs of pairs that are nondistinct, as they come from the same mouse. Also, the pairing outlined above is purely arbitrary, as it would make no difference whether xT1 gets paired with xC1,xC2, or xC3.
Please let me know what you think! My only option so far is to go with plan (2) mentioned above, but I do not know if it is the correct way or if there's a better way!
Answer: I think you're looking at a mixed effects model where the random effect is the mouse ID, and the fixed effect is the binary control/treatment status. Your response variable will be the difference: for example $d_{i1} = x_{i1C} - x_{i1T}$ for mouse $i$. The random effect captures the variance from repeated measures on the same mouse.
I am assuming that the first control measurement is actually paired with the first treatment measurement. Not sure if this is actually the case - if there isn't an actual pairing, then the response would just the the $x$ variable rather than the difference.
Comment: Thanks for your input Alex! I've been going back and forth whether to consider the first treatment paired with the first control or not. Certainly, the two data points were obtained closer together than the second pair of treatment/control, so there's a temporal argument to be made. It might be a good idea to do so, as there are certain temporal variables that may be confounding (such as temperature and the animal's circadian rhythm)
Comment: I don't know much about biology, but if you can account for those temporal variables, then certainly go for it!
Answer: I simply wanted to respond to Alex's answer about implementing a mixed-effects model by showing how it can be done using the statsmodel package in python (because I don't really use R or MATLAB). This is my sample code with random data...
<code>import pandas as pd
import statsmodels.api as sm
from statsmodels.regression.mixed_linear_model import MixedLM

# Create a pandas DataFrame with your data
data = pd.DataFrame({
    'Mouse': ['Mouse 836'] * 6 + ['Mouse 837'] * 6 + ['Mouse 897'] * 6,
    'Condition': ['Control'] * 3 + ['Treatment'] * 3 + ['Control'] * 3 + ['Treatment'] * 3 + ['Control'] * 3 + ['Treatment'] * 3,
    'Distance': [10, 12, 15, 8, 9, 11, 14, 16, 13, 7, 6, 9, 11, 13, 10, 12, 14, 15]
})

data.head(18)

# Define the mixed effects model formula
formula = "Distance ~ Condition"

# Fit the mixed effects model
mixed_model = MixedLM.from_formula(formula, data=data, groups=data["Mouse"])
result = mixed_model.fit()

# Print the summary of the model
print(result.summary())
</code>
I still welcome any additional responses/perspectives. I will be reading more on the mixed-effects model and see exactly how to interpret the result for my own data. Thanks again!

Paired t-test with redundant data


How to convert a sub collection to list with flutter and firestore?

Question: I have an object Dish who containes a list of ingredients and I want to get them. How can I do?
In Firebase, Dish is a Document and Ingredient is a sub collection. I tried this but it doesn't work.
class Dish{

  String name;
  DocumentReference reference;
  List<Ingredient> ingredients;

  Dish.fromMap(Map<String, dynamic> map, {this.reference}){
    this.name = map['name'];

    this
        .reference
        .collection("ingredients")
        .snapshots()
        .listen((QuerySnapshot snap) {
      final List<DocumentSnapshot> ingredientsDocuments = snap.documents;
      List<Ingredient> ing = [];
      for (var i = 0; i < ingredientsDocuments.length; i++) {
        ing.add(Ingredient.fromSnapshot(ingredientsDocuments[i]));
      }
      this.ingredients = ing;
    });
  }

  Dish.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Dish<$String>";

}

class Ingredient{
  final String name;
  final DocumentReference reference;

  Ingredient.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        name = map['name'];

  Ingredient.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Ingredient<$String>";
}

Comment: please check https://stackoverflow.com/a/50867881/2863386, please comment if it doesn't works
Answer: How are you trying to fetch data from Firestore using Dish class? Were you using any asynchronous task(i.e. Future)? What's not working in your implementation? Any errors that you received?
Since I'm unable to run the repro you've provided, here's a sample code that you can try.
List<Ingredient> ingredients;
// call getDocuments() to fetch data from Firestore and add it to the List
Future<void> getDocuments() async {
  ingredients = List();

  var collection = FirebaseFirestore.instance
      .collection('ingredients');

  collection.get().then((value) {
    value.docs.forEach((element) {
      setState(() {
        // add the object to the List
        ingredients.add(Ingredient(Ingredient.fromMap(element.data())));
      });
    });
  });
}

As for the Object, it can be as simple as this. No need to pass DocumentReference since we'll only be using it to map the data to the Object and be able to add it in the List.
class Ingredients {
  var name;

  Ingredients(Ingredients document) {
    this.documentName = document.getName();
  }

  dynamic getName() => name;

  Ingredients.fromMap(Map<dynamic, dynamic> document)
      : name = document['name'];
}

You can check a working sample I've posted in here. It has pagination added, but it should have a similar approach with the code snippets I've shared here.


R: How to create a basic x,y plot (2 vars) with repeated points having a different color (~heatmap)

Question: This plot:
plot(Data$grade, Data$absences)
produces the plot I need, except I need to be able to identify the repeated values.
Absences ranges from 0 to 19.  Grade ranges from 0 to 10 (integers).
There are 320 students.
For example, a grade of 7 with absences of 0 has 84 repeats.
I would like a scaled heat map, where the color of a point starts at light blue (1 data point) and scales up to dark blue (>70), with 7 steps. (Approximately.) Heat mapped points of different colors could also work.
Answer: There probably is a specific function to build a heatmap, but you can count the number of unique rows in your df (with dplyr) and use that count as the alpha (transparency) parameter on ggplot2:
library(ggplot2)
library(dplyr)

df = data.frame( # Creating some dummy data
  Grades = sample(0:10, 10000, TRUE),
  Abscences = sample(0:19, 10000, TRUE))

df = df %>% group_by_all() %>% summarise(COUNT = n())

ggplot(df, aes(y=Grades, x=Abscences, alpha=COUNT)) +
  geom_point(color="darkblue", size=5, shape="square")

Output:
Comment: I like your original version better.  I want a plot, with independent points, which is what that give me.  Thanks.
Comment: Thanks.  That's working.
Comment: Did some research and found that `geom_tile` is better. Try `ggplot(df, aes(y=Grades, x=Abscences, fill=COUNT)) +  geom_tile()`


discrete differences, doubt about sign

Question: Let $G\in C(\mathbb R)$ then
$\lim_{N\to +\infty}\frac{G(x-\frac{1}{N})-G(x)}{-\frac{1}{N}}=G'(x)$?
I have a doubt about the sign in front of $G'$, it is a $+$ or a $-$?
Thanks to everyone
Answer: The definition of the derivative is usually stated as:
$$
G'(x) = \lim \limits_{h \rightarrow 0} \frac{G(x+h)-G(x)}{h}
$$
If we replace $h$ by $-\frac{1}{N}$, we get the expression in your question. So, the sign in front of $G'$ is indeed positive.

discrete differences, doubt about sign


Best method of statistical analysis for large dataset of different points

Question: I have generated a set of ground displacements at certain points using two different methods. I am now trying to find a good method of statistical analysis to compare how similar the results of the two methods are.
I only have two measurements for each point but I have over 1 million different points. Is there a method of analysis that I can use to compare the similarity of the displacement generated by both of the methods at each of the different points which will then allow me to calculate the similarity of the overall data set?
Answer: It sounds like a natural method to analyze your data would be a paired t-test.  For each point, you compute the difference $d_i$ between the two measurements, $d_i=x_{i1}-x_{i2}$ where $x_{i1}$ is the measurement using method 1 and $x_{i2}$ is the measurement using method 2.  Once you have your 1 million $d_i$'s, you could perform a one sample t-test on the $d_i$'s to see if they are statistically significant from zero (which is almost guaranteed since you have 1 million pairs of points).  You could also construct a confidence interval to estimate the mean difference between the two methods.  Without more context, it's hard to know what kind of similarity measure would be useful.  Perhaps there are magnitudes of discrepancies between the two measurements that would be meaningful?  In such a case, it could be interesting to report what proportion of differences are within an interesting absolute range or perhaps measurements that are within some relative percent of the other.  You could also report summary measures as simple as what proportion of the time the difference is positive.
Other potentially interesting methods of analysis would be to regress the measurements from method 2 on method 1 to explore the shape of the relationship.  Things to look for could that would be relevant include a non-linear relationship or heteroskedasticity.  If the relationship appears linear, the correlation could be a nice summary measure of how strongly correlated the two measurements are.


What is the effect of stale ARP cache entry on traffic to that DIP till the entry ages out of the ARP table?

Question: If the host, for which an ARP table entry is present on the connected router, has changed its NIC(so that its MAC address has changed), what will happen when a packet is sent out on the link with the old MAC address by the router?
Will any kind of error message(like ICMP) be generated at layer2/3? If yes, what will be its SIP and DIP?
Comment: Matches between MAC and IP are stores in the ARP cache. Unless you manually created a static entry these will time out. The time out period depends on your OS. (For modern windows installs this takes about 30 seconds according to http://support.microsoft.com/kb/949589 ).

So nothing abnormal will happen if you can wait a short period after changing the NIC.

(Not posted as an answer since I do not actually know what will happen if you do try this before the time out. I suspect it will depend on the operating systems involved. Or more precisely, on the used TCP/IP stack).
Answer: Nothing will happen, the packet will be "lost", and time-out.
Depending on the implementation, the router will then try with arp again, get the new mac and then send the next* packet to the new address.
*with tcp, the lost packets will be retransmitted, with udp, it depends on the higher protocol (l7) - usually not


Soft high pitched sound

Question: Hi all i'm fresh here and this is my first post on this website.
My name is mirko and i hope this is the right place to post this
i have this problem here and i was hopiung to get an answer so if it happens again i can fix it with your help , i will put the viedeo right here so you can listen :

The hiss goes away when I touch the metal part of my cable but the problem it's not permanent I mean for a period of time I have not this hiss and some time after it comes back
Comment: are these "solderless" cables? I did a quick check and the first hit for a non-kit version of a planet waves switchable cable was solderless. Bad connections might be a source of signal ingress.
Answer: It sounds to me like a grounding problem in one of your pieces of equipment but the sound is unusually high pitched for this. It can sometimes come naturally in a guitar when not touching the strings or any metal part, the hiss should disappear when touching almost any metal part of your guitar or amp. Does this only happen when recording? If not:

Does the hissing stop when touching any metal part of the guitar?
Does the hissing stop when touching any metal part of the amp?
Does the hissing stop when touching any metal part of the lead?
The piece of equipment where the hissing doesn't stop touching most of its metal parts may need to be seen by a technician to be fixed.
Check your guitar for bad grounding, either a ground loop or loose wire.
Check your amp for dodgy grounding, either a ground loop or loose wire.

If this is not the problem, it could be a problem of outer emf. This would explain why it only happens at certain times. Is there an electrical thing always turned on when this hissing happens? (Usually high voltage) Try turning all electrical things in your house off (except guitar and amp) including lights and see if the hissing stops. If you are in an apartment, try take your equipment to another persons house and see if the hissing stops. Try to open up the back panel on your guitar, do you see some kind of paint that is around the wood in the electrical section? The paint that may be there is called shielding paint. If this paint isn't there you may have to get a technician to add shielding paint to the insides of your guitar (you could try do this yourself if you want, google shielding paint for guitar).
As a last resort, try to swap around equipment to find the problem. Use a different lead, use a different amp, use a different guitar. If these don't offer a solution, I'm hoping someone with more experience in electronics may know the answer. I know most of this knowledge by the internet, not large amounts of experience so I can't be certain. Try asking on electricalengineering.stackexchange.
Hope this helps. Good Luck. :)
Comment: I forgot to mention (maybe) that the hiss doesent exist when I don't plug any cable in my amp. And when I plug a cable and bring it close to the the back of the amp where the power supply is and the speaker cable or another metal part it stops and become quiet
Answer: Make sure your cables are "balanced" (meaning they have a ground). Any jacks should have two components for mono and three for stereo. They'll be divided by a strip of rubber on the jack.
Also make sure you're running into balanced TRS or XLR ports in addition to using balanced cables.
Comment: This is reasonable advice for vocal & keyboard signal chains, but it will not help electric guitarists, who exclusively use unbalanced cables – the equipment simply does not have TRS or XLR ports, except for DI units designed for plugging into a mixer.

Soft high pitched sound


Gridview row editing - dynamic binding to a DropDownList

Question: I'm trying to get an ASP.NET 3.5 GridView to show a selected value as string when being displayed, and to show a DropDownList to allow me to pick a value from a given list of options when being edited. Seems simple enough?
My gridview looks like this (simplified):
<asp:GridView ID="grvSecondaryLocations" runat="server"
              DataKeyNames="ID" OnInit="grvSecondaryLocations_Init"
              OnRowCommand="grvSecondaryLocations_RowCommand"
              OnRowCancelingEdit="grvSecondaryLocations_RowCancelingEdit"
              OnRowDeleting="grvSecondaryLocations_RowDeleting"
              OnRowEditing="grvSecondaryLocations_RowEditing"
              OnRowUpdating="grvSecondaryLocations_RowUpdating"  >
<Columns>
    <asp:TemplateField>
         <ItemTemplate>
              <asp:Label ID="lblPbxTypeCaption" runat="server"
                                 Text='<%# Eval("PBXTypeCaptionValue") %>' />
         </ItemTemplate>
         <EditItemTemplate>
                      <asp:DropDownList ID="ddlPBXTypeNS" runat="server"
                               Width="200px"
                               DataTextField="CaptionValue"
                               DataValueField="OID" />
         </EditItemTemplate>
    </asp:TemplateField>
</asp:GridView>

The grid gets displayed OK when not in editing mode - the selected PBX type shows its value in the asp:Label control. No surprise there.
I load the list of values for the DropDownList into a local member called _pbxTypes in the OnLoad event of the form. I verified this - it works, the values are there.
Now my challenge is: when the grid goes into editing mode for a particular row, I need to bind the list of PBX's stored in _pbxTypes.
Simple enough, I thought - just grab the drop down list object in the RowEditing event and attach the list:
protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
    grvSecondaryLocations.EditIndex = e.NewEditIndex;

    GridViewRow editingRow = grvSecondaryLocations.Rows[e.NewEditIndex];

    DropDownList ddlPbx = (editingRow.FindControl("ddlPBXTypeNS") as DropDownList);
    if (ddlPbx != null)
    {
        ddlPbx.DataSource = _pbxTypes;
        ddlPbx.DataBind();
    }

    .... (more stuff)
}

Trouble is - I never get anything back from the FindControl call - seems like the ddlPBXTypeNS doesn't exist (or can't be found).
What am I missing?? Must be something really stupid.... but so far, all my Googling, reading up on GridView controls, and asking buddies hasn't helped.
Who can spot the missing link? ;-)
Answer: Quite easy... You're doing it wrong, because by that event the control is not there:
protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow &&
        (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
    {
        // Here you will get the Control you need like:
        DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
    }
}

That is, it will only be valid for a DataRow (the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.
Comment: Tricky.... I get this event, but the RowState is "Alternate | Edit" - so your IF never is true :-)
Comment: OK, I changed your if to check for the "Edit" bit being set (ignoring any other bits that might be set) and now it works like a charm! Thanks a heap!!
Comment: I actually changed it to :

`(e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit`

in order to just filter out the "Edit" flag regardless of any other flags that might be set
Comment: there are so many ways to accomplish the same :) but I prefer your idea, it's cleaner! ... edited ;)
Comment: balexandre your answer is great! really help me to fix a similar problem http://stackoverflow.com/questions/5169538/gridview-take-a-row looking on the net i could not find any good sample of code like your!
Comment: Glad i could assist you. Nothing is hard when you know how :D
Comment: should it really be this complicated?  I'm just annoyed I didn't find this solution *before* trying to figure it out for 2 hours
Answer: protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)
{
    grvSecondaryLocations.EditIndex = e.NewEditIndex;

    DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
    if (ddlPbx != null)
    {
        ddlPbx.DataSource = _pbxTypes;
        ddlPbx.DataBind();
    }

    .... (more stuff)
}

Answer: I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:
protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    // This stmt is used to execute the code only in case of edit
    if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
    {
        ((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
        ((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
    }
}

Comment: balexandre ... i hav already mentioned its NOT a gridview ... this was just an FYI not a soln ... it will be better if u guys learn to give -ve points to 'incorrect answers' rather than 'other solns or fyis'
Comment: it's not a List is a gridView!
Comment: exactly - and I really don't want to change it just to get it to work, if ever possible..... thanks anyway!
Answer: You can use SelectedValue:
<EditItemTemplate>
    <asp:DropDownList ID="ddlPBXTypeNS"
                      runat="server"
                      Width="200px"
                      DataSourceID="YDS"
                      DataTextField="CaptionValue"
                      DataValueField="OID"
                      SelectedValue='<%# Bind("YourForeignKey") %>' />
    <asp:YourDataSource ID="YDS" ...../>
</EditItemTemplate>

Comment: This is clean and simple. Worked for me.
Answer: The checked answer from balexandre works great.  But, it will create a problem if adapted to some other situations.
I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.
When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database.  (There's an ObjectDataSource attached to the GridView.)
The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:
protected void gv_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            // Here you will get the Control you need like:
            ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
            ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
        }
    }
}

Answer:  <asp:GridView ID="GridView1" runat="server" PageSize="2" AutoGenerateColumns="false"
            AllowPaging="true" BackColor="White" BorderColor="#CC9966" BorderStyle="None"
            BorderWidth="1px" CellPadding="4" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating"
            OnPageIndexChanging="GridView1_PageIndexChanging" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowDeleting="GridView1_RowDeleting">
            <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
            <RowStyle BackColor="White" ForeColor="#330099" />
            <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
            <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
            <Columns>
            <asp:TemplateField HeaderText="SerialNo">
            <ItemTemplate>
            <%# Container .DataItemIndex+1 %>.&nbsp
            </ItemTemplate>
            </asp:TemplateField>
                <asp:TemplateField HeaderText="RollNo">
                    <ItemTemplate>
                        <%--<asp:Label ID="lblrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtrollno" runat="server" Text='<%#Eval ("RollNo")%>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="SName">
                    <ItemTemplate>
                    <%--<asp:Label ID="lblsname" runat="server" Text='<%#Eval("SName")%>'></asp:Label>--%>
                        <asp:TextBox ID="txtsname" runat="server" Text='<%#Eval("SName")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="C">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblc" runat="server" Text='<%#Eval ("C") %>'></asp:Label>--%>
                        <asp:TextBox ID="txtc" runat="server" Text='<%#Eval ("C") %>'></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Cpp">
                    <ItemTemplate>
                    <%-- <asp:Label ID="lblcpp" runat="server" Text='<%#Eval ("Cpp")%>'></asp:Label>--%>
                       <asp:TextBox ID="txtcpp" runat="server" Text='<%#Eval ("Cpp")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Java">
                    <ItemTemplate>
                       <%--  <asp:Label ID="lbljava" runat="server" Text='<%#Eval ("Java")%>'> </asp:Label>--%>
                        <asp:TextBox ID="txtjava" runat="server" Text='<%#Eval ("Java")%>'> </asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit" ShowHeader="False">
                    <EditItemTemplate>
                        <asp:LinkButton ID="lnkbtnUpdate" runat="server" CausesValidation="true" Text="Update"
                            CommandName="Update"></asp:LinkButton>
                        <asp:LinkButton ID="lnkbtnCancel" runat="server" CausesValidation="false" Text="Cancel"
                            CommandName="Cancel"></asp:LinkButton>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:LinkButton ID="btnEdit" runat="server" CausesValidation="false" CommandName="Edit"
                            Text="Edit"></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField HeaderText="Delete" ShowDeleteButton="True" ShowHeader="True" />
                <asp:CommandField HeaderText="Select" ShowSelectButton="True" ShowHeader="True" />
            </Columns>
        </asp:GridView>

                    <asp:Label ID="lblrollno" runat="server" Text="RollNo"></asp:Label>
                    <asp:TextBox ID="txtrollno" runat="server"></asp:TextBox>

                    <asp:Label ID="lblsname" runat="server" Text="SName"></asp:Label>
                    <asp:TextBox ID="txtsname" runat="server"></asp:TextBox>

                    <asp:Label ID="lblc" runat="server" Text="C"></asp:Label>
                    <asp:TextBox ID="txtc" runat="server"></asp:TextBox>

                    <asp:Label ID="lblcpp" runat="server" Text="Cpp"></asp:Label>
                    <asp:TextBox ID="txtcpp" runat="server"></asp:TextBox>

                    <asp:Label ID="lbljava" runat="server" Text="Java"></asp:Label>
                    <asp:TextBox ID="txtjava" runat="server"></asp:TextBox>

                    <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click" />
                    <asp:Button ID="Reset" runat="server" Text="Reset" OnClick="Reset_Click" />

Comment: Welcome to StackOverflow: if you post code, XML or data samples, **please** highlight those lines in the text editor and click on the "code samples" button ( `{  }` ) on the editor toolbar to nicely format and syntax highlight it!


Percorrendo array de objetos

Question: Boa noite.
Tenho um array de um objeto e gostaria de pegar dois valores:
object(OrgaosJurisdicionais)[17]
  protected 'data' =>
    array (size=3)
      'id' => string '3' (length=1)
      'nome' => string 'Tribunal de Justiça do Estado do Pernambuco' (length=44)
      'sigla' => string 'TJPE' (length=4)
  protected 'vdata' => null
  protected 'attributes' =>
    array (size=2)
      0 => string 'nome' (length=4)
      1 => string 'sigla' (length=5)

Como faço para pegar apenas o ID e o NOME desse array?
Usei o foreach abaixo mais não retornou valor algum:
foreach ($unidades as $keys => $unidade)
        {
            echo $keys.' - '.$unidade->nome;
        }

Comment: Você precisa dos dados em `data`, que é um campo `protected`. Você possui algum método público na classe `OrgaosJurisdicionais` que te permite acessar esse valor?
Answer: Acredito que sua variável unidades é um array de objetos OrgaosJurisdicionais, esse objeto possui um atributo chamado data e é uma array que contém os dados id e nome, então pra pegar o valor id por exemplo, tem que acessar o atributo data e posteriormente a chave id.
<?php
foreach ($unidades as $keys => $unidade) {
    echo $unidade->data['id'] . ' - ' . $unidade->data['nome'];
}

Comment: Único problema é que `data` é um campo `protected` do objeto e você não conseguirá acessá-lo assim.
Answer: Você consegue extrair todos os valores com array_map
$valores[] = array_map(function($obj) {
    return array($obj->data['id'], $obj->data['name']);
}, $unidades);

Comment: Único problema é que `data` é um campo `protected` do objeto e você não conseguirá acessá-lo assim.
Comment: Sim, acho que precisará chamar um método que retorne isso ao invés de acessar diretamente o atributo `protected`.
Answer: Consegui resolver simplesmente com:
echo $unidade->id.' - '.$unidade->nome.'
';

em vez de
echo $keys.' - '.$unidade->nome;

ficando assim:
foreach ($unidades as $keys=>$unidade)
{
    echo $unidade->id.' - '.$unidade->nome.'
';
}

Comment: Esse é exatamente o mesmo código que você colocou na pergunta e que disse não ter funcionado. Por que agora funcionou?
Comment: Você tem razão, Anderson. Olhando aqui verifiquei que realmente usei a mesma função, mas com num parâmetro de critério diferente. O problema estava justamente nos campos `protected`, como você falou, pois esse parâmetro não tem esses campos protegidos.
Valeu amigo.
Comment: Então acho que tanto a pergunta quanto a resposta carecem de mais detalhes. Parece-me que o problema real foi omitido em ambas.

Percorrendo array de objetos


Calculate possible combinations of an array in order of presented arrays

Question: This is a php question.
I have an array of arrays:
Array ( [1] => Array ( [1] => 1 [2] => 2 [3] => 3) [2] => Array ( [4] => 4 ) [3] => Array ( [7] => 7 [8] => 8 [9] => 9 ) [4] => Array ( [36] => 36 ) )
I need to make all possible combinations in order but never out of order, and never missing a previous possible..that likely a bad explanation but this is what i mean:
1
1 - 4
1 - 4 - 7
1 - 4 - 8
1 - 4 - 9
1 - 4 - 7 - 36
1 - 4 - 8 - 36
1 - 4 - 9 - 36
I do not ever want to get 1 - 9 - 4 as in it must use the arrays as the order, and I cannot skip any like so 1 - 9 - 36
Any help would be seriously appreciated!
I tried the solution below (on a larger more realistic array):
<code>$myarray = 'a:4:{i:1;a:29:{i:1;s:1:"1";i:2;s:1:"2";i:3;s:1:"3";i:10;s:2:"10";i:11;s:2:"11";i:12;s:2:"12";i:13;s:2:"13";i:14;s:2:"14";i:15;s:2:"15";i:16;s:2:"16";i:17;s:2:"17";i:18;s:2:"18";i:19;s:2:"19";i:20;s:2:"20";i:21;s:2:"21";i:22;s:2:"22";i:23;s:2:"23";i:24;s:2:"24";i:25;s:2:"25";i:26;s:2:"26";i:27;s:2:"27";i:28;s:2:"28";i:29;s:2:"29";i:30;s:2:"30";i:31;s:2:"31";i:32;s:2:"32";i:33;s:2:"33";i:34;s:2:"34";i:35;s:2:"35";}i:2;a:3:{i:4;s:1:"4";i:5;s:1:"5";i:6;s:1:"6";}i:3;a:3:{i:7;s:1:"7";i:8;s:1:"8";i:9;s:1:"9";}i:4;a:2:{i:36;s:2:"36";i:37;s:2:"37";}}';
</code>
$yourarray = unserialize($myarray);
$array_iter   = new RecursiveArrayIterator($yourarray);
$iter_iter    = new RecursiveIteratorIterator($array_iter);
foreach($iter_iter as $iwishitwashomework)
{
echo $iwishitwashomework;
}`
this is what it printed:
12310111213141516171819202122232425262728293031323334354567893637
Comment: no it is a oh crap how do I do this fast question
Comment: hey, did you found answer? looking for same :)
Answer: <code>$array_iter   = new RecursiveArrayIterator($yourarray);
$iter_iter    = new RecursiveIteratorIterator($array_iter);

foreach($iter_iter as $myhomework)
{
echo $myhomework;
}
</code>
Comment: this is what it printed:

12310111213141516171819202122232425262728293031323334354567893637


Entity Framework 6 erro ao logar os SQLs

Question: Estou tentando ver os SQLs executados pelo Entity Framework, uso a versão 6.
Estou seguindo esse guia.
Fiz um novo DBContext usando a interface grafica. 5 tabelas apenas.
O código está dentro de um Controller Web API2:
public class TAGsController : ApiController
{
    private MEUDB db = new MEUDB();

    // GET: api/TAGs/5
    [Route("{Key}/api/tag/tag/{id}")]
    [ResponseType(typeof(TAG))]
    public async Task<IHttpActionResult> GetTAG(long id)
    {
        db.Database.Log = Console.Write;
        TAG tAG = await db.TAGs.FindAsync(id);
        if (tAG == null)
        {
            return NotFound();
        }

        return Ok(tAG);
    }

}

Ao fazer o debug eu fui até a linha do Find e ele retornou o seguinte na janela de output:

The thread 0x8188 has exited with code 259 (0x103).

O que eu estou fazendo de errado? Segundo o guia deveria ser apenas isso.
Editado: Mais informações
Ao fazer tudo igual, só que usando o Find(), sem o Async(), ele funciona.
TAG tAG = await db.TAGs.Find(id);

Existe alguma configuração extra para isso? Ou algum cuidado especial?
Comment: Cara, veja se este [link][1] te ajuda.

  [1]: http://stackoverflow.com/questions/18887864/what-is-a-thread-exit-code
Comment: Ele fala sobre o debug, mesmo sem o debug ele continua sem logar. Tem  a ver com o Async, usando o Find sem async ele funciona.
Answer: Você pode fazer o log não necessariamente em console. Pode ser feito em arquivo de texto, no Event Viewer, em Trace... como a ideia é passar um delegate, para fazer log em arquivo de texto, você pode usar:
context.Database.Log = mensagem => File.AppendText("C:\\meuarquivodelog.txt").WriteLine(mensagem);

Comment: Fiz o que vc falou com o log4net, funcionou normal, mesma ideia de passar o degate. Obrigado.


Default value to 'datetime' field in form loaded from the database

Question: I want to display the datetime field on my Drupal 8 form with some date loaded from the database, but the front end always shows empty fields as if no data has been provided. I tried several combinations to default_value field, but none of them are showing any thing.
The code I am using is the following.
<code>$form['dateopening'] = array(
  '#type' => 'datetime',
  '#title' => t('Opening Date'),
  '#default_value'=> date('Y-m-d H:i:s', strtotime($dateFromDB)),
);
</code>
Why doesn't it set the default value as expected?
Comment: add a format like : $format = 'Y-n-d'; then add default value like:
'#default_value' => date('c'),
Comment: It is 'datetime' field not 'date' field which I wanted. It is not working.
Answer: The response is in this thread : on stackoverflow
<code>$form['valid_dt'] = array(
    '#type' => 'datetime',
    '#default_value' => DrupalDateTime::createFromTimestamp($data->valid_dt),
    '#title' => $this->t('Valid'),
);
</code>


DateTime conversions using NodaTime on ASP.Net MVC 3 Razor website. How to?

Question: I have the Date/Time stored in the database on the London's time zone (not UTC).
What I need is to retrieve this Date/Time, convert it to UTC and display considering the user's time zone (which they define when registering to the site - ie: en-GB, en-US, etc).
My first question is more related to the MVC structure, as I'm totally new to this (am a WebForms developer) - Where should I put this conversion code/class/helper? Model? ViewModel?
The second question is the conversion itself - I've played around with the NodaTime test project but can't find a proper way to do this conversion.
Any help is much appreciated.
Thank you in advance.
Answer: Jon Skeet may need to correct me, as I'm assuming this is correct in nodatime:
<code>// Timezone data provider (inject with DI)
IDateTimeZoneProvider timeZoneProvider = DateTimeZoneProviders.Tzdb;

// London Timezone (can keep this as a singleton, since it'll be used often)
var londonTimeZone = timeZoneProvider["Europe/London"];

// Get your date/time from the database and map it as being local to London timezone
var yourDateFromDb = new DateTime(2013, 01, 23, 21, 00, 00); // This is what you'll get back from your database (although you may get back a DateTimeOffset)
ZoneLocalMapping zonedDbDateTime = londonTimeZone.AtLeniently(LocalDateTime.FromDateTime(yourDateFromDb)); <-- This is your date time with the correct offset (taking into account DST etc.)

// Map the London zoned date/time to the users local date/time
var usersTimezoneId = "Europe/Paris"; // <-- Store this value in users profile/db
var usersTimezone = timeZoneProvider[usersTimezoneId];
var usersZonedDateTime = zonedDbDateTime.WithZone(usersTimezone);

Assert.That(usersZonedDateTime.Hour == 22);
</code>
You should probably be aware that during timezone transitions (autumn clock change), you may get 2 possible dates for the zonedDbDateTime.  The code here just gets the first or earliest date/time.
Edit: Updated code snippet with changes suggested by Jon Skeet
Comment: I'd use `londonTimeZone.AtLeniently` rather than the map, but otherwise that's right. It may be worth noting that `en-GB` (etc) aren't normal time zone identifiers.
Comment: @MelanciaUK: `ZonedDateTime.ToDateTimeUtc` or `ZonedDateTime.ToDateTimeUnspecified` depending on which Kind you want.
Comment: Also, it might be worth changing `usersLocalDateTime` to `usersZonedDateTime` as it *is* a `ZonedDateTime`.
Comment: @JonSkeet good point regarding the locale. I should've put my question on a better way. I'll do this conversion based on the user's date/time settings (time zone) - using a javascript plugin which will return me the time zone id. The locale saved on the user's profile will be used just to format the result.
Comment: Thanks both for the answer. Will try it now.
Comment: Just one more thing. I'll be returning the result as DateTime. What's the best way to convert from ZonedDateTime to DateTime? Thanks!
Answer: you can write some extension method like this :
<code>public static DateTime ConvertToUtc(this DateTime d)
{
    //do conversin and return it
}
</code>
and you will be able to call it like @Model.MyDate.ConvertToUtc() from any view you wish as long as you have the namespace of the ConvertToUtc inclucded on the top of page.
and to do the conversion see this pages
Convert DateTime from UTC to a user provided time zone with C#
http://www.dotnetcurry.com/ShowArticle.aspx?ID=593
How to work with time zones in ASP.NET?
Comment: Thank you very much for the answer, but I'm currently using NodaTime on this project.


How to plot a rolling window of five points from a matrix using animate in Maple

Question: This question is about animating a plot of 3d points in Maple.
Consider the parametric function
$$f(t)=(0,\cos{t},\sin{t})$$
Let's create a matrix of twenty points of this function, each row being a point.
pd := Matrix([seq(f(t), t = 0 .. 20)]);

We can plot these points
pointplot3d(pd)

to obtain

Now, imagine we want to have an animation that plots a rolling window of five points. That is, first we plot rows 1-5, then rows 2-6, then 3-7, and so on.
I thought about implementing this as follows
with(plots):
animate(pointplot3d, [pd[t .. t + 5, () .. ()]], t = [1, 2, 3, 4, 5])

However, I get an error

Error, non-integer ranges in Matrix index

The indexing of the matrix is being done using values of $t$ from $1$ to $5$, if I understand correctly.
Here is a similar example that also uses a list for this same parameter to animate
animate(plot3d, [[sin(q^2 + q)*cos(q), sin(q^2 + q)*sin(q), cos(q^2 + q)], q = s - 1 .. s], s = [seq(i, i = 1 .. 5)], frames = 100)

This produces the correct animation.
I would like to attach my worksheet, but I can't see how.
In any case, why does the first use of animate not work?
EDIT: the following workaround seems to work
m1 := proc(pd, t)
  return pointplot3d(pd[t .. t + 5, () .. ()]);
end proc

animate(m1, [pd, t], t = [seq(i, i = 1 .. 15)])

What I am doing with this code is passing my own function as the first parameter to pointplot3d. The docs say this first parameter is a

Maple procedure that generates a 2-D or 3-D plot or plot objects

I wasn't sure if this would work because when I check the return value of pointplot3d it is a function. I am not sure how the type system is in Maple. But this did work. And when I print out the value of t in the function m1 they seem to be integers.
Not sure why the original (easier) way isn't working.
Answer: You are making a common mistake and encountering what is sometimes known in Maple as premature evaluation.
The usual mechanism for how Maple handles procedure calls is that the arguments are evaluated up front, and then passed into the procedure.
You are passing the following as the second argument to the animate command, and it emits an error because at this moment (prior to entering the animate procedure itself) there is no value of t. And the Matrix pd cannot be indexed in such an indeterminate way.
pd[t .. t + 25, ..];
Error, non-integer ranges in Matrix index

There are several ways to accomplish what you're after.
One way is to delay the evaluation of pointplot3d by using a so-called operator calling sequence of animate, with another procedure, as in your second example.
Another way is delay the evaluation with single right-ticks (aka uneval quotes in Maple).
For example (using a slightly larger number of points, for fun):
restart;
with(plots):
f := t -> [0,cos(t),sin(t)]:
pd := Matrix([seq(f(t), t=0..50)]):

pointplot3d(pd);

animate(pointplot3d,
        ['pd[t .. t + 25, ..]'],
        t = [$1..25]);

There are other ways, including construction of the individual frames using seq, which has special evaluation rules.


Hammer.js swipe doesn't work until button is clicked

Question: I'm using hammer.js library to add swipe gestures for touch devices.
My code is:
var bodyElement = document.getElementById('body');
    var swipe = new Hammer(bodyElement);
    swipe.on("swipeleft", function() {
        $(".close-button").click();
    });
    swipe.on("swiperight", function() {
        $(".open-menu").click();
    });

What I'm trying to do is to click on one button element when swipe right and click on another button element when swipe left, but this is not working until I click on button first (.open-menu) manually, after that everything working fine (swipe left, swipe right clicks on buttons).
I have the ID 'body' on body element, I want to swipe working when user swipes anywhere.
Am I missing something with hammer.js? What could be the problem.
Answer: It seems that trying to swipe on 'body' causes Hammer to throw the following error:
hammer.js:222 Uncaught TypeError: Cannot read property 'addEventListener' of null
I guess you need to add the swipe listener on an existing element that isn't body.
The following code works for me:

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
  <title>Test</title>

        Open - Close

Basically I've wrapped the links into a div called 'wrap' and the swiping is tied to that div. With the styles I've applied to the div, it stretches across the entire page so it basically acts like 'body' would anyway.
I hope that helps!


understanding an estimation of the perimeter of sets, $|P(\hat{V})-P(V)|\le P(B_r(x))$

Question: Let $V$ be a Borel set in $\mathbb{R}^n$ such that the Lebesgue measure of $V$, $|V|$, satisfies $|V|\approx |B_1(0)|$, but $|V|\neq |B_1(0)|$ (i.e. $|V|$ is slightly greater or less than $|B_1(0)|$).
We modify the set $V$ to obtain a set $\hat{V}$ satisfying $|\hat{V}|=|B_1(0)|$ in the following way:
Fix a point $x$ on the boundary of $V$, $\partial V$, and let $r>0$ such that if we set $$\hat{V}:=\begin{cases}
V\cup B_r(x),\;\text{if}\; |V|\le |B_1(0)|\\
V\setminus B_r(x),\;\text{if}\;\; |V|> |B_1(0)|\\
\end{cases} $$
we have $|\hat{V}|=|B_1(0)|$.
Let $P(E)=\sup\left\{\int_{\mathbb{R}^n}\chi_E(x) \mathrm{div}\boldsymbol{\phi}(x) \, \mathrm{d}x : \boldsymbol{\phi}\in C_c^1(\mathbb{R}^n,\mathbb{R}^n),\ \|\boldsymbol{\phi}\|_{L^\infty(\mathbb{R}^n)}\le 1\right\}$ is be the perimeter of a borel set $E$. See https://en.wikipedia.org/wiki/Caccioppoli_set
Why is $|P(\hat{V})-P(V)|\le P(B_r(x))$?
Heuristically, if we draw a picture, the estimate is clear, but I don't know how to prove it analytically. I tried to prove it with a case distinction, case $|V|\le |B_1(0)|$ and case $|V|> |B_1(0)|$ and using that we have the following for the characteristic functions: $\chi_{V\cup B_r(x)}=\chi_V+\chi_{B_r(x)}-\chi_{V\cap B_r(x)}$ and $\chi_{V\setminus B_r(x)}=\chi_V-\chi_{V\cap B_r(x)}$. However, I am not sure how to handle |sup.. minus sup..|calculations.
Answer: The estimate is false. Suppose $B$ is a ball with radius slightly smaller (or slightly larger) than 1, choose point $x$ on the boundary. Now you can modify your set on a small neighbourhood of $x$ so that the Lebesgue measure doesn't change much, but the perimeter increases arbitrarily (think of a comb-like shape on the boundary). That's your $V$, with $|V|\not=|B_1(0)|$. Now, the perimeter of $\hat{V}$ will be small again, as long as $B_r(x)$ contains the "comb" we created earlier. Then
$$ |P(\hat{V})-P(V)| \gg P(B_r(x)),$$
with the left hand side arbitrarily large.
In general, for $E$ and $F$ sets of finite perimeter, you have
$$P(E\cup F) + P(A\cap F) \le P(E)+P(F),$$
and
$$P(E\setminus F)\le P(E)+P(F),$$
see the book of Maggi on sets of finite perimeter, (12.17) and (12.19).


Offload cached pages to different Apache process

Question: On our Drupal 6 and Drupal 7 sites each idle Apache process averages 60-100MB each.  When the page gets loaded from cache only about 10MB is really needed, but sometimes a page is not cached yet so the process jumps up to 60-100+MB.
We use prefork, so each apache process stays about 60-100MB in size, when in reality 99.99% of the page loads are cached and the processes could easily be down to 10MB.
Our MaxClients settings could be about 5x greater if there were a way to keep the apache sizes down to 10MB.
Is there a way to have two apache processes available, one with a low maxclients for non-cached pages and one with a high maxclients for cached pages?  And also, is there a way to route cached & non-cached requests to different processes?
Answer: It is not a direct answer to your question, but play around with setting MaxMemFree and MaxRequestsPerChild in the prefork section of your httpd.conf.  MaxMemFree should force Apache to free memory that it doesn't need, and MaxRequestsPerChild will force Apache to fork a new process (and free memory in the process) after servicing a particular number of requests.  You may have some performance impacts, but gain memory improvements.
Comment: Giving this a shot right now.  This would be a very simple solution if it works.  Doesn't offload cache, but it could allow us to safely increase our MaxClients considerably.
Comment: The MaxMemFree didn't seem to do anything at all.  But we set the MaxRequestsPerChild from 4000 to 100 and it is pretty effective at getting rid of the large processes.
Answer: I'd suggest moving to the idea of a dedicated, lightweight, configurable cache daemon, for example Varnish which can run in its own right, taking the load off apache for the majority of cache hits for the site, and can even be moved onto a separate physical server in the future should you still need more power.
Answer: Apache would need to know if the cache exists if it where to route the process; it currently doesn't. http://httpd.apache.org/docs/trunk/mod/mod_dbd.html might be one idea if you wish to create your own apache module that will query the cache_page table. Another option is to look at using something like boost http://drupal.org/project/boost which will not start up PHP on page cache hits.


Cloudera Command: hdfs dfs -put testfile.txt Failure

Question: I use a MAC OS Yosemite with a cloudera-quickstart-vm-5.4.2-0-virtualbox. I would like to put a "testfile.txt" in the HDFS. When I use the command "hdfs dfs -put testfile.txt" in the Terminal I have the Exception:

what should I do?
Comment: In the "File Browser" TAB of the HUE I have the follow Error-Message: **Cannot access: /user/clouera. The HDFS REST service is not available. Note: You are a Hue admin but not a HDFS superuser (which is "hdfs").** ('Connection aborted.', error(111, 'Connection refused'))
Answer: All the basic Hadoop services should be running when you start the Cloudera VM. Port 8020 is for the hadoop-hdfs-namenode service. These services must have failed and just needs to be restarted.
To check the status of a service:
service <service-name> status

To restart a service:
service <service-name> restart

To restart, hadoop-hdfs-namenode service
service hadoop-hdfs-namenode restart

if you get an Error -  "root user required", when restarting the service, run with sudo as shwon below:
sudo service hadoop-hdfs-namenode restart

if hadoop-hdfs-datanode service is also not running,
service hadoop-hdfs-namenode restart

Alternatively, You can also start/stop/restart the service by login in to Cloudera Manager from Firefox in Cloudera VM.
Comment: Hi, @Vinkal, I have written in Terminal: **"service hadoop-hdfs-namenode status"** and the message was **"Hadoop namenode is dead and pid file exists [FAILED]"**. Then I tried **"service hadoop-hdfs-namenode restart"** and I have got **Error: root user required**.
Comment: try with sudo: sudo service hadoop-hdfs-namenode restart
Comment: I tried and the message was: (1) **no namenode to stop** (2) **Stopped Hadoop namenode: [OK]** (3) **starting namenode, logging to /var/log/hadoop-hdfs/hadoop-hdfs-namenode-quickstart.cloudera.out** (4) **Failed to start Hadoop namenode. Return value: 1 [FAILED]**
Comment: Go through the log file. I guess, may be some permission issue.Check the permission for dfs.namenode.name.dir mentioned in hdfs-site.xml. Give the appropriate permission if that's the case.
Comment: Hi @Vinkal . I have found the "hdfs-site.xml" log file. By  from **dfs.namenode.name.dir** I have: "/var/lib/hadoop-hdfs/cache/${user.name}/dfs/name". What does that mean?In this case which permission must I give?
Comment: @JEFA - dump the content of log file. open the file - sudo gedit  /var/log/hadoop-hdfs/hadoop-hdfs-namenode-quickstart.cloudera.out
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/92635/discussion-between-vinkal-and-jefa).


How to do Darboux sums

Question: Can someone explain to me how do I find out if it is upper or lower Darboux sum and on which interval is it? Here is example, it says that it is uppear Darboux sum on interval $[0,1]$.

Sorry for my bad english.
Answer: This sum corresponds to the function $f(x)=1/(1+x^2)$ on the partition $\{x_k\}_{k=0}^n$ with $x_k=k/n$, $0\le k\le n$. The sum is $\sum_{k=1}^n f(x_k)(x_k-x_{k-1})$. Since $f$ is decreasing, $f(x_k)=\inf_{x_{k-1}\le x\le x_k}f(x)$. The sum is thus a lower sum.

How to do Darboux sums