text:
Q: Definition of a function I am giving a two part presentation to a class on cardinality. I have done the first part but the prof wasn't satisfied with my definition of a function. For this presentation I have limited time so I want to go through definitions as quickly as possible. For this reason I don't want to talk about relations.
Does this work as a definition of a function:
$$\{(x,f(x))|\forall x \in A, \, \exists ! y\in B \mathrm{\,such \,that \,}f(x) = y \}$$
where A is the domain and B is the codomain? Specifically, does this ensure that everything in A gets mapped to something? Do I have to say that x is in A and f(x) is in B and for all A there exists a unique etc etc?

A: I don't see anything wrong with the standard definition of a function: a subset $S$ of $A\times B$ with the property that for each $x\in A$, there exists a unique $y\in B$ such that $(x,y)\in S$. And given a function $S$, we define the notation $f(x)$ to mean exactly that unique such $y$.
This will probably be more digestible to the audience (in a short amount of time) anyway than trying to write it in symbols. Oversymboling mathematics rarely makes it more understandable to those who don't already understand it.

A: As Andres wrote in the comments, you are using $f$ to define what a function is, but the notation $f(x)$ already implies (at least intuitively) that $f$ is a function.
You should write that $f\colon A\to B$ is a function from $A$ to $B$ if:

*

*$f\subseteq A\times B$.

*For every $a\in A$ there exists a unique $b$ such that $(a,b)\in f$.

Alternatively, you could define a function independently of $A$ and $B$ by saying that $f$ is a function if:

*

*Every element of $f$ is an ordered pair.

*If $(a,b)\in f$ and $(a,c)\in f$ then $b=c$.

Then you can add that $f\colon A\to B$ is a shorthand for the following:

*

*$f$ is a function.

*For every $a\in A$ there is some $b\in B$ such that $(a,b)\in f$.

*For every pair $(a,b)\in f$ we have that $b\in B$.


text:
Q: Why isn't my code working?      Private Sub CommandButton1_Click()
       Dim rTable                 As Range
           Dim lRow                   As Long

        Set rTable = Sheets("Revenue Dashboard").PivotTables("PivotTable6").TableRange1
            With Sheets("Overall Dashboard")
         lRow = Application.Max(.Cells(.Rows.Count, "T").End(xlUp).Row + 1, 63)
       .Range("T" & lRow).Value = rTable.Cells(rTable.Cells.Count).Value
        .Select
       End With
        End Sub

    Private Sub CommandButton2_Click()
    Dim rngInput As Range
       Set rngInput = Sheet1.Range("R63:T69") '
        rngInput.ClearContents
     End Sub

        Private Sub CommandButton3_Click()
        Dim rTable                 As Range
        Dim lRow                   As Long

        Set rTable = Sheets("Impression      Dashboard").PivotTables("PivotTable5").TableRange1
       With Sheets("Overall Dashboard")
          lRow = Application.Max(.Cells(.Rows.Count, "T").End(xlUp).Row + 1, 127)
          .Range("T" & lRow).Value = rTable.Cells(rTable.Cells.Count).Value
            .Select
     End With
       End Sub

         Private Sub CommandButton4_Click()
          Dim rngInput As Range
         Set rngInput = Sheet1.Range("R127:T137") '
         rngInput.ClearContents
      End Sub

       Private Sub CommandButton5_Click()
       Dim rTable                 As Range
      Dim lRow                   As Long

       Set rTable = Sheets("Clicks Dashboard").PivotTables("PivotTable8").TableRange1
       With Sheets("Overall Dashboard")
  lRow = Application.Max(.Cells(.Rows.Count, "S").End(xlUp).Row + 1, 197)
  .Range("S" & lRow).Value = rTable.Cells(rTable.Cells.Count).Value
   .Select
       End With
       End Sub

        Private Sub CommandButton6_Click()
        Dim rngInput As Range
          Set rngInput = Sheet1.Range("Q197:T207") '
           rngInput.ClearContents

         End Sub

      Private Sub CommandButton7_Click()
      Dim slcr As SlicerCache

        For Each slcr In ActiveWorkbook.SlicerCaches

     slcr.ClearManualFilter
    Next slcr
            End Sub

This is code for a series of compare buttons for different sets of data and each one has a 'clear data' button. At the end I have a 'clear slicer' button at the end.
It was working before but after a few clicks of the button it is no longer displaying data in cell T63 (for command button one)
The code hasn't changed as far as I'm aware - what is causing the problem?
Thanks

A: Should this statement not have a column reference?
Code:
       rTable.Cells(rTable.Cells.Count).Value

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the concept behind this 'dual problem'? I'm trying to solve the following problem:
Show that the dual of ht epolynomial regression program
$$\min t, -t \leq \sum_{i=0}^{d} c_is^i - f(s) \leq t, \quad \forall s\in S $$
is equivalent to the program
$$\max_{\lambda, \sigma} \frac{1}{2}\big(\sum_{s\in S} \lambda_s f(s) - \sum_{s\in S} \sigma_s f(s)\big) $$
$$ \sum_{s\in S} \lambda_s s^i = \sum_{s\in S} \sigma_s s^i, \quad \forall i\in \{1,\dots,d\} $$
$$ \sum_{s\in S} \lambda_s = \sum_{s\in S} \sigma_s = 1, \lambda\geq 0, \sigma\geq 0$$
And in the solutions it makes the following step that I do not understand:
First we rewrite the nequality constraints of the regression program as:
$$t+\sum_{i=0}^{d} c_is^i \geq f(s), \forall s\in S$$
$$t-\sum_{i=0}^{d} c_is^i \geq -f(s), \forall s\in S$$
And now comes the part where I lose it:
Using $\alpha^+, \alpha^- \geq 0$ as the dual multipliers (?) for the first and second set of constraints respectively, this yields the dual program:
$$\max \sum_{s\in S} f(s)(\alpha^+ - \alpha^-)$$
$$\sum_{s\in S}(\alpha^+ + \alpha^-) = 1 $$
$$\sum_{s\in S} s^i(\alpha^+ - \alpha^-) = 0, \forall i\in\{0,\dots,d\} $$
$$\alpha^+, \alpha^- \geq 0$$
I do not understand where this step follows from. I've tried to find an explanation for what the dual of a program is and what the dual multipliers are, but I just can't find anything that makes me understand what we've formed here and why it is the dual problem.


text:
Q: Looking for a better way to write CSVs I have written a couple of PowerShell scripts to gather some statistics from a windows machine. The first one was about gathering CPU, memory usage etc. at certain intervals. Which works fine. I have written another one that basically checks lastaccesstime for files and creates a CSV, code below:
$dest="C:\users\Administrator\Documents\filelist.csv"
$csvdata=@()
$source="x:\"
$count=0

Get-ChildItem -Recurse $source | foreach{

$csvdata += New-Object PSObject -Property @{FileName=$_.FullName;DateAccessed=($_.LastAccessTime).ToShortDateString()}

$csvdata|Export-Csv $dest -notype

$count+=1
$count

}

Alright so if I keep adding things to $csvdata and only export file when the loop ends then there is a possibility I might lose data if script ends due to some error or something. So instead I export it within the loop as shown in the code. But this also means the $csvdata will keep increasing in size and that means it will have a memory footprint which can grow to be megabytes or even more.
Is there any way to dump this data to CSV, empty $csvdata variable without affecting the results? Hope this makes sense.

A: Note: the code you have in your current question is odd as it will keep overwriting the file at every pass with all the data that was already there. With a small data set you might not have noticed but it is bad nonetheless. Read on to see what you could have done instead.

But this also means the $csvdata will keep increasing in size and that means it will have a memory footprint which can grow to be megabytes or even more.

There are a couple of issues here. First is how you are building $csvdata. Using += will destroy the array and remake it one element larger. This is a costly operation and creates a performance issue. You should be able to use the pipeline to accomplish what you need (based on what little we see here.)
Get-ChildItem -Recurse $source | foreach{

    New-Object PSObject -Property @{FileName=$_.FullName;DateAccessed=($_.LastAccessTime).ToShortDateString()} |
        $csvdata | Export-Csv $dest -NoTypeInformation -Append

    $count+=1
    $count
}

You have no reason to store $csvdata so don't bother doing it. Moving on to your other source of woe.
If you must store it and you expect large data sets consider using the .Net arraylist type instead. Really basic example in use
$csvData  = New-Object System.Collections.ArrayList

0..9 | ForEach-Object{
    [void]($csvData.Add([pscustomobject]@{Number=$_;Even=!($_%2)}))
}

$csvData | ExportTo-Csv -NoTypeInformation

there is a possibility I might lose data if script ends due to some error or something.

This is the main reason you have asked your question it seems. You are worried about data loss during the process. I will have to be vague working with your example but you are trying to fix the wrong problem I think. Instead of trying to find a more resilient export process you should be worrying about error handling.
If there is the potential for code failure you should consider using try{}catch{} blocks as well as the common cmdlets parameter for -ErrorAction. The both have their place depending on if you are dealing with terminating or non terminating errors.
Using those in areas of failure will prevent your entire process from being in an incomplete or questionable state.

A: I don't think there's a partial export-csv, but you could just write comma separated values as a string and append them to the file inside the loop:
$dest="C:\users\Administrator\Documents\filelist.csv"
$csvdata=@()
$source="x:\"
$count=0

"FileName,DateAccessed" | Set-Content $dest

Get-ChildItem -Recurse $source | foreach{

    "$($_.FullName),$($_.LastAccessTime.ToShortDateString())" | Add-Content $dest

$count+=1
$count
}


text:
Q: How to draw ~1A from Li batteries without damaging/over-stressing them? I have designed a micropump driver powered by 2x AA (Li) batteries, the pump is piezoelectric and requires 27V.
The pump requires a switching waveform, at the battery side this draws (including inefficiencies and driver consumption) 400mA and 900mA at the battery voltage which is nominal 3V (depending on the pressure being created by the pump), the batteries won't really see the switching because I am using a H-bridge and so there are two signals that are orthogonal to eachother and other than the small (ns) deadtime between them the boost converter will only see a DC drain (and even the deadtime will get lost in the feedback loop response time of the SMPS).
Several problems have arisen:

*

*After a failed life-cycle test I measured the voltage across the batteries, one was sitting at 0.2V the other 1.47V, they are used in series, so why would one battery have such drastically different voltage? Does this suggest damage? or simply one is much more drained that the other?

