text:
Q: Different definitions of affine subspace
Let $V$ be a finite-dimensional vector space, let $X$ be a set(whose
  elements we will call points) and suppose we have an operation
  $$+:X\times V\to X$$ satisfying these properties:
1) $P+\mathbf{0}=P$ for any $P\in X$.
2) $(P+\mathbf{x})+\mathbf{y}=P+(\mathbf{x}+\mathbf{y})$ for any $P\in
 X$ and $\mathbf{x},\mathbf{y}\in V$.
3) For any two points $P,Q\in X$ there is a unique vector
  $\mathbf{v}\in V$ such that $P+\mathbf{v}=Q$. This vector is usually
  denoted by $\overline{PQ}$.
In this case we call $X$ to be an affine space associated with vector
  space $V$.

Suppose $Y\subset X$ and $W$ is a subspace of $V$. Then we say that $(Y,W$) is an affine subspace of $(X,V)$ if $(Y,W)$ is an affine space under operation defined  on $(X,V)$.
But after some thoughts I have noticed the following: Any affine subspace $Y$ associated with $W$ can be written as a translation $p+W$ for $p\in Y$.
Indeed, let's take any $p\in Y$ and let's show that $Y=p+W$.
Take any element $y\in Y$ then there is a vector $\mathbf{w}\in W$ such that $p+\mathbf{w}=y
$. In other words, $y=p+\mathbf{w}\in p+W$, i.e. $Y\subset p+W$.
Take any $x\in p+W$ then $x=p+\mathbf{w}$ but since $(Y,W)$ is affine subspace then $p+\mathbf{w}\in Y$, i.e. $x\in Y$. It tells us that $p+W\subset Y$.
Hence $Y=p+W$.
Is this proof correct? Would be very thankful for any remarks!

A: Yep, it looks right.
The $Y \subset p + W$ direction leverages condition (3) for the (unique) existence of $\mathbf{w}$. The $p + W \subset Y$ direction uses condition (2) to establish inclusion using the premise that $(Y, W)$ is an affine space.
In fact it is often helpful to intuit affine spaces as shifted linear spaces! Linear spaces must contain the origin $\mathbf{0}$, but affine spaces do not. For instance, this shift is helpful when projecting off-centered data onto off-centered subspaces.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way to schedule payment jobs in Rails I want to schedule API calls to the Braintree API to process transactions x hours after the end date of an event.
I've been using Resque scheduler and Redis to queue up payment jobs for say, 24 hours after an end date.
To my knowledge, if my Redis server or Resque workers ever go offline, all the jobs are wiped, meaning the payment transactions will never go through.
Is this the proper way to handle these payment jobs, or should I instead have cron jobs do a nightly scanthrough of the database and run a payment job for a particular event if it's necessary?
It'd be preferable if payment processing happened at a fixed x amount of time after an event's end date, but running cron jobs nightly is fine too.

A: Why not ensure persistence in Redis? http://redis.io/topics/persistence


text:
Q: Do not replicate items if they exists in a foreach loop My head is clearly not working here. The logic is simple but I can't seem to get it right.
I have a tv schedule post type and I want to display:
2016-12-01
2017-04-01
2017-05-17
Instead of:
2016-12-01
2017-03-01
2017-03-01
2017-03-01
2017-03-01
2017-03-01
At the moment I am stuck with repeating times. I want to only show one time if it already exists as in the first case.
This is my code:
`<?php
$args = array(
    'post_type' => 'tv-schedule',
    'posts_per_page' => -1,
    'orderby' => 'date',
    'order' => 'ASC',
    'post_status' => array('publish', 'future'),
);
$posts_array = query_posts($args);

foreach ($posts_array as $post_array) {
    $date = $post_array->post_date_gmt;
    $new_date = date ('Y-m-01', strtotime($date) );
    echo $new_date . '
';

    /*
    if(!in_array($new_date, $post_array->post_date_gmt)){
        //$a[]=$value;
        echo "test";
    }
    */

}`

A: Just set a flag to check for a new value, and only display the date if the new value does not match the flag, like so:
<?php
$args = array(
    'post_type' => 'tv-schedule',
    'posts_per_page' => -1,
    'orderby' => 'date',
    'order' => 'ASC',
    'post_status' => array('publish', 'future'),
);
$posts_array = query_posts($args);

$flag = ''; // set an initial value that won't match the first date

foreach ($posts_array as $post_array) {
    $date = $post_array->post_date_gmt;
    $new_date = date ('Y-m-01', strtotime($date) );
    if($new_date != $flag) {
        echo $new_date . '
';
        $flag = $new_date; // $flag only changes when we actually display a new date
    }

    /*
    if(!in_array($new_date, $post_array->post_date_gmt)){
        //$a[]=$value;
        echo "test";
    }
    */

}

UPDATE
Changed !== to != so that it would work.

A: I finally got it right... I knew my big head was not working:
<?php
$args = array(
    'post_type' => 'tv-schedule',
    'posts_per_page' => -1,
    'orderby' => 'date',
    'order' => 'ASC',
    'post_status' => array('publish', 'future'),
);
$posts_array = query_posts($args);

$lastdate = "";

foreach ($posts_array as $post_array) {

    $date = $post_array->post_date_gmt;
    $new_date = date ('Y-m-01', strtotime($date) );

    if ($newdate != $lastdate) {
        echo $newdate;
    }

    $lastdate = $newdate;

}
?>


text:
Q: Limiting per-request download AND upload speed on Apache or Nginx I'm currently running a couple of Web servers (one is Apache 2.4 based, another is running nginx 1.8).
I need to set a rate limit, on each individual GET/POST request, that can throttle both download and upload speed.
I've googled around but every solution I've found seems to focus on download rate only, and I can't find a way to set a limit also on data sent from the client to the server in a request body.
I need this because most requests are related to file uploads.
Any suggestion would be greatly appreciated.
Thanks!

A: You can't probably find this information because it's not generally needed; your case is just too rare.
Downloads can be of any size, even extremely huge, and rate limiting will allow equitable distribution of network capacity between the users: one huge download can't cause slowing down on typical browsing etc.
HTTP uploads, however, are normally limited in size and they may reserve memory during the upload, that can only be released when the upload is over and the file can be saved. Therefore, I'd suggest limiting the amount of concurrent uploads instead, as I would want a single upload to be over as soon as possible.
Besides, the upload speed in most cases is already limited by an asynchronous Internet connection, so your users would suffer from a bad user experience if you'd limit it even further.


text:
Q: SQL - Tuple as Primary Key How would you create a primary key out of a tuple from a table?
Example -
table a: [id|name]
table b: [id|name]
table axb:[a_id|b_id]

Now we want to add a primary key to axb so that the tuple {alpha, beta} is unique. In other words, the table can't contain the rows (alpha, beta) and (beta, alpha). This would extend to ntuples but I'm asking about couples to start to keep this simple.
I'm working with MySql 14.14/5.5.50 - but I'm hoping that doesn't matter.
Note that a composite key doesn't solve this as a composite key on a_id/b_id would still allow the row with inverse tuple order as a new row

A: Unfortunately, you need to use a trigger to do this in MySQL.  Many databases would support a syntax such as:
create unique index unq_t_alpha_beta on (least(alpha, beta), greatest(alpha, beta));

Although the syntax might be different, indexes on expressions or computed columns solve this problem.
Another method is to require that alpha < beta (using a check constraint) and then build a unique index on (alpha, beta).
But, MySQL supports none of the following:

*

*check constraints

*indexes on expressions

*computed columns

So, that leaves triggers.

A: Just throwing it out there: could you use a generated column which combines the columns always in order (so alpha, beta = alphabeta and beta, alpha = alphabeta), then create a unique index on that generated column? MySql isnt my bag but this says it should be possible: https://dev.mysql.com/doc/refman/5.7/en/create-table-secondary-indexes.html


text:
Q: TFS/TFVC merge selected changeset vs git cherry-pick between branches We will be migrating our TFS/TFVC repository to Git.
In TFVC we used to have a trunk based development with long lasting release maintenance branches.
Bug fixes on release branches have to be merged back to the trunk.
Sometimes smaller features have to be carried over from trunk to a release branch.
In TFVC we did this by "merging" individual (or small groups of) changesets from one branch to the other.
The resulting changesets were marked as "merge", although I don't exactly know what that implies for TFVC, especially considering future merge operations.
So I imagine the branch graph to look something like this:
(Although note that TFVC never displays any graphs)
-A--B--C---D--E--F---    trunk
  \       /    \
   G--H--I--J---K--L-    release-x

(Here the release branch has been created from A, I->D is a bugfix merge, E->K is a feature-forward)
But maybe I'm wrong. In this case could someone explain what a TFVC merge changeset really does?
I've been told that an equivalent way of doing in Git is cherry-picking individual commits.
However, on the resulting branch graphs, I don't see any link between the branches following a cherry-pick commit.
I am aware that cherry-picking is not technically a merge operation and thus history relation between the branches is not carried over.
Is there something I am missing? Is there a better way of carrying over such small commits from one branch to another, yet still retain some merge information?
I DO NOT want to merge the entire branch. As for example changesets B,C or H must remain isolated from each other branch.

A: When Cherry picking you can add the -x option to have git add a message to the commit-message of each cherry-picked commit:

-x
When recording the commit, append a line that says "(cherry picked from commit …)" to the original commit message in order to indicate which commit this change was cherry-picked from. This is done only for cherry picks without conflicts. Do not use this option if you are cherry-picking from your private branch because the information is useless to the recipient. If on the other hand you are cherry-picking between two publicly visible branches (e.g. backporting a fix to a maintenance branch for an older release from a development branch), adding this information can be useful.

This is the closest you'll get. A cherry picked commit it recorded as a new commit on the target branch, not as a reverse or forward integration.
Git doesn't do "partial merges" since git stores the status of the worktree as a "version". TFVC stores the workspace versions of individual files instead.
What you're seeing are 2 very different things.
In TFVC you see a branch graph that is clearly defined through branch objects that have a defined parent branch. Each integration between those branches is visualized, since the merge stores which files were merged, which changesets were part of that merge and over which branch relationship these were merged. A changeset in TFVC (closest thing to a commit in git) is also a very different thing. For one, a changeset can span multiple branches, even repositories, and a changeset contains 1 or more changes to files.
In Git a branch is just a special pointer to a commit somewhere in the commit graph. Parentage is calculated (based on the commit graph) and branches can freely merge without respecting a preconfigured hierarchy. The visualization shows the relationships between commits, not branches. A special type of commit, the merge, stores when a new commit was created from the basis of 2 or more other commits. The relation to these commits is stored, not the names of the branches that happened to point to these commits. A Commit stores the changes to the worktree. One or more branches may point to that commit.
Since a cherry-pick replays the changes on one branch in the commit tree onto another, it's not recorded as a merge where multiple sets of commits are linked together. Instead, it's recorded as a new commit that happens to have the same diff (and potentially not even that if you needed to do conflict resolution).
By adding the -x flag the relationship is stored in the comments.


text:
Q: Excel cell size limitation-causing macro to fail I am developing macro in which i am expecting string such as (present in text file):
QUALAPP@QUALAPPC@GENRESOUS@NOMAPP@NOMAGENCE@PRENOMAPP@ADR1APP@ADR2APP~
ADR3APP@ADR4APP@VILLEAPP@CPAPP@PAYSAPP@TELAPP@NUMCONTRAT@DATEEFFCTR~

in which each field is delimited by @ and each record is delimited by ~ to be in tabular format.
Such as each field will be in consecutive cell and new record start in new row.
I have macro which currently requires copying data in one cell. But as string size increases beyond some limit I am unable to paste it. So, please provide other easy option.

A: If the size of the string exceeds the capacitiy of a single cell, then read the data in one character at a time and parse the data into fields as you go.

