Alternativa assíncrona para Thread.Sleep sem travar aplicação em C#

Question: As vezes queremos que nossa aplicação aguarde alguns momentos para prosseguir com a próxima instrução, porém o Thread.Sleep(0) pode causar travamentos em sua aplicação, principalmente utilizando em loops.
Por isso, aqui vai uma dica de como aguardar um período que desejar sem causar nenhum travamento da aplicação.
Answer: Defina uma variável booleana:
bool await;

Crie um objeto Windows Timer com nome(exemplo) awaitTimer, e no seu Evento Tick adicione o seguinte código:
private void awaitTimer_Tick(object sender, EventArgs e)
{
    awaitTimer.Stop();
    await = false;
}

Crie um método, aqui vamos chamar de Await:
public void Await(int interval)
{
    await = true;
    awaitTimer.Interval = interval;
    awaitTimer.Start();
    while (await)
    {
        Application.DoEvents();
    }
}

Para utilizar, bastar digitar Await(*), entre parenteses colocar o tempo que desejar esperar para a próxima instrução em milissegundos.
//Events

Await(1000); //1000 para esperar 1 segundo

//Events

Answer: Pode obter o mesmo resultado sem o uso do timer:
public void Await(int milliseconds)
{
    DateTime dateTimeTarget = DateTime.Now.AddMilliseconds(milliseconds);

    while (DateTime.Now < dateTimeTarget)
    {
        Application.DoEvents();
    }
}

Veja também o método Task.Delay() a partir do .Net Framework 4.5
Comment: excelente vik, muito obrigado! :)


E Banach space $(x_n)\subset E$ such that $ \| x_n \| = 1 $ and $x_n$ weak convergent to $0$ Suppose that $ M \subset E$ finite dimensional subspace.

Question: Let E Banach space and $ (x_n)\subset E$  such that $ \| x_n \| = 1 $ and $x_n$ weak convergent to $0$. Suppose that $ M \subset E$ finite dimensional subspace, prove that for each $0 < \delta < 1$ there exists $ n_0 \in \mathbb{N}$ such that $ \forall x \in M$ , $\lambda \in F \; \; (\mathbb{R} \;
\; \textrm{or}\;\; \mathbb{C}) $ and  for all $n \geqslant n_0$,
$$  \| x + \lambda x_n \| \geqslant (1-\delta) \|x_n\| $$
My proof is: $ M \subset E$ finite dimensional so $S_M$ (ball surface) compact then $ S_M$ is totally bounded hence,
$$ S_M \subset \cup  _{j=1} ^{p} B(a_j,\delta)$$
where $ a_1 ,a_2 , \cdots , a_p \in S_M$. By Hahn Banach thereom, we have for all $ 1 \leqslant j \leqslant p \; $, $\; \phi _{j} (a_j) = 1$ where $ \phi _1 , \phi , _2 \cdots , \phi _n \in S_{E^{'}}$. Also $ x_n \rightarrow 0$ weak convergent then we have for all $ j \in \{ 1, \cdots ,p\} $
$$ \phi _j (x_n) \rightarrow 0 \textrm{weak convergent} $$
and then
\begin{equation}
\begin{split}
\| x + \lambda x_n \| & = \| x + a_j - a_j + \lambda x_n \|\\
&\geqslant | \| a_j + \lambda x_n \| - \| a_j - x\| |\\
& \geqslant | \phi _j (a_j + \lambda x_n) - \delta | \\
& = | \phi _j (a_j) + \lambda \phi_j (x_n) - \delta | \\
& =| 1 + \lambda\phi_j(x_n) -\delta|
\end{split}
\end{equation}
i stack here. Could you any hint ?
Comment: Please do not vandalize your own posts.
Answer:
I assume the following "uniformity" is desired: For any $\lambda\in \Bbb K$ and $\delta\in(0,1)$ there is a $n(\delta;\lambda)$ so that for all $x\in M$ one has $$\|x+\lambda x_j\| ≥ \|x\|(1-\delta)$$
whenever $j≥n$. This change is necessary because the statement clearly fails if the $n$ should exist for all $\lambda$ simultaneously (eg $E=M=\Bbb R$, $x_j=-\frac1j$) you have for $\lambda = n(\delta)$ that the statement fails for $x=1$).
Suppose the statement holds for all $x$ with $\|x\|=1$ and all $\lambda$. Then it holds for all $x$ and all $\lambda$ since
$$\|x+\lambda x_j\| =\|x\|\cdot\|\frac{x}{\|x\|}+\frac{\lambda}{\|x\|}x_j\| ≥\|x\|\cdot \left(\|\frac{x}{\|x\|}\|(1-\delta)\right)=\|x\|(1-\delta)$$

So its enough to show the existence of this $n$ for all $x$ with $\|x\|=1$ and $\lambda$ arbitrary but fix.
Let $x\in M$, $\lambda\in\Bbb K$ be arbitrary but fixed. By Hahn Banach there is some norm one functional $f$ so that $f(x)=\|x\|$. Then
$$\|x+\lambda x_j\|≥ |f(x+\lambda x_j)| ≥ f(x)-|\lambda |\ |f(x_j)|=\|x\|- |\lambda|\ |f(x_j)|$$
(where it was used that $g(z) ≤ \|g\|\cdot \|z\|$ for any $g,z$) now since $x_j$ converges to $0$ weakly you have that the right-hand side converges to $\|x\|$. Put a $\liminf$ on both sides of the inequality to get that there is an $N(x;\epsilon)$ so that
$$\|x+\lambda x_j\| ≥ \liminf_n \|x+\lambda x_n\| +\epsilon ≥ \|x\|-|\lambda| \epsilon+\epsilon$$
where $\epsilon$ is arbitrary $>0$. Taking $\epsilon = \delta\frac{\|x\|}{1-|\lambda|}$ would recover the statement if there weren't that additional condition that this should work for all $x\in M$ simultaneously.
Now cover the unit sphere of $M$ with finitely many balls of radius $r$ - to be determined later. Suppose $y_1,...,y_k$ are the centres, do the example above for each $y_i$ separately to find that
$$\|y_i-\lambda x_j\| ≥ 1(1-\widetilde\delta)$$
when $j>n$ for $n(\lambda;\widetilde\delta)$ finite. $\widetilde\delta$ is some number in $(0,1)$ that can be chosen freely. Then for any $x$ in the unit sphere there is a $y_i$ so that $\|x-y_i\|<r$ whence
$$\|x-\lambda x_j\| ≥ 1-\widetilde\delta-r$$
for all $x$ in the unit sphere and $j>n(\lambda;\widetilde \delta)$. Now take $r=\delta/2$, $\widetilde \delta = \delta/2$ and you are done.


Implementing a horizontally branching nav menu

Question: I am essentially trying to implement a DOM object that contains many different html templates and can be navigated using different options. I am comfortable with the AngularJS / controller side of this, but unsure about bootstrap and utilizing existing classes/directives.

My project is currently using angularjs, bootstrap, and angular ui-boostrap. The functionality I  want is pretty similar to ui-bootstrap's accordion functionality but rotated sideways. But all the other options get hidden away when one is selected. Does something like this already exist? Also is there existing code/directive can I use to make the creation of this easier?
I plan for the menu's width and height to be mostly static so my only concern is creating this menu while giving it a clean 'bootstrap' feel.
Answer: I think I used this before and was happy with it:
http://bootsnipp.com/snippets/featured/multi-level-dropdown-menu-bs3
See issue in angular-ui/bootstrap also:
https://github.com/angular-ui/bootstrap/issues/2421


Override or extend function of a contributed module

Question: i need to modify the submit function of the module custom_search (8.x-1.0-beta3).
I need to set a Cookie every time the guest user search something, how can i override or extend the submit function?
It looks like not represent a hook. The function is: custom_search_search_page_submit located in the file custom_search.module and called by the custom_search_form_alter function that implements hook_form_alter()
<code>/**
 * Search pages settings form callback.
 */
function custom_search_search_page_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $pageId = $form_state->getValue('id');
  // Save settings, and path as well so we can use it to retrieve the correct settings later.
  \Drupal::configFactory()->getEditable('custom_search.settings.results')->set($pageId . '.path', $form_state->getValue('path'))
    ->set($pageId . '.search', $form_state->getValue('custom_search_search'))
    ->set($pageId . '.advanced.visibility', $form_state->getValue('custom_search_advanced_search'))
    ->set($pageId . '.advanced.collapsible', $form_state->getValue('custom_search_collapsible'))
    ->set($pageId . '.advanced.collapsed', $form_state->getValue('custom_search_collapsed'))
    ->set($pageId . '.advanced.criteria', $form_state->getValue('custom_search_criteria'))
    ->set($pageId . '.advanced.types', $form_state->getValue('custom_search_types'))
    ->set($pageId . '.advanced.languages', $form_state->getValue('custom_search_languages'))
    ->set($pageId . '.info', $form_state->getValue('custom_search_info'))
    ->set($pageId . '.filter.position', $form_state->getValue('custom_search_filter_position'))
    ->set($pageId . '.filter.label', $form_state->getValue('custom_search_filter_label'))
    ->set($pageId . '.filter.any', $form_state->getValue('custom_search_filter_any'))
    ->save();
}
</code>
Answer: You don't need to override the submit function. Each module or theme can do exactly the same as the custom search module does. Use a form alter hook and add their own submit function to the form array. On submit they are each executed one after another.
mymodule.module
<code>/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id') {
    $form['actions']['submit']['#submit'][] = 'mymodule_search_page_submit';
  }
}

function mymodule_search_page_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  // set cookie
}
</code>
Comment: This belongs in a custom module. It's best to maintain the separation between code that controls how your site works (modules) and code that controls how your site looks (theme).
Comment: I need to create a new module? Or i can place the above code somewhere in my theme?
Comment: @LeninMeza: This works both in modules and themes. In a theme you put the code in `mytheme.theme`. I agree with marcvangend, a module is the better place.
Answer: I ended up with the next code on my own module, thanks to @4k4 and @marcvangend
It works like a charm!!
<code><?php

/**
 * @file
 * Bring customizations to the default core functions
 *
 */
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Datetime\DrupalDateTime;

 /**
 * Implements hook_form_alter().
 */
function my_module_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'search_form') {
    $form['#submit'][] = 'my_module_search_page_submit';
  }
}

function my_module_search_page_submit($form, FormStateInterface $form_state) {
  $form_values = $form_state->getValues();
  $date = new DrupalDateTime();
  user_cookie_save(['search_form-'.$date->format('Y-m-d_H-i-s') => $form_values['keys'] ]);
}
</code>


Computing the coefficients for a Affine Transform of a triangle

Question: While working through a paper concerning computer generated holograms I have come across a affine transform of a triangle. Since I am not that familiar with affine transforms I do not exactly understand how they obtained the final form of the transform.

Suppose we have a triangle with three non-collinear vertices at $(s_1,t_1)$, $(s_2,t_2)$ and $(s_3,t_3)$. Furthermore I want to transform these vertices to a basic triangle with the vertices $(0,0)$,$(0,1)$ and $(1,1)$ by using a affine transform of the form
$$\begin{bmatrix}s\\t\end{bmatrix}~=~\begin{bmatrix}a_{11}&a_{12}\\a_{21}&a_{22}\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}+\begin{bmatrix}a_{31}\\a_{32}\end{bmatrix}$$
Form hereon I am struggling with determining the coefficients $a_{ij}$. Setting up the pairwise correspondence $(0,0)\to(s_1,t_1)$,$(1,0)\to(s_2,t_2)$ and $(1,1)\to(s_3,t_3)$ and solving the system of six equations yields to
$$\begin{bmatrix}s\\t\end{bmatrix}~=~\begin{bmatrix}s_2-s_1&s_3-s_2-s_1\\t_2-t_1&t_3-t_2-t_1\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}+\begin{bmatrix}s_1\\t_1\end{bmatrix}$$
This formula looks ridiculously simple compared to the final form given within the paper

