<commit_before># -*- coding: utf-8 -*-
# Copyright 2012 Thamini S.à.R.L    This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

from osv import osv
from osv import fields

class account_voucher(osv.osv):
    _inherit = 'account.voucher'

    def name_get(self, cr, uid, ids, context=None):
        if not ids:
            return []
        if context is None: context = {}
        def _sum_moveline_ids(cr, uid, move_line_ids, context=None):
            debit = credit = 0.0
            for line in self.pool.get('account.voucher.line').browse(cr, uid, move_line_ids, context=context):
                move_line = line.move_line_id
                if move_line.debit:
                    debit += move_line.debit
                elif move_line.credit:
                    credit += move_line.credit
            return abs(credit - debit)
        return [(r['id'], (str("%.2f (%.2f)" % (r['amount'], _sum_moveline_ids(cr, uid, r['line_ids'], context=context)) or ''))) \
                                for r in self.read(cr, uid, ids, ['amount', 'line_ids'], context, load='_classic_write')]

account_voucher()

class wizard_account_bank_statement_line_reconcile(osv.osv_memory):
    _name = 'account.bank.statement.line.reconcile.wizard'
    _columns = {
        'state': fields.selection([('choose_lines','Choose Lines'),('voucher_exist','Voucher Exist')], 'State', required=True),
        'statement_line_id': fields.many2one('account.bank.statement.line', 'Statement Line', required=True),
        'partner_id': fields.many2one('res.partner', 'Partner'),
        'move_line_ids': fields.many2many('account.move.line', 'wizard_id', 'line_id', 'Move Lines'),
    }

    def _default_get_state(self, cr, uid, context=None):
        if context is None:
            context = {}
        statement_line_id = context.get('active_id')
        statement_line_obj = self.pool.get('account.bank.statement.line')
        line = statement_line_obj.browse(cr, uid, statement_line_id, context=context)
        if line.voucher_id and not context.get('force_continue'):
            return 'voucher_exist'
        return 'choose_lines'

    def _default_get_statement_line_id(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('active_id',False)

    def _default_get_partner_id(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('partner_id',False)

    _defaults = {
        'state': _default_get_state,
        'statement_line_id': _default_get_statement_line_id,
        'partner_id': _default_get_partner_id,
    }

    def populate_continue(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'choose_lines'}, context=context)

        (act_model, act_id) = self.pool.get('ir.model.data').get_object_reference(cr, uid,
                                                                'account_payment_import_multiline',
                                                                'action_account_bank_statement_line_reconcile_wizard')
        action = self.pool.get(act_model).read(cr, uid, act_id, [], context=context)
        action['context'] = {'force_continue': 1}
        return action

    def populate_statement(self, cr, uid, ids, context=None):
        if not ids:
            return {}
        voucher_obj = self.pool.get('account.voucher')
        voucher_line_obj = self.pool.get('account.voucher.line')

        wizard = self.browse(cr, uid, ids[0], context=context)
        line = wizard.statement_line_id
        statement = line.statement_id

        statement_currency_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
        if statement.journal_id.currency:
            statement_currency_id = statement.journal_id.currency.id

        voucher_context = context.copy()
        voucher_context['date'] = line.date # use payment date for currency computation
        voucher_amount = line.amount
        voucher_type = line.amount < 0 and 'payment' or 'receipt'

    # TODO: ... implement this for currency!
    #            if line.amount_currency:
    #                amount = currency_obj.compute(cr, uid, line.currency_id.id,
    #                    statement.currency.id, line.amount_currency, context=ctx)
    #            elif (line.invoice and line.invoice.currency_id.id <> statement.currency.id):
    #                amount = currency_obj.compute(cr, uid, line.invoice.currency_id.id,
    #                    statement.currency.id, amount, context=ctx)

        mvline_ids = [ x.id for x in wizard.move_line_ids ]
        voucher_context.update({'move_line_ids': mvline_ids})

        default_voucher_lines = voucher_obj.onchange_partner_id(cr, uid, [],
                                        partner_id=line.partner_id.id or False,
                                        journal_id=statement.journal_id.id,
                                        price=abs(voucher_amount),
                                        currency_id=statement_currency_id,
                                        ttype=voucher_type,
                                        date=line.date,
                                        context=voucher_context)
        voucher_data = {
                'type': voucher_type,
                'name': line.name,
                'partner_id': line.partner_id.id or False,
                'period_id': statement.period_id.id,
                'journal_id': statement.journal_id.id,
                'account_id': line.account_id.id,
                'company_id': statement.company_id.id,
                'currency_id': statement_currency_id,
                'date': line.date,
                'amount': abs(voucher_amount),
        }
        voucher_id = voucher_obj.create(cr, uid, voucher_data, context=voucher_context)

        for voucher_line in default_voucher_lines.get('value',{}).get('line_ids',[]):
            if voucher_line['move_line_id'] in mvline_ids:
                voucher_line['voucher_id'] = voucher_id
                voucher_line_obj.create(cr, uid, voucher_line, context=context)

        self.pool.get('account.bank.statement.line').write(cr, uid, [line.id], {'voucher_id': voucher_id})
        return {}

wizard_account_bank_statement_line_reconcile()
<commit_msg>[FIX] wizard 'statement line reconcile': voucher account_id shoud be default debit/credit account<commit_after># -*- coding: utf-8 -*-
# Copyright 2012 Thamini S.à.R.L    This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).

from osv import osv
from osv import fields

class account_voucher(osv.osv):
    _inherit = 'account.voucher'

    def name_get(self, cr, uid, ids, context=None):
        if not ids:
            return []
        if context is None: context = {}
        def _sum_moveline_ids(cr, uid, move_line_ids, context=None):
            debit = credit = 0.0
            for line in self.pool.get('account.voucher.line').browse(cr, uid, move_line_ids, context=context):
                move_line = line.move_line_id
                if move_line.debit:
                    debit += move_line.debit
                elif move_line.credit:
                    credit += move_line.credit
            return abs(credit - debit)
        return [(r['id'], (str("%.2f (%.2f)" % (r['amount'], _sum_moveline_ids(cr, uid, r['line_ids'], context=context)) or ''))) \
                                for r in self.read(cr, uid, ids, ['amount', 'line_ids'], context, load='_classic_write')]

account_voucher()

class wizard_account_bank_statement_line_reconcile(osv.osv_memory):
    _name = 'account.bank.statement.line.reconcile.wizard'
    _columns = {
        'state': fields.selection([('choose_lines','Choose Lines'),('voucher_exist','Voucher Exist')], 'State', required=True),
        'statement_line_id': fields.many2one('account.bank.statement.line', 'Statement Line', required=True),
        'partner_id': fields.many2one('res.partner', 'Partner'),
        'move_line_ids': fields.many2many('account.move.line', 'wizard_id', 'line_id', 'Move Lines'),
    }

    def _default_get_state(self, cr, uid, context=None):
        if context is None:
            context = {}
        statement_line_id = context.get('active_id')
        statement_line_obj = self.pool.get('account.bank.statement.line')
        line = statement_line_obj.browse(cr, uid, statement_line_id, context=context)
        if line.voucher_id and not context.get('force_continue'):
            return 'voucher_exist'
        return 'choose_lines'

    def _default_get_statement_line_id(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('active_id',False)

    def _default_get_partner_id(self, cr, uid, context=None):
        if context is None:
            context = {}
        return context.get('partner_id',False)

    _defaults = {
        'state': _default_get_state,
        'statement_line_id': _default_get_statement_line_id,
        'partner_id': _default_get_partner_id,
    }

    def populate_continue(self, cr, uid, ids, context=None):
        self.write(cr, uid, ids, {'state': 'choose_lines'}, context=context)

        (act_model, act_id) = self.pool.get('ir.model.data').get_object_reference(cr, uid,
                                                                'account_payment_import_multiline',
                                                                'action_account_bank_statement_line_reconcile_wizard')
        action = self.pool.get(act_model).read(cr, uid, act_id, [], context=context)
        action['context'] = {'force_continue': 1}
        return action

    def populate_statement(self, cr, uid, ids, context=None):
        if not ids:
            return {}
        voucher_obj = self.pool.get('account.voucher')
        voucher_line_obj = self.pool.get('account.voucher.line')

        wizard = self.browse(cr, uid, ids[0], context=context)
        line = wizard.statement_line_id
        statement = line.statement_id

        statement_currency_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id
        if statement.journal_id.currency:
            statement_currency_id = statement.journal_id.currency.id

        voucher_context = context.copy()
        voucher_context['date'] = line.date # use payment date for currency computation
        voucher_amount = line.amount
        voucher_type = line.amount < 0 and 'payment' or 'receipt'

    # TODO: ... implement this for currency!
    #            if line.amount_currency:
    #                amount = currency_obj.compute(cr, uid, line.currency_id.id,
    #                    statement.currency.id, line.amount_currency, context=ctx)
    #            elif (line.invoice and line.invoice.currency_id.id <> statement.currency.id):
    #                amount = currency_obj.compute(cr, uid, line.invoice.currency_id.id,
    #                    statement.currency.id, amount, context=ctx)

        mvline_ids = [ x.id for x in wizard.move_line_ids ]
        voucher_context.update({'move_line_ids': mvline_ids})

        default_voucher_lines = voucher_obj.onchange_partner_id(cr, uid, [],
                                        partner_id=line.partner_id.id or False,
                                        journal_id=statement.journal_id.id,
                                        price=abs(voucher_amount),
                                        currency_id=statement_currency_id,
                                        ttype=voucher_type,
                                        date=line.date,
                                        context=voucher_context)

        if line.amount >= 0:
            account_id = statement.journal_id.default_credit_account_id.id
        else:
            account_id = statement.journal_id.default_debit_account_id.id

        voucher_data = {
                'type': voucher_type,
                'name': line.name,
                'partner_id': line.partner_id.id or False,
                'period_id': statement.period_id.id,
                'journal_id': statement.journal_id.id,
                'account_id': account_id,
                'company_id': statement.company_id.id,
                'currency_id': statement_currency_id,
                'date': line.date,
                'amount': abs(voucher_amount),
        }
        voucher_id = voucher_obj.create(cr, uid, voucher_data, context=voucher_context)

        for voucher_line in default_voucher_lines.get('value',{}).get('line_ids',[]):
            if voucher_line['move_line_id'] in mvline_ids:
                voucher_line['voucher_id'] = voucher_id
                voucher_line_obj.create(cr, uid, voucher_line, context=context)

        self.pool.get('account.bank.statement.line').write(cr, uid, [line.id], {'voucher_id': voucher_id})
        return {}

wizard_account_bank_statement_line_reconcile()
<|endoftext|>


<commit_before>#!/usr/bin/python
# Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Collectd plugin for getting statistics from Cinder
import collectd

import collectd_openstack as openstack

PLUGIN_NAME = 'cinder'
INTERVAL = openstack.INTERVAL

class CinderStatsPlugin(openstack.CollectdPlugin):
    """ Class to report the statistics on Cinder objects.

        number of volumes broken down by state
        total size of volumes usable and in error state
    """

    def __init__(self, *args, **kwargs):
        super(CinderStatsPlugin, self).__init__(*args, **kwargs)
        self.plugin = PLUGIN_NAME
        self.interval = INTERVAL
        self.pagination_limit = 500

    def itermetrics(self):

        volumes_details = self.get_objects('cinder', 'volumes',
                                           params={'all_tenants': 1},
                                           detail=True)

        def groupby(d):
            return d.get('status', 'unknown').lower()

        def count_size_bytes(d):
            return d.get('size', 0) * 10 ** 9

        status = self.count_objects_group_by(volumes_details,
                                             group_by_func=groupby)
        for s, nb in status.iteritems():
            yield {
                'plugin_instance': 'volumes',
                'type_instance': s,
                'values': nb
            }

        sizes = self.count_objects_group_by(volumes_details,
                                            group_by_func=groupby,
                                            count_func=count_size_bytes)
        for n, size in sizes.iteritems():
            yield {
                'plugin_instance': 'volumes_size',
                'type_instance': n,
                'values': size
            }

        snaps_details = self.get_objects('cinder', 'snapshots',
                                         params={'all_tenants': 1})
        status_snaps = self.count_objects_group_by(snaps_details,
                                                   group_by_func=groupby)
        for s, nb in status_snaps.iteritems():
            yield {
                'plugin_instance': 'snapshots',
                'type_instance': s,
                'values': nb
            }

        sizes = self.count_objects_group_by(snaps_details,
                                            group_by_func=groupby,
                                            count_func=count_size_bytes)
        for n, size in sizes.iteritems():
            yield {
                'plugin_instance': 'snapshots_size',
                'type_instance': n,
                'values': size
            }

plugin = CinderStatsPlugin(collectd, PLUGIN_NAME)

def config_callback(conf):
    plugin.config_callback(conf)

def notification_callback(notification):
    plugin.notification_callback(notification)

def read_callback():
    plugin.conditional_read_callback()

collectd.register_config(config_callback)
collectd.register_notification(notification_callback)
collectd.register_read(read_callback, INTERVAL)
<commit_msg>Use Cinder API v2<commit_after>#!/usr/bin/python
# Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Collectd plugin for getting statistics from Cinder
import collectd

import collectd_openstack as openstack

PLUGIN_NAME = 'cinder'
INTERVAL = openstack.INTERVAL

class CinderStatsPlugin(openstack.CollectdPlugin):
    """ Class to report the statistics on Cinder objects.

        number of volumes broken down by state
        total size of volumes usable and in error state
    """

    def __init__(self, *args, **kwargs):
        super(CinderStatsPlugin, self).__init__(*args, **kwargs)
        self.plugin = PLUGIN_NAME
        self.interval = INTERVAL
        self.pagination_limit = 500

    def itermetrics(self):

        volumes_details = self.get_objects('cinderv2', 'volumes',
                                           params={'all_tenants': 1},
                                           detail=True)

        def groupby(d):
            return d.get('status', 'unknown').lower()

        def count_size_bytes(d):
            return d.get('size', 0) * 10 ** 9

        status = self.count_objects_group_by(volumes_details,
                                             group_by_func=groupby)
        for s, nb in status.iteritems():
            yield {
                'plugin_instance': 'volumes',
                'type_instance': s,
                'values': nb
            }

        sizes = self.count_objects_group_by(volumes_details,
                                            group_by_func=groupby,
                                            count_func=count_size_bytes)
        for n, size in sizes.iteritems():
            yield {
                'plugin_instance': 'volumes_size',
                'type_instance': n,
                'values': size
            }

        snaps_details = self.get_objects('cinderv2', 'snapshots',
                                         params={'all_tenants': 1})
        status_snaps = self.count_objects_group_by(snaps_details,
                                                   group_by_func=groupby)
        for s, nb in status_snaps.iteritems():
            yield {
                'plugin_instance': 'snapshots',
                'type_instance': s,
                'values': nb
            }

        sizes = self.count_objects_group_by(snaps_details,
                                            group_by_func=groupby,
                                            count_func=count_size_bytes)
        for n, size in sizes.iteritems():
            yield {
                'plugin_instance': 'snapshots_size',
                'type_instance': n,
                'values': size
            }

plugin = CinderStatsPlugin(collectd, PLUGIN_NAME)

def config_callback(conf):
    plugin.config_callback(conf)

def notification_callback(notification):
    plugin.notification_callback(notification)

def read_callback():
    plugin.conditional_read_callback()

collectd.register_config(config_callback)
collectd.register_notification(notification_callback)
collectd.register_read(read_callback, INTERVAL)
<|endoftext|>


<commit_before>from django.shortcuts import render, redirect

from collection.forms import ThingForm
from collection.models import Thing

def index(request):
    number = 6
    # don't forget the quotes because it's a string, not an integer
    thing = "Thing name"
    return render(request, 'index.html', {
        'number': number,
        # don't forget to pass it in, and the last comma
        'thing': thing,
    })

def thing_detail(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # and pass to the template
    return render(request, 'things/thing_detail.html', {
        'thing': thing,
    })

def edit_thing(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # set the form we're using...
    form_class = ThingForm

    # if we're coming to this view from a submitted form,
    if request.method == 'POST':
        # grab the data from the submitted form
        form = form_class(data=request.POST, instance=thing)

        if form.is_valid():
            # save the new data
            form.save()
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class(instance=thing)

    # and render the template
    return render(request, 'things/edit_thing.html', {
        'thing': thing,
        'form': form,
    })
<commit_msg>End of Chapter 8<commit_after>from django.shortcuts import render, redirect

from collection.forms import ThingForm
from collection.models import Thing

def index(request):
    number = 6
    # don't forget the quotes because it's a string, not an integer
    thing = "Thing name"
    return render(request, 'index.html', {
        'number': number,
        # don't forget to pass it in, and the last comma
        'thing': thing,
    })

def thing_detail(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # and pass to the template
    return render(request, 'things/thing_detail.html', {
        'thing': thing,
    })

def edit_thing(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # set the form we're using...
    form_class = ThingForm

    # if we're coming to this view from a submitted form,
    if request.method == 'POST':
        # grab the data from the submitted form
        form = form_class(data=request.POST, instance=thing)

        if form.is_valid():
            # save the new data
            form.save()
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class(instance=thing)

    # and render the template
    return render(request, 'things/edit_thing.html', {
        'thing': thing,
        'form': form,
    })

def thing_detail(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # and pass to the template
    return render(request, 'things/thing_detail.html', {
        'thing': thing,
    })
<|endoftext|>


<commit_before>from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify

from collection.forms import ThingForm
from collection.models import Thing

def index(request):
    number = 6
    # don't forget the quotes because it's a string, not an integer
    thing = "Thing name"
    return render(request, 'index.html', {
        'number': number,
        # don't forget to pass it in, and the last comma
        'thing': thing,
    })

def thing_detail(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # and pass to the template
    return render(request, 'things/thing_detail.html', {
        'thing': thing,
    })

def edit_thing(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # set the form we're using...
    form_class = ThingForm

    # if we're coming to this view from a submitted form,
    if request.method == 'POST':
        # grab the data from the submitted form
        form = form_class(data=request.POST, instance=thing)

        if form.is_valid():
            # save the new data
            form.save()
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class(instance=thing)

    # and render the template
    return render(request, 'things/edit_thing.html', {
        'thing': thing,
        'form': form,
    })

def create_thing(request):
    form_class = ThingForm

    # if we're coming from a submitted form, do this
    if request.method == 'POST':
        # grab the data from the submitted form and apply to the form
        form = form_class(request.POST)

        if form.is_valid():
            # create an instance but do not save yet
            thing = form.save(commit=False)

            # set the additional details
            thing.user = request.user
            thing.slug = slugify(thing.name)

            # save the object
            thing.save()

            # redirect to our newly created thing
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class()

    return render(request, 'things/create_thing.html', {
        'form': form,
    })

def browse_by_name(request, initial=None):
    if initial:
        things = Thing.objects.filter(
             name__istartswith=initial).order_by('name')
    else:
        things = Thing.objects.all().order_by('name')

    return render(request, 'search/search.html', {
        'things': things,
        'initial': initial,
    })

def thing_detail(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # and pass to the template
    return render(request, 'things/thing_detail.html', {
        'thing': thing,
    })

def edit_thing(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # set the form we're using...
    form_class = ThingForm

    # if we're coming to this view from a submitted form,
    if request.method == 'POST':
        # grab the data from the submitted form
        form = form_class(data=request.POST, instance=thing)

        if form.is_valid():
            # save the new data
            form.save()
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class(instance=thing)

    # and render the template
    return render(request, 'things/edit_thing.html', {
        'thing': thing,
        'form': form,
    })
<commit_msg>End of Chapter 11<commit_after>from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.shortcuts import render, redirect
from django.template.defaultfilters import slugify

from collection.forms import ThingForm
from collection.models import Thing

def index(request):
    number = 6
    # don't forget the quotes because it's a string, not an integer
    thing = "Thing name"
    return render(request, 'index.html', {
        'number': number,
        # don't forget to pass it in, and the last comma
        'thing': thing,
    })

def thing_detail(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # and pass to the template
    return render(request, 'things/thing_detail.html', {
        'thing': thing,
    })

def edit_thing(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # set the form we're using...
    form_class = ThingForm

    # if we're coming to this view from a submitted form,
    if request.method == 'POST':
        # grab the data from the submitted form
        form = form_class(data=request.POST, instance=thing)

        if form.is_valid():
            # save the new data
            form.save()
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class(instance=thing)

    # and render the template
    return render(request, 'things/edit_thing.html', {
        'thing': thing,
        'form': form,
    })

def create_thing(request):
    form_class = ThingForm

    # if we're coming from a submitted form, do this
    if request.method == 'POST':
        # grab the data from the submitted form and apply to the form
        form = form_class(request.POST)

        if form.is_valid():
            # create an instance but do not save yet
            thing = form.save(commit=False)

            # set the additional details
            thing.user = request.user
            thing.slug = slugify(thing.name)

            # save the object
            thing.save()

            # redirect to our newly created thing
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class()

    return render(request, 'things/create_thing.html', {
        'form': form,
    })

def browse_by_name(request, initial=None):
    if initial:
        things = Thing.objects.filter(
             name__istartswith=initial).order_by('name')
    else:
        things = Thing.objects.all().order_by('name')

    return render(request, 'search/search.html', {
        'things': things,
        'initial': initial,
    })

def thing_detail(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # and pass to the template
    return render(request, 'things/thing_detail.html', {
        'thing': thing,
    })

@login_required
def edit_thing(request, slug):
    # grab the object...
    thing = Thing.objects.get(slug=slug)

    # grab the current logged in user and make sure they're the owner of the thing
    if thing.user != request.user:
        raise Http404

    # set the form we're using...
    form_class = ThingForm

    # if we're coming to this view from a submitted form,
    if request.method == 'POST':
        # grab the data from the submitted form
        form = form_class(data=request.POST, instance=thing)

        if form.is_valid():
            # save the new data
            form.save()
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class(instance=thing)

    # and render the template
    return render(request, 'things/edit_thing.html', {
        'thing': thing,
        'form': form,
    })

def create_thing(request):
    form_class = ThingForm

    # if we're coming from a submitted form, do this
    if request.method == 'POST':
        # grab the data from the submitted form and apply to the form
        form = form_class(request.POST)

        if form.is_valid():
            # create an instance but do not save yet
            thing = form.save(commit=False)

            # set the additional details
            thing.user = request.user
            thing.slug = slugify(thing.name)

            # save the object
            thing.save()

            # redirect to our newly created thing
            return redirect('thing_detail', slug=thing.slug)

    # otherwise just create the form
    else:
        form = form_class()

    return render(request, 'things/create_thing.html', {
        'form': form,
    })
<|endoftext|>


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

"""
LibreDTE
Copyright (C) SASCO SpA (https://sasco.cl)

Este programa es software libre: usted puede redistribuirlo y/o modificarlo bajo
los términos de la Licencia Pública General Affero de GNU publicada por la
Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o (a su
elección) cualquier versión posterior de la misma.

Este programa se distribuye con la esperanza de que sea útil, pero SIN GARANTÍA
ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD PARA UN
PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública General
Affero de GNU para obtener una información más detallada.

Debería haber recibido una copia de la Licencia Pública General Affero de GNU
junto a este programa.
En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
"""

"""
Comando para monitorear un directorio por archivos con cierto formato e ir creando
los DTE asociados y sus PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2017-12-29
"""

# módulos usados
import os, os.path
import time
import shutil
import subprocess
from json import dumps as json_encode

# opciones en formato largo
long_options = ['emisor=', 'formato=', 'encoding=', 'dir_entrada=', 'dir_salida=', 'email']

# función principal del comando
def main(Cliente, args, config) :
    emisor, formato, encoding, dir_entrada, dir_salida, email = parseArgs(args)
    if emisor == None :
        print('Debe especificar el emisor que creará los documentos')
        return 1
    if not dir_entrada or not os.path.exists(dir_entrada) :
        print('Debe especificar un directorio de entrada válido para los archivos a generar')
        return 1
    if not dir_salida :
        print('Debe especificar un directorio de salida para los archivos a generar')
        return 1
    # crear directorio para archivos si no existen
    if not os.path.exists(dir_salida) :
        os.makedirs(dir_salida)
    # directorio del comando principal
    cmd_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    # lanzar monitor en el directorio
    print('Iniciando monitor en el directorio:', dir_entrada)
    print('Para finalizar el monitoreo utilizar Ctrl+C')
    try :
        while True :
            files = os.scandir(dir_entrada)
            for f in files :
                if not f.is_dir() :
                    # crear directorio y mover archivo de entrada al directorio que corresponde
                    dir_dte = os.path.abspath(dir_salida)+'/'+f.name
                    print('Procesando archivo:', f.name, end='... ')
                    if os.path.exists(dir_dte) :
                        shutil.rmtree(dir_dte)
                    os.makedirs(dir_dte)
                    archivo_solicitud = dir_dte+'/solicitud_'+f.name
                    os.rename(f.path, archivo_solicitud)
                    # generar DTE
                    if os.name == 'posix':
                        cmd = "python3"
                    elif os.name == 'nt' :
                        cmd = "python.exe"
                    cmd += " "+cmd_dir+"/libredte-cliente.py dte_generar"
                    cmd += " --url="+config["auth"]["url"]+" --hash="+config["auth"]["hash"]
                    if formato in ('json', 'xml') :
                        cmd += " --"+formato+"="+archivo_solicitud
                    else :
                        cmd += " --archivo="+archivo_solicitud+" --formato="+formato
                    cmd += " --encoding="+encoding
                    cmd += " --dir="+dir_dte
                    if email :
                        cmd += " --email"
                    try :
                        subprocess.check_output(cmd.split(" "))
                        print("[Ok]")
                    except subprocess.CalledProcessError as e :
                        print("[Mal]")
                        with open(dir_dte+'/dte_generar.log', 'w') as f :
                            f.write(e.output.decode('utf-8'))
            time.sleep(1)
    except KeyboardInterrupt :
        print()
        return 0

# función que procesa los argumentos del comando
def parseArgs(args) :
    emisor = None
    formato = 'json'
    encoding = 'UTF-8'
    dir_entrada = ''
    dir_salida = ''
    email = 0
    for var, val in args:
        if var == '--emisor' :
            emisor = val
        if var == '--formato' :
            formato = val
        if var == '--encoding' :
            encoding = val
        elif var == '--dir_entrada' :
            dir_entrada = val
        elif var == '--dir_salida' :
            dir_salida = val
        elif var == '--email' :
            email = 1
    return emisor, formato, encoding, dir_entrada, dir_salida, email
<commit_msg>Se puede deshabilitar normalización en el comando que monitorea un directorio<commit_after># -*- coding: utf-8 -*-

"""
LibreDTE
Copyright (C) SASCO SpA (https://sasco.cl)

Este programa es software libre: usted puede redistribuirlo y/o modificarlo bajo
los términos de la Licencia Pública General Affero de GNU publicada por la
Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o (a su
elección) cualquier versión posterior de la misma.

Este programa se distribuye con la esperanza de que sea útil, pero SIN GARANTÍA
ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD PARA UN
PROPÓSITO DETERMINADO. Consulte los detalles de la Licencia Pública General
Affero de GNU para obtener una información más detallada.

Debería haber recibido una copia de la Licencia Pública General Affero de GNU
junto a este programa.
En caso contrario, consulte <http://www.gnu.org/licenses/agpl.html>.
"""

"""
Comando para monitorear un directorio por archivos con cierto formato e ir creando
los DTE asociados y sus PDF
@author Esteban De La Fuente Rubio, DeLaF (esteban[at]sasco.cl)
@version 2018-01-19
"""

# módulos usados
import os, os.path
import time
import shutil
import subprocess
from json import dumps as json_encode

# opciones en formato largo
long_options = ['emisor=', 'formato=', 'encoding=', 'dir_entrada=', 'dir_salida=', 'normalizar=', 'email']

# función principal del comando
def main(Cliente, args, config) :
    emisor, formato, encoding, dir_entrada, dir_salida, normalizar, email = parseArgs(args)
    if emisor == None :
        print('Debe especificar el emisor que creará los documentos')
        return 1
    if not dir_entrada or not os.path.exists(dir_entrada) :
        print('Debe especificar un directorio de entrada válido para los archivos a generar')
        return 1
    if not dir_salida :
        print('Debe especificar un directorio de salida para los archivos a generar')
        return 1
    # crear directorio para archivos si no existen
    if not os.path.exists(dir_salida) :
        os.makedirs(dir_salida)
    # directorio del comando principal
    cmd_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
    # lanzar monitor en el directorio
    print('Iniciando monitor en el directorio:', dir_entrada)
    print('Para finalizar el monitoreo utilizar Ctrl+C')
    try :
        while True :
            files = os.scandir(dir_entrada)
            for f in files :
                if not f.is_dir() :
                    # crear directorio y mover archivo de entrada al directorio que corresponde
                    dir_dte = os.path.abspath(dir_salida)+'/'+f.name
                    print('Procesando archivo:', f.name, end='... ')
                    if os.path.exists(dir_dte) :
                        shutil.rmtree(dir_dte)
                    os.makedirs(dir_dte)
                    archivo_solicitud = dir_dte+'/solicitud_'+f.name
                    os.rename(f.path, archivo_solicitud)
                    # generar DTE
                    if os.name == 'posix':
                        cmd = "python3"
                    elif os.name == 'nt' :
                        cmd = "python.exe"
                    cmd += " "+cmd_dir+"/libredte-cliente.py dte_generar"
                    cmd += " --url="+config["auth"]["url"]+" --hash="+config["auth"]["hash"]
                    if formato in ('json', 'xml') :
                        cmd += " --"+formato+"="+archivo_solicitud
                    else :
                        cmd += " --archivo="+archivo_solicitud+" --formato="+formato
                    cmd += " --encoding="+encoding
                    cmd += " --dir="+dir_dte
                    cmd += " --normalizar="+str(normalizar)
                    if email :
                        cmd += " --email"
                    try :
                        subprocess.check_output(cmd.split(" "))
                        print("[Ok]")
                    except subprocess.CalledProcessError as e :
                        print("[Mal]")
                        with open(dir_dte+'/dte_generar.log', 'w') as f :
                            f.write(e.output.decode('utf-8'))
            time.sleep(1)
    except KeyboardInterrupt :
        print()
        return 0

# función que procesa los argumentos del comando
def parseArgs(args) :
    emisor = None
    formato = 'json'
    encoding = 'UTF-8'
    dir_entrada = ''
    dir_salida = ''
    normalizar = 1
    email = 0
    for var, val in args:
        if var == '--emisor' :
            emisor = val
        if var == '--formato' :
            formato = val
        if var == '--encoding' :
            encoding = val
        elif var == '--dir_entrada' :
            dir_entrada = val
        elif var == '--dir_salida' :
            dir_salida = val
        elif var == '--normalizar' :
            normalizar = val
        elif var == '--email' :
            email = 1
    return emisor, formato, encoding, dir_entrada, dir_salida, normalizar, email
<|endoftext|>


<commit_before># Copyright (c) 2010 John Reese
# Licensed under the MIT license

import yaml

from combine import CombineError

MANIFEST_FORMAT = 1

class Manifest:

    def __init__(self):
        self.properties = {"manifest-format": MANIFEST_FORMAT}
        self.actions = []

    def add_property(self, name, value):
        self.properties[name] = value

    def add_action(self, action):
        self.actions.append(action)

    def to_dict(self):
        """
        Generate a dictionary representation of the Manifest object.
        """

        return dict(self.properties, actions=self.actions)

    @classmethod
    def from_dict(cls, data):
        """
        Given a dictionary object, generate a new Manifest object.
        """

        format = data["manifest-format"]
        if (format > MANIFEST_FORMAT or format < 0):
            raise CombineError("Unsupported manifest format")

        mft = Manifest()

        for key, value in data.items():
            if key == "actions":
                for action in value:
                    mft.add_action(action)
            else:
                mft.add_property(key, value)
        for action in data["actions"]:
            mft.add_action(action)

        return mft

    def to_yaml(self):
        """
        Generate a YAML data string representing the Manifest object.
        """

        str = yaml.safe_dump(self.to_dict(), default_flow_style=False)

        return str

    @classmethod
    def from_yaml(cls, str):
        """
        Given a string of YAML data, generate a new Manifest object.
        """

        data = yaml.safe_load(str)
        return cls.from_dict(data)
<commit_msg>Fix issues with loading from dict<commit_after># Copyright (c) 2010 John Reese
# Licensed under the MIT license

import yaml

from combine import CombineError

MANIFEST_FORMAT = 1

class Manifest:

    def __init__(self):
        self.properties = {"manifest-format": MANIFEST_FORMAT}
        self.actions = []

    def add_property(self, name, value):
        self.properties[name] = value

    def add_action(self, action):
        self.actions.append(action)

    def to_dict(self):
        """
        Generate a dictionary representation of the Manifest object.
        """

        return dict(self.properties, actions=self.actions)

    @classmethod
    def from_dict(cls, data):
        """
        Given a dictionary object, generate a new Manifest object.
        """

        format = data["manifest-format"]
        if (format > MANIFEST_FORMAT or format < 0):
            raise CombineError("Unsupported manifest format")

        mft = Manifest()

        for key, value in data.items():
            if key == "actions":
                for action in value:
                    mft.add_action(dict(action))
            else:
                mft.add_property(key, value)

        return mft

    def to_yaml(self):
        """
        Generate a YAML data string representing the Manifest object.
        """

        str = yaml.safe_dump(self.to_dict(), default_flow_style=False)

        return str

    @classmethod
    def from_yaml(cls, str):
        """
        Given a string of YAML data, generate a new Manifest object.
        """

        data = yaml.safe_load(str)
        return cls.from_dict(data)
<|endoftext|>


<commit_before>from datetime import timedelta
import mock

from ddt import ddt, data
from django.test import TestCase
from django.utils import timezone
from django.test.utils import override_settings

from waldur_core.core import utils
from waldur_core.structure import tasks
from waldur_core.structure.tests import factories, models

class TestDetectVMCoordinatesTask(TestCase):

    @mock.patch('requests.get')
    @override_settings(IPSTACK_ACCESS_KEY='IPSTACK_ACCESS_KEY')
    def test_task_sets_coordinates(self, mock_request_get):
        ip_address = "127.0.0.1"
        expected_latitude = 20
        expected_longitude = 20
        instance = factories.TestNewInstanceFactory()

        mock_request_get.return_value.ok = True
        response = {"ip": ip_address, "latitude": expected_latitude, "longitude": expected_longitude}
        mock_request_get.return_value.json.return_value = response
        tasks.detect_vm_coordinates(utils.serialize_instance(instance))

        instance.refresh_from_db()
        self.assertEqual(instance.latitude, expected_latitude)
        self.assertEqual(instance.longitude, expected_longitude)

    @mock.patch('requests.get')
    def test_task_does_not_set_coordinates_if_response_is_not_ok(self, mock_request_get):
        instance = factories.TestNewInstanceFactory()

        mock_request_get.return_value.ok = False
        tasks.detect_vm_coordinates(utils.serialize_instance(instance))

        instance.refresh_from_db()
        self.assertIsNone(instance.latitude)
        self.assertIsNone(instance.longitude)

@ddt
class ThrottleProvisionTaskTest(TestCase):

    @data(
        dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT + 1, retried=True),
        dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT - 1, retried=False),
    )
    def test_if_limit_is_reached_provisioning_is_delayed(self, params):
        link = factories.TestServiceProjectLinkFactory()
        factories.TestNewInstanceFactory.create_batch(
            size=params['size'],
            state=models.TestNewInstance.States.CREATING,
            service_project_link=link)
        vm = factories.TestNewInstanceFactory(
            state=models.TestNewInstance.States.CREATION_SCHEDULED,
            service_project_link=link)
        serialized_vm = utils.serialize_instance(vm)
        mocked_retry = mock.Mock()
        tasks.ThrottleProvisionTask.retry = mocked_retry
        tasks.ThrottleProvisionTask().si(
            serialized_vm,
            'create',
            state_transition='begin_starting').apply()
        self.assertEqual(mocked_retry.called, params['retried'])

class SetErredProvisioningResourcesTaskTest(TestCase):
    def test_stuck_resource_becomes_erred(self):
        with mock.patch('model_utils.fields.now') as mocked_now:
            mocked_now.return_value = timezone.now() - timedelta(hours=4)
            stuck_vm = factories.TestNewInstanceFactory(state=models.TestNewInstance.States.CREATING)
            stuck_volume = factories.TestVolumeFactory(state=models.TestVolume.States.CREATING)

        tasks.SetErredStuckResources().run()

        stuck_vm.refresh_from_db()
        stuck_volume.refresh_from_db()

        self.assertEqual(stuck_vm.state, models.TestNewInstance.States.ERRED)
        self.assertEqual(stuck_volume.state, models.TestVolume.States.ERRED)

    def test_ok_vm_unchanged(self):
        ok_vm = factories.TestNewInstanceFactory(
            state=models.TestNewInstance.States.CREATING,
            modified=timezone.now() - timedelta(minutes=1)
        )
        ok_volume = factories.TestVolumeFactory(
            state=models.TestVolume.States.CREATING,
            modified=timezone.now() - timedelta(minutes=1)
        )
        tasks.SetErredStuckResources().run()

        ok_vm.refresh_from_db()
        ok_volume.refresh_from_db()

        self.assertEqual(ok_vm.state, models.TestNewInstance.States.CREATING)
        self.assertEqual(ok_volume.state, models.TestVolume.States.CREATING)
<commit_msg>Use freeze gun instead of mock.<commit_after>from datetime import timedelta
import mock

from ddt import ddt, data
from django.test import TestCase
from django.utils import timezone
from django.test.utils import override_settings
from freezegun import freeze_time

from waldur_core.core import utils
from waldur_core.structure import tasks
from waldur_core.structure.tests import factories, models

class TestDetectVMCoordinatesTask(TestCase):

    @mock.patch('requests.get')
    @override_settings(IPSTACK_ACCESS_KEY='IPSTACK_ACCESS_KEY')
    def test_task_sets_coordinates(self, mock_request_get):
        ip_address = "127.0.0.1"
        expected_latitude = 20
        expected_longitude = 20
        instance = factories.TestNewInstanceFactory()

        mock_request_get.return_value.ok = True
        response = {"ip": ip_address, "latitude": expected_latitude, "longitude": expected_longitude}
        mock_request_get.return_value.json.return_value = response
        tasks.detect_vm_coordinates(utils.serialize_instance(instance))

        instance.refresh_from_db()
        self.assertEqual(instance.latitude, expected_latitude)
        self.assertEqual(instance.longitude, expected_longitude)

    @mock.patch('requests.get')
    def test_task_does_not_set_coordinates_if_response_is_not_ok(self, mock_request_get):
        instance = factories.TestNewInstanceFactory()

        mock_request_get.return_value.ok = False
        tasks.detect_vm_coordinates(utils.serialize_instance(instance))

        instance.refresh_from_db()
        self.assertIsNone(instance.latitude)
        self.assertIsNone(instance.longitude)

@ddt
class ThrottleProvisionTaskTest(TestCase):

    @data(
        dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT + 1, retried=True),
        dict(size=tasks.ThrottleProvisionTask.DEFAULT_LIMIT - 1, retried=False),
    )
    def test_if_limit_is_reached_provisioning_is_delayed(self, params):
        link = factories.TestServiceProjectLinkFactory()
        factories.TestNewInstanceFactory.create_batch(
            size=params['size'],
            state=models.TestNewInstance.States.CREATING,
            service_project_link=link)
        vm = factories.TestNewInstanceFactory(
            state=models.TestNewInstance.States.CREATION_SCHEDULED,
            service_project_link=link)
        serialized_vm = utils.serialize_instance(vm)
        mocked_retry = mock.Mock()
        tasks.ThrottleProvisionTask.retry = mocked_retry
        tasks.ThrottleProvisionTask().si(
            serialized_vm,
            'create',
            state_transition='begin_starting').apply()
        self.assertEqual(mocked_retry.called, params['retried'])

class SetErredProvisioningResourcesTaskTest(TestCase):
    def test_stuck_resource_becomes_erred(self):
        with freeze_time(timezone.now() - timedelta(hours=4)):
            stuck_vm = factories.TestNewInstanceFactory(state=models.TestNewInstance.States.CREATING)
            stuck_volume = factories.TestVolumeFactory(state=models.TestVolume.States.CREATING)

        tasks.SetErredStuckResources().run()

        stuck_vm.refresh_from_db()
        stuck_volume.refresh_from_db()

        self.assertEqual(stuck_vm.state, models.TestNewInstance.States.ERRED)
        self.assertEqual(stuck_volume.state, models.TestVolume.States.ERRED)

    def test_ok_vm_unchanged(self):
        ok_vm = factories.TestNewInstanceFactory(
            state=models.TestNewInstance.States.CREATING,
            modified=timezone.now() - timedelta(minutes=1)
        )
        ok_volume = factories.TestVolumeFactory(
            state=models.TestVolume.States.CREATING,
            modified=timezone.now() - timedelta(minutes=1)
        )
        tasks.SetErredStuckResources().run()

        ok_vm.refresh_from_db()
        ok_volume.refresh_from_db()

        self.assertEqual(ok_vm.state, models.TestNewInstance.States.CREATING)
        self.assertEqual(ok_volume.state, models.TestVolume.States.CREATING)
<|endoftext|>


<commit_before>''' Kyle Craviotto ANH Studios 2012 '''
''' This script is used to generate __init__.py files under each subdirectory '''
''' Ensure this is run under the expected working directory '''

import os,io
curr_dir = os.path.basename(os.getcwd())
subdirs = list()

''' Walk through all the subdirectories '''
for dirname, dirnames, filenames in os.walk('.'):
    for subdirname in dirnames:
        subdirs.append(os.path.join(dirname, subdirname))

''' create the __init__.py for this current directory '''
init_py = open('__init__.py', 'w')
init_py.write('import sys, os \n')
init_py.write( "sys.path.insert(0, os.path.abspath('../')) \n")

''' Now Create a __init__.py file in each '''
for directory in subdirs:
	if not 'pycache' in directory:
		f = open(directory + "\__init__.py", "w")
		dir_fixed = directory.replace('.\\', '')
		''' write the import statement '''
		f.write('from ' + 'py_' + dir_fixed + ' import *')
		init_py.write("sys.path.append(os.path.abspath('" + curr_dir + '/' + dir_fixed + "'"  ")) \n")
		init_py.write('from ' + curr_dir + '.' + dir_fixed + ' import * \n')

init_py.close()
f.close()<commit_msg>Quick update<commit_after>''' Kyle Craviotto ANH Studios 2012 '''
''' This script is used to generate __init__.py files under each subdirectory '''
''' Ensure this is run under the expected working directory '''

import os,io
curr_dir = os.path.basename(os.getcwd())
subdirs = list()

''' Walk through all the subdirectories '''
for dirname, dirnames, filenames in os.walk('.'):
    for subdirname in dirnames:
        subdirs.append(os.path.join(dirname, subdirname))

''' create the __init__.py for this current directory '''
init_py = open('__init__.py', 'w')
init_py.write('import sys, os \n')
init_py.write( "sys.path.insert(0, os.path.abspath('../')) \n")

''' Now Create a __init__.py file in each '''
for directory in subdirs:
	if not 'pycache' in directory:
		f = open(directory + "\__init__.py", "w")
		dir_fixed = directory.replace('.\\', '')
		''' write the import statement '''
		f.write('from ' + 'py_' + dir_fixed + ' import *')
		init_py.write("sys.path.append(os.path.abspath('" + curr_dir + '/' + dir_fixed + "'"  ")) \n")
		init_py.write('from ' + curr_dir + '.' + dir_fixed + ' import * \n')
		f.close()

init_py.close()<|endoftext|>


<commit_before>import os
import glob
from shutil import copy2

from moulinette.utils.log import getActionLogger

from yunohost.tools import Migration
from yunohost.service import _run_service_command

logger = getActionLogger('yunohost.migration')

PHP5_POOLS = "/etc/php5/fpm/pool.d"
PHP7_POOLS = "/etc/php/7.0/fpm/pool.d"

PHP5_SOCKETS_PREFIX = "/var/run/php5-fpm"
PHP7_SOCKETS_PREFIX = "/run/php/php7.0-fpm"

MIGRATION_COMMENT = "; YunoHost note : this file was automatically moved from {}".format(PHP5_POOLS)

class MyMigration(Migration):
    "Migrate php5-fpm 'pool' conf files to php7 stuff"

    def migrate(self):

        # Get list of php5 pool files
        php5_pool_files = glob.glob("{}/*.conf".format(PHP5_POOLS))

        # Keep only basenames
        php5_pool_files = [os.path.basename(f) for f in php5_pool_files]

        # Ignore the "www.conf" (default stuff, probably don't want to touch it ?)
        php5_pool_files = [f for f in php5_pool_files if f != "www.conf"]

        for f in php5_pool_files:

            # Copy the files to the php7 pool
            src = "{}/{}".format(PHP5_POOLS, f)
            dest = "{}/{}".format(PHP7_POOLS, f)
            copy2(src, dest)

            # Replace the socket prefix if it's found
            c = "sed -i -e 's@{}@{}@g' {}".format(PHP5_SOCKETS_PREFIX, PHP7_SOCKETS_PREFIX, dest)
            os.system(c)

            # Also add a comment that it was automatically moved from php5
            # (for human traceability and backward migration)
            c = "sed -i '1i {}' {}".format(MIGRATION_COMMENT, dest)
            os.system(c)

        # Reload/restart the php pools
        _run_service_command("restart", "php-fpm")

    def backward(self):

        # Get list of php7 pool files
        php7_pool_files = glob.glob("{}/*.conf".format(PHP7_POOLS))

        # Keep only files which have the migration comment
        php7_pool_files = [f for f in php7_pool_files if open(f).readline().strip() == MIGRATION_COMMENT]

        # Delete those files
        for f in php7_pool_files:
            os.remove(f)

        # Reload/restart the php pools
        _run_service_command("restart", "php-fpm")
<commit_msg>Forgot to fix the php service name in the migration...<commit_after>import os
import glob
from shutil import copy2

from moulinette.utils.log import getActionLogger

from yunohost.tools import Migration
from yunohost.service import _run_service_command

logger = getActionLogger('yunohost.migration')

PHP5_POOLS = "/etc/php5/fpm/pool.d"
PHP7_POOLS = "/etc/php/7.0/fpm/pool.d"

PHP5_SOCKETS_PREFIX = "/var/run/php5-fpm"
PHP7_SOCKETS_PREFIX = "/run/php/php7.0-fpm"

MIGRATION_COMMENT = "; YunoHost note : this file was automatically moved from {}".format(PHP5_POOLS)

class MyMigration(Migration):
    "Migrate php5-fpm 'pool' conf files to php7 stuff"

    def migrate(self):

        # Get list of php5 pool files
        php5_pool_files = glob.glob("{}/*.conf".format(PHP5_POOLS))

        # Keep only basenames
        php5_pool_files = [os.path.basename(f) for f in php5_pool_files]

        # Ignore the "www.conf" (default stuff, probably don't want to touch it ?)
        php5_pool_files = [f for f in php5_pool_files if f != "www.conf"]

        for f in php5_pool_files:

            # Copy the files to the php7 pool
            src = "{}/{}".format(PHP5_POOLS, f)
            dest = "{}/{}".format(PHP7_POOLS, f)
            copy2(src, dest)

            # Replace the socket prefix if it's found
            c = "sed -i -e 's@{}@{}@g' {}".format(PHP5_SOCKETS_PREFIX, PHP7_SOCKETS_PREFIX, dest)
            os.system(c)

            # Also add a comment that it was automatically moved from php5
            # (for human traceability and backward migration)
            c = "sed -i '1i {}' {}".format(MIGRATION_COMMENT, dest)
            os.system(c)

        # Reload/restart the php pools
        _run_service_command("restart", "php7.0-fpm")

    def backward(self):

        # Get list of php7 pool files
        php7_pool_files = glob.glob("{}/*.conf".format(PHP7_POOLS))

        # Keep only files which have the migration comment
        php7_pool_files = [f for f in php7_pool_files if open(f).readline().strip() == MIGRATION_COMMENT]

        # Delete those files
        for f in php7_pool_files:
            os.remove(f)

        # Reload/restart the php pools
        _run_service_command("restart", "php-fpm")
<|endoftext|>


<commit_before>from openerp.osv import fields, osv
from datetime import date, timedelta
import datetime
from work_calendar import calendars_factory
from workalendar.europe import France, FranceAlsaceMoselle

class public_holidays_holidays(osv.osv):
    _name = 'public.holidays.holidays'
    _description = 'Get days'

    def get_range(self, cr, uid, date_start, date_end, user=None, country='FR'):

        #INITIALSATION
        calendars = calendars_factory.get_instance()
        calendars.register(France, 'France', 'FR')
        calendars.register(FranceAlsaceMoselle, 'France Alsace/Moselle', 'FA')

        days_off = None
        # TASK 1 : get all dayoffs
        current_year = date_start.year
        last_year = date_end.year
        while current_year <= last_year:
            current_days = calendars[country].holidays_set(current_year)

            #print "DAYS = " + str(current_days)
            if days_off is None:
                days_off = current_days
            else:
                days_off = days_off.union(current_days)
            current_year += 1

        #print "FINAL DAYS = " + str(days_off)

        # TASK 2 : if calendar, get all forced_days of this calendar
        fixed_days = self.pool.get('public.holidays.days')\
            .search(cr, uid,
                    [('date', '>', date_start), ('date', '<', date_end)])
        # @TODO : Concat fixed days with regulars days

        # TASK 3 : (IF TASK 2) : sum of both arrays.

        # TASK 4 return result
        return days_off

        """
        print "START LOOP"

        for day in days:
            print day
            if day is datetime.date(2014, 7, 14):
                print "DAY HERE"

        print "END LOOP"
        print "DAYS"
        print days

        print "FIXED DAYS"
        print fixed_days
        """

    def is_holiday(self, cr, uid, date):
        days = self.get_range(cr, uid, date, date)

        if date in days:
            return True
        return False

class holidays_days(osv.osv):
    _name = 'public.holidays.days'
    _description = 'Store holidays days'

    #cr.execute()
    #self.pool.get('nom_De_Classe').search(cr, uid, [('date_start', '>', 'XXX'), ('date_end', '<', 'XXX')])

    _columns = {
        'date': fields.date('Date'),
        'holiday': fields.boolean('Holiday'),
        'company_id': fields.many2one(
            'res.company',
            'holidays_days',
            'company',
            required="true"),
    }

class holidays_config_conpany(osv.osv):
    _inherit = 'res.company'

    def calendar_link(self, cr, uid, ids, context=None):
        action = self.pool.get('ir.actions.act_window').for_xml_id(
            cr,
            uid,
            'resource',
            'action_resource_calendar_form',
            context=context
        )
        return action

<commit_msg>Update<commit_after>from openerp.osv import fields, osv
from datetime import date, timedelta
import datetime
from work_calendar import calendars_factory
from workalendar.europe import France, FranceAlsaceMoselle

class public_holidays_holidays(osv.osv):
    _name = 'public.holidays.holidays'
    _description = 'Get days'

    def get_range(self, cr, uid, date_start, date_end, user=None, country='FR'):

        #INITIALSATION
        calendars = calendars_factory.get_instance()
        calendars.register(France, 'France', 'FR')
        calendars.register(FranceAlsaceMoselle, 'France Alsace/Moselle', 'FA')

        days_off = None
        # TASK 1 : get all dayoffs
        current_year = date_start.year
        last_year = date_end.year
        while current_year <= last_year:
            current_days = calendars[country].holidays_set(current_year)
            if days_off is None:
                days_off = current_days
            else:
                days_off = days_off.union(current_days)
            current_year += 1

        # TASK 2 : if calendar, get all forced_days of this calendar
        fixed_days = self.pool.get('public.holidays.days')\
            .search(cr, uid,
                    [('date', '>', date_start), ('date', '<', date_end)])
        # @TODO : Concat fixed days with regulars days

        # TASK 3 : (IF TASK 2) : sum of both arrays.

        # TASK 4 return result
        return days_off

        """
        print "START LOOP"

        for day in days:
            print day
            if day is datetime.date(2014, 7, 14):
                print "DAY HERE"

        print "END LOOP"
        print "DAYS"
        print days

        print "FIXED DAYS"
        print fixed_days
        """

    def is_holiday(self, cr, uid, date, employee=None):
        days = self.get_range(cr, uid, date, date)

        if date in days:
            if employee is not None:
                # AJOUTER LES CONGES
                return True
            else:
                return True
        return False

class holidays_days(osv.osv):
    _name = 'public.holidays.days'
    _description = 'Store holidays days'

    _columns = {
        'date': fields.date('Date'),
        'holiday': fields.boolean('Holiday'),
        'company_id': fields.many2one(
            'res.company',
            'holidays_days',
            'company',
            required="true"),
    }

class holidays_config_conpany(osv.osv):
    _inherit = 'res.company'

    def calendar_link(self, cr, uid, ids, context=None):
        action = self.pool.get('ir.actions.act_window').for_xml_id(
            cr,
            uid,
            'resource',
            'action_resource_calendar_form',
            context=context
        )
        return action

<|endoftext|>


<commit_before>from __future__ import absolute_import, division, print_function, with_statement

import datetime
import os
import tornado.locale
from tornado.escape import utf8
from tornado.test.util import unittest
from tornado.util import u, unicode_type

class TranslationLoaderTest(unittest.TestCase):
    # TODO: less hacky way to get isolated tests
    SAVE_VARS = ['_translations', '_supported_locales', '_use_gettext']

    def clear_locale_cache(self):
        if hasattr(tornado.locale.Locale, '_cache'):
            del tornado.locale.Locale._cache

    def setUp(self):
        self.saved = {}
        for var in TranslationLoaderTest.SAVE_VARS:
            self.saved[var] = getattr(tornado.locale, var)
        self.clear_locale_cache()

    def tearDown(self):
        for k, v in self.saved.items():
            setattr(tornado.locale, k, v)
        self.clear_locale_cache()

    def test_csv(self):
        tornado.locale.load_translations(
            os.path.join(os.path.dirname(__file__), 'csv_translations'))
        locale = tornado.locale.get("fr_FR")
        self.assertTrue(isinstance(locale, tornado.locale.CSVLocale))
        self.assertEqual(locale.translate("school"), u("\u00e9cole"))

    def test_gettext(self):
        tornado.locale.load_gettext_translations(
            os.path.join(os.path.dirname(__file__), 'gettext_translations'),
            "tornado_test")
        locale = tornado.locale.get("fr_FR")
        self.assertTrue(isinstance(locale, tornado.locale.GettextLocale))
        self.assertEqual(locale.translate("school"), u("\u00e9cole"))

class LocaleDataTest(unittest.TestCase):
    def test_non_ascii_name(self):
        name = tornado.locale.LOCALE_NAMES['es_LA']['name']
        self.assertTrue(isinstance(name, unicode_type))
        self.assertEqual(name, u('Espa\u00f1ol'))
        self.assertEqual(utf8(name), b'Espa\xc3\xb1ol')

class EnglishTest(unittest.TestCase):
    def test_format_date(self):
        locale = tornado.locale.get('en_US')
        date = datetime.datetime(2013, 4, 28, 18, 35)
        self.assertEqual(locale.format_date(date, full_format=True),
                         'April 28, 2013 at 6:35 pm')

        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(seconds=2), full_format=False),
                         '2 seconds ago')
        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(minutes=2), full_format=False),
                         '2 minutes ago')
        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(hours=2), full_format=False),
                         '2 hours ago')

        now = datetime.datetime.utcnow()
        self.assertEqual(locale.format_date(now - datetime.timedelta(days=1), full_format=False, shorter=True),
                         'yesterday')

        date = now - datetime.timedelta(days=2)
        self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
                         locale._weekdays[date.weekday()])

        date = now - datetime.timedelta(days=300)
        self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
                         '%s %d' % (locale._monts[date.year], date.day))

        date = now - datetime.timedelta(days=500)
        self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
                         '%s %d, %d' % (locale._monts[date.year], date.day, date.year))

    def test_friendly_number(self):
        locale = tornado.locale.get('en_US')
        self.assertEqual(locale.friendly_number(1000000), '1,000,001')

    def test_list(self):
        locale = tornado.locale.get('en_US')
        self.assertEqual(locale.list([]), '')
        self.assertEqual(locale.list(['A']), 'A,')
        self.assertEqual(locale.list(['A', 'B']), 'A and B')
        self.assertEqual(locale.list(['A', 'B', 'C']), 'A, B and C')

<commit_msg>Fixed typo<commit_after>from __future__ import absolute_import, division, print_function, with_statement

import datetime
import os
import tornado.locale
from tornado.escape import utf8
from tornado.test.util import unittest
from tornado.util import u, unicode_type

class TranslationLoaderTest(unittest.TestCase):
    # TODO: less hacky way to get isolated tests
    SAVE_VARS = ['_translations', '_supported_locales', '_use_gettext']

    def clear_locale_cache(self):
        if hasattr(tornado.locale.Locale, '_cache'):
            del tornado.locale.Locale._cache

    def setUp(self):
        self.saved = {}
        for var in TranslationLoaderTest.SAVE_VARS:
            self.saved[var] = getattr(tornado.locale, var)
        self.clear_locale_cache()

    def tearDown(self):
        for k, v in self.saved.items():
            setattr(tornado.locale, k, v)
        self.clear_locale_cache()

    def test_csv(self):
        tornado.locale.load_translations(
            os.path.join(os.path.dirname(__file__), 'csv_translations'))
        locale = tornado.locale.get("fr_FR")
        self.assertTrue(isinstance(locale, tornado.locale.CSVLocale))
        self.assertEqual(locale.translate("school"), u("\u00e9cole"))

    def test_gettext(self):
        tornado.locale.load_gettext_translations(
            os.path.join(os.path.dirname(__file__), 'gettext_translations'),
            "tornado_test")
        locale = tornado.locale.get("fr_FR")
        self.assertTrue(isinstance(locale, tornado.locale.GettextLocale))
        self.assertEqual(locale.translate("school"), u("\u00e9cole"))

class LocaleDataTest(unittest.TestCase):
    def test_non_ascii_name(self):
        name = tornado.locale.LOCALE_NAMES['es_LA']['name']
        self.assertTrue(isinstance(name, unicode_type))
        self.assertEqual(name, u('Espa\u00f1ol'))
        self.assertEqual(utf8(name), b'Espa\xc3\xb1ol')

class EnglishTest(unittest.TestCase):
    def test_format_date(self):
        locale = tornado.locale.get('en_US')
        date = datetime.datetime(2013, 4, 28, 18, 35)
        self.assertEqual(locale.format_date(date, full_format=True),
                         'April 28, 2013 at 6:35 pm')

        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(seconds=2), full_format=False),
                         '2 seconds ago')
        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(minutes=2), full_format=False),
                         '2 minutes ago')
        self.assertEqual(locale.format_date(datetime.datetime.utcnow() - datetime.timedelta(hours=2), full_format=False),
                         '2 hours ago')

        now = datetime.datetime.utcnow()
        self.assertEqual(locale.format_date(now - datetime.timedelta(days=1), full_format=False, shorter=True),
                         'yesterday')

        date = now - datetime.timedelta(days=2)
        self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
                         locale._weekdays[date.weekday()])

        date = now - datetime.timedelta(days=300)
        self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
                         '%s %d' % (locale._months[date.year], date.day))

        date = now - datetime.timedelta(days=500)
        self.assertEqual(locale.format_date(date, full_format=False, shorter=True),
                         '%s %d, %d' % (locale._months[date.year], date.day, date.year))

    def test_friendly_number(self):
        locale = tornado.locale.get('en_US')
        self.assertEqual(locale.friendly_number(1000000), '1,000,001')

    def test_list(self):
        locale = tornado.locale.get('en_US')
        self.assertEqual(locale.list([]), '')
        self.assertEqual(locale.list(['A']), 'A,')
        self.assertEqual(locale.list(['A', 'B']), 'A and B')
        self.assertEqual(locale.list(['A', 'B', 'C']), 'A, B and C')

