How to check for mcrypt existence at the start of moodle installation

Question: I am new to moodle. Would really appericiate if you people can help me out here.
I am creating a repository plugin in moodle for which I need that mcrypt has to be installed before moodle get installed on the machine. I was wondering if any of you can tell me how I can I stop moodle installation if mcrypt is not installed, as I don't want to temper core files of moodle.
Thanks in advance...:)
Answer: Use the extension loaded method
<?php
if (!extension_loaded('mcrypt')) {
    // do something if you don't have mcrypt
}

// run rest of script as normal with mcrypt installed

Comment: Thanks a lot but I don't want to change my core files so plz guide me how to put an extra file when installing the moodle.
Comment: I can't see how you would prevent `moodle` itself from being installed unless you either change the core files or build some kind of pre-installer that runs your checks then triggers the moodle installer if they pass


Prove using mathematical induction: $1 \cdot 2 \cdot 3 + \ldots + n \cdot (n+1) \cdot (n+2) =  \frac{n(n+1)(n+2)(n+3)}{4}$

Question: So I have the easy stuff done. However, I'm not sure how to go about doing the inductive step with such an awkward proof. :/
Statement:
$$ 1 \cdot 2 \cdot 3 + … + n \cdot (n+1) \cdot (n+ 2) = \frac{n \cdot (n + 1) \cdot (n + 2) \cdot (n +3)}{4} .$$
Base step: $n = 1$:
$$ 0  \cdot (0 + 1) \cdot (0 + 2) + 1 \cdot (1 + 1) \cdot (1 +2) = \frac{ 1 \cdot (1+ 1) \cdot (1 + 2) \cdot (1 + 3) }{4} .$$
$$ 0 \cdot (0 + 1) \cdot (0 + 2) +1 \cdot (1 + 1) \cdot (1 +2) = 0 + 6 = 6$$
$$ \frac{ 1 \cdot (1+ 1) \cdot (1 + 2) \cdot (1 + 3) }{4} = \frac{24}{ 4} = 6 .$$
$$6 = 6.$$
Inductive step:
$n = n + 1$
Comment: Not to be too picky here, but: there is no part of mathematical induction in which we set $n$ equal to $n+1$!
Comment: See also http://math.stackexchange.com/questions/15145/a-general-formula-for-sum-k-1k-2k-3
Comment: Actually, the base case is also not that right. In the left hand side, you are supposed to add $n$ terms starting with $1 \cdot 2 \cdot 3, 2 \cdot 3 \cdot 4$ and so on. So for $n=1$, you should have 1 term; namely, $1 \cdot 2 \cdot 3$. You added a spurious $0 \cdot 1 \cdot 2$ term. Well, I agree that extra term is just $0$, but in some other series, that might not be so and your base case could come out wrong.
Comment: I agree with Jonas. Just divide everything by six, and stare long and hard at Pascal's triangle.
Answer: Recommendation 1. Never, ever, write "$n=n+1$". It's just wrong.
Recommendation 2. It's easier if you state the inductive step in two parts: state the induction hypothesis explicitly, then state what you need to prove.
(Recommendation 2 is my strongest recommendation, especially if you are beginning induction and are having some difficulty; it helps organize your thoughts, it helps you keep straight what you are assuming vs. what you want to prove, it helps prevent confusion between the inductive step and the theorem as a whole. It's a chore, perhaps, but I really do strongly recommend doing it).
Recommendation 3. It is often useful to prevent confusion by stating the inductive step using a letter different from what you are trying to prove, so that your "induction hypothesis" doesn't get confused with the theorem to be proven; using a letter that is not being used for anything else can help. (It also prevents writing things that bring such horror to a trained mathematician like "$n=n+1$"...)  Here, the statement we are trying to prove uses $n$ for the variable and nothing else. To avoid getting confused, use $k$ for the induction hypothesis and $k+1$ for what you need to prove in the induction hypothesis.
This is purely aesthetical; it plays no mathematical role. It's just a way to prevent possible confusion, and nothing more.
Here, try this:
Inductive step.
Induction hypothesis: The result holds for $k$. That is, we assume that:

$$(1)(2)(3) + (2)(3)(4) + \cdots + (k)(k+1)(k+2) = \frac{k(k+1)(k+2)(k+3)}{4}$$
  is true.

To be proven: The result holds for $k+1$; that is, we need to prove that:

$$\small (1)(2)(3) + (2)(3)(4) + \cdots + (k+1)\bigl((k+1)+1\bigr)\bigl((k+1)+2\bigr) = \frac{(k+1)(k+2)(k+3)(k+4)}{4}.$$
  is true.

(The above is what I mean by "state the induction hypothesis explicitly, then state what you need to prove)
Okay let's try to prove that the second highlighted statement is true. With induction, we want to bring the Induction Hypothesis into play somehow; usually, by trying to think of the $k+1$ case as being "do the $k$-step and then do something else"; then we can use the induction hypothesis to simplify the "$k$-step".  This works very well here.
We have:
$$(1)(2)(3) + (2)(3)(4) + \cdots + (k+1)(k+2)(k+3).$$
In order to think about it as "the $k$-step and then a bit more", let's write the the $k$th summand as well as the $k+1$st:
$$(1)(2)(3) + (2)(3)(4) + \cdots + k(k+1)(k+2)+ (k+1)(k+2)(k+3).$$
Now, we can do the sum by first adding the first $k$ summands, and then adding $(k+1)(k+2)(k+3)$ to the result of that; so the entire sum we have is equal to:
$$
\Biggl( (1)(2)(3)+(2)(3)(4)+\cdots+k(k+1)(k+2)\Biggr) + (k+1)(k+2)(k+3).$$
Now, we may realize that the stuff inside the big parenthesis is precisely
the sum about which the Induction Hypothesis tells us something. The Induction Hypothesis says that:
$$(1)(2)(3) + (2)(3)(4) + \cdots + (k)(k+1)(k+2) = \frac{k(k+1)(k+2)(k+3)}{4},$$
so we can replace that first parenthetical expression with $\frac{k(k+1)(k+2)(k+3)}{4}$. So, in summary, we have:
$$\begin{align*}
(1)(2)(3) &+ (2)(3)(4) + \cdots + k(k+1)(k+2)+ (k+1)(k+2)(k+3)\\
&=\Biggl( (1)(2)(3)+(2)(3)(4)+\cdots+k(k+1)(k+2)\Biggr) + (k+1)(k+2)(k+3)\\
&= \Biggl(\frac{k(k+1)(k+2)(k+3)}{4}\Biggr) + (k+1)(k+2)(k+3)
\end{align*}$$
with the first equality being just by associativity of the sum; and the second equality justified because we have applied the induction hypothesis.

That is, we have simplified the sum of the first $k$ terms through the use of the induction hypothesis.
Can you take it from here?
Comment: @Pete: Thank you very much. To quote Faramir in "The Two Towers",'praise from the praiseworthy is beyond all rewards.'
Comment: +1: Arturo, your ability to crank out these high quality answers nearly instantaneously is amazing "even" to me...
Comment: @Pete: I recommend switching to a letter not being used *only* to prevent confusion between the statement of the theorem we are proving, the induction hypothesis, and what you need to prove; I should say that explicitly, though. My main and strongest recommendation for beginning students, though, is Recommendation 2: write out what your induction hypothesis is *explicitly* and have it handy; then write out *explicitly* what you are trying to prove, and have it handy. *Then* go on to prove it. But I certainly agree that if you *think* you have to change it, then you didn't really "get it".
Comment: Here is a more random comment: I see that you endorse "switching from $n$ to $k$" in induction proofs, as is quite commonly done. I can never bring myself to do this, which means that I often get asked questions like "Is it okay that I used $k$ instead of $n$?" My somewhat crotchety position on this is that if you think you need to switch the name of the "dummy" variable then you haven't fully understood the logic of induction. (Also, what happens when there is also a $k$ in $P(n)$, e.g. when working with binomial coefficients??) What do you think about this?
Comment: Thanks guys. I appreciate the response. However your response could've had a little more clarification on your last equation, iit was confusing how you got there. Thanks though for the help!
Comment: @Patryk: Is that less confusing?
Answer: For the record, the "correct" way to prove this identity is combinatorially. Written differently (after dividing both sides by $6$), it reads
$$ \sum_{k=3}^{n+2} \binom{k}{3} = \binom{n+3}{4}. $$
This is because each $4$-subset of $[n+3]$ is composed of its maximum $k+1$ and a $3$-subset of $[k]$.
Answer: $$1 \cdot 2 \cdot 3 + \cdots + n(n+1)(n+2) = \frac{n(n + 1)(n + 2)(n + 3)}{4}.$$
Step 1: (Must prove that the given relation is true for $n=1$)
$$p(1): 1\cdot 2\cdot 3=\frac{1\cdot (1+1)\cdot (1+2)\cdot(1+3)}{4} \Rightarrow 1\cdot 2\cdot 3= 1\cdot 2\cdot 3.$$
The base case is true.
Step 2: Suppose thaat the given relation is valid for $n=k$.
$$p(k): 1\cdot 2 \cdot 3 + \cdots + k(k+1)(k+2) = \frac{k(k + 1)(k + 2)(k +3)}{4}.$$
Step 3: Now we must prove that the given relation is correct for $n=k+1$.
$$p(k+1): 1\cdot 2 \cdot 3 + \cdots + (k+1)(k+2)(k+3) = \frac{(k+1)(k+2)(k + 3)(k +4)}{4}.$$
The above relation can be written:
$$\underbrace{1\cdot 2 \cdot 3 + \cdots + k(k+1)(k+2)} + (k+1)(k+2)(k+3) = \frac{(k+1)(k + 2)(k + 3)(k +4)}{4}.$$
The underlined partion in fact is the step 2. So we have
\begin{align*}
& 1\cdot 2 \cdot 3 + \cdots + k(k+1)(k+2) + (k+1)(k+2)(k+3) \\
 & = \frac{k(k + 1)(k + 2)(k +3)}{4} + (k+1)(k+2)(k+3) \\
 & = \frac{k(k+1)(k+2)(k+3) + 4(k+1)(k+2)(k+3)}{4} \\
 & = \frac{(k+1)(k+2)(k+3)(k+4)}{4}.
\end{align*}
Comment: -1. Duplicates previous answer and errs seriously in using implications.


How does this ipv4 network card understand this ipv6 listening server?

Question: So, I just setup a new server on a droplet and looking at eth0 with ifconfig I can see that the network card is setup for one IPv4 address and one IPv6 address (IPv4 changed for protection):
inet addr:192.168.111.111  Bcast:192.168.111.255  Mask:255.255.240.0
inet6 addr: fe80::601:29ff:fe72:9601/64 Scope:Link

I see that the IPv6 is local since it starts with fe80.
Then I setup Apache2 and attempt a load of the front page using the IPv4 address (because I did not setup the AAAA record for an IPv6, it has to be the IPv4 plus the IPv6 is local.) However, when I look at the listen, the Apache2 server looks like this:
tcp6       0      0 :::443                  :::*                    LISTEN

The SSH listener does the same thing.
So what I'm wondering is... how can the system connect the incoming IPv4 to the listening IPv6? Before, as I recall, I had to change the Apache2 setup to force a listen on the IPv4 address instead.
I have another question, since the IPv6 is a local address, I would imagine I can DROP most everything in my ip6tables, correct? Leave the lo interface alone, but drop anything else, what would you say?
Answer: Some application can use v4-mapped-on-v6, supporting both protocols at once with minimum modification.
Did you check if the IPv4 was actually working?
http://linux.die.net/man/7/ipv6

IPv4 connections can be handled with the v6 API by using the
  v4-mapped-on-v6 address type; thus a program only needs to support
  this API type to support both protocols. This is handled transparently
  by the address handling functions in the C library.
Comment: Ah! That looks like the correct answer. It makes sense although I always thought that you'd have to write your program to support both IPv4 and IPv6. It's cool we don't have to support IPv4 anymore.


Renderizar html para múltiplas pastas no servidor

Question: Estou em busca de uma implementação que me possibilite publicar o mesmo html em vários domínios da minha hospedagem. Meu objetivo é centralizar o controle da mesma em apenas uma aplicação. Gostaria de saber se isso é possível e qual a tecnologia capaz de resolver esse problema.
Answer: De forma simples e pouco técnica, mas que te dê margem para avançar:

Apontar o DNS de todos os domínios para o mesmo servidor;
Configurar o servidor web (nginx/apache/iis) para direcionar TUDO para o mesmo diretório;

Isso fará com que seu sistema esteja acessível independente se o usuário veio de www.dominio1.com.br ou www.dominio48.com.lo.
Daí caberá a sua aplicação identificar isso internamente e fazer o que você quiser.
Se atente ao controlador de Sessão da aplicação, isso pode estar atrelado ao dominio e precise tratar.
Se você implementar mais informações a sua pergunta, posso implementar mais detalhes aqui para facilitar.


Does Android Speech Synthesis do not work for HTC Dream firmware version 1.6 build DRD20?

Question: I have a HTC Dream firmware version 1.6 build DRD20.
I am unable to install voice data in Menu ==> Settings ==> Speech Synthesis ==> Install voice data. The option just brings me back to previous screen of settings. I also tried installing Speech Synthesis Data Installer and many other applications for text to speech. But none works and give back Sorry! Force close error. Is there any way by which I can install voice data ? Or any way I can use text to speech ?
Can anyone also tell what is latest offical firmware available for this mobile ?
Answer: Answering my own old question. Text to speech did not work in any case. But now installed  cynogenmod 6.1 running Froyo made it possible installing voice data .. and now everything .. all apps using TTS feature works !


How to loop through list and get every href value?

Question: I am using a for loop to loop through a list that has links and I am trying to get the href's value's and not being successful.
I can return the links by doing this..

let me = $('#wizTabs li a');

but not able to still get the href.
I have tried me[i].attr("href") and I get an error about attr not being a function.
I also tried just $(this) and that didn't work

let me = $('#wizTabs li');

for (i = 0; i < me.length; i++) {
  console.log(me[i]);
}

Customer Info

Contacts

Ship To Info

Company Info

Comment: me[i] is not a jQuery collection you cant use .attr() on it. its a DOM element
Answer: looping a jQuery collection with a for loop will give you the DOM elements of this collection and therefore you cannot use jQuery methods on them. you will have to wrap the DOM element in a $() in order to be able to use jQuery methods on it.

let me = $('#wizTabs li a').each(function(){
  console.log($(this).attr("href"));
});

//Javascript solution
for (i = 0; i < me.length; i++) {
  console.log(me[i].getAttribute("href"));
}

Customer Info

Contacts

Ship To Info

Company Info

Comment: @Stakvino yes, and making that part of the answer would be better. Not everyone reads all the comments.
Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
Comment: `this` within iteration is actual JS DOM object, so you also could get `href` value just like `this.href` (without using jQyery)
Comment: i actually did a comment on the question
Comment: Well, considering you are changing `for (...)` with `.each()` and then still wrapping `this` in a jQuery object, it's actually less-efficient than the OP just doing `$(me[i]).attr("href")`. Both of which are less efficient than just `me[i].href`. So, some explanation on why your answer solves the problem is highly recommended.
Comment: @Andriy Which is what the OP had to begin with, with `me[i]`.
Comment: how comes ? my english is bad
Comment: @Stakvino `this` inside your `each()` iterator is exactly equivalent to `me[i]`. It's a DOM element. In order to get jQuery wrapper around the DOM element, you have to wrap `this` in `$()`, which you can also do with `me[i]`. So, `$(this)` is equivalent to `$(me[i])`. `.each()` vs `for (...)` is not the crux of the OP's issue.
Comment: true but looping with jQuery each method will return the collection for chaining and this is why i use it when working with jQuery and i just learned jQuery this month so i might be wrong somewhere
Comment: This solution works for using JQuery, but what about in plain javascript? @mhodges, me[i].href returns it as a link, but I just want the href text
Comment: @Stakvino, perfect. Thanks
Answer: I have included here 2 different ways to do it.

Using jQuery map, using jQuery to grab the array and loop through it, each does the same thing.
Using vanilla javascript on the array you already got.

NOTE they provide different values for href, one fully qualified and one not.  I did modify your selector to target the anchor and not the list-item

let me = $('#wizTabs li a');
//using jquery map
$(me).map(function(idx, elem) {
  console.log($(elem).attr("href"));
});
//minimal changes to your code
for (i = 0; i < me.length; i++) {
  console.log(me[i].href);
}

Customer Info

Contacts

Ship To Info

Company Info

Comment: The me[i].href returns as a link but I just need the text as you shown by using map
Answer: document.links
The most easiest HTMLCollections.
document.links gets you all links on a page
The following one liner uses:

document.links to gather the links into a NodeList

Array.from() to convert the NodeList into an array

map() to get the value of each [href] attr/prop.

var lnx = Array.from(document.links).map((A, i) => A.href);

console.log(lnx);
a::after {content:' 'attr(href)}

document.links


How do I create a field template or template override for a specific display mode?

Question: Because in the Drupal 7 Commerce module, the fields, 'sku,' 'title,' and 'status' aren't editable by Display Suite field wrappers, I'm unable to edit the field wrapper via the Drupal front end, I need to use a template to update "commerce-product-title.tpl.php" with an H2 wrapper, but I only need this for the 'product_full' view mode on all products. Is there a way to target this field in this display mode only with a template or theme function?
Comment: Possible duplicate of [How to provide template for particular view mode?](https://drupal.stackexchange.com/questions/27025/how-to-provide-template-for-particular-view-mode)
Comment: I am looking specifically for instructions on field templates as opposed to node templates.
Answer: Fields
You have to add the theme hook suggestion yourself, first. For fields it's just the same as for nodes. Simply place the following snippet in your theme's template.php or your module's *.module file and replace MYTHEME/MYMODULE with your theme's or module's machine name.
Now copy the /modules/field/theme/field.tpl.php file over to your theme's /templates directory and name it along one of the following patterns:

field--field-name--view-mode.tpl.php
field--field-name--bundle--view-mode.tpl.php

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_field(&$variables) {

  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];
  $bundle = $variables['element']['#bundle'];

  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $view_mode;
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $bundle . '__' . $view_mode;
}

Commerce Product title
For Commerce' product titles though things are a little bit different, as you don't get the view mode or the referencing entity from within its preprocess hook. But you can simply use your own logic to add your template suggestions. For example a pattern in the URL alias or something like that.
Then copy the /sites/all/modules/contrib/commerce/modules/product/theme/commerce-product-title.tpl.php file over to you theme's /templates directory and rename it along your desired pattern.

commerce-product-title--foo.tpl.php

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_commerce_product_title(&$variables) {

  // The following suggestion only gets added when there's
  // a certain keyword at the third position in the URL alias
  // as in /myproducts/overview/foo/myproduct.
  if (arg(2, drupal_get_path_alias()) === 'foo') {
    $variables['theme_hook_suggestions'][] = $variables['theme_hook_original'] . '__' . 'foo';
  }
}


MS Access can see item in the watch window but error thrown saying "item not found in this collection"

Question: Trying to assign a value from one DAO recordet to another. And getting error 3265 "Item not found in this collection". However when i look in the watch window the collection item and value is available. Am I not using the correct syntax here?
So the 'Select' involved in the 'rs' grabs a query statement from the database
the query is executed in rs2 and the the first field should be posted back into the first recordset
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True

     qry = rs!Query

     'process the query
     Set rs2 = db.OpenRecordset(qry)
     If Not (rs2.EOF And rs2.BOF) Then
        rs2.MoveFirst
        Do Until rs2.EOF = True
            rs!NewValue = rs2.Fields(1).value

            rs2.MoveNext

            DoEvents

        Loop
     End If
...

When I look in the watch window under rs2.Fields, Count=1 and and 'Item 1' has the value expected. However as with the code execution if I look at rs2.Field(1) it reports "Item not found in this collection."
Any thoughts please?
Answer: Fields in recordsets are indexed from 0. Try this:
rs!NewValue = rs2.Fields(0).value


UWP CustomRenderer for Checkbox: Pointer over Checkbox changes style?

Question: I'm working with Xamarin.Forms and I made a CustomRenderer for Checkbox in UWP. When I set all the Checkboxes of my items in the ListView to true by clicking the button "Alle", the Checkboxes are displayed correctly with the check inside the box:

However, if I hover my mouse over the Checkboxes, they immediately change their appearence (the check disappears but it's still selected). In the following screenshot, I moved my cursor over the 3rd - 7th Checkboxes:

This is my overridden OnElementChanged method in the CustomRenderer:
protected override void OnElementChanged(ElementChangedEventArgs<EvaCheckbox> e)
{
    base.OnElementChanged(e);
    var model = e.NewElement;
    if (model == null)
    {
        return;
    }

    nativeCheckbox = new CheckBox();
    CheckboxPropertyChanged(model, null);
    model.PropertyChanged += OnElementPropertyChanged;

    nativeCheckbox.Checked += (object sender, Windows.UI.Xaml.RoutedEventArgs eargs) =>
    {
        model.IsChecked = (bool)nativeCheckbox.IsChecked;
    };

    nativeCheckbox.Unchecked += (object sender, Windows.UI.Xaml.RoutedEventArgs eargs) =>
    {
        model.IsChecked = (bool)nativeCheckbox.IsChecked;
    };

    SetNativeControl(nativeCheckbox);
}

I tried to override the PointerEntered event of nativeCheckbox. It works, for example if I set the model.IsChecked to true on this event, it will be set to true:
nativeCheckbox.PointerEntered += (s, args) =>
{
    model.IsChecked = true;
};

But I don't know how to (if even at this place) prevent the checkbox from changing it's appearance when moving the cursor above the Checkbox. Just leaving the triggered event with empty code like this won't change anything about the described behaviour:
nativeCheckbox.PointerEntered += (s, args) => { };

How can I prevent the Checkbox from changing it's appearance when I move my cursor over it?
Update:
I've created a sample project for this issue. You can find the repository here: https://github.com/Zure1/CustomCheckbox
It has the exact same described behavior. In the following screenshot I pressed the button "All" on the bottom of the screen and then the checkboxes look like correct with a check inside of them:

After moving the mouse cursor over the bottom 3 checkboxes, their change their appearance:

Information: I'm debugging on my desktop (Windows 10). I don't know if this issue exists on WinPhone. Just in case you're wondering why my checkboxes are red: My system color in Windows is red.
Answer: This is a tricky one as I have been struggling with this issue for a while, I'll try my best to answer this.
TL;DR: It's caused by ViewCell.
The issue comes down to Xamarin Forms ListView and ViewCell.
I haven't been able to track down the cause yet for many months and the way I get around this issue is by refreshing the ListView every time a change happens forcing a redraw of the entire ListView which can really impact performance.
My educated guess on what the cause could be is the rendering code for the ViewCell is missing something.
As for your particular issue, I have created a CheckBoxCell which you can use to display a list of checkboxes with a title. I forked your project and made the changes.
This will display something similar to what you are trying to achieve and doesn't have rendering issues so will be a good starting point. You are able to customize this to display images and the like but you'll have to do that in the platform-specific layout code.
Please note that I have only created the code for UWP and that should be enough to get you going for the other platforms.
I hope this helps somewhat.


Spaces that accept Turing Machines as points

Question: I know that is a naive question, but are there any mathematical spaces whose points consist of Turing Machines?
Answer: Let's identify Turing machines with natural numbers via your favorite indexing scheme. The positive topology on $\mathbb{N}$ then has as basis the sets $$\{e: F\subseteq W_e\}$$ for $F\subseteq\mathbb{N}$ finite, where "$W_e$" denotes the $e$th c.e. set (that is, the set of inputs on which $\Phi_e$ halts). Note that this is really a topology on c.e. sets, rather than on Turing machines - if $W_c=W_d$, then $c$ and $d$ are in exactly the same open sets (so in particular this space is not $T_0$, although we can fix this by instead thinking of this as a topology on the c.e. sets rather than their indices).
This topology, if I recall correctly, has some applications to priority arguments (Lachlan wrote some notes on topology for priority arguments, which I'm trying to get a hold of) and the theory of isols (see here or here); I'll post some specific links illustrating this application when I have time (and if my recollection is correct).
Comment: I have to learn so many things to grasp your answer :) Moreover, this means my question is not useless :)
Answer: I am not sure what kind of "spaces" you are interested in. In "Russian style" or "Markov style" computable/constructive analysis, real numbers are identified with algorithms: to give someone a real number means to give them an algorithm to compute that number.  So in this framework the "points" on the real line are, in some sense, Turing machines.
This causes several differences compared to classical analysis. The first is that equality is intensional, rather than extensional. Two different Turing machines can compute the same real numbers, so it is necessary to distinguish between having two different algorithms compares to having two genuinely different real numbers. This is a common feature of constructive systems.
The second change is that, because all real numbers are (by definition) computable in this framework, some classically valid results become invalid. For example, in this framework a Specker sequence simply does not converge, so the theorem that simply states "a bounded increasing sequence of rationals must converge" is false.  If we additionally require a computable modulus of convergence, then the theorem becomes true.  This is a second common feature of constructive mathematics: sometimes classical theorems require additional information to become constructively valid.
Comment: I am just a beginner of mathematical logic. As there are function spaces, I wondered if there any Turing Machine spaces. Your answer helps a great deal, thanks.


CGI Script not running in PHP file

Question: I have a CGI script in the server called script.cgi and I have added the following code to the domain vhost:
<code>   Action add-footer /cgi-bin/script.cgi
   AddHandler add-footer .htm .html
</code>
I have change it to:
<code>   Action add-footer /cgi-bin/script.cgi
   AddHandler add-footer .htm .html .php
</code>
If the page is HTML the code will run but if the page is PHP the code will not run.
Is there any code I need to add to the vhost so that PHP files can run this script?
****EDITED:****
I want to "inject" an HTML code in every possible page of the server this includes HTML and PHP files.
The code only works for html files and I don't know why.
Answer: Sorry, but I don't understand CGI is not PHP, it is Perl and this requires Perl/CGI support not PHP. PHP scripts have .php extensions, not .cgi/.fcgi.
Maybe I missed something here. Can you further clarify question. Like what web server you're using? Is this PHP code embedded into .cgi script or?
***** EDIT *****
So you can look at CGI as an interface, in your case interface that uses Perl. You cannot intermix PHP in CGI environment, but you can modify the .cgi script to make external call towards .php script.
This can be done in few ways:

system() command
exec() command
using handles
using backticks

The HTML "works" normally because HTML is interpreted by the browser and PHP is server-side language which must be executed in adequate environment.
I propose further reading on how Perl executes external scripts:
http://www.perlhowto.com/executing_external_commands
Comment: For question please use the COMMENTS section and not the ANSWER section.
Comment: I have edited the question...

CGI Script not running in PHP file


The indicator function of an open set is an increasing limit of a sequence of continuous functions

Question: Let $G$ be an open set on some measure space $(\Omega,\Sigma, \mu)$.
Show that the indicator function of $G$ is an increasing limit of a sequence of continuous functions.
I understand that this is a "simple text book exercise". I am only seeking for hints.
My idea (at least in 2D) is that we should construct some smooth trapezoidal-like functions, where the gradients near the endpoints of $G$ gets steeper and steeper.
Am I on the right track? Also, how do I write this out mathematically?
Comment: In order to measure the distance to the edge, you could use open balls in the space, since it is measurable. Something like $f(x)=0$ outside and $f(x)=\min(1,\sup\{nr:B(x,r)\subseteq G\})$ on the inside of $G$.
Answer: Every open set in a separable metric space is a union of a sequence of open balls. So start by working out how to write the characteristic function of an open ball as an increasing sequence of continuous functions. As you suggested, this can be done with trapezoidal functions that get steeper in a certain way. The endpoints of the trapezoids need to move to make the sequence increasing...
In the most general sense, a measure space consists of a set $\Omega$, a $\sigma$-algebra $\Sigma$, and a measure $\mu$. Because no topology is mentioned in this definition, it does not make sense to try to prove anything about "open" sets or "continuous" functions in a general measure space. You have to be talking about some class of topological measure spaces for those terms to make sense. In this way, the question is underspecified, because it does not specify what type of topological measure spaces are being considered. In general, whether every open set of a topological space is an increasing limit of continuous functions is a purely topological question, having little to do with measure theory.


Map Reducing with timezones

Question: I'm trying to map reduce a bunch of data in order to generate a daily graph, the catch is that the application has users from all over the world and they want the data in their own timezone.
The current map reduction I have is pretty simple
var map = function(){
var userLogin = this;

var d = this.StartTime;
var start = d.getFullYear() + '-' + d.getMonth() + 1, + '-' + d.getDate();

var reduceValue = {
    SuccessSession: 0,
    FailSession: 0
}

if(userLogin.ExitReason.Severity <2)
{
    reduceValue.SuccessSession += 1;
} else {
    reduceValue.FailSession += 1;
}

emit({ClientId: this.ClientId, StartDate:start, IsAdmin: this.IsAdmin},
    {SuccessSession: reduceValue.SuccessSession, FailSession: reduceValue.FailSession })
}

and the Reduce
var reduce = function(key, value) {
var reducedValue = {
    SuccessSession: 0,
    FailSession : 0
};

for(var idx = 0; idx < value.length; idx++)
{
 reducedValue.SuccessSession += value[idx].SuccessSession;
 reducedValue.FailSession += value[idx].FailSession;
}

return reducedValue;
};

The problem with this approach is that it calculates from midnight UTC to midnight UTC, however I'd prefer to be able to query the Map Reduced and still be able to query depending upon which timezone a user is in.
Is there any simple way to accomplish being able to mapreduce and yet keep the ability to use timezones?
Answer: No easy way. Map is a javascript, so you will need at least IANA TZ database there. Something like https://momentjs.com/timezone/ being available within the map function.
Would you consider aggregation framework instead of map-reduce? It has support of timezones and is much faster. The pipeline could be as simple as this:
db.collection.aggregate([
    { $group: {
        _id: {
            ClientId: "$ClientId",
            start: { $dateToString: {
                format: "%Y-%m-%d",
                date: "$StartTime",
                timezone: "Europe/Kiev"
            } },
            IsAdmin: "$IsAdmin"
        },
        "SuccessSession": { $sum: { $cond: {
            if: { $lt: [ "$ExitReason.Severity", 2 ] },
            then: 1,
            else: 0
        } } },
        "FailSession":{ $sum: { $cond: {
            if: { $lt: [ "$ExitReason.Severity", 2 ] },
            then: 0,
            else: 1
        } } },
    } }
])

Map Reducing with timezones


how to change hidden value with jQuery after clicking div

Question: I am appending some images in a function but when I click on any of the appended images I want to change the hidden value to "Yes". It is by default set to "No".
var id = $(this).data("id");
$( ".thumbs" ).append("

x
<input type='hidden' name='featured' value='No' id='hidden'>
");

Here is the code for when I click on the thumb-wrapper class:
$( ".thumbs" ).on("click", ".thumb-wrapper", function(e) {
        var hidden = $(this).closest("#hidden").val("Yes");
        alert(hidden);

This currently alerts "undefined".
An example of the generated HTML is:

x

 <input type="hidden" name="featured" value="No" id="hidden">

Comment: Can you post the HTML?
Comment: @PhaniKumarM, I have updated the original question.
Comment: Where does the first JS code implemented?
Answer: Your problem here is closest is searching through up. You need to use find instead to search down instead of up.
var hidden = $(this).find("#hidden").val("Yes");

Jquery closest official explanation:

Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

There were other related questions asking for an alternative to closest changing direction of search from up to down: Is there an equivalent to .closest() that searches down the DOM tree instead of up?
If you want to save the value on a var use:
var hiddenObj = $(this).find("#hidden");
var valueVar = hiddenObj.val();
alert(valueVar);

Comment: @user8463989  use `console.log()`  instead of alert to see what is inside objects! in chrome console
Comment: Thank you. the alert gives me [Object Object]. If I leave out yes and just have .val() then it alerts the current value i.e.: "No"
Comment: No, it gives me [Object Object] instead of "Yes".
Comment: Hmm. But the value of the hidden field does change. Just the alert says Object Object.
Comment: hidden is the object. Everything is ok. If you want to see the value put `alert($(this).find("#hidden").val("Yes"))`
Comment: If you want to save it on a var put this `othervar = $(this).find("#hidden").val()` and then `alert(othervar)`. I edited my answer with this.
Comment: Thank you. How do I change the value later? If I just get the current value `var hidden = $(this).find(".hidden").val();` and later want to change it after doing something? I tried `$(hidden).val("Yes");` but that does nothing
Comment: Sorry, I will ask a new related question
Answer: You better change the input hidden to class:
 <input type="hidden" name="featured" value="No" class="hidden">

$( ".thumbs" ).on("click", ".thumb-wrapper", function(e) {
    var hidden = $(this).find(".hidden").val("Yes");
    alert(hidden);

you can not have multiple elements sharing the same id!


Rails: Can't save file from URL and save it to Amazon S3 (S3::Error::ResponseError)

Question: I am trying to save file from a URL and then save it to S3. This is the rake task code that I've written:
require 's3'
require 'open-uri'

task :testing => [:environment] do
  aws_object = S3::Service.new(access_key_id: Rails.application.secrets.aws_access_key_id, secret_access_key: Rails.application.secrets.aws_secret_access_key)
  bucket = aws_object.buckets.find(Rails.application.secrets.aws_bucket)
  url = 'https://pbs.twimg.com/profile_images/1111729635610382336/_65QFl7B_400x400.png'
  downloded_file = open(url)

  new_file = bucket.objects.build('twitter.jpg')
  new_file.content = (File.read downloded_file)

  if new_file.save
    puts "Success!"
  end
end

But when I run this rake task code above, this is what I got on my terminal:
rake aborted!
S3::Error::ResponseError: S3::Error::ResponseError
/Users/ryzal/Sites/test/lib/tasks/testing.rake:17:in `block in <top (required)>'
/Users/ryzal/.rbenv/versions/2.3.1/bin/bundle:23:in `load'
/Users/ryzal/.rbenv/versions/2.3.1/bin/bundle:23:in `'
Tasks: TOP => testing
(See full trace by running task with --trace)

I've checked all my S3 details and all are correct. Can somebody help?
Thanks!
Comment: Take a look at the error and see what is really happening.

    `begin
      # your code
    rescue Exception => e
      e.response.inspect
    end`
Comment: No idea about your version of the aws sdk, but s3 now always needs the region of your S3. https://docs.aws.amazon.com/de_de/general/latest/gr/rande.html
Answer: I've finally solved this and this is how I did it:
1) I use aws-sdk-ruby gem instead of s3 gem
2) I refer S3 documentation here and renew my code to this:
require 'aws-sdk-s3'
require 'open-uri'

task :testing => [:environment] do
  s3 = Aws::S3::Resource.new(region: Rails.application.secrets.aws_region)
  obj = s3.bucket(Rails.application.secrets.aws_bucket).object("any_unique_key_you_want_such_as_email_or_username")

  url = 'https://pbs.twimg.com/profile_images/1111729635610382336/_65QFl7B_400x400.png'
  file = open(url)

  obj.put(body: file, acl: "public-read")

  puts "URL is: #{obj.public_url}"
end


Decide if quotient module is free module

Question: Let $U=\{\lambda\cdot (-3+i):\lambda \in \mathbb{Z}\}$ a sub-module of the $\mathbb{Z}$-module $\mathbb{Z}[i]$ (Gaussian integers). Is $\mathbb{Z}[i]/U$ a free module?

My attempt:
It's pretty obvious that $\mathbb{Z}[i]/U$ is a straight line in the complex plane and that's very familiar with quotient spaces from linear algebra. So $\{-3+i\}$ is a basis in $U$. Now I have to complete this basis to a basis in $\mathbb{Z}[i]$, right?
I could just choose $\{\{-3+i\},\{i\}\}$, because they're linearly independent.
But I could in principal do the same for $V=\{\lambda\cdot(6+2i ):\lambda\in \mathbb{Z}\}$ but I was told that $\mathbb{Z}[i]/V$ is not a free module. I think this is because $(-3+i) + V \in \mathbb{Z}[i]/V$ and
$$\mathbb{Z}\times (\mathbb{Z}[i]/V) \longrightarrow \mathbb{Z}[i]/V, \quad (\lambda,x+V)\mapsto \lambda\cdot x +V$$
So choosing $\lambda=2$, we have:
$$(2,(-3+i)+V) = (-6-2i)+V=V$$
and $V$ is in that sense the neutral Element $0_{\mathbb{Z}[i]/V}$? I my thinking correct?
So it seems like I need to check something else to decide if $\mathbb{Z}[i]/U$ is a free module?
Comment: Modules over what? Over $\Bbb Z$? Over $\Bbb Z[i]$?
Comment: @Arthur $\mathbb{Z}$, sorry.
Answer: Claim: $\mathbb Z[\mathrm i]/U\cong \mathbb Z$ as $\mathbb Z$-modules.
Proof. One shows that the map $\phi:\mathbb Z[\mathrm i]/U\to\mathbb Z, a+b\mathrm i+U\mapsto a+3b$ is an isomorphism of $\mathbb Z$-modules, that is

$\phi$ is well-defined (one shows that if $a+b\mathrm i+U=c+d\mathrm i+U$, then $a+3b=c+3d$);
$\phi$ is a $\mathbb Z$-module (this is straightforward);
$\phi$ is surjective (as for $a\in\mathbb Z$, we have $\phi(a+U)=a$);
$\phi$ is injective (since $\ker\phi=0$).$\quad\tiny\blacksquare$

Since $\mathbb Z$ is obviously $\mathbb Z$-free (having $B=\{1\}$ as a basis), the module $\mathbb Z[\mathrm i]/U$ is as well.

To see what $\phi$ does intuitively, let us take a look at the following graph.

Each element of $\mathbb Z[\mathrm i]/U$ corresponds to one of the depicted lines (intersected with $\mathbb Z[\mathrm i]$). The map $\phi$ now sends each such line to its intersection point with the $x$-axis.
Comment: Very good answer, thank you! The graph was very helpful too!
Answer: As a slightly different perspective: first, we see that this has nothing to do with Gaussian integers. The question is equivalent to asking whether $\mathbb Z^2$ modulo $\mathbb Z\cdot (-3,1)$ is free.
It is probably worthwhile to note that $\mathbb Z^n$ modulo $\mathbb Z\cdot (v_1,\ldots,v_n)$ is free if and only if the greatest common divisor of integers $v_j$ is $1$. And that, in any case, the quotient is isomorphic to $\mathbb Z^{n-1}\oplus \mathbb Z/\mathrm{gcd}$.
Such stuff follows from a good version of the structure theorem for finitely-generated modules over PIDs.


'At most' and 'either' in combinations

Question: Five people are to be chosen from a group of ten people, to form a committee.
(b) Amongst the ten people, we have Alice, Bob, Eve and Oscar. Alice and Bob are extremely
talkative during meetings, and so at most one of these two can be chosen. Eve and Oscar are
inseparable, and so a committee must either contain both of them or neither of them. With these
constraints, how many different five-person committees can be formed?
I have the solution already, I just want to understand how to express 'either' and 'at most' and understand the solution. For the following answers, I don't understand the $2$ or $6$ in the ncr.
Comment: I think "ncr" means ${_n}{C_r} = C(n,r) = {{n}\choose{r}}$.
Comment: I don't know what you mean by "ncr."  The solution is essentially counting the number of possible combinations of committee members who are *not* any of Alice, Bob, Eve, or Oscar.  So, for example, if none of them are on the committee, you must choose $5$ members from the remaining $6$ people, which gives you $\binom 65=6$.
Comment: @RobertShore Thanks Robert, can you explain the first scenario?
Comment: If Alice is included and Eve and Oscar are out, there are $\binom 64=\binom 62$ ways to choose the other committee members.  (Choosing $4$ out of $6$ to include is the same as choosing $2$ out of $6$ to exclude -- that's  the combinatorial explanation for why $\binom 64=\binom 62$.)  It's exactly the same calculation if Bob is included and Eve and Oscar are out, so multiply that number by $2$ to account for both cases.
Comment: [You have been asked before not to use pictures of text.](https://math.stackexchange.com/questions/4712981/find-all-isomorphisms-between-this-group-and-itself-confusion#comment9980666_4712981)
Answer: We can divide the people into three groups: Alice and Bob, Eve and Oscar, and the other six people.  The number of ways of selecting $k$ people from the group that includes Alice and Bob, $m$ people from the group that includes Eve and Oscar, and $n$ people from the remaining six people is
$$\binom{2}{k}\binom{2}{m}\binom{6}{n}$$
The problem requires that we select at most one person from the group consisting of Alice and Bob, either zero or two people from the group that consisting of Eve and Oscar, and the remaining $n = 5 - k - m$ people from among the remaining six people.  Note that at most one means either $0$ or $1$ people since the number of people we select must be a nonnegative integer.
Let's consider cases:
One of Alice or Bob, neither Eve nor Oscar:  If we select one person from the group consisting of Alice and Bob and no people from the group consisting of Eve and Oscar, we must select $5 - 1 - 0 = 4$ people from the remaining six people.  There are
$$\binom{2}{1}\binom{2}{0}\binom{6}{4} = 2 \cdot 1 \cdot \binom{6}{4} = 2\binom{6}{4}$$
such selections.
Neither Alice nor Bob, neither Eve nor Oscar:  As Robert Shore explained in the comments, this means all five people must be selected from the group of six people, which can be done in
$$\binom{2}{0}\binom{2}{0}\binom{6}{5} = 1 \cdot 1 \cdot \binom{6}{5} = \binom{6}{5}$$
ways.
One of Alice or Bob, both Eve and Oscar:  If we select one person from the group consisting of Alice and Bob and select both people in the group consisting of Eve and Oscar, we must select $5 - 1 - 2 = 2$ people from among the remaining six people.  There are
$$\binom{2}{1}\binom{2}{2}\binom{6}{2} = 2 \cdot 1 \cdot \binom{6}{2} = 2\binom{6}{2}$$
such selections.
Neither Alice nor Bob, both Eve and Oscar:  Can you finish this case on your own?

'At most' and 'either' in combinations


Unable to find package Microsoft.AspNet.SignalR

Question: I'm trying to install SignalR on Visual Studio 2010
PM> Install-Package Microsoft.AspNet.SignalR -Version 1.2.2

and
PM> Install-Package Microsoft.AspNet.SignalR

I have the following error

Unable to find package 'Microsoft.AspNet.SignalR'
Comment: This could be because your Nuget is set to look at a package source that isn't the official Nuget one.  Check your nuget package sources.
Comment: This is my package source : https://www.nuget.org/api/v2/ (official)
Answer: I've tryied to specify a package source with
-Source nuget.org

It works!
PM> Install-Package Microsoft.AspNet.SignalR -Source nuget.org

Comment: See, I told ya so :)
Comment: Haha yes :) Thanks you!


Tensorflow: Select one column index per row using a list of indices

Question: I saw questions 39684415, 37026425, and 40722200 which have answers and asked the same question.
However, these were asked over a year ago, and I was wondering if there was an updated answer to do this more efficiently. In addition, I wasn't sure if they were differentiable due to the use of gather_nd.
Comment: gather_nd is differentiable
Answer: It's easy to implementation.
For example, suppose you have a tensor data [[1,2],[3,4]], you want to get the first column.
you can use tf.transpose(data, perm=[1, 0]) and tf.gather_nd(data, [[0]])
<code>import tensorflow as tf
import numpy as np

data = [[1, 3], [2, 4]]

a = tf.Variable(initial_value=data, dtype=tf.float32)
b = tf.transpose(a, perm=[1, 0])
fc = tf.gather_nd(b, [[0]])

init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    column = sess.run([fc])[0]
    print(column)
</code>
Comment: Actually, If you want to get sequential columns, you can directly use `y=x[:,begin:end]`. But if you want to use random integer list to select columns  as long as you construct a list like [[a],[b],[c]] and use the method metioned.


Laravel Numbers Only Validation

Question: How to validate only numbers in laravel?
I've try numeric and digits but it accept + and - character as a valid numbers / digits which I don't want. (+123 or -123 is validated as valid numeric)
Is there a existing rule on laravel that only accept 0-9 as a valid numbers or I have to go with regex instead?
Comment: You could do integer
Comment: @tam It's still accept + and - and cannot use 0 at front. (0123) is not valid
Comment: Oh right. Well ya I think u gotta use regex bc the PHP function is_numeric allows for the sign, it's a very simple regex though
Answer: So I end up using regex instead.
regex:/^[0-9]+$/

Answer: try this rule :
digits_between:min,max

it only allows numbers, you just need to specify the min and max number of digits.
exemple:
'CowsNumber' => 'digits_between:3,10',

Laravel Numbers Only Validation


Element UI not showing data from fetch-suggestion  vue js

Question: I've been switching from el-select remote search to remote search input el-autocomplete. My problem the data are not showing in the dropdown.
<el-autocomplete
v-model="searchValue"
:fetch-suggestions="getData"
placeholder="Type here"
loading="loadingCascade"
</el-autocomplete>

VueJS in methods code
getData(searchString){
            if (searchString !== '') {
                this.loadingCascade = true

                setTimeout(() => {
                        this.$API.Public.getData(searchString)
                        .then(res => {
                            let result = res.data
                            let resSearchList = result.data
                            //Include search data
                            let arr = {id : searchString, name : searchString}
                            resSearchList.unshift(arr)

                            this.searchList = resSearchList.name

                        })
                        .catch(err => {
                        })
                        .then(_ => {
                            this.loadingCascade = false
                        })

                }, 500);
            }

        },

Answer: Method must have callback function. Change getData() method something like:
getData(searchString, cb) {
  if (searchString !== '') {
    this.loadingCascade = true

    setTimeout(() => {
      this.$API.Public.getData(searchString)
        .then(res => {
          let result = res.data
          let resSearchList = result.data
          //Include search data
          let arr = {
            id: searchString,
            name: searchString
          }
          resSearchList.unshift(arr)

          this.searchList = resSearchList.name
          cb(this.searchList); // call callback function to return suggestions
        })
        .catch(err => {})
        .then(_ => {
          this.loadingCascade = false
        })

    }, 500);
  }

},

You can look at the usage here
Comment: like this ```const results = [this.$API.Public.getData(searchString)]```?
Comment: If `this.$API.Public.getData(searchString)` returns an Array, just `const results=this.$API.Public.getData(searchString)` is enough.
Comment: The important thing is to fill results according to the API, and call callback function for this results
Comment: still not working, cannot display the item name on the fetch suggestion
Comment: Could you add  `console.log(results)` before the line `cb(results)`, and share the output of the console.log?
Comment: I have edited the answer, please take a look again.


Convert integer to string on bidirectional binding

Question: In the project I am working on, have a dropdown field component which is being used for all the dropdown fields thorough out the application.
The component has an @input options which gets the options for the dropdown in this format [{value: '', label: ''},.. ]
This works with most of my dropdowns , but for one, the value comes as integer. As '2' !== 2 , the dropdown cant display the value.
<mat-select class="form-control" [(value)]="value">
   <mat-option *ngFor="let option of options" [value]="option.value">{{option.label}}</mat-option>
</mat-select>

There is a similar issue reported on github.
As this comment, I can have have a work around for this by having input and output separately.
<mat-select class="form-control" [value]="value.toString()" (change)="value = $event.value">
    <mat-option *ngFor="let option of options" [value]="option.value">{{option.label}}</mat-option>
</mat-select>

But I wonder, anyone have a nice solution for this problem.
Many Thanks,
Notes: (Pls don't suggest to change the value to integer type, as this will affect other dropdowns which has uuid etc as value)
Answer: [value]="option.value"

Convert it to
[value]="{{option.value}}"

Comment: This doesn't work and cause error.

Uncaught Error: Template parse errors:
Parser Error: Got interpolation ({{}}) where expression was expected at column 0

Even using value="{{option.value}}" doesn't work


Round to Even Rule

Question: The standard practice for rounding numbers appears to include the "round to even" rule for cases where the digit to the right of the least significant digit is equal to 5. Here is an example from
http://www.chemteam.info/SigFigs/Rounding.html
Example #4 Round
24.8514 to three significant figures. Look at the fourth digit. It is a 5, so now you must also look at the third digit. It is 8, an even number, so you simply drop the 5 and the figures that follow it. The original number becomes 24.8. (rule #3 above)
They say that the intent of this rule it to ensure that in the long run we round up as often as we round down. If we are dealing with real numbers with infinite precision, this rule is of course unnecessary. But how about the case when we are working with floating point representations of real numbers that carry 16 or more digits of precision as would be stored internally in a computer. It seems to me that we could dispense with the round to even rule in this case with little risk of having an imbalance of round ups and round downs in the long run. Does this sound reasonable? If so, can someone offer a reference that discusses this subject and comes to the same conclusion that I did?
Comment: https://en.wikipedia.org/wiki/Rounding#Round_half_to_even This discussion here seems relevant. Also, review the IEEE standard for more information about this system.
Comment: The probability of getting exactly 0.5 floating-point number in a computer is not zero.
Comment: Did you read the next paragraph? "This method treats positive and negative values symmetrically, and is therefore free of sign bias. More importantly, for reasonable distributions of y values, the average value of the rounded numbers is the same as that of the original numbers. However, this rule will introduce a towards-zero bias when y − 0.5 is even, and a towards-infinity bias for when it is odd."
Comment: Thank you for your clarification.  I am now wondering what "probability" you are referring to.  In some (real) applications half or more of the numbers are exact half-values! (One example: mean counts in paired data.) It therefore seems you might have some particular application or model in mind that governs the creation of numbers that will be rounded.  What is it?
Comment: This reference also gives the unhelpful example of "Thus, for example, +23.5 becomes +24, as does +24.5; while −23.5 becomes −24, as does −24.5." What about the case when we have 23.5[13 more digits]? Is there any practical need to follow this rule?
Comment: "If we are dealing with real numbers with infinite precision, this rule is of course unnecessary."  The justification for this eludes me: could you explain?  I suspect you are making some implicit assumptions which, if brought into the open, might indicate how to frame a useful answer.
Comment: I am saying that if we round 23.50000000000000 to 24 and 24.500000000000000 to 25 (i.e., don't use the round to even rule) that any bias introduced is of no practical significance because the probability of getting exactly in a X.50000000000000 in a result is very small compared to getting X.5.
Comment: What is the probability of getting exactly 0.5 in a real number? It is 0, so the round to even rule would never be invoked.
Comment: True, but I specified a real number in my statement, not a floating point number.
Comment: It doesn't matter what's the real number in the context of your question. There's no need in rounding if you could operate real numbers. You get them in the computer, and it becomes a floating-point.
Comment: @Aksakal, please read the comments in order. I was responding to whuber's question about my original posting.
Comment: The data are radiochemical analytical results and their associated uncertainties. Both are reported to machine precision (16-17 digits). The uncertainty is rounded to 2 significant digits and the result is rounded to match the uncertainty.The chances of having to invoke the "round to even" rule with these data seems very small to me.
Comment: I strongly doubt those results have accuracy comparable to that precision.  At some point it would likely be helpful to report the values in a more realistic manner, using only a few significant figures.  That's typically where rounding plays a role.
Comment: @whuber There's no way radiochemical analytical results are measured at 16 digits accuracy. In my distant past I dealt with that kind of data, it was nowhere near that precision. I'd love to know what kind of experiment generates this data
Comment: @Aksakal That's right.  Indeed, *no data in the world* are that accurate. In this context, though, I think it's important to maintain the distinction between *accuracy* and *precision*.  These data likely were obtained as counts (of detected decay events) divided by measured times, then renormalized according to some calibration (and then perhaps adjusted for a measured or assumed background).  As a result they indeed can be recorded with 16 digits *precision* despite having (at most) a few digits *accuracy*.
Comment: @whuber, in radiochemistry it's not just the decay event counts. It's things like concentration of radioactive elements in samples, these are measured by chemical and physical methods other than decay counts. however, I agree with you in principle that the calculations will in fact produce floating point numbers with whatever number of digits that they can hold. Even in this case, say you have 16 digit number, at the time when you publish this in phys/chem journal you have to round it to significant digits, so you'll get ties left and right, like in examples in the comment to my answer below.
Answer: There's more than one rounding rule. I doubt you'll find the reputable reference that comes to the same conclusion as you did.
There are many rounding rules. Particularly, in the floating point IEEE standard there are at least five different rules. Some programming languages such as Java support multiple rules.
Also, note that there are different ways to represent floating points even with IEEE 754 standard, e.g. binary and decimals, which may have different default rounding modes. It's not always binary representation.
Comment: I understand that there are many different rounding rules. Thanks for pointing out IEEE 754, which I was not familiar with. My question deals with one particular rule, the "round to even rule." It appears to be of practical significance only when one is presented with low precision results like in the example I gave. I was seeking feedback on that hypothesis.
Comment: On practice most inputs are "low precision" in your definition. Consider typical weight and length measurements of people or animals: hardly 3 or 4 significant digits are used. Once you calculate the mean you have to round to the same 3 or 4 digits. You are bringing up highly theoretical examples which are probably encountered in quantum physics only, even there rarely. Where do you ever get 16 significant digits input?
Comment: I never said that all of the 16 digits were significant. Of course they are not. I am being presented with the double precision output of a code that calculates the concentration of an analyte in a sample. I am trying to round the result  to an appropriate number of significant digits based on the uncertainty of the measurement. When you round a 16 digit result like this to a 2 to 4 digit result (which is more reasonable as you say) the round to even rule will almost never be invoked. All I am looking for is a conversation that leads to a yea or nay to this idea.
Comment: Don't use this rule if you don't like it. You can switch the rule. The rule will be invoked though if you use it. E.g. if you round 4.456678943 or 4.3566589653 to 2 digits you get 4.4 for both numbers with round to even. Finally, think logically, why would people wrote ieee754 if the rule was not reasonable?
Comment: In R, which implements the round to even rule: signif(4.456678943,2)
= 4.5 and signif(4.3566589653,2) = 4.4.
Comment: @Thomas, you're right. that was a terrible example. the argument is still the same: there are many cases when your data comes in two digits or so of precision, and having exactly 0.5 is highly probable. that's why this rounding rule is also called banker's rule, think of dollars and cents.
Comment: You all have answered my question (just use the standard rounding rules). Thanks for the lively discussion!
Answer: The core of the question was about floating point representation of numbers and rounding. Floating point numbers are hard to reason about but easy to experiment with.
Given a modern computer, based on floating point arithmetics, we can use a reasonable random number generator and produce continously distributed random data, e. g. normally distributed data, and round them. We can count how many times rounding is upwards or downwards an perform a binomial test to see, whether there is a tendency towards one of them.
The following R code does that with 10^8 random numbers
set.seed(42)
# huge number of random numbers normally distributed around 100:
sampled <- rnorm(1e+08, mean=100, sd=1)
# boolean count, whether a number was rounded upwards
rounded_up <- round(sampled)>sampled
# count those booleans
tabl <- table(rounded_up)
print(tabl)
# perform binomial test on results
binom.test(x=tabl)

My result here is p = .635 If you take a few minutes time, you can test it with n = 10^9. If there is a tendency towards rounding up or down that is not significant in n = 10^9, I don't think it will ever be relevant in any process that I am going to investigate in my life.
Of course, if you round the values to say 3 digits and perform the above test, there will be a significant tendency towards rounding down:
set.seed(42)
# huge number of random numbers normally distributed around 100:
sampled <- round(rnorm(1e+08, mean=100, sd=1), digits=3)
# boolean count, whether a number was rounded upwards
rounded_up <- round(sampled)>sampled
# count those booleans
tabl <- table(rounded_up)
print(tabl)
# perform binomial test on results
binom.test(x=tabl)

will produce a p-value < 2.2e-16.
Of course, this is only simulation and not a theoretical approach, but it should still answer the question: The more digits you use, the higher an n is needed, to make a difference between standard rounding and rounding to even. Simulation is suitable to investigate, whether for a given n, the standard resolution of your software/computer (in this case R on Windows) is sufficient. If n gets larger than feasible for simulation, it's probably not possible to handle it with your statistics program anyways. So for all practical uses, simulation should be good enough.
Comment: Your simulation appears to support my intuition that the importance of the "round to even rule" decreases as the precision of the number you are rounding increases. I would like to find a reference in the open literature that says this because it is much easier to provide a reference than a custom proof to naysayers and intervenors.

Round to Even Rule


Motivation for studying rational curves

Question: Why do we study rational curves?
A curve $f(x,y)=0$ is called a rational curve if there exists two rational functions $\chi(t)$ and $\psi(t)$ such that $f(\chi(t),\psi(t))=0$ for all $t$.
Why is it not sufficient to study polynomials?
I read somewhere that we want to study conic sections but conic sections are not covered by polynomials. I do not really know what this means. Please enlighten me about this.
Comment: Dear kk lm, don't worry: rational curves are beginners stuff, despite the efforts of some books and people to hide that fact :-) I'll show that below.
Comment: I'm not sure if this is helpful but one possible reason is that rational curves are birational to $\mathbb{P}^1$, and varieties with many rational curves have good deformation properties.
Comment: I do not know what is birational... i do not know what are deformation properties.. @DerekAllums. Please suggest where can i have a look at what you have said
Comment: It may be helpful to let everyone know what your background is then.
Comment: I am just a beginner... I just only know the definition and some examples of rational curves.. i know that $y^2=x^2+x^3$ is a rational curve..
Answer: 1) The curve  $f(x,y)=x^2+y^2-1=0$ (our friend the good old circle!) is a rational curve since it can be parametrized as $$x=\frac {t^2-1}{t^2+1} \quad ,\quad y=\frac {2t}{t^2+1}$$ 2) This is interesting because it allows one to find points on a circle with rational coordinates by plugging in rational numbers for $t$.
Equivalently it allows us to find right-angled triangles with integral sides.
For example: choosing $t=6$ we get $x=\frac {35}{37}, y= \frac {12}{37}$ so that $(\frac {35}{37})^2+(\frac {12}{37})^2=1$ and we get a right angle triangle with sides $35,12,37$ satisfying Pythagoras' relation $35^2+12^2=37^2$.
Amazingly,  the Babylonians somehow knew about this about 3800 years ago.
3)  However it is impossible to find two polynomials (at least one of them non-constant)  $x=P(t), y=Q(t)$ satisfying $P^2(t)+Q^2(t)=1$.
Why? For example because the the limit of $P^2(t)+Q^2(t)$ for $t$ tending to infinity is infinity.
4) So, yes, we need rational functions and not just polynomials  to define rational curves: mathematical terminology is sometimes pleasantly logical (or should I say rational ?)
Comment: [Shafarevich, Basic Algebraic Geometry, Volume 1](http://www.amazon.com/Basic-Algebraic-Geometry-Varieties-Projective/dp/3540548122) pages 4,5,9,171,174. By the way, *every* page of that book is worth reading!
Comment: I think i got it but What are rectangular triangles?
Comment: @kklm: See [right-angled triangle](https://en.wikipedia.org/wiki/Right-angled_triangle) (in some languages, they're called rectangular triangles).
Comment: @Remy : Thanks Thanks..
Comment: I do not know whether to accept this answer or not.. I think this is sufficient... I do not know what to ask more...
Comment: Thanks, @Remy: I have changed my gallicism *rectangular triangle* to *right angled triangle* in my answer. Although almost everything I read in the professional mathematical literature is in English, I don't know the English terminology of elementary mathematics so well, since as a child  everything I read or heard was of course in French. For example  I only recently learned the complicated word *protractor*  :-)
Comment: @GeorgesElencwajg : Can you please give some good reference to learn this rational curves...

Motivation for studying rational curves


Logout from web console?

Question: I'm really new to eJabber, and I don't seem to be able to find a better way to log-out from the web admin console other the closing and opening the browser.
Is there any button to log-out?
Thanks
EDIT
Well, I may have been a bit too vague about what I'm trying to accomplish. I apologize. I'm trying to set up a stand alone ejabberd server on my localhost (using latest macOS). So I've downloaded and installed it in my /Applications folder.
Now after fiddling a bit with various configurations, I wanted to try to log in and out from the web admin interface. Actually I'm trying to enter the web admin interface with different user names.
Therefore the point is, just to answer HBruijn's answer, "what is the point of having a login at all, then"?
When I browse to http://localhost:5280/admin, I'm presented a LOGIN window, with username/password fields and nice "LOGIN" button.
And even after login , there's no cookie or session variable stored in the browser.
So, how do I say to my browser (and eJabber) that I'm not the user email@example.com but email@example.com?
Answer: I don't know that particular product but anything that uses http basic authentication does NOT come with a log off button.
Since with basic auth there  is no session maintained server side no server side  function  can terminate the login session.
And AFAIK no browser  ever implemented doing so client side.
Comment: Please see my edited post

Logout from web console?


How to plot 3D figures correctly?

Question: When we always draw e.g. cylinder on the whiteboard, we get kind of this:

But naturally (assumed axes are perpendicular) when we have z-axis to the top and y-axis to the right, x-axis must point to us (from display) like this:

And when we look from another point so that x-axis is diagonally and z-axis to the top, then y-axis naturally can't be horizontal as on first image, it is a bit rotated.
My lecturer said these are two different kinds of plotting, but could not remember how are they called.
So here comes the question: what are the names of both these methods (natural and alternative plotting) and how to plot correctly in both situations?
Comment: This might be helpful: http://en.wikipedia.org/wiki/Graphical_projection
Answer: Isometric, Trimetric and Dimetric, these are all standard projections that are used for industrial purposes. ZulfiqarIII's link has all the info.

How to plot 3D figures correctly?


Prove that if $C \in \overrightarrow{AB}$ and $C \neq A$, then $\overrightarrow{AB} = \overrightarrow{AC}$

Question: Prove that if $C \in \overrightarrow{AB}$ and $C \neq A$, then $\overrightarrow{AB} = \overrightarrow{AC}$.
I am a little confused on how to go about this. In particular, what axioms to apply because I do not know if I am allowed to apply the "Incidence Axioms" to this exercise.
I believe two rays are said to be equal if they share a common point which is not the apex, but then I am not sure what is supposed to be said because I feel tht solves the problem.
I know $C$ lies in the ray $AB$. I know $C \neq A$. Then $AC = AB$ because $C \in AB$.
But do I have to invoke any specific axioms? I feel it is too simple.
Comment: Please edit your question to include a definition of $\overrightarrow{AB}$ and the axioms you are supposed to prove the statement from.
Answer:
$\textbf{Definition (Ray)}$. Given two distinct points $A$, $B$, the ray $\vec{AB}$ is the set consisting of $A$, plus all points on the line $AB$ that are on the same side of $A$ as $B$.

If $C\in\vec{AB}$, by the axiom (B$3$), it happens that $A\star C \star B$ or $A\star B\star C$, where $\star$ denotes the relation of betweenness. In both cases, $A$ is not in the segment $\overline{BC}$, so $B$ is on the same side of $A$ as $C$ (so $B\in\vec{AC}$) and $C$ is on the same side of $A$ as $B$ (so $C\in\vec{AB}$)
Let $D\in \vec{AB}$ be a point distinct of $A$ and $C$.
$(1)$ If $A\star D\star C$, $A$ is not in the segment $\overline{DC}$, so $D$ is on the same side of $A$ as $C$ (so $D\in\vec{AC}$).
$(2)$ If $A\star C\star D$, $A$ is not in the segment $\overline{DC}$, so $D$ is on the same side of $A$ as $C$ (so $D\in\vec{AC}$).
Hence, $\vec{AB}\subset \vec{AC}$. Doing the same thing but reversal, we get  $\vec{AC}\subset \vec{AB}$, so the equality holds.


how to combine textbox values in a linq query?

Question: I have a page in which I have several textboxes in order to search depending the value of the textboxes,If I make the search eith only one value everithing works fine but if I try to combine 2 or more values I only get the result of the last textbox.
Here's my query hope you could help me.
<code>var query = from m in SolContext.Menores
                            where ((m.Solicitud.fiIdSolicitud == rdTxtFolio.Value) || (m.Solicitud.fiAnioSolicitud == rdTxtAnioFolio.Value)
                            || (m.Solicitud.CTEdoSolicitud.fcDescEdoSol == status) || (m.Solicitud.fiCircuito == cto) || (m.Solicitud.fiCiudad == cd)
                            || (m.Solicitud.fcCveAdsc == adsc) || (m.Solicitud.fiExpEmpleado == rdTxtExp.Value) || (m.Solicitud.fcNomEmpleado == rdTxtNom.Text)
                            || (m.Solicitud.fcPatEmpleado == rdTxtAPat.Text) || (m.Solicitud.fcMatEmpleado == rdTxtAMat.Text) || (m.fcPatMenor == rdTxtAPatMenor.Text)
                            || (m.fcMatMenor == rdTxtAmatMenor.Text) || (m.fcNomMenor == rdTxtNomMenor.Text) || (m.fiSexoMenor == sexo) || (m.fiAnosMenor == rdTxtAniosMenor.Value) || (m.fiMesesMenor == rdTxtMesMenor.Value))
                            select m;
                rgSolic.DataSource = query;
                rgSolic.Rebind();
</code>
Comment: No one wants to help if you don't accept answers (click the arrow icon next to the answer that best works to accept it as the answer). It's how people get recognized and helps the integrety of the site.
Comment: You have't selected an answer to any of your previous questions...
Comment: Ok I already did it now Can you help me?
Answer: My guess is that the result of the first textbox is included in the result of the second one.
Answer: My guess is that you're using or. The first textbox that matches your value will end your search. If you want to check if it matches all your values, use and.
If that doesn't solve it, we'll need more info.


Uniform convergence of the series $\sum_{n=1}^{\infty} \frac{1}{((x+\pi)n)^2}$ for $x \in (-\pi,\pi)$?

Question: I was checking for the uniform convergence of the series $\sum_{n=1}^{\infty} \frac{1}{((x+\pi)n)^2}$ for $x \in (-\pi,\pi)$.
How to think of a bound for $\frac{1}{((x+\pi)n)^2}$ where $x \in (-\pi,\pi)$?, we know $(x+\pi) \in (0,2\pi)$ and for $1\leq(x+\pi)<2\pi $ we have $\frac{1}{((x+\pi)n)^2} < \frac{1}{4\pi^2 n ^2}$ and we are done by the Weierstrass criterion but for $x \in (0,1)$ we have $\frac{1}{((x+\pi)n)^2} > \frac{1}{n^2}$, so its not true for all $x \in (0,2\pi)$ . ?
The true for all $x$ is required as per the definition of Uniform convergence.
Comment: As $x \to -\pi+$, each term goes to $\infty$, so how could it possibly be uniform?
Comment: If $0<(x+\pi)<2\pi$ then $\frac{1}{((x+\pi)n)^2} > \frac{1}{4\pi^2 n ^2}$.
Answer: Hint. Note that for $x_n=-\pi+1/n$ we have that
 $$\frac{1}{((x_n+\pi)n)^2}=1.$$
On the other hand, when $x\in [a,\pi)$ for $a\in (-\pi,\pi)$,
$$0<\frac{1}{((x+\pi)n)^2}\leq \frac{1/(a+\pi)^2}{n^2}.$$
Comment: The second inequality means that we have uniform convergence in $[a,\pi)$ with any $a\in(-\pi,\pi)$. This does not imply that  we have uniform convergence also in $(-pi,\pi)$ (see my first remark).
Comment: for the sequence $x_{n}$ mentioned the series diverges as we will be adding 1 infinite number of times, and for the $a$ in the next part the series converges so I am confused?
Comment: $x_n$ is a sequence of points. right? How do you claim that series does not converge uniformly by plugging the countable points to different $f_n's$ rather than plugging some pont $x_0 \in (-\pi,\pi)$? Would you please explain?
Comment: @Mathgeek If $S_{N}=\sum_{n=1}^{N} \frac{1}{((x+\pi)n)^2}\to S$ converges uniformly  in $(-\pi,\pi)$ then $\sup_{x\in(-\pi,\pi)} |S_N-S_{N-1}|=\sup_{x\in(-\pi,\pi)} \frac{1}{((x_N+\pi)n)^2}$ goes to zero which is not by the above sequence.


Erro ao enviar arquivo ZIP via Intent no Android

Question: Estou tentando enviar um arquivo ZIP via Intent no Android com o código abaixo:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(out));
sendIntent.setType("application/zip");
startActivity(sendIntent);

Porém apenas consigo enviar se for via whatsapp, outros apps como Gmail, Outlook, OneDrive ou Google Drive retornam erros do tipo "não foi possível anexar/enviar o arquivo".
Modifiquei a última linha do Intent para:
startActivityForResult(sendIntent, ZIP_OK);

Onde ZIP_OK = 101;
Em:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
O resultCode retorna como 0 (zero) se não for via whatsapp.
Alguém sabe o que faltou eu fazer, ou o que estou fazendo de errado?
Answer: Para compartilhar um arquivo é necessário passar uma URI com referência à localização dele, você pode experimentar:
Uri.fromFile(File file)

ou
FileProvider.getUriForFile(Context context, String authority, File file)

Documentação:

fromFile
getUriForFile
Comment: Deu certo, muito obrigado!!


Expand/Collapse groups in expandable recyclerview

Question: I am using this library to implement an expandable RecyclerView. I have implemented it, and it works fine. But what I want is the group should only expand if I click a particular view. Right now what is happening is if I click anywhere on the RecyclerView item, the group expands. I have an ImageView, and when I click that ImageView, only then the group should expand. How can I implement this?
RecyclerViewAdapter.java:
public class GenresSongAdapter extends ExpandableRecyclerViewAdapter<SongDetailsViewHolder, OptionViewHolder> {
    private Context mContext;
    public GenresSongAdapter(Context context, List<? extends ExpandableGroup> groups) {
        super(groups);
        mContext = context;
    }

    @Override
    public SongDetailsViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_song, parent, false);
        return new SongDetailsViewHolder(view);
    }

    @Override
    public OptionViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.row_artists, parent, false);
        return new OptionViewHolder(view);
    }

    @Override
    public void onBindChildViewHolder(OptionViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
        ArtistsModel artistsModel = (ArtistsModel) group.getItems().get(childIndex);
        holder.ArtistText.setText(artistsModel.getArtistsName());
    }

    @Override
    public void onBindGroupViewHolder(SongDetailsViewHolder holder, int flatPosition, ExpandableGroup songInfo) {
        holder.setSongDetails(mContext, songInfo);
    }
}

SongDetailsViewHolder.java
class SongDetailsViewHolder extends GroupViewHolder {
    public TextView songName;
    public TextView artistName;
    public TextView duration;
    public ImageView iv_artwork;

    public SongDetailsViewHolder(View itemView) {
        super(itemView);
        songName = (TextView) itemView.findViewById(R.id.SongName);
        artistName = (TextView) itemView.findViewById(R.id.ArtistName);
        duration = (TextView) itemView.findViewById(R.id.duration);
        iv_artwork = (ImageView) itemView.findViewById(R.id.iv_artwork);
    }

    public void setSongDetails(Context mContext, ExpandableGroup songInfo) {
        if (songInfo instanceof SongInfo) {
            songName.setText(songInfo.getTitle());
            artistName.setText(((SongInfo) songInfo).getArtistName());
            duration.setText(((SongInfo) songInfo).getSongDuration());
            Picasso.with(mContext).load(((SongInfo) songInfo).getImageURI()).placeholder(R.drawable.ic_launcher).into(iv_artwork);
        }
    }
}

OptionViewHolder.java
class OptionViewHolder extends ChildViewHolder {
    TextView ArtistText;

    public OptionViewHolder(View itemView) {
        super(itemView);
        ArtistText = itemView.findViewById(R.id.ArtistText);
    }
}

Comment: feel free to modify ExpandableRecyclerViewAdapter (whatever it is) source to fulfill your needs ... eventually ask library's author to do this
Answer: I am doing a bit of guesswork here since I can't afford to make a test project with your setup at the moment.
You don't need to "modify" ExpandableRecyclerViewAdapter as @Selvin is suggesting; it suffice to overwrite the class as you already did with GenresSongAdapter. Simply add to this class. My approach would entail two steps (but it turns out that these steps can be taken in a single method):

Disable the built-in expand-on-click behaviour and
Connect an OnGroupClickListener (whose onGroupClick callback encapsulates that behaviour) with the ImageViews.

We disable the OnGroupClickListeners of the adapter by not setting them to the view holders in the first place (as it is done in the parent class). Therefore we need to overwrite the onCreateViewHolder() method of the adapter and simply skip the command by which the listener is set. However, in the same method we can get a view holder, including all its members. Therefore we can attach a listener to each view holders' ImageView.
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    switch (viewType) {
        case ExpandableListPosition.GROUP:
            SongDetailsViewHolder sdvh = onCreateGroupViewHolder(parent, viewType);
            sdvh.iv_artwork.setOnGroupClickListener(this);
            return sdvh;
        case ExpandableListPosition.CHILD:
            OptionViewHolder ovh = onCreateChildViewHolder(parent, viewType);
            return ovh;
        default:
            throw new IllegalArgumentException("viewType is not valid");
    }
}

You will also have to evade the OnClickListeners set by the GroupViewHolder class, possibly by simply extending SongDetailsViewHolder directly from RecyclerView.ViewHolder.
This is untested code, but I am pretty sure that at least the idea is correct :)
Comment: Hi, thank you for sparing your time for this, actually I solved this by myself. I did pretty much same as you. I disabled the `OnGroupClickListeners ` and add this `toggle(layout)` to my viewHolder.


IllegalArgumentException: No such service ComponentInfo{JobIntentService}

Question: SO answers regarding this issue has not helped me, I have declared all permissions and already have, accepted answers in my code.
AppInfoJobService(CustomJobIntentService) throws following error on Android OS 8+ devices and it happens rarely, not able to reproduce.
We enqueueWork in BaseActivity's onCreate.We mainly have one activity and fragments.
Fatal Exception: java.lang.IllegalArgumentException: No such service ComponentInfo{<app package>AppInfoJobService}
   at android.os.Parcel.readException(Parcel.java:2009)
   at android.os.Parcel.readException(Parcel.java:1951)
   at android.app.job.IJobScheduler$Stub$Proxy.enqueue(IJobScheduler.java:211)
   at android.app.JobSchedulerImpl.enqueue(JobSchedulerImpl.java:53)
   at android.support.v4.app.JobIntentService$JobWorkEnqueuer.enqueueWork(JobIntentService.java:342)
   at android.support.v4.app.JobIntentService.enqueueWork(JobIntentService.java:522)
   at android.support.v4.app.JobIntentService.enqueueWork(JobIntentService.java:500)
   at <application package>AppInfoJobService.startWork(AppInfoJobService.java:254)
   at <application package>MyApplication.onStartStopChanged(MusicApplication.java:694)
   at <application package>AppStateMonitor.notifyStartStop(AppStateMonitor.java:150)
   at <application package>AppStateMonitor.access$000(AppStateMonitor.java:14)
   at <application package>AppStateMonitor$CreateDestroyRunnable.run(AppStateMonitor.java:71)
   at android.os.Handler.handleCallback(Handler.java:790)
   at android.os.Handler.dispatchMessage(Handler.java:99)
   at android.os.Looper.loop(Looper.java:164)
   at android.app.ActivityThread.main(ActivityThread.java:6545)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:857)

Comment: I am facing the same issue on LAVA devices running Oreo.. did you find anything?
Comment: No not able to find anything, so I moved my code from JobIntentService to a simple thread.
Comment: Do you think the problem is caused with the fact that we are trying to start a jobIntentService in the onCreate of a fragment?
Comment: We are starting JobIntentService when our first Activity is created, inside a handler with 300ms delay not in fragments onCreate.why it is a problem in onCreate?
Comment: No it's not a problem.. it shouldn't be.. I am just trying to debug and investigate why this is happening.. and in my case its only occurring on LAVA devices running android 8.. anyways, I made it a priority to solve so hopefully I will soon find the bottom of the problem.. having said that, after calling your job inside post delayed handler, are you still encountering this error?
Comment: Yes, error is still there.I think JobIntentService has some internal problem in OS 8+. we get lot of crashes related to JobIntentService for version 8, 8.1 in our Crashlytics report.You can refer this link https://issuetracker.google.com/issues/63622293
Comment: the link that you have sent me is different than the issue that we are trying to resolve here. I have resolved java.lang.SecurityException of JobIntentService by writing a SafeJobIntentService which extends JobIntentService and catches the exception. check out this link https://github.com/evernote/android-job/tree/master/library/src/main/java/android/support/v4/app for the code to overwrite JobIntentService. DO NOTE: you have to add the files under android.support.v4.app (package / directory)
Comment: have you mentioned your AppInfoJobService class in your Manifest?
Comment: @Nikhil yes it is already mentioned
Comment: @shalini Can you update the question with AppInfoJobService Java class. So  I could have a deep understanding of the issue.
Comment: @Nikhil AppInfoJobService is simple class. In its onHandleWork method I am firing some Analytics events.I dont think there is any problem in this, as it is crashing just when "enqueWork(...)" of JobIntentService is called.
Comment: @shalini Have a look at this

https://github.com/OneSignal/OneSignal-Android-SDK/commit/8025425e7f18c2756a8bc91c1cca58cd5dab3875

Hope you may find something useful.
Comment: @Bassel Mourjan Got the same crash report from a Lava Z61 running Android 8.1.0.
Comment: This solved the issue for me. https://stackoverflow.com/a/35740474/6117565
Answer: Note: Starting a separate thread as I do not have enough reputation to comment and want to help the author.
This actually is an issue with LAVA devices having Android Oreo and works absolutely fine with other devices.
I too observed this on LAVA Z60s & LAVA Z61.
Addining related information from crashlytics
Comment: That's correct, and I am unable to reproduce since I don't have access to a LAVA device, hopefully somebody could have an answer/fix to this issue.
Comment: @SaranSankaran sorry for the delayed response but we could not find any solution for the same and ended suppressing the exception at our end.
Comment: @BasselMourjan I was able to replicate the same. Can you try something like [this](https://github.com/evernote/android-job/blob/master/library/src/main/java/android/support/v4/app/SafeJobIntentService.java)?

You can neglect this as of now by adding an 'IllegalArgumentException' along with 'SecurityException' there.
Comment: I will try it in the next release.. why not.. but I don't think that it's the solution since the main problem is "No such service"
Comment: @BasselMourjan it is definitely not the solution but you can avoid a crash just to improve user experience.
Comment: I already have this applied to avoid SecurityException on android 8.. cheers
Comment: We are also seeing this same issue on Z60 device. Where you able to find any solution?
Comment: @VrajeshHirani I called one of our users suffering from this issue and his description for the crash was as follows: "After installing the app everything works perfectly, but on second launch it crashes and he would re-install it once again for it to work"
Comment: I am now trying to reach LAVA's software development team but so far without any luck
Comment: @BasselMourjan the behavior remains same after user re-installs?
Comment: @VrajeshHirani according to the LAVA user, it works normally the first time after installation, then fails on second launch.
Answer: Problem is finally resolved after switching to the new Android WorkManager
Comment: I was thinking of doing the same. Is WM tested solution, I hope it just not add another bug count.
Comment: to be honest I waited till it was a stable release and applied it to my active app with 10k+ active users... so far, 3 crashes affected 1 user only
Answer: My case is I didn't create service in AndroidManifest.xml, so it didn't find that service.
To do that, add following to that :
    ...
    /activity>
    <service
        android:name=".YOUR_FOLDER.YOUR_SERVICE_FILENAME"
        android:permission="android.permission.BIND_JOB_SERVICE"
        android:exported="false" />
    <receiver
        android:name=".YOUR_FOLDER.YOUR_RECEIVER_FILENAME"></receiver>

</application>

Comment: down voted because this is a different issue that we are discussing
Answer: You cannot start a service or intentService using method startService while the app is background or application is gets killed and trying to restart the service.
As far as I can understand the situation is (as you said happened rarely) somehow app is trying to restart the application while the app is not in the memory.
Comment: Downvoted because this doesn't address the specific issue in the question.  Namely why is JobScheduler.schedule throwing an IllegalArgumentException in this case.


Usar o array_key_exists

Question: estou tentando verificar se algum valor existe em um array no 1 array consigo verificar se existe mais quando o array tem outro array dentro não consigo verificar se existe.
1 array
$array = array("Volvo" => 'BMW', "BMW" => 'X5');

array (size=2)
  'Volvo' => string 'XC90' (length=4)
  'BMW' => string 'X5' (length=2)

resultado do 1 array
if (array_key_exists("Volvo",$array):
      echo "existe!";
  else :
      echo "não existe!";
  endif;

// resultado "existe"

2 array
$array = array(array('volvo' => 'XC90'), array('BMW' => 'X5'));

0 =>
    array (size=1)
      volvo' => string 'XC90' (length=4)
  1 =>
    array (size=1)
      'BMW' => string 'X5' (length=4)

resultado do 2 array
if (array_key_exists("Volvo",$array):
    echo "existe!";
else :
    echo "não existe!";
endif;

// resultado "não existe"

Comment: a verdade q o erro todo do seu codigo é que volvo ta minusculo e você ta chamando ele como maiusculo
Answer: Este é o comportamento esperado, não existe chave "Volvo" na array inicial. Se você tem uma array dentro da outra (array multidimensional) você deve verificar cada array, basta fazer um loop.
Quando você faz:
$array = [['volvo' => 'XC90'], ['BMW' => 'X5']];

É o mesmo que fazer:
$array = [0 => ['volvo' => 'XC90'], 1 => ['BMW' => 'X5']];

Por isso fazer: array_key_exists(1, $array); retornará verdadeiro, para esses dois casos acima.

Se você quiser busca a chave de array dentro de outra array pode fazer:
function multi_array_key_exists($key, array $array) : bool {
    // Pesquisamos no array atual:
    if (array_key_exists($key, $array)) {
        return true;
    }

    foreach ($array as $v) {

        // Chamamos a função novamente, para que ele continue a busca no array interno:
        if (is_array($v) && multi_array_key_exists($key, $v)) {
            return true;
        }
    }

    return false;
}

Comment: obrigado pela resposta consegui resolver.
Answer: Olá, a solução para seu problema é mais simples do que parece. Você deve criar uma função que percorra todo o array (usando o foreach) e verifique se aquele determinado índice é um array (para isso vamos utilizar a função is_array), se o elemento verificado for um array ele chama a função novamente passando esse elemento como array principal. Se não, ele compara o índice do elemento verificado com aquele valor passado. Veja:
function verificaArray($array, $elemento){
    foreach ($array as $key => $value){
        if(!is_array($value)){ // verifica se elemento atual não é um array
            if($key === $elemento){ // se o elemento a ser procurado for igual ao do índice atual
                return true; // Se achou retorna true
            }else{
                end($array);

                if($key === key($array)){
                    return false; // se não acho e estiver no último elemento, retorna falso
                }
            }
        }else{
            return verificaArray ($value, $elemento); // Chama a função para fazer tudo de novo quando é array
        }
    }
}

$a = []; // seu array aqui

if(verificaArray($a, "Volvo")){
    echo "Existe";
}else{
    echo "Não existe";
}

Espero ter ajudado, abraço!
Comment: Teste a entrada `['Foo' => 'Bar', 'Volvo' => 1]`; mesmo procurando por `Volvo` a saída será `Não existe`. Além dos erros de sintaxe, você precisa rever o seu `return false`.
Comment: ao executar o código realmente retorna não existe com erro de sintaxe pensei que tinha funcionado só que não tinha salvo o código antes agora salvei e deu esse erro
Comment: Olá amigos, obrigado por me informarem meus erros. Creio eu que já foram corrigidos. De qualquer maneira obrigado por tornar a comunidade melhor!
Answer: Para buscar determinada chave de um array multidimensional é necessário utilizar a recursividade e a função array_key_exists não faz isso.
function array_key_exists_recursive($needle, array $array)
{
    foreach ($array as $key => $value) {
        if ($key === $needle) return $value;
        if (is_array($value)) {
            if ($x = array_key_exists_recursive($key, $value)) return $x;
        }
    }
    return false;
}

Comment: Um detalhe muito importante é que a função não retornará `true` quando encontrar, mas sim o próprio valor encontrado, então cuidados como não fazer `$resultado === true` devem ser tomados.
Comment: E @VictorCarnaval, recomendo manter o `===`, pois com apenas dois isso pode acontecer: `array_key_exists_recursive(true, ['Volvo' => 'Foo'])` retornar `Foo`
Comment: Quando você transformou esse método de alguma classe sua em função esqueceu de acertar o conteúdo da função removendo o `$this` dela. Seu código do jeito que está irá lançar um erro fatal `Fatal error: Uncaught Error: Using $this when not in object context...` pois você está usando `$this` fora do contexto de uma classe.
Comment: Muito obrigado pela observação @Vinicius.Silva. Corrigi o erro.
Comment: Mesmo assim não é motivo algum dar voto negativo, é só avisar!
Comment: Estava tentando dar scroll no pad do notebook e acabou gerando clique e o SO não me deixava remover o downvote (que já foi removido) até que você editasse a resposta.
Comment: Entendi @AndersonCarlosWoss, obrigado pela explicação.
Answer: Código de uma resposta no SOen: Check if specific array key exists in multidimensional array - PHP
function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key === $keySearch) {
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}

var_dump(findKey($array, 'Volvo'));

Observação: Essa resposta leva em conta somente se o valor procurado é o igual ao pesquisado.
Comment: E se pesquisar por `true`? Usar a comparação frouxa é bastante perigosa nessas situações.
Comment: Perigoso no sentido de abrir brechas para efeitos colaterais que podem ser difíceis de identificar na aplicação e dar manutenção.
Comment: obrigado testei e deu certo .
Comment: @AndersonCarlosWoss não concordo com bastante perigoso, tudo depende do contexto, talvez a pessoa não queria testar o tipo e valor somente o valor. Vale lembrar que a resposta é retirada na integra do SOen e colocada aqui igualzinha dando a credibilidade adequada ... Mesmo não tendo validade o que falou eu coloquei mais um igual que eu sei que testa valor e tipo.

Usar o array_key_exists