<commit_before>import random

from django.conf import settings
from django.db import IntegrityError
from django.db import models
from django.dispatch import Signal
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from .settings import (
    COUPON_TYPES,
    CODE_LENGTH,
    CODE_CHARS,
    SEGMENTED_CODES,
    SEGMENT_LENGTH,
    SEGMENT_SEPARATOR,
)

try:
    user_model = settings.AUTH_USER_MODEL
except AttributeError:
    from django.contrib.auth.models import User as user_model
redeem_done = Signal(providing_args=["coupon"])

class CouponManager(models.Manager):
    def create_coupon(self, type, value, users=[], valid_until=None, prefix="", campaign=None, user_limit=None):
        coupon = self.create(
            value=value,
            code=Coupon.generate_code(prefix),
            type=type,
            valid_until=valid_until,
            campaign=campaign,
        )
        if user_limit is not None:  # otherwise use default value of model
            coupon.user_limit = user_limit
        try:
            coupon.save()
        except IntegrityError:
            # Try again with other code
            coupon = Coupon.objects.create_coupon(type, value, users, valid_until, prefix, campaign)
        if not isinstance(users, list):
            users = [users]
        for user in users:
            CouponUser(user=user, coupon=coupon).save()
        return coupon

    def create_coupons(self, quantity, type, value, valid_until=None, prefix="", campaign=None):
        coupons = []
        for i in range(quantity):
            coupons.append(self.create_coupon(type, value, None, valid_until, prefix, campaign))
        return coupons

    def used(self):
        return self.exclude(users__redeemed_at__isnull=True)

    def unused(self):
        return self.filter(users__redeemed_at__isnull=True)

    def expired(self):
        return self.filter(valid_until__lt=timezone.now())

@python_2_unicode_compatible
class Coupon(models.Model):
    value = models.IntegerField(_("Value"), help_text=_("Arbitrary coupon value"))
    code = models.CharField(
        _("Code"), max_length=30, unique=True, blank=True,
        help_text=_("Leaving this field empty will generate a random code."))
    type = models.CharField(_("Type"), max_length=20, choices=COUPON_TYPES)
    user_limit = models.PositiveIntegerField(_("User limit"), default=1)
    created_at = models.DateTimeField(_("Created at"), auto_now_add=True)
    valid_until = models.DateTimeField(
        _("Valid until"), blank=True, null=True,
        help_text=_("Leave empty for coupons that never expire"))
    campaign = models.ForeignKey('Campaign', verbose_name=_("Campaign"), blank=True, null=True, related_name='coupons')

    objects = CouponManager()

    class Meta:
        ordering = ['created_at']
        verbose_name = _("Coupon")
        verbose_name_plural = _("Coupons")

    def __str__(self):
        return self.code

    def save(self, *args, **kwargs):
        if not self.code:
            self.code = Coupon.generate_code()
        super(Coupon, self).save(*args, **kwargs)

    def expired(self):
        return self.valid_until is not None and self.valid_until < timezone.now()

    @property
    def is_redeemed(self):
        """ Returns true is a coupon is redeemed (completely for all users) otherwise returns false. """
        return self.users.filter(
            redeemed_at__isnull=False
        ).count() >= self.user_limit and self.user_limit is not 0

    @property
    def redeemed_at(self):
        try:
            return self.users.filter(redeemed_at__isnull=False).order_by('redeemed_at').last().redeemed_at
        except self.users.through.DoesNotExist:
            return None

    @classmethod
    def generate_code(cls, prefix="", segmented=SEGMENTED_CODES):
        code = "".join(random.choice(CODE_CHARS) for i in range(CODE_LENGTH))
        if segmented:
            code = SEGMENT_SEPARATOR.join([code[i:i + SEGMENT_LENGTH] for i in range(0, len(code), SEGMENT_LENGTH)])
            return prefix + code
        else:
            return prefix + code

    def redeem(self, user=None):
        try:
            coupon_user = self.users.get(user=user)
        except CouponUser.DoesNotExist:
            try:  # silently fix unbouned or nulled coupon users
                coupon_user = self.users.get(user__isnull=True)
                coupon_user.user = user
            except CouponUser.DoesNotExist:
                coupon_user = CouponUser(coupon=self, user=user)
        coupon_user.redeemed_at = timezone.now()
        coupon_user.save()
        redeem_done.send(sender=self.__class__, coupon=self)

@python_2_unicode_compatible
class Campaign(models.Model):
    name = models.CharField(_("Name"), max_length=255, unique=True)
    description = models.TextField(_("Description"), blank=True)

    class Meta:
        ordering = ['name']
        verbose_name = _("Campaign")
        verbose_name_plural = _("Campaigns")

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class CouponUser(models.Model):
    coupon = models.ForeignKey(Coupon, related_name='users')
    user = models.ForeignKey(user_model, verbose_name=_("User"), null=True, blank=True)
    redeemed_at = models.DateTimeField(_("Redeemed at"), blank=True, null=True)

    class Meta:
        unique_together = (('coupon', 'user'),)

    def __str__(self):
        return str(self.user)
<commit_msg>do not create user coupons with none user values<commit_after>import random

from django.conf import settings
from django.db import IntegrityError
from django.db import models
from django.dispatch import Signal
from django.utils.encoding import python_2_unicode_compatible
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from .settings import (
    COUPON_TYPES,
    CODE_LENGTH,
    CODE_CHARS,
    SEGMENTED_CODES,
    SEGMENT_LENGTH,
    SEGMENT_SEPARATOR,
)

try:
    user_model = settings.AUTH_USER_MODEL
except AttributeError:
    from django.contrib.auth.models import User as user_model
redeem_done = Signal(providing_args=["coupon"])

class CouponManager(models.Manager):
    def create_coupon(self, type, value, users=[], valid_until=None, prefix="", campaign=None, user_limit=None):
        coupon = self.create(
            value=value,
            code=Coupon.generate_code(prefix),
            type=type,
            valid_until=valid_until,
            campaign=campaign,
        )
        if user_limit is not None:  # otherwise use default value of model
            coupon.user_limit = user_limit
        try:
            coupon.save()
        except IntegrityError:
            # Try again with other code
            coupon = Coupon.objects.create_coupon(type, value, users, valid_until, prefix, campaign)
        if not isinstance(users, list):
            users = [users]
        for user in users:
            if user:
                CouponUser(user=user, coupon=coupon).save()
        return coupon

    def create_coupons(self, quantity, type, value, valid_until=None, prefix="", campaign=None):
        coupons = []
        for i in range(quantity):
            coupons.append(self.create_coupon(type, value, None, valid_until, prefix, campaign))
        return coupons

    def used(self):
        return self.exclude(users__redeemed_at__isnull=True)

    def unused(self):
        return self.filter(users__redeemed_at__isnull=True)

    def expired(self):
        return self.filter(valid_until__lt=timezone.now())

@python_2_unicode_compatible
class Coupon(models.Model):
    value = models.IntegerField(_("Value"), help_text=_("Arbitrary coupon value"))
    code = models.CharField(
        _("Code"), max_length=30, unique=True, blank=True,
        help_text=_("Leaving this field empty will generate a random code."))
    type = models.CharField(_("Type"), max_length=20, choices=COUPON_TYPES)
    user_limit = models.PositiveIntegerField(_("User limit"), default=1)
    created_at = models.DateTimeField(_("Created at"), auto_now_add=True)
    valid_until = models.DateTimeField(
        _("Valid until"), blank=True, null=True,
        help_text=_("Leave empty for coupons that never expire"))
    campaign = models.ForeignKey('Campaign', verbose_name=_("Campaign"), blank=True, null=True, related_name='coupons')

    objects = CouponManager()

    class Meta:
        ordering = ['created_at']
        verbose_name = _("Coupon")
        verbose_name_plural = _("Coupons")

    def __str__(self):
        return self.code

    def save(self, *args, **kwargs):
        if not self.code:
            self.code = Coupon.generate_code()
        super(Coupon, self).save(*args, **kwargs)

    def expired(self):
        return self.valid_until is not None and self.valid_until < timezone.now()

    @property
    def is_redeemed(self):
        """ Returns true is a coupon is redeemed (completely for all users) otherwise returns false. """
        return self.users.filter(
            redeemed_at__isnull=False
        ).count() >= self.user_limit and self.user_limit is not 0

    @property
    def redeemed_at(self):
        try:
            return self.users.filter(redeemed_at__isnull=False).order_by('redeemed_at').last().redeemed_at
        except self.users.through.DoesNotExist:
            return None

    @classmethod
    def generate_code(cls, prefix="", segmented=SEGMENTED_CODES):
        code = "".join(random.choice(CODE_CHARS) for i in range(CODE_LENGTH))
        if segmented:
            code = SEGMENT_SEPARATOR.join([code[i:i + SEGMENT_LENGTH] for i in range(0, len(code), SEGMENT_LENGTH)])
            return prefix + code
        else:
            return prefix + code

    def redeem(self, user=None):
        try:
            coupon_user = self.users.get(user=user)
        except CouponUser.DoesNotExist:
            try:  # silently fix unbouned or nulled coupon users
                coupon_user = self.users.get(user__isnull=True)
                coupon_user.user = user
            except CouponUser.DoesNotExist:
                coupon_user = CouponUser(coupon=self, user=user)
        coupon_user.redeemed_at = timezone.now()
        coupon_user.save()
        redeem_done.send(sender=self.__class__, coupon=self)

@python_2_unicode_compatible
class Campaign(models.Model):
    name = models.CharField(_("Name"), max_length=255, unique=True)
    description = models.TextField(_("Description"), blank=True)

    class Meta:
        ordering = ['name']
        verbose_name = _("Campaign")
        verbose_name_plural = _("Campaigns")

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class CouponUser(models.Model):
    coupon = models.ForeignKey(Coupon, related_name='users')
    user = models.ForeignKey(user_model, verbose_name=_("User"), null=True, blank=True)
    redeemed_at = models.DateTimeField(_("Redeemed at"), blank=True, null=True)

    class Meta:
        unique_together = (('coupon', 'user'),)

    def __str__(self):
        return str(self.user)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Standard library imports
import os
import shlex

# Local imports
from . import mappings, paths
from .repos import LocalRepo
from .reporter import get_reporter
from .module import Module, is_module, is_exact_match, best_match

__all__ = [
    'ResolveError',
    'Resolver',
    'Activator',
    'Copier',
    'Localizer',
    'module_resolvers',
    'is_redirecting',
    'redirect_to_modules',
    'parse_redirect',
]

class ResolveError(Exception):
    '''Raised when a Resolver fairs to resolve a module or list of modules.'''

