Erro na execução de imagem do activity_main.xml

Question: recentemente instalei o android studio versao 3.0 e segui as instruções de instalação e configuração dele, porém surgiu esse erro. Desinstalei e reinstalei e persiste na mesma, o que devo fazer?
Comment: Pela mensagem parece que você está com versões de dependências conflitantes. Verifique se não foram declaradas mais de uma vez ou se as versões instaladas estão de acordo com o projeto.
Comment: o que seriam essas dependências conflitantes? poderia me explicar?
Answer: Parece que no seu arquivo build.gradle do seu módulo app a dependência com.android.support:support-annotations declarada mais de uma vez e com versões diferentes. Aparentemente, você tem essa dependência com a versão 26.1.0 e 17.1.1. Basta verificar qual a versão do seu compileSdkVersion. Caso seja 27, então mude todas as versões das dependências com.android.support para 27, caso contrário mude para versão que se encontra.
Se preferir, poste o código do seu build.gradle aqui para analisarmos.


Evaluating $\int_{0}^{\pi}\ln (1+\cos x)\, dx$

Question: The problem is
$$\int_{0}^{\pi}\ln (1+\cos x)\ dx$$
What I tried was using standard limit formulas like changing $x$ to $\pi - x$ and I also tried integration by parts on it to no avail. Please help. Also this is my first question so please tell if I am wrong somewhere.
Comment: @Jack thanks for edit ... I was wondering why latex wasn't rendering. Now I get it that I should use mathjax
Comment: You may find some inspiration in [this similar question](http://math.stackexchange.com/questions/909712/evaluate-int-0-frac-pi2-ln1-cos-x-dx).
Answer: $$\begin{eqnarray*}\int_{0}^{\pi}\log(1+\cos x)\,dx &=& \int_{0}^{\pi/2}\log(1+\cos x)\,dx+\int_{0}^{\pi/2}\log(1+\cos(\pi-x))\,dx\\ &=& \int_{0}^{\pi/2}\log(\sin^2 x)\,dx=\int_{0}^{\pi}\log(\sin x)\,dx \tag{1}\end{eqnarray*}$$
And by a notorious identity:
$$ \prod_{k=1}^{n-1}\sin\frac{k\pi}{n} = \frac{2n}{2^n},\tag{2}$$
hence the RHS of $(1)$ can be computed as a Riemann sum:
$$ \int_{0}^{\pi}\log(\sin x)\,dx = \lim_{n\to +\infty}\frac{\pi}{n}\sum_{k=1}^{n-1}\log\sin\frac{\pi k}{n}=\color{red}{-\pi \log 2}.\tag{3}$$
There is also a well-known proof through symmetry:
$$ \begin{eqnarray*}I=\int_{0}^{\pi}\log(\sin x)&=&2\int_{0}^{\pi/2}\log(\sin(2t))\,dt=2\int_{0}^{\pi/2}\log(2\sin t\cos t)\,dt\\&=&\pi\log 2+2\int_{0}^{\pi/2}\log(\sin t)\,dt+2\int_{0}^{\pi/2}\log(\cos t)\,dt\\&=&\pi \log 2 + 2I\tag{4}\end{eqnarray*}$$
from which $I=-\pi\log 2$ immediately follows.
Comment: This is really nice!
Answer: Another way to solve is to use the Cauchy Integral Formula
$$ f(z)=\frac{1}{2\pi i}\int_{\partial D}\frac{f(\xi)}{\xi-z}d\xi$$
where $f(z)$ is analytic in $D$ and continuous in $\bar{D}$. Note that
$$ |1+\cos t+i\sin t|^2=2(1+\cos t).$$
So
\begin{eqnarray}
&&\int_{0}^\pi\log(1+\cos t)\; dt\\
&=&\frac12\int_{0}^{2\pi}\log(1+\cos t)\; dt\\
&=&\frac12\int_{0}^{2\pi}\log|1+\cos t+i\sin t|\; dt-\pi\log2\\
&=&\frac12\int_{0}^{2\pi}\Re\left[\log(1+\cos t+i\sin t)\right]\; dt-\pi\log2\\
&=&\frac12\Re\left[\int_{0}^{2\pi}\log(1+\cos t+i\sin t)\; dt\right]-\pi\log2\\
&=&\frac12\Re\left[\int_{|z|=1}\log(1+z)\; \frac{dz}{iz}\right]-\pi\log2\\
&=&\frac12\times2\pi \log 1-\pi\log2\\
&=&-\pi\log2.
\end{eqnarray}
Answer: Using Fourier Series
As shown in this answer,
$$
\log(1+\cos(x))=2\sum_{k=1}^\infty(-1)^{k-1}\frac{\cos(kx)}{k}-\log(2)\tag{1}
$$
For all $k\in\mathbb{Z}\setminus\{0\}$
$$
\int_0^\pi\cos(kx)\,\mathrm{d}x=0\tag{2}
$$
Therefore,
$$
\int_0^\pi\log(1+\cos(x))\,\mathrm{d}x=-\pi\log(2)\tag{3}
$$

A More Elementary Approach
$$
\begin{align}
\int_0^\pi\log(1+\cos(x))\,\mathrm{d}x
&=\int_0^\pi\log\left(2\cos^2\left(\frac x2\right)\right)\,\mathrm{d}x\\
&=\pi\log(2)+\int_0^\pi\log\left(\cos^2\left(\frac x2\right)\right)\,\mathrm{d}x\\
&=\pi\log(2)+2\int_0^{\pi/2}\log\left(\cos^2(x)\right)\,\mathrm{d}x\tag{4}
\end{align}
$$
and
$$
\begin{align}
\int_0^\pi\log(1-\cos(x))\,\mathrm{d}x
&=\int_0^\pi\log\left(2\sin^2\left(\frac x2\right)\right)\,\mathrm{d}x\\
&=\pi\log(2)+\int_0^\pi\log\left(\sin^2\left(\frac x2\right)\right)\,\mathrm{d}x\\
&=\pi\log(2)+2\int_0^{\pi/2}\log\left(\sin^2(x)\right)\,\mathrm{d}x\tag{5}
\end{align}
$$
By substituting $x\mapsto\pi-x$, we see that the left side of $(4)$ equals the left side of $(5)$. Therefore,
$$
\begin{align}
2\int_0^\pi\log(1+\cos(x))\,\mathrm{d}x
&=\int_0^\pi\log(1+\cos(x))\,\mathrm{d}x+\int_0^\pi\log(1-\cos(x))\,\mathrm{d}x\tag{6}\\
&=\int_0^\pi\log\left(\sin^2(x)\right)\,\mathrm{d}x\tag{7}\\
&=2\int_0^\pi\log(1-\cos(x))\,\mathrm{d}x\tag{8}\\
&=2\pi\log(2)+4\int_0^{\pi/2}\log\left(\sin^2(x)\right)\,\mathrm{d}x\tag{9}\\
&=2\pi\log(2)+2\int_0^\pi\log\left(\sin^2(x)\right)\,\mathrm{d}x\tag{10}\\
&=-2\pi\log(2)\tag{11}
\end{align}
$$
Explanation:
$\phantom{1}(6)$: the left side of $(4)$ equals the left side of $(5)$
$\phantom{1}(7)$: add the integrands
$\phantom{1}(8)$: twice the left side of $(4)$ equals twice the left side of $(5)$
$\phantom{1}(9)$: apply $(5)$
$(10)$: $\sin(x)=\sin(\pi-x)$
$(11)$: $2$ times $(7)$ minus $(10)$
Thus, dividing $(11)$ by $2$, we get
$$
\int_0^\pi\log(1+\cos(x))\,\mathrm{d}x=-\pi\log(2)\tag{12}
$$
Answer: Notice, $$\color{blue}{\int_{0}^\pi\log(1+\cos x)\ dx}=2\int_{0}^{\pi/2}\log(1+\cos 2x)\ dx=2\int_{0}^{\pi/2}\log\left(2\cos^2 x\right)\ dx$$$$=4\int_{0}^{\pi/2}\log\left(\cos x\right)\ dx+2\log2\int_0^{\pi/2}\ dx$$ $$=4\color{red}{I}+\pi\log2\tag 1$$
Where, $$\color{red}{I}=\int_{0}^{\pi/2}\log\left(\cos x\right)\ dx\tag 2$$
$$I=\int_{0}^{\pi/2}\log\left(\sin \left(\frac \pi2-x\right)\right)\ dx=\int_{0}^{\pi/2}\log\left(\sin x\right)\ dx\tag 3$$
Adding (2) & (3), one should get
$$2I=\int_{0}^{\pi/2}\log\left(\sin x\cos x\right)\ dx=\int_{0}^{\pi/2}\log\left(\frac{\sin 2x}{2}\right)\ dx=\int_{0}^{\pi/2}\log\left(\sin 2x\right)\ dx-\frac{\pi}{2}\log 2$$
$$2I=\frac{1}{2}\int_{0}^{\pi}\log\left(\sin x\right)\ dx-\frac{\pi}{2}\log 2=\frac{2}{2}\int_{0}^{\pi/2}\log\left(\sin x\right)\ dx-\frac{\pi}{2}\log 2=I-\frac{\pi}{2}\log 2$$
$$\color{red}{I=-\frac{\pi}{2}\log 2}$$, now setting the value of $I$ in (1), one should get
$$\color{blue}{\int_{0}^\pi\log(1+\cos x)\ dx}=4\left(-\frac{\pi}{2}\log 2\right)+\pi\log 2=\color{blue}{-\pi\log 2}$$


uniform and free ultrafilter

Question: I saw two definition for uniform ultrafilter:
For $\kappa$ an infinite cardinal number, an ultrafilter $\mathscr{F}$ over $\kappa$ is called uniform if |F| = $\kappa$ for all $F \in  \mathscr{F}$.
A ultrafilter $\mathscr{F}$ on $X$is called uniform if $|F|=  |X|$ for all $F \in  \mathscr{F}$.
so,

Is  defined the uniform ultrafilter on only infinite set?
Are equal uniform and free ultrafilters on  infinite set?
Comment: This seems to be almost an exact duplicate: http://math.stackexchange.com/questions/508819/free-and-uniform-ultrafilter/508845#508845
Answer: An ultrafilter could be defined on a finite set. However, it is of no interest, since it is of necessity principal. Uniform ultrafilters on a finite set are even less interesting, for the underlying set of such an ultrafilter would have to be a $1$-element set.
A free ultrafilter need not be uniform. For example, let $U$ be a free ultrafilter on $\mathbb{N}$.  Define $U'$ on $\mathbb{R}$ by saying that $X\in U'$ if and only if $X\cap \mathbb{N}\in U$. It is not hard to verify that $U'$ is a free ultrafilter on $\mathbb{R}$. But both $\mathbb{N}$ and $\mathbb{R}$ are in $U'$, so $U'$ is not uniform.
The two definitions you quote are roughly equivalent. The first is on a cardinal number, the second on a general set. But (with AC) for any set there is a bijection between the set and some cardinal.  In certain situations, we may be interested in, say, the interaction between an ultrafilter on $\mathbb{N}$ and arithmetic progressions. In that case, structure on the underlying set, and not just cardinality, may be relevant.

uniform and free ultrafilter


Space requirements when running rsync

Question: I have two partitions, /disk1 and /disk2, each with 100GB of space, and both of them are 45% full now.
I want to rsync /disk1 to /disk2/backup/, is it safe to use rsync for this purpose?
rsync -avc /disk1 /disk2/backup/

e.g. How much temp space are required for the above command? How to estimate?
Answer: You can always run rsync in dry-run mode, that will tell you the total size of the files transferred and more.
rsync --dry-run -avc /disk1 /disk2/backup/

Comment: Hi, my concern would be the temp file size created during the transfer, not the total size of transfer itself..
Comment: Rsync works in-place. There are (nearly) no temporary files.
Comment: my understanding is rsync will only update the file in an atomic fashion when the transfer is completed, so there must be temp file in the receiver side, right?

Space requirements when running rsync


How to check if file has changed during (hook) form_validate in a form?

Question: I have a custom content type, and the relative form for creating/editing contents. It contains a file field. I need to check, during hook
<code> function mymodule_myform_form_validate($form, $form_state){...}
</code>
if the user changed the file with another (while editing the content). This can be done by checking if the fid has changed, and the fid of the new file can be found, for example, in
<code> $lang_field = $form['my_field']['#language'];
 $file_fid = $form_state['input']['my_field'][$lang_field][0];
</code>
but what about the fid of the old file? Exploring form and form_state array i found several occurrences of the old and the new fid, but i am not sure which i'm supposed to use. I am not even certain that the code above is the correct one for retrieving the fid of the new file... There is a standard (safe) way to retrieve these informations?
Answer: There are 2 approach we can look into:

Query the DB using db_query in field table, like if your field machine name is field_image, then its field will be field_data_field_image, and get fid of a particular node, in this case fid will be in field_image_fid
SELECT field_image_fid from field_data_field_image WHERE entity_id=NODE_ID

It will get u previous fid, and u can validate

Load Node from nid, either using node_load or entity_load_single, from here you will get your Old FID, as image has not yet been attached to the node, it has only been saved in file_managed Table.
Comment: Yes, if it is previously there, then loading node or fetching data will be resource wasting..
Comment: not a bad idea, but i saw that the informations i need are already in either of the two arrays, so it would be less resource-wasting taking them directly... isn't?
Answer: Finally i found an explanation of the form_state array here
form_state
Unfortunately is not so complete... better than nothing.
To get the fid of the new file i did
<code>$lang_field_package = $form['my_field']['#language'];
$fid_new = $form_state['values']['my_field'][$lang_field_package][0]['fid'];
</code>

values: An associative array of values submitted to the form. The
  validation functions and submit functions use this array for nearly
  all their decision making. (Note that #tree determines whether the
  values are a flat array or an array whose structure parallels the
  $form array. See Form API reference for more information.) These are
  raw and unvalidated, so should not be used without a thorough
  understanding of security implications. In almost all cases, code
  should use the data in the 'values' array exclusively. The most common
  use of this key is for multi-step forms that need to clear some of the
  user input when setting 'rebuild'. The values correspond to $_POST or
  $_GET, depending on the 'method' chosen.

This has proven safer than 'input'. Using 'input', when the user chose a file without pressing the 'upload' button beside the file field, the fid was retrieved as zero instead of the chosen file fid, while in 'values' the fid was correct. It does make sense, but, whether you press upload or not, the file would be load on submit, so i required the right fid anyway.
To get the fid of the old file i did
<code>$lang_field_package = $form['my_field']['#language'];
if (!empty($form_state['build_info']['args'][0]->my_field)) {
  $fid_old = $form_state['build_info']['args'][0]->my_field[$lang_field_package][0]['fid'];
}
</code>

build_info: Internal. An associative array of information stored by
  Form API that is necessary to build and rebuild the form from cache
  when the original context may no longer be available:
  args: A list of
  arguments to pass to the form constructor.
Comment: For me: $form_state->getValue('my_field')[0]['fids'] did work. That gives you an array with the uploaded file ID(s).


How can I encourage a soloist to play louder?

Question: In the training band I conduct, we sometimes choose pieces that focus on one player as a soloist. Many of the players have no previous experience of playing in public. Often, the children's natural shyness takes over, and they play more quietly to blend into the ensemble.
I already keep reminding the soloist to play out, and the band to play quietly, making sure they can hear the soloist. But what else can I do to encourage my soloists to belt it out more?
Answer: Generally, there are two factors that contribute to quiet playing:
1.) They are insecure with their part - not comfortable physically playing the music.  For children, it is often because they don't practice enough.  For older kids and adults, it's often because they don't practice enough. :)
2.) Social psychology: by playing as a soloist they are excluding themselves from "the group" and so because they are different they are afraid of being judged or made fun of. As a soloist, there's nowhere to hide and if you feel insecure about your playing, then playing in front of others can be terrifying.
Solutions:
1.) Make sure (to the best of your ability) that each student is as comfortable with their part as possible - encouraging them to come to you after school if necessary.  If they feel like they know their part, it will go a long way toward building confidence when it comes time to perform.
2.) Make sure that you have a gentle, supportive rehearsal environment.  It is important for the kids to know that they won't be judged or made fun of if they mess up or make a funny noise by accident.  Here are a few ideas as to how you could go about creating that dynamic:

Tell the students directly: "This is a good class and we need to support one another - playing solos are hard! Congratulate each other on a job well done!"
Let them know teasing about it won't be tolerated - punishing students if necessary.
If they make mistakes (and they will) talk about the importance of over-coming them and moving on, not focusing on them.
Add humor. If the students think of what they're doing as fun rather than scary and high-pressure, they'll be more comfortable and more likely to play out.
Be the example. Equalize a situation by making even goofier sounds than they make on their instrument. If they honk on their instrument, make a goofy sound while singing a part to them in rehearsal. If they see how successfully you handle your own mistakes, they'll use that information to handle their own mistakes.
Use imagery. Using goofy imagery is a great way to get them to focus on something. For example, tell them that they're in a giant arena of stuffed animals and the animals in the back of the arena have to hear the solo. Using imagery allows them to pretend and take the focus off "okay, this is my big solo now."

By and large though, preparedness with parts will take care many, many problems by itself.
Hope that helps.
Answer: Stop your band.
Ask your soloist to play a note as loud as they possibly can.  Any note. Loudissimo...none more loud!
Give your snare drummer a copy of the soloist's music.  Ask the snare drum and the soloist to play the first phrase together.  Tell the soloist that the "game" is whoever plays louder, snare or soloist, wins. three tries. The rest of the band "votes" on the winner, and the soloist wins on a tie!
Then run the section down again, whole band.


Export Data-Tier Application with Data (bacpac) from a database that contains encrypted objects

Question: I have a SQL Server 2012 Database project that I have been working on for deployment of our database.  The dacpac deployments are working great but I have run into a roadblock when it comes to deploying data along with the schema.
My plan was to have a local copy of the database that contains all of the default data so that I could deploy the dacpac to that database then export a bacpac that contains the latest schema as well as the default data set for deployment to remote sites.
However, we have a handful of objects in the database that are encrypted and the bacpac export fails on those objects.  Is there a way to export a bacpac from a database that contains encrypted objects or how might you recommend addressing this issue?
Edit: I am also running into issues with objects that reference system databases such as Master and MSDB if you have any suggestions for that.
Answer: I think that export encrypted object as data-tier application is not possible for now.
As for system databases references you need to go to the Solution->Project->Reference->Add Database Reference (see screenshot below)

and add reference to the system database msdb (or master).
Comment: Thanks for taking the time to respond.  Unfortunately this doesn't resolve my issue.  I've got those references in the database project just like what you are showing and that works just fine.  I can deploy the dacpac without issue.

The problem occurs when I go to the database that I deployed to (the database that contains my default data set) and I try to export a bacpac from there.

It doesn't appear to have an option that allows me to provide a decryption key for my encrypted objects or to specify external database references.  The export fails with errors on both of these items.
Answer: Thanks for this question.  I have the same issue, though three days ago, I was exporting encrypted objects without an issue locally and now I'm running into this error.
My work-around has been to create a copy of the database, drop the encrypted objects of the database copy, then export that (I need the data).  However, I do not know of a work-around to extract all the objects, including the encrypted objects.


Responsive fixed-width image showcase without JS

Question: I'd like to create simple responsive website containing a showcase of pictures. By myself, but if there's a template, no problem. But I want to learn it anyway.
Requirements:

images with one width no matter the browser width
images always in the middle of the page (0 auto)
number of columns - images changing with the browser width
no height limitation of the image. only fixed width (+ keep aspect ratio).
perfect example: www.kristianhammerstad.com - try to resize the window, I'd like to achieve exactly this. Works also on mobile browser (shows image after image)
I'd prefer without JS, only media queries - possible?

Here's what I have so far:

* { margin: 0; padding: 0; -webkit-font-smoothing: antialiased; font-smoothing: antialiased; }

body { font: normal 14px Helvetica, Arial, sans-serif; line-height: 30px; color: #333; }

.left { float: left; }
.right { float: right; }

.clearfix:before,
.clearfix:after { content: " "; /* 1 */ display: table; /* 2 */ }
.clearfix:after { clear: both; }

hr {
  margin: 0;
  border: 0;
  width: auto;
  border-top: 1px solid #aaaaaa;
  opacity: .25;
  margin: 0 auto;
}

h1 {
    letter-spacing: 2px;
    font-weight: 300;
    text-align: center;
    font-size: 2em;
    line-height: 1.3em;
    color: #333;
}

h2 {
    letter-spacing: 1px;
    font-weight: 300;
    text-align: center;
    font-size: 1em;
    margin-bottom: 60px;
    color: #666;
    text-transform: uppercase;
}

/* ---------------------------------------------------------- */

.wrapper {
    width: 950px; margin: 0 auto;
}

#name {
    margin-top: 50px;
}

/* ---------------------------------------------------------- */

#works {
    margin-top: 50px;
}

#works h2 {
    font-family: Helvetica, Arial, sans-serif;
    letter-spacing: 1px;
    font-weight: 300;
    text-align: left;
    font-size: 1.3em;
    margin-bottom: 10px;
    color: #666;
    text-transform: none;
}

#work-one {
    display: block;
    width: 460px;
    height: 500px;
    margin-right: 30px;
    margin-bottom: 30px;
}

#work-two {
    display: block;
    width: 460px;
    height: 300px;
}

#work-three {
    display: block;
    width: 460px;
    height: 700px;
    margin-bottom: 30px;
}

#work-four {
    display: block;
    width: 460px;
    height: 200px;
}

/* ---------------------------------------------------------- */

@media (min-width: 768px) and (max-width: 1024px) {

/* I am not sure about break points */

}

@media only screen and (min-width: 320px) and (max-width: 767px) {

/* I am not sure about content here */

}

IMAGES

showcase

