Why can't some websites be shown without the "www" in the URL?

Question: I used to type the website URL without the "www" and it works fine with almost all sites that I have tried, so far.
But I realize that my university's website never show up if you don't type the "www" before.
Typing this
 http://u-psud.fr/

shows a dead page, but adding the "www" works well:
 http://www.u-psud.fr/

Why is it not working for one's own site, or why is it working for the other website :)
Comment: seriouslly??? would I bother asking if I know the answer, r u ok people out here???
Comment: Seems more of an end-user question than a serverfault "sysadmin" question.  Belongs elsewhere?
Comment: Why the close votes? Maybe this person really doesn't know.
Comment: For someone new in server admin who doesn't know how DNS works I think this is a completely valid question.  Its asking how DNS works.
Comment: Not really programming-related, but could be of use to web developers
Comment: @John it's not really programming related. If anything it should be asked at serverfault, but I suspect it would get closed there too.
Answer: The "www" part is not really a standard. It's a tradition. It's up to the webmaster/sysadmin to make it work. Just because most sites have enabled both ways (with www and without www), doesn't mean that they have to. In fact, have you noticed that some websites have something like www1, www2, etc.? That's because the sysadmin can decide what he/she wants to put there (or if he/she wants to put anything there at all). As I said - it's just a tradition.
Answer: It's because the "www." is part of the DNS name that resolves to their web server's addresses. The ones that don't have "www." don't have it as part of their DNS name.
Comment: It's not sufficient to set up two domain names in DNS. The webserver also has to be bound to both names
Comment: @activa, sorta kinda yes but not always. If you have one IP address for one website, I think most web servers will traditionally accept any old host header and point them at that site. If you have a complex set up with several sites/URLs using one IP address then yes you'd need to set up host headers. But this is just telling the web server what to accept, the issue with "www or not www" is a DNS issue.
Comment: It means there are two DNS names, and that they probably point to the same set of IP addresses.
Comment: is that means "google.com" and "www.google.com" are not the same??
Answer: The part of the URL before the domain name (the www. in this example) is normally interpreted as the logical name of the computer on that domain's network that is required (so you might have a server which calls itself 'www', one which calls itself 'mail', etc.).
If you don't specify a specific domain resource then the default is used, and normally that's set up to be www, but some network admins won't have set this up for whatever reason and so you must enter the www explicitly to get to that resource.
Answer: Let's look at the specific examples:
$ nslookup u-psud.fr
Server:     192.168.0.1
Address:    192.168.0.1#53

Non-authoritative answer:
Name:   u-psud.fr
Address: 188.8.131.52

So, u-psud.fr -> 126.96.36.199
$ nslookup www.u-psud.fr
Server:     192.168.0.1
Address:    192.168.0.1#53

Non-authoritative answer:
www.u-psud.fr   canonical name = cms10-default.u-psud.fr.
Name:   cms10-default.u-psud.fr
Address: 18.104.22.168

And, www.u-psud.fr -> 22.214.171.124
So, in short, you are connecting to two different web servers.
The history of this is more convoluted. A long time ago, as the Internet grew in popularity, many of the services you know were only growing in popularity. Most of the users were local, so systems often appeared as what they were named locally. (I saw a list circa 1990 that showed the most popular hostnames were things like: calvin, hobbes, mac1, mac2, etc.)
When the Internet usage became more globalized, smart administrators started naming their SMTP hosts "mail", their POP servers "pop" and their FTP servers "ftp". (You would be amazed how hard it was to convince people this made sense...)
For a long time, DNS-smart-but-lazy administrators tried to serve everything off a server for the top level entry (domain.com). These days, few administrators are this foolhardy, you need to spread out the load across several systems. From a naming perspective, using the name-of-service-in-the-domainname makes a lot of sense for end users, it is hard to get wrong.
Answer: This is the responsibility of whoever sets up the web server. In order for both domain names to work, there should be DNS entries for both names (usually one is an alias for the other), AND the website should be linked to both names.
Answer: A lot of sites set their name and suffix in the DNS, e.g. google.com and may be set to allow all non-specified sub-sites to go there.
My website (it's rubbish) is setup as cksiteoftreats.co.uk, but you can put anything in front of it and it will work:
useless.cksiteoftreats.co.uk

whatishethingking.cksiteoftreats.co.uk

serverfault.com.cksiteoftreats.co.uk

Answer: There is even a movement against the usage of www which technically should be a subdomain.
They say that, by default, all popular Web browsers assume the HTTP protocol. In doing so, the software prepends the 'http://' onto the requested URL and automatically connect to the HTTP server on port 80. Why then do many servers require their websites to communicate through the www subdomain? Mail servers do not require you to send emails to firstname.lastname@example.com. Likewise, web servers should allow access to their pages though the main domain unless a particular subdomain is required.
Succinctly, use of the www subdomain is redundant and time consuming to communicate. The internet, media, and society are all better off without it.
It used to be located here.
Answer: Oh! my dear why all these trumped up answers. It is a laymans question whomsoever he/she  is. The answer also should be a laymans answer to the query.Suppose you have your own web server configured in your system. It becomes a web server. It needs a domain name for others to access your web server.Suppose your DNS(Domain Name Server) provider is microsoft who have registered their  domain name for its DNS as microsoft.com . Now that you have to register with microsoft.com DNS with the name of your choice for your web server.You give the name www.myweb for registration . Now your domain bame has become www.myweb.microsft.com.
If you had give the name myweb only , your domain name shall become myweb.microsoft.com.
What if you wish to give the name www only. If there are no other www registered by the microsoft DNS , they may permit the name for your use. Then your web server will have the URL www.microsoft.com.
So all in all , it is all in the name.Because of the embeded beauty of the name www, many use it .
Your university has included www for registration of its domain name with their Internet Service provider. That is why you are unable to get the site otherwise.
I hope I am a layman.
Comment: Welcome to Server Fault. Remember that this is a site for IT professionals, as such it's expected that most people here will have some basic understanding of various IT concepts.


Laravel 5.4 with Pusher Illuminate\Broadcasting\BroadcastException' with message '404 NOT FOUND

Question: I'm attempting to get Pusher working with Laravel 5.4, but I keep running into the push failing in the queue.
I've tested the Channel from the Pusher debug console and it works without issue.
I can also see the browser listening on the chosen channel.
I've followed the setup on the Pusher getting started page.
I've used artisan to clear config and cache, done a httpd restart as well to be sure.
I don't know if I am missing a step, or something else. I've seen this question asked a few times on here, but each solution which I've encorporated below, doesn't resolve the issue.
Hoping someone can come up with a suggestion.
Thanks in advance.
Setup
.env (Setup, and checked is working correctly):
APP_URL=*****
DB_HOST=*****
BROADCAST_DRIVER=pusher
PUSHER_APP_ID=******
PUSHER_APP_KEY=*******************
PUSHER_APP_SECRET=***********************

broadcasting.php (Added CURL options, no success):
    'pusher' => [
        'driver' => 'pusher',
        'key' => config('services.pusher.app_key'),
        'secret' => config('services.pusher.app_secret'),
        'app_id' => config('services.pusher.app_id'),
        'options' => [
            'cluster' => 'ap4',
            'useTLS' => true,
            'curl_options' => [
                CURLOPT_SSL_VERIFYHOST => 0,
                CURLOPT_SSL_VERIFYPEER => 0,
            ]
        ],
    ],

TicketComment.php (Event)
<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

class TicketComment implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $tries = 5;

    public $username;

    public $message;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($username)
    {
        $this->username = $username;
        $this->message  = "{$username} liked your status";
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return ['status-liked'];
    }

    public function broadcastAs() {

        return 'event-liked';

    }
}

global.js (front-end js):
    var _notificationListener = function(){
        // Enable pusher logging - don't include this in production
        Pusher.logToConsole = true;

        var pusher = new Pusher('*******************', {
            cluster: 'ap4',
            encrypted: true
        });

        var channel = pusher.subscribe('my-channel');
        channel.bind('event-liked', function(data) {
            alert(JSON.stringify(data));
        });
}

Queue (Exception):
exception 'Illuminate\Broadcasting\BroadcastException' with message '404 NOT FOUND
' in /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php:106
Stack trace:
#0 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Broadcasting/BroadcastEvent.php(49): Illuminate\Broadcasting\Broadcasters\PusherBroadcaster->broadcast(Array, 'event-liked', Array)
#1 [internal function]: Illuminate\Broadcasting\BroadcastEvent->handle(Object(Illuminate\Broadcasting\Broadcasters\PusherBroadcaster))
#2 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(30): call_user_func_array(Array, Array)
#3 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#4 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#5 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/Container.php(539): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#6 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(94): Illuminate\Container\Container->call(Array)
#7 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(114): Illuminate\Bus\Dispatcher->Illuminate\Bus\{closure}(Object(Illuminate\Broadcasting\BroadcastEvent))
#8 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(102): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Broadcasting\BroadcastEvent))
#9 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Bus/Dispatcher.php(98): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#10 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Queue/CallQueuedHandler.php(43): Illuminate\Bus\Dispatcher->dispatchNow(Object(Illuminate\Broadcasting\BroadcastEvent), NULL)
#11 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Queue/Jobs/Job.php(69): Illuminate\Queue\CallQueuedHandler->call(Object(Illuminate\Queue\Jobs\DatabaseJob), Array)
#12 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(317): Illuminate\Queue\Jobs\Job->fire()
#13 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(267): Illuminate\Queue\Worker->process('database', Object(Illuminate\Queue\Jobs\DatabaseJob), Object(Illuminate\Queue\WorkerOptions))
#14 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Queue/Worker.php(224): Illuminate\Queue\Worker->runJob(Object(Illuminate\Queue\Jobs\DatabaseJob), 'database', Object(Illuminate\Queue\WorkerOptions))
#15 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(102): Illuminate\Queue\Worker->runNextJob('database', 'default', Object(Illuminate\Queue\WorkerOptions))
#16 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Queue/Console/WorkCommand.php(86): Illuminate\Queue\Console\WorkCommand->runWorker('database', 'default')
#17 [internal function]: Illuminate\Queue\Console\WorkCommand->fire()
#18 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(30): call_user_func_array(Array, Array)
#19 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(87): Illuminate\Container\BoundMethod::Illuminate\Container\{closure}()
#20 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/BoundMethod.php(31): Illuminate\Container\BoundMethod::callBoundMethod(Object(Illuminate\Foundation\Application), Array, Object(Closure))
#21 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Container/Container.php(539): Illuminate\Container\BoundMethod::call(Object(Illuminate\Foundation\Application), Array, Array, NULL)
#22 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Console/Command.php(182): Illuminate\Container\Container->call(Array)
#23 /var/www/html/php56/ml/vendor/symfony/console/Command/Command.php(255): Illuminate\Console\Command->execute(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#24 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Console/Command.php(168): Symfony\Component\Console\Command\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Illuminate\Console\OutputStyle))
#25 /var/www/html/php56/ml/vendor/symfony/console/Application.php(963): Illuminate\Console\Command->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#26 /var/www/html/php56/ml/vendor/symfony/console/Application.php(254): Symfony\Component\Console\Application->doRunCommand(Object(Illuminate\Queue\Console\WorkCommand), Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#27 /var/www/html/php56/ml/vendor/symfony/console/Application.php(147): Symfony\Component\Console\Application->doRun(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#28 /var/www/html/php56/ml/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php(122): Symfony\Component\Console\Application->run(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#29 /var/www/html/php56/ml/artisan(36): Illuminate\Foundation\Console\Kernel->handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
#30 {main}