A: Assign the string to a variable (let's call it "my_var") and then
arr_1 = Split(my_var, "~", -1, vbTextCompare)

For x = LBound(arr_1,1) to UBound(arr_1,1)
  activecell = arr_1(x)
  activecell.offset(1,0).select
Next

this creates an array and each element is one of your records; it then places each record in a new row.  You could then go back through and split each row based on "@" and place the split data in adjacent columns.


text:
Q: Computing the binomial coefficient in C I found the following code for computing nCr, but don't understand the logic behind it. Why does this code work?
long long combi(int n,int k)
{
    long long ans=1;
    k=k>n-k?n-k:k;
    int j=1;
    for(;j<=k;j++,n--)
    {
        if(n%j==0)
        {
            ans*=n/j;
        }else
        if(ans%j==0)
        {
            ans=ans/j*n;
        }else
        {
            ans=(ans*n)/j;
        }
    }
    return ans;
}

A: that's a clever code!
In general it aims to calculate the following formula:
ans = n! / (k!)(n-k)!

It is equal to:
ans = n(n-1)(n-2) ... (n-k)...1 / k(k-1)...1 * (n-k)(n-k-1) ... 1

And after obvious cancellation:
ans = n(n-1)(n-2)..(n-k+1) / k!

Now notice that nominator and denominator have the same number of elements (k element)
So the calculation of ans will be like the following:
ans  = 1 // initially
ans *= n/1
ans *= (n-1)/2
ans *= (n-2)/3
.
.
.
ans *=  (n-k+1)/k

take a look again at the code and you notice that:

*

*ans is being multiplied by n at each iteration

*n is reduced by 1 at each iteration (n--)

*ans is divided by j at each iteration

This is exactly what is done by the posted code, Now let's see the meanings of different conditions in the loop, with nominator starting from n and denominator from 1 to k, so variable j is assigned to denominator right?
1) if(n%j==0)
at each step if n/j is (computable) So we calculate it first here than multiply to the whole ans, this practice keeps the result at its smallest possible value.
2) else if(ans%j==0)
at each step if we couldn't calculate n/j but actually can calculate ans/j so that's not bad to say :
ans /= j; //first we divide
ans *= n; //then we multiply

This is always keeping our overall output as small as possible, right?
3) last condition
at each step, if we couldn't compute neither n/j nor ans/j in this case we are not lucky enough to divide first then multiply (hence keeping the result small). But well we need to carry on even-though we are left with only one choice which is
ans *= n; // multiply first
ans /= j; // then divide

ET VOILA!
Example
consider the case 3C7
we know that the answer is 7!/ 3!*4!
hence : ans = 7*6*5 / 1*2*3
let's see what happen at each iteration:
//1
ans = 1

//2
n = 7
j = 1
ans = ans * n/j
first compute 7/1 = 7
then multiply to ans
ans = 1*7
ans = 7

//3
n = 6
j = 2
ans = ans* n/j

evaluate n/j = 6/2 (can be divided)
         n/j = 3
ans = ans *(n/j)
    = 7 * 3
    = 21

// 4
n = 5
j = 3

ans = ans * n/j
evaluate n/j = 5/3 oppsss!! (first if)
evaluate ans/j = 21/3 = 7 YES (second if)

ans = (ans/j)*n
    = 7*5
    = 35

// end iterations

Note that in last iteration if we calculate straight forward we would say:
ans = ans*n/j
    = 21 * 5 / 3
    = 105 / 3
    = 34

yes it does find right result but meanwhile the value flies up to 105 before getting back to 35. Now imagine calculating real large numbers?!
Conclusion
This code is computing carefully the binomial coefficients trying to keep the output as small as possible at each step of calculation, it does that by checking if it is possible to divide (int) then execute, hence it is capable of calculating some very big kCn that the straightforward coding cannot handle (OverFlow may occur)

A: To answer the question in part, consider the fact that the entries of n choose k constitute Pascal's triangle. As Pascal's triangle is symmetric, it is sufficient to move the argument k into the left half, which is done with the
k=k>n-k?n-k:k;
statement; see the definition of C's conditional operator.
Furthermore, the result ans is initialized in the beginning to contain 1, which is the first entry of every row in Pascal's triangle, which means that initially, ans is in fact n choose j.

A: The fact is that nCr for 1<=k<=n/2 is same as in n/2+1<=k<=n.so first change in k so that it values lies value in the left half.One more thing nCk means (n*(n-1).....(n-k))/(k*(k-1)*....*2*1) so the above code apply it iteratively.

A: yes.
[N choose K] reduces its factorials a lot because the dividend and divisor share many factors that cancel each other out to x/x=1 (for x>0)
the trick is to not calculate the large factorials, because these large factors require too much address space (too many bits)
the first trick is to reduce the fraction, before dividing.
the second trick is to do modulo within a conditional to chose one of 3 operations for the current iteration. this can be done differently, and integer modulo is chosen to be a fast operator, skipping some slower integer division approaches.
you iteratively traverse pascals triangle.
with each path that you take, you multiply something.
There are 3 possible branching paths for every iterative step:
each of the 3 steps multiplies the accumulator "ans" with a different value, representing the factor between 2 "positions" on pascals triangle.
you always end up doing N multiplications, where N is the number of iterations, and end up at the binomial coefficient's value.
N is the column # of pascals triangle that you want to know, and you accumulate an N, multiplied by something, while reducing the number of column s (and lines) of pascals triangle by N=N-1 for each iteration.
j=1;
ans=0;
//within each iteration;
ans=ans*n;

n=n-1;

ans=ans/j;

j=n+1;

the integer division is slow and can be skipped (or made faster by making the divisor smaller) at least once, and often many more times (because there are a lot of shared prime factors in pascals triangle), this is being done by the modulo conditionals.
pascals triangle is extremely symmetric (on summing up its domains), therefore this works.
the difference between (partial) sums of columns of pascals triangle shows the symmetry that is important for the multiplications and divisions here.
just watch some youtube videos on the symmetries and identities of pascals triangle.


text:
Q: Understanding Components Learning Aframe / Javascript at the same time.
Attempting to write my own component that changes the radius of an object to 2 on click but if if the radius of the object is already 2 then it should decrease the radius to 1.
How would I reference the sphere object that I am trying to alter the radius of in the component.
Thanks
Here is my component logic.
AFRAME.registerComponent('change-radius', {

schema: {
    radius: {type: 'int'}
},

init: function(){
    var data = this.data;
    this.el.addEventListener('click',

    function(){
        if (data.radius === 1) {
            this.setAttribute('radius', data.radius);
            console.log('THIS ONE');
        } else {
            this.setAttribute('radius', 1);
            console.log('NO !!!! THIS ONE');
        }
    })
}
});

Here is my sphere code.
<a-sphere id="sphere" change-radius="radius: 2" change-color="color: #0000FF" color="#F44336" radius="1" position="0 2 -4"></a-sphere>

A: Accessing the sphere object from the component is a matter of scope.
- For the attached component, this.el is the sphere element.
- Inside the this.el.addEventListener();, this refers to the sphere element, as the listeners function scope is this.el. If it was defined elsewhere, You could bind it ( in order to keep the this scope), or call it from the listener
- Otherwise You would need to make a let el = this.el reference, in order to access the element at Your convinience
Of course You can get any object using document.querySelector('cssSelector)

I would suggest making a boolean switch checking if the sphere is enlarged or not, then set the radius and the boolean accordingly:

init: function(){
  var data = this.data;
  let el = this.el;
  let enlarged = false;
  this.el.addEventListener('click',function(){
    //BOOL SWITCH
    if(!enlarged){
      data.radius = 2;
    } else {
      data.radius = 1;
    }
    // STATE CHANGE, AND RADIUS CHANGE
    enlarged != enlarged;
    el.setAttribute('radius',data.radius);
    }
  })
}

Imo it's better than actual radius checking, for It's way faster to get a boolean state, than checking the object's properties.
You could just check if data.radius == 1, and then change the radius accordingly, may be shorter, but It's up to You


