Call to undefined function db_affected_rows()

Question: D6 module https://www.drupal.org/project/uc_dependent_attributes is converted to D7 here: http://dupgrade.com/ and I found out db_affected_rows() was removed from D7.
I tried few codes, basically copy and paste, based on this answer db_affected_rows gives fatal error in drupal 7. Now I have a different error: Call to a member function rowCount() on a non-object.
Code which throws Call to undefined function db_affected_rows()
function uc_dependent_attributes_uc_product_adjustments_form_submit(&$form, &$form_state) {
  foreach ($form_state['values']['body'] as $value) {
    if (!$value['enabled']) {
     db_update('uc_dependent_attributes')->fields(array(
        'enabled' => 0,
      ))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
      if (!db_affected_rows()) {
       db_insert('uc_dependent_attributes')->fields(array(
          'nid' => $form_state['values']['nid'],
          'combination' => $value['combo_array'],
          'enabled' => 0,
        ))->execute();
      }
    }
    else {
      db_delete('uc_dependent_attributes')->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
    }
  }
}
Changed: This gives 'Fatal error: Call to a member function rowCount() on a non-object' error.
function uc_dependent_attributes_uc_product_adjustments_form_submit(&$form, &$form_state) {
  foreach ($form_state['values']['body'] as $value) {
    if (!$value['enabled']) {
     $result = db_update('uc_dependent_attributes')->fields(array(
        'enabled' => 0,
      ))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
      $affected_rows = $result->rowCount();
      if ($affected_rows!=0) {
        db_insert('uc_dependent_attributes')->fields(array(
          'nid' => $form_state['values']['nid'],
          'combination' => $value['combo_array'],
          'enabled' => 0,
        ))->execute();
      }
    }
    else {
      db_delete('uc_dependent_attributes')->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
    }
  }
}

