Running process in background

Question: for i in `cat input`
    do
    youtube-dl $i &&
done

Here input file contains a list of YouTube video links. I expected this code to do a parallel download of the videos from the list. But the job was completed one after the other. Is it a problem with the code?
Answer: You have an extra &, so :
for i in $(< input); do
    youtube-dl "$i" &
done

 To go further

the && operator is used in boolean tests, like : ((1 == 1)) && echo "1 == 1" || echo "1 != 1"
always protect your variables with double quotes to prevent bash word splitting !
the backticks are deprecated in 2013 in favor of the $( ) form. It's more readable, and easy to nest.
Comment: Could you be so kind to provide a link about **` `** deprecation? I remember that people stopped using backticks long time before 2013, but I am interested in the official status
Answer: Use the & symbol instead of the && to run a process in the background. The script should look like this:
while read -r i
do
    youtube-dl "$i" &
done < "input"
wait ## Optional if you want the script to wait for all videos to download before exiting

Comment: This answer is better than others because it will work correctly with links that contain space characters. But this is going to work only if your links are separated by newline characters.
Comment: I agree. Limiting the number of parallel processes may be useful if the internet speed is slow, or if the number of connections is too large.
Comment: Though it may be better to use ``xargs``
Comment: Actually I meant of putting only one "&". It was  a mistake sry.
Answer: for i in `cat input`; do
    youtube-dl "$i" &
done

Also, if you don't want to spam youtube with too many simultaneous downloads, you can use this:
cat file.txt | xargs -d '\n' -L 1 -P 5 youtube-dl

This code will be downloading only 5 videos at the same time. I am pretty sure that it is exactly what you're trying to do. This code will also work for links that contain spaces.
Comment: Yes I was trying to do the same. Is there any other gnu tools which I could use for running jobs in parallel??

Running process in background


Chord Progression fits Modal Interchange but seems to have a borrowed chord(?)

Question: I have written the following chord progression. Straight chords, no inversions or anything.
A > F > E > A
A > C > G > D7 (or D6)
C > G > B7 > B7
As denoted by uppercase, these are all major chords. My somewhat basic understanding of music theory tells me that this is modal interchange between A major and A minor scales, but the G and B in major forms don't fit either of those.
This is where I start confusing myself. Can it be that the key has changed by the third bar, rather than G and B7 being used as major rather than minor?  Or, if they are borrowed, then from where?
I would appreciate any resources, which could explain these topics in further detail.
Thanks
Comment: The G fits from A minor, and B7 is V/V in key A.
Comment: What happens after the B7?
Comment: Well, I don't know how I missed that.
It goes back to A.
Comment: Yeah, the B7 looping back to A is going to make analyzing this key-wise *really* difficult, along with the D7 -> C.
Comment: this is harmonically non-standard, and there is a lot more context required to definitively put it in any key -- if it is even tonal at all
Answer: I agree with your assessment, modal interchange between A major and minor, or parallel major and minor. Many of the chords are borrowed from the minor, F,C,G. You mentioned the G doesn't fit but G is diatonic to the A natural minor scale. The G, a bVII chord is widely used in both major and minor keys. ("All along the Watchtower" in minor, "A Hard Day's Night" in major)
The D7/D6 is actually also modal interchange in a way but with the A Dorian mode (F# instead of F) or the melodic minor scale. The IV7 chord is also widely used in many well known songs in both major and minor keys.
I see the only oddball chord, the B7 as an unresolved V of V. You can also think of it as a non-diatonic II7, a chord used in many songs such as "The Girl From Ipanema" and "Take the A Train" among many others. However in those songs there is a delayed devolution to the V which isn't the case here.
Comment: Thank you very much for the reply. I love music theory and hope to learn more here.
Comment: @JessinPrison My pleasure, MPT is a great resource for asking questions or searching topics of interest to you, there is a lot of great info and discussions here!
Answer: This progression is better explained as modal interchange between E major and minor. From that perspective, the progression is
IV > bII > I > IV
IV > bVI > bIII > bVII7
bVI > bIII > V7 > V7
In terms of where each chord comes from:
major > "Neapolitan chord" (What is a Neapolitan 6th?) > major > major
major > minor > minor > minor
minor > minor > either > either
Comment: Maybe it can be explained that way but it doesn't sound like a chord progression in the key of E. The only E chord functions as a dominant.
Comment: Thank you. I will be sure to read up on the Neopolitan 6th. I've also recently fallen in love with the Picardy 3rd.
Comment: I'd have to agree with @JohnBelzaguy, the argument for E major as the key here doesn't look too good. If B7 in A is a stretch, then what the heck is G major doing going to D7 in E? Seems a lot more logical to call it A major, if not purely based on where the A chords sit in relation to the hypermetric structure - why start and end sections on the IV like that? It's an interesting alternative theory, but IMO a bit far-fetched with no context to point to as evidence for me to believe it at the moment.
Comment: @user45266 - A G chord going to a D7 chord *always* makes sense (if all else fails, temporarily tonicize the G chord).
Comment: It feels and sounds more like A is tonic, and the only E in there works as dominant.
Answer: As other answers have concluded, modal interchange is a great term to describe what's going on here. Between A major and A minor, a majority of the chords can be explained pretty nicely. I do have a few additional thoughts about the progression (mostly in question form, since there's not enough context for me to make the determination myself - however, the principles behind what I'm asking apply to any analyst):

The second line A C G D is a pattern often referred to as the plagal cascade when it is done in A minor, so perhaps that pattern dictates the perception to some degree.
The last line C G B7 B7 on its own is reminiscent of E minor, however the progression jumps back up to an A chord to repeat. Is it possible that your progression could be better interpreted as periodically shifting between two (or more) keys?
The fact that most of the apparently-nonfunctional chord movements occur between 4-measure phrases might also be of relevance. Perhaps this means there's merit to looking at each unit of hypermeter (relax, every phrase of 4 measures) as its own separate thing?
There are two dominant 7th chords, D7 and B7. Both are immediately followed by the major chord built on their 7th (e.g. D7's 7th is the note C, which is the chord after the D7, and same for B7 and A). Could that parallelism reveal anything about the structure of the music? In fact, similar things can be noted about other mini-sequences: I noticed also that there are three occurrences of a major chord moving downwards by a major third, which is not common in most functional progressions. Do you think this observation has meaning?

Context is everything here. Is there a melody? It may even be best to simply accept that the progression defies functional expectations, and there may be little we can do to map it onto the patterns we commonly observe in functional music. My best advice if you want to understand the progression is to ask yourself why you picked the progression that you wrote. You weren't just randomly throwing chords together, right? You probably liked the sound of the progression, otherwise why isolate those specific chords as worthy of analysis? So try changing things, little things, and see what changes make it sound similar and which make it completely different and wrong. If you can pick out what the important things about the progression are, you can start to understand why you like it and how to (re)create similar things in your compositions.
Here's a head start on some little changes: Strip it down to only the root movement. Do you still like it? If all the A major chords were changed to A minor, does it still sound good to you? What about if some of the major chords become 7th chords? (if you can figure out which 7th chord type to pick that's a clue as to function) Or what if the last B7 chord were an E7 chord? See what changes matter, and which ones don't.


Textarea função php passar dados

Question: Tenho uma dúvida de como posso estar passando o valor de um textarea pra uma função do php.
Tenho a seguinte função:
function _dup($cclist) {
        for ($i = 0; $i < count($cclist); $i++) {
                $ccnum = info($cclist[$i]);

                if (is_array($ccnum)) {
                        $cc = $ccnum['num'];
                        for ($j = $i + 1; $j < count($cclist); $j++) {
                                if (inStr(str_replace("-", "", str_replace(" ", "", $cclist[$j])), $cc))
                                        $cclist[$j] = "";
                        }
                }
        }

        foreach ($cclist as $i => $cc)
                if ($cc == "")
                        unset($cclist[$i]);

        $ok = array_values($cclist);
        return $ok;
}

E pra executar o script tenho essa outra função:
function check($ccnum, $ccmonth, $ccyear, $cccvv) {
        $ccline = $ccnum."|".$ccmonth."|".$ccyear."|".$cccvv;
        $action = new Run();
        $action->addToCart();
        $action->CCLINE = $ccline;
        return $action->checkOut();
}

O texarea vai receber o valor nome|cpf|mae|data pra que a função check possa fazer a sua validação.
HTML

<form action="" method=post name=f> <textarea wrap="off" name=cclist cols=90 rows=20> </textarea>

 <input style="width:100px" class="button" type=submit name=submit size=10 value="Valida"> </form>

Comment: Olá, não sei se isto foi apenas durante a crianção da pergunta, ou se fizeste o mesmo no script, mas coloque as `aspas` nos atributos `html`, e outra coisa é, onde é que a função `_dup` é chamada ? E qual a verdadeira função dela no script ? ^^ na verdade não sei do que se trata o código, mas tenho impressão que se trata de um filtro para certos dados digitados na `textarea`. Aguardo retorno.
Comment: A textarea está num form?
Comment:

Comment: Edite sua pergunta colocando esse código (existe um botão editar logo aqui em cima)
Comment: Editada . poderia me ajuda agora ?
Comment: Seria só submeter o form para uma página em PHP que chamasse a função. Você já tentou isso?
Comment: Fica em branco .
Answer: Sua duvida está confusa, mas respondendo à pergunta:

como posso estar passando o valor de um textarea pra uma função do
  php.?
  Seria assim:

HTML

<form action="" method=post name=f>
<textarea wrap="off" name=cclist cols=90 rows=20> </textarea>

<input style="width:100px" class="button" type=submit name=submit size=10 value="Valida">
</form>

PHP
<?php
function nomeFuncao(){
   $cclist =  $_POST['cclist'];

Depois para separar os valores nome|cpf|mae|data se eles estarão separados por | fica facil:
    $cclist_separados = explode("|", $cclist);
    print_r($cclist_separados);
}

Textarea função php passar dados


Wasn't this comment rude?

Question: I flagged the following comment as rude, and the flag got declined. Wasn't this comment implicitly calling the OP "smart-ass" rude?

One thing I found is that playing smart-ass with USCIS is just asking for trouble.
Answer: I declined the flag. I read the comment and decided that while it pushes the limits of be nice that it provides enough value that I decided to keep it. As I think you know, there is a fine line between censoring comments via deletion and maintaining a welcoming community.
In retrospect, at a minimum, instead of declining the flag, I should have marked the flag as helpful (even while keeping the comment). In reviewing the comment, I have now edited the useful information (in a nicer format) into the answer.

Wasn't this comment rude?


Generating a random number in SML

Question: How can you generate a random number from a specific range, for example the integer 34 in the range [1, 100]?
I looked at the Random structure but it doesn't give me what I want, at least from what I can understand.
Comment: You're on the right track, have a look at the function `randRange` within the structure `Random`, it should be a perfect fit for what you need
Comment: Use the function `Rand.rand : (int * int) -> rand` to instantiate a random number generator. Also, be careful to leave out the enclosing parentheses when calling a curried function: `Random.randRange (i, j) s`
Comment: @waldrumpus Hmm, alright, but I don't understand how to write the arguments. It should be something like `Random.randRange((i, j) s)`, (or I'm completley wrong) but what is `s`?
Comment: @waldrumpus In Poly/ML there is no support for Random structure. How shall this be done with Poly/ML?
Answer: I think you have to use the Random structure in the given link like this ...
- val nextInt = Random.randRange (1,100);
- val r = Random.rand (1,1);
- val x1 = nextInt r;
- val x2 = nextInt r;