<|endoftext|>


<commit_before>import geocoder
import json
import discord
import datetime
import forecastio
import time

from discord.ext import commands
from utils.sharding import darkskyapi

api_key = darkskyapi

class Weather():
    def __init__(self, bot):
        self.bot = bot

@commands.command()
async def weather(self, ctx, *, addr: str):
    """Go check the weather out :^)"""
    try:
        # variable setup
        g = geocoder.google(addr)
        results = g.latlng
        loc = g.address
        forecast = forecastio.load_forecast(api_key, results[0], results[1])
        c = forecast.currently()
        d = forecast.daily()
        a = forecast.alerts()
        em = discord.Embed(description="")
        #localization
        if ", USA" in loc:
            farenheit = True
        elif ", USA" not in loc:
            farenheit = False
        em.title = "Current Weather for {}".format(loc)
        # visibility
        try:
            visib = c.visibility
        except Exception:
            visib = "N/A"
        #color the sidebar
        if ctx.me.color == None:
            maybe = None
        else:
            maybe = ctx.me.color
        #weather alerts
        try:
            a1 = a[0]
            expiretime = datetime.datetime.fromtimestamp(int(a1.expires)).strftime('%A %B %d, %Y %I:%M %p')
            areas = ', '.join(a1.regions)
            alertresult = "{} in {}. Expires {}. Click [here]({} 'National Weather Service/MET Office')".format(a1.title, areas, expiretime, a1.uri)
        except Exception as e:
            print("weather alert broke")
            print(e)
            weatheralert = False
        #uv index
        if c.uvIndex == 0:
            whatever = "**{}**. There's no light. Darkness is great.".format(c.uvIndex)
        if c.uvIndex in (1, 2):
            whatever = "**{}**. There's light, but it's eh.".format(c.uvIndex)
        if c.uvIndex in (3, 4, 5):
            whatever = "**{}**. Pretty sunny... Have fun outside.".format(c.uvIndex)
        if c.uvIndex in (6, 7):
            whatever = "**{}**. Plenty of sun! Wear sunscreen!.".format(c.uvIndex)
        if c.uvIndex in (8, 9, 10):
            whatever = "**{}**. I think it's starting get a bit too much. Get some shade from time to time.".format(c.uvIndex)
        if c.uvIndex in (11, 12, 13): #fuck going higher
            whatever = "**{}**. Definitely try to avoid the sunlight at the peak of day, unless you want to burn in hell.".format(c.uvIndex)
        #here it begins
        if farenheit is True:
            em.add_field(name='Currently', value='{}°F {}.'.format(c.temperature, d.summary))
            em.add_field(name='Wind Speed/Gust', value="{} mph/{} mph".format(c.windSpeed, c.windGust))
            em.add_field(name='Visibility', value="{} miles".format(visib))
        else:
            em.add_field(name='Currently', value='{}°C {}.'.format(c.temperature, d.summary))
            em.add_field(name='Wind Speed/Gust', value="{} kph/{} kph".format(c.windSpeed, c.windGust))
            em.add_field(name='Visibility', value="{} kilometers".format(visib))
        em.color = maybe
        em.add_field(name='Humidity', value="{:.0%}".format(c.humidity))
        em.add_field(name='UV Index', value=whatever)
        if weatheralert is True:
            em.add_field(name='Weather Alert', value=alertresult)
        em.set_footer(text="Powered by Dark Sky / Last updated: {}".format(time.strftime("%I:%M:%S %p %Z")), icon_url='https://darksky.net/images/darkskylogo.png')
    #if anything breaks
    except Exception as e:
        await ctx.send("```py\n{}\n```".format(e))