class Resolver(object):
    '''Responsible for resolving ModuleSpecs from requirement strings.

    Modules will be looked up sequentially in all registered Repos. By default
    this order is:
        1. LocalRepo pointing to current working directory
        2. LocalRepo pointing to cpenv_home_modules_path ($CPENV_HOME/modules)
        3. LocalRepo pointing to cpenv_user_modules_path
        4. LocalRepos pointing to the paths in $CPENV_MODULES
        5. Custom Repos registered via cpenv.add_repo

    If there are still unresolved modules, we fallback to the old algorithm
    for module lookups using the resolve functions in the
    cpenv.resolver.module_resolvers list.
    '''

    def __init__(self, repos):
        self.repos = repos
        self.reporter = get_reporter()

    def resolve(self, requirements):
        '''Given a list of requirement strings, resolve ModuleSpecs.

        Returns:
            list of ModuleSpec objects

        Raises:
            ResolveError when a requirement can not be resolved.
        '''

        self.reporter.start_resolve(requirements)
        unresolved = list(requirements)
        resolved = []

        for requirement in requirements:
            self.reporter.find_requirement(requirement)
            # TODO: handle more complex requirements.
            #       possibly use the new resolvelib being developed by pypa

            match_gen = (
                module_spec for repo in self.repos
                for module_spec in repo.find(requirement)
            )

            # best_match returns the first ModuleSpec that matches
            # both name and version or the ModuleSpec with the
            # highest version > the required version
            match = best_match(requirement, match_gen)
            if match:
                self.reporter.resolve_requirement(requirement, match)
                unresolved.remove(requirement)
                resolved.append(match)
            else:
                # TODO: once old resolve algorithm is removed
                # report a module resolution failure here.
                pass

        if unresolved:
            # Try the old resolution alogirthm for backwards compatability
            resolved.extend(old_resolve_algorithm(self, unresolved))

        self.reporter.end_resolve(resolved, unresolved)

        if unresolved:
            raise ResolveError(
                'Could not resolve: ' + ' '.join(unresolved)
            )

        return resolved

class Activator(object):
    '''Responsible for activating modules.'''

    def __init__(self, localizer=None):
        self.localizer = localizer or Localizer(to_repo='home')

    def combine_modules(self, modules):
        '''Combine a list of module's environments.'''

        return mappings.join_dicts(*[obj.environment for obj in modules])

    def activate(self, module_specs):
        '''Activate a list of module specs.'''

        modules = self.localizer.localize(module_specs)
        env = self.combine_modules(modules)
        mappings.set_env(env)

        for module in modules:
            module.activate()

        return modules

class Copier(object):
    '''Responsible for copying modules to a specific module.'''

    def __init__(self, to_repo):
        from .api import get_repo
        self.to_repo = get_repo(to_repo)

    def copy(self, module_specs, overwrite=False):
        '''Given ModuleSpecs, copy them to this copiers to_repo.'''
        from .api import get_cache_path

        copied = []
        for module_spec in module_specs:

            matches = self.to_repo.find(module_spec.qual_name)
            already_exists = False
            for match in matches:
                if is_exact_match(module_spec.qual_name, match):
                    already_exists = True
                    break

            if already_exists and not overwrite:
                continue

            # Get local module or download module from repo
            if isinstance(module_spec.repo, LocalRepo):
                module = Module.from_spec(module_spec)
            else:
                download_path = get_cache_path(
                    'tmp',
                    str(hash(module_spec.repo.name)),
                    module_spec.name,
                    module_spec.version.string,
                )
                module = module_spec.repo.download(
                    module_spec,
                    where=download_path,
                    overwrite=overwrite,
                )

            # Upload module to_repo
            new_module_spec = self.to_repo.upload(
                module,
                overwrite=overwrite,
            )
            copied.append(new_module_spec)

        tmp = get_cache_path('tmp')
        if os.path.isdir(tmp):
            paths.rmtree(tmp)

        return copied

class Localizer(object):
    '''Downloads modules from remote Repos to a specific LocalRepo.

    This is similar to a copy operation, but skips all module_specs that are
    already in LocalRepos. If they are in LocalRepos then they are already
    available to be activated.
    '''

    def __init__(self, to_repo='home'):
        from .api import get_repo

        self.to_repo = get_repo(to_repo)
        self.reporter = get_reporter()

        if not isinstance(self.to_repo, LocalRepo):
            raise ValueError(
                'Localizer expected LocalRepo got %s' % type(to_repo)
            )

    def localize(self, module_specs, overwrite=False):
        '''Given ModuleSpecs, download them to this Localizers repo.'''

        self.reporter.start_localize(module_specs)
        localized = []
        for module_spec in module_specs:

            # Module is already local
            if isinstance(module_spec.repo, LocalRepo):
                localized.append(Module(module_spec.path))
                self.reporter.localize_module(module_spec, localized[-1])
                continue

            # Module already exists in to_repo
            matches = self.to_repo.find(module_spec.qual_name)
            already_exists = False
            for match in matches:
                if is_exact_match(module_spec.qual_name, match):
                    already_exists = True
                    localized.append(Module(match.path))
                    self.reporter.localize_module(module_spec, localized[-1])
                    break

            if already_exists and not overwrite:
                self.reporter.localize_module(module_spec, localized[-1])
                continue

            # Generate a new module path in to_repo
            if module_spec.version.string in module_spec.real_name:
                new_module_path = self.to_repo.relative_path(
                    module_spec.real_name
                )
            else:
                new_module_path = self.to_repo.relative_path(
                    module_spec.name,
                    module_spec.version.string,
                )

            module = module_spec.repo.download(
                module_spec,
                where=new_module_path,
                overwrite=overwrite,
            )
            localized.append(module)
            self.reporter.localize_module(module_spec, localized[-1])

        self.reporter.end_localize(localized)
        return localized

# Deprecated
# The following functions represet the old resolution algorithm
# this is called by Resolver.resolve only when no Repos are able to resolve
# a requirement.

def old_resolve_algorithm(resolver, paths):

    modules = []
    for path in list(paths):

        for module_resolver in module_resolvers:
            try:

                resolved = module_resolver(resolver, path)
                paths.remove(path)

                if isinstance(resolved, list):
                    modules.extend(resolved)
                else:
                    modules.append(resolved)

                break
            except ResolveError:
                continue

    return modules

def path_is_module_resolver(resolver, path):
    '''Checks if path is already a :class:`Module` object'''

    if isinstance(path, Module):
        return path

    raise ResolveError

def cwd_resolver(resolver, path):
    '''Checks if path is already a :class:`Module` object'''

    mod_path = paths.normalize(os.getcwd(), path)
    if is_module(mod_path):
        resolved = Module(mod_path).as_spec()
        resolver.reporter.resolve_requirement(path, resolved)
        return resolved

    raise ResolveError

def modules_path_resolver(resolver, path):
    '''Resolves modules in CPENV_MODULES path and CPENV_HOME/modules'''

    from .api import get_module_paths

    for module_dir in get_module_paths():
        mod_path = paths.normalize(module_dir, path)

        if is_module(mod_path):
            resolved = Module(mod_path).as_spec()
            resolver.reporter.resolve_requirement(path, resolved)
            return resolved

    raise ResolveError

def redirect_resolver(resolver, path):
    '''Resolves environment from .cpenv file...recursively walks up the tree
    in attempt to find a .cpenv file'''

    if not os.path.exists(path):
        raise ResolveError

    if os.path.isfile(path):
        path = os.path.dirname(path)

    for root, _, _ in paths.walk_up(path):
        if is_redirecting(root):
            env_paths = redirect_to_modules(
                paths.normalize(root, '.cpenv')
            )
            r = Resolver(resolver.repos)
            return r.resolve(env_paths)

    raise ResolveError

module_resolvers = [
    redirect_resolver,
    cwd_resolver,
    path_is_module_resolver,
    modules_path_resolver,
]

def is_redirecting(path):
    '''Returns True if path contains a .cpenv file'''

    candidate = paths.normalize(path, '.cpenv')
    return os.path.exists(candidate) and os.path.isfile(candidate)

def redirect_to_modules(path):
    '''Get environment path from redirect file'''

    with open(path, 'r') as f:
        data = f.read()

    return parse_redirect(data)

def parse_redirect(data):
    '''Parses a redirect string - data of a .cpenv file'''

    lines = [line for line in data.split('\n') if line.strip()]
    if len(lines) == 1:
        return shlex.split(lines[0])
    else:
        return lines
<commit_msg>change: order of lookup in Resolver docstrin<commit_after># -*- coding: utf-8 -*-

# Standard library imports
import os
import shlex

# Local imports
from . import mappings, paths
from .repos import LocalRepo
from .reporter import get_reporter
from .module import Module, is_module, is_exact_match, best_match

__all__ = [
    'ResolveError',
    'Resolver',
    'Activator',
    'Copier',
    'Localizer',
    'module_resolvers',
    'is_redirecting',
    'redirect_to_modules',
    'parse_redirect',
]

class ResolveError(Exception):
    '''Raised when a Resolver fairs to resolve a module or list of modules.'''

class Resolver(object):
    '''Responsible for resolving ModuleSpecs from requirement strings.

    Modules will be looked up sequentially in all registered Repos. By default
    this order is:
        1. LocalRepo pointing to current working directory
        2. LocalRepo pointing to cpenv_user_modules_path
        3. LocalRepo pointing to cpenv_home_modules_path ($CPENV_HOME/modules)
        4. LocalRepos pointing to the paths in $CPENV_MODULES
        5. Custom Repos registered via cpenv.add_repo

    If there are still unresolved modules, we fallback to the old algorithm
    for module lookups using the resolve functions in the
    cpenv.resolver.module_resolvers list.
    '''

    def __init__(self, repos):
        self.repos = repos
        self.reporter = get_reporter()

    def resolve(self, requirements):
        '''Given a list of requirement strings, resolve ModuleSpecs.

        Returns:
            list of ModuleSpec objects

        Raises:
            ResolveError when a requirement can not be resolved.
        '''

        self.reporter.start_resolve(requirements)
        unresolved = list(requirements)
        resolved = []

        for requirement in requirements:
            self.reporter.find_requirement(requirement)
            # TODO: handle more complex requirements.
            #       possibly use the new resolvelib being developed by pypa

            match_gen = (
                module_spec for repo in self.repos
                for module_spec in repo.find(requirement)
            )

            # best_match returns the first ModuleSpec that matches
            # both name and version or the ModuleSpec with the
            # highest version > the required version
            match = best_match(requirement, match_gen)
            if match:
                self.reporter.resolve_requirement(requirement, match)
                unresolved.remove(requirement)
                resolved.append(match)
            else:
                # TODO: once old resolve algorithm is removed
                # report a module resolution failure here.
                pass

        if unresolved:
            # Try the old resolution alogirthm for backwards compatability
            resolved.extend(old_resolve_algorithm(self, unresolved))

        self.reporter.end_resolve(resolved, unresolved)

        if unresolved:
            raise ResolveError(
                'Could not resolve: ' + ' '.join(unresolved)
            )

        return resolved