text:
Q: Memory quota exceeded error when deploying .WAR file on Heroku - SpringMVC I am trying to deploy a SpringMVC Java project on Heroku, using Tomcat. The application is a small one, but I get the following error when I try to deploy the .war file:
2013-01-07T12:21:53+00:00 heroku[web.1]: Starting process with command `${PRE_JAVA}java ${JAVA_OPTS} -jar webapp-runner-7.0.29.3.jar --port ${PORT} ${WEBAPP_RUNNER_OPTS} web-movie-collector-1.0.0-BUILD-SNAPSHOT.war`
2013-01-07T12:21:54+00:00 app[web.1]: Adding Context / for web-movie-collector-1.0.0-BUILD-SNAPSHOT.war
2013-01-07T12:21:56+00:00 app[web.1]: Jan 7, 2013 12:21:56 PM org.apache.coyote.AbstractProtocol init
2013-01-07T12:21:56+00:00 app[web.1]: INFO: Initializing ProtocolHandler ["http-nio-21063"]
2013-01-07T12:21:56+00:00 heroku[web.1]: Error R11 (Bad bind) -> Process bound to port 45464, should be 21063 (see environment variable PORT)
2013-01-07T12:21:56+00:00 heroku[web.1]: Stopping process with SIGKILL
2013-01-07T12:21:58+00:00 heroku[web.1]: Process exited with status 137
2013-01-07T12:21:58+00:00 heroku[web.1]: State changed from starting to crashed
2013-01-07T12:21:58+00:00 heroku[web.1]: State changed from crashed to starting
2013-01-07T12:22:00+00:00 heroku[web.1]: Starting process with command `${PRE_JAVA}java ${JAVA_OPTS} -jar webapp-runner-7.0.29.3.jar --port ${PORT} ${WEBAPP_RUNNER_OPTS} web-movie-collector-1.0.0-BUILD-SNAPSHOT.war`
2013-01-07T12:22:01+00:00 app[web.1]: Adding Context / for web-movie-collector-1.0.0-BUILD-SNAPSHOT.war
2013-01-07T12:22:01+00:00 app[web.1]: Jan 7, 2013 12:22:01 PM org.apache.coyote.AbstractProtocol init
2013-01-07T12:22:01+00:00 app[web.1]: INFO: Initializing ProtocolHandler ["http-nio-41469"]
2013-01-07T12:22:01+00:00 app[web.1]: Jan 7, 2013 12:22:01 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
2013-01-07T12:22:01+00:00 app[web.1]: INFO: Using a shared selector for servlet write/read
2013-01-07T12:22:01+00:00 app[web.1]: Jan 7, 2013 12:22:01 PM org.apache.catalina.core.StandardService startInternal
2013-01-07T12:22:01+00:00 app[web.1]: INFO: Starting service Tomcat
2013-01-07T12:22:01+00:00 app[web.1]: Jan 7, 2013 12:22:01 PM org.apache.catalina.core.StandardEngine startInternal
2013-01-07T12:22:01+00:00 app[web.1]: INFO: Starting Servlet Engine: Apache Tomcat/7.0.29
2013-01-07T12:22:01+00:00 heroku[web.1]: State changed from starting to up
2013-01-07T12:22:02+00:00 app[web.1]: Jan 7, 2013 12:22:02 PM org.apache.catalina.startup.ContextConfig getDefaultWebXmlFragment
2013-01-07T12:22:02+00:00 app[web.1]: INFO: No global web.xml found
2013-01-07T12:22:28+00:00 heroku[web.1]: Process running mem=745M(145.6%)
2013-01-07T12:22:28+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2013-01-07T12:22:50+00:00 heroku[web.1]: Process running mem=769M(150.4%)
2013-01-07T12:22:50+00:00 heroku[web.1]: **Error R14 (Memory quota exceeded)**
2013-01-07T12:22:57+00:00 heroku[router]: at=error code=H12 desc="Request timeout" method=GET path=/ host=web-movie-collector-new.herokuapp.com fwd=91.208.120.254 dyno=web.1 queue=0ms wait=0ms connect=2ms service=30000ms status=503 bytes=0
**2013-01-07T12:23:12+00:00 heroku[web.1]: Process running mem=793M(155.1%)
2013-01-07T12:23:12+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)
2013-01-07T12:23:34+00:00 heroku[web.1]: Process running mem=761M(148.8%)
2013-01-07T12:23:34+00:00 heroku[web.1]: Error R14 (Memory quota exceeded)**
2013-01-07T12:23:37+00:00 app[web.1]: Jan 7, 2013 12:23:37 PM org.apache.catalina.core.ApplicationContext log
2013-01-07T12:23:37+00:00 app[web.1]: INFO: No Spring WebApplicationInitializer types detected on classpath
2013-01-07T12:23:37+00:00 app[web.1]: Jan 7, 2013 12:23:37 PM org.apache.catalina.core.ApplicationContext log
2013-01-07T12:23:37+00:00 app[web.1]: INFO: Initializing Spring root WebApplicationContext
2013-01-07T12:23:37+00:00 app[web.1]: INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
2013-01-07T12:23:38+00:00 app[web.1]: INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Mon Jan 07 12:23:38 UTC 2013]; root of context hierarchy
2013-01-07T12:23:38+00:00 app[web.1]: INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
2013-01-07T12:23:38+00:00 app[web.1]: INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7458e2a1: defining beans [infoSourceConfigLoader,htmlNodePathMapper]; root of factory hierarchy
2013-01-07T12:23:39+00:00 app[web.1]: INFO : org.springframework.beans.factory.config.PropertiesFactoryBean - Loading properties file from class path resource [xpath.properties]
2013-01-07T12:23:39+00:00 app[web.1]: INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 2062 ms
2013-01-07T12:23:39+00:00 app[web.1]: null
2013-01-07T12:23:39+00:00 app[web.1]: Jan 7, 2013 12:23:39 PM org.apache.catalina.core.StandardContext listenerStart
2013-01-07T12:23:39+00:00 app[web.1]: SEVERE: Exception sending context initialized event to listener instance of class ro.isdc.LanguageLoaderListener
2013-01-07T12:23:39+00:00 app[web.1]: java.lang.NullPointerException
2013-01-07T12:23:39+00:00 app[web.1]:   at java.io.File.<init>(File.java:239)
2013-01-07T12:23:39+00:00 app[web.1]:   at ro.isdc.controllers.LocaleAwareController.loadSupportedLanguages(LocaleAwareController.java:40)
2013-01-07T12:23:39+00:00 app[web.1]:   at ro.isdc.LanguageLoaderListener.contextInitialized(LanguageLoaderListener.java:15)
2013-01-07T12:23:39+00:00 app[web.1]:   at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
2013-01-07T12:23:39+00:00 app[web.1]:   at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
2013-01-07T12:23:39+00:00 app[web.1]:   at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
2013-01-07T12:23:39+00:00 app[web.1]:   at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
2013-01-07T12:23:39+00:00 app[web.1]:   at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
2013-01-07T12:23:39+00:00 app[web.1]:   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
2013-01-07T12:23:39+00:00 app[web.1]:   at java.util.concurrent.FutureTask.run(FutureTask.java:166)
2013-01-07T12:23:39+00:00 app[web.1]:   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
2013-01-07T12:23:39+00:00 app[web.1]:   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
2013-01-07T12:23:39+00:00 app[web.1]:   at java.lang.Thread.run(Thread.java:636)
2013-01-07T12:23:39+00:00 app[web.1]: Jan 7, 2013 12:23:39 PM org.apache.catalina.core.StandardContext startInternal
2013-01-07T12:23:39+00:00 app[web.1]: SEVERE: Error listenerStart
2013-01-07T12:23:39+00:00 app[web.1]: Jan 7, 2013 12:23:39 PM org.apache.catalina.core.StandardContext startInternal
2013-01-07T12:23:39+00:00 app[web.1]: SEVERE: Context [/] startup failed due to previous errors
2013-01-07T12:23:39+00:00 app[web.1]: SEVERE: Context [/] failed in [org.apache.catalina.core.StandardContext] lifecycle. Allowing Tomcat to shutdown.
2013-01-07T12:23:39+00:00 app[web.1]: Jan 7, 2013 12:23:39 PM org.apache.catalina.core.ApplicationContext log
2013-01-07T12:23:39+00:00 app[web.1]: INFO: Closing Spring root WebApplicationContext
2013-01-07T12:23:39+00:00 app[web.1]: INFO : org.springframework.web.context.support.XmlWebApplicationContext - Closing Root WebApplicationContext: startup date [Mon Jan 07 12:23:38 UTC 2013]; root of context hierarchy
2013-01-07T12:23:39+00:00 app[web.1]: INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@7458e2a1: defining beans [infoSourceConfigLoader,htmlNodePathMapper]; root of factory hierarchy
2013-01-07T12:23:40+00:00 app[web.1]: Jan 7, 2013 12:23:40 PM org.apache.coyote.AbstractProtocol start
2013-01-07T12:23:40+00:00 app[web.1]: INFO: Starting ProtocolHandler ["http-nio-41469"]
2013-01-07T12:23:42+00:00 heroku[web.1]: Process exited with status 0
2013-01-07T12:23:42+00:00 heroku[web.1]: State changed from up to crashed
2013-01-07T12:23:59+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path=/ host=web-movie-collector-new.herokuapp.com fwd=91.208.120.254 dyno= queue= wait= connect= service= status=503 bytes=

How can I solve this or what may cause the problem?

A: Did you notice the large NullPointerException in your log, you should look at this, I think this is the reason, the startup doesn't work.
According to Heroku Troubleshooting Memory Issues in Java Applications it is ok for your application to use more than 512MB memory on Heroku, but it will be swapped to disk, causing performance problems.

A: Look at
ro.isdc.controllers.LocaleAwareController.loadSupportedLanguages(LocaleAwareController.java:40)

It is passing null in java.io.File.


text:
Q: Proof of existence of Levi-Civita connection via the Koszul Formula I'm currently self-studying the basic concepts of Riemannian Manifolds, and I'm stuck on the proof of the existence of the Levi-Civita connection that is presented in the book "Semi-Riemannian Geometry" by O'Neill, which is a coordinate-free approach.
Suppose $(M,g)$ is a Riemannian manifold, and let $\nabla:\mathfrak{X}(M)\times\mathfrak{X}(M)\to\mathfrak{X}(M)$ be a connection. So far, I've been able to prove that, if $\nabla$ verifies the conditions of the Levi-Civita connection, then it must satisfy the Koszul Formula:
$
\langle\nabla_{X}Y,Z\rangle=\dfrac{1}{2}(X\langle Y, Z\rangle+Y\langle Z, X\rangle-Z\langle X, Y\rangle
-\langle Y,[X, Z]\rangle-\langle Z,[Y, X]\rangle+\langle X,[Z, Y]\rangle).
$
So now, I'm trying to prove existence by using the formula: more precisely, with this result that I proved previously:

If $\omega:\mathfrak{X}(M)\to \mathcal{F}(M)$ is a differential $1$-form, then there exists a unique vector field $V$ such that for any other vector field $X$, we have $\omega(X)=\langle V,X\rangle$.

My reasoning is the following: fix two vector fields $X,Y$, and let $\omega_{X,Y}:\mathfrak{X}(M)\to \mathcal{F}(M)$ be the map
$\omega_{X,Y}(Z)=\dfrac{1}{2}(X\langle Y, Z\rangle+Y\langle Z, X\rangle-Z\langle X, Y\rangle
-\langle Y,[X, Z]\rangle-\langle Z,[Y, X]\rangle+\langle X,[Z, Y]\rangle).$
If I were able to prove that $\omega_{X,Y}$ is $\mathcal{F}(M)$-linear (which, knowing the Theorem to be true, it must be), then by using the preceding result I can define a unique vector field $\nabla_{X}Y$ such that $\omega_{X,Y}(Z)=\langle \nabla_{X}Y,Z \rangle$. Thus, I would have a well defined map $\nabla$ satisfying the Koszul Formula, and it would be (after some property checking) the Levi-Civita connection.
The problem is that, while it's easy to see that $\omega_{X,Y}(Z_{1}+Z_{2})=\omega_{X,Y}(Z_{1})+\omega_{X,Y}(Z_{2})$, I haven't been able to prove that $\omega_{X,Y}(fZ)=f\omega_{X,Y}(Z)$. In reality, what I've gotten is that
$\omega_{X,Y}(fZ)=f\omega_{X,Y}(Z)-\dfrac{1}{2}\langle (Xf)Y+(Yf)X,Z \rangle$,
but I'm not sure that the second summand is $0$. Is my attempt correct so far, or am I missing something?
Thank you in advance!

A: Just checked and $\omega_{X,Y}$ is in fact $C^\infty$ linear. It seems like the terms you picked up were from the 4th and 6th term, the first and second terms also give extra terms:
$$X(\langle Y,fZ\rangle ) = X(f\langle Y,Z\rangle) =X(f)\langle Y,Z \rangle + fX(\langle Y,Z\rangle)$$
Similarly for the second term, these will exactly cancel the other two terms that you found.
Also this is cool because thats the first time I've seen this being proven coordinate free!


text:
Q: how to make removable media private How might it be possible to rig a system such that some removable media, like a USB stick, can be mounted by a user without any need for root privileges, and yet be made private for that user? I'm thinking of some multiuser situation, like a school or library, where there are many terminals. I sit down at a terminal, plug in my USB stick, mount it, without needing any privileges, have full access to it, and yet it is completely private to me. I know I can gain privacy my mounting the stick in my home directory, but I'd need root privileges to make the mount.  In fstab I can use the 'user,noauto' option, which lets me, or anyone else,  mount, OTOH, then, once mounted, the sick is visible to anyone. Is there some way of making the device itself private? chmod'ing the contents is not sufficient since other users can still do things like write new files. I think this should be doable but I'm damned if I can figure it out.

A: This issue does not lie in the removable media, but rather in the filesystem. The FAT filesystem does not support individual access control.
You can solve your problem by defining default access rights in your fstab. From the manpage:
   umask=value
          Set the umask (the bitmask of  the  permissions  that  are  not
          present). The default is the umask of the current process.  The
          value is given in octal.

   dmask=value
          Set the umask applied to directories only.  The default is  the
          umask of the current process.  The value is given in octal.

   fmask=value
          Set  the  umask  applied to regular files only.  The default is
          the umask of the current process.  The value is given in octal.

So, e.g. "user,noauto,umask=077" should take all rights away from anybody else then the user performing the mount. Note that this is already the default dmask on most systems! Maybe something is wrong with your setup.


text:
Q: In which situation are those Facebook IOS FBSessionDelegate methods called? It's clear to me that these are called upon login if a user grants or denials permission:
- (void)fbDidLogin;
- (void)fbDidNotLogin:(BOOL)cancelled;

But i was wondering when the following FBSessionDelegate methods could be called:
- (void)fbDidExtendToken:(NSString*)accessToken expiresAt:(NSDate*)expiresAt;
- (void)fbDidLogout;
- (void)fbSessionInvalidated;

The documentation says:
//Called after the access token was extended.
- (void)fbDidExtendToken:(NSString*)accessToken expiresAt:(NSDate*)expiresAt;

//Called when the user logged out.
- (void)fbDidLogout;

//Called when the current session has expired.
- (void)fbSessionInvalidated;

Now when would such a thing happen? When i call the following?
[Facebook authorize:nil];

There is no chance i will get a fbDidLogout call back right?
Maybe if a user removes my app from his Facebook account via the Facebook app, would this method be called than? No, because my app doesn't open in that case..
...so in which situation would these be called?