Comment: Try removing the APP_URL from your .env file.
Comment: @doydoy attempted that before, did nothing. I can do a push from the Pusher debug console, and that works.
Answer: You may try php artisan config:cache command. Did the trick for me to working.
var channel = pusher.subscribe('my-channel');

Here you are subscribing to my channel but from the event.
public function broadcastOn()
{
    return ['status-liked'];// ->channel 'status-liked' should be replace by 'my-channel'
}

Comment: I had tried that, and composer dump autoload, neither made a difference. I've since gone to PHP7.2 and Laravel 7 and gotten this working


How does LIBC_PROBE macro actually work in Glibc?

Question: I was trying to understand how mallopt() works in glibc, but unable to understand the use of LIBC_PROBE macro used in the function mallopt(). The definition of LIBC_PROBE is creating another macro LIBC_PROBE_1 and again it is creating another one STAP_PROBE##n. In case of mallopt() it is STAP_PROBE3(a1, a2, a3). After this there no clue how STAP_PROBE3 going to work ?
Source file: https://github.com/lattera/glibc/blob/master/malloc/malloc.c (line:5141).
Comment: can you paste the source in question or a link to it? the file name and line number in libc ?
Comment: https://github.com/lattera/glibc/blob/master/malloc/malloc.c. line number 5141.
Answer: From include/stap-probe.h:
Without USE_STAP_PROBE, that does nothing but evaluates all
its arguments (to prevent bit rot, unlike e.g. assert).

Systemtap's header defines the macros STAP_PROBE (provider, name) and
STAP_PROBEn (provider, name, arg1, ..., argn).  For "provider" we paste
in MODULE_NAME (libc, libpthread, etc.) automagically.

The format of the arg parameters is discussed here:

https://sourceware.org/systemtap/wiki/UserSpaceProbeImplementation

The precise details of how register names are specified is
architecture specific and can be found in the gdb and SystemTap
source code.  */

So:

Don't worry about it -- it's not important for understanding how malloopt() works.
If you really care, read the wiki article referenced above, and look for how the macro is defined in SystemTap sources (SystemTap is entirely separate project from GLIBC).


How do I calculate values for the current user in ruby on rails?

Question: I have an application with a series of tests (FirstTest, SecondTest etc.)
Each test has a calculation set out its relevant model that gets calculated before being saved to the database set out like this:
<code>#first_test.rb
before_save :calculate_total

private

def calculate_total
...
end
</code>
I then have an index page for each user (welcome/index) which displays the current user's results for each test. This all works fine, however I want to work out various other things such as each users average score overall etc.
Is it possible to access the current user from the welcome model?
Currently my welcome.rb is accessing the data follows:
<code>#welcome.rb
def self.total

   FirstTest.last.total

end
</code>
This obviously access the last overall test NOT the last test from the current user.
I feel like I may have just laid the whole application out in a fairly unintelligent manner...
Thanks in advance x
Answer: Well you need to save user_id in a column for each record in FirstTest. Then you can find the total for current user
<code>FirstTest.where(:user_id => current_user.id).last.total
</code>
Comment: Thanks for your help. I already have a user_id column. However if I use that code it still can't locate the current_user it comes up with:

    "undefined local variable or method `current_user' for Welcome(id:
    integer, created_at: datetime, updated_at: datetime):Class Did you
    mean? current_scope"
Comment: Ok you need to get the current user somehow. How are you authenticating the user? You can use devise if you want to https://github.com/plataformatec/devise


Why is there private method outOfBoundsMsg in java.util.ArrayList?

Question: Here's snippet from java.util.ArrayList:
/**
 * Constructs an IndexOutOfBoundsException detail message.
 * Of the many possible refactorings of the error handling code,
 * this "outlining" performs best with both server and client VMs.
 */
private String outOfBoundsMsg(int index) {
    return "Index: "+index+", Size: "+size;
}