$$\begin{bmatrix}s\\t\end{bmatrix}~=~\frac1{J}\begin{bmatrix}(t_3-t_2)&(s_2-s_3)\\(t_1-t_2)&(s_2-s_1)\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}+\frac1{J}\begin{bmatrix}-((t_3-t_2)s_1+(s_2-s_3)t_1)\\-((t_1-t_2)s_1+(s_2-s_1)t_1)\end{bmatrix}$$

with $J$ the defined as $a_{11}a_{22}-a_{12}a_{21}$.
To be honest, I have no idea to arrive at this transform or how to reshape my solution to look alike the "right" one. Further I do not exactly know how I can compute something at all with this equation since $J$ is defined in terms of the original coefficients $a_{ij}$ and so for example $a_{11}$ would be given by
$$a_{11}=\frac{t_3-t_2}{a_{11}a_{22}-a_{12}a_{21}}$$
which is kind of recursive. Hence I have got for equations of this type and four variables it would be possible to  determine each coefficient individually but I do not think that this is the right way to approach to this.

Could someone explain to me where I did made a mistake that leads to the wrong solution or how to transform my own attempt to look alike the one given in the article. I would appreciate if someone could show me how to set up the final formula starting by the general defintion of an affine transform and the given pairwise correspondences.

Thanks in advance!
Comment: @amd First of all thank you for your response. I have just checked the formula I cited in the original paper again. I guess it could be that I messed up the pariwise correspondence since the authors states $(0,1)\to(s_2,t_2)$ instead of $(1,0)\to(s_2,t_2)$ which he used previously within a sketch. I guess this may be the crucial point but I do not exactly know. Could you maybe provide a way how to arrive at the right solution?
Comment: Sorry. The transformation from the paper is correct after all. I made a transcription error myself when I checked it.
Answer: Your guess as to what went wrong is correct: you've computed the transformation that maps the basic triangle onto the arbitrary one—the inverse of the map that's needed.† Try plugging in any of the vertices into your formula to see this: you won't get $(0,0)$, $(1,0)$ or $(1,1)$. The transformation in the paper goes in the correct direction. In fact, it's precisely the inverse of yours.
To get from your solution to the correct one, solve the two equations that it represents  for $x$ and $y$. (Their roles are reversed in the two formulas.) Alternatively, start from scratch with the correct direction:
From $(s1,t1)\to(0,0)$ you get $$s_1 a_{11}+t_1 a_{12}+a_{31} = 0 \\ s_1 a_{21} + t_1 a_{22} + a_{32} = 0$$ and so on for the other three point pairs. Solve the resulting system of 6 equations as you did before.
As for the $J$ in that formula, it's the determinant of the matrix in your formula, which appears naturally when that matrix is inverted. The $a$'s in the definition of $J$ are meant to be elements of a generic $2\times2$ matrix. In this particular instance, they're the elements of the matrix in your formula, i.e., $a_{11}=s_2-s_1$ and so on, giving $$J = (s_2-s_1)(t_3-t_2-t_1)-(t_2-t_1)(s_3-s_2-s_1).$$
If you're familiar with matrices, it's fairly easy to invert your formula directly. That transformation consists of a linear transformation followed by a translation, i.e., it has the form $\mathbf p = M\mathbf x+\mathbf p_1$, so to invert it you undo each of those components in reverse order: $\mathbf x = M^{-1}(\mathbf p-\mathbf p_1) = M^{-1}\mathbf p-M^{-1}\mathbf p_1$ Applying this to your transformation after swapping $(x,y)$ and $(s,t)$, we translate back: $$\begin{bmatrix}x\\y\end{bmatrix} - \begin{bmatrix}s_1\\t_1\end{bmatrix} = \begin{bmatrix}s_2-s_1&s_3-s_2\\t_2-t_1&t_3-t_2\end{bmatrix}\begin{bmatrix}s\\t\end{bmatrix}$$ then invert the linear part of the transformation $$\begin{bmatrix}s_2-s_1&s_3-s_2\\t_2-t_1&t_3-t_2\end{bmatrix}^{-1} \left( \begin{bmatrix}x\\y\end{bmatrix} - \begin{bmatrix}s_1\\t_1\end{bmatrix} \right) = \begin{bmatrix}s\\t\end{bmatrix}.$$ Now invert the matrix and distribute the multiplication: $$\begin{bmatrix}s\\t\end{bmatrix} = \frac1J\begin{bmatrix} (t_3-t_2) & (s_2-s_3) \\ (t_1-t_2) & (s_2-s_1) \end{bmatrix} \begin{bmatrix}x\\y\end{bmatrix} - \frac1J\begin{bmatrix} (t_3-t_2)s_1 + (s_2-s_3)t_1 \\ (t_1-t_2)s_1 + (s_2-s_1)t_1 \end{bmatrix},$$ with $J$ as above.
If you use homogeneous coordinates, then there's a conceptually simple way to construct the required transformation. Recalling that the columns of a transformation matrix are the images of the basis vectors, we can see that the matrix $$\begin{bmatrix} x_1 & x_2 & x_3 \\ y_1 & y_2 & y_3 \\ 1&1&1\end{bmatrix}$$ maps the standard basis onto the points $(x_1,y_1)$, $(x_2,y_2)$ and $(x_3,y_3)$. So, to map the given triangle onto the basic one, we can first map its vertices onto the standard basis, then map that onto the standard triangle. The resulting transformation is given by the matrix product $$\begin{bmatrix}0&1&1\\0&0&1\\1&1&1\end{bmatrix} \begin{bmatrix}s_1&s_2&s_3\\t_1&t_2&t_3\\1&1&1\end{bmatrix}^{-1}.$$ If you do this correctly, the last row of the resulting matrix will be $[0,0,1]$, which tells you that you have an affine transformation as required. You can use this same method to construct the affine transformation between any two triangles: just put the appropriate destination vertex coordinates into the left-hand matrix.
† Actually, there's a mistake somewhere in your calculations because your transformation doesn't map $(1,1)$ to $(s_3,t_3)$, but that's not the important thing here.
Comment: @mrtaurho The map you came up with takes those points to $(s_1,t_1)$, $(s_2,t_2)$, $(s_3,t_3)$, respectively. If you want to find the images of those points, plug them into your formula and see what you get.
Comment: Well, thank you again amd. This is quite the response I had in my mind. Clear and structured and therefore quite helpful. I always like to know where something comes from so I am glad you provide such a comprehensibly answer. Could you maybe explain me to which triangle this transform converts a given triangle when it is not the one wiht $(0,0)$,$(1,0)$ and $(1,1)$?
Comment: Ah, okay. Thank you again. I guess this will be quite helpful for me to proceed with.


Is there a name for a semigroup whose idempotents form a subsemigroup?