A: I think i found it myself...
This one:
- (void)fbDidExtendToken:(NSString*)accessToken expiresAt:(NSDate*)expiresAt;

Could be called when you call:
[facebook extendAccessTokenIfNeeded];

This one:
- (void) fbDidLogout;

Gets called when you call
[facebook logout] //(of course..)

The last one:
- (void)fbSessionInvalidated;

Get's called when you try to send a http request to Facebook with an expired session token.
I found it in the Facebook SDK header file Facebook.m
I'll leave the question here for anyone looking for the answer :)


text:
Q: force automake and autoconf to set the -lz flag behind the compilation line, and do it without changing the .ac files I am having some source package whose developer is comfortably using an ancient GCC version, where compilation requires the -lz flags before the object specs. The package is very "branchy" and the automake and autoconf very "stuffy" so I have two questions:
First question is how to configure my autotools to set the -lz flag behind?
Second, is it possible to force setting at back of this -lz flag without messing with the makefile.ac and configure.ac files? Since this is not my software package always editing these files whenever I am doing a new build is simply not an option.
Note that if I copy the compilation line that throws the error and just put the -lz and -lxerces-c flags at the end then it works. So I have to somehow change this in autotools.
UPDATE:
Well I managed to somehow fix it by running the badly configured line with
$ g++ line_contents -lz -lxerces-c
(making sure to be in the right directory)
And then I just had the idea of running make again, it seemed that automake considered that step passed and just went forward.
Still, it would be nice to find an answer on how to change the order with the autotools!

A: You can write your own "gcc" for that task.
Python or bash script that check if one of arguments is -lz,
and reoder them and then call real gcc.
After that just run CC=path/to/your/gcc ./configure and all stuff should work.


text:
Q: How to write and split a datatable on different pages using itextsharp? first at all, here is my code:
                    string pdfTemplate = Application.StartupPath + "\\Templates\\Template Medico.pdf";
                    string newFile = Application.StartupPath + "\\Relatórios\\Relatório Médico_" + dataArquivo + ".pdf";

                    PdfReader pdfReader = new PdfReader(pdfTemplate);
                    PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));

                    AcroFields pdfFormFields = pdfStamper.AcroFields;

                    // Form Filling
                    pdfFormFields.SetField("data", data);
                    pdfFormFields.SetField("medico_nome", campo);
                    pdfFormFields.SetField("numero_consultas", numeroConsultas);

                    // Table Building
                    int numColumns = ds.Tables[0].Columns.Count;
                    PdfPTable datatable = new PdfPTable(numColumns);
                    datatable.DefaultCell.Padding = 10;
                    datatable.WidthPercentage = 100;
                    datatable.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
                    float[] columnWidths = { 80, 80, 80, 80, 80, 80, 80, 80, 80 };
                    datatable.SetWidths(columnWidths);
                    float[] totalWidth = { 80, 80, 80, 80, 80, 80, 80, 80, 80 };
                    datatable.SetTotalWidth(totalWidth);

                    // Table Header
                    for (int k = 0; k < ds.Tables[0].Columns.Count; k++)
                    {
                        Phrase collumname = new Phrase(ds.Tables[0].Columns[k].ColumnName, FontFactory.GetFont("Verdana", 9));
                        datatable.AddCell(collumname);
                    }
                    // Lines and Columns
                    if (ds.Tables[0].Rows.Count <= 9) // less than 9 rows = no problem, no new pages and table spliting needed
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                            {
                                datatable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
                                datatable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
                                Phrase phrase = new Phrase(ds.Tables[0].Rows[i][j].ToString(), FontFactory.GetFont("Verdana", 9));
                                datatable.AddCell(phrase);
                            }
                        }
                        // Write down the table on page 2
                        PdfContentByte content = pdfStamper.GetUnderContent(2);
                        datatable.WriteSelectedRows(0, -1, 70.0f, 495.0f, content);
                    }
                    else
                    {
                        int newPage = 3;
                        int currentPage = 2;
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                            {
                                datatable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
                                datatable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
                                Phrase phrase = new Phrase(ds.Tables[0].Rows[i][j].ToString(), FontFactory.GetFont("Verdana", 9));
                                datatable.AddCell(phrase);
                            }
                            if (i > 0 && i % 9 == 0)
                            {   //How do i print the table ONLY every 9 iterations? (9 iterations = 9 rows)
                                PdfContentByte content = pdfStamper.GetUnderContent(currentPage);
                                // Or how do i make a loop using the rowStart and rowEnd arguments of the
                                // WriteSelectedRows function in order to write only a set of 9 rows for each page?
                                datatable.WriteSelectedRows(0, -1, 70.0f, 495.0f, content);
                                pdfStamper.InsertPage(newPage, pdfReader.GetPageSize(2));
                                newPage++;
                                currentPage++;
                            }
                        }
                    }

The code is well commented with the main issues i'm having at the moment, but the real bigger one, as described on the thread title is to somehow "split" or "control" the loop/iteration through the rows and columns to match the page, jump to the other page, and keep writing the table.
Any help will be apreciated.

A: Did it guys, took me 2 days and lots of cooffe but i did it, here is the code:
                else
                {
                    int newPageNumber = 3;
                    int currentPage = 2;
                    int lastLinePrinted = 0;
                    int maxLine = 9;
                    bool lastPage = false;
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        for (int j = 0; j < ds.Tables[0].Columns.Count; j++)
                        {
                            datatable.DefaultCell.BackgroundColor = iTextSharp.text.BaseColor.WHITE;
                            datatable.DefaultCell.HorizontalAlignment = iTextSharp.text.Element.ALIGN_LEFT;
                            Phrase phrase = new Phrase(ds.Tables[0].Rows[i][j].ToString(), FontFactory.GetFont("Verdana", 9));
                            datatable.AddCell(phrase);
                        }
                        // must decrement the ds.Tables[0].Rows.Count here,
                        // otherwise it'll never enter the code below, we'll
                        // increment it back when we reach the last page
                        if ((i > 0 && i % 9 == 0) || i == ds.Tables[0].Rows.Count - 1)
                        {
                            PdfContentByte content = pdfStamper.GetUnderContent(currentPage);
                            datatable.WriteSelectedRows(lastLinePrinted, maxLine, 70.0f, 495.0f, content);
                            if (!lastPage)
                            {
                                pdfStamper.InsertPage(newPage, pdfReader.GetPageSize(2));
                                newPage++;
                                currentPage++;
                                lastLinePrinted = maxLine;
                                maxLine += 9;
                            }
                            if (maxLine > ds.Tables[0].Rows.Count)
                            {
                                maxLine = ds.Tables[0].Rows.Count+1;
                                lastPage = true;
                            }
                        }
                    }
                }

Hope it helps a lot more people :D

A: You can do it easier by fully using WriteSelectedRows
int pageRows=0;
while (pageRows<datatable.Rows.Count+8)
      {
         content.BeginText();
         table.WriteSelectedRows(pageRows, pageRows+9, 20, 550, cb);
         pageRows = pageRows + 9;
         content.EndText();
         document.NewPage();
       }

You write 9 rows at a time, and then you call for a new page.


text:
Q: assign three values based on condition to pandas df column I have a pandas df that contains a column of positive, negative nos and zeros. I wanted to crate another column which is 1 if no is > 0, -1 if no is < 0 and 0 if the number is 0.
I am trying to do this using a for loop for each row but it is taking too long. I wanted to know if there was a faster way to do this. I also wanted to know if the same logic could be extended to positive and negative timedelta objects.
Thank you.
My final df should look like this:
df = pd.DataFrame({'a':[1, 2, -1, 0, -2], 'b':[1, 1, -1, 0, -1]})

     a   b
0    1   1
1    2   1
2   -1  -1
3    0   0
4   -2  -1

where b is the col to assign based on values of a

A: Here is one way numpy sign
np.sign(df.a)
Out[118]:
0    1
1    1
2   -1
3    0
4   -1
Name: a, dtype: int64
df['b'] = np.sign(df.a)

A: try using np.where and provide conditions
import numpy as np

df['b']= np.where(df['a']>0,1,
         np.where(df['a']<0,-1,0))

     a   b
0    1   1
1    2   1
2   -1  -1
3    0   0
4   -2  -1

Solution by  @rafaelc
m1= df['a'] >0
m2= df['a'] <0

df['b'] = np.select([m1, m2],
                    [ 1, -1],
                    default=0)


text:
Q: How can i make the lose label to appear once the timer hits zero? I'm a beginner in coding and I need help in the following code. I'm trying to make the "You Lose!" label appear after the timer hits zero, but when I try to do it; it doesn't show anything. Please help me!
class Game: SKScene {

    let Ball = SKSpriteNode(imageNamed: "Red.png")
    var QuitOption = SKLabelNode()
    var ScoreLabel = SKLabelNode()
    var timesecond = Int(60)
    var locked = false
    var loseOption = SKLabelNode()
    var winOption = SKLabelNode()
    let whiteBall = SKSpriteNode(imageNamed: "whiteDot")
    let showMessage = SKLabelNode()

    override func didMoveToView(view: SKView) {

        backgroundColor = SKColor.whiteColor() // background for the display

        self.physicsWorld.gravity = CGVectorMake(0, -9.8)

        let SceneBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
        SceneBody.friction = 0
        self.physicsBody = SceneBody

        Ball.size = CGSize(width: 82, height: 82)
        Ball.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height*0.1)
        Ball.physicsBody = SKPhysicsBody(circleOfRadius: 42)
        Ball.physicsBody?.affectedByGravity = true
        Ball.physicsBody?.density = 10
        Ball.physicsBody?.restitution = 0.1
        Ball.physicsBody?.linearDamping = 0
        Ball.name = "Ball"

        self.addChild(Ball)

        QuitOption.text = "Quit"
        QuitOption.fontName = "Noteworthy-Light"
        QuitOption.fontColor = SKColor.redColor()
        QuitOption.fontSize = 35
        QuitOption.position = CGPoint(x: self.frame.size.width/2 - 160, y: self.frame.size.height*1 - 110)
        QuitOption.name = "Quit"

        addChild(QuitOption)

        ScoreLabel = SKLabelNode(fontNamed: "Noteworthy-Light")
        ScoreLabel.fontColor = SKColor.redColor()
        ScoreLabel.fontSize = 35                 // The + will move it to the right side and - to the left side for more accuracy.
        ScoreLabel.position = CGPoint(x: self.frame.size.width/2 + 160, y: self.frame.size.height/1 - 115) // position of ScoreLabelNode
        ScoreLabel.name = "Score+"
        ScoreLabel.hidden = false

        self.addChild(ScoreLabel)

        whiteBall.size = CGSize(width: 55, height: 55)
        whiteBall.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height*0.8)
        whiteBall.name = "whiteBall"

        self.addChild(whiteBall)

        showMessage.fontName = "Noteworthy-Light"
        showMessage.fontSize = 55
        showMessage.fontColor = SKColor.whiteColor()
        showMessage.text = "YOU LOSE!"
        showMessage.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height*0.7)
        showMessage.zPosition = 100
        showMessage.hidden = true
        showMessage.name = "show Message"

        self.addChild(showMessage)

    }

    // Making the ball jump after user touches ball

    override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {

        var touch = touches.first as! UITouch
        var location = touch.previousLocationInNode(self)
        // var location = touch.locationInNode(self)
        var node = self.nodeAtPoint(location)

        if (node.name == "Quit"){

            let myScene = GameScene(size: self.size)
            myScene.scaleMode = scaleMode
            let reveal = SKTransition.fadeWithDuration(1)
            self.view?.presentScene(myScene, transition: reveal)

        }

        if (node.name == "Ball"){

            for touch: AnyObject in touches {

                let location = touch.locationInNode(self)

                Ball.physicsBody?.allowsRotation = true
                Ball.physicsBody?.velocity = CGVectorMake(0, 0)
                Ball.physicsBody?.applyImpulse(CGVectorMake(0, 450))

            }

        }

        if(!self.locked){

            self.locked = true

        var actionrun = SKAction.waitForDuration(0.5)

        var actionwait = SKAction.runBlock({

            self.timesecond--

            if self.timesecond == 60 {self.timesecond = 0}

            self.ScoreLabel.text = "\(self.timesecond)"})

            let loopAction = SKAction.repeatAction(SKAction.sequence([actionwait, actionrun]), count: 60)

            ScoreLabel.runAction(loopAction, withKey: "scoreAction")

            if (timesecond == 0){

                showMessage.hidden = false

            }

        }

    }

}