Answer: To get 34 integers between 1 and 100, you could use:
let
    val seed = Random.rand (123,456)
in
    List.tabulate(34, fn i => Random.randRange (1,100)  seed)
end;

Note that the value seed is a reference that gets updated with each call to Random.randRange.

Generating a random number in SML


How do I disable Twig and block cache for a specific module?

Question: I'm working on a module in Drupal 8 which retrieves time sensitive data from an external REST api. The data is processed and forwarded to a Block. The final data is sent to a Twig template like so:
...

public function build() {
  $build = [];

  $build['ticker_block'] = [
    '#theme' => 'module_theme',
    '#data' => $myService->data(),
  ];

  return $build;
}

This doesn't work on the production environment where cache is enabled and the rendered data shows up as stale. How do I disable cache for my module only, and do I have to do it for both the Twig template and Block plugin?
Answer: You can control the cache in the render array with the #cache element.
To disable the cache add:
$build['#cache']['max-age'] = 0;

In this case the block will not be cached for logged in users or anonymous users with a session.
If you want to disable the cache for anonymous users without a session:

Disable it either by uninstalling the page_cache module completely or
  by triggering the kill switch, see
  How can I prevent a particular page being cached? for example.

The caching of the twig code is not connected to this, the twig code is only cached once, the first time it is used after you cleared the cache.
(edit acc. to comments of Berdir)
Comment: $build['#cache']['max-age'] = 0; did the trick !!! Beers all round! :)
Comment: I suppose a cache context won't help in this specific case, but maybe you want to use an actual max-age instead of 0 which disabled caching completely, like 60. Not sure how time sensitive your data is, but usually, things can be cached for a minute or a few. Also, note that max-age does not affect the anonymous page cache. If you need this for anonymous users, you need to disable that completely or fetch the data using javascript.
Comment: @Berdir: I use the max-age=0 for anonymous users, but with sessions. This is working now in dev. Do you think this is OK for production? What do you mean with disable completely?
Comment: It's fine if you have sessions, then it works. Disable it either by uninstalling the page_cache module completely or by triggering the kill switch, see http://drupal.stackexchange.com/questions/151254/how-can-i-prevent-a-particular-page-being-cached-in-drupal-8/151289#151289 for example.
Comment: Thank you for the great info, i've added this in the answer.
Comment: Great info from both of you. Could of easily missed the caching for anonymous users.
Answer: To stop caching a specific block use the following function:
/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function template-name_preprocess_block(&$vars) {
  if($vars['derivative_plugin_id'] == 'add-block-id-name') {
    //-- This stops the block being cache in drupal 8
    $vars['#cache']['max-age'] = 0;
  }
}

Comment: Excellent answer.
Answer: Disable cache for a specific page/content type/controller

Disable cache for a custom page from route declaration.
If you want to
  disable cache for a custom controller (Custom module), You have
  no_cache option (YOUR_MODULE.routing.yml). Example : File :
  mymodule.routing.yml

mymodule.myroute:
  path: '/mymodule/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Pages::mypage'
    _title: 'No cache page'
  requirements:
    _access: 'TRUE'
  options:
    no_cache: 'TRUE'

Added 'no_cache' route option to mark a route's responses as uncacheable
Answer: To prevent caching of a particular block:
add the below code in theme_name.theme file
function theme_name_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_id') {
    $variables['#cache']['max-age'] = 0;
  }
}

Answer: To disable the cache for a block type, preprocess the block of that type and set max_age to 0.
   /**
     * Implements hook_preprocess_HOOK() for Block document templates.
     */
    function THEMENAME_preprocess_block(array &$variables) {

      //disbale cache from spotlight
      $content = $variables['elements']['content'];
      //dump($content); //check the contents
      if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {

        if ($content['#block_content']->bundle() == 'BLOCK_TYPE') {
          $variables['#cache']['max-age'] = 0;
        }

      }

    }


Best way to define error code and error message mapping in .NET

Question: I want to create custom error code and message mapping file. Currently I use Dictionary<int, string> to store them but I think they may have better way to achieve this.
If there is common practice to do this please let me know.
Answer: Maybe rather have a look at using a resource in the project
Adding and Editing Resources (Visual C#)
Comment: I think using resource file in this case is not appropriate, because my error code is int but resource name is string. This mean there will be boxing and un-boxing during get and set error code. BTW if you can suggest me how to change type of name of resource file from string to int, I'd appreciate it. :)
Answer: You could define an enum for your error codes that map to a resource file, that way they can be esaly manage, localized, etc.


Kernel Test: Programmatically create a vocabulary and add a field to it

Question: I want to add a taxonomy term and add field to it. My current code looks this way:
<code><?php

namespace Drupal\Tests\permissions_by_term\Kernel;

use Drupal\KernelTests\KernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\taxonomy\Entity\Vocabulary;

/**
 * Tests the ERR composite relationship upgrade path.
 *
 * @group permissions_by_term
 */
class SelectTermTest extends KernelTestBase {

  /**
   * {@inheritdoc}
   */
  public static $modules = array('taxonomy', 'text');

  /**
   * List of taxonomy term names by language.
   *
   * @var array
   */
  public $termNames = [];

  /**
   * The vocabulary used for creating terms.
   *
   * @var \Drupal\taxonomy\VocabularyInterface
   */
  protected $vocabulary;

  function setUp() {
    parent::setUp();

    $this->installEntitySchema('taxonomy_term');

    // Create a vocabulary.
    $this->vocabulary = Vocabulary::create([
      'name' => 'Views testing tags',
      'vid' => 'views_testing_tags',
    ]);
    $this->vocabulary->save();

    // Add a translatable field to the vocabulary.
    $field = FieldStorageConfig::create(array(
      'field_name' => 'field_foo',
      'entity_type' => 'taxonomy_term',
      'type' => 'text',
    ));
    $field->save();
    FieldConfig::create([
      'field_name' => 'field_foo',
      'entity_type' => 'taxonomy_term',
      'label' => 'Foo',
      'bundle' => 'views_testing_tags',
    ])->save();
  }

  public function testSomething() {
  }

}
</code>
If I run the test by the following command:

vendor/bin/phpunit -c modules/permissions_by_term
  modules/permissions_by_term/tests/src/Kernel/SelectTermTest.php

I'm getting the following output:

PHPUnit 4.8.11 by Sebastian Bergmann and contributors.
E
Time: 882 ms, Memory: 6.00Mb
There was 1 error:
1)
  Drupal\Tests\permissions_by_term\Kernel\SelectTermTest::testSomething
  Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The
  Drupal\field\Entity\FieldStorageConfig class does not correspond to an
  entity type.
/home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/EntityTypeRepository.php:98
  /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/EntityManager.php:375
  /home/peter/Websites/pbt-d8/core/lib/Drupal/Core/Entity/Entity.php:509
  /home/peter/Websites/pbt-d8/modules/permissions_by_term/tests/src/Kernel/SelectTermTest.php:49
FAILURES! Tests: 1, Assertions: 1, Errors: 1.

I do not understand this part:

Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The
  Drupal\field\Entity\FieldStorageConfig class does not correspond to an
  entity type.

As an example I have used the Drupal core taxonomy test from

core/modules/taxonomy/src/Tests/Views/TaxonomyFieldFilterTest.php

This test does what I want to do, but is not a Kernel test. It is a Simpletest, since it inherits from WebTestBase. If I use WebTestBase, it works. But the test is much slower then. Do you know what's missing in my code for running it as a Kernel Test?
Comment: I didn't try but I guess it should be similar as creating node with field. Please take a look on the answer of this [post](http://drupal.stackexchange.com/a/189095/56904).
Comment: This is corrected.
Comment: Thanks for your comments so far. Actually I want to create an automated test for taxonomy terms. For my test I need to add a field to a taxonomy term. I tried it the following way so far: [GitHub Gist](https://gist.github.com/jepster/363f8ce3b43d9ca6490eb1d39b29c42e)

But I get the following error:

Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The Drupal\field\Entity\FieldStorageConfig class does not correspond to an entity type.

How can I fix this?
Comment: The way you show us is to create a vocabulary and attach a field to that vocabulary. You question is misleading, could you update it?
Comment: You have been right, what I really wanted to do was to create a vocabulary and add a field to it. I was thinking I need to add a field to the term. Thanks for the hint. I have updated my question.
Answer: You need to enable the field module so its entity types are present. Kernel test base does not enable required modules so the FieldConfig and FieldStorageConfig entity types don't exist until you enable the field module. Put it in the $modules property with 'taxonomy' and 'text'.
Answer: You should try FieldKernelTestBase instead of just KernelTestBase. There is a helper method called createFieldWithStorage who will do the job.
Comment: Why not just export and import the config? Instead of recreating the fields with storage? Just curious


Why is MVC scaffolding failing? (w/ different errors in VS2012 vs VS2013)

Question: I'm leveraging a large existing codebase of business objects and their associated data access layer into an ASP.NET MVC web application.  When scaffolding views for the business objects, the scaffolding engine fails with the following message in Visual Studio 2013:

Error
There was an error running the selected code generator:
  'The method or operation is not implemented.'

In Visual Studio 2012, the error is:

Error
There was an error running the selected code generator:
  'The Extender Provider failed to return an Extender for this object.'

Already tried:

Copying the default templates to a CodeTemplates folder: I got custom templates to work just fine on some POCOs I added directly to the project, but they fail on the real objects I want to use.
Wrapping the CodeTemplates in try/catch blocks with the catch set to write to trace: I tried this method but never got any trace results.  I suspect the error is before the template itself starts processing.

Of note, the business objects are split into three partial classes each.  The "Model class" select list in the "Add View" window shows three of each class name, but selecting any of the three for any of the business object classes gives the same error.
How can I find out what is causing the actual error and either correct it or find a workaround?
Comment: I had this same problem when my model inherited a type defined in another assembly.  I could use the generator if I specified the external type directly or if I removed the inheritance, but every time I tried to maintain an inheritance relationship between assemblies I got "The method or operation is not implemented" (this in VS 2015).  Annoying.
Comment: Are you able to find in the stack trace what method or operation is throwing that VS2013 exception?
Comment: No, which is a big part of the problem.  All I get are message boxes with the error.  Nothing even shows up in the output pane.
Comment: can you share same some of code against which you are using scaffolding.
Comment: That would be difficult since the code is on a closed network--I'm more interested in getting any kind of feedback at all from the scaffolding system to tell me where it's having a problem.
Comment: Have you tried deleting all binaries and obj files within the solution as suggested [here](http://stackoverflow.com/q/3397779/3242721)?
Comment: Yes, I have a batch file that deletes out all the bin and obj folders in the solution tree.  It did not help, however.
Answer: Check what version of EntityFramework are you using, if it is > 6.1.0
turn it to 6.1.0. or lower.
I dont know why it is so, but when i changed version of EntityFramework in my project scaffolding starts work correctly.
Answer: In my experiences, most error is either the code haven't compiled yet (It's kinda a weird issue, VS sometimes can't see the class that is not compiled yet), or perhaps different namespace used,
I hope that's really helps


Pass multiple sets of variables to theme function

Question: If I want to loop through multiple sets of theme variables in my custom theme template, how do I define them in my theme function and pass them to hook_theme?
For instance, in my case, I'm generating an email body to send via drupal_mail(), and the body will contain a list of spa openings. I want to iterate through each set in the mail (the same way views templates iterate over views rows). I have my theme function defined like so:
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_module_mail' => array(
      'variables' => array(
        'service_name' => NULL,
        'time' => NULL,
        'therapist' => NULL,
        'booking_link' => NULL,
      ),
      'template' => 'templates/my-module-mail',
    ),
  );
}