Here's snippet from com.google.collect.Preconditions:
  /*
   * All recent hotspots (as of 2009) *really* like to have the natural code
   *
   * if (guardExpression) {
   *    throw new BadException(messageExpression);
   * }
   *
   * refactored so that messageExpression is moved to a separate
   * String-returning method.
   *
   * if (guardExpression) {
   *    throw new BadException(badMsg(...));
   * }
   *
   * The alternative natural refactorings into void or Exception-returning
   * methods are much slower.  This is a big deal - we're talking factors of
   * 2-8 in microbenchmarks, not just 10-20%.  (This is a hotspot optimizer
   * bug, which should be fixed, but that's a separate, big project).
   *
   * The coding pattern above is heavily used in java.util, e.g. in ArrayList.
   * There is a RangeCheckMicroBenchmark in the JDK that was used to test this.

May somebody shed light on:

why private outOfBoundsMsg is required
meaning of "this outlining performs best..."
should I start refactoring my code to include string returning methods for my exception constructors?
Comment: `outOfBoundsMsg` is not 'required', the developers of Java (and apparently also Google Collections) found it was a sufficient performance improvement for their library (probably after careful testing). It is also an optimization that might not work with all Java versions and implementations.
Answer:
meaning of "this outlining performs best..."

It's the opposite of inlining, but not a standard term, which is why it is scarequoted.

why private outOfBoundsMsg is required

That's what "outlining" is about—extracting code to a separate method.

should I start refactoring my code to include string returning methods for my exception constructors?

If you care about 3 nanoseconds wasted each time you throw an exception which does not have a string literal for a message, then yes. In other words: NO.
Comment: Exactly: NO. If you have to ask, you don't have a good reason for doing so.


Repetir um algoritmo se a resposta for errada em jogo adivinhação sem perder o número sorteado

Question: Eu fiz um algoritmo em Python com a proposta de adivinhar um número conforme o usuário digite, ou seja, o jogo da adivinhação. Porém gostaria de fazer uma condição que faça ele digitar novamente, caso ele não escolher o numero desejado, não faço ideia como faço, por causa do módulo random.
import random
import time

def c():

num =(int(input("Adivinha um numero de 0 a 5: ").strip()))
numB = random.randint(0,5)
print("CARREGANDO..............................")
time.sleep(1)

if num == numB:
    print('Parabéns! Você acertou o numero\n'
          'Você é um vencedor !')
elif num > numB: # Condição do valor diferente, só uma amostra(Está errado)
    print("Valor errado")

else:
    print("Errado! Tente de Novo")
    time.sleep(1)
    c()
c()

Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver 15 pontos).
Answer: Ficar chamando a mesma função não é muito adequado, pode inclusive estourar o stack, embora neste caso seja altamente improvável isto ocorrer, mas acostume-se fazer certo. O melhor é fazer um laço e sair só se estiver certo. O sorteio obviamente fica fora do laço para não sortear outro número em cada tentativa, simples e fácil quando usa o mecanismo certo.
import random

def c():
    numB = random.randint(0, 5)
    while True:
        num = int(input("Adivinha um numero de 0 a 5: ").strip())
        if num == numB:
            print('Parabéns! Você acertou o numero\n'
                  'Você é um vencedor !')
            break
        elif num > numB:
            print("Valor errado")
        else:
            print("Errado! Tente de Novo")
c()

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.


Why does Ajax prevents managed_file to be displayed?

Question: I have this form

created by this code:
public function buildForm(array $form, FormStateInterface $form_state, $contractId = NULL) {

    some initialisation code...

    $database = \Drupal::database();

    //  From database to populate $form['designation']
    $query_am = $database->select('member', 'am');
    $query_am->fields('am', ['id', 'designation']);
    $query_am->condition('status', [2, 3, 4], 'IN')
        ->orderBy('designation', 'ASC');
    $aMembers = $query_am->execute()->fetchAllKeyed();
    $aMembers = ["0" => ""] + $aMembers;

    $memberId = $form_state->getValue('designation');
    if ($memberId) {
        $query = $database->select('contract_subscription', 'cs')
            ->fields('cs')
            ->condition('contract_id', $contractId)
            ->condition('member_id', $memberId);
        $subscription = $query->execute()->fetchAssoc();
    }

    $wrapper = 'formWrapper';
    $form['#prefix'] = '
';
    $form['#suffix'] = '
';

    $form['designation'] = [
        '#type' => 'select',
        '#options' => $aMembers,
        '#title' => $this->t('Member'),
        '#required' => TRUE,
        '#default_value' => $memberId,
        '#ajax' => [
            'callback' => '::memberCallback',
            'wrapper' => 'theSubscription',
        ],
    ];

    $form['theSubscription'] = [
        '#type' => 'container',
        '#attributes' => ['id' => 'theSubscription'],
        '#quantities' => $iNumberOfQuantities,
    ];

        $value = $subscription['quantity01'];
        $form['theSubscription']['quantity01'] = [
            '#type' => 'number',
            '#title' => $aContractTypeHeader[$i - 1],
            '#min' => 0.00,
            '#max' => 99.95,
            '#step' => 0.05,
            '#value' => $value,
        ];
    }

    $form['theSubscription']['comment'] = [
        '#type' => 'textarea',
        '#title' => t('Comment'),
        '#rows' => 1,
        '#value' => $subscription['comment'],
    ];

    $fileId = (int) $subscription['file__target_id'];
    $form['theSubscription']['file'] = [
        '#type' => 'managed_file',
        '#description' => $this->t('Limited to @size MB.', ['@size' => $upload_max_inMB]) . '
' . $this->t('Allowed types: pdf.'),
        '#upload_location' => 'private://contracts/subscriptions/',
        '#upload_validators' => [
            'file_validate_extensions' => ['pdf'],
            'file_validate_size' => [$upload_max],
        ],
        '#default_value' => [$fileId],
    ];

    if ($sContractIsOpenForSubscription) {
        $form['save'] = [
            '#type' => 'submit',
            '#name' => 'save',
            '#value' => $this->t('Save'),
            '#ajax' => [
                'wrapper' => $wrapper,
                'callback' => '::ajaxSave',
            ],
        ];
    }

    $form['leave'] = [
        '#type' => 'submit',
        '#name' => 'leave',
        '#value' => $this->t('Leave'),
    ];

    $form['#attached']['library'][] = 'amap/amap';

    return $form;
}

public function memberCallback($form, FormStateInterface $form_state) {
    return $form['theSubscription'];
}

When I select an item in the select box, Ajax memberCallbackis called, $database->select('contract_subscription', 'cs') is executed and the form is updated with the values retrieved from the database.
That works for all the fields except for the file which is never displayed (only the default empty managed_file field shows up):

I wanted to check and I executed the form with $memberId = 64; hardcoded to force a first display without using Ajax and it works!

What is wrong with my code?
Answer: Tried to use field name of file like this:
$form['theSubscription']['file'][$fileId]
or either
$form['theSubscription'][$fileId]

instead of
 $form['theSubscription']['file']

Analysis: By passing "$fileId" variable in field name , it makes field name dynamic & cache 'll not maintain of rendering "file_widget" hooks, it 'll render dynamic value of "managed_file" field on ajax call.
Comment: It seems to work with `$form['theSubscription'][$fileId]`. Thanks! By the way, where am I supposed to find this kind of information?
Comment: Nice qus, It was just basic debugging & analysis skills that helps to fix issue however I did not found any link to resolve this issue.:)
Comment: Few days ago, I tried to alter the some contrib code functionality I figured out some hooks maintain their cache,similar pattern found here.
so I tried to pass dynamic variable in field_name with thought of if it's cache issue of 'file_widget' hooks then it should work, finally solution works and reached at solution by analysis.


How to make a global function for rails 3?

Question: Can somebody pls tell me how to make a function accessible to all, regardless if its a controller, model, helper, or view will call it. Is there a way to do this?
Answer: in your config/application.rb:
<code>Dir.glob("./lib/*.{rb}").each { |file| require file } # require each file from lib directory
</code>
then just create .rb file with all you need and put it to your /lib directory


where to place accent for beat when stem is above note

Question: In this example, the accents are above the notes:

What if you were accenting middle C? Would the accent go above the stem?
Answer: Horizontal accent marks, that look like '>', go close to the note head in single voice music (c.f. page 9-10 of this style guide). In multi-voiced music, the accents for the upper voice(s) are above the music, and thus are "on top of the stems", and the accents for the lower voice(s) are below.
The convention to keep '^' style accents above the notes, whether stem up or stem down, as indicated here, makes sense to me, but I don't have what I consider to be an authoritative reference on it (It's just that I've never seen it, and when I imagine it, it would look weird to me.)
Comment: The current "authoritative reference" is generally agreed to be https://www.amazon.co.uk/d/cka/Behind-Bars-Definitive-Guide-Notation-Elaine-Gould/0571514561 - but for placing accents there is more than one "standard." For example orchestra parts used in theater productions have different conventions from "classical" music. The most comprehensive music notation program I know of has a total of *twelve* different options for placing articulations relative to the staff, the notes in the score, slurs, and ties - i.e. there are 4096 possible sets of "default rules" for positioning them!!


Conditional probability problem given binomial variables - joint probability and independence

Question:
A test that verifies if mass-produced parts are up to standard is not completely reliable.

$C$ : the part is up to standard

$R$ : the part is classified as up to standard

We know :
$Pr(\bar{C})=20\%$
$Pr(\bar{R}|C)=13\%$
$Pr(R|\bar{C})=11\%$

In this problem, 43 parts are randomly chosen to be verified.

a) Calculate the probability that 8 parts are classified as not up to standard.

My answer : Let's start by finding $Pr(\bar{R})$
$Pr(C)=1-Pr(\bar{C})=0.8$
$Pr(R|C)=1-Pr(\bar{R}|C)=0.87$
$Pr(R)=Pr(R|\bar{C})Pr(\bar{C})+Pr(R|C)Pr(C)=0.718$
$Pr(\bar{R})=1-Pr(R)=0.282$
I found that $\bar{R}$ follows a binomial distribution of parameters $n=43$ and $p=Pr(\bar{R})=0.282$
So, $Pr(\bar{R}=8)=\left( \begin{array}{c} n \\ 8 \end{array} \right)p^{8}(1-p)^{n-8}=0.0534$

b) Knowing that 8 parts are classified as not up to standard by the test, what is the probability that there are exactly 12 parts that are not up to standard?

My answer : The formula I want to use is
$Pr(\bar{C}=12|\bar{R}=8)=\frac{Pr(\bar{C}=12 \bigcap \bar{R}=8)}{Pr(\bar{R}=8)}$
but I am aware it's not that simple. I need to start by determining whether the variables are independent or not. If $C$ and $R$ are independent, then $Pr(\bar{C}=12|\bar{R}=8)=Pr(\bar{C}=12)$.
To determine whether or not they are independent I need to find the joint distribution, but I'm stuck.
Can I somehow use $f_{Y|X=x}(y)=\frac{f(x,y)}{f_X(x)}$ ? And if so how would I find $f_{Y|X=x}(y)$ ?
Any help is appreciated
Answer: One needs to be more precise about notation.  $R$ and $C$, as well as their complements, are events, not random variables.  Thus, we need additional notation.  Let $X$ represent the random number of parts that are in fact not up to standard; and $Y$ represent the random number of parts that are classified as not up to standard.  Then $$X \sim \operatorname{Binomial}(n = 43, p = \Pr[\bar C] = 0.2),$$ and $$Y \sim \operatorname{Binomial}(n = 43, p = \Pr[\bar R] = 0.282).$$  These are marginal distributions and are dependent.
The answer to the first part of your question is $$\Pr[Y = 8] \approx 0.0534247.$$
For the second part, we should employ Bayes' theorem:  $$\Pr[X = 12 \mid Y = 8] = \frac{\Pr[Y = 8 \mid X = 12]\Pr[X = 12]}{\Pr[Y = 8]}.$$  The denominator has already been calculated.  Also, it is straightforward that $$\Pr[X = 12] = \binom{43}{12}(0.2)^{12} (1 - 0.2)^{43 - 12} \approx 0.0622211.$$  The only quantity remaining is $\Pr[Y = 8 \mid X = 12]$.  We reason that there are $12$ truly not up to standard parts, and the number $Y_{\bar C}$ of these parts that are not classified up to standard is binomial with $n_{\bar C} = 12$ and $p_{\bar C} = \Pr[\bar R \mid \bar C] = 0.89$. Similarly, the number $Y_C$ of parts that are not classified up to standard given they are in fact up to standard, is binomial with $n_C = 43 - 12 = 31$ and $p_C = \Pr[\bar R \mid C] = 0.13$.  These two random variables are in fact independent.  Therefore,
$$\begin{align}
\Pr[Y = 8 \mid X = 12]
&= \sum_{y=0}^8 \Pr[Y_{\bar C} = y]\Pr[Y_C = 8-y] \\
&= \sum_{y=0}^8 \binom{12}{y} (0.89)^y (1-0.89)^{12-y} \binom{31}{8-y} (0.13)^{8-y} (1-0.13)^{31-(8-y)} \\
&\approx 0.000860467.
\end{align}$$
Therefore, the desired probability is $$\Pr[X = 12 \mid Y = 8] \approx \frac{(0.000860467)(0.0622211)}{0.0534247} = 0.00100214.$$


On the Bounded Convergence Theorem

Question: Question: Does the Bounded Convergence Theorem hold if $\operatorname{m}\left(E\right)<+\infty$ but we drop the assumption that the sequence $\{f_n\}$ is uniformly bounded on $E$ but still pointwise bounded?
I know that the answer is no, however, I cannot think of a counterexample. I though about the sequence of functions $f_n:[0,1]\to\mathbb{R}$ defined by:
$$f_n(x):=n\cdot\chi_{(0,1/n[}.$$
But this sequence is not pointwise bounded.

For reference, this is a modification of a question out of Roydens Real Analysis text. Moreover, the question out of Roydens Real Analysis text is the following:
Question: Does the Bounded Convergence Theorem hold if $\operatorname{m}\left(E\right)<+\infty$ but we drop the assumption that the sequence $\{f_n\}$ is uniformly bounded on $E$?
Obviously, the sequence of functions $\{f_n\}$ defined above suffices as a counterexample for this question.
Answer: Define $(f_{n})_{n \in \mathbb{N}}$ in $(0,1]$ with Lebesgue measure as follows:
\begin{align*}
f_{n}(x) = x^{-1} \chi_{[n^{-2},n^{-1}]}(x)
\end{align*}
We have $\lim_{n \to \infty} f_{n} = 0$ pointwise in $(0,1]$.  Further, $f_{n}(x) \leq x^{-1}$ so we are pointwise bounded.  However, $\lim_{n \to \infty} \int_{0}^{1} f_{n}(x) \, dx \neq 0$ as
\begin{equation*}
\int_{0}^{1} f_{n}(x) \, dx = \int_{n^{-2}}^{n^{-1}} x^{-1} \, dx = \log(n^{-1}) - \log(n^{-2}) = \log(n).
\end{equation*}
Comment: Could you explain the last inequality?
Comment: Yes, the explanation is it was an error!  I edited the answer.
Comment: Just now seeing this, but this is a great answer! Thanks.

On the Bounded Convergence Theorem


How to know the request came from a trigger click

Question: I have two buttons namely 'Reject button' and  'Prev button'. On click of the Reject button I am doing a trigger call to the Prev button. Is it possible to know inside the Prev button handler that a request came from by clicking on the Reject button?
This is my code

$(document).on('click', '#prev', function(event) {
  var event_from = event.target.tagName;
  alert(event_from);
});

$(document).on('click', '#reje', function(event) {
  $("#prev").click();
});

  <input type="button" id="reje" value="Reject">

<input type="button" id="prev" value="prev">

I have tried by using the event.target.tagName; but I am getting value as INPUT in both the cases
http://jsfiddle.net/Us8uc/4350/
Comment: `event.target.id`? Or `$(this).attr('id');` or `$(this).val();` `tagName` is not going to work since they are both the same.
Comment: You want to get the event of the previous function? Is that correct?
Comment: because the event was triggered on the button you manually triggered the event on. You are not going to get the event of the original click. Inspecting the event objects, you would see what is different between the two.
Comment: Seems like an XY problem. If you need to know that the event was triggered somewhere else, it's likely that you really meant to call a shared function rather than trigger the same handler.
Answer:
Is it possible to know inside the Prev button handler that a request came from by clicking on the Reject button?

One option is to check the .isTrigger property on the event object. It should return true if the event was triggered (like in this case). As pointed out in the comments below, this is an undocumented internal feature which can potentially change (although that is arguably unlikely at this point). See the other alternative options below.
Updated Example
$(document).on('click', '#prev', function(event) {
  if (event.isTrigger) {
    alert('Triggered by reject.');
  }
});

$(document).on('click', '#reje', function(event) {
  $("#prev").click();
});

You could also check the .originalEvent property on the event object in order to determine how the event originated. The property is only set if the event originated from the browser, which means that it will be undefined when triggered:
Updated Example
$(document).on('click', '#prev', function(event) {
  if (event.originalEvent === undefined) {
    alert('Triggered by reject.');
  }
});

$(document).on('click', '#reje', function(event) {
  $("#prev").click();
});

Alternatively, you could set a flag before triggering the click event:
Updated Example
var triggeredByReject = false;

$(document).on('click', '#prev', function(event) {
  if (triggeredByReject) {
    triggeredByReject = false;
    alert('Triggered by reject.');
  }
});

$(document).on('click', '#reje', function(event) {
  triggeredByReject = true;
  $("#prev").click();
});

Another option would be to compare the timestamps on the events:
Updated Example
var lastRejectClick = 0;
$(document).on('click', '#prev', function(event) {
  if (lastRejectClick > event.timeStamp) {
    alert('Triggered by reject.');
  }
});

$(document).on('click', '#reje', function(event) {
  lastRejectClick = event.timeStamp + 10;
  $("#prev").click();
});

*I added 10 milliseconds to the timestamp to account for potential timestamp approximations/differences.
Comment: It appears you're taking advantage of an undocumented internal feature to jQuery. While I generally have no problem with using such features, it's worth at least calling out that it could break without warning if the implementation changes.
Comment: @zzzzBov You're right, surprisingly I couldn't find any official documentation on the property. Based on [the source code](https://github.com/jquery/jquery/blob/d92310050ca7bf0b33825d64e052f9a8809c3e9e/test/data/jquery-1.9.1.js#L3026), it should always be true if the event was triggered, so I highly doubt that it will change. I agree with your comment above though, this seems like an XY problem. There are various other solutions.


Plugin Wordpress para criar um contador de visitas (com texto)?

Question: Como posso colocar um contador de visitas em meu site Wordpress para que a cada acesso suba +1 ?

Tentei procurar por plugins, mas não achei nenhum que mostrasse somente o número de acessos em forma de texto, o que achei foi só o que conta as estatísticas, como IP, navegador, etc...
Comment: Pode mencionar os plugins que achou?
Comment: http://wordpress.org/plugins/who-hit-the-page-hit-counter/ - http://wordpress.org/plugins/free-counter/ - http://wordpress.org/plugins/counterize/ - entre outros...
Answer: Achei um script PHP + TXT para não haver necessidade de banco de dados.

Link: http://www.codigofonte.net/scripts/php/contador/1352_jcr-contador-v1-0

Eu baixei o script e enviei para o diretório do tema, e dei permissão 777 no arquivo contador.txt, para poder gravar os dados no arquivo .txt.
Depois fui no diretório do meu tema e editei o arquivo header.php e coloquei:
<?php include("contador/contador.php"); ?>

No lugar que queria que aparecesse.
Com esse script é possível:

Mostrar as visitas de hoje
Mostrar as visitas de ontem
Mostrar o total de visitas
Mostrar o recorde e data de visitas

Problema resolvido!


Implementing sampling from GEV distribution from scratch

Question: I am trying to implement sampling from GEV distribution without using external libraries (except numpy) and this is what I came up with:
import numpy as np
def gev_rvs(c=-0.583, loc=68.44, scale=66.05, size=1000):
    u = np.random.uniform(size=size)
    sample = loc + scale / c * (np.power(-np.log(u), -c) - 1)
    return sample

I am using the equation for the quantile function for GEV as in wikipedia. However when I compare it with the results from
from scipy.stats import genextreme as gev
sample = gev.rvs(c=-0.583, loc=68.44, scale=66.05, size=1000)

they give much different distributions of samples. What could be the reason?
Update:
The corrected version of Ben's equation seems to be the same as the one in wikipedia, however they are both far from the one provided by scipy:

Attaching below the code used for histogram in case I made a mistake somewhere:
def wikipedia_gev_rvs(c, loc, scale, size):
    u = np.random.uniform(size=size)
    sample = loc + scale / c * (np.power(-np.log(u), -c) - 1)
    return sample

def ben_gev_rvs(c, loc, scale, size):
    u = np.random.uniform(size=size)
    sample = loc + scale / c * (np.power(np.abs(np.log(u)), -c) - 1)
    return sample

def scipy_gev_rvs(c, loc, scale, size):
    sample = scipy.stats.genextreme.rvs(c, loc, scale, size=size)
    return sample

sample_w = wikipedia_gev_rvs(-0.583, 68.44, 66.05, size=1000)
sample_b = ben_gev_rvs(-0.583, 68.44, 66.05, size=1000)
sample_s = scipy_gev_rvs(-0.583, 68.44, 66.05, size=1000)

plt.hist(sample_w, bins=range(-200, 1500, 20), alpha=0.5, label='wikipedia')
plt.hist(sample_b, bins=range(-200, 1500, 20), alpha=0.5, label='ben')
plt.hist(sample_s, bins=range(-200, 1500, 20), alpha=0.5, label='scipy')
plt.legend()
plt.show()

Comment: I added the comparison of histograms.
Answer: Consider the GEV distribution for the standardised value $s = (x-\mu)/\sigma$.  This distribution has CDF given by:
$$F(s|\xi) = \begin{cases}
\exp(-\exp(-s)) & & & \text{for } \xi=0, \\[6pt]
\exp(-(1+\xi s)^{-1/\xi}) & & & \text{for } s > -1/\xi \ \text{ and } \ \xi \neq 0, \\[6pt]
0 & & & \text{for } s \leqslant -1/\xi \ \text{ and } \ \xi > 0, \\[6pt]
1 & & & \text{for } s \leqslant -1/\xi \ \text{ and } \ \xi < 0. \\[6pt]
\end{cases}$$
Inverting this function gives the corresponding quantile function for the standardised value:
$$Q(p|\xi) = \begin{cases}
-\log(-\log(p)) & & & \text{for } \xi=0, \\[6pt]
\frac{1}{\xi} (|\log(p)|^{-\xi}-1) & & & \text{for } \xi \neq 0. \\[6pt]
\end{cases}$$
Substituting the original parameters then gives the quantile function for the non-standardised value:
$$Q(p|\mu, \sigma, \xi) = \begin{cases}
\mu - \sigma \log(-\log(p)) & & & \text{for } \xi=0, \\[6pt]
\mu + \frac{\sigma}{\xi} (|\log(p)|^{-\xi}-1) & & & \text{for } \xi \neq 0. \\[6pt]
\end{cases}$$
The mathematical form in your code does not appear to correspond to this function, so I suspect that this is the source of the problems you are having.
Comment: I believe that now your current formula corresponds to the OP formula except using an absolute sign instead of negation.
Comment: It seems so to me as well, since **p** is between 0 and 1, then logarithm will be always negative which means adding minus is equivalent to abolute sign, which seems to be confrmed on the histograms when compared.
Comment: @SextusEmpiricus: Since $0<p<1$ we have $-\log(p) = |\log(p)|$ so this is really just a matter of preference as to which operations to state here.  Personally, I always use the absolute value sign in these cases since it makes it easier for the reader to immediately see that the quantity under discussion is non-negative.
Answer: Probably the difference is in the sign of $c$. This is explained in the notes of the scipy genextreme function (source on GitHub).
Notes
    -----
    For :math:`c=0`, `genextreme` is equal to `gumbel_r` with
    probability density function

    .. math::

        f(x) = \exp(-\exp(-x)) \exp(-x),

    where :math:`-\infty < x < \infty`.

    For :math:`c \ne 0`, the probability density function for `genextreme` is:

    .. math::
        f(x, c) = \exp(-(1-c x)^{1/c}) (1-c x)^{1/c-1},

    where :math:`-\infty < x \le 1/c` if :math:`c > 0` and
    :math:`1/c \le x < \infty` if :math:`c < 0`.

    Note that several sources and software packages use the opposite
    convention for the sign of the shape parameter :math:`c`.

    `genextreme` takes ``c`` as a shape parameter for :math:`c`.

Comment: Mystery solved! When changing the sign of **c** it aligns with the scipy version, thanks a lot.
Comment: I am a bit confused about the source code that I found, as the class genextreme has no rvs defined in it. Anyway, if it is somewhere else it might still be due to that convention about the shape parameter.
Comment: Yes, I was also looking at their source code before posting the question here, but couldn't understand it.


Consensus on the goalie 'hole' numbering in Hockey?

Question: In ice hockey, it seems fairly well agreed upon that there are 5 main 'holes' to aim for when shooting on the net. Upper left, lower left, upper right, lower right, and between the goalie's legs.
The last hole is always referred to as the '5-hole'. But is there any agreement on the numbering of the other 4? A quick google image search shows all sorts of numbering schemes, which leads me to believe that, no, there is no agreement:
https://www.google.com/search?q=hockey+goal+5+hole&tbm=isch
Comment: I haven't heard of any other location referred to by a number. Just high glove, low glove, high stick-side, and low-stick side. That's relative to the goalie. Shot location can also be noted in reference to where the shot is going to relative to the net (i.e., short-side and far-side).
Comment: I found [this discussion](https://en.wikipedia.org/wiki/Talk:Goaltender#Hole_numbering.3F) on a talk page  of a Wikipedia article. But it is rather brief.
Answer: No, there is no agreement.
You are accurate in your finding that there is no agreement. However in my experience it starts with one in the upper left and rotates clockwise down to the lower left to 4, with 5-hole added on.


Error of self edges in hive plot

Question: Absolutely cannot figure out why the error is coming even though there are no self edges.
Below is a reproducible code. Any help would be great
library(HiveR)

nodes = data.frame(id = 1:9, lab = c("A","B","C","E","F","G","H","I","J"),
axis = c(1,1,1,2,3,2,2,2,3), radius = rep(50,9),size = rep(10,9),
color = c("yellow","yellow","yellow", "green","red","green","green","green","red"))

edges = data.frame(id1 = c(1,2,3,4,5,4,1,9,8,6,1),id2 = c(2,3,4,1,9,9,9,8,7,7,6),
weight = rep(1,11),
color = c(rep("green",7), rep("red",4)))
        test3 <- ranHiveData(nx = 3)
        test3$nodes = nodes
        test3$edges = edges
        test3$edges$color <- as.character(test3$edges$color)
        test3$edges$id1 <- as.integer(test3$edges$id1)
        test3$edges$id2 <- as.integer(test3$edges$id2)
        test3$nodes$color <- as.character(test3$nodes$color)
        test3$nodes$lab <- as.character(test3$nodes$lab)
        test3$nodes$axis = as.integer(test3$nodes$axis)
        test3$nodes$id = as.integer(test3$nodes$id)
        test3$nodes$radius = as.numeric(test3$nodes$radius)
        test3$nodes$size = as.numeric(test3$nodes$size)
        test3$edges$weight = as.numeric(test3$edges$weight)
        test3$desc = "3 axes --9 nodes -- 11 edges"
        sumHPD(test3, chk.sm.pt = TRUE)

The code is giving self edges and the the plot is not rendering plotHive(test3) showing

Error in calcCurveGrob(x,x$debug) : end points must not be identical
Answer: In your code the position of the nodes of the axis (radius) are all set to 50. Hence there are overlapping points (3 on axis 1, 4 on axes 2 and 2 on axis 3).
A correct definition of radius solves the problem.
library(HiveR)

# radius has been changed !
nodes = data.frame(id = 1:9, lab = c("A","B","C","E","F","G","H","I","J"),
axis = c(1,1,1,2,3,2,2,2,3), radius = c(1,2,3,1,1,2,3,4,2),size = rep(1,9),
color = c("yellow","yellow","yellow", "green","red","green","green","green","red"))

edges = data.frame(id1 = c(1,2,3,4,5,4,1,9,8,6,1),id2 = c(2,3,4,1,9,9,9,8,7,7,6),
weight = rep(1,11),
color = c(rep("green",7), rep("red",4)))
        test3 <- ranHiveData(nx = 3)
        test3$nodes = nodes
        test3$edges = edges
        test3$edges$color <- as.character(test3$edges$color)
        test3$edges$id1 <- as.integer(test3$edges$id1)
        test3$edges$id2 <- as.integer(test3$edges$id2)
        test3$nodes$color <- as.character(test3$nodes$color)
        test3$nodes$lab <- as.character(test3$nodes$lab)
        test3$nodes$axis = as.integer(test3$nodes$axis)
        test3$nodes$id = as.integer(test3$nodes$id)
        test3$nodes$radius = as.numeric(test3$nodes$radius)
        test3$nodes$size = as.numeric(test3$nodes$size)
        test3$edges$weight = as.numeric(test3$edges$weight)
        test3$desc = "3 axes --9 nodes -- 11 edges"
        sumHPD(test3, chk.sm.pt = TRUE)

plotHive(test3)

Error of self edges in hive plot


Can the relation of $a^{p} \equiv a\pmod {2p}$ if (p prime and p>2) be added to Fermat's little theorem?

Question: Fermat's little theorem
$a^{p} \equiv a\pmod p$  if p prime
I have noticed that  the formula $a^{p} \equiv a\pmod {2p}$  (p prime and p>2)   can be also  written by using Fermat's little theorem
Proof:
Let $a$ be any integer and $p>2$ be some prime number.
$a^{p} \equiv a\pmod p$
$a^{p}-a \equiv 0\pmod p$
$a(a^{p-1}-1) \equiv 0\pmod p$
$a(a^{p-1}-1) \equiv 0\pmod p$
$F(a)=(a^{p-1}-1)$ can be divided to $(a-1)$ because $F(1)=(1^{p-1}-1)=0$
$F(a)=(a^{p-1}-1)=(a-1).R(a)$  //R(a) is polinom that has degree p-2 and coefficients are  Integer numbers.
$a (a-1) R(a)  \equiv 0\pmod p$
$a (a-1)$  is always an even number so $a (a-1) R(a)$ will be always even number and also can be divided to $p$ because of Fermat's little theorem . Thus $a^{p} \equiv a\pmod {2p}$  if (p prime and p>2) .
I searched internet but I have not seen that relation in the internet.
Is it known formula?Please help if it is known relation(I would like to learn what the subject is )
Sorry if someone else asked the same question in here.
Thank you for answers and helps.
Comment: If $a$ is any integer, and $n$ a positive integer, then $a^n \equiv a \mod 2$. Your equation is a combination of this fact and Fermat's little theorem. Both are known congruences, but I'm note sure there's a name for their combination.
Answer: You are correct I think, but the way you write it down makes it look more difficult than it is. Also you should be more specific on whether you are talking about one particular $a$ or "$\forall a$".
So let me show how I would write this down. First, let $a$ be any integer and $p>2$ be some prime number. Then
$$ a^p \equiv a \pmod{2p} \iff 2p \mid a^p - a  \iff 2\mid a^{p}-a \text{ and } p\mid a^p-a$$
The last equivalence holds because $2$ and $p$ are two different primes.
But $2\mid a^p-a$ for all $a$ and $p$: if $a$ is even, then clearly $a^p$ will be even as well; if $a$ is odd, then so is $a^p$ and hence $a^p-a$ will be even again. So this is indeed equivalent to
$$\dots \iff  p\mid a^p-a \iff a^p \equiv a \pmod p.$$
Comment: No actually it's a continuation of the chain of equivalences up above. So it should be read as $$ a^p \equiv a \pmod{2p} \iff \dots \iff a^p\equiv a \pmod{p}$$
Answer: This is the special case $\rm\ m = 2\:p,\ p\:$ odd, of the following generalization of Fermat's little theorem, quoted from Bill Dubuque's post
THEOREM  $\ $ For naturals $\rm\: k,m>1 $
$\qquad\rm m\ |\ a^k-a\ $ for all $\rm\:a\in\mathbb N\ \iff\ m\:$ is squarefree and prime $\rm\: p\:|\:m\: \Rightarrow\: p-1\ |\ k-1 $
Answer: As Joel rightly observed :If $a$ is any integer, and $n$ a positive integer, then $a^n\equiv a \pmod2$
So : $a^p\equiv a \pmod2$ , and $a^p\equiv a \pmod p$
According to Chinese Remainder Theorem :
$a^p \equiv a \pmod { \operatorname{lcm} (2,p)} $
,and since $p$ is an odd prime it follows that : $\operatorname{lcm}(2,p) = 2p$ , therefore :
$a^p \equiv a \pmod {2p}$
Comment: The answer, Maybe, can be perfect and  if we add some additional steps to show how proof of Chinese Remainder Theorem.

c,d,e are integers

if $a^p\equiv a \pmod2$  then $a^p=a+2.c$

$a^p-a=2.c$

if $a^p\equiv a \pmod p$ then $a^p=a+p.d$

$a^p-a=p.d=2.c$

$d=2.e$  can be written because $2.c$ is even number

Thus $a^p-a=p.d=2.c=2.p.e$

$a^p-a\equiv 0 \pmod{2p}$

$a^p\equiv a \pmod{2p}$

Thanks in advice


Undefined when displaying subscribe data for nested classes

Question: I am working with Angular 8.
With a nested class, I am trying to display data obtained from a subscribe operation to an observable. It works for the main attributes of the class (id, name), but I am getting an 'undefined' error whenever I try to access the child class (Players), at least until the data is finally feed by the observable.
The data structure is simple. I have a tournament with players in it.
import { Player } from './player';

export class Tournament {
   id: string;
   name: string;

   public Players: Player[];
}

The service is as follows. It returns the data correctly, in the format expected by the Tournament class.
  getTournament(id): Observable<Tournament> {
    return this.http.get<Tournament>(this.apiURL + '/tournaments/' + id)
    .pipe(
      retry(1),
      catchError(this.handleError)
    )
  }

The component, below. It initializes the data correctly as long as I don't try to access the child component, which of course is undefined since I declared the variable tournament as of type any
export class TournamentEditComponent implements OnInit {

  id = this.actRoute.snapshot.params['id'];
  tournament: any = [];

  constructor(public restApi: RestApiService, public actRoute: ActivatedRoute, public router: Router){}

  ngOnInit() {
    this.getTournament();
  }

  // Get tournament data to feed screen
  getTournament() {
    this.restApi.getTournament(this.id).subscribe((data: any) => {
      this.tournament = data;
      console.log('Tournament:\n',this.tournament);
    })
  }

Players ({{tournament.Players.length}})

      <ngb-accordion #acc="ngbAccordion" activeIds="">

          <ngb-panel title="{{player.username}}">
            <ng-template ngbPanelContent>

{{player.name}} {{player.surname}}

            </ng-template>
          </ngb-panel>

      </ngb-accordion>

The console seen in the component shows the following data (I've deleted some unnecessary data from it):
{
  id: 1
  name: "Express1"
  prize: 1000
  rounds: 25
  createdAt: "2020-01-09T17:03:13.772Z"
  updatedAt: "2020-01-13T09:48:28.582Z"
  Players: Array(2)
    0: {id: 1, username: "aaaa", name: "a", surname: "b", email: "email@example.com"}
    1: {id: 3, username: "bbbb", name: "b", surname: "a", email: "firstname.lastname@example.com"}
    length: 2
  __proto__: Array(0)
  __proto__: Object
}

Whenever I try to access the object/class Player from the HTML page, I get an undefined error, even if at the end it shows the data correctly. I have tried changing the variable tournament of the component to a variable of type Tournament to no success.
What am I doing wrong? How could I, at least, initialize the variable Tournament so that I don't get an undefined error while waiting for the result of the async operation?
Comment: Does the result of your console.log in the TournamentEditComponent return what you expected?
Comment: Can you post, your html ?
Comment: You could initialise the value of tournament to *something that's actually a Tournament*, not just an empty array. The fact that you had to type it as any should have been a clue that your value didn't make sense. Or use the elvis operator to safely navigate to props, or use ngIf to conditionally render once the data is available, or use the AsyncPipe to deal properly with an observable of the data you want. I'd recommend starting with https://angular.io/tutorial.
Comment: @AndrewStalker Yes, it does indeed. The problem I am having is before this data is retrieved from my server.
Comment: Players will be undefined until you have a tournament. As jonrsharpe says, manye an ngIf to conditionally render the panels would work. I'd set the initial tournament to null, and then in the accordion you could use *ngIf="tournament". See Emilien's answer.
Comment: Here's a blog post on async data I wrote a while ago: https://blog.jonrshar.pe/2017/Apr/09/async-angular-data.html
Answer: Maybe you can try this :
export class TournamentEditComponent implements OnInit {

  tournament$: Observable<any>;

  getTournament() {
    this.tournament$ = this.restApi.getTournament(this.id);
  }

Players ({{ players.length }})

      <ngb-accordion #acc="ngbAccordion" activeIds="">

          <ngb-panel title="{{ player.username }}">
            <ng-template ngbPanelContent>

{{ player.name }} {{ player.surname }}

            </ng-template>
          </ngb-panel>

      </ngb-accordion>

Comment: Thanks for the tip, I've read a bit more about the asyncpipe and it does make a lot of sense. I've tried applying your solution, and even if I don't get any error, the ngIf directive does not get updated when the async pipe gets de data. If I understand correctly, the pipe returning data should trigger the ngIf update and display the data.
Comment: I think yes but are you sure you have an object `Players` with titlecase into `tournaments$` ? Could you post a console.log from `tournaments$` like `this.tournaments$.subscribe(console.log)` ?
Comment: Please update your post to add this console.log data :)
Comment: Into your .html file, could you make test like `{{ (tournament$ | async) | json }}` and `{{ (tournament$ | async)?.Players | json }}`
Comment: If I do it as you indicate, I get `null` in both cases. However, If I remove the $ (observable) and async clauses ( `{{ (tournament | json) }} `), I get the data correctly
Comment: Oh, that mean you miss I override the name of `tournament$` :) Generally, observables are written with a `$` to distinguish them. So, is this working now ?
Comment: I forgot to remove the subscribe operation and change it for an observable element, to be used with sync later on. This solved my issue, thanks, it seems I have lots to learn yet :).


hadoop filesystem open file and skip first line

Question: I'm reading the file in my HDFS using Python language.
Each file has a header and I'm trying to merge the files. However, the header in each file also gets merged.
Is there a way to skip the header from second file?
hadoop = sc._jvm.org.apache.hadoop
conf = hadoop.conf.Configuration()
fs = hadoop.fs.FileSystem.get(conf)

src_dir = "/mnt/test/"
out_stream = fs.create(hadoop.fs.Path(dst_file), overwrite)

files = []
for f in fs.listStatus(hadoop.fs.Path(src_dir)):
  if f.isFile():
    files.append(f.getPath())

for file in files:
  in_stream = fs.open(file)
  hadoop.io.IOUtils.copyBytes(in_stream, out_stream, conf, False)

Currently I have solved the problem with below logic, however would like to know if there is any better and efficient solution? appreciate your help
for idx,file in enumerate(files):
            if debug:
                print("Appending file {} into {}".format(file, dst_file))

            # remove header from the second file
            if idx>0:
              file_str = ""
              with open('/'+str(file).replace(':',''),'r+') as f:
                for idx,line in enumerate(f):
                  if idx>0:
                    file_str = file_str + line

              with open('/'+str(file).replace(':',''), "w+") as f:
                f.write(file_str)
            in_stream = fs.open(file)   # InputStream object and copy the stream
            try:
                hadoop.io.IOUtils.copyBytes(in_stream, out_stream, conf, False)     # False means don't close out_stream
            finally:
                in_stream.close()

Answer: What you are doing now is appending repeatedly to a string. This is a fairly slow process. Why not write directly to the output file as you are reading?
for file_idx, file in enumerate(files):
  with open(...) as out_f, open(...) as in_f:
    for line_num, line in enumerate(in_f):
      if file_idx == 0 or line_num > 0:
        f_out.write(line)

If you can load the file all at once, you can also skip the first line by using readline followed by readlines:
for file_idx, file in enumerate(files):
  with open(...) as out_f, open(...) as in_f:
    if file_idx != 0:
      f_in.readline()
    f_out.writelines(f_in.readlines())

Comment: Hi Adran, I understand the solution, however, i'm trying to overwrite the existing file, does the proposed solution works for this case?
Comment: It will overwrite if you tell it to `open(..., 'w')`, note we are missing the `+` character next to `w`. It will only append to the file if you add the `+` character to the second parameter, e.g. `w+`. This doesn't delete the file, it just completely replaces the contents, so make sure to delete the old file with something like `os.remove` after moving it to HDFS if that's what you want.


Copy a mail using Microsoft Graph C# SDK

Question: I want to copy a mail from one folder to another.
Referring to the documentation, it should work like this:
var graphClient = new GraphServiceClient(authProvider);
var destinationId = "destinationId-value";

await graphClient.Me.Messages["{message-id}"]
  .Copy(destinationId)
  .Request()
  .PostAsync();

However, when I try to use .Copy() like described I get the error, that I can't use it like a method. If I try to add the information as an [], like it's done for the users or messages property, I receive a different error.
I have tried it like this:
var graphClient = GetGraphClientInstance();
var destinationFolderId = "destinationFolderId-value";

await graphClient.Users["myUserName"].Messages[specificMail.Id]
   .Copy(destinationFolderId )
   .Request()
   .PostAsync();

I'm using Microsoft.Graph version 5.0.0-preview-12.
Does anyone have an idea how to use the Copy property correctly?
Comment: I have used it the way the docs suggest and it work, does `.Move(destinationFolderId)` work for you?
Comment: @IvanGechev Nope, i get the same error. Can't be used like a method. I added the version of the Microsoft.Graph nuget to my original request. Maybe it's related to that.
Comment: both projects where I use `.Move()` and `.Copy()` have version `4.6.0` installed, maybe you can try downgrading.
Comment: @IvanGechev I can try this. However, in older versions the nuget is missing other functionalities i need :/.
Comment: what I used is `` and after using `using Microsoft.Graph;` in my controller, the code snippet doesn't report error. https://i.stack.imgur.com/PPVha.png
Answer: Using Microsoft.Graph v5 your original code:
var graphClient = new GraphServiceClient(authProvider);
var destinationId = "destinationId-value";

await graphClient.Me.Messages["{message-id}"]
  .Copy(destinationId)
  .Request()
  .PostAsync();

should be changed to:
var graphClient = new GraphServiceClient(authProvider);
var destinationId = "destinationId-value";

await graphClient.Users["myUserName"].Messages[specificMail.Id]
  .MicrosoftGraphCopy
  .PostAsync(new CopyPostRequestBody { DestinationId = destinationId });

5.1 has been released and the API changed a little:
var graphClient = new GraphServiceClient(authProvider);
var destinationId = "destinationId-value";

await graphClient.Users["myUserName"].Messages[specificMail.Id]
  .Copy
  .PostAsync(new CopyPostRequestBody { DestinationId = destinationId });

It looks like the C# doc is finally updated now that v5 is officially released, you can view it here.


How to calculate average Harddisk I/O on linux

Question: I want to calculate the average harddisk I/O.
Here i don't want to calculate the i/o currently performing on the system but also the capability of hard drive.
Thank you
Answer: Well there are lots of tools here ...
In order to know what io is happing on your system right now you could make use of iostat this will show you the total io per device, if you add a parameter (iostat 1) it will keep showing you the data each second.
vmstat (see the io columns) shows you aggregated io for the entire system.
In order to get an idea on the performance of a hard drive you could use hdparm -tT /dev/sda (replace /dev/sda by the device to test), this will perform timing of cache reads (-T) and timing of device reads (-t). This will should you the read performance of the device in general.
These are the 'polite' ways to get an idea of usage and throughput and allow you to do some comparisons
If you really want to stress things (e.g. simulate daemon behavior) you should take a look at more specialised benchmarking tools such as bonnie++ iozone and friends. Keep in mind that these will already focus on filesystem benchmarking as well and not only physical or os bound parameters.
Comment: iostat is definently the way to go !
Comment: Thank You for your reply.

iostat shows the no. of blocks read per second.
I want to get the no. of I/O performed per second.
Answer: In addition to iostat and vmstat, dstat is very nice.
Comment: which means you should install it, e.g. sudo apt-get install dstat on ubuntu-like distro's or installing the dstat package on other distro's
Comment: When i execute dstat it returns
command not found
Comment: how do i install it on redhat


Is there an eslint rule to check if the list has more than 0 items

Question: So, I love typescript a lot, but I get a lot of stupid errors because I use lists with 0 items. Is there an eslint rule to put a red line under the list[0] with the saying: 'List might be 0 items'
Comment: Don't you just want [the `noUncheckedIndexedAccess` compiler option](https://www.typescriptlang.org/tsconfig#noUncheckedIndexedAccess)?
Answer: This isn't the purpose of eslint. I'd recommend to simply check how many items there are in the array and using noUncheckedIndexedAccess (which will give you errors when compiling and having no checks):
if (items.length > 0) {
 // do stuff
}


Tradução Theme OpenCart

Question: Eu estou para comprar um tema do OpenCart no ThemesForest, mas gostaria de saber se qualquer tema que comprar tenho opção de tradução. Tanto do site como do Painel.

É um pacote de tradução que baixo ou tenho que fazer isso direto no arquivo PHP  ?
Eu já tenho instalado o OpenCart com tema padrão. Se eu comprar outro, o painel administrativo será o do novo tema ou permanece o padrão ?
Qualquer tema que comprar tenho a opção de instalar plugins para frete, PagSeguro e outros ?
Answer: 1- É um pacote sim. Na verdade quando eu instalei pt-br, baixei diretamente daqui, nesse link você tem as instruções de como instalar;
2 - Provavelmente será o mesmo, talvez ele tenha algum módulo adicional;
3 - Sim, qualquer plugin, pois o CMS sempre será o mesmo, o que você vai estar fazendo ao instalar algum tema é mudar a cara de sua loja, apenas.
Espero ter ajudado, abraço.
Comment: Ajudou sim. Valeu.
Comment: De nada! Boa sorte, abraço.

Tradução Theme OpenCart


Wodpress Custom Post Type in Backend Menu not shown

Question: I have created a custom post type with https://generatewp.com/.
I can activate my Plugin, but in the backend menu nothing is displayed.
// Register Custom Post Type
function wp_rating_add_post_type() {

 $labels = array(
    'name'                  => _x( 'Ratings', 'Post Type General Name', 'wp-rating' ),
    'singular_name'         => _x( 'Rating', 'Post Type Singular Name', 'wp-rating' ),
    'menu_name'             => __( 'Ratings', 'wp-rating' ),
    'name_admin_bar'        => __( 'Ratings', 'wp-rating' ),
    'archives'              => __( 'Item Archives', 'wp-rating' ),
    'attributes'            => __( 'Item Attributes', 'wp-rating' ),
    'parent_item_colon'     => __( 'Parent Item:', 'wp-rating' ),
    'all_items'             => __( 'All Items', 'wp-rating' ),
    'add_new_item'          => __( 'Add New Item', 'wp-rating' ),
    'add_new'               => __( 'Add New', 'wp-rating' ),
    'new_item'              => __( 'New Item', 'wp-rating' ),
    'edit_item'             => __( 'Edit Item', 'wp-rating' ),
    'update_item'           => __( 'Update Item', 'wp-rating' ),
    'view_item'             => __( 'View Item', 'wp-rating' ),
    'view_items'            => __( 'View Items', 'wp-rating' ),
    'search_items'          => __( 'Search Item', 'wp-rating' ),
    'not_found'             => __( 'Not found', 'wp-rating' ),
    'not_found_in_trash'    => __( 'Not found in Trash', 'wp-rating' ),
    'featured_image'        => __( 'Featured Image', 'wp-rating' ),
    'set_featured_image'    => __( 'Set featured image', 'wp-rating' ),
    'remove_featured_image' => __( 'Remove featured image', 'wp-rating' ),
    'use_featured_image'    => __( 'Use as featured image', 'wp-rating' ),
    'insert_into_item'      => __( 'Insert into item', 'wp-rating' ),
    'uploaded_to_this_item' => __( 'Uploaded to this item', 'wp-rating' ),
    'items_list'            => __( 'Items list', 'wp-rating' ),
    'items_list_navigation' => __( 'Items list navigation', 'wp-rating' ),
    'filter_items_list'     => __( 'Filter items list', 'wp-rating' ),
 );
 $args = array(
    'label'                 => __( 'Rating', 'wp-rating' ),
    'description'           => __( 'Post Type Description', 'wp-rating' ),
    'labels'                => $labels,
    'supports'              => false,
    'hierarchical'          => false,
    'public'                => true,
    'show_ui'               => true,
    'show_in_menu'          => false,
    'show_in_admin_bar'     => true,
    'show_in_nav_menus'     => true,
    'can_export'            => true,
    'has_archive'           => true,
    'exclude_from_search'   => false,
    'publicly_queryable'    => true,
    'capability_type'       => 'post',
 );
 register_post_type( 'wp_rating', $args );

}
add_action( 'init', 'wp_rating_add_post_type', 0 );

Answer: You have this line in your code:
'show_in_menu' => false,

That should be true instead of false


Verificar se valor existe em array de objetos

Question: Possuo um array que é da seguinte maneira
[
  {
    "Param": 1,
    "Valor": 68
  },
  {
    "Param" 1,
    "Valor": 79
  },
  {
    "Param": 2,
    "Valor": 165
  }
]

Gostaria de saber como verificar se o numero (no Valor) existe no array, caso exista, eu removo, caso não exista, eu adiciono.
Estou fazendo isso ao marcar um checkbox, se eu marco, eu adiciono no array, se eu desmarco, eu retiro, não estou usando jQuery.
Meu código para adicionar
this.checkOne.push({
          "Param": check,
          "Valor": id
        })

Tentei fazer da seguinte maneira para retirar
this.checkOne.map(val => {
          if(val.Valor.indexOf(id) != -1){
            alert('Tem')
          }else{
            alert('nao tem')
          }
        })

Comment: Se é um `checkbox` que irá controlar, não basta verificar se ele está selecionado ou não? Pois se ele estava selecionado, o elemento deve existir, se não estava, você inserirá o valor.
Answer: Você chegou perto, só que o mapnão é o método mais adequado, porque foi feito para transformar uma array em outra. Para excluir você vai precisar do índice do elemento que será removido, então é melhor usar findIndex:

let checkOne = [
  {
    "Param": 1,
    "Valor": 68
  },
  {
    "Param": 1,
    "Valor": 79
  },
  {
    "Param": 2,
    "Valor": 165
  }
];

function adicionaOuRemove(id) {
  let index = checkOne.findIndex(val => val.Valor == id);
  if(index < 0) {
      checkOne.push({Param: 0, Valor: id});
  } else {
      checkOne.splice(index, 1);
  }
}

adicionaOuRemove(165); // existe
console.log(checkOne)

adicionaOuRemove(99);  // não existe
console.log(checkOne)
Comment: Eu não consegui entender o codigo, poderia explicar? e tambem não funcionou aqui, ele adiciona, mas nunca cai para remover, sempre dá como se não existisse o valor, mesmo depois de eu ter adicionado
Comment: Tinha um erro no meu código. Corrigi e ampliei o exemplo pra você ver funcionando. Qual parte do código você não entendeu?
Comment: Agora funcionou, valeu amigo :D
Answer: Uma forma bem simples de conseguir o resultado seria com uso de um comando de loop for. de forma bem simples você consegue iterar sobre todos os elementos do seu array de objetos e verificar com if se existe o valor na propriedade desejada. deixo um exemplo bem simples da solução.

var arr = [
  {
    "Param": 1,
    "Valor": 68
  },
  {
    "Param" :1,
    "Valor": 79
  },
  {
    "Param": 2,
    "Valor": 165
  }
]

function addOuRemoverObj(valor){

var encontrou = false;

for(var index = 0, total =arr.length; index < total; index++){

var obj = arr[index];

if(obj.Valor == valor){
    arr.splice(index,1);
    encontrou = true;
 break;
}

}

if(encontrou == false)
{
   arr.push({"Param":3, "Valor": valor});

}

console.log(arr);

}
//remove
addOuRemoverObj(79);

//adiciona
addOuRemoverObj(333);


How do I show a block with a unique QR for each node?

Question: There is requirement where I need to Place a Block on node where each block will be having the Unique QR code.
I created an hard-coded QR code block with the following code.
public function build() {
  $path = '';
  $directory = "public://Images/QrCodes/";
  \Drupal::service('file_system')->prepareDirectory($directory, \Drupal\Core\File\FileSystemInterface::CREATE_DIRECTORY);
  $qrName = 'myQrcode';
  $uri = $directory . 'QR'. '.png'; // Generates a png image.

  $path =  \Drupal::service('file_system')->realpath($uri);

  \PHPQRCode\QRcode::png("www.google.com", $path, 'L', 4, 2);

  $relative_file_url =  \Drupal::service('file_url_generator')
    ->generateAbsoluteString($uri);

  $qr_image = "";

  return [
    '#markup' => $qr_image,
  ];
}

The only issue is that I am not able to add the block to nodes nor to make the QR code dynamic.
It means that Each node will have a unique QR Code Block.
How to create a dynamic block inside hook_preprocess_node ?
Please Help
Comment: You first need to understand what a block and a node are and how they differ from a page. You can't "place a block on a node". Blocks are placed on a *page*, as part of the page display; that page might or might not *also* display a node.
Comment: So this was the original task linked in the question https://github.com/Dineshkushwaha/sph-test/blob/main/README.md, and it looks a little bit as if you let others do your homework.
Comment: And there's just a list of pull request with possible solutions. https://github.com/Dineshkushwaha/sph-test/pulls Maybe try to read and understand them first.
Comment: The answer to *How do I create a dynamic block inside `hook_preprocess_node()`?* is *You don't.* since `hook_preprocess_node()` isn't thought to create dynamic blocks.
Answer: This is the original description of the task (now removed from the question):

Build the following:

A Drupal content type to hold all their products
A Drupal block that can be placed on any product page. The block, when placed on any product page, automatically shows the currently
displayed product's App Purchase Link as a QR code, that the site
visitors can scan using their mobile.

You can use the current route to get the node and add a unique block for each node:
/src/Plugin/Block/ExampleBlock.php:
<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides an example block.
 *
 * @Block(
 *   id = "mymodule_example",
 *   admin_label = @Translation("Example"),
 *   category = @Translation("mymodule")
 * )
 */