A: Your code:
    if (timesecond == 0){

        showMessage.hidden = false

    }

... should be in the block that runs every second:
var actionwait = SKAction.runBlock({

    self.timesecond--

    if self.timesecond == 60 {self.timesecond = 0}

    self.ScoreLabel.text = "\(self.timesecond)"

    if (self.timesecond == 0){

        showMessage.hidden = false

    }
})

let loopAction = SKAction.repeatAction(SKAction.sequence([actionwait, actionrun]), count: 60)

ScoreLabel.runAction(loopAction, withKey: "scoreAction")


text:
Q: How to use previous row's column's value for calculating the next row's column's value I have a table

Id | Aisle | OddEven | Bay | Size | Y-Axis
3  | A1    | Even    | 14  | 10   | 100
1  | A1    | Even    | 16  | 10   |
6  | A1    | Even    | 20  | 10   |
12 | A1    | Even    | 26  | 5    | 150
10 | A1    | Even    | 28  | 5    |
11 | A1    | Even    | 32  | 5    |
2  | A1    | Odd     | 13  | 10   | 100
5  | A1    | Odd     | 17  | 10   |
4  | A1    | Odd     | 19  | 10   |
9  | A1    | Odd     | 23  | 5    | 150
7  | A1    | Odd     | 25  | 5    |
8  | A1    | Odd     | 29  | 5    |

want to look like this

Id | Aisle | OddEven | Bay | Size | Y-Axis
1  | A1    | Even    | 14  | 10   | 100
2  | A1    | Even    | 16  | 10   | 110
3  | A1    | Even    | 20  | 10   | 120
4  | A1    | Even    | 26  | 5    | 150
5  | A1    | Even    | 28  | 5    | 155
6  | A1    | Even    | 32  | 5    | 160
7  | A1    | Odd     | 13  | 10   | 100
8  | A1    | Odd     | 17  | 10   | 110
9  | A1    | Odd     | 19  | 10   | 120
10 | A1    | Odd     | 23  | 5    | 150
11 | A1    | Odd     | 25  | 5    | 155
12 | A1    | Odd     | 29  | 5    | 160

I need a select query and update query. What its doing is there are already some Y-Axis Number been filled (at the start of the Odd/Even) then I need to take the previous row's Y-Axis column's value and adds to the current rows's size which = to current Y-Axis. Needs to keep doing it until it finds another Y-Axis has the value it skips the calculation and next row is using that number.
My thinking process is this:
Id will definitely be used, however, the Id is not sequence as shown my example
so I need to have
ROW_Number OVER (PARTITION BY Aisle,OddEven,Bay Order BY Aisle,OddEven,Bay)
Then some kind of JOIN the same table but the ON is T1.RN = T2.RN - 1
Where I am stuck is but the first row has not previous value it will try to update that value.
Anyone have an idea for SQL Query 2008 for Select and Update will be greatly appreciated! Thanks.

A: You seem to want a cumulative sum.  This would be easier in SQL Server 2012+.  You can do this in SQL Server 2008 using outer apply:
select t.*, cume_value
from t outer apply
     (select sum(size) + sum(yaxis) as cume_value
      from t t2
      where t2.aisle = t.aisle and t2.oddeven = t.oddeven and
            t2.bay < t.bay
     ) t2;

A: A little more difficult on 2008, but I think this is what you are looking for
Declare @Table table (Id int,Aisle varchar(25),OddEven varchar(25),Bay int,Size int,[Y-Axis] int)
Insert Into @Table values
(3,'A1','Even',14,10 ,100),
(1,'A1','Even',16,10 ,0),
(6,'A1','Even',20,10 ,0),
(12,'A1','Even',26,5,150),
(10,'A1','Even',28,5,0),
(11,'A1','Even',32,5,0),
(2,'A1','Odd',13,10 ,100),
(5,'A1','Odd',17,10 ,0),
(4,'A1','Odd',19,10 ,0),
(9,'A1','Odd',23,5,150),
(7,'A1','Odd',25,5,0),
(8,'A1','Odd',29,5,0)

;with cteBase as (
      Select *
            ,IDNew=Row_Number() over (Order By Aisle,Bay)
            ,RowNr=Row_Number() over (Order By Aisle,OddEven,Bay)
       From  @Table
 )
 , cteGroup as (Select TmpRowNr=RowNr,GrpNr=Row_Number() over (Order By RowNr) from cteBase where [Y-Axis]>0)
 , cteFinal as (
                Select A.*
                      ,GrpNr = (Select max(GrpNr) from cteGroup Where TmpRowNr<=RowNr)
                 From  cteBase A
                )
Select ID=Row_Number() over (Order By A.OddEven,A.Bay)
      ,A.Aisle
      ,A.OddEven
      ,A.Bay
      ,A.Size
      ,[Y-Axis] = Sum(case when B.[Y-Axis]>0 then B.[Y-Axis] else B.Size end)
 From  cteFinal A
 Join  cteFinal B on (B.RowNr<=A.RowNr and A.GrpNr=B.GrpNr)
 Group By
       A.IDNew
      ,A.Aisle
      ,A.OddEven
      ,A.Bay
      ,A.Size
 Order By A.OddEven,A.Bay

Returns
ID  Aisle   OddEven Bay Size    Y-Axis
1   A1      Even    14  10      100
2   A1      Even    16  10      110
3   A1      Even    20  10      120
4   A1      Even    26  5       150
5   A1      Even    28  5       155
6   A1      Even    32  5       160
7   A1      Odd     13  10      100
8   A1      Odd     17  10      110
9   A1      Odd     19  10      120
10  A1      Odd     23  5       150
11  A1      Odd     25  5       155
12  A1      Odd     29  5       160

A: I gotta leave my computer so update query should be easy to move on from here.
Below is the select query;
select  row_number() over (order by oddeven,bay) id,
    Aisle,
    OddEven,
    Bay,
    Size,
    max(ISNULL([Y-Axis],0)) over (partition by Aisle, OddEven,Size order by bay)
        + sum(CASE WHEN [Y-Axis] is null THEN Size ELSE 0 END) over (partition by Aisle,OddEven,size order by Bay) as [Y-Axis]
from oddseven
order by id


text:
Q: clear the value in select form element using jquery I am trying to clear/empty the selected value in an select element in a jQuery application

    Choose shipping method:
    <select style="font-weight: normal" name="select-choice-1" id="select-choice-1">
        <option value="standard">Standard: 7 day</option>
        <option value="rush">Rush: 3 days</option>
        <option value="express">Express: next day</option>
        <option value="overnight">Overnight</option>
    </select>

using the following line
$('#select-choice-1').val('');

However it does not clear. The selected value remains intact.
http://jsfiddle.net/neilghosh/MECXW/11/

A: A single-valued select always has a selected value, which will default to the first entry.
If you want an "empty" option, you need to add it to the top of the list of options yourself, and then exclude it if it's actually used.

A: val() is more like a shortcut for attr('value'). For your usage use text() or html() instead

A:

<select>
<option value="0">--select--</select>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<button>Reset</button>

A: You are using jQuery Mobile. So you need to refresh your component:
Check this forked fiddle: http://jsfiddle.net/guumaster/MECXW/15/ (*)
Basically you have to "refresh" it like this:
    $('#select-choice-1').selectmenu('refresh');

Check the jQuery Mobile docs for Selects
(*) I've also added an option without value called "None".


text:
Q: Как опустить кнопку вниз блока? Мне необходимо опустить кнопку вниз, чтобы она всегда была с отступом от низа в 100px. У меня не получается это сделать, пробовал через position:absolute; не получается. Делать через margin-top не хочу тк. с изменением размера экрана кнопка будет сьезжать. Помогите пожалуйста.

header {
 background: url(../img/background-image.png) no-repeat;
 background-size: 100% 100%;
 height: 100vh;
}

.header{
 padding-top:50px;
}
.logo{
 font-size: 25px;
 font-weight: 800;
 color: #fff;
 font-family: 'BIG JOHN';
 letter-spacing: 0.13em;
}
.logo:hover{
 cursor: pointer;
}
.menu a{
 margin-left: 7px;
 font-size: 16px;
 color:#fff;
 font-family: 'Open Sans';
 padding: 7px 9px;
 border: 2px solid transparent;
 transition: 0.3s;
}
.menu a:hover{
 border: 2px solid #fff;
 border-radius: 100px;
 color:#fff;
 text-decoration: none;
 transition: 1s ease;
}
.title h1{
 margin-top:35%;
 color:#fff;
 font-weight: 300;
}
.title p{

 padding-top: 30px;
 color:#fff;
}
.scroll {

}
.scroll img{
 display: block;
 transition: 0.5s ease;
}
.scroll img:hover{
 transition: 0.5s ease;
 transform: scale(1.2);
 cursor: pointer;
}

BOUNCY

      Hello
      About
      Services
      Portfolio
      Team
      Blog
      Contact

We Are Code Cafe

At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum

A: попробуй еще раз absolute, только убери ее из
 просто в контейнере помести


text:
Q: Symfony admin generator I have a table A->Users that has a backend generated with symfony admin generator; I have filters and forms too. Is there a way to filter by a get/post request the records that appear when I call backend_dev.php/users, by one of its field (i.e. id field)?

A: Are you using Propel or Doctrine? If you want a subset of the users you have to add the following to your generator.yml (inside users folder):
config:
  --your config
  list:
    peer_method: YOURFUNCTION

I mean the default behavior is to select all, using peer_method you tell symfony to use your custom method. Remember to implement YOURFUNCTION inside  users model.
This works for propel, Doctrine users check this link:
Doctrine table_method


text:
Q: HTML file input not working in PHP I'm making a social media website for a project. I have a PHP function that allows the user to upload an image to a post and inside the function is an html form to allow them to select a form.
echo "<form method='post' enctype='multipart/form-data'>";
            echo "<input type='file' name='myFile'/>";
            echo "<label for='myFile' id='fileLabel'>File input</label>";
            echo "<input type='submit' name='submitFileForm' value='Upload' />";
echo "</form>";

When I process the form with this code and print_r($_FILES) is empty but if I echo $_POST['myFile'] it displays the correct file name.
if (isset($_POST['submitFileForm'])) {

print_r($_FILES);
$my_folder = "img/";

if (move_uploaded_file($_FILES['myFile']['tmp_name'], $my_folder . $_FILES['myFile']['name'])) {
    echo 'Received file' . $_FILES['myFile']['name'] . ' with size ' . $_FILES['myFile']['size'];
} else {
    echo 'Upload failed!';

    var_dump($_FILES['myFile']['error']);
}
}

Thank you for the help , I have been trying to debug this for the last 2 hours. Also I forgot to mention, I already tried increasing upload_max_filesize = 100M and input_max_size = 100M and that is not the problem.