class Activator(object):
    '''Responsible for activating modules.'''

    def __init__(self, localizer=None):
        self.localizer = localizer or Localizer(to_repo='home')

    def combine_modules(self, modules):
        '''Combine a list of module's environments.'''

        return mappings.join_dicts(*[obj.environment for obj in modules])

    def activate(self, module_specs):
        '''Activate a list of module specs.'''

        modules = self.localizer.localize(module_specs)
        env = self.combine_modules(modules)
        mappings.set_env(env)

        for module in modules:
            module.activate()

        return modules

class Copier(object):
    '''Responsible for copying modules to a specific module.'''

    def __init__(self, to_repo):
        from .api import get_repo
        self.to_repo = get_repo(to_repo)

    def copy(self, module_specs, overwrite=False):
        '''Given ModuleSpecs, copy them to this copiers to_repo.'''
        from .api import get_cache_path

        copied = []
        for module_spec in module_specs:

            matches = self.to_repo.find(module_spec.qual_name)
            already_exists = False
            for match in matches:
                if is_exact_match(module_spec.qual_name, match):
                    already_exists = True
                    break

            if already_exists and not overwrite:
                continue

            # Get local module or download module from repo
            if isinstance(module_spec.repo, LocalRepo):
                module = Module.from_spec(module_spec)
            else:
                download_path = get_cache_path(
                    'tmp',
                    str(hash(module_spec.repo.name)),
                    module_spec.name,
                    module_spec.version.string,
                )
                module = module_spec.repo.download(
                    module_spec,
                    where=download_path,
                    overwrite=overwrite,
                )

            # Upload module to_repo
            new_module_spec = self.to_repo.upload(
                module,
                overwrite=overwrite,
            )
            copied.append(new_module_spec)

        tmp = get_cache_path('tmp')
        if os.path.isdir(tmp):
            paths.rmtree(tmp)

        return copied

class Localizer(object):
    '''Downloads modules from remote Repos to a specific LocalRepo.

    This is similar to a copy operation, but skips all module_specs that are
    already in LocalRepos. If they are in LocalRepos then they are already
    available to be activated.
    '''

    def __init__(self, to_repo='home'):
        from .api import get_repo

        self.to_repo = get_repo(to_repo)
        self.reporter = get_reporter()

        if not isinstance(self.to_repo, LocalRepo):
            raise ValueError(
                'Localizer expected LocalRepo got %s' % type(to_repo)
            )

    def localize(self, module_specs, overwrite=False):
        '''Given ModuleSpecs, download them to this Localizers repo.'''

        self.reporter.start_localize(module_specs)
        localized = []
        for module_spec in module_specs:

            # Module is already local
            if isinstance(module_spec.repo, LocalRepo):
                localized.append(Module(module_spec.path))
                self.reporter.localize_module(module_spec, localized[-1])
                continue

            # Module already exists in to_repo
            matches = self.to_repo.find(module_spec.qual_name)
            already_exists = False
            for match in matches:
                if is_exact_match(module_spec.qual_name, match):
                    already_exists = True
                    localized.append(Module(match.path))
                    self.reporter.localize_module(module_spec, localized[-1])
                    break

            if already_exists and not overwrite:
                self.reporter.localize_module(module_spec, localized[-1])
                continue

            # Generate a new module path in to_repo
            if module_spec.version.string in module_spec.real_name:
                new_module_path = self.to_repo.relative_path(
                    module_spec.real_name
                )
            else:
                new_module_path = self.to_repo.relative_path(
                    module_spec.name,
                    module_spec.version.string,
                )

            module = module_spec.repo.download(
                module_spec,
                where=new_module_path,
                overwrite=overwrite,
            )
            localized.append(module)
            self.reporter.localize_module(module_spec, localized[-1])

        self.reporter.end_localize(localized)
        return localized

# Deprecated
# The following functions represet the old resolution algorithm
# this is called by Resolver.resolve only when no Repos are able to resolve
# a requirement.

def old_resolve_algorithm(resolver, paths):

    modules = []
    for path in list(paths):

        for module_resolver in module_resolvers:
            try:

                resolved = module_resolver(resolver, path)
                paths.remove(path)

                if isinstance(resolved, list):
                    modules.extend(resolved)
                else:
                    modules.append(resolved)

                break
            except ResolveError:
                continue

    return modules

def path_is_module_resolver(resolver, path):
    '''Checks if path is already a :class:`Module` object'''

    if isinstance(path, Module):
        return path

    raise ResolveError

def cwd_resolver(resolver, path):
    '''Checks if path is already a :class:`Module` object'''

    mod_path = paths.normalize(os.getcwd(), path)
    if is_module(mod_path):
        resolved = Module(mod_path).as_spec()
        resolver.reporter.resolve_requirement(path, resolved)
        return resolved

    raise ResolveError

def modules_path_resolver(resolver, path):
    '''Resolves modules in CPENV_MODULES path and CPENV_HOME/modules'''

    from .api import get_module_paths

    for module_dir in get_module_paths():
        mod_path = paths.normalize(module_dir, path)

        if is_module(mod_path):
            resolved = Module(mod_path).as_spec()
            resolver.reporter.resolve_requirement(path, resolved)
            return resolved

    raise ResolveError

def redirect_resolver(resolver, path):
    '''Resolves environment from .cpenv file...recursively walks up the tree
    in attempt to find a .cpenv file'''

    if not os.path.exists(path):
        raise ResolveError

    if os.path.isfile(path):
        path = os.path.dirname(path)

    for root, _, _ in paths.walk_up(path):
        if is_redirecting(root):
            env_paths = redirect_to_modules(
                paths.normalize(root, '.cpenv')
            )
            r = Resolver(resolver.repos)
            return r.resolve(env_paths)

    raise ResolveError

module_resolvers = [
    redirect_resolver,
    cwd_resolver,
    path_is_module_resolver,
    modules_path_resolver,
]

def is_redirecting(path):
    '''Returns True if path contains a .cpenv file'''

    candidate = paths.normalize(path, '.cpenv')
    return os.path.exists(candidate) and os.path.isfile(candidate)

def redirect_to_modules(path):
    '''Get environment path from redirect file'''

    with open(path, 'r') as f:
        data = f.read()

    return parse_redirect(data)

def parse_redirect(data):
    '''Parses a redirect string - data of a .cpenv file'''

    lines = [line for line in data.split('\n') if line.strip()]
    if len(lines) == 1:
        return shlex.split(lines[0])
    else:
        return lines
<|endoftext|>


<commit_before>from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator

default_args = {
    'owner': 'mreid@mozilla.com',
    'depends_on_past': False,
    'start_date': datetime(2016, 6, 27),
    'email': ['telemetry-alerts@mozilla.com', 'mreid@mozilla.com'],
    'email_on_failure': True,
    'email_on_retry': True,
    'retries': 2,
    'retry_delay': timedelta(minutes=30),
}

dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily')

# Make sure all the data for the given day has arrived before running.
t0 = BashOperator(task_id="delayed_start",
                  bash_command="sleep 1800"
                  dag=dag)

t1 = EMRSparkOperator(task_id="main_summary",
                      job_name="Main Summary View",
                      execution_timeout=timedelta(hours=6),
                      instance_count=10,
                      env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.airflow_bucket }}"},
                      uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh",
                      dag=dag)

# Wait a little while after midnight to start for a given day.
t1.set_upstream(t0)
<commit_msg>Fix broken main_summary DAG.<commit_after>from airflow import DAG
from datetime import datetime, timedelta
from operators.emr_spark_operator import EMRSparkOperator
from airflow.operators import BashOperator

default_args = {
    'owner': 'mreid@mozilla.com',
    'depends_on_past': False,
    'start_date': datetime(2016, 6, 27),
    'email': ['telemetry-alerts@mozilla.com', 'mreid@mozilla.com'],
    'email_on_failure': True,
    'email_on_retry': True,
    'retries': 2,
    'retry_delay': timedelta(minutes=30),
}

dag = DAG('main_summary', default_args=default_args, schedule_interval='@daily')

# Make sure all the data for the given day has arrived before running.
t0 = BashOperator(task_id="delayed_start",
                  bash_command="sleep 1800",
                  dag=dag)

t1 = EMRSparkOperator(task_id="main_summary",
                      job_name="Main Summary View",
                      execution_timeout=timedelta(hours=6),
                      instance_count=10,
                      env = {"date": "{{ ds_nodash }}", "bucket": "{{ task.__class__.airflow_bucket }}"},
                      uri="https://raw.githubusercontent.com/mozilla/telemetry-airflow/master/jobs/main_summary_view.sh",
                      dag=dag)

# Wait a little while after midnight to start for a given day.
t1.set_upstream(t0)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, today, getdate, cint
from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_checks_for_pl_and_bs_accounts

def post_depreciation_entries(date=None):
	# Return if automatic booking of asset depreciation is disabled
	if not cint(frappe.db.get_value("Accounts Settings", None, "book_asset_depreciation_entry_automatically")):
		return

	if not date:
		date = today()
	for asset in get_depreciable_assets(date):
		make_depreciation_entry(asset, date)
		frappe.db.commit()

def get_depreciable_assets(date):
	return frappe.db.sql_list("""select a.name
		from tabAsset a, `tabDepreciation Schedule` ds
		where a.name = ds.parent and a.docstatus=1 and ds.schedule_date<=%s and a.calculate_depreciation = 1
			and a.status in ('Submitted', 'Partially Depreciated')
			and ifnull(ds.journal_entry, '')=''""", date)