Comment: Have you tried to start doing it? Show some code! You can start with bootstrap... http://getbootstrap.com/
Comment: What's the best service to show you my results? https://jsfiddle.net?
Comment: Okay, I found codepen. Here, very basic and "fixed" code: http://codepen.io/Kiks/pen/EKBKpK - always two columns, done manualy, very not smart, I realize.
Comment: have you tried this link? http://masonry.desandro.com/
Comment: @user2517200, thanks. only this could be useful http://www.kristianhammerstad.com (but images always in the middles and without "Bio text" - but what now, should I go through all their code? Looks too much, or this is the way of learning?
Comment: Hi @Kiks, have a look in this code (http://codepen.io/desandro/pen/bdgRzg)  and try to improve the way you like on the mansory.desandro.com documentation.
Comment: I saw that approach in many templates, but I need no image resizing as the browser windows gets more narrow. I don't know how to keep image size the same no matter what and use all available width with filling in as many colmns as possible.
Comment: @Kiks if you go with no resize, the layout will not be responsive, in responsive layout they are fluid and will resize depends on screensize
Comment: You might be right about terminology, thanks :)
Comment: I copied code to try one of the examples you, @user2517200, showed me - http://codepen.io/Kiks/pen/BKgzGy - but why images behave differently? There are in exact rows, not like "tetris", they don't have margins. Why? The same code. Even if I try it with all three JS files
Comment: I even tried "clean" Masonry, here http://codepen.io/desandro/pen/osFxj, but there's still this unwanted effect (empty spaces), see http://jmp.sh/kJuDbIL
Comment: Looks like disabled JS to me, or at least some errors due to them the masonry magic is not applied. Look in your console for errors.
Comment: @Seika85 thanks. probably you're right, I noticed small icon my chrome is constantly showing me: "js was blocked on this site" but in the settings everything is allowed. I'll reinstall it...
Comment: @Seika85 please, see my latest comment after your answer.
Answer: First of all it would recommend using a grid system. One common known and used would be bootstrap.
With it you can easily set your wanted layout.
Second, to achieve this "repositioning" effect, you would need a JS library called masonry. It hooks itself in the resize event as well as initially on initialization of the dom.
There it calculates the width of the container wrapping all images and the width of the images, calculates the new positions using complex algorithms, and reposition them using the animation effect you see.
Maybe this tutorial (with source) will help you further: http://creative-punch.net/2014/01/full-screen-image-gallery-using-css-masonry/
Comment: Thank you @Seika85 and everyone. I'm fighting with this Bootstrap but there's still a problem. I want my images to always have fixed width (no matter the browser width - exactly like pajc.sk). But the Bootstrap Grid is resizing the images all the time. How can I achieve pajc sk or kristianhammerstad.com layout? This is that I have so far: http://codepen.io/Kiks/pen/vGoBEG - you can see I set wider container and there are manually set 4 cols. But what if I'll need only 3, 2, you know the story. Any help what I'm missing? First I'd like to set the layout, later apply masonry magic
Comment: Maybe I do not need a Bootstrap Grid for this. What do you think, @Seika85?
Comment: Look, I think I moved forward a bit http://codepen.io/Kiks/pen/NNQKXz (without usage of Bootstrap Grid)
Comment: Okay, I think this is what I wanted in my life http://codepen.io/Kiks/pen/NNQKXz Until now. Thanks everyone, you helped me a lot!
Comment: Well, images (.item) are our of the viewport when checking the website on the phone (ios). Next challenge ahead of me...
Comment: I checked your latest codepen with my phone (android) and Chrome's *device mode*, I couldn't reproduce your stated issue. All is aligned fine here. Maybe your viewport isn't set up correctly (``)?
Comment: I progressed to the next problem with masonry (JS). If you'd have time, here's the thread https://stackoverflow.com/questions/37444559/loading-images-while-using-masonry-imageloaded Thank you.


split a file based on string

Question: I am trying to split one big file into individual entries. Each entry ends with the character "//". So when I try to use
#!/usr/bin/python
import sys,os
uniprotFile=open("UNIPROT-data.txt") #read original alignment file
uniprotFileContent=uniprotFile.read()
uniprotFileList=uniprotFileContent.split("//")
for items in uniprotFileList:
        seqInfoFile=open('%s.dat'%items[5:14],'w')
        seqInfoFile.write(str(items))

But I realised that there is another string with "//"(http://www.uniprot.org/terms)
hence it splits there as well and eventually I don't get the result I want. I tried using regex but was not abler to figure it out.
Comment: Do you mean forward (/) or backward (\) slash? You use both, confusing.
Comment: This in inconsistent you say 1) ends with the character "\" and 2)  another string with "//" - what is the issue as these are different
Comment: Does it end with \ or //? You say one and show the other.
Answer: Use a regex that only splits on // if it's not preceded by :
import re
myre = re.compile("(?<!:)//")
uniprotFileList = myre.split(uniprotFileContent)

Comment: @shabana: You should *accept* this answer by checking it on the left.
Comment: When i run above code, I get 54 (18*3) items in the list rather than 18. It is not affecting my output as it is overwriting the files but I think it would be good to address the problem. Any suggestions?
Comment: Can you elaborate? Are there empty entries or duplicate entries in the list or something else? Without knowing your data, it's hard to make a suggestion.
Comment: These are the duplicates. So I am using set command to get rid of the duplicates uniprotFileList=list(set(uniprotFileList)). But I am not sure why I am getting these duplicates.
Comment: Can you post a data sample (edit your question, paste it there, select it and press Ctrl-K)? You shouldn't be getting duplicates from `split` unless they already are duplicate in your input.
Comment: Yes, there were duplicates in the file. I should have been more intelligent. But I do get an empty string as an element of list when I split the file. I did check for blank line at the end of the file but there is none. Thanks much!
Comment: Well, if the string ends in `//`, then `split()` returns an empty string as the last element (which is the correct behavior). So you might need to adjust for that case.
Answer: I am using the code with modified split pattern and it works fine for me:
#!/usr/bin/python
import sys,os
uniprotFile = open("UNIPROT-data.txt")
uniprotFileContent = uniprotFile.read()
uniprotFileList = uniprotFileContent.split("//\n")
for items in uniprotFileList:
    seqInfoFile = open('%s.dat' % items[5:17], 'w')
    seqInfoFile.write(str(items))

Answer: You're confusing \ (backslash) and / (slash). You don't need to escape a slash, just use "/". For a backslash, you do need to escape it, so use "\\".
Secondly, if you split with a backslash it will not split on a slash or vice-versa.
Answer: Split using a regular exception that doesn't permit the "http:" part before your // marker.
For example: "([^:])\/\/"
Comment: That will include the character before `//` in the split, removing it from the string.
Answer: You appear to be splitting on the wrong characters. Based on your question, you should split on r"\", not "//". Open a prompt and inspect the strings you're using. You'll see something like:
>>> "\\"
'\\'
>>> "\"
SyntaxError
>>> r"\"
'\\'
>>> "//"
'//'

So, you can use "\" or r"\" (I recommend r"\" for clarity in splitting and regex operations.
Comment: I am sorry it is the forward slash ("\\").

split a file based on string


How to use existing Intellij projects as a I move forward with SBT?

Question: Novice SBT question - Now that I've started with some basic SBT tutorials, I'd like to start using SBT build files (within Intellij) a lot more often. However, there's a couple of problems with this :
1) Existing projects that I currently publish to a jar, and later import into other projects... how do I publish this jar file to my local repository? SBT publish-local doesn't seem to fit my situation, because the project was made in Intellij and is not (yet) an SBT project.
2) Suppose I do convert the project to an SBT build setup (and then import it into Intellij).. how do I configure Intellij to to publish-local (update) each time I build the project? I do not see many configurable settings around SBT within the new Intellij SBT support.
Using Intellij 13 and SBT 0.13.1
Thanks!
Answer: to get you started up quickly on using SBT to drive Idea, have a look at my template project called skeleton
It supports most of the basic tasks you'd want to do.
To publish to your repository, use the publish task.
hope that helps!
Comment: Thanks for the link, I'll give your project a try!
Answer: For publishing, you simply use the publish action:
To specify the repository, assign a repository to publishTo and optionally set the publishing style. For example, to upload to Nexus:
<code>publishTo := Some("Sonatype Snapshots Nexus" at "https://oss.sonatype.org/content/repositories/snapshots")
</code>
As for your second question, despite being a JetBrains fanboy, I have found SBT integration quite disappointing. For one thing, as the JetBrains documentation states itself, you need two plugins: their plugin and sbt-idea. You use sbt-idea to synchronize the IDEA module structure with the SBT build, and you use JetBrains' idea-sbt-plugin to execute SBT tasks in the "Before Launch" action in Run Configurations.
It sounds like you want to do an "install" on every build, so "Before Launch" action support isn't useful. I would suggest writing your own custom SBT task to install on build and using the Command Line Tools Console to execute that task with SBT as if from the command line. I know; that indirection is annoying.
Bear in mind one more thing. I have found numerous bugs with idea-sbt-plugin. At least on Mac. JetBrains told me the next version will be much better, and you can see for yourself with the next EAP version.
I certainly welcome others who have managed to have more success than I have to chime in.
Comment: The `publishM2` task publishes to the local Maven repo. The `publishLocal` task publishes to the local Ivy repo. As I said, if I were to execute either via IntelliJ, I would do it through the Command Line Tools plugin because I don't think the robust support is there for SBT. Again, this has just been my experience. If you or anyone else can get everything working great with the SBT plugin proper, please tweet me.
Comment: Thanks this is great info! Im still not entirely sure how to publish-local , from within Intellij..


Checking the periodicity of a signal

Question: We're given this signal:
$X_a(t) = x(t)\cdot rect(\frac{t}{100})$, where $x(t) = cos(3t)$
And we have to check if it's periodic or not, and find the period if it is.
Now, for $cos(3t)$, the period $T_A$ is $\frac{2π}{ω_1} = \frac{2π}{3}$.
For $rect(\frac{t}{100})$, we can use Fourier transformation to get $100sinc(100πf)$, if I'm not mistaken.
But then I don't know how to continue. What do i do from here?
Answer: If your rect function is defined as
$$\operatorname{rect}(t) =
\begin{cases}
 0, & \text{if } |t| > \frac{1}{2} \\
 \frac{1}{2}, & \text{if } |t| = \frac{1}{2} \\
 1, & \text{if } |t| < \frac{1}{2}.
\end{cases}$$
So
$$\operatorname{rect}(\frac{t}{100}) =
\begin{cases}
 0, & \text{if } |t| > 50 \\
 \frac{1}{2}, & \text{if } |t| = 50 \\
 1, & \text{if } |t| < 50.
\end{cases}$$
Then your periodicity is ruined because of this rect function.
Comment: Thank you. Since we're not given an exact definition of the rect function, but we're assuming, is this sufficient as an answer?
Comment: @Ahmad Why suggesting $$rect(t) = \frac{1}{2}, |t| = \frac{1}{2} $$?

Checking the periodicity of a signal


JavaScript and CSS settings fail unexpectedly: The files were not created

Question:
Possible Duplicate:
Drupal Commons site has no style after installation

See the Drupal Commons site running on boysday.org
well how to start. i am new to drupal and I have serious flaws during the installation; Tried it dozens of times.I get warnings about too many files open. Somebody gave me the advice to do the adjustments in the administrative section (admin/settings/performance).
On "Bandwidth optimizations,"  the option "Optimize CSS files" and "Optimize JavaSript files" were enabled. I have tried to switch off; for testing and customize my Drupal Commons install it's better to disable as to have CSS and JavaScript development support with tools like "Firebug" using Firefox.
I tried to do so, and got back a very interesting message.

Performance
The file could not be created.
  The file could not be created.