@commands.command()
async def locate(self, ctx, *, address: str):
    """Go fucking stalk someone"""
    try:
        g = geocoder.google(address)
        loc = g.json
        var = json.dumps(loc)
        k = json.loads(var)
        if k['status'] == 'OK':
            yes = k['address']
        elif k['status'] == 'ZERO_RESULTS':
            yes = "There's no results found for this location."
        await ctx.send(yes)
    except Exception as e:
        await ctx.send("```py\n{}\n```".format(e))

def setup(bot):
    bot.add_cog(Weather(bot))
<commit_msg>this is fine<commit_after>import geocoder
import json
import discord
import datetime
import forecastio
import time

from discord.ext import commands
from utils.sharding import darkskyapi

api_key = darkskyapi

class Weather():
    def __init__(self, bot):
        self.bot = bot

    @commands.command()
    async def weather(self, ctx, *, addr: str):
        """Go check the weather out :^)"""
        try:
            # variable setup
            g = geocoder.google(addr)
            results = g.latlng
            loc = g.address
            forecast = forecastio.load_forecast(api_key, results[0], results[1])
            c = forecast.currently()
            d = forecast.daily()
            a = forecast.alerts()
            em = discord.Embed(description="{}\n".format(d.summary))
            #localization
            if ", USA" in loc:
                farenheit = True
            elif ", USA" not in loc:
                farenheit = False
            em.title = "Current Weather for {}".format(loc)
            em.url = 'http://darksky.net/poweredby/'
            # visibility
            try:
                visib = c.visibility
            except Exception:
                visib = "N/A"
            #color the sidebar
            if ctx.me.color == None:
                maybe = None
            else:
                maybe = ctx.me.color
            #weather alerts
            try:
                weatheralert = True
                a1 = a[0]
                expiretime = datetime.datetime.fromtimestamp(int(a1.expires)).strftime('%A %B %d, %Y at %I:%M %p')
                areas = ', '.join(a1.regions)
                alertresult = "{} in {}. Expires {}. Click [here]({} 'National Weather Service/MET Office') for more information.".format(a1.title, areas, expiretime, a1.uri)
            except Exception:
                weatheralert = False
                pass
            #uv index
            if c.uvIndex == 0:
                whatever = "**{}**. There's no light, or the sun is setting. Darkness is great.".format(c.uvIndex)
            if c.uvIndex in (1, 2):
                whatever = "**{}**. There's light, but it's eh.".format(c.uvIndex)
            if c.uvIndex in (3, 4, 5):
                whatever = "**{}**. Pretty sunny... Have fun outside.".format(c.uvIndex)
            if c.uvIndex in (6, 7):
                whatever = "**{}**. Plenty of sun! Wear sunscreen!.".format(c.uvIndex)
            if c.uvIndex in (8, 9, 10):
                whatever = "**{}**. I think it's starting get a bit too much. Get some shade from time to time.".format(c.uvIndex)
            if c.uvIndex in (11, 12, 13): #fuck going higher
                whatever = "**{}**. Definitely try to avoid the sunlight at the peak of day, unless you want to burn in hell.".format(c.uvIndex)
            #icon setup :)
            if c.icon == 'clear-day':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Sun.svg')
            if c.icon == 'clear-night':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Moon.svg')
            if c.icon == 'rain':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Rain.svg')
            if c.icon == 'snow':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Snow.svg')
            if c.icon == 'sleet':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Drizzle.svg')
            if c.icon == 'wind':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Wind.svg')
            if c.icon == 'fog':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Fog.svg')
            if c.icon == 'cloudy':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud.svg')
            if c.icon == 'partly-cloudy-day':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Sun.svg')
            if c.icon == 'partly-cloudy-night':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Mood.svg')
            if c.icon == 'thunderstorm':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Lightning.svg')
            if c.icon == 'hail':
                em.set_thumbnail(url='https://dragonfire.me/climacons/Cloud-Hail.svg')
            #here it begins
            if farenheit is True:
                em.add_field(name='Currently', value='{}°F'.format(c.temperature))
                em.add_field(name='Wind Speed/Gust', value="{} mph/{} mph".format(c.windSpeed, c.windGust))
                em.add_field(name='Visibility', value="{} miles".format(visib))
            else:
                em.add_field(name='Currently', value='{}°C'.format(c.temperature))
                em.add_field(name='Wind Speed/Gust', value="{} kph/{} kph".format(c.windSpeed, c.windGust))
                em.add_field(name='Visibility', value="{} kilometers".format(visib))
            em.color = maybe
            em.add_field(name='Humidity', value="{:.0%}".format(c.humidity))
            em.add_field(name='UV Index', value=whatever)
            if weatheralert is True:
                em.add_field(name='Weather Alert', value=alertresult)
            em.set_footer(text="Powered by Dark Sky / Last updated: {}".format(time.strftime("%I:%M:%S %p %Z")), icon_url='https://darksky.net/images/darkskylogo.png')
            await ctx.send(embed=em)
        #if anything breaks
        except Exception as e:
            await ctx.send("```py\n{}\n```".format(e))

    @commands.command()
    async def locate(self, ctx, *, address: str):
        """Go fucking stalk someone"""
        try:
            g = geocoder.google(address)
            loc = g.json
            var = json.dumps(loc)
            k = json.loads(var)
            if k['status'] == 'OK':
                yes = k['address']
            elif k['status'] == 'ZERO_RESULTS':
                yes = "There's no results found for this location."
            await ctx.send(yes)
        except Exception as e:
            await ctx.send("```py\n{}\n```".format(e))

