Functions and Fractals - Recursive Trees - Bash! Logic Issue

Question: I am trying to build a fractal tree based on requirement to build it.
Something is wrong. Please assist. I am trying to build fractal tree based on the level requested. Here the levels are getting skipped. Need to understand how to fix the issue.
<code>    #!/bin/bash
declare -A matrix
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        matrix[$i,$j]='_'
    done
done
function update_matrix {
p1=$1
p2=$(echo $2-1|bc)
p1=$(echo $p1-1|bc)
p3=$(echo 2^$p2|bc)
p4=$(echo 2*$p3|bc)
p5=$(echo $p3/2|bc)
p6=$3
for ((q1=$p3;q1<$p4;q1++)) do
        if [ "$(echo $q1-$p3|bc)" -lt "$p5" ]
            then
            q2=$(echo $p6-$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            q3=$(echo $p6+$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            matrix[$q1,$q2]=1
            matrix[$q1,$q3]=1
            #printf '%s' "$q1 $q2 -- $q1 $q3"
            #echo ""
            else
            matrix[$q1,$p6]=1
            #echo $q1 $p6
        fi
done

if [ $p1 -ge 1 ]
then
update_matrix $p1 $p2 $(echo $p6+$p5|bc)
update_matrix $p1 $p2 $(echo $p6-$p5|bc)
else
return
fi
}
read iteration
if [ $iteration -ge 1 ]
then
    update_matrix $iteration 6 32
fi
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        printf '%s' "${matrix[$i,$j]}"
    done
    echo ""
done
</code>
Output is:
<code>____________________________________________________________________________________________________
________________________________________________1_1_________________________________________________
_________________________________________________1__________________________________________________
_________________________________________________1___1______________________________________________
__________________________________________________1_1_______________________________________________
___________________________________________________1________________________________________________
___________________________________________________1________________________________________________
___________________________________________________1_______1________________________________________
____________________________________________________1_____1_________________________________________
_____________________________________________________1___1__________________________________________
______________________________________________________1_1___________________________________________
_______________________________________________________1____________________________________________
_______________________________________________________1____________________________________________
_______________________________________________________1____________________________________________
_______________________________________________________1____________________________________________
_______________________________________1_______________1____________________________________________
________________________________________1_____________1_____________________________________________
_________________________________________1___________1______________________________________________
__________________________________________1_________1_______________________________________________
___________________________________________1_______1________________________________________________
____________________________________________1_____1_________________________________________________
_____________________________________________1___1__________________________________________________
______________________________________________1_1___________________________________________________
_______________________________________________1____________________________________________________
_______________________________________________1____________________________________________________
_______________________________________________1____________________________________________________
_______________________________________________1____________________________________________________
_______________________________________________1____________________________________________________
_______________________________________________1____________________________________________________
_______________________________________________1____________________________________________________
_______________________________________________1____________________________________________________
_______________1_______________________________1____________________________________________________
________________1_____________________________1_____________________________________________________
_________________1___________________________1______________________________________________________
__________________1_________________________1_______________________________________________________
___________________1_______________________1________________________________________________________
____________________1_____________________1_________________________________________________________
_____________________1___________________1__________________________________________________________
______________________1_________________1___________________________________________________________
_______________________1_______________1____________________________________________________________
________________________1_____________1_____________________________________________________________
_________________________1___________1______________________________________________________________
__________________________1_________1_______________________________________________________________
___________________________1_______1________________________________________________________________
____________________________1_____1_________________________________________________________________
_____________________________1___1__________________________________________________________________
______________________________1_1___________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
_______________________________1____________________________________________________________________
</code>
Need to understand why left node created right one is not created.
Answer: What I was missing is to declare variables as local. Due to which global variables were getting updated and thus my program was not working properly.
I fixed the issue and used local variables and it worked like a charm.
Code for the solution is
Its for Hackerrank Functions and Fractals - Recursive Trees - Bash! Program.
Took me 3hr to nail it down. Really refreshing to finally solve it.
<code>    #!/bin/bash
declare -A matrix
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        matrix[$i,$j]='_'
    done
done
i=0
declare -A arr
function update_matrix {
local p1 p2 p3 p4 p5 p6 q1 q2 q3 p11 p12 p13 p14 p15 p16
p1=$1
p2=$(echo $2-1|bc)
p1=$(echo $p1-1|bc)
p3=$(echo 2^$p2|bc)
p4=$(echo 2*$p3|bc)
p5=$(echo $p3/2|bc)
p6=$3
for ((q1=$p3;q1<$p4;q1++)) do
        if [ "$(echo $q1-$p3|bc)" -lt "$p5" ]
            then
            q2=$(echo 18+$p6-$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            q3=$(echo 18+$p6+$(echo $p5-$(echo $q1-$p3|bc)|bc)|bc)
            matrix[$q1,$q2]=1
            matrix[$q1,$q3]=1
            #printf '%s' "$q1 $q2 -- $q1 $q3"
            #echo ""
            else
            matrix[$q1,$(echo 18+$p6|bc)]=1
            #echo $q1 $p6
        fi
done

if [ $p1 -ge 1 ]
then
p11=$p1
p12=$p2
p13=$(echo $p6-$p5|bc)
p14=$(echo $p6+$p5|bc)
p15=$p1
p16=$p2

#echo $p11 $p12 $p6 $p5 $p13
update_matrix $p11 $p12 $p13
#echo $p15 $p16 $p6 $p5 $p14

update_matrix $p15 $p16 $p14
t=4
else
s=2
fi
}
read iteration
if [ $iteration -ge 1 ]
then
    #echo $iteration 6 32
    update_matrix $iteration 6 32
fi
for ((i=1;i<=63;i++)) do
    for ((j=1;j<=100;j++)) do
        printf '%s' "${matrix[$i,$j]}"
    done
    echo ""
done
</code>
Answer: The question asked by HackerRank requires you to make the code recursive. To be recursive the code must call itself at some point. Below I've made a create_y function that is recursive. This function will continually call itself until it meets its stop condition. The stop condition is the if statement that checks if the iteration variable is greater than 0.
The function itself naturally wants to build a Y, and at the end of the Y branches, make new Y's that are half the size of the original. When it is done it will print to standard out.
<code>#!/bin/bash
declare -A SCREEN
SCREENR=63
SCREENW=100
DEPTH=0
MAX=16

function create_y {
    local originR=$1
    local originC=$2
    local iteration=$3
    local size=$4
    local originVR=0
    local originVC=0
    local originNYLR=0
    local originNYLC=0
    local originNYRR=0
    local originNYRC=0

    if [[ iteration -gt 0 ]]; then
        for ((i=0;i<$size;i++))
        do
            SCREEN[$(($originR-$i)),$originC]=1
            let originVR="$(($originR-$i))"
        done

        for ((i=1;i<=$size;i++))
        do
             SCREEN[$(($originVR-$i)),$(($originC - $i))]=1
             let originNYLR="$(($originVR-$i))"
             let originNYLC="$(($originC - $i))"
             SCREEN[$(($originVR-$i)),$(($originC + $i))]=1
             let originNYRR="$(($originVR-$i))"
             let originNYRC="$(($originC + $i))"
        done

        create_y $(($originNYLR-1)) $originNYLC $(($iteration-1)) $(echo "$size/2" | bc)
        create_y $(($originNYRR-1)) $originNYRC $(($iteration-1)) $(echo "$size/2" | bc)
    fi
}

for ((i=1;i<=$SCREENR;i++))
do
    for ((j=1;j<=$SCREENW;j++))
    do
        SCREEN[$i,$j]='_'
    done
done

read DEPTH

create_y $SCREENR $(echo "$SCREENW/2" | bc) $DEPTH $MAX

for ((i=1;i<=$SCREENR;i++)) do
    for ((j=1;j<=$SCREENW;j++)) do
         printf '%s' "${SCREEN[$i,$j]}"
    done
    echo ""
done

exit 0
</code>
Comment: Thank you for this code snippet, which might provide some limited short-term help.  A proper explanation [would greatly improve](//meta.stackexchange.com/q/114762) its long-term value by showing *why* this is a good solution to the problem, and would make it more useful to future readers with other, similar questions.  Please [edit] your answer to add some explanation, including the assumptions you've made.
Answer: Attempting to explain why this is optimal below. Idea of creating the grid and solving the problem is pretty straight-forward in terms of logic.
Algorithm:

Create a grid.
Create a solving function.
Create a column (vertical line) of 1's, with length of l (interval, initially 16) starting from the middle.
Mark left, right diagonals from the end of the line with 1's.
You now have a Y!
Recurse left and right from the top corners of Y, to create "sub-Y's".
When recursing be sure your data are correct (interval should be divided by 2 etc.).

PS: Ladies and Gentlemen when sharing code, please give it a proper try when it comes on commenting, even for the smallest snippet. It will change your lives!
<code> #!/bin/bash

 declare -A grid

 #Solves the fractal problem.
 #Variables:
 #  d: depth of recursion.
 #  l: length of gaps/interval.
 #  r: row
 #  c: column.
 solve(){
  local d=$1
  local l=$2
  local r=$3
  local c=$4

  #base case, return.
  if [ $d -eq 0 ]; then
      return
  fi

# iterate backwards.
# create a column/vertical. line of 1's.
# sizeof(line) = l (length of interval) [initially 16].
# See graph below:
: '
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
        -------------------------------------------------1--------------------------------------------------
'
for (( i = l; i > 0; i-- )); do
    grid[$((r-i)).$c]=1
done

((r -= l))

# iterate backwards.
# create the V-shaped tree/fractal.
# sizeof(tree) = l (length of interval) [initially 16].
# should fill all diagonal cells with 1's .
#       {[r-1, c-1] (left), [r-1, c+1] (right)} --> 1st.
#       {[r-2, c-2] (left), [r-2, c+2] (right)} --> 2nd.                                        for(i in [1,l]) {                       //remember l is dynamic. (16, 8, 4, 2, 1, ..)
#           ...                                                                         ---->       {[r-i, c-l] (left), [r-i, c+l] (right)} = 1
#           ...                                                                                }
#       {[r-l, c-l] (left), [r-l, c+l] (right)} --> 16th (or l-th).

for (( i = l; i > 0; i--)); do
    grid[$((r-i)).$((c-i))]=1
    grid[$((r-i)).$((c+i))]=1
done

: '
    This for n = 1 creates the following pattern:

    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ---------------------------------1-------------------------------1----------------------------------
    ----------------------------------1-----------------------------1-----------------------------------
    -----------------------------------1---------------------------1------------------------------------
    ------------------------------------1-------------------------1-------------------------------------
    -------------------------------------1-----------------------1--------------------------------------
    --------------------------------------1---------------------1---------------------------------------
    ---------------------------------------1-------------------1----------------------------------------
    ----------------------------------------1-----------------1-----------------------------------------
    -----------------------------------------1---------------1------------------------------------------
    ------------------------------------------1-------------1-------------------------------------------
    -------------------------------------------1-----------1--------------------------------------------
    --------------------------------------------1---------1---------------------------------------------
    ---------------------------------------------1-------1----------------------------------------------
    ----------------------------------------------1-----1-----------------------------------------------
    -----------------------------------------------1---1------------------------------------------------
    ------------------------------------------------1-1-------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------

'

#   Now comes the fun part, we should recurse.
#   For a complete analysis about why recursion is optimal u could read CLRS
#   or any other Algorithms book of ur choice (be extra carefull on big-O notation, Master Theorem and recursion trees).

# Idea:
#   - We will subrtact 1 from the depth for each complete fractal we create, so we will eventually terminate.
#   - Interval gets reduced by half for any fractal, thus l' = l/2.
#   - r-l: Executed 2 times (see line 48) will bring us to the left/right topmost part of the newly created Y (left/right corner), on the proper row [---------].
#   - c-l/c+l: Will result us beeing on either left or right corner of the Y [See below figure for more].

: '

    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ----------------------------------------------------------------------------------------------------
    ---------------------------------O-------------------------------O----------------------------------        After performing 2 recursive calls (left/right), the execution on the new copy
    ----------------------------------1-----------------------------1-----------------------------------        will start from points marked with "O".
    -----------------------------------1---------------------------1------------------------------------
    ------------------------------------1-------------------------1-------------------------------------
    -------------------------------------1-----------------------1--------------------------------------
    --------------------------------------1---------------------1---------------------------------------
    ---------------------------------------1-------------------1----------------------------------------
    ----------------------------------------1-----------------1-----------------------------------------
    -----------------------------------------1---------------1------------------------------------------
    ------------------------------------------1-------------1-------------------------------------------
    -------------------------------------------1-----------1--------------------------------------------
    --------------------------------------------1---------1---------------------------------------------
    ---------------------------------------------1-------1----------------------------------------------
    ----------------------------------------------1-----1-----------------------------------------------
    -----------------------------------------------1---1------------------------------------------------
    ------------------------------------------------1-1-------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------
    -------------------------------------------------1--------------------------------------------------

'

# This will work recursivelly so only thing we need to do, is wait and pray that our exit case will work.
# This can also be seen as "Divide and Conquer" algorithm.

solve $((d-1)) $((l/2)) $((r-l)) $((c-l))
solve $((d-1)) $((l/2)) $((r-l)) $((c+l))

}

 # Just visualize the grid under given assumptions
 print_grid(){
    for ((i=0; i<63; i++)); do
        for ((j=0; j<100; j++)); do
              if [[ ${grid[$i.$j]} ]]; then
              printf 1
              else
                printf -
              fi
        done
        echo
    done
 }

 read n
 solve $n 16 63 49
 print_grid
</code>


OpenSSL - Output PEM encoded part only when signing a certificate request


Fisher's Exact Test with weights?

Question: Does anyone know of a variation of Fisher's Exact Test which takes weights into account? For instance sampling weights.
So instead of the usual 2x2 cross table, every data point has a "mass" or "size" value weighing the point.
Example data:
A B weight
N N 1
N N 3
Y N 1
Y N 2
N Y 6
N Y 7
Y Y 1
Y Y 2
Y Y 3
Y Y 4

Fisher's Exact Test then uses this 2x2 cross table:
A\B  N  Y All
 N   2  2   4
 Y   2  4   6
All  4  6  10

If we would take the weight as an 'actual' number of data points, this would result in:
A\B  N  Y All
 N   4 13  17
 Y   3 10  13
All  7 23  30

But that would result in much too high a confidence. One data point changing from N/Y to N/N would make a very large difference in the statistic.
Plus, it wouldn't work if any weight contained fractions.
Answer: I have a suspicion that 'exact' tests and sampling weights are essentially incompatible concepts. I checked in Stata, which has good facilities for sample surveys and reasonable ones for exact tests, and its 8 possible test statistics for a crosstab with sample weights don't include any 'exact' tests such as Fisher's.
The relevant Stata manual entry (for svy: tabulate twoway) advises using its default test in all cases. This default method is based on the usual Pearson's chi-squared statistic. To quote:
"To account for the survey design, the statistic is turned into an F statistic with noninteger degrees of freedom by using a second-order Rao and Scott (1981, 1984) correction".
Refs:

Rao, J. N. K., and A. J. Scott. 1981. The analysis of categorical data from complex sample surveys: Chi-squared tests for goodness of fit and independence in two-way tables. Journal of the American Statistical Association 76:221–230.
Rao, J. N. K., and A. J. Scott. 1984. On chi-squared tests for multiway contingency tables with cell proportions estimated from survey data. Annals of Statistics 12: 46–60.
Answer: Interesting question.  What do you mean by weight?
I would be inclined to do a bootstrap...pick your favorite statistic (i.e. Fisher's Exact), and compute it on your data.  Then assign new cells to each instance according to your null hypothesis, and repeat the process 999 times.  This should give a pretty good empirical distribution for your test statistic under the null hypothesis, and allow easy computation of your p-value!
Comment: Thanks! But I hoped for a statistic that is faster and more stable to calculate...
Answer: One quick thing about sample weights - they are usually a way to incorporate some information about the population that one is sampling from - but usually they are based on "big sample" type scenarios (typically constrained BLUP or BLUE prediction in disguise).  So I would imagine that sample weights will probably do no better than no weights.  What would be better I think is to use the information about the population that the sample design was based on directly.
For example, on what basis were the selection probabilities calculated?  My bet is that you knew a population total or some kind of population break-down which does not involve A or B (say age by sex groups).  If this is not correct then I am about to waste some space, but if it is correct, and supposing you had population totals $R_{1},\dots,R_{k}$ for $k$ groups (or strata), and within each group you had a "mini" 2 by 2 contingency table.  So we can now write $R_{1;11},R_{1;12},R_{1;21},R_{1;22},\dots$ as the "target" of our inference.  Or perhaps it is the sum $\sum_{l=1}^{k}R_{l;ij}$ that is the target of inference (how many in the population give response N/N??).  You are then trying to reason about $R_{l;ij}$ from the sampled numbers $r_{l;ij}$ subject to the constraint that $\sum_{i,j}R_{l;ij}=R_{l}$ for $(l=1,\dots,k)$.  (maxent anyone?)
Note that if the sampling probabilities were based only on what data you were likely to receive, then they are irrelevant (and Fisher's exact test applies), because once you receive the data, you know what sample you received.  So the coherent thing to do is to update the sampling probability to $P(D_{m})=1$ if the mth unit is in the sample, and $P(D_{m})=0$ if they weren't in the sample.  However, usually the design is based in more information than just the data one is likely to observe.  but note that it is the information rather than the survey design per se that is important.  Design based inference is just a rather efficient way to incorporate all that information into your analysis.

Fisher's Exact Test with weights?


log transformation vs square root transformation, Can I do both?

Question: I am analyzing ARIMA or multiple regression model. $Y= X_1 + X_2 + X_3 + X_4$
Can I have the log on Y and square root on X1 and square root on X2, at the same time?  That is,
$\log Y = \sqrt{X_1} + \sqrt{X_2} + X_3 + X_4$
If yes, how can I interpret the results?
Answer: Yes; you can do this and still achieve a valid model.
Interpretation, however, is complicated by this transformation. Your model then looks like
$$\log(E(Y_i)) = \beta_0+ \beta_1\sqrt{X_{i1}} + \beta_2\sqrt{X_{i2}} + \beta_3X_{i3} + \beta_4X_{i4}$$
This means that e.g. a doubling of $X_1$ is associated with an expected increase of $Y$ by a factor $\exp(\beta_1\sqrt{2})$, all other factors kept equal. For a unit increase in $X_1$ there is no easy interpretation; that depends on the current value of $X_1$.
A unit increase of $X_3$ is associated with an expected increase of $Y$ by a factor $\exp(\beta_3)$. So, interpretation is easier without transforming the variables. However, if square root transformation improves the fit or is necessary in some other way, then it is mathematically perfectly correct.


Removing element from hasMany association is not working

Question: Calling ArrayList#remove() or ArrayList#removeAll() is not working. Why could that be?
class Category {
    static hasMany = [elems: Elem]
    // ..
}

class Elem {
    static belongsTo = Category
    // ..
}

// ExampleController.groovy
def saveCategory(/* args */) {
    def category = categoryService.get.. // get some category object
    def elem = elemService.getElem(1)    // get some element that's in the category
    category.elems.remove(elem)  // *How to get this working*? Returns false as the object is not getting removed.
    category = categoryService.saveCategory(category)
    JSON.registerObjectMarshaller(Category) {
        def map = [:]
        map['id'] = it.id
        map['elems'] = it.elems
        return map
    }
    JSON.registerObjectMarshaller(Elem) {
        def map = [:]
        map['id'] = it.id
        return map
    }
    render(['category': category] as JSON)
}

Thanks.
Comment: you want to try http://grails.org/doc/latest/ref/Domain%20Classes/removeFrom.html
Comment: is this a typo?  ``Category`` vs ``PatientCategory``?  might as well be a thrid class involved, but still is confusing.
Answer: the official way to handle this is to use the addTo* and removeFrom* methods.  you might want to look into the way, they are handling this.
http://grails.org/doc/latest/ref/Domain%20Classes/addTo.html
http://grails.org/doc/latest/ref/Domain%20Classes/removeFrom.html
Comment: No effect. Getting a copy of the collection and iterating on it and removing it the old school way and then assigning it back to the `category` object seems to work.
Comment: just to be save: after the ``removeFromElems`` you called ``category.save()``?
Comment: Yes `save` method is called. I expect the `removeFromElems` as mentioned in the docs to work, but this might be some weird anomaly.
Comment: just to be here on the save side too: how do you determine, that the elem got removed?  also i would asume, that ``removeFrom*`` with an unknown element might just ignore your wish silently.
Comment: I send the final object back to client as JSON. Added it in code example. The element is known and the id is actually send in from the client as an argument to the func.
Comment: in your original code with just the remove i would say, that elem in the list and the elem returned from the service is just another one.  so maybe you are tripping over different identities of something that seems the same object to you. as the elem is supposed to be in the category, why not just take this elem (instead of asking the service). e.g. ``def elem = category.elems.find{ it.id==1 }; if (elem) { ... category.removeFromElems(elem); ... }``
Answer: are you saving the category instance afterwards?
category.elems.remove(elem)
category.save()

Comment: Of course, by calling a service method which does `category.save(flush: true)`.
Comment: are you sure that the `elem` gets removed from the collection? print the `elems` before and after deletion


What is the maximum time it will take to open a combination lock?

Question: You have a barrel lock with $4$ wheels, each of which has $6$ numbers. If you can try one combination every three seconds, what is the maximum time (in hours, minutes, and seconds) it will take you to open the lock?
If there are $6$ numbers on each wheel, it's $6 \times 6 \times 6 \times 6 = 1296$ for the number of possibilities, right? I don't really know. But then if that is right how would I translate into minutes and seconds etcetera.
Comment: How many possible lock combinations are there?
Comment: Welcome to MathSE.  When you pose a question here, it is expected that you share your own thoughts on the problem.  Please edit your question to show what you have attempted and explain where you are stuck so that you receive responses that address the specific difficulties you are encountering.  This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Comment: You have posted a large number of questions recently that seem like mathcounts or AMC questions. I don't think this is the best use of this website; consider going on the AOPS website for similar problems and solutions. Their database is quite good and quite extensive
Comment: You are correct that there are $6^4 = 1296$ possible combinations.  Multiplying that by $3$ will give you the number of seconds it takes to try all the combinations.  There are $60$ seconds in a minute and $60^2 = 3600$ seconds in an hour.
Comment: @N. F. Taussig   I tried this and got 3888 seconds, 64.8 minutes, and 1.08 hours, but it was still wrong.
Answer: Since there are six choices for each of the four wheels, there are indeed $6^4 = 1296$ possible combinations to try.  Since each combination takes $3$ seconds to try, trying all the combinations takes $3 \cdot 1296 = 3888$ seconds, as you found.
There are $60$ seconds in a minute and $60^2 = 3600$ seconds in an hour.  To determine the number of hours, minutes, and seconds, use division with remainder.  First, we find the number of complete hours and the number of additional seconds.
$$3888~\text{s} = 3600~\text{s} + 288~\text{s} = 1~\text{h} + 288~\text{s} \tag{1}$$
Next, we find the number of minutes and additional seconds in $288~\text{s}$.
$$288~\text{s} = 4 \cdot 60~\text{s} + 48~\text{s} = 4~\text{m} + 48~\text{s} \tag{2}$$
Substituting our result from equation 2 into equation 1 yields
$$3888~\text{s} = 1~\text{h} + 4~\text{m} + 48~\text{s}$$


how can i scale up website or scale down depending on screen size

Question: so i made a website that has images multiple textboxes and etc, some user percentage and some use pixels by that i mean they use that to be in the specific place there in right now. So if you connect your laptop to a tv and put the website it will automatically scale up perfectly it just causes the things to be a little blurry but everything is in place. i was wondering how i can add like a function for my website that selects everything in the page and just shrinks it or expands it depending on the screen size, i dont care if it gets blurry after shrinking or expanding. Or if anyone has any other idea on how i can make everything fit to page no matter screen size it would be very helpful.
Comment: You should google for *responsive website* and you will find lots of tutorials on how to do this. This is too broad of a question to be properly answered here. Part of the solution might be [media queries](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries).
Comment: so lets say you like a couple pictures and a couple text boxes in a specific position and a specific size, when i plug my laptop to a tv it will automatically scale up and look normal, but if you go on a bigger screen size from another laptop it will look bad and things would be out of position. I was wondering how i could like scale it up like when its connected to the tv. But still thank you i will do that.
Comment: Yes I know what you mean, but trust me this is a very common topic which pretty much any modern website faces and there is a lot to cover starting from selecting the right image formats like svg, to media queries, flexbox, grid etc. . All play a part in this so called responsive web design. You could spend a lot of time on this.
Comment: yes i searched it up a bit and i found out it needed lots of work but i was wondering if i could like scale it up like when you connect it to a tv. But still thankyou for your suggestion
Comment: use vw instead of px XD
Comment: first can you use vw for the size of something and like the position and second will it keep something in the same place no matter how big the screen
Answer: First of all, there are multiple ways to make a site responsiv,
the easiest way are the media queries:
@media only screen and (max-width: 600px) {
  body {
    background: #fff;
  }
}
@media only screen and (min-width: 601px) {
  body {
    background: #ccc;
  }
}

This can also be applied to different stylesheets:
    <link rel="stylesheet" type="text/css" href="/styles/gardener_main.css" media="screen"/>
    <link rel="stylesheet" type="text/css" href="/styles/additional.css" media="screen"/>
    <link rel="stylesheet" type="text/css" href="/styles/gardener_800.css" media="screen and (min-width: 800px)"/>
    <link rel="stylesheet" type="text/css" href="/styles/gardener_799.css" media="screen and (max-width: 799px)"/>

They are basicly telling the devices what styles to use for what display size.
For the start you can work through this:
https://www.w3schools.com/css/css_rwd_mediaqueries.asp
to get a better understanding of the media query itself.
But! Most somehow tend to forget that you also need to adjust your html:
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

Depending on how much devices and how much older devices you want to support you can also add a switch that basicly replaces everything:
<?php

    $mobrowser = '0';
    if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android)/i',
    strtolower($_SERVER['HTTP_USER_AGENT']))) {
    $mobrowser++;
    }if ((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml') > 0) or
    ((isset($_SERVER['HTTP_X_WAP_PROFILE'])
    or isset($_SERVER['HTTP_PROFILE'])))) {$mobile_browser++;}
    $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
    $mobile_agents = array(
    'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
    'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
    'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
    'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
    'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
    'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
    'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
    'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
    'wapr','webc','winw','winw','xda ','xda-');

    if (in_array($mobile_ua,$mobile_agents)) {$mobrowser++;}
    if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini') > 0) {$mobrowser++;}
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows') > 0) {$mobrowser = 0;}
    if ($mobrowser > 0) {
    echo '
    HTML old mobile devices etc
    ';
    }
    else {
    echo '
    HTML desktop
    ';
    }?>

With this enormus something you can grab the mobile agents,
but such things are only interesting if you really want to support
historic devices.
Comment: yes i know this but this would take lots and lots of time i was wondering can you just select everything in the body and just make it bigger. if not ill go this way
Comment: Using pre made templates and libarys, it really depends on how much work you want to put into it.
Comment: Can you use VH and VW and if you do what are the downsides to using them
Comment: There are no downsides, just follow thier rules or to say it better use them the right way: https://elementor.com/help/whats-the-difference-between-px-em-rem-vw-and-vh/
Answer: Maybe you could try to add some css like
@media screen and (min-width: 1240px) {...}
Comment: what will that do
Comment: with css @media screen you can add the min-width and max-width, depending on the device size you want to style. You can test how it looks in browser with inspect element and toggle device toolbar
Comment: do you have like a quick demo with a picture or something so i can see how it works
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Responsive
Here is how you can test it. Just open it in browser, go right click inspect element or f12. I marked with red where you can see that, how it will look on different sizes.


Prove $\frac{d}{d\theta} R(\mathbf{n}, \theta) = S(\hat{\mathbf{n}})R(\mathbf{n}, \theta)$

Question: I think I am close with this proof - I just need the final step.
Let $R(\mathbf{n}, \theta) \in SO(3) $ be the 3D rotation matrix of angle $\theta$ around axis $\mathbf{n}$. Then show that $$\frac{d}{d\theta} R(\mathbf{n}, \theta) = S(\hat{\mathbf{n}})R(\mathbf{n}, \theta)$$ where $\hat{\mathbf{n}}$ is the unit vector lying on the axis $\mathbf{n}$, and $S(\mathbf{x})$ is the skew-symmetric matrix $$ S(\mathbf{x}) = \begin{pmatrix}
0 & -x_3 & x_2 \\
x_3 & 0 & -x_1\\
-x_2 & x_1 & 0
\end{pmatrix}$$
We have
$$R(\mathbf{n}, \theta)R(\mathbf{n}, \theta)^T = \mathbf{I}$$
so
$$\frac{d}{d\theta}(R(\mathbf{n}, \theta)R(\mathbf{n}, \theta)^T) = \frac{d}{d\theta}\mathbf{I}$$
$$(\frac{d}{d\theta}R(\mathbf{n}, \theta))R(\mathbf{n}, \theta)^T + R(\mathbf{n}, \theta)(\frac{d}{d\theta}R(\mathbf{n}, \theta))^T  = \mathbf{0}$$
$$(\frac{d}{d\theta}R(\mathbf{n}, \theta))R(\mathbf{n}, \theta)^T + ((\frac{d}{d\theta}R(\mathbf{n}, \theta))R(\mathbf{n}, \theta)^T)^T  = \mathbf{0}$$
which implies
$$S + S^T = \mathbf{0}$$
for $$S = (\frac{d}{d\theta}R(\mathbf{n}, \theta))R(\mathbf{n}, \theta)^T$$
So $S$ is a skew-symmetric matrix, and $$\frac{d}{d\theta}R(\mathbf{n}, \theta) = SR(\mathbf{n}, \theta)$$
$\hat{\mathbf{n}}$ is an eigenvector of $R(\mathbf{n}, \theta)$, so multiplying both sides by $\hat{\mathbf{n}}$, we have:
$$\frac{d}{d\theta}R(\mathbf{n}, \theta)\hat{\mathbf{n}} = SR(\mathbf{n}, \theta)\hat{\mathbf{n}}$$ $$\frac{d}{d\theta}(R(\mathbf{n}, \theta)\hat{\mathbf{n}}) = S(R(\mathbf{n}, \theta)\hat{\mathbf{n}})$$ $$\frac{d}{d\theta}\hat{\mathbf{n}} = S\hat{\mathbf{n}}$$ $$\mathbf{0} = S\hat{\mathbf{n}}$$
Solving for S, we find:
$$ S = \begin{pmatrix}
0 & -a\hat{\mathbf{n}}_3 & a\hat{\mathbf{n}}_2 \\
a\hat{\mathbf{n}}_3 & 0 & -a\hat{\mathbf{n}}_1\\
-a\hat{\mathbf{n}}_2 & a\hat{\mathbf{n}}_1 & 0
\end{pmatrix} = aS(\hat{\mathbf{n}})$$
for all real $a$, and so we have:
$$\frac{d}{d\theta} R(\mathbf{n}, \theta) = aS(\hat{\mathbf{n}})R(\mathbf{n}, \theta)$$
So it seems that all that there is left to do is show that $a = 1$, but I can't work out how to do this. Taking the determinant and trace seem like algebraic dead ends, because $det(S) = tr(S)= 0$. Any ideas?
Comment: What is $\|S\|_F^2$ ?
Comment: $\| S \|_F^2 = 2a^2$, so I should try to show that $\| \frac{d}{d\theta} R(\mathbf{n}, \theta)\|_F^2 = 2$? Is that on the right track?
Comment: Yes, now evaluate the derivative at $\theta=0$.
Answer: Let $N=S(n)$ and recall that $\,\,N^3=-N$.
Using the Rodrigues formula, the proof is simple.
$$\eqalign{
R &= I + N\sin\theta + N^2(1-\cos\theta) \cr
NR &= N + N^2\sin\theta + N^3(1-\cos\theta) = N^2\sin\theta + N\cos\theta \cr
\frac{d}{d\theta}R &= \big(N\cos\theta + N^2\sin\theta\big) = NR \cr
}$$
Comment: Thanks, but I was hoping to do it without an explicit form for the rotation matrix, which seems like a much stronger result. The derivation of the derivative is trivial from there.


Expressão Regular para obter o que há fora dos colchetes

Question: Texto de exemplo:
Itaú [123.456,89]

Para obter o que há dentro dos colchetes (incluindo os colchetes) eu usei:
\[(.*?)\]

A dúvida é saber como obter o que está fora?
Imagino que seja uma lista negada, algo simples. Já pesquisei mais de hora e nada.
Se possível, eu queria saber também como obter o que está dentro do colchete, sem incluir os colchetes?
Tudo em uma única expressão, sem prolongar o código [pedaladas].
Texto de exemplo pode ser:

"Itaú 1 [123.456,89]", "Itaú 2 [543.456,59]", "Banco do Brasil [987.543,21]", etc.

Ou seja, incluem acentos, mais de uma palavra, logo tem espaços e pode ocorrer de começar com números.
Comment: Tem outro exemplo? as linhas sempre iniciam com a-z0-9 seguidas de conchetes?
Comment: Texto de exemplo pode ser "Itaú 1 [123.456,89]", "Itaú 2 [543.456,59]", "Banco do Brasil [987.543,21]", etc. Ou seja, incluem acentos, mais de uma palavra, logo tem espaços e pode ocorrer de começar com números.
Answer: Minha sugestão é usar classes negadas para combinar "tudo o que não for colchete": [^\[]+ e [^\]]+.
Juntando e colocando os grupos ficou: ([^\[]+) (\[([^\]]+)\])
Exemplo:

var str = 'Itaú 1 [123.456,89]';
var result = str.replace(/([^\[]+) (\[([^\]]+)\])/, 'grupo 1: "$1"
grupo 2: "$2"
grupo 3: "$3"
');
document.body.innerHTML = result;
Comment: Gostei! Nada mal!
Comment: Essa fico boa!!
Answer: Veja funcionando no Regex.
Qualquer esclarecimento pergunte.
Pattern:
/^([^\]]+) \[([^\]]*)\]/gm

Input:
Itau [2.265,41]
Bradesco [1.375,21]
Santander Bradesco [784,12]
Caixa 2 []

Match:
MATCH 1
1.  [0-4]   `Itau`
2.  [6-14]  `2.265,41`
MATCH 2
1.  [16-24] `Bradesco`
2.  [26-34] `1.375,21`
MATCH 3
1.  [36-54] `Santander Bradesco`
2.  [56-62] `784,12`
MATCH 4
1.  [64-71] `Caixa 2`
2.  [73-73] ``

Comment: Boa! Mandou bem!
Answer: Em javascript, eu faria da seguinte forma:
Para obter somente a palavra Itaú:
'Itaú [123.456,89]'.replace(/(\[.*\])/g, '');

Para obter o que está dentro do colchetes (sem os colchetes):
'Itaú [123.456,89]'.match(/\[(.*)\]/)[1]

Comment: Não sou muito bom de `regexp` :(
Comment: Texto de exemplo pode ser "Itaú 1 [123.456,89]", "Itaú 2 [543.456,59]", "Banco do Brasil [987.543,21]", etc. Ou seja, incluem acentos, mais de uma palavra, logo tem espaços e pode ocorrer de começar com números.
Comment: Acho fantástico a mágica das expressões regulares, mas também tenho muita dificuldade de achar o Pattern. Devido a demora, muitas vezes surge a "pedalada" pra chegar na solução com mais linhas, hehe.
Answer: Veja funcionando no Regex.
https://regex101.com/r/vD2kN9/1
$re = "/([A-Za-zÀ-ú0-9]+)([.,]?)/";
$str = "Itaú [123.456,89]";

preg_match_all($re, $str, $matches);


Comunicação do c# e C++

Question: Como posso fazer o código C# chamar uma variável que está em um arquivo de C++ por exemplo. Sabendo que estou utilizando o Visual Studio.
Código C++:
<code>#include "stdafx.h"
#include <iostream>

int main()
{
    int test = 10;
    return 0;
}
</code>
mas como posso acessar essa variável no c#
Comment: Basicamente você precisa de uma interface, um método que te permita acessar o valor da variável. Depois compilar o código `c++` como uma biblioteca `dll` para que possa ser acessada dentro do código `c#`.
Comment: Como vc quer fazer isso? Por dll (funciona, já fiz com delphi e c#)? vc que código fonte inline? Criar um projeto CLR na solution? (funciona, vc pode ter projetos de linguagens diferentes na mesma solution, C#,VB,C++)
Comment: Não é possível fazer diretamente no mesmo código fonte... pois o compilador do c# trabalha de uma forma diferente do c++.
Comment: Existem formas de fazer isso, aliás ótima pergunta !
Comment: Bom eu tentei com o qt mas foi um completo fracasso de fazer uma gui entao resolvi usar o c# so que eu precisaria urgentemente disso, mas os tutoriais dos foruns sao bem antigos e bagunçados
Comment: Qual é o fluxo da chamada? É sua aplicação c++ que vai chamar uma biblioteca c#, ou é uma interface c# que chama uma biblioteca c++?
Comment: @WilliamJohnAdamTrindade c# chamando uma biblioteca em c++
Comment: Verifique esse artigo: [Using C++ in C# by Example](http://www.dorodnic.com/blog/2014/12/10/calling-cpp-by-example/).
Comment: @jean Sim mas eu preciso estabelecr uma comunicação entre os dois
Comment: Dlls se comunicam com .exe através de métodos que passem primitivas como parâmetros e retorno. Já se vc tiver dois projetos, um C++ e outro c# no visual studio talvez fique + fácil pois eles podem compartilhar classes
Answer: Tu precisa fazer interop. Basicamente tu vai gerar uma dll em c++ expondo uma interface para ser consumida no c#. Na aplicação c# tu vai importar essa dll e então fazer a chamada do código nativo dentro do código gerenciado. No MSDN tem uma série ótima falando sobre o uso do Pinvoke.

https://msdn.microsoft.com/en-us/library/eyzhw3s8.aspx
https://msdn.microsoft.com/en-us/library/2x8kf7zx.aspx

Palavras chaves para pesquisa: Pinvoke, Interop, dllimporter
Answer: Já que é uma só variável, mantenha a variável do C++ salva em um XML e quando quiser obtê-la no c#, basta ler o xml. Essa ideia da interface pelo arquivo .dll é interessante ser usado em uma aplicação bem pesada.

Comunicação do c# e C++


In decision tree construction, can a good splitter have low information gain?

Question: I have a data set with a candidate splitter variable that is a natural choice from the business perspective.  It has two values, and the distributions of the target when conditioned on the two values of this variable are quite distinct (visually).  Yet the information gain of this variable is very small (almost 80% smaller than some other variables whose conditional distributions are far less differentiated.) Is it possible that a variable with low information gain is nevertheless a good splitter in some other sense?
Answer: You can use Information Gain (IG) to see if features that are natural choice to predict some target class are really better than the other features you can use. In your application domain, it might be true that there are better predictive variables than yours (Say $V$).
However:
There are cases where IG gets inflated just because of random chance. More specifically when the training set is small. See http://en.wikipedia.org/wiki/Adjusted_mutual_information
If the other features are continuous the decision tree induction process goes for binary discretization. Due to multiple comparisons, the chances to find a high value for IG are not negligible. See http://en.wikipedia.org/wiki/Multiple_comparisons_problem
Similar to the point above, when there are lots of features you can use for prediction the chance to find a group of very predictive features because of overfitting are high. See this paper about ensemble of trees: http://www.pnas.org/content/99/10/6562.abstract
Keep in mind that there are other splitting criteria, for example the Gini Gain (GG) used in CART (http://en.wikipedia.org/wiki/Decision_tree_learning). However, if you used that you might have the same results you obtained with IG because they are different parametrization of the same thing (Rényi Entropy http://en.wikipedia.org/wiki/R%C3%A9nyi_entropy). See if statistical tests (e.g. Chi-square) leads to different results. http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.92.9930
If you are interested in the quality of your predictor variable $V$ you might use feature importance in Random Forest. This can assess its quality in a more robust way. See http://www.stat.berkeley.edu/~breiman/RandomForests/cc_home.htm . R version http://cran.r-project.org/web/packages/randomForest/index.html
Also, there should be a reason why you consider $V$ as important. Things that are not included in the IG computation. Is $V$ easy to measure? Cheap to measure?


Tennis coaches can't coach during a match?

Question: Serena Williams lost a tennis match yesterday at the 2018 US Open, but not without some controversy.

[Williams was] penalized in the second set because of three separate game violations.
Source

The first violation is mostly where I'm confused.

Williams got the first violation from umpire Carlos Ramos, who ruled that Williams received coaching earlier in the set; she told him she'd "rather lose" than cheat.

What does that mean? Coaches can't "coach" during a match? Does that mean no communication is allowed between coach and player? Why have a coach then if they can't give you a second perspective during a match? Seems like such a strange rule.
How closely is this rule followed? Williams' coach seems to think it's both a bad rule and generally not enforced. Is this true? Are there other sports leagues with a similar rule? I'm coming from an American football and baseball understanding, where coaching is vital to play.
Comment: It is definitely not always enforced. Look at 7:53 of [this video](https://www.youtube.com/watch?v=ZWjSOj4Ln4Y) showing the 5th set tiebreaker between Nadal and Fritz in the 2022 Wimbledon quarterfinal. Fritz just lost a point, and his coach is doing a whole lot of talking and hand gesturing from the stands. No violation was called.
Answer: On-court coaching is defined by the WTA as the player being allowed, once per set, to call their coach onto the court for coaching, and that any active communication between the coach and player outside of this is considered a violation. However, the WTA allows on-court coaching for all tournaments except the four grand slams.
During the game, chair umpire Carlos Ramos apparently saw some signals from Serena Williams' coach and interpreted it as an attempt at coaching, despite the fact that Serena was unaware of the signal and may not have been even looking at her coach's box that point. At that point, as with the abuse of racket and unsportsmanlike conduct violations that followed, handing the code violation for on-court coaching was fully at the discretion of the chair umpire, who deemed it necessary.

On-court coaching in tennis : Blessing or a curse? - Essentially
Sports
WTA tour to allow on-court tennis coaching - Tennis -
Telegraph
Answer: By rule, no, coaches are not permitted to coach during a match at the professional level. However, there have been recent interviews with popular coaches for some of the game's biggest names and they confirmed that coaching does occur in nearly every match. It's sort of like baseball. Coaches just have signals they give the players, only they're very subtle. For instance, prior to a serve a coach may sit with his face in his hands as a sign to the player that they should serve down the T or out wide. After a point, a coach may clap a certain number of times when the player is facing the box to indicate something that they notice as a weakness of an opponent.
You'll never be able to point out exactly when coaching is occurring, but know that it is indeed happening!


Ratio of circle's quadrant and circle

Question: You are given a circle's quadrant and you are supposed to calculate the ratio of its circumference and the whole circle's circumference.
Which one of these is right:
(A): 1 over 4 (B): 4+Pi over 4*Pi (C): 4+Pi over 2*Pi (D): 4*Pi over 4+Pi (E): 3 over four
I think it's B. Is that correct?
Comment: What do you mean "a circle's quadrant" and what do you mean "its circumference"?
Comment: Okay, I googled.  What is the formula for the circumference of a quadrant?  And what is the formula for the circumference of a circle?  What is the ratio between them?  Where do you have problems answering those questions?
Comment: I know the formulas, I just need someone to confirm it.
Comment: How in the pluperfect hell are we supposed to confirm your results if you don't tell us what your results were?!!?!!?!!?!!?!!?!!?!!?
Comment: Give your reason and I'll tell you if it is right.
Comment: My reasoning was that it's choice B, because it's clearly not 1 over four, it's also not 3 over 4. It cannot be D, because the whole circle's circumference cannot be 4+Pi. It could be C, but I think that the perimeter of the whole circle is bigger than one quadrants.
Answer: The circumference of a circle is $2\pi r$.
A quadrant has $\frac 14$ of that or $1/2\pi r$ as an arc plus two radii as legs.  So the perimeter of a quadrant is \frac 14 \pi 4 + 2r$.
So the ratio is $1/2 \pi r + 2r : 2\pi r$ /~/ $\pi + 4: 4\pi$
which is B).

Ratio of circle's quadrant and circle


Is there a polynomial (or series) expression for summing $S_d(a,N)=\sum_{k=0}^{N-1} \log(1+{1\over a+k \cdot d})$? (perhaps Bernoulli-type)

Question: I need a quickly evaluatable expression for sums of consecutive logarithms of the type
$$ S_{d}(a,N) = \log(1+ {1\over a})+\log(1+ {1\over a+d})+\log(1+ {1\over a+2d})+ \cdots + \log(1+ {1\over a+(N-1)d})
$$
Here $N$ is typically very large (as well as $a$ while $d$ may be a small integer) why it is not feasible to evaluate the direct sum. The goal is to find some $a$ (not necessarily integer) with given fixed $d$ and $N$ which gives the sum a pre-determined value. For instance by a binary search inside a range of $a_\min$ and $a_\max$, and such a search needs to evaluate the sum multiple times.
I thought of some idea like assuming a Hurwitz-zeta-like ansatz of an infinite series and take the difference of two "exemplars" of them
$$ \begin{array}{lll}
 S^{^\star}_{d}(a) &= \log(1+ {1\over a})+\log(1+ {1\over a+d})+\log(1+ {1\over a+2d})+ \cdots  \\
 S_d(a,N) & \overset?= S^{^\star}_{d}(a/d) -  S^{^\star}_{d}(a/d+N)
\end{array}$$
Fumbling with transposing the Bernoulli-polynomials as a matrix of coefficients I seem to have got a possible solution, but perhaps there is a well known expression, perhaps like $\psi()$ function (in Pari/GP) or the like, or possibly even some more obvious expression.

Q: Is there a polynomial or powerseries-expression for the finite sum of $\log(1+1/a_k)$ with equally spaced $a_k$ (having integer difference)?

Update: I've now an exposition of that method which employs the Bernoulli-numbers  /Zeta-values for an asymptotic series. It was too difficult to start this explanation in an answerbox here. I began with a draft in a pdf-file (see here) which I shall convert soon in a valid answer here.
Comment: I suppose that one key is the starting guess of the root. I am still working the problem. See you tomorrow (I hope)
Comment: I made some progress for the starting guess. See my edit. Please, let me know how this works. Cheers.
Comment: @Claude - good morning (our local time- morning sun is on my desk)! Thanks for your work. It seems much more precise than my own results using the Bernoulli/Zeta ansatz while the timing of the latter seems better, but both are so fast in Pari/GP that this shall make no difference. Please see my new answer for a comparision of precisions.
Comment: Hi Gottfried ! Where is your new answer ?
Comment: @Claude - upps: the reproduction of the table to be copied into my answer needed a bit more time than I thought... Unexpected finetuning of the table for the readers pleasure included :-)
Comment: Hi @Claude - I needed a long time to explain the ansatz with the Bernoulli-numbers resp -polynomials and it was too difficult to begin this in a MSE-answer-box. I've now a hopefully readable version as a pdf-file and shall from this derive a (shorter) MSE-answer as soon as possible. If you like see here: http://go.helms-net.de/math/collatz/HurwitzZetaAndSumOfLogs.pdf a draft version yet without references and so.
Comment: Hi Gottfried ! I am very impressed, be sure. Cheers :-)
Answer: I do not know how much this could help.
$$\sum_{k=0}^{N-1} \log(1+{1\over a+k \, d})=\sum_{k=0}^{N-1} \log(1+ a+k \, d)-\sum_{k=0}^{N-1} \log( a+k \, d)$$
$$\sum_{k=0}^{N-1} \log(b+k \, d)=\log\left(\prod_{k=0}^{N-1} (b+k \, d) \right)=\log \left(b d^{N-1} \left(\frac{b+d}{d}\right)_{N-1}\right)=\log \left(\frac{b d^{N-1} \Gamma \left(\frac{b}{d}+N\right)}{\Gamma
   \left(\frac{b+d}{d}\right)}\right)$$
$$S_{d}(a,N) =\log \left(\frac{\Gamma \left(\frac{a}{d}\right) \Gamma
   \left(\frac{a+1}{d}+N\right)}{\Gamma \left(\frac{a+1}{d}\right) \Gamma
   \left(\frac{a}{d}+N\right)}\right)$$ Using the  log gamma function could make the problem "simple" from a numerical point of view.
The derivative is
$$\frac{\partial} {\partial a} S_{d}(a,N)=\frac{\psi
   \left(\frac{a+1}{d}+N\right)-\psi \left(\frac{a}{d}+N\right)+\psi \left(\frac{a}{d}\right)-\psi\left(\frac{a+1}{d}\right)}{d}$$
I tried using $d=3$, $N=10^6$ and $S_{3}(a,10^6)=4.567$ using Newton method with $a_0=1$. The iterates are
$$\left(
\begin{array}{cc}
 n & a_n \\
 0 & 1.00000 \\
 1 & 2.19160 \\
 2 & 3.54105 \\
 3 & 4.19248 \\
 4 & 4.27054 \\
 5 & 4.27141
\end{array}
\right)$$
It seems that the function looks like an hyperbola with an infinite branch when $a \to 0^+$. Trying polynomials does not seem (at least to me) to be a good idea.
Edit
If $N$ is really large, using Stirling approximations
$$S_{d}(a,N)\sim \log \left(\frac{\Gamma \left(\frac{a}{d}\right)}{\Gamma
   \left(\frac{a+1}{d}\right)}\right)+\frac{\log \left({N}\right)}{d}$$ Now, using an expansion around $a=1$ would give as a crude estimate
$$a=1+\frac {d \left(S_{d}(a,N)-\log \left(\frac{\Gamma \left(\frac{1}{d}\right)}{\Gamma
   \left(\frac{2}{d}\right)}\right)\right)-\log (N) } {\psi \left(\frac{1}{d}\right)-\psi \left(\frac{2}{d}\right) }$$
For the worked example, this gives almost exactly the first iterate of Newton method : $2.191599091$ instead of $2.191599310$. So, this is not of any interest.
For the generation of the starting guess, we can avoid the use of the $\Gamma(.)$ and $\psi(.)$ functions using the integral over $k$ instead of the sum. This would then require to solve (even approximately) for $a$ the equation
$$d\,S_{d}(a,N)=-(a+d (N-1)) \log (a+d (N-1))+(a+d (N-1)+1) \log (a+d (N-1)+1)+a \log (a)-(a+1)
   \log (a+1)$$ Considering that $N$ is large, this could reduce to
$$(a+1) \log (a+1)-a \log (a)=C\qquad \text{where} \qquad C=\log (edN)-d\,S_{d}(a,N)$$
Using a quick and dirty regression (data were generated for the range $0 \leq a \leq 10^4$) revealed as a good approximation
$$\log(a)=C-1$$
Applied to the worked example, this would give $a=3.364$
Comment: Ah, very nice. I'll look at it deeper in the afternoon. I thought also to use the derivative of the ln, make a geometric series, simplify and take the integral, but did not check yet. The good thing with your proposal is that Pari/GP has the lngamma() and the  psi()-function on board, however I don't know yet about the time-efficiency of it.
Comment: Upps, my initial-values estimated for the Newton-algo have been much too restricted and then have been much too optimistic for the general case. I'll have to look at your estimates again...
Comment: Hi Claude, this seems crazy... I got a *simple* estimate for the $a$-value to be found by the Newton-algo (which means, it's also a perfect initial guess) by the formula $a_\text{init} = d \cdot N / (\exp(\Lambda \cdot d)-1 )$. The true value $a$ is at most $1$ larger than that guess... . I hope I've not introduced some completely simple error...
Comment: Hi Claude - I noticed numerical issues with the $lngamma()$ function in Pari/GP for very high $N$. Please see my updated answer on the comparision and the precision issues.
Answer: The following are precision-comparisions of the two methods.Update, see end

Precision

Claude Leibovici's solution is called "su_lngamma" and my own (provisorical) approximation using the modified ZETA-matrix (involving the Bernoulli numbers) giving 16 or 32 coefficients for a powerseries is called "su_zetamat". Default numerical precision in Pari/GP was $200$ dec digits:
    N=100             d=3
        a              su      su_lngamma        err_lngamma       su_zetamat         err_zetamat
  -----------------------------------------------------------------------------  ----------------
       10       1.1773591       1.1773591   (2.7863493 E-200)       1.1773591  (0.00000000030768858)
      100      0.46460322      0.46460322  (-4.4142713 E-200)      0.46460322       (3.6176459 E-27)
     1000     0.087531701     0.087531701   (1.9429811 E-199)     0.087531701       (3.4555879 E-44)
    10000    0.0098539050    0.0098539050   (1.7019105 E-198)    0.0098539050       (1.3751738 E-61)
   100000   0.00099851296   0.00099851296   (1.7766216 E-197)   0.00099851296       (1.7278168 E-79)
  1000000  0.000099985103  0.000099985103   (4.0133228 E-196)  0.000099985103       (1.7700314 E-97)

  N=1000000         d=3
          a         su   su_lngamma      err_lngamma     su_zetamat           err_zetamat
  ----------------------------------------------------------------------  ----------------
         10   4.2376194   4.2376194  (-1.0962866 E-196)   4.2376194  (0.00000000030768858)
        100   3.4396673   3.4396673  (-9.8020930 E-196)   3.4396673       (3.6176459 E-27)
       1000   2.6692336   2.6692336  (-7.2429241 E-196)   2.6692336       (3.4959594 E-44)
      10000   1.9024033   1.9024033  (-4.3753696 E-196)   1.9024033       (3.4815251 E-61)
     100000   1.1446656   1.1446656   (1.5592125 E-196)   1.1446656       (3.4800708 E-78)
    1000000  0.46209837  0.46209837   (7.7997020 E-196)  0.46209837       (3.4800344 E-95)

Obviously the lngamma()-solution as implemented in Pari/GP provides maximal precision while the use of the Zeta-matrix and the $O(x^{16})$ resp $O(x^{32})$ truncation of its (only asymptotic!) powerseries has of course little precision for small startvalues $a$.
For the application of the problem (eventually searching an integer (lower bound) for $a$) the orders of the found errors show, that the errors themselves are a minuscle problem, but of course one likes an arbitrary-precise solution much much more than an asymptotic one, if the other requirements are not too costly...

Timing

The average timing with large $a$ and $N$ was $1.3 \text{msec}$ for the lngamma and $0.3 \text{msec}$ for the matrix-solution.
I've not yet checked the binary-search/Newton-iteration application for time-consumption, I'll add this soon. (Thanks also to Claude for the simple(!) idea to apply Newton, I've just crooked around with a binary search...)
Given some value $\Lambda$ for the sum-of-logarithms (given $d,N$) we can find a very nice estimate $a_\text{init}$ for the $a$ for the Newton-algorithm:
From
   $$ \Lambda = \sum_{k=0}^{N-1} \log(1+1/(a+k \cdot d)) $$
using the logarithmic expression which occurs in the zetamatrix-method (I'll explain this method soon in another answer) this gives
$$ a_\text{init} =  N \cdot {d \over \exp(\Lambda\cdot d)-1} \\
 \small{\text{with } \mid a-a_\text{init} \mid \lt 1 \text{ heuristically}}
$$
$\qquad \qquad$ (1)(previous, insufficient solution moved to bottom of text)

Binary search

With this I get the average timeconsumption for the binary-search with the su_lngamma-solution of about $37 \text{msec} $ with my default real-precision of $200$ digits.

Newton-Algorithm

Testing the su_lngamma with the Newton-Algorithm (with inital values $a_\text{init}$ using random $\Lambda$ as targets I get an average time of $14 \text{ msec }$ getting nearly full precision of $200$ decimal digits for the found $a$ which satisfies the equation.
Using the su_zetamat method I get an average finding-time of $6.5 \text{ msec }$ with error about $1e-80$ for $a >1000$ and $32$-terms of the powerseries.
It is remarkable that the estimate $a_\text{init}$ is at most $1$ away from the true value $a$ to be found in all experimental tests and even converges from below when $N$ increases.

Numerical issues (Update)
When testing with high $N$ the lngamma()-method ran in numerical problems where the zetamatrix-method stayed stable. Having the default precision for $200$ decimal digits I looked at $N$ from the convergents of the continued fractions of $\beta=\log_2(3)$ and $\Lambda$ defined using $S=\lceil \beta \cdot N \rceil$ as
$$\Lambda = S \log 2 - N \log 3$$
For application of the methods discussed here in the thread for the problem of estimates of upper bounds for the minimal element $a_1$ for attempted Collatz-cycles the basic sum-of-logarithms entries must get a scaling factor of $m=3$ such that we try to fit the given $\Lambda$ with that sum
$$ \small{\Lambda = \log(1+1/3/a_1) +  \log(1+1/3/(a_1+d)) + \log(1+1/3/(a_1+2d)) +...+\log(1+1/3/(a_1+(N-1)d))} \\ \qquad \qquad \to \text{search that $a_1$ that gives equality} $$
That additional coefficient $m$ can easily be introduced into the lngamma() and psi() function given by Claude Leibovici as well as in the matrix-computation.
The convergents of the continued fraction gives values for $\Lambda$ alternating going towards zero or towards $\log 2$. With default real precision of $200$ I could go to the 16'th convergent before the Newton-algorithm with the lngamma()-method ran into numerical errors and diverged. I needed $800$ digits internal precision to allow $N$ from the $\approx 90$'th indexes, while the zetamatrix-method gave always reliably its approximates.
Note that the ini-values for the Newton-algorithm was the simple expression $$a_\text{ini}= {d \cdot N \over \exp( d \cdot m \cdot \Lambda)-1}= {3 N \over \exp( 9 \Lambda)-1}$$
and gave the extremely nice initial values at most $1.3333...$ aside of the final value for $a_1$.
mystat(cvgts[1,12])
 N=79335  S=125743   m=3 d=3
 sub_cyc=90957.1975845
     cyc=272871.592753                 (lower bounds for a1) by "1-cycle"-formula
 ---------
     ini=7215983491.01                 (upper bounds for a1)
     seq=7215983492.34    by Newton-lngamma 16 msec
     seq=7215983492.34    by Newton-mat 16 msec
    mean=7216102492.69                    (by a_1 ~ mean(a_k) formula)

mystat(cvgts[1,22])
 N=6586818670  S=10439860591   m=3 d=3
 sub_cyc=32927907417.2
     cyc=98783722251.5                     (lower bounds for a1)
 ---------
     ini=2.16890155331 E20                 (upper bounds for a1)
     seq=diverg    by Newton-lngamma 15 msec
     seq=2.16890155331 E20    by Newton-mat 16 msec
    mean=2.16890155341 E20

Changing precision to 800 digits
prec=800 display=g0.12
mystat(cvgts[1,22])
 N=6586818670  S=10439860591   m=3 d=3
 sub_cyc=32927907417.2
     cyc=98783722251.5                     (lower bounds for a1)
 ---------
     ini=2.16890155331 E20                 (upper bounds for a1)
     seq=2.16890155331 E20    by Newton-lngamma 187 msec
     seq=2.16890155331 E20    by Newton-mat 47 msec
    mean=2.16890155341 E20

mystat(cvgts[1,32])
 N=5750934602875680  S=9115015689657667   m=3 d=3
 sub_cyc=3.13413394194 E15
     cyc=9.40240182583 E15                 (lower bounds for a1)
 ---------
     ini=1.80241993368 E31                 (upper bounds for a1)
     seq=1.80241993368 E31    by Newton-lngamma 187 msec
     seq=1.80241993368 E31    by Newton-mat 47 msec
    mean=1.80241993368 E31

mystat(cvgts[1,92])
 N=31319827079776296150692564373472726097745399  S=49640751450516424688384944890954638315952916   m=3 d=3
 sub_cyc=1.22784746078 E44
     cyc=3.68354238234 E44                 (lower bounds for a1)
 ---------
     ini=3.84559701519 E87                 (upper bounds for a1)
     seq=3.84559701519 E87    by Newton-lngamma 94 msec
     seq=3.84559701519 E87    by Newton-mat 16 msec
    mean=3.84559701519 E87

mystat(cvgts[1,93])
 N=252466599014583305866715048411999465710443694  S=400150092122719341414742538102872703744992098   m=3 d=3
 sub_cyc=0.333333333333
     cyc=1.00000000000                     (lower bounds for a1)
 ---------
     ini=1.48219138365 E42                 (upper bounds for a1)
     seq=1.48219138365 E42    by Newton-lngamma 140 msec
     seq=1.48219138365 E42    by Newton-mat 31 msec
    mean=1.21410770129 E44

Reducing precision to 400 digits
prec=400 display=g0.12
mystat(cvgts[1,24])
 N=137528045312  S=217976794617   m=3 d=3
 sub_cyc=370924750025.
     cyc=1.11277425008 E12                 (lower bounds for a1)
 ---------
     ini=5.10125558286 E22                 (upper bounds for a1)
     seq=5.10125558286 E22    by Newton-lngamma 31 msec
     seq=5.10125558286 E22    by Newton-mat 16 msec
    mean=5.10125558288 E22

mystat(cvgts[1,44])
 N=205632218873398596256  S=325919355854421968365   m=3 d=3
 sub_cyc=3.74500056370 E21
     cyc=1.12350016911 E22                 (lower bounds for a1)
 ---------
     ini=7.70092775595 E41                 (upper bounds for a1)
     seq=7.70092775595 E41    by Newton-lngamma 32 msec
     seq=7.70092775595 E41    by Newton-mat 15 msec
    mean=7.70092775595 E41

mystat(cvgts[1,54])
 N=2438425051595107335801557824  S=3864812267597295609689840565   m=3 d=3
 sub_cyc=1.76555780448 E27
     cyc=5.29667341343 E27                 (lower bounds for a1)
 ---------
     ini=4.30518038047 E54                 (upper bounds for a1)
     seq=diverg    by Newton-lngamma 47 msec
     seq=4.30518038047 E54    by Newton-mat 0 msec
    mean=4.30518038047 E54

mystat(cvgts[1,64])
   *** for: division by zero

Surely, the problem is here with the Pari/GP-implementation of the lngamma() and/or the psi()-functions, and possibly other software works here more robustly.
Finally, it really amazes me, that the $a_\text{ini}$ values is so precise without any Newton-algorithm at all and I consider to just accept this value, possibly corrected a little bit upwards as upper bound for the $a_1$ for this estimation-method (based on the sum of logarithms of linearly progressing arguments).

Conclusion
Well, after the finding routines go for about 15 msec (nearly independently of size of $N,d$ and $\Lambda$) plus the advantage of the system-immanent precision of the lngamma() and psi() function I think the solution provided by Claude Leibovici is much favorable over my initial rough approach using the ansatz via Bernoulli-numbers/ZETA-matrix.

(1)  Original, but insufficient initializing was:
We can determine, assuming $d=0$ an upper bound for $a$ (call it $a_u$):
   $$ \Lambda = N \log(1+1/(a_u+0)) $$
then
   $$    a_u=1/(\exp(\Lambda/N)-1) \qquad \qquad \qquad \;  \\
     a_l=a_u-N \cdot d \qquad \qquad \text{lower bound} $$
Comment: I am waiting for you next answer about the initial estimate.
Comment: Hi @Claude, I've already updated that new estimate into my answer as $a_\text{init}$ ; the old estimate is now at the bottom for reference.
Comment: I am more than likely dumb : I do not see how you get $\Lambda$
Comment: Ah, well. Just choose *any* value for the Lambda. Then find the appropriate $a$ using the Newton-algo, and check by inserting that found $a$ into the sum-expression (or, if $N$ is large, into your *lngamma* expression). For the initializing of the Newton-algo use $a_\text{init}$ as described.  Well, actually I'm getting the Lambda from the expression $\Lambda = S \ln 2 - N \ln 3 $ where $S=\lceil\ N \log_2(3) \rceil $ . This is a problem of distance of powers of 2 and of 3 (as observed in the discussion of cycles in the Collatz-problem). $N$ can become really large by the contfrac convergents.


redirect route for validation in laravel

Question: I have a problem with the redirectRoute property in Laravel. What I want to do is: after the validation of the request, for example, the register request fails, redirect to another view with the proper errors. I have tried with protected $redirectRoute = '/route-name' in the RegisterController but it's not working. I'm using Laravel 5.4
Comment: Also it would be helpful to specify which version of Laravel you are using and apply the appropriate tag
Answer: See here: https://laravel.com/docs/5.4/validation#manually-creating-validators
You'll need to manually create the validator and then you can tell it exactly where to redirect to if the validation fails:
    $validator = Validator::make($request->all(), [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    if ($validator->fails()) {
        return redirect('post/create')
                    ->withErrors($validator)
                    ->withInput();
    }

And if you are using Form Requests, you can override the following properties to redirect to a custom location:
protected $redirect; // A simple URL. ex: google.com
protected $redirectRoute; // A route name to redirect to.
protected $redirectAction; // A controller action to redirect to.

Comment: I've tried the $redirectRoute property, but it doesn't work. I'll try the custom request then. Thank you very much :)
Answer: Updated answer, tested in Laravel 8. it is possible to create a ValidationException and set a custom redirect on it.
Summary:
use Illuminate\Validation\ValidationException;

$validator->setException( (new ValidationException($validator))->redirectTo('your/custom/location'));
$validator->validate();


DKIM for Email Service Provider clients

Question: How would you go about implementing DKIM signing in this scenario?

You have a service that allows customers to logon to your web application, create a newsletter, and send it to their subscribers using their domain name. (Like MailChimp, Constant Contact, etc.)
Each customer will have a different domain name.
The mail will be sent through your servers.

Is there a way for the customers emails to be DKIM signed without adding a DNS record for their domain? Is there a way to have the emails coming from the providers domain but have the customers "from" address?
Answer: You could use the Sender: header for this - put your domain in the Sender: header and sign with your DKIM key.  The From: header would continue to specify your customer's domain.  This approach is condoned by the DKIM specification (RFC 4871, appendix B.1.4).
You should be aware that many mail clients will display the Sender: header in addition to the From: header (gmail says "On behalf of").  Also I'm not sure whether in practice your deliverability with this approach will be as good as it would be if you signed with a key in the From: domain.  I suspect that using the From: domain's key will always give the best results, but that would require sticking a key in your customers' DNS.
Comment: AGWA i agree with you and we are on the same page as Zach's problem. We use INterspire as platform for sending email on behalf of our client. The application creates user account and inputs their company email as from email and its not using our domain as authorized sender. We would like to configure our mailer to do the same use our authorized sending domain on behalf of client just bu changing the Envelope header to be our domain as permited sender. Did you find resolution to your issue. Please share

DKIM for Email Service Provider clients


$_GET[] não funciona

Question: Tenho uma página .onion hospedada por Freedom, no qual suporta PHP 5, estou tentando carregar a página inicial do site home.html a partir do "loader" index.php, no qual tem esse início no código:
<?php
   $get = $_GET['load'];
   if(strpos($_GET['load'],'/language/') !== false) {
     $loadurl = file_get_contents("home.html");
     echo($loadurl);
     exit;
  }

aí quando vou entrar no site, é isso que aparece no início da página e ela não é exibida corretamente:

ambos arquivos estão na raiz do diretório da hospedagem. como solucionar essas mensagens?
Answer: Você precisa usar isset para checar se o get possui o índice.
   if( isset( $_GET['load'] ) )
   {
       if( strpos( $_GET['load'] , '/language/' ) !== false )
       {
         $loadurl = file_get_contents("home.html");
         echo($loadurl);
         exit;
      }
  }

Answer: Tente passar a variavel load como parametro na sua url
index.php?load=VALOR

$_GET[] não funciona


JavaScript: How to iterate through a table and remove the second cell in Javascript

Question: Lets say that I have a very simple table:

      TextFirst
      TextSecond

How can I traverse the table and remove "TextSecond".  The table could be any number of rows or cells.
Comment: $("table td:nth-child(2)").remove()
Comment: you only need to take out the second or ALL the TextSecond?
Comment: Do you want to do this for every row? Or just the first? What are the conditions that must be met for removal to occur?
Comment: I want to do it for every row and there may be more rows.
Answer: In your posted example you have, at least, two options I can think of:
$('td:nth-child(2)').remove();

Or:
$('tr td:eq(1)').remove(); // zero-based index, thanks @ZDYN for the catch

Or, in plain JavaScript:
var removeThis = document.getElementsByTagName('td')[1];
removeThis.parentNode.removeChild(removeThis);

JS Fiddle demo.
Comment: I believe `:eq()` index is 0-based.
Comment: Oh... **darn**, yeah: you're right! Sigh...I knew that, too. +1 for good eyes, and a thank you. **edited into answer** :)
Comment: in your plain js, would i not have to make a loop somehow?  it looks like it is only doing one
Comment: @William, it is, yeah; but I don't know what logic you're following to remove the second `td` elements. You say that "[the] table could be any number of rows or cells" but don't define how many, or whether it's always the second `td` of the row, or just the `td` that contains the string "TextSecond" and without that information, I can't really offer a more thorough alternative.
Answer: $("table td:nth-child(2)").remove()

Comment: You might want to take a read of [the mark-down help page](http://stackoverflow.com/editing-help/) for code-formatting. :)
Comment: kek i wrote it as fast as i could sorry :P ill fix that up right now
Comment: No worries; it seemed odd that you didn't know how to format code with a rep >2000... :)
Answer:     //var table = document.getElementById("?");
    for (i=0; i
 1)
            table.rows[i].cells[1].removeNode(true);
    }

or if you want to delete cells based on some condition. just because
    //var table = document.getElementById("?");
    for (i=0; i
= 0; j--)
        {
            if (table.rows[i].cells[j].innerHTML == 'TextSecond')
                table.rows[i].cells[j].removeNode(true);
        }
    }

Answer: You can use nth-child... :
$('table :nth-child(2)').remove();
JSFIDDLE


Amazon EC2 Can't Open Ports?

Question: I have an Amazon EC2 instance, and can't seem to figure out how to open additional ports.
I've added the ports to a security group, and assigned the group to the instance, but the ports are still not open. Only port 22 is open, which I believe is the default behavior. I can't open any other ports.
The instance is running Ubuntu. Firewall on the instance is disabled with ufw disable. Any help is really appreciated. I use https://www.yougetsignal.com/tools/open-ports/ to test my ports.
Here's my security group configuration:
Comment: What exactly isn't working? Testing ports isn't open can be interesting, but it's not a goal. You need a service listening on a port to really determine if it's open. Since ssh works your setup is probably correct. Port 22 being open is definitely not default behaviour, and you should limit what IPs can connect using SSH.
Comment: Could you check your config for network acl under your VPC subnet?
Comment: figured it out. needed to add `GatewayPorts yes` to my sshd_config file
Comment: Also I think Tim was right, I didn't have a service listening when I was testing initially.
Answer: Your security group settings look good.  You being able to SSH into the instance is a good sign.  I would think that you probably are testing the private IP address or the elastic IP address which may not return the results that you are looking for.  Just running #netstat -ant and verifying the ports that way may be a better test for you.  Also you can just use telnet to test the ports if its installed.
Comment: I don't think this is correct, assuming the person asking the question is testing the private IP address. Also, netstat doesn't help all that much because it doesn't tell you if the ports are externally accessible.
Comment: @Tim then please provide a suggestion.
Comment: I provided a suggestion in my comment above - nothing listening on the ports. Security group looks fine, but may not be assigned to instance. NACLs could also be involved. There's not enough information to say for sure.

Amazon EC2 Can't Open Ports?


Tirar tag do html pelo css na responsividade

Question: To querendo tirar a tag
 do html pelo css para responsividade
HTML:

Sistemas Próprios Para
 Empresas Autênticas

Lorem ipsum dolor sit amet, consectetur adipisicing elit.

CSS:
@media (max-width:600px){

.chamda1 h2{}
}

Tipo é p/ no responsivo não fique com uma quebra de linha no texto pra mim aplicar estilos no texto livremente sem essa quebra.
Comment: Sobre esconder um elemento, já tem várias postagens no site explicando como fazer (com o `` é mesma coisa) - Mas para fins de aprendizado, o problema do seu caso específico é que está usando `` para estilização, e a finalidade dele não é essa. Se quer estilizar um pedaço específico do cabeçalho de maneira diferente sem problema semântico, pode usar  no trecho desejado, e mudar o tipo de display ou layout com CSS puro. Ainda lembrando que a associação que fez de px com a largura do texto é problemática. Se quer insistir nessa idéia pode fazer algo até mais simples:
Comment: `Sistemas Próprios para Empresas Autênticas` - o   é o espaço inquebrável (pode ser substituido pelo unicode equivalente se quiser evitar uso legado de htmlentities). Desta forma, o texto será quebrado apenas no espaço convencional se necessário (o browser cuida disso sem `@media`). Note que não é recomendação do melhor meio, só comentei por ser mais simples e um pouco "menos pior" que o ``. O ideal é realmente pensar na semântica e evitar a situação atual, que é denominada [Problema XY](https://pt.meta.stackoverflow.com/q/499/70)
Answer: Podes adicionar para o br ficar com um "display: none" caso o width máx seja 600px. Por exemplo:

@media (max-width:600px) {
  .chamda1 h2 {}
  br {
    display: none
  }
}

Sistemas Próprios Para
 Empresas Autênticas

Lorem
ipsum dolor sit amet,
 consectetur adipisicing elit.

Se for o caso de apenas esse br não aparecer, então cria uma classe específica de estilo para ele. Como em:

@media (max-width:600px) {
  .chamda1 h2 {}
  .responsive-br {
    display: none
  }
}

Sistemas Próprios Para
 Empresas Autênticas

Lorem
ipsum dolor sit amet,
 consectetur adipisicing elit.

Comment: Já testou isso em diferentes navegadores? Você sabe se funciona no Safari ou no Firefox?
Comment: Testei no Chrome e Firefox
Comment: Parece que não funciona no FireFox? Correto?
Comment: Funcionou em ambos


Do I need to manually remove all event to make my object remove from memory?

Question: I have read in MSDN that is require to Unsubscribing every events an object has to be able to dispose it from memory. I always used -= to remove all references to event inside my object (like MSDN show).
Now, I have to maintain code and it has some memory leak on it. I see that the previous developer simply set the object that has all events subscribes on it to NULL and do not -= every event method.
Example:
<code>_watcher.Changed += new ...
_watcher.Created += new ...
_watcher.Deleted += ..

//later.

_watcher = NULL;
</code>
Is it a good way or does it keeps the variable in memory?
Comment: Possible duplicate - http://stackoverflow.com/questions/345130/do-i-need-to-unsubscribe-from-manually-subscribed-to-events-in-asp-net
Comment: @ChrisF: not exactly. There are talking specially for ASP.NET. This seems to be a more general .NET question.
Comment: I need to know for general use of .net. The problem occur in a Windows Service
Answer: If there are no other references to <code>_watcher</code>, then there is no need to remove the event handlers to avoid a memory leak.
As a matter of habit I tend to explicitly remove event handlers.
Comment: Correct. As long as there's no strong reference to the object itself, the object will be GCed and the event handlers automatically unsubscribed. MSDN isn't very clear on this...
Comment: @Noldorin: yeah, I always have to think twice about it!


select only tr in main table, not nested tables

Question: This question has been asked before, see: jQuery select only tr/td in main table, not nested tables.  however it didn't work as a solution for me.
      $("#tablePartners tr:odd").addClass("odd");
      $("#tablePartners tr:even").hide();
      $("#tablePartners tr:first-child").show();

      $("#tablePartners tr.odd").click(function(){
          $(this).next("tr").toggle();
          $(this).find(".arrow").toggleClass("up");
      });

That code works fine for toggling a row on a table, however, it breaks when I have nested tables in the table:

            Name
            Description
            Address

        Partner Name
        Random description
        1 Random Street

                        Phone
                        0123456789

                        Contact Name
                        Jamie

I've tried doing this to apply the events only to the parent and not nested tables (as suggested in the other question thread), but it didn't work:
  $("#tablePartners>tbody>tr:odd").addClass("odd");
  $("#tablePartners>tbody>tr:even").hide();
  $("#tablePartners>tbody>tr:first-child").show();

  $("#tablePartners>tbody>tr.odd").click(function(){
      $(this).next("tr").toggle();
      $(this).find(".arrow").toggleClass("up");
  });

EDIT: By not working, what I mean is: the toggle event does not work and the odd rows are not hidden. In the first javascript, the toggle worked and the odd rows were hidden but the nest table odd rows were hidden too which I what I don't want.
I think this must be trivial but I've got tunnel vision.
I've put it on jsfiddle: http://jsfiddle.net/9eJ8y/2/
Comment: What do you mean by *but it didn't work*? What did not work?
Comment: My apologies, the toggle event didn't work and the odd rows weren't hidden.
Comment: Moving "didn't work" into a longer sentence isn't necessarily more helpful. Please avoid the phrase entirely.
Answer: The problem is that the first code also selects the header row. Using tbody does not, i.e. you have one row less. You could switch odd and even to create the same effect:
$("#tablePartners > tbody > tr:even").addClass("even");
$("#tablePartners > tbody > tr:odd").hide();
$("#tablePartners > tbody > tr:first-child").show();

$("#tablePartners > tbody > tr.even").click(function(){
  $(this).next("tr").toggle();
  $(this).find(".arrow").toggleClass("up");
});

DEMO
Comment: Excellent! thanks very much! :-) Very prompt response. Have a good day. :-)


Can GWT Properties be used from the server?

Question: I have a GWT app that uses GWT RPC to talk to App Engine servlets. I would like to use constants defined in a .properties file on the server. Is that possible?
Answer: To enable .properties in client you use
GWT.create(file_name.properties);

But this combination don't work on server-side, cause it's only availible on client-side, you'll get this error:
GWT.create() is only usable in client code!  It cannot be called, for example, from server code.

But, I suppose, you can use standard approach of processing .properties files like
Properties props = new Properties();
props.load(new FileInputStream("file_name.properties"));

And use a relative path, not an absolute path. It should work on GAE
Answer: Use the GWT Dictionary class.
Declare you javascript objects in your html hosting file, then use Dictionary to retrieve them anytime after onModuleLoad.
Use JSP to construct your html hosting file - so that you could have a dynamically server generated set of constants. You can have a user-sensitive set of constants. Your servlet/jsp (JSPs are essentially servlets) would be able to read any property file or any database record within its reach on the server to create those constants.
Read this answer: GWT-Platform login + session management.


Speed techniques in fingerstyle guitar

Question: I'm transitioning from playing primarily with a pick, to using just fingers, (no finger or thumb picks either).
I feel this gives me a greater range of tone and better control in most scenarios - however, playing lead lines or faster melodies is noticeably harder.  I tend to pick melodies with just the index finger, using more for harmonies (double and triple stops).
What types of techniques are used to develop speed when finger picking?  Is there anything similar to 'alternate picking' or 'economy picking' with finger style?  Or rather, are there accepted methods and techniques to develop speed?
Answer: Yes - alternate your fingers.
Picking hand fingers are usually indicated with initials for the Spanish names of the fingers, because fingerstyle guitar originated in Spain.  You've got P (pulgar: thumb), I (indice: index), M (medio: middle), and A (anular: the ring finger).
For most passages you use an alternating i-m or m-i fingering.  If the line involves a string skip you might use i-a, a-i, m-a, or a-m to handle those bits.  And rapid notes on the same string can be handled with i-m-a or a-i-m.
It takes a bit of practice.  Any classical guitar method should give you some basic exercises to work with.
Answer: Have a closer look at the players that play solos/melodies exclusively with fingers. Mark Knopfler and Derek Trucks would be good examples.
They both alternate between thumb and index a lot with other fingers joining in when handy.
Mark Knopfler in particular has an interesting technique where he the alternate plucks are more like a snaps where the string sort of gets passed back and forth between thumb and index finger. Have a look at him playing the fast bit of solo from "Sultans of Swing" to see what I mean.
Obviously speed is relative, and it's hard to build up speed using fingers only right up to what's possible with a pick but for some players out there the advantages of more control over the tone, color and articulation will prevail.
Also bear in mind that even though playing a fast notes on a single string might be harder with fingers, many other things are easier. Like changing string really fast, skipping strings ect. so it could be argued that some licks can be actually played faster with only fingers.
For example the way Mark Knopfler plays these little arpeggios - that has a unique sound to it and even though it could be approximated by someone with a very good sweep picking technique, there's not way to make it sound a little "portato" so that there are little pauses between each note.
Answer: As well as the above answers, which talk about standard classical technique, my favourite cheat is to put my thumb and first finger together and use the first finger as a pick.
The usual alternating i & m technique is not fast unless you're very good at it and a pick will always win the race. The above trick is a sort of half-way house but a good tone may be elusive at first. Alternating p & i is very fast if you can master it but I feel it works better on steel strings than nylon because of the tonal difference between p & i.

Speed techniques in fingerstyle guitar