Can this be caused by the fact the folders in /home/vhost/WWW/mysite/sites/default/files were all owned by the wwwrun user? What can I do?
There are no pictures, and no CSS. Is there any right or permission problem?

warning: array_map() [function.array-map]: Argument #2 should be an array in /home/vhost/WWW/mysite/modules/system/system.module on line 1020.
  warning: array_keys() expects parameter 1 to be array, null given in /home/vhost/WWW/mysite/includes/theme.inc on line 1832.
  warning: Invalid argument supplied for foreach() in /home/vhost/WWW/mysite/includes/theme.inc on line 1832.
Comment: @MPD A question is a duplicated if it is asking the same thing asked in another question; the fact the question is asked by another user doesn't matter.
Comment: But OP is different account?
Comment: hello FR6 hello MPD - hello kiamlauno. Thx for he answer and the comments. well i have serious troubles on all the server. I guess that i have to upgrad the server to apache 2.2 - the old server-horse apache 1.3. is ment to be depriciated! well what do you suggest!?
Comment: @zero, is this the same problem/question as FVR linked to above?  The original version of the question was for the same website.
Comment: @kiamlaluno Yes, potential duplicate, but I would not say they were exact dups.  The OP should at least have the chance to address whether it was a duplicate and delete it themselves.
Comment: @MPD In this case, the question is a duplicate because both the questions are referring to Drupal Commons, and in both the cases the issue the files not being created. FR6 doesn't have the privilege of voting to close, and he added a comment, but he is right about the question being a duplicate; he just started the comment with "possible duplicate" because he saw the automatic comments generated when the first user votes to close a question.
Comment: The fact the user linked to the same site seems a little suspicious; it could be both the users maintain the same site, but I don't see any reason for asking a question when another maintainer already asked it. That is not what makes the difference between a duplicate question and a not duplicate question, but it is a good catch from your side. Why did the OP refer to the same site? Does that mean the OP was aware of the other question? Is the OP asking a question because a real problem, or did he simply copy another question?
Comment: hello dear moderators: you do a very well job here - and have all my respect. i am the guy who is in trouble and does not know how to solve the issues
i am new to drupal and to this forum here. For Account-Creation i was asked to sign in with stack-exchange/overflow-account. The first login was yesterday from office - As i logged me in today (at home) with that way i saw that i have somewhat like two identities. That is not what is wanted. To be frank-i love stackexchange, but i am a novice regarding the technique that is used here. The user-managenemt is very clever,a bit too clever for me.
Comment: but back to drupal: i have very very much issues with drupal and i do not know how to solve.plz plz dont bear with me! I have a dedicated server and i try to find out if i have to drop this server - since it is too old and to weak to cope with drupal.
Therfore i do some test-installations (on diffferent domains), Each time i install i do some little shift in the configuration - in
oder to find out where this damned problem origins.. where it is rootet.
Comment: Conclusion: so you are right - i am the poor guy  who can t go ahead and who has the (allmost same) issues on different trials of intallation.
but for now: i do not post new questions with similar content - but i am going to work out all the answers and try to solve the issue.

And last but not least - i try to learn more about the stack-user-account-principles that are some what like a mystic thing to me.
Answer: As you already suggested, this is most likely a file permission problem. Make sure the entire directory under sites\default\files is writable by the apache user, often this is called www-data.
To get you going maybe download XAMPP for your platform and get your first Drupal installation working locally.


Pesquisa mysql com apenas um dos campos selecionados

Question: estou com uma dúvida sobre como organizar essa informação, eu tenho dois selects no meu código, que ao usuário escolher os dois ele, gera a tabela buscando quem tem as duas informações, porém eu gostaria que a pesquisa fosse feita mesmo se o usuário selecionar apenas um dos dois campos
Esse é o código do request
if($_SERVER['REQUEST_METHOD']=='POST'){
            $id_categoria = $_POST['id_categoria'];
            $id_sub_categoria = $_POST['id_sub_categoria'];
            $pagina = 1;
            $_SESSION['id_categoria'] = $id_categoria;
            $_SESSION['id_sub_categoria'] = $id_sub_categoria;

E no caso esse é query executada
                    $result_empresas = "SELECT *
                                FROM clientes
                                WHERE (categoria_id = '$id_categoria' OR '$id_categoria' IS NULL) AND
                                ( subcategoria_id = '$id_sub_categoria' OR '$id_sub_categoria' IS NULL) AND
                                ('$id_sub_categoria' IS NOT NULL OR '$id_categoria' IS NOT NULL)
                                 LIMIT $inicio, $qnt_result_pg";

Agradeço a todos que puderem ajudar.
Answer: $result_empresas = "SELECT * FROM clientes WHERE
                   (categoria_id = '$id_categoria' OR '$id_categoria' = NULL) AND
                   (subcategoria_id = '$id_sub_categoria' OR '$id_sub_categoria' = NULL)
                   LIMIT $inicio, $qnt_result_pg";

Suponho que apenas isso deva funcionar, caso não funcione com NULL, use ''.
$result_empresas = "SELECT * FROM clientes WHERE
                   (categoria_id = '$id_categoria' OR '$id_categoria' = '') AND
                   (subcategoria_id = '$id_sub_categoria' OR '$id_sub_categoria' = '')
                   LIMIT $inicio, $qnt_result_pg";

Comment: Não funcionou nesse caso, se eu seleciono apenas um dos seletcs, ele não gera a tabela
Comment: Tenta do segundo jeito q coloquei no exemplo


After Artifactory upgrade to 5.10.2, remote repo connections fail with Proxy Error 407

Question: We have updated our Artifactory from 5.2.0 to 5.10.2.
Since that, all remote repository test connection failed with Proxy error 407.
The proxy is correctly set in Admin section, the Proxy has been set for all repo.
login/password are valid.
There's no log error except this one :
<code>20180419151212|30|REQUEST|172.22.50.135|usertst|POST|/ui/admin/repositories/testremote|HTTP/1.1|400|1610
</code>
Unfortunately I can't bypass the proxy.
It used to work so I don't understand why it doesn't work anymore since the update.
Answer: This is a bug that has been reported. You may want to vote & watch the JIRA for updates.


Can I use PerCall instancing and Reentrant concurrency in the same service?

Question: I've been studying the instancing and concurrency modes in WCF and I'm trying to understand if there is any case where it makes sense to use PerCall instancing and Reentrant concurrency. In the following MSDN link it is stated that "in PerCall instancing, concurrency is not relevant".

The use of concurrency is related to the instancing mode. In PerCall instancing, concurrency is not relevant, because each message is processed by a new InstanceContext and, therefore, never more than one thread is active in the InstanceContext.

However, I think there might be a case where these two modes (PerCall and Reentrant) must be used in conjunction. Please correct me and/or give me any input on this. Consider the following scenario:
Service A uses a Duplex MEP. Service A exposes an operation contract which returns an object (i.e, it is NOT a one way operation). The service's callback contract also exposes an operation contract which returns an object (i.e, it is NOT a one way operation). The service endpoint uses a wsDualHttp Binding.
The operation contract implementation calls the client's callback before returning. In this scenario, if I set the ConcurrencyMode to Single, a Deadlock will occur, whether if I set the ConcurrencyMode to Reentrant everything works as expected.
So, why is Microsoft saying that concurrency is not relevant in a PerCall mode?
Answer: Concurrency is bound to how many threads are accessing an Instance of the service (InstanceContext).
In percall instancing, every call creates a new instance of the service and its related resources as in ASP.Net. When the call is over, this instance would not be valid. More over, this instance would not be accessible by any other thread, even from the same session.
So that's the reason for the statement, "in PerCall instancing, concurrency is not relevant".
Regarding your scenario, in Duplex MEP, let's say A is the client and B is the service.
When A calls B, an instance of Service is created. In duplex MEP the response has to happen through a different channel (callback channel), and the execution has to jump to a different instance (client instance which you set during the proxy creation) for execution. After completing this, it has to jump back to the original service instance and continue from where it left.
So in order for a duplex MEP to be successful, it needs to keep the original service's instance alive and re-enterable, when it jumps over to the callback channel for execution. With percall instancing, this is not be possible.
That's the reason duplex channel is looking for Reentrant/Multiple concurrency and PerSession InstanceContextMode
Also note that when you don't specify the instance context mode, the default it PerSession.
Comment: Hi, thanks for your response. Although I understand you answer, I have a working example of my scenario where I have set the PerCall instancing and Reentrant concurrency and it is working correctly.... So what is happening here??? Thanks.
Answer: In my opinion, the MSDN article is simplifying things. Concurrency mode does play a part in PerCall instancing mode.
Check out this blog post: http://blogs.msdn.com/b/rickrain/archive/2009/06/17/wcf-instancing-concurrency-and-throttling-part-2.aspx.
In the blog, the author had to use ConcurrencyMode.Multiple with PerCall, because using the default 'Single' wouldn't work well when multiple threads make calls to the service using the same proxy object.
In ConcurrencyMode.Single, if the binding uses reliable session then all calls in a channel are queued even for PerCall.
Also, what if you have static variable in the service class? PerCall doesn't make it thread-safe, as implied by the statement 'In PerCall, concurrency is not relevant".


Can Netty send/receive more than 1024 bytes per frame over TCP with SSL?

Question: SOLUTION: Using a ChannelTrafficShapingHandler;
Problem
It appears that my implementation Netty (version 4.1.25Final) cannot send or receive more than 1024 bytes of data per second on average.
Question
Is it possible to send/receive more than 1024 bytes per second using TCP and a SSL? If so, how?
Server Implementation
<code> @Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    SslHandler handler = context.newHandler(ch.alloc());

    handler.setHandshakeTimeoutMillis(20_000);
    handler.setCloseNotifyFlushTimeoutMillis(20_000);
    handler.setCloseNotifyReadTimeoutMillis(20_000);

    pipeline.addLast(handler);
    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 8, 0, 8));
    pipeline.addLast("decoder", new ByteArrayDecoder());
    pipeline.addLast(new LengthFieldPrepender(8));
    pipeline.addLast("encoder", new ByteArrayEncoder());
    pipeline.addLast("handler", new ServerInboundHandler());
}
</code>
Client Implementation
<code>    @Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(context.newHandler(ch.alloc(), "localhost", 1337));
    pipeline.addLast(new LengthFieldBasedFrameDecoder(1024 * 1024, 0, 8, 0, 8));
    pipeline.addLast("decoder", new ByteArrayDecoder());
    pipeline.addLast(new LengthFieldPrepender(8));
    pipeline.addLast("encoder", new ByteArrayEncoder());

    pipeline.addLast(new LoggingHandler(LogLevel.INFO));
    pipeline.addLast("handler", new ClientLoginChannelHandler(application, application.getPacketManager()));
}
</code>
It is worth noting that I have the following enabled;
<code>// Server
.option(ChannelOption.TCP_NODELAY, true)
.option(ChannelOption.SO_KEEPALIVE, true)

// Client
.option(ChannelOption.RCVBUF_ALLOCATOR, new DefaultMaxBytesRecvByteBufAllocator(1024 * 1024, 1024 * 1024))
                .option(ChannelOption.SO_RCVBUF, 1024 * 1024)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