@frappe.whitelist()
def make_depreciation_entry(asset_name, date=None):
	frappe.has_permission('Journal Entry', throw=True)

	if not date:
		date = today()

	asset = frappe.get_doc("Asset", asset_name)
	fixed_asset_account, accumulated_depreciation_account, depreciation_expense_account = \
		get_depreciation_accounts(asset)

	depreciation_cost_center, depreciation_series = frappe.get_cached_value('Company',  asset.company,
		["depreciation_cost_center", "series_for_depreciation_entry"])

	depreciation_cost_center = asset.cost_center or depreciation_cost_center

	accounting_dimensions = get_checks_for_pl_and_bs_accounts()

	for d in asset.get("schedules"):
		if not d.journal_entry and getdate(d.schedule_date) <= getdate(date):
			je = frappe.new_doc("Journal Entry")
			je.voucher_type = "Depreciation Entry"
			je.naming_series = depreciation_series
			je.posting_date = d.schedule_date
			je.company = asset.company
			je.finance_book = d.finance_book
			je.remark = "Depreciation Entry against {0} worth {1}".format(asset_name, d.depreciation_amount)

			credit_entry = {
				"account": accumulated_depreciation_account,
				"credit_in_account_currency": d.depreciation_amount,
				"reference_type": "Asset",
				"reference_name": asset.name
			}

			debit_entry = {
				"account": depreciation_expense_account,
				"debit_in_account_currency": d.depreciation_amount,
				"reference_type": "Asset",
				"reference_name": asset.name,
				"cost_center": depreciation_cost_center
			}

			for dimension in accounting_dimensions:
				if (asset.get(dimension['fieldname']) or dimension.get('mandatory_for_bs')):
					credit_entry.update({
						dimension['fieldname']: asset.get(dimension['fieldname']) or dimension.get('default_dimension')
					})

				if (asset.get(dimension['fieldname']) or dimension.get('mandatory_for_pl')):
					debit_entry.update({
						dimension['fieldname']: asset.get(dimension['fieldname']) or dimension.get('default_dimension')
					})

			je.append("accounts", credit_entry)

			je.append("accounts", debit_entry)

			je.flags.ignore_permissions = True
			je.save()
			if not je.meta.get_workflow():
				je.submit()

			d.db_set("journal_entry", je.name)

			idx = cint(d.finance_book_id)
			finance_books = asset.get('finance_books')[idx - 1]
			finance_books.value_after_depreciation -= d.depreciation_amount
			finance_books.db_update()

	asset.set_status()

	return asset

def get_depreciation_accounts(asset):
	fixed_asset_account = accumulated_depreciation_account = depreciation_expense_account = None

	accounts = frappe.db.get_value("Asset Category Account",
		filters={'parent': asset.asset_category, 'company_name': asset.company},
		fieldname = ['fixed_asset_account', 'accumulated_depreciation_account',
			'depreciation_expense_account'], as_dict=1)

	if accounts:
		fixed_asset_account = accounts.fixed_asset_account
		accumulated_depreciation_account = accounts.accumulated_depreciation_account
		depreciation_expense_account = accounts.depreciation_expense_account

	if not accumulated_depreciation_account or not depreciation_expense_account:
		accounts = frappe.get_cached_value('Company',  asset.company,
			["accumulated_depreciation_account", "depreciation_expense_account"])

		if not accumulated_depreciation_account:
			accumulated_depreciation_account = accounts[0]
		if not depreciation_expense_account:
			depreciation_expense_account = accounts[1]

	if not fixed_asset_account or not accumulated_depreciation_account or not depreciation_expense_account:
		frappe.throw(_("Please set Depreciation related Accounts in Asset Category {0} or Company {1}")
			.format(asset.asset_category, asset.company))

	return fixed_asset_account, accumulated_depreciation_account, depreciation_expense_account

@frappe.whitelist()
def scrap_asset(asset_name):
	asset = frappe.get_doc("Asset", asset_name)

	if asset.docstatus != 1:
		frappe.throw(_("Asset {0} must be submitted").format(asset.name))
	elif asset.status in ("Cancelled", "Sold", "Scrapped"):
		frappe.throw(_("Asset {0} cannot be scrapped, as it is already {1}").format(asset.name, asset.status))

	depreciation_series = frappe.get_cached_value('Company',  asset.company,  "series_for_depreciation_entry")

	je = frappe.new_doc("Journal Entry")
	je.voucher_type = "Journal Entry"
	je.naming_series = depreciation_series
	je.posting_date = today()
	je.company = asset.company
	je.remark = "Scrap Entry for asset {0}".format(asset_name)

	for entry in get_gl_entries_on_asset_disposal(asset):
		entry.update({
			"reference_type": "Asset",
			"reference_name": asset_name
		})
		je.append("accounts", entry)

	je.flags.ignore_permissions = True
	je.submit()

	frappe.db.set_value("Asset", asset_name, "disposal_date", today())
	frappe.db.set_value("Asset", asset_name, "journal_entry_for_scrap", je.name)
	asset.set_status("Scrapped")

	frappe.msgprint(_("Asset scrapped via Journal Entry {0}").format(je.name))

@frappe.whitelist()
def restore_asset(asset_name):
	asset = frappe.get_doc("Asset", asset_name)

	je = asset.journal_entry_for_scrap

	asset.db_set("disposal_date", None)
	asset.db_set("journal_entry_for_scrap", None)

	frappe.get_doc("Journal Entry", je).cancel()

	asset.set_status()

@frappe.whitelist()
def get_gl_entries_on_asset_disposal(asset, selling_amount=0, finance_book=None):
	fixed_asset_account, accumulated_depr_account, depr_expense_account = get_depreciation_accounts(asset)
	disposal_account, depreciation_cost_center = get_disposal_account_and_cost_center(asset.company)
	depreciation_cost_center = asset.cost_center or depreciation_cost_center

	idx = 1
	if finance_book:
		for d in asset.finance_books:
			if d.finance_book == finance_book:
				idx = d.idx
				break

	value_after_depreciation = (asset.finance_books[idx - 1].value_after_depreciation
		if asset.calculate_depreciation else asset.value_after_depreciation)
	accumulated_depr_amount = flt(asset.gross_purchase_amount) - flt(value_after_depreciation)

	gl_entries = [
		{
			"account": fixed_asset_account,
			"credit_in_account_currency": asset.gross_purchase_amount,
			"credit": asset.gross_purchase_amount
		},
		{
			"account": accumulated_depr_account,
			"debit_in_account_currency": accumulated_depr_amount,
			"debit": accumulated_depr_amount
		}
	]

	profit_amount = flt(selling_amount) - flt(value_after_depreciation)
	if profit_amount:
		debit_or_credit = "debit" if profit_amount < 0 else "credit"
		gl_entries.append({
			"account": disposal_account,
			"cost_center": depreciation_cost_center,
			debit_or_credit: abs(profit_amount),
			debit_or_credit + "_in_account_currency": abs(profit_amount)
		})

	return gl_entries

@frappe.whitelist()
def get_disposal_account_and_cost_center(company):
	disposal_account, depreciation_cost_center = frappe.get_cached_value('Company',  company,
		["disposal_account", "depreciation_cost_center"])

	if not disposal_account:
		frappe.throw(_("Please set 'Gain/Loss Account on Asset Disposal' in Company {0}").format(company))
	if not depreciation_cost_center:
		frappe.throw(_("Please set 'Asset Depreciation Cost Center' in Company {0}").format(company))

	return disposal_account, depreciation_cost_center
<commit_msg>automatic booking of asset depreciation fix<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2016, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import flt, today, getdate, cint
from erpnext.accounts.doctype.accounting_dimension.accounting_dimension import get_checks_for_pl_and_bs_accounts

def post_depreciation_entries(date=None):
	# Return if automatic booking of asset depreciation is disabled
	if cint(frappe.db.get_single_value("Accounts Settings", "book_asset_depreciation_entry_automatically"))==0:
		return

	if not date:
		date = today()
	for asset in get_depreciable_assets(date):
		make_depreciation_entry(asset, date)
		frappe.db.commit()

def get_depreciable_assets(date):
	return frappe.db.sql_list("""select a.name
		from tabAsset a, `tabDepreciation Schedule` ds
		where a.name = ds.parent and a.docstatus=1 and ds.schedule_date<=%s and a.calculate_depreciation = 1
			and a.status in ('Submitted', 'Partially Depreciated')
			and ifnull(ds.journal_entry, '')=''""", date)

@frappe.whitelist()
def make_depreciation_entry(asset_name, date=None):
	frappe.has_permission('Journal Entry', throw=True)

	if not date:
		date = today()

	asset = frappe.get_doc("Asset", asset_name)
	fixed_asset_account, accumulated_depreciation_account, depreciation_expense_account = \
		get_depreciation_accounts(asset)

	depreciation_cost_center, depreciation_series = frappe.get_cached_value('Company',  asset.company,
		["depreciation_cost_center", "series_for_depreciation_entry"])

	depreciation_cost_center = asset.cost_center or depreciation_cost_center

	accounting_dimensions = get_checks_for_pl_and_bs_accounts()

	for d in asset.get("schedules"):
		if not d.journal_entry and getdate(d.schedule_date) <= getdate(date):
			je = frappe.new_doc("Journal Entry")
			je.voucher_type = "Depreciation Entry"
			je.naming_series = depreciation_series
			je.posting_date = d.schedule_date
			je.company = asset.company
			je.finance_book = d.finance_book
			je.remark = "Depreciation Entry against {0} worth {1}".format(asset_name, d.depreciation_amount)

			credit_entry = {
				"account": accumulated_depreciation_account,
				"credit_in_account_currency": d.depreciation_amount,
				"reference_type": "Asset",
				"reference_name": asset.name
			}

			debit_entry = {
				"account": depreciation_expense_account,
				"debit_in_account_currency": d.depreciation_amount,
				"reference_type": "Asset",
				"reference_name": asset.name,
				"cost_center": depreciation_cost_center
			}

			for dimension in accounting_dimensions:
				if (asset.get(dimension['fieldname']) or dimension.get('mandatory_for_bs')):
					credit_entry.update({
						dimension['fieldname']: asset.get(dimension['fieldname']) or dimension.get('default_dimension')
					})

				if (asset.get(dimension['fieldname']) or dimension.get('mandatory_for_pl')):
					debit_entry.update({
						dimension['fieldname']: asset.get(dimension['fieldname']) or dimension.get('default_dimension')
					})

			je.append("accounts", credit_entry)

			je.append("accounts", debit_entry)

			je.flags.ignore_permissions = True
			je.save()
			if not je.meta.get_workflow():
				je.submit()

			d.db_set("journal_entry", je.name)

			idx = cint(d.finance_book_id)
			finance_books = asset.get('finance_books')[idx - 1]
			finance_books.value_after_depreciation -= d.depreciation_amount
			finance_books.db_update()

	asset.set_status()

	return asset