class ExampleBlock extends BlockBase {

  public function build() {

    $build = [];

    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof \Drupal\node\NodeInterface) {
      // calculate $qr_image with $node
      $build = [
        '#markup' => $qr_image,
        '#cache' => ['tags' => $node->getCacheTags()],
      ];
    }

    $build['#cache']['contexts'] = ['route'];
    return $build;
  }
}

2. Version
Implementing the same block with a node context, as @leymann suggested:
/src/Plugin/Block/ExampleBlock.php:
<?php

namespace Drupal\mymodule\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides an example block.
 *
 * @Block(
 *   id = "mymodule_example",
 *   admin_label = @Translation("Example"),
 *   category = @Translation("mymodule"),
 *   context_definitions = {
 *     "node" = @ContextDefinition("entity:node")
 *   }
 * )
 */
class ExampleBlock extends BlockBase {

  public function build() {
    $node = $this->getContextValue('node');
    // calculate $qr_image with $node
    return [
      '#markup' => $qr_image,
    ];
  }

}

The advantage, you don't need to take care about caching, the context does this automatically. The disadvantage, you need to make the block dependent on a context when placing it in the block layout. Drupal is not yet able to map a block context automatically. You could, for example, add a visibility for the content type, which is probably a good idea anyway.
Comment: @leymannx, the context is a great idea and this removes any \Drupal calls, without DI ;-)
Comment: But How do I add block on node ?
Comment: Place the block in the right sidebar, according to [your plan](https://drupal.stackexchange.com/questions/310719/how-do-i-show-a-block-with-a-unique-qr-for-each-node/310724?noredirect=1#comment395068_310721). When you then visit a node the block will be displayed, with the QR-Code for that node. On other pages the block is empty and will be hidden.
Comment: (The node could be injected from context and \Drupal calls should be avoided. )
Comment: You can also add the block in Layout Builder if you are using it.
Answer:
The simple answer is: if you don't want/can't use the https://www.drupal.org/project/twig_tweak - then just copy the code of the drupal_block Twig extension from that module to your own module.

If that is not the case - just simply implement hook_preprocess_node and put your block build code there or load the block and send it to a node template via $variables.

Use the layout builder module (in core) to place the blocks on the node pages.
Comment: BTW, from your code I don't see how this connected to particular node.
Comment: I have searched a lot but not finding the way to place the block on nodes. Could you please help
Comment: found this https://stackoverflow.com/questions/43771500/using-preprocess-hook-on-specific-node-type-in-drupal-8..Trying now
Comment: Just copy the content of your block `build()` method to node preprocess and get rid of the block.
Comment: Added one more solution.
Comment: In problem statement, it is clearly mentioned that I have to make a use of Block and that block should be placed on right side bar, but thanks for your answers.
Answer: The Barcodes module https://www.drupal.org/project/barcodes provides a block displaying a barcode of any type, including QR code. This task is as simple as enabling the module then configuring the block to display what you want. No coding necessary. Barcodes supports tokens so you can dynamically encode and display a product ID, a node ID, or any other information in your barcode block.


Defining module.links.action.yml with route parameters

Question: How can I pass dynamically route parameters to module.links.action.yml?
My code of module.links.action.yml:
module.group_apply:
  route_name: module.group_apply
  title: 'Subscribe to group'
  weight: 0
  appears_on:
    - entity.node.canonical

My code of module.routing.yml:
module.group_apply:
  path: '/projects/{project}/usergroup/{group}/subscribe'
  defaults:
    _controller: '\Drupal\module\Controller\SubscriptionController::subscribe'
    _title: 'Apply'
  options:
    parameters:
      project:
        type: entity:node
      group:
        type: entity:node
  requirements:
    _permission: 'access content'

My subscibe function (actually):
public function subscribe(NodeInterface $project, NodeInterface $group) {
    return array(
        '#markup' => 'HERE WE GO!',
    );
}

Comment: I think you understand it now, alias != route, of course you can replace the missing parameters with fixed ones, but that's not the point
Comment: Can you explain a bit what are you trying to do?
Comment: /projects/{project}/
/projects/{project}/usergroup/{group}/
this pathes are node-views (contextual filtered by a node-id)

And I want to attach some functionality to the views as action links with the contextual attributes like:

http://www.url.com/projects/32/usergroup/45/subscribe

So that I can do some stuff with the information of 32 and 45 (two nodes)
Comment: This could work, if both routes, the appears_on and the target route have the same two parameters. But this is not what you have in the question.
Comment: Excuse me, my comment above is wrong. /project is a view -  /project/{project} is a node - /projects/{project}/usergroup/ is a view - /projects/{project}/usergroup/{group} is a node. And i want to insert that action link on the node page of /projects/{project}/usergroup/{group}.
Comment: yes, exactly, you can place on the page `/projects/{project}/usergroup/{group}` an action link for `/projects/{project}/usergroup/{group}/subscribe`, the target link will pick up the route parameters if they match
Comment: Thats interesting, because I get this error:
Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("project", "group") to generate a URL for route "module.group_apply". in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 171 of /var/www/vhosts/xxx/xxx/drupal/core/lib/Drupal/Core/Routing/UrlGenerator.php).
That isn't the problem of the module.routing.yml, because I can navigate to /projects/{project}/usergroup/{group}/subscribe without errors. This error appears on the nodepage, where the link should appear.
Comment: so you still try to place the action link on the page `entity.node.canonical` = `/node/{node}`
Comment: Thats right, but the URL-Alias is: projects/[node:field_related_project:target_id]/user-groups/[node:nid]
And the link should only appear on Node-Pages of Type "Group". Not on the node pages of project or other node types.
Comment: you can't place a link action on an alias, only on routes, it would be no problem to define a route with the two parameters
Comment: I can. If I would append `route_parameters project: 12 group: 2` to module.links.action.yml. It would work. But then, these parameters are fixed - but I need these link parameters dynamically, based on url parameters.
Comment: So it's right, that I've to define a route for the node "group"?
Like:
`module.group.canonical:
  path: '/projects/{project}/user-groups/{group}'
  defaults:
    _entity_view: group.default
    _title: 'Node'
  options:
    parameters:
      project:
        type: entity:node
      group:
        type: entity:node
  requirements:
    _permission: 'access content'`