</code>
Comment: So where the solution using the ChannelTrafficShapingHandler?
I had a similar problem I was developing TCP client and the xml that was from the server was cut off on 1024 byte, I was trying to figure out what is wrong, and adding

.option(ChannelOption.RCVBUF_ALLOCATOR, new DefaultMaxBytesRecvByteBufAllocator(1024 * 1024, 1024 * 1024))

helped me, but I'm still curious about ChannelTrafficShapingHandler and how it can help me in this situation.
Thanks.
Answer: Yes it can, you need to accumulate data in channelRead() and invoke read() on channel before return from channelRead(). When there is no more data, your channelReadComplete() will be invoked and there is a moment when you send your accumulated data to your response handler.
Comment: I apologize, the resolve was using a ChannelTrafficShapingHandler which is the intended solution.


GL drawing view clears drawings on rotation

Question: I am making a simple drawing app - I have modified the apple GLPaint example somewhat. The problem is when the user rotates the device, the drawings are cleared. is there a way around this?
I'm also having trouble saving an image representation, if you know about this take a look:
Saving imageRef from GLPaint creates completely black image
Answer: I determined that this was due to layoutSubviews being called which was destroying then creating the frameBuffer. I created a bool that tracked if the frame buffer had been created once and then only destroyed/created the first time. the view was loaded.


Calling web service to web service; Architecture View

Question: An interesting situation has came today as in the past too.
I have two web services. The transaction will be over after those two has done their own jobs. For this discussion I will name these web services as:

RLService
NavService

I cannot combine both services because the service 2 is owned by 3rd party. This 3rd party web service provides me a webmethod that read the xml file stored in that machine, where web service is, and process.
I have two options:

Client to Service**(S)**

Client call my web service, RLService, with xml data.
RLService store xml data to xml file and return the xml file path
Client call Navision web service, NAVService, with xml file path
NAVService return the result as xml path.
Client call my web service, RLService, with xml file path, which returns back with an Object to proceed further.

State Diagram:

Service to Services

Client call my web service, RLService, with xml data.
RLService store xml data to xml file
RLService call Navision web service, NAVService, with xml file path
NAVService return the result as xml path.
RLService, processed returned xml and convert to an Object to proceed further.
Client receive a class Result object.

State Diagram:

Here is how the physical architecture looks like:

I have followed both ways, but what is the right approach and why?
Of course, I know that the second solution is good. But what about patterns and best practices.
Comment: Like I said below, "Option 2" appears to be better.  For the simple reason that it appears to minimize the number of network messages going back and forth.  IMHO...
Comment: PS: 1) "RLService store xml data to xml file".  Q: Why?  Why not just forward it directly to the web service (without writing unnecessary files)?  2) RLService, processed returned xml and convert to an Object to proceed further.  Q: Why?  Why can't the client interpret the XML?  Or JSON?  If you convert it to an "object", it's still going to have to be serialized before you transmit it, then deserialized at the client?  Why not send the data directly, and just have the client deserialize it (once)?
Comment: @FoggyDay 1. NAVService webservice only expose the webmethod with file path to process and I don't own the code of this web service.

2. Because RLService hosted on the same as server as NAVService and RLService can only access the stored result file attached here with. Client is physically located somewhere else.

The only reason why I don't want client to serialize or deserialize is because I want all clients to get the same object and I don't think itis a good idea to send raw Xml that later will be de serialize by each client (manually).
Comment: @FoggyDay to make things bit clearer, I own RLService code, but I don't NAVService. The only reason why I end up making RLService because I don't put adapter against NAVService and expose the way I want it. So It is like an Adapter pattern where RLService is taking my request to do the job the way NAVService wants.
Answer: Q: Which approach is better?
A: The fewer round trips, the better.
A: The more you can do in one call (without making another, separate call), the better.
In other words (all things being equal), it looks like your second design is a LOT better than the first alternative.
IMHO...
Comment: Question was to know more towards patterns and since both services are hosted within same IIS I could not buy that it will boost the performance. Nevertheless, I appreciate your active participation.
Answer: If you put this logic in your service, obviously it decouples the client application from the needed workflow and makes sure the application/business logic is in your business service. In fact, it would be better to keep your client as thin as possible. So solution two would be the preferred solution (for me). You can still decide to make it an asynchronous operation, of course, that depends on your use case.
As a result, any change in logic only impacts your service, not the clients.


Hikari connection pooling + Hibernate 4.3.8 + Spring Data JPA configuration?

Question: please tell me.
How can I configure the "Hikari connection pooling + Hibernate 4.3.8 + Spring Data JPA configuration"?
Here is my configuration, but for some reason I am sure that this configuration is not correct. Because the the console does not appear anything like the "connetction pooling".
On the Internet I can not find the tutorial for the beginner.
Thanks.
<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" p:packagesToScan="com.history"
    p:jpaVendorAdapter-ref="jpaVendorAdapter">
    <property name="jpaProperties" ref="hibernateProperties" />
</bean>

<bean id="jpaVendorAdapter"
    class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
    <property name="showSql" value="true" />
    <property name="generateDdl" value="true" />
    <property name="database" value="ORACLE" />
    <property name="databasePlatform" value="org.hibernate.dialect.OracleDialect" />
</bean>

<util:map id="hibernateProperties">
    <entry key="hibernate.connection.driver_class"
        value="org.hibernate.hikaricp.internal.HikariCPConnectionProvider" />
    <entry key="connection.url" value="${dataSource.url}" />
    <entry key="connection.driver_class" value="${dataSource.driverClassName}" />
    <entry key="connection.username" value="${dataSource.username}" />
    <entry key="connection.password" value="${dataSource.password}" />
    <entry key="hibernate.jdbc.batch_size" value="100" />
    <entry key="hibernate.order_inserts" value="true" />
    <entry key="hibernate.order_updates" value="true" />
</util:map>

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${dataSource.driverClassName}" />
    <property name="url" value="${dataSource.url}" />
    <property name="username" value="${dataSource.username}" />
    <property name="password" value="${dataSource.password}" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
    p:entityManagerFactory-ref="entityManagerFactory">
</bean>

Answer: If you want to use Hikari, you'll need to declare it, so your dataSource config should be
<bean id="dataSource"
    class="com.zaxxer.hikari.HikariDataSource">
    <property name="driverClassName" value="${dataSource.driverClassName}" />
    <property name="jdbcUrl" value="${dataSource.url}" />
    <property name="username" value="${dataSource.username}" />
    <property name="password" value="${dataSource.password}" />
</bean>

Comment: Thanks. Only need to do this? How to configure it? Where can I see all kinds of settings? Something I do not understand. Or do not need to configure anything?
Answer: Your datasource config should be like this:
 <beans:bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"  destroy-method="close">
                <beans:property name="dataSourceClassName" value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"/>
                <beans:property name="maximumPoolSize" value="5" />
                <beans:property name="maxLifetime" value="30000" />
                <beans:property name="idleTimeout" value="30000" />
                <beans:property name="dataSourceProperties">
                          <beans:props>
                              <beans:prop key="url">jdbc:mysql://localhost:3306/exampledb</beans:prop>
                              <beans:prop key="user">root</beans:prop>
                              <beans:prop key="password"></beans:prop>
                               <beans:prop key="prepStmtCacheSize">250</beans:prop>
                               <beans:prop key="prepStmtCacheSqlLimit">2048</beans:prop>
                               <beans:prop key="cachePrepStmts">true</beans:prop>
                               <beans:prop key="useServerPrepStmts">true</beans:prop>
                          </beans:props>
                </beans:property>
</beans:bean>

Complete example with sample project to download can be found in link :
http://frameworkonly.com/hikaricp-connection-pooling-in-spring-hibernate-jpa/
Answer: We can also use it like below in customized JPAConfiguration class where you are establishing connection and creating entity Manager Factory object.
         import com.zaxxer.hikari.HikariConfig;
         import com.zaxxer.hikari.HikariDataSource;

        @Bean
        public DataSource dataSource() {
            // In classpath from spring-boot-starter-web
            final Properties props = new Properties();
            props.put("driverClassName", "com.mysql.jdbc.Driver");
            props.put("jdbcUrl", "jdbc:mysql://localhost:3306/master?createDatabaseIfNotExist=true");
            props.put("username", "root");
            props.put("password", "mysql");
            HikariConfig hc = new HikariConfig(props);
            HikariDataSource ds = new HikariDataSource(hc);
            return ds;
        }


React Native - upload image to Firebase storage

Question: First I create a blob file
  RNFetchBlob.fs.readFile(localImgUrl2, 'base64')
    .then(base64ImageStr => Blob.build('image.png', base64ImageStr, { type: 'image/png;BASE64' }))

......then i try to upload to firebase
    .then((data) => {FBStorageRef.put(data, { contentType: mime })})

...but it gives me the error
Firebase Storage: Object 'profilePics/image.png' does not exist

I believe its my FBStorageRef that it has a beef with.....my cloud storage is totally empty and I want to create a folder called profilePics.......and the file within I want to call image.png
const FBStorageRef = Firebase.storage().ref('/profilePics/image.png');

It says that profilePics/image.png doe not exist which is true enough.....but thats exactly why I want to upload it right :)
Comment: Hey James, I use firebase storage to save images, this way right? I just take a photo URI from the picker and save it to firebase as image ".jpg"!
Comment: Please refer https://medium.com/@davidjsehl/react-native-and-the-infamous-blob-uploading-images-to-firebase-b1a440f9e078
Comment: Yes @hongdevelop Ive read this article - unfortunately does not help......If you compare my code versus the article you will see it is mirrored very closely.  However I have a feeling this issue is only related to uploading images to Firebase.....dont think theres anything wrong with code that uses rn-fetch-blob
Comment: Hello James, did you check the "Rules" section? What do you have as a configuration? Maybe permissions or invalid configuration :)
Comment: I did Yes - rules are set for dev so anyone can read/write
Answer:
If the file path looks like file:///.... You can just simple put it to Firebase function, don't need readFile step.

My code works properly up to now:

  static uploadProfileAvatar(userID, fileURI) { // file URI is a path of a local image
    const updateTime = moment().unix();
    const storagePath = `${PROFILE_AVATAR_PATH}/${userID}_${updateTime}.jpg`;
    const fileMetaData = { contentType: 'image/jpeg' };
    return FirebaseStorage.uploadFile(fileURI, storagePath, fileMetaData);
  }

  static uploadFile(fileURI, storagePath, fileMetaData = null) {
    const uploadTask = firebase.storage().ref().child(storagePath).put(fileURI, fileMetaData);
    return uploadTask;
  }

If you have the path like rct-image-store://0. You have to write it and then get the local path image. After that upload local image as case 1

  ImageStore.getBase64ForTag(
    rctFileURI, // rct-image-store: path
    (base64Image) => {
      const imagePath = `${RNFS.DocumentDirectoryPath}/${new Date().getTime()}.jpg`;
      RNFS.writeFile(imagePath, `${base64Image}`, 'base64')
      .then((success) => {
        // now your file path is imagePath (which is a real path)
        if (success) {
          // upload with imagePath, same as the 1
        }
      })
      .catch(() => {});
    },
    () => {},
  );