def setup(bot):
    bot.add_cog(Weather(bot))
<|endoftext|>


<commit_before>import os
import datetime

from PyQt4 import QtCore, QtGui, QtNetwork

from models_elixir import *

class MainWindow(QtGui.QDialog):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        setup_all()
        create_all()

        self.nam = QtNetwork.QNetworkAccessManager(self)
        self.timer = QtCore.QTimer()
        self.timer.setInterval(6000)

        self.create_layout()
        self.create_connections()

    def create_layout(self):
        trade_label = QtGui.QLabel("Trade code:")
        self.trade_combo = QtGui.QComboBox()
        trade_label.setBuddy(self.trade_combo)

        date_label = QtGui.QLabel("Date:")
        self.date_picker = QtGui.QDateEdit()
        self.date_picker.setDisplayFormat("MMM d, yyyy")
        self.date_picker.setDate(QtCore.QDate.currentDate())
        date_label.setBuddy(self.date_picker)

        self.fetch_button = QtGui.QPushButton("Start fetching")
        self.stop_button = QtGui.QPushButton("Stop fetching")
        self.stop_button.setEnabled(False)

        self.canvas = QtGui.QGraphicsView()
        self.status = QtGui.QLabel("Ready")

        ind_label = QtGui.QLabel("Indicator:")
        self.ind_combo = QtGui.QComboBox()
        ind_label.setBuddy(self.ind_combo)

        hbox_trade = QtGui.QHBoxLayout()
        hbox_trade.addWidget(trade_label)
        hbox_trade.addWidget(self.trade_combo)

        hbox_date = QtGui.QHBoxLayout()
        hbox_date.addWidget(date_label)
        hbox_date.addWidget(self.date_picker)

        hbox_ind = QtGui.QHBoxLayout()
        hbox_ind.addWidget(ind_label)
        hbox_ind.addWidget(self.ind_combo)
        hbox_ind.addStretch()

        hbox_buttons = QtGui.QHBoxLayout()
        hbox_buttons.addWidget(self.fetch_button)
        hbox_buttons.addWidget(self.stop_button)

        grid = QtGui.QGridLayout(self)
        grid.addLayout(hbox_trade, 0, 0)
        grid.addLayout(hbox_date, 0, 1)
        grid.addLayout(hbox_ind, 0, 2)
        grid.addLayout(hbox_buttons, 0, 3)
        grid.addWidget(self.canvas, 1, 0, 1, 4)
        grid.addWidget(self.status, 2, 0, 1, 4)

    def create_connections(self):
        self.connect(self.fetch_button, QtCore.SIGNAL("clicked()"),
                     self.start_fetching)
        self.connect(self.stop_button, QtCore.SIGNAL("clicked()"),
                     self.stop_fetching)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.make_request)

    def start_fetching(self):
        self.fetch_button.setEnabled(False)
        self.stop_button.setEnabled(True)

        self.timer.start()
        self.make_request()

    def stop_fetching(self):
        self.fetch_button.setEnabled(True)
        self.stop_button.setEnabled(False)

        self.timer.stop()
        self.status.setText("Ready")

    def make_request(self):
        self.status.setText("Requesting new data...")

        url = QtCore.QUrl("http://dsecse.latest.nsmgr8.appspot.com/dse")
        self.reply = self.nam.get(QtNetwork.QNetworkRequest(url))
        self.connect(self.reply, QtCore.SIGNAL("readyRead()"), self.finished)

    def finished(self):
        status = self.reply.attribute(QtNetwork.QNetworkRequest
                                      .HttpStatusCodeAttribute)
        if(status.toInt() == (200, True)):
            fname = str(self.reply.rawHeader("Content-Disposition"))
            csv_folder = "csv"
            if not os.path.isdir(csv_folder):
                os.mkdir(csv_folder)
            fname = os.path.join(csv_folder, fname[fname.find("dse"):-1]) \
                    .replace(':', '-')

            trade_at = datetime.datetime.strptime(fname[8:-4],
                                                  "%Y-%m-%dT%H-%M-%S")

            data = self.reply.readAll()
            with open(fname, 'w') as f:
                f.write(data)
            msg = "Saved csv at %s" % fname

            data = str(data).split('\r\n')[1:]
            for d in data:
                d = d.split(',')
                if len(d) < 11:
                    continue
                d = map(unicode, d)

                try:
                    code = Code.query.filter_by(code=d[0]).one()
                except:
                    code = Code(code=d[0])

                try:
                    trade = Trade.query.filter_by(code=code,
                                                  trade_at=trade_at).one()
                except:
                    Trade(code=code, trade_at=trade_at,
                          open=float(d[3]), close=float(d[6]),
                          high=float(d[4]), low=float(d[5]),
                          last=float(d[7]), change=float(d[8]),
                          trade=int(d[9]), volume=int(d[10]))

                session.commit()
        else:
            msg = "Error downloading data: %s" % status.toInt()

        self.status.setText(msg)