def get_depreciation_accounts(asset):
	fixed_asset_account = accumulated_depreciation_account = depreciation_expense_account = None

	accounts = frappe.db.get_value("Asset Category Account",
		filters={'parent': asset.asset_category, 'company_name': asset.company},
		fieldname = ['fixed_asset_account', 'accumulated_depreciation_account',
			'depreciation_expense_account'], as_dict=1)

	if accounts:
		fixed_asset_account = accounts.fixed_asset_account
		accumulated_depreciation_account = accounts.accumulated_depreciation_account
		depreciation_expense_account = accounts.depreciation_expense_account

	if not accumulated_depreciation_account or not depreciation_expense_account:
		accounts = frappe.get_cached_value('Company',  asset.company,
			["accumulated_depreciation_account", "depreciation_expense_account"])

		if not accumulated_depreciation_account:
			accumulated_depreciation_account = accounts[0]
		if not depreciation_expense_account:
			depreciation_expense_account = accounts[1]

	if not fixed_asset_account or not accumulated_depreciation_account or not depreciation_expense_account:
		frappe.throw(_("Please set Depreciation related Accounts in Asset Category {0} or Company {1}")
			.format(asset.asset_category, asset.company))

	return fixed_asset_account, accumulated_depreciation_account, depreciation_expense_account

@frappe.whitelist()
def scrap_asset(asset_name):
	asset = frappe.get_doc("Asset", asset_name)

	if asset.docstatus != 1:
		frappe.throw(_("Asset {0} must be submitted").format(asset.name))
	elif asset.status in ("Cancelled", "Sold", "Scrapped"):
		frappe.throw(_("Asset {0} cannot be scrapped, as it is already {1}").format(asset.name, asset.status))

	depreciation_series = frappe.get_cached_value('Company',  asset.company,  "series_for_depreciation_entry")

	je = frappe.new_doc("Journal Entry")
	je.voucher_type = "Journal Entry"
	je.naming_series = depreciation_series
	je.posting_date = today()
	je.company = asset.company
	je.remark = "Scrap Entry for asset {0}".format(asset_name)

	for entry in get_gl_entries_on_asset_disposal(asset):
		entry.update({
			"reference_type": "Asset",
			"reference_name": asset_name
		})
		je.append("accounts", entry)

	je.flags.ignore_permissions = True
	je.submit()

	frappe.db.set_value("Asset", asset_name, "disposal_date", today())
	frappe.db.set_value("Asset", asset_name, "journal_entry_for_scrap", je.name)
	asset.set_status("Scrapped")

	frappe.msgprint(_("Asset scrapped via Journal Entry {0}").format(je.name))

@frappe.whitelist()
def restore_asset(asset_name):
	asset = frappe.get_doc("Asset", asset_name)

	je = asset.journal_entry_for_scrap

	asset.db_set("disposal_date", None)
	asset.db_set("journal_entry_for_scrap", None)

	frappe.get_doc("Journal Entry", je).cancel()

	asset.set_status()

@frappe.whitelist()
def get_gl_entries_on_asset_disposal(asset, selling_amount=0, finance_book=None):
	fixed_asset_account, accumulated_depr_account, depr_expense_account = get_depreciation_accounts(asset)
	disposal_account, depreciation_cost_center = get_disposal_account_and_cost_center(asset.company)
	depreciation_cost_center = asset.cost_center or depreciation_cost_center

	idx = 1
	if finance_book:
		for d in asset.finance_books:
			if d.finance_book == finance_book:
				idx = d.idx
				break

	value_after_depreciation = (asset.finance_books[idx - 1].value_after_depreciation
		if asset.calculate_depreciation else asset.value_after_depreciation)
	accumulated_depr_amount = flt(asset.gross_purchase_amount) - flt(value_after_depreciation)

	gl_entries = [
		{
			"account": fixed_asset_account,
			"credit_in_account_currency": asset.gross_purchase_amount,
			"credit": asset.gross_purchase_amount
		},
		{
			"account": accumulated_depr_account,
			"debit_in_account_currency": accumulated_depr_amount,
			"debit": accumulated_depr_amount
		}
	]

	profit_amount = flt(selling_amount) - flt(value_after_depreciation)
	if profit_amount:
		debit_or_credit = "debit" if profit_amount < 0 else "credit"
		gl_entries.append({
			"account": disposal_account,
			"cost_center": depreciation_cost_center,
			debit_or_credit: abs(profit_amount),
			debit_or_credit + "_in_account_currency": abs(profit_amount)
		})

	return gl_entries

@frappe.whitelist()
def get_disposal_account_and_cost_center(company):
	disposal_account, depreciation_cost_center = frappe.get_cached_value('Company',  company,
		["disposal_account", "depreciation_cost_center"])

	if not disposal_account:
		frappe.throw(_("Please set 'Gain/Loss Account on Asset Disposal' in Company {0}").format(company))
	if not depreciation_cost_center:
		frappe.throw(_("Please set 'Asset Depreciation Cost Center' in Company {0}").format(company))

	return disposal_account, depreciation_cost_center
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

import numpy as np
from scipy.stats import maxwell

from . import constants as c

def ln_prior(x, dart):
    """
    Calculate all the prior probabilities.

    """

    if dart.second_SN:
        if dart.prior_pos is None:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, v_kick2, theta_kick2, phi_kick2, ln_t_b = x
        else:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, v_kick2, theta_kick2, phi_kick2, ra_b, dec_b, ln_t_b = x
    else:
        if dart.prior_pos is None:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, ln_t_b = x
        else:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, ra_b, dec_b, ln_t_b = x

    # Set defaults
    kick_sigma = c.v_kick_sigma
    M1_alpha = c.alpha
    mass_function = 'Salpeter'
    M1_min = c.min_mass_M1
    M1_max = c.max_mass_M1
    M2_min = c.min_mass_M2
    a_min = c.min_a
    a_max = c.max_a
    t_min = c.min_t
    t_max = c.max_t
    # End defaults

    # Set values according to inputs
    for key, value in dart.prior_kwargs.items():
        if key == 'kick_sigma': kick_sigma = value
        if key == 'M1_alpha': M1_alpha = value
        if key == 'M1_min': M1_min = value
        if key == 'M1_max': M1_min = value
        if key == 'M2_min': M2_min = value
        if key == 'a_min': a_min = value
        if key == 'a_max': a_max = value
        if key == 't_min': t_min = value
        if key == 't_max': t_max = value
        if key == 'mass_function': mass_function = value

    # Calculate prior probabilities
    lp = 0.0
    lp += dart.prior_M1(ln_M1, mass_function=mass_function, alpha=M1_alpha, M1_min=M1_min, M1_max=M1_max)
    lp += dart.prior_M2(ln_M2, ln_M1, M2_min=M2_min)
    lp += dart.prior_ecc(ecc)
    lp += dart.prior_a(ln_a, ecc, a_min=a_min, a_max=a_max)
    lp += dart.prior_v_kick1(v_kick1, sigma=kick_sigma)
    lp += dart.prior_theta_kick1(theta_kick1)
    lp += dart.prior_phi_kick1(phi_kick1)

    if dart.second_SN:
        lp += dart.prior_v_kick2(v_kick2, sigma=kick_sigma)
        lp += dart.prior_theta_kick2(theta_kick2)
        lp += dart.prior_phi_kick2(phi_kick2)

    if dart.prior_pos is None:
        lp += dart.prior_t(ln_t_b, t_min=t_min, t_max=t_max)
    else:
        lp += dart.prior_pos(ra_b, dec_b, ln_t_b)

    return lp

def ln_prior_M1(M1, mass_function='Salpeter', alpha=c.alpha, M1_min=c.min_mass_M1, M1_max=c.max_mass_M1):
    """
    Return the prior probability on M1: P(M1).

    """

    if M1 < M1_min or M1 > M1_max: return -np.inf
    norm_const = (alpha+1.0) / (np.power(M1_max, alpha+1.0) - np.power(M1_min, alpha+1.0))
    return np.log( norm_const * np.power(M1, alpha) )

def ln_prior_ln_M1(ln_M1, mass_function='Salpeter', alpha=c.alpha, M1_min=c.min_mass_M1, M1_max=c.max_mass_M1):
    """
    Return the prior probability on the natural log of M1: P(ln_M1).

    """

    M1 = np.exp(ln_M1)

    if M1 < M1_min or M1 > M1_max: return -np.inf
    norm_const = (alpha+1.0) / (np.power(M1_max, alpha+1.0) - np.power(M1_min, alpha+1.0))
    return np.log( norm_const * np.power(M1, alpha+1.0) )

def ln_prior_M2(M2, M1, M2_min=c.min_mass_M2):
    """
    Return the prior probability on M2: P(M2 | M1).

    """

    if M2 < M2_min or M2 > M1: return -np.inf
    return np.log(1.0 / M1)

def ln_prior_ln_M2(ln_M2, ln_M1, M2_min=c.min_mass_M2):
    """
    Return the prior probability on the natural log of M2: P(ln_M2 | M1).

    """

    M1 = np.exp(ln_M1)
    M2 = np.exp(ln_M2)

    if M2 < M2_min or M2 > M1: return -np.inf
    return np.log(M2 / M1)

def ln_prior_a(a, ecc, a_min=c.min_a, a_max=c.max_a):
    """
    Return the prior probability on a: P(a).

    """

    if a*(1.0-ecc) < a_min or a*(1.0+ecc) > a_max: return -np.inf
    norm_const = 1.0 / (np.log(a_max / (1.0+ecc)) - np.log(a_min / (1.0-ecc)))

    return np.log( norm_const / a )

def ln_prior_ln_a(ln_a, ecc, a_min=c.min_a, a_max=c.max_a):
    """
    Return the prior probability on the natural log of a: P(ln_a).

    """

    a = np.exp(ln_a)

    if a*(1.0-ecc) < a_min or a*(1.0+ecc) > a_max: return -np.inf
    norm_const = 1.0 / (np.log(a_max / (1.0+ecc)) - np.log(a_min / (1.0-ecc)))

    return np.log( norm_const )

def ln_prior_ecc(ecc):
    """
    Return the prior probability on ecc: P(ecc).

    """

    if ecc < 0.0 or ecc > 1.0: return -np.inf
    return np.log(2.0 * ecc)

def ln_prior_v_kick(v_kick, sigma=c.v_kick_sigma):
    """
    Return the prior probability on v_kick: P(v_kick).

    """

    if v_kick < 0.0: return -np.inf
    return np.log(maxwell.pdf(v_kick, scale=sigma))

def ln_prior_theta_kick(theta_kick):
    """
    Return the prior probability on the SN kick theta: P(theta).

    """

    if theta_kick <= 0.0 or theta_kick >= np.pi: return -np.inf
    return np.log(np.sin(theta_kick) / 2.0)