*I'm using boost solution that can boost from ~1.5V up to the required 27V. I have noticed that the someway into a test the battery voltage drops off during a pump cycle, very quickly dropping below 1V and after the cycle ends quickly recovering to 2.8-2.9V, does this suggest I am drawing to much current out of the battery? or that the battery is damaged or simply running dry?
I assume my design is damaging or stressing the batteries somehow, are there any standard practices to be used in this scenario?
Based on a constant discharge test with reference to the battery manufacturer I estimate that the batteries that drop off in voltage drastically after a period of time being used are less than 1/3 discharged. I.e with a load drawing a defined constant current and measuring teh voltage across the terminals and comparign this with a the discharge curve (http://data.energizer.com/pdfs/l91.pdf)
Unfortunately I can't upload schematics due to confidentiality agreements with the customer, however I'll provide whatever additional information I can.

A: Batteries have different capacities and the one with the lesser capacity will define how much capacity you get from a series connection of multiple cells.
As you can see in the datasheet you linked, the cells will hold their voltage pretty constant until they drop off a cliff at the end. So I don't think you have a strange behaviour with one cell at 1.47 V and the other at 0.2 V. Both are actually discharged. Here is a relevant document explaining that cells which have an open circuit voltage of less than 1.7 V are to be considered discharged when they had the chance to rest (and recover their open circuit voltage)
But there is a second effect happening which might be the troublesome part for you. As the cell gets discharged, the internal resistance rises. So if one cell is drained the internal resistance might be too high for you to draw all the current you need.
Third thing is that your current requirement will rise during discharge. While it is 1 A at 3 V at the beginning it will be 2 A at 1.5 V when the batteries are almost dead which is overstressing them.
The effect you see in 2. is the battery relaxation effect. I think that the batteries are running dry and you are in the region where the internal resistance is rising. In that state you can extract energy of the battery only with a smaller current.
Depending on your SMPS design, it might draw peaks which are a lot higher than your average current, which will stress the batteries even more. You could try to reduce the problem with a really low ESR capacitor bank which provides the peak currents while the batteries then provide the average current.


text:
Q: Entity System in C++ I've recently discover the Entity System architecture and i've got some difficulties to do it in C++ / understand implementation.
How i see Entity System :
Components : A class with attributs, set and get.

*

*Sprite

*Physicbody

*SpaceShip

*...

System : A class with a list of components.

*

*List item

*EntityManager

*Renderer

*Input

*Camera

*...

Entity : Just a empty class with a list of components.
What i've done :
Currently, i've got a program who allow me to do that :
// Create a new entity/
Entity* entity = game.createEntity();

// Add some components.
entity->addComponent( new TransformableComponent() )
            ->setPosition( 15, 50 )
            ->setRotation( 90 )
        ->addComponent( new PhysicComponent() )
            ->setMass( 70 )
        ->addComponent( new SpriteComponent() )
            ->setTexture( "name.png" )
            ->addToSystem( new RendererSystem() );

If I've correctly understood the EntitySystem, each System has its own list of components on which it works. (List of components or list of entity, that is the question)
class Component;

/////////////////////////////////////////////////
/// \brief  An abstract system. (Interface)
///
/////////////////////////////////////////////////
class System
{
public:

    /////////////////////////////////////////////////
    /// \brief Call when process is created.
    ///
    /////////////////////////////////////////////////
    virtual bool start() = 0;

    /////////////////////////////////////////////////
    /// \brief Call when process is updated.
    ///
    /////////////////////////////////////////////////
    virtual void update() = 0;

    /////////////////////////////////////////////////
    /// \brief Call when process is removed.
    ///
    /////////////////////////////////////////////////
    virtual void end() = 0;

    /////////////////////////////////////////////////
    /// \brief Call when process is removed.
    ///
    /////////////////////////////////////////////////
    virtual void addComponent( Component* component )
    {
        elements.push_back( component );
    }

protected:

    std::vector<Component*> elements;

};

(I'had put the code in .h just for fast debug ^^)
The problem
I want add a "T" Component in a System with a list of X components
What i've tried :
std::vector<Component*> elements;

But i want something like that :
std::vector<T*> elements;

My System class is abstract. My System childrens class needs to have this list with is own type.
Solution :
I've tried to put my System class has a template class, so i've just to do :
class Renderer : System
But my SystemManager doesn't like this code : std::vector<System> systems.
System class with T type :
template<class T>
class System
{
public:

    /////////////////////////////////////////////////
    /// \brief Call when process is created.
    ///
    /////////////////////////////////////////////////
    virtual bool start() = 0;

    /////////////////////////////////////////////////
    /// \brief Call when process is updated.
    ///
    /////////////////////////////////////////////////
    virtual void update() = 0;

    /////////////////////////////////////////////////
    /// \brief Call when process is removed.
    ///
    /////////////////////////////////////////////////
    virtual void end() = 0;

    /////////////////////////////////////////////////
    /// \brief Call when process is removed.
    ///
    /////////////////////////////////////////////////
    virtual void addComponent( T* component )
    {
        elements.push_back( component );
    }

protected:

    std::vector<T*> elements;

};

SystemManager code :
class System;

class SystemManager
{
public:

    /////////////////////////////////////////////////
    /// \brief Default constructor.
    ///
    /////////////////////////////////////////////////
    SystemManager();

    /////////////////////////////////////////////////
    /// \brief Call when system is created.
    /// \param system A system to add.
    ///
    /////////////////////////////////////////////////
    bool addSystem( System* system);

    /////////////////////////////////////////////////
    /// \brief Call when system is updated.
    ///
    /////////////////////////////////////////////////
    void update();

    /////////////////////////////////////////////////
    /// \brief Call when system is removed.
    /// \param system A system to remove.
    ///
    /////////////////////////////////////////////////
    void removeSystem( System* system );

private:

    std::vector<System*> systemList;

};

With this, i've got this error in my SystemManager :
"Redefinition of 'System' as different kind of symbol"
(Pointing on the line "class System" in the SystemManager)
Did you have a solution for this problem ? Did my EntitySystem approch is good ?
Thanks!

A: In your code System is a template, later in the System manager class you try to use System as if it were not a template.  This will not work.  You need to either specify the type, make system manager a template and pass the type parameter through to system, or not have system be a template.  Also forward declaring templates, as a non template no less, isn't going to work.  Take a step back and figure out how templates work in C++.
Further more http://gamedev.stackexchange.com has many questions and answers about entity component designs, you might find it useful.


text:
Q: Excel Conditional Statement - 2 cells equal keep 1 based on value of another Hi I am looking for help writing an if statement in excel. I have a data set containing zip codes, and a residing/adjacent column. I would like to create a new column that contains either blanks, keep, remove based on the below conditions.
My current statement works for the 'keep' but does nothing else =IF(D2=B2,IF(F2= "Residing", "Keep", "Discard"),"")  Below is some sample data.
Possibilities:

*

*two zips do not match and adjacent (wont ever be residing) - new column would be blank (eg row 3)

*Two zips match and residing but also have matches that are adjacent- want those to be keep (eg row 1)

*Two zips match and = adjacent but also have a residing match- want those to be labeled "remove" (eg row 2)

Any suggestions would be greatly appreciated!

A: Try the following formula:
=IF(AND(A2=B2,C2="Adjacent",COUNTIFS(A:A,A2,B:B,B2,C:C,"Residing")>0),"Remove",IF(AND(A2=B2,C2="Residing"),"Keep",""))

Sample result:


text:
Q: TypeError: a bytes-like object is required, not 'str' in run line = line.split('\t') I'm using Python 3.7 (64-bit), and I run into the following error when running the code:
in run
    line = line.split('\t')
TypeError: a bytes-like object is required, not 'str'
The code I'm trying to run is the following:
    out_path = os.getcwd() + "/" + self.options['output folder'] + "/"
    out_file_name = out_path + "decision_log__" + self.options['input file']

    out_file = open(out_file_name, 'w')
    self.output_files['log'] = out_file

    tm_file = open(input_file_path, 'rb')
    if self.have_alignment is True:
        tm_align_file = open(align_file_path, 'r')
    if self.have_token is True:
        tm_token_file = open(token_file_path, 'rb')

    line_no = 0
    for line in tm_file:
        line_no += 1
        line = line.split("\t")

Originally, the codes were programmed in Python 2.7, then I used 2to3 to translate the files into the newest, 3.x, syntax.
What is the root of this issue and how can I fix it most effectively?
Best regards,
Adam


text:
Q: Generating parameterized F# quotations Let's say we have a simple F# quotation:

type Pet = {  Name : string }
let exprNonGeneric = <@@ System.Func(fun (x : Pet) -> x.Name) @@>

The resulting quotation is like:

val exprNonGeneri : Expr =
  NewDelegate (System.Func`2[[FSI_0152+Pet, FSI-ASSEMBLY, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]],
             x, PropertyGet (Some (x), System.String Name, []))

Now I want to generalize it, so I instead of type "Pet" and property "Name" I could use an arbitrary type and method/property defined on it. Here is what I am trying to do:

let exprGeneric<'T, 'R> f = <@@ System.Func<'T, 'R>( %f ) @@>
let exprSpecialized = exprGeneric<Pet, string> <@ (fun (x : Pet) -> x.Name) @>

The resulting expression is now different:

val exprSpecialized : Expr =
  NewDelegate (System.Func`2[[FSI_0152+Pet, FSI-ASSEMBLY, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]],
             delegateArg,
             Application (Lambda (x,
                                  PropertyGet (Some (x), System.String Name, [])),
                          delegateArg))

As you can see, the difference between the first and the second expression is that in first case the top level NewDelegate expression contains PropertyGet, while the second expression wraps PropertyGet in a Application/Lambda expression. And when I pass this expression to an external code it does not expect such expression structure and fails.
So I need some way to build a generalized version of quotation, so when it gets specialized, the resulting quotation is an exact match of <@@ System.Func(fun (x : Pet) -> x.Name) @@>. Is this possible? Or it there only choice to manually apply pattern matching to a generated quotation and transform it to what I need?
UPDATE. As a workaround I implemented the following adapter:

let convertExpr (expr : Expr) =
    match expr with
    | NewDelegate(t, darg, appl) ->
        match (darg, appl) with
        | (delegateArg, appl) ->
            match appl with
            | Application(l, ldarg) ->
                match (l, ldarg) with
                | (Lambda(x, f), delegateArg) ->
                    Expr.NewDelegate(t, [x], f)
                | _ -> expr
            | _ -> expr
    | _ -> expr

It does the job - I can now convert expression from 1st to 2nd form. But I am interested in finding out if this can be achieved in a simple way, without traversing expression trees.

A: I don't think it will be possible to do this; in the second case, you are plugging in the expression <@ (fun (x : Pet) -> x.Name) @>, which is represented using a Lambda node, into the hole in the other expression.  The compiler does not simplify expressions during this plugging process, so the Lambda node won't be removed no matter what you do.
However your pattern matching workaround can be greatly simplified:
let convertExpr = function
| NewDelegate(t, [darg], Application(Lambda(x,f), Var(arg)))
    when darg = arg -> Expr.NewDelegate(t, [x], f)
| expr -> expr

In fact, your more complicated version is incorrect.  This is because the delegateArg in your innermost pattern is not matching against the value of the previously bound delegateArg identifier from the outer pattern; it is a new, freshly bound identifier which also happens to be called delegateArg.  In fact, the outer delegateArg identifier has type Var list while the inner one has type Expr!  However, given the limited range of expression forms generated by the compiler your broken version may not be problematic in practice.
EDIT
Regarding your followup questions, if I understand you correctly it may not be possible to achieve what you want.  Unlike C#, where x => x + 1 could be interpreted as having a type of either Func<int,int> or Expression<Func<int,int>>, in F# fun x -> x + 1 is always of type int->int.  If you want to get a value of type Expr<int->int> then you generally need to use the quotation operator (<@ @>).
There is one alternative that may be of use, however.  You can use the [<ReflectedDefinition>] attribute on let bound functions to make their quotations available as well.  Here's an example:
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.ExprShape
open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns

let rec exprMap (|P|_|) = function
| P(e) -> e
| ShapeVar(v) -> Expr.Var v
| ShapeLambda(v,e) -> Expr.Lambda(v, exprMap (|P|_|) e)
| ShapeCombination(o,l) -> RebuildShapeCombination(o, l |> List.map (exprMap (|P|_|)))

let replaceDefn = function
| Call(None,MethodWithReflectedDefinition(e),args)
    -> Some(Expr.Applications(e, [args]))
| _ -> None

(* plugs all definitions into an expression *)
let plugDefs e = exprMap replaceDefn e

[<ReflectedDefinition>]
let f x = x + 1

(* inlines f into the quotation since it uses the [<ReflectedDefinition>] attribute *)
let example = plugDefs <@ fun y z -> (f y) - (f 2) @>


text:
Q: Mixed horizontal an vertical css with
* I'm trying to creat a menu with mixed vertical an horizontal items. That's how the menu should look like:

item 1     item 3     item 5     item 7
  item 2     item 4     item 6     item 8

What i tried ist the following HTML:
<menu>

item 1

item 2

item 3

item 4

item 5

item 6

item 7

item 8

</menu>

And CSS:
.navigation menu {
    float: right;
    margin-top:103px;
    width:683px;
}
.navigation menu li {
    display:block;
    width: 115px;
    float: none;
    background-image:none;
    text-align:right;
}
.navigation menu li:nth-child(3) {
    float: left;
}
.navigation menu li:nth-child(4) {
    float: none;
}
.navigation menu li:nth-child(5) {
    float: left;
}
.navigation menu li:nth-child(6) {
    float: none;
}

But it doesn't work, i think, it's too much for CSS :)
Anybody got an idea? Thanks in advance for any help!
Greetings Est Ro

A: What you could do is set the menu items to
width:25%;

on each of your menu items and then just float them left. You can get rid of everything else. Also as a side do not use the menu tag is it deprecated. :)
JSFIDDLE
http://jsfiddle.net/eERR7/
UPDATED FIDDLE
http://jsfiddle.net/eERR7/2/

