#StackBounty: #bayesian #model-comparison Test for comparing log likelihoods that include error terms

Bounty: 50

Suppose I have two models with likelihoods calculated through thermodynamic integration. thermodynamic_integration_log_evidence in PTSampler returns both an estimate of the integral and an error term for it, which the docs say arises from sampling at a finite number of temperatures.

If I was confident in the likelihoods $L_1, L_2$ for my models $M_1,M_2$ then I could just compute the Bayes factor $L_1/L_2$ (or $exp(LL_1-LL_2)$ for log likelihoods) to see how many times more likely is $M_1$ than $M_2$.

But as $L_1, L_2$ come with corresponding errors $sigma_{L1}, sigma_{L2}$ how can I take these into account in the comparison?


Get this bounty!!!

#StackBounty: #apt #package-management #dependencies #compiling Which package provides -lGL on Ubuntu 18.04?

Bounty: 100

I’m trying to install the pip3 python package wxpython which fails due to

g++ -shared -fPIC -o /tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib/libwx_gtk3u_gl-3.0.so.0.4.0  gldll_glcmn.o gldll_glx11.o gldll_gtk_glcanvas.o    -L/tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib   -Wl,-soname,libwx_gtk3u_gl-3.0.so.0  -pthread         -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpango-1.0 -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lgthread-2.0 -pthread -lglib-2.0 -lX11 -lXxf86vm -lSM -lgtk-3 -lgdk-3 -lpangocairo-1.0 -lpango-1.0 -latk-1.0 -lcairo-gobject -lcairo -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lnotify -lgdk_pixbuf-2.0 -lgio-2.0 -lgobject-2.0 -lglib-2.0 -lpng -lz -ljpeg -ltiff  -lwxregexu-3.0  -pthread   -Wl,--version-script,/tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/version-script -lz -ldl -lm  -lwx_gtk3u_core-3.0 -lwx_baseu-3.0  -lGL -lGLU -lz -ldl -lm
(cd /tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib/; rm -f libwx_gtk3u_html-3.0.so libwx_gtk3u_html-3.0.so.0; ln -s libwx_gtk3u_html-3.0.so.0.4.0 libwx_gtk3u_html-3.0.so.0; ln -s libwx_gtk3u_html-3.0.so.0 libwx_gtk3u_html-3.0.so)
(cd /tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib/; rm -f libwx_gtk3u_stc-3.0.so libwx_gtk3u_stc-3.0.so.0; ln -s libwx_gtk3u_stc-3.0.so.0.4.0 libwx_gtk3u_stc-3.0.so.0; ln -s libwx_gtk3u_stc-3.0.so.0 libwx_gtk3u_stc-3.0.so)
(cd /tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib/; rm -f libwx_gtk3u_webview-3.0.so libwx_gtk3u_webview-3.0.so.0; ln -s libwx_gtk3u_webview-3.0.so.0.4.0 libwx_gtk3u_webview-3.0.so.0; ln -s libwx_gtk3u_webview-3.0.so.0 libwx_gtk3u_webview-3.0.so)
/usr/bin/x86_64-linux-gnu-ld: -lGL kann nicht gefunden werden
collect2: error: ld returned 1 exit status
Makefile:16113: recipe for target '/tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib/libwx_gtk3u_gl-3.0.so.0.4.0' failed
make: *** [/tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib/libwx_gtk3u_gl-3.0.so.0.4.0] Error 1
make: *** Auf noch nicht beendete Prozesse wird gewartet …
(cd /tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib/; rm -f libwx_gtk3u_adv-3.0.so libwx_gtk3u_adv-3.0.so.0; ln -s libwx_gtk3u_adv-3.0.so.0.4.0 libwx_gtk3u_adv-3.0.so.0; ln -s libwx_gtk3u_adv-3.0.so.0 libwx_gtk3u_adv-3.0.so)
g++ -o wxrc wxrc_wxrc.o    -L/tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/lib  -pthread     -lwx_baseu_xml-3.0 -lexpat -lwx_baseu-3.0     -lwxregexu-3.0  -pthread   -Wl,--version-script,/tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/version-script -lz -ldl -lm  -lz -ldl -lm
make[1]: Verzeichnis „/tmp/pip-build-c0hbjq4b/wxpython/build/wxbld/gtk3/utils/wxrc“ wird verlassen
Error building
ERROR: failed building wxWidgets
Traceback (most recent call last):
  File "build.py", line 1295, in cmd_build_wx
    wxbuild.main(wxDir(), build_options)
  File "/tmp/pip-build-c0hbjq4b/wxpython/buildtools/build_wxwidgets.py", line 498, in main
    exitIfError(wxBuilder.build(dir=buildDir, options=args), "Error building")
  File "/tmp/pip-build-c0hbjq4b/wxpython/buildtools/build_wxwidgets.py", line 85, in exitIfError
    raise builder.BuildError(msg)