def ln_prior_phi_kick(phi_kick):
    """
    Return the prior probability on the SN kick phi: P(phi).

    """

    if phi_kick < 0.0 or phi_kick > np.pi: return -np.inf
    return -np.log(np.pi)

def ln_prior_t(t_b, t_min=c.min_t, t_max=c.max_t):
    """
    Return the prior probability on the binary's birth time (age).

    """

    if t_b < t_min or t_b > t_max: return -np.inf
    norm_const = 1.0 / (t_max - t_min)

    return np.log(norm_const)

def ln_prior_ln_t(ln_t_b, t_min=c.min_t, t_max=c.max_t):
    """
    Return the prior probability on the natural log of the binary's birth time (age).

    """

    t_b = np.exp(ln_t_b)

    if t_b < t_min or t_b > t_max: return -np.inf
    norm_const = 1.0 / (t_max - t_min)
    return np.log(norm_const * t_b)
<commit_msg>Fixed minor bug in priors.py<commit_after># -*- coding: utf-8 -*-

import numpy as np
from scipy.stats import maxwell

from . import constants as c

def ln_prior(x, dart):
    """
    Calculate all the prior probabilities.

    """

    if dart.second_SN:
        if dart.prior_pos is None:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, v_kick2, theta_kick2, phi_kick2, ln_t_b = x
        else:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, v_kick2, theta_kick2, phi_kick2, ra_b, dec_b, ln_t_b = x
    else:
        if dart.prior_pos is None:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, ln_t_b = x
        else:
            ln_M1, ln_M2, ln_a, ecc, v_kick1, theta_kick1, phi_kick1, ra_b, dec_b, ln_t_b = x

    # Set defaults
    kick_sigma = c.v_kick_sigma
    M1_alpha = c.alpha
    mass_function = 'Salpeter'
    M1_min = c.min_mass_M1
    M1_max = c.max_mass_M1
    M2_min = c.min_mass_M2
    a_min = c.min_a
    a_max = c.max_a
    t_min = c.min_t
    t_max = c.max_t
    # End defaults

    # Set values according to inputs
    for key, value in dart.prior_kwargs.items():
        if key == 'kick_sigma': kick_sigma = value
        if key == 'M1_alpha': M1_alpha = value
        if key == 'M1_min': M1_min = value
        if key == 'M1_max': M1_max = value
        if key == 'M2_min': M2_min = value
        if key == 'a_min': a_min = value
        if key == 'a_max': a_max = value
        if key == 't_min': t_min = value
        if key == 't_max': t_max = value
        if key == 'mass_function': mass_function = value

    # Calculate prior probabilities
    lp = 0.0
    lp += dart.prior_M1(ln_M1, mass_function=mass_function, alpha=M1_alpha, M1_min=M1_min, M1_max=M1_max)
    lp += dart.prior_M2(ln_M2, ln_M1, M2_min=M2_min)
    lp += dart.prior_ecc(ecc)
    lp += dart.prior_a(ln_a, ecc, a_min=a_min, a_max=a_max)
    lp += dart.prior_v_kick1(v_kick1, sigma=kick_sigma)
    lp += dart.prior_theta_kick1(theta_kick1)
    lp += dart.prior_phi_kick1(phi_kick1)

    if dart.second_SN:
        lp += dart.prior_v_kick2(v_kick2, sigma=kick_sigma)
        lp += dart.prior_theta_kick2(theta_kick2)
        lp += dart.prior_phi_kick2(phi_kick2)

    if dart.prior_pos is None:
        lp += dart.prior_t(ln_t_b, t_min=t_min, t_max=t_max)
    else:
        lp += dart.prior_pos(ra_b, dec_b, ln_t_b)

    return lp

def ln_prior_M1(M1, mass_function='Salpeter', alpha=c.alpha, M1_min=c.min_mass_M1, M1_max=c.max_mass_M1):
    """
    Return the prior probability on M1: P(M1).

    """

    if M1 < M1_min or M1 > M1_max: return -np.inf
    norm_const = (alpha+1.0) / (np.power(M1_max, alpha+1.0) - np.power(M1_min, alpha+1.0))
    return np.log( norm_const * np.power(M1, alpha) )

def ln_prior_ln_M1(ln_M1, mass_function='Salpeter', alpha=c.alpha, M1_min=c.min_mass_M1, M1_max=c.max_mass_M1):
    """
    Return the prior probability on the natural log of M1: P(ln_M1).

    """

    M1 = np.exp(ln_M1)

    if M1 < M1_min or M1 > M1_max: return -np.inf
    norm_const = (alpha+1.0) / (np.power(M1_max, alpha+1.0) - np.power(M1_min, alpha+1.0))
    return np.log( norm_const * np.power(M1, alpha+1.0) )

def ln_prior_M2(M2, M1, M2_min=c.min_mass_M2):
    """
    Return the prior probability on M2: P(M2 | M1).

    """

    if M2 < M2_min or M2 > M1: return -np.inf
    return np.log(1.0 / M1)

def ln_prior_ln_M2(ln_M2, ln_M1, M2_min=c.min_mass_M2):
    """
    Return the prior probability on the natural log of M2: P(ln_M2 | M1).

    """

    M1 = np.exp(ln_M1)
    M2 = np.exp(ln_M2)

    if M2 < M2_min or M2 > M1: return -np.inf
    return np.log(M2 / M1)

def ln_prior_a(a, ecc, a_min=c.min_a, a_max=c.max_a):
    """
    Return the prior probability on a: P(a).

    """

    if a*(1.0-ecc) < a_min or a*(1.0+ecc) > a_max: return -np.inf
    norm_const = 1.0 / (np.log(a_max / (1.0+ecc)) - np.log(a_min / (1.0-ecc)))

    return np.log( norm_const / a )

def ln_prior_ln_a(ln_a, ecc, a_min=c.min_a, a_max=c.max_a):
    """
    Return the prior probability on the natural log of a: P(ln_a).

    """

    a = np.exp(ln_a)

    if a*(1.0-ecc) < a_min or a*(1.0+ecc) > a_max: return -np.inf
    norm_const = 1.0 / (np.log(a_max / (1.0+ecc)) - np.log(a_min / (1.0-ecc)))

    return np.log( norm_const )

def ln_prior_ecc(ecc):
    """
    Return the prior probability on ecc: P(ecc).

    """

    if ecc < 0.0 or ecc > 1.0: return -np.inf
    return np.log(2.0 * ecc)

def ln_prior_v_kick(v_kick, sigma=c.v_kick_sigma):
    """
    Return the prior probability on v_kick: P(v_kick).

    """

    if v_kick < 0.0: return -np.inf
    return np.log(maxwell.pdf(v_kick, scale=sigma))

def ln_prior_theta_kick(theta_kick):
    """
    Return the prior probability on the SN kick theta: P(theta).

    """

    if theta_kick <= 0.0 or theta_kick >= np.pi: return -np.inf
    return np.log(np.sin(theta_kick) / 2.0)

def ln_prior_phi_kick(phi_kick):
    """
    Return the prior probability on the SN kick phi: P(phi).

    """

    if phi_kick < 0.0 or phi_kick > np.pi: return -np.inf
    return -np.log(np.pi)

def ln_prior_t(t_b, t_min=c.min_t, t_max=c.max_t):
    """
    Return the prior probability on the binary's birth time (age).

    """

    if t_b < t_min or t_b > t_max: return -np.inf
    norm_const = 1.0 / (t_max - t_min)

    return np.log(norm_const)

def ln_prior_ln_t(ln_t_b, t_min=c.min_t, t_max=c.max_t):
    """
    Return the prior probability on the natural log of the binary's birth time (age).

    """

    t_b = np.exp(ln_t_b)

    if t_b < t_min or t_b > t_max: return -np.inf
    norm_const = 1.0 / (t_max - t_min)
    return np.log(norm_const * t_b)
<|endoftext|>


<commit_before>from __future__ import division
import sys
import os
import numpy as np
from math import log
from collections import deque
from random import random,randrange

from . import parameter
from .proposal import DefaultProposalCycle