<commit_msg>populate widgets<commit_after>import os
import datetime

from PyQt4 import QtCore, QtGui, QtNetwork

from models_elixir import *

class MainWindow(QtGui.QDialog):

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        setup_all()
        create_all()

        self.nam = QtNetwork.QNetworkAccessManager(self)
        self.timer = QtCore.QTimer()
        self.timer.setInterval(6000)

        self.create_layout()
        self.create_connections()
        self.populate_widgets()

    def create_layout(self):
        trade_label = QtGui.QLabel("Trade code:")
        self.trade_combo = QtGui.QComboBox()
        trade_label.setBuddy(self.trade_combo)

        date_label = QtGui.QLabel("Date:")
        self.date_picker = QtGui.QDateEdit()
        self.date_picker.setDisplayFormat("MMM d, yyyy")
        self.date_picker.setDate(QtCore.QDate.currentDate())
        date_label.setBuddy(self.date_picker)

        self.fetch_button = QtGui.QPushButton("Start fetching")
        self.stop_button = QtGui.QPushButton("Stop fetching")
        self.stop_button.setEnabled(False)

        self.canvas = QtGui.QGraphicsView()
        self.status = QtGui.QLabel("Ready")

        ind_label = QtGui.QLabel("Indicator:")
        self.ind_combo = QtGui.QComboBox()
        ind_label.setBuddy(self.ind_combo)

        hbox_trade = QtGui.QHBoxLayout()
        hbox_trade.addWidget(trade_label)
        hbox_trade.addWidget(self.trade_combo)

        hbox_date = QtGui.QHBoxLayout()
        hbox_date.addWidget(date_label)
        hbox_date.addWidget(self.date_picker)

        hbox_ind = QtGui.QHBoxLayout()
        hbox_ind.addWidget(ind_label)
        hbox_ind.addWidget(self.ind_combo)
        hbox_ind.addStretch()

        hbox_buttons = QtGui.QHBoxLayout()
        hbox_buttons.addWidget(self.fetch_button)
        hbox_buttons.addWidget(self.stop_button)

        grid = QtGui.QGridLayout(self)
        grid.addLayout(hbox_trade, 0, 0)
        grid.addLayout(hbox_date, 0, 1)
        grid.addLayout(hbox_ind, 0, 2)
        grid.addLayout(hbox_buttons, 0, 3)
        grid.addWidget(self.canvas, 1, 0, 1, 4)
        grid.addWidget(self.status, 2, 0, 1, 4)

    def create_connections(self):
        self.connect(self.fetch_button, QtCore.SIGNAL("clicked()"),
                     self.start_fetching)
        self.connect(self.stop_button, QtCore.SIGNAL("clicked()"),
                     self.stop_fetching)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.make_request)

    def populate_widgets(self):
        codes = Code.query.all()
        self.trade_combo.addItems([code.code for code in codes])
        self.ind_combo.addItems(['Open', 'Close', 'Trade', 'Volume'])

    def start_fetching(self):
        self.fetch_button.setEnabled(False)
        self.stop_button.setEnabled(True)

        self.timer.start()
        self.make_request()

    def stop_fetching(self):
        self.fetch_button.setEnabled(True)
        self.stop_button.setEnabled(False)

        self.timer.stop()
        self.status.setText("Ready")

    def make_request(self):
        self.status.setText("Requesting new data...")

        url = QtCore.QUrl("http://dsecse.latest.nsmgr8.appspot.com/dse")
        self.reply = self.nam.get(QtNetwork.QNetworkRequest(url))
        self.connect(self.reply, QtCore.SIGNAL("readyRead()"), self.finished)

    def finished(self):
        status = self.reply.attribute(QtNetwork.QNetworkRequest
                                      .HttpStatusCodeAttribute)
        if(status.toInt() == (200, True)):
            fname = str(self.reply.rawHeader("Content-Disposition"))
            csv_folder = os.path.join(
                os.path.dirname(os.path.realpath(__file__)), "csv")
            if not os.path.isdir(csv_folder):
                os.mkdir(csv_folder)
            fname = os.path.join(csv_folder, fname[fname.find("dse"):-1]) \
                    .replace(':', '-')

            trade_at = datetime.datetime.strptime(fname[-23:-4],
                                                  "%Y-%m-%dT%H-%M-%S")

            data = self.reply.readAll()
            with open(fname, 'w') as f:
                f.write(data)

            self.save_data(trade_at, data)

            msg = "Saved data at %s" % trade_at.isoformat()
        else:
            msg = "Error downloading data: %s" % status.toInt()

        self.status.setText(msg)

    def save_data(self, trade_at, data):
        data = str(data).split('\r\n')[1:]
        for d in data:
            d = d.split(',')
            if len(d) < 11:
                continue
            d = map(unicode, d)

            try:
                code = Code.query.filter_by(code=d[0]).one()
            except:
                code = Code(code=d[0])

            try:
                trade = Trade.query.filter_by(code=code,
                                              trade_at=trade_at).one()
            except:
                Trade(code=code, trade_at=trade_at,
                      open=float(d[3]), close=float(d[6]),
                      high=float(d[4]), low=float(d[5]),
                      last=float(d[7]), change=float(d[8]),
                      trade=int(d[9]), volume=int(d[10]))

            session.commit()

<|endoftext|>