buildtools.builder.BuildError: Error building
Finished command: build_wx (3m27.477s)
Finished command: build (3m27.478s)
Command '"/usr/bin/python3" -u build.py build' failed with exit code 1.

----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-c0hbjq4b/wxpython/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-dt7af70p-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-c0hbjq4b/wxpython/

libgl-dev referes to libgl1-mesa-dev which is already installed as well as libglw1-mesa-dev which seems the only other possible candidate based on the auto-completion of sudo apt-get install libgl.


Get this bounty!!!

#StackBounty: #android #android-studio #android-productflavors Product flavors in Android Studio

Bounty: 100

I can not get product flavours working. I have this gradle

apply plugin: 'com.android.application'
android {
    defaultConfig {
      minSdkVersion 14
      targetSdkVersion 24
      compileSdkVersion 27
    }
    signingConfigs {
        release {
      }
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
            signingConfig signingConfigs.release
        }
    }
    repositories {
        maven { url "https://jitpack.io" }
    }
    flavorDimensions "dim1", "dim2", "dim3"
    productFlavors {
        flavor1 {
            dimension "dim1"
            applicationId "com.example.dim1.app"
        }
        flavor3 {
            dimension "dim2"
            applicationId "com.example.dim2.app"
        }
        flavor3 {
            dimension "dim3"
            applicationId "com.example.dim3.app"
        }
    }
    sourceSets {
        flavor1 {
          java.srcDirs = ["W:/android-studio-projects/sharedid/app/src/main/java/"]
          manifest.srcFile "W:/android-studio-projects/sharedid/app/src/example1/AndroidManifest.xml"
          assets.srcDirs = ["W:/android-studio-projects/sharedid/app/src/example1/assets/"]
          resources.srcDirs = ["W:/android-studio-projects/sharedid/app/src/main/res/", "W:/android-studio-projects/sharedid/app/src/example1/res/"]
        }
        flavor2 {
          manifest.srcFile "W:/android-studio-projects/sharedid/app/src/example2/AndroidManifest.xml"
          manifest.srcFile "W:/android-studio-projects/sharedid/app/src/example2/AndroidManifest.xml"
          assets.srcDirs = ["W:/android-studio-projects/sharedid/app/src/example2/assets/"]
          resources.srcDirs = ["W:/android-studio-projects/sharedid/app/src/main/res/", "W:/android-studio-projects/sharedid/app/src/example2/res/"]
        }
        flavor3 {
          manifest.srcFile "W:/android-studio-projects/sharedid/app/src/example3/AndroidManifest.xml"
          manifest.srcFile "W:/android-studio-projects/sharedid/app/src/example3/AndroidManifest.xml"
          assets.srcDirs = ["W:/android-studio-projects/sharedid/app/src/example3/assets/"]
          resources.srcDirs = ["W:/android-studio-projects/sharedid/app/src/main/res/", "W:/android-studio-projects/sharedid/app/src/example3/res/"]
        }
    }
}
dependencies {
    api 'com.google.android.gms:play-services-maps:15.0.0'
    api 'com.google.android.gms:play-services-location:15.0.0'
    api 'com.android.support:appcompat-v7:27.1.1'
    api 'com.github.PhilJay:MPAndroidChart:v2.0.8'

}

When I got to “Build | Select variant” I can only select

Module:app
Build Variant:flavor1Flavor2Flavor3Debug,flavor1Flavor2Flavor3Release

I would have liked to get

  • the following build variants: flavor1Debug,flavor2Debug,flavor3Debug,flavor1Release,flavor2Release,flavor3Release

I have tried “File | Sync project with gradle file”

I get this error

Caused by: java.lang.RuntimeException: Cannot read packageName from
W:android-studio-projectssharedidappsrcmainAndroidManifest.xml

I have tried to both

  • have no such file (hoping it would take the product flavor one?)
  • have the “main” manifest only define shared stuff between all product flavors


Get this bounty!!!

#StackBounty: #ubuntu #ansible No package matching 'docker-ce' is available with ansible

Bounty: 50

On ubuntu 18.04 I am running this ansible (version 2.5.1) role:

---
- name: Add Docker apt repository key.
  apt_key:
    url: "https://download.docker.com/linux/ubuntu/gpg"
    state: present

- name: gather facts
  setup:    

- name: Set the stable docker repository
  apt_repository: 
    repo: "deb [arch=amd64] https://download.docker.com/linux/ubuntu {{ ansible_lsb.codename }} stable"
    state: present
    update_cache: yes    