And then delete the url alias pattern for this nodetype?
Comment: yes, and a custom node view controller, or use {node} instead of {group}
Answer: 1、you can add class to process as follows:

2、you can debug in getRouteParameters function, localAction.php content as follows:
Answer: I was on the wrong track the whole time.
The right way is to use entity.node.canonical as route (/node/{node}) and using other variables from node itself in the subscribe function ($node).
Thank you @4k4 for your help.


How to make a user not being able to publish his content?

Question: how is this possible to make a user/role not being able to publish content he has created ,but to be able to create new (unpublished) content?
thanks
Comment: Workbench moderation module has a lot of configuration options for publishing workflows. Perhaps that would help? https://drupal.org/project/workbench_moderation
Answer: How about [implementing hook_node_presave($node)][1] in your custom module,so as example code consider the following
function mymodulename_node_presave($node) {
  global $user;
  // check if user has role and checking node->original is not set ensures it works only when insertion of node happens not when it is edited
  if (in_array("your_user_role",$user->roles) && (!isset($node->original))) {
    // keep the node unpublished
    $node->status = 0;
  }
}

Answer: You can achieve this functionality using below step.

Go to Administration -> Structure -> types.
Edit your content type.
Uncheck 'Published' check-box under 'Publishing options' fieldset in the form.