A: Maybe something like this? It's a little bit rusty but it my fit what you want.
I added some of the and changed a bit
.navigation menu li:nth-child(6) {
    float: none;
}

http://jsfiddle.net/JXxU8/2/

A: Keep the odd elements floating left.
Make the even elements have no width (margin-right: -115px) and position them 155 px to the left and the apropiate distance to the bottom:
CSS
.menu {
    float: left;
    margin-top:13px;
    width:683px;
}
.menu li {
    display:block;
    width: 115px;
    float: left;
    background-image:none;
    text-align:right;
}

.menu li:nth-child(even) {
    position: relative;
    top: 1.2em;
    left: -115px;
    margin-right: -115px;
}

fiddle


text:
Q: Can't use flash method in prod environment I'm using the setFlash and hasFlash methods of symfony 1.4 with WAMP 2.0
Locally with my frontend_dev app, all work fine.
But in production environment, my test $this->forward404Unless($user->hasFlash('resultsArray')); fails.
I thought that the flash methods where enabled by default. What can I do to make it works please ?
Edit : I found an interesting error message.
Here is my filters.yml file
# You can find more information about this file on the symfony website:
# http://www.symfony-project.org/reference/1_4/en/12-Filters

rendering: ~
security:  ~

# insert your own filters here

cache:     ~
flash:     ~
execution: ~

In the frontend_prod.log, I have :

Mar 16 05:57:42 symfony [info] {sfPatternRouting} Match route "homepage" (/) for / with parameters array (  'module' => 'main',  'action' => 'index',)
  Mar 16 05:57:42 symfony [err] {sfParseException} Configuration file "D:\wamp\bin\php\symfony\symfony14\lib/config/config/filters.yml" specifies category "flash" with missing class key.

A: Do you call the executeShowResult action in a redirect/forward context? The flash has a limited lifetime and it will disappear after the very next request. Clearly the resultsArray has been flushed out.

A: You have a 404 being generated in production (favicon or image) and that counts as a request to the 404 action (after a redirect) clearing out your flash variables.

A: Not sure if this is the answer, but I don't have a flash key in my filters.yml file, in a Symfony 1.4.3 app, and I haven't touched it since grabbing the version from the Symfony site.  Have you tried removing that line from the yml file, clearing your cache and trying again?

A: I wonder if you have caching enabled for prod?
If you do, and are caching with_layout (or if flash is in the action template, then caching the relevant action), then it will returned the cached page without the flash message on subsequent views.

A: Be sure you have the use_flash=true on your factories.yml
user:
  class: myUser
  param:
    timeout:         3600
    logging:         %SF_LOGGING_ENABLED%
    use_flash:       true
    default_culture: %SF_DEFAULT_CULTURE%

A pretty old response but I hope is of some use to anybody else with the same problem.


text:
Q: In-App-Purchase: New subscription purchase does not trigger paymentqueue updatedTransactions I'm building out subscriptions in an iOS application.
I have an implementation of a StoreObserver that conforms to both SKPaymentTransactionObserver and SKProductsRequestDelegate. My StoreObserver implementation is a singleton and is added to the default payment queue as a transaction observer during application:didFinishLaunchingWithOptions.
I'm currently testing the application in the sandbox environment. When testing with a fresh sandbox user, I am prompted to log in, which I do, followed by the expected dialogs. After receiving the You're all set! Your purchase has been successfully completed dialog, I expect a callback to paymentQueue:updatedTransactions. However, that callback never fires... until I kill the application and start it again.
Does anyone have context on why this would be happening?

A: Despite the StoreObserver being registered as the SKaymentQueue transaction observer in the AppDelegate, registering it again before adding a product to the queue seemed to fix the issue.


text:
Q: Replicating SQL's 'Join' in Python I'm in the process of trying to switch from R to Python (mainly issues around general flexibility). With Numpy, matplotlib and ipython, I've am able to cover all my use cases save for merging 'datasets'. I would like to simulate SQL's join by clause (inner, outer, full) purely in python. R handles this with the 'merge' function.
I've tried the numpy.lib.recfunctions join_by, but it critical issues with duplicates along the 'key':

join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2',
        defaults=None, usemask=True, asrecarray=False)

Join arrays r1 and r2 on key key.
The key should be either a string or a sequence of string corresponding
to the fields used to join the array.
An exception is raised if the key field cannot be found in the two input
arrays.
Neither r1 nor r2 should have any duplicates along key: the presence
of duplicates will make the output quite unreliable. Note that duplicates
are not looked for by the algorithm.
source: http://presbrey.mit.edu:1234/numpy.lib.recfunctions.html

Any pointers or help will be most appreciated!

A: Suppose you represent the equivalent of a SQL table, in Python, as a list of dicts, all dicts having the same (assume string) keys (other representations, including those enabled by numpy, can be logically boiled down to an equivalent form).  Now, an inner join is (again, from a logical point of view) a projection of their cartesian product -- in the general case, taking a predicate argument on (which takes two arguments, one "record" [[dict]] from each table, and returns a true value if the two records need to be joined), a simple approach would be (using per-table prefixes to disambiguate, against the risk that the two tables might otherwise have homonimous "fields"):
def inner_join(tab1, tab2, prefix1, prefix2, on):
  for r1 in tab1:
    for r2 in tab2:
      if on(r1, r2):
        row = dict((prefix1 + k1, v1) for k1, v1 in r1.items())
        row.update((prefix2 + k2, v2) for k2, v2 in r2.items())
        yield row

Now, of course you don't want to do it this way, because performance is O(M * N) -- but, for the generality you've specified ("simulate SQL's join by clause (inner, outer, full)") there is really no alternative, because the ON clause of a JOIN is pretty unrestricted.
For outer and full joins, you need in addition to keep info identifying which records [[from one or both tables]] have not been yielded yet, and otherwise yield -- e.g. for a left join you'd add a bool, reset to yielded = False before the for r2 inner loop, set to True if the yield executes, and after the inner loop, if not yielded:, produce an artificial joined record (presumably using None to stand for NULL in place of the missing v2 values, since there's no r2 to actually use for the purpose).
To get any substantial efficiency improvements, you need to clarify what constraints you're willing to abide on regarding the on predicate and the tables -- we already know from your question that you can't live with a unique constraint on either table's keys, but there are many other constraints that could potentially help, and to have us guessing at what such constraints actually apply in your case would be a pretty unproductive endeavor.

A: Revisiting this question I originally asked...
The pandas library is a perfect solution. It supplies a 'data frame' class and a 'merge' technique.


text:
Q: When I reload page values don't change, they only do when I log in So, I want when the user reloads the page his statistics to change based on the database.
For example, let's say that I just registered and my statistics are Money-0, Diamond-0, Ruby-0 and then somehow I added 10 money to the user.
Now, what I want is the user to be able to see his new statistics(Money-10, Diamond-0, Ruby-0) only when he decides to reload the page.
I have added onload function to the body, but it doesn't seem to work.
The user statistics only change when the user logs out and then logs in again.
index2.php(Where the user statistics should be displayed)
<?php include('server.php') ?>

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>PwettyKittyPincesa</title>

  <link href="./style.css" type="text/css" rel="stylesheet" />

                <?php echo $_SESSION['username']; ?>

                <?php echo $_SESSION['money']; ?>

                <?php echo $_SESSION['diamonds']; ?>

                <?php echo $_SESSION['ruby']; ?>

                Level:<?php echo $_SESSION['level']; ?>

A: In this case, you don't need any javascript to achieve this. You can run all your session assignments at the top of the document. Also, you'll need to include session_start() at the very top of the document to ensure the session variables become global values. However, if you do not need to use these values across other pages, then you can just use standard variables to store the data instead of storing it in a session.
This is using session variables:
<?php
session_start();

include('server.php');

$queryThree = "SELECT * FROM `register` WHERE username='$username'";
$userStats = mysqli_query($db,$queryThree);
while($userStatsTwo = mysqli_fetch_assoc($userStats)){
  $_SESSION['userid'] = $userStatsTwo['ID'];
  $_SESSION['username'] = $userStatsTwo['username'];
  $_SESSION['diamonds'] = $userStatsTwo['diamonds'];
  $_SESSION['ruby'] = $userStatsTwo['ruby'];
  $_SESSION['money'] = $userStatsTwo['money'];
  $_SESSION['level'] = $userStatsTwo['level'];
}
?>

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>PwettyKittyPincesa</title>

  <link href="./style.css" type="text/css" rel="stylesheet" />

                <?php echo $_SESSION['username']; ?>

                <?php echo $_SESSION['money']; ?>

                <?php echo $_SESSION['diamonds']; ?>

                <?php echo $_SESSION['ruby']; ?>

                Level:<?php echo $_SESSION['level']; ?>

This is using variables:
<?php
include('server.php');

$queryThree = "SELECT * FROM `register` WHERE username='$username'";
$userStats = mysqli_query($db,$queryThree);
while($userStatsTwo = mysqli_fetch_assoc($userStats)){
  $userid = $userStatsTwo['ID'];
  $username = $userStatsTwo['username'];
  $diamonds = $userStatsTwo['diamonds'];
  $ruby = $userStatsTwo['ruby'];
  $money = $userStatsTwo['money'];
  $level = $userStatsTwo['level'];
}
?>

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <title>PwettyKittyPincesa</title>

  <link href="./style.css" type="text/css" rel="stylesheet" />

                <?php echo $username; ?>

                <?php echo $money; ?>

                <?php echo $diamonds; ?>

                <?php echo $ruby; ?>

                Level:<?php echo $level; ?>


text:
Q: Place a comment on a specific post in PHP I'm doing a project for school, it is some similar as Instagram.
So you can post a photo on your timeline and then other users can place a comment on this photo.
This comment option is succesfully done: You can place a comment and the comment comes into the database.
Comment classe: PHP code
public function __set($p_sProperty, $p_vValue)
{
    switch($p_sProperty)
    {
        case "Comment":
            $this->m_sComment = $p_vValue;
            break;
    }
}