class Sampler(object):
    """
    Sampler class.
    Initialisation arguments:

    usermodel:
    user defined model to sample

    maxmcmc:
    maximum number of mcmc steps to be used in the sampler

    verbose:
    display debug information on screen
    default: False

    poolsize:
    number of objects for the affine invariant sampling
    default: 1000

    seed:
    Random seed

    proposal:
    JumpProposal class to use (defaults to proposals.DefaultProposalCycle)

    """
    def __init__(self,usermodel,maxmcmc,seed=None, verbose=False, poolsize=1000, proposal=None):
        self.user = usermodel
        self.initial_mcmc = maxmcmc//2
        self.maxmcmc = maxmcmc

        if proposal is None:
            self.proposal = DefaultProposalCycle()
        else:
            self.proposal = proposal

        self.Nmcmc = self.initial_mcmc
        self.Nmcmc_exact = float(self.initial_mcmc)

        self.poolsize = poolsize
        self.evolution_points = deque(maxlen=self.poolsize)
        self.verbose=verbose
        self.acceptance=0.0
        self.initialised=False
        self.samples = [] # the list of samples from the mcmc chain

    def reset(self):
        """
        Initialise the sampler
        """
        np.random.seed(seed=self.seed)
        for n in range(self.poolsize):
          while True:
            if self.verbose > 2: sys.stderr.write("process {0!s} --> generating pool of {1:d} points for evolution --> {2:.0f} % complete\r".format(os.getpid(), self.poolsize, 100.0*float(n+1)/float(self.poolsize)))
            p = self.user.new_point()
            p.logP = self.user.log_prior(p)
            if np.isfinite(p.logP): break
          p.logL=self.user.log_likelihood(p)
          self.evolution_points.append(p)
        if self.verbose > 2: sys.stderr.write("\n")

        self.proposals.set_ensemble(self.evolution_points)

        self.metropolis_hastings(-np.inf)

        if self.verbose > 2: sys.stderr.write("\n")
        if self.verbose > 2: sys.stderr.write("Initial estimated ACL = {0:d}\n".format(self.Nmcmc))
        self.proposals.set_ensemble(self.evolution_points)

        self.initialised=True

    def estimate_nmcmc(self, safety=1, tau=None):
        """
        Estimate autocorrelation length of chain using acceptance fraction
        ACL = (2/acc) - 1
        multiplied by a safety margin of 5
        Uses moving average with decay time tau iterations (default: self.poolsize)
        Taken from W. Farr's github.com/farr/Ensemble.jl
        """
        if tau is None: tau = self.poolsize

        if self.acceptance == 0.0:
            self.Nmcmc_exact = (1.0 + 1.0/tau)*self.Nmcmc_exact
        else:
            self.Nmcmc_exact = (1.0 - 1.0/tau)*self.Nmcmc_exact + (safety/tau)*(2.0/self.acceptance - 1.0)

        self.Nmcmc_exact = float(min(self.Nmcmc_exact,self.maxmcmc))
        self.Nmcmc = max(safety,int(self.Nmcmc_exact))

        return self.Nmcmc

    def produce_sample(self, queue, logLmin ):
        """
        main loop that generates samples and puts them in the queue for the nested sampler object
        """
        if not self.initialised:
          self.reset()
        # Prevent process from zombification if consumer thread exits
        queue.cancel_join_thread()

        self.counter=0

        while True:
            if logLmin.value==np.inf:
                break

            self.metropolis_hastings(logLmin.value)

            outParam = self.evolution_points[np.random.randint(self.poolsize)]

            # Push the sample onto the queue
            queue.put((self.acceptance,self.Nmcmc,outParam))
            # Update the ensemble every now and again
            if (self.counter%(self.poolsize/10))==0 or self.acceptance<0.001:
                self.proposal.set_ensemble(self.evolution_points)
            self.counter += 1

        print "MCMC samples accumulated = ",len(self.samples)
        import numpy.lib.recfunctions as rfn
        self.mcmc_samples = rfn.stack_arrays([self.samples[j].asnparray() for j in range(len(self.samples))],usemask=False)
        np.savetxt(os.path.join('mcmc_chain_%s.dat'%os.getpid()),self.mcmc_samples.ravel(),header=' '.join(self.mcmc_samples.dtype.names),newline='\n',delimiter=' ')
        sys.stderr.write("Sampler process {0!s}, saved chain in {1!s}\n".format(os.getpid(),'mcmc_chain_%s.dat'%os.getpid()))
        sys.stderr.write("Sampler process {0!s}, exiting\n".format(os.getpid()))
        return 0

    def metropolis_hastings(self,logLmin):
        """
        metropolis-hastings loop to generate the new live point taking nmcmc steps
        """
        accepted = 0

        for j in range(self.poolsize):

            oldparam = self.evolution_points.popleft()
            logp_old = self.user.log_prior(oldparam)

            for _ in range(self.Nmcmc):

                newparam = self.proposals.get_sample(oldparam.copy())
                newparam.logP = self.user.log_prior(newparam)
                if newparam.logP-logp_old + self.proposals.log_J > log(random()):
                    newparam.logL = self.user.log_likelihood(newparam)
                    if newparam.logL > logLmin:
                      oldparam = newparam
                      logp_old = newparam.logP
                      accepted+=1
            # Put sample back in the stack
            self.samples.append(oldparam)
            self.evolution_points.append(oldparam)

        self.acceptance = float(accepted)/float(self.poolsize*self.Nmcmc)
        self.estimate_nmcmc()
<commit_msg>deugging<commit_after>from __future__ import division
import sys
import os
import numpy as np
from math import log
from collections import deque
from random import random,randrange

from . import parameter
from .proposal import DefaultProposalCycle

class Sampler(object):
    """
    Sampler class.
    Initialisation arguments:

    usermodel:
    user defined model to sample

    maxmcmc:
    maximum number of mcmc steps to be used in the sampler

    verbose:
    display debug information on screen
    default: False

    poolsize:
    number of objects for the affine invariant sampling
    default: 1000

    seed:
    Random seed

    proposal:
    JumpProposal class to use (defaults to proposals.DefaultProposalCycle)

    """
    def __init__(self,usermodel,maxmcmc,seed=None, verbose=False, poolsize=1000, proposal=None):
        self.user = usermodel
        self.initial_mcmc = maxmcmc//2
        self.maxmcmc = maxmcmc

        if proposal is None:
            self.proposal = DefaultProposalCycle()
        else:
            self.proposal = proposal

        self.Nmcmc = self.initial_mcmc
        self.Nmcmc_exact = float(self.initial_mcmc)

        self.poolsize = poolsize
        self.evolution_points = deque(maxlen=self.poolsize)
        self.verbose=verbose
        self.acceptance=0.0
        self.initialised=False
        self.samples = [] # the list of samples from the mcmc chain

    def reset(self):
        """
        Initialise the sampler
        """
        np.random.seed(seed=self.seed)
        for n in range(self.poolsize):
          while True:
            if self.verbose > 2: sys.stderr.write("process {0!s} --> generating pool of {1:d} points for evolution --> {2:.0f} % complete\r".format(os.getpid(), self.poolsize, 100.0*float(n+1)/float(self.poolsize)))
            p = self.user.new_point()
            p.logP = self.user.log_prior(p)
            if np.isfinite(p.logP): break
          p.logL=self.user.log_likelihood(p)
          self.evolution_points.append(p)
        if self.verbose > 2: sys.stderr.write("\n")

        self.proposals.set_ensemble(self.evolution_points)

        self.metropolis_hastings(-np.inf)

        if self.verbose > 2: sys.stderr.write("\n")
        if self.verbose > 2: sys.stderr.write("Initial estimated ACL = {0:d}\n".format(self.Nmcmc))
        self.proposals.set_ensemble(self.evolution_points)

        self.initialised=True

    def estimate_nmcmc(self, safety=1, tau=None):
        """
        Estimate autocorrelation length of chain using acceptance fraction
        ACL = (2/acc) - 1
        multiplied by a safety margin of 5
        Uses moving average with decay time tau iterations (default: self.poolsize)
        Taken from W. Farr's github.com/farr/Ensemble.jl
        """
        if tau is None: tau = self.poolsize

        if self.acceptance == 0.0:
            self.Nmcmc_exact = (1.0 + 1.0/tau)*self.Nmcmc_exact
        else:
            self.Nmcmc_exact = (1.0 - 1.0/tau)*self.Nmcmc_exact + (safety/tau)*(2.0/self.acceptance - 1.0)

        self.Nmcmc_exact = float(min(self.Nmcmc_exact,self.maxmcmc))
        self.Nmcmc = max(safety,int(self.Nmcmc_exact))

        return self.Nmcmc

    def produce_sample(self, queue, logLmin ):
        """
        main loop that generates samples and puts them in the queue for the nested sampler object
        """
        if not self.initialised:
          self.reset()
        # Prevent process from zombification if consumer thread exits
        queue.cancel_join_thread()

        self.counter=0

        while True:
            if logLmin.value==np.inf:
                break

            self.metropolis_hastings(logLmin.value)

            outParam = self.evolution_points[np.random.randint(self.poolsize)]

            # Push the sample onto the queue
            queue.put((self.acceptance,self.Nmcmc,outParam))
            # Update the ensemble every now and again
            if (self.counter%(self.poolsize/10))==0 or self.acceptance<0.001:
                self.proposal.set_ensemble(self.evolution_points)
            self.counter += 1

        print "MCMC samples accumulated = ",len(self.samples)
        import numpy.lib.recfunctions as rfn
        self.mcmc_samples = rfn.stack_arrays([self.samples[j].asnparray() for j in range(len(self.samples))],usemask=False)
        np.savetxt(os.path.join('mcmc_chain_%s.dat'%os.getpid()),self.mcmc_samples.ravel(),header=' '.join(self.mcmc_samples.dtype.names),newline='\n',delimiter=' ')
        sys.stderr.write("Sampler process {0!s}, saved chain in {1!s}\n".format(os.getpid(),'mcmc_chain_%s.dat'%os.getpid()))
        sys.stderr.write("Sampler process {0!s}, exiting\n".format(os.getpid()))
        return 0

    def metropolis_hastings(self,logLmin):
        """
        metropolis-hastings loop to generate the new live point taking nmcmc steps
        """
        accepted = 0

        for j in range(self.poolsize):

            oldparam = self.evolution_points.popleft()
            logp_old = self.user.log_prior(oldparam)

            for n in range(self.Nmcmc):

                newparam = self.proposals.get_sample(oldparam.copy())
                newparam.logP = self.user.log_prior(newparam)
                if newparam.logP-logp_old + self.proposals.log_J > log(random()):
                    newparam.logL = self.user.log_likelihood(newparam)
                    if newparam.logL > logLmin:
                      oldparam = newparam
                      logp_old = newparam.logP
                      accepted+=1

            # Put sample back in the stack
            self.samples.append(oldparam)
            self.evolution_points.append(oldparam)

        self.acceptance = float(accepted)/float(self.poolsize*self.Nmcmc)
        self.estimate_nmcmc()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""
    wsgi
    ~~~~

    entrypoint wsgi script
"""

from werkzeug.serving import run_simple
from werkzeug.wsgi import DispatcherMiddleware
from biblib import app

application = app.create_app()

if __name__ == "__main__":

    run_simple(
        '0.0.0.0', 4000, application, use_reloader=False, use_debugger=True
    )
<commit_msg>Werkzeug import fix for Python 3<commit_after># -*- coding: utf-8 -*-
"""
    wsgi
    ~~~~

    entrypoint wsgi script