and I can pass one set of variables to the template just fine like so:
foreach ($available_openings[$tid['tid']] as $mail_opening) {
  $variables = $mail_opening;
  $body = theme('my_module_mail', $variables);
}

but what I want to do is pass an array of the variables array so that in my template can do something like this:
<?php foreach ($openings as $id => $opening): ?>
  <div class="<?php print $classes_array[$id]; ?>">
    <?php print $opening; ?>

<?php endforeach; ?>

What do I need to change to do that?
Thanks.
Answer: And, the general rule of "post a question and that helps you figure it out yourself" applies here yet again.
All I did was modify my theme hook like so:
/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return array(
    'my-module-mail' => array(
      'variables' => array(
        'openings' => array(
          'service_name' => NULL,
          'time' => NULL,
          'therapist' => NULL,
          'booking_link' => NULL,
        ),
      ),
      'template' => 'templates/my-module-mail',
    ),
  );
}

and fill my $variables array like so:
  // Loop through all openings for this category.
    foreach ($available_openings[$tid['tid']] as $mail_opening) {
      $variables['openings'][] = $mail_opening;
    }
    $body = theme('my_module_mail', $variables);
    // Define mail parameters.
    $params = array(
      'subject' => t('Your Available Openings'),
      'body' => $body,
    );
    // Send the mail.
    drupal_mail('my-module-mail', 'featured_openings', $entity->mail, language_default(), $params);

and it works like a charm.


Estimation with complex exponent

Question: Context (not necessary to understand the task). I'm working through so called Eigenvalue Estimation Problem from the field of Quantum Computing. More precisely, I try to measure the inaccuracy of the quantum circuit when an eigenvalue measured is irrational (the circuit is designed for rational phases).
The task can be reduced to the estimation with the lower bound of an (modulus of) expression:
$$
\frac 1 {2^m} \frac {1 - e^{2\pi i \delta 2^m}} {1 - e^{2\pi i \delta }}
$$
Here $m$ is a natural number, $\delta$ is a real from $[0,1)$, $i$ is the imaginary unit.
It is known that the desired lower bound is $2 / \pi$. It is suggested to get upper bound for denominator (which is clearly $2\pi\delta$) and lower bound for numerator (which is problematic for me) and then divide them. It is known that numerator $N$ can be estimated like this: $ N > 2\pi\delta2^m(2/\pi) > 4\delta 2^m$. Can anyone explain, how to obtain the bound in the left part of the inequality?
Comment: I think that desired estimation is wrong. See code: http://cpp.sh/8qiog
Comment: Key role plays 2^(-m) factor, result lower bound cannot be without it
Comment: I suppose, that your estimation will be right only in the case, where we have fixed number m (it plays role as constant), and b converges to +0.
Answer: It is another approach which finds more exact lower bound (you can see it in my program for example)
It gives lower bound 1 (as limit)
Note, it will works only if b converges to +0 (for very small b and fixed m)
Answer: The solution turns to be direct consequence of Jordan's inequality:
$$
    \sin x \geqslant x \frac 2 {\pi}
$$
We would like to obtain lower bound for $|1 - e^{2\pi i \delta 2^m}|$, that is $|AC|$ on the following graphics with unit circle:

$OB$ is altitude and, at the same time, bisector and median, so
$$|AC| = 2 |AB| = 2 \sin {\frac a 2} \geqslant 2 \frac a 2 \frac 2 {\pi} = \frac {2a} \pi .$$
Given that $a = 2\pi \delta 2^m$ we have desired $|AC| = |1 - e^{2\pi i \delta 2^m}| \geqslant 4 \delta 2^m$. The whole fraction from the post turns to be estimated as follows:
$$
\frac 1 {2^m} \frac {1 - e^{2\pi i \delta 2^m}} {1 - e^{2\pi i \delta }}
\geqslant
\frac 1 {2^m} \frac {4 \delta 2^m} {2 \pi \delta} = \frac 2 {\pi}.
$$

Estimation with complex exponent


How to manage user permissions?

Question: I would like to manage user permissions with Drush, but I don't find any command on the official documentation website.
How to achieve this?
I am using Drupal 6, and Drush 6.0-dev.
Comment: Drush is not supposed to do that. Its a site builder/developer tool.
Answer: Try this command:
drush role-add-perm 'user-role' 'permission'

Answer: You can install the Permissions API

The permissions_api module provides a method for granting and revoking
  permissions for a given role. This module helps with the issue of
  staging a Drupal site across multiple environments, from development
  sandbox to production environment.

...

Version 6.x-2.9 adds support for Drush!
Comment: ok i install the api permissions module, then where can i found commands ? i don't know how to see help in drush..
Answer: permissions_api will work for your purposes, but as of yet it has no 7.x version.  For those who want a solution that works with both Drupal 6 and Drupal 7, Drush v6.0-dev has commands to manage roles and permissions built in.  See drush help and this previous answer: Creating a new user role with Drush
Regarding finding the commands available in a module that has Drush support, use drush help --filter, and Drush will show the available command groupings. Select the module you are interested in, and all of the Drush commands it supports will be displayed.  If you are having trouble getting Drush to recognize a new commandfile, try drush cc drush to clear the Drush command cache.  Drush will do this automatically when a new module is downloaded and enabled, but you may need to do it manually if you copy in a Drush commandfile by hand.
Answer: have you tried ?
 drush php-eval 'node_access_rebuild();'

Comment: no,but i will when need appear

How to manage user permissions?


If $Y$ is a normal random variable with mean $\mu$ and standard deviation $\sigma$, find $p(|y-\mu|>2\sigma)$?

Question: If $Y$ is a normal random variable with mean $\mu$ and standard deviation $\sigma$, find $p(|y-\mu|>2\sigma)$
$\underline{Attempt}$
Given that $Y$ is normal distribution thus $z=\dfrac{y-\mu}{\sigma}$,
$$p(|y-\mu|>2\sigma)=p(|z\sigma|>2\sigma)=p(-2>z>2)$$ by using table I got
$p(|y-\mu|>2\sigma)=2p(z>2)=0.0456$
Is that correct I feel not correct?
Answer: You've a typo, it should be $$P(|Z|>2)=P(Z<-2\cup Z>2)=2P(Z>2)=2\times 0.0228=0.0456$$
So, it is approximately correct since the table is approximate.
P.S. Using uppercase letters for denoting random variables is better since lowercase letters are typically used for scalars.
Comment: Thank you for your informations
Comment: It wasn't a typo $|Z|>2 \iff-2>Z>2$ is that wrong
Comment: What do you think about -2 > 2?
Comment: Oh funny :) thank you mention it


How do i add custom Json to an elastic4s search

Question: Is there any way for elastic4s to allow me to build this search request:
<code> {
  "size" : 100,
  "query" : {
    "bool" : {
      "must" : {
        "term" : {
          "disabled" : false
        }
      }
    }
  },
  "gas-filter" : {
      "name" : "SearchResultCypherFilter",
      "query" : "MATCH (a)-[:KNOWS*]->(d{referenceId:'522d8b956819338605a53948c5dcef1a'}) RETURN distinct a.referenceId as guid",
      "exclude" : true
    }
  }
</code>
Answer: elastic4s version 2.3.1 and greater allows you to add a extra source Json
<code>search in "maalka" bool matchAllQuery limit 10 extraSource Json.stringify(Json.obj(
  "gas-filter" -> Json.obj(
      "name" -> "SearchResultCypherFilter",
      "query" -> "MATCH (a)-[:KNOWS*]->(d{referenceId:'522d8b956819338605a53948c5dcef1a'}) RETURN distinct a.referenceId as guid",
      "exclude" -> true)
))
</code>


How to provide/mock Angularfirestore module inside angular component for default test to pass?

Question: How can I provide AngularFirestore module inside my app.component so that my default toBeTruthy() test will pass?
Error: StaticInjectorError(DynamicTestModule)[AppComponent -> AngularFirestore]:
      StaticInjectorError(Platform: core)[AppComponent -> AngularFirestore]:
        NullInjectorError: No provider for AngularFirestore!

app.component
export class AppComponent implements OnInit {
  private notesCollection: AngularFirestoreCollection<any>;
  public notes: Observable<any[]>;

  constructor(private afs: AngularFirestore) {}

  ngOnInit() {
    this.notesCollection = this.afs.collection('notes');
    this.notes = this.notesCollection.valueChanges();
  }
}

it's just the default test:
class FirebaseMock implements AngularFirestore {
  app: FirebaseApp;
  firestore: FirebaseFirestore;
  persistenceEnabled$: Observable<boolean>;

  collection<T>(path: string, queryFn?: QueryFn): AngularFirestoreCollection<T> {
    return undefined;
  }

  doc<T>(path: string): AngularFirestoreDocument<T> {
    return undefined;
  }