- name: Install Docker
  apt:
    name: docker-ce
    state: present

With this playbook:

---


- hosts: localhost
  connection: local
  gather_facts: False
  become: true

  pre_tasks:
  - name: Install python for Ansible
    raw: test -e /usr/bin/python || (apt -y update && apt install -y python-minimal)

  tasks:  
  - name: Install list of packages
    apt: name={{item}} state=latest
    with_items:
         - nano
         - git
         - htop
         - gitg

  roles:
      - {role: 'docker', tags: 'docker'}

But I get the following error:

PLAY [localhost] *******************************************************************************************************************************

TASK [Install python for Ansible] **************************************************************************************************************
changed: [localhost]

TASK [docker : Add Docker apt repository key.] *************************************************************************************************
ok: [localhost]

TASK [docker : gather facts] *******************************************************************************************************************
ok: [localhost]

TASK [docker : Set the stable docker repository] ***********************************************************************************************
ok: [localhost]

TASK [docker : Install Docker] *****************************************************************************************************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "No package matching 'docker-ce' is available"}
    to retry, use: --limit @/home/user/repos/ansible-vps/src/ansible_create_workstation.retry

PLAY RECAP *************************************************************************************************************************************
localhost                  : ok=4    changed=1    unreachable=0    failed=1   

So for some reason the docker-ce package cannot be found, has that changed recently or is it something else I am doing wrong?

Also when I look in: /etc/apt/sources.list it does not contain a:

deb [arch=amd64] https://download.docker.com/linux/ubuntu  ...

entry.


Get this bounty!!!

#StackBounty: #networking #tcp #protocols Computer networking: During what transmission round is the 70th segment sent?

Bounty: 50

While practicing some exercises I came across the following exercises that I just can’t wrap my head around. Looking at the solution, I don’t get how they reach to the conclusion that packet 32 to 63 are sent in the 6th transmission round. How was 63 computed?

enter image description here

During what transmission round is the 70th segment sent?

Solution:

During the 1st transmission round, packet 1 is sent; 
packet 2-3 are sent in the 2nd transmission round; 
packets 4-7 are sent in the 3rd transmission round; 
packets 8-15 are sent in the 4th transmission round;
packets 16 to 31 are sent in the 5th transmission round; 
packets 32 to 63 are sent in the 6th transmission round; 
packets 64 to 96 are sent in the 7th transmission round. 
Thus packet 70 is sent in the 7th transmission round.


Get this bounty!!!

#StackBounty: #magento2 #multistore #locale #magento2.2.4 Resolver does not report correct locale

Bounty: 50

I have a very strange problem where the MagentoFrameworkLocaleResolver does not return the correct locale for the current store view.

I have setup a store with two separate store views which have locales set to English and Swedish. I have also configured the stores to append the store code to the current URL.

class Example {
  /** @var MagentoStoreModelStoreManagerInterface */
  private $storeManager;

  /** @var MagentoFrameworkLocaleResolver */
  private $resolver;

  public function __construct(StoreManagerInterface $storeManager,
                              Resolver $resolver)
  {
     $this->storeManager = $storeManager;
     $this->resolver = $resolver;
  }

  public function getLocale()
  {
     return $this->resolver->getLocale();
  }
}

In the above code the getLocale() always returns the locale of the default store view. I managed to solve this by using the ScopeConfigInterface like this:

$this->scopeConfig->getValue(
  'general/locale/code', 
   ScopeInterface::SCOPE_STORE,
   $this->storeManager->getStore()->getId()
);

Even though the above works I really would like to know why the resolver returns the incorrect locale for the current store? I am thinking that this might be some kind of weird caching issue, I have tried all the following without any success:

php bin/magento cache:clean
php bin/magento cache:flush
php bin/magento setup:di:compile
php bin/magento setup:upgrade
php bin/magento indexer:reindex


Get this bounty!!!

#StackBounty: #python #python-3.x #security #authentication #django Let's register that Django user

Bounty: 200

Short intro

So, I’ve been using Django for a while now and thought it would be nice to start a simple application. In an ideal World, each app must have a way of letting its users register and that’s what I’m gonna do below.


Description

I’ve used the latest Django version for this project -> because of this, I couldn’t use django-registration module as it’s incompatible with the above. Apart from this, I’ve used Python 3.6.5.

What I want to do it’s common along other web applications:

  1. The user goes to the registration page and fills in the following fields:
    • first_name
    • last_name
    • email
  2. The user submits the form and receives a confirmation email with an URL containing a unique token.

  3. When the user clicks on the received link, he’s redirected to a page where he’ll set his password.

  4. When done, he’s logged in to the dashboard page.


Code

models.py

from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.db import models
from django.utils.translation import ugettext_lazy as _