public function __get($p_sProperty)
{
    $vResult = null;
    switch($p_sProperty)
    {
    case "Comment":
        $vResult = $this->m_sComment;
        break;
    }
    return $vResult;
}

    public function Save() {
        $conn = Db::getInstance();
        //$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $statement = $conn->prepare('INSERT INTO comment(comment, postID, userID) VALUES(:comment)');
        $statement->bindValue(':comment', $this->Comment);
        $statement->execute();
    }

    public function GetRecentActivities($p_iPostID) {
        $conn = Db::getInstance();
        $allComments = $conn->query("SELECT * FROM comment ORDER BY id DESC;");
        return $allComments;
    }

}

But now the question is:
* Now the comment on a photo comes on every post and not on the specific post?
  In the URL of the post , i send a specific POSTID.    http://i.stack.imgur.com/IkJGL.png
How can i place the comment only on the post with the correct POSTID ?

A: In the answer I am assuming you use GetRecentActivities to get the comments for a post.
I noticed you're not setting the postID field in the database, why is that? The postID field will help you map a post to a comment.Without it, you (and SQL) can't determine the context in which the comment was written. I'm sure you know how to add postID to the INSERT statement you provided, but for reference:
$stmt = $conn->prepare("INSERT INTO comments (comment, postID) VALUES (:comment, :postID)");
$stmt->bindValue(':comment', $this->Comment);
$stmt->bindValue(':postID', $this->PostID);
$stmt->execute();

In your SQL where you are calling SELECT * FROM comment ORDER BY id DESC; you can add a WHERE clause to "filter" the data being returned. In your case this would be the syntax:
SELECT * FROM comment WHERE postID = <post_id> ORDER BY id DESC;

More information on what you can pass in your SELECT statement at http://dev.mysql.com/doc/refman/5.7/en/select.html


text:
Q: gnuradio source only outputting zeros I made a custom source block that is reading switch values on a zedboard. It is accessing them via a proc driver that I wrote. The /var/log/kern.log is reporting proper output. The debug printf in the source block is reporting proper output.
However pushing the data to a filesink as well as a GUI number sink is only reading zeros. Did I not set up the block properly?
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <gnuradio/io_signature.h>
#include "switches_impl.h"
#include <stdio.h>
#include <stdlib.h>
#include <uinstd.h>

namespace gr {
  namespace zedboard {

    switches::sptr
    switches::make()
    {
      return gnuradio::get_initial_sptr
        (new switches_impl());
    }

    /*
     * The private constructor
     */
    switches_impl::switches_impl()
      : gr::block("switches",
             gr::io_signature::make(0,0,0),
              gr::io_signature::make(1, 1, sizeof(unsigned int *)))
    {}

    /*
     * Our virtual destructor.
     */
    switches_impl::~switches_impl()
    {
    }

    void
    switches_impl::forecast (int noutput_items, gr_vector_int &ninput_items_required)
    {
      /* <+forecast+> e.g. ninput_items_required[0] = noutput_items */
    }

    int
    switches_impl::general_work (int noutput_items,
                       gr_vector_int &ninput_items,
                       gr_vector_const_void_star &input_items,
                       gr_vector_void_star &output_items)
    {
      //const <+ITYPE+> *in = (const <+ITYPE+> *) input_items[0];
      unsigned int *out = (unsigned int *) output_items[0];

      // Do <+signal processing+>
      // Tell runtime system how many input items we consumed on
      // each input stream.

        char buffer[5];
        size_t size = 1;
        size_t nitems = 5;
        FILE* fp;

        fp = fopen("/proc/zedSwitches","r");
        if (fp == NULL)
        {
            printf("Cannot open for read\n");
            return -1;
        }
        /*
        Expect return format:
        0x00
        */
        fread(buffer, size, nitems, fp);
        fclose(fp);
        out=(unsigned int *)strtoul(buffer,NULL,0);
        printf("read: 0x%02x",out);

      consume_each (noutput_items);

      // Tell runtime system how many output items we produced.
      return noutput_items;
    }

  } /* namespace zedboard */
} /* namespace gr */

A: A pointer is a pointer to data, usually:
  unsigned int *out = (unsigned int *) output_items[0];

out refers to the buffer for your output.
But you overwrite that pointer with another pointer:
    out=(unsigned int *)strtoul(buffer,NULL,0);

which just bends around your copy of that pointer, and doesn't affect the content of that buffer at all. Basic C!
You probably meant to say something like:
    out[0]= strtoul(buffer,NULL,0);

That will put your value into the first element of the buffer.
However, you tell GNU Radio that you not only produced a single item (the line above), but noutput_items:
  return noutput_items;

That must read
  return 1;

when you're only producing a single item, or you must actually produce as many items as you return.
Your consume_each call is nonsensical – GNU Radio Sources are typically instances of gr::sync_block, which means that you'd write a work() instead of a general_work() method as you did.
From the fact alone that this is a general_work and not a work I'd say you haven't used gr_modtool (with block type set to source!) to generate the stub for this block – you really should. Again, I'd like to point you to the Guided Tutorials which should really quickly explain usage of gr_modtool as well as the underlying GNU Radio concepts.