Question: For a semigroup $S,$ I will denote by $E(S)$ the set of all idempotents of $S$. For $X\subseteq S,$ let $X^2$ mean $\{xy\,|\,x,y\in X\}.$
Is there a name for the class of semigroups $S$ such that $$\left(E(S)\right)^2\subseteq E(S)?$$
To have an example, in every inverse semigroup, the idempotents form a subsemigroup. More generally, as rschwieb points out in a comment, any semigroup such that the idempotents commute with each other satisfies this condition.
I need a name to be able to search for information about such semigroups. So any contribution besides the name will be welcomed.
Comment: No, sorry, I did not even attempt to classify, only to give more examples. I mean that if idempotents commute with each other, then they are obviously closed under multiplication: $efef=eeff=ef$ if $e,f$ are idempotents.
Comment: We can start with *abelian semigroups* meaning "commutative". In ring theory sometimes "abelian" is used to mean "central idempotents", and that would work here too.
Comment: @rschwieb Do you mean that idempotents form a subsemigroup iff they commute with everything?
Comment: @rschwieb Oh, OK. Yes, I know about it -- I should have put it in the question. This is actually the case in inverse semigroups: an inverse semigroup is a regular semigroup whose idempotents commute.
Comment: I've just found out that the answer to my question in the comment is no: in the bicyclic semigroup, the idempotents do not commute with everything.
Comment: In a von Neumann regular which is reduced ($x^2=0$ means $x=0$) all of the idempotent elements are central :) Every product of division rings is such a ring.
Answer: In a very important paper, C.J. Ash, 'Finite semigroups with commuting idempotents', J. Austra. Math. Soc. 43 (1987), 81-90, Chris Ash proved that a finite semigroup has commuting idempotents if and if it divides (that is, is a homomorphic image of a subsemigroup) of an inverse semigroup.
There are examples of finite semigroups that have commuting idempotents, but do not embed in any inverse semigroup.
Birget, Margolis, Rhodes, `Semigroups whose idempotents form a subsemigroup' Bull. Austral. Math. Soc.  41 (1990) [161-184] prove that a finite semigroup has idempotents that form a semigroup if and only if it divides (but not necessarily embeds into) an orthodox finite semigroup, that is a regular semigroup with idempotents a subsemigroup. You can preserve the variety of bands in which the idempotents of the original semigroup reside.
These were all preliminaries for the so called Rhodes Type II conjecture which was also proved by Ash.
For details in book form, see Rhodes-Steinberg, "The q-theory of finite semigroups", Springer, 2009.
u
Answer: According to wikipedia, we have

A regular semigroup whose idempotents forms a subsemigroup is called an orthodox semigroup.
A completely regular semigroup whose idempotents forms a subsemigroup is called an orthogroup.

Every semigroup can be embedded into a regular semigroup. Perhaps subsemigroup of an orthodox semigroup comes closest to the condition you are looking for. I don't know whether there exists a semigroup which satisfies your condition without being a subsemigroup of an orthodox semigroup.
Comment: Thank you, Thomas. I haven't seen these terms before, so this is very helpful. I will accept this answer if no full answer comes up.
Answer: A semigroup whose idempotents form a subsemigroup is called an E-semigroup in a bunch of papers, e.g. J. Almeida, J.-E. Pin and P. Weil which was originally published in 1992, Gomes and Howie (1998), Weipoltshammer (2002), Gigoń (2012), or Fountain and Hayes (2014). Note that all of these were published after Birget, Margolis, and Rhodes' paper (1990), mentioned by Margolis himself above, which did not use this E-semigroup terminology. If the E-semigroup is also regular, then it is called an orthodox semigroup. (This latter terminology is much older dating to 1969.) I have updated the Wikipedia page on orthodox semigroup to mention E-semigroup, but E-semigroup is still a "red link" over there. I don't think the E-semigroup terminology has made it in any semigroup textbooks though and it seems to actually clash with the same name chosen for something else in Arveson's textbook. (Do note that Gomes & Howie's paper on the topic came out 3 years after Howie's textbook was published though.)


How to add User edit link in main menu

Question: Site  link
here, in this 9 is the user id.it is different according to register users.
When add link in main menu there is an option Path textbox
in that text box if i add "user/9/edit" then link is created but here 9 is login user id. then it is accessible only whose user id 9. but other not access.
I want to add link dynamic which user are login then that user access that user edit page.user/*/edit
Comment: have you tried user/*/edit in main menu
Answer: Install me aliases module.

Provides shortcut paths to current user's pages, eg user/me, blog/me,
  user/me/edit, tracker/me etc.
Answer: Menu token

Menu Token module provides tokens, that could be used in title or in
  path of menu items (links). For example, if you create a menu item
  with path: "user/[current-user:uid]", the url will be changed "on fly"
  to: "user/1" (assuming you are user 1).

or you can do it by using hook_menu_alter
<code>/**
 * Implements hook_menu_alter.
 * Check access for forum menu item.
 */
function MYMODULE_menu_alter(&$items) {
  $items['forum']['access callback'] = '_accesscheck';
}
/**
 * Callback to disallow access for the anonymous user.
 */
function _accesscheck(){
  global $user;
  return $user->uid;
}
</code>

How to add User edit link in main menu


How do I drawtext superscript -1 (unicode)?

Question: Unfortunately, I need to directly drawText on a button and I have to put -1 superscript on it.
Problem is that drawText prints small square instead of '\u207b' or ⁻ while it correctly prints  '\u00b9' or ¹. I suspect drawText does not recognize certain unicode characters.
In this case, what can I do?
Answer: This is a guess, but that character probably isn't supported by the font that you're using. Try looking for a font that supports it.
Comment: I'm looking for such a font for Android, so I can embed it into my app. Do you any?


"Not endless" background scroll with mouse position

Question: I don't know JS too much and I'd like to add this code to my site, however I don't want it to be endless. I want it to stop at certain limits or boundaries (min and max) in the x axis. How can I do that the simplest way?
Comment: Why not use the jQuery plugin mentioned in the post ? You will have to familiarize yourself with jQuery to do so, but thats probably the easiest way to do it.
Comment: I've tried doing `while (x =- 800)` but it doesn't work.
Comment: I'm currently using the code, but it is "endless" and I don't want it to behave this way.
Answer: Never mind, use jquery it is easy to do with that. Suppose limit for your scroll is 800 (as you mentioned) then put following code in your js
<code>$(window).scroll(function(){
  if($(window).scrollTop() > 800 ){
    return false;
  }
})
</code>
Your window will not scroll after top is 800px.
Thanks
Comment: Thank you for the answer but it didn't work. I think it's not the case that I need a "scroll" method or whatever it's called. Nor do I want the window to be scrolled. And it's not the y axis that I'm concerned about. Is the background image of the class `.backdrop` that I need to stop scrolling (in the x axis) after certain maximum and minimum value of the variable x.


Page not found when there are clean extra parameters in URL alias-

Question: I have a working site which has PathAuto with SubPath setting properly configured. When I try to access the site from localhost in XAMPP, it gives 404 not found at several pages where the clean URL has extra parameters.
For example,  this goes perfect: subdomain.example.com/url-friendly/extra-parameters
This, in local PC: www.example2.com/url-friendly/ goes right
This, in local PC. fails www.example2.com/url-friendly/extra-parameters
Is there some known issue with XAMPP and Drupal url alias?
Comment: "with SubPath setting properly configured" - how do you know? Do you have Linux-based instance of your site somewhere?
Answer: I have discovered the problem and the solution. When you change domain, or you add a domain to the list in Domain Access, you later have to switch off SubPath, save, and later turn on SubPath again. In that way, it refresh "something", and everything works perfectly.
So if you have free parameters passed on the clean friendly URLs, you need to make those steps in order to assure that the site will work with the changed or added domains.


Ajuda pesquisar ip

Question: Fiz um simples php, de geolocation, mas tem um porém, quero assim: quando o cara acessa o site sem pesquisar ip nenhum aparece o ip padrão dele como já está, mas caso ele acesse e bote na área de pesquisar ip um certo ip e ele clicar em pesquisar, ele vai pesquisar tal ip, e não sei como fazer isto. Se puderem me ajudar, desde já agradeço.
Segue abaixo o código. Eu sei que o código tem um monte de gambiarra mas depois arrumo, o importante é ser funcional.

<title>PEGADOR DE IP</title>

<input type="text" class="listcc" class="text" placeholder="PESQUISAR IP">

<input type="submit" value="PESQUISAR" class="startcheck">

<?php
header("Content-type: text/html; charset=utf-8"); //Seta o padrão como utf-8
error_reporting(0); //Bloqueia o sistema de mostrar algum erro inutil
//Inicio Vars
$user_ip = getenv('REMOTE_ADDR'); //Vai Puxar o ip do usuario
$geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); //Entra no site e puxa os dados
$city = $geo["geoplugin_city"]; //Vai puxar a cidade
$region = $geo["geoplugin_regionName"]; //Vai puxar o estado
$country = $geo["geoplugin_countryName"]; //Vai puxar o país
$browser =$_SERVER['HTTP_USER_AGENT']; //Vai puxar o navegador
date_default_timezone_set('America/Sao_Paulo'); //Vai definir a hora padrão de São paulo - America
$data =date("Y-m-d"); //Vai puxar a data
$hora =date("H:i:s"); //Vai puxar a hora
$useragent = $_SERVER['HTTP_USER_AGENT']; //Vai puxar o navegador utilizado
if (preg_match('|MSIE ([0-9].[0-9]{1,2})|',$useragent,$matched)) {
   $browser_version=$matched[1];
   $browser = 'IE';
} elseif (preg_match( '|Opera/([0-9].[0-9]{1,2})|',$useragent,$matched)) {
   $browser_version=$matched[1];
   $browser = 'Opera';
} elseif(preg_match('|Firefox/([0-9\.]+)|',$useragent,$matched)) {
   $browser_version=$matched[1];
   $browser = 'Firefox';
} elseif(preg_match('|Chrome/([0-9\.]+)|',$useragent,$matched)) {
   $browser_version=$matched[1];
   $browser = 'Chrome';
} elseif(preg_match('|Safari/([0-9\.]+)|',$useragent,$matched)) {
   $browser_version=$matched[1];
   $browser = 'Safari';
} else {
   // browser not recognized!
   $browser_version = 0;
   $browser= 'other';
}
//Fim Vars
?>

IP: <?php echo $user_ip; ?>

CIDADE: <?php echo $city; ?>

ESTADO: <?php echo $region; ?>

PAÍS: <?php echo $country; ?>

NAVEGADOR: <?php echo $browser; ?>

DATA: <?php echo $data; ?>

HORA: <?php echo $hora; ?>

Answer: Você precisa colocar o input onde se digita o ip dentro de uma tag form e depois receber o valor enviado por esse formulario no seu codigo php. O codigo com as alterações (as alterações estão com comentarios):
<!DOCTYPE html>

<title>PEGADOR DE IP</title>

    <form method="post">

        <input type="text" name="pesquisar_ip" class="listcc" class="text" placeholder="PESQUISAR IP">

        <input type="submit" value="PESQUISAR" class="startcheck">

    </form>

<?php
    header("Content-type: text/html; charset=utf-8"); //Seta o padrão como utf-8
    error_reporting(0); //Bloqueia o sistema de mostrar algum erro inutil

    /*
    Verifica se o formulario foi submetido, se sim obtem o ip
    */
    $pesquisar_ip = null;
    if(isset($_POST['pesquisar_ip'])){
        $pesquisar_ip = $_POST['pesquisar_ip'];
    }else{
        $pesquisar_ip = getenv('REMOTE_ADDR'); //Vai Puxar o ip do usuario
    }
    //Inicio Vars
    $user_ip = $pesquisar_ip;
    $geo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip=$user_ip")); //Entra no site e puxa os dados
    $city = $geo["geoplugin_city"]; //Vai puxar a cidade
    $region = $geo["geoplugin_regionName"]; //Vai puxar o estado
    $country = $geo["geoplugin_countryName"]; //Vai puxar o país
    $browser =$_SERVER['HTTP_USER_AGENT']; //Vai puxar o navegador
    date_default_timezone_set('America/Sao_Paulo'); //Vai definir a hora padrão de São paulo - America
    $data =date("Y-m-d"); //Vai puxar a data
    $hora =date("H:i:s"); //Vai puxar a hora
    $useragent = $_SERVER['HTTP_USER_AGENT']; //Vai puxar o navegador utilizado
    if (preg_match('|MSIE ([0-9].[0-9]{1,2})|',$useragent,$matched)) {
        $browser_version=$matched[1];
        $browser = 'IE';
    } elseif (preg_match( '|Opera/([0-9].[0-9]{1,2})|',$useragent,$matched)) {
        $browser_version=$matched[1];
        $browser = 'Opera';
    } elseif(preg_match('|Firefox/([0-9\.]+)|',$useragent,$matched)) {
        $browser_version=$matched[1];
        $browser = 'Firefox';
    } elseif(preg_match('|Chrome/([0-9\.]+)|',$useragent,$matched)) {
        $browser_version=$matched[1];
        $browser = 'Chrome';
    } elseif(preg_match('|Safari/([0-9\.]+)|',$useragent,$matched)) {
        $browser_version=$matched[1];
        $browser = 'Safari';
    } else {
    // browser not recognized!
    $browser_version = 0;
    $browser= 'other';
    }
    //Fim Vars

?>

IP: <?php echo $user_ip; ?>

CIDADE: <?php echo $city; ?>

ESTADO: <?php echo $region; ?>

PAÍS: <?php echo $country; ?>

NAVEGADOR: <?php echo $browser; ?>

DATA: <?php echo $data; ?>

HORA: <?php echo $hora; ?>

Comment: Valeu cara, eu ja tinha conseguido fazer com POST, mas mesmo assim, obrigado por ajudar :D

Ajuda pesquisar ip


Why are they padding only one shared memory?

Question:
An optimized handling of strided accesses using coalesced reads from global memory

The above link says that:

__global__ void coalescedMultiply(float *a, float *c, int M)
{
  __shared__ float aTile[TILE_DIM][TILE_DIM],
                   transposedTile[TILE_DIM][TILE_DIM];
  int row = blockIdx.y * blockDim.y + threadIdx.y;
  int col = blockIdx.x * blockDim.x + threadIdx.x;
  float sum = 0.0f;
  aTile[threadIdx.y][threadIdx.x] = > a[row*TILE_DIM+threadIdx.x];
  transposedTile[threadIdx.x][threadIdx.y] =
      a[(blockIdx.x*blockDim.x + threadIdx.y)*TILE_DIM +
      threadIdx.x];
  __syncthreads();
  for (int i = 0; i < TILE_DIM; i++) {
      sum += aTile[threadIdx.y][i]* transposedTile[i][threadIdx.x];
  }
  c[row*M+col] = sum;
}

(...)
These many-way bank conflicts are very expensive. The simple remedy is to pad the shared memory array so that it has an extra column, as in the following line of code.
__shared__ float transposedTile[TILE_DIM][TILE_DIM+1];

My question is,
Why are they padding only right-hand-side (transposedTile) shared memory, not both (transposedTile and aTile)?
Answer: Because only the access to that tile will exhibit bank conflicts, based on the access patterns in the code.  Therefore only that tile needs to be padded to avoid bank conflicts.
Briefly, bank conflicts in shared access occur when 2 or more threads in the warp are attempting to access values in the same bank, in the same transaction (basically like saying in the same instruction issue).  For simplicity, when we have a 32x32 threadblock array, and a 32x32 tile arrangement of 4-byte quantities, then banks and columns are synonymous.  Therefore the previous statement can be modified to say if two or more threads are accessing the same column in the tile, in the same cycle, there will be bank conflicts.
The exception to this rule is the broadcast exception.  If two or more threads are accessing the same bank (or column in this case) because they are accessing the same location, then that location will be broadcast to all necessary threads for that cycle, and the broadcast rule does not imply bank conflicts.
So this means we must look at all the access patterns (load and store) for each tile, and see which ones in the original code would be bank-conflicted.  Our rule is a bank conflict will occur if the column is the same between threads in a warp, but the row is different.  We should also be able to observe or quickly realize the general "layout" of a 32x32 threadblock: there are 32 warps in that threadblock.  In the first warp, all threads will have threadIdx.y equal to zero, and threadIdx.x varying from 0 to 31 across the warp.  The only difference for the second warp is that its threadIdx.y values will all be 1.  And 2 for the 3rd warp, and so on.
Now lets look at each access (one load and one store for each tile) and see which ones will have a bank-conflicted pattern in the original code:
aTile[threadIdx.y][threadIdx.x] = ...

This is the store operation for aTile.  threadIdx.y is in the row index, and threadIdx.x is in the column index. We know that for a given warp in a 32x32 threadblock, threadIdx.y is constant across the warp, and threadIdx.x varies across the warp in a linear way: 0,1,2,3,...31.  Therefore, this shared load transaction will have threads asking for data in the same row of shared memory, and no bank conflicts will occur.  Each thread is reading from a separate column, which is like saying a separate bank in this case, and that is the canonically best pattern for shared memory: no bank conflicts.
transposedTile[threadIdx.x][threadIdx.y] = ...

This is the shared store transaction for transposedTile.  We see that compared to the previous case, the indexing is reversed.  threadIdx.y, which is constant across a warp, is now in the column index, and threadIdx.x which varies across the warp, is in the row index.   This means that we are selecting a single column across the warp, with different threads accessing different members of that column.  This is columnar access (instead of row-wise access in the previous case) and when we have a tile arrangement such that each column corresponds to a bank of shared memory, this will be canonically the worst possible access pattern into shared memory.  All threads are accessing the same bank, and warp-wide we will have a 32-way bank conflict, which means that the access will take 32 times longer than the best possible case.
... * transposedTile[i][threadIdx.x];

this is the load-from-shared operation for transposedTile. i is constant across the warp (in any given loop iteration), and threadIdx.x varies across the warp.  Therefore we are selecting a particular row, and asking for the elements along that row.  This is the best case for shared access.
sum += aTile[threadIdx.y][i] ...

Considered across the warp, this has both row and column fixed/constant in any given loop iteration.  This is the broadcast case.  In any given loop iteration and instruction issue cycle, every thread in the warp is asking for the same location in shared memory. It is also canonically good.
Therefore only 1 of the 4 possible access patterns has the potential to be bank conflicted.  This access pattern pertains to transposedTile, and therefore only transposedTile needs to be padded, to avoid bank conflicts in this code.


finding a "semi-pro" project for Silverlight, suggestions?

Question: I'd like to get my feet wet in Silverlight. I think all the reading and tutorials in the world don't work nearly as well as a real project. Plus I've done tutorials, read some books, listened to podcasts and so on. I'm ready for the next step. I'm not sure how to make that step though. I'm certainly not ready to put "Silverlight development" on the resumé with any confidence. Some options:

get on elance and make some lowball bids for RIAs, assuming that part of my compensation is the experience
craigslist
find a designer who needs a programmer - already asked all my designer friends ;)

I'd like to find a non-profit ideally, it'd be cool if I felt like I was helping while I was learning. But that seems like a longshot. I'd really want it to be a publicly facing website so I can use it as a bit of a portfolio piece. And I'd be willing to work for free, or a sliding scale sort of fee. I'm not a designer, so I'd need some help in that dept. I've got some experience with that, but it was so long ago and I don't delude myself about my skills.
I've got about 4 yrs experience in ASP.NET, Winforms and C#.
Suggestions for finding this mythical project?
Answer: There is no shortage of non-profits who would love to have someone build software for them, and they don't care what technology it is (this is more or less the sentiment of any customer). I found a non-profit that has a technology need and I'm using ASP.NET MVC and Silverlight to fulfill that need, though admittedly with free time at a premium it's not progressing nearly as fast as a "paid" project. So, my advice is to find a non-profit whose mission you believe in and just send them an email. I doubt they'll turn you down.
Alternatively, help me out! :)
Comment: OK, I'm glad you found someone to help. But the question was "how" so tell me how you found this project.
Comment: I remembered a friend of mine was involved with an organization as a volunteer and emailed her, asking her what she would most need from technology to fulfill the organization's mandate better.
Answer: My first, and unfinished, project in Silverlight was started in November 2007.  I was designing a poll map of the US in which the user could see realtime vote count, hover over a state and get a detailed breakdown.  Similar to John King's Magic Map.
My newborn twins were three months old at the time, so I didn't have a chance to finish it but it was great experience.  Silverlight is great for very visual applications.  Some more ideas:

Anything geographical, like the polling stuff.  There is a free XAML USA map available, Google "XAML USA map".
Graphs, charts, etc.  There are some third-party controls available for this or you could experiment with rolling your own.
Drag and Drop type interfaces can really pop with Silverlight.
Games!  (My personal favorite)
Answer: Here are some ideas:

Make a easily-skinnable shopping cart in Silverlight that integrates with an e-commerce back-end system
I'd try to join an existing Silverlight open source project as a contributor like
this Silverlight Ribbon project on CodePlex.


How do I get the correct data out of a observable

Question: I am trying to get the data out of a observable but i'm not getting the correct data.
This is my get call to my API
    getLastxScans(amount: number): Observable<Scan[]> {
    return this.http.get<Scan[]>(`${this.ROOT_URL}/Scan/amount/${amount}`);
  }

Which returns this when i subscribe to it
{scans: Array(30)}

When i try to fill a Scan[] with this data it doesn't work.
Do I need to go deeper into the object to extract the data?
If so how do i do this? I've tried doing it this way
    this.deviceService.getLastxScans(this.scanAmount)
      .subscribe(scans => this.scans = scans);

And this way
this.deviceService.getLastxScans(this.scanAmount)
    .subscribe(res => this.scans = res.scans);

Comment: you just need supply the proper type to the `get` type parameter, and then inference will work for you: `return this.http.get<{scans: Scan[]}>(url).pipe(map(res => res.scans))`
Answer: Use: (since the array is the value of the scans key of the response)
this.deviceService.getLastxScans(this.scanAmount)
    .subscribe(res => this.scans = res.scans);

From the comments, you could also do:
getLastxScans(amount: number): Observable<Scan[]> {
   return this.http.get<Scan[]>(`${this.ROOT_URL}/Scan/amount/${amount}`)
              .pipe(
                 map((res:any) => res.scans)
              );
}

Comment: @NicholasK, that's why I prefer your answers over others. You explain everything everything very well.
Comment: You're welcome. That should be pretty straight forward. You can use *ngIf to determine whether the data is ready and then render it on the template.
Comment: Should've added that I've already tried that aswell. res already gets recognised as a Scan[] so it won't have that as a property
Comment: Change `this.http.get(\`${this.ROOT_URL}/Scan/amount/${amount}\`)` to `this.http.get(\`${this.ROOT_URL}/Scan/amount/${amount}\`)` in that case then coz the api returns an object `{}` and not an array `[]`
Comment: Still no luck even after I removed the Observable from the method aswell
Comment: That is because you typed it like that. Try: return this.http.get(`${this.ROOT_URL}/Scan/amount/${amount}`).pipe(map(res => res.scans))
Comment: Property 'scans' does not exist on type 'Scan[]'. Which i find a weird error since I can't write the initial values to a Scan[]
Comment: It looked like that worked, although the list itself doesn't get filled yet. The data itself looks correct though
`
this.deviceService.getLastxScans(this.scanAmount)
      .subscribe(res => this.scans = res);
    console.log(this.scans);
`
the console.log shows me a empty array.
Do you know why this is happening?
Comment: The `console.log(this.scans)` should be within the *subscription* block as its value gets assigned *asynchronously*.
Comment: Thank you @NicholasK, now I have another question how do I make the webpage update once this data gets in so that it can be visualized.


site php retorna >

Question: Minha pagina esta retornando > sinal de menor quando add o seguinte codigo que está comentado:
<form name="form_import" id="form_import" method="post" action="<?php echo $_endereco ?>" enctype="multipart/form-data">

          Agraves - importar

          Tipos de Agreve

Agrave 4 salarios

agrave 10 salarios

          Arquivo

          <input type="file" name="arquivo" id="nome_arquivo"/>

          <input type="hidden" name="advogado" id="acao" value="<?php echo $_SERVER['PHP_SELF']."?login=$_SESSION['_codigo_usuario']"; ?>">
          <button type="submit" src="mgm/importa.png" alt="Importar" class="elemento_a_direita"/>Importar

</form>

Comment: tentei reproduzir o erro e não obtive sucesso, você pode disponibilizar um trecho melhor do código?
Answer: Seu código está errado na linha:
<input type="hidden" name="advogado" id="acao" value="<?php echo $_SERVER['PHP_SELF']."?login=$_SESSION['_codigo_usuario']"; ?>">

Veja (não) funcionando no Ideone.

Se a intenção é concatenar o valor da sessão na string, o mais simples é retirá-la de dentro da mesma:
<input type="hidden" name="advogado" id="acao" value="<?php echo $_SERVER['PHP_SELF']."?login=".$_SESSION['_codigo_usuario']; ?>">

Veja funcionando no Ideone.

Ou utilizar as chaves para formatar corretamente a string:
<input type="hidden" name="advogado" id="acao" value="<?php echo "{$_SERVER['PHP_SELF']}?login={$_SESSION['_codigo_usuario']}"; ?>">

Veja funcionando no Ideone.

Pergunta relacionada:
Para que serve os { } no código abaixo? e qual a definição?
Answer: tente remover as duas barras após a concatenação:
   <form name="form_import" id="form_import" method="post" action="<?php echo $_SERVER['PHP_SELF']."?login=$_SESSION['_codigo_usuario']"; ?>" enctype="multipart/form-data">

Comment: Mas as duas barras é o que define o comentário. Por quê removê-las?
Comment: E por que você teria um comentário no meio de uma linha de código?
Comment: @Sergio o porquê eu não sei, mas é uma sintaxe válida e documentada. Veja um [exemplo](https://ideone.com/qaDRz8) e a [documentação](http://php.net/manual/pt_BR/language.basic-syntax.comments.php) sobre os comentários.
Comment: @AndersonCarlosWoss, todos os exemplos que você mostrou, os comentários estão em um final de linha. No caso do código acima, o comentário está no meio de um comando, fazendo com que todo o resto do código seja considerado um comentário também. O php ignora de onde começa o comentário _"...até o final da linha ou do bloco..."_, como diz na própria documentação.
Comment: @Sergio Exato. Inicialmente o autor colocou que o código estava comentado dando a entender que a intenção era que ele fosse ignorado.

site php retorna >


Troubles by understanding arity of terms in A Course in Universal Algebra.

Question: In A Course in Universal Algebra in definition 10.1 terms are introduced.
What puzzles me is the statement about arity:

"A term $p$ is $n$-ary if the number of variables appearing explicitly in $p$ is $\leq n$."

Does that mean that the arity of a term $p$ is at most limited but not defined, and can take several values?
If e.g. $p$ is a variable then can every integer $\geq1$ be put forward as arity of $p$?
This seems to be confirmed in the definition 10.2 (also troubling me) where for term $p(x_1,\dots,x_n):=x_i\in X$ a mapping $p^{\mathbf A}:A^n\to A$ is prescribed by $(a_1,\dots,a_n)\mapsto a_i$.
I really do not understand this definition.
If I just start with term $x$ wich is a variable  then according to def. 10.2 $x^{\mathbf A}$ must be some function $A^n\to A$. But if so, then what is $n$ (can it take several values?) and how is the function prescribed?
Answer: I think you've got it (ugly as it seems). The point is that a term on its own isn't a "complete" object, and so it doesn't have a unique arity.

Certainly there's no problem talking about the arity of a map from $A^n$ to $A$ (namely, just $n$). The point is that a single term can have multiple different interpretations as functions, and these yield different arities. You point this out yourself.
Specifically, for any term $p$ and any set $V$ of variables such that every variable occurring in $p$ is in $V$, we can view $p$ as a map $p_V: A^V\rightarrow A$. Note that the translation $(p,V)\mapsto p_V$ is completely straightforward; this is why one will (sadly) often conflate $p$ and $p_V$ when $V$ is clear from context.

Note that there's no requirement here that $V$ be finite!

In light of this, it isn't too weird to allow a term to have multiple arities - the point being that in some sense a term on its own is incomplete (for spiritual similarity, one might argue that the graph of a function is incomplete since it doesn't tell you the codomain).
Comment: Thank you Noah. Light starts shining, but (as always) I need time to digest.
Comment: You are saying that every (finite I guess) set $V$ induces together with $p$ a map $p_V:A^{|V|}\to A$. I understand, but shouldn't we say that for every *linear ordered* finite set $V$? If for instance $p$ is variable $x$ then it must be clear which projection (there are $|V|$ in total) is denoted by $p_V$, right? I asked a similar question to @Eran.
Comment: @drhab Yes, what you're saying is correct for finitary operations. However, a more general definition would be to interpret to domain $A^V$ as the collection of all functions from $V$ to $A$. Think of these elements of the domain as "$V$-tuples."  Then, I would call $f : A^V \to A$ a $V$-ary operation on $A$.
Comment: @WilliamDeMeo Ah, so actually everything will be okay immediately if we replace $|V|$ by $V$ here so that $p_V:A^V\to A$. Then the order I was asking for is present. Next to that it has the advantage that it eventually can be expanded to infinite $V$. Do I understand you correct?
Comment: @drhab Yes, exactly! And see the comment I'm about to post after Erin's answer.
Comment: @WilliamDeMeo Thank you very much!
Comment: @drhab You're right, I should have written "$V$" rather than "$\vert V\vert$" - fixed!
Comment: Light is really shining brightly now, as it should at Christmas time :-). Thank you very much again!
Answer: Personally, I wouldn't even define arity for a term; I would only define it for a term operation. Let me try to be more precise:
Let $X$ be a set of symbols, called variables, and let $\mathcal{F}$ be a set of operation symbols such that each operation symbol $f$ has an arity, $\mathrm{ar}(f)$, that is a non-negative integer. The set $\mathrm{T}(X)$ of all terms in $X$ is defined recursively:

every variable $x$ or operation symbol $c$ with $\mathrm{ar}(c)=0$ is in $\mathrm{T}(X)$,
if $t_1,\dots,t_k$ are terms and $f$ is an operation symbol with $\mathrm{ar}(f)=n$, then $f(t_1,\dots,t_n)$ is in $\mathrm{T}(X)$.

Now, let $X_k=\{x_1,\dots,x_k\}$ and let $\mathbf{A}$ be an algebra of type $\mathcal{F}$. To every term $t$ in $\mathrm{T}(X_k)$ we can define a $k$-ary operation $t^A$ on $A$ as follows:

if $t=x_i$ or $t=c$ with $\mathrm{ar}(c)=0$, then $t^A:A^k\to A$ is defined by $t^A(a_1,\dots,a_k)=a_i$ or $t^A(a_1,\dots,a_k)=c^A$, respectively.
if $t=f(t_1,\dots,t_n)$, then $t^A(a_1,\dots,a_k)=f^A(t_1^A(a_1,\dots,a_k),\dots,t_n^A(a_1,\dots,a_k))$.

The important thing to notice is that terms are just formal strings of symbols whereas when we assign meaning to a term in a specific algebra that is how we arrive at term operation. Based on this, I feel no reason to define arity for a term and the arity of a term operation is just the arity of the operation. I will conclude with an example:
Let $\mathcal{F}=\{+,-,0\}$. Then $t=(x_1+(-x_2))+x_3$ is in $\mathrm{T}(X_3)$, but it is also in $\mathrm{T}(X_k)$ for any $k\geq 3$. So, given an algebra $\mathbf{A}$ of type $\mathcal{F}$, we can define the term operation $t^A:A^3\to A$ by $t(a_1,a_2,a_3)=(a_1+(-a_2))+a_3$ or we could define it $t^A:A^k\to A$ for any $k\geq 3$ by $t(a_1,\dots,a_k)=(a_1+(-a_2))+a_3$. This first term operation has arity equal to 3 and the second one has arity equal to $k$, but there is no reason to define arity for $t$.
Comment: Thank you. I will take a good look at this (and also the answer of Noah).
Comment: The first 2. in your answer starts with "if $t_1,\dots,t_k$.." but I suspect the $k$ must be $n$ here. Correct? Secondly after the second 1. in your answer you define $t^A$ as the $i$-th projection if $t=x_i$. So the index $i$ is determining. Doesn't that ask for a tuple $$ instead of a set $X_k=\{x_1,\dots,x_n\}$, or otherwise for a set $X_k$ having $k$ elements that is accompanied by a linear order? Maybe that was done implicitly already by introducing indices for the elements of $X_k$.
Comment: @drhab When trying to write programs to handle general operations and terms, (Andrej Bauer showed me) it's easier to handle arities in a more general way.  For finitary operations or terms, input arguments are finite tuples, like $a = (a_1, \dots, a_n)$, but a tuple is really a function $a : \{1,2,\dots, n\} \to A$ (or replace $A$ with $T$ if you want input arguments to be terms).  More generally, if $\rho : F \to \alpha$ is a function from operation symbols to the "arity" type $\alpha$, then operations have type $f : A^{\rho f} \to A$.  The arity type $\alpha$ can be fairly general.
Comment: If you know Coq, and you want to see how this is actually implemented (in dependent type theory), look [here](https://gist.github.com/andrejbauer/3cc438ab38646516e5e9278fdb22022c), or if you know Lean, look [here](https://github.com/UniversalAlgebra/lean-ualib/blob/master/src/basic.lean).
Comment: Everything is clear to me now, and this answer was very very useful. So was the one of Noah (and also the comments of @WilliamDeMeo). Actually I regret that I can only accept one answer. Thanks a lot!


Popping or dismissing a ViewController

Question: I have a Feedback View Controller that is accessed in 7 locations across 4 different screens.
One way it's presented in a navigationController via pushViewController. The other 6 times it's presented modally.
Here's the function that opens the Feedback VC's
struct Constants{
    static func openFeedback(openFrom: UIViewController, nav:Bool) {
        let fbStoryboard = UIStoryboard(name: "FeedbackViewController", bundle: nil)
        let fbVC = fbStoryboard.instantiateViewController(withIdentifier: "FBSBID")
        fbVC.modalPresentationStyle = .overFullScreen
        fbVC.modalTransitionStyle = .crossDissolve
        if nav {
            openFrom.navigationController?.pushViewController(fbVC, animated: true)
        } else {
            openFrom.present(fbVC, animated: true, completion: nil)
        }
    }
}

The Feedback VC is called with either Constants.openFeedback(openFrom: self, nav: true) or Constants.openFeedback(openFrom: self, nav: false)
Opening the VC works just fine!
Here's my close button on the Feedback View Controller:
@IBAction func closeButtonPressed(_ sender: UIButton) {
    self.dismiss(animated: true, completion: nil)
}

Which works 6 out of the 7 times, when not in the navigation stack. When it's in the navigation stack, the close button does not do anything.
My question is, how do I close out of the Feedback View Controller, based on if it's in the navigationController stack or not?
Answer: You can simply check if view controller is embedded inside UINavigationController by checking if controller's navigationController is nil or not.
So if it is embedded you can use popViewController(animated:) on navigation controller to "dismiss" pushed controller
if let navCon = navigationController {
    navCon.popViewController(animated: true)
} else {
    dismiss(animated: true)
}

Popping or dismissing a ViewController


Página não para de carregar quando uso exec no WAMP

Question: Eu preciso fazer um script PHP que execute um programa no servidor, porém a página não para de carregar, é como se ele estivesse esperando o processo ser terminado.
Já fui no services.msc e coloquei o processo do apache para poder interagir com a minha desktop, porém ele vai para outra sessão, como se não fosse a minha.
Meu código é o seguinte:
<?php
    exec('C:\\teste.exe');
?>

Answer: Segundo a documentação da função exec(), o PHP aguarda o término da execução do comando, pois o valor retornado pela função exec() é a última linha dessa mesma execução.
Comment: Certo, e o que você recomenda que eu use para iniciar um programa em ambiente windows?
Comment: Tente chamar a seguinte função: `pclose(popen("start /B C:\\teste.exe", "r"));`
Comment: O script roda e nada acontece, porém se eu boto um arquivo que não existe, o script fica rodando sem parar..
Answer: O Exec aguarda o termino do processo para acabar de interpretar o seu código, um exemplo legal para que você entenda seria fazer um teste com o notepad ("Bloco de notas do Windows.");
 <?php exec("notepad.exe"); ?>

Assim que executar ele irá abrir o bloco de notas, note que a página vai ficar carregando.... assim que você fechar o bloco de notas a execução irá acabar.


How do I navigate to hidden anchors?

Question:
I have a hidden element on my page with id select-box:
<select style="display:none;" id="select-box">

There's a  at the top of my page:
Select box

Because the <select> is hidden, clicking on the  has no effect. Is there a way to achieve this, preferably without using any JavaScript?
Comment: Achieve what exactly? If the select is not there, how is the user expected to use it? Also, this is a form element, not an anchor.
Answer: The css feature display:none; removes the element from the document.
try:
style="visibility:hidden; width:0px"

visibility:hidden keeps the element in the dom and also takes up space so I've given a width of 0px to ensure no blank space will remain.
Comment: you may need this .. http://stackoverflow.com/questions/3475119/css-properties-display-vs-visibility
Answer: Ignoring the fact you are missing the link to your anchor in what you posted, you're right it looks like "display:none" anchors don't work (see: http://jsfiddle.net/odwneeL7/). But you can easily just make an anchor with no content beside what you want to link to, eg:
Select box

...content...

    <select style="display:none;" id="select-box">

See fiddle: http://jsfiddle.net/odwneeL7/1/
Comment: I don't think the OP intended to use an anchor. It sounds like he wanted the label to focus a hidden `` element, which doesn't seem to work. The purpose of focusing a hidden input is unclear. However, your idea of using an anchor seems like a good solution.

How do I navigate to hidden anchors?


Atualizar PartialView

Question: Como faço para atualizar uma partialview (asp .net) após eu selecionar alguma informação pai, por exemplo:
Tenho uma lista de notas fiscais e uma partialview ao lado para mostrar os itens dessa nota.
Ao selecionar uma das notas fiscais a minha partialview deve buscar os itens de acordo a nota selecionada, como fazer?
Comment: Utilizando `ajax`. Você deverá implementar alguma função em javascript que monitore as alterações e que faça a busca no servidor das informações necessárias.
Comment: Acredito que isso poderá te dar uma ideia do que fazer: http://stackoverflow.com/questions/19392212/how-to-use-jquery-or-ajax-to-update-razor-partial-view-in-c-asp-net-for-a-mvc-p
Comment: Você tem algum exemplo Richard Dias?
Answer: Implemente uma função que utilize ajax para realizar a comunicação com uma controller (DetalheNotaFiscalController, por exemplo):
function DetalharNotaFiscal(idNota) {
    $.post("/DetalheNotaFiscal/Detalhar", { id: idNota }).done(function (retorno) {
        $("#detalhe_nf").html(retorno); //id da div com a partial, recebendo o retorno da controller
    }).error(function (xhr, ajaxOptions, errorThrown) {
        alert("Erro Interno. Favor contatar o administrador.");
    });
}

Na controller:
[HttpPost]
public ActionResult Detalhar(string id)
{
    //TODO: Recuperação da nota através do id
    var model = TODO; //model da partial view

    return PartialView("Index", model);
}

Atualizar PartialView


jQuery Canvas Pause and Start listener based on HasClass

Question: I'm having problems setting up a listener that will pause and start a canvas animation based on HasClass. Basically I want the animation to pause when a  has a certain class. Using jQuery I know enough how to add and remove but not tie it all together so they work together nicely. This is a little out of my comfort zone and appreciate any help.
Below is my simple HTML code:

    Pause
    Resume

<canvas id="world"> </canvas>

Below is my JavaScript:
jQuery(function($) {

    !+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!+-+-+!
function(d, w){
    var FPS = 30;
    var F = 300;
    var N = 3;
    var VERTEX_MAX = 10;
    var TRAIL_QUALITY = 4000;
    var mu = 0.5;
    var bmRandom = function(mu, sigma){
        var x, y, r, tmp=null, tmp2;
        return function(){
            if(tmp !== null){
                tmp2 = tmp;
                tmp = null;
                return y*tmp2+mu;
            }
            do{
                x = Math.random()*2-1;
                y = Math.random()*2-1;
                r = x*x+y*y;
            }while(r>=1);
            tmp = sigma*Math.sqrt(-2*Math.log(r)/r);
            return x*tmp+mu;
        };
    };
    pointCopy = function(src, dst){
        dst.x = src.x;
        dst.y = src.y;
        dst.z = src.z;
        return dst;
    };
    Trail = function(pos, t, color_f){
        this.pos={x:0,y:0,z:0};
        this.start={x:0,y:0,z:0};
        this.goal={x:0,y:0,z:0};
        this.anchor_1={x:0,y:0,z:0};
        this.anchor_2={x:0,y:0,z:0};
        this.start_time = 0;
        this.take_time = 1;
        this.vertexes = [];
        this.anchors_1 = [];
        this.anchors_2 = [];
        this.color_f = color_f;
        pointCopy(pos, this.pos);
        pointCopy(pos, this.start);
        pointCopy(pos, this.goal);
        this.setNextGoal(t);
    };
    Trail.prototype.setNextGoal = function(t, target){
        pointCopy(this.goal, this.start);
        this.anchor_1.x = this.start.x+(this.start.x-this.anchor_2.x)*mu;
        this.anchor_1.y = this.start.y+(this.start.y-this.anchor_2.y)*mu;
        this.anchor_1.z = this.start.z+(this.start.z-this.anchor_2.z)*mu;
        if(target){
            this.anchor_2.x = (this.anchor_1.x+target.x)/2+myrand();
            this.anchor_2.y = (this.anchor_1.y+target.y)/2+myrand();
            this.anchor_2.z = (this.anchor_1.z+target.z)/2+myrand();
            this.goal.x = target.x;
            this.goal.y = target.y;
            this.goal.z = target.z;
        }else{
            this.anchor_2.x = this.anchor_1.x+myrand();
            this.anchor_2.y = this.anchor_1.y+myrand();
            this.anchor_2.z = this.anchor_1.z+myrand();
            this.goal.x = this.anchor_2.x+myrand();
            this.goal.y = this.anchor_2.y+myrand();
            this.goal.z = this.anchor_2.z+myrand();
        }
        this.start_time = t;
        this.take_time = 200+Math.random()*200;
        this.vertexes.push(pointCopy(this.start, {x:0,y:0,z:0}));
        this.anchors_1.push(pointCopy(this.anchor_1, {x:0,y:0,z:0}));
        this.anchors_2.push(pointCopy(this.anchor_2, {x:0,y:0,z:0}));
        if(this.vertexes.length > VERTEX_MAX){
            this.vertexes.splice(0,this.vertexes.length-VERTEX_MAX);
            this.anchors_1.splice(0,this.anchors_1.length-VERTEX_MAX);
            this.anchors_2.splice(0,this.anchors_2.length-VERTEX_MAX);
        }
    };
    Trail.prototype.update = function(t, target){
        bezier3(
            t-this.start_time,
            this.start,
            this.anchor_1,
            this.anchor_2,
            this.goal,
            this.take_time,
            this.pos
            );
        if(t-this.start_time > this.take_time){
            this.setNextGoal(this.start_time+this.take_time, target);
            this.update(t, target);
        }
    };
    Trail.prototype.draw = function(ctx, camera, t){
        var i, dz, dt, ddt, rt, a, v={x:0, y:0, z:0};
        var ps = {x:0, y:0};
        ctx.beginPath();
        if(perspective(this.vertexes[0], camera, ps)){
            ctx.moveTo(ps.x, ps.y);
        }
        var x0 = ps.x;
        rt = (t-this.start_time)/this.take_time;
        for(i=1; i<this.vertexes.length; i++){
            ddt = 0.01;
            for(dt=0; dt<1; dt+=ddt){
                bezier3(dt,
                        this.vertexes[i-1],
                        this.anchors_1[i-1],
                        this.anchors_2[i-1],
                        this.vertexes[i],
                        1,
                        v);
                if(perspective(v, camera, ps)){
                    dz = v.z-camera.z;
                    a = 1-(this.vertexes.length-i+1-dt+rt)/VERTEX_MAX;
                    this.color_f(ctx, a, dz);
                    ctx.lineTo(ps.x, ps.y);
                    ctx.stroke();
                    ctx.beginPath();
                    ctx.moveTo(ps.x, ps.y);
                    ddt = dz/TRAIL_QUALITY+0.01;
                }
            }
        }
        ddt = 0.01;
        for(dt=0; dt<rt; dt+=ddt){
            bezier3(dt,
                    this.start,
                    this.anchor_1,
                    this.anchor_2,
                    this.goal,
                    1,
                    v);
            if(perspective(v, camera, ps)){
                dz = v.z-camera.z;
                a = 1-(1-dt+rt)/VERTEX_MAX;
                this.color_f(ctx, a, dz);
                ctx.lineTo(ps.x, ps.y);
                ctx.stroke();
                ctx.beginPath();
                ctx.moveTo(ps.x, ps.y);
                ddt = dz/TRAIL_QUALITY+0.01;
            }
        }
        if(perspective(this.pos, camera, ps)){
            dz = this.pos.z-camera.z;
            a = 1-1/VERTEX_MAX;
            this.color_f(ctx, a, dz);
            ctx.lineTo(ps.x, ps.y);
            ctx.stroke();
        }
    };
    bezier3 = function(t, a, b, c, d, e, dst){
        t /= e;
        dst.x =
            a.x*(1-t)*(1-t)*(1-t)+
            b.x*3*t*(1-t)*(1-t)+
            c.x*3*t*t*(1-t)+
            d.x*t*t*t;
        dst.y =
            a.y*(1-t)*(1-t)*(1-t)+
            b.y*3*t*(1-t)*(1-t)+
            c.y*3*t*t*(1-t)+
            d.y*t*t*t;
        dst.z =
            a.z*(1-t)*(1-t)*(1-t)+
            b.z*3*t*(1-t)*(1-t)+
            c.z*3*t*t*(1-t)+
            d.z*t*t*t;
    };
    perspective = function(point, camera, dst){
        var dx = point.x-camera.x;
        var dy = point.y-camera.y;
        var dz = point.z-camera.z;
        if(dz > 0){
            dst.x = F*dx/dz;
            dst.y = F*dy/dz;
            return true;
        }
        return false;
    };
    updateScene = function(ctx){
        var i, goal;
        time_now = new Date().getTime();
        var time_d = time_now-time_pre;
        trails[0].update(time_now);
        for(i=1; i<trails.length; i++){
            trails[i].update(time_now, trails[i-1].pos);
        }
        camera.x += (trails[0].pos.x-camera.x)*0.0005*time_d;
        camera.y += (trails[0].pos.y-camera.y)*0.0005*time_d;
        camera.z += (trails[0].pos.z-camera.z-100)*0.0005*time_d;
        time_pre = time_now;
    };
    drawScene = function(ctx){
        var i;
        ctx.clearRect(-canvas.width/2, -canvas.height/2, canvas.width, canvas.height);
        for(i=0; i<trails.length; i++){
            trails[i].draw(ctx, camera, time_now);
        }
    };
    var myrand = bmRandom(0,20);
    var canvas = d.getElementById("world");
    var ctx = canvas.getContext("2d");
    var trails = [];
    var i;
    var time_now = new Date().getTime();
    var time_pre = time_now;
    var camera = {x:0, y:0, z:-200};
    for(i=0; i<N; i++){
        trails.push(new Trail({x:myrand(), y:myrand(), z:myrand()},
                              time_now,
                              function(a,z){return "#FFFFFF";}));
    }
    for(i=0; i<N; i++){
        switch(i%3){
            case 0:
                trails[i].color_f=function(ctx, a, dz){
                    var b = dz<10?0:a*F/dz;
                    b = (b>1?1:b)*(dz<30?(dz-10)/20:1);
                    ctx.strokeStyle = "rgba(230,230,230,"+b+")";
                    ctx.lineWidth = F/dz;
                    ctx.lineCap = b>0.8?"round":"butt";
                };
                break;
            case 1:
                trails[i].color_f=function(ctx, a, dz){
                    var b = dz<10?0:a*F/dz;
                    b = (b>1?1:b)*(dz<30?(dz-10)/20:1);
                    ctx.strokeStyle = "rgba(230, 230,230,"+b+")";
                    ctx.lineWidth = F/dz;
                    ctx.lineCap = b>0.8?"round":"butt";
                };
                break;
            default:
                trails[i].color_f=function(ctx, a, dz){
                    var b = dz<10?0:a*F/dz;
                    b = (b>1?1:b)*(dz<30?(dz-10)/20:1);
                    ctx.strokeStyle = "rgba(132,232,251,"+b+")";
                    ctx.lineWidth = F/dz;
                    ctx.lineCap = b>0.8?"round":"butt";
                };
                break;
        }
    }
    var loop = function(){
        canvas.width = w.innerWidth;
        canvas.height = w.innerHeight;
        ctx.translate(canvas.width/2, canvas.height/2);
        updateScene();
        drawScene(ctx);
        w.requestAnimationFrame(loop);
    }
    loop();
    }(document, window);

    $("#eY").click(function(){
        $("#eY").toggleClass("start");
    });
});

And here you can see my JsFiddle to make things easier. The other solution I've thought about is using CSS to hide the canvas but am I right in saying using display:none; on a canvas doesn't stop the calculations which effectively will put load on the browser?
Answer: Hiding the canvas will only hide the element itself, but it won't stop the loop from running. You need something to tell the animation loop to stop from inside it. You can for example use a boolean flag.
Example:
var isRunning = true;                  // this will keep animation running or stop it
var loop = function(){
    canvas.width = w.innerWidth;
    canvas.height = w.innerHeight;
    ctx.translate(canvas.width/2, canvas.height/2);
    updateScene();
    drawScene(ctx);
    if (isRunning) w.requestAnimationFrame(loop);  // check if we're running...
}
loop();

// helper function to restart the loop when toggled from not running, to running
function toggle() {
    isRunning = !isRunning;
    if (isRunning) loop();  // if new status is running, start loop
};

// move this inside the animation scope so we have access to the loop etc.
$("#eY").click(function(){
    $("#eY").toggleClass("start");
    toggle();                      // also call this
});

Updated fiddle
There may be other issues, I only addressed this one. Just open new question if there should be.
Off-topic: cool animation, reminds me of TrapCode's Strokes in AE/Combustion.
Comment: Cheers Ken, using the code you provided I was able to make a solution that worked for me!
Comment: Hi Ken and thanks for the reply. Because the nature of the design I'd like a listener toggle on HasClass, so 'if HasClass toggle' I'm poor at JavaScript is this doable and if so, how. The idea behind this method is that when I click a menu element, it adds pause to an element and then a listener pauses the animation. And primary the reason I thought hasclass would be better since it'll work outside the scope as you put it.
Comment: @bybe you could expose the toggle flag to the outside by adding it as a property on the object. The problem here is that the scope here is "closed", there is no access from the outside. You have to expose methods/properties on it but it can be challenging with the pattern (function(args) {})(args);


Lucky Numbers Python Program Incorrect Python Output

Question:
Practice Problems /
  Lucky String
  All submissions to this problem are public. View all submissions.
Lucky numbers are those numbers which contain only "4" and/or "5". For example 4, 5, 44, 54,55,444 are lucky numbers while 457, 987 ,154 are not.
Lucky number sequence is one in which all lucky numbers exist in increasing order for example 4,5,44,45,54,55,444,445,454,455...
Now we concatenate all the lucky numbers (in ascending order) to make a lucky string "4544455455444445454455..."
Given n, your task is to find the nth digit of the lucky string. If the digit is 4 then you >have to print "Hacker" else you have to print "Earth".

Input:
first line contain number of test cases T , next T line contain a single integer n.
Output:
For each test case print Hacker if n-th digit of lucky string is 4 else print Earth if n-th digit of lucky string is 5.
Constraints:
1 <= t <= 10^5
1 <= n <= 10^15

Following is the python code :
test_cases = int(input())

final = []

def check(stra,num):
    if stra[num-1]==4:
        final.append("Hacker")
    else:
        final.append("Earth")

def GenStr(num):
    stra = "4"
    i = int(5)
    while(len(stra)<num+2):
        X = str(i)
        flag = True
        for j in range(len(str(i))):
            if(X[j]==4 or X[j]==5):
                pass
            else:
                flag = False
        if flag==True:
            stra+=X
        i+=1
    print(stra)
    return stra

for i in range(test_cases):
    num = int(input())
    # generate string
    stra = GenStr(num)
    print("stra "+stra)
    # check the stat
    check(stra,num)

print("\n".join(final))

What is wrong in this code, please do not mind if it is a silly mistake I am just a beginner in python programming
Comment: What is wrong in this code, please do not mind if it is a silly mistake I am just a beginner in python programming
Comment: "next T line contain a single integer n ", what do you mean? please give numerical examples for the inputs.
Comment: Next T lines means that suppose user enters 4 that means he wants to test for 4 values the above code now he enters 4 more numbers on 4 other lines
Answer:
The immediately incorrect thing is the following. stra is 4. flag always becomes False. Thus stra never grows, and while(len(stra)<num+2): is an infinite loop.
The approach itself will not fully solve the problem, since you can't construct a string of length 1015, it would take too much time and just won't fit into memory.
Answer: Comments on your Code
There are several things in your code which don't quite make sense, and need to be addressed:

int(input()) says to ask the user nothing, try to convert any string they type before pressing enter to an integer, and crash otherwise.
The pattern for i in range(len(x)) is almost always wrong in Python. Strings are iterable (they are lists of characters), which is why you can use the list-style index operator (as you do with x[j]), so just iterate over them: for j in str(i).
The pattern if x==True: is always wrong in Python. We prefer if x:.
i = int(5). There is no need to convert an integer literal to an integer. i = 5 is the correct assignment statement.
Try to use better variable names. It's very difficult to follow your code and your reasoning because it is littered with meaningless identifiers like stra (string a??), X, num, etc.

How to Approach the Assignment
I will be honest: I don't fully understand the assignment as presented. It's not clear what a "test case" is or how the input will be formatted (or, for that matter, where the input is coming from). That said, a few thoughts on how to approach this:

Finding numbers that contain only 4 or 5 means treating them as strings. This could be as easy as testing len(str(x).replace('4', '').replace('5', '')), and there are better ways than that.
Listing 'lucky numbers' in increasing order can be accomplished with the built-in sorted function.
Concatenating that list would be ''.join(sorted(lucky_numbers)) or similar.
Taking the nth digit of that list could then be done with string indexing as before.
Comment: Your suggestions are quite correct and reasonable. I should take the approach of replacing 4 and 5 in the string. Thank You..
Answer: As @Gassa points out, brute-forcing this is just not going to work; you would need a million gigabytes of RAM, and it would take far too long.
So what would an analytic solution look like?
If you replace "4" with "0" and "5" with "1", you will see that the lucky number sequence becomes 0, 1, 00, 01, 10, 11, 000, 001, 010, 011, 100, 101, 110, 111, .... This should look familiar: it is every 1-digit binary number in ascending order, followed by every 2-digit binary number in ascending order, followed by every 3-digit binary number in ascending order, etc.
So if you do something like
n = 491         # the digit we are seeking (for example)

d = 1           # number of binary digits
p = 2           # 2**d == number of items encoded
while n > d*p:  # sought digit is past the end of the next binary expansion?
    n -= d*p        # reduce offset by appropriate number of digits
    d += 1
    p *= 2

then n = 233, d = 6 means we are looking for the 233rd character in the 6-bit expansion.
But we can improve on that:
k, n = n // d, n % d

which gives n = 5, k = 38, d = 6 means we are looking at the 5th character of the 38th 6-bit value.
Note: all offsets here are 0-based; if you expect 1-based offsets, you will have to adjust your math accordingly!
The 38th 6-bit value is just 38 converted to a 6-bit binary value; you could muck about with strings to extract the character you want, but it's probably easier to remember that integers are stored as binary internally so we can get what we want with a bit of math:
digit = (k >> (d - n - 1)) & 1   # => 0

so the character in the original string would be a "4".


Why is guitar music written one octave higher?

Question: I was always a guitar player and so I never really cared about the difference, but since starting piano it is a bit annoying writing the guitar parts since I always have to transpose by an octave. Is there any reason why you can't write guitar music just the same as piano on the grand staff? I think if you use both instruments then wouldn't it make more sense to keep the guitar in its right octave?
Comment: Proposal: all guitar music should be written in alto clef instead.
Comment: Closely related [question](https://music.stackexchange.com/q/22219/2600).
Comment: @MichaelSeifert - that would most likely work quite well. '*But we've always done it this way...'*
Answer: I'm following up on @Tim's answer. I didn't use a comment because I wanted to show a picture and discuss it.

As you can see, the notes that fit on a typical guitar fret-board fit nicely on the treble stave. There are roughly the same number of ledger lines above and below the stave.
I personally have trouble with more than 3 ledger lines and in the picture you will notice that this takes you neatly from bottom E on the open 6th string to top E on the twelfth fret of the 1st string. Ok there are a few higher notes but these are much more rarely played.
Comment: @gidds - Have a look at this ---> http://classical-guitar.net/Pic/classical_guitar_score.gif .You might spot a little subscript lurking there. This is the norm for classical guitar. Transcriptions of popular music tend to simplify. They don't want to constantly field questions about "What does that little 8 mean?"
Comment: @npostavs That page says: "As the true tenor clef has fallen into disuse in vocal writings, this "octave-dropped" treble clef is often called the tenor clef."  I've never heard of nor seen this 'true' tenor clef in any vocal or choral music, so that 'often' may if anything be an understatement :-)
Comment: Thanks for the diagram. I agree that they do fit nicely but they fit rather nicely on the grand stave without having to use any additional ledger lines and those playing piano are already used to these notes and the grand stave. I guess I am just not so convinced that writing the guitar like this is right if you are already used to piano. Yes, if you only play guitar then it is better because you dont need to learn the bass stave.
Comment: @armani - if you're used to piano (maybe 10% of guitarists) then just using treble clef is no big deal. Often the r.h. in piano music uses ledger lines. I reckon if guitar music was written on grand stave, even fewer guitar players would bother with dots!
Comment: So why is guitar music not written in a _tenor_ clef?  That looks just like the treble clef, but with a subscript '8' indicating that it's written an octave higher than it sounds.  It has the benefits of fitting nearly on the stave _and_ being precise about the actual pitch.  (Which is exactly why it's used for tenor voices, of course.)
Comment: @gidds That's not what I would call tenor clef. https://en.wikipedia.org/wiki/clef#Tenor_clef
Comment: @armani I guess that the bass stave was thought to be reserved for.. bass? "Don't meddle with the affairs of bassists, as they are subtle and quick to anger"
Comment: @gidds If anyone does call it "the tenor clef", that would be misleading, seeing that that is the name of a different clef. The fact that the tenor clef is no longer used in vocal music is moot, because it is still used in instrumental music -- for cello, bassoon and tenor trombone.
Comment: Your 2nd paragraph is misleading. 'The notes that fit' could be changed to 'the notes we write' - as there's actually that octave disparity.
Comment: @Tim - I'm not sure what you mean, We don't write on the fretboard.
Comment: 'The notes that fit' aren't the actual notes (concert pitch). They're the 'notes we write'. Difficult to explain! Just trying to make answers crystal clear!
Comment: @Tim - I'm saying that the notes most used on the fretboard are from the open low E-string, up to the 12th fret on the high E-string. It so happens that if you use the treble clef and transpose down an octave, those same notes are symmetrical around the clef. I'm not sure what point you are making
Answer: If it was written in the same octave that it was played in, it would stray too often into the much lower parts of the grand stave. By keeping it where it is written, apart from the notes on the bottom and 5th string, most of its notes are happily placed within the treble clef, with only three ledger lines needed below that for the lowest notes.
Putting the notes into the bass clef would mean that too often, the notes played would be on even more ledger lines above that stave.
Comment: @JohnnyApplesauce - no, you have the guitar upside down!
Comment: @Tim thanks. So what if it strays into the bass clef? It sounds like you are saying that the bass clef should be avoided.
Comment: @cmp You don't *have* to do that; it's just that in the most common position, the C chord includes an extra C and E above.
Comment: @MichaelCurtis  - what would be the point in complicating the issue with changes of clef? With a range of a comfortable 3 octaves without going too far up the neck, the treble clef one octave out works, and has worked for a long, long time. If it ain't broke...
Comment: This is most interesting. I did read that if you play a C Major chord on the guitar, you also have to play the C and the E an octave higher in order to make it sound "fuller". Why do you have to do this, Tim?
Comment: Fifth string? Don't you mean second string?
Comment: But if the lowest actual pitch of standard guitar is `E2` and cello is `C2` it does seem like guitar could use the same clefs as cello: bass with clef changes in higher registers.
Comment: The basic concept of one staff for an instrument generally works well. Obviously not for piano! But some instruments have their range in unusual places, so they would use the **C clef**. However, guitar with its lowest note needing only three ledger lines, fits the treble clef as well as is needed. Even going up to the dusty end, three ledger lines above caters for that - any higher, and the oft used *8va* comes out to play. Seeing guitar music written in bass clef? Very unusual!
Comment: @MichaelCurtis - did you miss out 'not' - or not?!
Comment: @Tim, I'm _not_ actually suggesting a change. I'm comparing the ranges.
Comment: @cmp - because we can. The notes (whichever beong to the chord) are available to be played easily, so we tend to include them. We could even play a G on top string instead, if we felt like it - it's easily frettable. The actual number of each note from a chord that's playable is up to reachability, and the decision of the player. One of each suffices - maybe even leave out a 5, but sometimes we can have three of one note name - as it happens, in standard open C, there's two of each. In open A, there's two A, three E and that leaves one C#.
Comment: It would only 'stray' to a single ledger line below the bass clef, for the low E, so I don't think that's a reason at all.   And 'more ledger lines above that stave' is just a false argument, as the higher notes would transfer to the treble clef.
Perhaps it's just that the Grand Staff is more suited to keyboard, where each hand is often confined to either bass or treble clef.
Answer: As to the original question, I think it was answered somewhere in there.
But there was a lot of convoluted speculation about the issue.
The rule is simple: the actual pitch intended is to be written higher (so it sounds an octave lower) on the treble staff with the guitar's open, low E string in the space below the third (F) ledger line. Unfortunately, many arrangers/orchestrators and composers were never taught this, so sometimes it's up to the guitarist to figure out the intention. It is currently (and for a very long time) the best way to do it.
And the reason is, as suggested, you'd get blurry-eyed and frustrated counting ledger lines below the staff.
On the other hand, and though it probably will never happen, a grand staff for guitar might work because modern electric guitar playa way above the staff. Now I'm speculating . Sorry.
Anyway, the use of 8va etc. is a reasonable approach.


checking a proof regarding finiteness of sets

Question: If $X$ set and $U_i$, $i \in I$ a set family.
I know that $X \setminus \bigcup_{i\in I}$ is finite.
I want to prove that $X \setminus U_1 \cap U_2$ is also finite:
Here is my attempt:
$$X \setminus U_1 \cap U_2 = \{X \setminus U_1 \cup U_2\} \setminus\{\{U_1 \cup U_2\}\setminus\{U_1 \cap U_2\}\}$$
We notice that $\{X \setminus U_1 \cup U_2\}$ is finite and obviously you reduce the size of the set by "taking off" $\{\{U_1 \cup U_2\}\setminus\{U_1 \cap U_2\}\}$
Therefore $X \setminus U_1 \cap U_2$  is finite
Comment: By $X \setminus U_1 \cap U_2$ do you mean $X\setminus (U_1\cap U_2)$ or do you mean $(X\setminus U_1)\cap U_2\text{ ?} \qquad$
Comment: BTW, my edit to the question should make some things clear about proper MathJax usage. $\qquad$
Answer: Suppose $X=\{1,2,3,\ldots\}$ and $U_i= \{i\}$ for $i=1,2,3,\ldots$  Then $X \setminus \bigcup_{i=1}^\infty U_i=\varnothing,$ so that is a finite set, but $X\setminus(U_1 \cap U_2) = X\setminus\varnothing = X,$ and that is very far from finite.
Answer: Consider $X=[-1,1]$ and $U_i=(-1+1/i,1-1/i), i=2,3,\ldots.$ The set $X\setminus \bigcup_{i\in I}U_i=\{-1,1\}$ is finite. But $X \setminus U_2 \cap U_3$ is not.


How do I read the music when there are more beats in bar than the time signature specifies

Question: I am a beginner and have encountered the following tab/sheet music notes. It is in the 3/4 time signature, but it clearly shows more than 3 quarter notes in a bar. I am stumped on how to read and play this (this is for fingerstyle guitar):

I am guessing it has something to do with the chords in each bar, but have no idea how to proceed. If it is any help, this is the notes for the start of this song:

I tried following along to decipher the rhythm, but I find my ear too inexperienced and the song too fast. Any help will be appreciated.
Comment: which bar are you looking at? all of them have three beats
Comment: After reading the answers I realized that the stems pointing up and down are to be considered separately in terms of the time signature. Do excuse any misuse of terminology as I am self-taught.
Answer: In the first Am chord, all except the lowest A note are quarter notes, of which there are 3 in each measure in a 3/4 time signature. This probably makes sense to you if we for now ignore that low A and the dotted E (the 2 on the D string in tab).
The trick is the dotted A note in the first chord, which has the length of 1.5 quarter note. Looking at the dotted E we omitted before, which is also 1.5 quarter note, we again get 3 quarter notes in a 3/4 time signature.
You simply play the Am chord on the first beat, the B note (4 in tab) on the second beat, the dotted E between the second and third beat and the final C (1 in tab) on the third beat.

     1   and  2  and  3  and  1  and  2
     Am       B   E   C       G       A
Answer: There are two things going on at the same time there, it's like a grand staff (treble staff above and bass staff below) compressed into a single staff.
The chords and top notes are one line, and the lower (dotted) notes are another line. The lower notes are also syncopated (in each bar, the first one is on a down beat and the second on an up beat). Quite tricky to play until you get the hang of it.
In practice, first learn the top notes (all down beats), then learn the second line separately (two notes per bar) and finally put them together.
Answer: Take a good look at the stems on the notes. Some point upwards, some downwards. In each bar, there are two dotted crotchets. Bars 1,2 and 4 they all have stems down, and bar 3, stems up.Count them and it works out right - 2 x 1 and a half = 3.
Now look at the other notes, including the notes written on top of each other. They all amount to 3 crotchets per bar - good for 3/4 time.
Imagine one instrument playing the stems up notes, another playing the stems down notes. Simultaneously. That's what could happen. However, one player gets to play it all. And it's easier to write like this for guitar or piano. Try playing each part separately before trying it all together. That way, you can hear what each part is like. If you have a looper pedal, you could record stems up, and play over it stems down.
Answer: There are not too many beats in the bar, what is confusing you is that some notes are lasting while other are being played.
You can see it as two groups:

the non-dotted notes, each one lasting one beat, so 3 beats total
the dotted notes, each one lasting one beat and a half, so 3 beats total.

I would note have written this way, but more something like: quarter chord, 2 quavers and one quarter with a "let ring" indication…


Glass beads for prepared piano

Question: Music for Piano (Frangis Ali-Sade) notes:

Prepare the piano by laying a glass-bead necklace tautly along the
  strings between the above mentioned notes [C#-G#: 9.5 whole steps].

What type of glass necklace? True glass necklaces (as opposed to resin beads) are hard to find in the US so I have to get it right on the first attempt.
Three strings form a note and strings of the same note are closer together. Do these instructions mean:

Beads between notes
Beads between all strings
It doesn't matter

I assume the beads should be large enough to rest between the strings without support from the necklace.
Comment: also, how can one "lay...taughtly"?  Tightness/tension requires some force along the necklace, which suggest it is tied to something and tensioned.  Laying suggests no tension along the string, only down from gravity.
Comment: @WilburWhateley Probably means "no slack in the line", ie. the necklace forms a perfect straight line over the strings.
Comment: Wow -- at least he didn't instruct putting thumbtacks in the hammers' felt (a way to make the piano sound "honky-tonk" and ruin the hammers :-(
Comment: The point is if the instructions are that coarse, the details left out of the description of the necklace probably aren't so important.
Comment: Also, note the composer is a 'she'.
Comment: Also, the composer is contemporary (read: living) and has a facebook page https://www.facebook.com/franghizalizadeh/.  Maybe ask her?  Indeed the best you are going get here is speculation and interpretation, and if that is acceptable...you don't need to ask, you just need to interpret it yourself.  The only answer that could be marked as "correct" here would be from the composer herself, in my mind.
Answer: I find it hard to imagine that the exact material matters so long as each bead is a rigid crystalline substance. (Yeah, I know glass is usually noncrystalline.  Go argue with Penrose).  He's presumably looking for the beads to rebound elastically, so anything with beads whose size is on the order of the string spacings should work out fine.
Answer: Given my piano: strings of the same note are separated by 5mm and string between notes are separated by 7mm. I managed to test:

8mm diameter (advertised as 10mm) glass beads with nylon (fishing line) core
12mm diameter (advertised as 14mm) glass beads with nylon (fishing line) core
8mm diameter (advertised as 10mm) amethyst (quartz) with doubled cotton string core

Buyer beware: Despite the label most "glass" beads are actually glazed ceramic or acrylic or some other dried resin. I can only hope my glass beads are actual glass, though since they have the look and feel of glass marbles I'm pretty confident. Also that my quartz beads aren't man-made (amorphous) fused silica, though I think that's pricier than natural quartz.
The glass is amorphous, the quartz crystalline. My results:

8mm glass beads: A good first impression but a little "twangy". The additional vibrations producing the zither effect sometime fade in advance of the natural piano sound.
12mm glass beads: Dull sound, probably from the excess weight. The beads are also too large to fit beneath the metal crossbars.
8mm amethyst beads: Similar to the 8mm glass beads. Produces a slightly less "twangy" sound even though the beads seem to hop off the strings to greater degree. Might be an issue in long sessions. Possibly the cloth core is muting the excess vibrations rather than a fundamental difference between glass and quartz. The sound is also more homogeneous with less separation between the zither and piano sounds.

I can't emphasize enough how subtle is the difference between glass and quartz, even though I prefer the quartz. Judging by the degree of bounce I suspect any lightweight bead, even inelastic plastic beads, would vibrate sufficiently to produce a zither effect.
Also note that if the necklace is strung too tightly you lose most of the effect.

Glass beads for prepared piano


Pass parameters to Azure DevOps tasks depending on the trigger with YAML

Question: I have a YAML Pipeline in Azure DevOps that uses different triggers:

Continuous Integration
PR Completion

This pipeline uses VsTest to execute UnitTests, and i would like to have different parameters depending on how the pipeline was triggered, i.e:

Enable code coverage and run only on impacted tests if the pipeline is triggered for PR completion
Run all the tests if this is for continuous integration

Is there any environment variable i could use to use to affect different values to my variables (both are Booleans).
I couldn't find any environment variables in Microsoft documentation that refers to how the pipeline was triggered.
I could use two different pipelines with different YAML configurations, but that's not ideal.
Thanks for your time and your help!
Answer: You can find here the env variable Build.Reason:
Manual: A user manually queued the build.
IndividualCI: Continuous integration (CI) triggered by a Git push or a TFVC check-in.
BatchedCI: Continuous integration (CI) triggered by a Git push or a TFVC check-in, and the Batch changes was selected.
Schedule: Scheduled trigger.
ValidateShelveset: A user manually queued the build of a specific TFVC shelveset.
CheckInShelveset: Gated check-in trigger.
PullRequest: The build was triggered by a Git branch policy that
requires a build.
BuildCompletion: The build was triggered by another build
ResourceTrigger: The build was triggered by a resource trigger or it was triggered by another build.
So in your steps add the corresponding condition, for example:
and(succeeded(), eq(variables['Build.Reason'], 'IndividualCI'))


Como receber um dado em um componente React Native?

Question: Olá, Pessoal! Estou estudando react native e me deparei com um problema que não consegui resolver, tentei de todas as maneiras e procurei em vários lugares :(
Tenho uma lista de funcionários e cada funcionário possui um id, nome, cargo e setor. As operações de listagem e exclusão estão funcionando, porém, estou querendo fazer a operação de edição. para isso eu preciso do id do funcionário. Não estou conseguindo passar esse id para a outra tela, que seria a de edição do mesmo.
Este é o código até o momento:
return (

        <FlatList
            data={colaboradores}
            keyExtractor={item=>item.id}
            renderItem={({ item }) => (
                <View style={styles.item}>
                    <Text style={styles.nome}>{item.nome}</Text>
                    <Text style={styles.cargo}>{item.cargo}</Text>
                    <View style={styles.touchOpacity}>
                        <TouchableOpacity style={styles.buttonEditar} id={item.id} onPress={()=>navigation.navigate('EditarColaboradores')}>
                            <Text style={styles.textButton}>Editar</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.buttonExcluir} onPress={()=>excluiColaborador(item.id)}>
                            <Text style={styles.textButton}>Excluir</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            )} />

    )

Este é o arquivo de edição:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import {
    View,
    Text
} from 'react-native';

const EditarColaborador = (props)=>{

    return(
        <View>
            <Text>
                Editar Colaborador
            </Text>
            {
                console.log(props.id)
            }
        </View>
    )

}

export default EditarColaborador

Eu achei que escrevendo uma propriedade chamada ID no botão e "recebendo" ela no 'props' do arquivo destinatário iria resolver o problema. mas o valor de props.id é "undefined"
Answer: Você precisa passar os parâmetros pela rota utilizando o navigation do react navigation, adicionando um objeto com as informações:
navigation.navigate('Home', { post: postText });

Para pegar na próxima pagina basta utilizar o route.params
 const {post} = route.params;

ou
const {post} = props.route.params;

Também não acho uma boa ideia utilizar um console.log dentro do seu jsx, basta printar só o Id mesmo interpolando com chaves: { id } ou { props.id }