class UserManager(BaseUserManager):
    """
    A custom user manager to deal with emails as unique identifiers for auth
    instead of usernames. The default that's used is "UserManager"
    """

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """

        if not email:
            raise ValueError('The Email must be set')

        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)

        return user

    def create_user(self, email, password=None, **extra_fields):
        """
        Create and save a regular User with the given email and password.
        """

        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_superuser', False)

        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        """
        Create and save a SuperUser with the given email and password.
        """

        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(unique=True, null=True, max_length=64)
    first_name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)

    is_staff = models.BooleanField(
        _('staff status'),
        default=False,
        help_text=_('Designates whether the user can log into this site.'),
    )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_(
            'Designates whether this user should be treated as active. '
            'Unselect this instead of deleting accounts.'
        ),
    )
    USERNAME_FIELD = 'email'
    objects = UserManager()

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.email

forms.py

from django.contrib.auth import get_user_model
from django.forms import ModelForm

User = get_user_model()


class RegistrationForm(ModelForm):

    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name')

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        if commit:
            user.save()
        return user

views.py

from django.contrib import messages
from django.contrib.auth import update_session_auth_hash, get_user_model, authenticate, login
from django.contrib.auth.forms import AuthenticationForm, SetPasswordForm
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView, LogoutView
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from django.views.generic import TemplateView, View

from .forms import RegistrationForm
from .tokens import account_activation_token

User = get_user_model()


class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'base/home.html'


class CustomLoginView(LoginView):
    template_name = 'base/login.html'
    form_class = AuthenticationForm


class CustomLogoutView(LogoutView):
    template_name = 'base/login.html'


class RegistrationView(View):

    def get(self, request):
        registration_form = RegistrationForm()
        return render(request, 'base/register.html', {'form': registration_form})

    def post(self, request):
        registration_form = RegistrationForm(request.POST)

        if registration_form.is_valid():
            user = registration_form.save(commit=False)
            user.is_active = False
            user.set_unusable_password()
            user.save()

            current_site = get_current_site(request)
            mail_subject = 'Activate your account.'
            message = render_to_string('base/activation-email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(),
                'token': account_activation_token.make_token(user),
            })
            to_email = registration_form.cleaned_data.get('email')
            email = EmailMessage(
                mail_subject, message, to=[to_email]
            )
            email.send()

            return render(request, 'base/confirm-email.html')


class ActivationView(View):

    def get(self, request, uidb64, token):
        try:
            uid = force_text(urlsafe_base64_decode(uidb64))
            user = User.objects.get(pk=uid)
        except(TypeError, ValueError, OverflowError, User.DoesNotExist):
            user = None

        if user is not None and account_activation_token.check_token(user, token):
            user.is_active = True
            user.save()
            login(request, user)

            form = SetPasswordForm(request.user)
            return render(request, 'base/password-set.html', {'form': form})
        else:
            return render(request, 'base/verification-failed.html')

    def post(self, request, uidb64, token):

        try:
            uid = force_text(urlsafe_base64_decode(uidb64))
            user = User.objects.get(pk=uid)
        except(TypeError, ValueError, OverflowError, User.DoesNotExist):
            user = None

        form = SetPasswordForm(user, request.POST)

        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)

            user = authenticate(username=user.email, password=form.cleaned_data['new_password1'])
            login(request, user)

            return HttpResponseRedirect('/')
        else:
            messages.error(request, form.errors)
            return render(request, 'base/password-set.html', {'form': form})

urls.py

from django.conf.urls import url
from django.views.generic import TemplateView

from .views import (
    CustomLoginView, CustomLogoutView, HomeView, 
    RegistrationView, ActivationView
)

app_name = 'apps.base'

urlpatterns = [
    url(r'^$', HomeView.as_view(), name='home'),

    url(r'^login/$', CustomLoginView.as_view(), name='login'),
    url(r'^logout/$', CustomLogoutView.as_view(), name='logout'),

    url(r'^register/$', RegistrationView.as_view(), name='register'),
    url(r'^confirm_email/$', TemplateView.as_view(template_name='base/confirm-email.html'), name='confirm_email'),
    url(r'^activate/(?P<uidb64>[0-9A-Za-z_-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        ActivationView.as_view(), name='activate'),
]

tokens.py

from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.utils import six


class TokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.is_active)
        )


account_activation_token = TokenGenerator()

Things that I’d like to be reviewed:

  • Django Design Patterns: Did I use the correct views / forms / models in my app? Should some of the logic be written somewhere else etc…
  • Security: Is my register system secure? If not, what can I do to make it so?
  • General feedback: Anything that comes to your mind is welcome (including criticism, ideas, improvements, cats…aliens..)


Get this bounty!!!