Now, when any user except administrator of the site, create new content, by default content be unpublished. Only administrator or user which has permission to override publishing options, can published or modify publishing options.
If you would like use to access their unpublished content, you need to provide access 'View own unpublished content' to user role.
Answer: I think I found this,with these two modules https://drupal.org/project/publishcontent
and https://drupal.org/project/override_node_options
Answer: One way of doing the same is using the hook_node_presave() and set the node to unpublish for certain users/roles as below:
/**
 * Implements hook_node_presave().
 */
function MyModule_node_presave($node) {
  global $user;
  $user_id = $user->uid;

  // Check if the author of node is user whose content you want to unpublish,
  // similarly for checking the user role: "in_array("USER_ROLE_TO_CHECK",$user->roles)"
  // To add the add check for content type, add "$node->type === 'CONTENT_TYPE'"
  if (($user_id === 'USER_ID_WHOSE_CONTENT_IS_TO_BE_UNPUBLISHED') && (!isset($node->original))) {
    // Unpublish nodes when node is created:
    $node->status = 0;
  }
}

This will always unpublish the content created by the user belonging to that user_ids/roles.

Alternatively you can use the Override node options module: The Override Node Options module allows permissions to be set to each field within the Authoring information and Publishing options field sets on the node form.


Interpretation of absolute value of ADE in mediatoin analysis