A: You have to change the if condition as following
if (isset($_POST['submitFileForm'])) {

It will be working


text:
Q: EC2 Load Balancer - installing CA Bundle SSL / intermediate certificate I am using the EC2 Load Balancer to handle HTTPS requests. For Chrome & Safari, having the Load Balancer Protocol set HTTPs at Port 443 with the the SSL cert handles most traffic correctly. HTTPS requests from Safari & Chrome are fine. However in Firefox, I get the connection is insecure "(Error code: sec_error_unknown_issuer)." In checking with a cert checker, I get

The certificate is not signed by a trusted authority (checking against
  Mozilla's root store). If you bought the certificate from a trusted
  authority, you probably just need to install one or more Intermediate
  certificates.

In talking with my cert provider, the information I got was :

As we can see certificate has been installed improperly at the server.
  There is no CA bundle at the server that is why browsers may show
  warning messages.

How do you install a CA Bundle using the Load Balancer?

A: The solution is to add the ca_bundle to your load_balancer under "Certificate Chain"

A: That depends on how you are creating the ELB (Elastic Load Balancer).
If you are creating it from the AWS Console, then, when you create the ELB you can create a new SSL sercificate and, when promted, and as @Emile said, you have to specify the contents of the provided "CA Bundle" under the "Certificate Chain" field.
If you are creating it from the command line or using the API, then when you create the SSL certificate you have to specify the "CA Bundle" contents in the "Certificate Chain" parameter.
Right now, what you probably have to do is to create a new ELB specifying the right paramenters, modify your DNS accordingly and once the change has been applied, delete the old load balancer.

A: First you'll need to obtain a copy of the appropriate certificate bundle from your certificate authority.
Then you'll need to update the SSL certificate on your AWS ELB. Select "Upload a new SSL Certificate" from the ELB Select Certificate window. Paste your current private and public certificate keys into the appropriate fields and then paste the certificate bundle into the "Certificate Chain" field.


text:
Q: AngularJS - Updating one element in ng-if causes all elements to get updated I am using angluar2 and TypeScript to create a table. I couldn't figure out how to make the <select> in each  of the same row
 to be independent.  My codes would allow user to pick an option from any column.  Once a user pick an option, all columns in the same row will be updated.

{{hdr.DayOfMonth}}

{{hdr.DayOfWeek}}

        <template ngFor let-roster="$implicit" [ngForOf]="rosterList">
          {{roster.DutyOption}}
          {{roster.DutyOption}}
          {{roster.DutyOption}}
          {{roster.DutyOption}}

            <select class="form-control input-sm" [ngModel]="_selDutyOption" (ngModelChange)="updateUserRequest($event, roster)">
              <option></option>
              <option *ngFor="let dutyOption of _dutyOptions; let j=index" (ngValue)="dutyOption" [selected]="dutyOption.Id === roster.DutyOptionId ? true : false">{{dutyOption.Description}}</option>
            </select>

        </template>

A: This is because you bind all the select elements with the same value:_selDutyOption, when one select changed, all will update.
Defining distinct models for each select element will solve your problem.


text:
Q: LibGDX FileHandle: Renaming a file deletes the file To rename a file I use
FileHandle#moveTo(FileHandle dest)
It works fine in most cases. But when I try to rename, for example, a file "abc" to "ABC", the file gets deleted.
I think the problem is that file names are insensitve ( at least on Desktop, Windows).
This is the implementation of the method mentioned above (I left commentaries in the code):
public void moveTo (FileHandle dest) {
    if (type == FileType.Classpath) throw new GdxRuntimeException("Cannot move a classpath file: " + file);
    if (type == FileType.Internal) throw new GdxRuntimeException("Cannot move an internal file: " + file);
    copyTo(dest); // file is not copied into another file, since "abc" file  is the same as the dest "ABC" file
    delete(); // and here the "original" file is deleted, but in this case original file equals to dest file, so the file is lost
    if (exists() && isDirectory()) deleteDirectory();
}

Questions:
1) Is such behaviour intentional? Honestly, it feels wrong.
2) Is it ok to do renaming like this (it works in this case, but maybe there are another caveats):
FileHandle src = ...;
FileHandle dest = ...;
src.file().renameTo(dest.file());

If not, what's the right way?
Update
As @exenza suggested, opened an issue on LibGDX issue tracker

A: On Windows, file names are case insensitive. This means that "abc" and "ABC" refer to the same file. Your copyTo() call, will copy the file to itself. Then delete() deletes the file. During all of this there is only one file and no copy.


text:
Q: How I can add alt attribute to posted images that are separated from text? This is my code to give alt attribute to all images on published post.
It works fine for all images on normal post.
function auto_alt_set($html)
{
    global $post;
    $pic_alt = get_the_title();
    if ($pic_alt !== '') {
        $html = str_replace('alt=""', 'alt="' . esc_attr($pic_alt) . '"', $html);
    }
    return $html;
}
add_filter('the_content', 'auto_alt_set');

Now I like to know how I can set alt attribute to images that are extracted from content by the following code.
<?php
$beforeEachImage = "<div>";
$afterEachImage = "</div>";
preg_match_all("/(<img [^>]*>)/", get_the_content(), $matches, PREG_PATTERN_ORDER);
for ($i = 0; isset($matches[1]) && $i < count($matches[1]); $i++) {
    echo $beforeEachImage . $matches[1][$i] . $afterEachImage;
}
?>


text:
Q: Is there an onload event for Python's tkinter Window? Currently learning the tkinter module for Python 3.7
Is there an Onload() event (kind of like the c#'s WPF onload event)?
The background, I am trying to load a progress bar 5 values every second till full, but so far I can only trigger this using the button "command" eg:
btn = Button(window, text="Click Me", command=clicked)

Thanks,
Here is my code after Bryan's help, the progress bar is still loading before the main window is populated:
from tkinter import Tk,Button,Frame #import *
from tkinter.ttk import Progressbar
from tkinter import ttk
import time

starttime=time.time()

def loadbar(value):
    bar['value'] += value

def clicked():
    loadbar(5)

def tick_loadingbar(event):
    if event.widget == window:
        while(bar["value"] < 100):
            loadbar(25)
            time.sleep(1)

window = Tk()
window.title("Loading Bar app")
window.geometry('350x200')
window.bind("<Map>", tick_loadingbar)
style = ttk.Style()
style.theme_use("default")
style.configure("black.Horizontal.TProgressbar", background='lightgreen')
bar = Progressbar(window, length=200, style='black.Horizontal.TProgressbar')
bar['value'] = 25
bar.grid(column=0, row=0)
btn = Button(window, text="Click Me", command=clicked)
btn.grid(column=1, row=1)

window.mainloop()

A: There might be a solution. You could update your window with the update() method and do the onload code. After that you mainloop the window. That worked for me.


text:
Q: Magento 2.3 translations (translate label) in the admin panel (backend) In Magento 1 I just added a translate.csv for my admin area.
How can I achieve this in Magento 2?
I just want to change the translations of a few things and add some missing translations. Can't I put a de_De.csv for the adminhtml area somewhere?
How to handle translations for the admin panel (backend).
Thanks

A: You can download code from here
Edit/Add CSV as per your Locale.
app/design/adminhtml/Shah/default/i18n

A: With your custom module, you can create an i18n folder and place your translation file inside.  The path should look like this:

app\code\vendor\module\i18n\yourTranslationFile.csv
  which in your case is de_De.csv

A: In Magento 2, translations file is saved in /vendor/magento/<module-modulename>/i18n folder.
For example, if you want to modify translation for word related to checkout module, it could be saved in /vendor/magento/module-checkout/i18n/<locale-folder> folder.
You can copy locale's csv file from /vendor/magento/module-checkout/i18n folder to app/code/Magento/module-checkout/i18n directory.

A: I tried your solution on Magento 2.2.9 but seems not working
I need to add fr_FR.csv translation for some extensions who are under /vendor/amasty/extension_name
so I had created directory structure under /app/code/Amasty/Extension_name/i18n
and uploaded fr_FR.csv file inside
... but translation doesn't work !
N.B : if i upload fr_FR.csv file under the /vendor/...../i18n it works but in this case each time I update the extension, it erease the translation file.
Does someone find a solution for module translation ?
Thanks a lot

A: put translate file under theme not working for backend.
Need create a custom module, add  in module.xml, then add translation file under i18n folder (vendor/VENDOR/MODULE/i18n/en_NZ.csv, or app/code/.../i18n/en_NZ.csv).
Double-check your account interface Locale set properly.
e.g. en_NZ.csv work for English(New Zealand).
above solution not working for en_US, if need support this, then
just create admin theme, follow magento docs https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/themes/admin_theme_create.html and https://devdocs.magento.com/guides/v2.4/frontend-dev-guide/themes/admin_theme_apply.html
then add en_NZ.csv/en_US.csv under admin theme i18n folder.


text:
Q: Why does a  inside a  not notice the outer  margin? I have the following:

       xxx

#modal-body {
  display: block;
  margin-top: 5rem;
}

.modal-input-row {
  margin-top: 2rem;
  overflow: hidden;
  display: block;
}

When I look at these with Google Chrome developer tools I see that:

*

*The modal-body top area starts 5rem below the #x

*The modal-input-row top area starts 5rem below the #x

As modal-input-row is inside modal-body then whey does it not start 7rem below the #x
 ?

A: What you're seeing is a case known as margin collapse. It happens under several conditions, and yours is known as the scenario where there is no clearance between the top margin of the parent and the first child.

If there is no border, padding, inline content, or clearance to separate the margin-top of a block with the margin-top of its first child block, or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block with the margin-bottom of its last child, then those margins collapse. The collapsed margin ends up outside the parent.

It would be advisable to use paddings instead, as they don't collapse.
Margin collapse is also discussed in greater detail in the W3C box model specification

A: In your HTML, modal-input-row is a class.
CSS markup should be
.modal-input-row {
    margin-top: 2rem;
    overflow: hidden;
    display: block;
}

OR:
Change

to

A: As per this fiddle: http://jsfiddle.net/gjNAW/ It seems to be fine.
Borders absence is making it collapse.
See this one without borders: http://jsfiddle.net/gjNAW/1/
Aside:
(1) you misplaced the "." for the class.
(2) no need to explicitly specify display:block, because divs are block elements.


text:
Q: Password protecting an asp.net site using a log in page I am trying to password protect an asp.net site, i have done this okay, however if they put /home.aspx at the end of the address then it will by pass the log in page, is there a way of making those other pages only accessible through the buttons, and if they are accessed directly it will redirect you to the login page?
THanks

A: unless you are using some other way.. just checkout the asp.net membership provider documentation on msdn:
http://msdn.microsoft.com/en-us/library/ff648345.aspx
if you scroll right to the bottom this is what you are looking for, but this page gives all the info you'll need.

A: You could store the log on state in session and check on page load or pre init for an isLoggedin flag which only gets set if they have logged in successfully. This won't prevent them navigating directly to pages if they are logged in but will keep them out if they aren't.

A: At the moment you login you should start a session.
This is some code I used in one of my high school projects
> public void LoginUser(string id, string mail, string ww, string admin)
>     {
>         Session["UserID"] = id;
>         Session["IsAdmin"] = admin;
>         if(admin == "admin")
>         {
>             Response.Redirect("~/Admin/AdminCP.aspx");
>         }
>         else if (admin == "user")
>         {
>             Response.Redirect("~/User/UserCP.aspx");
>         }
>         else
>         {
>             lblLoginError.Text = "An error has accurred";
>             lblLoginError.Visible = true;
>             lblLoginError.CssClass = "failureNotification left";
>         }
>     }

This is a way I used detecting if a user was an admin or a basic user.
After this, in every page in the Page_Load-section you have to add
> if (Session["UserID"] == null)
>         {
>             Response.Redirect("~/Account/Login.aspx");
>         }

This will check everytime if the session UserID is running. If it is empty, the login never happened, so the user will be redirected to the page where he can login.
Hope this helped ;-)