Answer: Use RNFirebase for handling firebase storage upload and download. check the below link for more details about installation.
https://github.com/invertase/react-native-firebase/tree/master/packages/storage
then upload a file using below code
 import firebase from 'react-native-firebase';

  export const uploadMediaUri = (uri, path) => {

    return new Promise((resolve, reject) => {
        firebase.storage()
            .ref(path)
            .putFile(uri)
            .then(() => {
                resolve()
            })
            .catch(e => {
                reject(e)
            });
    })
}

Here  uri is the local path that which file you want to upload
and path is the upload path of firebase storage
Comment: Hi Vinayak - this looks promising thanks.....however I installed package as per git instructions (npm install @react-native-firebase/storage --save) then imported with "import rnFb from '@react-native-firebase/storage'";.....but its giving me the error "@react-native-firebase/app/lib.common does not exist in the Haste module map"....can you help?
Comment: Check @react-native-firebase/storage in node_module folder. if it there then restart your metro builder and run again
Comment: Yes - storage file is there....restart doesnt help unfortunately.  Also although there is a "storage" folder there is no "app" folder (which is what the error appears to be complaining about)


Android Convert device coordinate system to "user" coordinate system

Question: My question is similar to Changing sensor coordinate system in android
I want to be able to compare a user's movements with each other regardless of device orientation. So that when the users holds out the phone in portrait orientation and bends his arm, acceleration readings are the same as when he holds out his phone in landscape and then bends his arm in the same direction.
This is what I call the "user" coordinate system. It is different from the world coordinate system since it should not matter what wind direction the user is facing. It is different from device coordinates since it should not matter how the user holds his device.
It is acceptable in my application to do a calibration step before each movement so the base/resting orientation matrices can be determined. Is it perhaps just a matter of multiplying the matrix of the first movement with the inverse of the second (and then with the new values?)
The answer in the question mentioned seems about right, but I need a more concrete explanation, actual code samples would be ideal.
Note remapCoordinateSystem won't suffice, it only accepts right angles. I need to be able to work with small deviations since the device is strapped to a wrist, which might not always be at right angles with the arm.
Answer: I'm currently working on this issue, and I think this might help:
convert device coordinate system to world corrdinate system
We can assume that for the most of the time, people use the phone standing or walking or sitting, which means the user coordinate system share the same z-axis(gravity), and a fixed difference in degree between y-axis (user coordinate, front of user's face) and y-axis(world coordinate, north direction). The difference of degree can be obtained via TYPE_MAGNETIC_FIELD sensor. Thus we can transform from world coordinate to user coordinate.
What's about the user using the phone lying on the bed? I think for that kind of case, a pre-calibration is need by define y-axis of user coordinate, like a movement to tell the phone which direction is the front of user's face.


Como bloquear usuários baseado em sua localização?

Question: Tenho uma aplicação onde usuários tipo A posta informações. Por default esses posts estarão disponíveis para quaisquer usuário na web, em qualquer lugar do mundo.
Mas existe a possibilidade do usuário A restringir o seu post 123 para algumas cidades. Ou seja digamos que o usuárioA proibiu o seu post 123, de estar disponível para pessoas que acessam das cidades de Brasília, Salvador e André da Rocha (pequena cidade do Rio Grande do Sul). Estou usando exemplos aleatórios entre pequenas e médias cidades.
Como implementar tal funcionalidade?
Vamos considerar que todos usuários que irão acessar o sistema não estarão fazendo uso de proxy.
Estou usando php.
Answer: No site do php eles fazem referência a extensão GEOIP.
Com ela você consegue informações detalhadas de um host name ou um Ip.
Veja na documentação aqui.
Ou você pode utilizar dessa api aqui https://ipinfo.io/.
Podendo consultar antes de exibir os posts disponíveis para o usuário
da cidade  em questão, e tomar a decisão de exibir ou não
Ex
<code>$.get("https://ipinfo.io", function(response) {
  console.log(response.ip, response.country);
}, "jsonp")
</code>
Acho que isso atenderia a situação que precisa.

Na comunidade so stack (inglês) já foi feito essa pergunta e tem uma
  boa solução implementada lá, verifique aqui.


Erro biblioteca OSMAR (OpenStreetMap)

Question: Olá,
Estou tentando usar a biblioteca OSMAR no R para plotar rotas e não estou conseguindo.
library(osmar)
library(leaflet)
library(igraph)

src <- osmsource_api()

get_osm(node(18961430), source = src)

Está aparecendo o seguinte erro:
Space required after the Public Identifier
SystemLiteral " or ' expected
SYSTEM or PUBLIC, the URI is missing
Opening and ending tag mismatch: hr line 7 and body
Opening and ending tag mismatch: body line 4 and html
Premature end of data in tag html line 2
Error: 1: Space required after the Public Identifier
2: SystemLiteral " or ' expected
3: SYSTEM or PUBLIC, the URI is missing
4: Opening and ending tag mismatch: hr line 7 and body
5: Opening and ending tag mismatch: body line 4 and html
6: Premature end of data in tag html line 2

Alguém teria uma dica sobre o que esta acontecendo? Pois meu código esta minusculo e o erro foi logo no inicio.
desde já, obrigado
Answer: Este erro é um problema de acesso ao servidor do open street map, onde os dados estão armazenados. Basicamente, o pacote está desatualizado e tenta acessar usando o protocolo http, mas atualmente apenas acessos via https são permitidos. Uma maneira de resolver este problema é declarando explicitamente a url da api utilizando https:
library(osmar)
library(leaflet)
library(igraph)

src <- osmsource_api(url = "https://api.openstreetmap.org/api/0.6/")

get_osm(node(18961430), source = src)
osmar object
1 nodes, 0 ways, 0 relations

Erro biblioteca OSMAR (OpenStreetMap)


Should pam_mkhomedir go in /etc/pam.d/login , sshd or system-auth?

Question: I want to enable pam_mkhomedir.so for users who authenticate to our system. I want a user's home directory to be created when they SSH into the box.
One common convention seems to be to put pam_mkhomedir.so into /etc/pam.d/sshd .
However, could pam_mkhomedir.so actually be placed into /etc/pam.d/login , so that home directories are upon login?
Pretend that I want the home directory to be created when a user logs into the box using sftp, telnet, or another method.
Answer: It seems like you have correctly stated the two options.  You can put any given PAM module in a service-specific configuration (like /etc/pam.d/sshd) or in a common location where it will be used by multiple services.
Which choice you make depends entirely on your local requirements.  Maybe you only want to auto-provision home directories if someone successfully logs in via ssh, but otherwise treat missing home directories as missing (so someone cannot log in via telnet or ftp until they first successfully connect with ssh).
...and of course if ssh is the only mechanism by which people can log in to your system, it doesn't really matter.
That said, I would probably place pam_mkhomedir in a common location.


get Layers list only in SVF2 models?

Question: I have the same nwd model translated two times in Forge.
One in classic SVF, one in SVF2.
If I test with the SVF2 model, everything working fine when I use:
' var root = viewer.impl.getLayersRoot();
The variable root contains a list of all layers
When I test with SVF model the same code:
'  var root = viewer.impl.getLayersRoot();
The variable Root now it's empty.
Why?
There is an official API  to get the list of all layers in SVF  models?
Thank you in advance
Answer: The layers are typically accessed via viewer.model.getData().layersRoot. This is working for SVF as well.
Comment: Maybe I missing something.  If I type in my browser console viewer.model.getData().layersRoot, the result from it is "undefined".  On both the SVF and SVF2 models.
For now I get list of layers only in SVF2 using viewer.impl.getLayersRoot();
I am using the latest viewer available 7.80
Comment: That's strange. In that case I'd suggest that you share your design with us (confidentially) via `forge (dot) help (at) autodesk (dot) com` if possible so that we can debug it on our end.

get Layers list only in SVF2 models?


Visual Studio 2013 Ultimate Update2 - Load testing - Missing Manifest

Question: I have created a Web/Load test and whilst running the newly created WebTest works as expected, if I add that to a Load test, locally it executes but does not testing.  If I push it up to TFS-Online I get a Manifest dialog error.
The path is long and does not exist but sits within appdata\local\assembly.  The end of it is CommonExtension\Microsoft\Webclient\TestServiceplugin\TestStatus.json not found.
I have repaired my new install of Visual Studio but still the same error, I have two references in the project: Microsoft.VisualStudio.QualityTools.LoadTestFramework, Microsoft.VisualStudio.QualityTools.WebTestFramework, am I missing anything?
Possibly related is if I try to open Load Test Manager from the Load Test Menu, I get an Exception dialog of Exception has been thrown by the target of an invocation.
An online search has drawn a blank, anyone seen this or know how I can troubleshoot?
Steve.
Answer: I got some help on the MS Forums, it has now been resolved but not particularly clear what the exact issue was.
http://social.msdn.microsoft.com/Forums/vstudio/en-US/d3009f05-e848-4bdc-a929-4648f38fb11a/visual-studio-2013-ultimate-update2-load-testing-missing-manifest?forum=TFService&prof=required
Hopefully helps others with this or similar random issue as re-installs did not fix it.
Steve.
Comment: Steve, I looked at the link to see if it would help my own similar problem but mine is happening locally. No TFS involved. I get this when running any webtest or loadtest that I created in the project. Did you ever see the problem in that scenario? (Because I'm also finding nothing else on the web but this post). Thanks!
Comment: No, it seems to be some kind of config issue but MS never identified it.  Have you tried the various cache clearing processes?  Other than that you could try a local version of what I did.  You can open a new solution and add a new test and run it.  If its the same issue as me, that will work.  You can then switch back to yours and hopefully that just starts working.  Its a quirky one but no idea why it behaves the way it does.
Comment: New solutions/new tests/ nothing worked. I ended up completely uninstalling VS2013 and then reinstalling and reapplying Update 3 and voila it worked!Thanks for the reply. :)


Cotangent space - redundant definition?

Question: I am extremely confused about the exact difference between a vector and a covector. For instance:
Let a curve $\gamma : \mathbb{R} \rightarrow M$ be a smooth curve through a point $p \in M$, where $M$ is a manifold. Then the directional derivative operator is the linear map:
$X_{\gamma, p} : C^{\infty} (M) \rightarrow \mathbb{K}$,
where $\mathbb{K}$ is the underlying ring. Now, all books I have seen on higher geometry states that this a vector and that the operator can be written as $X_{\gamma, p} := e_i f$, despite the fact that is seems to behave like a covector (i.e. mapping an element from $C^{\infty}$ into the underlying ring)? Likewise, everyone agrees that any $X \in T_p M$, where $T_p M$ is the tangent space for $p \in M$, can be written as
$X= \sum_{i} x^i e_i$,
where $x^i \in \mathbb{K}$. In other words: Clearly a covector, judging from the notation. However, the gradient operator $d_p$ is said to be a covector, and a map $d_p : C^{\infty} (M) \rightarrow T_p^{\ast}(M)$, where $T_p^{\ast} M$ is the cotangent space. This defintion seems redundant, since any $X \in T_p M$ is already a map $C^{\infty}(M) \rightarrow \mathbb{K}$?
Can anyone clarify these concepts? What is the relationship between the tangent vectors, the gradient etc.?
Comment: There are multiple definitions of tangent and cotangent spaces, and it's not clear to me what definitions you've started with. That said: 1. a mapping from _smooth functions to scalars_ (e.g., the directional derivative, a tangent vector) must not be conflated with a mapping from _tangent vectors to scalars_ (a covector). 2. If $f$ is a function, then $df$ is a covector, but that's not to say the operator $d$ _itself_ is a covector.
Comment: First, $d_p$ is *not* the gradient, it is the differential at the point $p$. The gradient is a different business, it usually requires a Riemannian metric. Second, $d_p$ is not a covector; it is $d_p f$ (the differential of $f$ at $p$) who is.
Answer: It seems you are confused by the notation? As you pointed out, the tangent space of a point can be seen as the space of directional derrivatives with evaluation at that point. The cotangent space (space of differential forms at the point) is just the dual vector space in the sense of linear algebra. So covectors map vectors to numbers. From the sense of linear algebra you can form the dual space of any vector space. In particular the tangent space can be the space of derrivations, as you described.
Now you are right in that $C^{\infty}(M)$ is a vector space, in fact it is even a ring. But the space $T_pM$ is NOT the dual space of this. That is: Only a small part of the mappings $C^{\infty}(M)\to \mathbb{K}$ are actually vectors at points of $M$. They have to satisfy the Leibnitz-rule: If $V\in T_pM$ then for all $f,g\in C^{\infty}(M)$ (you could also take equivalence classes of functions equal on a neighbourhood of the point instead)
\begin{equation}
V(f\cdot g)=V(f)g(p)+f(p)V(g)
\end{equation}
In general, the space of vetor fields is a module over the ring $C^{\infty}(M)$. This way you can try to carry over some of the linear algebra from the tangent space at a point to more global constructions.
In the notation you used, the $e_i$ are basis vectors of the space $T_pM$. Hence a linear combination of those is a vector. In case you are confused by the index placement (otherwise ignore the following): In the notation the components of vectors receive upper indices. The basis vectors have indices down, so the components can be contracted with them avoiding summation signs.
Gradients are usually thought of as vectors. If you have a metric (a symmetric bilinear form, depending on what else you have (Riemanian) also positive definite, which varies smoothly from one tangent space to others) $g:T_pM\times T_pM\to \mathbb{K}$, you can convert covectors into vectors by assigning a vector $V$ to the covector, which maps $T_pM\ni W\mapsto g(V,W)$. Thus the metric induces a mapping $T_pM\to T^*_pM$ which is called "musical isomorphism". This map can be inverted and thus any covector can be converted into a vector via the metric, too. The gradient of a function $f\in C^{\infty}(M)$ at the point $p$ is the vector that you get, when you convert the covector $d_pf$ into a vector. That being said, the covetor $df$ contains the information we usually associate with a gradient in classical vector analysis. For most uses where you would use the gradient you don't actually need or want it to be a vector (every time you "dot" the gradient into something). Thus you could also see $df$ as "the correct way to think about the gradient", as long as you don't forget it's not a vector.
Comment: Hey. Thanks for your answer, but I think my question is more general than this:

Are the elements of $T_p M$ vectors or covectors? Because they seem to behave like covectors, but everyone calls them vectors.
Comment: @Henry1981 Why do you think they behave like co-vectors?
Comment: @Henry1981 They are vectors. Why do you think they "behave" like covectors? As I pointed out, $T_pM$ is not the dual space of $C^{\infty}(M)$. There are also different ways to define the tangent space (space of vectors) than as derrivations on the function ring, as pointed out in the comments to the question.
Comment: The reason I thought it was a covector, is due to the definition of a rank $(r,s)$-tensor $T_s^r$, which can be reconstructed from its coordinate as

$T_s^r = T_{i_1, \dots, i_s}^{j_1, \dots, j_s} \epsilon^{i_1} \otimes \dots \otimes \epsilon^{i_s} \otimes e_{j_1} \otimes \dots \otimes e_{j_r}$.

Here, the basis vectors for a rank $(0,1)$-tensor (which is a vector?) is written as $\epsilon^i$? Likewise, the metric tensor is $g = g_{ij} dx^i \otimes dx^j$?

Also, a covector would be a map $V \rightarrow \mathbb{K}$, which they seem to satisfy?
Comment: In the tensor product above the $e_i$ stand for the basis of the Tangent space and the $\epsilon^i$ stand for the basis of the cotangent space (Dual to the others basis, i.e. $\epsilon^i(e_j)=\delta^i_j$.) The $dx^i$ are another notation for the Dual basis (the corresponding notation for the basis of the Tangent space would be $\partial_i$). A covector is a map $V\to\mathbb K$ but in the context of differential geometry $V$ is the space $T_pM$. We have the terminology that functions are the smooth scalar fields,  vectors are maps $T_pM\to \mathbb K$ and covectors are maps $T_pM\to \mathbb K$.
Comment: I am sorry for  bugging you, but you have to clarify: A rank $(p,q)$-tensor is a map that takes $p$ copies of $V$ and $q$ copies of $V^{\ast}$ and maps it into $\mathbb{K}$ (right?). We write this as $T_{i_1, \dots, i_q}^{j_1, \dots, j_p} e_{j_1} \otimes \dots \otimes e_{j_p} \otimes \epsilon^{i_1} \otimes \dots \otimes \epsilon^{i_q}$. So in this notation, a rank $(1,0)$-tensor (covector), should be written as $T^j e_j$? But this is exactly the notation that we used for the "vectors" in $TM$?
Comment: Sorry for the typo in the last line of my last comment. Vectors are maps $C^{\infty}\to\mathbb{K}$. Tried writing that on a mobile device.
The order of meaning in $(p,q)$ tensors is actually different from source to source. If however (at which point it's no longer about differential geometry) you talk about a map that takes $p$ copies of $V$ and $q$ copies of $V^*$ to the scalars, such a map will consist of tensor producs of $p$ copies of covectors and $q$ copies of vectors. In this case we identify the space $V$ with the double dual space $V^{**}$ and vectors take covectors to scalars, too
Comment: To illustrate: If $e_1,\dots e_n$ is a basis of $V$ and  $\epsilon^1\dots\epsilon^n$ is a basis of $V^*$ then the map
$$
T=e_1\otimes e_2 \otimes \epsilon^3
$$
takes two covectors and a vector to the scalar. Now for example
$$T(\epsilon^1, \epsilon^3, e_4)=\epsilon^1(e_1)\epsilon^3(e_2)\epsilon^3(e_4)=0.$$
Here you can see how "vectors act on covectors" by dual pairing in the sense of my comment above.

Cotangent space - redundant definition?


Role of $d^2 = 0$ in chain complex

Question: What is the motivation for requiring that the square of a differential be $0$ for a complex, aside from enabling us to speak of the homology of a complex?
Other homological notions like chain maps, homotopic maps, homotopy equivalences seem to be meaningful without any restriction on the differential (of course, no longer do homotopic maps induce isomorphisms on Homology, for Homology no longer is meaningful).
If we ignore any connections to Homology, is there some other moral reason to want that the differential square to $0$?
Comment: From the other end, why a lot of commonly occurring complexes do have $d^2 = 0$: it often comes from the fact that an exact complex (for example a resolution) has $d^2 = 0$, and the fact that applying any functor preserves the condition that $d^2 = 0$ (while not that many functors preserve exactness).
Comment: @rschwieb "morally" and "moral" are actually often used to mean something similar to "intuitive" (but not exactly the same thing -althoug it's still a vague, unprecise notion), in some places at least. OP : Cartan famously said "if I could only understand the beautiful consequences following from the concise proposition $d^2=0$". An unsatisfactory answer would be : homology theory was built when many examples of this "$d^2=0$" phenomenon were found, like for instance the differential of the de Rham complex (unsatisfactory because it's probably not historically accurate)
Comment: A number of people have studied $N$-complexes (where $d^N=0$ in place of $d^2=0$), going back to Mayer in 1942. A fairly recent paper, with lots of references to previous work, is https://arxiv.org/abs/1309.6039
Comment: The word "moral" is totally inapplicable here, but something like "intuitive" or "heuristic"  would do.
Comment: Like you said, it enables us to speak of the homology of a complex.
Comment: There are certainly situations where one has $d^n=0$, and then a variant on homology (or several variants, depending on $i$) can be defined as $\textrm{ker} d^i/\textrm{im} d^{n-i}$.
Comment: @JohnPalmier Do you have any good examples of that on hand? I haven't seen that before.
Comment: [Related mathoverflow question](https://mathoverflow.net/q/640/19965)
Comment: Perhaps another point of view is that group extensions are interesting, and they are particular sequences $A\to B\to C$ with $g\circ f =0$. Chain complexes are then a generalization of that
Comment: @Max Interesting Cartan quote... that makes it all the more interesting.  Another question is why something like $d^3=0$ is not as interesting or practical.
Comment: @SantanaAfton: any graded module $M = \bigoplus M_i$ over the graded ring $k[x]/(x^n)$, with $x$ in degree $-1$, gives an example. Multiplication by the element $d$ gives a map $M_i \to M_{i-1}$ for each $i$.
Comment: @JohnPalmieri I thought that might be the case :) And yet somehow the case with just $2$ is the workhorse.  Perhaps because it is the least complex thing that does what we want? Maybe there is an example for which at least $3$ is needed to do something that $2$ can't do... that would be a good addition for an interesting solution here.
Comment: Your instruction in the last paragraph to ignore homology is rather unfortunate. The motivations and intuitions behind the equation $d^2=0$ come from homology, and they are manifold (pun intended). Other usages of that equation are conceptually driven by mathematical efforts to widen the applicability of homological ideas, i.e. to addapt those ideas to broader and broader settings which stretch them beyond their manifold roots (pun intended once more!)
Comment: Thank you everyone for the responses. I worked through some standard facts (like the fact that we get an equivalence relation, nice behaviour under composition) about homotopic maps, homotopy equivalences, etc., and they all hold true without the condition that $d^2=0$. Can someone suggest where a commonly known fact about homoptic maps, homotopy equivalences might break if we leave out the condition that $d^2=0$?
Answer: The main motivation for wanting $d \circ d = 0$ is because it arises naturally in so many applications. As others have already said in comments, exact sequences are common and important, and you often get chain complexes by applying functors to exact sequences. At that point, homology measures how far the new sequence is from being exact: often a very interesting question.
More generally, people certainly study diagrams of the form
$$
X_1 \to X_2 \to X_3 \to \cdots
$$
with no condition on the maps, and then you can examine maps between such diagrams — the analog of chain maps. This happens all the time in algebra; for example, $X_i$ might be a submodule of $X_{i+1}$ for each $i$, giving a filtration of $\bigcup X_i$.
In the case when $d^2 \neq 0$, although I suppose the analog of "chain homotopy" could be defined, it is not clear what use it would be. What can you deduce if $f$ and $g$ are "chain homotopic" in this more general sense? What does it tell you in the case where each $X_i \to X_{i+1}$ is injective? Is surjective? When considering honest chain complexes, the definition of chain homotopy is motivated by the definition of homotopy in topology, and indeed, homotopic maps between topological spaces induce chain homotopic maps on their singular chain complexes: there is a mechanism for producing chain homotopies, at least in this one situation. Is there any mechanism that produces this analog of a chain homotopy? Without good motivating examples and/or interesting consequences, it doesn't seem worthwhile (to me, at least) to devote too much energy to it.
Comment: "It arises in so many applications". Could you list two or three? The only place I've ever seen it in particular is with differential forms. Also, when you refer to some relationship with exact sequences, it is a complete mystery to me what the connection is, so I imagine it might be the case to others too. Could you explain that briefly in the solution?
Comment: @rschwieb: in algebraic topology, there are several ways to produce a chain complex from a suitable topological space: the singular, cellular, and simplicial chain complexes. Also in any exact sequence, you have $d^2=0$. Then if you apply a functor, say $- \otimes_{\mathbb{Z}} G$ for your favorite abelian group $G$, you will get a sequence which may no longer be exact but has $d^2=0$. Read about homological algebra and group cohomology for two large areas which are replete with chain complexes and exact sequences.
Comment: @rschwieb: If you like more examples coming from analysis, take a look at [Cousin problems](https://en.wikipedia.org/wiki/Cousin_problems) which first appear as questions in complex analysis but they are best understood in terms of sheaf cohomology (which also provides some tools for solving the problems).
Comment: @JohnPalmieri That still flew far, far over my head, so I took a look at the wiki article. I was surprised to see that $d^2=0$ is apparently a shorthand for something I had not expected, namely pairwise relationships between the arrows in a sequence.  Is there some precise sense in which this is really an operator that squares to zero, or have I just been mislead by a convention?
Comment: I don't understand your question. Which parts flew over your head? Regarding $d^2 = 0$, can you clarify your question? It's in the title of the question here, and the setup should be a chain complex in which each map is called $d$, so the composite of two consecutive ones is $d \circ d := d^2$.
Comment: @JohnPalmieri The first sentence was over my head in the sense that I don't have any experience with those tools. The second sentence was an assertion that the very thing I'm asking about is true.  I understand the third sentence as an example of an application.  The last sentence suggests something I would like to do, but has a scope which I can't accommodate, now.
Comment: @JohnPalmieri In the meantime I've thought about $d$. My only picture for it right now is differential forms on $\mathbb R^n$, and that you can define it to take $k$ forms to $k+1$ forms, so really that should perhaps be $d_k$. I guess one could consider it a single map $d$ on the union of $k$ forms for positive integers $k$, but that union isn't a very sensible object, algebraically speaking.  I understand that might be one way to think of it though. Is that normally what is done? You think of all the connecting morphisms as "a single map"?
Comment: In the case of alternating $k$-forms, it looks like $d$ can be considered a function $\cup_{k\in\mathbb N} \Lambda ^k(V)\to \cup_{k\in\mathbb N} \Lambda ^k(V)$ which really does have square zero.  Not sure if that trick would work for general chain complexes, but that's OK.

Role of $d^2 = 0$ in chain complex


Failed to install mono for android on windows 7

Question: Heres the link to log http://pastebin.com/jqjhqjdR
It has downloaded about 750MB plus of data and still complaining. I have run setup.exe with administrator access too.
let me know if you need more information.
Answer: The problem is you don't have enough space available on the machine to install it. Here is a log extras:

[Info] MSI (s) (88:E0) [14:37:14:059]: Product: Mono for Android 4.2.1 -- Disk full: Out of disk space -- Volume: 'C:'; required space: 7,17,101 KB; available space: 6,85,744 KB.  Free some disk space and retry.
  [Info] Disk full: Out of disk space -- Volume: 'C:'; required space: 7,17,101 KB; available space: 6,85,744 KB.  Free some disk space and retry. [Info] Action ended 14:37:14: InstallValidate. Return value 3.

As a side note, to easily identify where a MSI failed, you can look the log for "value 3". If a standard action or custom action returns this value it means the installation was stopped. Of course if the log is generated in another language use the equivalent of the word "value" in that language.
Comment: thanx for the input, but it installed successfully after a restart - i did not create any more space, any clue?
Comment: maybe the restart triggered some cleaning operations in the OS that made more HHD space available, can't say for sure.


Find the derived set of $S$ where $S=\{m+\frac{1}{n}\mid m,n\in\mathbb N\}$

Question: Let $S=\{m+\frac{1}{n}\mid m,n\in\mathbb N\}$. I want to find the derived set (the set of cluster points) of $S$.
I tried this. It seems that the answer is $\mathbb{N}$. So $S\subset[1,\infty)$. Then $$[1,\infty)-\mathbb{N}=(1,2)\cup(2,3)\cup\ldots \cup(k,k+1)\cup \ldots$$ If $x \in (1,2)$ then I was trying to prove that $x$ is not a cluster point of $(1,2)$ and so on. But can't approach to that proof. Maybe I'm wrong.
Comment: What are $m$ and $n$? What do you mean by "derived set"?
Comment: This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.  Be sure to include the entire mathematical expression between dollar signs.
Comment: Oh! Sorry i didn't mention this. Here $m$ & $n$ both natural numbers. And derived set= set of all cluster points
Answer: The answer is $\mathbb{N}\cup\{\infty\}$. Indeed, if $m\in\mathbb{N}$ then $m$ is the limit point of the sequence $(m+1/n)_{n=1}^\infty$ that is a sequence of $S$. Also, $\infty$ is the limit point of the sequence $(m+1)_{m=1}^\infty$, also a sequence of $S$. Now how do we prove that there is nothing else in that set? Obviously, the only possible limit points are positive numbers. Take $x>0$ not an integer and let $N\in\mathbb{N}$ such that $x\in(N,N+1)$. let $m+1/n\in S$. If $m<N$, then $m+1/n\leq N$ hence the distance of all those elements of $S$ from $x$ is at least $h:=x-N>0$. If $m\geq N+1$, then $m+1/n>N+1$, therefore the distance of these elements of $S$ from $x$ is at least $h':=N+1-x>0$. The only elements of $S$ left for us to check are $(N+1/n)_{n=1}^\infty$. But this is a sequence that converges to $N$, hence it cannot have a subsequence converging to $x$. Therefore we have proved that $x$ is not the limit of any sequence formed by elements of $S$, hence not in the cluster set of $S$.
Note: In case you are not interested in sequences converging to infinity but only in sequences converging to elements of $\mathbb{R}$, forget about that part.
Comment: @Ennar Okay, maybe there is no space for sequences converging to infinity. Otherwise its the one point compactification of the line. I will add a note, thanks for pointing this out
Comment: I guess OP wants to consider $S$ as a subset of $\mathbb R$. In that case, what is $\infty$?
Answer: Hint: Pick $x\in (k,k+1)$. If it were cluster point of $S$, every neighborhood of $x$ would contain a point from $S\setminus\{x\}$. But, $x\in [k+\frac 1{n+1},k+\frac 1n]$ for some natural $n$ and $k+\frac 1{n+1}$, $k+\frac 1n$ are the closest points of $S$ to $x$. Can you find a neighborhood that proves $x$ is not a limit point of $S$?


How does the piano middle pedal work? Is there a standard symbol for it?

Question: What are the mechanics behind the middle piano pedal? I have been using the middle pedal for a variety of music, it is wonderful, but I can't figure out how it works (I mean the mechanical process).  A drawing or animation would be ideal.
I know that the middle pedal is very underused, and I've never seen a music sheet specifying that one should press the middle and not the damper pedal.  Is there standard notation for it?
EDIT:
I'm talking about the original middle pedal, invented by Steinway. I think it's also called sostenuto pedal.
Comment: The latter part would be considered a poll, i.e., Not Constructive, so I took it out.  Interesting question though.
Comment: Since you're essentially asking two different questions here, I've edited your tags to match the mechanical side of things.
Answer: There are two different ways that the middle pedal on American pianos works. This pedal is called the "Sostenuto" pedal and, unlike the Sustain pedal, does not sustain every note on the piano. This website gives great videos and explanations of each piano pedal.

On higher end pianos, the middle pedal (Sostenuto pedal), sustains only those notes which are depressed on the keyboard at the time when the pedal is pushed down. Once the pedal is depressed, the notes played thereafter are not effected by the pedal.
Lower end pianos have a similar acting Sostenuto pedal, which, however, is not a true Sostenuto pedal. On these pianos, the middle pedal, while depressed, undamps only the lowest strings on the piano.

When a composer asks the player to use the Sostenuto pedal, he or she will use any of the following:

S.P
Sost. Ped.
ThP. (from German "Tonhalte-Pedal")

Some pianos, instead of using a Sostenuto pedal, provide a "Practice pedal" as the middle pedal. This pedal dampens the strings beyond the left most "Soft pedal". Often, this pedal has a locking mechanism as well.
The best way to know which type middle pedal a piano has is to test it out and see which of the above options it is.
EDIT: This website gives pictures and discussion of how some Sostenuto pedals work.
EDIT #2: This video demonstrates the sostenuto pedal mechanism.
Comment: Thanks for the notation on the sost. pedal, Reina, but I know I have a sostenuto pedal, and I know how and when to use it. What I do not know is how it actually works, mechanically.
Probably this is not very explicit in my question, I will edit it. Good answer though, +1! :)
Comment: @Victor, I'm assuming the mechanics will differ slightly depending on the maker. Lots of times, things like this are under patent and so can't be copied exactly from piano maker to piano maker.
Comment: Remarkable piece of engineering! Thank you very much for the schematics. Although it may be slightly different depending on the maker, I now understand how (and why) it works!
Comment: And a third type of piano have the middle peddle as a switch to put something between the hammers and strings (I think) to turn it into an electric piano - very useful for when neighbours get tired of loud practicing.
Comment: @Victor can you open your piano and try to see what happens when you use the pedal (or someone else does)?
Answer: On professional quality pianos and mediocre quality grand pianos, the middle pedal maintains only the notes that were maintained when the middle pedal was being depressed.  This helps in any passage where a note or some notes should be maintained while some notes far away should not be maintained throughout.  On some mediocre or poor quality upright pianos and poor quality grand pianos, the middle pedal maintains only the notes in the left-most register.  This helps in a passage where all the notes that should be maintained are in the left-most register while all the notes that should not be maintained throughout are in some other register.  On some other upright pianos, the middle pedal inserts a piece of felt between the hammers and the strings in each register.  This helps if others tend to feel uncomfortable hearing the practice, and if any of the strings that are going to be played are painfully out of tune.  On yet other upright pianos, the middle pedal is a duplicate of the left pedal.  Some middle pedals on upright pianos have a locking option.
Answer: There often is no notation — you just use the sostenuto pedal out of necessity.  For example, in Rachmaninoff's Prelude in c♯ minor, you would use it on the low C♯, especially in measure 6.  You could use the damper pedal, but that would make a sloppy mess.


mixing binary and real-valued features with SGD

Question: I'm going to be using a logistic regression model and using SGD to determine the feature weights.  Is it OK for me to use a mix of binary and real features, without doing anything like scaling or normalization, and just leave it to SGD to give me a model with weights that will work?
Thanks
Answer: Binary features have a natural scale, so there is no need to rescale them. The real valued features need to be normalized by subtracting the mean and dividing by the range.
Comment: Rescaling has the effect of making the surface of the gradient of your error less elliptical, allowing you to tune the step-size for an epoch more sensibly. Cross-validate with and without normalization. If you don't have too much data (<500,000 observations), compare the results with bfgs.
Comment: Is it necessary, though, in logistic regression?  Wouldn't gradient  descent find suitable coefficients regardless of whether I scaled the parameters or not?