  createId(): string {
    return undefined;
  }
}

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(
    async(() => {
      TestBed.configureTestingModule({
        imports: [
          RouterTestingModule,

        ],
        declarations: [ AppComponent ],
        providers: [
          {
            provide: AngularFirestoreModule,
            useClass: FirebaseMock
          },
        ],
      }).compileComponents();
    }),
  );

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Comment: Use  [katowulf/mockfirebase](https://github.com/katowulf/mockfirebase/wiki/Testing-AngularFire), or roll your own. Make sure you add a provider reference to TestBed.
Comment: This is from AngularJS... theres gotta be a better way no? Also using firestore which maybe different?
Answer: You have to either mock "AngularFirestore" or inject it as is and create spy on its methods so it won't get called. I would not recommend the second option because it requires the real service to be injected which may depend on other services too. So, you have to inject them as well which may end up requiring millions of services to test just one component. So, let's go with the first option.
If it is commonly used among your component, I'd suggest you create a "stub" module for these kinds of services and import this module in components test modules that you want to test. If it is just for this component, you can create something easy like this: (let's start with easy one and create module later)
app.component.spec.ts
describe('AppComponent', () => {
    let component: AppComponent;
    let fixture: ComponentFixture<AppComponent>;

    const AngularFirestoreStub = {
        // I just mocked the function you need, if there are more, you can add them here.
        collection: (someString) => {
            // return mocked collection here
        }
    };

    beforeEach(
        async(() => {
           TestBed.configureTestingModule({
               imports: [ RouterTestingModule],
               // I used 'useValue' because it is just a json. If it was class, I'd use 'useClass'
               providers: [{provide: AngularFirestore, useValue: AngularFirestoreStub}]
               declarations: [ AppComponent ]
           }).compileComponents();
        })
    );

    beforeEach(() => {
        fixture = TestBed.createComponent(AppComponent); // Should be fine
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy(); // Should pass
    });
});

As I said before, if AngularFirestore is a service used by many of your components, then create a stub module somewhere in your project (in my project I created a testing folder and put it next to src)
CommonServiceModuleStub
@NgModule({
    providers: [{provide: AngularFirestore, useClass: AngularFirestoreStub}]
})
export class CommonServiceModuleStub {}

// I'd recommend you put this service in a subfolder.
// This time, I created a class instead of a json.
// It is because, your other components may require more 'mocked' functions.
// It may be harder to maintain them within a json.
@Injectable()
export class AngularFirestoreStub {
    collection(someString) {
        // return mock collection;
    }
}

Now, instead of providing yourself just import the module we just created
app.component.spec.ts
 ...
 TestBed.configureTestingModule({
     imports: [ RouterTestingModule, CommonServiceModuleStub],
     declarations: [ AppComponent ]
 }).compileComponents();

Option 2
Sometimes, your services are simple ones and you don't want to bother going all the way to "mock" them. Take a look at the following example
app.component.ts
@Component({ ... })
export class AppComponent {
    constructor(private myService: AwesomeService) {}

    doSomethingCool() {
        this.myService.getAwesomeStuff();
    }
}

Let's configure TestBed first,
app.component.spec.ts
 ...
 TestBed.configureTestingModule({
     imports: [ RouterTestingModule],
     // since, 'AwesomeService' is a service on its own and
     // doesn't require other services, we easily provide it here
     providers: [ AwesomeService ]
     declarations: [ AppComponent ]
 }).compileComponents();

And within a test
it('should do something cool without getting awesome stuff', () => {
    spyOn(component.myService, 'getAwesomeStuff');
    // Note: if you want to spy on it and you want it to get called for real
    // you should do following
    // spyOn(component.myService, 'getAwesomeStuff').and.callThrough();
    // or return fake output
    // spyOn(component.myService, 'getAwesomeStuff')
    //        .and.callFake((arguments, can, be, received) =>  {
    //                          return fake;
    //                      });

    component.doSomethingCool();
    expect(component.myService.getAwesomeStuff).toHaveBeenCalled();
});

For more info, you can take a look at jasmine docs
Comment: So I did the first example and am still getting the same error.  I implemented firestore to get the real members.. any idea where I'm going wrong?
Comment: Because, you wrote `provide: AngularFirestoreModule` instead of `AngularFirestore` which is the service your component needs.
Comment: Lol you right... Marking correct but could you show the last example of spying on the service as I'm such a noob.


What procedures does the FIA take when there are thunderstorms?

Question: For the 2022 Formula 1 Season, Miami is hosting one of two races in the USA.
Miami, and Florida as a whole, has a bit of a reputation for quite severe thunderstorms, and particularly whereby sporting events have had to be postponed because of such weather. 1 2
Although there may be lightning in the air, that may not necessarily mean the track conditions are unsuitable for racing, for example any rain that comes with the thunderstorm could be negated by Wet tyres, and a thunderstorm does not necessarily mean heavy rain. However, given that the drivers are going around in an electrically conductive box, and that fans are usually situated on uncovered temporary stands (read: scaffolding), lightning could be seen as a danger.
Are there any specific set of procedures for the Race Director to follow in the case of thunderstorms?
Answer: Looking at the official FIA sporting regulations document listed on the FIA site, there's not a specific set of procedures for the scenario that you are painting.
But if this scenario were to happen, it would be at the discretion of the race director on the day to either keep the practice/race going, or Abort/Red Flag the session.
The logical option would be to follow the same procedures to restarting a wet-weather session.
Here are some steps that may be taken as per the Sporting regulations document:

4.4.6 Should it become necessary to stop any practice session because the circuit is blocked by an
accident or because weather or other conditions make it dangerous to continue, the clerk of the
course will order red flags to be shown at all marshal posts and the abort lights to be shown at the
Line.
When the signal is given to stop all cars must immediately reduce speed and proceed slowly back
to the pit lane. In order to ensure that drivers reduce speed sufficiently, from the time at which
the "RED FLAG" message appears on the official messaging system until the time that each car
crosses the first safety car line when entering the pit lane, drivers must stay above the minimum
time set by the FIA ECU at least once in each marshalling sector (a marshalling sector is defined as
the section of track between each of the FIA light panels).
All cars abandoned on the track will be removed to a safe place.
At the end of each practice session no driver may cross the Line more than once.

I also think that section 4.8.14 (c) of the sporting regulations may also apply during the restarts, but it's too long for this post, so I've added a link to the 2022 sporting regulations below.
2022 FORMULA 1 SPORTING REGULATIONS


What is the mean and variance of $Y$, where $Y$ is sum of iid's