"""

from werkzeug.serving import run_simple
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from biblib import app

application = app.create_app()

if __name__ == "__main__":

    run_simple(
        '0.0.0.0', 4000, application, use_reloader=False, use_debugger=True
    )
<|endoftext|>


<commit_before>#!/usr/bin/env python3
import os
import sys
import warnings
#import requests
from math import log
from flask import Flask, render_template, request
from indCAPS import hammingBool, hamming, revComp, baseNumbers, deltaG, deltaS
from indCAPS import saltAdjusted, basicTemp, nearestNeighbor, estimateTM
from indCAPS import lastSharedBase, scanUnshared, scanSequence, evaluateSites
from indCAPS import generatePrimer, compareEnzymes, makePrimer, enzymes

# Set up Flask stuff
app = Flask(__name__)
#app.config.from_object(os.environ['APP_SETTINGS'])
app.jinja_env.trim_blocks = True

@app.route('/', methods=['GET','POST'])
def index():
	return(render_template('index.html'))

@app.route('/results', methods=['GET','POST'])
def results():
	seq1 = False
	seq2 = False
	hamDist = False
	errors = []
	allResults = []
	if request.method == "POST":
		# Get stuff the user entered
		try:
			seq1 = request.form['seq1']
			seq2 = request.form['seq2']
			hamDist = int(request.form['ham'])
		except:
			errors.append("No sequences provided.")
		if seq1 and seq2 and hamDist:
			# Call function to evaluate enzymes
			for eachEnzyme in enzymes:
				enzymeName = eachEnzyme
				enzymeValue = enzymes[eachEnzyme]
				enzymeResults = evaluateSites(seq1,seq2,enzymeValue,hamDist, enzymeName)
				if enzymeResults is not None:
					allResults.append(enzymeResults)
			# Call function to generate primers

			# Call function to generate output

			# Display output
	return(render_template('results.html',allResults=allResults))

if __name__ == '__main__':
	app.run()
<commit_msg>January 17th, 2017<commit_after>#!/usr/bin/env python3
import os
import sys
import warnings
#import requests
from math import log
from flask import Flask, render_template, request
from indCAPS import hammingBool, hamming, revComp, baseNumbers, deltaG, deltaS
from indCAPS import saltAdjusted, basicTemp, nearestNeighbor, estimateTM
from indCAPS import lastSharedBase, scanUnshared, scanSequence, evaluateSites
from indCAPS import generatePrimer, compareEnzymes, makePrimer, enzymes

# Set up Flask stuff
app = Flask(__name__,instance_path="/var/lib/openshift/587e498942d9f524f40001d7/app-root/repo")
#app.config.from_object(os.environ['APP_SETTINGS'])
app.jinja_env.trim_blocks = True

@app.route('/', methods=['GET','POST'])
def index():
	return(render_template('index.html'))

@app.route('/results', methods=['GET','POST'])
def results():
	seq1 = False
	seq2 = False
	hamDist = False
	errors = []
	allResults = []
	if request.method == "POST":
		# Get stuff the user entered
		try:
			seq1 = request.form['seq1']
			seq2 = request.form['seq2']
			hamDist = int(request.form['ham'])
		except:
			errors.append("No sequences provided.")
		if seq1 and seq2 and hamDist:
			# Call function to evaluate enzymes
			for eachEnzyme in enzymes:
				enzymeName = eachEnzyme
				enzymeValue = enzymes[eachEnzyme]
				enzymeResults = evaluateSites(seq1,seq2,enzymeValue,hamDist, enzymeName)
				if enzymeResults is not None:
					allResults.append(enzymeResults)
			# Call function to generate primers

			# Call function to generate output

			# Display output
	return(render_template('results.html',allResults=allResults))

if __name__ == '__main__':
	app.run()
<|endoftext|>


<commit_before>from hunt import logger
from flask import request

import json
import requests

def hunt_activity_id(hunt_id):
    return "{}/hunts/{}".format(request.host_url, hunt_id)

def hunt_activity(hunt):
    return {
        "id": hunt_activity_id(hunt.hunt_id),
        "definition": {
            "type": "{}/activities/type/scavengerhunt".format(
                request.host_url),
            "name": hunt.name
        },
        "objectType": "Activity"
    }

def begin_hunt_statement(actor, hunt):
    return {
        "actor": actor,
        "verb": {
            "id": "http://adlnet.gov/expapi/verbs/registered",
            "display": {
                "en-US": "registered"
            }
        },
        "object": hunt_activity(hunt)
    }

def verb_completed():
    return {
        "id": "http://adlnet.gov/expapi/verbs/completed",
        "display": {
            "en-US": "completed"
        }
    }

def found_item_statement(actor, hunt, item):
    return {
        "actor": actor,
        "verb": {
            "id": "{}/verbs/found".format(request.host_url),
            "display": {
                "en-US": "found"
            }
        },
        "object": {
            "id": "{}/hunts/{}".format(request.host_url, hunt.hunt_id),
            "definition": {
                "type": "{}/activities/type/scavengerhunt".format(
                    request.host_url),
                "name": "found item {} from {}".format(item.name, hunt.name)
            },
            "objectType": "Activity"
        },
        "context": {
            "contextActivities": {
                "parent": hunt_activity(hunt)
            }
        }
    }

# participant found all required items but not all items
def found_all_required_statement(actor, hunt):
    return {
        'actor': actor,
        'verb': verb_completed(),
        "object": {
            #activity name suggestions?
            "id": "{}/activities/findallrequired/hunts/{}".format(
                request.host_url, hunt.hunt_id),
            "description": {
                "type": "{}/activities/type/scavengerhunt".format(
                    request.host_url),
                "name": "finding all required items for {}".format(hunt.name)
            }
        }
    }

# participant found every item
def completed_hunt_statement(actor, hunt):
    return {
        'actor': actor,
        'verb': verb_completed(),
        "object": hunt_activity(hunt)
    }

def send_statement(statement, setting):
    response = requests.post(
        setting.endpoint,
        headers={
            "Content-Type": "application/json",
            "x-experience-api-version": "1.0.0"
        },
        data=json.dumps(statement),
        auth=(setting.login, setting.password)
    )
    logger.debug('statement response status: %s', response.status_code)
    return response

def put_state(data, params, setting):
    response = requests.put(
        'https://testsite.waxlrs.com/TCAPI/activities/state',
        params=params,
        data=data,
        headers={
            "x-experience-api-version": "1.0.0"
        },
        auth=(setting.login, setting.password)
    )

    logger.debug('put state api respone: %s', response.status_code)
    logger.debug('response.text: %s', response.text)
    return response

def post_state(data, params, setting):
    response = requests.post(
        'https://testsite.waxlrs.com/TCAPI/activities/state',
        params=params,
        data=data,
        headers={
            "x-experience-api-version": "1.0.0"
        },
        auth=(setting.login, setting.password)
    )
    logger.debug('post state api respone: %s', response.status_code)
    logger.debug('response.text: %s', response.text)
    return response

def get_state_response(params, setting):
    response = requests.get(
        'https://testsite.waxlrs.com/TCAPI/activities/state',
        params=params,
        headers={
            "x-experience-api-version": "1.0.0"
        },
        auth=(setting.login, setting.password)
    )
    logger.debug('get state api respone: %s', response.status_code)
    logger.debug('response.text: %s', response.text)
    return response

def default_params(email, hunt_id):
    return {
        'agent': make_agent(email),
        'activityId': "{}/hunts/{}".format(request.host_url, hunt_id),
        'stateId': 'hunt_progress'
    }

# no. just get rid of this
def initialize_state_doc(hunt_id, email, params, data, setting):
    params = params or default_params(email, hunt_id)
    put_state(data, params, setting)

def make_agent(email):
    return json.dumps({'mbox': 'mailto:{}'.format(email)})
<commit_msg>fix json and path bugs<commit_after>from hunt import logger
from flask import request

import json
import requests

def hunt_activity_id(hunt_id):
    return "{}hunts/{}".format(request.host_url, hunt_id)

def hunt_activity(hunt):
    return {
        "id": hunt_activity_id(hunt.hunt_id),
        "definition": {
            "type": "{}activities/type/scavengerhunt".format(
                request.host_url),
            "name": {
                "und": hunt.name
            }
        },
        "objectType": "Activity"
    }

def begin_hunt_statement(actor, hunt):
    logger.debug(
        'participant began hunt. sending statement to Wax')
    return {
        "actor": actor,
        "verb": {
            "id": "http://adlnet.gov/expapi/verbs/registered",
            "display": {
                "en-US": "registered"
            }
        },
        "object": hunt_activity(hunt)
    }

def verb_completed():
    return {
        "id": "http://adlnet.gov/expapi/verbs/completed",
        "display": {
            "en-US": "completed"
        }
    }

def found_item_statement(actor, hunt, item):
    logger.debug(
        'participant found item, %s, sending statement to wax', item.name)
    return {
        "actor": actor,
        "verb": {
            "id": "{}verbs/found".format(request.host_url),
            "display": {
                "en-US": "found"
            }
        },
        "object": {
            "id": "{}hunts/{}/items/{}".format(request.host_url, hunt.hunt_id, item.item_id),
            "definition": {
                "type": "{}activities/type/scavengerhunt".format(
                    request.host_url),
                "name": {
                    "und": "found item {} from {}".format(item.name, hunt.name)
                }
            },
            "objectType": "Activity"
        },
        "context": {
            "contextActivities": {
                "parent": hunt_activity(hunt)
            }
        }
    }

# participant found all required items but not all items
def found_all_required_statement(actor, hunt):
    logger.debug(
        'participant found required items. sending statement to Wax')
    return {
        'actor': actor,
        'verb': verb_completed(),
        "object": {
            #activity name suggestions?
            "id": "{}activities/findallrequired/hunts/{}".format(
                request.host_url, hunt.hunt_id),
            "description": {
                "type": "{}activities/type/scavengerhunt".format(
                    request.host_url),
                "name": {
                    "und": "finding all required items for {}".format(hunt.name)
                }
            }
        }
    }

# participant found every item
def completed_hunt_statement(actor, hunt):
    logger.debug(
        'participant completed hunt. sending statement to Wax')
    return {
        'actor': actor,
        'verb': verb_completed(),
        "object": hunt_activity(hunt)
    }

def send_statement(statement, setting):
    response = requests.post(
        setting.endpoint,
        headers={
            "Content-Type": "application/json",
            "x-experience-api-version": "1.0.0"
        },
        data=json.dumps(statement),
        auth=(setting.login, setting.password)
    )
    logger.debug('statement response status %s %s for statement: %s', response.status_code, response.text, statement)
    return response

def put_state(data, params, setting):
    logger.debug('setting in put state: %s', setting)
    response = requests.put(
        'https://testsite.waxlrs.com/TCAPI/activities/state',
        params=params,
        data=data,
        headers={
            "x-experience-api-version": "1.0.0"
        },
        auth=(setting.login, setting.password)
    )

    logger.debug('put state api respone: %s', response.status_code)
    logger.debug('response.text: %s', response.text)
    return response

def post_state(data, params, setting):
    response = requests.post(
        'https://testsite.waxlrs.com/TCAPI/activities/state',
        params=params,
        data=data,
        headers={
            "x-experience-api-version": "1.0.0"
        },
        auth=(setting.login, setting.password)
    )
    logger.debug('post state api respone: %s', response.status_code)
    logger.debug('response.text: %s', response.text)
    return response

def get_state_response(params, setting):
    response = requests.get(
        'https://testsite.waxlrs.com/TCAPI/activities/state',
        params=params,
        headers={
            "x-experience-api-version": "1.0.0"
        },
        auth=(setting.login, setting.password)
    )
    logger.debug('get state api respone: %s', response.status_code)
    logger.debug('response.text: %s', response.text)
    return response

def default_params(email, hunt_id):
    return {
        'agent': json.dumps(make_agent(email)),
        'activityId': "{}/hunts/{}".format(request.host_url, hunt_id),
        'stateId': 'hunt_progress'
    }

# no. just get rid of this
def initialize_state_doc(hunt_id, email, params, data, setting):
    params = params or default_params(email, hunt_id)
    return put_state(data, params, setting)

def make_agent(email):
    return {"mbox": "mailto:{}".format(email)}
<|endoftext|>