text:
Q: WFE's out of Synch I have 2 SharePoint WFE Servers, due to some changes by my previous administrator, one of the WFE is out of synch. Can you please suggest.. what could be the issue?
Example: When a create a new web application, it creates the website only on One WFE and not on other. ANother thing.. when I am creating a new web application.. "Opeartion in Progress " continues for ever...
Please suggest.

A: restarting the timer services should resolve the issue if the server is healthy.
You can also run stsadm -o execadmsvcjobs to initiate any pending changes immediately.

A: We faced a similar problem in MOSS 2007 environment . where the webapplication is  created in one server and it is not created in the other.
The steps which we did was delete the webapplication first
Restart the timer services in both the WFE and try creating a webapplication . This should solve


text:
Q: Integral on continuous functions metric space, is it right? The function $f$ is defined : $\begin{cases} C_{[0,1]}\to\mathbb{R}
                             \\f\to f(0)\end{cases}$ And
$C_{[0,1]}$ is the metric space of continuous functions with the integral metric $d$. We define a function $g$ that lies on the neighbourhood of $f$:

\begin{align}g:[0,1]&\to\mathbb{R}\\
x&\rightarrow\begin{cases}f(\epsilon^´)\frac{x}{\epsilon´}&\text{if }x<\epsilon´\\
f(x)&\text{otherwise}\end{cases}\end{align}

My question is about the integral. How can $\int_0^{\epsilon´}\left|f-g\right|\leqslant 2M\epsilon$ be true. Is this right? I got it from a textbook exercise solution. $M=sup\left|f\right|$.Thanks for reading!
\begin{align}d(f,g_n)&=\int_0^1\left|f-g\right|\\
&\ =\int_0^{\epsilon´}\left|f-g\right|\\
&\leqslant 2M\epsilon´  \end{align}