text:
Q: Pulling Gmail's 'Other Contacts' group via the Google Contacts API I'm trying to pull my Gmail contacts, so I can auto-complete on the 3,000 or so contacts I have within Gmail.  Using the Google Contacts Data API, I'm able to get a list of (1) default contacts and (2) groups.
However, (1) the default contacts (http://www.google.com/m8/feeds/contacts/default/full) only pulls contacts in my 'My Contacts' group, and (2) when I look for my groups (through the interactive samples Google provides), 'Other Contacts' is not an available group to pull from.
This leads to a pretty terrible auto-complete experience: I've got about 100 'My Contacts' members, compared to 3,000 contacts in 'Other Contacts'; I can only imagine that other Gmail users are in roughly the same boat.
I've looked around the interwebs, but haven't found much:

*

*Google explaining directory vs private contacts

*Google explaining default contact groups

*A similar complaint on the Google Contacts API google group from 2008
So far, my backup is just asking for username/password and scraping (or using IMAP).  Is there a better way out there?

A: For (1), are you sure you're getting "My Contacts" and not just the first page of results for "All Contacts"? From http://code.google.com/apis/contacts/docs/3.0/developers_guide_protocol.html:
"Note: The feed may not contain all of the user's contacts because there's a default limit on the number of results returned. For more information, see the max-results query parameter in Retrieving contacts using query parameters."
For (2), https://mail.google.com/support/bin/answer.py?hl=en&answer=97952, which you linked to, says "Other Contacts includes any contacts that haven't already been categorized into My Contacts or another contact group." In other words, it doesn't show up because the group doesn't really exist.


text:
Q: Need help finding UMVUE for a Poisson Distribution My fellow classmates and I are stuck on a homework problem that is a three part problem to find the UMVUE of a Poisson distribution.
The problem goes like this:
Let X ~ Pois$(\lambda$), and we want to estimate $\theta=e^{-\lambda}$.
a) Find the Rao-Cramer lower bound for an unbiased estimator for $\theta$ (based on a sample of size n). Hint: The differentiation needs to be with respect to $\theta$, not $\lambda$.
So the majority of us used the Fisher Information Index to get:
$I_1(\theta) = \Sigma ((\frac{d}{d\theta}ln(e^{-\lambda}\frac{\lambda^x}{x!}))^2*e^{-\lambda}\frac{\lambda^x}{x!})$
We then substituted in our ln $e^{-\lambda}$ for $\theta$.
$I_1(\theta) = \Sigma ((\frac{d}{d\theta}ln(\theta\frac{\lambda^x}{x!}))^2*e^{-\lambda}\frac{\lambda^x}{x!})$
After that, we broke out the ln function:
$I_1(\theta) = \Sigma ((\frac{d}{d\theta}ln(\theta) + ln(\lambda^x) - ln(x!))^2*e^{-\lambda}\frac{\lambda^x}{x!})$
Then we took the derivative with respect to $\theta$.
$I_1(\theta) = \Sigma ((\frac{1}{\theta})^2*e^{-\lambda}\frac{\lambda^x}{x!})$
This is where we have a little difference of opinion because one of us came up with the final answer as being:
$\frac{ne^{\lambda}}{\theta}$
He took the final answer by cancelling one of the $\theta$s and then using the Taylor series to get $e^{\lambda}$
Where two of us got the answer as being:
$\frac{n}{\theta^2}$
We don't know which is right because either one could make sense.
If someone could please let us know on this, we would be grateful.
Part b we are also stuck on as well.
b) Show that $T=\Sigma X_i$ is a complete sufficient statistics for $\theta=e^{-\lambda}$
Now, from our notes, we have that a probability distribution belongs to an exponential family if it can be written in the form $e^{A(x)B(\theta)+C(X)+D(\theta)}$
So we start out and we get:
$e^{-\lambda}\frac{\lambda^x}{x!}$
$=e^{-\lambda}e^{ln(\frac{\lambda^x}{x!})}$
$=e^{-\lambda}e^{xln(\lambda)-ln(x!)}$
This is where we get stuck because we are not sure 1) where to put the T into this equation and 2) how are we supposed to relate this back to the theta.
So far, we have only come up with:
$=e^{ln(\theta+\Sigma X_i ln(\lambda)-ln(\Sigma X_i!)}$
We know we are probably completely and totally wrong on this.
When it comes to part c, of our equation, we are a bit stuck as to what to do.
Part c goes like:
If we use $T^* = (\frac{n-1}{n})^{\Sigma X_i}$ as an estimator for $\theta=e^{-\lambda}$, as the Rao-Blackwell Theorem indicated, combine your findings in Parts (a) and (b) to determine Var($T^*$).
We know that this is a UVMUE that can probably be solved by the Lehmann-Scheffe theorem.
The thing is that we just don't know how to really apply it or how we can use what we find from parts a and b to get Var($T^*$).
If anyone can help out with any parts of this problem, we will be very grateful because we are very, very, very stuck on this.

A: (a)
As I mentioned in comment, you should focus on the parameter of interest $\theta$, it is not good to write some formulas contain both $\theta$ and $\lambda$. Following this, it is routine to get the log-likelihood (denote $\sum X_i$ by $T$ and omit terms which don't contain $\theta$) :
$$\ell(\theta) = n\log\theta + T\log(-\log\theta)$$
Therefore,
$$\ell'(\theta) = \frac{n}{\theta} + \frac{T}{\theta\log\theta}$$
$$\ell''(\theta) = -\frac{n}{\theta^2} - \frac{T(\log\theta + 1)}{(\theta\log\theta)^2}$$
As $E_\theta(T) = -n\log\theta$, it follows that the Fisher information is
$$I(\theta) = -E_\theta(\ell''(\theta)) = -\frac{n}{\theta^2\log\theta}$$
Hence the C-R lower bound is given by $1/I(\theta) = \boxed{-\theta^2\log(\theta)/n}$.
Since $\theta = P_\theta(X_i = 0)$, an unbiased estimate of $\theta$ could be the sample proportion which takes 0, namely,
$$\hat{\theta} = \frac{\sum_{i = 1}^n \mathrm{I}\{X_i = 0\}}{n}.$$
Or even simpler, just take
$$\hat{\theta} = \mathrm{I}\{X_1 = 0\}.$$
(b) This is routine application of Fisher's factorization theorem and the property of exponential family. Not hard if you write things clearly.
(c) You may verify that (recall $T \sim \mathrm{Poisson}(n\lambda)$, and here would be easier to go back to work with $\lambda$ but keep in mind $\theta$ and $\lambda$ is one-to-one correspondence):
$$E_\theta(T^*) = \sum_{k = 0}^\infty \left(1 - \frac{1}{n}\right)^k e^{-n\lambda}\frac{(n\lambda)^k}{k!} = e^{-n\lambda}e^{n\lambda(1 - n^{-1})}
 = \theta.$$
Hence $T^*$ can be (also) used as an unbiased estimator of $\theta$ (in fact, it is the Rao-Blackwellization of $\hat{\theta}$, see the last paragraph of this answer).
In addition,
\begin{align*}
E_\theta((T^*)^2) = \sum_{k = 0}^\infty \left(1 - \frac{1}{n}\right)^{2k} e^{-n\lambda}\frac{(n\lambda)^k}{k!} =
e^{-n\lambda}e^{n\lambda(1 - n^{-1})^2} = \theta^{2 - \frac{1}{n}}.
\end{align*}
It then follows that
$$\mathrm{Var}_\theta(T^*) = \theta^{2 - \frac{1}{n}} - \theta^2.$$
One may verify that we indeed have the C-R lower bound is strictly less (as @81235 pointed out in the comment) than $\mathrm{Var}_\theta(T^*)$, as the consequence of the famous inequality
\begin{align*}
e^{\frac{\lambda}{n}} > 1 + \frac{\lambda}{n}.
\end{align*}
On the other hand, $\mathrm{Var}_\theta(T^*)$ is indeed not bigger than $$\mathrm{Var}_\theta(\hat{\theta}) = P(X_1 = 0)(1 - P(X_1 = 0)) = e^{-\lambda}(1 - e^{-\lambda}) = \theta - \theta^2.$$
Together, we observe that

*

*$T^*$ is the UMVUE for $\theta$ (as the Rao-Blackwell Theorem guarantees);

*The UMVUE does not necessarily achieve the C-R lower bound.

Part (c) relates to part (a) and part (b) in "as Rao-Blackwell Theorem indicated", which is worthwhile to elaborate. Basically, we want to show that the Rao-Blackwellized estimate $E(\hat{\theta} \mid T)$ based on the the estimate $\hat{\theta}$ proposed in part (a) exactly yields $T^*$. Indeed, applying the classical distributional result
\begin{align*}
X_1 \mid X_1 + \cdots + X_n = t \sim \text{Binom}(t, n^{-1}),
\end{align*}
it follows that
\begin{align*}
E(\hat{\theta} \mid T) = P(X_1 = 0 \mid T) = (1 - n^{-1})^T = T^*,
\end{align*}
hence the form of $T^*$.

A: How about the indicator function:
$g(X_1)=I_{(X_1=0)}=\begin{cases}
1,  & \text{if $X_1=0$ } \\
0 & \text{otherwise}  \\
\end{cases}$

A: $x_1,...,x_n\sim Pois(\lambda)$
(a)
We want to estimate $\theta=e^{-\lambda}$, which is exactly $P(x_1=0)$. We take $T(x)=I\{x_1=0\}$ as an estimator. It might look dumb, but it is an unbiased estimator:
$$E[T(x)]=1\cdot P(x_1=0) + 0\cdot P(x_1 \neq 0)=P(x_1=0)=\frac{e^{-\lambda}\cdot\lambda^0}{0!}=e^{-\lambda}=\theta$$
Now, let's loot at the MSE:
$$E[(T(x)-\lambda)^2]=E[(T(x)-\theta+\theta-\lambda)^2]=E[(T(x)-\theta)^2]-2E[(T(x)-\theta)(\theta-\lambda)]+E[(\theta-\lambda)^2]$$
$T(x)$ is an unbiased estimator of $\theta$ and thus $2E[(T(x)-\theta)(\theta-\lambda)]$ falls. Using the MSE decomposition we get $b^2(T,\lambda)=(\theta-\lambda)^2$, so the bias of $T$ w.r.t. $\lambda$ is simply $\theta-\lambda$.
Now, it is time for the mighty CRB:
$$Var(T)=E[(T(x)-\theta)^2]-(\theta-\lambda)^2 \geq \frac{\left(1+\frac{d}{d\lambda}b(T,\lambda)\right)^2}{I(\lambda)}$$
a momentary pause: the Fisher information for the Poisson is $I(\lambda)=\frac{1}{\lambda}$, so:
$$Var(T)\geq\lambda \left(1+\frac{d}{d\lambda}(\theta-\lambda)\right)^2$$
another pause: we were hinted to differentiate w.r.t. $\theta$, so we need do substitute $\lambda=-log(\theta)$ and substitute the derivation:
$$\frac{db}{d\lambda}=\frac{db}{d\theta}\cdot\frac{d\theta}{d\lambda}=\frac{db}{d\theta}\cdot\frac{d}{d\lambda}(e^{-\lambda})=\frac{db}{d\theta}\cdot(-e^{-\lambda})=-\theta\cdot\frac{db}{d\theta}$$
So we substitute:
$$Var(T)\geq -log(\theta) \left(1-\theta\frac{d}{d\theta}(\theta+log(\theta))\right)^2=-log(\theta) \left(1-\theta\left(1+\frac{1}{\theta}\right)\right)^2=-log(\theta) (1-\theta -1)^2$$
and finally get:
$$Var(T)\geq-log(\theta)\theta^2$$

(b)
$$L(x,\lambda)=\prod_{i=1}^{n}{\frac{e^{-\lambda}\lambda^{x_i}}{x_i!}}=\frac{1}{\prod{x_i!}}e^{-n\lambda}\lambda^{\sum{x_i}}=\frac{1}{\prod{x_i!}}exp(-n\lambda)exp(log(\lambda)\sum{x_i})$$
So by denoting $\eta=log(\lambda), S(x)=\sum{x_i}, A(\eta)=n\lambda, h(x)=\frac{1}{\prod{x_i!}}$ we get a representation of the likelihood function as an exponential family.
Reparametrizing using $\theta$ we get $\eta=log(-log(\theta)), A(\eta)=-n log(\theta), S(x)=\sum{x_i}, h(x)=\frac{1}{\prod{x_i!}}$, again en exponential family. This is important as we get that $S(x)=\sum{x_i}$ is a sufficient statistic due to properties of exponential families (Fisher-Neyman factorization theorem).
$S(x)$ is the sum of $x_1,...,x_n\sim Pois(-log(\theta))$, so $S(x)$ itself is a Poisson RV with parameter $-nlog(\theta)$. Now, let $g(S(x))$ be a function s.t $E[g(S)]=0$:
$$E[g(S)]=\theta^{-n}\sum_{s=0}^{\infty}{g(s)\cdot\frac{\left(-n log(\theta) \right)^s}{s!}}$$
The only term that can be zero is $g(s)$, so if $E[g(S(x))]=0$ we conclude that $g(s)=0$ for all values of $s$, hence $S(x)=\sum{x_i}$ is a complete statistic. QED!

(c)
This is almost cheating: The corollary from the Lehmann-Scheffé theorem is that if S is a complete sufficient statistic, then applying the R-B procedure would yield the UMVUE.
last momentary pause: we were told "combine your findings in Parts (a) and (b)", so let's do it
In part (a) we got $Var(T)\geq-log(\theta)\theta^2$, in part (b) we got that $S(x)=\sum{x_i}$ is complete sufficient statistic, R-B has yielded $T^*$, so $Var(T^* )\geq-log(\theta)\theta^2$. That's it.
PS It would be proper to thank Prof. Pavel Chigansky of HUJI, who has taught us this exact problem in his statistical inference course.


text:
Q: Embedding Google Drive folder in website stopped working I have had the following iframe code for embedding a folder on my Wordpress website (http://topnotchcanines.com/tnc_events/akc-dec/) for about 11 months and it has worked beautifully.  Yesterday I had a client tell me my folder is not displaying.  I am now getting a message in the lower left "waiting for clients6.google.com".  I have given them a link directly to the google folder since I have an event coming soon. But..  really need to get this working again.
Any advice ?
What I have discovered:
   If I am logged into my Drive account everything displays nicely.  If I am not logged in,  I get the above message.  Yes the folder is shared with "Anyone with the link can view"
   The problem occurs in Chrome, Edge and Safari on my ipad.
Has Google changed something ??

A: Please check your connection to Google server, clear browser cache, try on different devices. I can see your files even in Incognito mode (not logged in any Google accounts).


text:
Q: For odd $n$, $n\times n$ matrix with real entries have at least one real eigenvalues. Reading a linear algebra textbook, I encounter

For odd $n$, $n\times n$ matrix with real entries have at least one real eigenvalues.

I noticed in Determinant-free proof that a real $n \times n$ matrix has at least one real eigenvalue when $n$ is odd., the proof without determinant are posts.
It seems for me with the trick of determinant, this problem might be easy.  The first thing I came up with is $\det(A_n-\lambda I_n)$ but this does not guarantee that the solution has at least one real eigenvalues. i.e., setting characteristic polynomial as $f_{A}(\lambda) =\lambda^n + a_{n-1} \lambda^{n-2} + \cdots + a_0$ with $a_i \in \mathbb{R}$, we do not know one of $\lambda$ should be real.
What can be the simple proof with determinants?

A: Setting the characteristic polynomial as $f_{A}(\lambda) =\lambda^n + a_{n-1} \lambda^{n-2} + \cdots + a_0$ with $a_i \in \mathbb{R}$, we know that $f_A$ has at least one real root when $n$ is odd by the intermediate value theorem.
As $\lambda \to -\infty$, $f_A(\lambda) \to - \infty$; as $\lambda \to +\infty$, $f_A(\lambda) \to +\infty$. We know both of these, because that's the behavior of $\lambda^n$ for large $|\lambda|$, and $\lambda_n$ will eventually dominate over the other terms.
Therefore there must be some very negative value of $\lambda$ where $f_A(\lambda)<0$, and some very positive value of $\lambda$ where $f_A(\lambda)>0$. Between these, there must be a value of $\lambda$ where $f_A(\lambda)=0$, and this gives us a real eigenvalue.

A: If $n$ is odd, then
$$f_A( \lambda) \to \infty$$
as $ \lambda \to \infty$
and
$$f_A( \lambda) \to -\infty$$
as $ \lambda \to -\infty.$
The IVT shows now that there is $ \lambda_0 \in \mathbb R$ such that $f_A( \lambda_0=0.$

A: For odd $n$, the characteristic polynomial of an $n\times n$ real matrix has real coefficients and odd degree, but an odd degree polynomial with real coefficients has a real root by the intermediate value theorem.

A: I think you can use your characteristic polynomial. In fact, if you factorize $f_A$, you get a result like this :
$$f_A(\lambda)=\prod \underbrace{(\lambda-\lambda_i)^{a_i}}_{\text{real eigenvalues}}\times\prod \underbrace{(b_i\lambda^2+c_i\lambda+d_i)^{2e_i}}_{\text{corresponds to complex eigenvalues}} $$
If you had only complex eigenvalues, it would mean that $\forall i, a_i=0 $, so that $\sum 2e_i=n $. But n is odd, and $2e_i$ is always even, so $\sum 2e_i $ is also even, which is a contradiction.
$$ $$
So you get that $ \exists i, a_i\neq 0$, so that there is at least one real eigenvalue

A: The characteristic polynomial is of odd degree.  Since complex roots come in conjugate pairs, and by the fundamental theorem of algebra there are an odd number of roots over $\Bbb C$ (counting multiplicity), there must be a real root.


text:
Q: How to use PHP constant in routing YAML I'm using Symfony 3.4
I managed to get the PHP constant to work for a service (as described in the documentation). But I can't figure out how to get it to work in a routing file. Here's what I have so far.
Entity:
namespace CompanyName\AppBundle\Entity\SomeDirectory;

class MyEntity
{
    public const STATUS__CREATED = 1;
}

routing.yml:
view_my_entity_with_status_created:
  path:       /created/
  defaults:
    _controller: "AppBundle:SomeOtherDirectory/Something:index"
    status: !php/const CompanyName\AppBundle\Entity\SomeDirectory\MyEntity::STATUS__CREATED

SomethingController:
public function indexAction(?int $status = null): Response
{
 // ...
}

From what I can tell the !php/const is being ignored since status is always null.

A: Depending on your symfony version, this can be done with specific typo:
https://symfony.com/blog/new-in-symfony-3-2-php-constants-in-yaml-files
Before 3.2 it is not possible
from 3.2 to 3.4
arguments:
            - '@app.other_service'
            - !php/const:AppBundle\Entity\BlogPost::MUM_ITEMS
            - !php/const:Symfony\Component\HttpKernel\Kernel::VERSION

after 3.4:
arguments:
            - '@app.other_service'
            - !php/const AppBundle\Entity\BlogPost::MUM_ITEMS
            - !php/const Symfony\Component\HttpKernel\Kernel::VERSION

for your routing file:
# config/routes.yaml
blog_list:
    path:       /blog/{page}
    controller: AppBundle:SomeOtherDirectory/Something:index
    defaults:
        status: !php/const CompanyName\AppBundle\Entity\SomeDirectory\MyEntity::STATUS__CREATED

A: You can't in Symfony 3.4.
Using !php/const in routing YAML configuration files was not enabled until Symfony 4.1.
While the feature was added to YamlFileLoader in 3.2, it was only enabled by default for the dependency injection component, not for the routing component.
This is when the feature was merged.


text:
Q: Connection reset by peer and No space left on device errors for apache spark? I kept getting the following on my stack trace very often
WARN TransportChannelHandler: Exception in connection from /172.31.3.245:46014
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
at sun.nio.ch.IOUtil.read(IOUtil.java:192)
at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)
at io.netty.buffer.PooledUnsafeDirectByteBuf.setBytes(PooledUnsafeDirectByteBuf.java:221)
at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:898)
at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:242)
at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:119)
at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:468)
at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:382)
at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:354)
at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:112)