Question: I'm quite new to mediation analysis and try to understand the results I get. I have a new online shop feature I tested in a randomized field experiment. The treated group sees the new feature and the control group does not see the new feature. I now estimated the effect of the new feature on the order value of all customers who order something. For this, I use a Poisson Model that estimates the value of an order in Cents (outcome variable) and the binary treatment variable (cents ~ treatment). The coefficients are as follows:
<code>            Estimate Std. Error z value Pr(>|z|)
(Intercept) 7.644134   0.001836  4162.7   <2e-16 ***
treatTrue   0.139755   0.002465    56.7   <2e-16 ***
</code>
I expect the number of articles a customer visits to be a mediation variable. I checked whether this is a potential mediator by first running a Poisson regression on the number of articles (articles ~ treatment) and see that it is slightly significant:
<code>        Estimate Std. Error z value Pr(>|z|)
(Intercept)  0.92750    0.05278  17.574   <2e-16 ***
treatTrue   -0.13845    0.07573  -1.828   0.0675 .
</code>
Next, I run a poisson regression on the order value using the mediator (articles) and get the following results:
<code>              Estimate Std. Error z value Pr(>|z|)
(Intercept)  7.6628604  0.0015380 4982.40   <2e-16 ***
articles     0.0227628  0.0003569   63.77   <2e-16 ***
</code>
If I now run the mediation analysis (using the r mediation package), I get the following output:
<code>                        Estimate 95% CI Lower 95% CI Upper p-value
ACME (control)           -16.2655     -38.0539         5.43    0.14
ACME (treated)           -18.8448     -44.1006         6.29    0.14
ADE (control)            330.5374     319.5988       341.73  <2e-16 ***
ADE (treated)            327.9581     317.1875       338.83  <2e-16 ***
Total Effect             311.6926     286.8376       337.21  <2e-16 ***
</code>
How do I interpret the absolute values of ACME, ADE, and total effect? I understand that ACME is not significant and it is the Total Effect - ADE. But how do I come from the very first regression (cents ~ treatment) with its estimates of 7.6 for the intercept and 0.14 for the treatment variable to the total effect of 312?
Thank you very much :)
Answer: The mediation package reports all effects as mean differences on the units of the predictor. So the total effect of 312 means the treatment increases the order value by 312 (whatever units those are; "cents", I guess). The coefficient on treatment in a Poisson regression of the outcome on the treatment is the log of the treatment effect on the ratio scale; that is, the treatment has an average outcome $\exp(0.139755)=1.15$ times that of the control group.
Note that the regression of the outcome on the mediator alone is unrelated to mediation analysis; you need to include the treatment variable in that model to arrive at any conclusion about mediation.
I urge you to bootstrap the standard errors since the usual Poisson regression standard errors are very sensitive to the assumptions of Poisson regression (the conditional mean equals the conditional variance).