A: Note that $g(x) = f(x)$ for $x > \epsilon'$.
$\int_0^1 |f-g| = \int_0^{\epsilon'} |f(x)-g(x)| dx \le \int_0^{\epsilon'} (|f(x)|+|g(x)|)dx \le \int_0^{\epsilon'} 2M dx = 2M \epsilon'$.


text:
Q: TypeError: Cannot read properties of null (reading 'collection') module.exports = {
  doSignUp: (adminData) => {
    return new Promise(async (resolve, reject) => {
      adminData.Password = await bcrypt.hash(adminData.Password, 10);
      console.log(adminData);
      db.get()
        .collection(collection.ADMIN_DETAILS)
        .insertOne(adminData)
        .then((data) => {
          resolve.apply(data);
        });
    });
  },
};

C:\Users\jibiy\OneDrive\Desktop\Week 6\Admin
Panel\helpers\admin-helper.js:11
db.get().collection(collection.ADMIN_DETAILS).insertOne(adminData).then((data)=>{
^
TypeError: Cannot read properties of null (reading 'collection')


text:
Q: Corrupt usr/bin/java I just did a pretty stupid thing, when I tried to copy JSTestDriver.jar into usr/bin/java by typing this command: cp jsTestDriver.jar usr/bin/java.
Now every 'java' command in terminal just prints out this:
/usr/bin/java: line 1: PK: command not found
/usr/bin/java: line 2:Q?EA: command not found
/usr/bin/java: line 3P?EAan???META-INF/MANIFEST.MFM???: No such file or directory
~?n?/bin?m8?|<(.???l?s?.???c}?s??N̥7?)??U[?/????PB?PK
Tg.Acom/PK
Tg.A
    com/google/PK
Vg.Acom/google/jstestdriver/PK
Tg.Acom/google/jstestdriver/action/PK
Tg.A$com/google/jstestdriver/annotations/PK
Tg.A com/google/jstestdriver/browser/PK
Tg.A!com/google/jstestdriver/commands/PK
Tg.Acom/google/jstestdriver/config/PK
Ug.A!com/google/jstestdriver/debugger/PK
Ug.A!com/google/jstestdriver/embedded/PK
Ug.Acom/google/jstestdriver/guice/PK
Ug.Acom/google/jstestdriver/hooks/PK
Vg.Acom/google/jstestdriver/html/PK
P?EA#com/google/jstestdriver/javascript/PK
Vg.A*com/google/jstestdriver/javascript/compat/PK
P?EAcom/google/jstestdriver/javascript/lib/PK: No such file or directory
/usr/bin/java: line 20:Vg.A+com/google/jstestdriver/javascript/plugins/PK: No such file or directory
/usr/bin/java: line 21:Vg.A1com/google/jstestdriver/javascript/plugins/async/PK: No such file or directory
/usr/bin/java: line 22:Ug.Acom/google/jstestdriver/model/PK: No such file or directory
/usr/bin/java: line 23:Ug.Acom/google/jstestdriver/output/PK: No such file or directory
/usr/bin/java: line 24:Ug.A: command not found
/usr/bin/java: line 25:Ug.A!com/google/jstestdriver/protocol/PK: No such file or directory
/usr/bin/java: line 26: syntax error near unexpected token `com/google/jstestdriver/requesthandlers/PK'
/usr/bin/java: line 26: Ug.A(com/google/jstestdriver/requesthandlers/PK'

I've googled my problem, but cannot find a solution to my problem.
I am running Mac OS 10.6.8, which doesn't support Java SE 7.0. Which i had hoped would fix my problem.
Does anyone know how I can restore /usr/bin/java ?

A: /usr/bin/java is usually just a symlink, sometimes to your actual java installation, sometimes to something like /etc/alternatives/java.
What java are you using?  Sun/Oracle?  OpenJDK?  And what is your distro?
Running the command:
find / -type f -name java

Should get you started finding the real java binary.

A: just to be sure: could you execute the following and post the result?
readlink -f /usr/bin/java
file /System/Library/Frameworks/JavaVM.framework/Versions/A/Commands/java
/System/Library/Frameworks/JavaVM.framework/Versions/A/Commands/java -version


text:
Q: What is the proper usage of the prepositional phrase "of which"? Is the second sentence below grammatically correct? If not, why so?

*

*We are looking for the house the windows of which are broken.

*We are looking for the house of which the windows are broken.

A: Yes. Both are grammatically correct - and the second more idiomatically usual than the former.
If you want to use the first it might be improved by putting a comma after "house".


text:
Q: jquery two different values to sum up but how? I'm having trouble to sum two different kinds of values. I have one value that I get from a json request like so:
function bakVormShipping(targetClass){
  $.getJSON('http://shop.com/cart/?format=json', function(data){
    $.each(data.cart.shipping.methods, function(index, methods){
      if (index == "core|10292|40695" || index == "core|10292|40693" || index == "core|10292|40718"){
        $('').html('€' + (+methods.price.price_incl).toFixed(2)).appendTo(targetClass); // this is value 1
      }
    });
  });
}

The other value is in a div somewhere in a html page, like so:

Totaal (incl.btw):

    {{ page.cart.total.price | money }} // this is value 2

Is it even possible to sum these two values? If so can somebody please give me some examples or maybe some directions? I've tried numerous things with parseFloat etc. but it returns nothing, NaN or undefined. So some help is more then welcome :)

A: Please don't do a price calculation on the client side ("never trust a client", because they can be hacked.  For that reason, you end up duplicating code on the client and server side).
Instead, look into using Ajax to call back to the server for recalculations, and updates to the web page, as necessary.
http://en.wikipedia.org/wiki/Ajax_(programming)
http://api.jquery.com/category/ajax/
If the server isn't currently performing all calculations you need, the only safe way to fix the problem is to modify the server code.


text:
Q: Create a new record in data frame if column value has more than one value I have a df:
        author                    text                 symbols
0  IAMLLUCIANA        ZERO are legends                ['ZERO']
1  IAMLLUCIANA        I love this game                 ['ERN']
2  IAMLLUCIANA           This is great                ['ZERO']
3  IAMLLUCIANA  Ricky knows about this          ['HTR', 'ZCX']
4  IAMLLUCIANA        You CANNOT match               ['BONDLY']
5  IAMLLUCIANA        I love this game    ['ERN', 'HTR', 'ZCX']

Where the symbols column has more than one symbol in a record (for example record 3 has two symbols (HTR and ZCX).  Is it possible to create a separate record for each so my desired output would look like:
        author                    text          symbols
0  IAMLLUCIANA        ZERO are legends          ['ZERO']
1  IAMLLUCIANA        I love this game           ['ERN']
2  IAMLLUCIANA           This is great          ['ZERO']
3  IAMLLUCIANA  Ricky knows about this           ['HTR']
4  IAMLLUCIANA  Ricky knows about this           ['ZCX']
5  IAMLLUCIANA        You CANNOT match        ['BONDLY']
6  IAMLLUCIANA        I love this game           ['ERN']
7  IAMLLUCIANA        I love this game           ['HTR']
8  IAMLLUCIANA        I love this game           ['ZCX']

A: From your DataFrame :
>>> import pandas as pd

>>> df_1 = pd.DataFrame({'author': ['IAMLLUCIANA', 'IAMLLUCIANA', 'IAMLLUCIANA', 'IAMLLUCIANA', 'IAMLLUCIANA', 'IAMLLUCIANA'],
...                      'text': ['ZERO are legends', 'I love this game', 'This is great', 'Ricky knows about this', 'You CANNOT match', 'I love this game'],
...                      'symbols': ["['ZERO']", "['ERN']", "['ZERO']", "['HTR', 'ZCX']", "['BONDLY']", "['ERN', 'HTR', 'ZCX']"]},
...                     index = [0, 1, 2, 3, 4, 5])
>>> df_1
    author          text                    symbols
0   IAMLLUCIANA     ZERO are legends        ['ZERO']
1   IAMLLUCIANA     I love this game        ['ERN']
2   IAMLLUCIANA     This is great           ['ZERO']
3   IAMLLUCIANA     Ricky knows about this  ['HTR', 'ZCX']
4   IAMLLUCIANA     You CANNOT match        ['BONDLY']
5   IAMLLUCIANA     I love this game        ['ERN', 'HTR', 'ZCX']

We add missing brackets in the list :
>>> df_1['symbols'] = df_1['symbols'].str.replace(", ",'],[')
>>> df_1
    author          text                    symbols
0   IAMLLUCIANA     ZERO are legends        ['ZERO']
1   IAMLLUCIANA     I love this game        ['ERN']
2   IAMLLUCIANA     This is great           ['ZERO']
3   IAMLLUCIANA     Ricky knows about this  ['HTR'],['ZCX']
4   IAMLLUCIANA     You CANNOT match        ['BONDLY']
5   IAMLLUCIANA     I love this game        ['ERN'],['HTR'],['ZCX']

We build a new DataFrame where we stack the list elements :
>>> df_2 = df_1['symbols'].str.split(',', expand=True).stack().to_frame().reset_index().drop('level_1', axis=1)
>>> df_2 = df_2.rename(columns={0: 'all_symbol'})
>>> df_2
    level_0     all_symbol
0   0           ['ZERO']
1   1           ['ERN']
2   2           ['ZERO']
3   3           ['HTR']
4   3           ['ZCX']
5   4           ['BONDLY']
6   5           ['ERN']
7   5           ['HTR']
8   5           ['ZCX']

Then we merge the result with the first DataFrame to get the expected result :
>>> df = pd.merge(df_2,
...               df_1,
...               how='left',
...               left_on=['level_0'],
...               right_index=True)
>>> df.drop('level_0', axis=1)
    all_symbol  author          text                    symbols
0   ['ZERO']    IAMLLUCIANA     ZERO are legends        ['ZERO']
1   ['ERN']     IAMLLUCIANA     I love this game        ['ERN']
2   ['ZERO']    IAMLLUCIANA     This is great           ['ZERO']
3   ['HTR']     IAMLLUCIANA     Ricky knows about this  ['HTR'],['ZCX']
4   ['ZCX']     IAMLLUCIANA     Ricky knows about this  ['HTR'],['ZCX']
5   ['BONDLY']  IAMLLUCIANA     You CANNOT match        ['BONDLY']
6   ['ERN']     IAMLLUCIANA     I love this game        ['ERN'],['HTR'],['ZCX']
7   ['HTR']     IAMLLUCIANA     I love this game        ['ERN'],['HTR'],['ZCX']
8   ['ZCX']     IAMLLUCIANA     I love this game        ['ERN'],['HTR'],['ZCX']


text:
Q: Excel OFFSET function to work on visible cell only / Formula to generate summary title for repeated cells I have the data as shown in the image below. This is sorted on column B (Project Priority). I want to create a helper column to show the Priority label based only on the first 'visible' priority name from Column B. The current formula that I am using for Column C works fine for unfiltered data but not when I apply filter. For example, if I exclude Row 2 (Project 01), the summarized label in Column C will become invisible too.
Is there a way to make the values in Column C to adjust to visible cells only? I know this could probably be achieved with the combination of SUBTOTAL(103,ref), OFFSET but I have not been able to figure this out. I want to avoid VBA if at all possible.
Thanks a lot in advance.

A: You can use this line to see if the call is visible or hidden and change it's value by that.
= IF( SUBTOTAL(103,A2)=1, "VISIBLE", "HIDDEN (or blank)" )
For more information you can look at
https://superuser.com/questions/885159/excel-function-determine-if-a-cell-is-visible

A: Not the Best solution but it works.
The formula:
=IF(AND(SUBTOTAL(103,A5)=1,C4<>B5,C3<>B5,C2<>B5),B5,"")

A: this will work in C2 and copy down
English
=IF(OR(AND(COUNTIF($C$1:C1,B2)=0,SUBTOTAL(103,B2)=1),AND(SUBTOTAL(103,B2)=1,B2<>B1)),B2,"")

German
=WENN(ODER(UND(ZÄHLENWENN($C$1:C1;B2)=0;TEILERGEBNIS(103;B2)=1);UND(TEILERGEBNIS(103;B2)=1;B2<>B1));B2;"")

best regards chris


text:
Q: In Python 2, can I pass a list to the percent-format operator? I have a list of things I'd like to print using a format string.  In Python 3-style, using "a string".format(arg,arg,arg), this is easy.  I can just replace with arguments with *mylist, like
mylist = [1,2,3]
"{} {} {}".format(*mylist)

I can't seem to make this work with the older percent-formatting.  I've tried stuff like "%i %i %i" % mylist, %i %i %i" % (mylist), and %i %i %i" % (*mylist) but I just keep getting syntax errors or "not enough arguments".
Is this impossible in 2.x style?
ETA: I am changing the example above, I actually did mean list, not tuple.  I'm still learning and I'm not used to having two distinct array-like constructs.

A: str % tuple should just work.
>>> mylist = (1, 2, 3)  # <---- tuple
>>> "%i %i %i" % mylist
'1 2 3'

BTW, (1, 2, 3) is a tuple literal, not a list literal.
>>> mylist = [1, 2, 3]  # <----- list
>>> "%i %i %i" % mylist
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not list

If you want to make it work for list, convert the list into a tuple.
>>> "%i %i %i" % tuple(mylist)
'1 2 3'

A: If you want to print a list delimited by spaces, here is a more flexible solution that can support any number of elements
>>> l = [5,4,3,2,1]
>>> ' '.join(map(str,l))
'5 4 3 2 1'

This also works for tuples
>>> l = (5,4,3,2,1)
>>> ' '.join(map(str,l))
'5 4 3 2 1'


text:
Q: Installation error 80029564 on PS3 I have a problem when installing the game Midnight Club Los Angeles: Complete Edition, which is available for a test of 60 minutes via the PlayStationPlus membership. All went well during the download, but when installing, 14%, I get the error 80029564. My research is not very fruitful. Many say format, others say that formatting the disk did not solve their problem. Some say try to install several times, what I do. Many talk about re-download, or even several times. I don't want to re-download 5.1go several times for only 60 minutes, especially for a game to $ 19.99.

A: As you say there are many suggestions to fix this error. But after reading this thread, it seems that you should do the following :

*

*Do not download in the background.

*Improve wireless connection if possible or use cabled connection.

*Download the whole file in one go, to minimize risk of corrupting the download.
So right now you should restart the download, while following the directions above.


text:
Q: How to add rows to UITableView dynamically? Need the application to add rows dynamically to a TableView. How to implement that?

This doesn't seem to work:
NSIndexPath *path = [[NSIndexPath alloc]initWithIndex:(rowCount - 1)];
[self.tableView insertRowsAtIndexPaths:
    [NSArray arrayWithObject:path] withRowAnimation:UIViewAnimationCurveEaseIn];

A: Have a look at:
-(void)insertRowsAtIndexPaths:(NSArray *)indexPaths
       withRowAnimation:(UITableViewRowAnimation)animation

If you would have waited a while writing this question, you would have seen numerous
suggestions for similar questions.


text:
Q: Javascript detect when inner html has changed I have tried attaching the even onchange and change(with jquery) to an element that updates every couple seconds. Neither of these events are raised when the inner html is changed.
How can I detect with with javascript or jquery?

A: Maybe you're looking for the DOMSubtreeModified event? See the DOM event reference on MDN.

A: is it updating by ajax? can't you just store the value before the call is made and compare it with what is returned?


text:
Q: How to derive Clone for structures with boxed closure? I have the following structure:
struct MyStruct {
   foo: Box<dyn Fn(usize) -> usize>
}

And I want to derive Clone for MyStruct. However, the compiler turns out error:
the trait bound `dyn std::ops::Fn(usize) -> usize: std::clone::Clone` is not satisfied

And for now (rustc 1.46.0), the dyn does not support addition of non-auto traits like Box<dyn Fn(usize) -> usize + Clone>.
From the rust-reference:

A closure is Clone or Copy if it does not capture any values by unique immutable or mutable reference, and if all values it captures by copy or move are Clone or Copy, respectively.

So I think this derivation makes sense in theory, but I don't know if I can do it for now.
I don't mind manually implementing Clone for MyStruct, but I don't know how to do it, either.
I don't want to do something like
#[derive(Clone)]
struct MyStruct<F: Fn(usize) -> usize> {
    foo: F
}

because this struct is used as an associated type for an implementation of another struct for a trait, and both that struct and the trait has no generics, and I don't want to messed up with PhantomData.

A: Expanding on @mcarton comment above, but using the dyn-clone crate to overcome Clone not being object safe, the code is quite straightforward.
use dyn_clone::DynClone;

trait FnClone: DynClone {
    fn call(&self, x: usize) -> usize;
}

impl<F> FnClone for F
    where F: Fn(usize) -> usize + Clone

{
    fn call(&self, x: usize) -> usize {
        self(x)
    }
}

struct MyStruct {
   foo: Box<dyn FnClone>
}

impl Clone for MyStruct {
    fn clone(&self) -> MyStruct {
        MyStruct {
            foo: dyn_clone::clone_box(&*self.foo),
        }
    }

}

fn main() {
    let a = MyStruct{
        foo: Box::new(|x| x + 1)
    };
    let b = a.clone();
    println!("{} {}", a.foo.call(1), b.foo.call(2));
}

This crate also provides a macro clone_trait_object! to make the Clone derivable for the Box<dyn FnClone>, but you don't seem to want that.


text:
Q: Vertical chapter title in the table of contents I'm about to write my thesis, and finally decided to do so in LaTeX. I'm still new to it though, and was wondering if something like this is possible in the table of contents:
--+
  |
I |
N |  Topic 1 ................ 1
T |  Topic 2 ................ 3
R |      Subtopic 1 ......... 4
O |
  |
--+
  |
T |  Topic 3 ................ 6
H |  Topic 4 ................ 8
E |      Subtopic ........... 9
O |          Subsub ......... 11
R |  ... etc
Y |
  |
--+

The lines used on the left should not be ASCII characters if possible, and the text on the left is the chapter names, in case it isn't clear :-)
Edit
Okay, so I will attach a mwe here, although it really doesn't make sense in it's current form.
\documentclass[a4paper]{book}
\begin{document}
\tableofcontents
\chapter{Intro}
    \section{Topic 1}
    \section{Topic 2}
        \subsection{Subtopic 1}
\chapter{Theory}
    \section{Topic 3}
    \section{Topic 4}
        \subsection{Subtopic}
            \subsubsection{Subsub}
    \section{... etc}
\end{document}

This will produce the following TOC, where I'd like to move the chapter names (Intro and Theory) to the side, as shown in my ASCII graphics above.

A: See alternate presentation below, for a perhaps superior appearance.
ORIGINAL PRESENTATION
This is a question of can, not should.  First, reading vertical text is not easy on the eyes.  Second, if the chapter title is too long, you may require an abbreviation to make it fit the vertical space allocated for the toc listing.
So, I approach it with the optional argument, as
\chapter[\boxtoc{T h e o r y}{4}]{Theory}

where \boxtoc{}{} is the macro that sets the title vertically in the toc, the 1st argument is a possibly abbreviated chapter title that is space separated (with more work, I could have the macro deal with that), and the 2nd argument is how many \baselineskip you wish to allocate for the vertical box; however, if the chapter name is too long, it could grow the vertical extent of the box beyond that allocated by argument #2\baselineskip.
To accomplish its goal, \boxtoc uses an \llap of an \fboxed stack.  The stack is placed in a fixed-width \makebox, to insure that all vertical chapter titles are a uniform width.
This approach will screw up book class headers, unless special provisions are taken, but I leave that fix to someone else.
EDITED to blot out the chapter number with a white-block overlay.
\documentclass[a4paper]{book}
\usepackage{stackengine,color}
\setstackgap{L}{.75\baselineskip}
\newcommand\boxtoc[2]{%
 \smash{\llap{\fbox{\protect\rule[-#2\baselineskip]{0pt}{#2\baselineskip}%
   \protect\makebox[2ex]{\Longunderstack{#1}}}%
  \kern\fboxrule\usebox{\whiteblock}}}%
}
\newsavebox\whiteblock
\savebox\whiteblock{\textcolor{white}{\protect\rule{.3in}{2ex}}}
\begin{document}
\tableofcontents
\chapter[\boxtoc{I n t r o}{3}]{Intro}
    \section{Topic 1}
    \section{Topic 2}
        \subsection{Subtopic 1}
\chapter[\boxtoc{T h e o r y}{4}]{Theory}
    \section{Topic 3}
    \section{Topic 4}
        \subsection{Subtopic}
            \subsubsection{Subsub}
    \section{... etc}
\end{document}

Note: For some reason, this method is incompatible with the xcolor package; however, it works fine with the color package.

ALTERNATIVE PRESENTATION
Thanks to JúdaRonén in comment, the suggestion was made to rotate the Latin text.  In my estimation, the look is superior.  In this case, there should not be spaces introduced in the optional chapter names.
\documentclass[a4paper]{book}
\usepackage{color,graphicx}
\newcommand\boxtoc[2]{%
 \smash{\llap{\fbox{%
   \protect\Rotatebox{\protect\makebox[#2\baselineskip][r]{\strut#1}}}%
  \kern\fboxrule\protect\Whiteblock}}%
}
\def\Rotatebox#1{\rotatebox[origin=r]{90}{#1}}
\def\Whiteblock{\textcolor{white}{\protect\rule{.3in}{2ex}}}
\begin{document}
\tableofcontents
\chapter[\boxtoc{Intro}{3}]{Intro}
    \section{Topic 1}
    \section{Topic 2}
        \subsection{Subtopic 1}
\chapter[\boxtoc{Theory}{4}]{Theory}
    \section{Topic 3}
    \section{Topic 4}
        \subsection{Subtopic}
            \subsubsection{Subsub}
    \section{... etc}
\end{document}