and eventually I get No space left on device error but after researching I found that I could do .set("spark.local.dir", "/home/ubuntu/sparktempdata"); this has reduced the frequency of "No space left on device" errors in my trace however there is one more remaining such as the one below and I am not sure how to fix it?
16/09/06 08:34:18 ERROR FileAppender: Error writing stream to file /usr/local/spark/work/app-20160906083355-0000/1/stderr
java.io.IOException: No space left on device
    at java.io.FileOutputStream.writeBytes(Native Method)
    at java.io.FileOutputStream.write(FileOutputStream.java:326)
    at org.apache.spark.util.logging.FileAppender.appendToFile(FileAppender.scala:92)
    at org.apache.spark.util.logging.FileAppender$$anonfun$appendStreamToFile$1.apply$mcV$sp(FileAppender.scala:75)
    at org.apache.spark.util.logging.FileAppender$$anonfun$appendStreamToFile$1.apply(FileAppender.scala:62)
    at org.apache.spark.util.logging.FileAppender$$anonfun$appendStreamToFile$1.apply(FileAppender.scala:62)
    at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1287)
    at org.apache.spark.util.logging.FileAppender.appendStreamToFile(FileAppender.scala:78)
    at org.apache.spark.util.logging.FileAppender$$anon$1$$anonfun$run$1.apply$mcV$sp(FileAppender.scala:39)
    at org.apache.spark.util.logging.FileAppender$$anon$1$$anonfun$run$1.apply(FileAppender.scala:39)
    at org.apache.spark.util.logging.FileAppender$$anon$1$$anonfun$run$1.apply(FileAppender.scala:39)
    at org.apache.spark.util.Utils$.logUncaughtExceptions(Utils.scala:1857)
    at org.apache.spark.util.logging.FileAppender$$anon$1.run(FileAppender.scala:38)

and when I open the file /usr/local/spark/work/app-20160906083355-0000/1/stderr I see the following
INFO Utils: Fetching spark://172.31.11.187:58519/jars/analytics-1.0-SNAPSHOT.jar to /tmp/spark-69b1866b-f302-4ab8-a25f-f2a8cc1f4b4f/executor-99c9eeb0-d45c-4619-8054-7f6d3f15803c/spark-c28a16b5-5ac5-440b-9e4d-7ed1b1b8bcbe/fetchFileTemp6564441043886275791.tmp
16/09/06 08:34:18 WARN TransportChannelHandler: Exception in connection from /172.31.11.187:58519
java.io.IOException: Broken pipe
        at sun.nio.ch.FileDispatcherImpl.write0(Native Method)
        at sun.nio.ch.FileDispatcherImpl.write(FileDispatcherImpl.java:60)
        at sun.nio.ch.IOUtil.writeFromNativeBuffer(IOUtil.java:93)
        at sun.nio.ch.IOUtil.write(IOUtil.java:51)
        at sun.nio.ch.SinkChannelImpl.write(SinkChannelImpl.java:167)
        at org.apache.spark.rpc.netty.NettyRpcEnv$FileDownloadCallback.onData(NettyRpcEnv.scala:395)
        at org.apache.spark.network.client.StreamInterceptor.handle(StreamInterceptor.java:69)
        at org.apache.spark.network.util.TransportFrameDecoder.feedInterceptor(TransportFrameDecoder.java:202)
        at org.apache.spark.network.util.TransportFrameDecoder.channelRead(TransportFrameDecoder.java:70)
        at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:308)
        at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:294)
        at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:846)
        at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
        at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:511)
        at io.netty.channel.nio.NioEventLoop.pro
                                                                                425,2-9       Bot

here is my df -h on my worker node. Also, All my machines have same amount of resources
Filesystem      Size  Used Avail Use% Mounted on
udev            7.4G   12K  7.4G   1% /dev
tmpfs           1.5G  344K  1.5G   1% /run
/dev/xvda1      7.8G  7.3G   92M  99% /
none            4.0K     0  4.0K   0% /sys/fs/cgroup
none            5.0M     0  5.0M   0% /run/lock
none            7.4G     0  7.4G   0% /run/shm
none            100M     0  100M   0% /run/user
/dev/xvdb        37G   49M   35G   1% /mnt