Question:
Here's my work for part a. I could use clarification on part b and d. Is part d the same as part a ($E[A_n] = E[Y]$) ?
a)
$$E[Y_n] = E[\frac{X_n}{2^n}]$$ ($X$'s are iid so...) $$= \frac{E[X]}{2^n} = \frac2{2^n}$$
$$Var(Y_n) = \frac{Var(X_n)}{4^n} = \frac9{4^n}$$
b) $E[T_n] = E[\sum_{i=0}^n Y_i] = E[1 + \frac12 + \frac14 + ... + \frac2{2^n}] = E[\frac1{1-\frac12}] = 2$
Is this correct?
Comment: Is $T_n$, the **sum** of the $Y_i$, given by $\sum_{i=1}^n Y_i$ or $\sum_{i=1}^n Y_i^2$?
Comment: Sum of the Y_i. My mistake, did not mean to write ^2.
Answer: What you have for b is wrong this is because
$$E[T_{n}]=E\left[\sum_{i=1}^{n}Y_{i}\right]=\sum_{i=1}^{n}E[Y_{i}]=\sum_{i=1}^{n}\frac{2}{2^{i}}=\sum_{i=1}^{n}\frac{1}{2^{i-1}}=\sum_{i=0}^{n-1}\frac{1}{2^{i}}$$
Now here you also attempted to use fact about a geometric series, but remember n is finite here (it is not approaching infinity like it does in a geometric series). Thus we actually have (which is derived here (http://en.wikipedia.org/wiki/Geometric_series#Proof_of_convergence)
$$=\frac{1-\frac{1}{2^{n}}}{1-\frac{1}{2}}=2\left(1-\frac{1}{2^{n}}\right)$$
For further use of this, i guess you would call it, "finite geometric sum" the property is that
$$\sum_{i=0}^{n-1}ar^{i}=a\frac{1-r^{n}}{1-r}$$
where you must make sure indices and such are exactly the same form to use this exact result.
Comment: Also note for a) you say "$X_{i}$'s are iid so..", the properties you use following do not require any iid aspects, this will come into play for finding variance in (b) and (c)
Comment: So is $var(T_n)$ and $var(A_n)$ = $\frac{9n}{4^n} and \frac9{n*4^n}$, respectively?
Comment: Var(Tn) should equal $3(1-\frac{1}{4^{n}})$ and $Var(An)=Var(\frac{Tn}{n})=\frac{1}{n^{2}}Var(Tn)$, I think you are trying to evoke property that for $W_{i}$ iid rvs (thus all have same variance) that $Var(\sum_{i=1}^{n}W_{i})=n\sigma^{2}$, but notice that $Y_{i}$'s aren't iid
Comment: (namely not identically distributed)
Comment: Understood. Thank you for explaining.
Comment: Yea its definitely something to get easily confused, just remember if you are dealing with iid many properties that make these computations easy can't be used so you have be careful when doing problem
Comment: Please delete the $a$ in your last displayed equation, or insert an $a$ on the right hand side.
Comment: @dilipSarwate thanks for that catch


Why is a Perfect Fourth Considered Consonant?

Question: I've been doing some research into the harmonic series lately. What I've come to understand is that the lower the ratio between the harmonics, the more pleasant/consonant the interval is. So, an octave is consonant and so are perfect fifths. And if the harmonic ratio is very large, it is dissonant, like tritones and minor seconds. But the Perfect Fourth first appears as the 21st harmonic, which is very high. So why is the Perfect Fourth consonant?
I also realize that the perfect fourth and the perfect fifth are inversions of each other, so thus should have the same level of consonance, but how does this relate to harmonics?
Comment: It wasn't always considered as such a consonant. If you study classic harmony, you'll they were trying to avoid it (but it was used)
Answer: True that the 21st harmonic of a fundamental pitch
is somewhere near 4 octaves plus a fourth.
Somewhere near, as in 29 cents flat,
at 52.71 half-steps out of 53.
More important for consonance, however,
is that the 3rd and 4th harmonics of a fundamental pitch
are almost exactly a fourth apart.

For the fourth between C4 and F4, that fundamental pitch is F2.

   Note   Pitch         Harmonics of F2  (pertinent)       Harmonics of C0  (misleading)

    F4   349.2 Hz             4      349.2 Hz                   21      343.4 Hz

    C4   261.6 Hz             3      261.9 Hz                   16      261.6 Hz

                              2      174.6 Hz                    8      180.8 Hz
                         fundamental  87.3 Hz  F2                4       65.4 Hz
                                                                 2       32.7 Hz
                                                            fundamental  16.4 Hz  C0

A C4–F4 fourth is extremely consonant,
mathematically at least, for three reasons.

One note is almost exactly an overtone of F2
while the other is utterly exact.
The higher note has a very low harmonic number, at 4.
The lower the better.

This is equivalent to having a simpler fraction for the pitch ratio.
The fundamental pitch F2 is fairly high, at 87.3 Hz.
The higher the better.

This often-overlooked factor
helps explain why the same interval two octaves lower
sounds much less consonant and is rarely used.
Answer: The perfect fourth has a frequency ratio of 4/3.  I don't know how you arrive at "19th harmonic" here.  A perfect fifth has a frequency ratio of 3/2, and a perfect fourth is one octave up and a perfect fifth down again.
If you take a look at overtone series and "normalize" the octave (and remove previous ratios), the denominator will always be a power of 2 (because of normalizing the octave).  You'll never get at 4/3, a perfect fourth, in that manner.
So you are doing something strange apparently.  What is it?
Comment: I meant 21st harmonic, since that's when it first appears in the harmonic series. But the ratio of 4/3 makes more sense. Thanks.
Comment: Actually, as user40161 says, the ratio of 4/3 never appears in the harmonic sequence with the fundamental tone the lower.
Answer: I wouldn't say that two intervals being inversions of each other will have the same level of consonance.  A minor 9 is significantly more dissonant than a major 7, as one extreme example.
While the harmonic series seems to supply a decent correlation with consonance in the way that you have described, it can lead you astray.  The way that I think of this is that if you look at the wave lengths of two intervals and see how frequently they align, you will get a better measure of harmonic consonance/dissonance.  The octave is the most consonant interval at a 2:1 ratio (the upper note of the octave goes through two cycles for each one of the lower note), followed by the fifth with a 3:2 ration, then the fourth at 4:3.
An interesting way to conceptualize this is to look at intervals at different frequency ranges.  I've mentioned that wavelength/frequency and how frequently those align between two notes is a valid measure of consonance.  If you were to take an interval that is kind of in the middle, say a major third (5:4), play it around the middle of the piano, then play if down three octaves, you would find that the same interval sounds more dissonant further down the keyboard.  The lower frequency notes have a longer wavelength and since we've established that how frequently two sound waves align determines consonance/dissonance, we can understand that the increased dissonance that we experience at a lower octave is the result of the longer wavelengths taking more time to align again as compared to the same interval in a higher register.
I'd also mention that in your quest to better understand consonance and dissonance, you should pay attention to relative levels of each based on context.  Any note taken alone will not have a feeling of consonance or dissonance but when played in a series of notes, they will end up having noticeable dissonance.  For instance, if you play an ascending major scale and stop on the 7th degree, you will find that the ear really wants to take the last step up to the octave, ie, the 7th degree of the scale is more dissonant than the others and desires resolution to the root, hence its name "leading tone".  Similarly, you will notice that a major chord played by itself will sound nice and consonant but when played in a chord progression, different major chords have different levels of consonance or dissonance.  For example, the dominant tonic relationship: if we are in the key of C and play a G major chord, it wants to resolve to C because it is dissonant within the context.  You should find that this contextual dissonance outweighs the logic described above, eg, the G that wants to resolve to C will feel more dissonant than the C, even when the G is in a higher register (the above logic would dictate that G would be more consonant because it is the same group of intervals in a higher register).
I've heard a definition of dissonance that kind of breaks the usual concept and I can't entirely agree with.  The idea was that dissonance is essentially the measure of how much a note or group of notes wants to resolve to another note or group of notes.  I don't really take issue with this.  However, using this logic, the least dissonant music would be atonal music since the idea of atonality is to avoid having any one note feel more like home than any other, so no note or group of notes has a strong pull to any other note or group of notes.  This is the part I take issue with.  Anyone listening to atonal music can tell you as objectively as a human is able that it is more dissonant than a I-IV-V-I progression.  I only really mention this as another thing to consider.
Answer: Despite being a mathematician, I feel that the idea that consonance is determined by simple frequency ratios is exaggerated.  Does a fifth sound more consonant than a third?  Play a melody with an accompaniment a third or a fifth away, which sounds nicer?  A diminished fifth is famously dissonant but add a couple more notes to make a diminished chord and it does not sound dissonant.
Also, if it were that simple then any interval other than an octave would sound terrible on a well tempered instrument since all of the frequency ratios are irrational.


Create a menu block based on path using views

Question: I'm trying to use views 3 to create a view that I can place in a block that is based on the url path
For example
example.com/student/
example.com/student/page1
example.com/student/page2
example.com/student/page3
All 4 pages are in the menu along with other pages
Students
   page1
   page2
   page3
I want to create a view that will display (dynamically) on pages with the following url pattern example.com/student/*
I want the view to only return child menu items that have Student as a parent.
I'm working with menu view, but I can not get the contextual filter and relationship to work correctly.  Any tips. Or an alternate way to accomplish
Answer: You can simply use Menu Block module to accomplish this task. If you want to display a block on specific pages just goto the relevant block configuration and under " Show block on specific pages" select "Only on listed pages" define the following
student/*
Now your block will appear only if this URL pattern will match. No matter what you have used to create your block.
Comment: Right, but then I will have to create a block for every url type. Correct??  One for */student/* another for courses/* etc... and I'll need distinct menus for each group of pages? I would like to be able to do it dynamically based on the sub section of the main menu.


Adicionar funções em kivy

Question: Sou iniciante em python e em programação no gera, estou fazendo um projeto para a feira de ciências da escola e preciso de ajuda para adicionar está função à minha interface gráfica(estou utilizando python 3.6 e estou no Ubuntu):
class Assistente(Screen):
def frase(self):
    resp = input('Olá! O meu nome é AVUSA. A sua Assistente Virtual para o Uso Sustentável da Água.\n'
                   'Você você precisa de assistência  quanto ao controle do uso de água na sua residência?')

    if resp == 'sim':
        temChuv = int(input('Então vamos lá! Quanto tempo, em minutos, você gasta debaixo do chuveiro em um dia?:'))

        Lbanho = temChuv * 6

        temVaso = float(input('Beleza! Quantas descargas você costuma dar em um dia?:'))

        LVaso = temVaso * 12

        tempb = float(input('Ok! Quanto tempo, em minutos, você gasta usando a pia do banheiro em um dia?:'))

        Lpb = tempb * 5

        tempc = float(input('Ok! Quanto tempo, em minutos, você gasta usando a pia da cozinha em um dia?:'))
        Lpc = tempc * 6

        temTan = float(input('Ok! Quanto tempo, em minutos, você gasta usando o tanquinho, em um dia?'))
        LTan = temTan * 15

        temMaq = float(input('Beleza! Quantas vezes você utiliza a máquina de lavar roupas por semana?:'))
        LMaq = temMaq * 12

        TotalpDia = float(Lbanho + LVaso + Lpc + Lpb + LMaq + LTan)
        TotalpMes = float(TotalpDia * 31)
        AcreDia = (TotalpDia * 3.14 / 1000)
        AcreMes = (31 * AcreDia)
        conredu = float(AcreMes - 10.54)

        print('Você consome cerca de {:.2f} litros de água por dia!\n'.format(TotalpDia))
        print('E em um mês você consome cerca de {:.2f} litros de água!\n'.format(TotalpMes))
        print(
            'Isto representa um acréscimo de cerca de R${:.2f} por dia e R${:.2f} por mês na sua conta de água\n'.format
            (AcreDia, AcreMes))

        if TotalpDia > 110.0:
            print('A ONU (Organização das Nações Unidas) diz que 110.0 litros por dia são suficientes para\n'
                  'atender as necessidades básicas de consumo e higiene de uma pessoa. ')

            print(
                'Portanto, caso você reduza seu consumo de água de {:.2f} para 110 litros por dia. Conseguirá\numa redução de '
                'cerca de R$ 10.54 na sua conta de água, que passará a ser R${:.2f}, e estará fazendo a sua parte no uso consciente deste recurso.'.format(
                    TotalpDia, conredu))

        else:
            print(
                'Parabéns! Você está dentro do limite do uso diário de água estipulado pela ONU (Organização das Nações Unidas')

    elif resp == 'não':
        print('Tá bom. Se precisar, estarei sempre à sua disposição! :)')

test.kv:

    Menu:
        name:'menu'
Tarefas:
    name:'tarefas'

Assistente:
    name:'assistente'

:
    BoxLayout:
        orientation:'vertical'
        padding:root.width*0.32, root.height*0.25
        spacing:'25dp'
        canvas:
            Color:
                rgba:1,1,1,1
            Rectangle:
                size:self.size
                pos:self.pos
    Image:
        source:'logo.png'
        size_hint_y:2.3
        allow_strech:True

    Botao:

        text:'Tarefas'
        on_release:app.root.current = 'tarefas'
        on_release:app.root.transition.direction = 'right'
    Botao:
        text:'Assistente'
        on_release:app.root.current = 'assistente'
        on_release:app.root.transition.direction = 'left'

    Botao:
        text:'Sair'
        on_release:root.confirmacao()

:
    BoxLayout:
        orientation:'vertical'
        canvas:
            Color:
                rgba:1,1,1,1
            Rectangle:
                size:self.size
                pos:self.pos
    ActionBar:
        ActionView:
            ActionPrevious:
                title:'Tarefa'
                on_release:app.root.current = 'menu'

            ActionButton:
                text:'Sair'
                on_release:app.stop()

    ScrollView:
        BoxLayout:
            id:box
            orientation:'vertical'
            size_hint_y:None
            height:self.minimum_height
            color:0,0,0,1

    BoxLayout:
        size_hint_y:None
        height:'40sp'
        TextInput:
            id:texto

        Button:
            text:'+'
            size_hint_x:None
            width:'40sp'
            on_release:root.addWidget()
            background_color:(0,1,2,1)

:
    size_hint_y:None
    height:'100sp'
    Splitter:
        strip_size:'3pt'
        sizable_from:'bottom'
        Label:
            id:label
            font_size:'20sp'
            color:0,0,0,1
Button:
    text:'X'
    size_hint_x:None
    width:'40sp'
    on_release:app.root.get_screen('tarefas').removeWidget(root)
    background_color:(0,1,2,1)

:
    BoxLayout:
        orientation:'vertical'
        canvas:
            Color:
                rgba:1,1,1,1
            Rectangle:
                size:self.size
                pos:self.pos
    ActionBar:
        ActionView:
            ActionPrevious:
                title:'Assistente'
                on_release:app.root.current = 'menu'

            ActionButton:
                text:'Sair'
                on_release:app.stop()

    ScrollView:
        BoxLayout:
            id:box
            orientation:'vertical'
            size_hint_y:None
            height:self.minimum_height
            color:0,0,0,1

    BoxLayout:
        size_hint_y:None
        height:'40sp'
        TextInput:
            id:texto

        Button:
            text:'>'
            size_hint_x:None
            width:'40sp'
            background_color:(0,1,2,1)
            on_release:??????????????

Answer: O comando pra ser referir a uma função pelo código kv seria algo parecido com on_press: root.funcao(), mas pra isso, primeiro você teria que construir uma interface gráfica com input, output e botões bem definidos, e não somente rodar a função com o código que Python inteiro.
Refiz um pouco da sua ideia para você ver como funcionaria (e para chamar a função usei uma sintaxe que funciona no lado Python da aplicação, que seria o método bind).
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout  import BoxLayout
from kivy.lang import Builder
from kivy.core.window import Window

Window.size = (360, 640)
Window.clearcolor = [.85, .85, .85, .85]

class RootBox(BoxLayout):
    def __init__(self, **kwargs):
        super(RootBox, self).__init__(**kwargs)

        self.upperbox = BoxLayout(id = 'upper', orientation = 'vertical')
        self.add_widget(self.upperbox)

        self.ti = TextInput(id = 'textinput', text= 'Deseja começar? pressione Sim ', font_size = 30)
        self.upperbox.add_widget(self.ti)

        self.submitbox = BoxLayout(orientation = 'horizontal', padding=30)
        self.upperbox.add_widget(self.submitbox)

        self.btns = Button(id = 'btns', text = 'submit', font_size = 30)
        self.btns.bind(on_press=self.click) #conecta o evento on_press a execução da função click
        self.btns.disabled = True #desabilita botão por default, será habilitado denovo depois pressionamento do botão 'sim'
        self.submitbox.add_widget(self.btns)

        self.si = TextInput(id = 'submitinput', font_size = 30)
        self.submitbox.add_widget(self.si)

        self.lowerbox = BoxLayout()
        self.add_widget(self.lowerbox)

        self.btn1 = Button(id = 'btn1', text = 'Sim', font_size = 30)
        self.btn1.bind(on_press=self.fraseinicial)
        self.lowerbox.add_widget(self.btn1)

    controle =0
    def click(self, num):
        self.controle += 1
        if self.controle ==1:
            self.temchuv = int(self.si.text)
            self.Lbanho = self.temchuv * 6
            print('Lbanho: ', self.Lbanho)
            self.si.text = ''
            self.ti.text ='Beleza! Quantas descargas você costuma dar em um dia?'
            self.controle += 1

        elif self.controle ==3:
            self.temvaso = int(self.si.text)
            self.LVaso = self.temvaso * 12
            print('LVaso: ', self.LVaso)
            self.si.text = ''
            self.strb = str(self.Lbanho)
            self.strv = str(self.LVaso)
            self.ti.text = "Ok, seu gasto com chuveiro é de " + self.strb + " e gasto com descarga é de " + self.strv
            self.controle += 1

        elif self.controle ==5:
            print('4º output depois do click()')
            self.controle += 1

        elif self.controle ==7:
            print('5º output depois do click()')
            self.controle += 1

        elif self.controle ==9:
            print('etc etc etc')
            self.controle += 1

        else: pass

    def fraseinicial(self, num):
        self.btns.disabled = False
        self.ti.text ='Então vamos lá! Quanto tempo, em minutos, você gasta debaixo do chuveiro em um dia?'
        self.btn1.disabled = True

class PrincipalApp(App):
    def build(self):
        Builder.load_string("""
#:kivy 1.11.0
<RootBox>:
    orientation: 'vertical'
    """)
        return RootBox()

if __name__ == '__main__':
    PrincipalApp().run()

Adicionar funções em kivy


Sendmail Java - Android Studio

Question: Bom dia, estou a desenvolver uma aplicação, onde tenho a seguinte duvida.
Pretendo enviar por email um formulário, utilizando o Intent's. O Código aparentemente está tudo OK, mas quando efetudo o clique no botao "Enviar" o programa nao efetua nada.
Por favor, gostaria que me ajudassem.
Segue abaixo o codigo Java e XML.:
JAVA
package pt.penafielverde.serpeagu.serpaguv110.agu;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class enviarmail extends AppCompatActivity {
    Button enviar = findViewById(R.id.enviar);
    final EditText assunto = findViewById(R.id.assunto);
    EditText operador = findViewById(R.id.operador);
    final EditText corpoemail = findViewById(R.id.corpoemail);
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_enviar_email);
        enviar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendMail();
                assunto.setText("");
                operador.setText("");
                corpoemail.setText("");
            }
            private void sendMail() {
                String recipientList = "email@example.com";
                String[] recipients = recipientList.split(",");
                String subject = assunto.getText().toString();
                String message = corpoemail.getText().toString();
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_EMAIL, recipients);
                intent.putExtra(Intent.EXTRA_SUBJECT, subject);
                intent.putExtra(Intent.EXTRA_TEXT, message + "Mensagem enviada por," + operador);
                intent.setType("message/rfc822");
                startActivity(Intent.createChooser(intent, "Escolha o cliente email, por onde deseja enviar a mensagem :"));
            }
            ;
        });
    }
}

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="pt.penafielverde.serpeagu.serpaguv110.agu.enviarmail">

    <TextView
        android:id="@+id/textView10"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginStart="66dp"
        android:layout_marginTop="51dp"
        android:text="Operador.:" />

    <TextView
        android:id="@+id/textView11"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="14dp"
        android:text="COMUNICAÇÃO "
        android:textColor="@android:color/holo_green_light"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/assunto_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignEnd="@+id/textView10"
        android:layout_alignParentTop="true"
        android:layout_marginTop="81dp"
        android:text="Assunto.:" />

    <EditText
        android:id="@+id/operador"
        android:layout_width="wrap_content"
        android:layout_height="36dp"
        android:layout_alignBaseline="@+id/textView10"
        android:layout_toEndOf="@+id/textView10"
        android:ems="10"
        android:inputType="textPersonName"
        android:textSize="12sp" />

    <EditText
        android:id="@+id/assunto"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView10"
        android:layout_toEndOf="@+id/textView10"
        android:ems="10"
        android:inputType="textPersonName"
        android:textSize="12sp" />

    <EditText
        android:id="@+id/corpoemail"
        android:layout_width="334dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="154dp"
        android:ems="10"
        android:inputType="textMultiLine" />

    <TextView
        android:id="@+id/textView13"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/corpoemail"
        android:layout_alignStart="@+id/corpoemail"
        android:layout_marginBottom="-154dp"
        android:text="Descrição da Anómalia" />

    <Button
        android:id="@+id/enviar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="17dp"
        android:text="enviar" />
</RelativeLayout>

Comment: Inspecionando os logs, não há nenhuma mensagem de erro também?
Comment: @StatelessDev aparentemente nao, pelo menos nao encontro qualquer erro no Log
Answer: Adicione um (mailto: Uri) logo após a criação da Intent
intent.setData(Uri.parse("mailto"));

Sendmail Java - Android Studio


Probability that the blue disk is in the center after $n$ moves

Question: Jimmy has two red disks and one blue disk, and he places them in a row such that the blue disk is in the center. Every move, Jimmy switches one of the outer disks with the center disk. Find the probability that the blue disk is in the center after $n$ moves.

I let $E_n$ be the probability that the blue disk is in the center after $n$ moves. Then, I had
\begin{align*}
E_1 &= 0 \\
E_2 &= \frac{1}{2} 1 + \frac{1}{2} E_1 = \frac{1}{2}.
\end{align*}
However, I wasn't sure how to proceed on the case for $E_3.$
Comment: The aim of this exercise is that you learn to construct a recursion relation between the probabilities after $n$ turns in terms of the probabilities after $n-1$ terms. You can tem use the initial state (Blue in the middle) to derive the required solution.
Comment: $E$ usually means expectation. Better to use $P$ for probabilities.
Answer: After $n-1$ turns, let $L(n-1)$, $M(n-1)$, $R(n-1)$ be the probabilities that the blue disk is in the Left, Middle or Right position. We now perform the next turn and compute the new probabilities. We obtain the following recursion relations:
$$L(n) = (1/2)L(n-1) + (1/2)M(n-1)$$
$$M(n) = (1/2)L(n-1) + (1/2)R(n-1)$$
$$R(n) = (1/2)R(n-1) + (1/2)M(n-1)$$
Summing the three equations we see that the sum of probabilities is conserved, as expected. Since $L+ M + R = 1$ holds, we can use this to rewrite the equation for $M$ as follows:
$$M(n) = 1/2 - (1/2)M(n-1)$$
We can easily verify that $M = 1/3$ is a possible solution. Indeed, for large $n$ the $M(n)$ converge to this value. The trend towards this constant value is oscillatory. By plugging in the initial values for M we get numbers that confirm the oscillatory behaviour. The exact solution is found to be:
$$M(n) = 1/3 + (2/3) (-1/2)^n$$
Comment: The problem is symmetric, so you don't really need separate values $L_n$ and $R_n$.
Comment: That is true. I wanted to give the general equations first, and only then focus on $M(n)$.


Question on mixed voice (with audio sample)

Question: So i had been working o my mixed voice for a while but to develop the proper balance is very hard sometimes especially when i was tired or not having enough sleep. Another issue is that the tonal quality. From my understanding, mixed voice tonal quality should not sound too distinct from the chest voice right? Sometimes, I noticed that sometimes my mixed voice sounds very different from my chest, but it depends on the song. I mix around G4, but there are some songs that I had to mix earlier around F#4 or F4 and that was when the huge change in tonal quality happened. So when I mixed at F4 or F#4, the sound will be very different from the lower notes sometime it sounded weak, perhaps mixing in the lower notes require more support right? Because sometimes, depends on the consonant/vowel, my voice will strain when I sing up to F#4. Please correct me I was mistaken on my understanding.
Anyways this song is a good example the issues I mentioned earlier because I had to sing lots of F#4 and G#4 which was around where my break started. So, what do you think on the notes I sung around F#4s and G#4s? Did they sounded weak and if yes should I mix higher?
Link : http://picosong.com/WFLc/
Answer: Have you used some melodyne or autotune on your recording? There are some parts where the pitch is kind of weird.
My first advice is: focus on staying in tune. There are some parts that you understand, so don't worry if you have to "mix" in certain note or the other one. Just keep practising that "mix" (although I wouldn't call it Mixed Voice). Also, keep that support, sometimes it seems that you relax it and you start to sound less closed.
If you want to sound with more body and not that weak in certain notes try simply opening your jaw so that your color is not that light. For me, I start "mixing" as you call it, way before that. And I go to reinforced falsetto depending on the passage, from F#4 and up.
Depends on the consonant your voice wants to strain, because you're closing in certain part of your mouth/throat. But keep doing vowel exercises and then put a consonant before them to keep working for your vowels instead of for your consonants.


How can I prove that if $A$ is a singular square matrix, then $\det A = 0$ without using Binet's Theorem?

Question: Well, I need to prove that if $A$ is a $n \times n$ matrix and it is singular, then $\det A = 0$, in order to show Binet's Theorem $\det(AB) = \det(A)\cdot\det(B)$ in the case when both $A$ and $B$ are singular square matrices.
I'll thank any help with this issue!
Comment: How do you define singular, and how do you define determinant?
Comment: How do you define singular matrix then?
Comment: A non - invertible matrix?
Answer: By definition, $\det$ is an alternating multilinear form in the matrix columns. By assumption, there exists non-zero $v$ with $Av=0$, i.e., the column vectors are linearly dependent. Use this and alternating multilinearity to show that $\det A$ equals $\det B$ for a matrix $B$ with one column equal to $0$, and there we see from linearity in that column that $\det B=0$.
Comment: @Arthur Agreed. In the absence of a specific definition in the OP, I took the "the unique alternating $n$-form that maps $I\mapsto 1$" as definition of $\det$. Other definitions may lead to different answers with different methods. One will finally suit the asker best, possibly others may be helpful to future visitors. (Essentially, *Wuestenfix*'s Gauß elimination is the down-to-earth formulation of the alternating-form argument - and I assume his way is preferable)
Comment: "By definition" Well, that depends. There are many different definitions out there. "By assumption" Again, depending on your definition is, that's not directly the assumption. If you don't use the "right" definitions, then showing these things isn't difficult, but it must be done if one is to follow this answer. And if you do it that way, then much of the work lies in showing these things.
Answer: There are two basic operations you can do with matrices and their determinants: First, if any pair of columns (or rows) of a matrix is interchanged, the determinant is multiplied with −1. Second, if a scalar multiple of one column is added to another column, the value of the determinant is not altered. In this way, you can do Gauss elimination on the matrix and keep track of the determinant of the matrix. If the matrix is singular, you end up with a zero column (or row) giving you determinant 0.
Comment: Would this be the same if I try to get the answers to $A\vec{x} = \vec{0}$? If $A$ was invertible, I'd only get $\vec{x} = \vec{0}$, but it it's not, then I'd have infinitely many answer for $\vec{x}$ and that would mean that I have free variables and I'd have less equations than variables, right?
Answer: Consider $B=A \cdot C^T$ where $C$ is the cofactor matrix of $A$.
Then $b_{i,j}=\sum_k a_{i,k} \, c_{j,k}$, where $c_{j,k}$ is the $j,k$ minor of $A$.
If $i = j$ , that corresponds to the computation of the determinant of $A$ along the row $i$, hence $b_{i,i}=\det A$
If $i\ne j$ , that corresponds to the computation of the determinant of a matrix that's equal to $A$ except that the row $j$ has been overwriten by the contents of row $i$. But the determinant of a matrix with duplicated rows is zero, hence $b_{i,j}=0$.
This can be written $$A \cdot C^T = \det(A) \, I \tag{1}$$
If $\det A\ne 0$ then we can write $$ A \, \frac{C^T}{\det A}=I \iff A^{-1}=\frac{C^T}{\det A}=\frac{adj(A)}{\det A} \tag{2}$$
(This esentially amounts to rediscovering/proving Cramer's rule)
That is, $\det A\ne 0 \implies A^{-1} $ exists (hence, $A$ is non singular).
Consequently, if $A$ is singular (i.e. the inverse does not exist) then we must have $\det A=0$.
Comment: I think I'm starting to understand... since the inverse is unique, if it exists, it must be $\frac{C^T}{|A|}$, but if it doesn't, the only way for it to be undefined is when $|A| = 0$, since $C^T$ is always defined, right?
Comment: More or less. I've proved that _if_ $|A|\ne 0 $ then the inverse exists, and $A$ is not singular. By [contraposition](https://en.wikipedia.org/wiki/Contraposition) (or Reductio ad absurdum, if you prefer) it follows: if $A$ is singular then $|A|= 0 $.
Answer: The inverse exists when the determinant is nonzero.  There is a formula for it:  $$A^{-1}=\frac1{\operatorname{det}A}\operatorname{adj}A$$, where $\operatorname{adj}A$ is the transpose of the matrix of cofactors,  the so-called adjugate of $A$.
Comment: Since it is unique, it must be the way you wrote it, right? Then if $A$ is singular, then that $A^-1$ is undefined and the only way this is the case is if $det A = 0$ from that formula, right?
Comment: Right.   This actually gives the _contrapositive_  of the statement you want.
Answer: I would use two proof

Permutation change the sign of the determinant
Multiplying a row by a constant multiply the determinant by this constant

Then, you can just say if you have a singular matrix S, 2 row $r_i$ and $r_j$ are linearly dependent. You can multiply $r_i$ by a constant C to get a new matrix S' where $r_i$ = $r_j$.
We know
\begin{equation}
det(S') = C det(S)
\end{equation}
Then, you can swap $r_i$ and $r_j$ but you have the same matrix has before so
\begin{equation}
det(S') = -det(S') = -C det(S) = C det(S)
\end{equation}
The equation det(S) = -det(S) means det(S) is 0.


Groupyby count with condition

Question: I am struggling with the last line of the code attached below. In the final line I am seeking to get the count of all 'PM_Temp' that are equal to or less than 10, but I do not know how to write. Any help would be much appreciated
df1 = df.groupby(['City', 'year'])\
  .agg(Avg_Duration = ('duration', 'mean'),
        Max_Duration = ('duration', 'max'),
        Min_Duration = ('duration', 'min'),
        Ave_AM_Temp = ('AM_Temp', 'mean'),
        Max_AM_Temp = ('AM_Temp', 'max'),
        Min_AM_Temp = ('AM_Temp', 'min'),
        Ave_PM_Temp = ('PM_Temp', 'mean'),
        Max_PM_Temp = ('PM_Temp', 'max'),
        Min_PM_Temp = ('PM_Temp', 'min'),
        PM_Temp_10_or_less = (('PM_Temp', (<=10).count())

Answer: Use a lambda function here:
df1 = df.groupby(['City', 'year'])\
  .agg(Avg_Duration = ('duration', 'mean'),
        Max_Duration = ('duration', 'max'),
        Min_Duration = ('duration', 'min'),
        Ave_AM_Temp = ('AM_Temp', 'mean'),
        Max_AM_Temp = ('AM_Temp', 'max'),
        Min_AM_Temp = ('AM_Temp', 'min'),
        Ave_PM_Temp = ('PM_Temp', 'mean'),
        Max_PM_Temp = ('PM_Temp', 'max'),
        Min_PM_Temp = ('PM_Temp', 'min'),
        PM_Temp_10_or_less = ('PM_Temp', lambda x: x.le(10).sum())

Comment: Thanks that was wonderful. Is it possible to add another condition, like this:
PM_Temp_10_or_less = ('PM_Temp', lambda x: x.le(10).sum() and 'Day' == 'Mon)
Comment: You can't, since named agg only sees/applies on one column at a time. You need another groupby object.
Comment: Perhaps then, an idea could be to reset the index, and then add new column applying conditions?

Groupyby count with condition


JAVA 2D Find the K closest points to the origin in 2D plane

Question: Find the K closest points to the origin in 2D plane, given an array containing N points. You can assume K is much smaller than N and N is very large.
This is what i have so far:
<code>   public class OriginQuestion {

     public static class Point {

     public double x;

    public double y;

 }
  public static Point[] closestk( Point  myList[], int k ) {}
    for(int i=0;i<myList.length;i++){

    }

  }
</code>
Help appreciated
Comment: I think that at the very least, you need to come up with some sort of plan for how you might accomplish this.  Maybe start by thinking about how you'd do this by hand if you were given a list of points on paper?
Comment: So, basically, you have nothing.
Answer: This problem is a variant of the nearest neighbor search problem. The simplest solution is to compute the distance from the origin to all N points and then find the K that are nearest using for example the quickselect algorithm, giving a time and space complexity of O(n).
Answer: This problem can be solved using heap. We can start with creating a max-heap of size k and start adding points to it. After we are done adding K points to our heap.
Now if the (K+1)th point is at distance lower than the max-heap root , we remove root and add this (K+1)th point to our max-heap.
After we are done processing all the N points, our heap will give us the solution.
The worst case complexity should be N(log K) as we will do it for N numbers and log K operations are required to move a node in the heap.


How to convert a simple GCC command to CMake?

Question: My source code
#include <tree_sitter/api.h>
int main() {
    TSParser *parser = ts_parser_new();
}

I compile it with the following gcc command
gcc \
-I ~/source_repos/tree-sitter/lib/include \
test-json-parser.c \
~/source_repos/tree-sitter-json/src/parser.c \
~/source_repos/tree-sitter/libtree-sitter.a \
-o test-json-parser

This works fine. But if I do the following in CMake
cmake_minimum_required(VERSION 3.17)
project(tmp_tree_sitter C)

set(CMAKE_C_STANDARD 11)

include_directories(/home/rip/source_repos/tree-sitter/lib/include)

add_executable(tmp_tree_sitter
        main.c
        /home/rip/source_repos/tree-sitter/libtree-sitter.a
        /home/rip/source_repos/tree-sitter-json/src/parser.c
)

The following error message raises
Scanning dependencies of target tmp_tree_sitter
[ 33%] Building C object CMakeFiles/tmp_tree_sitter.dir/main.c.o
[ 66%] Linking C executable tmp_tree_sitter
/usr/bin/ld: CMakeFiles/tmp_tree_sitter.dir/main.c.o: in function `main':
/home/rip/CLionProjects/tmp_tree-sitter/main.c:12: undefined reference to `ts_parser_new'

The only difference is, I have different directories, so in one the source file is named test-json-parser.c and in the other main.c. So how can I do the same in CMake, as I did with gcc?
Comment: I don't know if I should post the error message, because than I would have to post the source code as well, and this is unrelated to my question, I think, because the source code is the same, that works well with gcc.
Comment: "doesn't work" isn't giving us a lot to work with. Error message would help.
Comment: Ok, I added the error message.
Comment: Expansion of `~` is done by the shell. Maybe CMake does not do this. Did you try to use full path names for your C files?
Comment: Yeah, I tried this as well. I will update the paths in the question.
Answer: you need to tell Cmake that you want to link the libraries.
I use target_link_libraries for that. https://cmake.org/cmake/help/latest/command/target_link_libraries.html


How do I change the javascript loading order

Question: I am using mixitup.js for my custom module. But it gives error when firing because it needs to load the jQuery before loading the mixitup.js. But my jQuery files are in my site folder which are loading in the end of the page. Is there way to load my mixitup.js in the end of the page. mixitup.js should be in my custom module too.
Comment: See sonfd's reply below. That's the way to do it. If you set jquery as a dependeny, jQuery will load above it.
Comment: What do you mean with "...in site folder..."? jQuery is part of Drupal's core, just add a dependency to `core/jquery` it in your module's `library.yml` file, you don't need any manual load ordering.
Comment: How are you adding the scripts? This will determine the solution.
Comment: @Jaypan in the library.yml
Comment: @Hudri Yes. I have already added jQuery to libraries.yml. But that too loads in the end of the page. Not on the top. I need to load all the javascripts at the top of the page.
Comment: Do you truly want all js in the header? or just the js used by your custom module?
Comment: Thanks @Jaypan, updated my answer to include that info.
Comment: I'm not clear - you've been given the information you need - is your problem solved?
Answer: To add a js library to the header, define your library in my_module.libraries.yml with the header: true property.
my_library:
  header: true
  etc ...

Any dependencies defined for your library will always be loaded before your library whether loading your js in the header or footer.
See Asset loading order section here.
Answer: As mentionned above, one way to control the order is to declare in your library the dependencies of other libraries containing the js you want to be loaded before
agenda:
  version: 1.x
  css:
    component:
      css/agenda.css: {}
  js:
    js/agenda.js: {}
  dependencies:
    - fullcalendar_view/fullcalendar


How to do a Cronjob via SSH on Linux

Question: I have a linux server where I want to install a Cron.
I was given a URL, and by visiting this URL (GET request), it will automatically rebuild a new sitemap for my website.
Basically, I want a cron to go to this URL once a day, thus my sitemap will be regenerated once a day
I'm not sure what info I need to give you regarding cron on my server...but when I go to /etc/ I can see...
cron.d , cron.daily , cron.deny , cron.hourly , cron.monthy , crontab
one other thing, when i visit the GET request url myself, it takes a while before the page loads. It takes about 1-2 minutes and then a "SITEMAP COMPLETE" page appears. So the cron will have to stay at it for the entire duration until that message appears, else the sitemap will only partially regenerate.
Edit *** I think I found the answer, can someone please confirm of this is correct ???
In crontab -e, I enter:
0 0 1 * *  /usr/bin/wget -q -O - "http://www.domain.com/GET-REQUEST"
Answer: You can use 'wget' or 'curl', so yes your example is correct. You can ether add it with crontab -e or add the line to /etc/crontab (But add which user to run as)
Comment: If i use the wget, will it save a file on my server somewhere everytime the cron is run?
Comment: @Virendar Yes, if you use CURL it won't (Unless you specify the -O flag, but don't do that). Just set the command as `curl http://yourdomain/script.php` and that will download the file but not save it
Comment: @Virendar you could use *wget* with *--spider* as argument and that will make don't save the output
Comment: hmm, so wget -q -O should be changed to either wget --spider or curl ?
Comment: @Verendar Ether use `wget --spider http://yourdomain/script.php` or `curl http://yourdomain/script.php`, not both =) I prefer CURL, purely because the syntax is easier, there's probably a performance comparison somewhere but it's more down to personal choice, which one you find easier to use.
Comment: @Virendar Yes, that would work fine. I just used script.php as an example, I probably confused the issue more than I should have done. If you were having to use /usr/bin/wget rather than just `wget` you'll probably need to use /usr/bin/curl instead of just `curl` so it gets the right path

How to do a Cronjob via SSH on Linux


How to know if an an array contains only a particular value for all the elements

Question: How can I more elegantly tell if a JavaCard byte array contains only a particular element as shown in the example below:
{(byte) 0xAA, (byte) 0xAA, (byte) 0xAA, (byte) 0xAA}

I am trying not to write loops and if-else to search through the entire array and match if it contains just a particular element (0xAA for this example above). Is there some sort of method to do it ?
Comment: @chx101 I find your downvoting quite unfair and it seems to be motivated by the fact that your answer was not accepted. Java Card is a very complicated platform and no, the easiest solution (loop) is not often the best one. Java Card proprietary libraries (and specific implementations of Java Card libraries) often provide hardware-specific low-level instructions you cannot use from your code directly. Java Card is not Java.
Comment: To put it straight, chx101, I am not the one to -1 on your post and in fact I decided to bold and italic my original post (in case i weren't clear enough originally) when I noticed your answers are not matching my question to give you time to re-think or withdraw. My open question to the community for a more efficient way to check elements in an array in a constrained environment is precisely what vojta voiced as I am only working on a 2KB RAM and 16 bit processor smart card and have very little RAM space left and I need a solution to reduce loops, speed things up and efficiently handle RAM.
Comment: You mean like using a lookup table?
Comment: Yes. I am trying to implement a lookup array. I want to know if the entire array is filled with a specific particular element or not.
Comment: Ok. Check my answer.
Comment: -1 For the fact that you know you're working on a confined platform and  should know that the most **elegant** way, library or not, will still be done using a loop.
Comment: @thotheolh Is your problem solved? Should I add some information? Please, update us with some info, or accept the answer.
Answer: Java Card is a very limited platform with almost no fancy libraries. A loop and if-else/break is generally the best thing you can do and it there is nothing wrong about doing so.

If your array had a fixed (or limited) size, you might create a RAM buffer and use Util class and its static methods to fill it with your byte value and then compare the whole array in one piece:
private final byte[] temp = JCSystem.makeTransientByteArray(SIZE_LIMIT, JCSystem.CLEAR_ON_DESELECT);
private final boolean containsSameValues(final byte[] arr, final byte value)
{
    if (arr.length > SIZE_LIMIT) {
         //throw some error code...
    }
    Util.fillArrayNonAtomic(temp, (short) 0, (short) arr.length, value);
    return Util.arrayCompare(arr, (short) 0, temp, (short) 0, (short) arr.length) == 0;
}

However, this solution might be even slower than a common loop. Everything depends on your hardware and your Java Card implementation.
Comment: If there is only a limited number of searched for patterns (as in case of e.g. checking the correct padding), it _might_ make sense to prepare all the arrays in advance during the applet installation (in the persistent memory as it is really cheap) an then just call the `Util.arrayCompare()`.
Comment: And love the idea that if the tested array's size has some upper bound, you can use that long reference array and check only the actual length of the tested array (would emphasize it a bit more in the answer) -- using that myself for zero padding check (even in C).


How to interpret the hurdle or zero-inflated model

Question: I have 137 data points that are inspection and I'm trying to find the hurdle negative binomial distribution that fits. Here is how the data looks

I have the following code
modelhurdNB<-hurdle(Count ~ Start, data=inspData,
                   dist = "negbin", zero.dist = "binomial", link = "logit",
                   model = TRUE, y = TRUE, x = FALSE)
AICHurdNB=AIC(modelhurdNB)

summary of the model is
Call:
hurdle(formula = Count ~ Start, data = inspData, dist = "negbin",
    zero.dist = "binomial", link = "logit", model = TRUE, y = TRUE,
    x = FALSE)

Pearson residuals:
      Min        1Q    Median        3Q       Max
-0.627069 -0.524570 -0.488098  0.007419  5.510233

Count model coefficients (truncated negbin with log link):
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  1.530519   0.671367   2.280   0.0226 *
Start       -0.002971   0.002211  -1.344   0.1791
Log(theta)  -0.645959   0.899062  -0.718   0.4725
Zero hurdle model coefficients (binomial with logit link):
             Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.515575   0.683851   0.754    0.451
Start       -0.003274   0.002714  -1.206    0.228
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Theta: count = 0.5242
Number of iterations in BFGS optimization: 13
Log-likelihood: -125.3 on 5 Df

This is the model that has the lowest AIC. However, The start time of the inspection has a p value higher than 0.05. The binomial part is also statistically insignificant. Hence,
1) How good of a model is this?
2) How do I obtain the parameter of the binomial? (Is it the statistically insignificant coefficient?)
Answer: I'll answer your questions in reverse.
Your model posits that the log odds of "jumping the hurdle" look like
$$ \operatorname{logit}(p) = \hat{\beta}_0 + \hat{\beta}_1\operatorname{Start}$$
With $\hat{\beta}_0 = 0.51$ and $\hat{\beta}_1 \approx 0$.  To obtain the binomial probability, invert the logit using
$$ p = \dfrac{1}{1+\exp(-(\hat{\beta}_0 + \hat{\beta}_1\operatorname{Start}))}$$
It seems like the effect of Start on the binomial probability is negligible considering the scale of the covariate.  So, ignoring that, it seems like the binomial probability is about 62%.  A confidence interval would be more appropriate, though I'll leave that to you.  Since we fail to reject the null for the test associated with this coefficient, we can conclude that the data are consistent with a binomial probability of 50%.
As for if this is a good model, the answer is "it depends".  We need much more context than what you've provided about i) What this model's intended use is, and ii) What the data concern.


Propositional logic "equivalent to" using union, intersection and negation

Question: In the Maths book, "implies to" is described as
$A\rightarrow$B equals to $\lnot\ A \lor  B $
How can I represent $A \Leftrightarrow B$ in the same way?
Comment: What do you mean by "union, intersection, and negation"?  Do you mean the propositional connectives conjunction, disjunction, and negation?  Or do you mean the sets union, intersection, and complement?
Answer: If you think about the propositions as sets, then $A\iff B$ is the same as $A=B$.
Answer: $A \iff B$ is equivalent to $( \neg A \lor B ) \land ( \neg B \lor A )$
which in turn is equivalent to $( \neg A \land \neg B ) \lor ( A \land B )$


Upgrading to freebsd10 breaks apache24

Question: Until now I was using freebsd9 with apache22 with ssl, every thing went well. But recently I moved to freebsd10 (fresh install) and then installed apache24 with same config as on old machine.
Everything is ok except that apache24 when used with ssl on port 443 produces error AH022240: Server should be SSL-aware but has no certificate configured [Hint: SSLCertificatefile] ((null): 0) And Apache24 refuses to run.
openssl verify mycertificate produces error 18 which (I think) is normal as it is a self signed certificate.
I have done whatever I could searching google/yahoo, and trying treatments suggested there but no results.
Alas my bad luck I have just formatted my old hard disk without any backup in order to install freebsd10.
Comment: Check if the mod_ssl module is availiable using `phpinfo()`  Also  `SSLCertificateFile` is the directive which requires a path to the certificate.  A self-signed certificate should return an OK message but will indicate that it's not signed. For more details try http://www.freebsd.org/doc/handbook/network-apache.html
Comment: "Alas my bad luck I have just formatted my old hard disk without any backup in order to install freebsd10." -> I guess you are not talking about production server, are you?
Comment: @EricDANNIELOU You are right.
Comment: @val0x00ff, I can not check what you suggest as Apache24 is not running. -(
Comment: @Nishan You need to first be able to start apache24 as it is, without ssl or anything. write a    and see what modules there are. If you cannot start apache then i the problem is your apache not ssl.
Comment: I SOLVED THE PROBLEM -)

THANKS TO MY STARS & THE COMMUNITY
Answer: Your problem is not FreeBSD, it's Apache.
Apache 2.4 has substantially different configuration file directives than Apache 2.2.
You  cannot just throw the 2.2 configuration file in place and start your 2.4 server using it - you will need to put important bits (like the SSL Certificate and Key files - per the error message you're getting) in place, and update your configuration (or write a new configuration file implementing the same functionality as your previous one) so Apache 2.4 understands it..
Refer to the Apache manual (which you should have read BEFORE upgrading) for specific instructions.
Comment: I respect and value your advice.

But, BUT I am running *Apache24 with same config on FreeBSD91* NO PROBLEMS WITH SSL OR NO SSL AT ALL, my surprise.

*APACHE IS INNOCENT GUY IN THIS CASE* _~)_

I am not blaming but sure FreeBSD10 has changed its way of working potentially, which I have to understand afresh.

Upgrading to freebsd10 breaks apache24