How can I change db_affected_rows() to D7 properly?
Comment: Similar: [Error while moving Drupal moving error](http://stackoverflow.com/q/17743806/55075)
Answer: As it happens UpdateQuery::execute() returns

The number of rows affected by the update.

So instead of:
$result = db_update('uc_dependent_attributes')->fields(array(
  'enabled' => 0,
))->condition('nid', $form_state['values']['nid'])->condition('combination', $value['combo_array'])->execute();
$affected_rows = $result->rowCount();
if ($affected_rows!=0) {

use:
...
$affected_rows = db_update('uc_dependent_attributes')
  ->fields(array('enabled' => 0))
  ->condition('nid', $form_state['values']['nid'])
  ->condition('combination', $value['combo_array'])
  ->execute();

if ($affected_rows == 0) {
...

(there's also a small fix to the conditional logic)
Comment: In general Clive you're right. But `RETURN_AFFECTED` [src](https://api.drupal.org/api/drupal/includes%21database%21query.inc/class/UpdateQuery/7) may not always return updated rows depending upon the schema configuration. Things like INSERT ... ON DUPLICATE KEY and also Updates to rows with identical values will not return a necessarily meaningful value for `$affected_rows` http://php.net/manual/en/pdostatement.rowcount.php  I'm basically putting this as a comment as a public service announcement that rowCount() and its kin may be misleading.
Comment: i can save adjustment form in 'node/7/edit/adjustments' now without the above errors.  thank you both for your time.


How to set data to the devexpress's treelist

Question: I have a treelist, I must to fill it with some data from text or excel file, also as possibility from class, please tell me how to do that?
Answer: It is really difficult to answer your question as it does not contain any specific information.  Anyway, the Data Binding topic provides the complete information on binding the TreeList to data.  I hope, it will be of some help to you.  If not, please give us more details about the task.


Meaning of unique umvue

Question: For a random sample of size $n$ from Bernoulli distribution with parameter $p$, find the unique UMVUE of $1-p(1-p)$.
I found that $1-X_1$ is a UMVUE of $1-p(1-p)$. But can't this $X_1$ be replaced by any of $X_2$ or $X_3$ or. . . $X_n$. In that case is this UMVUE unique?
Comment: https://math.stackexchange.com/q/2687375/, https://stats.stackexchange.com/questions/404136/find-umvue-of-p3
Answer: Generally, an UMVUE is essentially unique. The estimator you provided is not an UMVUE though, indeed it is not even unbiased!!
Notice that  $\mathrm E[1-X]= 1-\mathrm E[X]=1-p$ provided that our random variable is a Bernoulli with parameter $p$.
I'd suggest to proceed finding the UMVUE for $p(1-p)$. Then, using the fact that given an UMVUE estimator $U$ for the unknown parameter $\theta$, $a+bU$ with $a,b \in \Bbb R$ is UMVUE for $a+b\theta$, you retrive the desired estimator.
The starting point should be, for example a trivial unbiased estimator like $U= X_1(1-X_2)$, then using Rao-Blackwell theorem and the sufficient and complete statistic $T$ for $\theta$, i.e. $T=\sum_{i=1}^n X_i$, you'd find your estimator. This last result is the so called Lehman-Scheffé theorem.
Comment: The MVUE is the conditional expectation of any unbiased estimator, given the value of the complete sufficient statistic. Is that what you mean in your last sentence?
Comment: Yes, exactly it should be the lehman-scheffè theorem
Comment: Ok. Might help the OP to make that more explicit. Good answer +1

Meaning of unique umvue


How to programmatically list member entities of an Organic Group?

Question: How can I programmatically get a list of member entities of an Organic Group?
(I know how to get a list of group members using Views — I'd prefer to do this using the Organic Groups API, but haven't been able to find the right method.)
Answer: Using directly the Organic Groups API:
og_get_group_members_properties($yourGroupNode, array(), 'members', 'node');

gives you an array of user ids.
To obtain only active, pending or blocked users, you can put 'members__1', 'members__2' or 'members__3' in place of 'members', like in this example:
og_get_group_members_properties($yourGroupNode, array(), 'members__1', 'node');

of, if you prefer, like this one:
og_get_group_members_properties($yourGroupNode, array(), 'members__' . OG_STATE_ACTIVE, 'node');

Example of the returned value:
Array
(
    [0] => 48
    [1] => 49
    [2] => 51
)

Comment: This should be the correct answer
Answer: Or via DBTNG:
$query = db_select("og_membership", "ogm");
$query->condition("ogm.gid", $yourGroupID, "=");
$query->condition("ogm.group_type", "node", "=");
$query->fields("ogm", array("entity_type", "etid"));
$result = $query->execute();
print_r($result->fetchAll());

...which allows you to join other tables, rather than having to filter the result set in PHP code as you would if using EntityFieldQuery.
Answer: $query = new EntityFieldQuery();
$query
  ->entityCondition("entity_type", "og_membership", "=")
  ->propertyCondition("gid", $yourGroupID, "=");
$result = $query->execute();
print_r($result["og_membership"]);

(Based on http://api.drupal.org/api/drupal/includes--common.inc/function/entity_load/7#comment-14544)
Answer: smokris solution worked but I found another way with EntityFieldQuery:
$query = new EntityFieldQuery();
$entities = $query->entityCondition('entity_type', 'node')
  ->fieldCondition('og_group_ref', 'target_id', $yourGroupID)
  ->execute();

Example of the returned value:
{"node":
  {"22":{"nid":"22","vid":"22","type":"panoramique"},
   "32":{"nid":"32","vid":"32","type":"panoramique"},
   "35":{"nid":"35","vid":"35","type":"panoramique"},
   "36":{"nid":"36","vid":"36","type":"panoramique"}
  }
}

Answer: Extending answer from @smokris.
The active status for the  memberships is "1"  (->condition('ogm.state', 1, '=') ).
function _get_users_in_group($gid) {
  $query = db_select('users', 'u');

  $query
    ->condition('u.uid', 0, '<>')
    ->condition('u.status', 1, '=')
    ->condition('ogm.state', 1, '=')
    ->fields('u', array('uid', 'name'))
    ->join('og_membership', 'ogm', "ogm.gid = :gid AND u.uid = ogm.etid AND ogm.entity_type = 'user'", array(':gid' => $gid));
  return $query->execute();
}


If $R\equiv RR$, then $R\equiv \emptyset\text { or } R\equiv \epsilon\text{ or } L(R)\text{ is infinite}$

Question: If $R\equiv RR$, then $R\equiv \emptyset\text { or } R\equiv \epsilon\text{ or } L(R)\text{ is infinite}$
This seems true to me just looking at it.
For example if $R\equiv \emptyset$, then this means $L(R)=L(\emptyset)=\emptyset$
Then $\emptyset\emptyset=\emptyset$, and so we satisfty our assumption that $R\equiv RR$
Similarly, if $R\equiv \epsilon$, then this means $L(R)=L(\epsilon)=\{\epsilon\}$
Then $\{\epsilon\}\{\epsilon\}=\{\epsilon\}$, and so we satisfty our assumption that $R\equiv RR$
Finally, if $L(R)$ is infinite, then this means that $R$ is closed under the Kleene star $*$ operation, and so $RR$ is still just $R$.
So in all cases, it agrees with the assumption.
I'm not sure how to "prove it" though.
How do you prove something of $A\to (B\lor C\lor D)$
Comment: What is $R$? It helps to give context at the top.
Comment: Based on the context and tags, I assume it's a regular expression.
Comment: yes its a regex
Answer: Often, if you want to show that one of multiple conclusions is true, you can assume that all but one are false and show that the last one has to be true.
Here, assume that $R \not\equiv \varnothing$ and $R \not\equiv \{\varepsilon\}$. We show that $L(R)$ must be infinite.
We know that $L(R)$ must contain a nonempty string, call it $w$. Then we also know that $w^k$ satisfies $R^k$. But we have that $R \equiv R^k$ for any $k \in \mathbb{Z}^+$ (by induction, $R^{k+1} \equiv RR^k \equiv RR \equiv R$). Thus, $w^k \in L(R)$ for any $k \in \mathbb{Z}^+$. This shows that our language contains an infinite number of strings, and we are done.
Note that it's not true that $L(R)$ being infinite implies that it is closed under Kleene-$*$. For example, consider $R = ab*$. This contains an infinite number of strings, but is in fact not closed under Kleene-$*$, since every string in the language must contain exactly one $a$. In this case, we are close, since $R \equiv R^k$ for any $k \in \mathbb{Z}^+$, but we don't neccessarily know if this is true for $k = 0$, which is required for closure under Kleene-$*$.


XMPP packet data maximum limitation with using open fire server in iOS

Question: I am currently working on chat application in iOS. For that I use XMPP and OpenFire server.
My questions are:

What is maximum packet data size we can send through chat message?
Is there any server side (OpenFire) setting require to limit max chat message size?
Answer: From the code, it seems to be one MB
https://github.com/igniterealtime/Openfire/blob/6cc1e42df094fa36c94968745409921022bff6cf/src/java/org/jivesoftware/openfire/nio/XMLLightweightParser.java, line 110
<code>// Set default max buffer size to 1MB. If limit is reached then close connection
maxBufferSize = JiveGlobals.getIntProperty(MAX_PROPERTY_NAME, 1048576);
</code>


How to change working directory of container_command in Elastic Beanstalk custom platform

Question: The working directory to execute container_command defined in the application's .ebextensions is /tmp on the sample custom platform NodePlatform_Ubuntu, while I expected it to be the staging directory as stated in this document.
How can I change the working directory to the staging (the root of unzipped source code) directory?
This is .ebextensions/foo.config of the test app to see the working directory.
container_commands:
  10-test:
    command: env

Then, this is its output in /var/log/eb-activity.log.
[2018-04-30T04:26:54.394Z] INFO  [19153] - [Application update test-app-4@4/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_cocci_custom_eb_test/Command 10-test] : Starting activity...
[2018-04-30T04:26:54.399Z] INFO  [19153] - [Application update test-app-4@4/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_cocci_custom_eb_test/Command 10-test] : Completed activity. Result:
  PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
  PWD=/tmp
  SHLVL=1
  HOME=/root
  EB_IS_COMMAND_LEADER=true
  _=/usr/bin/env

[2018-04-30T04:26:54.618Z] INFO  [19153] - [Application update test-app-4@4/AppDeployStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_cocci_custom_eb_test/Command 20-check-process] : Starting activity...

Comment: It seems the working directory is defined by `app_staging_dir`. `sudo /opt/elasticbeanstalk/bin/get-config container -k app_staging_dir` returns `/tmp`. But now, how can I set `app_staging_dir`?
Answer: I could change it by specifying it in platform.yaml file of the custom platform.
container:
  app_staging_dir: "/var/app/staging"

The log of container_command;
[2018-04-30T09:49:14.452Z] INFO  [1482]  - [Application deployment test-app-4@2/StartupStage0/EbExtensionPostBuild/Infra-EmbeddedPostBuild/postbuild_0_cocci_custom_eb_test/Command 10-test] : Completed activity. Result:
  PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
  PWD=/var/app/staging
  SHLVL=1
  HOME=/root
  EB_IS_COMMAND_LEADER=false
  _=/usr/bin/env

I'm guessing that other options can be specified in the same way.
ubuntu@ip-xxxxxx:~$ sudo /opt/elasticbeanstalk/bin/get-config container --output YAML
---
app_staging_dir: "/var/app/staging"
instance_port: '80'
config_staging_dir: "/tmp"
common_log_list:
- "/var/log/eb-activity.log"
log_group_name_prefix: "/aws/elasticbeanstalk"
source_bundle: "/opt/elasticbeanstalk/deploy/appsource/source_bundle"


Rotate svg path around its centre d3

Question: I have a simple cog wheel drawn in illustrator. I've placed the svg markup in the index page and all is well. I can access it by its id.
The code below is part of a function that is executed on that time period so I don't need to worry about the time element.
I've looked around and am not understanding the examples I've found. This is what I have:
var motor=d3.select('#wheel')
motor.attr('transform', 'rotate(0, 0, 2)');

I want to rotate a couple of degrees every 300 milliseconds.
Comment: var rotate = d3.svg.transform().rotate(amountOfRotation) then motor.attr('transform', rotate); is that what you want ?  http://stackoverflow.com/questions/20030473/combining-translate-and-rotate-with-d3
Comment: No sorry that doesn't seem to work
Comment: could you mock up a fiddle so we could give it a go
Comment: Terribly sorry, don't know how to use it. Fairy new to this. This nearly works but the wheel jumps to the left about 30 pixels and doesn't continue to rotate motor.attr("transform", "rotate(2)")
Comment: did the answer solve your problem ?
Comment: No sorry, just having to do other stuff at the moment, but thanks for asking
Comment: you need to mock up an example. Go into this link : http://jsfiddle.net/Qh9X5/7218/ past HTML top left, CSS top right and Javascript bottom left. I have inmorted D3 for you so shouldnt be difficult. Otherwise your problem is difficult to solve
Answer: Your original code doesn't seem very functional (the commas in rotate are not needed). So taking those out, your statement is asking the svg to rotate by 0 degrees around the x, y coordinates 0, 2 (2 pixels down from the top-left corner).  What you want is closer to:
var motor=d3.select('#wheel')
motor.attr('transform', 'rotate(2 ' + (objectwidth / 2) + ' ' + (objectHeight/2) + ')');

Rotate svg path around its centre d3


If the limit of a series is 0 and it is decreasing does it also converge ?

Question: This question is about the alternating series test.  That says an alternating series converges if the limit is 0 AND it is decreasing BUT wouldn't this be true regardless of whether or not the series is alternating?
I assume not accept I am having trouble thinking of an examples and thought someone would be kind enough to show an example of a series that has a limit of 0 and is decreasing but is not converging due to the fact that it is not alternating.
Comment: The series $\sum \frac{1}{n} = 1/2 + 1/3 + 1/4 + \cdots$ does not converge.
Comment: If it was true, there would be no alternating series test.
Comment: You have a lot of strange things bouncing around, such as "limit of a series" and "it is decreasing" I'm guessing you are confusing the series with its terms.
Comment: Oh...I see now....thank you ....I feel stupid....the alternating add and subtracts....that makes a big difference........thank you for clearing that up.   I will delete the question in a few....
Answer: Note that for $\sum a_n$ the condition $a_n\to 0$ is a necessary but not sufficient condition.
The classical example is of course given by the harmonic series $\sum \frac1n$.


Convolutional neural network fails even when given answer

Question: I was having problems with a CNN giving the prediction as true for everything regardless of input. Taking advice from this forum, I simplified the input to give it the output as the input and it's still unable to make the prediction correctly! Shape is 99,22, 2.  The output boolean is in the input in the 3rd dimension of the input.
Here's an example of 1 sample of the input: https://pastebin.com/jCVU3brn to predict the output as 0.
<code>def CNN(train_X, train_y, test_X, test_y):

model = Sequential([
  Conv2D(30, kernel_size=3, activation="relu", input_shape=(99, 25, 2)),
  Conv2D(64, kernel_size=3, activation="relu"),
  Flatten(),
  Dense(1, activation='softmax')
])

    # Compile the model.
model.compile(
  'adam',
  loss='categorical_crossentropy',
  metrics=['accuracy'],
)

# Train the model.
model.fit(
  train_X,
  train_y,
  epochs=1
)
preds = np.round(model.predict(test_X), 0)

return preds
</code>
Model summary:
<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_11 (Conv2D)           (None, 97, 23, 30)        570
_________________________________________________________________
conv2d_12 (Conv2D)           (None, 95, 21, 64)        17344
_________________________________________________________________
flatten_4 (Flatten)          (None, 127680)            0
_________________________________________________________________
dense_4 (Dense)              (None, 1)                 127681
=================================================================
Total params: 145,595
Trainable params: 145,595
Non-trainable params: 0
</code>
Answer: Your last layer is a fully connected layer with 1 output unit and softmax activation. The softmax activation takes vector $x$ as input and computes a vector $y$ of outputs, where $$y_i = \frac{e^{x_i}}{\sum_{j=1}^D e^{x_j}}$$ and $D$ is the dimension of the input. In your case, since the dimension of the output is 1, this reduces to:
$$y_1 = \frac{e^{x_1}}{e^{x_1}} = 1$$
So you've trained a classification network, but the last layer implies there's only 1 valid category, which means the network must assign probability 1 to that category. It sounds like it's the case that you have more than one category, in which case you should use more than 1 output unit.
Comment: if you have "true" and "false", then that is two categories. you have two categories, but you're only allowing your network to output a single category, which is why your results are nonsense
Comment: There is only one output category. It is either true or false. The output is always 0.
Comment: OK thanks but there is really no way to output a single binary result for just one category in a CNN? 0 = not the category, 1 = is the category? Is the problem that it is softmax?
Comment: If I understood the answer correctly, all you need to do is increase the dimensions of the last layer to 2:
```Dense(2, activation='softmax')```
Although you could use a sigmoid function instead - see https://stats.stackexchange.com/questions/218542/which-activation-function-for-output-layer


How to show $\lim_{n \to \infty}f(x_n)=f(x)?$

Question: consider the Banach space $\ell^1$,  and let $e_i$ be the sequence $(0,\dots,1,0\dots)$, with $1$ in the $i$-th position.  show that $\{e_i\}$ converges weakly to $0$ in $\ell^1$ but not strongly.
My attempt : I found the answer here but i don't understand the answer
A sequence $(x_n)$ in a normed space $X$ is said to be weakly  convergent if there is an $x \in X$ such that $$\lim_{n \to \infty}f(x_n)=f(x)$$ where $ f \in X'$( dual space of $X$)
Take $e^{(n)}\in\ell_1$ given by $e^{(n)}_i:=\begin{cases}1&\mbox{ if }n=i;\\\
0&\mbox{otherwise.}
\end{cases}$ Then $d\left(e^{(m)},e^{(n)}\right)=2$ if $m\neq n$
This implies sequence $\{e_i\}$ has no convergent subsequence
Thus $\{e_i\}$  is not strongly convergent
$l^1$ has infinitely linearly independent set, so we can write  $x=a_1e_1+ a_2e_2+.....$
now  $f : \ell^1 \to \mathbb{F}$ define by $$f(x) = f(a_1e_1+a_2e_2 +...)= af(e_1)+a_2f(a_2).....=\sum_{i=1}^{\infty}a_if(e_i)$$
since  $\ell^{\infty}$ is the dual space of $\ell^1 $ so $f(x) \in \ell^{\infty}$
My confusion is that  how to show $\lim_{n \to \infty}f(x_n)=f(x)?$
Answer: Your sequence does not converge to $0$ weakly. For example, let $f\in( \ell^1)^*$ be given by
$$f((a_i)_{i=1}^\infty)=\sum_{i=1}^\infty a_i.$$
Then $f(e^{(n)})=1$ for all $n$, but $f(0)=0$.
Comment: Isn't the theorem you linked imply that it is impossible @jasmine ? If a sequence converges weakly in $\ell^1$, it also converges strongly.
Comment: ok  got it @Artic char  what type  of sequence i have to  take so that $f(x_n)=0$ will  satisfy
Comment: okk got it now.. it is a  Schur property @Arctic char


Proving $r^t \not\equiv 1\pmod p$

Question: $p>q$ are  primes with $q \mid p-1$. Let $t=(p-1)/q$. I want to show the existence of $r$ such that $0<r<p$ and $r^t \not\equiv 1\pmod{p}$. It seems that there is no prime $p$ such that $p$ divides $2^t, 3^t, \cdots, (p-1)^t$ but why?
Comment: How many solutions ($r$) may $r^t \equiv 1\pmod{p}$ have?
Comment: sorry! r must be nozero
Comment: w.r.t r, i dont know
Answer: Let $r$ be a primitive root modulo $p$. Since $t<p-1$ and the order of $r$ is $p-1$, $r^t\not\equiv1\bmod p$. This implies the second statement is true, since $p$ was arbitrary.
Comment: Thank!!! For the second question, i made a typo; i should have wrote 2^t-1, 3^t-1, ...

Proving $r^t \not\equiv 1\pmod p$


How to write a string quartet

Question: I have major problems with writing for the string quartet. I have studied 4-part-writing for some time now, but I still have very little clue about how to expand from the basic chorale texture, where almost every beat has a new chord.
Usually I start the quartet with a melody, whether it's in the high register or not, and the I write the bass and finally fill in the harmony parts. But I find it hard to write interesting harmony parts that complement the melody and the bass line. Whenever I apply embellishments to my basic structure, the music starts to sound random and disjointed, because I don't know what kind of parts could complement the main parts. I just try out some different embellishments and rhythms and sometimes it works, sometimes it sounds horrible.
The question really is, that what is your process when writing for a string quartet, or for an ensemble of similar kind? And how do you expand from the boring chorale-type harmonizations? I'm asking this because I think that I have some flaws in my approach to writing.
Answer: Writing a string quartet is a goal of mine too. I can't advise from a background of finished quartets, but I can share what I've tried to get there.
But first, I think don't keep trying to adapt chorales. Certainly you can play chorales with a string quartet, and it sounds nice, but the texture is different than the typical string quartet. For example, in quartets you will have a lot of broken chord, broken third, repeated note accompaniment patterns that never appear in a chorale.
Another big difference is form. A chorale is usually a few phrases that modulate quickly to related keys. There usually isn't a lot of repeated and varied phrase structure which is what you will find in a quartet. In a quartet you will commonly have sonata, minuet da capo, and rondo forms. Periodic phrases and recapitulation will be important structural devices.
This is what I have tried:

write minuets first (16 bars), then work up to the trio with da capo repeat. Structurally this is the smallest part of the quartet. If it can't be handled, the other forms will probably be too much. Try writing "sketches" rather than working out completely the final, four parts to shift the focus onto the formal structure which is the real concern of composition.
write short phrases of complete four part settings with attention to the distribution of melodic elements among the four instruments. I used Mozart for my exercise. What I saw frequently is the main melodic interest is often in one or two voices with the others playing very simple accompaniments. Melodic stuff can often be doubled in two parts in thirds or octaves.
Copy quartet scores into a notation program. This may seems like a waste of time, because your aren't making any compositional choices. But, when you copy note for note from the score - which is very tedious! - you force yourself to be much more aware of the contents of the composition. I did this with the opening of Ravel's string quartet and saw things I hadn't really paid attention to before when only reading/listening to the score. I then tried writing a quartet opening of my own modeled on the features I saw in Ravel's.
Do analysis of quartets and write harmonic reductions. You should find that the harmonic phrasing and harmonic rhythm is simpler in a classical quartet than in a chorale. Very broadly speaking four bars of a chorale will have lots of harmonic movement whereas four bars of a string quartet will sometimes be not more than tonic/dominant harmony. Texture-wise a chorale is more contrapuntal, a quartet more homophonic.

I'm thinking mostly of Haydn and Mozart for the quartet models and comparison to chorales. A Romantic era composer like Brahms might provide better models for expanding a chorale texture to a quartet.

I had one other thought. If you, like myself, are not a string player, try to familiarize yourself with the string instruments. Get a cheap violin if you can, or a mandolin which has the same string tuning an neck scale. Knowing about how the bow feels, fingerings, etc. puts you in better touch with how to write for strings. Connect with anyone who plays strings for advice or just for super close listening. I had a friend in college who played cello. I would pester him to play the Bach cello suites. I could sit right next to him, read the score along with his playing. I tried to write little things in the same vein and he would play them... such as they were.
Comment: Imho when learning a form studying the existing works in that form is invaluable. Imagine trying to write a song without ever having heard a song before! I suggest enhancing and/or adding the concept of reading **and** listening to other quartets as a way to understand what can be done. Sometimes stealing ideas is very helpful, other times finding ideas that no one seems to have had before is the big breakthrough.
Comment: No, I was just saying maybe it would improve the answer to be more explicit about listening and even what kinds of listening to do. I upvoted the answer before I commented - it's a good answer and I'm not criticizing it in any way. Just thought of something that could be added but it's only a suggestion.
Comment: I'm glad this mentions Ravel. The first thing I thought when I read "I have trouble breaking out of chorale texture" was "try mimicking the 2nd mvmt of the Ravel quartet," with its quasi-[hocketing](https://en.wikipedia.org/wiki/Hocket) texture.
Comment: @ToddWilcox, of course you would listen to quartets. I mention listening to scores, buying/playing a violin, working with string players. Does it really sound like I'm advising quartet writing without listening?
Answer: I want to highlight something that most of the other answers suggest, for the benefit of the original poster if they're still following, or others. In learning to compose, like any creative pursuit, it's important to do "exercises" or "studies"—things that you don't actually intend to put forth as finished products, but simply to learn from the experience.
If you want to be a great writer, it's terrible advice to just sit down at the typewriter and start your Great American Novel with "Chapter 1. Once upon a time...", and expect to produce your masterwork all at once. The advice is to write a little bit every day, throwaway jottings, and that the sheer volume of output will hone your craft. There's a book called Exercises in Style in which the author retells a simple story of what he saw on the bus, but in 99 different styles or techniques, simply to broaden his range. Visual artists fill notebooks with sketches; they copy hundreds of existing paintings and try little ideas and approaches. Most of the great musical composers kept "sketchbooks" in which they would jot down ideas, and they went through training that often involved writing in the styles of earlier composers, or writing pieces within rigid rules.
As with most musical pursuits, the best advice is to "get a teacher," who will undoubtedly assign such exercises. Most of the "great" composers of the Western classical tradition (and many other traditions for that matter) had formal training. If you must teach yourself, though, assign yourself exercises to experiment with different textures, styles, and effects. Write counterpoint in all the species. Write fugues. Write "divisions on a ground." Write in four parts but allowing no more than three to be playing at any given moment. Give the melody to the viola ("you'll gain a friend for life!"). Copy the quartets of everyone from Haydn to George Crumb. Mash them up (do Mozart's theme in Debussy's style).
Along the way, not only will you find your own musical "voice," you'll probably acquire lots of ideas and fragments, even brand-new ones, just by being stimulated by these restrictions.
Answer: It might be a good idea to try arranging before composing. Getting to know how a melody could be split across the ensemble and how the parts interact is exciting.
You could start with something simple like Pachelbel's canon. This is a good song to start with a bassline and slowly add more complexity.
A more complicated cannon is Bach's Little Fugue in G-minor which starts from the top-down and has a ton of harmonization.  While written for organ, this is a foundational song in the Canadian Brass' brass-quintet repertoire and has been with them since they formed so it's obviously good for a small ensemble.
Anything big like organ music will generally have lots of parts to choose from. Symphonies work really well too. These will be ripe with melodies which jump between sections, counter melodies, and supporting baselines and chords.  You really get to make lots of creative choices about what to include and what to skip.  Some movements of Pictures at an Exhibition  come to mind as something that would be fun to adapt for string quartet (it was such an exciting piano score that Ravel arranged it for a full Orchestra).
In my process, I start with original sheet music which I painstakingly enter into my music typesetting software with a keyboard.  While extremely tedious, this lets my mind wander so that I consider each phrase that I'm typing, thinking of how it could sound with each instrument and how it could fit into a small ensemble.  Eventually I get to the fun task of splitting up the phrases, adding some gaps, filling in others.  Discovering how how/why certain counter-melodies harmonize is also a eureka moment.  Also when there are fewer than four simultaneous parts, it's also fine to have one player sit-out for a moment, or to double-up on parts.  Maybe the viola can play with the cello to emphasis the low-end.
Answer: The string quartet is an inherently contrapuntal medium, and having four relatively similar sounding instruments making it harder to pick out the counterpoint actually makes it more necessary to have counterpoint, not less.
If you are thinking of having a melody, a bass, and harmony parts, then you're thinking of writing for a quartet all wrong.  Although it won't quite turn out that way, you should think of writing for a quartet as writing four separate melody parts that happen to be related and all go together.
I have written an exaggeration - humans don't do very well at following four melody lines at once.  At any given time, you're going to have more important lines and less important lines.  There will be passages where one instrument carries the melody for a few measures.  However, an effective quartet generally has the focus moving from one instrument to another quite regularly.
I would say that you should be ready to write a fugue when you write your first quartet.  If you haven't written a fugue - try that as an exercise (and if you want to write your fugue for quartet, that's fine).
Comment: At least when I look at Mozart/Beethoven/Schubert/Dvorak string quartets, I still see string quartet music as melody, harmony parts, and maybe a bassline. The melody is easily passed between instruments, but harmony parts that reinforce homophony instead of polyphony are still continually present.

How to write a string quartet


Error in proving subgroup is normal

Question: Let $G$ be a $p$-group and let $H$ be a subgroup of $G$ of index $p$ ($p$ is prime). Prove that $H$ is normal.
I have tried to prove it, but accidentally have proven the opposite by some error:
Let $G$ act on $G/H$ by conjugation. We have proven as a lemma that the number of fixed points of this action is equivalent to $|G/H|$ mod $p$, because $G$ is a $p$-group (see here). Thus, since $|G/H| = p \equiv 0 $ mod $p$, it follows there are no fixed points. Thus $H$ is not a fixed point of the action, so there exists some $g\in G$ such that $g.H\neq H \implies gHg^{-1}\neq H$. So $H$ is not normal in $G$.
I have tried to find the error but cannot. Where have I gone wrong? Is the action itself not well-defined? I am not sure how to proceed.
Comment: $|G/H|$ is $p$, and the number of fixed points is congruent to this mod $p$.  But this is satisfied by both $0$ as well as $p$:  they're both congruent to $p$ mod $p$.  So, you can't automatically say there are no fixed points.
Comment: "Since $|G/H| \equiv 0 \mod p$, there are no fixed points". No, it just means  that the number of fixed points is  multiple of $p$, like $2p,p, 0$ etc.
Comment: It doesn't even make sense to do quotient before knowing nH$ is normal, it is exactly what to prove. The statement indeed follows directly from Sylow Theorem.
Comment: Now that I think about it, I don't see how this action is an action at all.
Answer: Thinking more about this, there are two issues with your argument.  The one raised already is that the orbit-stabilizer techniques show that the number of fixed points must be congruent to $0 \bmod p$, but this doesn't mean it has to be the integer $0$.  Hence there could be fixed points.
I think the bigger issue is your action itself.  If $H$ is not known to be normal (yet), then $G/H$ can only mean the set of left (or right, pick a side) cosets of $H$ in $G$.  Standard actions of $G$ on this set in standard Sylow-ish proofs involve action by left multiplication, not conjugation.  Indeed, if your action is "defined" by
$$
g \cdot xH = g(xH)g^{-1}
$$
this doesn't make any sense at all:  how is $g(xH)g^{-1}$ again a left coset?  There's no reason.
Comment: You're correct, and it turns out it does work, but only because the conclusion that H is normal is true. One can prove that with a totally different argument, but I think an interesting thing about this one is it actually proves (once you know H is normal) that every left coset is fixed under conjugation.
Answer: Randall commented correctly that the fact that $|G/H|=p$ does not mean that the number of fixed points is a multiple of $p$, not that it is zero.

Error in proving subgroup is normal


Nonnegative $C^{\omega}$ function $f$ with $\int_\mathbb{R} f(t) \ dt < + \infty$ but $\lim f(x) \neq 0$

Question:
Is there a nonnegative $C^{\omega}$ function $f$ with $\int_\mathbb{R} f(t) \ dt < + \infty$ (in the Riemann sense) but $\lim f(x) \neq 0$ as $x \to +\infty$ or $x \to -\infty$?

Additionally, what can we say about stronger conditions? For example, if $f$ is positive (as opposed to merely nonnegative)? Or instead of $\lim f(x) \neq 0$, $\limsup f(x) = +\infty$?
Unless I'm mistaken, here is an example for the $C^{\infty}$ case, which is, of course, weaker.
Consider the bump function
$$\sigma(x) =
\begin{cases}
\exp\left( -\frac{1}{1 - x^2}\right) & \mbox |x| < 1\\
0 & \mbox{$x \in [-2, -1] \cup [1, 2)$}
\end{cases}$$
extended $4$ periodically to $\mathbb{R}$. Since this is even, we will only consider $x \geq 0$. We alter this as follows. The "bump" portion of each period (ie. where $f(x) \neq 0$) is scaled horizontally so it's width is very small. A consequence of this is that the "$0$" portion of each period gets relatively larger within each period. We must make the $nth$ bump so thin that the area underneath the bump is less than $2^{-n}$. This can be done since the height is bounded. Note that, since $x \geq 0$, the first bump is sort of a half-bump, but this makes no difference.
Our original function $\sigma$ was $C^{\infty}$, so our new function, which has only been scaled, is as well.
Answer: I believe the function
$$
f(x) = 1 + \tanh\left[\left(\sin^2x-1\right)e^{x^2}\right]\coth\left(e^{x^2}\right)
$$
satisfies your condition. Analytic functions are closed under addition, multiplication, and composition, so the above is analytic itself. The limit as $x\rightarrow \pm\infty$ does not exist, because $f(x)$ returns to 1 every odd multiple of $\pi/2$, but the area under each period vanishes quickly enough to converge.
In fact, the periods vanish quickly enough that I could probably add a growing multiplicative factor in front and make the lim sup infinite.
Answer: The function
$$f(x) = (x^2+1)\left ( \frac{2+\cos x}{3}\right )^{x^8}$$
is real analytic on $\mathbb R,$ is strictly positive everwhere, and satisfies $\int_{\mathbb R} f(x) \, dx < \infty.$ Note that $f(2n\pi) = (2n\pi)^2 + 1 \to \infty.$
How do we know $\int_{\mathbb R} f(x) \, dx < \infty?$ Laplace's method shows
$$\int_0^{2\pi}\left ( \frac{2+\cos x}{3}\right )^{n}\,dx = O\left ( \frac{1}{\sqrt n}\right )$$
as $n\to \infty.$  Once we know that, we can obtain
$$\int_{2n\pi}^{2(n+1)\pi} f(x)\, dx = O(1/n^2),$$
which gives the result.
A lot more is true actually: A beautiful result of Carleman shows the following: Suppose $g:\mathbb R \to \mathbb R$ is continuous, and $\epsilon: \mathbb R \to (0,\infty)$ is any positive continuous function. Then there exists an entire function $f$ such that $|f(x)-g(x)| < \epsilon(x)$ for all $x\in \mathbb R.$ Since it is easy to find a continuous function that does what you asked for, taking $\epsilon (x) = e^{-x^2}$ and applying Carleman will give you an entire function that does the same thing.


null Header httpclient android

Question: <code>//more code
public void run()
          {
            DefaultHttpClient localDefaultHttpClient = new DefaultHttpClient();
            try
            {
                Object localObject = localDefaultHttpClient.execute(new HttpGet("http://ev5.playevo.com/_/Special:Register"));
              ((Header[]) null);
//more code
</code>
the last part gives me a this.
Syntax error, insert "AssignmentOperator Expression" to complete Expression
Answer: You need to implement a ResponseHandler to do that.
Comment: The sad thing is I do not know how to implement that.
Comment: Can you explain how to do that? I'm trying to fix an app that someone gave up on.
Comment: I may have figured it out but i have to fix a few other things to get it to launch. Once I do I will post my fix and select this answer.
Comment: A newer answer would be nice. There is no need to apologize. I'm just a little antsy about getting things done.

null Header httpclient android


Category tags like drupal.org (Drupal 7)

Question: I am wondering how to create tags like they have on the main drupal site:

I assume drupal.org is designed using Drupal :)
Can anyone tell me if this is somehow built in to drupal?  The only options I see for term reference fields are list, text fields (which only allow the user to input one tag) or hierarchical reference fields.  Is there some module that allows for the use of these more sophisticated tags?
Answer: There are a number of modules such as:

Nice Tags, here is an excerpt about it from the module's project page:

... improves seamlessly the UX for taxonomy tags input fields.
No 3rd party JS libraries are required, as it works out of the box with jQ version shipped with Drupal.

Active Tags, here is an excerpt about it from the module's project page:

... adds a new option to free tagging taxonomies. If selected the taxonomy widget is replaced by a new jQuery enabled tag entry widget.
Works with core Taxonomy module and Content Taxonomy module.
This module came about through work on a site where some users found separating tags with commas confusing. Some users got it, and some didn't. This resulted in a site littered with concatenated tags. Wordpress has a similar tag entry mechanism where tags are entered separately. It has been implemented here using jQuery to rewrite the standard taxonomy entry form.

You can also use your taxonomies as tags as well if that's something you are interested in.


Changing the key of a track without changing the speed of a track

Question: I have two mp3 tracks.
Track1 has a key of A flat major. Track2 has a key of  D minor.
I would like to increase the key of track1 to match the key of track2 without changing the speed of track1 so it won't sound like the vocalist is singing after inhaling helium. If I can get both tracks on the same key, I plan to do a mashup with them with the Mashup2 software.
I also have a Mac with Garage Band in case that software can be used to do the key change.
I tried several online tools but they all left track1 sounding like the vocalist inhaled helium. :-)
Thanks.
Comment: Another approach you could take would be to get the songs into related keys, rather than the same key.
Comment: The "helium" effect doesn't mean the online tools are bad - it's a natural by product of pitch shifting up. To avoid it, you need a pitch shifter that can work in terms of formants (https://en.wikipedia.org/wiki/Formant). I know Melodyne advertises this feature, but I don't know how well it works.
Comment: You speak/sing higher when breathing helium, so avoiding a speed-up has nothing to do with it -- pitching it higher does it.  [Audacity](http://www.audacityteam.org/download/) is one tool I've used that has time-dependent and -independent pitch shifting, as is Adobe Audition.
Answer: You could try using Logic Pro X. It has a function which allows you to transpose audio up or down without altering the speed.
However even if you transpose the Ab major track to D, it's still going to be in a major key. Playing a D major track over a D minor track probably won't sound very good. There is no easy way as far as I know of converting audio in a major key to a minor key.
EDIT: Actually you can change the major/minor key of audio using a plugin called Melodyne. Here's an example of Bohemian Rhapsody converted to a minor key.
Also as @topo morto pointed out, you could try converting your Ab major track to the relative major key of D minor. In your case this would be F major. It still might sound a bit weird though.
Comment: Thanks for the quick replies. I will be ok if the other track is in harmony according to the Camelot Wheel.
Comment: GarageBand on the Mac is "Logic Lite" — I'm 99% sure the feature you are describing is there in the GarageBand for Mac software that Emad-ud-deen already has.
Comment: Hi Everyone. I'm going to try Melodyne.
Answer: Either take track A down to F major, or, track B up to F minor. This way, you're in relative keys. Better than trying to dub a major and a minor together.
Answer: I did this once using Audacity which is open source, it was on a PC but they also have a version for Mac.
I believe you can also do this with Amazing Slow Downer but you have to pay for that one.


Como fazer com que uma UL fique centralizada horizontalmente e verticalmente numa nav?

Question:

*{margin: 0; padding: 0;}
nav{ width: 100%; height: 100px; background:gy;margin: 0 auto;text-align: center;background: rgba(0,0,0, 0.6);}
nav ul{list-style: none; }
nav ul li {display: inline;padding: 5px; padding-top: 50px;}
nav ul li a {text-decoration: none; font-size: 20px; color: white;margin-top: 50px}
nav ul li:hover {background: rgb(18, 155, 219); transition: 1s linear}

body{background: url(https://i.ytimg.com/vi/0517Im379dI/maxresdefault.jpg);
background-repeat: no-repeat; background-size: 100%;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="estilo.css">

Inicio

Contatos

produtos

Portifólio

Sobre Nós

Comment: O seu `padding-top` na LI não funcionou pq vc colocou `display:inline` nela. Se vc quiser alinhar com padding como vc tentou basta colocar `nav ul li {display: inline-block;.....` ai seu `padding-top` vai começar a "fazer efeito".
Comment: Muito obrigada pela ajuda
Comment: Disponha, e mesmo vc já tendo resolvido o problema ai, tira uma meia horinha para ler a resposta que marquei como duplicada. Ela já vai te ajudar a resolver metade dos problemas de alinhamento que vc vai ter no futuro! []´s
Comment: Como eu fecho a pergunta?
Comment: Não se preocupe com isso, deixa que agora ela vai ser *clickbait* para as buscas orgânicas rss. Mas se quiser mesmo excluir tem um link de `remover` na sua pergunta, é só clicar nele...
Answer: Veja se é disso que precisa:

*{margin: 0; padding: 0;}
nav {
    width: 100%;
    height: 100px;
    background:gy;
    margin: 0 auto;
    text-align: center;
    background: rgba(0,0,0, 0.6);
    display: flex;
    align-items: center;
}
nav ul{
    list-style: none;
    margin: 0 auto;
}
nav ul li {display: inline;padding: 5px; padding-top: 50px;}
nav ul li a {text-decoration: none; font-size: 20px; color: white;margin-top: 50px}
nav ul li:hover {background: rgb(18, 155, 219); transition: 1s linear}

body{
    background: url(https://i.ytimg.com/vi/0517Im379dI/maxresdefault.jpg);
    background-repeat: no-repeat;
    background-size: 100%;
}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="estilo.css">

Inicio

Contatos

produtos

Portifólio

Sobre Nós

Leitura recomendada: CSS-Tricks - A Complete Guide to Flexbox
Comment: muito obrigada pela sua ajuda


Oracle query with to_date() gets ORA-01858

Question: I am using the below syntax to convert a character field into a date within 'Toad for Oracle':
to_date(value_char, 'MM/DD/YYYY HH:MI:SS AM','NLS_DATE_LANGUAGE = American')

I receive the error:

ORA-01858: a non-numeric character was found where a numeric was expected'

I believe the error may be to single digit months and days. For example here are a couple values of the field:
3/3/2020 9:56:00 AM
12/14/2020 10:39:00 AM

Is there a specific syntax to specific no preceding '0'.
Comment: You don't get that error from that data - [db<>fiddle](https://dbfiddle.uk/?rdbms=oracle_18&fiddle=6fa8f1e0609333a0f7dab6698a81322f). Though the NLS argument isn't doing anything. So it's something else in your query, or more likely other values in the column. The name suggests you might have different types of data crammed into one string field - maybe numbers, or dates in mixed formats, or invalid dates - always a risk with data stored as the wrong data type.
Comment: Thank you for the response. That field is used for other attributes as well and is sorted by a different category attribute. Originally, I had used a where statement to filter for the needed category. I have also tried a subquery (in the from clause) with the category specified but still receiving same error. Is there a way to partition the field to only the specific category to allow the use of to_date?
Answer: You don't give a database version, but the following should tell you where the problem is if your are in 12.2 or later.
select value_char
from table
where to_date(value_char default null on conversion error,
          'MM/DD/YYYY HH:MI:SS AM','NLS_DATE_LANGUAGE = American') is null;

Answer:
Originally, I had used a where statement to filter for the needed category. I have also tried a subquery (in the from clause) with the category specified but still receiving same error.

Oracle won't necessarily apply all filters before attempting data conversions; particularly if you are using that converted date value within a filter/join condition.
Fortunately case expressions use short-circuit evaluation, so you can use one to restrict when the conversion is attempted:
case when value_type = 'DATE' then
  to_date(value_char, 'MM/DD/YYYY HH:MI:SS AM')
end

... where value_type = 'DATE' is whatever category check you would use to identify a row that holds a suitable value - and then you still have to hope you don't have malformed data, of course, but that's the cost of storing everything as strings.
If you're on 12cR2+ then @Gary's suggestion to use the to_date() function on conversion error clause with would also work - on it's own, or combined with this so it's only catching malformed values.
Comment: Hello Alex, Thank you for the response. I do not believe I am on 12cR2 as Gary's statement does not work.  I am able to successfully run the query with the case statement, however it also returns the other category attributes with a blank value. To filter it to only the specified date category attribute, I added back in the where statement but receives the original error. Is there another wa to filter the response for only that specific date attribute? Thanks Again
Comment: No, I wasn't saying to remove the existing where condition; the case expression is in addition to that, not instead. But, if you're still seeing the error with the case expression (with or without the where - that might just mean you hit it sooner) then it sounds like you have string values that cannot be converted to dates, when you think they should be. Maybe in different formats, or maybe just rubbish. If you aren't on 12.2 yet (query v$version) then you can visually inspect all values without converting; or [write a function to identify them](https://stackoverflow.com/a/14702163/266304).
Answer: In the Given-case you cannot use one-simple-query which fits-all directly.

you have to isolate-rows based on the resulting rows obtained from
below query and perform update on those sets of rows to make them
eligible dates either using substr, lpad or combination of both.
building a complex "case" in single SQL query also

Note i've assumed column-name and table-name; Hope you get the Drift.
select length(value_char),count(1)
    from your_table
        group by length(value_char);


Stop from terminating program in Ubuntu terminal

Question: I've created a program that makes some calculations on random graphs, when I run it on Ubuntu terminal, I've received some initial results from simple graphs but when the graphs get bigger I get "Terminated" from the console as if it took too long to run the program, is that a problem? How to prevent this
Comment: most likely an error in your program. Are you trying to access invalid memory?
Comment: I doubt it's an error as it only happens when terminal has nothing to display for a long time, but who nows
Comment: Check the return code of your program. Since the terminal itself doesn't close down, you could do this. Next, install a signal handler in your program to detect if your program recieve a close signal from an other process. If it doesn't, your program closes itself.
Comment: so, as it turns out bigger graphs use too much ram and swap space, when its full it turns off, changing size of swap space helps, also running program on a computer with more ram is a good idea
Answer: A process can run in the terminal non-stop.
Your process dies because it has no resources to run with. You can solve this by increasing your swap area (your process will be much slower when using the swap) or by increasing your RAM.


An improper integral involving a Gaussian and Hermite polynomials.

Question: Let $ x \ge b \ge 0$ and let $\mu_0 \le 1/2$. Then let $j \in {\mathbb R}$. Consider the following integral:
\begin{equation}
{\mathcal J}^{(x,b,\mu_0)}_j := \frac{2^{\frac{j}{2}-1}}{\sqrt{\pi}} \cdot
\int\limits_0^\infty t^{-\frac{j}{2}-1} \cdot e^{- \frac{\left( \log[\frac{b}{x}] - (\mu_0-\frac{1}{2}) t\right)^2}{2 t}} \cdot H_{j+1} \left[ \frac{\log[\frac{x}{b}]}{\sqrt{2 t} } \right] dt \tag{1}
\end{equation}
where $H_n[x]$ are Hermite polynomials.
By doing numerical experiments we have found that:
\begin{equation}
{\mathcal J}^{(x,b,\mu_0)}_j = \left(1 - 2 \mu_0\right)^j \tag{2}
\end{equation}
In[3369]:= LL = {}; M = 2;
Do[
  {x, b} = RandomReal[{0, M}, 2, WorkingPrecision -> 50];
  If[b > x, tmp = x; x = b; b = tmp;];
  mu0 = RandomReal[{-M, 1/2}, WorkingPrecision -> 50];
  j = RandomReal[{-M, M}, WorkingPrecision -> 50];
  ll = {1/Sqrt[Pi] NIntegrate[
      2^(j/2 - 1) (t)^(-j/2 - 1)
        Exp[-((Log[b/x] - (mu0 - 1/2) t)^2/( 2 t))] HermiteH[j + 1,
        Log[x/b]/(Sqrt[2] t^(1/2))], {t, 0, Infinity},
      WorkingPrecision -> 20], (1 - 2 mu0)^j};
  LL = Join[LL, {ll}];
  , {which, 1, 100}];
Mean[Abs[#[[1]]/#[[2]] - 1] & /@ LL]

Out[3371]= 2.425121*10^-13

Being intrigued by the simplicity of this result we tried to prove it.
Below, we prove it for $ j \in {\mathbb Z}$ and $j \ge -1$. Here we go:
\begin{eqnarray}
&&{\mathcal J}^{(x,b,\mu_0)}_j = \\
&& \frac{1}{\sqrt{\pi}} \exp \left[ (-\frac{1}{2} + \mu_0) \log[\frac{b}{x}]\right] \cdot
\sum\limits_{m_2=0}^{\lfloor \frac{j+1}{2} \rfloor}
\frac{(-1)^{-m_2} (j+1)! 2^{j-m_2-\frac{1}{2}}  }{m_2! \left(j-2 m_2+1\right)!}
[\log \left(\frac{x}{b}\right)]^{j-2
   m_2+1}
%
\int\limits_0^\infty
t^{-j+m_2-\frac{3}{2}}e^{-\frac{\log ^2\left(\frac{b}{x}\right)}{2
   t}-\frac{1}{8} \left(1-2 \mu _0\right){}^2 t}
dt = \\
&& \frac{1}{\sqrt{\pi}} \exp \left[ (-\frac{1}{2} + \mu_0) \log[\frac{b}{x}]\right] \cdot
\sum\limits_{m_2=0}^{\lfloor \frac{j+1}{2} \rfloor}
\frac{(-1)^{-m_2} (j+1)! }{m_2! \left(j-2
   m_2+1\right)!}
%
\left(\frac{\log ^{\frac{1}{2}-m_2}\left(\frac{x}{b}\right)}{(1-2 \mu _0)^{j-m_2+\frac{1}{2}}}\right)
K_{-j+m_2-\frac{1}{2}}\left(\log
   \left(\frac{x}{b}\right) \left(\frac{1}{2}-\mu _0\right)\right) = \\
&& \left( 1 - 2 \mu_0\right)^j \cdot \left[
%
1_{j=-1} +
1_{j \ge 0}
\sum\limits_{L=0}^j \left( \log[\frac{x}{b}] (1-2 \mu_0)\right)^{-L}
\cdot
\underbrace{
\frac{(j+1)!}{(-L+j)!}  \cdot
\sum\limits_{m_2=0}^{\lfloor \frac{j+1}{2} \rfloor \wedge L}
\frac{(-1)^{-m_2} \left(j+L-2 m_2\right)!}{m_2! \left(j-2 m_2+1\right)!
   \left(L-m_2\right)!}
}_{\delta_{L,0}}
%
\right] = \\
&& \left( 1 - 2 \mu_0\right)^j
\end{eqnarray}
In the second line we used Rodrigues' formula and expanded the Hermite polynomials and we swapped the integration with the sum over the terms.
In the third line we used (Gradshteyn & Ryzhik 3.471.9) at $\alpha = 1/2 \log[b/x]^2$, $\beta = 1/8 (1-2 \mu_0)^2$ and $\nu = -1/2-j+m_2$.
In the forth line we used this result for the modified Bessel functions of a half-integer argument.
(*Check normalization. (*j\[GreaterEqual]-1;*)*)
{x, b} = RandomReal[{0, 2}, 2, WorkingPrecision -> 50]; If[b > x,
 tmp = x; x = b; b = tmp;];
mu0 = RandomReal[{-2, 0}, WorkingPrecision -> 50];
n = RandomInteger[{1, 10}]; th = 9/10;
j = RandomInteger[{-1, n}];(*j\[GreaterEqual]-1;*)

1/Sqrt[Pi] NIntegrate[
  2^(j/2 - 1) (t)^(-j/2 - 1)
    Exp[-((Log[b/x] - (mu0 - 1/2) t)^2/( 2 t))] HermiteH[j + 1,
    Log[x/b]/(Sqrt[2] t^(1/2))], {t, 0, Infinity}]

1/Sqrt[Pi] Exp[+(-(1/2) + mu0) Log[b/
    x]] Sum[(j + 1)!/((j + 1 - 2 m2)! m2!) 2^(j - 1/2 -
      m2) (-1)^(-m2) ( Log[x/b])^(j + 1 - 2 m2) NIntegrate[
    t^(-(3/2) - j + m2)
      Exp[-(1/8) (1 - 2 mu0)^2 t - Log[b/x]^2/(2 t)], {t, 0,
     Infinity}], {m2, 0, Floor[(j + 1)/2]}]

(*Use https://math.stackexchange.com/questions/128687/bessel-function-\
integral-and-mellin-transform?rq=1 (Gradshteyn&Ryzhik 3.471.9,) at \
alpha =Log[b/x]^2/2, beta = 1/8 (1-2 mu0)^2, nu = -1/2-j+m2 *)
1/Sqrt[Pi] Exp[+(-(1/2) + mu0) Log[b/
    x]] Sum[(j + 1)!/((j + 1 - 2 m2)! m2!) (-1)^(-m2) (
     Log[x/b])^(1 - m2 - 1/2) (1/(1 - 2 mu0))^((-1/2 - j +
      m2)) BesselK[-1/2 - j + m2, Log[x/b] (1/2 - mu0)], {m2, 0,
   Floor[(j + 1)/2]}]
(*Use https://functions.wolfram.com/Bessel-TypeFunctions/BesselK/03/\
01/02/02/0001/*)
(1 - 2 mu0)^j If[j == -1, 1,
  Sum[(j + 1)!/(-L +
       j)! Sum[((-1)^(-m2) (+L + j - 2 m2)! )/((j + 1 -
         2 m2)! m2! (L - m2)! ), {m2, 0,
      Min[Floor[(j + 1)/2], L]}] (Log[x/b] (1 - 2 mu0))^(-L)  , {L, 0,
     j}]]

((1 - 2 mu0)^j)

Having said all this my question is how do we prove $(2)$ for other values of $j$ in particular for negative integers. Clearly Hermite polynomials are well defined for the order being a negative integer as explained here for example.
Update:
By using the same considerations as above one can show  that proving the identity in question is equivalent to proving that: $\sum\limits_{n=0}^\infty \frac{(-1)^{n+1} 2^{\frac{j-n}{2}} A^{\frac{n-j}{2}} (j-n+2)_n \Gamma \left(\frac{j-n}{2}+1\right) \left(I_{\frac{1}{2}
   (-j-n)}(A)-I_{\frac{j+n}{2}}(A)\right)}{n!} = \exp(-A)$. Here $A \ge 0 $ and $j \in {\mathbb R}$. and $I_{\cdot}(\cdot)$ is the modified Bessel function of the first kind.
Answer: This is by no means a complete answer to this question but I believe it is a step in the right direction so I am posting it. If we start from the conjectured identity given in the Update above and use the series representation of the modified Bessel function of the first kind then we need to prove the following:
\begin{equation}
(-1) \sum\limits_{n=0}^\infty \frac{(-j-1)^{(n)} \Gamma[1+\frac{j}{2} - \frac{n}{2}]}{n!} \cdot \sum\limits_{m=0}^\infty
\frac{(A/2)^{2 m}}{m!} \left[  \frac{(A/2)^{-j}}{(m - \frac{j+n}{2})!} - \frac{(A/2)^{+n}}{(m + \frac{j+n}{2})!}\right] = \exp(-A) \tag{A}
\end{equation}
Now by swapping the order of sums in the above and doing the sum over $n\in {\mathbb N}$ the identity $(A)$ is equivalent to the following two identities:
\begin{eqnarray}
&&\sum\limits_{m=0}^\infty \frac{(A/2)^{2 m}}{m!} \cdot \\
&&\left[ \frac{\Gamma \left(\frac{j+2}{2}\right) \,
   _1F_2\left(-\frac{j}{2}-\frac{1}{2};\frac{1}{2},\frac{j}{2}+m+1;-\frac{A^2}{4}\right)}{\left(\frac{j}{2}+m\right)!}-\frac{A \Gamma
   \left(\frac{j+3}{2}\right) \, _1F_2\left(-\frac{j}{2};\frac{3}{2},\frac{j}{2}+m+\frac{3}{2};-\frac{A^2}{4}\right)}{\left(\frac{1}{2} (j+2 m+1)\right)!}\right] = \\
&& \exp(-A) \tag{B1}
\end{eqnarray}
and
\begin{eqnarray}
&&\sum\limits_{m=0}^\infty \frac{(A/2)^{2 m}}{m!} \cdot \\
&&2^j A^{-j} \left(\frac{\Gamma \left(\frac{j+2}{2}\right) \,
   _2F_1\left(-\frac{j}{2}-\frac{1}{2},\frac{j}{2}-m;\frac{1}{2};1\right)}{\left(m-\frac{j}{2}\right)!}-\frac{2 \Gamma \left(\frac{j+3}{2}\right) \,
   _2F_1\left(-\frac{j}{2},\frac{1}{2} (j-2 m+1);\frac{3}{2};1\right)}{\left(-\frac{j}{2}+m-\frac{1}{2}\right)!}\right) = \\
&& 0 \tag{B2}
\end{eqnarray}
But now if we use Mathematica and we expand the left hand sides of the conjectured identities $(B1)$ and $(B2)$ in a series in the variable $A$ then we get the following:
In[3892]:=
M = 5; j =.; m =.; A =.;
Collect[Normal[
  Series[Sum[(A/2)^(2 m)/
      m! ((Gamma[(2 + j)/
         2] HypergeometricPFQ[{-(1/2) - j/2}, {1/2, 1 + j/2 + m}, -(
          A^2/4)])/(j/2 + m)! - (
       A  Gamma[(3 + j)/
         2] HypergeometricPFQ[{-(j/2)}, {3/2, 3/2 + j/2 + m}, -(A^2/
          4)])/ (1/2 (1 + j + 2 m))!), {m, 0, M}], {A, 0,
    2 M}]], A, FullSimplify]
Collect[Normal[
  Series[Sum[(A/2)^(2 m)/
      m! (2^j A^-j ((
         Gamma[(2 + j)/2] Hypergeometric2F1[-(1/2) - j/2, j/2 - m, 1/
           2, 1])/(-(j/2) + m)! - (
         2 Gamma[(3 + j)/2] Hypergeometric2F1[-(j/2),
           1/2 (1 + j - 2 m), 3/2, 1])/(-(1/2) - j/2 + m)!)), {m, 0,
     M}], {A, 0, 2 M}]], A, FullSimplify]

Out[3893]= 1 - A + A^2/2 - A^3/6 + A^4/24 - A^5/120 + A^6/720 - \
A^7/5040 + A^8/40320 - A^9/362880 + A^10/3628800

Out[3894]= 0

And this result is exactly what we would be expecting. The first ouput is just a truncated Taylor expansion of $\exp(-A)$!.
So what remains is to prove that $(B1)$ and $(B2)$ are identities.
Update:
Here we prove that $(B1)$ is an identity. We will show that coefficients at particular powers in both sides are equal. Here we go.
Even powers:
\begin{eqnarray}
&&@[A^{2 m}](lhs)=\\
&& \frac{1}{2^{2 m}} \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot \frac{(-j/2-1/2)^{(l)}}{(1/2)^{(l)} (j/2+m-l+1)^{(l)} } \cdot \frac{\Gamma(j/2+1)}{(j/2+m-l)!}= \\
&& \frac{1}{2^{2 m}} \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot \frac{(-j/2-1/2)^{(l)}}{(1/2)^{(l)}
\underline{ (j/2+m-l+1)^{(l)} (j/2+1)^{(m-l)} }}= \\
&& \frac{1}{2^{2 m}} \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot \frac{(-j/2-1/2)^{(l)}}{(1/2)^{(l)}
\underline{ (j/2+1)^{(m)} }}= \\
&& \frac{1}{2^{2 m}} \frac{1}{ (j/2+1)^{(m)} } \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot \frac{(-j/2-1/2)^{(l)}}{(1/2)^{(l)}
}= \\
&& \frac{1}{2^{2 m}} \frac{1}{ (j/2+1)^{(m)} } \cdot \frac{2^{2 m} \left(\frac{1}{2} (j+2 m)\right)!}{\frac{j}{2}! (2 m)!} = \\
&& \frac{1}{2^{2 m}}  \cdot \frac{2^{2 m} }{ (2 m)!} = \\
&& \frac{1}{ (2 m)!} = \\
&&@[A^{2 m}](rhs)
\end{eqnarray}
Odd powers:
\begin{eqnarray}
&&@[A^{2 m+1}](lhs)=\\
&& -\frac{1}{2^{2 m}} \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot
\frac{(-j/2)^{(l)}}{(3/2)^{(l)} (j/2+m-l+3/2)^{(l)}} \cdot \frac{\Gamma((j+3)/2)}{\Gamma((j+3)/2 + m-l)} = \\
&& -\frac{1}{2^{2 m}} \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot
\frac{(-j/2)^{(l)}}{(3/2)^{(l)} \underline{ (j/2+m-l+3/2)^{(l)} ((j+3)/2)^{(m-l)} }}  = \\
&& -\frac{1}{2^{2 m}} \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot
\frac{(-j/2)^{(l)}}{(3/2)^{(l)} \underline{  ((j+3)/2)^{(m)} }}  = \\
&& -\frac{1}{2^{2 m}} \frac{1}{  ((j+3)/2)^{(m)} } \sum\limits_{l=0}^m \frac{1}{(m-l)!} \frac{(-1)^l}{l!} \cdot
\frac{(-j/2)^{(l)}}{(3/2)^{(l)} }  = \\
&& -\frac{1}{2^{2 m}} \frac{1}{  ((j+3)/2)^{(m)} } \frac{2^{2 m} \left(\frac{1}{2} (j+2 m+1)\right)!}{\frac{j+1}{2}! (2 m+1)!} = \\
&& -\frac{1}{2^{2 m}}  \frac{2^{2 m} }{ (2 m+1)!} = \\
&&- \frac{1}{ (2 m+1)!} = \\
&& @[A^{2m+1}](rhs)
\end{eqnarray}
Finally we prove that $(B2)$ is an identity as well. Again, we look at the coefficients of the left hand side at powers of $A$. We have:
\begin{eqnarray}
&&@[A^{2 m}](lhs)=\\
&&\frac{1}{2^{2 m}} \frac{1}{m!} 2^{j} A^{-j} \cdot
\left[ \right. \\
&& \left.
\frac{ \Gamma(\frac{j+2}{2}) \hspace -5ex\diagup }{(m- \frac{j}{2})!} \cdot
\underline{
\frac{\Gamma(\frac{1}{2}) \Gamma(\frac{1}{2} + \frac{1}{2} +m)}{\Gamma(1+\frac{j}{2})  \hspace -5ex\diagup \hspace 5ex  \Gamma(\frac{1}{2} - \frac{j}{2} +m)}
}
\right. \\
&& \left.
-
2 \cdot \frac{\Gamma(\frac{j+3}{2})  \hspace -5ex\diagup}{(-\frac{j}{2} + m - \frac{1}{2})!} \cdot
\underline{
\frac{\Gamma(\frac{3}{2}) \Gamma(\frac{3}{2} + m - \frac{1}{2})}{\Gamma(\frac{3}{2} + \frac{j}{2})  \hspace -5ex\diagup \hspace 5ex \Gamma(\frac{3}{2} - \frac{j}{2} + m -\frac{1}{2})}
} \right. \\
&& \left.
\right] = \\
%%%%%
&&\frac{1}{2^{2 m}} \frac{1}{m!} 2^{j} A^{-j} \cdot
\left[ \right. \\
&& \left.
\frac{1}{(m- \frac{j}{2})!} \cdot
\underline{
\frac{\Gamma(\frac{1}{2}) \Gamma(\frac{1}{2} + \frac{1}{2} +m)}{ \Gamma(\frac{1}{2} - \frac{j}{2} +m)}
}
\right. \\
&& \left.
-
2 \cdot \frac{1}{(-\frac{j}{2} + m - \frac{1}{2})!} \cdot
\underline{
\frac{\Gamma(\frac{3}{2}) \Gamma(\frac{3}{2} + m - \frac{1}{2})}{\Gamma(\frac{3}{2} - \frac{j}{2} + m -\frac{1}{2})}
} \right. \\
&& \left.
\right] = \\
%%%%%%
&&\frac{1}{2^{2 m}} \frac{1}{m!} 2^{j} A^{-j} \cdot
\left[ \right. \\
&& \left.
\frac{1}{(m- \frac{j}{2})!} \cdot
\underline{
\frac{\Gamma(\frac{1}{2}) \Gamma(1 +m)}{ \Gamma(\frac{1}{2} - \frac{j}{2} +m)}
}
\right. \\
&& \left.
-
2 \cdot \frac{1}{\Gamma(-\frac{j}{2} + m + \frac{1}{2})} \cdot
\underline{
\frac{\Gamma(\frac{3}{2}) \Gamma(1 + m )}{( - \frac{j}{2} + m )!}
} \right. \\
&& \left.
\right] = \\
%%%%%%%
&& 0
\end{eqnarray}
In the first line we used the Gauss' summation theorem and then we just simplified.


Finding acute triangle probability

Question: A stick is broken in three parts of any length ,  if we join the pieces then what's the probability of getting a acute angled triangle?
Comment: This problem has been answered several times on Math.SE.  Since you ask for a probability, it is necessary to work with a probability distribution of the lengths into which the stick is broken.  There is more than one reasonable interpretation of how to proceed in breaking the stick.
Comment: Possible duplicate of [Calculating probability for forming a triangle](http://math.stackexchange.com/questions/1383434/calculating-probability-for-forming-a-triangle)
Comment: I don't think this is a duplicate. It sure is related to the linked question.
Comment: To characterize acuteness, you can use the Pythagorean Theorem. That is, If $a \le b \le c$ are the stick lengths in increasing order, then you need both $a+b > c$ for the sticks to form a triangle, and $a^2+b^2 > c^2$ for the triangle to be acute.
Comment: I think this question is the same as http://math.stackexchange.com/questions/1962301/acute-triangle-from-a-stick, but that question was not answered.
Comment: The interested Reader may want to look at [the write-up here](http://www.randomservices.org/random/buffon/Triangles.html) which completes the discussion of chance of forming a triangle with details regarding the acute and obtuse outcomes.
Comment: See [this post] for a relevant simulation.
Answer: WLOG the stick has length 1, here the experience can be modeled  e.g. by choosing two cutting points $x_1 \le x_2$ uniformly at random in $[0, 1]$. Then we have three sticks with length $l_1=x_1$, $l_2=x_2-x_1$ and $l_3=1-x_2$.
Then you can notice geometrically that the triangle formed with them is acute iff. $\sqrt{l_2^2-l_1^2} \le l_3 \le \sqrt{l_1^2+l_2^2}$ (the two extreme cases are obtained for right triangles).
Comment: The condition in the last paragraph assumes that $l_2>l_1$. But I think putting an absolute value around the difference would fix that.

Finding acute triangle probability


Color icon and text in Android Studio

Question: how to make the color of text and icon in List View automatically based on gender?
Example blue for boys and pink for girl.
this sample of the interface. the list names get from database in server
       @Override
            public View getView(final int position, View convertView, ViewGroup parent) {

                // Get ImageView
                ImageView ivGender = (ImageView) convertView.findViewById(R.id.ivGender);

                // Check if it is male or female and set the image
                if (GetAll.get(position).getgender().equals('M')){
                    ivGender.setImageResource(R.drawable.roundM);
                }else{
                    ivGender.setImageResource(R.drawable.roundF);
                }

                return convertView;
            }

This is my coding for icon.
How to to change the text color?
Comment: please show your code
Comment: I edit my question and put some interface
Comment: Design two custom list-view items with blue and pink color. Keep the values in shared prefs and later check for boy/ girl condition. Accordingly show the list-view.
Comment: how about the coding?
Comment: what text? You only have an ImageView
Comment: sorry.. I miss some coding there
Comment: // Check if it is male or female and set the image and colour of text name
        if (nameArrayList.get(position).equals("M")){
                ivGender.setImageResource(R.drawable.roundm);
                tvNama.setTextColor(Color.parseColor("#0f64cb"));

        }

        else {
                ivGender.setImageResource(R.drawable.roundf);
                tvNama.setTextColor(Color.parseColor("#fa00c3"));
        }

            return convertView;
Answer: You have to use holder in listiview to set different property based on your sorting here it is gender with many records in your list.
This is your model class,
ArrayList<YourModel> list = new ArrayList<>();

Static list class used in getView() method,
static class ListContent {

        ImageView ivGender;

    }

This way you can
public View getView(final int position, View convertView, ViewGroup parent) {
                        // TODO Auto-generated method stub
                        final ListContent holder;
                        View v = convertView;
                        if (v == null) {
                            v = mInflater.inflate(R.layout.row_pvs_list_item, parent, false);
                            holder = new ListContent();
                            holder.ivGender = (ImageView) v.findViewById(R.id.ivGender);
                            v.setTag(holder);
                        } else {
                            holder = (ListContent) v.getTag();
                        }
                        YourModel ym = list.get(position);  //your model class and arraylist declared above
                        if(ym.getgender().equalsIgnoreCase("M")){
                           holder.ivGender.setImageDrawable(getResources().getDrawable(R.drawable.roundM));
                        else{
                            holder.ivGender.setImageDrawable(getResources().getDrawable(R.drawable.roundM));
                        }
                        }
                        return v;
                    }

Check ImageView in List for more description.
Hope this helps.
Comment: ListContent is it your class name?
Comment: // Check if it is male or female and set the image and colour of text name
        if (nameArrayList.get(position).equals("M")){
                ivGender.setImageResource(R.drawable.roundm);
                tvNama.setTextColor(Color.parseColor("#0f64cb"));

        }

        else {
                ivGender.setImageResource(R.drawable.roundf);
                tvNama.setTextColor(Color.parseColor("#fa00c3"));
        }

            return convertView;
Comment: yes, that is done in my answer ---  YourModel ym = list.get(position); if(ym.getgender().equalsIgnoreCase("M")){
                ivGender.setImageResource(R.drawable.roundM);
            }else{
                ivGender.setImageResource(R.drawable.roundF);
            }
Comment: I just can view one color. Why it's being like this?

Color icon and text in Android Studio


Probabilistically learning how many numbers in a set have a specific property

Question: There are $n$ numbers in a set. $k$ of these numbers have a specific property; the task is to learn how many of the numbers have such a property, i.e. the number $k$.
The learning is done by repeated experiments.
Each experiment consists of randomly selecting numbers from the set until a number who does not have the property is selected. Each number can be  selected only once.
Each new experiment starts from the full set again.
For example, if numbers 1, 2, 3 have the property but the number 4 does not, then "1, 4" and "2, 3, 4" and "4" are all examples of valid experiments, but "4, 1" or "3,3,4" are not.
What is the probability that after $m$ experiments all $k$ numbers with the property have been seen, i.e. the number $k$ is learned?
I tried to reason like this (assuming that learning each number is independent):

The probability for each single specific number to be observed in a single experiment is $p = \frac{1}{n - k + 1}$.
The probability a number is observed after $m$ experiments is $1 - (1-p)^m$
The probability that all $k$ numbers are observed is $\Pi_{i=1}^{k}{(1 - (1-p_i)^m)} = (1 - (1-p)^m)^k$.

However, this does not match the numbers I got from running simulations on specific cases.
For example, for $n=8$ and $k=4$ and number of experiments $m=10$, the formula gives probability 0.6348597233188475, but simulations give around 0.660309.
Comment: There are $k$ events in play, namely that each property-having number is observed in the $m$ experiments. Presumably the error in your calculation is assuming that those $k$ events are independent. You can probably do the case $n=3,k=2$ by hand to verify this.
Comment: In case you are interested: https://ideone.com/ViBK7G
Comment: What numbers did you get from running simulations?
Comment: Are successive experiments selecting numbers that have already been chosen in a previous experiment?  If not, it seems like the number of experiments must be either $n-k$ (if the last number chosen does not have the property) or $n-k+1$ (if it does).  After all, each experiment ends either on a single number lacking the property, or the exhaustion of the $n$ numbers.
Comment: No, the numbers are not removed. And there is always guaranteed to be at least one number in the set with that property.
Comment: So the extractions are with replacement?
Comment: @leonbloy Clarified in the question.
Comment: I doubt that this can get a simple solution. Computed numerically (not by simulation, but by recursive exact equation) I get $p=0.66068061766$
Comment: Why do you call all k-members selected at least once "k learnt"? You won't know that there aren't more unless you exhausted all elements in one of the experiments.
Answer: The identity of the elements that lack the property is irrelevant; they serve merely to produce a probability $1-k/n$ of ending the experiment in each step. Thus we are drawing from $k$ numbers, and the number $X_m$ of numbers drawn in $m$ experiments has negative binomial distribution $X_m\sim \text{NB}(m,k/n)$ with
$$P(X_m=j)=\binom{j+m-1}j\left(\frac kn\right)^j\left(1-\frac kn\right)^m\;.$$
Conditional on $X_m=j$, the probability that all $k$ numbers have been observed is given by the Probability distribution in the coupon collector's problem:
$$
\def\stir#1#2{\left\{#1\atop#2\right\}}
P(\text{done after $m$ experiments}\mid X_m=j)=\frac{k!}{k^j}\stir jk=\frac1{k^j}\sum_{l=0}^k(-1)^{k-l}\binom kll^j\;,
$$
where $\stir jk$ is a Stirling number of the second kind that counts the number of partitions of $j$ labeled elements into $k$ non-empty unlabeled subsets.
The probability you want is obtained by summing over $j$:
\begin{align}
P(\text{done after $m$ experiments})&=\sum_{j=0}^\infty P(X_m=j)P(\text{done after $m$ experiments}\mid X_m=j)\\
&=\sum_{j=0}^\infty\binom{j+m-1}j\left(\frac kn\right)^j\left(1-\frac kn\right)^m\frac1{k^j}\sum_{l=0}^k(-1)^{k-l}\binom kll^j\\
&=\left(1-\frac kn\right)^m\sum_{l=0}^k(-1)^{k-l}\binom kl\sum_{j=0}^\infty\binom{j+m-1}j\left(\frac ln\right)^j\\
&=\left(1-\frac kn\right)^m\sum_{l=0}^k(-1)^{k-l}\binom kl\left(1-\frac ln\right)^{-m}\\
&=\sum_{l=0}^k(-1)^{k-l}\binom kl\left(\frac{n-k}{n-l}\right)^m\;.
\end{align}
I don't see how to simplify this further. The value that you simulated for $n=8$, $k=4$ and $m=10$ is
$$
\sum_{l=0}^4(-1)^l\binom4l\left(\frac4{8-l}\right)^{10}=\frac{36733580223913986742043}{55599603260670000000000}\approx0.66068061766\;,
$$
as already calculated by leonbloy.
Comment: Thanks a lot! Good to know that the answer was not trivial.


Cross-validation for grouped time-series (panel) data

Question: I work with panel data: I observe a number of units (e.g. people) over time; for each unit, I have records for the same fixed time intervals.
When splitting the data into train and test sets, we need to make sure that both sets are disjoint and sequential, i.e. the latest records in the train set should be before the earliest records in the test set (see e.g. this blog post).
Is there any standard Python implementation of cross-validation for panel data?
I've tried Scikit-Learn's TimeSeriesSplit, which cannot account for groups, and GroupShuffleSplit which cannot account for the sequential nature of the data, see code below.
import pandas as pd
import numpy as np
from sklearn.model_selection import GroupShuffleSplit, TimeSeriesSplit

# generate panel data
user = np.repeat(np.arange(10), 12)
time = np.tile(pd.date_range(start='2018-01-01', periods=12, freq='M'), 10)
data = (pd.DataFrame({'user': user, 'time': time})
        .sort_values(['time', 'user'])
        .reset_index(drop=True))

tscv = TimeSeriesSplit(n_splits=4)
for train_idx, test_idx in tscv.split(data):
    train = data.iloc[train_idx]
    test = data.iloc[test_idx]
    train_end = train.time.max().date()
    test_start = test.time.min().date()
    print('TRAIN:', train_end, '\tTEST:', test_start, '\tSequential:', train_end < test_start, sep=' ')

Output:
TRAIN: 2018-03-31   TEST: 2018-03-31    Sequential: False
TRAIN: 2018-05-31   TEST: 2018-05-31    Sequential: False
TRAIN: 2018-08-31   TEST: 2018-08-31    Sequential: False
TRAIN: 2018-10-31   TEST: 2018-10-31    Sequential: False

So, in this example, I want the train and test sets to still be sequential.
There are a number of related, older posts, but with no (convincing) answer, see e.g.

https://stackoverflow.com/questions/51861417/time-series-prediction-for-grouped-data [now deleted]

Stratified Cross validation of timeseries data
Comment: I'm not sure what you want to do. TimeSeriesSplit will always do sequential splits. In that it may happen that same date (only a single date in each fold) may be on both sides. Do you just want the train or test size to be adjusted so that the split always happen from next date? Its not related to GroupShuffleSplit in my opinion. Can you give an example of what you want?
Comment: Thanks for your comment, see updated question. Yes, train/test sets should not overlap in time when inputting panel data (repeated time measurements).
Comment: Well, there is not anything in scikit-learn to do this. But this should not be difficult to do in my opinion. You can manully group by the data by time and then split. Then just change the indices of the date according to your original data.
Answer: This feature was requested on scikit-learn and I have added a PR for it  .
This technique was used with awesome results on some recent Kaggle Notebooks .

scikit-learn Feature Request
: https://github.com/scikit-learn/scikit-learn/issues/14257
scikit-learn PR :
https://github.com/scikit-learn/scikit-learn/pull/16236
Kaggle Notebook 1 Code block below
Kaggle Notebook 2 ( Purged Time Series CV)  : This is an excellent modification with gap parameter between different groups . Feature Request for the same has been raised on Scikit-learn .
Kaggle Notebook 3 : Summarizes all the methods very clearly.

from sklearn.model_selection._split import _BaseKFold, indexable, _num_samples
from sklearn.utils.validation import _deprecate_positional_args

# https://github.com/getgaurav2/scikit-learn/blob/d4a3af5cc9da3a76f0266932644b884c99724c57/sklearn/model_selection/_split.py#L2243
class GroupTimeSeriesSplit(_BaseKFold):
    """Time Series cross-validator variant with non-overlapping groups.
    Provides train/test indices to split time series data samples
    that are observed at fixed time intervals according to a
    third-party provided group.
    In each split, test indices must be higher than before, and thus shuffling
    in cross validator is inappropriate.
    This cross-validation object is a variation of :class:`KFold`.
    In the kth split, it returns first k folds as train set and the
    (k+1)th fold as test set.
    The same group will not appear in two different folds (the number of
    distinct groups has to be at least equal to the number of folds).
    Note that unlike standard cross-validation methods, successive
    training sets are supersets of those that come before them.
    Read more in the :ref:`User Guide <cross_validation>`.
    Parameters
    ----------
    n_splits : int, default=5
        Number of splits. Must be at least 2.
    max_train_size : int, default=None
        Maximum size for a single training set.
    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.model_selection import GroupTimeSeriesSplit
    >>> groups = np.array(['a', 'a', 'a', 'a', 'a', 'a',\
                           'b', 'b', 'b', 'b', 'b',\
                           'c', 'c', 'c', 'c',\
                           'd', 'd', 'd'])
    >>> gtss = GroupTimeSeriesSplit(n_splits=3)
    >>> for train_idx, test_idx in gtss.split(groups, groups=groups):
    ...     print("TRAIN:", train_idx, "TEST:", test_idx)
    ...     print("TRAIN GROUP:", groups[train_idx],\
                  "TEST GROUP:", groups[test_idx])
    TRAIN: [0, 1, 2, 3, 4, 5] TEST: [6, 7, 8, 9, 10]
    TRAIN GROUP: ['a' 'a' 'a' 'a' 'a' 'a']\
    TEST GROUP: ['b' 'b' 'b' 'b' 'b']
    TRAIN: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] TEST: [11, 12, 13, 14]
    TRAIN GROUP: ['a' 'a' 'a' 'a' 'a' 'a' 'b' 'b' 'b' 'b' 'b']\
    TEST GROUP: ['c' 'c' 'c' 'c']
    TRAIN: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\
    TEST: [15, 16, 17]
    TRAIN GROUP: ['a' 'a' 'a' 'a' 'a' 'a' 'b' 'b' 'b' 'b' 'b' 'c' 'c' 'c' 'c']\
    TEST GROUP: ['d' 'd' 'd']
    """
    @_deprecate_positional_args
    def __init__(self,
                 n_splits=5,
                 *,
                 max_train_size=None
                 ):
        super().__init__(n_splits, shuffle=False, random_state=None)
        self.max_train_size = max_train_size

    def split(self, X, y=None, groups=None):
        """Generate indices to split data into training and test set.
        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Training data, where n_samples is the number of samples
            and n_features is the number of features.
        y : array-like of shape (n_samples,)
            Always ignored, exists for compatibility.
        groups : array-like of shape (n_samples,)
            Group labels for the samples used while splitting the dataset into
            train/test set.
        Yields
        ------
        train : ndarray
            The training set indices for that split.
        test : ndarray
            The testing set indices for that split.
        """
        if groups is None:
            raise ValueError(
                "The 'groups' parameter should not be None")
        X, y, groups = indexable(X, y, groups)
        n_samples = _num_samples(X)
        n_splits = self.n_splits
        n_folds = n_splits + 1
        group_dict = {}
        u, ind = np.unique(groups, return_index=True)
        unique_groups = u[np.argsort(ind)]
        n_samples = _num_samples(X)
        n_groups = _num_samples(unique_groups)
        for idx in np.arange(n_samples):
            if (groups[idx] in group_dict):
                group_dict[groups[idx]].append(idx)
            else:
                group_dict[groups[idx]] = [idx]
        if n_folds > n_groups:
            raise ValueError(
                ("Cannot have number of folds={0} greater than"
                 " the number of groups={1}").format(n_folds,
                                                     n_groups))
        group_test_size = n_groups // n_folds
        group_test_starts = range(n_groups - n_splits * group_test_size,
                                  n_groups, group_test_size)
        for group_test_start in group_test_starts:
            train_array = []
            test_array = []
            for train_group_idx in unique_groups[:group_test_start]:
                train_array_tmp = group_dict[train_group_idx]
                train_array = np.sort(np.unique(
                                      np.concatenate((train_array,
                                                      train_array_tmp)),
                                      axis=None), axis=None)
            train_end = train_array.size
            if self.max_train_size and self.max_train_size < train_end:
                train_array = train_array[train_end -
                                          self.max_train_size:train_end]
            for test_group_idx in unique_groups[group_test_start:
                                                group_test_start +
                                                group_test_size]:
                test_array_tmp = group_dict[test_group_idx]
                test_array = np.sort(np.unique(
                                              np.concatenate((test_array,
                                                              test_array_tmp)),
                                     axis=None), axis=None)
            yield [int(i) for i in train_array], [int(i) for i in test_array]

Example with GridSearchCV . Code modified from SO post here.

import xgboost as xgb
from sklearn.model_selection import  GridSearchCV
import numpy as np
groups = np.array(['a', 'a', 'a', 'b', 'b', 'c'])

X = np.array([[4, 5, 6, 1, 0, 2], [3.1, 3.5, 1.0, 2.1, 8.3, 1.1]]).T
y = np.array([1, 6, 7, 1, 2, 3])

model = xgb.XGBRegressor()
param_search = {'max_depth' : [3, 5]}

tscv = GroupTimeSeriesSplit(n_splits=2)
gsearch = GridSearchCV(estimator=model, cv=tscv,
                        param_grid=param_search)
gsearch.fit(X, y , groups=groups)

Comment: @TiTo- Added  a code snippet above.
Comment: Same as for @Kuba_'s answer: How can I implement your solution to GridSearchCV()? I can't initiate the class giving it a group parameter (date index).
Comment: @Miguel - The PR is still open.  The code on the PR and this post has diverged but the code snippet in the post here should be good on its own .
Comment: This is excellent.  I know sklearn is resisting full compatibility with pandas but seems like it would be trivial to wrap this to produce a groupby index from a time series or period index.   What I'm trying to do is to produce a walk forward cross validation similar to this medium post https://medium.com/eatpredlove/time-series-cross-validation-a-walk-forward-approach-in-python-8534dd1db51a and hyndman guidance but using the time index (in my case part of multi-level index) as the split.
Comment: @GauravChawla any update on this topic ? how is your PR going ? facing the same issue as the OP. Can I stiil use the code u shared here os it it out of date ?
Answer: I have recently hit the same task and after I failed to find appropriate solution I decided to write my own class which is a tweaked version of scikit-learn TimeSeriesSplit implementation. Therefore, I'll leave here for whoever comes later looking for the solution.
The idea is basically to sort the data by time, group the observations according to time variable and then just build cross-validator the same way TimeSeriesSplit does, but on the newly formed groups of observations.
import numpy as np
from sklearn.utils import indexable
from sklearn.utils.validation import _num_samples
from sklearn.model_selection._split import _BaseKFold

class GroupTimeSeriesSplit(_BaseKFold):
    """
    Time Series cross-validator for a variable number of observations within the time
    unit. In the kth split, it returns first k folds as train set and the (k+1)th fold
    as test set. Indices can be grouped so that they enter the CV fold together.

    Parameters
    ----------
    n_splits : int, default=5
        Number of splits. Must be at least 2.
    max_train_size : int, default=None
        Maximum size for a single training set.
    """
    def __init__(self, n_splits=5, *, max_train_size=None):
        super().__init__(n_splits, shuffle=False, random_state=None)
        self.max_train_size = max_train_size

    def split(self, X, y=None, groups=None):
        """
        Generate indices to split data into training and test set.

        Parameters
        ----------
        X : array-like of shape (n_samples, n_features)
            Training data, where n_samples is the number of samples and n_features is
            the number of features.
        y : array-like of shape (n_samples,)
            Always ignored, exists for compatibility.
        groups : array-like of shape (n_samples,)
            Group labels for the samples used while splitting the dataset into
            train/test set.
            Most often just a time feature.

        Yields
        -------
        train : ndarray
            The training set indices for that split.
        test : ndarray
            The testing set indices for that split.
        """
        n_splits = self.n_splits
        X, y, groups = indexable(X, y, groups)
        n_samples = _num_samples(X)
        n_folds = n_splits + 1
        indices = np.arange(n_samples)
        group_counts = np.unique(groups, return_counts=True)[1]
        groups = np.split(indices, np.cumsum(group_counts)[:-1])
        n_groups = _num_samples(groups)
        if n_folds > n_groups:
            raise ValueError(
                ("Cannot have number of folds ={0} greater"
                 " than the number of groups: {1}.").format(n_folds, n_groups))
        test_size = (n_groups // n_folds)
        test_starts = range(test_size + n_groups % n_folds,
                            n_groups, test_size)
        for test_start in test_starts:
            if self.max_train_size:
                train_start = np.searchsorted(
                    np.cumsum(
                        group_counts[:test_start][::-1])[::-1] < self.max_train_size + 1,
                        True)
                yield (np.concatenate(groups[train_start:test_start]),
                       np.concatenate(groups[test_start:test_start + test_size]))
            else:
                yield (np.concatenate(groups[:test_start]),
                       np.concatenate(groups[test_start:test_start + test_size]))

And applying it to OP example we get:
gtscv = GroupTimeSeriesSplit(n_splits=3)
for split_id, (train_id, val_id) in enumerate(gtscv.split(data, groups=data["time"])):
    print("Split id: ", split_id, "\n")
    print("Train id: ", train_id, "\n", "Validation id: ", val_id)
    print("Train dates: ", data.loc[train_id, "time"].unique(), "\n", "Validation dates: ", data.loc[val_id, "time"].unique(), "\n")

Split id:  0

Train id:  [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29]
 Validation id:  [30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
 54 55 56 57 58 59]
Train dates:  ['2018-01-31T00:00:00.000000000' '2018-02-28T00:00:00.000000000'
 '2018-03-31T00:00:00.000000000']
 Validation dates:  ['2018-04-30T00:00:00.000000000' '2018-05-31T00:00:00.000000000'
 '2018-06-30T00:00:00.000000000']

Split id:  1

Train id:  [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 48 49 50 51 52 53 54 55 56 57 58 59]
 Validation id:  [60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 84 85 86 87 88 89]
Train dates:  ['2018-01-31T00:00:00.000000000' '2018-02-28T00:00:00.000000000'
 '2018-03-31T00:00:00.000000000' '2018-04-30T00:00:00.000000000'
 '2018-05-31T00:00:00.000000000' '2018-06-30T00:00:00.000000000']
 Validation dates:  ['2018-07-31T00:00:00.000000000' '2018-08-31T00:00:00.000000000'
 '2018-09-30T00:00:00.000000000']

Split id:  2

Train id:  [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89]
 Validation id:  [ 90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107
 108 109 110 111 112 113 114 115 116 117 118 119]
Train dates:  ['2018-01-31T00:00:00.000000000' '2018-02-28T00:00:00.000000000'
 '2018-03-31T00:00:00.000000000' '2018-04-30T00:00:00.000000000'
 '2018-05-31T00:00:00.000000000' '2018-06-30T00:00:00.000000000'
 '2018-07-31T00:00:00.000000000' '2018-08-31T00:00:00.000000000'
 '2018-09-30T00:00:00.000000000']
 Validation dates:  ['2018-10-31T00:00:00.000000000' '2018-11-30T00:00:00.000000000'
 '2018-12-31T00:00:00.000000000']

Comment: How can I implement your solution to `GridSearchCV()`? I can't initiate the class giving it a group parameter (date index).


mcumgr_flutter, does not move to a successful state reaching 100% firmware transfer

Question: I am trying to move to mcumgr_flutter, from mcumgr plugin, I am having a problem where when reaching 100% transfer of the firmware I am not getting the state steam observer to send me the success state. It crashes after sending me the Confirm state.
I am able to send the firmware data but when reaching 100% I get the event confirm and then nothing happens. I do not see under the updateManager any method to confirm or how to confirm any thing so I can reset the device and I never get the FirmwareUpgradeState.success event.
logs I get in the terminal:
flutter: A Upgrade started with 1 images using 'Confirm Only' mode
flutter: W Device capabilities not supported.
flutter: I Cancelling 'Erase App Settings' since device capabilities are not supported.
flutter: I Validation response: {"splitStatus" : 0, "images" : {{"version" : "0.0.10.6", "pending" : false, "active" : true, "bootable" : true, "hash" : 0x6A953AFF74B69E7DBFA84BCF4F44C04B907A5C417450152331D64F4A946E8B68, "permanent" : false, "slot" : 0, "confirmed" : true}, {"slot" : 1, "permanent" : false, "version" : "0.0.10.6", "confirmed" : false, "hash" : 0x6A953AFF74B69E7DBFA84BCF4F44C04B907A5C417450152331D64F4A946E8B68, "pending" : false, "active" : false, "bootable" : true}}}
flutter: E Request (Group: image, seq: 1) failed: Insufficient MTU: 249.)
flutter: I MTU set to 249
.....
.....
flutter: Confirm

and the code I used from reading the "documentation" on the pub.dev page.
 final managerFactory = FirmwareUpdateManagerFactory();
// `deviceId` is a String with the device's MAC address (on Android) or UUID (on iOS)
    final updateManager = await managerFactory.getUpdateManager(_deviceID!);
// call `setup` before using the manager
    final updateStream = updateManager.setup();

    Uint8List content = loadFirmware();

    // `firmware` is a List of data and index pairs
    final List<Tuple2<int, Uint8List>> firmwareScheme = [Tuple2(1, content)];
    const configuration = FirmwareUpgradeConfiguration(
      estimatedSwapTime: Duration(seconds: 0),
      byteAlignment: ImageUploadAlignment.fourByte,
      eraseAppSettings: true,
      pipelineDepth: 1,
    );
// `configuration` is an optional parameter. If not provided, default values will be used.

    final logger = updateManager.logger;
    _loggerSub = logger.logMessageStream.listen((event) {
      for (var msg in event) {
        print("${msg.level.shortName} ${msg.message}");
      }
    });

    updateManager.update(firmwareScheme, configuration: configuration).catchError((e) {
      AlertDialog alert = const AlertDialog(
        title: Text('Firmware Upload Error'),
        content: Text('An error happened while uploading the firmware, please reset Egrid manually'),
      );
      showDialog(
          context: locator.get<NavigationService>().navigatorKey.currentContext!,
          builder: (ctx) {
            return alert;
          });
      return e;
    });

    _updateStateStreamSub = updateManager.updateStateStream?.listen((event) async {
      print(event);
      if (event == FirmwareUpgradeState.success) {
      //never gets called
        await _updateStateStreamSub?.cancel();
        await _progressStreamSub?.cancel();
        await connection?.cancel();
      } else if (event == FirmwareUpgradeState.confirm) {
         // ????what do here
      } else {}
    });

    _progressStreamSub = updateManager.progressStream.listen((event) {
      locator.get<BikeViewModel>().firmwareProgres = event.bytesSent / event.imageSize * 100;
      locator.get<BikeViewModel>().firmwareProgressUpdate =
          "${event.bytesSent.fileSize(round: 1)} / ${event.imageSize.fileSize(round: 1)} bytes sent";
    });

Answer: problem was simple. I forgot to set the updateManager to a field. so once it was done doing it thing it got garbage collected.
this._updateManager = updateManager;