How can I modify this function to use multiple tabs and columns for each tab?

Question: I am using this function to copy down columns.

function copyDown4() {

var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var tabs = ['Imported'];
  var columns = [9];
  if(tabs.indexOf(activeSheet.getName()) !== -1){
  var cell = activeSheet.getActiveCell();
  var col = cell.getColumn();
    if(columns.indexOf(col) !== -1){
      if(cell.getFormula() !== ""){
    var destination = activeSheet.getRange(2, col, activeSheet.getLastRow()-1, 1);
        cell.copyTo(destination)
      }
    }
  }
}

How can I modify it so, rather than creating multiple copies of this function, I can include multiple tabs each with their own specific column numbers?
I assume I can add more tabs simply with this
var tabs = ['Imported','Another','And Another'];
  var columns = [9];

But I'm not sure about the columns. Thanks for any help with this.
Comment: In your current script, it seems that the value of the active cell is copied to from the row 2 to last row for the column at the active cell. You want to run this script at the several sheets and several columns by modifying the script. Is my understanding correct? If my understanding is correct, for example, how about modifying `var tabs = ['Imported','Another','And Another'];` and `var columns = [9, 10, 11];`? In this modification, the sheet can be selected by `if(tabs.indexOf(activeSheet.getName()) !== -1)`, and the column can be selected by `if(columns.indexOf(col) !== -1)`.
Answer: To include multiple tabs each with their own specific column numbers, you can create a dictionary.
function copyDown4() {
  var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var tabs = {
    'Imported': [9],
    'Another': [10, 11],
    'And Another': [12, 17]
  };
  var currentName = activeSheet.getName();
  if (! tabs[currentName]) { // not in the dictionary, abort
    return;
  }
  var cell = activeSheet.getActiveCell();
  var col = cell.getColumn();
  if (tabs[currentName].indexOf(col) === -1) { // not in the dictionary, abort
    return;
  }
  if (cell.getFormula() !== "") {
    cell.copyTo(activeSheet.getRange(2, col, activeSheet.getLastRow()-1, 1));
  }
}

Comment: Thank you very much. Both these answers seem to work. However, further to this, what if one tab starts on a different row. Is there a way to accommodate that also?
Comment: @StephenCousins I'd be happy to help, but can you clarify what you mean by "what if one tab starts on a different row?" and how the current solution fails?
Answer: You need to "bind" the column numbers to the tab names

You can create two arrays - tabs and columns, whereby the order of the column numbers in columns should correspond to the one of the sheets in `tabs
You check with tabs.indexOf(activeSheet.getName()) which to which array position the active sheet corresponds
You get the column number corresponding to this array position, and thus to the present tab

function copyDown4() {
var activeSheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var tabs = ['Imported','Another','And Another'];
var columns = [9,4,7];  //as example
if(tabs.indexOf(activeSheet.getName()) !== -1){
  var column=columns[tabs.indexOf(activeSheet.getName())];
  var cell = activeSheet.getActiveCell();
  var col = cell.getColumn();
    if(col==column){
      if(cell.getFormula() !== ""){
        var destination = activeSheet.getRange(2, col, activeSheet.getLastRow()-1, 1);
        cell.copyTo(destination)
      }
    }
  }
}


Auto login to LinkedIn

Question: I have installed HybridAuth module. I can login from my website using LinkedIn. But my question is, how can I login automatically into LinkedIn when I login from my website using LinkedIn login?
I have gone though various APIs but could not get proper information.
Comment: Nope, that's only my guess and not my knowledge. If someone can do a bit of research, please do and post answer. If no, I'll try to elaborate... in about 8 hours from now, when I'll have more time. Not enough time now.
Comment: I don't think it is possible. Opposite (auto-login if you already are logged to LinkedIn) should be possible, if you decided to trust LinkedIn. But why LinkedIn should trust you?
Comment: Thanks Molot for a reply. can you add this as an answer with some more information so that I can accept ?
Answer: Got something closely related to your case and I won't say this is not possible, you can have some workaround by following these threads:
Login to Drupal using LinkedIn
This feature is not available right now, to login into Linkedin while using its credential on your site. But it seems that, this thread is in knowledge of Linkedin Officials as well and there may be some work is going on to provide you create app feature just like Facebook.
Here is something to elaborate the same:
http://developer.linkedin.com/forum/how-create-linkedin-application-tripit-or-slideshare
Answer: This is only done with both website communicate each other. It means that your website and linkedin both assured each other credential information and surely linkedin cant trust your website so it is not possible

Auto login to LinkedIn


Solve the equation $\sqrt[3]{15-x^3+3x^2-3x}=2\sqrt{x^2-4x+2}+3-x$.

Question: Solve the equation $\sqrt[3]{15-x^3+3x^2-3x}=2\sqrt{x^2-4x+2}+3-x$.
I have tried to solve for x by Casio and try to make the equation to $u.v=0$ but the solution is not in $\mathbb{Q}$. Any help is appreciated. Thanks
Comment: potentially interesting rewrite, but now sure how useful yet $$\sqrt[3]{14 - (x-1)^3} = 2\sqrt{(x-2)^2-2} - (x-3)$$
Comment: I have rewrite this but I'm stuck now
Answer: For the square root to be defined we need:
$$x^2-4x+2\geq 0$$
Therefore, we have:
$$2\sqrt{x^2-4x+2} = x-3+\sqrt[3]{15-x^3+3x^2-3x}=$$
$$=\frac{(x-3)^3+15-x^3+2x^2-3x}{(x-3)^2-(x-3)\sqrt[3]{15-x^3+3x^2-3x}+\sqrt[3]{(15-x^3+3x^2-3x)^2}}$$
$$=\frac{-6(x^2-4x+2)}{(x-3)^2-(x-3)\sqrt[3]{15-x^3+3x^2-3x}+\sqrt[3]{(15-x^3+3x^2-3x)^2}}\leq 0$$
The numerator is negative $x^2-4x+2 \geq 0 \Rightarrow -6(x^2-4x+2)\leq 0$.  The denominator is of the form $a^2-ab+b^2$ which is always non-negative because:
$$a^2-ab+b^2=\frac{1}{2}[a^2+b^2+(a-b)^2]\geq 0$$
And thus $x^2-4x+2=0$ which means $x=2\pm\sqrt{2}$.
Comment: Can you explain more why it's $\le 0$?
Comment: @NguyenThy, Because the numerator is negative. $x^2-4x+2 \geq 0 \Rightarrow -6(x^2-4x+2)\leq 0$
Comment: How about determinator ?
Comment: @NguyenThy, I edited to add more detail.
Comment: I see. Thank you very much.


Solving three alike problems $a_{n+1} = \frac{1+a_n^2}{1+a_n}$

Question: I have two problems alike:

If $a_1=a$, $a>0$, $a_{n+1} = \dfrac{1+a_n^2}{1+a_n}$, study its convergence.
If $a_0 >0$, $a_1>0$ and $a_{n+2} = \dfrac{2+a_{n+1}}{2+a_n}$, study this one's convergence.

I can solve this using two different situations: when $a$ is between $0$ and $1$ and when $a$ is between $1$ and $+\infty$ for the first problem and then say it is monotonic and it has an lower bond, therefore is convergent. But for me this solution does not help for the second, similar problem. Could you either show me how to solve the second one, not necessarily using my way, or show me a method that works for both? Thank you.
Comment: BTW, the second one is a [duplicate](https://math.stackexchange.com/questions/2174888/prove-that-if-x-n2-frac2x-n12x-n-then-x-n-converges)
Comment: What do $x_0, x_1$ have to do with the second problem?  Should that be $a_0, a_1?$
Comment: Yes, sorry. I`ve corrected. Thanks.
Comment: If you have three questions, you should ask three questions. They aren't any more similar than any two mathematical problems, non-linear recurrences are very rarely "similar".
Comment: I have changed the formatting of the title so as to
[make it take up less vertical space](https://math.meta.stackexchange.com/a/9686/290189) --
this is a policy to ensure that the scarce space on the main page is distributed evenly over the questions.
See [here](https://math.meta.stackexchange.com/a/9730) for more information. Please take this into consideration for future
questions. Thanks in advance.
Answer: Too many questions. I'll take the 1st one.
Evidently $a_n>0\Rightarrow a_{n+1}=\frac{1+a_n^2}{1+a_n}>0$
Also $a_n>1\Rightarrow a_n^2>a_n\Rightarrow a_{n+1}=\frac{1+a_n^2}{1+a_n}>1$
and $a_n<1\Rightarrow a_n^2<a_n\Rightarrow a_{n+1}=\frac{1+a_n^2}{1+a_n}<1$
Now $a_{n+1}-a_{n}=\frac{1-a_n}{1+a_n}$
So if $a>1$ then $a_n$ is decreasing and bounded $a_n>1$ and if
$a<1$ then $a_n$ is increasing and bounded $a_n<1$
In both cases it convergs, say , to $L$. By taking limits in both sides of $a_{n+1}=\frac{1+a_n^2}{1+a_n}$ we have $L=\frac{1+L^2}{1+L}\Rightarrow L=1$
The case $a=1$ is trivial : $a_n=1$
Answer: Hint with the 2nd one, it is easy to show by induction that $a_n>0$, then
$$\color{red}{0<a_{n+2}}=\frac{2+a_{n+1}}{2+a_{n}}<
\frac{2+a_{n+1}}{2}=
1+\frac{a_{n+1}}{2}<
1+\frac{1+\frac{a_{n}}{2}}{2}=
1+\frac{1}{2}+\frac{a_n}{2^2}<\\
1+\frac{1}{2}+\frac{1}{2^2}+\frac{a_{n-1}}{2^3}<...<\\
1+\frac{1}{2}+\frac{1}{2^2}+...+\frac{1}{2^{n}}+\frac{a_{1}}{2^{n+1}}\color{red}{<
2+\frac{a_{1}}{2^{n+1}}}$$
so $(a_n)$ is bounded. More to come later ...