A: I think this error is due to broken pipe. basically the client(say your laptop did not hear anything from the server for a long time, so it assumes it is not connected any more. use SIGPIPE command and set it two 2 minutes. the below link will help you.
broken pipe link


text:
Q: Load large csv's directly into Big Query without cloud storage? I'm looking into loading CSV(s) into Big Query from a remote server, and they will be greater than 10MB, even if compressed. My understanding is that to load remote files directly into Big Query, this would technically follow the process of "load data from local files" implemented in a script on the remote server where the data lives.
According to big query documentation, this is limited to 10MB/File. Do I need to load files into GCS and then use BQ Data Transfer Service for this task? Is breaking down huge CSV's into a bunch of 10MB CSV's a practical option? This needs to be scalable.

A: The right way is to upload the file in Cloud Storage and then to perform a load job from GCS (not a Transfer Service).
The load job is powerful. It's very fast, and you can import one a several file in the same time and in the same table!
It's definitively the best way to be scalable.


text:
Q: await js async function (promise) inside a go function I am looking to integrate indexdb in a wasm based app. How do you "await" in a go function a promise from a js function. Here is the example
    async getItem(key) {
        try{
            const out = await database.getItem(key);
            return out;
        }catch(err){
            return null;
        }
    }

and in go
func Get(key string)[]byte{

    found :=  js.Global().Get("Store").Call('getItem', key )
    // await for found
    // convert js.Value to to []byte
    return nil

}

Async callbacks are fine too.
LE: one bad solution would be to create a go routine with an infinite loop waiting until a DOM variable exists like global.solution+ID to be set. But I believe this is a bad solution

A: You can use the then method from the Promise object to wait for the result, something like this:
package main

import (
    "fmt"
    "syscall/js"
)

func main() {
    wait := make(chan interface{})
    js.Global().Call("sayHello", 5000).Call("then", js.FuncOf(func(this js.Value, args []js.Value) interface{} {
        fmt.Println(args[0])
        wait <- nil
        return nil
    }))
    <-wait
    fmt.Println("we're done here")
}

Notice that we are using a channel to actually wait in the Go code. We need to do that because the Go program must still be running while receiving the callback from Javascript.
The index.html file:
<html>
    <head>
        <meta charset="utf-8"/>
        <script src="wasm_exec.js"></script>
        <script>
            const go = new Go();
            WebAssembly.instantiateStreaming(fetch("main.wasm"), go.importObject).then((result) => {
                go.run(result.instance);
            });

            function sayHello(time) {
                return new Promise(resolve => {
                    console.log('waiting %dms and resolving', time)
                    setTimeout(() => resolve('hola!'), time)
                })
            }
        </script>
    </head>
    <body></body>
</html>

A: Promise, real example (go.1.18):
type DevicesData struct {
    DeviceId string
    GroupId string
    Kind string
    Label string
}

list = make([]DevicesData, 0)
end := make(chan struct{})

// golang has a bug:
// enumerateDevices() returns an array, but, go returns an object.
forEach := js.FuncOf(func(_ js.Value, args []js.Value) any {
    data := DevicesData{
        DeviceId: args[0].Get("deviceId").String(),
        GroupId:  args[0].Get("groupId").String(),
        Kind:     args[0].Get("kind").String(),
        Label:    args[0].Get("label").String(),
    }
    list = append(list, data)

    // aways return nil
    return nil
})

// promise success function
var success = js.FuncOf(func(_ js.Value, args []js.Value) interface{} {
    args[0].Call("forEach", forEach)
    end <- struct{}{}

    // aways return nil
    return nil
})

var failure = js.FuncOf(func(this js.Value, args []js.Value) interface{} {
    err = errors.New(args[0].Get("message").String())

    // aways return nil
    return nil
})

js.Global().Get("navigator").Get("mediaDevices").Call("enumerateDevices").Call("then", success, failure)

// wait async call
<-end


text:
Q: How does vibration motor create motion in particular direction? I am building an autonomous robot for robot swarm reasonably small in size (say 30mm x 30mm). I was analyzing such robot's locomotion and found that coin vibration motors are used widely as opposed to generic DC motors with wheels. I get that the the coin vibration motors are very cheap and can keep the overall size of the robot fairly small, whereas with DC motors, wheels will be involved which will make the overall body size of the robot bigger compared to using vibration motors.
My question is how do coin vibration motors create forward motion. Say a robot uses two of these motors. How can it be determined which direction the robot will travel and WHY? Is this something to do with centripetal forces?

A: Vibration does not in itself create continuous motion in one direction- the center of mass stays exactly fixed in the same place in the absence of external forces (assuming it was not moving to begin with).
If you have feet that slip more easily in one direction than the other then vibration can cause motion. There are other options, but it's the interaction of the object with the environment that causes motion.
Here is a paper on the subject. Link expired, new link


text:
Q: Unable to read HDF5 file in R which was written using Python I wrote a Pandas dataframe on disk using to_hdf() function of a dataframe (Pandas / Python 2.7).
I want to read this dataframe in R-environment. I am using the rhdf5 package in R to read the file.
Python code to dump the dataframe
data.to_hdf('myDataFrame.h5', 'table', append=True) #data is a pandas dataframe

R code to read it
library(rhdf5)
data <- h5read("myDataFrame.h5", "table")

How can this be achieved? Is there a better way to exchange dataframes between the 2 languages? I don't want to involve .csv as it will lose all meta information and will be slower to parse every time I read.
I don't have error messages, only a couple of warnings. But the data I read is nowhere similar to what I want and I am unable to find what I stored. This is what it looks like when I try to explore the read object. Whereas the dataframe I stored has shape (1,400,000 x 267).
List of 2
 $ _i_table:List of 1
  ..$ index:List of 10
  .. ..$ abounds  : int [1:680(1d)] 0 2048 4096 6144 8192 10240 12288 14336 16384 18432 ...
  .. ..$ bounds   : int [1:135, 1:5] 2048 4096 6144 8192 10240 12288 14336 16384 18432 20480 ...
  .. ..$ indices  : int [1:278528, 1:5] 0 0 0 0 0 0 0 0 0 0 ...
  .. ..$ indicesLR: int [1:278528(1d)] 2165 2165 2165 2165 2165 2165 2165 2165 2165 2165 ...
  .. ..$ mbounds  : int [1:680(1d)] 1024 3072 5120 7168 9216 11264 13312 15360 17408 19456 ...
  .. ..$ mranges  : int [1:5(1d)] 140288 418816 697344 975872 1254400
  .. ..$ ranges   : int [1:2, 1:5] 0 278527 278528 557055 557056 835583 835584 1114111 1114112 1392639
  .. ..$ sorted   : int [1:278528, 1:5] 0 1 2 3 4 5 6 7 8 9 ...
  .. ..$ sortedLR : int [1:278665(1d)] 1392640 1392641 1392642 1392643 1392644 1392645 1392646 1392647 1392648 1392649 ...
  .. ..$ zbounds  : int [1:680(1d)] 2047 4095 6143 8191 10239 12287 14335 16383 18431 20479 ...
 $ table   :'data.frame':   1400000 obs. of  6 variables:
  ..$ index         : int [1:1400000(1d)] 0 1 2 3 4 5 6 7 8 9 ...
  ..$ values_block_0: num [1:1400000(1d)] NA NA NA NA NA NA NA NA NA NA ...
  ..$ values_block_1: num [1:1400000(1d)] NA NA NA NA NA NA NA NA NA NA ...
  ..$ values_block_2: num [1:1400000(1d)] NA NA NA NA NA NA NA NA NA NA ...
  ..$ values_block_3: num [1:1400000(1d)] NA NA NA NA NA NA NA NA NA NA ...
  ..$ values_block_4: num [1:1400000(1d)] NA NA NA NA NA NA NA NA NA NA ...


text:
Q: JS not returning value of a variable Q display 0 and not the value of c, what is wrong with these code?
Am i wrong in the return statement?
main js file
var q=0;
search(a,21,q);
document.getElementById("demo1").innerHTML = q;

another js file
function search(array, target, c) {
  left = 0;
  right = array.length - 1;

  while (left <= right) {
    mid = (left + right) / 2;
    if (array[Math.trunc(mid)] == target) {
      c = Math.trunc(mid);
      console.log(c);

      return array, target, c;

    } else if (target < array[mid]) {
      right = Math.trunc(mid) - 1;
    } else {
      left = Math.trunc(mid) + 1;
    }
  }
}

A: Number in JS is a primitive data type and those types are passed by value, so it will copy the value of q into a new variable named c and if you change c, q will not change.
you can return array[Math.trunc(mid)] and do something like this:
document.getElementById("demo1").innerHTML = search(a,21);


text:
Q: What do these skills do in Don't get fired? I'm playing Don't get fired on Android and I came across some skills which I don't understand.
What do the skills "workload", "faster touch work" and "team work" do?
I tried to search on the Web but couldn't find anything...
Thanks!

A: Workload increases the total amount of work that you can have at any time, ie you can have a bigger pile of "books"/work.
Faster touch work means that when you tap on yourself (and your team members, once you make Deputy General Manager,) the increase in work speed is faster.
Team work means that your team members (once you reach Assistant Manager) will complete their work faster.


text:
Q: How do I find all controls of a particular type from a page inside a master page? I have to enable/disable via javascript all RadComboBoxes from my page, which is inside a master page. I was pointed to this simple tutorial (http://www.telerik.com/support/kb/aspnet-ajax/general/how-to-create-a-javascript-array-of-all-particular-radcontrols-on-the-page.aspx), but instead of finding all telerik RadControls in the page, it returns me only the RadControls of the master page. There's something I'm missing to point out that I want the controls of the page inside the master page?
This is what I have now (allRadControls return me the RadSplitter, RadPane ans RadButtons from my master page)
 function DisableSave(habilita, botao) {
                    var btSalvar = $find(botao);
                    if (btSalvar != null) {
                        var allRadControls = $telerik.radControls;
                        if (habilita == "True") {
                            btSalvar.set_enabled(true);
                            $("#<%=pnlPrincipal.ClientID%>").find("input,a,textarea,table").attr("disabled", false);
                        }
                        else {
                            btSalvar.set_enabled(false);
                            $("#<%=pnlPrincipal.ClientID%>").find("input,a,textarea,table").attr("disabled", true);
                        }
                    }

A: RadComboBox exposes an array at client-side that contains all RadComboBox instances. This array can be accessed like:
Telerik.Web.UI.RadComboBox.ComboBoxes
For example:
If RadComboBox controls are embedded in another control, you can simply get these controls from the array described above.
Here is an example of radcombobox nested inside a Grid:
<telerik:RadGrid ID="RadGrid1" runat="server" ...>
    ...
    <EditItemTemplate>
    <telerik:RadComboBox ID="RadComboBox1" runat="server"></telerik:RadComboBox>
    <telerik:RadComboBox ID="RadComboBox2" runat="server"></telerik:RadComboBox>
    <telerik:RadComboBox ID="RadComboBox3" runat="server"></telerik:RadComboBox>
    </EditItemTemplate>
... </telerik:RadGrid>

And here is the JavaScript code:
<script>
    function pageLoad() {
        var combo1 = Telerik.Web.UI.RadComboBox.ComboBoxes[0];
        var combo2 = Telerik.Web.UI.RadComboBox.ComboBoxes[1];
        var combo3 = Telerik.Web.UI.RadComboBox.ComboBoxes[2];
    }
</script>

Here is the help documentation link:
http://www.telerik.com/help/aspnet-ajax/combobox-client-side-basics.html
Hope this helps...


text:
Q: WoE for Random Forest and SVM There are a lot written about WoE (Weight of Evidence) transformation for the case of Logistic Regression Classifier. It works great.
The question: can one (or does it make sense) to use this WoE approach for, say, Random Forest or Support Vectors Machine?

A: I'm not sure that the WoE transformation makes much sense at all, at least is looks dated, maybe time to look into better methods. But: The transformation does seem to be coupled to the binary nature of the response, so can be used with binary logistic regression, but also with other methods made for binary response variables, like classification trees and ... (fill out the dots!)
In fact, to me, WoE looks like a variant of target encoding used with binary response (or target) variables,  see Target encoding a categorical variable in a highly imbalanced dataset for binary classification.


text:
Q: Looping for ggplot how to use the for loop variable i inside the loop I have a dataframe (what is the dataframe? i,e is not important).
I am using that and plotting some point curves. like below
#EXP <- 3 (example)
#EXP_VEC <- c(1:EXP)

for (i in 1:EXP)
{
gg2_plot[i] <- ggplot(subset(gg2,Ei == EXP_VEC[i] ),aes(x=hours, y=variable, fill = Mi)) + geom_point(aes(fill = Mi,color = Mi),size = 3)
}

As you can see EXP_VEC = c(1,2,3.......) (Depends on user input Ex: if user inputs 2 then EXP_VEC = c(1,2))
Dataframe has Ei = 1,2,3,4,........
Now I have to do the plotting for all these Ei values depending on the user input.
Consider, EXP_VEC=3
now the for loop should produce three plots for Ei = 1 , Ei = 2 and Ei = 3
for this if the for loop I have written works then it would have been done and finished.
But obviously for loop is not working. I cant use aes_string because variable "i" is outside the aes().
Ex: consider the following dataset
dd<-data.frame(
    Ei = c(1L, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2),
    Mi = c(1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2),
    hours = c(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3),
    variable = c(0.1023488, 0.1254325, 0.1523245, 0.1225425, 0.1452354,
    0.1853324, 0.1452369, 0.1241241, 0.0542232, 0.8542154, 0.021542,
    0.2541254))

As you can see I have two sets of Ei, I want to plot 1st plot for Ei = 1 and then beside this plot I want to again plot for Ei = 2.
So I thought of saving the plots for Ei=1 and Ei=2 in two separate variables and then using then in some kind of cascade function which I am yet to find out.
How do I do it?
Is there a easy way to do this by just using ggplot without any loop?
If not then how can I call "i" value inside my for loop?

A: I would do something like this:
plot_exp <-
  function(i){
    dat <- subset(gg2,Ei == i )
    if (nrow(dat) > 0)
       ggplot(dat,aes(x=hours, y=variable, fill = Mi)) +
              geom_point(aes(color = Mi),size = 3)
  }

ll <- lapply(seq_len(EXP), plot_exp)

ll is a list of plot of ggplot objects.


text:
Q: neo4j plugin method signature mismatch In my Neo4j plugin I have a method:
@Procedure("myworld.implement")
public static Stream<MyItem> implement() {
    ...

When I invoke it in the browser:
call myworld.implement()

I get the response:
Failed to invoke procedure `myworld.implement`: Caused by:
java.lang.invoke.WrongMethodTypeException: cannot convert
MethodHandle()Stream to (Object)Object

How is there a mismatch between my method declaration and my method invocation?
(Neo4j 3.0.1 Community Edition)

A: I should not have declared the method as static
correct:
@Procedure("myworld.implement")
public Stream<MyItem> implement() {
    ...


text:
Q: Testing with RSpec, :js => true but only opens blank browser window I'm trying to write a test for my delete link.
My delete link triggers an alert confirmation first (same way delete link does when created with scaffold) so it relies upon JavaScript.
Below is my code to try and run this test using JavaScript.
feature "delete link", :js => true do
  scenario "delete a video when delete icon is clicked" do
    favorite = FactoryGirl.create(:favorite)
    visit favorites_path
    find("a.delete_icon").click
    expect(page).to_not have_content(favorite.title)
  end
end

What happens is that the browser window opens, but it's blank and it just remains open while my running test just appears to be waiting.
I have to close the browser window myself and then close the test (Ctrl+C).
What might I do doing wrong?


text:
Q: Can't write an SQLite Query Using the file posts.csv in the data folder of this repo (the sample of 10,000 public Facebook posts by members of the US congress from 2017), solve the following with dplyr:

*

*Do not consider posts with zero likes

*Compute the comment to like ratio (i.e. comments_count / likes_count) for each post and store it in a column clr

*For each screen_name, compute a normaliser_based_on_even_months = max(clr) - min(clr), i.e. the maximum minus the minimum clr value of posts by that screen_name, however, only taking into account the posts made in even months, i.e. posts made in in February, April, June, August, October, December when computing max(clr) - min(clr) for each screen_name

*Set all normaliser_based_on_even_months that have a value of zero to NA or delete them

*Afterwards create a column normalised_clr which stores the clr of all posts from the original data frame (other than those with zero likes which were deleted in the first step) divided by the normaliser_based_on_even_months of the associated screen name.
The only exception are posts from screen names that had a normaliser_based_on_even_months value of zero and were deleted/set to NA before -- for these posts just set the value in normalised_clr to NA as well or drop the post from the final data frame.

*In other words, the value of a single post/line i (written by a politician p) in that normalised_clr column can be computed as: normalised_clr_{i,p} = clr{i}/normaliser_based_on_even_months_{p} for all observations for which there is a non-NA normaliser_based_on_even_months (no need to use a loop for this though, dplyr allows to compute it in a vectorised way)

*Keep only those rows with normalised_clr > 0

*Arrange the data frame according to normalised_clr in ascending order

*Print out only screen_name and normalised_clr for the first 10 rows, i.e. the posts with the 10 lowest normalised_clr
I have written an R program for this. However, my task is to convert that into a SINGLE SQLite query. Here's what I've done:
# Create database
posts_db <- dbConnect(RSQLite::SQLite(), "C:/Users/HP/Documents/posts.sqlite")

# Reading the first file into R
data <- read.csv("C:/Users/HP/Documents/posts.csv",
    stringsAsFactors = FALSE)

dbWriteTable(posts_db, "posts", data, overwrite = TRUE)

dbListFields(posts_db, "posts")

dbGetQuery(posts_db,"WITH
cte1 AS (SELECT screen_name, comments_count*1.0/likes_count AS clr,
strftime('%m', date) AS month FROM posts WHERE likes_count>0),
cte2 AS (SELECT (MAX(clr) - MIN(clr)) AS normaliser_based_on_even_months
FROM cte1
WHERE month % 2 = 0
GROUP BY screen_name),
cte3 AS (SELECT screen_name, clr, normaliser_based_on_even_months,
clr/normaliser_based_on_even_months AS normalized_clr FROM cte1, cte2
WHERE normaliser_based_on_even_months>0)
SELECT screen_name, normalized_clr FROM cte3
WHERE normalized_clr>0
ORDER BY normalized_clr")

Here's the output:
               screen_name normalized_clr
1             repmarkpocan   0.0002546821
2             repmarkpocan   0.0002690018
3  CongressmanRalphAbraham   0.0002756995
4  CongressmanRalphAbraham   0.0002912010
5             derek.kilmer   0.0003549631
6           RepJimMcGovern   0.0003664136
7      CongresswomanNorton   0.0003687929
8             derek.kilmer   0.0003749212
9           RepJimMcGovern   0.0003870155
10     CongresswomanNorton   0.0003895286

Sample Data
For reference here is the R code that produces the result I want the SQLite Query to produce:
posts <- read.csv("C:/Users/HP/Documents/posts.csv")

#Remove columns with zero likes
posts <- posts %>% filter(likes_count > 0)

#create 'clr' which is the comment to like ratio
posts <- posts %>% mutate(clr = comments_count / likes_count)

#Compute the maximum minus the minimum `clr` value of posts by that `screen_name`, however, only taking into account __the posts made in even months, i.e. posts made in in February, April, June, August, October, December__ when computing `max(clr) - min(clr)` for each `screen_name`. Code from https://stackoverflow.com/questions/30606360/subtract-value-from-previous-row-by-group

posts$date <- ymd(posts$date)
posts$date <- month(posts$date)

posts_normaliser <- posts %>% group_by(screen_name) %>% mutate(normaliser_based_on_even_months = case_when(date%%2==0 ~ (max(clr) - min(clr))))

#Set all `normaliser_based_on_even_months` that have a value of zero to NA or delete them
posts_normaliser <- posts_normaliser %>% filter(normaliser_based_on_even_months > 0)

#Afterwards create a column `normalised_clr` which stores the `clr` of all posts from the original data frame (other than those with zero likes which were deleted in the first step) divided by the `normaliser_based_on_even_months` of the associated screen name.

merged_df <- merge(posts, posts_normaliser)

merged_df <- merged_df %>% group_by(screen_name)%>% mutate(normalised_clr = clr / normaliser_based_on_even_months)

#Keep only those rows with `normalised_clr` \> 0

merged_df <- merged_df %>% filter(normalised_clr > 0)

#Arrange the data frame according to `normalised_clr` in ascending order

merged_df <- merged_df %>% arrange(normalised_clr)

#Print out only `screen_name` and `normalised_clr` for the first 10 rows, i.e. the posts with the 10 lowest `normalised_clr`

merged_df[1:10, c("screen_name", "normalised_clr")]

Here's the Output from R:
> merged_df[1:10, c("screen_name", "normalised_clr")]
# A tibble: 10 × 2
# Groups:   screen_name [5]
   screen_name                   normalised_clr
   <chr>                                  <dbl>
 1 CongresswomanSheilaJacksonLee        0.00214
 2 CongresswomanSheilaJacksonLee        0.00218
 3 CongresswomanSheilaJacksonLee        0.00277
 4 RepMullin                            0.00342
 5 SenDuckworth                         0.00342
 6 CongresswomanSheilaJacksonLee        0.00357
 7 replahood                            0.00477
 8 SenDuckworth                         0.00488
 9 SenDuckworth                         0.00505
10 RepSmucker                           0.00516

I keep going through the statements but I can't figure out why the outputs are different.

A: If you look at the output from your SQL query, it results in 4,543,128 rows out of the original 10,000, indicating that your joins are exploding. You need to join on something; since all of the tables you're joining are either (a) original rows or (b) summarized, unique screen_name, I think we can use that column.
I modified your query to do two things:

*

*add screen_name to cte2

*update the join inside cte3

*add limit 10 since you said "all into a single query", and "lowest 10" is part of the constraints.

WITH
cte1 AS (
  SELECT screen_name, comments_count*1.0/likes_count AS clr,
    strftime('%m', date) AS month
  FROM posts WHERE likes_count > 0
),
cte2 AS (
  SELECT screen_name, (MAX(clr) - MIN(clr)) AS normaliser_based_on_even_months
  FROM cte1
  WHERE month % 2 = 0
  GROUP BY screen_name
),
cte3 AS (
  SELECT cte1.screen_name, clr, normaliser_based_on_even_months,
    clr/normaliser_based_on_even_months AS normalized_clr
  FROM cte1
    LEFT JOIN cte2 on cte1.screen_name = cte2.screen_name
  WHERE normaliser_based_on_even_months > 0
)
SELECT screen_name, normalized_clr
FROM cte3
  WHERE normalized_clr > 0
ORDER BY normalized_clr
LIMIT 10

This produces:
      screen_name normalized_clr
1    SenDuckworth    0.002318900
2       RepMullin    0.003415301
3    SenDuckworth    0.003425708
4  repmikecoffman    0.003861004
5    SenDuckworth    0.004173566
6    SenDuckworth    0.004880627
7    SenDuckworth    0.005035819
8    SenDuckworth    0.005051889
9    SenDuckworth    0.005112120
10        RepBost    0.005600815


text:
Q: Command Line Tips and Tricks ==>> What are the most useful Unix shell "one-liners" that you use? <<==
Here are a couple of mine to get the conversation started:
1. Repeat the previous command with a substring replacement:
Syntax:
^before^after^

Example:
You entered:
git clonr https://unbelievablylongurl.org/projectdirectory/evenmoreprojects/project.git

Use this:
^clonr^clone^

And your command will be re-run with the replaced substring:
git clone http://unbelievablylongurl.org/projectdirectory/evenmoreprojects/project.git

2. Repeat the previous command with an additional string/character
Shell Idiom:
!!

Example:
You ran a command that requires superuser privileges on your box.  Re-run the command without retyping it like this:
sudo !!


text:
Q: Finitely additive, $\kappa$-additive atomless measures in ZFC Under Martin's Axiom (and non-CH) the Lebesgue measure is $2^\omega$-additive in the sense that unions of fewer than continuum ($2^\omega$) many null sets are measureable and null. In ZFC we may however extend the Lebesgue measure to a finitely-additive measure on the power set of $[0,1]$ and still call it atomless.
Are there ZFC examples of finitely-additive measures that extend  an atomless measure $\mu$ and are $\kappa$-additive in the above sense w.r.t $\mu$-null sets, where $\kappa > 2^\omega$?

A: I claim that a non-atomic measure $\mu$ can never be $<{2^\omega}^+$-additive. Then the same applies to any finitely-additve extension.
Let $(\Omega, \frak{A}, \mu)$ be a measure space and let us assume that $\mu$ is non-atomic. It follows that there exists $A \in \frak{A}$ such that $0 < \mu(A) < \infty$. I now want to partition $A$ into $2^\omega$ many null sets. Start by splitting $A$ into $A_0$ and $A_1$ both are sets in $\frak{A}$ of positive measure. This can be done, since $\mu$ is non-atomic. Assume that $A_s$ for $s\in 2^{<\omega}$ has been defined and partition it into $A_{s^\frown 0}$ and $A_{s^\frown 1}$. For every $x \in \,^{\omega}2$ define $A_x:= \bigcap_{n < \omega} A_{x \restriction n}$, which is the first limit step.
First note that $\mu(A_x)=\inf_{n < \omega} \mu(A_{x \restriction n})$ and that some $A_x$ may already have measure 0, while others may still have positive measure. If $A_x$ has measure 0, then we do not have to take care of it anymore. If $A_x$ has positive measure, we continue as before and split it into $A_{x^\frown 0}$ and $A_{x^\frown 1}$. This way we get a (transfinite) binary tree, such that some branches die out at limit stages.
I claim that every branch dies out at countable height, i.e. there is no $\omega_1$-branch. If not, there exists a $\subseteq$-decreasing sequence $(A_\alpha)_{\alpha < \omega_1}$ of length $\omega_1$ such that $\mu(A_\beta) < \mu(A_\alpha)$ if $\beta > \alpha$. But this is impossible, since there cannot exist an uncountable decreasing sequence in $\mathbb{R}$ (separability). Therefore, there are only $2^\omega$ branches and so $A=\bigcup_{\alpha < 2^\omega} A_\alpha$.
This and (much) more can be found in Jech's book in chapter 10.


text:
Q: How to change a file inside apk and change cert.sf and manifest.sf without java but with php I am new here. I haven't found any solution to my problem.
WHY i need that? I am building a Joomla based system for fast custom Android app creation working on php hostings having no java installed available for people to develop and install apps easily on their devices. Thus i am interested only PHP or universal-like solutions implementable in PHP too. Only CHANGING FILES UNPACKED AND NOT DECOMPILED IS AN OPTION. No apktool no whatever else like that. I am working with DEBUG packages with self generated keys. or something like that, because i am a beginning phone gap developer.
For example i would like my own icons for an app, or change the title of it in AndroidManifest.xml. And update sha1 digest hashes for cert.sf and manifest.sf for the changed files. I need human understandable procedure step by step.
PHP gives sha1 and base64 encoding and many more like that.
I was trying to get the same codes like cert.sf and manifest.sf (no file was changed before) but i wasn't able to do so. I tried silly ways to sha1 files and base64 them and no outcome was as in the files mentioned.
Please there is no answer like that i need.
Let me say the anwswer to the question will help people or at least will help to build application development systems.
P.S.
For Adobe Air apps i will be trying to do the same what for .apk apps. I hope it won't create the same issues. But not about it is the main question.
UPDATE:
I feel from a couple topics of this kind that any practical help on this matter is unavailable and sometimes even perceived negatively. Thus what i am going to do is to use an additional server for making apps (simply command: cordova build) and send an app produced to a server which requested for it. This only because for some unknown reasons i cannot sign any files with php (debug packages). But why? It seems that the effect would be just the same as with installing running stuff with additional server using java, would it not?
Update:
I don't think there will be any answer. So i do .air and .apk apps using home computer hosting java what is not the best idea - two servers one not professional. There is http://build.phonegap.com/ and it can be interesting for building apps manually or via api. For free one app can be private and more open source. IOS and Windows are supported too there.

A: If you change a file, you must resign the APK with an existing certificate.
APK files are signed with the java jarsigner tool, so you can't do it only manually just by editing some files, you need the private key of the certificate.
Maybe you should try to add a Java application next to your Joomla server and use jarsigner for signing the generated APKs.